diff --git a/.clang-format b/.clang-format index 447934fd67c..2ee80c3f694 100644 --- a/.clang-format +++ b/.clang-format @@ -55,7 +55,7 @@ Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true +FixNamespaceComments: false ForEachMacros: - foreach - Q_FOREACH @@ -70,6 +70,7 @@ IncludeCategories: Priority: 3 IncludeIsMainRegex: '([-_](test|unittest))?$' IndentCaseLabels: true +InsertNewlineAtEOF: true IndentPPDirectives: BeforeHash IndentWidth: 4 IndentWrappedFunctionNames: false @@ -99,7 +100,7 @@ SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 12 +SpacesBeforeTrailingComments: 2 SpacesInAngles: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false diff --git a/Client/ceflauncher_DLL/CCefApp.h b/Client/ceflauncher_DLL/CCefApp.h index e3fb138c609..665bb5b3f6d 100644 --- a/Client/ceflauncher_DLL/CCefApp.h +++ b/Client/ceflauncher_DLL/CCefApp.h @@ -10,7 +10,7 @@ #include #include #include "V8Helpers.h" -#include "CCefAppAuth.h" // IPC message append helpers +#include "CCefAppAuth.h" // IPC message append helpers using V8Helpers::CV8Handler; class CCefApp : public CefApp, public CefRenderProcessHandler @@ -41,7 +41,8 @@ class CCefApp : public CefApp, public CefRenderProcessHandler if (!node) return; - if (node->GetType() == CefDOMNode::Type::DOM_NODE_TYPE_ELEMENT && node->GetFormControlElementType() != CefDOMNode::FormControlType::DOM_FORM_CONTROL_TYPE_UNSUPPORTED) + if (node->GetType() == CefDOMNode::Type::DOM_NODE_TYPE_ELEMENT && + node->GetFormControlElementType() != CefDOMNode::FormControlType::DOM_FORM_CONTROL_TYPE_UNSUPPORTED) { auto message = CefProcessMessage::Create("InputFocus"); message->GetArgumentList()->SetBool(0, true); @@ -77,7 +78,7 @@ class CCefApp : public CefApp, public CefRenderProcessHandler return; CefRefPtr message = V8Helpers::SerialiseV8Arguments("TriggerLuaEvent", arguments); - if (!CefAppAuth::AppendAuthCodeToMessage(message)) [[unlikely]] // AUTH: race condition check + if (!CefAppAuth::AppendAuthCodeToMessage(message)) [[unlikely]] // AUTH: race condition check return; frame->GetBrowser()->GetMainFrame()->SendProcessMessage(PID_BROWSER, message); } diff --git a/Client/ceflauncher_DLL/CCefAppAuth.h b/Client/ceflauncher_DLL/CCefAppAuth.h index ad046de01cd..ee1da977269 100644 --- a/Client/ceflauncher_DLL/CCefAppAuth.h +++ b/Client/ceflauncher_DLL/CCefAppAuth.h @@ -29,13 +29,13 @@ namespace CefAppAuth return false; auto& authCode = AuthCodeStorage(); - + // Block messages until initialized (prevents race condition) if (authCode.empty()) [[unlikely]] return false; - + CefRefPtr args = message->GetArgumentList(); - const auto size = args->GetSize(); + const auto size = args->GetSize(); args->SetSize(size + 1); args->SetString(size, authCode.c_str()); return true; diff --git a/Client/ceflauncher_DLL/Main.cpp b/Client/ceflauncher_DLL/Main.cpp index fa4b2a895a5..5774d949a9a 100644 --- a/Client/ceflauncher_DLL/Main.cpp +++ b/Client/ceflauncher_DLL/Main.cpp @@ -30,27 +30,27 @@ #include #ifdef CEF_ENABLE_SANDBOX -#include -#pragma comment(lib, "cef_sandbox.lib") + #include + #pragma comment(lib, "cef_sandbox.lib") #endif // Return codes -inline constexpr int CEF_INIT_SUCCESS = 0; -inline constexpr int CEF_INIT_ERROR_NO_BASE_DIR = -1; -inline constexpr int CEF_INIT_ERROR_DLL_LOAD_FAILED = -2; +inline constexpr int CEF_INIT_SUCCESS = 0; +inline constexpr int CEF_INIT_ERROR_NO_BASE_DIR = -1; +inline constexpr int CEF_INIT_ERROR_DLL_LOAD_FAILED = -2; -inline constexpr DWORD CEF_PARENT_CHECK_INTERVAL = 1000; -inline constexpr const char* CEF_DLL_NAME = "libcef.dll"; -inline constexpr const char* CEF_MTA_SUBDIR = "MTA"; +inline constexpr DWORD CEF_PARENT_CHECK_INTERVAL = 1000; +inline constexpr const char* CEF_DLL_NAME = "libcef.dll"; +inline constexpr const char* CEF_MTA_SUBDIR = "MTA"; -inline constexpr DWORD PARENT_CHECK_ERROR_NO_QUERY_FUNC = 1; -inline constexpr DWORD PARENT_CHECK_ERROR_QUERY_FAILED = 2; -inline constexpr DWORD PARENT_CHECK_ERROR_OPEN_FAILED = 3; +inline constexpr DWORD PARENT_CHECK_ERROR_NO_QUERY_FUNC = 1; +inline constexpr DWORD PARENT_CHECK_ERROR_QUERY_FAILED = 2; +inline constexpr DWORD PARENT_CHECK_ERROR_OPEN_FAILED = 3; using NtQueryInformationProcessFunc = NTSTATUS(NTAPI*)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG); // Safe parent monitor thread shutdown -std::atomic g_bShouldTerminateMonitor{false}; +std::atomic g_bShouldTerminateMonitor{false}; std::atomic g_hMonitorThread{nullptr}; namespace @@ -60,19 +60,19 @@ namespace const auto ntdll = GetModuleHandleW(L"ntdll.dll"); if (!ntdll) return nullptr; - + const auto procAddr = GetProcAddress(ntdll, "NtQueryInformationProcess"); if (!procAddr) return nullptr; - + return reinterpret_cast(procAddr); } [[nodiscard]] auto GetParentProcessId(NtQueryInformationProcessFunc queryFunc) noexcept -> DWORD { PROCESS_BASIC_INFORMATION info{}; - ULONG returnLength = 0; - + ULONG returnLength = 0; + if (const auto status = queryFunc(GetCurrentProcess(), ProcessBasicInformation, &info, sizeof(info), &returnLength); !NT_SUCCESS(status) || returnLength < sizeof(PROCESS_BASIC_INFORMATION)) { @@ -87,7 +87,7 @@ namespace while (!g_bShouldTerminateMonitor.load(std::memory_order_acquire)) { const DWORD result = WaitForSingleObject(parentProcess, CEF_PARENT_CHECK_INTERVAL); - + if (result == WAIT_OBJECT_0) { DWORD exitCode = 0; @@ -104,7 +104,7 @@ namespace } } } -} // namespace +} // namespace DWORD WINAPI CheckParentProcessAliveness(LPVOID) noexcept; @@ -120,7 +120,7 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, [[maybe_unused]] LPVOID l { g_bShouldTerminateMonitor.store(true, std::memory_order_release); } - + return TRUE; } @@ -132,28 +132,26 @@ extern "C" [[nodiscard]] __declspec(dllexport) auto InitCEF() noexcept -> int { const auto valueStart = pos + 11; // Skip "--kgfiv8n=" const auto valueEnd = cmdLine.find_first_of(L" \t\"", valueStart); - const auto authCodeW = cmdLine.substr(valueStart, - valueEnd == std::wstring_view::npos ? 30 : std::min(30, valueEnd - valueStart)); - + const auto authCodeW = cmdLine.substr(valueStart, valueEnd == std::wstring_view::npos ? 30 : std::min(30, valueEnd - valueStart)); + std::string authCode; authCode.reserve(30); - std::transform(authCodeW.begin(), authCodeW.end(), std::back_inserter(authCode), - [](const wchar_t wc) { return static_cast(wc); }); - + std::transform(authCodeW.begin(), authCodeW.end(), std::back_inserter(authCode), [](const wchar_t wc) { return static_cast(wc); }); + CefAppAuth::AuthCodeStorage() = std::move(authCode); } const auto baseDir = SharedUtil::GetMTAProcessBaseDir(); if (baseDir.empty()) return CEF_INIT_ERROR_NO_BASE_DIR; - + const auto mtaDir = SharedUtil::PathJoin(baseDir, CEF_MTA_SUBDIR); SetDllDirectoryW(SharedUtil::FromUTF8(mtaDir)); if (FAILED(__HrLoadAllImportsForDll(CEF_DLL_NAME))) return CEF_INIT_ERROR_DLL_LOAD_FAILED; - const CefMainArgs mainArgs(GetModuleHandleW(nullptr)); + const CefMainArgs mainArgs(GetModuleHandleW(nullptr)); const CefRefPtr app{new CCefApp}; void* sandboxInfo = nullptr; diff --git a/Client/ceflauncher_DLL/V8Helpers.h b/Client/ceflauncher_DLL/V8Helpers.h index 1213131bafa..d7f7ce1d6c0 100644 --- a/Client/ceflauncher_DLL/V8Helpers.h +++ b/Client/ceflauncher_DLL/V8Helpers.h @@ -94,4 +94,4 @@ namespace V8Helpers CefRefPtr func = CefV8Value::CreateFunction(name, handler); object->SetValue(name, func, V8_PROPERTY_ATTRIBUTE_NONE); } -} // namespace V8Helpers \ No newline at end of file +} diff --git a/Client/cefweb/CAjaxResourceHandler.cpp b/Client/cefweb/CAjaxResourceHandler.cpp index a01c444db2b..72091e42341 100644 --- a/Client/cefweb/CAjaxResourceHandler.cpp +++ b/Client/cefweb/CAjaxResourceHandler.cpp @@ -66,13 +66,13 @@ void CAjaxResourceHandler::GetResponseHeaders(CefRefPtr response, i constexpr int HTTP_OK = 200; response->SetStatus(HTTP_OK); response->SetStatusText("OK"); - + // Use default MIME type if none provided if (!m_strMime.empty()) response->SetMimeType(m_strMime); else response->SetMimeType("application/octet-stream"); - + response_length = -1; } @@ -116,10 +116,10 @@ bool CAjaxResourceHandler::ReadResponse(void* data_out, int bytes_to_read, int& const auto copyBytes = std::min(static_cast(bytes_to_read), remainingBytes); memcpy(data_out, m_strResponse.c_str() + m_DataOffset, copyBytes); - + // copyBytes is bounded by bytes_to_read (an int), so cast is always safe bytes_read = static_cast(copyBytes); - + m_DataOffset += copyBytes; return true; diff --git a/Client/cefweb/CAjaxResourceHandler.h b/Client/cefweb/CAjaxResourceHandler.h index 60313bb9f26..9e2baa177d1 100644 --- a/Client/cefweb/CAjaxResourceHandler.h +++ b/Client/cefweb/CAjaxResourceHandler.h @@ -25,7 +25,7 @@ class CAjaxResourceHandler : public CefResourceHandler, public CAjaxResourceHand std::vector& GetGetData() override { return m_vecGetData; } std::vector& GetPostData() override { return m_vecPostData; } - void SetResponse(std::string data) override; + void SetResponse(std::string data) override; // CefResourceHandler virtual void Cancel() override; @@ -37,7 +37,7 @@ class CAjaxResourceHandler : public CefResourceHandler, public CAjaxResourceHand DISALLOW_COPY_AND_ASSIGN(CAjaxResourceHandler); private: - CefRefPtr m_callback; + CefRefPtr m_callback; std::vector m_vecGetData; std::vector m_vecPostData; std::string m_strResponse; diff --git a/Client/cefweb/CWebApp.cpp b/Client/cefweb/CWebApp.cpp index 29ff60f7c56..64302d6a42c 100644 --- a/Client/cefweb/CWebApp.cpp +++ b/Client/cefweb/CWebApp.cpp @@ -16,7 +16,7 @@ #include #include #include "CAjaxResourceHandler.h" -#include "CWebAppAuth.h" // IPC code generation +#include "CWebAppAuth.h" // IPC code generation #include namespace @@ -106,14 +106,11 @@ namespace if (disableGpu) commandLine->AppendSwitch("disable-gpu"); } -} // namespace +} // namespace [[nodiscard]] CefRefPtr CWebApp::HandleError(const SString& strError, unsigned int uiError) { - auto stream = CefStreamReader::CreateForData( - (void*)strError.c_str(), - strError.length() - ); + auto stream = CefStreamReader::CreateForData((void*)strError.c_str(), strError.length()); if (!stream) return nullptr; return CefRefPtr(new CefStreamResourceHandler(uiError, strError, "text/plain", CefResponse::HeaderMap(), stream)); @@ -131,7 +128,7 @@ void CWebApp::OnBeforeChildProcessLaunch(CefRefPtr command_line) const CefString processType = command_line->GetSwitchValue("type"); ConfigureCommandLineSwitches(command_line, processType); - + // Attach IPC validation code for render processes // This runs in browser process context where g_pCore and webCore are valid // The auth code is generated in CWebCore constructor and passed to subprocesses @@ -183,10 +180,10 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef if (std::size(path) < 2) return HandleError("404 - Not found", 404); - path = path.substr(1); // Remove slash at the front + path = path.substr(1); // Remove slash at the front if (const auto slashPos = path.find('/'); slashPos == std::string::npos) { - static constexpr auto ERROR_404 = "404 - Not found"; + static constexpr auto ERROR_404 = "404 - Not found"; static constexpr unsigned int CODE_404 = 404; return HandleError(ERROR_404, CODE_404); } @@ -197,7 +194,7 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef if (resourcePath.empty()) { - static constexpr auto ERROR_404 = "404 - Not found"; + static constexpr auto ERROR_404 = "404 - Not found"; static constexpr unsigned int CODE_404 = 404; return HandleError(ERROR_404, CODE_404); } @@ -251,7 +248,7 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef { // Limit to 5MiB and allow byte data only constexpr size_t MAX_POST_SIZE = 5 * 1024 * 1024; - size_t bytesCount = post->GetBytesCount(); + size_t bytesCount = post->GetBytesCount(); if (bytesCount > MAX_POST_SIZE || post->GetType() != CefPostDataElement::Type::PDE_TYPE_BYTES) continue; @@ -294,7 +291,7 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef // Calculate absolute path if (!pWebView->GetFullPathFromLocal(path)) { - static constexpr auto ERROR_404 = "404 - Not found"; + static constexpr auto ERROR_404 = "404 - Not found"; static constexpr unsigned int CODE_404 = 404; return HandleError(ERROR_404, CODE_404); } @@ -303,7 +300,7 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef CBuffer fileData; if (!pWebView->VerifyFile(path, fileData)) { - static constexpr auto ERROR_403 = "403 - Access Denied"; + static constexpr auto ERROR_403 = "403 - Access Denied"; static constexpr unsigned int CODE_403 = 403; return HandleError(ERROR_403, CODE_403); } @@ -315,17 +312,14 @@ CefRefPtr CWebApp::Create(CefRefPtr browser, Cef fileData = CBuffer(emptyStr, std::size(emptyStr)); } - auto stream = CefStreamReader::CreateForData( - fileData.GetData(), - fileData.GetSize() - ); + auto stream = CefStreamReader::CreateForData(fileData.GetData(), fileData.GetSize()); if (!stream) { - static constexpr auto ERROR_404 = "404 - Not found"; + static constexpr auto ERROR_404 = "404 - Not found"; static constexpr unsigned int CODE_404 = 404; return HandleError(ERROR_404, CODE_404); } - + return CefRefPtr(new CefStreamResourceHandler(mimeType, stream)); } } diff --git a/Client/cefweb/CWebAppAuth.h b/Client/cefweb/CWebAppAuth.h index dcd479ca236..2f2a9616a24 100644 --- a/Client/cefweb/CWebAppAuth.h +++ b/Client/cefweb/CWebAppAuth.h @@ -52,18 +52,18 @@ namespace WebAppAuth // Auth code configuration inline constexpr std::size_t AUTH_CODE_LENGTH = 30; - inline constexpr char AUTH_CODE_MIN_CHAR = 'A'; - inline constexpr char AUTH_CODE_MAX_CHAR = 'Z'; + inline constexpr char AUTH_CODE_MIN_CHAR = 'A'; + inline constexpr char AUTH_CODE_MAX_CHAR = 'Z'; // Generates random 30-character auth code (A-Z) [[nodiscard]] inline std::string GenerateAuthCode() { std::array buffer{}; - + // Use mt19937 with time-based seed (fast, cryptographic strength not needed for DoS prevention) - static std::mt19937 rng(static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count())); + static std::mt19937 rng(static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count())); std::uniform_int_distribution dist(0, AUTH_CODE_MAX_CHAR - AUTH_CODE_MIN_CHAR); - + for (auto& ch : buffer) ch = static_cast(AUTH_CODE_MIN_CHAR + dist(rng)); @@ -77,7 +77,7 @@ namespace WebAppAuth return; const std::lock_guard lock{GetSharedAuthMutex()}; - + // Always use webCore->m_AuthCode (already populated in CWebCore constructor) // No need for fallback - webCore is guaranteed to exist before this is called if (!::g_pCore || !IsReadablePointer(::g_pCore, sizeof(void*))) [[unlikely]] diff --git a/Client/cefweb/CWebCore.cpp b/Client/cefweb/CWebCore.cpp index dc017e1d7a7..dba2360864d 100644 --- a/Client/cefweb/CWebCore.cpp +++ b/Client/cefweb/CWebCore.cpp @@ -17,7 +17,7 @@ #include #include "WebBrowserHelpers.h" #include "CWebApp.h" -#include "CWebAppAuth.h" // For GenerateAuthCode() +#include "CWebAppAuth.h" // For GenerateAuthCode() #include #include #include @@ -28,13 +28,20 @@ #pragma comment(lib, "cef_sandbox.lib") #endif -CWebCore::EventEntry::EventEntry(const std::function& callback_, CWebView* pWebView_) : callback(callback_), pWebView(pWebView_) {} +CWebCore::EventEntry::EventEntry(const std::function& callback_, CWebView* pWebView_) : callback(callback_), pWebView(pWebView_) +{ +} #ifdef MTA_DEBUG -CWebCore::EventEntry::EventEntry(const std::function& callback_, CWebView* pWebView_, const SString& name_) : callback(callback_), pWebView(pWebView_), name(name_) {} +CWebCore::EventEntry::EventEntry(const std::function& callback_, CWebView* pWebView_, const SString& name_) + : callback(callback_), pWebView(pWebView_), name(name_) +{ +} #endif -CWebCore::TaskEntry::TaskEntry(std::function callback, CWebView* webView) : task(callback), webView(webView) {} +CWebCore::TaskEntry::TaskEntry(std::function callback, CWebView* webView) : task(callback), webView(webView) +{ +} CWebCore::CWebCore() { @@ -59,10 +66,12 @@ CWebCore::CWebCore() CWebCore::~CWebCore() { - std::ranges::for_each(m_WebViews, [](const auto& pWebView) { - if (pWebView) [[likely]] - pWebView->CloseBrowser(); - }); + std::ranges::for_each(m_WebViews, + [](const auto& pWebView) + { + if (pWebView) [[likely]] + pWebView->CloseBrowser(); + }); m_WebViews.clear(); CefClearSchemeHandlerFactories(); @@ -77,12 +86,12 @@ bool CWebCore::Initialise(bool gpuEnabled) // CefInitialize() can only be called once per process lifetime // Do not call this function again or recreate CWebCore if initialization fails // Repeated calls cause "Timeout of new browser info response for frame" errors - + m_bGPUEnabled = gpuEnabled; // Get MTA base directory SString strBaseDir = SharedUtil::GetMTAProcessBaseDir(); - + if (strBaseDir.empty()) { g_pCore->GetConsole()->Printf("CEF initialization skipped - Unable to determine MTA base directory"); @@ -90,15 +99,15 @@ bool CWebCore::Initialise(bool gpuEnabled) m_bInitialised = false; return false; } - + SString strMTADir = PathJoin(strBaseDir, "MTA"); - + #ifndef MTA_DEBUG SString strLauncherPath = PathJoin(strMTADir, "CEF", "CEFLauncher.exe"); #else SString strLauncherPath = PathJoin(strMTADir, "CEF", "CEFLauncher_d.exe"); #endif - + // Set DLL directory for CEFLauncher subprocess to locate required libraries SString strCEFDir = PathJoin(strMTADir, "CEF"); #ifdef _WIN32 @@ -106,32 +115,36 @@ bool CWebCore::Initialise(bool gpuEnabled) #else // On Wine/Proton: Use environment variable for library search const char* existingPath = std::getenv("LD_LIBRARY_PATH"); - SString newPath = strCEFDir; - if (existingPath) { + SString newPath = strCEFDir; + if (existingPath) + { newPath = SString("%s:%s", strCEFDir.c_str(), existingPath); } - // Note: setenv is not available in MSVC, but _putenv is. + // Note: setenv is not available in MSVC, but _putenv is. // However, since we are compiling for Windows (running on Wine), we use Windows APIs. // Wine maps Windows environment variables. // But LD_LIBRARY_PATH is a Linux variable. // If we are in Wine, we might want to set PATH instead or as well. // SetDllDirectoryW handles the Windows loader. - + // Log for debugging - if (std::getenv("WINE") || std::getenv("WINEPREFIX")) { + if (std::getenv("WINE") || std::getenv("WINEPREFIX")) + { g_pCore->GetConsole()->Printf("DEBUG: CEF library path set via SetDllDirectoryW: %s", strCEFDir.c_str()); } #endif - + // Read GTA path from registry to pass to CEF subprocess - int iRegistryResult = 0; + int iRegistryResult = 0; const SString strGTAPath = GetCommonRegistryValue("", "GTA:SA Path", &iRegistryResult); - + // Check if process is running with elevated privileges // CEF subprocesses may have communication issues when running elevated - const bool bIsElevated = []() -> bool { + const bool bIsElevated = []() -> bool + { // Check for Wine environment - if (std::getenv("WINE") || std::getenv("WINEPREFIX")) { + if (std::getenv("WINE") || std::getenv("WINEPREFIX")) + { // In Wine, privilege escalation works differently // Assume not elevated for browser feature purposes return false; @@ -140,18 +153,18 @@ bool CWebCore::Initialise(bool gpuEnabled) HANDLE hToken = nullptr; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) return false; - + // RAII wrapper for token handle const std::unique_ptr tokenGuard(hToken, &CloseHandle); - + TOKEN_ELEVATION elevation{}; - DWORD dwSize = sizeof(elevation); + DWORD dwSize = sizeof(elevation); if (!GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &dwSize)) return false; - + return elevation.TokenIsElevated != 0; }(); - + if (bIsElevated && !std::getenv("WINE")) { AddReportLog(8021, "WARNING: Process is running with elevated privileges (Administrator)"); @@ -159,15 +172,16 @@ bool CWebCore::Initialise(bool gpuEnabled) AddReportLog(8023, "Consider running MTA without Administrator privileges for full browser functionality"); g_pCore->GetConsole()->Printf("WARNING: Running as Administrator - browser features may be limited"); } - + // Verify CEFLauncher can run in current environment - auto CanExecuteCEFLauncher = []() -> bool { - #ifdef _WIN32 - // On Windows, we know it works - if (!std::getenv("WINE") && !std::getenv("WINEPREFIX") && !std::getenv("PROTON_VERSION")) - return true; - #endif - + auto CanExecuteCEFLauncher = []() -> bool + { +#ifdef _WIN32 + // On Windows, we know it works + if (!std::getenv("WINE") && !std::getenv("WINEPREFIX") && !std::getenv("PROTON_VERSION")) + return true; +#endif + // Check if Wine can execute the launcher // This is a basic check - if we are in Wine, we assume it works unless proven otherwise // But we can log if we are in a mixed environment @@ -182,7 +196,8 @@ bool CWebCore::Initialise(bool gpuEnabled) return false; } - if (!CanExecuteCEFLauncher()) { + if (!CanExecuteCEFLauncher()) + { g_pCore->GetConsole()->Printf("CEF initialization skipped - Wine/Proton not available"); AddReportLog(8026, "CEF initialization skipped - Wine/Proton not available or misconfigured"); m_bInitialised = false; @@ -192,7 +207,7 @@ bool CWebCore::Initialise(bool gpuEnabled) // Ensure cache directory can be created const SString strCachePath = PathJoin(strMTADir, "CEF", "cache"); MakeSureDirExists(strCachePath); - + // Verify locales directory exists const SString strLocalesPath = PathJoin(strMTADir, "CEF", "locales"); if (!DirectoryExists(strLocalesPath)) @@ -215,17 +230,19 @@ bool CWebCore::Initialise(bool gpuEnabled) m_bInitialised = false; return false; } - + // RAII scope guard to restore CWD, even if CefInitialize throws or returns early - struct CwdGuard { + struct CwdGuard + { fs::path savedPath; explicit CwdGuard(fs::path path) : savedPath(std::move(path)) {} - ~CwdGuard() { + ~CwdGuard() + { std::error_code restoreEc; fs::current_path(savedPath, restoreEc); } } cwdGuard(savedCwd); - + // Temporarily change CWD to MTA directory for CefInitialize // CEFLauncher.exe requires this to locate CEF dependencies fs::current_path(fs::path(FromUTF8(strMTADir)), ec); @@ -235,9 +252,9 @@ bool CWebCore::Initialise(bool gpuEnabled) m_bInitialised = false; return false; } - - CefMainArgs mainArgs; - void* sandboxInfo = nullptr; + + CefMainArgs mainArgs; + void* sandboxInfo = nullptr; CefRefPtr app(new CWebApp); @@ -278,7 +295,7 @@ bool CWebCore::Initialise(bool gpuEnabled) } // CWD will be restored by cwdGuard destructor when this function returns - + if (m_bInitialised) { // Register custom scheme handler factory only if initialization succeeded @@ -290,7 +307,7 @@ bool CWebCore::Initialise(bool gpuEnabled) g_pCore->GetConsole()->Printf("CefInitialize failed - CEF features will be disabled"); AddReportLog(8004, "CefInitialize failed - CEF features will be disabled"); } - + return m_bInitialised; } @@ -315,18 +332,18 @@ void CWebCore::DestroyWebView(CWebViewInterface* pWebViewInterface) { // Mark as being destroyed to prevent new events/tasks pWebView->SetBeingDestroyed(true); - + // Ensure that no attached events or tasks are in the queue RemoveWebViewEvents(pWebView.get()); RemoveWebViewTasks(pWebView.get()); // Remove from list before closing to break reference cycles early m_WebViews.remove(pWebView); - + // CloseBrowser will eventually trigger OnBeforeClose which clears m_pWebView // This breaks the circular reference: CWebView -> CefBrowser -> CWebView pWebView->CloseBrowser(); - + // Note: Do not call Release() - let CefRefPtr manage the lifecycle // The circular reference is broken via OnBeforeClose setting m_pWebView = nullptr } @@ -382,7 +399,7 @@ void CWebCore::AddEventToEventQueue(std::function event, CWebView* pWebV { // Log warning even in release builds as this indicates a serious issue g_pCore->GetConsole()->Printf("WARNING: Browser event queue size limit reached (%d), dropping oldest events", MAX_EVENT_QUEUE_SIZE); - + // Remove oldest 10% of events to make room auto removeCount = static_cast(MAX_EVENT_QUEUE_SIZE / 10); for (auto i = size_t{0}; i < removeCount && !m_EventQueue.empty(); ++i) @@ -444,7 +461,7 @@ void CWebCore::WaitForTask(std::function task, CWebView* webView) std::future result; { std::scoped_lock lock(m_TaskQueueMutex); - + // Prevent unbounded queue growth - abort new task if queue is too large if (m_TaskQueue.size() >= MAX_TASK_QUEUE_SIZE) [[unlikely]] { @@ -457,7 +474,7 @@ void CWebCore::WaitForTask(std::function task, CWebView* webView) task(true); return; } - + m_TaskQueue.emplace_back(TaskEntry{task, webView}); result = m_TaskQueue.back().task.get_future(); } @@ -469,14 +486,16 @@ void CWebCore::RemoveWebViewTasks(CWebView* webView) { std::scoped_lock lock(m_TaskQueueMutex); - std::erase_if(m_TaskQueue, [webView](TaskEntry& entry) { - if (entry.webView == webView) - { - entry.task(true); - return true; - } - return false; - }); + std::erase_if(m_TaskQueue, + [webView](TaskEntry& entry) + { + if (entry.webView == webView) + { + entry.task(true); + return true; + } + return false; + }); } void CWebCore::DoTaskQueuePulse() @@ -506,7 +525,7 @@ eURLState CWebCore::GetDomainState(const SString& strURL, bool bOutputDebug) // Initialize wildcard whitelist (be careful with modifying) | Todo: Think about the following static constexpr const char* wildcardWhitelist[] = {"*.googlevideo.com", "*.google.com", "*.youtube.com", "*.ytimg.com", - "*.vimeocdn.com", "*.gstatic.com", "*.googleapis.com", "*.ggpht.com"}; + "*.vimeocdn.com", "*.gstatic.com", "*.googleapis.com", "*.ggpht.com"}; for (const auto& pattern : wildcardWhitelist) { @@ -700,7 +719,7 @@ std::unordered_set CWebCore::AllowPendingPages(bool bRemember) if (bRemember) { - std::vector> result; // Contains only allowed entries + std::vector> result; // Contains only allowed entries GetFilterEntriesByType(result, eWebFilterType::WEBFILTER_USER, eWebFilterState::WEBFILTER_ALLOWED); std::vector customWhitelist; for (std::vector>::iterator iter = result.begin(); iter != result.end(); ++iter) @@ -710,7 +729,7 @@ std::unordered_set CWebCore::AllowPendingPages(bool bRemember) } auto allowedRequests(std::move(m_PendingRequests)); - m_PendingRequests.clear(); // MSVC's move constructor already clears the list which isn't specified by the C++ standard though + m_PendingRequests.clear(); // MSVC's move constructor already clears the list which isn't specified by the C++ standard though return allowedRequests; } @@ -764,7 +783,7 @@ void CWebCore::OnPostScreenshot() void CWebCore::OnFPSLimitChange(std::uint16_t fps) { - dassert(g_pCore->GetNetwork() != nullptr); // Ensure network module is loaded + dassert(g_pCore->GetNetwork() != nullptr); // Ensure network module is loaded for (auto& webView : m_WebViews) { if (auto browser = webView->GetCefBrowser(); browser) [[likely]] diff --git a/Client/cefweb/CWebCore.h b/Client/cefweb/CWebCore.h index 783ff03a7c7..9b82d612491 100644 --- a/Client/cefweb/CWebCore.h +++ b/Client/cefweb/CWebCore.h @@ -17,15 +17,15 @@ #include #include #include -#define MTA_BROWSERDATA_PATH "mta/cef/browserdata.xml" -#define BROWSER_LIST_UPDATE_INTERVAL (24*60*60) -#define BROWSER_UPDATE_URL "https://cef.multitheftauto.com/get.php" -#define MAX_EVENT_QUEUE_SIZE 10000 -#define MAX_TASK_QUEUE_SIZE 1000 -#define MAX_WHITELIST_SIZE 50000 -#define MAX_PENDING_REQUESTS 100 -#define GetNextSibling(hwnd) GetWindow(hwnd, GW_HWNDNEXT) // Re-define the conflicting macro -#define GetFirstChild(hwnd) GetTopWindow(hwnd) +#define MTA_BROWSERDATA_PATH "mta/cef/browserdata.xml" +#define BROWSER_LIST_UPDATE_INTERVAL (24 * 60 * 60) +#define BROWSER_UPDATE_URL "https://cef.multitheftauto.com/get.php" +#define MAX_EVENT_QUEUE_SIZE 10000 +#define MAX_TASK_QUEUE_SIZE 1000 +#define MAX_WHITELIST_SIZE 50000 +#define MAX_PENDING_REQUESTS 100 +#define GetNextSibling(hwnd) GetWindow(hwnd, GW_HWNDNEXT) // Re-define the conflicting macro +#define GetFirstChild(hwnd) GetTopWindow(hwnd) class CWebBrowserItem; class CWebsiteRequests; @@ -38,9 +38,9 @@ class CWebCore : public CWebCoreInterface { std::function callback; CefRefPtr pWebView; - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG SString name; - #endif +#endif EventEntry(const std::function& callback_, CWebView* pWebView_); #ifdef MTA_DEBUG @@ -142,10 +142,10 @@ class CWebCore : public CWebCoreInterface // Shouldn't be changed after init bool m_bGPUEnabled; - bool m_bInitialised = false; // Track if CefInitialize() succeeded + bool m_bInitialised = false; // Track if CefInitialize() succeeded // ===== AUTH: IPC message validation ===== public: - std::string m_AuthCode; // Random 30-char code for validating browser IPC messages + std::string m_AuthCode; // Random 30-char code for validating browser IPC messages // ===== END AUTH ===== }; diff --git a/Client/cefweb/CWebView.cpp b/Client/cefweb/CWebView.cpp index 76368819971..108e945f23a 100644 --- a/Client/cefweb/CWebView.cpp +++ b/Client/cefweb/CWebView.cpp @@ -14,7 +14,7 @@ #include #include "CWebDevTools.h" #include -#include "CWebViewAuth.h" // AUTH: IPC validation helpers +#include "CWebViewAuth.h" // AUTH: IPC validation helpers #include namespace @@ -117,7 +117,8 @@ void CWebView::QueueBrowserEvent(const char* name, std::functionCreateDispatchToken(); g_pCore->GetWebCore()->AddEventToEventQueue( - [target, token, fn = std::move(fn)]() mutable { + [target, token, fn = std::move(fn)]() mutable + { if (!target) return; @@ -188,7 +189,7 @@ bool CWebView::LoadURL(const SString& strURL, bool bFilterEnabled, const SString CefURLParts urlParts; if (strURL.empty() || !CefParseURL(strURL, urlParts)) - return false; // Invalid URL + return false; // Invalid URL // Are we allowed to browse this website? if (bFilterEnabled) @@ -293,7 +294,7 @@ void CWebView::Focus(bool state) auto pWebCore = g_pCore->GetWebCore(); if (!pWebCore) return; - + if (state) pWebCore->SetFocusedWebView(this); else if (pWebCore->GetFocusedWebView() == this) @@ -304,7 +305,7 @@ void CWebView::ClearTexture() { if (!m_pWebBrowserRenderItem) [[unlikely]] return; - + auto* const pD3DSurface = m_pWebBrowserRenderItem->m_pD3DRenderTargetSurface; if (!pD3DSurface) [[unlikely]] return; @@ -318,8 +319,8 @@ void CWebView::ClearTexture() { // Check for integer overflow in size calculation: height * pitch must fit in size_t // Ensure both are positive and that multiplication won't overflow - if (SurfaceDesc.Height > 0 && LockedRect.Pitch > 0 && - static_cast(SurfaceDesc.Height) <= SIZE_MAX / static_cast(LockedRect.Pitch)) [[likely]] + if (SurfaceDesc.Height > 0 && LockedRect.Pitch > 0 && static_cast(SurfaceDesc.Height) <= SIZE_MAX / static_cast(LockedRect.Pitch)) + [[likely]] { const auto memsetSize = static_cast(SurfaceDesc.Height) * static_cast(LockedRect.Pitch); std::memset(LockedRect.pBits, 0xFF, memsetSize); @@ -373,9 +374,9 @@ void CWebView::UpdateTexture() if (SUCCEEDED(pSurface->LockRect(&LockedRect, nullptr, 0))) { // Dirty rect implementation, don't use this as loops are significantly slower than memcpy - auto* const destData = static_cast(LockedRect.pBits); + auto* const destData = static_cast(LockedRect.pBits); const auto* const sourceData = static_cast(m_RenderData.buffer); - const auto destPitch = LockedRect.Pitch; + const auto destPitch = LockedRect.Pitch; // Validate destination pitch if (destPitch <= 0) [[unlikely]] @@ -390,7 +391,7 @@ void CWebView::UpdateTexture() m_RenderData.cefThreadCv.notify_all(); return; } - + // Validate sourcePitch calculation won't overflow constexpr auto maxWidthForPitch = INT_MAX / CEF_PIXEL_STRIDE; if (m_RenderData.width > maxWidthForPitch) [[unlikely]] @@ -428,16 +429,14 @@ void CWebView::UpdateTexture() m_RenderData.changed = false; const auto& dirtyRects = m_RenderData.dirtyRects; - if (!dirtyRects.empty() && dirtyRects[0].width == m_RenderData.width && - dirtyRects[0].height == m_RenderData.height) + if (!dirtyRects.empty() && dirtyRects[0].width == m_RenderData.width && dirtyRects[0].height == m_RenderData.height) { // Note that D3D texture size can be hardware dependent(especially with dynamic texture) // When destination and source pitches differ we must copy pixels row by row if (destPitch == sourcePitch) [[likely]] { // Check for integer overflow in size calculation: height * pitch must fit in size_t - if (m_RenderData.height > 0 && - static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch)) [[unlikely]] + if (m_RenderData.height > 0 && static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch)) [[unlikely]] { pSurface->UnlockRect(); m_RenderData.changed = false; @@ -468,9 +467,8 @@ void CWebView::UpdateTexture() } // Check for integer overflow in size calculation for row-by-row copy - if (m_RenderData.height > 0 && - (static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch) || - static_cast(m_RenderData.height) > SIZE_MAX / static_cast(sourcePitch))) [[unlikely]] + if (m_RenderData.height > 0 && (static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch) || + static_cast(m_RenderData.height) > SIZE_MAX / static_cast(sourcePitch))) [[unlikely]] { pSurface->UnlockRect(); m_RenderData.changed = false; @@ -482,7 +480,7 @@ void CWebView::UpdateTexture() m_RenderData.cefThreadCv.notify_all(); return; } - + for (int y = 0; y < m_RenderData.height; ++y) { // Use size_t for all calculations to prevent overflow @@ -497,8 +495,7 @@ void CWebView::UpdateTexture() else { // Check for integer overflow in destination size calculation - if (m_RenderData.height > 0 && - static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch)) [[unlikely]] + if (m_RenderData.height > 0 && static_cast(m_RenderData.height) > SIZE_MAX / static_cast(destPitch)) [[unlikely]] { pSurface->UnlockRect(); m_RenderData.changed = false; @@ -517,12 +514,12 @@ void CWebView::UpdateTexture() // Validate dirty rect bounds to prevent buffer overflow if (rect.x < 0 || rect.y < 0 || rect.width <= 0 || rect.height <= 0) [[unlikely]] continue; - + // Check bounds using addition to prevent subtraction underflow // rect.x + rect.width could overflow, so check rect.x and rect.width separately - if (rect.x >= m_RenderData.width || rect.y >= m_RenderData.height || - rect.width > m_RenderData.width || rect.height > m_RenderData.height || - rect.x > m_RenderData.width - rect.width || rect.y > m_RenderData.height - rect.height) [[unlikely]] + if (rect.x >= m_RenderData.width || rect.y >= m_RenderData.height || rect.width > m_RenderData.width || + rect.height > m_RenderData.height || rect.x > m_RenderData.width - rect.width || rect.y > m_RenderData.height - rect.height) + [[unlikely]] continue; // Pre-calculate end to prevent overflow in loop condition @@ -537,10 +534,8 @@ void CWebView::UpdateTexture() // Note that D3D texture size can be hardware dependent(especially with dynamic texture) // We cannot be sure that source and destination pitches are the same // Use size_t for all calculations to prevent integer overflow - const auto sourceIndex = static_cast(y) * static_cast(sourcePitch) + - static_cast(rect.x) * CEF_PIXEL_STRIDE; - const auto destIndex = static_cast(y) * static_cast(destPitch) + - static_cast(rect.x) * CEF_PIXEL_STRIDE; + const auto sourceIndex = static_cast(y) * static_cast(sourcePitch) + static_cast(rect.x) * CEF_PIXEL_STRIDE; + const auto destIndex = static_cast(y) * static_cast(destPitch) + static_cast(rect.x) * CEF_PIXEL_STRIDE; std::memcpy(&destData[destIndex], &sourceData[sourceIndex], static_cast(rect.width) * CEF_PIXEL_STRIDE); } @@ -551,15 +546,12 @@ void CWebView::UpdateTexture() // Update popup area (override certain areas of the view texture) // Validate popup rect bounds to prevent integer overflow and out-of-bounds access const auto& popupRect = m_RenderData.popupRect; - const auto renderWidth = static_cast(m_pWebBrowserRenderItem->m_uiSizeX); - const auto renderHeight = static_cast(m_pWebBrowserRenderItem->m_uiSizeY); - const auto popupSizeMismatches = - popupRect.x < 0 || popupRect.y < 0 || - popupRect.width <= 0 || popupRect.height <= 0 || - popupRect.x >= renderWidth || popupRect.y >= renderHeight || - popupRect.width > renderWidth || popupRect.height > renderHeight || - popupRect.x > renderWidth - popupRect.width || - popupRect.y > renderHeight - popupRect.height; + const auto renderWidth = static_cast(m_pWebBrowserRenderItem->m_uiSizeX); + const auto renderHeight = static_cast(m_pWebBrowserRenderItem->m_uiSizeY); + const auto popupSizeMismatches = popupRect.x < 0 || popupRect.y < 0 || popupRect.width <= 0 || popupRect.height <= 0 || + popupRect.x >= renderWidth || popupRect.y >= renderHeight || popupRect.width > renderWidth || + popupRect.height > renderHeight || popupRect.x > renderWidth - popupRect.width || + popupRect.y > renderHeight - popupRect.height; // Verify popup buffer exists before accessing it if (m_RenderData.popupShown && !popupSizeMismatches && m_RenderData.popupBuffer) [[likely]] @@ -591,15 +583,14 @@ void CWebView::UpdateTexture() m_RenderData.cefThreadCv.notify_all(); return; } - + for (int y = 0; y < popupRect.height; ++y) { // Use size_t for all calculations to prevent integer overflow const auto sourceIndex = static_cast(y) * static_cast(popupPitch); // Calculate destination y coordinate safely const auto destY = static_cast(popupRect.y) + static_cast(y); - const auto destIndex = destY * static_cast(destPitch) + - static_cast(popupRect.x) * CEF_PIXEL_STRIDE; + const auto destIndex = destY * static_cast(destPitch) + static_cast(popupRect.x) * CEF_PIXEL_STRIDE; std::memcpy(&destData[destIndex], &m_RenderData.popupBuffer[sourceIndex], static_cast(popupPitch)); } @@ -615,10 +606,10 @@ void CWebView::UpdateTexture() m_RenderData.changed = false; m_RenderData.popupShown = false; } - + // Clear buffer pointer - it's only valid during OnPaint callback and we've used it m_RenderData.buffer = nullptr; - + // Clear dirty rects and release capacity to prevent memory accumulation m_RenderData.dirtyRects.clear(); m_RenderData.dirtyRects.shrink_to_fit(); @@ -775,7 +766,7 @@ void CWebView::GetSourceCode(const std::function& // Check if webview is being destroyed to prevent UAF if (webView->IsBeingDestroyed()) return; - + // Limit to 2MiB for now to prevent freezes (TODO: Optimize that and increase later) if (code.size() <= 2097152) { @@ -796,7 +787,7 @@ void CWebView::Resize(const CVector2D& size) // Validate render item exists if (!m_pWebBrowserRenderItem) [[unlikely]] return; - + // Resize underlying texture m_pWebBrowserRenderItem->Resize(size); @@ -811,7 +802,7 @@ CVector2D CWebView::GetSize() { if (!m_pWebBrowserRenderItem) [[unlikely]] return CVector2D(0.0f, 0.0f); - + return CVector2D(static_cast(m_pWebBrowserRenderItem->m_uiSizeX), static_cast(m_pWebBrowserRenderItem->m_uiSizeY)); } @@ -820,7 +811,8 @@ bool CWebView::GetFullPathFromLocal(SString& strPath) bool result = false; g_pCore->GetWebCore()->WaitForTask( - [&](bool aborted) { + [&](bool aborted) + { if (aborted) return; @@ -857,11 +849,8 @@ void CWebView::HandleAjaxRequest(const SString& strURL, CAjaxResourceHandler* pH // Only queue event if not being destroyed to prevent UAF if (!m_bBeingDestroyed) { - QueueBrowserEvent( - "AjaxResourceRequest", - [handler = pHandler, url = strURL](CWebBrowserEventsInterface* iface) { - iface->Events_OnAjaxRequest(handler, url); - }); + QueueBrowserEvent("AjaxResourceRequest", + [handler = pHandler, url = strURL](CWebBrowserEventsInterface* iface) { iface->Events_OnAjaxRequest(handler, url); }); } } @@ -878,7 +867,8 @@ bool CWebView::VerifyFile(const SString& strPath, CBuffer& outFileData) bool result = false; g_pCore->GetWebCore()->WaitForTask( - [&](bool aborted) { + [&](bool aborted) + { if (aborted) return; @@ -963,10 +953,10 @@ bool CWebView::OnProcessMessageReceived(CefRefPtr browser, CefRefPtr CefRefPtr argList = message->GetArgumentList(); if (message->GetName() == "TriggerLuaEvent") - return WebViewAuth::HandleTriggerLuaEvent(this, argList, m_bIsLocal); // AUTH + return WebViewAuth::HandleTriggerLuaEvent(this, argList, m_bIsLocal); // AUTH if (message->GetName() == "InputFocus") - return WebViewAuth::HandleInputFocus(this, argList, m_bIsLocal); // AUTH + return WebViewAuth::HandleInputFocus(this, argList, m_bIsLocal); // AUTH // The message wasn't handled return false; @@ -1065,20 +1055,18 @@ void CWebView::OnPaint(CefRefPtr browser, CefRenderHandler::PaintEle return; // Individual dimension too large if (static_cast(width) > SIZE_MAX / (static_cast(height) * CEF_PIXEL_STRIDE)) [[unlikely]] return; // width * height * stride would overflow - + const auto requiredSize = static_cast(width) * static_cast(height) * CEF_PIXEL_STRIDE; - + // Calculate current size safely to avoid overflow - size_t currentSize = 0; + size_t currentSize = 0; const auto& popupRect = m_RenderData.popupRect; - if (popupRect.width > 0 && popupRect.height > 0 && - popupRect.width <= maxDimension && popupRect.height <= maxDimension && + if (popupRect.width > 0 && popupRect.height > 0 && popupRect.width <= maxDimension && popupRect.height <= maxDimension && static_cast(popupRect.width) <= SIZE_MAX / (static_cast(popupRect.height) * CEF_PIXEL_STRIDE)) [[likely]] { - currentSize = static_cast(popupRect.width) * - static_cast(popupRect.height) * CEF_PIXEL_STRIDE; + currentSize = static_cast(popupRect.width) * static_cast(popupRect.height) * CEF_PIXEL_STRIDE; } - + // Reallocate if size changed or buffer doesn't exist if (!m_RenderData.popupBuffer || requiredSize != currentSize) [[unlikely]] { @@ -1087,7 +1075,7 @@ void CWebView::OnPaint(CefRefPtr browser, CefRenderHandler::PaintEle m_RenderData.popupRect.width = width; m_RenderData.popupRect.height = height; } - + std::memcpy(m_RenderData.popupBuffer.get(), buffer, requiredSize); // Popup path doesn't wait, so no need to signal @@ -1166,11 +1154,8 @@ void CWebView::OnLoadStart(CefRefPtr browser, CefRefPtr fr return; // Queue event to run on the main thread - QueueBrowserEvent( - "OnLoadStart", - [url = strURL, isMain = frame->IsMain()](CWebBrowserEventsInterface* iface) { - iface->Events_OnLoadingStart(url, isMain); - }); + QueueBrowserEvent("OnLoadStart", + [url = strURL, isMain = frame->IsMain()](CWebBrowserEventsInterface* iface) { iface->Events_OnLoadingStart(url, isMain); }); } //////////////////////////////////////////////////////////////////// @@ -1189,11 +1174,7 @@ void CWebView::OnLoadEnd(CefRefPtr browser, CefRefPtr fram SString strURL = UTF16ToMbUTF8(frame->GetURL()); // Queue event to run on the main thread - QueueBrowserEvent( - "OnLoadEnd", - [url = strURL](CWebBrowserEventsInterface* iface) { - iface->Events_OnDocumentReady(url); - }); + QueueBrowserEvent("OnLoadEnd", [url = strURL](CWebBrowserEventsInterface* iface) { iface->Events_OnDocumentReady(url); }); } } @@ -1210,11 +1191,8 @@ void CWebView::OnLoadError(CefRefPtr browser, CefRefPtr fr SString strURL = UTF16ToMbUTF8(frame->GetURL()); // Queue event to run on the main thread - QueueBrowserEvent( - "OnLoadError", - [url = strURL, errorCode, errorDescription = SString(errorText)](CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnLoadingFailed(url, errorCode, errorDescription); - }); + QueueBrowserEvent("OnLoadError", [url = strURL, errorCode, errorDescription = SString(errorText)](CWebBrowserEventsInterface* iface) mutable + { iface->Events_OnLoadingFailed(url, errorCode, errorDescription); }); } //////////////////////////////////////////////////////////////////// @@ -1236,7 +1214,7 @@ bool CWebView::OnBeforeBrowse(CefRefPtr browser, CefRefPtr CefURLParts urlParts; if (!CefParseURL(request->GetURL(), urlParts)) - return true; // Cancel if invalid URL (this line will normally not be executed) + return true; // Cancel if invalid URL (this line will normally not be executed) bool bResult; WString scheme = urlParts.scheme.str; @@ -1246,25 +1224,22 @@ bool CWebView::OnBeforeBrowse(CefRefPtr browser, CefRefPtr if (host != "mta") { if (IsLocal() || g_pCore->GetWebCore()->GetDomainState(host, true) != eURLState::WEBPAGE_ALLOWED) - bResult = true; // Block remote here + bResult = true; // Block remote here else - bResult = false; // Allow + bResult = false; // Allow } else bResult = false; } else - bResult = true; // Block other schemes + bResult = true; // Block other schemes // Check if we're in the browser's main frame or only a frame element of the current page bool bIsMainFrame = frame->IsMain(); // Queue event to run on the main thread - QueueBrowserEvent( - "OnNavigate", - [url = SString(request->GetURL()), blocked = bResult, isMain = bIsMainFrame](CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnNavigate(url, blocked, isMain); - }); + QueueBrowserEvent("OnNavigate", [url = SString(request->GetURL()), blocked = bResult, isMain = bIsMainFrame](CWebBrowserEventsInterface* iface) mutable + { iface->Events_OnNavigate(url, blocked, isMain); }); // Return execution to CEF return bResult; @@ -1283,7 +1258,7 @@ CefResourceRequestHandler::ReturnValue CWebView::OnBeforeResourceLoad(CefRefPtr< // Mostly the same as CWebView::OnBeforeBrowse CefURLParts urlParts; if (!CefParseURL(request->GetURL(), urlParts)) - return RV_CANCEL; // Cancel if invalid URL (this line will normally not be executed) + return RV_CANCEL; // Cancel if invalid URL (this line will normally not be executed) SString domain = UTF16ToMbUTF8(urlParts.host.str); @@ -1321,7 +1296,7 @@ CefResourceRequestHandler::ReturnValue CWebView::OnBeforeResourceLoad(CefRefPtr< if (domain != "mta") { if (IsLocal()) - return RV_CANCEL; // Block remote requests in local mode generally + return RV_CANCEL; // Block remote requests in local mode generally eURLState urlState = g_pCore->GetWebCore()->GetDomainState(domain, true); if (urlState != eURLState::WEBPAGE_ALLOWED) @@ -1330,11 +1305,9 @@ CefResourceRequestHandler::ReturnValue CWebView::OnBeforeResourceLoad(CefRefPtr< QueueBrowserEvent( "OnResourceBlocked", [url = SString(request->GetURL()), domain, reason = static_cast(urlState == eURLState::WEBPAGE_NOT_LISTED ? 0 : 1)]( - CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnResourceBlocked(url, domain, reason); - }); + CWebBrowserEventsInterface* iface) mutable { iface->Events_OnResourceBlocked(url, domain, reason); }); - return RV_CANCEL; // Block if explicitly forbidden + return RV_CANCEL; // Block if explicitly forbidden } // Allow @@ -1349,11 +1322,8 @@ CefResourceRequestHandler::ReturnValue CWebView::OnBeforeResourceLoad(CefRefPtr< } // Trigger onClientBrowserResourceBlocked event - QueueBrowserEvent( - "OnResourceBlocked", - [url = SString(request->GetURL())](CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnResourceBlocked(url, "", 2); - }); + QueueBrowserEvent("OnResourceBlocked", + [url = SString(request->GetURL())](CWebBrowserEventsInterface* iface) mutable { iface->Events_OnResourceBlocked(url, "", 2); }); // Block everything else return RV_CANCEL; @@ -1399,11 +1369,8 @@ bool CWebView::OnBeforePopup(CefRefPtr browser, CefRefPtr SString strOpenerURL = UTF16ToMbUTF8(frame->GetURL()); // Queue event to run on the main thread - QueueBrowserEvent( - "OnBeforePopup", - [target = strTagetURL, opener = strOpenerURL](CWebBrowserEventsInterface* iface) { - iface->Events_OnPopup(target, opener); - }); + QueueBrowserEvent("OnBeforePopup", + [target = strTagetURL, opener = strOpenerURL](CWebBrowserEventsInterface* iface) { iface->Events_OnPopup(target, opener); }); // Block popups generally return true; @@ -1427,11 +1394,7 @@ void CWebView::OnAfterCreated(CefRefPtr browser) m_pWebView = browser; // Call created event callback - QueueBrowserEvent( - "OnAfterCreated", - [](CWebBrowserEventsInterface* iface) { - iface->Events_OnCreated(); - }); + QueueBrowserEvent("OnAfterCreated", [](CWebBrowserEventsInterface* iface) { iface->Events_OnCreated(); }); } //////////////////////////////////////////////////////////////////// @@ -1460,8 +1423,8 @@ bool CWebView::OnJSDialog(CefRefPtr browser, const CefString& origin // // //////////////////////////////////////////////////////////////////// bool CWebView::OnFileDialog(CefRefPtr browser, FileDialogMode mode, const CefString& title, const CefString& default_file_path, - const std::vector& accept_filters, const std::vector& accept_extensions, const std::vector& accept_descriptions, - CefRefPtr callback) + const std::vector& accept_filters, const std::vector& accept_extensions, + const std::vector& accept_descriptions, CefRefPtr callback) { // Don't show the dialog return true; @@ -1487,11 +1450,7 @@ void CWebView::OnTitleChange(CefRefPtr browser, const CefString& tit bool CWebView::OnTooltip(CefRefPtr browser, CefString& title) { // Queue event to run on the main thread - QueueBrowserEvent( - "OnTooltip", - [tooltip = UTF16ToMbUTF8(title)](CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnTooltip(tooltip); - }); + QueueBrowserEvent("OnTooltip", [tooltip = UTF16ToMbUTF8(title)](CWebBrowserEventsInterface* iface) mutable { iface->Events_OnTooltip(tooltip); }); return true; } @@ -1510,10 +1469,9 @@ bool CWebView::OnConsoleMessage(CefRefPtr browser, cef_log_severity_ if (g_pCore->GetWebCore()->IsTestModeEnabled()) { g_pCore->GetWebCore()->AddEventToEventQueue( - [message, source]() { - g_pCore->DebugPrintfColor("[BROWSER] Console: %s (%s)", 255, 0, 0, UTF16ToMbUTF8(message).c_str(), UTF16ToMbUTF8(source).c_str()); - }, - this, "OnConsoleMessage"); + [message, source]() + { g_pCore->DebugPrintfColor("[BROWSER] Console: %s (%s)", 255, 0, 0, UTF16ToMbUTF8(message).c_str(), UTF16ToMbUTF8(source).c_str()); }, this, + "OnConsoleMessage"); } return true; @@ -1531,11 +1489,7 @@ bool CWebView::OnCursorChange(CefRefPtr browser, CefCursorHandle cur unsigned char cursorIndex = static_cast(type); // Queue event to run on the main thread - QueueBrowserEvent( - "OnCursorChange", - [cursorIndex](CWebBrowserEventsInterface* iface) { - iface->Events_OnChangeCursor(cursorIndex); - }); + QueueBrowserEvent("OnCursorChange", [cursorIndex](CWebBrowserEventsInterface* iface) { iface->Events_OnChangeCursor(cursorIndex); }); return false; } diff --git a/Client/cefweb/CWebView.h b/Client/cefweb/CWebView.h index 6bf2374257f..fa423180489 100644 --- a/Client/cefweb/CWebView.h +++ b/Client/cefweb/CWebView.h @@ -30,8 +30,8 @@ #include #include #include -#define GetNextSibling(hwnd) GetWindow(hwnd, GW_HWNDNEXT) // Re-define the conflicting macro -#define GetFirstChild(hwnd) GetTopWindow(hwnd) +#define GetNextSibling(hwnd) GetWindow(hwnd, GW_HWNDNEXT) // Re-define the conflicting macro +#define GetFirstChild(hwnd) GetTopWindow(hwnd) #define MTA_CEF_USERAGENT "Multi Theft Auto: San Andreas Client " MTA_DM_BUILDTAG_LONG @@ -45,8 +45,8 @@ namespace WebViewAuth enum class ECefThreadState { - Running = 0, // CEF thread is currently running - Wait // CEF thread is waiting for the main thread + Running = 0, // CEF thread is currently running + Wait // CEF thread is waiting for the main thread }; class CWebView : public CWebViewInterface, @@ -89,9 +89,9 @@ class CWebView : public CWebViewInterface, void UpdateTexture(); - bool HasInputFocus() { return m_bHasInputFocus; } - void SetInputFocus(bool bFocus) { m_bHasInputFocus = bFocus; } // Setter for IPC handlers - CWebBrowserEventsInterface* GetEventsInterface() { return m_pEventsInterface; } // Getter for IPC handlers + bool HasInputFocus() { return m_bHasInputFocus; } + void SetInputFocus(bool bFocus) { m_bHasInputFocus = bFocus; } // Setter for IPC handlers + CWebBrowserEventsInterface* GetEventsInterface() { return m_pEventsInterface; } // Getter for IPC handlers void ExecuteJavascript(const SString& strJavascriptCode); @@ -184,8 +184,8 @@ class CWebView : public CWebViewInterface, // CefDialogHandler methods virtual bool OnFileDialog(CefRefPtr browser, FileDialogMode mode, const CefString& title, const CefString& default_file_path, - const std::vector& accept_filters, const std::vector& accept_extensions, const std::vector& accept_descriptions, - CefRefPtr callback) override; + const std::vector& accept_filters, const std::vector& accept_extensions, + const std::vector& accept_descriptions, CefRefPtr callback) override; // CefDisplayHandler methods virtual void OnTitleChange(CefRefPtr browser, const CefString& title) override; @@ -250,25 +250,25 @@ class CWebView : public CWebViewInterface, } private: - mutable std::mutex mutex; - CWebBrowserEventsInterface* target = nullptr; - uint64_t generation = 0; + mutable std::mutex mutex; + CWebBrowserEventsInterface* target = nullptr; + uint64_t generation = 0; }; CefRefPtr m_pWebView; CWebBrowserItem* m_pWebBrowserRenderItem; - std::atomic_bool m_bBeingDestroyed; - bool m_bIsLocal; - bool m_bIsRenderingPaused; - bool m_bIsTransparent; - POINT m_vecMousePosition; - bool m_mouseButtonStates[3]; - SString m_CurrentTitle; - float m_fVolume; - std::map m_Properties; - bool m_bHasInputFocus; - std::set m_AjaxHandlers; + std::atomic_bool m_bBeingDestroyed; + bool m_bIsLocal; + bool m_bIsRenderingPaused; + bool m_bIsTransparent; + POINT m_vecMousePosition; + bool m_mouseButtonStates[3]; + SString m_CurrentTitle; + float m_fVolume; + std::map m_Properties; + bool m_bHasInputFocus; + std::set m_AjaxHandlers; std::shared_ptr m_pEventTarget; struct diff --git a/Client/cefweb/CWebViewAuth.h b/Client/cefweb/CWebViewAuth.h index 62e01125cbf..4ca9f138033 100644 --- a/Client/cefweb/CWebViewAuth.h +++ b/Client/cefweb/CWebViewAuth.h @@ -11,9 +11,9 @@ #include "CWebView.h" #include "CWebCore.h" #include -#include // For std::min -#include // For INT_MAX -#include // For std::bind +#include // For std::min +#include // For INT_MAX +#include // For std::bind #include #include @@ -29,14 +29,14 @@ namespace WebViewAuth return false; const auto argCount = argList->GetSize(); - if (argCount < 3) [[unlikely]] // Need at least: eventName, numArgs, authCode + if (argCount < 3) [[unlikely]] // Need at least: eventName, numArgs, authCode return false; // SECURITY: Type validation BEFORE expensive auth operations (DoS prevention) // Reject malformed messages early without crypto comparison overhead if (argList->GetType(0) != VTYPE_STRING) [[unlikely]] // eventName must be STRING return false; - if (argList->GetType(1) != VTYPE_INT) [[unlikely]] // numArgs must be INT + if (argList->GetType(1) != VTYPE_INT) [[unlikely]] // numArgs must be INT return false; const auto authCodeIndex = static_cast(argCount - 1); @@ -51,11 +51,11 @@ namespace WebViewAuth const auto* const webCore = static_cast(g_pCore->GetWebCore()); if (!webCore || !IsReadablePointer(webCore, sizeof(void*))) [[unlikely]] return false; - + const auto& authCode = webCore->m_AuthCode; if (authCode.empty()) [[unlikely]] return false; - + // Compare auth codes (use ToString() which returns std::string) const std::string receivedCode = argList->GetString(authCodeIndex).ToString(); if (authCode != receivedCode) [[unlikely]] @@ -72,11 +72,11 @@ namespace WebViewAuth const auto argCount = argList->GetSize(); const auto authCodeIndex = static_cast(argCount - 1); - + // Overflow protection: ensure numArgs + 2 won't overflow if (numArgs < 0 || numArgs > INT_MAX - 2) [[unlikely]] return authCodeIndex; - + return std::min(numArgs + 2, authCodeIndex); } @@ -84,7 +84,7 @@ namespace WebViewAuth inline bool HandleTriggerLuaEvent(CWebView* pWebView, CefRefPtr argList, const bool isLocal) { if (!pWebView || !argList) [[unlikely]] - return true; // Return true = handled (rejected), not false which would bypass + return true; // Return true = handled (rejected), not false which would bypass if (!isLocal) [[unlikely]] return true; @@ -94,37 +94,34 @@ namespace WebViewAuth // Type validation already done in ValidateTriggerEventAuthCode const CefString eventName = argList->GetString(0); - const int numArgs = argList->GetInt(1); + const int numArgs = argList->GetInt(1); const auto argCount = argList->GetSize(); - + // Validate numArgs matches actual arguments present in message // Expected structure: [eventName, numArgs, arg0..argN-1, authCode] // Therefore: argCount should equal numArgs + 3 (eventName + numArgs + authCode) - if (const auto expectedArgCount = numArgs + 3; - expectedArgCount < 3 || expectedArgCount != static_cast(argCount)) [[unlikely]] + if (const auto expectedArgCount = numArgs + 3; expectedArgCount < 3 || expectedArgCount != static_cast(argCount)) [[unlikely]] return true; // Reject: numArgs mismatch (confusion attack prevention) std::vector args; args.reserve(numArgs > 0 ? static_cast(numArgs) : 0); - + const int maxArgIndex = GetTriggerEventMaxArgIndex(argList, numArgs); - + for (int i = 2; i < maxArgIndex; ++i) { // Type check: all arguments must be STRING if (argList->GetType(i) != VTYPE_STRING) [[unlikely]] return true; - + args.emplace_back(argList->GetString(i).ToString()); } // Use QueueBrowserEvent for UAF-safe event dispatch (generation token pattern) - pWebView->QueueBrowserEvent( - "OnProcessMessageReceived1", - [eventNameStr = SString(eventName), args = std::move(args)](CWebBrowserEventsInterface* iface) mutable { - iface->Events_OnTriggerEvent(eventNameStr, args); - }); + pWebView->QueueBrowserEvent("OnProcessMessageReceived1", + [eventNameStr = SString(eventName), args = std::move(args)](CWebBrowserEventsInterface* iface) mutable + { iface->Events_OnTriggerEvent(eventNameStr, args); }); return true; } @@ -132,7 +129,7 @@ namespace WebViewAuth inline bool HandleInputFocus(CWebView* pWebView, CefRefPtr argList, const bool isLocal) { if (!pWebView || !argList) [[unlikely]] - return true; // Return true = handled (rejected), not false which would bypass + return true; // Return true = handled (rejected), not false which would bypass if (!isLocal) [[unlikely]] return true; @@ -144,11 +141,8 @@ namespace WebViewAuth // Use QueueBrowserEvent for UAF-safe event dispatch (generation token pattern) const bool hasFocus = pWebView->HasInputFocus(); - pWebView->QueueBrowserEvent( - "OnProcessMessageReceived2", - [focus = hasFocus](CWebBrowserEventsInterface* iface) { - iface->Events_OnInputFocusChanged(focus); - }); + pWebView->QueueBrowserEvent("OnProcessMessageReceived2", + [focus = hasFocus](CWebBrowserEventsInterface* iface) { iface->Events_OnInputFocusChanged(focus); }); return true; } } diff --git a/Client/cefweb/CWebsiteRequests.h b/Client/cefweb/CWebsiteRequests.h index 5aa08027321..54c9320f6dc 100644 --- a/Client/cefweb/CWebsiteRequests.h +++ b/Client/cefweb/CWebsiteRequests.h @@ -9,7 +9,7 @@ *****************************************************************************/ #pragma once -#define WEBSITEREQUESTS_WINDOW_DEFAULTWIDTH 476 +#define WEBSITEREQUESTS_WINDOW_DEFAULTWIDTH 476 #define WEBSITEREQUESTS_WINDOW_DEFAULTHEIGHT 297 class CGUIWindow; class CGUILabel; diff --git a/Client/cefweb/CefWeb.cpp b/Client/cefweb/CefWeb.cpp index 6b0cd1ad3d2..9e6c7c9e128 100644 --- a/Client/cefweb/CefWeb.cpp +++ b/Client/cefweb/CefWeb.cpp @@ -45,7 +45,7 @@ namespace // Set up memory allocation failure handler for CEF processes SharedUtil::SetMemoryAllocationFailureHandler(); } -} // namespace +} // namespace // // DLL export: Initialize the web browser subsystem diff --git a/Client/core/CAdditionalVertexStreamManager.cpp b/Client/core/CAdditionalVertexStreamManager.cpp index dffe1c4bbec..38bbacd0927 100644 --- a/Client/core/CAdditionalVertexStreamManager.cpp +++ b/Client/core/CAdditionalVertexStreamManager.cpp @@ -78,7 +78,7 @@ namespace } std::mutex g_singletonMutex; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -238,7 +238,7 @@ bool CAdditionalVertexStreamManager::SetAdditionalVertexStream(SCurrentStateInfo return false; uint ReadOffsetSize = static_cast(readOffsetSize64); - uint OffsetInBytesN = ConvertPTOffset(state.stream1.OffsetInBytes); + uint OffsetInBytesN = ConvertPTOffset(state.stream1.OffsetInBytes); uint64_t writeOffsetStart64 = static_cast(viMinBased) * StrideN + OffsetInBytesN; if (writeOffsetStart64 > std::numeric_limits::max()) return false; @@ -305,7 +305,7 @@ void CAdditionalVertexStreamManager::MaybeUnsetAdditionalVertexStream() if (m_pOldVertexDeclaration) { - HRESULT hr = m_pDevice->TestCooperativeLevel(); + HRESULT hr = m_pDevice->TestCooperativeLevel(); const bool bDeviceOperational = (hr == D3D_OK); if (bDeviceOperational) @@ -427,8 +427,8 @@ bool CAdditionalVertexStreamManager::UpdateAdditionalStreamContent(SCurrentState std::vector indices(numIndices); { void* pIndexBytes = nullptr; - if (FAILED(state.pIndexData->Lock(static_cast(startByte), static_cast(requiredBytes), &pIndexBytes, - D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY))) + if (FAILED( + state.pIndexData->Lock(static_cast(startByte), static_cast(requiredBytes), &pIndexBytes, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY))) return false; if (indexStride == sizeof(WORD)) @@ -462,10 +462,10 @@ bool CAdditionalVertexStreamManager::UpdateAdditionalStreamContent(SCurrentState uint32_t v2 = indices[i + 2]; if (v0 >= NumVerts || v1 >= NumVerts || v2 >= NumVerts) - continue; // vert index out of range + continue; // vert index out of range if (v0 == v1 || v0 == v2 || v1 == v2) - continue; // degenerate tri + continue; // degenerate tri // Get vertex positions from original stream CVector* pPos0 = reinterpret_cast(pSourceArrayBytes + v0 * StridePT); @@ -654,7 +654,7 @@ SAdditionalStreamInfo* CAdditionalVertexStreamManager::CreateAdditionalStreamInf // Create new stream info.Stride = sizeof(float) * 3; - UINT Size2 = ConvertPTSize(state.decl.VertexBufferDesc1.Size); + UINT Size2 = ConvertPTSize(state.decl.VertexBufferDesc1.Size); if (FAILED(m_pDevice->CreateVertexBuffer(Size2, D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &info.pStreamData, nullptr))) { SAFE_RELEASE(info.pVertexDeclaration); @@ -705,7 +705,7 @@ void CAdditionalVertexStreamManager::OnVertexBufferRangeInvalidated(IDirect3DVer return; } - uint convertedOffset = ConvertPTOffset(Offset); + uint convertedOffset = ConvertPTOffset(Offset); uint verticesTouched = Size / 20; if ((Size % 20) != 0) @@ -714,9 +714,8 @@ void CAdditionalVertexStreamManager::OnVertexBufferRangeInvalidated(IDirect3DVer if (verticesTouched == 0) verticesTouched = 1; - uint64_t convertedSize64 = static_cast(verticesTouched) * static_cast(pAdditionalInfo->Stride); - uint convertedSize = convertedSize64 > std::numeric_limits::max() ? std::numeric_limits::max() - : static_cast(convertedSize64); + uint64_t convertedSize64 = static_cast(verticesTouched) * static_cast(pAdditionalInfo->Stride); + uint convertedSize = convertedSize64 > std::numeric_limits::max() ? std::numeric_limits::max() : static_cast(convertedSize64); pAdditionalInfo->ConvertedRanges.UnsetRange(convertedOffset, convertedSize); } diff --git a/Client/core/CAdditionalVertexStreamManager.h b/Client/core/CAdditionalVertexStreamManager.h index 7411eb17c2f..b9d80b84adf 100644 --- a/Client/core/CAdditionalVertexStreamManager.h +++ b/Client/core/CAdditionalVertexStreamManager.h @@ -85,7 +85,7 @@ class CAdditionalVertexStreamManager static CAdditionalVertexStreamManager* GetSingleton(); static CAdditionalVertexStreamManager* GetExistingSingleton(); - static void DestroySingleton(); + static void DestroySingleton(); protected: bool SetAdditionalVertexStream(SCurrentStateInfo& renderState); diff --git a/Client/core/CChat.cpp b/Client/core/CChat.cpp index b4b7e3b95be..f4d9f120980 100644 --- a/Client/core/CChat.cpp +++ b/Client/core/CChat.cpp @@ -227,13 +227,13 @@ void CChat::Draw(bool bUseCacheTexture, bool bAllowOutline) iRenderTargetSizeY, g_pDeviceState->AdapterState.Name.c_str())); } } - m_iCacheTextureRevision = -1; // Make sure the graphics will be updated + m_iCacheTextureRevision = -1; // Make sure the graphics will be updated } // If we can't get a rendertarget for some reason, just render the text directly to the screen if (!m_pCacheTexture) { - drawList.bOutline = false; // Outline too slow without cache texture + drawList.bOutline = false; // Outline too slow without cache texture DrawDrawList(drawList, chatTopLeft); return; } @@ -359,7 +359,7 @@ void CChat::GetDrawList(SDrawList& outDrawList, bool bUsingOutline) uiLine = (uiLine + 1) % CHAT_MAX_LINES; uiLinesDrawn++; - if (uiLine == m_uiMostRecentLine) // Went through all lines? + if (uiLine == m_uiMostRecentLine) // Went through all lines? break; } } @@ -466,21 +466,21 @@ void CChat::UpdateSmoothScroll(float* pfPixelScroll, int* piLineScroll) // Also update CssStyle override alpha // float fTarget = (!m_bCssStyleText || m_bInputVisible || m_iScrollingBack) ? 1.0f : 0.0f; - float fMaxAmount = fDeltaSeconds * 2.0f; // 0.5 seconds fade time + float fMaxAmount = fDeltaSeconds * 2.0f; // 0.5 seconds fade time m_fCssStyleOverrideAlpha += Clamp(-fMaxAmount, fTarget - m_fCssStyleOverrideAlpha, fMaxAmount); // // Also update background alpha // fTarget = (!m_bCssStyleBackground || m_bInputVisible || m_iScrollingBack) ? 1.0f : 0.0f; - fMaxAmount = fDeltaSeconds * 5.0f; // 0.2 seconds fade time + fMaxAmount = fDeltaSeconds * 5.0f; // 0.2 seconds fade time m_fBackgroundAlpha += Clamp(-fMaxAmount, fTarget - m_fBackgroundAlpha, fMaxAmount); // // Also update input background alpha // fTarget = (m_bInputVisible) ? 1.0f : 0.0f; - fMaxAmount = fDeltaSeconds * 5.0f; // 0.2 seconds fade time + fMaxAmount = fDeltaSeconds * 5.0f; // 0.2 seconds fade time m_fInputBackgroundAlpha += Clamp(-fMaxAmount, fTarget - m_fInputBackgroundAlpha, fMaxAmount); } @@ -660,14 +660,14 @@ bool CChat::CharacterKeyHandler(CGUIKeyEventArgs KeyboardArgs) else if (m_strCommand.compare("login") != 0) { // If the input is a command, check that it isn't the 'login' command, if it is censor it - char szInput[256]; + char szInput[256]; unsigned int uiLength = sizeof(szInput) - 1; strncpy(szInput, m_strInputText.c_str() + 1, uiLength); szInput[uiLength] = '\0'; const char* szCommand = strtok(szInput, " "); - + if (szCommand && (strcmp(szCommand, "login") != 0)) m_pInputHistory->Add(m_strInputText); else if ((m_pInputHistory->Empty() || m_pInputHistory->GetLast() != std::string("/login"))) @@ -768,7 +768,7 @@ bool CChat::CharacterKeyHandler(CGUIKeyEventArgs KeyboardArgs) if (m_strLastPlayerName.size() != 0) m_strLastPlayerName.clear(); - if (KeyboardArgs.codepoint == 127) // "delete" char, used to remove the previous word from input + if (KeyboardArgs.codepoint == 127) // "delete" char, used to remove the previous word from input { if (m_strInputText.size() > 0) { @@ -808,13 +808,13 @@ bool CChat::CharacterKeyHandler(CGUIKeyEventArgs KeyboardArgs) if (KeyboardArgs.codepoint >= 32) { unsigned int uiCharacter = KeyboardArgs.codepoint; - if (uiCharacter < 127) // we have any char from ASCII + if (uiCharacter < 127) // we have any char from ASCII { // injecting as is m_strInputText += static_cast(KeyboardArgs.codepoint); SetInputText(m_strInputText.c_str()); } - else // we have any char from Extended ASCII, any ANSI code page or UNICODE range + else // we have any char from Extended ASCII, any ANSI code page or UNICODE range { // Generate a null-terminating string for our character wchar_t wUNICODE[2] = {static_cast(uiCharacter), '\0'}; @@ -1195,21 +1195,21 @@ const char* CChatLine::Format(const char* text, float width, CColor& color, bool const wchar_t* sectionEnd = szString; const wchar_t* lastWrapPoint = szString; bool lastSection = false; - while (!lastSection) // iterate over sections + while (!lastSection) // iterate over sections { m_Sections.resize(m_Sections.size() + 1); CChatLineSection& section = *(m_Sections.end() - 1); section.SetColor(color); - if (m_Sections.size() > 1 && colorCoded) // If we've processed sections before - sectionEnd += 7; // skip the color code + if (m_Sections.size() > 1 && colorCoded) // If we've processed sections before + sectionEnd += 7; // skip the color code sectionStart = sectionEnd; lastWrapPoint = sectionStart; unsigned int seekPos = 0; std::wstring strSectionStart = sectionStart; - while (true) // find end of this section + while (true) // find end of this section { float sectionWidth = CChat::GetTextExtent(UTF16ToMbUTF8(strSectionStart.substr(0, seekPos)).c_str(), g_pChat->m_vecScale.fX); diff --git a/Client/core/CChat.h b/Client/core/CChat.h index 53710076ac5..1aa79c2a834 100644 --- a/Client/core/CChat.h +++ b/Client/core/CChat.h @@ -16,10 +16,10 @@ class CChatLineSection; -#define CHAT_WIDTH 320 // Chatbox default width -#define CHAT_TEXT_COLOR CColor(235, 221, 178) // Chatbox default text color -#define CHAT_MAX_LINES 100 // Chatbox maximum chat lines -#define CHAT_BUFFER 1024 // Chatbox buffer size +#define CHAT_WIDTH 320 // Chatbox default width +#define CHAT_TEXT_COLOR CColor(235, 221, 178) // Chatbox default text color +#define CHAT_MAX_LINES 100 // Chatbox maximum chat lines +#define CHAT_BUFFER 1024 // Chatbox buffer size #define CHAT_INPUT_HISTORY_LENGTH 128 // Chatbox input history length class CColor @@ -47,7 +47,7 @@ class CColor { R = (ulColor >> 16) & 0xFF; G = (ulColor >> 8) & 0xFF; - B = (ulColor)&0xFF; + B = (ulColor) & 0xFF; return *this; } bool operator==(const CColor& other) const { return R == other.R && G == other.G && B == other.B && A == other.A; } @@ -74,8 +74,8 @@ class CChatLineSection void InvalidateCache(); protected: - std::string m_text; - CColor m_color; + std::string m_text; + CColor m_color; mutable float m_cachedWidth; mutable unsigned int m_cachedLength; }; @@ -156,7 +156,7 @@ class CChat friend class CChatLineSection; public: - CChat(){}; + CChat() {}; CChat(CGUI* pManager, const CVector2D& vecPosition); virtual ~CChat(); @@ -225,8 +225,8 @@ class CChat void DrawInputLine(bool bUsingOutline); void InvalidateAllCachedWidths(); - CChatLine m_Lines[CHAT_MAX_LINES]; // Circular buffer - int m_iScrollState; // 1 up, 0 stop, -1 down + CChatLine m_Lines[CHAT_MAX_LINES]; // Circular buffer + int m_iScrollState; // 1 up, 0 stop, -1 down unsigned int m_uiMostRecentLine; unsigned int m_uiScrollOffset; float m_fSmoothScroll; @@ -270,8 +270,8 @@ class CChat bool m_bVisible; bool m_bInputBlocked; bool m_bInputVisible; - int m_iScrollingBack; // Non zero if currently scrolling back - float m_fCssStyleOverrideAlpha; // For fading out 'CssStyle' effect. (When entering text or scrolling back) + int m_iScrollingBack; // Non zero if currently scrolling back + float m_fCssStyleOverrideAlpha; // For fading out 'CssStyle' effect. (When entering text or scrolling back) float m_fBackgroundAlpha; float m_fInputBackgroundAlpha; diff --git a/Client/core/CClientVariables.cpp b/Client/core/CClientVariables.cpp index ea7b3b07bd7..3bf88681364 100644 --- a/Client/core/CClientVariables.cpp +++ b/Client/core/CClientVariables.cpp @@ -242,7 +242,6 @@ void CClientVariables::ValidateValues() FPSLimits::IsValidAndSetValid(fps, fps); CVARS_SET("fps_limit", fps); - ClampValue("chat_font", 0, 3); ClampValue("chat_lines", 3, 62); ClampValue("chat_color", CColor(0, 0, 0, 0), CColor(255, 255, 255, 255)); @@ -286,119 +285,120 @@ void CClientVariables::LoadDefaults() if (!Exists("nick")) { - DEFAULT("nick", _S(CNickGen::GetRandomNickname())); // nickname - CCore::GetSingleton().RequestNewNickOnStart(); // Request the user to set a new nickname + DEFAULT("nick", _S(CNickGen::GetRandomNickname())); // nickname + CCore::GetSingleton().RequestNewNickOnStart(); // Request the user to set a new nickname } - DEFAULT("host", _S("127.0.0.1")); // hostname - DEFAULT("port", 22003); // port - DEFAULT("password", _S("")); // password - DEFAULT("debugfile", _S("")); // debug filename - DEFAULT("console_pos", CVector2D(0, 0)); // console position - DEFAULT("console_size", CVector2D(200, 200)); // console size - DEFAULT("serverbrowser_size", CVector2D(720.0f, 495.0f)); // serverbrowser size - DEFAULT("fps_limit", 100); // frame limiter - DEFAULT("vsync", true); // vsync - DEFAULT("chat_font", 2); // chatbox font type - DEFAULT("chat_lines", 10); // chatbox lines - DEFAULT("chat_color", CColor(0, 0, 0, 0)); // chatbox background color - DEFAULT("chat_text_color", CColor(172, 213, 254, 255)); // chatbox text color + DEFAULT("host", _S("127.0.0.1")); // hostname + DEFAULT("port", 22003); // port + DEFAULT("password", _S("")); // password + DEFAULT("debugfile", _S("")); // debug filename + DEFAULT("console_pos", CVector2D(0, 0)); // console position + DEFAULT("console_size", CVector2D(200, 200)); // console size + DEFAULT("serverbrowser_size", CVector2D(720.0f, 495.0f)); // serverbrowser size + DEFAULT("fps_limit", 100); // frame limiter + DEFAULT("vsync", true); // vsync + DEFAULT("chat_font", 2); // chatbox font type + DEFAULT("chat_lines", 10); // chatbox lines + DEFAULT("chat_color", CColor(0, 0, 0, 0)); // chatbox background color + DEFAULT("chat_text_color", CColor(172, 213, 254, 255)); // chatbox text color DEFAULT("chat_text_outline", false); - DEFAULT("chat_input_color", CColor(0, 0, 0, 0)); // chatbox input background color - DEFAULT("chat_input_prefix_color", CColor(172, 213, 254, 255)); // chatbox input prefix color - DEFAULT("chat_input_text_color", CColor(172, 213, 254, 255)); // chatbox input text color - DEFAULT("chat_scale", CVector2D(1.0f, 1.0f)); // chatbox scale - DEFAULT("chat_width", 1.5f); // chatbox width - - DEFAULT("chat_css_style_text", false); // chatbox css/hl style text - DEFAULT("chat_css_style_background", false); // chatbox css/hl style background - DEFAULT("chat_line_life", 12000); // chatbox line life time - DEFAULT("chat_line_fade_out", 3000); // chatbox line fade out time - DEFAULT("chat_use_cegui", false); // chatbox uses cegui - DEFAULT("chat_nickcompletion", true); // chatbox nick completion - DEFAULT("chat_position_offset_x", 0.0125f); // chatbox relative x position offset - DEFAULT("chat_position_offset_y", 0.015f); // chatbox relative y position offset - DEFAULT("chat_position_horizontal", Chat::Position::Horizontal::LEFT); // chatbox horizontal position - DEFAULT("chat_position_vertical", Chat::Position::Vertical::TOP); // chatbox vertical position - DEFAULT("chat_text_alignment", Chat::Text::Align::LEFT); // chatbox horizontal text alignment - DEFAULT("server_can_flash_window", true); // allow server to flash the window - DEFAULT("allow_tray_notifications", true); // allow scripts to create tray balloon notifications - DEFAULT("text_scale", 1.0f); // text scale - DEFAULT("invert_mouse", false); // mouse inverting - DEFAULT("fly_with_mouse", false); // flying with mouse controls - DEFAULT("steer_with_mouse", false); // steering with mouse controls - DEFAULT("classic_controls", false); // classic/standard controls - DEFAULT("mastervolume", 1.0f); // master volume - DEFAULT("mtavolume", 1.0f); // custom sound's volume - DEFAULT("voicevolume", 1.0f); // voice chat output volume - DEFAULT("mapalpha", 155); // player map alpha - DEFAULT("mapimage", 0); // player map image - DEFAULT("browser_speed", 1); // Browser speed - DEFAULT("single_download", 0); // Single connection for downloads - DEFAULT("packet_tag", 0); // Tag network packets - DEFAULT("progress_animation", 1); // Progress spinner at the bottom of the screen - DEFAULT("update_build_type", 0); // 0-stable 1-test 2-nightly - DEFAULT("update_auto_install", 1); // 0-off 1-on - DEFAULT("volumetric_shadows", 0); // Enable volumetric shadows - DEFAULT("aspect_ratio", 0); // Display aspect ratio - DEFAULT("hud_match_aspect_ratio", 1); // GTA HUD should match the display aspect ratio - DEFAULT("anisotropic", 0); // Anisotropic filtering - DEFAULT("grass", 1); // Enable grass - DEFAULT("heat_haze", 1); // Enable heat haze - DEFAULT("tyre_smoke_enabled", 1); // Enable tyre smoke - DEFAULT("high_detail_vehicles", 0); // Disable rendering high detail vehicles all the time - DEFAULT("high_detail_peds", 0); // Disable rendering high detail peds all the time - DEFAULT("blur", 1); // Enable blur - DEFAULT("corona_reflections", 0); // Disable corona rain reflections - DEFAULT("dynamic_ped_shadows", 0); // Disable dynamic ped shadows - DEFAULT("fast_clothes_loading", 1); // 0-off 1-auto 2-on - DEFAULT("allow_screen_upload", 1); // 0-off 1-on - DEFAULT("allow_external_sounds", 1); // 0-off 1-on - DEFAULT("max_clientscript_log_kb", 5000); // Max size in KB (0-No limit) - DEFAULT("display_fullscreen_style", 0); // 0-standard 1-borderless 2-borderless keep res 3-borderless stretch - DEFAULT("display_windowed", 0); // 0-off 1-on - DEFAULT("multimon_fullscreen_minimize", 1); // 0-off 1-on - DEFAULT("borderless_gamma_power", 0.95f); // Gamma exponent applied to windowed gamma ramp (1.0 = unchanged) - DEFAULT("borderless_brightness_scale", 1.03f); // Brightness multiplier for windowed gamma ramp (1.0 = unchanged) - DEFAULT("borderless_contrast_scale", 1.0f); // Contrast multiplier for borderless presentation (1.0 = unchanged) - DEFAULT("borderless_saturation_scale", 1.0f); // Saturation multiplier for borderless presentation (1.0 = unchanged) - DEFAULT("borderless_enable_srgb", false); // Enable sRGB correction when running borderless - DEFAULT("borderless_gamma_enabled", false); // Apply gamma adjustment while borderless tuning active - DEFAULT("borderless_brightness_enabled", false); // Apply brightness adjustment while borderless tuning active - DEFAULT("borderless_contrast_enabled", false); // Apply contrast adjustment while borderless tuning active - DEFAULT("borderless_saturation_enabled", false); // Apply saturation adjustment while borderless tuning active - DEFAULT("borderless_apply_windowed", false); // Apply display adjustments while windowed/borderless - DEFAULT("borderless_apply_fullscreen", false); // Apply display adjustments while in exclusive fullscreen + DEFAULT("chat_input_color", CColor(0, 0, 0, 0)); // chatbox input background color + DEFAULT("chat_input_prefix_color", CColor(172, 213, 254, 255)); // chatbox input prefix color + DEFAULT("chat_input_text_color", CColor(172, 213, 254, 255)); // chatbox input text color + DEFAULT("chat_scale", CVector2D(1.0f, 1.0f)); // chatbox scale + DEFAULT("chat_width", 1.5f); // chatbox width + + DEFAULT("chat_css_style_text", false); // chatbox css/hl style text + DEFAULT("chat_css_style_background", false); // chatbox css/hl style background + DEFAULT("chat_line_life", 12000); // chatbox line life time + DEFAULT("chat_line_fade_out", 3000); // chatbox line fade out time + DEFAULT("chat_use_cegui", false); // chatbox uses cegui + DEFAULT("chat_nickcompletion", true); // chatbox nick completion + DEFAULT("chat_position_offset_x", 0.0125f); // chatbox relative x position offset + DEFAULT("chat_position_offset_y", 0.015f); // chatbox relative y position offset + DEFAULT("chat_position_horizontal", Chat::Position::Horizontal::LEFT); // chatbox horizontal position + DEFAULT("chat_position_vertical", Chat::Position::Vertical::TOP); // chatbox vertical position + DEFAULT("chat_text_alignment", Chat::Text::Align::LEFT); // chatbox horizontal text alignment + DEFAULT("server_can_flash_window", true); // allow server to flash the window + DEFAULT("allow_tray_notifications", true); // allow scripts to create tray balloon notifications + DEFAULT("text_scale", 1.0f); // text scale + DEFAULT("invert_mouse", false); // mouse inverting + DEFAULT("fly_with_mouse", false); // flying with mouse controls + DEFAULT("steer_with_mouse", false); // steering with mouse controls + DEFAULT("classic_controls", false); // classic/standard controls + DEFAULT("mastervolume", 1.0f); // master volume + DEFAULT("mtavolume", 1.0f); // custom sound's volume + DEFAULT("voicevolume", 1.0f); // voice chat output volume + DEFAULT("mapalpha", 155); // player map alpha + DEFAULT("mapimage", 0); // player map image + DEFAULT("browser_speed", 1); // Browser speed + DEFAULT("single_download", 0); // Single connection for downloads + DEFAULT("packet_tag", 0); // Tag network packets + DEFAULT("progress_animation", 1); // Progress spinner at the bottom of the screen + DEFAULT("update_build_type", 0); // 0-stable 1-test 2-nightly + DEFAULT("update_auto_install", 1); // 0-off 1-on + DEFAULT("volumetric_shadows", 0); // Enable volumetric shadows + DEFAULT("aspect_ratio", 0); // Display aspect ratio + DEFAULT("hud_match_aspect_ratio", 1); // GTA HUD should match the display aspect ratio + DEFAULT("anisotropic", 0); // Anisotropic filtering + DEFAULT("grass", 1); // Enable grass + DEFAULT("heat_haze", 1); // Enable heat haze + DEFAULT("tyre_smoke_enabled", 1); // Enable tyre smoke + DEFAULT("high_detail_vehicles", 0); // Disable rendering high detail vehicles all the time + DEFAULT("high_detail_peds", 0); // Disable rendering high detail peds all the time + DEFAULT("blur", 1); // Enable blur + DEFAULT("corona_reflections", 0); // Disable corona rain reflections + DEFAULT("dynamic_ped_shadows", 0); // Disable dynamic ped shadows + DEFAULT("fast_clothes_loading", 1); // 0-off 1-auto 2-on + DEFAULT("allow_screen_upload", 1); // 0-off 1-on + DEFAULT("allow_external_sounds", 1); // 0-off 1-on + DEFAULT("max_clientscript_log_kb", 5000); // Max size in KB (0-No limit) + DEFAULT("display_fullscreen_style", 0); // 0-standard 1-borderless 2-borderless keep res 3-borderless stretch + DEFAULT("display_windowed", 0); // 0-off 1-on + DEFAULT("multimon_fullscreen_minimize", 1); // 0-off 1-on + DEFAULT("borderless_gamma_power", 0.95f); // Gamma exponent applied to windowed gamma ramp (1.0 = unchanged) + DEFAULT("borderless_brightness_scale", 1.03f); // Brightness multiplier for windowed gamma ramp (1.0 = unchanged) + DEFAULT("borderless_contrast_scale", 1.0f); // Contrast multiplier for borderless presentation (1.0 = unchanged) + DEFAULT("borderless_saturation_scale", 1.0f); // Saturation multiplier for borderless presentation (1.0 = unchanged) + DEFAULT("borderless_enable_srgb", false); // Enable sRGB correction when running borderless + DEFAULT("borderless_gamma_enabled", false); // Apply gamma adjustment while borderless tuning active + DEFAULT("borderless_brightness_enabled", false); // Apply brightness adjustment while borderless tuning active + DEFAULT("borderless_contrast_enabled", false); // Apply contrast adjustment while borderless tuning active + DEFAULT("borderless_saturation_enabled", false); // Apply saturation adjustment while borderless tuning active + DEFAULT("borderless_apply_windowed", false); // Apply display adjustments while windowed/borderless + DEFAULT("borderless_apply_fullscreen", false); // Apply display adjustments while in exclusive fullscreen if (Exists("borderless_enable_srgb")) { - bool legacyEnable = false; + bool legacyEnable = false; Get("borderless_enable_srgb", legacyEnable); Set("borderless_apply_windowed", legacyEnable); } - DEFAULT("vertical_aim_sensitivity", 0.0015f); // 0.0015f is GTA default setting - DEFAULT("process_priority", 0); // 0-normal 1-above normal 2-high - DEFAULT("process_dpi_aware", false); // Enable DPI awareness in core initialization - DEFAULT("mute_master_when_minimized", 0); // 0-off 1-on - DEFAULT("mute_sfx_when_minimized", 0); // 0-off 1-on - DEFAULT("mute_radio_when_minimized", 0); // 0-off 1-on - DEFAULT("mute_mta_when_minimized", 0); // 0-off 1-on - DEFAULT("mute_voice_when_minimized", 0); // 0-off 1-on - DEFAULT("share_file_cache", 1); // 0-no 1-share client resource file cache with other MTA installs - DEFAULT("show_unsafe_resolutions", 0); // 0-off 1-show resolutions that are higher that the desktop - DEFAULT("fov", 70); // Camera field of view - DEFAULT("browser_remote_websites", true); // Load remote websites? - DEFAULT("browser_remote_javascript", true); // Execute javascript on remote websites? - DEFAULT("filter_duplicate_log_lines", true); // Filter duplicate log lines for debug view and clientscript.log - DEFAULT("always_show_transferbox", false); // Should the transfer box always be visible for downloads? (and ignore scripted control) - DEFAULT("allow_discord_rpc", true); // Enable Discord Rich Presence - DEFAULT("discord_rpc_share_data", false); // Consistent Rich Presence data sharing - DEFAULT("discord_rpc_share_data_firsttime", false); // Display the user data sharing consent dialog box - for the first time - DEFAULT("browser_enable_gpu", true); // Enable GPU in CEF? (allows stuff like WebGL to function) - DEFAULT("process_cpu_affinity", true); // Set CPU 0 affinity to improve game performance and fix the known issue in single-threaded games - DEFAULT("ask_before_disconnect", true); // Ask before disconnecting from a server - DEFAULT("allow_steam_client", false); // Allow connecting with the local Steam client (to set GTA:SA ingame status) - DEFAULT("use_mouse_sensitivity_for_aiming", false); // It uses the horizontal mouse sensitivity for aiming, making the Y-axis sensitivity the same as the X-axis + DEFAULT("vertical_aim_sensitivity", 0.0015f); // 0.0015f is GTA default setting + DEFAULT("process_priority", 0); // 0-normal 1-above normal 2-high + DEFAULT("process_dpi_aware", false); // Enable DPI awareness in core initialization + DEFAULT("mute_master_when_minimized", 0); // 0-off 1-on + DEFAULT("mute_sfx_when_minimized", 0); // 0-off 1-on + DEFAULT("mute_radio_when_minimized", 0); // 0-off 1-on + DEFAULT("mute_mta_when_minimized", 0); // 0-off 1-on + DEFAULT("mute_voice_when_minimized", 0); // 0-off 1-on + DEFAULT("share_file_cache", 1); // 0-no 1-share client resource file cache with other MTA installs + DEFAULT("show_unsafe_resolutions", 0); // 0-off 1-show resolutions that are higher that the desktop + DEFAULT("fov", 70); // Camera field of view + DEFAULT("browser_remote_websites", true); // Load remote websites? + DEFAULT("browser_remote_javascript", true); // Execute javascript on remote websites? + DEFAULT("filter_duplicate_log_lines", true); // Filter duplicate log lines for debug view and clientscript.log + DEFAULT("always_show_transferbox", false); // Should the transfer box always be visible for downloads? (and ignore scripted control) + DEFAULT("allow_discord_rpc", true); // Enable Discord Rich Presence + DEFAULT("discord_rpc_share_data", false); // Consistent Rich Presence data sharing + DEFAULT("discord_rpc_share_data_firsttime", false); // Display the user data sharing consent dialog box - for the first time + DEFAULT("browser_enable_gpu", true); // Enable GPU in CEF? (allows stuff like WebGL to function) + DEFAULT("process_cpu_affinity", true); // Set CPU 0 affinity to improve game performance and fix the known issue in single-threaded games + DEFAULT("ask_before_disconnect", true); // Ask before disconnecting from a server + DEFAULT("allow_steam_client", false); // Allow connecting with the local Steam client (to set GTA:SA ingame status) + DEFAULT("use_mouse_sensitivity_for_aiming", + false); // It uses the horizontal mouse sensitivity for aiming, making the Y-axis sensitivity the same as the X-axis if (!Exists("locale")) { @@ -421,5 +421,4 @@ void CClientVariables::LoadDefaults() #undef DEFAULT #undef _S - } diff --git a/Client/core/CClientVariables.h b/Client/core/CClientVariables.h index 1528a57a8b8..767dcecd73d 100644 --- a/Client/core/CClientVariables.h +++ b/Client/core/CClientVariables.h @@ -27,9 +27,13 @@ class CClientVariables : public CCVarsInterface, public CSingleton { - // Sanity macros << Who ever did this is idiot - #define SAN if(!m_pStorage) return - #define SANGET if(!Node(strVariable)) return false +// Sanity macros << Who ever did this is idiot +#define SAN \ + if (!m_pStorage) \ + return +#define SANGET \ + if (!Node(strVariable)) \ + return false public: CClientVariables(); diff --git a/Client/core/CCommandFuncs.h b/Client/core/CCommandFuncs.h index 0e161e10e35..854d2f87ccf 100644 --- a/Client/core/CCommandFuncs.h +++ b/Client/core/CCommandFuncs.h @@ -13,7 +13,7 @@ #include -#define DECLARE_COMMAND_HANDLER(a) static void a ( const char * szParameters ); +#define DECLARE_COMMAND_HANDLER(a) static void a(const char* szParameters); class CCommandFuncs { diff --git a/Client/core/CCompressorJobQueue.cpp b/Client/core/CCompressorJobQueue.cpp index 402f04744a1..48434e09109 100644 --- a/Client/core/CCompressorJobQueue.cpp +++ b/Client/core/CCompressorJobQueue.cpp @@ -48,7 +48,7 @@ class CCompressorJobQueueImpl : public CCompressorJobQueue // Main thread variables CThreadHandle* m_pServiceThreadHandle; std::set m_IgnoreResultList; - std::set m_FinishedList; // Result has been used, will be deleted next pulse + std::set m_FinishedList; // Result has been used, will be deleted next pulse // Other thread variables // -none- @@ -317,7 +317,7 @@ bool CCompressorJobQueueImpl::PollCommand(CCompressJobData* pJobData, uint uiTim bool CCompressorJobQueueImpl::FreeCommand(CCompressJobData* pJobData) { if (MapContains(m_IgnoreResultList, pJobData)) - return false; // Already ignoring query handle + return false; // Already ignoring query handle // if in command or result queue, then put in ignore result list bool bFound; @@ -488,10 +488,10 @@ void CCompressorJobQueueImpl::ProcessCommand(CCompressJobData* pJobData) bool CCompressJobData::SetCallback(PFN_SCREENSHOT_CALLBACK pfnScreenShotCallback, uint uiTimeSpentInQueue) { if (callback.bSet) - return false; // One has already been set + return false; // One has already been set if (this->stage > EJobStage::RESULT) - return false; // Too late to set a callback now + return false; // Too late to set a callback now // Set new callback.uiTimeSpentInQueue = uiTimeSpentInQueue; diff --git a/Client/core/CConnectManager.cpp b/Client/core/CConnectManager.cpp index c9e0edbb017..4909b5d7ba2 100644 --- a/Client/core/CConnectManager.cpp +++ b/Client/core/CConnectManager.cpp @@ -83,7 +83,7 @@ bool CConnectManager::Connect(const char* szHost, unsigned short usPort, const c if (!CheckNickProvided((char*)szNick)) { SString strBuffer = _("Connecting failed. Invalid nick provided!"); - CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC20"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Invalid nick provided + CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC20"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Invalid nick provided return false; } @@ -114,7 +114,7 @@ bool CConnectManager::Connect(const char* szHost, unsigned short usPort, const c if (!CServerListItem::Parse(m_strHost.c_str(), m_Address)) { SString strBuffer = _("Connecting failed. Invalid host provided!"); - CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC21"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Invalid host provided + CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC21"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Invalid host provided return false; } @@ -130,7 +130,7 @@ bool CConnectManager::Connect(const char* szHost, unsigned short usPort, const c if (m_usPort && !pNet->StartNetwork(strAddress, m_usPort, CVARS_GET_VALUE("packet_tag"))) { SString strBuffer(_("Connecting to %s at port %u failed!"), m_strHost.c_str(), m_usPort); - CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC22"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Failed to connect + CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC22"), strBuffer, MB_BUTTON_OK | MB_ICON_ERROR); // Failed to connect return false; } @@ -283,11 +283,11 @@ void CConnectManager::DoPulse() { case RID_RSA_PUBLIC_KEY_MISMATCH: strError = _("Disconnected: unknown protocol error"); - strErrorCode = _E("CC24"); // encryption key mismatch + strErrorCode = _E("CC24"); // encryption key mismatch break; case RID_INCOMPATIBLE_PROTOCOL_VERSION: strError = _("Disconnected: unknown protocol error"); - strErrorCode = _E("CC34"); // old raknet version + strErrorCode = _E("CC34"); // old raknet version break; case RID_REMOTE_DISCONNECTION_NOTIFICATION: strError = _("Disconnected: disconnected remotely"); @@ -328,7 +328,7 @@ void CConnectManager::DoPulse() { CCore::GetSingleton().ShowNetErrorMessageBox(_("Error") + strErrorCode, strError); } - else // Otherwise, remove the message box and hide quick connect + else // Otherwise, remove the message box and hide quick connect { CCore::GetSingleton().RemoveMessageBox(false); } @@ -412,7 +412,7 @@ bool CConnectManager::StaticProcessPacket(unsigned char ucPacketID, NetBitStream { // Failed loading the mod strArguments.Format(_("No such mod installed (%s)"), strModName.c_str()); - CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC31"), strArguments, MB_BUTTON_OK | MB_ICON_ERROR); // Mod loading failed + CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC31"), strArguments, MB_BUTTON_OK | MB_ICON_ERROR); // Mod loading failed g_pConnectManager->Abort(); } } diff --git a/Client/core/CConnectManager.h b/Client/core/CConnectManager.h index 906d61e37a8..e80eb964887 100644 --- a/Client/core/CConnectManager.h +++ b/Client/core/CConnectManager.h @@ -33,7 +33,7 @@ class CConnectManager void OnServerExists(); void SetQuickConnect(bool quick) noexcept { m_quickConnect = quick; } - + static void OpenServerFirewall(in_addr Address, ushort usHttpPort = 80, bool bHighPriority = false); static bool StaticProcessPacket(unsigned char ucPacketID, class NetBitStreamInterface& bitStream); diff --git a/Client/core/CConsole.cpp b/Client/core/CConsole.cpp index 340187f1d84..be40befa214 100644 --- a/Client/core/CConsole.cpp +++ b/Client/core/CConsole.cpp @@ -15,7 +15,7 @@ using SharedUtil::CalcMTASAPath; using std::string; #define CONSOLE_INPUT_HISTORY_LENGTH 128 -#define CONSOLE_SIZE 4096 +#define CONSOLE_SIZE 4096 #define MAX_CONSOLE_COMMAND_LENGTH 255 @@ -368,13 +368,13 @@ void CConsole::SetNextAutoCompleteMatch() while (CEntryHistoryItem* pEntryHistoryItem = m_pConsoleHistory->Get(++iIndex)) { const char* szItem = *pEntryHistoryItem; - if (strlen(szItem) < 3) // Skip very short lines + if (strlen(szItem) < 3) // Skip very short lines continue; // Save the index of any matches if (strnicmp(szItem, strInput.c_str(), strInput.length()) == 0) { - if (m_AutoCompleteList.size()) // Dont add duplicates of the previously added line + if (m_AutoCompleteList.size()) // Dont add duplicates of the previously added line { CEntryHistoryItem* pPrevEntryHistoryItem = m_pConsoleHistory->Get(m_AutoCompleteList.at(m_AutoCompleteList.size() - 1)); if (!pPrevEntryHistoryItem) @@ -556,7 +556,7 @@ void CConsole::FlushPendingAdd() uiSelectionStart = 0; uiSelectionEnd -= uiBufferLengthDiff; } - else // Both start and end of selection are greater than length difference + else // Both start and end of selection are greater than length difference { // Whole selection would still be visible on the screen, // just a simple movement is needed diff --git a/Client/core/CCore.cpp b/Client/core/CCore.cpp index 2167a2e8cd7..1128bfc0b6b 100644 --- a/Client/core/CCore.cpp +++ b/Client/core/CCore.cpp @@ -18,7 +18,7 @@ #include #include #include -#include "Userenv.h" // This will enable SharedUtil::ExpandEnvString +#include "Userenv.h" // This will enable SharedUtil::ExpandEnvString #define ALLOC_STATS_MODULE_NAME "core" #include "SharedUtil.hpp" #include @@ -49,7 +49,7 @@ extern fs::path g_gtaDirectory; template <> CCore* CSingleton::m_pSingleton = NULL; -static auto Win32LoadLibraryA = LoadLibraryA; +static auto Win32LoadLibraryA = LoadLibraryA; static constexpr long long TIME_DISCORD_UPDATE_RICH_PRESENCE_RATE = 10000; static HMODULE WINAPI SkipDirectPlay_LoadLibraryA(LPCSTR fileName) @@ -698,7 +698,7 @@ void CCore::ApplyGameSettings() void CCore::SetConnected(bool bConnected) { m_pLocalGUI->GetMainMenu()->SetIsIngame(bConnected); - UpdateIsWindowMinimized(); // Force update of stuff + UpdateIsWindowMinimized(); // Force update of stuff if (g_pCore->GetCVars()->GetValue("allow_discord_rpc", false)) { @@ -812,7 +812,7 @@ void CCore::ShowNetErrorMessageBox(const SString& strTitle, SString strMessage, strTroubleLink += SString("&neterrorcode=%08X", uiErrorCode); } else if (bLinkRequiresErrorCode) - strTroubleLink = ""; // No link if no error code + strTroubleLink = ""; // No link if no error code AddReportLog(7100, SString("Core - NetError (%s) (%s)", *strTitle, *strMessage)); ShowErrorMessageBox(strTitle, strMessage, strTroubleLink); @@ -1213,12 +1213,12 @@ CWebCoreInterface* CCore::GetWebCore() // Log current working directory wchar_t cwdBeforeWebInit[32768]{}; - DWORD cwdBeforeWebInitLen = GetCurrentDirectoryW(32768, cwdBeforeWebInit); + DWORD cwdBeforeWebInitLen = GetCurrentDirectoryW(32768, cwdBeforeWebInit); if (cwdBeforeWebInitLen > 0) { WriteDebugEvent(SString("CCore::GetWebCore - CWD before Initialise: %S", cwdBeforeWebInit)); } - + // Keep m_pWebCore alive even if Initialise() fails // CefInitialize() can only be called once per process // Deleting and recreating m_pWebCore causes repeated initialization attempts @@ -1233,7 +1233,7 @@ CWebCoreInterface* CCore::GetWebCore() WriteDebugEvent("CCore::GetWebCore - Initialise threw exception"); bInitSuccess = false; } - + if (!bInitSuccess) { WriteDebugEvent("CCore::GetWebCore - Initialise failed"); @@ -1246,7 +1246,7 @@ CWebCoreInterface* CCore::GetWebCore() if (!m_pWebCore->IsInitialised()) return nullptr; } - + return m_pWebCore; } @@ -1340,8 +1340,8 @@ void CCore::DoPostFramePulse() if (m_menuFrame == 1) { - WatchDogCompletedSection("L2"); // gta_sa.set seems ok - WatchDogCompletedSection("L3"); // No hang on startup + WatchDogCompletedSection("L2"); // gta_sa.set seems ok + WatchDogCompletedSection("L3"); // No hang on startup // Start watchdog thread now that initial loading is complete // Use 120 second timeout to allow for large mod asset loading @@ -1406,7 +1406,7 @@ void CCore::DoPostFramePulse() m_bLastFocused = true; } - GetJoystickManager()->DoPulse(); // Note: This may indirectly call CMessageLoopHook::ProcessMessage + GetJoystickManager()->DoPulse(); // Note: This may indirectly call CMessageLoopHook::ProcessMessage m_pKeyBinds->DoPostFramePulse(); if (m_pWebCore) @@ -1564,7 +1564,7 @@ void CCore::Quit(bool bInstantly) // Show that we are quiting (for the crash dump filename) SetApplicationSettingInt("last-server-ip", 1); - WatchDogBeginSection("Q0"); // Allow loader to detect freeze on exit + WatchDogBeginSection("Q0"); // Allow loader to detect freeze on exit // Hide game window to make quit look instant PostQuitMessage(0); @@ -1580,7 +1580,6 @@ void CCore::Quit(bool bInstantly) // Destroy ourself (unreachable but kept for completeness) delete CCore::GetSingletonPtr(); - } else { @@ -1911,9 +1910,9 @@ void CCore::ApplyCoreInitSettings() SetApplicationSettingInt("reset-settings-revision", 21486); } - HANDLE process = GetCurrentProcess(); + HANDLE process = GetCurrentProcess(); const int priorities[] = {NORMAL_PRIORITY_CLASS, ABOVE_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS}; - int priority = CVARS_GET_VALUE("process_priority") % 3; + int priority = CVARS_GET_VALUE("process_priority") % 3; SetPriorityClass(process, priorities[priority]); @@ -1924,7 +1923,7 @@ void CCore::ApplyCoreInitSettings() DWORD_PTR mask; DWORD_PTR sys; - BOOL result = GetProcessAffinityMask(process, &mask, &sys); + BOOL result = GetProcessAffinityMask(process, &mask, &sys); if (result) SetProcessAffinityMask(process, mask & ~1); @@ -1941,7 +1940,7 @@ void CCore::OnGameTimerUpdate() void CCore::OnFPSLimitChange(std::uint16_t fps) { - if (m_pNet != nullptr && IsWebCoreLoaded()) // We have to wait for the network module to be loaded + if (m_pNet != nullptr && IsWebCoreLoaded()) // We have to wait for the network module to be loaded GetWebCore()->OnFPSLimitChange(fps); } @@ -1959,7 +1958,7 @@ void CCore::DoReliablePulse() // Non frame rate limit stuff if (IsWindowMinimized()) - m_iUnminimizeFrameCounter = 4; // Tell script we have unminimized after a short delay + m_iUnminimizeFrameCounter = 4; // Tell script we have unminimized after a short delay UpdateModuleTickCount64(); } @@ -1987,7 +1986,7 @@ void CCore::OnTimingDetail(const char* szTag) // void CCore::OnDeviceRestore() { - m_iUnminimizeFrameCounter = 4; // Tell script we have restored after 4 frames to avoid double sends + m_iUnminimizeFrameCounter = 4; // Tell script we have restored after 4 frames to avoid double sends m_bDidRecreateRenderTargets = true; } @@ -2445,9 +2444,8 @@ bool CCore::IsUsingCustomStreamingMemorySize() // Streaming memory size used [In Bytes] size_t CCore::GetStreamingMemory() { - return IsUsingCustomStreamingMemorySize() - ? m_CustomStreamingMemoryLimitBytes - : CVARS_GET_VALUE("streaming_memory") * 1024 * 1024; // MB to B conversion + return IsUsingCustomStreamingMemorySize() ? m_CustomStreamingMemoryLimitBytes + : CVARS_GET_VALUE("streaming_memory") * 1024 * 1024; // MB to B conversion } // Discord rich presence diff --git a/Client/core/CCore.h b/Client/core/CCore.h index 72310f565ac..7b9ee431fdc 100644 --- a/Client/core/CCore.h +++ b/Client/core/CCore.h @@ -55,15 +55,15 @@ class CDiscordInterface; #define MTA_CONSOLE_LOG_PATH "mta/logs/console.log" #define MTA_CONSOLE_INPUT_LOG_PATH "mta/logs/console-input.log" #define CONFIG_ROOT "mainconfig" -#define CONFIG_NODE_CVARS "settings" // cvars node -#define CONFIG_NODE_KEYBINDS "binds" // keybinds node +#define CONFIG_NODE_CVARS "settings" // cvars node +#define CONFIG_NODE_KEYBINDS "binds" // keybinds node #define CONFIG_NODE_JOYPAD "joypad" #define CONFIG_NODE_UPDATER "updater" -#define CONFIG_NODE_SERVER_INT "internet_servers" // backup of last successful master server list query -#define CONFIG_NODE_SERVER_FAV "favourite_servers" // favourite servers list node -#define CONFIG_NODE_SERVER_REC "recently_played_servers" // recently played servers list node -#define CONFIG_NODE_SERVER_OPTIONS "serverbrowser_options" // saved options for the server browser -#define CONFIG_NODE_SERVER_SAVED "server_passwords" // This contains saved passwords (as appose to save_server_passwords which is a setting) +#define CONFIG_NODE_SERVER_INT "internet_servers" // backup of last successful master server list query +#define CONFIG_NODE_SERVER_FAV "favourite_servers" // favourite servers list node +#define CONFIG_NODE_SERVER_REC "recently_played_servers" // recently played servers list node +#define CONFIG_NODE_SERVER_OPTIONS "serverbrowser_options" // saved options for the server browser +#define CONFIG_NODE_SERVER_SAVED "server_passwords" // This contains saved passwords (as appose to save_server_passwords which is a setting) #define CONFIG_NODE_SERVER_HISTORY "connect_history" #define CONFIG_INTERNET_LIST_TAG "internet_server" #define CONFIG_FAVOURITE_LIST_TAG "favourite_server" @@ -105,7 +105,7 @@ class CCore : public CCoreInterface, public CSingleton CLocalGUI* GetLocalGUI(); CLocalizationInterface* GetLocalization() { return g_pLocalization; }; CWebCoreInterface* GetWebCore(); - CWebCoreInterface* GetWebCoreUnchecked() { return m_pWebCore; } // For cleanup in destructors only - bypasses initialization check + CWebCoreInterface* GetWebCoreUnchecked() { return m_pWebCore; } // For cleanup in destructors only - bypasses initialization check CTrayIconInterface* GetTrayIcon() { return m_pTrayIcon; }; std::shared_ptr GetDiscord(); CSteamClient* GetSteamClient() { return m_steamClient.get(); } @@ -217,7 +217,7 @@ class CCore : public CCoreInterface, public CSingleton // Misc void RegisterCommands(); - bool IsValidNick(const char* szNick); // Move somewhere else + bool IsValidNick(const char* szNick); // Move somewhere else void Quit(bool bInstantly = true); void InitiateUpdate(const char* szType, const char* szData, const char* szHost) { m_pLocalGUI->InitiateUpdate(szType, szData, szHost); } bool IsOptionalUpdateInfoRequired(const char* szHost) { return m_pLocalGUI->IsOptionalUpdateInfoRequired(szHost); } @@ -294,8 +294,8 @@ class CCore : public CCoreInterface, public CSingleton const SString& GetLastConnectedServerName() const { return m_strLastConnectedServerName; } void SetLastConnectedServerName(const SString& strServerName) { m_strLastConnectedServerName = strServerName; } - void SetCurrentRefreshRate(uint uiRefreshRate) { m_uiCurrentRefreshRate = uiRefreshRate; } - uint GetCurrentRefreshRate() const { return m_uiCurrentRefreshRate; } + void SetCurrentRefreshRate(uint uiRefreshRate) { m_uiCurrentRefreshRate = uiRefreshRate; } + uint GetCurrentRefreshRate() const { return m_uiCurrentRefreshRate; } void OnPostColorFilterRender() override; @@ -400,8 +400,8 @@ class CCore : public CCoreInterface, public CSingleton // Command line static void ParseCommandLine(std::map& options, const char*& szArgs, const char** pszNoValOptions = NULL); - std::map m_CommandLineOptions; // e.g. "-o option" -> {"o" = "option"} - const char* m_szCommandLineArgs; // Everything that comes after the options + std::map m_CommandLineOptions; // e.g. "-o option" -> {"o" = "option"} + const char* m_szCommandLineArgs; // Everything that comes after the options long long m_timeDiscordAppLastUpdate; }; diff --git a/Client/core/CCrashDumpWriter.cpp b/Client/core/CCrashDumpWriter.cpp index f53ebb69b9f..0bcb31a6994 100644 --- a/Client/core/CCrashDumpWriter.cpp +++ b/Client/core/CCrashDumpWriter.cpp @@ -44,12 +44,12 @@ static constexpr int MAX_WIDE_TO_UTF8_BYTES = 1 * 1024 * 1024; static const std::chrono::milliseconds PROCESS_WAIT_TIMEOUT{500}; static const std::chrono::milliseconds WINDOW_POLL_TIMEOUT{100}; -static constexpr std::size_t MAX_WINDOW_POLL_ATTEMPTS = 30; -static constexpr std::size_t SHELL_EXEC_POLL_ATTEMPTS = 20; +static constexpr std::size_t MAX_WINDOW_POLL_ATTEMPTS = 30; +static constexpr std::size_t SHELL_EXEC_POLL_ATTEMPTS = 20; static const std::chrono::milliseconds ALT_KEY_DURATION{50}; -static constexpr int SCREEN_MARGIN_PIXELS = 50; -static constexpr int EMERGENCY_MSGBOX_WIDTH = 600; -static constexpr int EMERGENCY_MSGBOX_HEIGHT = 200; +static constexpr int SCREEN_MARGIN_PIXELS = 50; +static constexpr int EMERGENCY_MSGBOX_WIDTH = 600; +static constexpr int EMERGENCY_MSGBOX_HEIGHT = 200; constexpr DWORD Milliseconds(std::chrono::milliseconds duration) { @@ -58,8 +58,7 @@ constexpr DWORD Milliseconds(std::chrono::milliseconds duration) [[nodiscard]] static DWORD ResolveCrashExitCode(const _EXCEPTION_POINTERS* exceptionPtrs) { - if (const auto* record = (exceptionPtrs != nullptr) ? exceptionPtrs->ExceptionRecord : nullptr; - record != nullptr && record->ExceptionCode != 0) + if (const auto* record = (exceptionPtrs != nullptr) ? exceptionPtrs->ExceptionRecord : nullptr; record != nullptr && record->ExceptionCode != 0) { return record->ExceptionCode; } @@ -120,21 +119,18 @@ namespace EmergencyCrashLogging TryAddReportLog(9800, msg); } - // SEH-isolated reader for exception record - #pragma warning(push) - #pragma warning(disable: 4702) - static ReadResult TryReadExceptionRecord(const _EXCEPTION_POINTERS* pException, - char* buf, size_t bufSize) +// SEH-isolated reader for exception record +#pragma warning(push) +#pragma warning(disable : 4702) + static ReadResult TryReadExceptionRecord(const _EXCEPTION_POINTERS* pException, char* buf, size_t bufSize) { ReadResult result = ReadResult::AccessFault; __try { if (pException->ExceptionRecord != nullptr) { - sprintf_s(buf, bufSize, "Code=0x%08lX Addr=0x%08lX ThreadId=%lu", - static_cast(pException->ExceptionRecord->ExceptionCode), - static_cast(reinterpret_cast( - pException->ExceptionRecord->ExceptionAddress)), + sprintf_s(buf, bufSize, "Code=0x%08lX Addr=0x%08lX ThreadId=%lu", static_cast(pException->ExceptionRecord->ExceptionCode), + static_cast(reinterpret_cast(pException->ExceptionRecord->ExceptionAddress)), static_cast(GetCurrentThreadId())); result = ReadResult::Success; } @@ -151,9 +147,7 @@ namespace EmergencyCrashLogging } // SEH-isolated reader for context record - static ReadResult TryReadContextRecord(const _EXCEPTION_POINTERS* pException, - char* buf1, size_t buf1Size, - char* buf2, size_t buf2Size) + static ReadResult TryReadContextRecord(const _EXCEPTION_POINTERS* pException, char* buf1, size_t buf1Size, char* buf2, size_t buf2Size) { ReadResult result = ReadResult::AccessFault; __try @@ -162,11 +156,10 @@ namespace EmergencyCrashLogging { const CONTEXT* ctx = pException->ContextRecord; - sprintf_s(buf1, buf1Size, "EAX=0x%08lX EBX=0x%08lX ECX=0x%08lX EDX=0x%08lX", - ctx->Eax, ctx->Ebx, ctx->Ecx, ctx->Edx); + sprintf_s(buf1, buf1Size, "EAX=0x%08lX EBX=0x%08lX ECX=0x%08lX EDX=0x%08lX", ctx->Eax, ctx->Ebx, ctx->Ecx, ctx->Edx); - sprintf_s(buf2, buf2Size, "ESI=0x%08lX EDI=0x%08lX EBP=0x%08lX ESP=0x%08lX EIP=0x%08lX EFL=0x%08lX", - ctx->Esi, ctx->Edi, ctx->Ebp, ctx->Esp, ctx->Eip, ctx->EFlags); + sprintf_s(buf2, buf2Size, "ESI=0x%08lX EDI=0x%08lX EBP=0x%08lX ESP=0x%08lX EIP=0x%08lX EFL=0x%08lX", ctx->Esi, ctx->Edi, ctx->Ebp, ctx->Esp, + ctx->Eip, ctx->EFlags); result = ReadResult::Success; } @@ -181,19 +174,19 @@ namespace EmergencyCrashLogging } return result; } - #pragma warning(pop) +#pragma warning(pop) -} // namespace EmergencyCrashLogging +} // Call SEH-isolated readers static void LogEmergencyExceptionRecord(const _EXCEPTION_POINTERS* pException) { using namespace EmergencyCrashLogging; - + std::array buf{}; - + const auto result = TryReadExceptionRecord(pException, buf.data(), buf.size()); - + switch (result) { case ReadResult::Success: @@ -214,14 +207,12 @@ static void LogEmergencyExceptionRecord(const _EXCEPTION_POINTERS* pException) static void LogEmergencyContextRecord(const _EXCEPTION_POINTERS* pException) { using namespace EmergencyCrashLogging; - + std::array buf1{}; std::array buf2{}; - - const auto result = TryReadContextRecord(pException, - buf1.data(), buf1.size(), - buf2.data(), buf2.size()); - + + const auto result = TryReadContextRecord(pException, buf1.data(), buf1.size(), buf2.data(), buf2.size()); + switch (result) { case ReadResult::Success: @@ -243,7 +234,7 @@ static void LogEmergencyContextRecord(const _EXCEPTION_POINTERS* pException) static void LogEmergencyCrashContext(const _EXCEPTION_POINTERS* pException) { using namespace EmergencyCrashLogging; - + SafeEmergencyLog("=== EMERGENCY CRASH CONTEXT ==="); if (pException == nullptr) @@ -299,13 +290,13 @@ namespace SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_DEFERRED_LOADS); } } - + std::mutex& GetSymInitMutex() { static std::mutex symMutex; return symMutex; } -} // namespace +} // namespace class SymbolHandlerGuard { @@ -318,11 +309,11 @@ class SymbolHandlerGuard if (m_process != nullptr) { std::lock_guard lock{GetSymInitMutex()}; - + ConfigureDbgHelpOptions(); - + const SString& processDir = SharedUtil::GetMTAProcessBaseDir(); - const char* searchPath = processDir.empty() ? nullptr : processDir.c_str(); + const char* searchPath = processDir.empty() ? nullptr : processDir.c_str(); if (SymInitialize(m_process, searchPath, TRUE) != FALSE) m_initialized = true; @@ -636,9 +627,9 @@ static void EnsureCrashReasonForDialog(CExceptionInformation* pExceptionInformat // If we still have "unknown", try registry-resolved module info as fallback CExceptionInformation_Impl* pImpl = dynamic_cast(pExceptionInformation); - const char* resolvedModuleName = nullptr; - DWORD resolvedIdaAddress = 0; - bool hasResolvedInfo = false; + const char* resolvedModuleName = nullptr; + DWORD resolvedIdaAddress = 0; + bool hasResolvedInfo = false; if (pImpl != nullptr && pImpl->HasResolvedModuleInfo()) { @@ -651,15 +642,14 @@ static void EnsureCrashReasonForDialog(CExceptionInformation* pExceptionInformat if (strcmp(moduleBaseName, "unknown") == 0 && hasResolvedInfo && resolvedModuleName != nullptr && resolvedModuleName[0] != '\0') { // Use registry-resolved info when basic module resolution failed - strReason = SString("\n\nReason: %s at %s+0x%08X (IDA: 0x%08X)", - exceptionType.c_str(), resolvedModuleName, pImpl->GetResolvedRva(), resolvedIdaAddress); + strReason = + SString("\n\nReason: %s at %s+0x%08X (IDA: 0x%08X)", exceptionType.c_str(), resolvedModuleName, pImpl->GetResolvedRva(), resolvedIdaAddress); } else if (hasResolvedInfo && resolvedModuleName != nullptr && resolvedModuleName[0] != '\0') { // Include IDA address as additional info when we have both sources - strReason = SString("\n\nReason: %s at %s+0x%08X (IDA via %s: 0x%08X)", - exceptionType.c_str(), moduleBaseName, pExceptionInformation->GetAddressModuleOffset(), - resolvedModuleName, resolvedIdaAddress); + strReason = SString("\n\nReason: %s at %s+0x%08X (IDA via %s: 0x%08X)", exceptionType.c_str(), moduleBaseName, + pExceptionInformation->GetAddressModuleOffset(), resolvedModuleName, resolvedIdaAddress); } else { @@ -743,14 +733,11 @@ static void AppendCrashDiagnostics(const SString& text) if (!hasSymbols) { static std::once_flag logOnce; - std::call_once(logOnce, [] { - SAFE_DEBUG_OUTPUT("CaptureStackTraceText: capturing without symbols (raw addresses only)\n"); - }); + std::call_once(logOnce, [] { SAFE_DEBUG_OUTPUT("CaptureStackTraceText: capturing without symbols (raw addresses only)\n"); }); } // For callback exceptions (0xC000041D), context and stack may be unreliable - const bool isCallbackException = (pException->ExceptionRecord != nullptr && - pException->ExceptionRecord->ExceptionCode == 0xC000041D); + const bool isCallbackException = (pException->ExceptionRecord != nullptr && pException->ExceptionRecord->ExceptionCode == 0xC000041D); if (isCallbackException) { SAFE_DEBUG_OUTPUT("CaptureStackTraceText: Callback exception detected - using reduced trace depth\n"); @@ -783,9 +770,7 @@ static void AppendCrashDiagnostics(const SString& text) SymbolHandlerGuard symbolGuard(hProcess, hasSymbols); const bool useDbgHelp = symbolGuard.IsInitialized(); - const auto routines = useDbgHelp - ? StackTraceHelpers::MakeStackWalkRoutines(true) - : StackTraceHelpers::MakeStackWalkRoutines(false); + const auto routines = useDbgHelp ? StackTraceHelpers::MakeStackWalkRoutines(true) : StackTraceHelpers::MakeStackWalkRoutines(false); static_assert(MAX_SYM_NAME > 1, "MAX_SYM_NAME must include room for a terminator"); constexpr DWORD kSymbolNameCapacity = MAX_SYM_NAME - 1; @@ -799,15 +784,8 @@ static void AppendCrashDiagnostics(const SString& text) for (std::size_t frameIndex = 0; frameIndex < MAX_FALLBACK_STACK_FRAMES; ++frameIndex) { - BOOL bWalked = StackWalk64(IMAGE_FILE_MACHINE_I386, - hProcess, - hThread, - &frame, - &context, - routines.readMemory, - routines.functionTableAccess, - routines.moduleBase, - nullptr); + BOOL bWalked = StackWalk64(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &frame, &context, routines.readMemory, routines.functionTableAccess, + routines.moduleBase, nullptr); if (bWalked == FALSE) break; @@ -835,9 +813,9 @@ static void AppendCrashDiagnostics(const SString& text) IMAGEHLP_LINE64 lineInfo{}; lineInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); - DWORD lineDisplacement = 0; - SString lineDetail; - + DWORD lineDisplacement = 0; + SString lineDetail; + if (useDbgHelp && SymGetLineFromAddr64(hProcess, address, &lineDisplacement, &lineInfo) != FALSE) { const char* fileName = lineInfo.FileName != nullptr ? lineInfo.FileName : "unknown"; @@ -881,9 +859,8 @@ static void TryLogCallbackContext(_EXCEPTION_POINTERS* pException) if (pException->ContextRecord != nullptr) { std::array szDebug; - SAFE_DEBUG_PRINT_C(szDebug.data(), szDebug.size(), - "CCrashDumpWriter: Callback context EIP=0x%08X ESP=0x%08X\n", - pException->ContextRecord->Eip, pException->ContextRecord->Esp); + SAFE_DEBUG_PRINT_C(szDebug.data(), szDebug.size(), "CCrashDumpWriter: Callback context EIP=0x%08X ESP=0x%08X\n", pException->ContextRecord->Eip, + pException->ContextRecord->Esp); } } __except (EXCEPTION_EXECUTE_HANDLER) @@ -935,9 +912,9 @@ namespace } private: - std::vector> m_buffers; - std::vector m_streams; - MINIDUMP_USER_STREAM_INFORMATION m_info{}; + std::vector> m_buffers; + std::vector m_streams; + MINIDUMP_USER_STREAM_INFORMATION m_info{}; }; std::string FormatExceptionSummary(const ENHANCED_EXCEPTION_INFO& info) @@ -1010,11 +987,7 @@ namespace } } - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - "Thread ID: %lu Process ID: %lu\n", - static_cast(info.threadId), + _snprintf_s(line, sizeof(line), _TRUNCATE, "Thread ID: %lu Process ID: %lu\n", static_cast(info.threadId), static_cast(info.processId)); summary += line; @@ -1057,39 +1030,17 @@ namespace char line[160]{}; registers += "CPU Registers:\n"; - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " EAX=0x%08X EBX=0x%08X ECX=0x%08X EDX=0x%08X\n", - info.eax, - info.ebx, - info.ecx, - info.edx); + _snprintf_s(line, sizeof(line), _TRUNCATE, " EAX=0x%08X EBX=0x%08X ECX=0x%08X EDX=0x%08X\n", info.eax, info.ebx, info.ecx, info.edx); registers += line; - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " ESI=0x%08X EDI=0x%08X EBP=0x%08X ESP=0x%08X\n", - info.esi, - info.edi, - info.ebp, - info.esp); + _snprintf_s(line, sizeof(line), _TRUNCATE, " ESI=0x%08X EDI=0x%08X EBP=0x%08X ESP=0x%08X\n", info.esi, info.edi, info.ebp, info.esp); registers += line; _snprintf_s(line, sizeof(line), _TRUNCATE, " EIP=0x%08X EFLAGS=0x%08X\n", info.eip, info.eflags); registers += line; - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " CS=0x%04X DS=0x%04X ES=0x%04X FS=0x%04X GS=0x%04X SS=0x%04X\n", - info.cs, - info.ds, - info.es, - info.fs, - info.gs, - info.ss); + _snprintf_s(line, sizeof(line), _TRUNCATE, " CS=0x%04X DS=0x%04X ES=0x%04X FS=0x%04X GS=0x%04X SS=0x%04X\n", info.cs, info.ds, info.es, info.fs, + info.gs, info.ss); registers += line; return registers; @@ -1126,13 +1077,12 @@ namespace return text; } - std::string BuildAdditionalInfoPayload(const ENHANCED_EXCEPTION_INFO* info, - std::string_view telemetryFallback, - std::string_view fallbackSummary = {}) + std::string BuildAdditionalInfoPayload(const ENHANCED_EXCEPTION_INFO* info, std::string_view telemetryFallback, std::string_view fallbackSummary = {}) { std::string payload; - const auto appendBlock = [&](std::string_view block) { + const auto appendBlock = [&](std::string_view block) + { if (block.empty()) return; @@ -1204,17 +1154,13 @@ namespace summary += '\n'; } - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - "Module Offset: 0x%08X\n", - pExceptionInformation->GetAddressModuleOffset()); + _snprintf_s(line, sizeof(line), _TRUNCATE, "Module Offset: 0x%08X\n", pExceptionInformation->GetAddressModuleOffset()); summary += line; } return summary; } -} // namespace +} // namespace template void AppendDumpSection(const SString& targetPath, const char* tryLabel, const char* successLabel, DWORD tagBegin, DWORD tagEnd, SectionGenerator&& generator) @@ -1418,14 +1364,14 @@ static const char* GetMTAPathForSEH() { static char szPath[MAX_PATH] = {0}; static bool initialized = false; - + if (!initialized) { SString strPath = GetMTASABaseDir(); strncpy_s(szPath, sizeof(szPath), strPath.c_str(), _TRUNCATE); initialized = true; } - + return szPath; } @@ -1441,9 +1387,9 @@ static void TryWriteReentrantFlag(DWORD exceptionCode) } else { - return; // Cant proceed without path + return; // Cant proceed without path } - + __try { if (FILE* pFlagFile = File::Fopen(szFlagPath, "w")) @@ -1481,18 +1427,18 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept // Absolute first action - log that we entered the handler (before anything can fail) // This is critical for diagnosing exceptions that may fault during handling OutputDebugStringSafe("CCrashDumpWriter::HandleExceptionGlobal - EMERGENCY ENTRY MARKER\n"); - + // Log exception code and registers immediately - ensures crash context is captured // even if subsequent processing fails and no dump is generated (stale artifact scenario) // Uses SafeEmergencyLog internally which is SEH-protected LogEmergencyCrashContext(pException); - + SAFE_DEBUG_OUTPUT("========================================\n"); SAFE_DEBUG_OUTPUT("CCrashDumpWriter::HandleExceptionGlobal - ENTRY\n"); SAFE_DEBUG_OUTPUT("========================================\n"); const DWORD crashExitCode = ResolveCrashExitCode(pException); - + // Protect against stale/corrupted exception frames - use SEH to safely dereference exception pointers // This applies to any exception that may have invalid pointers (callbacks, stack corruption, etc.) const DWORD exceptionCodeSafe = SafeReadExceptionCode(pException); @@ -1502,7 +1448,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept if (!ms_bInCrashHandler.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) { SAFE_DEBUG_OUTPUT("CCrashDumpWriter: RECURSIVE CRASH - Already in crash handler\n"); - + // Try emergency minimal dump for any reentrant exception if (exceptionCodeSafe != 0) { @@ -1510,7 +1456,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Exception during crash handling - attempting emergency artifacts\n"); TryWriteReentrantFlag(exceptionCodeSafe); } - + TerminateCurrentProcessWithExitCode(crashExitCode); return EXCEPTION_EXECUTE_HANDLER; } @@ -1521,7 +1467,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept // Use the safely-obtained exception code from SEH block DWORD exceptionCode = SafeRereadExceptionCode(pException, exceptionCodeSafe); - + if (pException == nullptr || exceptionCode == 0) { SAFE_DEBUG_OUTPUT("CCrashDumpWriter::HandleExceptionGlobal - NULL or invalid exception\n"); @@ -1554,7 +1500,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept SAFE_DEBUG_OUTPUT("CCrashDumpWriter: STATUS_FATAL_USER_CALLBACK_EXCEPTION detected\n"); SAFE_DEBUG_OUTPUT("CCrashDumpWriter: This exception occurred in a Windows callback\n"); SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Stack frames may be incomplete or corrupted\n"); - + // Try to capture what we can with additional protection TryLogCallbackContext(pException); OutputDebugStringSafe("CCrashDumpWriter: EMERGENCY - Callback exception context capture attempted\n"); @@ -1577,9 +1523,8 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept if (storedCode == 0 && exceptionCode != 0) { std::array szDebug; - SAFE_DEBUG_PRINT_C(szDebug.data(), szDebug.size(), - "CCrashDumpWriter: CRITICAL - Set() failed, stored code is 0 (expected 0x%08X)\n", exceptionCode); - + SAFE_DEBUG_PRINT_C(szDebug.data(), szDebug.size(), "CCrashDumpWriter: CRITICAL - Set() failed, stored code is 0 (expected 0x%08X)\n", exceptionCode); + // This may occur due to null/corrupted context - try to salvage what we can SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Set() failed (likely null/corrupted context) - proceeding with minimal info\n"); // Continue processing with whatever partial info we have @@ -1723,10 +1668,8 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept {"dialog", crashDialogShown}, }}; - const bool crashArtifactsGenerated = std::any_of(crashStages.cbegin(), crashStages.cbegin() + 2, - [](const CrashStage& stage) { return stage.succeeded; }); - const bool crashHandlingComplete = std::all_of(crashStages.cbegin(), crashStages.cend(), - [](const CrashStage& stage) { return stage.succeeded; }); + const bool crashArtifactsGenerated = std::any_of(crashStages.cbegin(), crashStages.cbegin() + 2, [](const CrashStage& stage) { return stage.succeeded; }); + const bool crashHandlingComplete = std::all_of(crashStages.cbegin(), crashStages.cend(), [](const CrashStage& stage) { return stage.succeeded; }); SAFE_DEBUG_OUTPUT("CCrashDumpWriter: ======================================\n"); SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Crash processing complete - terminating\n"); @@ -1741,7 +1684,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept pExceptionInformation = nullptr; UniqueHandle crashDialogProcessHandle{ms_hCrashDialogProcess}; - const bool hadCrashDialogProcess = static_cast(crashDialogProcessHandle); + const bool hadCrashDialogProcess = static_cast(crashDialogProcessHandle); ms_hCrashDialogProcess = nullptr; if (hadCrashDialogProcess) @@ -1752,7 +1695,7 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept if (!hadCrashDialogProcess && crashDialogShown) { SAFE_DEBUG_OUTPUT("CCrashDumpWriter: No process handle (likely ShellExecute path), polling for dialog window...\n"); - + HWND hDialogWindow = nullptr; for (std::size_t attempts = 0; attempts < MAX_WINDOW_POLL_ATTEMPTS && hDialogWindow == nullptr; ++attempts) { @@ -1760,18 +1703,18 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept if (hDialogWindow == nullptr) Sleep(Milliseconds(WINDOW_POLL_TIMEOUT)); } - + if (hDialogWindow != nullptr && IsWindow(hDialogWindow)) { SAFE_DEBUG_OUTPUT(SString("CCrashDumpWriter: Found dialog window %p, waiting for it to close...\n", hDialogWindow).c_str()); - + while (true) { if (!IsWindow(hDialogWindow)) break; Sleep(Milliseconds(WINDOW_POLL_TIMEOUT)); } - + SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Dialog window closed\n"); } else @@ -1797,12 +1740,8 @@ long WINAPI CCrashDumpWriter::HandleExceptionGlobal(_EXCEPTION_POINTERS* pExcept std::transform(crashStages.cbegin(), crashStages.cend(), crashStageStatuses.begin(), [](const CrashStage& stage) { return stage.succeeded ? "ok" : "fail"; }); - AddReportLog(3146, - SString("Crash handler incomplete (code=0x%08X core=%s dump=%s dialog=%s)", - static_cast(crashExitCode), - crashStageStatuses[0], - crashStageStatuses[1], - crashStageStatuses[2])); + AddReportLog(3146, SString("Crash handler incomplete (code=0x%08X core=%s dump=%s dialog=%s)", static_cast(crashExitCode), + crashStageStatuses[0], crashStageStatuses[1], crashStageStatuses[2])); } SAFE_DEBUG_OUTPUT("CCrashDumpWriter: Force terminating crashed process NOW\n"); @@ -1831,13 +1770,12 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn // Use direct Win32 API to bypass potentially broken CRT after severe exceptions // (stack corruption, buffer overruns, invalid parameters can all corrupt CRT state) - bool flagFileCreated = false; - const auto hFlagFile = CreateFileA(CalcMTASAPath("mta\\core.log.flag"), GENERIC_WRITE, 0, nullptr, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + bool flagFileCreated = false; + const auto hFlagFile = CreateFileA(CalcMTASAPath("mta\\core.log.flag"), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFlagFile != INVALID_HANDLE_VALUE) { const char* flagData = "crash\n"; - DWORD bytesWritten = 0; + DWORD bytesWritten = 0; WriteFile(hFlagFile, flagData, static_cast(strlen(flagData)), &bytesWritten, nullptr); CloseHandle(hFlagFile); flagFileCreated = true; @@ -1862,13 +1800,13 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn constexpr auto kNullInstructionPointer = 0u; static_assert(kNullInstructionPointer == 0u, "Null instruction pointer must be zero"); - + const auto eip = pExceptionInformation->GetEIP(); const auto isNullJump = (eip == kNullInstructionPointer); - + constexpr std::string_view kNullJumpAnnotation = " (attempted jump to null)"; constexpr std::string_view kEmptyAnnotation = ""; - const auto eipAnnotation = isNullJump ? kNullJumpAnnotation : kEmptyAnnotation; + const auto eipAnnotation = isNullJump ? kNullJumpAnnotation : kEmptyAnnotation; SString strInfo{}; strInfo += SString("Version = %s\n", strMTAVersionFull.c_str()); @@ -1894,9 +1832,9 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n\n", pExceptionInformation->GetEAX(), pExceptionInformation->GetEBX(), pExceptionInformation->GetECX(), pExceptionInformation->GetEDX(), pExceptionInformation->GetESI(), pExceptionInformation->GetEDI(), pExceptionInformation->GetEBP(), pExceptionInformation->GetESP(), - pExceptionInformation->GetEIP(), static_cast(eipAnnotation.size()), eipAnnotation.data(), pExceptionInformation->GetEFlags(), - pExceptionInformation->GetCS(), pExceptionInformation->GetDS(), - pExceptionInformation->GetSS(), pExceptionInformation->GetES(), pExceptionInformation->GetFS(), pExceptionInformation->GetGS()); + pExceptionInformation->GetEIP(), static_cast(eipAnnotation.size()), eipAnnotation.data(), pExceptionInformation->GetEFlags(), + pExceptionInformation->GetCS(), pExceptionInformation->GetDS(), pExceptionInformation->GetSS(), pExceptionInformation->GetES(), + pExceptionInformation->GetFS(), pExceptionInformation->GetGS()); const auto invalidParameterCount = ms_uiInvalidParameterCount.load(std::memory_order_relaxed); strInfo += SString("InvalidParameterCount = %u\n", invalidParameterCount); @@ -1962,7 +1900,8 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn bool telemetryNotePresent = false; - const auto appendTelemetryNoteIfMissing = [&]() { + const auto appendTelemetryNoteIfMissing = [&]() + { if (telemetryNotePresent) return; @@ -2132,27 +2071,22 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn { constexpr std::size_t kTypicalStackDepth = 50; static_assert(kTypicalStackDepth > 0, "Stack depth must be positive"); - + std::vector lines{}; lines.reserve(kTypicalStackDepth); stackText.Split("\n", lines); - + if (const auto lineCount = lines.size(); lineCount > 0) { std::vector capturedFrames{}; capturedFrames.reserve(lineCount); - + std::transform(lines.cbegin(), lines.cend(), std::back_inserter(capturedFrames), - [](const auto& line) -> std::string { - return std::string{line.c_str()}; - }); - - const auto newEnd = std::remove_if(capturedFrames.begin(), capturedFrames.end(), - [](const auto& frame) -> bool { - return frame.empty(); - }); + [](const auto& line) -> std::string { return std::string{line.c_str()}; }); + + const auto newEnd = std::remove_if(capturedFrames.begin(), capturedFrames.end(), [](const auto& frame) -> bool { return frame.empty(); }); capturedFrames.erase(newEnd, capturedFrames.end()); - + if (const auto capturedCount = capturedFrames.size(); capturedCount > 0) { fallbackStackStorage = std::move(capturedFrames); @@ -2167,15 +2101,15 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn // Provide register-based context instead constexpr std::size_t kRegisterFrameCount = 3; static_assert(kRegisterFrameCount > 0, "Register frame count must be positive"); - + std::vector registerFrames{}; registerFrames.reserve(kRegisterFrameCount); - + const auto* ctx = pException->ContextRecord; registerFrames.emplace_back(SString("EIP=0x%08X (null instruction pointer - cannot walk stack)", ctx->Eip).c_str()); registerFrames.emplace_back(SString("ESP=0x%08X EBP=0x%08X (stack pointers)", ctx->Esp, ctx->Ebp).c_str()); registerFrames.emplace_back(SString("Last known address: check return address at [ESP] or recent call history", 0).c_str()); - + fallbackStackStorage = std::move(registerFrames); stackFrames = std::addressof(*fallbackStackStorage); stackHeader = "Stack trace (EIP=0 - register context only):\n"; @@ -2187,7 +2121,7 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn constexpr std::size_t kMaxDisplayFrames = 100; constexpr std::size_t kMaxFrameLength = 512; static_assert(kMaxDisplayFrames > 0 && kMaxFrameLength > 0, "Display limits must be positive"); - + const auto& frames = *stackFrames; const auto frameCount = frames.size(); const auto maxFrames = std::clamp(frameCount, std::size_t{0}, kMaxDisplayFrames); @@ -2196,9 +2130,8 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn stackHeader = "Stack trace:\n"; // For watchdog timeouts, add explanatory note about freeze point - const bool isWatchdogTimeout = pExceptionInformation != nullptr && - pExceptionInformation->GetCode() == CUSTOM_EXCEPTION_CODE_WATCHDOG_TIMEOUT; - + const bool isWatchdogTimeout = pExceptionInformation != nullptr && pExceptionInformation->GetCode() == CUSTOM_EXCEPTION_CODE_WATCHDOG_TIMEOUT; + if (isWatchdogTimeout && maxFrames > 0) { appendDetailedLine("Stack trace (captured from frozen thread - first frame shows freeze location):\n"); @@ -2207,16 +2140,15 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn { appendDetailedLine(stackHeader); } - - [[maybe_unused]] const auto allFramesValid = - std::all_of(frames.cbegin(), std::next(frames.cbegin(), static_cast(maxFrames)), - [](const auto& frame) constexpr -> bool { return !frame.empty(); }); - + + [[maybe_unused]] const auto allFramesValid = std::all_of(frames.cbegin(), std::next(frames.cbegin(), static_cast(maxFrames)), + [](const auto& frame) constexpr -> bool { return !frame.empty(); }); + for (std::size_t i{}; i < maxFrames; ++i) { const auto& frame = frames[i]; const std::size_t frameLength = std::clamp(frame.length(), std::size_t{0}, kMaxFrameLength); - + // First frame in watchdog timeout = exact freeze location if (isWatchdogTimeout && i == 0) { @@ -2234,10 +2166,11 @@ void CCrashDumpWriter::DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionIn } // Get crash dump file path if available - const auto dumpFileInfo = [dumpFilePath = GetApplicationSetting("diagnostics", "last-dump-save")]() -> SString { + const auto dumpFileInfo = [dumpFilePath = GetApplicationSetting("diagnostics", "last-dump-save")]() -> SString + { if (dumpFilePath.empty()) return {}; - + constexpr std::string_view kDumpFileHeader = "\nCrash dump file: "; return SString{kDumpFileHeader.data(), kDumpFileHeader.size()} + dumpFilePath + "\n"; }(); @@ -2409,10 +2342,10 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI MinidumpUserStreamCollection userStreams; - const std::string telemetryNote = CrashTelemetry::BuildAllocationTelemetryNote(); - std::string basicSummary; + const std::string telemetryNote = CrashTelemetry::BuildAllocationTelemetryNote(); + std::string basicSummary; ENHANCED_EXCEPTION_INFO enhancedInfo{}; - const bool hasEnhancedInfo = (GetEnhancedExceptionInfo(&enhancedInfo) != FALSE); + const bool hasEnhancedInfo = (GetEnhancedExceptionInfo(&enhancedInfo) != FALSE); if (hasEnhancedInfo) { @@ -2427,10 +2360,8 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI userStreams.AddTextStream(kStreamExceptionSummary, basicSummary); } - const std::string additionalInfoPayload = BuildAdditionalInfoPayload( - hasEnhancedInfo ? &enhancedInfo : nullptr, - telemetryNote, - hasEnhancedInfo ? std::string_view{} : std::string_view{basicSummary}); + const std::string additionalInfoPayload = BuildAdditionalInfoPayload(hasEnhancedInfo ? &enhancedInfo : nullptr, telemetryNote, + hasEnhancedInfo ? std::string_view{} : std::string_view{basicSummary}); userStreams.AddTextStream(kStreamAdditionalInfo, additionalInfoPayload); PMINIDUMP_USER_STREAM_INFORMATION userStreamParam = userStreams.Build(); @@ -2443,16 +2374,15 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI const DWORD dwError = GetLastError(); AddReportLog(9204, SString("CCrashDumpWriter::DumpMiniDump - MiniDumpWriteDump failed (%08x)", dwError)); SAFE_DEBUG_OUTPUT(SString("CCrashDumpWriter::DumpMiniDump - MiniDumpWriteDump FAILED with error 0x%08X\n", dwError).c_str()); - + // Retry with simpler dump type on partial copy errors (corrupted stacks, inaccessible memory) - if (dwError == 0x8007012B || dwError == ERROR_PARTIAL_COPY) // ERROR_PARTIAL_COPY + if (dwError == 0x8007012B || dwError == ERROR_PARTIAL_COPY) // ERROR_PARTIAL_COPY { SAFE_DEBUG_OUTPUT("CCrashDumpWriter::DumpMiniDump - Retrying with MiniDumpNormal only (no indirect memory)\n"); SetFilePointer(hFile, 0, nullptr, FILE_BEGIN); SetEndOfFile(hFile); - - bResult = pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, - MiniDumpNormal, &ExInfo, userStreamParam, nullptr); + + bResult = pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, userStreamParam, nullptr); if (bResult) { SAFE_DEBUG_OUTPUT("CCrashDumpWriter::DumpMiniDump - Retry with MiniDumpNormal succeeded\n"); @@ -2667,7 +2597,8 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI ReleaseCapture(); SystemParametersInfoW(SPI_SETCURSORS, 0, nullptr, 0); - auto EnsureCursorVisible = []() { + auto EnsureCursorVisible = []() + { int cursorCount = ShowCursor(TRUE); int loopGuard = 0; while (cursorCount < 1 && loopGuard++ < 256) @@ -2911,15 +2842,15 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI std::vector commandBuffer(commandLineWide.length() + 1u, L'\0'); std::copy(commandLineWide.begin(), commandLineWide.end(), commandBuffer.begin()); - STARTUPINFOW startupInfo{}; + STARTUPINFOW startupInfo{}; startupInfo.cb = sizeof(startupInfo); startupInfo.dwFlags = STARTF_USESHOWWINDOW; startupInfo.wShowWindow = SW_SHOWNORMAL; PROCESS_INFORMATION processInfo{}; constexpr DWORD kProcessCreationFlags = DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB | CREATE_NEW_PROCESS_GROUP; - const auto bProcessCreated = - CreateProcessW(nullptr, commandBuffer.data(), nullptr, nullptr, FALSE, kProcessCreationFlags, nullptr, candidateDirWidePtr, &startupInfo, &processInfo); + const auto bProcessCreated = CreateProcessW(nullptr, commandBuffer.data(), nullptr, nullptr, FALSE, kProcessCreationFlags, nullptr, candidateDirWidePtr, + &startupInfo, &processInfo); if (bProcessCreated) { AddReportLog(3124, SString("RunErrorTool launched crash dialog via CreateProcess (%s)", candidate.c_str())); @@ -3047,11 +2978,11 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI Sleep(1000); HWND hDialogWindow = nullptr; - for (std::size_t attempts = 0; attempts < SHELL_EXEC_POLL_ATTEMPTS && hDialogWindow == nullptr; attempts++) + for (std::size_t attempts = 0; attempts < SHELL_EXEC_POLL_ATTEMPTS && hDialogWindow == nullptr; attempts++) { hDialogWindow = FindWindowW(nullptr, L"MTA: San Andreas has encountered a problem"); if (hDialogWindow == nullptr) - Sleep(Milliseconds(WINDOW_POLL_TIMEOUT)); + Sleep(Milliseconds(WINDOW_POLL_TIMEOUT)); } if (hDialogWindow != nullptr && IsWindow(hDialogWindow)) @@ -3066,7 +2997,8 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI } else { - AddReportLog(3122, SString("RunErrorTool ShellExecute fallback failed with code %u for %s", static_cast(shellExecuteCode), candidate.c_str())); + AddReportLog( + 3122, SString("RunErrorTool ShellExecute fallback failed with code %u for %s", static_cast(shellExecuteCode), candidate.c_str())); } RestoreBaseDirectories(); @@ -3088,8 +3020,7 @@ void CCrashDumpWriter::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionI L"Contact support on the MTA discord: https://discord.gg/RygaCSD.\n\n" L"The game will now close."; - MessageBoxW(nullptr, emergencyMessage, L"MTA: San Andreas - Fatal Error", - MB_OK | MB_ICONERROR | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_TOPMOST); + MessageBoxW(nullptr, emergencyMessage, L"MTA: San Andreas - Fatal Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_TOPMOST); } return dialogLaunched; @@ -3320,7 +3251,7 @@ namespace return iOut; } -} // namespace +} // namespace void CCrashDumpWriter::GetPoolInfo(CBuffer& buffer) { diff --git a/Client/core/CCrashDumpWriter.h b/Client/core/CCrashDumpWriter.h index 6928e2a1692..228dcd0d374 100644 --- a/Client/core/CCrashDumpWriter.h +++ b/Client/core/CCrashDumpWriter.h @@ -39,26 +39,26 @@ enum EDumpFileNameParts class CCrashDumpWriter { public: - static long WINAPI HandleExceptionGlobal(_EXCEPTION_POINTERS* pException); - static void DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation); - static void DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation); + static long WINAPI HandleExceptionGlobal(_EXCEPTION_POINTERS* pException); + static void DumpCoreLog(_EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation); + static void DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation); [[nodiscard]] static bool RunErrorTool(CExceptionInformation* pExceptionInformation); - static void AppendToDumpFile(const SString& strPathFilename, const CBuffer& dataBuffer, DWORD dwMagicStart, DWORD dwMagicEnd); - static void GetPoolInfo(CBuffer& buffer); - static void GetD3DInfo(CBuffer& buffer); - static void GetCrashAvertedStats(CBuffer& buffer); - static void GetLogInfo(CBuffer& buffer); - static void GetDxInfo(CBuffer& buffer); - static void GetMemoryInfo(CBuffer& buffer); - static void GetCurrentAnimTaskInfo(CBuffer& buffer); - static void GetMiscInfo(CBuffer& buffer); - static void OnCrashAverted(uint uiId); - static void OnEnterCrashZone(uint uiId); - static void LogEvent(const char* szType, const char* szContext, const char* szBody); - static SString GetCrashAvertedStatsSoFar(); - static void ReserveMemoryKBForCrashDumpProcessing(uint uiMemoryKB); - static void FreeMemoryForCrashDumpProcessing(); - static void SetHandlers(); - static void UpdateCounters(); - static void HandleInvalidParameter(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved); + static void AppendToDumpFile(const SString& strPathFilename, const CBuffer& dataBuffer, DWORD dwMagicStart, DWORD dwMagicEnd); + static void GetPoolInfo(CBuffer& buffer); + static void GetD3DInfo(CBuffer& buffer); + static void GetCrashAvertedStats(CBuffer& buffer); + static void GetLogInfo(CBuffer& buffer); + static void GetDxInfo(CBuffer& buffer); + static void GetMemoryInfo(CBuffer& buffer); + static void GetCurrentAnimTaskInfo(CBuffer& buffer); + static void GetMiscInfo(CBuffer& buffer); + static void OnCrashAverted(uint uiId); + static void OnEnterCrashZone(uint uiId); + static void LogEvent(const char* szType, const char* szContext, const char* szBody); + static SString GetCrashAvertedStatsSoFar(); + static void ReserveMemoryKBForCrashDumpProcessing(uint uiMemoryKB); + static void FreeMemoryForCrashDumpProcessing(); + static void SetHandlers(); + static void UpdateCounters(); + static void HandleInvalidParameter(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved); }; diff --git a/Client/core/CCredits.cpp b/Client/core/CCredits.cpp index 4df8a1a0cf3..cd4dab1705c 100644 --- a/Client/core/CCredits.cpp +++ b/Client/core/CCredits.cpp @@ -17,7 +17,7 @@ namespace CCreditsGUI { float fWindowX = 560.0f; float fWindowY = 300.0f; -} // namespace CCreditsGUI +} using namespace CCreditsGUI; CCredits::CCredits() @@ -315,7 +315,6 @@ CCredits::CCredits() "UnRAR (https://www.rarlab.com/)\n" "zlib (https://zlib.net/)\n"; - // SA credits m_strCredits += "\n\n\n== Grand Theft Auto: San Andreas (TM) (c) 2005 Rockstar Games, Inc. ==\n\n\n"; @@ -1092,8 +1091,7 @@ CCredits::CCredits() "Sarah Oram\n" "Smoke Stack\n" "Trattoria Siciliana\n" - "Black Bull\n" - ; + "Black Bull\n"; // Create our window CVector2D RelativeWindow = CVector2D(fWindowX / pManager->GetResolution().fX, fWindowY / pManager->GetResolution().fY); @@ -1101,7 +1099,7 @@ CCredits::CCredits() m_pWindow->SetCloseButtonEnabled(false); m_pWindow->SetMovable(false); m_pWindow->SetPosition(CVector2D(0.5f - RelativeWindow.fX * 0.5f, 0.5f - RelativeWindow.fY * 0.5f), true); - m_pWindow->SetSize(CVector2D(fWindowX, fWindowY)); // relative 0.70, 0.50 + m_pWindow->SetSize(CVector2D(fWindowX, fWindowY)); // relative 0.70, 0.50 m_pWindow->SetSizingEnabled(false); m_pWindow->SetVisible(false); m_pWindow->SetAlwaysOnTop(true); @@ -1134,7 +1132,7 @@ CCredits::CCredits() // Create the label m_pLabels[uiLabelIndex] = reinterpret_cast(pManager->CreateLabel(m_pWindow, strBuffer.c_str())); m_pLabels[uiLabelIndex]->SetPosition(CVector2D(0.022f, fStartPosition), true); - m_pLabels[uiLabelIndex]->SetSize(CVector2D(532.0f, 1500.0f)); // relative 0.95, 6.0 + m_pLabels[uiLabelIndex]->SetSize(CVector2D(532.0f, 1500.0f)); // relative 0.95, 6.0 m_pLabels[uiLabelIndex]->SetHorizontalAlign(CGUI_ALIGN_HORIZONTALCENTER); ++uiLabelIndex; @@ -1153,7 +1151,7 @@ CCredits::CCredits() // Create the OK button m_pButtonOK = reinterpret_cast(pManager->CreateButton(m_pWindow, "OK")); m_pButtonOK->SetPosition(CVector2D(0.77f, 0.90f), true); - m_pButtonOK->SetSize(CVector2D(112.0f, 21.0f)); // relative 0.20, 0.07 + m_pButtonOK->SetSize(CVector2D(112.0f, 21.0f)); // relative 0.20, 0.07 m_pButtonOK->SetVisible(true); m_pButtonOK->SetAlwaysOnTop(true); diff --git a/Client/core/CDebugView.h b/Client/core/CDebugView.h index 3f43368f263..75b60306c64 100644 --- a/Client/core/CDebugView.h +++ b/Client/core/CDebugView.h @@ -15,8 +15,8 @@ #include #include "CChat.h" -#define DEBUGVIEW_WIDTH 576 // Debugview default width -#define DEBUGVIEW_TEXT_COLOR CColor( 235, 221, 178, 255 ) // Debugview default text color +#define DEBUGVIEW_WIDTH 576 // Debugview default width +#define DEBUGVIEW_TEXT_COLOR CColor(235, 221, 178, 255) // Debugview default text color class CDebugView : public CChat { @@ -28,5 +28,5 @@ class CDebugView : public CChat protected: // Debug view doesn't support position changes unlike chat box - void UpdatePosition() override{}; + void UpdatePosition() override {}; }; diff --git a/Client/core/CDiscordRichPresence.cpp b/Client/core/CDiscordRichPresence.cpp index bc49a07a91a..28473778292 100644 --- a/Client/core/CDiscordRichPresence.cpp +++ b/Client/core/CDiscordRichPresence.cpp @@ -37,7 +37,7 @@ CDiscordRichPresence::~CDiscordRichPresence() void CDiscordRichPresence::InitializeDiscord() { std::lock_guard lock(m_threadSafetyMutex); - DiscordEventHandlers handlers; + DiscordEventHandlers handlers; memset(&handlers, 0, sizeof(handlers)); handlers.ready = HandleDiscordReady; @@ -107,7 +107,7 @@ void CDiscordRichPresence::UpdatePresence() return; std::lock_guard lock(m_threadSafetyMutex); - DiscordRichPresence discordPresence; + DiscordRichPresence discordPresence; memset(&discordPresence, 0, sizeof(discordPresence)); discordPresence.largeImageKey = m_strDiscordAppAsset.c_str(); @@ -115,7 +115,8 @@ void CDiscordRichPresence::UpdatePresence() discordPresence.smallImageKey = m_strDiscordAppAssetSmall.c_str(); discordPresence.smallImageText = m_strDiscordAppAssetSmallText.c_str(); - discordPresence.state = (!m_strDiscordAppCustomState.empty() || !m_bDisallowCustomDetails) ? m_strDiscordAppCustomState.c_str() : m_strDiscordAppState.c_str(); + discordPresence.state = + (!m_strDiscordAppCustomState.empty() || !m_bDisallowCustomDetails) ? m_strDiscordAppCustomState.c_str() : m_strDiscordAppState.c_str(); discordPresence.details = (!m_strDiscordAppCustomDetails.empty() || !m_bDisallowCustomDetails) ? m_strDiscordAppCustomDetails.c_str() : m_strDiscordAppDetails.c_str(); diff --git a/Client/core/CExceptionInformation_Impl.cpp b/Client/core/CExceptionInformation_Impl.cpp index a2e94f8f21d..b1cc2e2922d 100644 --- a/Client/core/CExceptionInformation_Impl.cpp +++ b/Client/core/CExceptionInformation_Impl.cpp @@ -101,15 +101,16 @@ constexpr std::size_t MAX_SYMBOL_NAME = 256; if (copyResult == STRUNCATE) { char buffer[DEBUG_BUFFER_SIZE] = {}; - SAFE_DEBUG_PRINT_C(buffer, DEBUG_BUFFER_SIZE, "%.*s%s - Module path truncated to %zu bytes\n", - static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), context, destinationSize - 1U); + SAFE_DEBUG_PRINT_C(buffer, DEBUG_BUFFER_SIZE, "%.*s%s - Module path truncated to %zu bytes\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), + DEBUG_PREFIX_EXCEPTION_INFO.data(), context, destinationSize - 1U); return true; } if (copyResult != 0) { char buffer[DEBUG_BUFFER_SIZE] = {}; - SAFE_DEBUG_PRINT_C(buffer, DEBUG_BUFFER_SIZE, "%.*s%s - strncpy_s failed (error=%d)\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), context, copyResult); + SAFE_DEBUG_PRINT_C(buffer, DEBUG_BUFFER_SIZE, "%.*s%s - strncpy_s failed (error=%d)\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), + DEBUG_PREFIX_EXCEPTION_INFO.data(), context, copyResult); if (destinationSize > 0U) destination[0] = '\0'; return false; @@ -131,8 +132,7 @@ constexpr std::size_t MAX_FILE_NAME = 260; class SymbolHandlerGuard { public: - explicit SymbolHandlerGuard(HANDLE process, bool enableSymbols) - : m_process(process), m_initialized(false), m_uncaughtExceptions(std::uncaught_exceptions()) + explicit SymbolHandlerGuard(HANDLE process, bool enableSymbols) : m_process(process), m_initialized(false), m_uncaughtExceptions(std::uncaught_exceptions()) { if (!enableSymbols) { @@ -142,18 +142,17 @@ class SymbolHandlerGuard if (m_process != nullptr) { SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS); - + if (SymInitialize(m_process, nullptr, TRUE) != FALSE) { m_initialized = true; } else { - const DWORD dwError = GetLastError(); - char debugBuffer[DEBUG_BUFFER_SIZE] = {}; - SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sSymbolHandlerGuard: SymInitialize failed, error: %u\n", - static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), dwError); - + const DWORD dwError = GetLastError(); + char debugBuffer[DEBUG_BUFFER_SIZE] = {}; + SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sSymbolHandlerGuard: SymInitialize failed, error: %u\n", + static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), dwError); } } } @@ -192,9 +191,9 @@ class SymbolHandlerGuard if (!hasSymbols) { static std::once_flag logOnce; - std::call_once(logOnce, [] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_EXCEPTION_INFO, "CaptureEnhancedStackTrace - capturing without symbols (raw addresses only)\n"); - }); + std::call_once( + logOnce, + [] { SafeDebugPrintPrefixed(DEBUG_PREFIX_EXCEPTION_INFO, "CaptureEnhancedStackTrace - capturing without symbols (raw addresses only)\n"); }); } std::vector frames; @@ -219,9 +218,7 @@ class SymbolHandlerGuard const bool useDbgHelp = symbolGuard.IsInitialized(); - const auto routines = useDbgHelp - ? StackTraceHelpers::MakeStackWalkRoutines(true) - : StackTraceHelpers::MakeStackWalkRoutines(false); + const auto routines = useDbgHelp ? StackTraceHelpers::MakeStackWalkRoutines(true) : StackTraceHelpers::MakeStackWalkRoutines(false); alignas(SYMBOL_INFO) std::uint8_t symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME]; memset(symbolBuffer, 0, sizeof(symbolBuffer)); PSYMBOL_INFO pSymbol = reinterpret_cast(symbolBuffer); @@ -230,15 +227,8 @@ class SymbolHandlerGuard for (std::size_t frameIndex = 0; frameIndex < MAX_STACK_FRAMES; ++frameIndex) { - BOOL bWalked = StackWalk64(IMAGE_FILE_MACHINE_I386, - hProcess, - hThread, - &frame, - &context, - routines.readMemory, - routines.functionTableAccess, - routines.moduleBase, - nullptr); + BOOL bWalked = StackWalk64(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &frame, &context, routines.readMemory, routines.functionTableAccess, + routines.moduleBase, nullptr); if (bWalked == FALSE) break; @@ -313,22 +303,16 @@ class SymbolHandlerGuard struct ResolutionDiagnostics { DWORD eipUsed = 0; - int failReason = 0; - int chunkCount = 0; - int moduleCount = 0; - int innerFailReason = 0; + int failReason = 0; + int chunkCount = 0; + int moduleCount = 0; + int innerFailReason = 0; }; -static bool ResolveModuleFromRegistrySafe_Inner( - _EXCEPTION_POINTERS* pException, - void* pAddress, - CExceptionInformation_Impl::ResolvedInfo& outInfo, - std::string& outNameStorage, - ResolutionDiagnostics& diag) +static bool ResolveModuleFromRegistrySafe_Inner(_EXCEPTION_POINTERS* pException, void* pAddress, CExceptionInformation_Impl::ResolvedInfo& outInfo, + std::string& outNameStorage, ResolutionDiagnostics& diag) { - const DWORD eipForResolution = (pException->ContextRecord != nullptr) - ? pException->ContextRecord->Eip - : reinterpret_cast(pAddress); + const DWORD eipForResolution = (pException->ContextRecord != nullptr) ? pException->ContextRecord->Eip : reinterpret_cast(pAddress); diag.eipUsed = eipForResolution; @@ -369,12 +353,8 @@ static bool ResolveModuleFromRegistrySafe_Inner( // NO C++ objects with destructors allowed in this function! // ////////////////////////////////////////////////////////// -static bool ResolveModuleFromRegistrySafe_SEH( - _EXCEPTION_POINTERS* pException, - void* pAddress, - CExceptionInformation_Impl::ResolvedInfo& outInfo, - std::string& outNameStorage, - ResolutionDiagnostics& diag) +static bool ResolveModuleFromRegistrySafe_SEH(_EXCEPTION_POINTERS* pException, void* pAddress, CExceptionInformation_Impl::ResolvedInfo& outInfo, + std::string& outNameStorage, ResolutionDiagnostics& diag) { __try { @@ -405,16 +385,15 @@ void CExceptionInformation_Impl::ResolveModuleFromRegistrySafe(_EXCEPTION_POINTE if (ResolveModuleFromRegistrySafe_SEH(pException, m_pAddress, m_resolvedModuleInfo, m_resolvedModuleNameStorage, diag)) { char buf[256]; - sprintf_s(buf, sizeof(buf), "ResolveModule: OK EIP=0x%08X Base=0x%08X RVA=0x%08X IDA=0x%08X Chunks=%d Mods=%d\n", - diag.eipUsed, m_resolvedModuleInfo.moduleBase, m_resolvedModuleInfo.rva, m_resolvedModuleInfo.idaAddress, - diag.chunkCount, diag.moduleCount); + sprintf_s(buf, sizeof(buf), "ResolveModule: OK EIP=0x%08X Base=0x%08X RVA=0x%08X IDA=0x%08X Chunks=%d Mods=%d\n", diag.eipUsed, + m_resolvedModuleInfo.moduleBase, m_resolvedModuleInfo.rva, m_resolvedModuleInfo.idaAddress, diag.chunkCount, diag.moduleCount); OutputDebugStringA(buf); } else { char buf[256]; - sprintf_s(buf, sizeof(buf), "ResolveModule: FAIL EIP=0x%08X Reason=%d Chunks=%d Mods=%d InnerFail=%d\n", - diag.eipUsed, diag.failReason, diag.chunkCount, diag.moduleCount, diag.innerFailReason); + sprintf_s(buf, sizeof(buf), "ResolveModule: FAIL EIP=0x%08X Reason=%d Chunks=%d Mods=%d InnerFail=%d\n", diag.eipUsed, diag.failReason, diag.chunkCount, + diag.moduleCount, diag.innerFailReason); OutputDebugStringA(buf); m_resolvedModuleInfo = {}; @@ -478,7 +457,7 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p DebugPrintExceptionInfo("Set - Null context record (exception type requires context)\n"); return; } - + if (pException->ContextRecord == nullptr && isCallbackException) { DebugPrintExceptionInfo("Set - Null context for callback exception - proceeding with limited info\n"); @@ -501,13 +480,11 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p { char debugBuf[128]; - sprintf_s(debugBuf, sizeof(debugBuf), ">>> Set: GetEnhancedExceptionInfo returned %s <<<\n", - hasEnhancedInfo ? "TRUE" : "FALSE"); + sprintf_s(debugBuf, sizeof(debugBuf), ">>> Set: GetEnhancedExceptionInfo returned %s <<<\n", hasEnhancedInfo ? "TRUE" : "FALSE"); OutputDebugStringA(debugBuf); if (hasEnhancedInfo) { - sprintf_s(debugBuf, sizeof(debugBuf), ">>> Set: Enhanced code=0x%08X, current code=0x%08X <<<\n", - enhancedInfo.exceptionCode, iCode); + sprintf_s(debugBuf, sizeof(debugBuf), ">>> Set: Enhanced code=0x%08X, current code=0x%08X <<<\n", enhancedInfo.exceptionCode, iCode); OutputDebugStringA(debugBuf); } } @@ -515,7 +492,7 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p if (hasEnhancedInfo && enhancedInfo.exceptionCode == iCode) { DebugPrintExceptionInfo("Set - Using enhanced exception info from CrashHandler (FRESH)\n"); - + // Additional note for callback exceptions even when we have enhanced info if (iCode == 0xC000041D) { @@ -526,9 +503,8 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p { char mismatchBuffer[DEBUG_BUFFER_SIZE] = {}; SAFE_DEBUG_PRINT_C(mismatchBuffer, DEBUG_BUFFER_SIZE, - "%.*sSet - Exception code mismatch (stored: 0x%08X, current: 0x%08X) - STALE DATA, extracting fresh\n", - static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), - enhancedInfo.exceptionCode, iCode); + "%.*sSet - Exception code mismatch (stored: 0x%08X, current: 0x%08X) - STALE DATA, extracting fresh\n", + static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), enhancedInfo.exceptionCode, iCode); hasEnhancedInfo = false; } else if (!hasEnhancedInfo) @@ -681,37 +657,32 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p // Special handling for EIP=0: Start from return address at [ESP] instead constexpr auto kNullAddress = uintptr_t{0}; static_assert(kNullAddress == 0, "Null address must be zero"); - + const auto queryAddressValue = reinterpret_cast(pQueryAddress); - + if (queryAddressValue == kNullAddress && m_ulEIP == kNullAddress) { const auto espAddr = static_cast(m_ulESP); const auto pReturnAddress = reinterpret_cast(espAddr); - + char debugBuffer[DEBUG_BUFFER_SIZE] = {}; - SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, - "%.*sSet - EIP=0 detected (ESP=0x%08X), attempting to read return address...\n", - static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), - static_cast(espAddr)); - + SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sSet - EIP=0 detected (ESP=0x%08X), attempting to read return address...\n", + static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), static_cast(espAddr)); + if (SharedUtil::IsReadablePointer(pReturnAddress, sizeof(void*))) { pQueryAddress = *pReturnAddress; pExceptionAddress = pQueryAddress; - + const auto returnAddressValue = reinterpret_cast(pQueryAddress); - SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, - "%.*sSet - Successfully read return address: 0x%08X\n", + SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sSet - Successfully read return address: 0x%08X\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), static_cast(returnAddressValue)); } else { - SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, - "%.*sSet - Failed to read return address at ESP=0x%08X (not readable)\n", - static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), - static_cast(espAddr)); + SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sSet - Failed to read return address at ESP=0x%08X (not readable)\n", + static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), static_cast(espAddr)); } } @@ -732,8 +703,8 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p } const std::string_view tempPathView(tempModulePathBuffer.get()); - auto tempBaseNamePos = tempPathView.find_last_of('\\'); - const char* szModuleBaseNameTemp = + auto tempBaseNamePos = tempPathView.find_last_of('\\'); + const char* szModuleBaseNameTemp = tempBaseNamePos != std::string_view::npos ? tempModulePathBuffer.get() + tempBaseNamePos + 1 : tempModulePathBuffer.get(); if (szModuleBaseNameTemp == nullptr) @@ -743,8 +714,8 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p if (i == 0) { - const bool copied = CopyModulePathToBuffer(tempModulePathBuffer.get(), modulePathNameBuffer.get(), MAX_MODULE_PATH, - "Set - Initial module path copy"); + const bool copied = + CopyModulePathToBuffer(tempModulePathBuffer.get(), modulePathNameBuffer.get(), MAX_MODULE_PATH, "Set - Initial module path copy"); if (!copied) { DebugPrintExceptionInfo("Set - Initial module path copy failed\n"); @@ -756,8 +727,8 @@ void CExceptionInformation_Impl::Set(std::uint32_t iCode, _EXCEPTION_POINTERS* p if (::_strnicmp(szModuleBaseNameTemp, "ntdll", 5) != 0 && ::_strnicmp(szModuleBaseNameTemp, "kernel", 6) != 0 && ::_strnicmp(szModuleBaseNameTemp, "msvc", 4) != 0 && ::_stricmp(szModuleBaseNameTemp, "") != 0) { - const bool copied = CopyModulePathToBuffer(tempModulePathBuffer.get(), modulePathNameBuffer.get(), MAX_MODULE_PATH, - "Set - Selected module path copy"); + const bool copied = + CopyModulePathToBuffer(tempModulePathBuffer.get(), modulePathNameBuffer.get(), MAX_MODULE_PATH, "Set - Selected module path copy"); if (!copied) { DebugPrintExceptionInfo("Set - Selected module path copy failed\n"); @@ -895,7 +866,7 @@ bool CExceptionInformation_Impl::GetModule(void* pQueryAddress, char* szOutputBu } HMODULE hModule = nullptr; - + // Wrap in __try for exception addresses that may be invalid/in guard pages/trampolines // (callbacks, corrupted stacks, etc. can point to invalid memory) __try @@ -903,11 +874,11 @@ bool CExceptionInformation_Impl::GetModule(void* pQueryAddress, char* szOutputBu if (pfnGetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, static_cast(pQueryAddress), &hModule) == 0) { - const DWORD dwErrorHandle = GetLastError(); - char debugBuffer[DEBUG_BUFFER_SIZE] = {}; + const DWORD dwErrorHandle = GetLastError(); + char debugBuffer[DEBUG_BUFFER_SIZE] = {}; SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sGetModule - GetModuleHandleExA failed (0x%08X)\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), dwErrorHandle); - + // Address may be a system trampoline or invalid memory - don't proceed return false; } @@ -926,8 +897,8 @@ bool CExceptionInformation_Impl::GetModule(void* pQueryAddress, char* szOutputBu const DWORD dwResult = GetModuleFileNameA(hModule, szOutputBuffer, nOutputNameLength); if (dwResult == 0) { - const DWORD dwErrorFileName = GetLastError(); - char debugBuffer[DEBUG_BUFFER_SIZE] = {}; + const DWORD dwErrorFileName = GetLastError(); + char debugBuffer[DEBUG_BUFFER_SIZE] = {}; SAFE_DEBUG_PRINT_C(debugBuffer, DEBUG_BUFFER_SIZE, "%.*sGetModule - GetModuleFileNameA failed (0x%08X)\n", static_cast(DEBUG_PREFIX_EXCEPTION_INFO.size()), DEBUG_PREFIX_EXCEPTION_INFO.data(), dwErrorFileName); szOutputBuffer[0] = '\0'; diff --git a/Client/core/CFileFormatJpeg.cpp b/Client/core/CFileFormatJpeg.cpp index 3d50aa527e3..bc640910470 100644 --- a/Client/core/CFileFormatJpeg.cpp +++ b/Client/core/CFileFormatJpeg.cpp @@ -11,8 +11,8 @@ #include "StdInc.h" #include "jinclude.h" #include "jpeglib.h" -#include "jerror.h" /* get library error codes too */ -#include "cderror.h" /* get application-specific error codes */ +#include "jerror.h" /* get library error codes too */ +#include "cderror.h" /* get application-specific error codes */ // Custom error handler for libjpeg - allows recovery instead of exit() struct JpegErrorManager @@ -95,11 +95,11 @@ bool JpegDecode(const void* pData, uint uiDataSize, CBuffer* pOutBuffer, uint& u } // Validate dimensions (libjpeg max: 65500) - if (cinfo.image_width == 0 || cinfo.image_height == 0 || - cinfo.image_width > JPEG_MAX_DIMENSION || cinfo.image_height > JPEG_MAX_DIMENSION) + if (cinfo.image_width == 0 || cinfo.image_height == 0 || cinfo.image_width > JPEG_MAX_DIMENSION || cinfo.image_height > JPEG_MAX_DIMENSION) { if (pOutError) - *pOutError = "Invalid JPEG dimensions: " + std::to_string(cinfo.image_width) + "x" + std::to_string(cinfo.image_height) + " (max " + std::to_string(JPEG_MAX_DIMENSION) + ")"; + *pOutError = "Invalid JPEG dimensions: " + std::to_string(cinfo.image_width) + "x" + std::to_string(cinfo.image_height) + " (max " + + std::to_string(JPEG_MAX_DIMENSION) + ")"; jpeg_destroy_decompress(&cinfo); return false; } @@ -136,7 +136,8 @@ bool JpegDecode(const void* pData, uint uiDataSize, CBuffer* pOutBuffer, uint& u if (uiRequiredSize > UINT_MAX) { if (pOutError) - *pOutError = "JPEG dimensions too large for buffer: " + std::to_string(uiWidth) + "x" + std::to_string(uiHeight) + " requires " + std::to_string(uiRequiredSize) + " bytes"; + *pOutError = "JPEG dimensions too large for buffer: " + std::to_string(uiWidth) + "x" + std::to_string(uiHeight) + " requires " + + std::to_string(uiRequiredSize) + " bytes"; jpeg_destroy_decompress(&cinfo); return false; } @@ -175,14 +176,15 @@ bool JpegDecode(const void* pData, uint uiDataSize, CBuffer* pOutBuffer, uint& u while (cinfo.output_scanline < cinfo.output_height) { uint64 uiRowOffset = static_cast(cinfo.output_scanline) * uiWidth * 4; - BYTE* pRowDest = (BYTE*)pOutData + static_cast(uiRowOffset); + BYTE* pRowDest = (BYTE*)pOutData + static_cast(uiRowOffset); row_pointer[0] = (JSAMPROW)pRowTemp; JDIMENSION num_read = jpeg_read_scanlines(&cinfo, row_pointer, 1); if (num_read != 1) { if (pOutError) - *pOutError = "Failed to read JPEG scanline " + std::to_string(cinfo.output_scanline) + " of " + std::to_string(cinfo.output_height) + " (truncated image?)"; + *pOutError = "Failed to read JPEG scanline " + std::to_string(cinfo.output_scanline) + " of " + std::to_string(cinfo.output_height) + + " (truncated image?)"; jpeg_destroy_decompress(&cinfo); return false; } @@ -193,7 +195,7 @@ bool JpegDecode(const void* pData, uint uiDataSize, CBuffer* pOutBuffer, uint& u pRowDest[i * 4 + 0] = pRowTemp[i * 3 + 2]; // B pRowDest[i * 4 + 1] = pRowTemp[i * 3 + 1]; // G pRowDest[i * 4 + 2] = pRowTemp[i * 3 + 0]; // R - pRowDest[i * 4 + 3] = 255; // A + pRowDest[i * 4 + 3] = 255; // A } } @@ -225,7 +227,8 @@ bool JpegEncode(uint uiWidth, uint uiHeight, uint uiQuality, const void* pData, if (uiWidth > JPEG_MAX_DIMENSION || uiHeight > JPEG_MAX_DIMENSION) { if (pOutError) - *pOutError = "JPEG dimensions too large: " + std::to_string(uiWidth) + "x" + std::to_string(uiHeight) + " (max " + std::to_string(JPEG_MAX_DIMENSION) + ")"; + *pOutError = + "JPEG dimensions too large: " + std::to_string(uiWidth) + "x" + std::to_string(uiHeight) + " (max " + std::to_string(JPEG_MAX_DIMENSION) + ")"; return false; } @@ -245,7 +248,8 @@ bool JpegEncode(uint uiWidth, uint uiHeight, uint uiQuality, const void* pData, if (uiDataSize != static_cast(uiExpectedSize)) { if (pOutError) - *pOutError = "Input buffer size mismatch: expected " + std::to_string(static_cast(uiExpectedSize)) + " bytes, got " + std::to_string(uiDataSize); + *pOutError = + "Input buffer size mismatch: expected " + std::to_string(static_cast(uiExpectedSize)) + " bytes, got " + std::to_string(uiDataSize); return false; } @@ -267,7 +271,7 @@ bool JpegEncode(uint uiWidth, uint uiHeight, uint uiQuality, const void* pData, jpeg_create_compress(&cinfo); unsigned char* membuffer_ptr = nullptr; - size_t memlen_val = 0; + size_t memlen_val = 0; jpeg_mem_dest(&cinfo, &membuffer_ptr, &memlen_val); cinfo.image_width = uiWidth; @@ -298,12 +302,12 @@ bool JpegEncode(uint uiWidth, uint uiHeight, uint uiQuality, const void* pData, char* pRowTemp = rowBuffer.GetData(); - bool bSuccess = false; + bool bSuccess = false; JSAMPROW row_pointer[1]; while (cinfo.next_scanline < cinfo.image_height) { uint64 uiRowOffset = static_cast(cinfo.next_scanline) * uiWidth * 4; - BYTE* pRowSrc = (BYTE*)pData + static_cast(uiRowOffset); + BYTE* pRowSrc = (BYTE*)pData + static_cast(uiRowOffset); // Convert BGRA to RGB for (uint i = 0; i < uiWidth; i++) diff --git a/Client/core/CFileFormatPng.cpp b/Client/core/CFileFormatPng.cpp index f77f55a899f..8cc0a9b428f 100644 --- a/Client/core/CFileFormatPng.cpp +++ b/Client/core/CFileFormatPng.cpp @@ -258,7 +258,6 @@ void my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) stream->WriteBytes(data, length); } - /////////////////////////////////////////////////////////////// // // PngEncode @@ -268,9 +267,9 @@ void my_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) /////////////////////////////////////////////////////////////// bool PngEncode(uint uiWidth, uint uiHeight, const void* pData, uint uiDataSize, CBuffer& outBuffer) { - BYTE** ppScreenData = NULL; + BYTE** ppScreenData = NULL; png_struct* png_ptr = NULL; - png_info* info_ptr = NULL; + png_info* info_ptr = NULL; try { @@ -302,7 +301,8 @@ bool PngEncode(uint uiWidth, uint uiHeight, const void* pData, uint uiDataSize, png_set_write_fn(png_ptr, &stream, my_png_write_data, NULL); png_set_filter(png_ptr, 0, PNG_FILTER_NONE); png_set_compression_level(png_ptr, 1); - png_set_IHDR(png_ptr, info_ptr, uiWidth, uiHeight, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + png_set_IHDR(png_ptr, info_ptr, uiWidth, uiHeight, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, + PNG_FILTER_TYPE_DEFAULT); png_set_rows(png_ptr, info_ptr, ppScreenData); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR /*| PNG_TRANSFORM_STRIP_ALPHA*/, NULL); png_write_end(png_ptr, info_ptr); @@ -316,7 +316,8 @@ bool PngEncode(uint uiWidth, uint uiHeight, const void* pData, uint uiDataSize, { for (uint y = 0; y < uiHeight; y++) { - if (ppScreenData[y]) delete[] ppScreenData[y]; + if (ppScreenData[y]) + delete[] ppScreenData[y]; } delete[] ppScreenData; } diff --git a/Client/core/CGUI.cpp b/Client/core/CGUI.cpp index 486afc1e59f..cdea4e32f9d 100644 --- a/Client/core/CGUI.cpp +++ b/Client/core/CGUI.cpp @@ -20,11 +20,11 @@ template <> CLocalGUI* CSingleton::m_pSingleton = NULL; #ifndef HIWORD - #define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) + #define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) #endif -#define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam)) +#define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam)) -const char* const DEFAULT_SKIN_NAME = "Default 2023"; // TODO: Change to whatever the default skin is if it changes +const char* const DEFAULT_SKIN_NAME = "Default 2023"; // TODO: Change to whatever the default skin is if it changes CLocalGUI::CLocalGUI() { @@ -352,18 +352,20 @@ void CLocalGUI::DoPulse() void CLocalGUI::Draw() { // Get the game interface - CGame* pGame = CCore::GetSingleton().GetGame(); - SystemState systemState = pGame->GetSystemState(); - CGUI* pGUI = CCore::GetSingleton().GetGUI(); + CGame* pGame = CCore::GetSingleton().GetGame(); + SystemState systemState = pGame->GetSystemState(); + CGUI* pGUI = CCore::GetSingleton().GetGUI(); // Update mainmenu stuff m_pMainMenu->Update(); // If we're ingame, make sure the chatbox is drawn - bool bChatVisible = (systemState == SystemState::GS_PLAYING_GAME && m_pMainMenu->GetIsIngame() && m_bChatboxVisible && !CCore::GetSingleton().IsOfflineMod()); + bool bChatVisible = + (systemState == SystemState::GS_PLAYING_GAME && m_pMainMenu->GetIsIngame() && m_bChatboxVisible && !CCore::GetSingleton().IsOfflineMod()); if (m_pChat->IsVisible() != bChatVisible) m_pChat->SetVisible(bChatVisible, !bChatVisible); - bool bDebugVisible = (systemState == SystemState::GS_PLAYING_GAME && m_pMainMenu->GetIsIngame() && m_pDebugViewVisible && !CCore::GetSingleton().IsOfflineMod()); + bool bDebugVisible = + (systemState == SystemState::GS_PLAYING_GAME && m_pMainMenu->GetIsIngame() && m_pDebugViewVisible && !CCore::GetSingleton().IsOfflineMod()); if (m_pDebugView->IsVisible() != bDebugVisible) m_pDebugView->SetVisible(bDebugVisible, true); @@ -785,7 +787,7 @@ bool CLocalGUI::InputGoesToGUI() shouldShowCursorForGUI = false; } } - + return (IsConsoleVisible() || IsMainMenuVisible() || IsChatBoxInputEnabled() || m_bForceCursorVisible || shouldShowCursorForGUI || !CCore::GetSingleton().IsFocused() || IsWebRequestGUIVisible()); } @@ -897,13 +899,13 @@ DWORD CLocalGUI::TranslateScanCodeToGUIKey(DWORD dwCharacter) case VK_DELETE: return DIK_DELETE; case 0x56: - return DIK_V; // V + return DIK_V; // V case 0x43: - return DIK_C; // C + return DIK_C; // C case 0x58: - return DIK_X; // X + return DIK_X; // X case 0x41: - return DIK_A; // A + return DIK_A; // A default: return 0; } diff --git a/Client/core/CGUI.h b/Client/core/CGUI.h index 47d00bbfc02..cdc07302647 100644 --- a/Client/core/CGUI.h +++ b/Client/core/CGUI.h @@ -14,10 +14,10 @@ class CLocalGUI; #pragma once #ifndef WM_MOUSEWHEEL -#define WM_MOUSEWHEEL 0x20A // Defined only when including Windows.h -> Not getting defined? (<=XP only?) + #define WM_MOUSEWHEEL 0x20A // Defined only when including Windows.h -> Not getting defined? (<=XP only?) #endif -#define DIRECT3D_VERSION 0x0900 +#define DIRECT3D_VERSION 0x0900 #include "d3d9.h" #include "d3dx9.h" @@ -117,7 +117,7 @@ class CLocalGUI : public CSingleton int m_uiActiveCompositionSize; POINT m_StoredMousePosition; - int m_LastSettingsRevision; // the revision number the last time we saw the skin change + int m_LastSettingsRevision; // the revision number the last time we saw the skin change SString m_LastSkinName; SString m_LastLocaleName; uint m_LocaleChangeCounter; diff --git a/Client/core/CGraphStats.cpp b/Client/core/CGraphStats.cpp index e56316e2ff6..510b0fb5ccd 100644 --- a/Client/core/CGraphStats.cpp +++ b/Client/core/CGraphStats.cpp @@ -20,7 +20,7 @@ namespace SColor color; std::string strName; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -115,7 +115,7 @@ void CGraphStats::AddTimingPoint(const char* szName) CGraphicsInterface* pGraphics = g_pCore->GetGraphics(); std::uint32_t viewportWidth = pGraphics->GetViewportWidth(); - std::uint32_t sizeX = viewportWidth / 4; // one quarter of screen width + std::uint32_t sizeX = viewportWidth / 4; // one quarter of screen width // Start of next frame? if (szName[0] == 0) diff --git a/Client/core/CGraphStats.h b/Client/core/CGraphStats.h index 6949ea5f94d..445e0d14f35 100644 --- a/Client/core/CGraphStats.h +++ b/Client/core/CGraphStats.h @@ -10,8 +10,7 @@ #pragma once -#define TIMING_GRAPH(name) \ - GetGraphStats()->AddTimingPoint( name ); +#define TIMING_GRAPH(name) GetGraphStats()->AddTimingPoint(name); // // CGraphStatsInterface for measuring and displaying a timing graph diff --git a/Client/core/CJoystickManager.cpp b/Client/core/CJoystickManager.cpp index e3cd675e247..0b09c863178 100644 --- a/Client/core/CJoystickManager.cpp +++ b/Client/core/CJoystickManager.cpp @@ -23,12 +23,11 @@ extern IDirectInput8* g_pDirectInput8; // Helper stuff // -#ifndef NUMELMS // in DShow.h - #define NUMELMS(aa) (sizeof(aa)/sizeof((aa)[0])) +#ifndef NUMELMS // in DShow.h + #define NUMELMS(aa) (sizeof(aa) / sizeof((aa)[0])) #endif -#define VALID_INDEX_FOR( array, index ) \ - ( index >= 0 && index < NUMELMS(array) ) +#define VALID_INDEX_FOR(array, index) (index >= 0 && index < NUMELMS(array)) SString GUIDToString(const GUID& g) { @@ -75,10 +74,10 @@ enum eStick struct SMappingLine { - eJoy SourceAxisIndex; // 0 - 7 - eDir SourceAxisDir; // 0 - 2 - eStick OutputAxisIndex; // 0/1 2/3 4 5 - eDir OutputAxisDir; // 0 - 1 + eJoy SourceAxisIndex; // 0 - 7 + eDir SourceAxisDir; // 0 - 2 + eStick OutputAxisIndex; // 0/1 2/3 4 5 + eDir OutputAxisDir; // 0 - 1 bool bEnabled; int MaxValue; }; @@ -116,7 +115,7 @@ struct SJoystickState BYTE rgbButtons[32]; /* 32 buttons */ BYTE rgbButtonsWas[32]; BYTE povButtonsWas[4]; - BYTE axisButtonsWas[14]; // Axis as buttons + BYTE axisButtonsWas[14]; // Axis as buttons }; /////////////////////////////////////////////////////////////// @@ -325,7 +324,7 @@ BOOL CJoystickManager::DoEnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdido range.diph.dwSize = sizeof(DIPROPRANGE); range.diph.dwHeaderSize = sizeof(DIPROPHEADER); range.diph.dwHow = DIPH_BYID; - range.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis + range.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis range.lMin = -1000; range.lMax = +1000; @@ -348,10 +347,10 @@ BOOL CJoystickManager::DoEnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdido dead.diph.dwHeaderSize = sizeof dead.diph; dead.diph.dwHow = DIPH_BYID; dead.diph.dwObj = pdidoi->dwType; - dead.dwData = 0; // No Deadzone + dead.dwData = 0; // No Deadzone sat = dead; - sat.dwData = 10000; // No Saturation + sat.dwData = 10000; // No Saturation m_DevInfo.pDevice->SetProperty(DIPROP_DEADZONE, &dead.diph); m_DevInfo.pDevice->SetProperty(DIPROP_SATURATION, &sat.diph); @@ -400,7 +399,7 @@ BOOL CJoystickManager::DoEnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdido WriteDebugEvent(" " + strStatus); #ifdef MTA_DEBUG -#if 0 + #if 0 if ( CCore::GetSingleton ().GetConsole () ) CCore::GetSingleton ().GetConsole ()->Printf( "%p dwHow:%d dwObj:%d guid:%x index:%d lMin:%d lMax:%d" @@ -413,7 +412,7 @@ BOOL CJoystickManager::DoEnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdido ,range.lMax ); -#endif + #endif #endif } @@ -481,7 +480,7 @@ void CJoystickManager::InitDirectInput() } PreferredJoyCfg.dwSize = sizeof(PreferredJoyCfg); - if (SUCCEEDED(pJoyConfig->GetConfig(0, &PreferredJoyCfg, DIJC_GUIDINSTANCE))) // This function is expected to fail if no Joystick is attached + if (SUCCEEDED(pJoyConfig->GetConfig(0, &PreferredJoyCfg, DIJC_GUIDINSTANCE))) // This function is expected to fail if no Joystick is attached m_bPreferredJoyCfgValid = true; SAFE_RELEASE(pJoyConfig); @@ -693,7 +692,7 @@ void CJoystickManager::ReadCurrentState() for (int i = 0; i < 32; i++) m_JoystickState.rgbButtons[i] = 0; - DIJOYSTATE2 js; // DInput joystick state + DIJOYSTATE2 js; // DInput joystick state if (ReadInputSubsystem(js)) { @@ -763,7 +762,7 @@ void CJoystickManager::ReadCurrentState() range.diph.dwSize = sizeof(DIPROPRANGE); range.diph.dwHeaderSize = sizeof(DIPROPHEADER); range.diph.dwHow = DIPH_BYID; - range.diph.dwObj = m_DevInfo.axis[a].dwType; // Specify the enumerated axis + range.diph.dwObj = m_DevInfo.axis[a].dwType; // Specify the enumerated axis range.lMin = -2001; range.lMax = +2001; @@ -813,7 +812,7 @@ void CJoystickManager::ReadCurrentState() { CGraphicsInterface* pGraphics = CCore::GetSingleton().GetGraphics(); int x = 20; - int y = 20; // pGraphics->GetViewportHeight() / 2; + int y = 20; // pGraphics->GetViewportHeight() / 2; pGraphics->DrawRectQueued(x, y, 350, 150, 0xaf000000, true); pGraphics->DrawStringQueued(x + 10, y + 10, 0, 0, 0xFFFFFFFF, strStatus, 1, 1, DT_NOCLIP, NULL, true); } @@ -1081,7 +1080,7 @@ void CJoystickManager::ApplyAxes(CControllerState& cs, bool bInVehicle) // Debug output #ifdef MTA_DEBUG -#if 0 + #if 0 SString strBuffer = SString::Printf ( "LeftShoulder1: %u\n" "LeftShoulder2: %u\n" @@ -1153,7 +1152,7 @@ void CJoystickManager::ApplyAxes(CControllerState& cs, bool bInVehicle) CCore::GetSingleton ().GetGraphics ()->DrawString ( 20, 550, 0xFFFFFFFF, 1, strBuffer ); -#endif + #endif #endif } @@ -1195,7 +1194,7 @@ void CJoystickManager::SetDeadZone(int iDeadZone) { m_SettingsRevision++; if (iDeadZone != m_DevInfo.iDeadZone) - m_bAutoDeadZoneEnabled = false; // Disable auto dead zone on change (user edit) + m_bAutoDeadZoneEnabled = false; // Disable auto dead zone on change (user edit) m_DevInfo.iDeadZone = Clamp(0, iDeadZone, 49); } diff --git a/Client/core/CJoystickManager.h b/Client/core/CJoystickManager.h index ccd46e872f3..f8a59db1753 100644 --- a/Client/core/CJoystickManager.h +++ b/Client/core/CJoystickManager.h @@ -48,11 +48,11 @@ CJoystickManagerInterface* NewJoystickManager(); CJoystickManagerInterface* GetJoystickManager(); // Custom VK_ codes for the joystick buttons - Starts at VK_JOY(1) -#define VK_JOY(x) ( 0x100+(x) ) +#define VK_JOY(x) (0x100 + (x)) // Custom VK_ codes for the joystick pov hat - Starts at VK_POV(1) -#define VK_POV(x) ( 0x150+(x) ) +#define VK_POV(x) (0x150 + (x)) // Custom VK_ codes for the joystick axes - Starts at VK_AXIS(1) -#define VK_AXIS(x) ( 0x160+(x) ) +#define VK_AXIS(x) (0x160 + (x)) // Unique numbers for the joystick buttons - Used to identify buttons in the GTA settings -#define GTA_KEY_JOY(x) ( 500+(x) ) +#define GTA_KEY_JOY(x) (500 + (x)) diff --git a/Client/core/CKeyBinds.cpp b/Client/core/CKeyBinds.cpp index bbf0a5dc3e7..3664d326de2 100644 --- a/Client/core/CKeyBinds.cpp +++ b/Client/core/CKeyBinds.cpp @@ -29,7 +29,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON // TODO: Consider using VK_(L|R)(SHIFT|CONTROL|MENU) {"lshift", VK_SHIFT, GTA_KEY_LSHIFT, DATA_NOT_EXTENDED, 0}, - {"rshift", VK_SHIFT, GTA_KEY_RSHIFT, DATA_EXTENDED, 0}, // 10 + {"rshift", VK_SHIFT, GTA_KEY_RSHIFT, DATA_EXTENDED, 0}, // 10 {"lctrl", VK_CONTROL, GTA_KEY_LCONTROL, DATA_NOT_EXTENDED, 0}, {"rctrl", VK_CONTROL, GTA_KEY_RCONTROL, DATA_EXTENDED, 0}, {"lalt", VK_MENU, GTA_KEY_LMENU, DATA_NOT_EXTENDED, 0, true}, @@ -40,7 +40,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"enter", VK_RETURN, GTA_KEY_RETURN, DATA_NOT_EXTENDED, 0}, {"space", VK_SPACE, GTA_KEY_SPACE, DATA_NONE, 0}, {"pgup", VK_PRIOR, GTA_KEY_PGUP, DATA_NUMPAD, 74, true}, - {"pgdn", VK_NEXT, GTA_KEY_PGDN, DATA_NUMPAD, 68, true}, // 20 + {"pgdn", VK_NEXT, GTA_KEY_PGDN, DATA_NUMPAD, 68, true}, // 20 {"end", VK_END, GTA_KEY_END, DATA_NUMPAD, 66}, {"home", VK_HOME, GTA_KEY_HOME, DATA_NUMPAD, 72}, {"arrow_l", VK_LEFT, GTA_KEY_LEFT, DATA_NUMPAD, 69}, @@ -50,7 +50,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"insert", VK_INSERT, GTA_KEY_INSERT, DATA_NUMPAD, 65, true}, {"delete", VK_DELETE, GTA_KEY_DELETE, DATA_NUMPAD, 79}, {"0", 0x30, GTA_KEY_0, DATA_NONE, 0}, - {"1", 0x31, GTA_KEY_1, DATA_NONE, 0}, // 30 + {"1", 0x31, GTA_KEY_1, DATA_NONE, 0}, // 30 {"2", 0x32, GTA_KEY_2, DATA_NONE, 0}, {"3", 0x33, GTA_KEY_3, DATA_NONE, 0}, {"4", 0x34, GTA_KEY_4, DATA_NONE, 0}, @@ -60,7 +60,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"8", 0x38, GTA_KEY_8, DATA_NONE, 0}, {"9", 0x39, GTA_KEY_9, DATA_NONE, 0}, {"a", 0x41, GTA_KEY_A, DATA_NONE, 0}, - {"b", 0x42, GTA_KEY_B, DATA_NONE, 0}, // 40 + {"b", 0x42, GTA_KEY_B, DATA_NONE, 0}, // 40 {"c", 0x43, GTA_KEY_C, DATA_NONE, 0}, {"d", 0x44, GTA_KEY_D, DATA_NONE, 0}, {"e", 0x45, GTA_KEY_E, DATA_NONE, 0}, @@ -70,7 +70,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"i", 0x49, GTA_KEY_I, DATA_NONE, 0}, {"j", 0x4A, GTA_KEY_J, DATA_NONE, 0}, {"k", 0x4B, GTA_KEY_K, DATA_NONE, 0}, - {"l", 0x4C, GTA_KEY_L, DATA_NONE, 0}, // 50 + {"l", 0x4C, GTA_KEY_L, DATA_NONE, 0}, // 50 {"m", 0x4D, GTA_KEY_M, DATA_NONE, 0}, {"n", 0x4E, GTA_KEY_N, DATA_NONE, 0}, {"o", 0x4F, GTA_KEY_O, DATA_NONE, 0}, @@ -80,7 +80,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"s", 0x53, GTA_KEY_S, DATA_NONE, 0}, {"t", 0x54, GTA_KEY_T, DATA_NONE, 0}, {"u", 0x55, GTA_KEY_U, DATA_NONE, 0}, - {"v", 0x56, GTA_KEY_V, DATA_NONE, 0}, // 60 + {"v", 0x56, GTA_KEY_V, DATA_NONE, 0}, // 60 {"w", 0x57, GTA_KEY_W, DATA_NONE, 0}, {"x", 0x58, GTA_KEY_X, DATA_NONE, 0}, {"y", 0x59, GTA_KEY_Y, DATA_NONE, 0}, @@ -90,7 +90,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"num_2", VK_NUMPAD2, GTA_KEY_NUMPAD2, DATA_NONE, 0}, {"num_3", VK_NUMPAD3, GTA_KEY_NUMPAD3, DATA_NONE, 0}, {"num_4", VK_NUMPAD4, GTA_KEY_NUMPAD4, DATA_NONE, 0}, - {"num_5", VK_NUMPAD5, GTA_KEY_NUMPAD5, DATA_NONE, 0}, // 70 + {"num_5", VK_NUMPAD5, GTA_KEY_NUMPAD5, DATA_NONE, 0}, // 70 {"num_6", VK_NUMPAD6, GTA_KEY_NUMPAD6, DATA_NONE, 0}, {"num_7", VK_NUMPAD7, GTA_KEY_NUMPAD7, DATA_NONE, 0}, {"num_8", VK_NUMPAD8, GTA_KEY_NUMPAD8, DATA_NONE, 0}, @@ -100,7 +100,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {"num_sep", VK_SEPARATOR, NO_KEY_DEFINED, DATA_NONE, 0}, {"num_sub", VK_SUBTRACT, GTA_KEY_SUBTRACT, DATA_NONE, 0}, {"num_dec", VK_DECIMAL, GTA_KEY_DECIMAL, DATA_NONE, 0}, - {"num_div", VK_DIVIDE, GTA_KEY_DIVIDE, DATA_NONE, 0}, // 80 + {"num_div", VK_DIVIDE, GTA_KEY_DIVIDE, DATA_NONE, 0}, // 80 {"F1", VK_F1, GTA_KEY_F1, DATA_NONE, 0, true}, {"F2", VK_F2, GTA_KEY_F2, DATA_NONE, 0, true}, {"F3", VK_F3, GTA_KEY_F3, DATA_NONE, 0, true}, @@ -111,7 +111,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON // {"F8", VK_F8, GTA_KEY_F8, DATA_NONE, 0, true}, * Used for console {"F9", VK_F9, GTA_KEY_F9, DATA_NONE, 0, true}, {"F10", VK_F10, GTA_KEY_F10, DATA_NONE, 0, true}, - {"F11", VK_F11, GTA_KEY_F11, DATA_NONE, 0, true}, // 90 + {"F11", VK_F11, GTA_KEY_F11, DATA_NONE, 0, true}, // 90 {"F12", VK_F12, GTA_KEY_F12, DATA_NONE, 0, true}, {"scroll", VK_SCROLL, GTA_KEY_SCROLL, DATA_NONE, 0, true}, {";", 0xBA, GTA_KEY_SEMICOLON, DATA_NONE, 0}, @@ -121,7 +121,7 @@ const SBindableKey g_bkKeys[] = {{"mouse1", VK_LBUTTON, GTA_KEY_LMOUSE, DATA_NON {".", 0xBE, GTA_KEY_PERIOD, DATA_NONE, 0}, {"/", 0xBF, GTA_KEY_SLASH, DATA_NONE, 0}, {"'", 0xC0, GTA_KEY_APOSTROPHE, DATA_NONE, 0}, - {"[", 0xDB, GTA_KEY_LBRACKET, DATA_NONE, 0}, // 100 + {"[", 0xDB, GTA_KEY_LBRACKET, DATA_NONE, 0}, // 100 {"\\", 0xDC, GTA_KEY_BACKSLASH, DATA_NONE, 0}, {"]", 0xDD, GTA_KEY_RBRACKET, DATA_NONE, 0}, {"#", 0xDE, GTA_KEY_HASH, DATA_NONE, 0}, @@ -193,7 +193,7 @@ SBindableGTAControl g_bcControls[] = {{"fire", FIRE, CONTROL_FOOT, false, true, {"zoom_in", ZOOM_IN, CONTROL_FOOT, false, true, _td("Zoom in")}, {"zoom_out", ZOOM_OUT, CONTROL_FOOT, false, true, _td("Zoom out")}, {"enter_exit", ENTER_EXIT, CONTROL_BOTH, false, true, _td("Enter/Exit")}, - {"change_camera", CHANGE_CAMERA, CONTROL_BOTH, false, true, _td("Change camera")}, // 10 + {"change_camera", CHANGE_CAMERA, CONTROL_BOTH, false, true, _td("Change camera")}, // 10 {"jump", JUMP, CONTROL_FOOT, false, true, _td("Jump")}, {"sprint", SPRINT, CONTROL_FOOT, false, true, _td("Sprint")}, {"look_behind", LOOK_BEHIND, CONTROL_FOOT, false, true, _td("Look behind")}, @@ -203,7 +203,7 @@ SBindableGTAControl g_bcControls[] = {{"fire", FIRE, CONTROL_FOOT, false, true, {"vehicle_fire", VEHICLE_FIRE, CONTROL_VEHICLE, false, true, _td("Vehicle fire")}, {"vehicle_secondary_fire", VEHICLE_SECONDARY_FIRE, CONTROL_VEHICLE, false, true, _td("Vehicle secondary fire")}, {"vehicle_left", VEHICLE_LEFT, CONTROL_VEHICLE, false, true, _td("Vehicle left")}, - {"vehicle_right", VEHICLE_RIGHT, CONTROL_VEHICLE, false, true, _td("Vehicle right")}, // 20 + {"vehicle_right", VEHICLE_RIGHT, CONTROL_VEHICLE, false, true, _td("Vehicle right")}, // 20 {"steer_forward", STEER_FORWARDS_DOWN, CONTROL_VEHICLE, false, true, _td("Steer forwards/down")}, {"steer_back", STEER_BACK_UP, CONTROL_VEHICLE, false, true, _td("Steer backwards/up")}, {"accelerate", ACCELERATE, CONTROL_VEHICLE, false, true, _td("Accelerate")}, @@ -213,7 +213,7 @@ SBindableGTAControl g_bcControls[] = {{"fire", FIRE, CONTROL_FOOT, false, true, {"radio_user_track_skip", RADIO_USER_TRACK_SKIP, CONTROL_VEHICLE, false, true, _td("Radio user track skip")}, {"horn", HORN, CONTROL_VEHICLE, false, true, _td("Horn")}, {"sub_mission", SUB_MISSION, CONTROL_VEHICLE, false, true, _td("Sub-mission")}, - {"handbrake", HANDBRAKE, CONTROL_VEHICLE, false, true, _td("Handbrake")}, // 30 + {"handbrake", HANDBRAKE, CONTROL_VEHICLE, false, true, _td("Handbrake")}, // 30 {"vehicle_look_left", VEHICLE_LOOK_LEFT, CONTROL_VEHICLE, false, true, _td("Vehicle look left")}, {"vehicle_look_right", VEHICLE_LOOK_RIGHT, CONTROL_VEHICLE, false, true, _td("Vehicle look right")}, {"vehicle_look_behind", VEHICLE_LOOK_BEHIND, CONTROL_VEHICLE, false, true, _td("Vehicle look behind")}, @@ -223,7 +223,7 @@ SBindableGTAControl g_bcControls[] = {{"fire", FIRE, CONTROL_FOOT, false, true, {"special_control_down", SPECIAL_CONTROL_DOWN, CONTROL_VEHICLE, false, true, _td("Special control down")}, {"special_control_up", SPECIAL_CONTROL_UP, CONTROL_VEHICLE, false, true, _td("Special control up")}, {"aim_weapon", AIM_WEAPON, CONTROL_FOOT, false, true, _td("Aim weapon")}, - {"conversation_yes", CONVERSATION_YES, CONTROL_FOOT, false, true, _td("Conversation yes")}, // 40 + {"conversation_yes", CONVERSATION_YES, CONTROL_FOOT, false, true, _td("Conversation yes")}, // 40 {"conversation_no", CONVERSATION_NO, CONTROL_FOOT, false, true, _td("Conversation no")}, {"group_control_forwards", GROUP_CONTROL_FORWARDS, CONTROL_FOOT, false, true, _td("Group control forwards")}, {"group_control_back", GROUP_CONTROL_BACK, CONTROL_FOOT, false, true, _td("Group control backwards")}, @@ -432,16 +432,19 @@ bool CKeyBinds::ProcessKeyStroke(const SBindableKey* pKey, bool bState) bool wasBindFound = false; std::list processedCommandBinds; - auto wasCommandBindProcessed = [&processedCommandBinds](CCommandBind* commandBind) { - auto iter = std::find_if(processedCommandBinds.begin(), processedCommandBinds.end(), [&](CCommandBind* processedCommandBind) { - if (processedCommandBind->triggerState != commandBind->triggerState) - return false; + auto wasCommandBindProcessed = [&processedCommandBinds](CCommandBind* commandBind) + { + auto iter = std::find_if(processedCommandBinds.begin(), processedCommandBinds.end(), + [&](CCommandBind* processedCommandBind) + { + if (processedCommandBind->triggerState != commandBind->triggerState) + return false; - if (processedCommandBind->command != commandBind->command) - return false; + if (processedCommandBind->command != commandBind->command) + return false; - return commandBind->arguments.empty() || processedCommandBind->arguments == commandBind->arguments; - }); + return commandBind->arguments.empty() || processedCommandBind->arguments == commandBind->arguments; + }); return iter != processedCommandBinds.end(); }; @@ -506,7 +509,7 @@ bool CKeyBinds::ProcessKeyStroke(const SBindableKey* pKey, bool bState) processedCommandBinds.push_back(commandBind); } } - else // bindWithState->type == KeyBindType::FUNCTION + else // bindWithState->type == KeyBindType::FUNCTION { if (bAllowed) { @@ -565,17 +568,18 @@ void CKeyBinds::RemoveDeletedBinds() void CKeyBinds::ClearCommandsAndControls() { - const auto predicate = [](const KeyBindPtr& bind) { + const auto predicate = [](const KeyBindPtr& bind) + { if (bind->isBeingDeleted) return false; - + if (bind->type == KeyBindType::COMMAND) { auto commandBind = static_cast(bind.get()); // Only remove resource bindings, preserve user bindings return commandBind->context == BindingContext::RESOURCE; } - + // Remove all control bindings (GTA_CONTROL) return bind->type == KeyBindType::GTA_CONTROL; }; @@ -667,7 +671,7 @@ bool CKeyBinds::AddCommand(const char* szKey, const char* szCommand, const char* if (bScriptCreated) bind->originalScriptKey = szKey; else if (szOriginalScriptKey) - bind->originalScriptKey = szOriginalScriptKey; // Will wait for script to addcommand before doing replace + bind->originalScriptKey = szOriginalScriptKey; // Will wait for script to addcommand before doing replace } else { @@ -705,7 +709,8 @@ bool CKeyBinds::RemoveCommand(const char* szKey, const char* szCommand, bool bCh std::string_view command{szCommand}; - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::COMMAND) return false; @@ -728,7 +733,8 @@ bool CKeyBinds::RemoveAllCommands(const char* szKey, bool bCheckState, bool bSta if (!szKey) return false; - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::COMMAND) return false; @@ -967,7 +973,8 @@ void CKeyBinds::UserChangeCommandBoundKey(CCommandBind* pBind, const SBindableKe // void CKeyBinds::SortCommandBinds() { - auto compare = [](const KeyBindPtr& lhs, const KeyBindPtr& rhs) { + auto compare = [](const KeyBindPtr& lhs, const KeyBindPtr& rhs) + { // Group command binds last if (lhs->type != KeyBindType::COMMAND && rhs->type == KeyBindType::COMMAND) return true; @@ -1057,7 +1064,8 @@ bool CKeyBinds::RemoveGTAControl(const char* szKey, const char* szControl) if (!szKey || !szControl) return false; - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::GTA_CONTROL) return false; @@ -1073,7 +1081,8 @@ bool CKeyBinds::RemoveAllGTAControls(const char* szKey) if (!szKey) return false; - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::GTA_CONTROL) return false; @@ -1368,7 +1377,8 @@ bool CKeyBinds::RemoveFunction(const char* szKey, KeyFunctionBindHandler Handler bool CKeyBinds::RemoveFunction(const SBindableKey* pKey, KeyFunctionBindHandler Handler, bool bCheckState, bool bState) { - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::FUNCTION) return false; @@ -1385,7 +1395,8 @@ bool CKeyBinds::RemoveFunction(const SBindableKey* pKey, KeyFunctionBindHandler bool CKeyBinds::RemoveAllFunctions(KeyFunctionBindHandler Handler) { - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::FUNCTION) return false; @@ -1472,7 +1483,8 @@ bool CKeyBinds::RemoveControlFunction(const char* szControl, ControlFunctionBind bool CKeyBinds::RemoveControlFunction(SBindableGTAControl* pControl, ControlFunctionBindHandler Handler, bool bCheckState, bool bState) { - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::CONTROL_FUNCTION) return false; @@ -1489,7 +1501,8 @@ bool CKeyBinds::RemoveControlFunction(SBindableGTAControl* pControl, ControlFunc bool CKeyBinds::RemoveAllControlFunctions(ControlFunctionBindHandler Handler) { - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::CONTROL_FUNCTION) return false; @@ -1910,7 +1923,8 @@ void CKeyBinds::DoPostFramePulse() { SystemState systemState = CCore::GetSingleton().GetGame()->GetSystemState(); - if (m_bWaitingToLoadDefaults && (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_PLAYING_GAME)) // Are GTA controls actually initialized? + if (m_bWaitingToLoadDefaults && + (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_PLAYING_GAME)) // Are GTA controls actually initialized? { LoadDefaultBinds(); m_bWaitingToLoadDefaults = false; @@ -1962,16 +1976,16 @@ void CKeyBinds::DoPostFramePulse() { if (!bInVehicle) { - cs.ButtonCircle = (g_bcControls[0].bState && !bHasDetonator) ? 255 : 0; // Fire + cs.ButtonCircle = (g_bcControls[0].bState && !bHasDetonator) ? 255 : 0; // Fire if (bAimingWeapon) { - cs.RightShoulder2 = g_bcControls[8].bState ? 255 : 0; // Zoom Out - cs.LeftShoulder2 = g_bcControls[7].bState ? 255 : 0; // Zoom In + cs.RightShoulder2 = g_bcControls[8].bState ? 255 : 0; // Zoom Out + cs.LeftShoulder2 = g_bcControls[7].bState ? 255 : 0; // Zoom In } else { - cs.RightShoulder2 = g_bcControls[1].bState ? 255 : 0; // Next Weapon - cs.LeftShoulder2 = g_bcControls[2].bState ? 255 : 0; // Previous Weapon + cs.RightShoulder2 = g_bcControls[1].bState ? 255 : 0; // Next Weapon + cs.LeftShoulder2 = g_bcControls[2].bState ? 255 : 0; // Previous Weapon } if (!ControlForwardsBackWards(cs)) @@ -1986,39 +2000,39 @@ void CKeyBinds::DoPostFramePulse() // * Enter Exit // * Change View - cs.ButtonSquare = (!bEnteringVehicle && !bAimingWeapon && g_bcControls[11].bState) ? 255 : 0; // Jump - cs.ButtonCross = (g_bcControls[12].bState) ? 255 : 0; // Sprint - cs.ShockButtonR = (g_bcControls[13].bState) ? 255 : 0; // Look Behind - cs.ShockButtonL = (g_bcControls[14].bState) ? 255 : 0; // Crouch - cs.LeftShoulder1 = (g_bcControls[15].bState) ? 255 : 0; // Action - cs.m_bPedWalk = (g_bcControls[16].bState) ? 255 : 0; // Walk + cs.ButtonSquare = (!bEnteringVehicle && !bAimingWeapon && g_bcControls[11].bState) ? 255 : 0; // Jump + cs.ButtonCross = (g_bcControls[12].bState) ? 255 : 0; // Sprint + cs.ShockButtonR = (g_bcControls[13].bState) ? 255 : 0; // Look Behind + cs.ShockButtonL = (g_bcControls[14].bState) ? 255 : 0; // Crouch + cs.LeftShoulder1 = (g_bcControls[15].bState) ? 255 : 0; // Action + cs.m_bPedWalk = (g_bcControls[16].bState) ? 255 : 0; // Walk // * Vehicle Keys - cs.RightShoulder1 = (g_bcControls[39].bState) ? 255 : 0; // Aim Weapon - cs.DPadRight = (g_bcControls[40].bState) ? 255 : 0; // Conversation Yes - cs.DPadLeft = (g_bcControls[41].bState) ? 255 : 0; // Conversation No - cs.DPadUp = (g_bcControls[42].bState) ? 255 : 0; // Group Control Forwards - cs.DPadDown = (g_bcControls[43].bState) ? 255 : 0; // Group Control Backwards + cs.RightShoulder1 = (g_bcControls[39].bState) ? 255 : 0; // Aim Weapon + cs.DPadRight = (g_bcControls[40].bState) ? 255 : 0; // Conversation Yes + cs.DPadLeft = (g_bcControls[41].bState) ? 255 : 0; // Conversation No + cs.DPadUp = (g_bcControls[42].bState) ? 255 : 0; // Group Control Forwards + cs.DPadDown = (g_bcControls[43].bState) ? 255 : 0; // Group Control Backwards } else { - cs.ButtonCircle = (g_bcControls[17].bState) ? 255 : 0; // Fire - cs.LeftShoulder1 = (g_bcControls[18].bState) ? 255 : 0; // Secondary Fire + cs.ButtonCircle = (g_bcControls[17].bState) ? 255 : 0; // Fire + cs.LeftShoulder1 = (g_bcControls[18].bState) ? 255 : 0; // Secondary Fire cs.LeftStickX = ((g_bcControls[19].bState && g_bcControls[20].bState) || (!g_bcControls[19].bState && !g_bcControls[20].bState)) ? 0 : (g_bcControls[19].bState) ? -128 : 128; cs.LeftStickY = ((g_bcControls[21].bState && g_bcControls[22].bState) || (!g_bcControls[21].bState && !g_bcControls[22].bState)) ? 0 : (g_bcControls[21].bState) ? -128 : 128; - cs.ButtonCross = (g_bcControls[23].bState) ? 255 : 0; // Accelerate - cs.ButtonSquare = (g_bcControls[24].bState) ? 255 : 0; // Reverse - cs.DPadUp = (g_bcControls[25].bState) ? 255 : 0; // Radio Next - cs.DPadDown = (g_bcControls[26].bState) ? 255 : 0; // Radio Previous - cs.m_bRadioTrackSkip = (g_bcControls[27].bState) ? 255 : 0; // Radio Skip - cs.ShockButtonL = (g_bcControls[28].bState) ? 255 : 0; // Horn - cs.ShockButtonR = (g_bcControls[29].bState) ? 255 : 0; // Sub Mission - cs.RightShoulder1 = (g_bcControls[30].bState) ? 255 : 0; // Handbrake - cs.LeftShoulder2 = (g_bcControls[31].bState || g_bcControls[33].bState) ? 255 : 0; // Look Left - cs.RightShoulder2 = (g_bcControls[32].bState || g_bcControls[33].bState) ? 255 : 0; // Look Right + cs.ButtonCross = (g_bcControls[23].bState) ? 255 : 0; // Accelerate + cs.ButtonSquare = (g_bcControls[24].bState) ? 255 : 0; // Reverse + cs.DPadUp = (g_bcControls[25].bState) ? 255 : 0; // Radio Next + cs.DPadDown = (g_bcControls[26].bState) ? 255 : 0; // Radio Previous + cs.m_bRadioTrackSkip = (g_bcControls[27].bState) ? 255 : 0; // Radio Skip + cs.ShockButtonL = (g_bcControls[28].bState) ? 255 : 0; // Horn + cs.ShockButtonR = (g_bcControls[29].bState) ? 255 : 0; // Sub Mission + cs.RightShoulder1 = (g_bcControls[30].bState) ? 255 : 0; // Handbrake + cs.LeftShoulder2 = (g_bcControls[31].bState || g_bcControls[33].bState) ? 255 : 0; // Look Left + cs.RightShoulder2 = (g_bcControls[32].bState || g_bcControls[33].bState) ? 255 : 0; // Look Right // * Look Behind - uses both keys above simultaneously // Mouse Look cs.RightStickX = ((g_bcControls[35].bState && g_bcControls[36].bState) || (!g_bcControls[35].bState && !g_bcControls[36].bState)) ? 0 @@ -2028,8 +2042,8 @@ void CKeyBinds::DoPostFramePulse() : (g_bcControls[37].bState) ? 128 : -128; } - cs.ButtonTriangle = (g_bcControls[9].bState) ? 255 : 0; // Enter Exit - cs.Select = (g_bcControls[10].bState) ? 255 : 0; // Change View + cs.ButtonTriangle = (g_bcControls[9].bState) ? 255 : 0; // Enter Exit + cs.Select = (g_bcControls[10].bState) ? 255 : 0; // Change View bool disableGameplayControls = m_pCore->IsCursorForcedVisible() && m_pCore->IsCursorControlsToggled(); @@ -2195,7 +2209,7 @@ bool CKeyBinds::LoadFromXML(CXMLNode* pMainNode) SystemState systemState = CCore::GetSingleton().GetGame()->GetSystemState(); if (bLoadDefaults) { - if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_PLAYING_GAME) // Are GTA controls actually initialized? + if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_PLAYING_GAME) // Are GTA controls actually initialized? LoadDefaultBinds(); else m_bWaitingToLoadDefaults = true; @@ -2229,7 +2243,8 @@ bool CKeyBinds::SaveToXML(CXMLNode* pMainNode) CXMLAttributes& attributes = bindNode->GetAttributes(); - auto createAttribute = [&attributes](const char* key, const char* value) { + auto createAttribute = [&attributes](const char* key, const char* value) + { if (value && value[0]) { CXMLAttribute* attribute = attributes.Create(key); @@ -2259,7 +2274,7 @@ bool CKeyBinds::SaveToXML(CXMLNode* pMainNode) createAttribute("default", commandBind->originalScriptKey.c_str()); } } - else // bind->type == KeyBindType::GTA_CONTROL + else // bind->type == KeyBindType::GTA_CONTROL { auto controlBind = static_cast(bind.get()); createAttribute("key", controlBind->boundKey->szKey); @@ -2508,7 +2523,8 @@ void CKeyBinds::PrintBindsCommand(const char* szCmdLine) CConsoleInterface* console = m_pCore->GetConsole(); - auto print = [console](const KeyBindPtr& bind) { + auto print = [console](const KeyBindPtr& bind) + { switch (bind->type) { case KeyBindType::COMMAND: @@ -2674,7 +2690,8 @@ bool CKeyBinds::TriggerKeyStrokeHandler(const SString& strKey, bool bState, bool return true; } -bool CKeyBinds::CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState, bool state, const char* arguments, const char* resource) +bool CKeyBinds::CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState, bool state, const char* arguments, + const char* resource) { if (!key || !command) return false; @@ -2685,7 +2702,7 @@ bool CKeyBinds::CommandExistsInContext(const char* key, const char* command, Bin continue; auto commandBind = static_cast(bind.get()); - + if (commandBind->context != context) continue; @@ -2710,17 +2727,19 @@ bool CKeyBinds::CommandExistsInContext(const char* key, const char* command, Bin return false; } -bool CKeyBinds::RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState, bool state, const char* arguments, const char* resource) +bool CKeyBinds::RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState, bool state, const char* arguments, + const char* resource) { if (!key || !command) return false; - const auto predicate = [&](const KeyBindPtr& bind) { + const auto predicate = [&](const KeyBindPtr& bind) + { if (bind->isBeingDeleted || bind->type != KeyBindType::COMMAND) return false; auto commandBind = static_cast(bind.get()); - + if (commandBind->context != context) return false; @@ -2804,7 +2823,7 @@ bool CKeyBinds::HasBindingInContext(const char* key, BindingContext context, boo continue; auto commandBind = static_cast(bind.get()); - + if (commandBind->context != context) continue; diff --git a/Client/core/CKeyBinds.h b/Client/core/CKeyBinds.h index fb61387422d..ecde1221b79 100644 --- a/Client/core/CKeyBinds.h +++ b/Client/core/CKeyBinds.h @@ -76,8 +76,10 @@ class CKeyBinds final : public CKeyBindsInterface void SortCommandBinds(); // Context-aware binding methods - bool CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, const char* arguments = NULL, const char* resource = NULL); - bool RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, const char* arguments = NULL, const char* resource = NULL); + bool CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, + const char* arguments = NULL, const char* resource = NULL); + bool RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, + const char* arguments = NULL, const char* resource = NULL); bool HasAnyBindingForKey(const char* key, bool checkState = false, bool state = true); bool HasBindingInContext(const char* key, BindingContext context, bool checkState = false, bool state = true); diff --git a/Client/core/CLanguage.h b/Client/core/CLanguage.h index fcbd98e5c51..01ec4586d8c 100644 --- a/Client/core/CLanguage.h +++ b/Client/core/CLanguage.h @@ -31,6 +31,6 @@ class CLanguage private: Dictionary m_Dict; - SString m_strCode; // Language code - SString m_strName; // Human readable name + SString m_strCode; // Language code + SString m_strName; // Human readable name }; diff --git a/Client/core/CLanguageSelector.cpp b/Client/core/CLanguageSelector.cpp index d3e80fe2f86..6b4e47dca92 100644 --- a/Client/core/CLanguageSelector.cpp +++ b/Client/core/CLanguageSelector.cpp @@ -11,28 +11,28 @@ #include "StdInc.h" #include "CLanguageSelector.h" -#define LANGUAGE_ICON_SIZE_X 20 -#define LANGUAGE_ICON_SIZE_Y 24 -#define LANGUAGE_ICON_LABEL_GAP_X 10 // Gap between language icon and label +#define LANGUAGE_ICON_SIZE_X 20 +#define LANGUAGE_ICON_SIZE_Y 24 +#define LANGUAGE_ICON_LABEL_GAP_X 10 // Gap between language icon and label -#define LABEL_SIZE_X 165 -#define LABEL_SIZE_Y 16 +#define LABEL_SIZE_X 165 +#define LABEL_SIZE_Y 16 #define LANGUAGE_ICON_LABEL_OFFSET_Y ((LANGUAGE_ICON_SIZE_Y - LABEL_SIZE_Y) / 2) // Language icon and label combo -#define ITEM_SIZE_X 165 -#define ITEM_SIZE_Y 24 +#define ITEM_SIZE_X 165 +#define ITEM_SIZE_Y 24 // Current language button -#define BUTTON_MARGIN_X 20 -#define BUTTON_MARGIN_Y 5 +#define BUTTON_MARGIN_X 20 +#define BUTTON_MARGIN_Y 5 // All languages list -#define LIST_MARGIN_X 20 -#define LIST_MARGIN_Y 18 -#define LIST_ITEM_SPACING_X 10 -#define LIST_ITEM_SPACING_Y 1 +#define LIST_MARGIN_X 20 +#define LIST_MARGIN_Y 18 +#define LIST_ITEM_SPACING_X 10 +#define LIST_ITEM_SPACING_Y 1 /////////////////////////////////////////////////////////////// // @@ -57,7 +57,8 @@ CLanguageSelector::~CLanguageSelector() { CGUI* pGUI = g_pCore ? g_pCore->GetGUI() : nullptr; - auto destroyElement = [pGUI](auto*& element) { + auto destroyElement = [pGUI](auto*& element) + { if (!element) return; @@ -125,17 +126,17 @@ void CLanguageSelector::CreateGUI(CGUIElement* pMainMenuCanvas) pLabel->SetZOrderingEnabled(false); pLabel->SetText(g_pLocalization->GetLanguageNativeName()); - m_ButtonItem.strLocale = ""; - m_ButtonItem.pContainerPane = pContainerPane; - m_ButtonItem.pIcon = pIcon; - m_ButtonItem.vecIconInitialPos = pIcon->GetPosition(); - m_ButtonItem.vecIconInitialSize = pIcon->GetSize(); - m_ButtonItem.pLabel = pLabel; - m_ButtonItem.vecLabelInitialPos = pLabel->GetPosition(); - m_ButtonItem.vecLabelInitialSize = pLabel->GetSize(); - m_ButtonItem.pContainerPane->SetMouseButtonDownHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonClick, this)); - m_ButtonItem.pContainerPane->SetMouseEnterHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonEnter, this)); - m_ButtonItem.pContainerPane->SetMouseLeaveHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonLeave, this)); + m_ButtonItem.strLocale = ""; + m_ButtonItem.pContainerPane = pContainerPane; + m_ButtonItem.pIcon = pIcon; + m_ButtonItem.vecIconInitialPos = pIcon->GetPosition(); + m_ButtonItem.vecIconInitialSize = pIcon->GetSize(); + m_ButtonItem.pLabel = pLabel; + m_ButtonItem.vecLabelInitialPos = pLabel->GetPosition(); + m_ButtonItem.vecLabelInitialSize = pLabel->GetSize(); + m_ButtonItem.pContainerPane->SetMouseButtonDownHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonClick, this)); + m_ButtonItem.pContainerPane->SetMouseEnterHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonEnter, this)); + m_ButtonItem.pContainerPane->SetMouseLeaveHandler(GUI_CALLBACK(&CLanguageSelector::OnButtonLeave, this)); } // diff --git a/Client/core/CLinkedList.h b/Client/core/CLinkedList.h index b271232cfe4..7a46b295fb1 100644 --- a/Client/core/CLinkedList.h +++ b/Client/core/CLinkedList.h @@ -17,7 +17,7 @@ #pragma once // ignore the return type warning for the -> operator when we are potentially using pointers themselves -#pragma warning(disable:4284) +#pragma warning(disable : 4284) #include @@ -271,7 +271,7 @@ class CLinkedList void remove(CIterator& itNode, BOOL bIterateForwards = TRUE) { CNode* pTempNode = itNode.m_pCurrent; - CNode* pTempSingleNode = NULL; // will be used if only a single node remains + CNode* pTempSingleNode = NULL; // will be used if only a single node remains BOOL bIteratorSet = FALSE; diff --git a/Client/core/CLocalization.cpp b/Client/core/CLocalization.cpp index 709d49f2dd8..24c9875b200 100644 --- a/Client/core/CLocalization.cpp +++ b/Client/core/CLocalization.cpp @@ -11,7 +11,7 @@ #include "StdInc.h" #include "../../vendor/tinygettext/log.hpp" -#define MTA_LOCALE_TEXTDOMAIN "client" +#define MTA_LOCALE_TEXTDOMAIN "client" // TRANSLATORS: Replace with your language native name #define NATIVE_LANGUAGE_NAME _td("English") @@ -20,7 +20,7 @@ struct NativeLanguageName std::string locale; std::string name; } g_nativeLanguageNames[] = { - #include "languages.generated.h" +#include "languages.generated.h" }; CLocalization::CLocalization(const SString& strLocale, const SString& strLocalePath) @@ -107,7 +107,8 @@ CLanguage* CLocalization::GetLanguage(SString strLocale) try { - std::unique_ptr pLanguage = std::make_unique(m_DictManager.get_dictionary(Lang, MTA_LOCALE_TEXTDOMAIN), Lang.str(), Lang.get_name()); + std::unique_ptr pLanguage = + std::make_unique(m_DictManager.get_dictionary(Lang, MTA_LOCALE_TEXTDOMAIN), Lang.str(), Lang.get_name()); CLanguage* pLanguagePtr = pLanguage.get(); m_LanguageMap.emplace(strLocale, std::move(pLanguage)); return pLanguagePtr; @@ -237,7 +238,7 @@ SString CLocalization::GetLanguageDirectory(CLanguage* pLanguage) if (!pSelectLang) return SString(); - SString strFullPath = pSelectLang->GetDictionary().get_filepath(); + SString strFullPath = pSelectLang->GetDictionary().get_filepath(); // Replace all backslashes with forward slashes int idx = 0; diff --git a/Client/core/CMainMenu.cpp b/Client/core/CMainMenu.cpp index 65841685320..c7e4814e2e0 100644 --- a/Client/core/CMainMenu.cpp +++ b/Client/core/CMainMenu.cpp @@ -15,39 +15,40 @@ #include "CLanguageSelector.h" #include "CDiscordRichPresence.h" -#define NATIVE_RES_X 1280.0f -#define NATIVE_RES_Y 1024.0f +#define NATIVE_RES_X 1280.0f +#define NATIVE_RES_Y 1024.0f -#define NATIVE_BG_X 1280.0f -#define NATIVE_BG_Y 649.0f +#define NATIVE_BG_X 1280.0f +#define NATIVE_BG_Y 649.0f -#define NATIVE_LOGO_X 1058.0f -#define NATIVE_LOGO_Y 540.0f +#define NATIVE_LOGO_X 1058.0f +#define NATIVE_LOGO_Y 540.0f -#define CORE_MTA_MENUITEMS_START_X 0.168 +#define CORE_MTA_MENUITEMS_START_X 0.168 -#define CORE_MTA_BG_MAX_ALPHA 1.00f //ACHTUNG: Set to 1 for now due to GTA main menu showing through (no delay inserted between Entering game... and loading screen) -#define CORE_MTA_BG_INGAME_ALPHA 0.90f -#define CORE_MTA_FADER 0.05f // 1/20 -#define CORE_MTA_FADER_CREDITS 0.01f +#define CORE_MTA_BG_MAX_ALPHA \ + 1.00f // ACHTUNG: Set to 1 for now due to GTA main menu showing through (no delay inserted between Entering game... and loading screen) +#define CORE_MTA_BG_INGAME_ALPHA 0.90f +#define CORE_MTA_FADER 0.05f // 1/20 +#define CORE_MTA_FADER_CREDITS 0.01f -#define CORE_MTA_HOVER_SCALE 1.0f -#define CORE_MTA_NORMAL_SCALE 0.6f -#define CORE_MTA_HOVER_ALPHA 1.0f -#define CORE_MTA_NORMAL_ALPHA 0.6f +#define CORE_MTA_HOVER_SCALE 1.0f +#define CORE_MTA_NORMAL_SCALE 0.6f +#define CORE_MTA_HOVER_ALPHA 1.0f +#define CORE_MTA_NORMAL_ALPHA 0.6f -#define CORE_MTA_HIDDEN_ALPHA 0.0f -#define CORE_MTA_DISABLED_ALPHA 0.4f -#define CORE_MTA_ENABLED_ALPHA 1.0f +#define CORE_MTA_HIDDEN_ALPHA 0.0f +#define CORE_MTA_DISABLED_ALPHA 0.4f +#define CORE_MTA_ENABLED_ALPHA 1.0f #define CORE_MTA_ANIMATION_TIME_IN 200 #define CORE_MTA_ANIMATION_TIME_OUT 100 #define CORE_MTA_MOVE_ANIM_TIME 600 -#define CORE_MTA_STATIC_BG "cgui\\images\\background.png" -#define CORE_MTA_LOGO "cgui\\images\\background_logo.png" -#define CORE_MTA_FILLER "cgui\\images\\mta_filler.png" -#define CORE_MTA_VERSION "cgui\\images\\version.png" +#define CORE_MTA_STATIC_BG "cgui\\images\\background.png" +#define CORE_MTA_LOGO "cgui\\images\\background_logo.png" +#define CORE_MTA_FILLER "cgui\\images\\mta_filler.png" +#define CORE_MTA_VERSION "cgui\\images\\version.png" static const SColor headlineColors[] = {SColorRGBA(233, 234, 106, 255), SColorRGBA(233 / 6 * 4, 234 / 6 * 4, 106 / 6 * 4, 255), SColorRGBA(233 / 7 * 3, 234 / 7 * 3, 106 / 7 * 3, 255)}; @@ -88,7 +89,7 @@ CMainMenu::CMainMenu(CGUI* pManager) int iBackgroundSizeY; // First let's work out our x and y offsets - if (ScreenSize.fX > ScreenSize.fY) // If the monitor is a normal landscape one + if (ScreenSize.fX > ScreenSize.fY) // If the monitor is a normal landscape one { float iRatioSizeY = ScreenSize.fY / NATIVE_RES_Y; m_iMenuSizeX = NATIVE_RES_X * iRatioSizeY; @@ -100,7 +101,7 @@ CMainMenu::CMainMenu(CGUI* pManager) iBackgroundSizeX = ScreenSize.fX; iBackgroundSizeY = NATIVE_BG_Y * iRatioSizeX; } - else // Otherwise our monitor is in a portrait resolution, so we cant fill the background by y + else // Otherwise our monitor is in a portrait resolution, so we cant fill the background by y { float iRatioSizeX = ScreenSize.fX / NATIVE_RES_X; m_iMenuSizeY = NATIVE_RES_Y * iRatioSizeX; @@ -194,9 +195,9 @@ CMainMenu::CMainMenu(CGUI* pManager) m_iSecondItemCentre = (m_menuItems[1]->image)->GetPosition().fY + fSecondItemSize * 0.5f; // Store some mouse over bounding box positions - m_menuAX = (0.168f * m_iMenuSizeX) + m_iXOff; // Left side of the items - m_menuAY = m_iFirstItemCentre - fFirstItemSize * (CORE_MTA_HOVER_SCALE / CORE_MTA_NORMAL_SCALE) * 0.5f; // Top side of the items - m_menuBX = m_menuAX + ((390 / NATIVE_RES_X) * m_iMenuSizeX); // Right side of the items. We add the longest picture (browse_servers) + m_menuAX = (0.168f * m_iMenuSizeX) + m_iXOff; // Left side of the items + m_menuAY = m_iFirstItemCentre - fFirstItemSize * (CORE_MTA_HOVER_SCALE / CORE_MTA_NORMAL_SCALE) * 0.5f; // Top side of the items + m_menuBX = m_menuAX + ((390 / NATIVE_RES_X) * m_iMenuSizeX); // Right side of the items. We add the longest picture (browse_servers) m_menuAY += BODGE_FACTOR_1; m_pMenuArea = reinterpret_cast(pManager->CreateStaticImage(m_pCanvas)); @@ -223,7 +224,7 @@ CMainMenu::CMainMenu(CGUI* pManager) float fDrawSizeX = (vecNativeSize.fX / NATIVE_RES_X) * m_iMenuSizeX; float fDrawSizeY = (vecNativeSize.fY / NATIVE_RES_Y) * m_iMenuSizeY; m_pLatestNews->SetSize(CVector2D(fDrawSizeX, fDrawSizeY), false); - float fDrawPosX = 0.83f * m_iMenuSizeX - fDrawSizeX; // Right aligned + float fDrawPosX = 0.83f * m_iMenuSizeX - fDrawSizeX; // Right aligned float fDrawPosY = 0.61f * m_iMenuSizeY; m_pLatestNews->SetPosition(CVector2D(fDrawPosX, fDrawPosY), false); m_pLatestNews->SetVisible(false); @@ -320,7 +321,7 @@ CMainMenu::CMainMenu(CGUI* pManager) // Add feature branch alert m_pFeatureBranchAlertTexture.reset(reinterpret_cast(m_pManager->CreateTexture())); std::int32_t buffer = 0xFFFF0000; - m_pFeatureBranchAlertTexture->LoadFromMemory(&buffer, 1, 1); // HACK: Load red dot + m_pFeatureBranchAlertTexture->LoadFromMemory(&buffer, 1, 1); // HACK: Load red dot m_pFeatureBranchAlertImage.reset(reinterpret_cast(m_pManager->CreateStaticImage(m_pBackground))); m_pFeatureBranchAlertImage->LoadFromTexture(m_pFeatureBranchAlertTexture.get()); @@ -341,7 +342,7 @@ CMainMenu::CMainMenu(CGUI* pManager) // Add annonying alert m_pAlertTexture.reset(reinterpret_cast(m_pManager->CreateTexture())); std::int32_t buffer = 0xFFFF0000; - m_pAlertTexture->LoadFromMemory(&buffer, 1, 1); // HACK: Load red dot + m_pAlertTexture->LoadFromMemory(&buffer, 1, 1); // HACK: Load red dot m_pAlertImage.reset(reinterpret_cast(m_pManager->CreateStaticImage(m_pBackground))); m_pAlertImage->LoadFromTexture(m_pAlertTexture.get()); @@ -358,7 +359,8 @@ CMainMenu::CMainMenu(CGUI* pManager) CMainMenu::~CMainMenu() { - auto destroyElement = [this](auto*& element) { + auto destroyElement = [this](auto*& element) + { if (!element) return; m_pManager->DestroyElementRecursive(element); @@ -444,9 +446,9 @@ void CMainMenu::SetMenuVerticalPosition(int iPosY) m_pMenuArea->SetSize(CVector2D(m_menuBX - m_menuAX, m_menuBY - m_menuAY) + BODGE_FACTOR_6, false); } -void CMainMenu::SetMenuUnhovered() // Dehighlight all our items +void CMainMenu::SetMenuUnhovered() // Dehighlight all our items { - if (m_bIsIngame) // CEGUI hack + if (m_bIsIngame) // CEGUI hack { float fAlpha = m_pDisconnect->image->GetAlpha(); m_pDisconnect->image->SetAlpha(0.35f); @@ -478,8 +480,8 @@ void CMainMenu::Update() } // Get the game interface and the system state - CGame* pGame = CCore::GetSingleton().GetGame(); - SystemState systemState = pGame->GetSystemState(); + CGame* pGame = CCore::GetSingleton().GetGame(); + SystemState systemState = pGame->GetSystemState(); m_Credits.Update(); m_Settings.Update(); @@ -490,7 +492,7 @@ void CMainMenu::Update() if (m_bHideGame) m_pGraphics->DrawRectangle(0, 0, m_ScreenSize.fX, m_ScreenSize.fY, 0xFF000000); - if (m_bIsIngame) // CEGUI hack + if (m_bIsIngame) // CEGUI hack { float fAlpha = m_pDisconnect->image->GetAlpha(); m_pDisconnect->image->SetAlpha(0.35f); @@ -567,7 +569,8 @@ void CMainMenu::Update() { // Let's work out what the target progress should be by working out the time passed // Min of 0.5 progress fixes occasional graphical glitchekal - float newProgress = (*it)->animProgress - std::min(0.5f, ((float)ulTimePassed / CORE_MTA_ANIMATION_TIME_OUT) * (CORE_MTA_HOVER_ALPHA - CORE_MTA_NORMAL_ALPHA)); + float newProgress = + (*it)->animProgress - std::min(0.5f, ((float)ulTimePassed / CORE_MTA_ANIMATION_TIME_OUT) * (CORE_MTA_HOVER_ALPHA - CORE_MTA_NORMAL_ALPHA)); if (SetItemHoverProgress((*it), newProgress, false)) { std::set::iterator itToErase = it++; @@ -602,7 +605,7 @@ void CMainMenu::Update() float fTopItemSize = m_pDisconnect->image->GetSize(false).fY; float fTopItemCentre = m_pDisconnect->image->GetPosition(false).fY + fTopItemSize * 0.5f; - m_menuAY = fTopItemCentre - fTopItemSize * (CORE_MTA_HOVER_SCALE / CORE_MTA_NORMAL_SCALE) * 0.5f; // Top side of the items + m_menuAY = fTopItemCentre - fTopItemSize * (CORE_MTA_HOVER_SCALE / CORE_MTA_NORMAL_SCALE) * 0.5f; // Top side of the items m_menuAY += BODGE_FACTOR_1; m_pMenuArea->SetPosition(CVector2D(m_menuAX - m_iXOff, m_menuAY - m_iYOff) + BODGE_FACTOR_5, false); @@ -626,7 +629,7 @@ void CMainMenu::Update() if (m_fFader > 0.0f) { - m_bIsVisible = true; // Make cursor appear faster + m_bIsVisible = true; // Make cursor appear faster if (!m_bCursorAlphaReset) { @@ -646,7 +649,6 @@ void CMainMenu::Update() m_ucFade = FADE_VISIBLE; m_bIsVisible = true; m_bIsFullyVisible = true; - } } // Fade out @@ -661,11 +663,10 @@ void CMainMenu::Update() if (m_fFader < 1.0f) { - m_bIsVisible = false; // Make cursor disappear faster + m_bIsVisible = false; // Make cursor disappear faster m_bCursorAlphaReset = false; } - // If the fade is complete if (m_fFader <= 0) { @@ -706,8 +707,7 @@ void CMainMenu::Update() if (m_bIsVisible && systemState != SystemState::GS_INIT_PLAYING_GAME) { // If we're at the game's mainmenu, or ingame when m_bIsIngame is true show the background - if (systemState == SystemState::GS_FRONTEND || - systemState == SystemState::GS_PLAYING_GAME && !m_bIsIngame) + if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_PLAYING_GAME && !m_bIsIngame) { if (m_ucFade == FADE_INVISIBLE) Show(false); diff --git a/Client/core/CMainMenu.h b/Client/core/CMainMenu.h index 6c6e93c8ffe..810f568c366 100644 --- a/Client/core/CMainMenu.h +++ b/Client/core/CMainMenu.h @@ -23,7 +23,7 @@ class CMainMenu; class CNewsBrowser; class CLanguageSelector; -#define CORE_MTA_NEWS_ITEMS 3 +#define CORE_MTA_NEWS_ITEMS 3 struct sMenuItem { diff --git a/Client/core/CMemStats.cpp b/Client/core/CMemStats.cpp index e7889442378..098e6010444 100644 --- a/Client/core/CMemStats.cpp +++ b/Client/core/CMemStats.cpp @@ -244,7 +244,7 @@ namespace static SMemStatsInfo* pZeroed = new SMemStatsInfo(); memStats = *pZeroed; } -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -482,7 +482,7 @@ void CMemStats::SampleState(SMemStatsInfo& memStatsInfo) for (uint i = 0; i < RRR_BASE_ID; i++) { char* pModelInfo = pFileInfoArray + 20 /* sizeof(CStreamingInfo) */ * i; - char uiLoadedFlag = pModelInfo[0x10]; // CStreamingInfo.uiLoadFlag + char uiLoadedFlag = pModelInfo[0x10]; // CStreamingInfo.uiLoadFlag if (uiLoadedFlag) { memStatsInfo.modelInfo.uiTotal++; @@ -598,7 +598,7 @@ void CMemStats::UpdateIntervalStats() deltaList[i]->iCreatedBytes = nowList[i]->iCreatedBytes - prevList[i]->iCreatedBytes; deltaList[i]->iDestroyedCount = nowList[i]->iDestroyedCount - prevList[i]->iDestroyedCount; deltaList[i]->iDestroyedBytes = nowList[i]->iDestroyedBytes - prevList[i]->iDestroyedBytes; - deltaList[i]->iLockedCount = maxList[i]->iLockedCount; // Use per-frame max for lock stats + deltaList[i]->iLockedCount = maxList[i]->iLockedCount; // Use per-frame max for lock stats } m_MemStatsDelta.rwResourceStats.uiTextures = m_MemStatsNow.rwResourceStats.uiTextures - m_MemStatsPrev.rwResourceStats.uiTextures; @@ -664,27 +664,27 @@ void CMemStats::CreateTables() CGame* pGame = g_pCore->GetGame(); m_TableList.clear(); -// -// Color setups -// - #define YELLOW "#FFFF00" - #define RED "#FF0000" - #define BLUE "#0000FF" - #define WHITE "#FFFFFF" - - #define LT_RED "#FF5050" - #define DK_RED "#CF0000" - #define GREY "#808080" - #define LT_GREY "#C0C0C0" - #define INVIS "#000000" - #define DK_GREEN "#00CF00" - #define LT_GREEN "#30FF30" - #define PURPLE "#FF00FF" - #define CYAN "#00FFFF" - #define LT_CYAN "#00C0F0" - - // Table header - #define HEADER1(text) LT_CYAN text WHITE + // + // Color setups + // +#define YELLOW "#FFFF00" +#define RED "#FF0000" +#define BLUE "#0000FF" +#define WHITE "#FFFFFF" + +#define LT_RED "#FF5050" +#define DK_RED "#CF0000" +#define GREY "#808080" +#define LT_GREY "#C0C0C0" +#define INVIS "#000000" +#define DK_GREEN "#00CF00" +#define LT_GREEN "#30FF30" +#define PURPLE "#FF00FF" +#define CYAN "#00FFFF" +#define LT_CYAN "#00C0F0" + +// Table header +#define HEADER1(text) LT_CYAN text WHITE // Cell colour depending upon the value SString strNumberColorsCreat = GREY "0," CYAN "999999,"; diff --git a/Client/core/CMessageLoopHook.cpp b/Client/core/CMessageLoopHook.cpp index 5935bdb8c2c..c1d8963d0c1 100644 --- a/Client/core/CMessageLoopHook.cpp +++ b/Client/core/CMessageLoopHook.cpp @@ -211,10 +211,10 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w // Make sure our pointers are valid. if (pThis != NULL && hwnd == pThis->GetHookedWindowHandle() && g_pCore->AreModulesLoaded()) { - g_pCore->UpdateIsWindowMinimized(); // Force update of stuff + g_pCore->UpdateIsWindowMinimized(); // Force update of stuff if (uMsg == WM_TIMER && wParam == IDT_TIMER1) - g_pCore->WindowsTimerHandler(); // Used for 'minimized before first game' pulses + g_pCore->WindowsTimerHandler(); // Used for 'minimized before first game' pulses // Handle IME if input is not for the GUI if (!g_pCore->GetLocalGUI()->InputGoesToGUI()) @@ -322,7 +322,8 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w if ((uMsg == WM_KEYDOWN && wParam == VK_TAB)) { SystemState systemState = g_pCore->GetGame()->GetSystemState(); - if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_INIT_PLAYING_GAME || systemState == SystemState::GS_PLAYING_GAME) + if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_INIT_PLAYING_GAME || + systemState == SystemState::GS_PLAYING_GAME) { short sCtrlState = GetKeyState(VK_CONTROL); short sShiftState = GetKeyState(VK_SHIFT); @@ -345,7 +346,8 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w if ((uMsg == WM_KEYDOWN && (wParam >= VK_1 && wParam <= VK_9))) { SystemState systemState = g_pCore->GetGame()->GetSystemState(); - if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_INIT_PLAYING_GAME || systemState == SystemState::GS_PLAYING_GAME) + if (systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_INIT_PLAYING_GAME || + systemState == SystemState::GS_PLAYING_GAME) { short sCtrlState = GetKeyState(VK_CONTROL); if (sCtrlState & 0x8000) @@ -369,8 +371,8 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w if ((uMsg == WM_KEYDOWN && wParam == VK_F8) || (uMsg == WM_CHAR && wParam == '`')) { SystemState systemState = g_pCore->GetGame()->GetSystemState(); - if (CLocalGUI::GetSingleton().IsConsoleVisible() || systemState == SystemState::GS_FRONTEND || systemState == SystemState::GS_INIT_PLAYING_GAME || - systemState == SystemState::GS_PLAYING_GAME) + if (CLocalGUI::GetSingleton().IsConsoleVisible() || systemState == SystemState::GS_FRONTEND || + systemState == SystemState::GS_INIT_PLAYING_GAME || systemState == SystemState::GS_PLAYING_GAME) { CLocalGUI::GetSingleton().SetConsoleVisible(!CLocalGUI::GetSingleton().IsConsoleVisible()); } @@ -494,10 +496,10 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w if (!GetVideoModeManager()->IsWindowed()) { if (!CLocalGUI::GetSingleton().GetMainMenu() || !CLocalGUI::GetSingleton().GetMainMenu()->HasStarted()) - return true; // No auto-minimize + return true; // No auto-minimize if (GetVideoModeManager()->IsMultiMonitor() && !GetVideoModeManager()->IsMinimizeEnabled()) - return true; // No auto-minimize + return true; // No auto-minimize } } /* @@ -512,7 +514,7 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w } */ - if (uMsg == WM_SYSCOMMAND && wParam == 0xF012) // SC_DRAGMOVE + if (uMsg == WM_SYSCOMMAND && wParam == 0xF012) // SC_DRAGMOVE { CMessageLoopHook::GetSingleton().StartWindowMovement(); return true; diff --git a/Client/core/CMessageLoopHook.h b/Client/core/CMessageLoopHook.h index d1daafa98da..e8d16690d4b 100644 --- a/Client/core/CMessageLoopHook.h +++ b/Client/core/CMessageLoopHook.h @@ -15,8 +15,8 @@ #include "CSingleton.h" #define URI_CONNECT 1 -#define VK_1 0x30 -#define VK_9 0x39 +#define VK_1 0x30 +#define VK_9 0x39 class CMessageLoopHook : public CSingleton { diff --git a/Client/core/CModManager.cpp b/Client/core/CModManager.cpp index b128adb58ba..858b5ea86ef 100644 --- a/Client/core/CModManager.cpp +++ b/Client/core/CModManager.cpp @@ -57,7 +57,7 @@ bool CModManager::TriggerCommand(const char* commandName, size_t commandNameLeng void CModManager::DoPulsePreFrame() { TIMING_GRAPH("+DoPulsePreFrame"); - CCore::GetSingleton().GetFPSLimiter()->OnFrameStart(); // Prepare FPS limiting for this frame + CCore::GetSingleton().GetFPSLimiter()->OnFrameStart(); // Prepare FPS limiting for this frame if (m_client) { @@ -88,7 +88,7 @@ void CModManager::DoPulsePostFrame() TIMING_GRAPH("+DoPulsePostFrame"); - handleStateChange(); // Handle state changes before pulse + handleStateChange(); // Handle state changes before pulse if (m_client) { @@ -99,12 +99,12 @@ void CModManager::DoPulsePostFrame() CCore::GetSingleton().GetNetwork()->DoPulse(); } - CCore::GetSingleton().DoReliablePulse(); // Do reliable pulse + CCore::GetSingleton().DoReliablePulse(); // Do reliable pulse - handleStateChange(); // Handle state changes after pulse + handleStateChange(); // Handle state changes after pulse // TODO: ENSURE "CModManager::DoPulsePostFrame" IS THE LAST THING BEFORE THE FRAME ENDS - CCore::GetSingleton().GetFPSLimiter()->OnFrameEnd(); // Apply FPS limiting + CCore::GetSingleton().GetFPSLimiter()->OnFrameEnd(); // Apply FPS limiting TIMING_GRAPH("-DoPulsePostFrame"); TIMING_GRAPH(""); @@ -187,7 +187,7 @@ bool CModManager::TryStart() return false; } - using InitClientFn = CClientBase* (__cdecl*)(); + using InitClientFn = CClientBase*(__cdecl*)(); InitClientFn initClient = nullptr; if (!SharedUtil::TryGetProcAddress(library, "InitClient", initClient)) { diff --git a/Client/core/CModelCacheManager.cpp b/Client/core/CModelCacheManager.cpp index 189d8014409..a706c1a7daf 100644 --- a/Client/core/CModelCacheManager.cpp +++ b/Client/core/CModelCacheManager.cpp @@ -38,12 +38,12 @@ namespace constexpr std::uintptr_t FUNC_CGame_CanSeeOutsideFromCurrArea = 0x53C4A0; constexpr std::size_t PED_STREAMING_SLOT_COUNT = 8u; - constexpr int32_t PED_STREAMING_SLOT_MAX_VALUE = 0xFFFF; - constexpr uint32_t PED_STREAMING_FLOOR = 4u; - constexpr uint32_t VEHICLE_STREAMING_FLOOR_EXTERIOR = 7u; - constexpr uint32_t VEHICLE_STREAMING_FLOOR_INTERIOR = 4u; + constexpr int32_t PED_STREAMING_SLOT_MAX_VALUE = 0xFFFF; + constexpr uint32_t PED_STREAMING_FLOOR = 4u; + constexpr uint32_t VEHICLE_STREAMING_FLOOR_EXTERIOR = 7u; + constexpr uint32_t VEHICLE_STREAMING_FLOOR_INTERIOR = 4u; constexpr std::size_t VEHICLE_STREAMING_SLOT_COUNT = 23u; - constexpr int16_t VEHICLE_STREAMING_SLOT_UNUSED = -1; + constexpr int16_t VEHICLE_STREAMING_SLOT_UNUSED = -1; uint32_t GetNativeNumPedsLoaded() { @@ -114,7 +114,7 @@ namespace using Fn = bool(__cdecl*)(); return reinterpret_cast(FUNC_CGame_CanSeeOutsideFromCurrArea)(); } -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -151,14 +151,14 @@ class CModelCacheManagerImpl : public CModelCacheManager bool TryReleaseCachedModel(ushort usModelId, SModelCacheInfo& info, const char* contextTag, uint& uiNumModelsCachedHereOnly); protected: - CGame* m_pGame{}; - int m_iFrameCounter{}; - CTickCount m_TickCountNow{}; - bool m_bDonePreLoad{}; - uint m_uiMaxCachedPedModels{}; - bool m_IsUsingCustomPedCacheLimit{}; //< If `true` the value is set by the scripter, otherwise is calculated in `DoPulse()` - uint m_uiMaxCachedVehicleModels{}; - bool m_IsUsingCustomVehicleCacheLimit{}; //< If `true` the value is set by the scripter, otherwise is calculated in `DoPulse()` + CGame* m_pGame{}; + int m_iFrameCounter{}; + CTickCount m_TickCountNow{}; + bool m_bDonePreLoad{}; + uint m_uiMaxCachedPedModels{}; + bool m_IsUsingCustomPedCacheLimit{}; //< If `true` the value is set by the scripter, otherwise is calculated in `DoPulse()` + uint m_uiMaxCachedVehicleModels{}; + bool m_IsUsingCustomVehicleCacheLimit{}; //< If `true` the value is set by the scripter, otherwise is calculated in `DoPulse()` std::map m_PedModelCacheInfoMap{}; std::map m_VehicleModelCacheInfoMap{}; }; @@ -267,7 +267,7 @@ void CModelCacheManagerImpl::PreLoad() { if (bSlowMethod) SetApplicationSettingInt(DIAG_PRELOAD_UPGRADE_ATTEMPT_ID, i); - + AddModelRefCount(static_cast(i)); if (bSlowMethod) @@ -317,13 +317,16 @@ void CModelCacheManagerImpl::GetStats(SModelCacheStats& outStats) // Function to set custom limits, instead of calculating them automatically. // If the pointer is nullptr, the value is restored to the automatic one // otherwise it is set to whatever value the pointer points to -// +// /////////////////////////////////////////////////////////////// -void CModelCacheManagerImpl::SetCustomLimits(const size_t* numVehicles, const size_t* numPeds) { - if (m_IsUsingCustomPedCacheLimit = (numPeds != nullptr)) { +void CModelCacheManagerImpl::SetCustomLimits(const size_t* numVehicles, const size_t* numPeds) +{ + if (m_IsUsingCustomPedCacheLimit = (numPeds != nullptr)) + { m_uiMaxCachedPedModels = *numPeds; } - if (m_IsUsingCustomVehicleCacheLimit = (numVehicles != nullptr)) { + if (m_IsUsingCustomVehicleCacheLimit = (numVehicles != nullptr)) + { m_uiMaxCachedVehicleModels = *numVehicles; } } @@ -347,11 +350,13 @@ void CModelCacheManagerImpl::DoPulse() // 256MB streaming = 16+8 MB for peds & vehicles 72 peds + 56 veh // const auto iStreamingMemoryAvailableKB = *(int*)0x08A5A80; - if (!m_IsUsingCustomPedCacheLimit) { - SSamplePoint pedPoints[] = { {65536, 9}, {98304, 18}, {131072, 36}, {262144, 72} }; + if (!m_IsUsingCustomPedCacheLimit) + { + SSamplePoint pedPoints[] = {{65536, 9}, {98304, 18}, {131072, 36}, {262144, 72}}; m_uiMaxCachedPedModels = (int)EvalSamplePosition(pedPoints, NUMELMS(pedPoints), (float)iStreamingMemoryAvailableKB); } - if (!m_IsUsingCustomVehicleCacheLimit) { + if (!m_IsUsingCustomVehicleCacheLimit) + { SSamplePoint vehPoints[] = {{65536, 7}, {98304, 28}, {131072, 56}, {262144, 56}}; m_uiMaxCachedVehicleModels = (int)EvalSamplePosition(vehPoints, NUMELMS(vehPoints), (float)iStreamingMemoryAvailableKB); } @@ -490,7 +495,8 @@ void CModelCacheManagerImpl::UpdateModelCaching(const std::map& n // If at or above cache limit, try to uncache unneeded first bool bReleasedModel = false; - auto AttemptReleaseFromList = [&](const std::map& candidateList, const char* contextTag) -> bool { + auto AttemptReleaseFromList = [&](const std::map& candidateList, const char* contextTag) -> bool + { for (auto it = candidateList.rbegin(); it != candidateList.rend(); ++it) { const ushort modelId = it->second; @@ -616,7 +622,7 @@ void CModelCacheManagerImpl::OnRestreamModel(ushort usModelId) OutputDebugLine(SString("[Cache] End caching model %d (OnRestreamModel)", usModelId)); } } - } + } } /////////////////////////////////////////////////////////////// @@ -656,10 +662,10 @@ bool CModelCacheManagerImpl::TryReleaseCachedModel(ushort usModelId, SModelCache return false; } - CModelInfo* pModelInfo = m_pGame->GetModelInfo(usModelId, true); + CModelInfo* pModelInfo = m_pGame->GetModelInfo(usModelId, true); const eModelInfoType modelType = pModelInfo ? pModelInfo->GetModelType() : eModelInfoType::UNKNOWN; - const bool bIsPedModel = modelType == eModelInfoType::PED; - const bool bIsVehicleModel = modelType == eModelInfoType::VEHICLE; + const bool bIsPedModel = modelType == eModelInfoType::PED; + const bool bIsVehicleModel = modelType == eModelInfoType::VEHICLE; const bool bTrackedByNativePedSlots = bIsPedModel && IsModelTrackedByNativePedSlots(usModelId); const bool bTrackedByNativeVehicleGroup = bIsVehicleModel && IsModelTrackedByNativeVehicleGroup(usModelId); @@ -675,8 +681,8 @@ bool CModelCacheManagerImpl::TryReleaseCachedModel(ushort usModelId, SModelCache if (bTrackedByNativeVehicleGroup) { const uint32_t vehicleCount = GetNativeVehicleStreamCount(); - const bool bIsInterior = m_pGame->GetWorld() && m_pGame->GetWorld()->GetCurrentArea() != 0; - const bool bTreatAsInterior = bIsInterior || !NativeCanSeeOutsideFromCurrArea(); + const bool bIsInterior = m_pGame->GetWorld() && m_pGame->GetWorld()->GetCurrentArea() != 0; + const bool bTreatAsInterior = bIsInterior || !NativeCanSeeOutsideFromCurrArea(); const uint32_t minVehicleBudget = bTreatAsInterior ? VEHICLE_STREAMING_FLOOR_INTERIOR : VEHICLE_STREAMING_FLOOR_EXTERIOR; if (vehicleCount <= minVehicleBudget) { diff --git a/Client/core/CMouseControl.cpp b/Client/core/CMouseControl.cpp index 2e772c185cb..acf6ace4b61 100644 --- a/Client/core/CMouseControl.cpp +++ b/Client/core/CMouseControl.cpp @@ -19,7 +19,7 @@ #include #include -#define MOUSE_CONTROL_MULTIPLIER 35 +#define MOUSE_CONTROL_MULTIPLIER 35 extern CCore* g_pCore; @@ -75,11 +75,11 @@ bool CMouseControl::ProcessMouseMove(UINT uMsg, WPARAM wParam, LPARAM lParam) bool bVar; CVARS_GET("fly_with_mouse", bVar); - if (pModelInfo->IsPlane() || pModelInfo->IsHeli() && !bVar) // Are we in a plane, but not have mouse flight enabled? + if (pModelInfo->IsPlane() || pModelInfo->IsHeli() && !bVar) // Are we in a plane, but not have mouse flight enabled? return false; CVARS_GET("steer_with_mouse", bVar); - if (!bVar) // Are we in another type of vehicle, but not have mouse steering enabled? + if (!bVar) // Are we in another type of vehicle, but not have mouse steering enabled? return false; // Let's calculate our mouse movement directions diff --git a/Client/core/CNewsBrowser.cpp b/Client/core/CNewsBrowser.cpp index 3df2944f684..032d3fb06d0 100644 --- a/Client/core/CNewsBrowser.cpp +++ b/Client/core/CNewsBrowser.cpp @@ -67,9 +67,9 @@ void CNewsBrowser::InitNewsItemList() { SString strItemDir = directoryList[directoryList.size() - 1 - i]; if (strItemDir < strOldestPost) - continue; // Post too old + continue; // Post too old if (m_NewsitemList.size() >= uiMaxHistoryLength) - continue; // Post count too high + continue; // Post count too high SNewsItem newsItem; newsItem.strContentFullDir = PathJoin(strAllNewsDir, strItemDir); diff --git a/Client/core/CNickGen.h b/Client/core/CNickGen.h index 86a36990728..8ccb853405e 100644 --- a/Client/core/CNickGen.h +++ b/Client/core/CNickGen.h @@ -12,5 +12,5 @@ class CNickGen { public: - static SString GetRandomNickname(); + static SString GetRandomNickname(); }; diff --git a/Client/core/CQueryReceiver.cpp b/Client/core/CQueryReceiver.cpp index b6515991cb2..c09b4f967e9 100644 --- a/Client/core/CQueryReceiver.cpp +++ b/Client/core/CQueryReceiver.cpp @@ -22,11 +22,11 @@ CQueryReceiver::~CQueryReceiver() void CQueryReceiver::RequestQuery(in_addr address, ushort port) { - if (m_Socket == INVALID_SOCKET) // Create the socket + if (m_Socket == INVALID_SOCKET) // Create the socket { m_Socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); u_long flag = 1; - ioctlsocket(m_Socket, FIONBIO, &flag); // Nonblocking I/O + ioctlsocket(m_Socket, FIONBIO, &flag); // Nonblocking I/O } sockaddr_in addr; @@ -88,7 +88,7 @@ SQueryInfo CQueryReceiver::GetServerResponse() SQueryInfo info; if (m_Socket == INVALID_SOCKET) - return info; // Query not sent + return info; // Query not sent char szBuffer[SERVER_LIST_QUERY_BUFFER] = {0}; diff --git a/Client/core/CQuestionBox.cpp b/Client/core/CQuestionBox.cpp index 5b8bf46b661..7a6dbf78889 100644 --- a/Client/core/CQuestionBox.cpp +++ b/Client/core/CQuestionBox.cpp @@ -217,7 +217,7 @@ bool CQuestionBox::OnButtonClick(CGUIElement* pElement) if (m_Callback) m_Callback(m_CallbackParameter, m_uiLastButton); - if (m_CallbackEdit && !m_EditList.empty()) // Just grab the first editbox for now + if (m_CallbackEdit && !m_EditList.empty()) // Just grab the first editbox for now m_CallbackEdit(m_CallbackParameter, m_uiLastButton, m_EditList[0]->GetText()); return true; } diff --git a/Client/core/CScreenShot.cpp b/Client/core/CScreenShot.cpp index a7822bf1bea..c3d31d644fc 100644 --- a/Client/core/CScreenShot.cpp +++ b/Client/core/CScreenShot.cpp @@ -42,83 +42,83 @@ static bool savePhotoInDocuments = false; namespace { -float Clamp(float value, float minValue, float maxValue) -{ - if (value < minValue) - return minValue; - if (value > maxValue) - return maxValue; - return value; -} + float Clamp(float value, float minValue, float maxValue) + { + if (value < minValue) + return minValue; + if (value > maxValue) + return maxValue; + return value; + } -void ApplyBorderlessAdjustmentsToBuffer(void* rawData, uint width, uint height) -{ - if (!rawData || width == 0 || height == 0) - return; + void ApplyBorderlessAdjustmentsToBuffer(void* rawData, uint width, uint height) + { + if (!rawData || width == 0 || height == 0) + return; - bool isBorderless = false; - if (CVideoModeManagerInterface* videoModeManager = GetVideoModeManager()) - isBorderless = videoModeManager->IsDisplayModeWindowed() || videoModeManager->IsDisplayModeFullScreenWindow(); + bool isBorderless = false; + if (CVideoModeManagerInterface* videoModeManager = GetVideoModeManager()) + isBorderless = videoModeManager->IsDisplayModeWindowed() || videoModeManager->IsDisplayModeFullScreenWindow(); - if (!isBorderless && ::g_pDeviceState) - isBorderless = (::g_pDeviceState->CreationState.PresentationParameters.Windowed != 0); + if (!isBorderless && ::g_pDeviceState) + isBorderless = (::g_pDeviceState->CreationState.PresentationParameters.Windowed != 0); - float gammaPower = 1.0f; - float brightnessScale = 1.0f; - float contrastScale = 1.0f; - float saturationScale = 1.0f; - bool applyWindowed = true; - bool applyFullscreen = false; - ::BorderlessGamma::FetchSettings(gammaPower, brightnessScale, contrastScale, saturationScale, applyWindowed, applyFullscreen); + float gammaPower = 1.0f; + float brightnessScale = 1.0f; + float contrastScale = 1.0f; + float saturationScale = 1.0f; + bool applyWindowed = true; + bool applyFullscreen = false; + ::BorderlessGamma::FetchSettings(gammaPower, brightnessScale, contrastScale, saturationScale, applyWindowed, applyFullscreen); - const bool adjustmentsEnabled = isBorderless ? applyWindowed : applyFullscreen; - if (!adjustmentsEnabled) - return; + const bool adjustmentsEnabled = isBorderless ? applyWindowed : applyFullscreen; + if (!adjustmentsEnabled) + return; - if (!::BorderlessGamma::ShouldApplyAdjustments(gammaPower, brightnessScale, contrastScale, saturationScale)) - return; + if (!::BorderlessGamma::ShouldApplyAdjustments(gammaPower, brightnessScale, contrastScale, saturationScale)) + return; - BYTE* data = static_cast(rawData); - const size_t pixelCount = static_cast(width) * static_cast(height); - const float inv255 = 1.0f / 255.0f; - const float contrastPivot = 0.5f; + BYTE* data = static_cast(rawData); + const size_t pixelCount = static_cast(width) * static_cast(height); + const float inv255 = 1.0f / 255.0f; + const float contrastPivot = 0.5f; - for (size_t i = 0; i < pixelCount; ++i) - { - float r = Clamp(data[0] * inv255, 0.0f, 1.0f); - float g = Clamp(data[1] * inv255, 0.0f, 1.0f); - float b = Clamp(data[2] * inv255, 0.0f, 1.0f); + for (size_t i = 0; i < pixelCount; ++i) + { + float r = Clamp(data[0] * inv255, 0.0f, 1.0f); + float g = Clamp(data[1] * inv255, 0.0f, 1.0f); + float b = Clamp(data[2] * inv255, 0.0f, 1.0f); - r = powf(r, gammaPower); - g = powf(g, gammaPower); - b = powf(b, gammaPower); + r = powf(r, gammaPower); + g = powf(g, gammaPower); + b = powf(b, gammaPower); - r *= brightnessScale; - g *= brightnessScale; - b *= brightnessScale; + r *= brightnessScale; + g *= brightnessScale; + b *= brightnessScale; - r = (r - contrastPivot) * contrastScale + contrastPivot; - g = (g - contrastPivot) * contrastScale + contrastPivot; - b = (b - contrastPivot) * contrastScale + contrastPivot; + r = (r - contrastPivot) * contrastScale + contrastPivot; + g = (g - contrastPivot) * contrastScale + contrastPivot; + b = (b - contrastPivot) * contrastScale + contrastPivot; - float luminance = Clamp(0.299f * r + 0.587f * g + 0.114f * b, 0.0f, 1.0f); + float luminance = Clamp(0.299f * r + 0.587f * g + 0.114f * b, 0.0f, 1.0f); - r = luminance + (r - luminance) * saturationScale; - g = luminance + (g - luminance) * saturationScale; - b = luminance + (b - luminance) * saturationScale; + r = luminance + (r - luminance) * saturationScale; + g = luminance + (g - luminance) * saturationScale; + b = luminance + (b - luminance) * saturationScale; - r = Clamp(r, 0.0f, 1.0f); - g = Clamp(g, 0.0f, 1.0f); - b = Clamp(b, 0.0f, 1.0f); + r = Clamp(r, 0.0f, 1.0f); + g = Clamp(g, 0.0f, 1.0f); + b = Clamp(b, 0.0f, 1.0f); - data[0] = static_cast(r * 255.0f + 0.5f); - data[1] = static_cast(g * 255.0f + 0.5f); - data[2] = static_cast(b * 255.0f + 0.5f); + data[0] = static_cast(r * 255.0f + 0.5f); + data[1] = static_cast(g * 255.0f + 0.5f); + data[2] = static_cast(b * 255.0f + 0.5f); - data += 4; + data += 4; + } } -} -} // namespace +} // namespace void CScreenShot::InitiateScreenShot(bool bIsCameraShot) { @@ -224,8 +224,8 @@ DWORD WINAPI CScreenShot::ThreadProc(LPVOID lpdwThreadParam) ppScreenData[y] = new BYTE[ms_uiWidth * 4]; } - // Copy the surface data into a row-based buffer for libpng - #define BYTESPERPIXEL 4 +// Copy the surface data into a row-based buffer for libpng +#define BYTESPERPIXEL 4 unsigned long ulLineWidth = ms_uiWidth * 4; for (unsigned int i = 0; i < ms_uiHeight; i++) { diff --git a/Client/core/CSettings.cpp b/Client/core/CSettings.cpp index 676a85c9660..fe73aeaba80 100644 --- a/Client/core/CSettings.cpp +++ b/Client/core/CSettings.cpp @@ -20,11 +20,11 @@ using namespace std; -#define CORE_MTA_FILLER "cgui\\images\\mta_filler.png" -#define CORE_SETTINGS_UPDATE_INTERVAL 30 // Settings update interval in frames -#define CORE_SETTINGS_HEADERS 3 -#define CORE_SETTINGS_HEADER_SPACER " " -#define CORE_SETTINGS_NO_KEY " " +#define CORE_MTA_FILLER "cgui\\images\\mta_filler.png" +#define CORE_SETTINGS_UPDATE_INTERVAL 30 // Settings update interval in frames +#define CORE_SETTINGS_HEADERS 3 +#define CORE_SETTINGS_HEADER_SPACER " " +#define CORE_SETTINGS_NO_KEY " " extern CCore* g_pCore; extern SBindableGTAControl g_bcControls[]; @@ -32,150 +32,147 @@ extern SBindableKey g_bkKeys[]; namespace { -constexpr float kBorderlessGammaMin = 0.5f; -constexpr float kBorderlessGammaMax = 2.0f; -constexpr float kBorderlessGammaDefault = 0.95f; -constexpr float kBorderlessBrightnessMin = 0.5f; -constexpr float kBorderlessBrightnessMax = 2.0f; -constexpr float kBorderlessBrightnessDefault = 1.03f; -constexpr float kBorderlessContrastMin = 0.5f; -constexpr float kBorderlessContrastMax = 2.0f; -constexpr float kBorderlessContrastDefault = 1.0f; -constexpr float kBorderlessSaturationMin = 0.5f; -constexpr float kBorderlessSaturationMax = 2.0f; -constexpr float kBorderlessSaturationDefault = 1.0f; - -constexpr float kSettingsContentWidth = 680.0f; -constexpr float kSettingsBaseContentHeight = 480.0f; -constexpr float kSettingsWindowFrameHorizontal = 18.0f; // 9px left + 9px right -constexpr float kSettingsWindowFrameVertical = 22.0f; // 20px top + 2px bottom -constexpr float kSettingsBottomButtonAreaHeight = 38.0f; -constexpr float kPostFxCheckboxOffset = 24.0f; -constexpr float kSettingsTabHorizontalPadding = 20.0f; -constexpr float kSliderValueReserve = 80.0f; -constexpr float kSettingsSliderExtraAllowance = 0.0f; -constexpr float kSettingsSliderMinWidth = 32.0f; -constexpr float kSliderLabelSpacing = 6.0f; -constexpr float kSliderLeftSpacing = 6.0f; -constexpr float kBrowserColumnSpacing = 18.0f; -constexpr float kBrowserColumnMinWidth = 240.0f; - -float NormalizeSliderValue(float value, float minValue, float maxValue) -{ - if (maxValue <= minValue) - return 0.0f; - return std::clamp((value - minValue) / (maxValue - minValue), 0.0f, 1.0f); -} - -float DenormalizeSliderValue(float position, float minValue, float maxValue) -{ - position = std::clamp(position, 0.0f, 1.0f); - return minValue + position * (maxValue - minValue); -} - -float ComputeSliderWidth(float tabWidth, float sliderX, float preferredWidth, float reservedWidth = kSliderValueReserve) -{ - const float totalAvailable = std::max(0.0f, tabWidth - sliderX); - if (totalAvailable <= 0.0f) { - return 0.0f; - } - - const float clampedReserve = std::clamp(reservedWidth, 0.0f, totalAvailable); - const float spaceForSlider = totalAvailable - clampedReserve; - - float width = 0.0f; - if (spaceForSlider >= preferredWidth) + constexpr float kBorderlessGammaMin = 0.5f; + constexpr float kBorderlessGammaMax = 2.0f; + constexpr float kBorderlessGammaDefault = 0.95f; + constexpr float kBorderlessBrightnessMin = 0.5f; + constexpr float kBorderlessBrightnessMax = 2.0f; + constexpr float kBorderlessBrightnessDefault = 1.03f; + constexpr float kBorderlessContrastMin = 0.5f; + constexpr float kBorderlessContrastMax = 2.0f; + constexpr float kBorderlessContrastDefault = 1.0f; + constexpr float kBorderlessSaturationMin = 0.5f; + constexpr float kBorderlessSaturationMax = 2.0f; + constexpr float kBorderlessSaturationDefault = 1.0f; + + constexpr float kSettingsContentWidth = 680.0f; + constexpr float kSettingsBaseContentHeight = 480.0f; + constexpr float kSettingsWindowFrameHorizontal = 18.0f; // 9px left + 9px right + constexpr float kSettingsWindowFrameVertical = 22.0f; // 20px top + 2px bottom + constexpr float kSettingsBottomButtonAreaHeight = 38.0f; + constexpr float kPostFxCheckboxOffset = 24.0f; + constexpr float kSettingsTabHorizontalPadding = 20.0f; + constexpr float kSliderValueReserve = 80.0f; + constexpr float kSettingsSliderExtraAllowance = 0.0f; + constexpr float kSettingsSliderMinWidth = 32.0f; + constexpr float kSliderLabelSpacing = 6.0f; + constexpr float kSliderLeftSpacing = 6.0f; + constexpr float kBrowserColumnSpacing = 18.0f; + constexpr float kBrowserColumnMinWidth = 240.0f; + + float NormalizeSliderValue(float value, float minValue, float maxValue) { - width = std::min(spaceForSlider, preferredWidth + kSettingsSliderExtraAllowance); + if (maxValue <= minValue) + return 0.0f; + return std::clamp((value - minValue) / (maxValue - minValue), 0.0f, 1.0f); } - else if (spaceForSlider > 0.0f) + + float DenormalizeSliderValue(float position, float minValue, float maxValue) { - width = spaceForSlider; + position = std::clamp(position, 0.0f, 1.0f); + return minValue + position * (maxValue - minValue); } - else + + float ComputeSliderWidth(float tabWidth, float sliderX, float preferredWidth, float reservedWidth = kSliderValueReserve) { - width = std::min(preferredWidth, totalAvailable); - } + const float totalAvailable = std::max(0.0f, tabWidth - sliderX); + if (totalAvailable <= 0.0f) + { + return 0.0f; + } - if (width > 0.0f && width < kSettingsSliderMinWidth) - width = std::min(std::max(width, kSettingsSliderMinWidth), totalAvailable); + const float clampedReserve = std::clamp(reservedWidth, 0.0f, totalAvailable); + const float spaceForSlider = totalAvailable - clampedReserve; - return width; -} + float width = 0.0f; + if (spaceForSlider >= preferredWidth) + { + width = std::min(spaceForSlider, preferredWidth + kSettingsSliderExtraAllowance); + } + else if (spaceForSlider > 0.0f) + { + width = spaceForSlider; + } + else + { + width = std::min(preferredWidth, totalAvailable); + } -void FinalizeSliderRow(float tabWidth, - CGUIScrollBar* slider, - CGUILabel* valueLabel, - float preferredWidth, - float labelSpacing = kSliderLabelSpacing, - CGUILabel* textLabel = nullptr) -{ - if (!slider) - return; + if (width > 0.0f && width < kSettingsSliderMinWidth) + width = std::min(std::max(width, kSettingsSliderMinWidth), totalAvailable); - CVector2D sliderPos; - slider->GetPosition(sliderPos); + return width; + } - if (textLabel) + void FinalizeSliderRow(float tabWidth, CGUIScrollBar* slider, CGUILabel* valueLabel, float preferredWidth, float labelSpacing = kSliderLabelSpacing, + CGUILabel* textLabel = nullptr) { - CVector2D textPos; - textLabel->GetPosition(textPos); - CVector2D textSize; - textLabel->GetSize(textSize); - const float minSliderX = textPos.fX + textSize.fX + kSliderLeftSpacing; - if (sliderPos.fX < minSliderX) + if (!slider) + return; + + CVector2D sliderPos; + slider->GetPosition(sliderPos); + + if (textLabel) { - sliderPos.fX = minSliderX; - slider->SetPosition(CVector2D(sliderPos.fX, sliderPos.fY)); + CVector2D textPos; + textLabel->GetPosition(textPos); + CVector2D textSize; + textLabel->GetSize(textSize); + const float minSliderX = textPos.fX + textSize.fX + kSliderLeftSpacing; + if (sliderPos.fX < minSliderX) + { + sliderPos.fX = minSliderX; + slider->SetPosition(CVector2D(sliderPos.fX, sliderPos.fY)); + } } - } - float reservedWidth = 0.0f; - CVector2D labelSize; - if (valueLabel) - { - valueLabel->GetSize(labelSize); - reservedWidth = std::max(0.0f, labelSize.fX + labelSpacing); - } - else - { - reservedWidth = std::max(0.0f, labelSpacing); - } + float reservedWidth = 0.0f; + CVector2D labelSize; + if (valueLabel) + { + valueLabel->GetSize(labelSize); + reservedWidth = std::max(0.0f, labelSize.fX + labelSpacing); + } + else + { + reservedWidth = std::max(0.0f, labelSpacing); + } - const float maxSliderStart = std::max(0.0f, tabWidth - reservedWidth - kSettingsSliderMinWidth); - if (sliderPos.fX > maxSliderStart) - { - sliderPos.fX = maxSliderStart; - slider->SetPosition(CVector2D(sliderPos.fX, sliderPos.fY)); - } + const float maxSliderStart = std::max(0.0f, tabWidth - reservedWidth - kSettingsSliderMinWidth); + if (sliderPos.fX > maxSliderStart) + { + sliderPos.fX = maxSliderStart; + slider->SetPosition(CVector2D(sliderPos.fX, sliderPos.fY)); + } - float targetWidth = ComputeSliderWidth(tabWidth, sliderPos.fX, preferredWidth, reservedWidth); - if (targetWidth <= 0.0f) - targetWidth = std::max(0.0f, tabWidth - sliderPos.fX - reservedWidth); + float targetWidth = ComputeSliderWidth(tabWidth, sliderPos.fX, preferredWidth, reservedWidth); + if (targetWidth <= 0.0f) + targetWidth = std::max(0.0f, tabWidth - sliderPos.fX - reservedWidth); - CVector2D sliderSize; - slider->GetSize(sliderSize); - if (sliderSize.fY <= 0.0f) - sliderSize.fY = 20.0f; - sliderSize.fX = targetWidth; - slider->SetSize(sliderSize); + CVector2D sliderSize; + slider->GetSize(sliderSize); + if (sliderSize.fY <= 0.0f) + sliderSize.fY = 20.0f; + sliderSize.fX = targetWidth; + slider->SetSize(sliderSize); - if (!valueLabel) - return; + if (!valueLabel) + return; - if (labelSize.fX <= 0.0f) - valueLabel->GetSize(labelSize); + if (labelSize.fX <= 0.0f) + valueLabel->GetSize(labelSize); - CVector2D labelPos; - valueLabel->GetPosition(labelPos); - labelPos.fX = sliderPos.fX + targetWidth + labelSpacing; + CVector2D labelPos; + valueLabel->GetPosition(labelPos); + labelPos.fX = sliderPos.fX + targetWidth + labelSpacing; - const float maxLabelX = std::max(0.0f, tabWidth - labelSize.fX); - if (labelPos.fX > maxLabelX) - labelPos.fX = maxLabelX; + const float maxLabelX = std::max(0.0f, tabWidth - labelSize.fX); + if (labelPos.fX > maxLabelX) + labelPos.fX = maxLabelX; - valueLabel->SetPosition(labelPos); -} + valueLabel->SetPosition(labelPos); + } } void CSettings::ResetGuiPointers() @@ -484,7 +481,7 @@ void CSettings::CreateGUI() const float availableContentHeight = resolution.fY - kSettingsWindowFrameVertical; if (availableContentHeight > 0.0f) { - const float minContentHeight = fBottomButtonAreaHeight + 1.0f; // Adjusted for clarity + const float minContentHeight = fBottomButtonAreaHeight + 1.0f; // Adjusted for clarity const float maxContentHeight = std::max(availableContentHeight, minContentHeight); contentSize.fY = std::clamp(kSettingsBaseContentHeight, minContentHeight, maxContentHeight); } @@ -536,7 +533,8 @@ void CSettings::CreateGUI() m_pTabs->SetSelectionHandler(GUI_CALLBACK(&CSettings::OnTabChanged, this)); const float tabHorizontalPadding = kSettingsTabHorizontalPadding; - const auto placeBottomRightButton = [&](CGUIButton* button) { + const auto placeBottomRightButton = [&](CGUIButton* button) + { if (!button) return; CVector2D buttonSize; @@ -628,7 +626,7 @@ void CSettings::CreateGUI() m_pMouseSensitivity->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pMouseSensitivity->GetPosition(vecTemp); const CVector2D mouseSliderPos = vecTemp; - const float mouseSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mouseSliderPos.fX, 160.0f); + const float mouseSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mouseSliderPos.fX, 160.0f); m_pMouseSensitivity->SetSize(CVector2D(mouseSliderWidth, 20.0f)); m_pMouseSensitivity->GetSize(vecSize); m_pMouseSensitivity->SetProperty("StepSize", "0.01"); @@ -649,7 +647,7 @@ void CSettings::CreateGUI() m_pVerticalAimSensitivity->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pVerticalAimSensitivity->GetPosition(vecTemp); const CVector2D verticalSliderPos = vecTemp; - const float verticalSliderWidth = ComputeSliderWidth(tabPanelSize.fX, verticalSliderPos.fX, 160.0f); + const float verticalSliderWidth = ComputeSliderWidth(tabPanelSize.fX, verticalSliderPos.fX, 160.0f); m_pVerticalAimSensitivity->SetSize(CVector2D(verticalSliderWidth, 20.0f)); m_pVerticalAimSensitivity->GetSize(vecSize); m_pVerticalAimSensitivity->SetProperty("StepSize", "0.01"); @@ -657,7 +655,8 @@ void CSettings::CreateGUI() m_pLabelVerticalAimSensitivityValue = reinterpret_cast(pManager->CreateLabel(pTabControls, "0%")); m_pLabelVerticalAimSensitivityValue->SetPosition(CVector2D(verticalSliderPos.fX + vecSize.fX + kSliderLabelSpacing, verticalSliderPos.fY)); m_pLabelVerticalAimSensitivityValue->AutoSize("100%"); - FinalizeSliderRow(tabPanelSize.fX, m_pVerticalAimSensitivity, m_pLabelVerticalAimSensitivityValue, 160.0f, kSliderLabelSpacing, m_pLabelVerticalAimSensitivity); + FinalizeSliderRow(tabPanelSize.fX, m_pVerticalAimSensitivity, m_pLabelVerticalAimSensitivityValue, 160.0f, kSliderLabelSpacing, + m_pLabelVerticalAimSensitivity); vecTemp.fY += 30.f; m_pCheckboxVerticalAimSensitivity = reinterpret_cast(pManager->CreateCheckBox(pTabControls, _("Use mouse sensitivity for aiming"), false)); @@ -740,13 +739,13 @@ void CSettings::CreateGUI() vecTemp.fY += -91; // Layout the mapping buttons like a dual axis joypad - CVector2D vecPosList[] = {CVector2D(162, 202), // Left Stick + CVector2D vecPosList[] = {CVector2D(162, 202), // Left Stick CVector2D(280, 202), CVector2D(221, 182), CVector2D(221, 220), - CVector2D(351, 202), // Right Stick + CVector2D(351, 202), // Right Stick CVector2D(469, 202), CVector2D(410, 182), CVector2D(410, 220), - CVector2D(410, 276), // Acceleration/Brake + CVector2D(410, 276), // Acceleration/Brake CVector2D(221, 276)}; for (int i = 0; i < JoyMan->GetOutputCount() && i < 10; i++) @@ -766,7 +765,7 @@ void CSettings::CreateGUI() pLabel->SetPosition(CVector2D((vecPos.fX + 10) + vecSize.fX * 0.5f - 80.0f, vecPos.fY - 26)); pLabel->SetHorizontalAlign(CGUI_ALIGN_HORIZONTALCENTER); pLabel->SetVerticalAlign(CGUI_ALIGN_VERTICALCENTER); - pLabel->SetVisible(i >= 8); // Hide all labels except 'Acceleration' and 'Brake' + pLabel->SetVisible(i >= 8); // Hide all labels except 'Acceleration' and 'Brake' m_pJoypadLabels.push_back(pLabel); m_pJoypadButtons.push_back(pButton); @@ -852,7 +851,8 @@ void CSettings::CreateGUI() m_pCheckBoxAlwaysShowTransferBox->GetPosition(vecTemp, false); m_pCheckBoxAlwaysShowTransferBox->AutoSize(nullptr, 20.0f); - m_pCheckBoxAllowDiscordRPC = reinterpret_cast(pManager->CreateCheckBox(pTabMultiplayer, _("Allow connecting with Discord Rich Presence"), false)); + m_pCheckBoxAllowDiscordRPC = + reinterpret_cast(pManager->CreateCheckBox(pTabMultiplayer, _("Allow connecting with Discord Rich Presence"), false)); m_pCheckBoxAllowDiscordRPC->SetPosition(CVector2D(vecTemp.fX, vecTemp.fY + 20.0f)); m_pCheckBoxAllowDiscordRPC->GetPosition(vecTemp, false); m_pCheckBoxAllowDiscordRPC->AutoSize(NULL, 20.0f); @@ -863,12 +863,14 @@ void CSettings::CreateGUI() m_pCheckBoxAllowSteamClient->AutoSize(NULL, 20.0f); // Enable camera photos getting saved to documents folder - m_pPhotoSavingCheckbox = reinterpret_cast(pManager->CreateCheckBox(pTabMultiplayer, _("Save photos taken by camera weapon to GTA San Andreas User Files folder"), true)); + m_pPhotoSavingCheckbox = reinterpret_cast( + pManager->CreateCheckBox(pTabMultiplayer, _("Save photos taken by camera weapon to GTA San Andreas User Files folder"), true)); m_pPhotoSavingCheckbox->SetPosition(CVector2D(vecTemp.fX, vecTemp.fY + 20.0f)); m_pPhotoSavingCheckbox->GetPosition(vecTemp, false); m_pPhotoSavingCheckbox->AutoSize(NULL, 20.0f); - m_pCheckBoxAskBeforeDisconnect = reinterpret_cast(pManager->CreateCheckBox(pTabMultiplayer, _("Ask before disconnecting from server using main menu"), true)); + m_pCheckBoxAskBeforeDisconnect = + reinterpret_cast(pManager->CreateCheckBox(pTabMultiplayer, _("Ask before disconnecting from server using main menu"), true)); m_pCheckBoxAskBeforeDisconnect->SetPosition(CVector2D(vecTemp.fX, vecTemp.fY + 20.0f)); m_pCheckBoxAskBeforeDisconnect->GetPosition(vecTemp, false); m_pCheckBoxAskBeforeDisconnect->AutoSize(NULL, 20.0f); @@ -895,7 +897,7 @@ void CSettings::CreateGUI() m_pMapAlpha->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pMapAlpha->GetPosition(vecTemp, false); const CVector2D mapAlphaSliderPos = vecTemp; - const float mapAlphaSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mapAlphaSliderPos.fX, 160.0f); + const float mapAlphaSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mapAlphaSliderPos.fX, 160.0f); m_pMapAlpha->SetSize(CVector2D(mapAlphaSliderWidth, 20.0f)); m_pMapAlpha->GetSize(vecSize); m_pMapAlpha->SetProperty("StepSize", "0.01"); @@ -916,8 +918,8 @@ void CSettings::CreateGUI() m_pPlayerMapImageCombo = reinterpret_cast(pManager->CreateComboBox(pTabMultiplayer, "")); m_pPlayerMapImageCombo->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY - 1.0f)); m_pPlayerMapImageCombo->SetSize(CVector2D(170.f, 95.0f)); - m_pPlayerMapImageCombo->AddItem(_("1024 x 1024 (Default)")); // index 0 - m_pPlayerMapImageCombo->AddItem(_("2048 x 2048")); // index 1 + m_pPlayerMapImageCombo->AddItem(_("1024 x 1024 (Default)")); // index 0 + m_pPlayerMapImageCombo->AddItem(_("2048 x 2048")); // index 1 m_pPlayerMapImageCombo->SetReadOnly(true); /** @@ -941,7 +943,7 @@ void CSettings::CreateGUI() m_pAudioMasterVolume->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAudioMasterVolume->GetPosition(vecTemp, false); const CVector2D masterSliderPos = vecTemp; - const float masterSliderWidth = ComputeSliderWidth(tabPanelSize.fX, masterSliderPos.fX, 160.0f); + const float masterSliderWidth = ComputeSliderWidth(tabPanelSize.fX, masterSliderPos.fX, 160.0f); m_pAudioMasterVolume->SetSize(CVector2D(masterSliderWidth, 20.0f)); m_pAudioMasterVolume->GetSize(vecSize, false); m_pAudioMasterVolume->SetProperty("StepSize", "0.01"); @@ -963,7 +965,7 @@ void CSettings::CreateGUI() m_pAudioRadioVolume->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAudioRadioVolume->GetPosition(vecTemp, false); const CVector2D radioSliderPos = vecTemp; - const float radioSliderWidth = ComputeSliderWidth(tabPanelSize.fX, radioSliderPos.fX, 160.0f); + const float radioSliderWidth = ComputeSliderWidth(tabPanelSize.fX, radioSliderPos.fX, 160.0f); m_pAudioRadioVolume->SetSize(CVector2D(radioSliderWidth, 20.0f)); m_pAudioRadioVolume->GetSize(vecSize, false); m_pAudioRadioVolume->SetProperty("StepSize", "0.01"); @@ -985,7 +987,7 @@ void CSettings::CreateGUI() m_pAudioSFXVolume->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAudioSFXVolume->GetPosition(vecTemp, false); const CVector2D sfxSliderPos = vecTemp; - const float sfxSliderWidth = ComputeSliderWidth(tabPanelSize.fX, sfxSliderPos.fX, 160.0f); + const float sfxSliderWidth = ComputeSliderWidth(tabPanelSize.fX, sfxSliderPos.fX, 160.0f); m_pAudioSFXVolume->SetSize(CVector2D(sfxSliderWidth, 20.0f)); m_pAudioSFXVolume->GetSize(vecSize, false); m_pAudioSFXVolume->SetProperty("StepSize", "0.01"); @@ -1007,7 +1009,7 @@ void CSettings::CreateGUI() m_pAudioMTAVolume->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAudioMTAVolume->GetPosition(vecTemp, false); const CVector2D mtaSliderPos = vecTemp; - const float mtaSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mtaSliderPos.fX, 160.0f); + const float mtaSliderWidth = ComputeSliderWidth(tabPanelSize.fX, mtaSliderPos.fX, 160.0f); m_pAudioMTAVolume->SetSize(CVector2D(mtaSliderWidth, 20.0f)); m_pAudioMTAVolume->GetSize(vecSize, false); m_pAudioMTAVolume->SetProperty("StepSize", "0.01"); @@ -1029,7 +1031,7 @@ void CSettings::CreateGUI() m_pAudioVoiceVolume->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAudioVoiceVolume->GetPosition(vecTemp, false); const CVector2D voiceSliderPos = vecTemp; - const float voiceSliderWidth = ComputeSliderWidth(tabPanelSize.fX, voiceSliderPos.fX, 160.0f); + const float voiceSliderWidth = ComputeSliderWidth(tabPanelSize.fX, voiceSliderPos.fX, 160.0f); m_pAudioVoiceVolume->SetSize(CVector2D(voiceSliderWidth, 20.0f)); m_pAudioVoiceVolume->GetSize(vecSize, false); m_pAudioVoiceVolume->SetProperty("StepSize", "0.01"); @@ -1154,7 +1156,7 @@ void CSettings::CreateGUI() m_pCheckBoxDPIAware->SetPosition(CVector2D(vecTemp.fX + vecSize.fX + 10.0f, vecTemp.fY)); m_pCheckBoxDPIAware->AutoSize(NULL, 20.0f); - m_pVideoResolutionLabel->GetPosition(vecTemp, false); // Restore our label position + m_pVideoResolutionLabel->GetPosition(vecTemp, false); // Restore our label position // Fullscreen mode vecTemp.fY += 26; @@ -1196,7 +1198,7 @@ void CSettings::CreateGUI() m_pFieldOfView->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pFieldOfView->GetPosition(vecTemp, false); const CVector2D fovSliderPos = vecTemp; - const float fovSliderWidth = ComputeSliderWidth(tabPanelSize.fX, fovSliderPos.fX, 160.0f); + const float fovSliderWidth = ComputeSliderWidth(tabPanelSize.fX, fovSliderPos.fX, 160.0f); m_pFieldOfView->SetSize(CVector2D(fovSliderWidth, 20.0f)); m_pFieldOfView->GetSize(vecSize); @@ -1215,7 +1217,7 @@ void CSettings::CreateGUI() m_pDrawDistance->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pDrawDistance->GetPosition(vecTemp, false); const CVector2D drawDistanceSliderPos = vecTemp; - const float drawDistanceSliderWidth = ComputeSliderWidth(tabPanelSize.fX, drawDistanceSliderPos.fX, 160.0f); + const float drawDistanceSliderWidth = ComputeSliderWidth(tabPanelSize.fX, drawDistanceSliderPos.fX, 160.0f); m_pDrawDistance->SetSize(CVector2D(drawDistanceSliderWidth, 20.0f)); m_pDrawDistance->GetSize(vecSize); m_pDrawDistance->SetProperty("StepSize", "0.01"); @@ -1236,7 +1238,7 @@ void CSettings::CreateGUI() m_pBrightness->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pBrightness->GetPosition(vecTemp, false); const CVector2D brightnessSliderPos = vecTemp; - const float brightnessSliderWidth = ComputeSliderWidth(tabPanelSize.fX, brightnessSliderPos.fX, 160.0f); + const float brightnessSliderWidth = ComputeSliderWidth(tabPanelSize.fX, brightnessSliderPos.fX, 160.0f); m_pBrightness->SetSize(CVector2D(brightnessSliderWidth, 20.0f)); m_pBrightness->GetSize(vecSize); m_pBrightness->SetProperty("StepSize", "0.01"); @@ -1271,7 +1273,7 @@ void CSettings::CreateGUI() m_pAnisotropic->SetPosition(CVector2D(vecTemp.fX + fIndentX + 5.0f, vecTemp.fY)); m_pAnisotropic->GetPosition(vecTemp, false); const CVector2D anisotropicSliderPos = vecTemp; - const float anisotropicSliderWidth = ComputeSliderWidth(tabPanelSize.fX, anisotropicSliderPos.fX, 160.0f); + const float anisotropicSliderWidth = ComputeSliderWidth(tabPanelSize.fX, anisotropicSliderPos.fX, 160.0f); m_pAnisotropic->SetSize(CVector2D(anisotropicSliderWidth, 20.0f)); m_pAnisotropic->GetSize(vecSize); m_pAnisotropic->SetProperty("StepSize", SString("%1.2f", 1 / (float)m_iMaxAnisotropic)); @@ -1281,8 +1283,8 @@ void CSettings::CreateGUI() const SString anisotropicOffText = _("Off"); const SString anisotropicMaxText = (m_iMaxAnisotropic > 0) ? SString("%ix", 1 << m_iMaxAnisotropic) : anisotropicOffText; - const float anisotropicOffExtent = pManager->GetTextExtent(anisotropicOffText); - const float anisotropicMaxExtent = pManager->GetTextExtent(anisotropicMaxText); + const float anisotropicOffExtent = pManager->GetTextExtent(anisotropicOffText); + const float anisotropicMaxExtent = pManager->GetTextExtent(anisotropicMaxText); const SString anisotropicSizeHint = (anisotropicMaxExtent > anisotropicOffExtent) ? anisotropicMaxText : anisotropicOffText; const SString anisotropicSizePadding("%s ", anisotropicSizeHint.c_str()); m_pAnisotropicValueLabel->AutoSize(anisotropicSizePadding); @@ -1422,13 +1424,12 @@ void CSettings::CreateGUI() /** * PostFX tab **/ - CVector2D postFxPos(12.0f, 12.0f); + CVector2D postFxPos(12.0f, 12.0f); const float postFxRowHeight = 28.0f; const float postFxValueColumnPadding = 10.0f; const float postFxCheckboxColumnX = postFxPos.fX; const float postFxLabelColumnX = postFxCheckboxColumnX + kPostFxCheckboxOffset; - const float postFxLabelIndent = - pManager->CGUI_GetMaxTextExtent("default-normal", _("Gamma:"), _("Brightness:"), _("Contrast:"), _("Saturation:")) + 5.0f; + const float postFxLabelIndent = pManager->CGUI_GetMaxTextExtent("default-normal", _("Gamma:"), _("Brightness:"), _("Contrast:"), _("Saturation:")) + 5.0f; const float postFxSliderColumnX = postFxLabelColumnX + postFxLabelIndent; const float postFxValueColumnReserve = postFxValueColumnPadding + 60.0f; const float postFxSliderWidth = ComputeSliderWidth(tabPanelSize.fX, postFxSliderColumnX, 220.0f, postFxValueColumnReserve); @@ -1592,24 +1593,26 @@ void CSettings::CreateGUI() m_pGridBrowserBlacklist->SetPosition(CVector2D(vecTemp.fX, vecTemp.fY + 32.0f)); m_pGridBrowserBlacklist->GetPosition(vecTemp); const CVector2D blacklistGridPos = vecTemp; - const float browserBottomPadding = 32.0f; - const float browserButtonSpacing = 5.0f; + const float browserBottomPadding = 32.0f; + const float browserButtonSpacing = 5.0f; const CVector2D blacklistRemoveSize(155.0f, 22.0f); const CVector2D blacklistRemoveAllSize(155.0f, 22.0f); - const float blacklistRemoveAllSpacing = 165.0f; - const float blacklistHeightAvailable = tabPanelSize.fY - blacklistGridPos.fY - blacklistRemoveSize.fY - browserButtonSpacing - browserBottomPadding; + const float blacklistRemoveAllSpacing = 165.0f; + const float blacklistHeightAvailable = tabPanelSize.fY - blacklistGridPos.fY - blacklistRemoveSize.fY - browserButtonSpacing - browserBottomPadding; m_pGridBrowserBlacklist->SetSize(CVector2D(browserColumnWidth, std::max(80.0f, blacklistHeightAvailable))); m_pGridBrowserBlacklist->AddColumn(_("Domain"), 0.9f); m_pButtonBrowserBlacklistRemove = reinterpret_cast(pManager->CreateButton(m_pTabBrowser, _("Remove domain"))); m_pButtonBrowserBlacklistRemove->SetSize(blacklistRemoveSize); - m_pButtonBrowserBlacklistRemove->SetPosition(CVector2D(blacklistGridPos.fX, blacklistGridPos.fY + m_pGridBrowserBlacklist->GetSize().fY + browserButtonSpacing)); + m_pButtonBrowserBlacklistRemove->SetPosition( + CVector2D(blacklistGridPos.fX, blacklistGridPos.fY + m_pGridBrowserBlacklist->GetSize().fY + browserButtonSpacing)); m_pButtonBrowserBlacklistRemoveAll = reinterpret_cast(pManager->CreateButton(m_pTabBrowser, _("Remove all"))); m_pButtonBrowserBlacklistRemoveAll->SetSize(blacklistRemoveAllSize); - m_pButtonBrowserBlacklistRemoveAll->SetPosition(CVector2D(vecTemp.fX + blacklistRemoveAllSpacing, vecTemp.fY + m_pGridBrowserBlacklist->GetSize().fY + browserButtonSpacing)); + m_pButtonBrowserBlacklistRemoveAll->SetPosition( + CVector2D(vecTemp.fX + blacklistRemoveAllSpacing, vecTemp.fY + m_pGridBrowserBlacklist->GetSize().fY + browserButtonSpacing)); - m_pLabelBrowserCustomBlacklist->GetPosition(vecTemp); // Reset vecTemp + m_pLabelBrowserCustomBlacklist->GetPosition(vecTemp); // Reset vecTemp m_pLabelBrowserCustomWhitelist = reinterpret_cast(pManager->CreateLabel(m_pTabBrowser, _("Custom whitelist"))); m_pLabelBrowserCustomWhitelist->SetPosition(CVector2D(browserRightColumnX, vecTemp.fY)); @@ -1640,18 +1643,20 @@ void CSettings::CreateGUI() const CVector2D whitelistGridPos = vecTemp; const CVector2D whitelistRemoveSize(155.0f, 22.0f); const CVector2D whitelistRemoveAllSize(155.0f, 22.0f); - const float whitelistRemoveAllSpacing = 165.0f; - const float whitelistHeightAvailable = tabPanelSize.fY - whitelistGridPos.fY - whitelistRemoveSize.fY - browserButtonSpacing - browserBottomPadding; + const float whitelistRemoveAllSpacing = 165.0f; + const float whitelistHeightAvailable = tabPanelSize.fY - whitelistGridPos.fY - whitelistRemoveSize.fY - browserButtonSpacing - browserBottomPadding; m_pGridBrowserWhitelist->SetSize(CVector2D(browserColumnWidth, std::max(80.0f, whitelistHeightAvailable))); m_pGridBrowserWhitelist->AddColumn(_("Domain"), 0.9f); m_pButtonBrowserWhitelistRemove = reinterpret_cast(pManager->CreateButton(m_pTabBrowser, _("Remove domain"))); m_pButtonBrowserWhitelistRemove->SetSize(whitelistRemoveSize); - m_pButtonBrowserWhitelistRemove->SetPosition(CVector2D(whitelistGridPos.fX, whitelistGridPos.fY + m_pGridBrowserWhitelist->GetSize().fY + browserButtonSpacing)); + m_pButtonBrowserWhitelistRemove->SetPosition( + CVector2D(whitelistGridPos.fX, whitelistGridPos.fY + m_pGridBrowserWhitelist->GetSize().fY + browserButtonSpacing)); m_pButtonBrowserWhitelistRemoveAll = reinterpret_cast(pManager->CreateButton(m_pTabBrowser, _("Remove all"))); m_pButtonBrowserWhitelistRemoveAll->SetSize(whitelistRemoveAllSize); - m_pButtonBrowserWhitelistRemoveAll->SetPosition(CVector2D(vecTemp.fX + whitelistRemoveAllSpacing, vecTemp.fY + m_pGridBrowserWhitelist->GetSize().fY + browserButtonSpacing)); + m_pButtonBrowserWhitelistRemoveAll->SetPosition( + CVector2D(vecTemp.fX + whitelistRemoveAllSpacing, vecTemp.fY + m_pGridBrowserWhitelist->GetSize().fY + browserButtonSpacing)); /** * Advanced tab @@ -1838,7 +1843,7 @@ void CSettings::CreateGUI() // Hide if not Win8 if (atoi(GetApplicationSetting("real-os-version")) != 8) { -#ifndef MTA_DEBUG // Don't hide when debugging +#ifndef MTA_DEBUG // Don't hide when debugging m_pWin8Label->SetVisible(false); m_pWin8ColorCheckBox->SetVisible(false); m_pWin8MouseCheckBox->SetVisible(false); @@ -1866,7 +1871,8 @@ void CSettings::CreateGUI() vecTemp.fY += fLineHeight; // Process affinity - m_pProcessAffinityCheckbox = reinterpret_cast(pManager->CreateCheckBox(pTabAdvanced, _("Set CPU 0 affinity to improve game performance"), true)); + m_pProcessAffinityCheckbox = + reinterpret_cast(pManager->CreateCheckBox(pTabAdvanced, _("Set CPU 0 affinity to improve game performance"), true)); m_pProcessAffinityCheckbox->SetPosition(CVector2D(vecTemp.fX, vecTemp.fY)); m_pProcessAffinityCheckbox->AutoSize(nullptr, 20.0f); vecTemp.fY += fLineHeight; @@ -2362,10 +2368,10 @@ void CSettings::UpdateVideoTab() struct ResolutionData { - int width; - int height; - int depth; - int vidMode; + int width; + int height; + int depth; + int vidMode; bool isWidescreen; }; @@ -2385,13 +2391,13 @@ void CSettings::PopulateResolutionComboBox() if (!gameSettings) return; - VideoMode vidModemInfo; - int vidMode, numVidModes; + VideoMode vidModemInfo; + int vidMode, numVidModes; std::vector resolutions; if (!m_pComboResolution) return; - + m_pComboResolution->Clear(); numVidModes = gameSettings->GetNumVideoModes(); @@ -2428,7 +2434,7 @@ void CSettings::PopulateResolutionComboBox() break; } } - + if (!bDuplicate) resolutions.push_back(resData); } @@ -2437,21 +2443,23 @@ void CSettings::PopulateResolutionComboBox() return; // Sort resolutions by width (descending), then by height, then by depth - std::sort(resolutions.begin(), resolutions.end(), [](const ResolutionData& a, const ResolutionData& b) { - if (a.width != b.width) - return a.width > b.width; - if (a.height != b.height) - return a.height > b.height; - return a.depth > b.depth; - }); - - SString selectedText; + std::sort(resolutions.begin(), resolutions.end(), + [](const ResolutionData& a, const ResolutionData& b) + { + if (a.width != b.width) + return a.width > b.width; + if (a.height != b.height) + return a.height > b.height; + return a.depth > b.depth; + }); + + SString selectedText; VideoMode currentInfo; if (gameSettings->GetVideoModeInfo(¤tInfo, iNextVidMode)) { for (const auto& res : resolutions) { - SString strMode("%d x %d x %d", res.width, res.height, res.depth); + SString strMode("%d x %d x %d", res.width, res.height, res.depth); CGUIListItem* pItem = m_pComboResolution->AddItem(strMode); if (pItem) pItem->SetData((void*)res.vidMode); @@ -2497,12 +2505,12 @@ void CSettings::ProcessJoypad() void CSettings::UpdatePostFxTab() { - bool applyWindowed = false; - bool applyFullscreen = false; - bool gammaEnabled = false; - bool brightnessEnabled = false; - bool contrastEnabled = false; - bool saturationEnabled = false; + bool applyWindowed = false; + bool applyFullscreen = false; + bool gammaEnabled = false; + bool brightnessEnabled = false; + bool contrastEnabled = false; + bool saturationEnabled = false; float gammaValue = kBorderlessGammaDefault; float brightnessValue = kBorderlessBrightnessDefault; float contrastValue = kBorderlessContrastDefault; @@ -2600,8 +2608,8 @@ void CSettings::UpdateJoypadTab() // Update axes labels and buttons for (int i = 0; i < JoyMan->GetOutputCount() && i < (int)m_pJoypadButtons.size(); i++) { - string outputName = JoyMan->GetOutputName(i); // LeftStickPosX etc - string inputName = JoyMan->GetOutputInputName(i); // X+ or RZ- etc + string outputName = JoyMan->GetOutputName(i); // LeftStickPosX etc + string inputName = JoyMan->GetOutputInputName(i); // X+ or RZ- etc CGUILabel* pLabel = m_pJoypadLabels[i]; pLabel->SetText(outputName.c_str()); @@ -2679,7 +2687,7 @@ bool CSettings::OnVideoDefaultClick(CGUIElement* pElement) CVARS_SET("borderless_apply_windowed", false); CVARS_SET("borderless_apply_fullscreen", false); gameSettings->UpdateFieldOfViewFromSettings(); - gameSettings->SetDrawDistance(1.19625f); // All values taken from a default SA install, no gta_sa.set or coreconfig.xml modifications. + gameSettings->SetDrawDistance(1.19625f); // All values taken from a default SA install, no gta_sa.set or coreconfig.xml modifications. gameSettings->SetBrightness(253); gameSettings->SetFXQuality(2); gameSettings->SetAntiAliasing(1, true); @@ -2719,8 +2727,8 @@ void CSettings::RefreshBorderlessDisplayCalibration() void CSettings::UpdateBorderlessAdjustmentControls() { - const bool applyAdjustments = (m_pCheckBoxApplyBorderless && m_pCheckBoxApplyBorderless->GetSelected()) || - (m_pCheckBoxApplyFullscreen && m_pCheckBoxApplyFullscreen->GetSelected()); + const bool applyAdjustments = + (m_pCheckBoxApplyBorderless && m_pCheckBoxApplyBorderless->GetSelected()) || (m_pCheckBoxApplyFullscreen && m_pCheckBoxApplyFullscreen->GetSelected()); const bool gammaEnabled = applyAdjustments && (!m_pBorderlessGammaToggle || m_pBorderlessGammaToggle->GetSelected()); const bool brightnessEnabled = applyAdjustments && (!m_pBorderlessBrightnessToggle || m_pBorderlessBrightnessToggle->GetSelected()); @@ -3522,10 +3530,10 @@ bool CSettings::OnBindsListClick(CGUIElement* pElement) } #ifndef WM_XBUTTONDOWN -#define WM_XBUTTONDOWN 0x020B + #define WM_XBUTTONDOWN 0x020B #endif #ifndef WM_XBUTTONUP -#define WM_XBUTTONUP 0x020C + #define WM_XBUTTONUP 0x020C #endif bool CSettings::ProcessMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) @@ -3629,7 +3637,7 @@ void CSettings::Initialize() if (controlBind->control != pControl) continue; - if (!numMatches) // Primary key + if (!numMatches) // Primary key { // Add bind to the list iBind = m_pBindsList->InsertRowAfter(iRowGame); @@ -3641,7 +3649,7 @@ void CSettings::Initialize() m_pBindsList->SetItemData(iBind, m_hPriKey, controlBind); iGameRowCount++; } - else // Secondary key + else // Secondary key { for (size_t k = 0; k < SecKeyNum; k++) { @@ -3799,7 +3807,7 @@ void CSettings::SetVisible(bool bVisible) { #ifdef MTA_DEBUG if ((GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0) - CreateGUI(); // Recreate GUI (for adjusting layout with edit and continue) + CreateGUI(); // Recreate GUI (for adjusting layout with edit and continue) #endif m_pWindow->BringToFront(); m_pWindow->Activate(); @@ -3812,7 +3820,7 @@ void CSettings::SetVisible(bool bVisible) Initialize(); } - m_pWindow->SetZOrderingEnabled(!bVisible); // Message boxes dont appear on top otherwise + m_pWindow->SetZOrderingEnabled(!bVisible); // Message boxes dont appear on top otherwise } bool CSettings::IsVisible() @@ -4119,7 +4127,7 @@ void CSettings::LoadData() DWORD_PTR sys; HANDLE process = GetCurrentProcess(); - BOOL result = GetProcessAffinityMask(process, &mask, &sys); + BOOL result = GetProcessAffinityMask(process, &mask, &sys); if (bVar && result) SetProcessAffinityMask(process, mask & ~1); @@ -4235,7 +4243,7 @@ void CSettings::ReloadBrowserLists() m_bBrowserListsChanged = false; if (m_bBrowserListsLoadEnabled) { - auto pWebCore = g_pCore->GetWebCore(); + auto pWebCore = g_pCore->GetWebCore(); if (!pWebCore) return; std::vector> customBlacklist; @@ -4566,7 +4574,7 @@ void CSettings::SaveData() DWORD_PTR sys; HANDLE process = GetCurrentProcess(); - BOOL result = GetProcessAffinityMask(process, &mask, &sys); + BOOL result = GetProcessAffinityMask(process, &mask, &sys); if (affinity && result) SetProcessAffinityMask(process, mask & ~1); @@ -4601,7 +4609,7 @@ void CSettings::SaveData() // Player map alpha SString sText = m_pMapAlphaValueLabel->GetText(); - float fMapAlpha = ((atof(sText.substr(0, sText.length() - 1).c_str())) / 100) * 255; + float fMapAlpha = ((atof(sText.substr(0, sText.length() - 1).c_str())) / 100) * 255; CVARS_SET("mapalpha", fMapAlpha); // Player map image @@ -4700,7 +4708,7 @@ void CSettings::SaveData() if (m_bBrowserListsLoadEnabled) { - auto pWebCore = g_pCore->GetWebCore(); + auto pWebCore = g_pCore->GetWebCore(); if (pWebCore) { std::vector customBlacklist; @@ -4893,11 +4901,11 @@ void CSettings::CreateChatColorTab(eChatColorType eType, const char* szName, CGU m_pChatAlphaValue[eType]->AutoSize("255 "); FinalizeSliderRow(tabPanelSize.fX, m_pChatAlpha[eType], m_pChatAlphaValue[eType], chatSliderPreferredWidth, kSliderLabelSpacing, pLabelAlpha); - CVector2D alphaValuePos; - m_pChatAlphaValue[eType]->GetPosition(alphaValuePos); - CVector2D alphaValueSize; - m_pChatAlphaValue[eType]->GetSize(alphaValueSize); - fMarginX = alphaValuePos.fX + alphaValueSize.fX + 30.0f; + CVector2D alphaValuePos; + m_pChatAlphaValue[eType]->GetPosition(alphaValuePos); + CVector2D alphaValueSize; + m_pChatAlphaValue[eType]->GetSize(alphaValueSize); + fMarginX = alphaValuePos.fX + alphaValueSize.fX + 30.0f; } // @@ -5678,7 +5686,7 @@ bool CSettings::OnAllowDiscordRPC(CGUIElement* pElement) g_pCore->GetDiscord()->SetDiscordRPCEnabled(isEnabled); if (isEnabled) - ShowRichPresenceShareDataQuestionBox(); // show question box + ShowRichPresenceShareDataQuestionBox(); // show question box return true; } @@ -5695,7 +5703,7 @@ void CSettings::ShowRichPresenceShareDataQuestionBox() const SStringX strMessage( _("Rich Presence is currently enabled." "\nDo you want to allow data sharing with servers you connect to?" - "\n\nThis includes your Discord client ID, and game state info.")); + "\n\nThis includes your Discord client ID, and game state info.")); CQuestionBox* pQuestionBox = CCore::GetSingleton().GetLocalGUI()->GetMainMenu()->GetQuestionWindow(); pQuestionBox->Reset(); pQuestionBox->SetTitle(_("CONSENT TO ALLOW DATA SHARING")); @@ -5976,7 +5984,7 @@ bool CSettings::OnBrowserWhitelistDomainAddDefocused(CGUIElement* pElement) void NewNicknameCallback(void* ptr, unsigned int uiButton, std::string strNick) { - if (uiButton == 1) // We hit OK + if (uiButton == 1) // We hit OK { if (!CCore::GetSingleton().IsValidNick(strNick.c_str())) CCore::GetSingleton().ShowMessageBox(_("Error") + _E("CC81"), _("Your nickname contains invalid characters!"), MB_BUTTON_OK | MB_ICON_INFO); diff --git a/Client/core/CSettings.h b/Client/core/CSettings.h index 075fa761e64..3c23e99a25d 100644 --- a/Client/core/CSettings.h +++ b/Client/core/CSettings.h @@ -17,9 +17,9 @@ class CSettings; #include "CMainMenu.h" #include "CCore.h" -#define SKINS_PATH "skins/*" -#define CHAT_PRESETS_PATH "mta/config/chatboxpresets.xml" -#define CHAT_PRESETS_ROOT "chatboxpresets" +#define SKINS_PATH "skins/*" +#define CHAT_PRESETS_PATH "mta/config/chatboxpresets.xml" +#define CHAT_PRESETS_ROOT "chatboxpresets" // #define SHOWALLSETTINGS @@ -56,7 +56,7 @@ struct SKeyBindSection if (szOriginalTitle) delete[] szOriginalTitle; } - int currentIndex; // temporarily stores the index while the list is being created + int currentIndex; // temporarily stores the index while the list is being created char* szTitle; char* szOriginalTitle; int rowCount; @@ -123,28 +123,28 @@ class CSettings void ShowRichPresenceShareDataQuestionBox() const; protected: - const static int SecKeyNum = 3; // Number of secondary keys + const static int SecKeyNum = 3; // Number of secondary keys // Keep these protected so we can access them in the event handlers of CClientGame - CGUIElement* m_pWindow; - CGUITabPanel* m_pTabs; - CGUITab* m_pTabMultiplayer; - CGUITab* m_pTabVideo; - CGUITab* m_pTabInterface; - CGUITab* m_pTabBrowser; - CGUITab* m_pTabPostFX; - CGUITab* m_pTabAudio; - CGUITab* m_pTabBinds; - CGUITab* m_pTabControls; - CGUITab* m_pTabAdvanced; - CGUIButton* m_pButtonOK; - CGUIButton* m_pButtonCancel; - CGUILabel* m_pLabelNick; - CGUIButton* m_pButtonGenerateNick; - CGUIStaticImage* m_pButtonGenerateNickIcon; - CGUIEdit* m_pEditNick; - CGUICheckBox* m_pSavePasswords; - CGUICheckBox* m_pAutoRefreshBrowser; + CGUIElement* m_pWindow; + CGUITabPanel* m_pTabs; + CGUITab* m_pTabMultiplayer; + CGUITab* m_pTabVideo; + CGUITab* m_pTabInterface; + CGUITab* m_pTabBrowser; + CGUITab* m_pTabPostFX; + CGUITab* m_pTabAudio; + CGUITab* m_pTabBinds; + CGUITab* m_pTabControls; + CGUITab* m_pTabAdvanced; + CGUIButton* m_pButtonOK; + CGUIButton* m_pButtonCancel; + CGUILabel* m_pLabelNick; + CGUIButton* m_pButtonGenerateNick; + CGUIStaticImage* m_pButtonGenerateNickIcon; + CGUIEdit* m_pEditNick; + CGUICheckBox* m_pSavePasswords; + CGUICheckBox* m_pAutoRefreshBrowser; CGUILabel* m_pVideoGeneralLabel; CGUILabel* m_pVideoResolutionLabel; diff --git a/Client/core/CSteamClient.cpp b/Client/core/CSteamClient.cpp index 23476d4db75..0b18d7d8f53 100644 --- a/Client/core/CSteamClient.cpp +++ b/Client/core/CSteamClient.cpp @@ -49,30 +49,30 @@ using HandleScope = std::unique_ptr, HandleDeleter namespace { -DWORD GetProcessBaseName(HANDLE process, LPWSTR buffer, DWORD bufferLength) -{ - using ModuleBaseNameFn = DWORD(WINAPI*)(HANDLE, HMODULE, LPWSTR, DWORD); - ModuleBaseNameFn moduleBaseNameFn = nullptr; - - if (HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); kernel32 != nullptr) + DWORD GetProcessBaseName(HANDLE process, LPWSTR buffer, DWORD bufferLength) { - if (SharedUtil::TryGetProcAddress(kernel32, "K32GetModuleBaseNameW", moduleBaseNameFn) || - SharedUtil::TryGetProcAddress(kernel32, "GetModuleBaseNameW", moduleBaseNameFn)) + using ModuleBaseNameFn = DWORD(WINAPI*)(HANDLE, HMODULE, LPWSTR, DWORD); + ModuleBaseNameFn moduleBaseNameFn = nullptr; + + if (HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); kernel32 != nullptr) { - return moduleBaseNameFn(process, nullptr, buffer, bufferLength); + if (SharedUtil::TryGetProcAddress(kernel32, "K32GetModuleBaseNameW", moduleBaseNameFn) || + SharedUtil::TryGetProcAddress(kernel32, "GetModuleBaseNameW", moduleBaseNameFn)) + { + return moduleBaseNameFn(process, nullptr, buffer, bufferLength); + } } - } - HMODULE psapi = GetModuleHandleW(L"psapi.dll"); - if (psapi == nullptr) - psapi = LoadLibraryW(L"psapi.dll"); + HMODULE psapi = GetModuleHandleW(L"psapi.dll"); + if (psapi == nullptr) + psapi = LoadLibraryW(L"psapi.dll"); - if (psapi != nullptr && SharedUtil::TryGetProcAddress(psapi, "GetModuleBaseNameW", moduleBaseNameFn)) - return moduleBaseNameFn(process, nullptr, buffer, bufferLength); + if (psapi != nullptr && SharedUtil::TryGetProcAddress(psapi, "GetModuleBaseNameW", moduleBaseNameFn)) + return moduleBaseNameFn(process, nullptr, buffer, bufferLength); - return 0; -} -} // namespace + return 0; + } +} // namespace struct SignerInfo { diff --git a/Client/core/CTrayIcon.cpp b/Client/core/CTrayIcon.cpp index 168aa256f1a..67ed3a5a126 100644 --- a/Client/core/CTrayIcon.cpp +++ b/Client/core/CTrayIcon.cpp @@ -13,10 +13,10 @@ #include #include "resource.h" -#define TRAY_DUMMY_WINDOW_NAME L"NotificationsDummy" -#define TRAY_BALLOON_TITLE L"Notification from MTA:SA server" -#define TRAY_ICON_TOOLTIP_TEXT L"Multi Theft Auto: San Andreas" -#define TRAY_BALLOON_INTERVAL 30000L // ms +#define TRAY_DUMMY_WINDOW_NAME L"NotificationsDummy" +#define TRAY_BALLOON_TITLE L"Notification from MTA:SA server" +#define TRAY_ICON_TOOLTIP_TEXT L"Multi Theft Auto: San Andreas" +#define TRAY_BALLOON_INTERVAL 30000L // ms extern HINSTANCE g_hModule; diff --git a/Client/core/CVersionUpdater.Util.hpp b/Client/core/CVersionUpdater.Util.hpp index 669217ede77..12f83ade156 100644 --- a/Client/core/CVersionUpdater.Util.hpp +++ b/Client/core/CVersionUpdater.Util.hpp @@ -31,8 +31,8 @@ class CVersionUpdater; - https://updatesa.mtasa.com/sa/version/?v=%VERSION%&id=%ID%&ty=%TYPE%&da=%DATA%&be=%BETA%&re=%REFER% https://updatesa.mtasa.com/sa/version/?v=%VERSION%&id=%ID%&ty=%TYPE%&da=%DATA%&be=%BETA%&re=%REFER% https://updatesa.multitheftauto.com/sa/version/?v=%VERSION%&id=%ID%&ty=%TYPE%&da=%DATA%&be=%BETA%&re=%REFER% 12h @@ -133,9 +133,12 @@ namespace BUTTON_3, }; - CQuestionBox& GetQuestionBox() { return *CCore::GetSingleton().GetLocalGUI()->GetMainMenu()->GetQuestionWindow(); } + CQuestionBox& GetQuestionBox() + { + return *CCore::GetSingleton().GetLocalGUI()->GetMainMenu()->GetQuestionWindow(); + } -} // namespace +} // namespace namespace { @@ -656,7 +659,7 @@ namespace } }; -} // namespace +} // namespace namespace { @@ -755,7 +758,7 @@ namespace } }; -} // namespace +} // namespace namespace { @@ -858,7 +861,7 @@ namespace } slim; }; -} // namespace +} // namespace namespace { @@ -883,11 +886,11 @@ namespace CStringPair pair; pair.strValue1 = strValue1.ToLower(); pair.strValue2 = strValue2.ToLower(); - #if MTA_DEBUG +#if MTA_DEBUG CStringPair* pPair = MapFind(*this, strType.ToLower()); if (!pPair || pPair->strValue1 != pair.strValue1 || pPair->strValue2 != pair.strValue2) OutputDebugLine(SString("[Updater] SetCondition %s %s %s", strType.c_str(), strValue1.c_str(), strValue2.c_str())); - #endif +#endif MapSet(*this, strType.ToLower(), pair); } @@ -939,4 +942,4 @@ namespace class ExceptionQuitProgram : public std::exception { }; -} // namespace +} // namespace diff --git a/Client/core/CVersionUpdater.cpp b/Client/core/CVersionUpdater.cpp index cde550d4982..f2035572bfa 100644 --- a/Client/core/CVersionUpdater.cpp +++ b/Client/core/CVersionUpdater.cpp @@ -1152,40 +1152,40 @@ void CVersionUpdater::ProcessCommand(EUpdaterProgramType eProgramType) /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_VersionCheck() { - _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* - _StartDownload(); // Fetch update info from update server + _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* + _StartDownload(); // Fetch update info from update server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.update")) - goto dload; // If update server says 'update' then goto dload + goto dload; // If update server says 'update' then goto dload if (m_ConditionMap.IsConditionTrue("ProcessResponse.files")) - goto dload; // If update server says 'files' then goto dload: + goto dload; // If update server says 'files' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.silent")) - goto silentdload; // If update server says 'silent' then goto silentdload: + goto silentdload; // If update server says 'silent' then goto silentdload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.noupdate")) - goto noupdate; // If update server says 'noupdate' then goto noupdate: + goto noupdate; // If update server says 'noupdate' then goto noupdate: return; dload: - _DialogUpdateQuestion(); // Show "Update available" dialog + _DialogUpdateQuestion(); // Show "Update available" dialog if (m_ConditionMap.IsConditionTrue("QuestionResponse.!Yes")) - goto end; // If user says 'No', then goto end: - _DialogDownloading(); // Show "Downloading..." message + goto end; // If user says 'No', then goto end: + _DialogDownloading(); // Show "Downloading..." message _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _DialogUpdateResult(); // Show "Update ok/failed" message + _DialogUpdateResult(); // Show "Update ok/failed" message return; silentdload: _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _QUpdateResult(); // Maybe set OnRestartCommand + _QUpdateResult(); // Maybe set OnRestartCommand return; noupdate: - _ResetVersionCheckTimer(); // Wait 24hrs before checking again + _ResetVersionCheckTimer(); // Wait 24hrs before checking again return; end: @@ -1202,37 +1202,37 @@ void CVersionUpdater::Program_VersionCheck() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_ManualCheck() { - _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* - _DialogChecking(); // Show "Checking..." message - _StartDownload(); // Fetch update info from update server + _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* + _DialogChecking(); // Show "Checking..." message + _StartDownload(); // Fetch update info from update server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.update")) - goto dload; // If update server says 'update' then goto dload: + goto dload; // If update server says 'update' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.files")) - goto dload; // If update server says 'files' then goto dload: + goto dload; // If update server says 'files' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.silent")) - goto dload; // If update server says 'silent' then goto dload: + goto dload; // If update server says 'silent' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.noupdate")) - goto noupdate; // If update server says 'noupdate' then goto noupdate: + goto noupdate; // If update server says 'noupdate' then goto noupdate: if (m_ConditionMap.IsConditionTrue("ProcessResponse.cancel")) goto end; _DialogUpdateQueryError(); return; dload: - _DialogUpdateQuestion(); // Show "Update available" dialog + _DialogUpdateQuestion(); // Show "Update available" dialog if (m_ConditionMap.IsConditionTrue("QuestionResponse.!Yes")) - goto end; // If user says 'No', then goto end: - _DialogDownloading(); // Show "Downloading..." message + goto end; // If user says 'No', then goto end: + _DialogDownloading(); // Show "Downloading..." message _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _DialogUpdateResult(); // Show "Update ok/failed" message + _DialogUpdateResult(); // Show "Update ok/failed" message return; noupdate: - _ResetManualCheckTimer(); // Wait 1min before checking again - _DialogNoUpdate(); // Show "No update available" dialog + _ResetManualCheckTimer(); // Wait 1min before checking again + _DialogNoUpdate(); // Show "No update available" dialog return; end: @@ -1248,7 +1248,7 @@ void CVersionUpdater::Program_ManualCheck() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_ManualCheckSim() { - _DialogNoUpdate(); // Show "No update available" dialog + _DialogNoUpdate(); // Show "No update available" dialog return; } @@ -1261,28 +1261,28 @@ void CVersionUpdater::Program_ManualCheckSim() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_ServerSaysUpdate() { - _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* - _DialogServerSaysUpdateQuestion(); // Show "Server says update" dialog + _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* + _DialogServerSaysUpdateQuestion(); // Show "Server says update" dialog if (m_ConditionMap.IsConditionTrue("QuestionResponse.!Yes")) - goto end; // If user says 'No', then goto end: - _DialogChecking(); // Show "Checking..." message - _StartDownload(); // Fetch update info from update server + goto end; // If user says 'No', then goto end: + _DialogChecking(); // Show "Checking..." message + _StartDownload(); // Fetch update info from update server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.update")) - goto dload; // If update server says 'update' then goto dload: + goto dload; // If update server says 'update' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.files")) - goto dload; // If update server says 'files' then goto dload: + goto dload; // If update server says 'files' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.silent")) - goto dload; // If update server says 'silent' then goto dload: + goto dload; // If update server says 'silent' then goto dload: _DialogUpdateQueryError(); return; dload: - _DialogDownloading(); // Show "Downloading..." message + _DialogDownloading(); // Show "Downloading..." message _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _DialogUpdateResult(); // Show "Update ok/failed" message + _DialogUpdateResult(); // Show "Update ok/failed" message return; end: @@ -1298,37 +1298,37 @@ void CVersionUpdater::Program_ServerSaysUpdate() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_ServerSaysRecommend() { - _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* - _DialogConnectingWait(); // Show "Please wait..." message - _StartDownload(); // Fetch update info from update server + _UseVersionQueryURLs(); // Use VERSION_CHECKER_URL* + _DialogConnectingWait(); // Show "Please wait..." message + _StartDownload(); // Fetch update info from update server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.update")) - goto dload; // If update server says 'update' then goto dload: + goto dload; // If update server says 'update' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.files")) - goto dload; // If update server says 'files' then goto dload: + goto dload; // If update server says 'files' then goto dload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.silent")) - goto silentdload; // If update server says 'silent' then goto silentdload: + goto silentdload; // If update server says 'silent' then goto silentdload: _ActionReconnect(); return; dload: - _DialogServerSaysRecommendQuestion(); // Show "Server says update" dialog + _DialogServerSaysRecommendQuestion(); // Show "Server says update" dialog if (m_ConditionMap.IsConditionTrue("QuestionResponse.!Yes")) - goto reconnect; // If user says 'No', then goto reconnect: - _DialogDownloading(); // Show "Downloading..." message + goto reconnect; // If user says 'No', then goto reconnect: + _DialogDownloading(); // Show "Downloading..." message _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _DialogUpdateResult(); // Show "Update ok/failed" message + _DialogUpdateResult(); // Show "Update ok/failed" message return; silentdload: - _DialogHide(); // Don't show downloading progress - _ActionReconnect(); // Reconnect to game + _DialogHide(); // Don't show downloading progress + _ActionReconnect(); // Reconnect to game _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _QUpdateResult(); // Maybe set OnRestartCommand + _QUpdateResult(); // Maybe set OnRestartCommand return; reconnect: @@ -1358,8 +1358,8 @@ void CVersionUpdater::Program_ServerSaysDataFilesWrong() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_MasterFetch() { - _UseMasterFetchURLs(); // Use VERSION_CHECKER_URL* - _StartDownload(); // Fetch file info from server + _UseMasterFetchURLs(); // Use VERSION_CHECKER_URL* + _StartDownload(); // Fetch file info from server _ProcessMasterFetch(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.!ok")) goto error1; @@ -1380,21 +1380,21 @@ void CVersionUpdater::Program_MasterFetch() void CVersionUpdater::Program_SendCrashDump() { bool bUploadSuccess = false; // Declare before any goto targets - - _ShouldSendCrashDump(); // Have we already sent a matching dump? + + _ShouldSendCrashDump(); // Have we already sent a matching dump? if (m_ConditionMap.IsConditionTrue("ProcessResponse.!ok")) goto end; _UseCrashDumpQueryURLs(); _StartDownload(); - _ProcessCrashDumpQuery(); // Does the server want this dump? + _ProcessCrashDumpQuery(); // Does the server want this dump? if (m_ConditionMap.IsConditionTrue("ProcessResponse.!ok")) goto end; - _UseCrashDumpURLs(); // Use CRASH_DUMP_URL* - _UseCrashDumpPostContent(); // Use crash dump source - + _UseCrashDumpURLs(); // Use CRASH_DUMP_URL* + _UseCrashDumpPostContent(); // Use crash dump source + // Send data and check if upload succeeded bUploadSuccess = _StartSendPost(); - + if (bUploadSuccess) { // Upload succeeded - clear all settings to prevent duplicate sends @@ -1407,25 +1407,25 @@ void CVersionUpdater::Program_SendCrashDump() { // Upload failed - retry with backoff const int MAX_UPLOAD_RETRIES = 3; - int iCurrentRetry = GetApplicationSettingInt("diagnostics", "last-dump-load-retry"); - + int iCurrentRetry = GetApplicationSettingInt("diagnostics", "last-dump-load-retry"); + if (iCurrentRetry < MAX_UPLOAD_RETRIES) { iCurrentRetry++; SetApplicationSettingInt("diagnostics", "last-dump-load-retry", iCurrentRetry); - + // Store timestamp as string for backoff enforcement (prevents int overflow) const long long llCurrentTimeSec = GetTickCount64_() / 1000; SetApplicationSetting("diagnostics", "last-dump-retry-time", SString("%lld", llCurrentTimeSec)); - + // Calculate backoff delay int iBackoffSeconds = 5; for (int i = 1; i < iCurrentRetry; i++) iBackoffSeconds *= 3; - - AddReportLog(9320, SString("Program_SendCrashDump: Upload failed (attempt %d/%d) - Will retry in %d seconds", - iCurrentRetry, MAX_UPLOAD_RETRIES, iBackoffSeconds)); - + + AddReportLog(9320, SString("Program_SendCrashDump: Upload failed (attempt %d/%d) - Will retry in %d seconds", iCurrentRetry, MAX_UPLOAD_RETRIES, + iBackoffSeconds)); + // Reset flag to allow retry on next pulse m_bSentCrashDump = false; } @@ -1437,7 +1437,7 @@ void CVersionUpdater::Program_SendCrashDump() } } return; - + end: // Only reset if we're not retrying int iRetryCount = GetApplicationSettingInt("diagnostics", "last-dump-load-retry"); @@ -1466,9 +1466,9 @@ void CVersionUpdater::Program_SendCrashDump() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_SendReportLog() { - _UseReportLogURLs(); // Use REPORT_LOG_URL* - _UseReportLogPostContent(); // Use report log source - _StartSendPost(); // Send data + _UseReportLogURLs(); // Use REPORT_LOG_URL* + _UseReportLogPostContent(); // Use report log source + _StartSendPost(); // Send data } /////////////////////////////////////////////////////////////// @@ -1480,37 +1480,37 @@ void CVersionUpdater::Program_SendReportLog() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_SidegradeLaunch() { - _CheckSidegradeRequirements(); // Check if other version already installed + _CheckSidegradeRequirements(); // Check if other version already installed if (m_ConditionMap.IsConditionTrue("ProcessResponse.!installed")) - goto notinstalled; // Other version present and valid? - _DialogSidegradeLaunchQuestion(); // Does user want to launch and connect using the other version? + goto notinstalled; // Other version present and valid? + _DialogSidegradeLaunchQuestion(); // Does user want to launch and connect using the other version? if (m_ConditionMap.IsConditionTrue("QuestionResponse.!Yes")) goto nolaunch; - _DoSidegradeLaunch(); // If user says 'Yes', then launch + _DoSidegradeLaunch(); // If user says 'Yes', then launch nolaunch: return; notinstalled: - _UseSidegradeURLs(); // Use sidegrade URLs - _StartDownload(); // Fetch file info from server + _UseSidegradeURLs(); // Use sidegrade URLs + _StartDownload(); // Fetch file info from server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.update")) - goto hasfile; // Does server have the required file? - _DialogSidegradeQueryError(); // If no download available, show message + goto hasfile; // Does server have the required file? + _DialogSidegradeQueryError(); // If no download available, show message return; hasfile: - _DialogSidegradeDownloadQuestion(); // If it is downloadable, ask user what to do + _DialogSidegradeDownloadQuestion(); // If it is downloadable, ask user what to do if (m_ConditionMap.IsConditionTrue("QuestionResponse.Yes")) goto yesdownload; - return; // If user says 'No', then finish + return; // If user says 'No', then finish yesdownload: - _DialogDownloading(); // Show "Downloading..." message + _DialogDownloading(); // Show "Downloading..." message _UseProvidedURLs(); - _StartDownload(); // Fetch file binary from mirror + _StartDownload(); // Fetch file binary from mirror _ProcessPatchFileDownload(); - _DialogExeFilesResult(); // Show "ok/failed" message + _DialogExeFilesResult(); // Show "ok/failed" message return; } @@ -1523,24 +1523,24 @@ void CVersionUpdater::Program_SidegradeLaunch() /////////////////////////////////////////////////////////////// void CVersionUpdater::Program_NewsUpdate() { - _UseNewsUpdateURLs(); // Use news serverlist - _StartDownload(); // Fetch update info from update server + _UseNewsUpdateURLs(); // Use news serverlist + _StartDownload(); // Fetch update info from update server _ProcessPatchFileQuery(); if (m_ConditionMap.IsConditionTrue("ProcessResponse.silent")) - goto silentdload; // If update server says 'silent' then goto silentdload: + goto silentdload; // If update server says 'silent' then goto silentdload: if (m_ConditionMap.IsConditionTrue("ProcessResponse.noupdate")) - goto noupdate; // If update server says 'noupdate' then goto noupdate: + goto noupdate; // If update server says 'noupdate' then goto noupdate: return; silentdload: _UseProvidedURLs(); - _StartDownload(); // Fetch update binary from update mirror + _StartDownload(); // Fetch update binary from update mirror _ProcessPatchFileDownload(); - _QUpdateNewsResult(); // Maybe update news install queue + _QUpdateNewsResult(); // Maybe update news install queue return; noupdate: - _ResetNewsCheckTimer(); // Wait interval before checking again + _ResetNewsCheckTimer(); // Wait interval before checking again return; } @@ -2375,7 +2375,7 @@ void CVersionUpdater::_ProcessPatchFileQuery() // If version check file says there is a new master config file, force update next time m_VarConfig.master_lastCheckTime.SetFromSeconds(0); if (m_JobInfo.strStatus == "noupdate") - OnPossibleConfigProblem(); // Do it this time if no update here + OnPossibleConfigProblem(); // Do it this time if no update here } } @@ -2832,8 +2832,9 @@ int CVersionUpdater::_PollDownload() } if (m_JobInfo.bShowDownloadPercent) { - const bool bIsDownloadedSizeRight = m_JobInfo.uiBytesDownloaded > 0 && static_cast(m_JobInfo.iFilesize) >= m_JobInfo.uiBytesDownloaded; - const int fDownloadedPercent = bIsDownloadedSizeRight ? Round((float)m_JobInfo.uiBytesDownloaded / m_JobInfo.iFilesize * 100.f) : 0; + const bool bIsDownloadedSizeRight = + m_JobInfo.uiBytesDownloaded > 0 && static_cast(m_JobInfo.iFilesize) >= m_JobInfo.uiBytesDownloaded; + const int fDownloadedPercent = bIsDownloadedSizeRight ? Round((float)m_JobInfo.uiBytesDownloaded / m_JobInfo.iFilesize * 100.f) : 0; GetQuestionBox().SetMessage(SString(_("%3d %% completed"), fDownloadedPercent)); } if (m_JobInfo.iIdleTime > 1000 && m_JobInfo.iIdleTimeLeft > 500) @@ -2902,7 +2903,6 @@ void CVersionUpdater::_UseReportLogPostContent() GetReportWrap()->ClearLogContents("-all"); } - int CVersionUpdater::ValidateCrashDumpPath(const SString& strPathFilename, SString* pOutErrorMsg, bool bCheckFileExists) { // Constants for validation with constexpr for compile-time evaluation @@ -2911,7 +2911,7 @@ int CVersionUpdater::ValidateCrashDumpPath(const SString& strPathFilename, SStri constexpr size_t MAX_PATH_COMPONENTS = 256; constexpr size_t PATH_PARTS_RESERVE = 32; constexpr size_t MAX_DUMP_FILE_SIZE_MB = MAX_DUMP_FILE_SIZE / (1024 * 1024); - + if (const size_t pathLength = strPathFilename.length(); pathLength > MAX_PATH_LENGTH) { if (pOutErrorMsg) @@ -2926,19 +2926,19 @@ int CVersionUpdater::ValidateCrashDumpPath(const SString& strPathFilename, SStri return 9315; } - - auto validatePathParts = [&](const SString& separator) noexcept -> int { + auto validatePathParts = [&](const SString& separator) noexcept -> int + { std::vector pathParts; pathParts.reserve(PATH_PARTS_RESERVE); strPathFilename.Split(separator, pathParts); - + if (const size_t numParts = pathParts.size(); numParts > MAX_PATH_COMPONENTS) { if (pOutErrorMsg) *pOutErrorMsg = SString("Too many path components (%d > %d)", numParts, MAX_PATH_COMPONENTS); return 9315; } - + for (const auto& part : pathParts) { if (part == "..") @@ -2950,10 +2950,10 @@ int CVersionUpdater::ValidateCrashDumpPath(const SString& strPathFilename, SStri } return 0; }; - + if (const int result = validatePathParts(PATH_SEPERATOR); result != 0) return result; - + if (const bool hasForwardSlash = strPathFilename.Contains("/"); hasForwardSlash) { if (const int result = validatePathParts("/"); result != 0) @@ -2977,12 +2977,11 @@ int CVersionUpdater::ValidateCrashDumpPath(const SString& strPathFilename, SStri *pOutErrorMsg = "Failed to seek in file"; return 9317; } - + const long fileSize = ftell(pFile); fclose(pFile); - if (const bool isInvalidSize = fileSize < 0 || static_cast(fileSize) > MAX_DUMP_FILE_SIZE; - isInvalidSize) + if (const bool isInvalidSize = fileSize < 0 || static_cast(fileSize) > MAX_DUMP_FILE_SIZE; isInvalidSize) { if (pOutErrorMsg) *pOutErrorMsg = SString("File too large (%d bytes, max %d MB)", fileSize, MAX_DUMP_FILE_SIZE_MB); @@ -3011,11 +3010,10 @@ void CVersionUpdater::_ShouldSendCrashDump() constexpr const char* PROCESS_RESPONSE = "ProcessResponse"; constexpr const char* RESPONSE_OK = "ok"; constexpr const char* EMPTY_VALUE = ""; - + m_ConditionMap.SetCondition(PROCESS_RESPONSE, EMPTY_VALUE); - if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); - strPathFilename.empty()) + if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); strPathFilename.empty()) { return; } @@ -3028,10 +3026,9 @@ void CVersionUpdater::_ShouldSendCrashDump() return; } - SString strFilename; strPathFilename.Split(PATH_SEPERATOR, nullptr, &strFilename, -1); - + // constexpr validation constants for compile-time evaluation constexpr size_t MAX_FILENAME_LENGTH = 2048; constexpr size_t MAX_FILENAME_PARTS = 64; @@ -3039,67 +3036,58 @@ void CVersionUpdater::_ShouldSendCrashDump() constexpr size_t MAX_TAG_LENGTH = 1024; constexpr size_t MAX_DATETIME_LENGTH = 256; constexpr size_t MAX_HISTORY_SIZE = 100000; - constexpr int MAX_DUPLICATE_COUNT = 10000; + constexpr int MAX_DUPLICATE_COUNT = 10000; if (const size_t filenameLength = strFilename.length(); filenameLength > MAX_FILENAME_LENGTH) { - AddReportLog(9325, SString("_ShouldSendCrashDump: Filename too long (%d > %d)", - filenameLength, MAX_FILENAME_LENGTH)); + AddReportLog(9325, SString("_ShouldSendCrashDump: Filename too long (%d > %d)", filenameLength, MAX_FILENAME_LENGTH)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; } std::vector parts; - parts.reserve(PARTS_RESERVE); + parts.reserve(PARTS_RESERVE); strFilename.Split("_", parts); - if (const size_t numParts = parts.size(); numParts > MAX_FILENAME_PARTS) { - AddReportLog(9315, SString("_ShouldSendCrashDump: Too many filename parts (%d > %d)", - numParts, MAX_FILENAME_PARTS)); + AddReportLog(9315, SString("_ShouldSendCrashDump: Too many filename parts (%d > %d)", numParts, MAX_FILENAME_PARTS)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; - } - - if (const size_t maxRequiredIndex = std::max({DUMP_PART_VERSION, DUMP_PART_MODULE, DUMP_PART_OFFSET, - DUMP_PART_DATE, DUMP_PART_TIME}); + } + + if (const size_t maxRequiredIndex = std::max({DUMP_PART_VERSION, DUMP_PART_MODULE, DUMP_PART_OFFSET, DUMP_PART_DATE, DUMP_PART_TIME}); parts.size() <= maxRequiredIndex) { - AddReportLog(9313, SString("_ShouldSendCrashDump: Insufficient filename parts (parts=%d, max index=%d)", - parts.size(), maxRequiredIndex)); + AddReportLog(9313, SString("_ShouldSendCrashDump: Insufficient filename parts (parts=%d, max index=%d)", parts.size(), maxRequiredIndex)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; - } + } + + const SString strVersionAndModuleAndOffset = parts[DUMP_PART_VERSION] + "_" + parts[DUMP_PART_MODULE] + "_" + parts[DUMP_PART_OFFSET]; - const SString strVersionAndModuleAndOffset = - parts[DUMP_PART_VERSION] + "_" + parts[DUMP_PART_MODULE] + "_" + parts[DUMP_PART_OFFSET]; - if (const size_t tagLength = strVersionAndModuleAndOffset.length(); tagLength > MAX_TAG_LENGTH) { - AddReportLog(9326, SString("_ShouldSendCrashDump: Tag too long (%d > %d)", - tagLength, MAX_TAG_LENGTH)); + AddReportLog(9326, SString("_ShouldSendCrashDump: Tag too long (%d > %d)", tagLength, MAX_TAG_LENGTH)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; - } - + } + SString strDateAndTime = parts[DUMP_PART_DATE] + "_" + parts[DUMP_PART_TIME]; strDateAndTime.Split(".", &strDateAndTime, nullptr); // Remove .dmp extension from time part if (const size_t dateTimeLength = strDateAndTime.length(); dateTimeLength > MAX_DATETIME_LENGTH) { - AddReportLog(9327, SString("_ShouldSendCrashDump: Date/time string too long (%d > %d)", - dateTimeLength, MAX_DATETIME_LENGTH)); + AddReportLog(9327, SString("_ShouldSendCrashDump: Date/time string too long (%d > %d)", dateTimeLength, MAX_DATETIME_LENGTH)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; } CDataInfoSet& history = m_VarConfig.crashdump_history; - + if (const size_t historySize = history.size(); historySize > MAX_HISTORY_SIZE) { - AddReportLog(9318, SString("_ShouldSendCrashDump: History size limit exceeded (%d > %d)", - historySize, MAX_HISTORY_SIZE)); + AddReportLog(9318, SString("_ShouldSendCrashDump: History size limit exceeded (%d > %d)", historySize, MAX_HISTORY_SIZE)); // Aggressively trim to half of max size with explicit calculation constexpr size_t TRIM_TO_RATIO = 2; // Keep half when trimming history.erase(history.begin(), history.begin() + (historySize - MAX_HISTORY_SIZE / TRIM_TO_RATIO)); @@ -3120,17 +3108,15 @@ void CVersionUpdater::_ShouldSendCrashDump() } } - if (const int duplicateLimit = static_cast(m_MasterConfig.crashdump.iDuplicates); - iDuplicates > duplicateLimit) + if (const int duplicateLimit = static_cast(m_MasterConfig.crashdump.iDuplicates); iDuplicates > duplicateLimit) { - AddReportLog(9314, SString("_ShouldSendCrashDump: Duplicate limit reached (%d/%d)", - iDuplicates, duplicateLimit)); + AddReportLog(9314, SString("_ShouldSendCrashDump: Duplicate limit reached (%d/%d)", iDuplicates, duplicateLimit)); return; } SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_TAG, strVersionAndModuleAndOffset); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_DATETIME, strDateAndTime); - + m_ConditionMap.SetCondition(PROCESS_RESPONSE, RESPONSE_OK); } } @@ -3164,18 +3150,17 @@ void CVersionUpdater::_UseCrashDumpQueryURLs() constexpr const char* DIAGNOSTICS_SECTION = "diagnostics"; constexpr const char* LAST_DUMP_SAVE = "last-dump-save"; constexpr const char* EMPTY_VALUE = ""; - - constexpr size_t MAX_POST_FILENAME_LENGTH = 1024; + + constexpr size_t MAX_POST_FILENAME_LENGTH = 1024; constexpr unsigned char CONTROL_CHAR_THRESHOLD = 32; constexpr unsigned char DELETE_CHAR = 127; - constexpr char REPLACEMENT_CHAR = '_'; - + constexpr char REPLACEMENT_CHAR = '_'; + // Initialize job info with server list m_JobInfo = SJobInfo(); m_JobInfo.serverList = MakeServerList(m_MasterConfig.crashdump.serverInfoMap); - if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); - strPathFilename.empty()) + if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); strPathFilename.empty()) { return; } @@ -3191,28 +3176,25 @@ void CVersionUpdater::_UseCrashDumpQueryURLs() // Extract filename from path SString strFilename; strPathFilename.Split(PATH_SEPERATOR, nullptr, &strFilename, -1); - - if (const size_t queryFilenameLength = strFilename.length(); - queryFilenameLength > MAX_POST_FILENAME_LENGTH) + + if (const size_t queryFilenameLength = strFilename.length(); queryFilenameLength > MAX_POST_FILENAME_LENGTH) { - AddReportLog(9328, SString("_UseCrashDumpQueryURLs: Filename too long (%d > %d)", - queryFilenameLength, MAX_POST_FILENAME_LENGTH)); + AddReportLog(9328, SString("_UseCrashDumpQueryURLs: Filename too long (%d > %d)", queryFilenameLength, MAX_POST_FILENAME_LENGTH)); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE, EMPTY_VALUE); return; - } - - const auto is_control_char = [CONTROL_CHAR_THRESHOLD, DELETE_CHAR](unsigned char c) noexcept -> bool { - return c < CONTROL_CHAR_THRESHOLD || c == DELETE_CHAR; - }; + } + + const auto is_control_char = [CONTROL_CHAR_THRESHOLD, DELETE_CHAR](unsigned char c) noexcept -> bool + { return c < CONTROL_CHAR_THRESHOLD || c == DELETE_CHAR; }; SString strSanitizedFilename = strFilename; - + for (auto& ch : strSanitizedFilename) { if (is_control_char(static_cast(ch))) ch = REPLACEMENT_CHAR; } - + m_JobInfo.strPostFilename = strSanitizedFilename; } } @@ -3236,9 +3218,9 @@ void CVersionUpdater::_ProcessCrashDumpQuery() constexpr const char* DUMP_ITEM_NAME = "dump"; constexpr const char* TAG_ATTRIBUTE = "tag"; constexpr const char* DATE_ATTRIBUTE = "date"; - + constexpr size_t MAX_RESPONSE_SIZE = 10 * 1024 * 1024; - + m_ConditionMap.SetCondition(PROCESS_RESPONSE, EMPTY_VALUE); // Early return if no download buffer @@ -3247,8 +3229,7 @@ void CVersionUpdater::_ProcessCrashDumpQuery() if (const size_t responseSize = m_JobInfo.downloadBuffer.size(); responseSize > MAX_RESPONSE_SIZE) { - AddReportLog(9319, SString("_ProcessCrashDumpQuery: Response too large (%d > %d)", - responseSize, MAX_RESPONSE_SIZE)); + AddReportLog(9319, SString("_ProcessCrashDumpQuery: Response too large (%d > %d)", responseSize, MAX_RESPONSE_SIZE)); return; } @@ -3259,47 +3240,44 @@ void CVersionUpdater::_ProcessCrashDumpQuery() { // Server confirmed it wants the dump - retrieve metadata if (const SString strTag = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_TAG), - strDateTime = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_DATETIME); + strDateTime = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_DATETIME); !strTag.empty() && !strDateTime.empty()) { CDataInfoSet& history = m_VarConfig.crashdump_history; - + // Add to history SDataInfoItem item; item.strName = DUMP_ITEM_NAME; item.SetAttribute(TAG_ATTRIBUTE, strTag); item.SetAttribute(DATE_ATTRIBUTE, strDateTime); history.push_back(item); - + // Trim history if needed - if (const size_t historySize = history.size(); - historySize > static_cast(m_MasterConfig.crashdump.iMaxHistoryLength)) + if (const size_t historySize = history.size(); historySize > static_cast(m_MasterConfig.crashdump.iMaxHistoryLength)) { // Lambda for date comparison (GetAttribute is evaluated at runtime) - auto date_comparator = [](const SDataInfoItem& a, const SDataInfoItem& b) noexcept -> bool { - return a.GetAttribute("date") < b.GetAttribute("date"); - }; + auto date_comparator = [](const SDataInfoItem& a, const SDataInfoItem& b) noexcept -> bool + { return a.GetAttribute("date") < b.GetAttribute("date"); }; std::sort(history.begin(), history.end(), date_comparator); - + // Remove oldest entries // Note: If numToRemove exceeds MAX_HISTORY_EXCESS, trim to safe limit to prevent oversized history - if (const size_t numToRemove = historySize - m_MasterConfig.crashdump.iMaxHistoryLength; - numToRemove > 0) + if (const size_t numToRemove = historySize - m_MasterConfig.crashdump.iMaxHistoryLength; numToRemove > 0) { constexpr size_t MAX_HISTORY_EXCESS = 1000; - const size_t actualRemove = (numToRemove > MAX_HISTORY_EXCESS) ? (historySize - MAX_HISTORY_EXCESS) : numToRemove; + const size_t actualRemove = (numToRemove > MAX_HISTORY_EXCESS) ? (historySize - MAX_HISTORY_EXCESS) : numToRemove; history.erase(history.begin(), history.begin() + actualRemove); } } - + // Save config CCore::GetSingleton().SaveConfig(); - + // Clear metadata settings using constexpr string literals SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_TAG, EMPTY_VALUE); SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_DATETIME, EMPTY_VALUE); } - + m_ConditionMap.SetCondition(PROCESS_RESPONSE, RESPONSE_OK); } else @@ -3341,26 +3319,24 @@ void CVersionUpdater::_UseCrashDumpPostContent() constexpr const char* LAST_DUMP_LOAD_RETRY = "last-dump-load-retry"; constexpr const char* LAST_DUMP_RETRY_TIME = "last-dump-retry-time"; constexpr const char* LOG_PREFIX = "_UseCrashDumpPostContent: "; - - constexpr size_t MAX_POST_FILENAME_LENGTH = 1024; - constexpr size_t MAX_POST_CONTENT_SIZE = 2 * 1024 * 1024; // 2 MB for minidumps - constexpr int MAX_LOAD_RETRIES = 3; - constexpr int INITIAL_BACKOFF_SECONDS = 5; - constexpr int BACKOFF_MULTIPLIER = 3; + + constexpr size_t MAX_POST_FILENAME_LENGTH = 1024; + constexpr size_t MAX_POST_CONTENT_SIZE = 2 * 1024 * 1024; // 2 MB for minidumps + constexpr int MAX_LOAD_RETRIES = 3; + constexpr int INITIAL_BACKOFF_SECONDS = 5; + constexpr int BACKOFF_MULTIPLIER = 3; constexpr uint32_t MDMP_SIGNATURE = 0x504D444D; // "MDMP" in little-endian - constexpr size_t MIN_SIGNATURE_SIZE = sizeof(uint32_t); - constexpr int MILLISECONDS_PER_SECOND = 1000; - - if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); - strPathFilename.empty()) + constexpr size_t MIN_SIGNATURE_SIZE = sizeof(uint32_t); + constexpr int MILLISECONDS_PER_SECOND = 1000; + + if (const SString strPathFilename = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_SAVE); strPathFilename.empty()) { return; } else { // Early return if user disabled dump sending - if (const SString strSendDumps = GetApplicationSetting(DIAGNOSTICS_SECTION, SEND_DUMPS); - strSendDumps == NO_SEND) + if (const SString strSendDumps = GetApplicationSetting(DIAGNOSTICS_SECTION, SEND_DUMPS); strSendDumps == NO_SEND) { _ResetLastCrashDump(); return; @@ -3368,8 +3344,7 @@ void CVersionUpdater::_UseCrashDumpPostContent() // Validate path and file SString strErrorMsg; - if (const int iValidationResult = ValidateCrashDumpPath(strPathFilename, &strErrorMsg, true); - iValidationResult != 0) + if (const int iValidationResult = ValidateCrashDumpPath(strPathFilename, &strErrorMsg, true); iValidationResult != 0) { AddReportLog(iValidationResult, SString("%s%s", LOG_PREFIX, *strErrorMsg)); _ResetLastCrashDump(); @@ -3379,138 +3354,130 @@ void CVersionUpdater::_UseCrashDumpPostContent() // Extract filename from path SString strFilename; strPathFilename.Split(PATH_SEPERATOR, nullptr, &strFilename, -1); - + // Validate filename length - if (const size_t postFilenameLength = strFilename.length(); - postFilenameLength > MAX_POST_FILENAME_LENGTH) + if (const size_t postFilenameLength = strFilename.length(); postFilenameLength > MAX_POST_FILENAME_LENGTH) + { + AddReportLog(9329, SString("%sFilename too long (%d > %d)", LOG_PREFIX, postFilenameLength, MAX_POST_FILENAME_LENGTH)); + _ResetLastCrashDump(); + return; + } + + // Check if dump file writing is complete + if (const SString strDumpComplete = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_COMPLETE); strDumpComplete != COMPLETE_FLAG) + { + AddReportLog(9320, SString("%sDump file not yet complete - waiting for write to finish", LOG_PREFIX)); + + // Don't start retry counter yet - just wait for next pulse + // This prevents premature file access while crash handler is still writing + m_bSentCrashDump = false; + return; + } + + // Get current retry count + const int iCurrentRetry = GetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_LOAD_RETRY); + + // Lambda for backoff calculation with explicit return type + const auto calculate_backoff = [INITIAL_BACKOFF_SECONDS, BACKOFF_MULTIPLIER](int retry_count) noexcept -> int + { + if (retry_count <= 0) + return 0; + int backoff = INITIAL_BACKOFF_SECONDS; + for (int i = 1; i < retry_count; ++i) + backoff *= BACKOFF_MULTIPLIER; + return backoff; + }; + + // Calculate backoff for current retry + const int iBackoffSeconds = calculate_backoff(iCurrentRetry); + + // Check if we need to wait for retry backoff delay + if (iCurrentRetry > 0) + { + // Get retry timestamp + const long long llRetryTimeSec = GetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_RETRY_TIME); + const long long llCurrentTimeSec = GetTickCount64_() / MILLISECONDS_PER_SECOND; + const long long llElapsedSec = llCurrentTimeSec - llRetryTimeSec; + + // Check if backoff delay has elapsed + if (llElapsedSec >= 0 && llElapsedSec < iBackoffSeconds) { - AddReportLog(9329, SString("%sFilename too long (%d > %d)", - LOG_PREFIX, postFilenameLength, MAX_POST_FILENAME_LENGTH)); - _ResetLastCrashDump(); + // Still waiting for backoff delay + m_bSentCrashDump = false; return; } + } - // Check if dump file writing is complete - if (const SString strDumpComplete = GetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_COMPLETE); - strDumpComplete != COMPLETE_FLAG) + // Attempt to load file + if (const bool bLoadSuccess = FileLoad(strPathFilename, m_JobInfo.postContent); bLoadSuccess) + { + if (m_JobInfo.postContent.empty()) { - AddReportLog(9320, SString("%sDump file not yet complete - waiting for write to finish", LOG_PREFIX)); - - // Don't start retry counter yet - just wait for next pulse - // This prevents premature file access while crash handler is still writing - m_bSentCrashDump = false; + AddReportLog(9317, SString("%sLoaded content is empty", LOG_PREFIX)); + _ResetLastCrashDump(); return; } - - // Get current retry count - const int iCurrentRetry = GetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_LOAD_RETRY); - - // Lambda for backoff calculation with explicit return type - const auto calculate_backoff = [INITIAL_BACKOFF_SECONDS, BACKOFF_MULTIPLIER](int retry_count) noexcept -> int { - if (retry_count <= 0) - return 0; - int backoff = INITIAL_BACKOFF_SECONDS; - for (int i = 1; i < retry_count; ++i) - backoff *= BACKOFF_MULTIPLIER; - return backoff; - }; - - // Calculate backoff for current retry - const int iBackoffSeconds = calculate_backoff(iCurrentRetry); - - // Check if we need to wait for retry backoff delay - if (iCurrentRetry > 0) + + // Validate content size + if (const size_t contentSize = m_JobInfo.postContent.size(); contentSize > MAX_POST_CONTENT_SIZE) { - // Get retry timestamp - const long long llRetryTimeSec = GetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_RETRY_TIME); - const long long llCurrentTimeSec = GetTickCount64_() / MILLISECONDS_PER_SECOND; - const long long llElapsedSec = llCurrentTimeSec - llRetryTimeSec; - - // Check if backoff delay has elapsed - if (llElapsedSec >= 0 && llElapsedSec < iBackoffSeconds) - { - // Still waiting for backoff delay - m_bSentCrashDump = false; - return; - } + AddReportLog(9316, SString("%sLoaded content too large (%d > %d)", LOG_PREFIX, contentSize, MAX_POST_CONTENT_SIZE)); + m_JobInfo.postContent.clear(); + _ResetLastCrashDump(); + return; } - - // Attempt to load file - if (const bool bLoadSuccess = FileLoad(strPathFilename, m_JobInfo.postContent); bLoadSuccess) + + // Validate minidump signature + if (const size_t contentSize = m_JobInfo.postContent.size(); contentSize >= MIN_SIGNATURE_SIZE) { - if (m_JobInfo.postContent.empty()) - { - AddReportLog(9317, SString("%sLoaded content is empty", LOG_PREFIX)); - _ResetLastCrashDump(); - return; - } - - // Validate content size - if (const size_t contentSize = m_JobInfo.postContent.size(); - contentSize > MAX_POST_CONTENT_SIZE) + uint32_t signature; + memcpy(&signature, m_JobInfo.postContent.data(), sizeof(signature)); + + if (signature != MDMP_SIGNATURE) { - AddReportLog(9316, SString("%sLoaded content too large (%d > %d)", - LOG_PREFIX, contentSize, MAX_POST_CONTENT_SIZE)); + AddReportLog(9322, SString("%sInvalid minidump signature (0x%08X, expected 0x%08X)", LOG_PREFIX, signature, MDMP_SIGNATURE)); m_JobInfo.postContent.clear(); _ResetLastCrashDump(); return; } - - // Validate minidump signature - if (const size_t contentSize = m_JobInfo.postContent.size(); - contentSize >= MIN_SIGNATURE_SIZE) - { - uint32_t signature; - memcpy(&signature, m_JobInfo.postContent.data(), sizeof(signature)); - - if (signature != MDMP_SIGNATURE) - { - AddReportLog(9322, SString("%sInvalid minidump signature (0x%08X, expected 0x%08X)", - LOG_PREFIX, signature, MDMP_SIGNATURE)); - m_JobInfo.postContent.clear(); - _ResetLastCrashDump(); - return; - } - } - - // Set metadata - upload ready - m_JobInfo.strPostFilename = strFilename; - m_JobInfo.bPostContentBinary = true; - - // Don't clear settings yet - wait until upload succeeds - // Settings will be cleared in Program_SendCrashDump after _StartSendPost returns true - - AddReportLog(5200, SString("%sSuccessfully loaded crash dump file: %s (upload pending)", - LOG_PREFIX, *strFilename)); + } + + // Set metadata - upload ready + m_JobInfo.strPostFilename = strFilename; + m_JobInfo.bPostContentBinary = true; + + // Don't clear settings yet - wait until upload succeeds + // Settings will be cleared in Program_SendCrashDump after _StartSendPost returns true + + AddReportLog(5200, SString("%sSuccessfully loaded crash dump file: %s (upload pending)", LOG_PREFIX, *strFilename)); + } + else + { + // File load failed - retry + if (const int iNextRetry = iCurrentRetry + 1; iNextRetry <= MAX_LOAD_RETRIES) + { + // Increment retry counter + SetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_LOAD_RETRY, iNextRetry); + + // Store current timestamp for backoff delay + const long long llCurrentTimeSec = GetTickCount64_() / MILLISECONDS_PER_SECOND; + SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_RETRY_TIME, SString("%lld", llCurrentTimeSec)); + + // Calculate backoff for next retry + const int iNextBackoffSeconds = calculate_backoff(iNextRetry); + AddReportLog(9310, SString("%sFailed to load crash dump file (attempt %d/%d): %s - Will retry in %d seconds", LOG_PREFIX, iNextRetry, + MAX_LOAD_RETRIES, *strFilename, iNextBackoffSeconds)); + + // Reset flag to allow retry on next pulse (after backoff delay) + m_bSentCrashDump = false; } else { - // File load failed - retry - if (const int iNextRetry = iCurrentRetry + 1; iNextRetry <= MAX_LOAD_RETRIES) - { - // Increment retry counter - SetApplicationSettingInt(DIAGNOSTICS_SECTION, LAST_DUMP_LOAD_RETRY, iNextRetry); - - // Store current timestamp for backoff delay - const long long llCurrentTimeSec = GetTickCount64_() / MILLISECONDS_PER_SECOND; - SetApplicationSetting(DIAGNOSTICS_SECTION, LAST_DUMP_RETRY_TIME, SString("%lld", llCurrentTimeSec)); - - // Calculate backoff for next retry - const int iNextBackoffSeconds = calculate_backoff(iNextRetry); - AddReportLog(9310, SString("%sFailed to load crash dump file (attempt %d/%d): %s - Will retry in %d seconds", - LOG_PREFIX, iNextRetry, MAX_LOAD_RETRIES, *strFilename, iNextBackoffSeconds)); - - // Reset flag to allow retry on next pulse (after backoff delay) - m_bSentCrashDump = false; - } - else - { - // Max retries exceeded - give up - AddReportLog(9324, SString("%sFailed to load crash dump file after %d attempts: %s - Giving up", - LOG_PREFIX, MAX_LOAD_RETRIES, *strFilename)); - _ResetLastCrashDump(); - } + // Max retries exceeded - give up + AddReportLog(9324, SString("%sFailed to load crash dump file after %d attempts: %s - Giving up", LOG_PREFIX, MAX_LOAD_RETRIES, *strFilename)); + _ResetLastCrashDump(); } + } } } @@ -3634,7 +3601,7 @@ int CVersionUpdater::DoSendDownloadRequestToNextServer() unsigned short usNetRev = CCore::GetSingleton().GetNetwork()->GetNetRev(); unsigned short usNetRel = CCore::GetSingleton().GetNetwork()->GetNetRel(); SString strPlayerVersion("%d.%d.%d-%d.%05d.%d.%03d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, - MTASA_VERSION_BUILD, usNetRev, usNetRel); + MTASA_VERSION_BUILD, usNetRev, usNetRel); SString strUpdateBuildType; CVARS_GET("update_build_type", strUpdateBuildType); @@ -3651,9 +3618,9 @@ int CVersionUpdater::DoSendDownloadRequestToNextServer() fseek(fh, 0x38BDC80, SEEK_SET); for (uint i = 0; i < 20; i++) if (fgetc(fh)) - strSoundCut = "n"; // Non-zero found + strSoundCut = "n"; // Non-zero found if (ferror(fh)) - strSoundCut = "e"; // File error + strSoundCut = "e"; // File error fclose(fh); } } @@ -3675,14 +3642,14 @@ int CVersionUpdater::DoSendDownloadRequestToNextServer() iReqKB3035131 = IsHotFixInstalled("KB3035131") ? 0 : 1; } - int secureBootStatus = 0; + int secureBootStatus = 0; const SString secureBootValue = GetSystemRegistryValue((uint)HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\SecureBoot\\State", "UEFISecureBootEnabled", &secureBootStatus); bool bSecureBootEnabled = false; if (secureBootStatus > 0) { // Parse the registry value into a numeric flag - char* secureBootEnd = nullptr; + char* secureBootEnd = nullptr; const long secureBootNumeric = strtol(secureBootValue.c_str(), &secureBootEnd, 10); if (secureBootEnd != secureBootValue.c_str() && *secureBootEnd == '\0') { @@ -3694,62 +3661,61 @@ int CVersionUpdater::DoSendDownloadRequestToNextServer() g_pGraphics->GetRenderItemManager()->GetDxStatus(dxStatus); CGameSettings* gameSettings = CCore::GetSingleton().GetGame()->GetSettings(); SString strVideoCard = SStringX(g_pDeviceState->AdapterState.Name).Left(30); - std::replace_if( - strVideoCard.begin(), strVideoCard.end(), [](int c) { return !isalnum(c); }, '_'); + std::replace_if(strVideoCard.begin(), strVideoCard.end(), [](int c) { return !isalnum(c); }, '_'); SString strSystemStats( "1_%d_%d_%d_%d_%d" "_%d%d%d%d" "_%s", - static_cast(GetWMITotalPhysicalMemory() / 1024LL / 1024LL), // - g_pDeviceState->AdapterState.InstalledMemoryKB / 1024, // - gameSettings->GetCurrentVideoMode(), // - gameSettings->GetFXQuality(), // - dxStatus.settings.iDrawDistance, // - - GetVideoModeManager()->IsWindowed(), // - GetVideoModeManager()->IsMultiMonitor(), // - dxStatus.settings.bVolumetricShadows, // - dxStatus.settings.bAllowScreenUpload, // - - *GetApplicationSetting("real-os-version") // + static_cast(GetWMITotalPhysicalMemory() / 1024LL / 1024LL), // + g_pDeviceState->AdapterState.InstalledMemoryKB / 1024, // + gameSettings->GetCurrentVideoMode(), // + gameSettings->GetFXQuality(), // + dxStatus.settings.iDrawDistance, // + + GetVideoModeManager()->IsWindowed(), // + GetVideoModeManager()->IsMultiMonitor(), // + dxStatus.settings.bVolumetricShadows, // + dxStatus.settings.bAllowScreenUpload, // + + *GetApplicationSetting("real-os-version") // ); SString strSystemStats2( "2_%d_%d_%d" "_%d_%d_%d" "_%d_%d_%d_%d_%d_%x", - g_pGraphics->GetViewportWidth(), // - g_pGraphics->GetViewportHeight(), // - dxStatus.settings.b32BitColor, // - - GetApplicationSettingInt(DIAG_PRELOAD_UPGRADES_LOWEST_UNSAFE), // - GetApplicationSettingInt(DIAG_MINIDUMP_DETECTED_COUNT), // - GetApplicationSettingInt(DIAG_MINIDUMP_CONFIRMED_COUNT), // - - atoi(dxStatus.videoCard.strPSVersion), // - dxStatus.videoCard.iNumSimultaneousRTs, // - dxStatus.settings.iAntiAliasing, // - dxStatus.settings.iAnisotropicFiltering, // - (int)dxStatus.settings.fFieldOfView, // - dxStatus.videoCard.depthBufferFormat // + g_pGraphics->GetViewportWidth(), // + g_pGraphics->GetViewportHeight(), // + dxStatus.settings.b32BitColor, // + + GetApplicationSettingInt(DIAG_PRELOAD_UPGRADES_LOWEST_UNSAFE), // + GetApplicationSettingInt(DIAG_MINIDUMP_DETECTED_COUNT), // + GetApplicationSettingInt(DIAG_MINIDUMP_CONFIRMED_COUNT), // + + atoi(dxStatus.videoCard.strPSVersion), // + dxStatus.videoCard.iNumSimultaneousRTs, // + dxStatus.settings.iAntiAliasing, // + dxStatus.settings.iAnisotropicFiltering, // + (int)dxStatus.settings.fFieldOfView, // + dxStatus.videoCard.depthBufferFormat // ); SString strSystemStats3( - "3_0" // Was VS2013 runtime installed + "3_0" // Was VS2013 runtime installed "_%s_%s_%d" - "_0" // Was VS2015 runtime version + "_0" // Was VS2015 runtime version "_%d_%d_%d_%d_%d_%s_%s", - *GetApplicationSetting("real-os-build"), // - *GetApplicationSetting("locale").Replace("_", "-"), // - (uint)FileSize(PathJoin(GetSystemSystemPath(), "normaliz.dll")), // - - bSecureBootEnabled, // - static_cast(memoryStatus.ullTotalVirtual / 1024), // - Is64BitOS(), // - iReqKB3033929, // - iReqKB3035131, // - *verInfoKernel32.GetFileVersionString(), // - *verInfoNcrypt.GetFileVersionString() // + *GetApplicationSetting("real-os-build"), // + *GetApplicationSetting("locale").Replace("_", "-"), // + (uint)FileSize(PathJoin(GetSystemSystemPath(), "normaliz.dll")), // + + bSecureBootEnabled, // + static_cast(memoryStatus.ullTotalVirtual / 1024), // + Is64BitOS(), // + iReqKB3033929, // + iReqKB3035131, // + *verInfoKernel32.GetFileVersionString(), // + *verInfoNcrypt.GetFileVersionString() // ); SString strConnectUsage = SString("%i_%i", GetApplicationSettingInt("times-connected-editor"), GetApplicationSettingInt("times-connected")); @@ -3927,7 +3893,7 @@ int CVersionUpdater::DoSendPostToNextServer() unsigned short usNetRev = CCore::GetSingleton().GetNetwork()->GetNetRev(); unsigned short usNetRel = CCore::GetSingleton().GetNetwork()->GetNetRel(); SString strPlayerVersion("%d.%d.%d-%d.%05d.%d.%03d", MTASA_VERSION_MAJOR, MTASA_VERSION_MINOR, MTASA_VERSION_MAINTENANCE, MTASA_VERSION_TYPE, - MTASA_VERSION_BUILD, usNetRev, usNetRel); + MTASA_VERSION_BUILD, usNetRev, usNetRel); // Make the query URL SString strQueryURL = strServerURL; diff --git a/Client/core/CVertexStreamBoundingBoxManager.cpp b/Client/core/CVertexStreamBoundingBoxManager.cpp index 8ac917758c3..b38ba4ea341 100644 --- a/Client/core/CVertexStreamBoundingBoxManager.cpp +++ b/Client/core/CVertexStreamBoundingBoxManager.cpp @@ -37,7 +37,7 @@ namespace return fDistSq; } -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -298,8 +298,8 @@ bool CVertexStreamBoundingBoxManager::ComputeVertexStreamBoundingBox(SCurrentSta std::vector indices(numIndices); { void* pIndexBytes = NULL; - if (FAILED(state.pIndexData->Lock(static_cast(startByte), static_cast(requiredBytes), &pIndexBytes, - D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY))) + if (FAILED( + state.pIndexData->Lock(static_cast(startByte), static_cast(requiredBytes), &pIndexBytes, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY))) return false; if (indexStride == sizeof(WORD)) @@ -332,10 +332,10 @@ bool CVertexStreamBoundingBoxManager::ComputeVertexStreamBoundingBox(SCurrentSta uint32_t v2 = indices[i + 2]; if (v0 >= NumVerts || v1 >= NumVerts || v2 >= NumVerts) - continue; // vert index out of range + continue; // vert index out of range if (v0 == v1 || v0 == v2 || v1 == v2) - continue; // degenerate tri + continue; // degenerate tri // Get vertex positions from original stream CVector* pPos0 = (CVector*)(pSourceArrayBytes + v0 * StridePT); diff --git a/Client/core/CVertexStreamBoundingBoxManager.h b/Client/core/CVertexStreamBoundingBoxManager.h index 54952e00568..f2c8d2b0718 100644 --- a/Client/core/CVertexStreamBoundingBoxManager.h +++ b/Client/core/CVertexStreamBoundingBoxManager.h @@ -85,10 +85,7 @@ struct SCurrentStateInfo2 public: SCurrentStateInfo2() { ZERO_POD_STRUCT(this); } - ~SCurrentStateInfo2() - { - ReleaseComReferences(); - } + ~SCurrentStateInfo2() { ReleaseComReferences(); } // Info to DrawIndexPrimitive struct @@ -138,7 +135,7 @@ class CVertexStreamBoundingBoxManager static CVertexStreamBoundingBoxManager* GetSingleton(); static CVertexStreamBoundingBoxManager* GetExistingSingleton(); - static void DestroySingleton(); + static void DestroySingleton(); protected: float CalcDistanceSq(const SCurrentStateInfo2& state, const CBox& boundingBox); diff --git a/Client/core/CrashHandler.cpp b/Client/core/CrashHandler.cpp index 0bcc39f5359..40aa778ad92 100644 --- a/Client/core/CrashHandler.cpp +++ b/Client/core/CrashHandler.cpp @@ -84,8 +84,8 @@ static std::atomic g_bWerLocalDumpConfigured{false}; return false; HMODULE hModule{nullptr}; - if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - static_cast(exceptionAddress), &hModule) == 0) [[unlikely]] + if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, static_cast(exceptionAddress), + &hModule) == 0) [[unlikely]] return false; char modulePath[256]{}; @@ -93,8 +93,7 @@ static std::atomic g_bWerLocalDumpConfigured{false}; return false; // Libraries with a lot of bogus breakpoints - return strstr(modulePath, "libcef.dll") != nullptr || - strstr(modulePath, "chrome_elf.dll") != nullptr; + return strstr(modulePath, "libcef.dll") != nullptr || strstr(modulePath, "chrome_elf.dll") != nullptr; } // Helpers to isolate __try usage and prevent crashes in debug output itself @@ -231,8 +230,8 @@ static void CppNewHandlerBridge(); if (IsMemoryException(exceptionCode)) [[unlikely]] { std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "IsFatalException: Access violation/page fault 0x%08X - treating as fatal for dump generation\n", - exceptionCode); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), + "IsFatalException: Access violation/page fault 0x%08X - treating as fatal for dump generation\n", exceptionCode); return TRUE; } @@ -246,10 +245,8 @@ static void LogBasicExceptionInfo(_EXCEPTION_POINTERS* exception) if (exception == nullptr || exception->ExceptionRecord == nullptr) return; - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "Exception 0x%08X at 0x%p (TID: %lu)\n", - exception->ExceptionRecord->ExceptionCode, - exception->ExceptionRecord->ExceptionAddress, - GetCurrentThreadId()); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "Exception 0x%08X at 0x%p (TID: %lu)\n", exception->ExceptionRecord->ExceptionCode, + exception->ExceptionRecord->ExceptionAddress, GetCurrentThreadId()); } static void StoreBasicExceptionInfo(_EXCEPTION_POINTERS* pException) @@ -266,13 +263,11 @@ static void StoreBasicExceptionInfo(_EXCEPTION_POINTERS* pException) return; } - ENHANCED_EXCEPTION_INFO info{ - .exceptionCode = pException->ExceptionRecord->ExceptionCode, - .exceptionAddress = pException->ExceptionRecord->ExceptionAddress, - .timestamp = std::chrono::system_clock::now(), - .threadId = GetCurrentThreadId(), - .processId = GetCurrentProcessId() - }; + ENHANCED_EXCEPTION_INFO info{.exceptionCode = pException->ExceptionRecord->ExceptionCode, + .exceptionAddress = pException->ExceptionRecord->ExceptionAddress, + .timestamp = std::chrono::system_clock::now(), + .threadId = GetCurrentThreadId(), + .processId = GetCurrentProcessId()}; const auto telemetryNote = CrashTelemetry::BuildAllocationTelemetryNote(); if (!telemetryNote.empty()) @@ -415,22 +410,21 @@ static void LogEnhancedExceptionInfo(_EXCEPTION_POINTERS* pException) info.eflags = pException->ContextRecord->EFlags; CExceptionInformation_Impl moduleHelper; - std::array moduleBuffer{}; - void* moduleBase{nullptr}; + std::array moduleBuffer{}; + void* moduleBase{nullptr}; // For EIP=0 crashes, resolve module from return address at [ESP] instead of EIP - void* addressToResolve{info.exceptionAddress}; + void* addressToResolve{info.exceptionAddress}; constexpr auto kNullAddress{uintptr_t{0}}; - + const auto exceptionAddressValue{reinterpret_cast(info.exceptionAddress)}; - + if (exceptionAddressValue == kNullAddress && info.eip == kNullAddress) { const auto espAddr{static_cast(info.esp)}; const auto pReturnAddress{reinterpret_cast(espAddr)}; - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "LogEnhancedExceptionInfo - EIP=0 detected (ESP=0x%08X), reading return address...\n", + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogEnhancedExceptionInfo - EIP=0 detected (ESP=0x%08X), reading return address...\n", static_cast(espAddr)); if (SharedUtil::IsReadablePointer(pReturnAddress, sizeof(void*))) @@ -438,14 +432,12 @@ static void LogEnhancedExceptionInfo(_EXCEPTION_POINTERS* pException) addressToResolve = *pReturnAddress; const auto returnAddressValue{reinterpret_cast(addressToResolve)}; - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "LogEnhancedExceptionInfo - Return address: 0x%08X (resolving module from this)\n", + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogEnhancedExceptionInfo - Return address: 0x%08X (resolving module from this)\n", static_cast(returnAddressValue)); } else { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "LogEnhancedExceptionInfo - ESP not readable (0x%08X), cannot read return address\n", + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogEnhancedExceptionInfo - ESP not readable (0x%08X), cannot read return address\n", static_cast(espAddr)); } } @@ -748,24 +740,21 @@ static std::variant HandleExceptionModern(_EXCEPTION_POINTER break; } - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "%.*s (0x%08X) at 0x%p\n", - static_cast(exceptionType.size()), - exceptionType.data(), - exceptionCode, + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "%.*s (0x%08X) at 0x%p\n", static_cast(exceptionType.size()), exceptionType.data(), exceptionCode, pRecord->ExceptionAddress); return exceptionCode; } -static std::mutex g_handlerStateMutex; -static std::atomic g_pfnCrashCallback{nullptr}; -static std::atomic g_pfnOrigFilt{nullptr}; -static std::atomic g_pfnOrigTerminate{nullptr}; +static std::mutex g_handlerStateMutex; +static std::atomic g_pfnCrashCallback{nullptr}; +static std::atomic g_pfnOrigFilt{nullptr}; +static std::atomic g_pfnOrigTerminate{nullptr}; #if defined(_MSC_VER) using CrtNewHandler = int(__cdecl*)(size_t); -static std::atomic g_pfnOrigNewHandler{nullptr}; +static std::atomic g_pfnOrigNewHandler{nullptr}; #else -static std::atomic g_pfnOrigNewHandler{nullptr}; +static std::atomic g_pfnOrigNewHandler{nullptr}; #endif static std::atomic g_pfnKernelSetUnhandledExceptionFilter{nullptr}; static decltype(&SetUnhandledExceptionFilter) g_kernelSetUnhandledExceptionFilterTrampoline = nullptr; @@ -778,20 +767,21 @@ static std::atomic g_bInPureCallHandler{false}; static std::atomic g_bInTerminateHandler{false}; static std::atomic g_bInNewHandler{false}; -static std::atomic g_symbolsInitialized{false}; -static std::atomic g_symbolProcess{nullptr}; -static std::mutex g_symbolMutex; +static std::atomic g_symbolsInitialized{false}; +static std::atomic g_symbolProcess{nullptr}; +static std::mutex g_symbolMutex; using EnumProcessModulesExFn = BOOL(WINAPI*)(HANDLE, HMODULE*, DWORD, LPDWORD, DWORD); [[nodiscard]] static bool CollectProcessModules(HANDLE process, std::vector& modules) { - const HMODULE psapiModule = GetModuleHandleW(L"Psapi.dll"); + const HMODULE psapiModule = GetModuleHandleW(L"Psapi.dll"); EnumProcessModulesExFn enumModulesEx = nullptr; if (psapiModule != nullptr) enumModulesEx = reinterpret_cast(GetProcAddress(psapiModule, "EnumProcessModulesEx")); - auto enumModules = [&](HMODULE* buffer, DWORD bufferSize, DWORD* bytesNeeded) -> BOOL { + auto enumModules = [&](HMODULE* buffer, DWORD bufferSize, DWORD* bytesNeeded) -> BOOL + { if (enumModulesEx) return enumModulesEx(process, buffer, bufferSize, bytesNeeded, LIST_MODULES_ALL); return EnumProcessModules(process, buffer, bufferSize, bytesNeeded); @@ -846,20 +836,19 @@ using EnumProcessModulesExFn = BOOL(WINAPI*)(HANDLE, HMODULE*, DWORD, LPDWORD, D } else if (failuresLogged < 5) { - const auto error = GetLastError(); + const auto error = GetLastError(); std::array debugBuffer{}; SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - SymLoadModuleEx failed via EnumProcessModules for %s (error 0x%08X)\n", - modulePath.data(), error); + "CrashHandler: InitializeSymbolHandler - SymLoadModuleEx failed via EnumProcessModules for %s (error 0x%08X)\n", + modulePath.data(), error); ++failuresLogged; } } std::array debugBuffer{}; SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - Registered %lu modules via EnumProcessModules (failures=%lu)\n", - modulesRegistered, - failuresLogged); + "CrashHandler: InitializeSymbolHandler - Registered %lu modules via EnumProcessModules (failures=%lu)\n", modulesRegistered, + failuresLogged); return modulesRegistered != 0; } @@ -869,16 +858,12 @@ using EnumProcessModulesExFn = BOOL(WINAPI*)(HANDLE, HMODULE*, DWORD, LPDWORD, D const auto addressPtr = reinterpret_cast(static_cast(address)); HMODULE moduleHandle{nullptr}; - if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - addressPtr, - &moduleHandle) == 0) + if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, addressPtr, &moduleHandle) == 0) { - const auto error = GetLastError(); + const auto error = GetLastError(); std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CaptureUnifiedStackTrace - Unable to resolve module for address 0x%llX (error 0x%08X)\n", - address, - error); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CaptureUnifiedStackTrace - Unable to resolve module for address 0x%llX (error 0x%08X)\n", + address, error); return false; } @@ -889,48 +874,38 @@ using EnumProcessModulesExFn = BOOL(WINAPI*)(HANDLE, HMODULE*, DWORD, LPDWORD, D MODULEINFO moduleInfo{}; if (GetModuleInformation(process, moduleHandle, &moduleInfo, sizeof(moduleInfo)) == FALSE) { - const auto error = GetLastError(); + const auto error = GetLastError(); std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CaptureUnifiedStackTrace - GetModuleInformation failed for address 0x%llX (error 0x%08X)\n", - address, - error); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CaptureUnifiedStackTrace - GetModuleInformation failed for address 0x%llX (error 0x%08X)\n", + address, error); return false; } std::array modulePath{}; if (GetModuleFileNameExA(process, moduleHandle, modulePath.data(), static_cast(modulePath.size())) == 0) { - const auto error = GetLastError(); + const auto error = GetLastError(); std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CaptureUnifiedStackTrace - GetModuleFileNameEx failed for address 0x%llX (error 0x%08X)\n", - address, - error); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CaptureUnifiedStackTrace - GetModuleFileNameEx failed for address 0x%llX (error 0x%08X)\n", + address, error); return false; } - const DWORD imageSize = moduleInfo.SizeOfImage; + const DWORD imageSize = moduleInfo.SizeOfImage; SetLastError(ERROR_SUCCESS); if (SymLoadModuleEx(process, nullptr, modulePath.data(), nullptr, moduleBase, imageSize, nullptr, 0) == 0) { - const auto error = GetLastError(); + const auto error = GetLastError(); std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CaptureUnifiedStackTrace - SymLoadModuleEx failed for %s (address 0x%llX, error 0x%08X)\n", - modulePath.data(), - address, - error); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CaptureUnifiedStackTrace - SymLoadModuleEx failed for %s (address 0x%llX, error 0x%08X)\n", + modulePath.data(), address, error); return false; } std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CaptureUnifiedStackTrace - Registered module %s (base=0x%llX) for address 0x%llX\n", - modulePath.data(), - moduleBase, - address); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CaptureUnifiedStackTrace - Registered module %s (base=0x%llX) for address 0x%llX\n", + modulePath.data(), moduleBase, address); return true; } @@ -984,8 +959,7 @@ static bool ConfigureWerLocalDumps(); static void UninstallCrashHandlers(); static void ReportCurrentCppException(); -[[nodiscard]] static bool BuildExceptionContext(EXCEPTION_POINTERS& outExPtrs, EXCEPTION_RECORD*& outExRecord, CONTEXT*& outCtx, - DWORD dwExceptionCode); +[[nodiscard]] static bool BuildExceptionContext(EXCEPTION_POINTERS& outExPtrs, EXCEPTION_RECORD*& outExRecord, CONTEXT*& outCtx, DWORD dwExceptionCode); inline void InitializeExceptionRecord(EXCEPTION_RECORD* const pRecord, const DWORD code, const void* const address); @@ -1049,8 +1023,8 @@ inline void InitializeExceptionRecord(EXCEPTION_RECORD* const pRecord, const DWO static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI RedirectedSetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) { std::array szLog{std::array{}}; - SAFE_DEBUG_PRINT(szLog, "%.*sIntercepted SetUnhandledExceptionFilter call with arg 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), - static_cast(lpTopLevelExceptionFilter)); + SAFE_DEBUG_PRINT(szLog, "%.*sIntercepted SetUnhandledExceptionFilter call with arg 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), + DEBUG_PREFIX_CRASH.data(), static_cast(lpTopLevelExceptionFilter)); if (lpTopLevelExceptionFilter == nullptr) { @@ -1188,7 +1162,7 @@ class CleanUpCrashHandler g_bStackCookieCaptureEnabled.store(false, std::memory_order_release); g_pfnCrashCallback.store(nullptr, std::memory_order_release); - + if (g_symbolsInitialized.exchange(false, std::memory_order_acq_rel)) { if (HANDLE hProcess = g_symbolProcess.exchange(nullptr, std::memory_order_acq_rel); hProcess != nullptr) @@ -1205,11 +1179,11 @@ class CleanUpCrashHandler if (auto newHandler = g_pfnOrigNewHandler.exchange(nullptr, std::memory_order_acq_rel); newHandler != nullptr) { - #if defined(_MSC_VER) +#if defined(_MSC_VER) _set_new_handler(newHandler); - #else +#else std::set_new_handler(newHandler); - #endif +#endif } if (auto abortHandler = g_pfnOrigAbortHandler.exchange(nullptr, std::memory_order_acq_rel); abortHandler != nullptr) @@ -1244,342 +1218,334 @@ static CleanUpCrashHandler g_cBeforeAndAfter; namespace CrashHandler { -[[nodiscard]] const std::vector& GetPdbDirectories() -{ - static std::once_flag onceFlag; - static std::vector pdbDirs; - - std::call_once(onceFlag, [] { - try + [[nodiscard]] const std::vector& GetPdbDirectories() + { + static std::once_flag onceFlag; + static std::vector pdbDirs; + + std::call_once(onceFlag, + [] + { + try + { + const SString& processDir = SharedUtil::GetMTAProcessBaseDir(); + + if (processDir.empty()) [[unlikely]] + return; + + const std::filesystem::path rootPath{FromUTF8(processDir)}; + std::error_code ec{}; + + if (!std::filesystem::exists(rootPath, ec) || !std::filesystem::is_directory(rootPath, ec)) + return; + + std::set uniqueDirs; + + constexpr auto options = std::filesystem::directory_options::skip_permission_denied; + std::filesystem::recursive_directory_iterator iter{rootPath, options, ec}; + + if (ec) [[unlikely]] + return; + + constexpr auto maxDepth = 256u; + + for (const auto end = std::filesystem::recursive_directory_iterator{}; iter != end;) + { + if (iter.depth() > maxDepth) [[unlikely]] + iter.disable_recursion_pending(); + + std::error_code entryEc{}; + const bool isSymlink = iter->is_symlink(entryEc); + + if (entryEc || isSymlink) [[unlikely]] + { + iter.increment(ec), ec ? ec.clear() : void(); + continue; + } + + const bool isRegularFile = iter->is_regular_file(entryEc); + + if (entryEc) [[unlikely]] + { + iter.increment(ec), ec ? ec.clear() : void(); + continue; + } + + if (isRegularFile) [[likely]] + { + const auto extension = iter->path().extension().wstring(); + + if (extension.size() == 4 && (extension[0] == L'.') && (extension[1] == L'p' || extension[1] == L'P') && + (extension[2] == L'd' || extension[2] == L'D') && (extension[3] == L'b' || extension[3] == L'B')) [[unlikely]] + { + const auto parentPath = iter->path().parent_path(); + if (!parentPath.empty()) + { + const auto parentStr = ToUTF8(parentPath.wstring()); + uniqueDirs.insert(std::string{parentStr.c_str()}); + } + } + } + + iter.increment(ec), ec ? ec.clear() : void(); + } + + pdbDirs.assign(uniqueDirs.begin(), uniqueDirs.end()); + } + catch (...) + { + } + }); + + return pdbDirs; + } + + [[nodiscard]] bool ProcessHasLocalDebugSymbols() + { + return !GetPdbDirectories().empty(); + } + + [[nodiscard]] static bool InitializeSymbolHandler() + { + std::scoped_lock lock{g_symbolMutex}; + + if (g_symbolsInitialized.load(std::memory_order_acquire)) + return true; + + const HANDLE hProcess = GetCurrentProcess(); + + DWORD symOptions = SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS | SYMOPT_LOAD_ANYTHING; + +#ifdef _DEBUG + symOptions |= SYMOPT_DEBUG; + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - SYMOPT_DEBUG enabled for diagnostics\n"); +#endif + + SymSetOptions(symOptions); + + std::string symbolPath; + const auto& pdbDirs = GetPdbDirectories(); + + if (!pdbDirs.empty()) [[likely]] { - const SString& processDir = SharedUtil::GetMTAProcessBaseDir(); - - if (processDir.empty()) [[unlikely]] - return; - - const std::filesystem::path rootPath{FromUTF8(processDir)}; - std::error_code ec{}; - - if (!std::filesystem::exists(rootPath, ec) || !std::filesystem::is_directory(rootPath, ec)) - return; - - std::set uniqueDirs; - - constexpr auto options = std::filesystem::directory_options::skip_permission_denied; - std::filesystem::recursive_directory_iterator iter{rootPath, options, ec}; - - if (ec) [[unlikely]] - return; - - constexpr auto maxDepth = 256u; - - for (const auto end = std::filesystem::recursive_directory_iterator{}; iter != end;) + auto first{true}; + for (const auto& dir : pdbDirs) { - if (iter.depth() > maxDepth) [[unlikely]] - iter.disable_recursion_pending(); - - std::error_code entryEc{}; - const bool isSymlink = iter->is_symlink(entryEc); - - if (entryEc || isSymlink) [[unlikely]] - { - iter.increment(ec), ec ? ec.clear() : void(); - continue; - } - - const bool isRegularFile = iter->is_regular_file(entryEc); - - if (entryEc) [[unlikely]] - { - iter.increment(ec), ec ? ec.clear() : void(); - continue; - } - - if (isRegularFile) [[likely]] - { - const auto extension = iter->path().extension().wstring(); - - if (extension.size() == 4 && (extension[0] == L'.') && - (extension[1] == L'p' || extension[1] == L'P') && - (extension[2] == L'd' || extension[2] == L'D') && - (extension[3] == L'b' || extension[3] == L'B')) [[unlikely]] - { - const auto parentPath = iter->path().parent_path(); - if (!parentPath.empty()) - { - const auto parentStr = ToUTF8(parentPath.wstring()); - uniqueDirs.insert(std::string{parentStr.c_str()}); - } - } - } - - iter.increment(ec), ec ? ec.clear() : void(); + if (!std::exchange(first, false)) + symbolPath += ";"; + symbolPath += dir; } - - pdbDirs.assign(uniqueDirs.begin(), uniqueDirs.end()); } - catch (...) + else [[unlikely]] { + const auto& processDir = SharedUtil::GetMTAProcessBaseDir(); + if (!processDir.empty()) + symbolPath = processDir.c_str(); } - }); - - return pdbDirs; -} -[[nodiscard]] bool ProcessHasLocalDebugSymbols() -{ - return !GetPdbDirectories().empty(); -} - -[[nodiscard]] static bool InitializeSymbolHandler() -{ - std::scoped_lock lock{g_symbolMutex}; - - if (g_symbolsInitialized.load(std::memory_order_acquire)) - return true; - - const HANDLE hProcess = GetCurrentProcess(); - - DWORD symOptions = SYMOPT_UNDNAME | - SYMOPT_DEFERRED_LOADS | - SYMOPT_LOAD_LINES | - SYMOPT_FAIL_CRITICAL_ERRORS | - SYMOPT_NO_PROMPTS | - SYMOPT_LOAD_ANYTHING; - -#ifdef _DEBUG - symOptions |= SYMOPT_DEBUG; - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - SYMOPT_DEBUG enabled for diagnostics\n"); -#endif - - SymSetOptions(symOptions); - - std::string symbolPath; - const auto& pdbDirs = GetPdbDirectories(); - - if (!pdbDirs.empty()) [[likely]] - { - auto first{true}; - for (const auto& dir : pdbDirs) + std::array envBuffer{}; + if (const auto len = GetEnvironmentVariableA("_NT_SYMBOL_PATH", envBuffer.data(), static_cast(envBuffer.size())); + len > 0 && len < envBuffer.size()) { - if (!std::exchange(first, false)) - symbolPath += ";"; - symbolPath += dir; + const std::string_view envPath{envBuffer.data(), len}; + if (envPath.find("http") == std::string_view::npos && envPath.find("SRV") == std::string_view::npos) [[likely]] + { + if (!symbolPath.empty()) + symbolPath += ";"; + symbolPath += envBuffer.data(); + } } - } - else [[unlikely]] - { - const auto& processDir = SharedUtil::GetMTAProcessBaseDir(); - if (!processDir.empty()) - symbolPath = processDir.c_str(); - } - - std::array envBuffer{}; - if (const auto len = GetEnvironmentVariableA("_NT_SYMBOL_PATH", envBuffer.data(), static_cast(envBuffer.size())); - len > 0 && len < envBuffer.size()) - { - const std::string_view envPath{envBuffer.data(), len}; - if (envPath.find("http") == std::string_view::npos && envPath.find("SRV") == std::string_view::npos) [[likely]] + + std::array debugBuffer{}; + + if (symbolPath.empty()) { - if (!symbolPath.empty()) - symbolPath += ";"; - symbolPath += envBuffer.data(); + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - WARNING: Empty symbol search path, symbols may not load\n"); } - } - - std::array debugBuffer{}; - - if (symbolPath.empty()) - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - WARNING: Empty symbol search path, symbols may not load\n"); - } - else - { - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - Symbol search path (%zu chars): %s\n", - symbolPath.size(), symbolPath.c_str()); - } - - const char* pSymbolPath = symbolPath.empty() ? nullptr : symbolPath.c_str(); - - if (SymInitialize(hProcess, pSymbolPath, TRUE) == FALSE) [[unlikely]] - { - const auto error = GetLastError(); - std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - SymInitialize FAILED with error 0x%08X (path: %s)\n", - error, pSymbolPath ? pSymbolPath : ""); - - constexpr auto kErrorAlreadyExists = 0x000000B7; - constexpr auto kErrorFileNotFound = 0x00000002; - constexpr auto kErrorAccessDenied = 0x00000005; - - if (error == kErrorAlreadyExists) [[unlikely]] - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR_ALREADY_EXISTS despite lock, forcing cleanup\n"); - SymCleanup(hProcess); + else + { + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: InitializeSymbolHandler - Symbol search path (%zu chars): %s\n", + symbolPath.size(), symbolPath.c_str()); } - - return false; - } - - if (SymRefreshModuleList(hProcess) == FALSE) - { - std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - WARNING: SymRefreshModuleList failed\n"); - } - [[maybe_unused]] const bool modulesRegistered = RegisterProcessModulesWithDbgHelp(hProcess); - - auto moduleCount = DWORD{0}; - auto symbolsLoadedCount = DWORD{0}; - auto modulesNeedingLoad = DWORD{0}; + const char* pSymbolPath = symbolPath.empty() ? nullptr : symbolPath.c_str(); + + if (SymInitialize(hProcess, pSymbolPath, TRUE) == FALSE) [[unlikely]] + { + const auto error = GetLastError(); + std::array debugBuffer{}; + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), + "CrashHandler: InitializeSymbolHandler - SymInitialize FAILED with error 0x%08X (path: %s)\n", error, + pSymbolPath ? pSymbolPath : ""); + + constexpr auto kErrorAlreadyExists = 0x000000B7; + constexpr auto kErrorFileNotFound = 0x00000002; + constexpr auto kErrorAccessDenied = 0x00000005; + + if (error == kErrorAlreadyExists) [[unlikely]] + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR_ALREADY_EXISTS despite lock, forcing cleanup\n"); + SymCleanup(hProcess); + } - auto enumerateModules = [&]() -> bool { - moduleCount = 0; - symbolsLoadedCount = 0; - modulesNeedingLoad = 0; + return false; + } - struct EnumContext + if (SymRefreshModuleList(hProcess) == FALSE) { - DWORD* pModuleCount; - DWORD* pSymbolsCount; - DWORD* pNeedingLoad; - HANDLE hProcess; - }; + std::array debugBuffer{}; + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: InitializeSymbolHandler - WARNING: SymRefreshModuleList failed\n"); + } - EnumContext enumCtx{&moduleCount, &symbolsLoadedCount, &modulesNeedingLoad, hProcess}; + [[maybe_unused]] const bool modulesRegistered = RegisterProcessModulesWithDbgHelp(hProcess); - if (SymEnumerateModules64(hProcess, [](PCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext) -> BOOL { - auto* pCtx = static_cast(UserContext); - (*pCtx->pModuleCount)++; + auto moduleCount = DWORD{0}; + auto symbolsLoadedCount = DWORD{0}; + auto modulesNeedingLoad = DWORD{0}; - IMAGEHLP_MODULE64 moduleInfo{}; - moduleInfo.SizeOfStruct = sizeof(moduleInfo); + auto enumerateModules = [&]() -> bool + { + moduleCount = 0; + symbolsLoadedCount = 0; + modulesNeedingLoad = 0; - if (SymGetModuleInfo64(pCtx->hProcess, BaseOfDll, &moduleInfo) != FALSE) + struct EnumContext { - const bool hasSymbols = (moduleInfo.SymType != SymNone && - moduleInfo.SymType != SymDeferred && - moduleInfo.LoadedPdbName[0] != '\0'); + DWORD* pModuleCount; + DWORD* pSymbolsCount; + DWORD* pNeedingLoad; + HANDLE hProcess; + }; - if (hasSymbols) - { - (*pCtx->pSymbolsCount)++; -#ifdef _DEBUG - std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - " Module: %s [Base: 0x%llX, SymType: %d, PDB: %s]\n", - ModuleName ? ModuleName : "", BaseOfDll, moduleInfo.SymType, - moduleInfo.LoadedPdbName); -#endif - } - else - { - (*pCtx->pNeedingLoad)++; - if (ModuleName && ModuleName[0] != '\0') + EnumContext enumCtx{&moduleCount, &symbolsLoadedCount, &modulesNeedingLoad, hProcess}; + + if (SymEnumerateModules64( + hProcess, + [](PCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext) -> BOOL { - const DWORD64 loadedBase = SymLoadModuleEx(pCtx->hProcess, nullptr, ModuleName, nullptr, BaseOfDll, 0, nullptr, 0); - if (loadedBase != 0) + auto* pCtx = static_cast(UserContext); + (*pCtx->pModuleCount)++; + + IMAGEHLP_MODULE64 moduleInfo{}; + moduleInfo.SizeOfStruct = sizeof(moduleInfo); + + if (SymGetModuleInfo64(pCtx->hProcess, BaseOfDll, &moduleInfo) != FALSE) { - (*pCtx->pSymbolsCount)++; + const bool hasSymbols = (moduleInfo.SymType != SymNone && moduleInfo.SymType != SymDeferred && moduleInfo.LoadedPdbName[0] != '\0'); + + if (hasSymbols) + { + (*pCtx->pSymbolsCount)++; #ifdef _DEBUG - std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - " Module: %s [Base: 0x%llX] - Symbols loaded via SymLoadModuleEx\n", - ModuleName, BaseOfDll); + std::array debugBuffer{}; + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), " Module: %s [Base: 0x%llX, SymType: %d, PDB: %s]\n", + ModuleName ? ModuleName : "", BaseOfDll, moduleInfo.SymType, moduleInfo.LoadedPdbName); +#endif + } + else + { + (*pCtx->pNeedingLoad)++; + if (ModuleName && ModuleName[0] != '\0') + { + const DWORD64 loadedBase = SymLoadModuleEx(pCtx->hProcess, nullptr, ModuleName, nullptr, BaseOfDll, 0, nullptr, 0); + if (loadedBase != 0) + { + (*pCtx->pSymbolsCount)++; +#ifdef _DEBUG + std::array debugBuffer{}; + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), + " Module: %s [Base: 0x%llX] - Symbols loaded via SymLoadModuleEx\n", ModuleName, BaseOfDll); +#endif + } +#ifdef _DEBUG + else + { + const DWORD loadError = GetLastError(); + std::array debugBuffer{}; + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), + " Module: %s [Base: 0x%llX] - SymLoadModuleEx FAILED (error 0x%08X)\n", ModuleName, BaseOfDll, + loadError); + } #endif + } + } } #ifdef _DEBUG else { - const DWORD loadError = GetLastError(); + const DWORD moduleInfoError = GetLastError(); std::array debugBuffer{}; SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - " Module: %s [Base: 0x%llX] - SymLoadModuleEx FAILED (error 0x%08X)\n", - ModuleName, BaseOfDll, loadError); + " Module: %s [Base: 0x%llX] - SymGetModuleInfo64 FAILED (error 0x%08X)\n", + ModuleName ? ModuleName : "", BaseOfDll, moduleInfoError); } #endif - } - } - } -#ifdef _DEBUG - else + return TRUE; + }, + &enumCtx) == FALSE) { - const DWORD moduleInfoError = GetLastError(); + const DWORD enumError = GetLastError(); std::array debugBuffer{}; SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - " Module: %s [Base: 0x%llX] - SymGetModuleInfo64 FAILED (error 0x%08X)\n", - ModuleName ? ModuleName : "", BaseOfDll, moduleInfoError); + "CrashHandler: InitializeSymbolHandler - WARNING: SymEnumerateModules64 failed with error 0x%08X\n", enumError); + return false; } -#endif - return TRUE; - }, &enumCtx) == FALSE) - { - const DWORD enumError = GetLastError(); + std::array debugBuffer{}; SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - WARNING: SymEnumerateModules64 failed with error 0x%08X\n", - enumError); - return false; + "CrashHandler: InitializeSymbolHandler - Enumerated %lu modules, %lu with symbols (%lu needed explicit load)\n", moduleCount, + symbolsLoadedCount, modulesNeedingLoad); + + if (symbolsLoadedCount == 0 && moduleCount > 0) + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - CRITICAL: Zero symbols loaded despite modules present!\n"); + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Possible causes: PDB mismatch, wrong paths, or corrupted symbols\n"); + } + + return true; + }; + + bool enumerationOk = enumerateModules(); + + if ((!enumerationOk || moduleCount == 0) && RegisterProcessModulesWithDbgHelp(hProcess)) + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Module table rebuilt after EnumProcessModules registration\n"); + enumerationOk = enumerateModules(); } - std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: InitializeSymbolHandler - Enumerated %lu modules, %lu with symbols (%lu needed explicit load)\n", - moduleCount, symbolsLoadedCount, modulesNeedingLoad); + if (!enumerationOk) + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR: Unable to enumerate modules, cleaning up symbol handler\n"); + SymCleanup(hProcess); + return false; + } - if (symbolsLoadedCount == 0 && moduleCount > 0) + if (moduleCount == 0) { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - CRITICAL: Zero symbols loaded despite modules present!\n"); - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Possible causes: PDB mismatch, wrong paths, or corrupted symbols\n"); + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR: Symbol handler initialized but module list is empty\n"); + SymCleanup(hProcess); + return false; } - return true; - }; + g_symbolProcess.store(hProcess, std::memory_order_release); + g_symbolsInitialized.store(true, std::memory_order_release); - bool enumerationOk = enumerateModules(); + const auto validationOk = (symbolsLoadedCount > 0 || moduleCount == 0); - if ((!enumerationOk || moduleCount == 0) && RegisterProcessModulesWithDbgHelp(hProcess)) - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Module table rebuilt after EnumProcessModules registration\n"); - enumerationOk = enumerateModules(); - } + if (validationOk) [[likely]] + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Symbol handler initialized successfully\n"); + } + else [[unlikely]] + { + SafeDebugOutput("CrashHandler: InitializeSymbolHandler - WARNING: Initialized but no symbols loaded!\n"); + } - if (!enumerationOk) - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR: Unable to enumerate modules, cleaning up symbol handler\n"); - SymCleanup(hProcess); - return false; + return true; } - if (moduleCount == 0) - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - ERROR: Symbol handler initialized but module list is empty\n"); - SymCleanup(hProcess); - return false; - } - - g_symbolProcess.store(hProcess, std::memory_order_release); - g_symbolsInitialized.store(true, std::memory_order_release); - - const auto validationOk = (symbolsLoadedCount > 0 || moduleCount == 0); - - if (validationOk) [[likely]] - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - Symbol handler initialized successfully\n"); - } - else [[unlikely]] - { - SafeDebugOutput("CrashHandler: InitializeSymbolHandler - WARNING: Initialized but no symbols loaded!\n"); - } - - return true; } -} // namespace CrashHandler - [[nodiscard]] BOOL __stdcall SetCrashHandlerFilter(PFNCHFILTFN pFn) { if (pFn == nullptr) @@ -1591,19 +1557,21 @@ namespace CrashHandler g_pfnCrashCallback.store(pFn, std::memory_order_seq_cst); std::array debugBuffer{}; - SAFE_DEBUG_PRINT(debugBuffer, "%.*sInstalling handlers with callback at 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), reinterpret_cast(pFn)); + SAFE_DEBUG_PRINT(debugBuffer, "%.*sInstalling handlers with callback at 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), + reinterpret_cast(pFn)); SafeDebugOutput("========================================\n"); SafeDebugOutput("CrashHandler: Starting PDB detection and symbol initialization\n"); SafeDebugOutput("========================================\n"); - + // Warm up PDB detection early to avoid filesystem scan during crash handling // This performs the recursive directory search now rather than during exception processing const bool hasSymbols = CrashHandler::ProcessHasLocalDebugSymbols(); - + SafeDebugOutput("========================================\n"); - SAFE_DEBUG_PRINT(debugBuffer, "%.*sDebug symbols %s\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), hasSymbols ? "DETECTED" : "not found"); - + SAFE_DEBUG_PRINT(debugBuffer, "%.*sDebug symbols %s\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), + hasSymbols ? "DETECTED" : "not found"); + if (hasSymbols) { if (CrashHandler::InitializeSymbolHandler()) @@ -1645,7 +1613,8 @@ namespace CrashHandler g_bStackCookieCaptureEnabled.store(bEnableBool, std::memory_order_release); std::array szDebug{}; - SAFE_DEBUG_PRINT(szDebug, "%.*sStack cookie failure capture %s\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), bEnableBool ? "ENABLED" : "DISABLED"); + SAFE_DEBUG_PRINT(szDebug, "%.*sStack cookie failure capture %s\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), + bEnableBool ? "ENABLED" : "DISABLED"); if (bEnableBool) { @@ -1669,8 +1638,7 @@ namespace CrashHandler const int errnoValue = errno; constexpr auto bufferSize = DEBUG_BUFFER_SIZE; std::array szDebug{}; - SAFE_DEBUG_PRINT_C(szDebug.data(), bufferSize, - "CrashHandler: WARNING - Failed to restore SIGABRT handler, errno: %d\n", errnoValue); + SAFE_DEBUG_PRINT_C(szDebug.data(), bufferSize, "CrashHandler: WARNING - Failed to restore SIGABRT handler, errno: %d\n", errnoValue); } else { @@ -1779,7 +1747,7 @@ static bool ConfigureWerLocalDumps() } const SString& baseDir = SharedUtil::GetMTAProcessBaseDir(); - SString mtaDumpPath = PathJoin(baseDir, "mta\\dumps\\private"); + SString mtaDumpPath = PathJoin(baseDir, "mta\\dumps\\private"); if (!CreateDirectoryA(PathJoin(baseDir, "mta\\dumps"), nullptr)) { @@ -1804,8 +1772,7 @@ static bool ConfigureWerLocalDumps() HMODULE hWer = LoadLibraryW(L"wer.dll"); if (hWer) { - auto pfnWerRegisterAppLocalDump = reinterpret_cast( - GetProcAddress(hWer, "WerRegisterAppLocalDump")); + auto pfnWerRegisterAppLocalDump = reinterpret_cast(GetProcAddress(hWer, "WerRegisterAppLocalDump")); if (pfnWerRegisterAppLocalDump) { @@ -1824,8 +1791,7 @@ static bool ConfigureWerLocalDumps() } std::array debugBuffer{}; - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: WerRegisterAppLocalDump failed with 0x%08X, trying registry fallback\n", + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: WerRegisterAppLocalDump failed with 0x%08X, trying registry fallback\n", static_cast(hr)); } else @@ -1840,21 +1806,19 @@ static bool ConfigureWerLocalDumps() std::array debugBuffer{}; - HKEY hKey = nullptr; + HKEY hKey = nullptr; const wchar_t* exeName = wcsrchr(modulePath, L'\\'); exeName = exeName ? exeName + 1 : modulePath; wchar_t regPath[512]{}; - _snwprintf_s(regPath, _countof(regPath), _TRUNCATE, - L"SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\%s", exeName); + _snwprintf_s(regPath, _countof(regPath), _TRUNCATE, L"SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\%s", exeName); // LocalDumps registry settings are only supported in HKEY_LOCAL_MACHINE (requires admin to write) // First try to create/open with write access - succeeds if running as admin // Use KEY_WOW64_64KEY to write to the 64-bit registry view. // WER is a 64-bit system service that reads from the native 64-bit registry, // not the WOW6432Node that 32-bit apps normally access. - LONG result = RegCreateKeyExW(HKEY_LOCAL_MACHINE, regPath, 0, nullptr, - REG_OPTION_NON_VOLATILE, KEY_SET_VALUE | KEY_WOW64_64KEY, nullptr, &hKey, nullptr); + LONG result = RegCreateKeyExW(HKEY_LOCAL_MACHINE, regPath, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE | KEY_WOW64_64KEY, nullptr, &hKey, nullptr); if (result == ERROR_SUCCESS) { // We have write access (running as admin) - update values to ensure correct path @@ -1865,8 +1829,7 @@ static bool ConfigureWerLocalDumps() DWORD dumpCount = 10; RegSetValueExW(hKey, L"DumpCount", 0, REG_DWORD, reinterpret_cast(&dumpCount), sizeof(dumpCount)); - RegSetValueExW(hKey, L"DumpFolder", 0, REG_EXPAND_SZ, - reinterpret_cast(dumpPathW.c_str()), + RegSetValueExW(hKey, L"DumpFolder", 0, REG_EXPAND_SZ, reinterpret_cast(dumpPathW.c_str()), static_cast((dumpPathW.length() + 1) * sizeof(wchar_t))); RegCloseKey(hKey); @@ -1881,12 +1844,11 @@ static bool ConfigureWerLocalDumps() if (result == ERROR_SUCCESS) { wchar_t existingPath[MAX_PATH]{}; - DWORD pathSize = sizeof(existingPath); - DWORD pathType = 0; + DWORD pathSize = sizeof(existingPath); + DWORD pathType = 0; bool pathCorrect = false; - if (RegQueryValueExW(hKey, L"DumpFolder", nullptr, &pathType, - reinterpret_cast(existingPath), &pathSize) == ERROR_SUCCESS) + if (RegQueryValueExW(hKey, L"DumpFolder", nullptr, &pathType, reinterpret_cast(existingPath), &pathSize) == ERROR_SUCCESS) { if (pathType == REG_SZ || pathType == REG_EXPAND_SZ) { @@ -1905,18 +1867,15 @@ static bool ConfigureWerLocalDumps() } else { - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: WARNING - WER LocalDumps exists but points to wrong path!\n"); - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: Expected: %s\n", ToUTF8(dumpPathW).c_str()); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: WARNING - WER LocalDumps exists but points to wrong path!\n"); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: Expected: %s\n", ToUTF8(dumpPathW).c_str()); SafeDebugOutput("CrashHandler: Run MTA as admin once OR reinstall to fix WER dump path\n"); return false; } } // Neither write nor read succeeded - WER dumps won't work - SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), - "CrashHandler: Failed to access WER registry key in HKLM (error %ld)\n", result); + SAFE_DEBUG_PRINT_C(debugBuffer.data(), debugBuffer.size(), "CrashHandler: Failed to access WER registry key in HKLM (error %ld)\n", result); SafeDebugOutput("CrashHandler: WER LocalDumps requires either admin privileges or installer setup\n"); SafeDebugOutput("CrashHandler: NOTE: Reinstall MTA or run as admin once to enable WER crash dumps\n"); return false; @@ -1931,7 +1890,7 @@ static bool ConfigureWerLocalDumps() return false; const std::uint8_t rawChar{static_cast(buffer[0])}; - const char indicator{static_cast(std::tolower(rawChar))}; + const char indicator{static_cast(std::tolower(rawChar))}; outValue = !(indicator == '0' || indicator == 'f' || indicator == 'n'); return true; } @@ -1943,8 +1902,8 @@ static bool ConfigureWerLocalDumps() memset(pConfig, 0, sizeof(CRASH_HANDLER_CONFIG)); - auto disableSehDetourBool{false}; - auto forceSehDetourBool{false}; + auto disableSehDetourBool{false}; + auto forceSehDetourBool{false}; [[maybe_unused]] const auto r1 = TryReadEnvBool("MTA_DISABLE_SEH_DETOUR", disableSehDetourBool); [[maybe_unused]] const auto r2 = TryReadEnvBool("MTA_FORCE_SEH_DETOUR", forceSehDetourBool); @@ -1969,12 +1928,11 @@ static bool ConfigureWerLocalDumps() // Helper to perform protected stack walk for callback exceptions static BOOL ProtectedStackWalk64(DWORD machineType, HANDLE hProcess, HANDLE hThread, STACKFRAME64* frame, CONTEXT* context, - const StackTraceHelpers::StackWalkRoutines& routines) + const StackTraceHelpers::StackWalkRoutines& routines) { __try { - return StackWalk64(machineType, hProcess, hThread, frame, context, - routines.readMemory, routines.functionTableAccess, routines.moduleBase, nullptr); + return StackWalk64(machineType, hProcess, hThread, frame, context, routines.readMemory, routines.functionTableAccess, routines.moduleBase, nullptr); } __except (EXCEPTION_EXECUTE_HANDLER) { @@ -2031,33 +1989,28 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD const auto hasSymbols = CrashHandler::ProcessHasLocalDebugSymbols(); const auto initializedAtEntry = g_symbolsInitialized.load(std::memory_order_acquire); - - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Entry: hasSymbols=%s, initialized=%s\n", - hasSymbols ? "true" : "false", - initializedAtEntry ? "true" : "false"); - + + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Entry: hasSymbols=%s, initialized=%s\n", hasSymbols ? "true" : "false", + initializedAtEntry ? "true" : "false"); + if (!hasSymbols) { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - PDB detection returned FALSE - checking GetPdbDirectories()...\n"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - PDB detection returned FALSE - checking GetPdbDirectories()...\n"); const auto& pdbDirs = CrashHandler::GetPdbDirectories(); - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - GetPdbDirectories() returned %zu directories\n", pdbDirs.size()); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - GetPdbDirectories() returned %zu directories\n", pdbDirs.size()); } - + if (!hasSymbols) { static std::once_flag logOnce; - std::call_once(logOnce, [] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - capturing without symbols (raw addresses only)\n"); - }); + std::call_once(logOnce, + [] { SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - capturing without symbols (raw addresses only)\n"); }); } // Check if this is a callback exception - these have special handling requirements - const bool isCallbackException = (pException->ExceptionRecord != nullptr && - pException->ExceptionRecord->ExceptionCode == STATUS_FATAL_USER_CALLBACK_EXCEPTION); - + const bool isCallbackException = + (pException->ExceptionRecord != nullptr && pException->ExceptionRecord->ExceptionCode == STATUS_FATAL_USER_CALLBACK_EXCEPTION); + // Handle null ContextRecord - can occur with callbacks and other severe exceptions if (pException->ContextRecord == nullptr) { @@ -2071,7 +2024,7 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD } return FALSE; } - + if (isCallbackException) { SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Callback exception: using defensive stack capture\n"); @@ -2108,19 +2061,17 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD const bool hasControlContext = (context.ContextFlags & CONTEXT_CONTROL) != 0; if (!hasControlContext) { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Incomplete context (flags=0x%08X), cannot walk stack%s\n", - context.ContextFlags, - isCallbackException ? " (callback exception)" : ""); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Incomplete context (flags=0x%08X), cannot walk stack%s\n", context.ContextFlags, + isCallbackException ? " (callback exception)" : ""); return FALSE; } // For EIP=0 crashes, start stack walk from return address at [ESP] constexpr auto kNullAddress = uintptr_t{0}; static_assert(kNullAddress == 0, "Null address constant must be zero"); - + const auto isNullJump = (context.Eip == kNullAddress); - + if (isNullJump) { // Try to read return address from [ESP] @@ -2131,8 +2082,7 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD { const auto returnAddr{reinterpret_cast(*pReturnAddress)}; - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - EIP=0, starting stack walk from return address: 0x%08X\n", + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - EIP=0, starting stack walk from return address: 0x%08X\n", static_cast(returnAddr)); // Start stack walk from return address instead of null EIP @@ -2142,8 +2092,7 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD } else { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - EIP=0, ESP not readable (0x%08X), cannot capture stack\n", + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - EIP=0, ESP not readable (0x%08X), cannot capture stack\n", static_cast(espAddr)); return FALSE; } @@ -2160,35 +2109,29 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD frame.AddrStack.Mode = AddrModeFlat; auto symbolsAvailable = hasSymbols && initializedAtEntry; - + if (hasSymbols && !symbolsAvailable) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Symbols detected but handler not initialized, attempting late init\n"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Symbols detected but handler not initialized, attempting late init\n"); symbolsAvailable = CrashHandler::InitializeSymbolHandler(); - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Late init result: %s\n", symbolsAvailable ? "SUCCESS" : "FAILED"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Late init result: %s\n", symbolsAvailable ? "SUCCESS" : "FAILED"); } - const auto useDbgHelp = symbolsAvailable; + const auto useDbgHelp = symbolsAvailable; const HANDLE symHandle = g_symbolProcess.load(std::memory_order_acquire); - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Using DbgHelp: %s (symbolsAvailable=%s)\n", - useDbgHelp ? "YES" : "NO", - symbolsAvailable ? "true" : "false"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Using DbgHelp: %s (symbolsAvailable=%s)\n", useDbgHelp ? "YES" : "NO", + symbolsAvailable ? "true" : "false"); if (useDbgHelp && symHandle != nullptr) { if (SymRefreshModuleList(symHandle) == FALSE) { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - SymRefreshModuleList failed before stack walk\n"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - SymRefreshModuleList failed before stack walk\n"); } else { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - SymRefreshModuleList succeeded before stack walk\n"); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - SymRefreshModuleList succeeded before stack walk\n"); } [[maybe_unused]] const bool modulesRegistered = RegisterProcessModulesWithDbgHelp(symHandle); @@ -2198,20 +2141,20 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD constexpr auto kMaxSymbolNameLength = std::size_t{2048}; constexpr auto symbolBufferSize = sizeof(SYMBOL_INFO) + kMaxSymbolNameLength; - + alignas(SYMBOL_INFO) auto symbolBuffer = std::array{}; - auto* const pSymbol = reinterpret_cast(symbolBuffer.data()); + auto* const pSymbol = reinterpret_cast(symbolBuffer.data()); pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); pSymbol->MaxNameLen = kMaxSymbolNameLength; constexpr auto machineType = IMAGE_FILE_MACHINE_I386; - + for (auto frameIndex : std::views::iota(DWORD{0}, actualMaxFrames)) { // Always use protected stack walking as the stack might be corrupted // (e.g. stack overflow, buffer overrun, or just garbage pointers) BOOL bWalked = ProtectedStackWalk64(machineType, hProcess, hThread, &frame, &context, routines); - + if (bWalked == FALSE) { if (isCallbackException) @@ -2225,37 +2168,32 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD break; const auto address = frame.AddrPC.Offset; - - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: address=0x%llX, useDbgHelp=%s\n", - frameIndex, address, useDbgHelp ? "true" : "false"); - + + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: address=0x%llX, useDbgHelp=%s\n", frameIndex, address, + useDbgHelp ? "true" : "false"); + if (!useDbgHelp) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Using fallback formatting (no DbgHelp)\n", frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Using fallback formatting (no DbgHelp)\n", frameIndex); pOutTrace->emplace_back(StackTraceHelpers::FormatAddressWithModuleAndAbsolute(address)); continue; } - + if (symHandle == nullptr) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: symHandle is NULL\n", frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: symHandle is NULL\n", frameIndex); pOutTrace->emplace_back(StackTraceHelpers::FormatAddressWithModuleAndAbsolute(address)); continue; } - - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: symHandle=0x%p\n", frameIndex, symHandle); - + + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: symHandle=0x%p\n", frameIndex, symHandle); + auto moduleBase = SymGetModuleBase64(symHandle, address); if (moduleBase == 0) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Address not in any loaded module, attempting registration\n", - frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Address not in any loaded module, attempting registration\n", + frameIndex); if (RegisterModuleForAddress(symHandle, address)) { @@ -2266,54 +2204,46 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD if (moduleBase == 0) [[unlikely]] { SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Address still not associated with a module after registration attempt\n", - frameIndex); + "CaptureUnifiedStackTrace - Frame %lu: Address still not associated with a module after registration attempt\n", frameIndex); pOutTrace->emplace_back(StackTraceHelpers::FormatAddressWithModuleAndAbsolute(address)); continue; } - - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: moduleBase=0x%llX\n", frameIndex, moduleBase); - + + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: moduleBase=0x%llX\n", frameIndex, moduleBase); + std::string symbolName; symbolName.resize(64); _snprintf_s(symbolName.data(), symbolName.size(), _TRUNCATE, "0x%llX", address); symbolName.resize(std::strlen(symbolName.c_str())); - + if (!SafeSymFromAddr(symHandle, address, pSymbol, isCallbackException)) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: SymFromAddr failed\n", frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: SymFromAddr failed\n", frameIndex); symbolName.resize(64); _snprintf_s(symbolName.data(), symbolName.size(), _TRUNCATE, "0x%llX [lookup failed]", address); symbolName.resize(std::strlen(symbolName.c_str())); } else if (const auto nameView = std::string_view{pSymbol->Name ? pSymbol->Name : ""}; nameView.empty()) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Symbol lookup succeeded but name is empty\n", frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Symbol lookup succeeded but name is empty\n", frameIndex); symbolName.resize(64); _snprintf_s(symbolName.data(), symbolName.size(), _TRUNCATE, "0x%llX [no symbol]", address); symbolName.resize(std::strlen(symbolName.c_str())); } else [[likely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Resolved symbol '%s'\n", frameIndex, pSymbol->Name); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Resolved symbol '%s'\n", frameIndex, pSymbol->Name); symbolName.assign(nameView.begin(), nameView.end()); } - - IMAGEHLP_LINE64 lineInfo{ - .SizeOfStruct = sizeof(IMAGEHLP_LINE64) - }; - auto lineDisplacement = DWORD{0}; - + + IMAGEHLP_LINE64 lineInfo{.SizeOfStruct = sizeof(IMAGEHLP_LINE64)}; + auto lineDisplacement = DWORD{0}; + std::string frameInfo; - + if (!SafeSymGetLineFromAddr64(symHandle, address, &lineDisplacement, &lineInfo, isCallbackException)) [[unlikely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: No line info available\n", frameIndex); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: No line info available\n", frameIndex); frameInfo.resize(256); _snprintf_s(frameInfo.data(), frameInfo.size(), _TRUNCATE, "%s [0x%llX]", symbolName.c_str(), address); frameInfo.resize(std::strlen(frameInfo.c_str())); @@ -2326,18 +2256,16 @@ static bool SafeSymGetLineFromAddr64(HANDLE hProcess, DWORD64 address, DWORD* pD } else [[likely]] { - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Line info: %s:%lu\n", - frameIndex, lineInfo.FileName, lineInfo.LineNumber); + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Line info: %s:%lu\n", frameIndex, lineInfo.FileName, + lineInfo.LineNumber); frameInfo.resize(512); - _snprintf_s(frameInfo.data(), frameInfo.size(), _TRUNCATE, "%s (%.*s:%lu) [0x%llX]", - symbolName.c_str(), static_cast(fileName.size()), fileName.data(), lineInfo.LineNumber, address); + _snprintf_s(frameInfo.data(), frameInfo.size(), _TRUNCATE, "%s (%.*s:%lu) [0x%llX]", symbolName.c_str(), static_cast(fileName.size()), + fileName.data(), lineInfo.LineNumber, address); frameInfo.resize(std::strlen(frameInfo.c_str())); } - - SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, - "CaptureUnifiedStackTrace - Frame %lu: Final: %s\n", frameIndex, frameInfo.c_str()); - + + SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "CaptureUnifiedStackTrace - Frame %lu: Final: %s\n", frameIndex, frameInfo.c_str()); + pOutTrace->emplace_back(std::move(frameInfo)); } @@ -2362,7 +2290,8 @@ static bool InstallSehHandler() std::array szDebug{}; if (previousFilter != nullptr) { - SAFE_DEBUG_PRINT(szDebug, "%.*sSEH installed, previous filter at 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), static_cast(previousFilter)); + SAFE_DEBUG_PRINT(szDebug, "%.*sSEH installed, previous filter at 0x%p\n", static_cast(DEBUG_PREFIX_CRASH.size()), DEBUG_PREFIX_CRASH.data(), + static_cast(previousFilter)); } else { @@ -2727,7 +2656,7 @@ static BOOL TryLogEnhancedExceptionInfo(EXCEPTION_POINTERS* pException) catch (...) { SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogExceptionDetails - Exception caught in LogEnhancedExceptionInfo\n"); - return TRUE; // Return TRUE to indicate we handled the attempt, even if it failed + return TRUE; // Return TRUE to indicate we handled the attempt, even if it failed } } @@ -2744,12 +2673,12 @@ static BOOL TryLogEnhancedExceptionInfo(EXCEPTION_POINTERS* pException) } SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogExceptionDetails - pException OK\n"); - + if (pException->ExceptionRecord != nullptr) SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogExceptionDetails - ExceptionRecord OK\n"); else SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogExceptionDetails - ExceptionRecord is NULL\n"); - + if (pException->ContextRecord != nullptr) SafeDebugPrintPrefixed(DEBUG_PREFIX_CRASH, "LogExceptionDetails - ContextRecord OK\n"); else @@ -2840,7 +2769,7 @@ LONG __stdcall CrashHandlerExceptionFilter(EXCEPTION_POINTERS* pExPtrs) LONG lRet{EXCEPTION_CONTINUE_SEARCH}; static std::atomic bHandlerActive{false}; - bool expected{false}; + bool expected{false}; if (!bHandlerActive.compare_exchange_strong(expected, true, std::memory_order_acq_rel, std::memory_order_relaxed)) { @@ -2993,7 +2922,6 @@ namespace class HandleGuard { - public: HandleGuard() = default; explicit HandleGuard(HANDLE handle) : m_handle(handle) {} @@ -3041,10 +2969,10 @@ namespace alignas(hardware_destructive_interference_size) std::atomic lastHeartbeat{std::chrono::steady_clock::now()}; alignas(hardware_destructive_interference_size) std::atomic targetThreadId{0}; alignas(hardware_destructive_interference_size) std::atomic timeoutSeconds{20}; - + // Non-atomic handle doesn't need cache-line alignment HANDLE watchdogThreadHandle{nullptr}; - + ~WatchdogState() { // Note: watchdogThreadHandle should be closed by StopWatchdogThread, @@ -3057,46 +2985,39 @@ namespace } }; - static_assert(std::is_trivially_copyable_v, - "time_point must be trivially copyable for use with std::atomic"); + static_assert(std::is_trivially_copyable_v, "time_point must be trivially copyable for use with std::atomic"); static_assert(std::has_unique_object_representations_v, "time_point must have unique object representations for atomic operations"); - static_assert(std::atomic::is_always_lock_free, - "bool atomics must be lock-free on this platform"); - static_assert(std::atomic::is_always_lock_free, - "DWORD atomics must be lock-free on this platform"); - + static_assert(std::atomic::is_always_lock_free, "bool atomics must be lock-free on this platform"); + static_assert(std::atomic::is_always_lock_free, "DWORD atomics must be lock-free on this platform"); + // Validate timeout constraints at compile-time using std::conjunction - template - using valid_range = std::conjunction< - std::bool_constant<(Min > 0)>, - std::bool_constant<(Max >= Min)> - >; - + template + using valid_range = std::conjunction 0)>, std::bool_constant<(Max >= Min)> >; + inline WatchdogState g_watchdogState{}; - + [[nodiscard]] static bool TriggerWatchdogException(HANDLE targetThread, DWORD targetThreadId) { - AddReportLog(9300, SString("Watchdog freeze detected after %u seconds (thread %u)", - g_watchdogState.timeoutSeconds.load(std::memory_order_relaxed), + AddReportLog(9300, SString("Watchdog freeze detected after %u seconds (thread %u)", g_watchdogState.timeoutSeconds.load(std::memory_order_relaxed), targetThreadId)); - + // Suspend the thread once and capture everything while suspended if (SuspendThread(targetThread) == static_cast(-1)) { AddReportLog(9301, SString("Watchdog failed to suspend thread %u", targetThreadId)); return false; } - + // Thread is now suspended - capture context CONTEXT context{}; context.ContextFlags = CONTEXT_FULL; - + if (GetThreadContext(targetThread, &context) == FALSE) { AddReportLog(9302, SString("Watchdog failed to capture thread context for %u", targetThreadId)); - + // Must resume thread before returning! if (ResumeThread(targetThread) == static_cast(-1)) { @@ -3104,7 +3025,7 @@ namespace } return false; } - + // Create exception record and pointers for stack walking (thread still suspended) EXCEPTION_RECORD exceptionRecord{}; exceptionRecord.ExceptionCode = CUSTOM_EXCEPTION_CODE_WATCHDOG_TIMEOUT; @@ -3113,19 +3034,19 @@ namespace exceptionRecord.NumberParameters = 2; exceptionRecord.ExceptionInformation[0] = targetThreadId; exceptionRecord.ExceptionInformation[1] = g_watchdogState.timeoutSeconds.load(std::memory_order_relaxed); - + // Use static storage to keep exception pointers alive static thread_local CONTEXT s_capturedContext{}; s_capturedContext = context; - + EXCEPTION_POINTERS exceptionPointers{}; exceptionPointers.ExceptionRecord = &exceptionRecord; exceptionPointers.ContextRecord = &s_capturedContext; - + // Capture stack trace NOW while thread is still suspended - prevents race conditions std::vector stackTraceVec{}; - const auto stackCaptured = CaptureUnifiedStackTrace(&exceptionPointers, 32, &stackTraceVec); - + const auto stackCaptured = CaptureUnifiedStackTrace(&exceptionPointers, 32, &stackTraceVec); + // Now we can safely resume the thread - we have everything we need if (ResumeThread(targetThread) == static_cast(-1)) { @@ -3134,7 +3055,7 @@ namespace } AddReportLog(9305, SString("Watchdog captured context for thread %u", targetThreadId)); - + // Store enhanced exception info try { @@ -3142,7 +3063,8 @@ namespace if (std::unique_lock lock{g_exceptionInfoMutex, std::try_to_lock}; lock.owns_lock()) { // For cleaner initialization - g_lastExceptionInfo = [&]() { + g_lastExceptionInfo = [&]() + { ENHANCED_EXCEPTION_INFO info{}; info.exceptionCode = CUSTOM_EXCEPTION_CODE_WATCHDOG_TIMEOUT; info.exceptionAddress = exceptionRecord.ExceptionAddress; @@ -3151,10 +3073,10 @@ namespace info.processId = GetCurrentProcessId(); info.exceptionType = "Watchdog Timeout (Application Freeze)"; info.isFatal = true; - + const auto timeoutSecs = g_watchdogState.timeoutSeconds.load(std::memory_order_relaxed); info.additionalInfo = "Application became unresponsive for " + std::to_string(timeoutSecs) + " seconds"; - + info.eax = s_capturedContext.Eax; info.ebx = s_capturedContext.Ebx; info.ecx = s_capturedContext.Ecx; @@ -3171,14 +3093,14 @@ namespace info.fs = s_capturedContext.SegFs; info.gs = s_capturedContext.SegGs; info.eflags = s_capturedContext.EFlags; - + // Use the stack trace we captured while thread was suspended if (stackCaptured != FALSE && !stackTraceVec.empty()) { info.stackTrace = std::move(stackTraceVec); info.hasDetailedStackTrace = true; } - + return info; // Guaranteed copy - no move, no copy }(); } @@ -3199,25 +3121,25 @@ namespace AddReportLog(9308, "Watchdog exception while storing enhanced info"); } } - + // Trigger the global exception handler CCrashDumpWriter::HandleExceptionGlobal(&exceptionPointers); - + return true; } - + [[nodiscard]] static unsigned int __stdcall WatchdogThreadProc(void* /*pParameter*/) { AddReportLog(9309, "Watchdog thread started"); - + constexpr auto kCheckInterval = std::chrono::milliseconds{500}; static_assert(kCheckInterval.count() > 0, "Check interval must be positive"); - + const auto targetThreadId = g_watchdogState.targetThreadId.load(std::memory_order_acquire); - + // Open handle to target thread constexpr DWORD kThreadAccess = THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION; - HandleGuard targetThread{OpenThread(kThreadAccess, FALSE, targetThreadId)}; + HandleGuard targetThread{OpenThread(kThreadAccess, FALSE, targetThreadId)}; if (!targetThread) { @@ -3238,9 +3160,7 @@ namespace if (elapsed.count() >= static_cast(timeoutSecs)) { - AddReportLog(9311, SString("Watchdog detected freeze after %lld seconds (threshold %u)", - static_cast(elapsed.count()), - timeoutSecs)); + AddReportLog(9311, SString("Watchdog detected freeze after %lld seconds (threshold %u)", static_cast(elapsed.count()), timeoutSecs)); const bool triggered = TriggerWatchdogException(targetThread.get(), targetThreadId); if (!triggered) @@ -3272,12 +3192,12 @@ namespace AddReportLog(9314, "Watchdog thread already running"); return FALSE; } - + constexpr auto kMinTimeout = DWORD{5}; constexpr auto kMaxTimeout = DWORD{300}; static_assert(kMinTimeout > 0, "Minimum timeout must be positive"); static_assert(kMaxTimeout >= kMinTimeout, "Maximum timeout must be >= minimum"); - + if (timeoutSeconds < kMinTimeout || timeoutSeconds > kMaxTimeout) { AddReportLog(9315, SString("Watchdog invalid timeout %u (allowed %u-%u)", timeoutSeconds, kMinTimeout, kMaxTimeout)); @@ -3285,22 +3205,15 @@ namespace g_watchdogState.running.store(false, std::memory_order_release); return FALSE; } - + g_watchdogState.targetThreadId.store(mainThreadId, std::memory_order_release); g_watchdogState.timeoutSeconds.store(timeoutSeconds, std::memory_order_release); g_watchdogState.shouldStop.store(false, std::memory_order_release); g_watchdogState.lastHeartbeat.store(std::chrono::steady_clock::now(), std::memory_order_release); - + constexpr unsigned int kStackSize = 0; - const auto threadHandle{reinterpret_cast(_beginthreadex( - nullptr, - kStackSize, - WatchdogThreadProc, - nullptr, - 0, - nullptr - ))}; - + const auto threadHandle{reinterpret_cast(_beginthreadex(nullptr, kStackSize, WatchdogThreadProc, nullptr, 0, nullptr))}; + HandleGuard watchdogHandle{threadHandle}; if (!watchdogHandle) @@ -3314,7 +3227,7 @@ namespace g_watchdogState.watchdogThreadHandle = watchdogHandle.release(); AddReportLog(9317, SString("Watchdog monitoring thread %u with %u second timeout", mainThreadId, timeoutSeconds)); - + return TRUE; } @@ -3327,19 +3240,17 @@ void BUGSUTIL_DLLINTERFACE __stdcall StopWatchdogThread() AddReportLog(9318, "Stopping watchdog thread"); g_watchdogState.shouldStop.store(true, std::memory_order_release); - - if (g_watchdogState.watchdogThreadHandle != nullptr && - g_watchdogState.watchdogThreadHandle != INVALID_HANDLE_VALUE) + + if (g_watchdogState.watchdogThreadHandle != nullptr && g_watchdogState.watchdogThreadHandle != INVALID_HANDLE_VALUE) { constexpr DWORD kWaitTimeout = 5000; - if (const auto waitResult = WaitForSingleObject(g_watchdogState.watchdogThreadHandle, kWaitTimeout); - waitResult != WAIT_OBJECT_0) + if (const auto waitResult = WaitForSingleObject(g_watchdogState.watchdogThreadHandle, kWaitTimeout); waitResult != WAIT_OBJECT_0) { AddReportLog(9319, "Watchdog thread forced termination"); TerminateThread(g_watchdogState.watchdogThreadHandle, 1); WaitForSingleObject(g_watchdogState.watchdogThreadHandle, INFINITE); } - + CloseHandle(g_watchdogState.watchdogThreadHandle); g_watchdogState.watchdogThreadHandle = nullptr; } @@ -3354,4 +3265,3 @@ void BUGSUTIL_DLLINTERFACE __stdcall UpdateWatchdogHeartbeat() g_watchdogState.lastHeartbeat.store(std::chrono::steady_clock::now(), std::memory_order_release); } } - diff --git a/Client/core/CrashHandler.h b/Client/core/CrashHandler.h index 47fd383973c..97a910e2b1d 100644 --- a/Client/core/CrashHandler.h +++ b/Client/core/CrashHandler.h @@ -143,7 +143,7 @@ inline void SafeDebugPrint(Buffer& buffer, const char* format, ...) if (format == nullptr) return; - auto* data = buffer.data(); + auto* data = buffer.data(); const std::size_t size = buffer.size(); if (data == nullptr || size == 0) @@ -166,7 +166,7 @@ inline void SafeDebugPrintC(char* buffer, std::size_t bufferSize, const char* fo va_end(args); } -#define SAFE_DEBUG_PRINT(buffer, ...) SafeDebugPrint((buffer), __VA_ARGS__) +#define SAFE_DEBUG_PRINT(buffer, ...) SafeDebugPrint((buffer), __VA_ARGS__) #define SAFE_DEBUG_PRINT_C(buffer, bufferSize, ...) SafeDebugPrintC((buffer), (bufferSize), __VA_ARGS__) inline void SafeDebugPrintPrefixed(std::string_view prefix, const char* format, ...) @@ -246,7 +246,7 @@ extern "C" [[nodiscard]] BOOL BUGSUTIL_DLLINTERFACE __stdcall GetCrashHandlerConfiguration(PCRASH_HANDLER_CONFIG pConfig); [[nodiscard]] BOOL BUGSUTIL_DLLINTERFACE __stdcall CaptureUnifiedStackTrace(_EXCEPTION_POINTERS* pException, DWORD maxFrames, - std::vector* pOutTrace); + std::vector* pOutTrace); [[nodiscard]] BOOL BUGSUTIL_DLLINTERFACE __stdcall EnableSehExceptionHandler(); @@ -269,4 +269,4 @@ extern "C" namespace CrashHandler { [[nodiscard]] bool ProcessHasLocalDebugSymbols(); -} \ No newline at end of file +} diff --git a/Client/core/DXHook/CDirect3DData.cpp b/Client/core/DXHook/CDirect3DData.cpp index 15aee8ef910..45c606eba0e 100644 --- a/Client/core/DXHook/CDirect3DData.cpp +++ b/Client/core/DXHook/CDirect3DData.cpp @@ -17,16 +17,8 @@ template <> CDirect3DData* CSingleton::m_pSingleton = NULL; CDirect3DData::CDirect3DData() - : m_mViewMatrix{} - , m_mProjMatrix{} - , m_mWorldMatrix{} - , m_hDeviceWindow(0) - , m_dwViewportX(0) - , m_dwViewportY(0) - , m_dwViewportWidth(0) - , m_dwViewportHeight(0) + : m_mViewMatrix{}, m_mProjMatrix{}, m_mWorldMatrix{}, m_hDeviceWindow(0), m_dwViewportX(0), m_dwViewportY(0), m_dwViewportWidth(0), m_dwViewportHeight(0) { - } CDirect3DData::~CDirect3DData() diff --git a/Client/core/DXHook/CDirect3DData.h b/Client/core/DXHook/CDirect3DData.h index 56e23116a69..5beababf5fe 100644 --- a/Client/core/DXHook/CDirect3DData.h +++ b/Client/core/DXHook/CDirect3DData.h @@ -20,8 +20,8 @@ class CDirect3DData : public CSingleton CDirect3DData(); ~CDirect3DData(); - void StoreTransform(D3DTRANSFORMSTATETYPE dwMatrixToStore, const D3DMATRIX* pMatrix); - void GetTransform(D3DTRANSFORMSTATETYPE dwRequestedMatrix, D3DMATRIX* pMatrixOut); + void StoreTransform(D3DTRANSFORMSTATETYPE dwMatrixToStore, const D3DMATRIX* pMatrix); + void GetTransform(D3DTRANSFORMSTATETYPE dwRequestedMatrix, D3DMATRIX* pMatrixOut); const D3DMATRIX* GetTransformPtr(D3DTRANSFORMSTATETYPE dwRequestedMatrix) const; HWND GetDeviceWindow() { return m_hDeviceWindow; }; diff --git a/Client/core/DXHook/CDirect3DEvents9.cpp b/Client/core/DXHook/CDirect3DEvents9.cpp index 5ae8ad34363..d5e6a21a42d 100644 --- a/Client/core/DXHook/CDirect3DEvents9.cpp +++ b/Client/core/DXHook/CDirect3DEvents9.cpp @@ -24,10 +24,9 @@ #include "Graphics/CVideoModeManager.h" #include "Graphics/CRenderItem.EffectTemplate.h" - -std::atomic g_bInMTAScene{false}; +std::atomic g_bInMTAScene{false}; extern std::atomic g_bInGTAScene; -void ResetGTASceneState(); +void ResetGTASceneState(); // Other variables static uint ms_RequiredAnisotropicLevel = 1; @@ -38,119 +37,119 @@ CShaderItem* g_pActiveShader = NULL; namespace { -struct SResolvedShaderState -{ - CShaderInstance* pInstance = nullptr; - CEffectWrap* pEffectWrap = nullptr; - ID3DXEffect* pEffect = nullptr; -}; + struct SResolvedShaderState + { + CShaderInstance* pInstance = nullptr; + CEffectWrap* pEffectWrap = nullptr; + ID3DXEffect* pEffect = nullptr; + }; -bool TryResolveShaderState(CShaderItem* pShaderItem, SResolvedShaderState& outState) -{ - if (!pShaderItem) - return false; + bool TryResolveShaderState(CShaderItem* pShaderItem, SResolvedShaderState& outState) + { + if (!pShaderItem) + return false; - CShaderInstance* pInstance = pShaderItem->m_pShaderInstance; - if (!pInstance) - return false; + CShaderInstance* pInstance = pShaderItem->m_pShaderInstance; + if (!pInstance) + return false; - CEffectWrap* pEffectWrap = pInstance->m_pEffectWrap; - if (!pEffectWrap) - return false; + CEffectWrap* pEffectWrap = pInstance->m_pEffectWrap; + if (!pEffectWrap) + return false; - outState.pInstance = pInstance; - outState.pEffectWrap = pEffectWrap; - outState.pEffect = pEffectWrap->m_pD3DEffect; - return true; -} + outState.pInstance = pInstance; + outState.pEffectWrap = pEffectWrap; + outState.pEffect = pEffectWrap->m_pD3DEffect; + return true; + } } namespace { -struct SToneMapVertex -{ - static const DWORD FVF = D3DFVF_XYZRHW | D3DFVF_TEX1; - float x, y, z, w; - float u, v; -}; + struct SToneMapVertex + { + static const DWORD FVF = D3DFVF_XYZRHW | D3DFVF_TEX1; + float x, y, z, w; + float u, v; + }; -class BorderlessToneMapPass -{ -public: - bool Apply(IDirect3DDevice9* device, float gammaPower, float brightnessScale, float contrastScale, float saturationScale); - void Release(); - -private: - bool EnsureResources(IDirect3DDevice9* device, UINT width, UINT height, D3DFORMAT format); - bool EnsureShader(IDirect3DDevice9* device); - bool EnsureStateBlock(IDirect3DDevice9* device); - void ReleaseTexture(); - void ReleaseShader(); - void ReleaseStateBlock(); - - IDirect3DTexture9* m_sourceTexture = nullptr; - IDirect3DSurface9* m_sourceSurface = nullptr; - IDirect3DPixelShader9* m_pixelShader = nullptr; - LPD3DXCONSTANTTABLE m_constantTable = nullptr; - D3DXHANDLE m_toneParamsHandle = nullptr; - IDirect3DStateBlock9* m_restoreStateBlock = nullptr; - IDirect3DStateBlock9* m_applyStateBlock = nullptr; - UINT m_width = 0; - UINT m_height = 0; - D3DFORMAT m_format = D3DFMT_UNKNOWN; - bool m_shaderFailed = false; -}; - -static BorderlessToneMapPass g_BorderlessToneMapPass; - -static void RunBorderlessToneMap(IDirect3DDevice9* device) -{ - if (!device) - return; + class BorderlessToneMapPass + { + public: + bool Apply(IDirect3DDevice9* device, float gammaPower, float brightnessScale, float contrastScale, float saturationScale); + void Release(); + + private: + bool EnsureResources(IDirect3DDevice9* device, UINT width, UINT height, D3DFORMAT format); + bool EnsureShader(IDirect3DDevice9* device); + bool EnsureStateBlock(IDirect3DDevice9* device); + void ReleaseTexture(); + void ReleaseShader(); + void ReleaseStateBlock(); + + IDirect3DTexture9* m_sourceTexture = nullptr; + IDirect3DSurface9* m_sourceSurface = nullptr; + IDirect3DPixelShader9* m_pixelShader = nullptr; + LPD3DXCONSTANTTABLE m_constantTable = nullptr; + D3DXHANDLE m_toneParamsHandle = nullptr; + IDirect3DStateBlock9* m_restoreStateBlock = nullptr; + IDirect3DStateBlock9* m_applyStateBlock = nullptr; + UINT m_width = 0; + UINT m_height = 0; + D3DFORMAT m_format = D3DFMT_UNKNOWN; + bool m_shaderFailed = false; + }; - bool isWindowed = false; - bool havePresentationState = false; - if (CVideoModeManagerInterface* videoModeManager = GetVideoModeManager()) - { - isWindowed = videoModeManager->IsDisplayModeWindowed() || videoModeManager->IsDisplayModeFullScreenWindow(); - havePresentationState = true; - } + static BorderlessToneMapPass g_BorderlessToneMapPass; - if (!havePresentationState && g_pDeviceState) + static void RunBorderlessToneMap(IDirect3DDevice9* device) { - const auto& params = g_pDeviceState->CreationState.PresentationParameters; - isWindowed = params.Windowed != 0; - havePresentationState = true; - } + if (!device) + return; - if (!havePresentationState) - return; + bool isWindowed = false; + bool havePresentationState = false; + if (CVideoModeManagerInterface* videoModeManager = GetVideoModeManager()) + { + isWindowed = videoModeManager->IsDisplayModeWindowed() || videoModeManager->IsDisplayModeFullScreenWindow(); + havePresentationState = true; + } - float gammaPower = 1.0f; - float brightnessScale = 1.0f; - float contrastScale = 1.0f; - float saturationScale = 1.0f; - bool applyWindowed = true; - bool applyFullscreen = false; - BorderlessGamma::FetchSettings(gammaPower, brightnessScale, contrastScale, saturationScale, applyWindowed, applyFullscreen); + if (!havePresentationState && g_pDeviceState) + { + const auto& params = g_pDeviceState->CreationState.PresentationParameters; + isWindowed = params.Windowed != 0; + havePresentationState = true; + } - const bool adjustmentsEnabled = isWindowed ? applyWindowed : applyFullscreen; - if (!adjustmentsEnabled) - { - g_BorderlessToneMapPass.Release(); - return; - } + if (!havePresentationState) + return; - if (!BorderlessGamma::ShouldApplyAdjustments(gammaPower, brightnessScale, contrastScale, saturationScale)) - return; + float gammaPower = 1.0f; + float brightnessScale = 1.0f; + float contrastScale = 1.0f; + float saturationScale = 1.0f; + bool applyWindowed = true; + bool applyFullscreen = false; + BorderlessGamma::FetchSettings(gammaPower, brightnessScale, contrastScale, saturationScale, applyWindowed, applyFullscreen); - if (!g_BorderlessToneMapPass.Apply(device, gammaPower, brightnessScale, contrastScale, saturationScale)) - { - // Fallback: release resources to allow retry on future frames. - g_BorderlessToneMapPass.Release(); + const bool adjustmentsEnabled = isWindowed ? applyWindowed : applyFullscreen; + if (!adjustmentsEnabled) + { + g_BorderlessToneMapPass.Release(); + return; + } + + if (!BorderlessGamma::ShouldApplyAdjustments(gammaPower, brightnessScale, contrastScale, saturationScale)) + return; + + if (!g_BorderlessToneMapPass.Apply(device, gammaPower, brightnessScale, contrastScale, saturationScale)) + { + // Fallback: release resources to allow retry on future frames. + g_BorderlessToneMapPass.Release(); + } } -} -} // namespace +} // namespace bool BorderlessToneMapPass::EnsureShader(IDirect3DDevice9* device) { @@ -177,11 +176,12 @@ bool BorderlessToneMapPass::EnsureShader(IDirect3DDevice9* device) " return color;\n" "}\n"; - LPD3DXBUFFER shaderBuffer = nullptr; - LPD3DXBUFFER errorBuffer = nullptr; + LPD3DXBUFFER shaderBuffer = nullptr; + LPD3DXBUFFER errorBuffer = nullptr; LPD3DXCONSTANTTABLE constantTable = nullptr; - HRESULT hr = D3DXCompileShader(kShaderSource, sizeof(kShaderSource) - 1, nullptr, nullptr, "main", "ps_2_0", 0, &shaderBuffer, &errorBuffer, &constantTable); + HRESULT hr = + D3DXCompileShader(kShaderSource, sizeof(kShaderSource) - 1, nullptr, nullptr, "main", "ps_2_0", 0, &shaderBuffer, &errorBuffer, &constantTable); if (FAILED(hr)) { SString message("BorderlessToneMap: pixel shader compile failed (%08x)", hr); @@ -239,7 +239,7 @@ bool BorderlessToneMapPass::EnsureStateBlock(IDirect3DDevice9* device) if (!m_applyStateBlock) { device->BeginStateBlock(); - + // Configure all render states for tone mapping pass device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); @@ -249,11 +249,11 @@ bool BorderlessToneMapPass::EnsureStateBlock(IDirect3DDevice9* device) device->SetRenderState(D3DRS_FOGENABLE, FALSE); device->SetRenderState(D3DRS_STENCILENABLE, FALSE); device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE); - + device->SetPixelShader(m_pixelShader); device->SetVertexShader(nullptr); device->SetFVF(SToneMapVertex::FVF); - + device->SetTexture(0, m_sourceTexture); device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); @@ -261,7 +261,7 @@ bool BorderlessToneMapPass::EnsureStateBlock(IDirect3DDevice9* device) device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, FALSE); - + IDirect3DStateBlock9* applyBlock = nullptr; if (FAILED(device->EndStateBlock(&applyBlock)) || !applyBlock) { @@ -315,7 +315,7 @@ bool BorderlessToneMapPass::Apply(IDirect3DDevice9* device, float gammaPower, fl return false; IDirect3DSurface9* backBuffer = nullptr; - HRESULT hr = device->GetRenderTarget(0, &backBuffer); + HRESULT hr = device->GetRenderTarget(0, &backBuffer); if (FAILED(hr) || !backBuffer) return false; @@ -358,12 +358,8 @@ bool BorderlessToneMapPass::Apply(IDirect3DDevice9* device, float gammaPower, fl const float bottom = static_cast(m_height) - 0.5f; const SToneMapVertex vertices[6] = { - {left, top, 0.0f, 1.0f, 0.0f, 0.0f}, - {right, top, 0.0f, 1.0f, 1.0f, 0.0f}, - {left, bottom, 0.0f, 1.0f, 0.0f, 1.0f}, - {right, top, 0.0f, 1.0f, 1.0f, 0.0f}, - {right, bottom, 0.0f, 1.0f, 1.0f, 1.0f}, - {left, bottom, 0.0f, 1.0f, 0.0f, 1.0f}, + {left, top, 0.0f, 1.0f, 0.0f, 0.0f}, {right, top, 0.0f, 1.0f, 1.0f, 0.0f}, {left, bottom, 0.0f, 1.0f, 0.0f, 1.0f}, + {right, top, 0.0f, 1.0f, 1.0f, 0.0f}, {right, bottom, 0.0f, 1.0f, 1.0f, 1.0f}, {left, bottom, 0.0f, 1.0f, 0.0f, 1.0f}, }; device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, vertices, sizeof(SToneMapVertex)); @@ -384,7 +380,7 @@ void BorderlessToneMapPass::ReleaseTexture() m_width = 0; m_height = 0; m_format = D3DFMT_UNKNOWN; - + // Invalidate apply state block since it captured the old texture pointer SAFE_RELEASE(m_applyStateBlock); } @@ -395,7 +391,7 @@ void BorderlessToneMapPass::ReleaseShader() SAFE_RELEASE(m_constantTable); m_toneParamsHandle = nullptr; m_shaderFailed = false; - + // Invalidate apply state block since it captured the shader pointer SAFE_RELEASE(m_applyStateBlock); } @@ -504,8 +500,7 @@ void CDirect3DEvents9::OnInvalidate(IDirect3DDevice9* pDevice) const HRESULT hrCooperativeLevel = pDevice->TestCooperativeLevel(); const bool bDeviceOperational = (hrCooperativeLevel == D3D_OK); - const bool bDeviceTemporarilyLost = - (hrCooperativeLevel == D3DERR_DEVICELOST || hrCooperativeLevel == D3DERR_DEVICENOTRESET); + const bool bDeviceTemporarilyLost = (hrCooperativeLevel == D3DERR_DEVICELOST || hrCooperativeLevel == D3DERR_DEVICENOTRESET); if (!bDeviceOperational && !bDeviceTemporarilyLost) WriteDebugEvent(SString("OnInvalidate: unexpected cooperative level %08x", hrCooperativeLevel)); @@ -668,18 +663,18 @@ void CDirect3DEvents9::OnPresent(IDirect3DDevice9* pDevice) TIMING_CHECKPOINT("-OnPresent2"); - TIMING_CHECKPOINT(""); // End of frame for profiler + TIMING_CHECKPOINT(""); // End of frame for profiler } -#define SAVE_RENDERSTATE_AND_SET( reg, value ) \ +#define SAVE_RENDERSTATE_AND_SET(reg, value) \ const DWORD dwSaved_##reg = g_pDeviceState->RenderState.reg; \ - const bool bSet_##reg = ( dwSaved_##reg != value ); \ - if ( bSet_##reg ) \ - pDevice->SetRenderState ( D3DRS_##reg, value ) + const bool bSet_##reg = (dwSaved_##reg != value); \ + if (bSet_##reg) \ + pDevice->SetRenderState(D3DRS_##reg, value) -#define RESTORE_RENDERSTATE( reg ) \ - if ( bSet_##reg ) \ - pDevice->SetRenderState ( D3DRS_##reg, dwSaved_##reg ) +#define RESTORE_RENDERSTATE(reg) \ + if (bSet_##reg) \ + pDevice->SetRenderState(D3DRS_##reg, dwSaved_##reg) ///////////////////////////////////////////////////////////// // @@ -793,8 +788,8 @@ HRESULT CDirect3DEvents9::DrawPrimitiveShader(IDirect3DDevice9* pDevice, D3DPRIM pDevice->GetVertexShader(&pOriginalVertexShader); // Do shader passes - bool bEffectDeviceTemporarilyLost = false; - bool bEffectDeviceOperational = true; + bool bEffectDeviceTemporarilyLost = false; + bool bEffectDeviceOperational = true; IDirect3DDevice9* pEffectDevice = nullptr; if (SUCCEEDED(pD3DEffect->GetDevice(&pEffectDevice)) && pEffectDevice) { @@ -810,9 +805,9 @@ HRESULT CDirect3DEvents9::DrawPrimitiveShader(IDirect3DDevice9* pDevice, D3DPRIM return D3D_OK; } - DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE - uint uiNumPasses = 0; - HRESULT hrBegin = pEffectWrap->Begin(&uiNumPasses, dwFlags); + DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE + uint uiNumPasses = 0; + HRESULT hrBegin = pEffectWrap->Begin(&uiNumPasses, dwFlags); if (FAILED(hrBegin) || uiNumPasses == 0) { if (FAILED(hrBegin) && hrBegin != D3DERR_DEVICELOST && hrBegin != D3DERR_DEVICENOTRESET) @@ -860,7 +855,7 @@ HRESULT CDirect3DEvents9::DrawPrimitiveShader(IDirect3DDevice9* pDevice, D3DPRIM bCompletedAnyPass = true; } - HRESULT hrEnd = pEffectWrap->End(bEffectDeviceOperational && !bEncounteredDeviceLoss); + HRESULT hrEnd = pEffectWrap->End(bEffectDeviceOperational && !bEncounteredDeviceLoss); if (FAILED(hrEnd) && hrEnd != D3DERR_DEVICELOST && hrEnd != D3DERR_DEVICENOTRESET) WriteDebugEvent(SString("DrawPrimitiveShader: End failed %08x", hrEnd)); @@ -1018,8 +1013,8 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveShader(IDirect3DDevice9* pDevice, CEffectWrap* pActiveEffectWrap = activeState.pEffectWrap; ID3DXEffect* pActiveEffect = activeState.pEffect; - bool bDeviceTemporarilyLost = false; - bool bDeviceOperational = true; + bool bDeviceTemporarilyLost = false; + bool bDeviceOperational = true; IDirect3DDevice9* pEffectDevice = nullptr; if (SUCCEEDED(pActiveEffect->GetDevice(&pEffectDevice)) && pEffectDevice) { @@ -1084,8 +1079,8 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveShader(IDirect3DDevice9* pDevice, pDevice->GetVertexShader(&pOriginalVertexShader); // Do shader passes - bool bEffectDeviceTemporarilyLost = false; - bool bEffectDeviceOperational = true; + bool bEffectDeviceTemporarilyLost = false; + bool bEffectDeviceOperational = true; IDirect3DDevice9* pEffectDevice = nullptr; if (SUCCEEDED(pD3DEffect->GetDevice(&pEffectDevice)) && pEffectDevice) { @@ -1103,9 +1098,9 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveShader(IDirect3DDevice9* pDevice, return D3D_OK; } - DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE - uint uiNumPasses = 0; - HRESULT hrBegin = pEffectWrap->Begin(&uiNumPasses, dwFlags); + DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE + uint uiNumPasses = 0; + HRESULT hrBegin = pEffectWrap->Begin(&uiNumPasses, dwFlags); if (FAILED(hrBegin) || uiNumPasses == 0) { if (FAILED(hrBegin) && hrBegin != D3DERR_DEVICELOST && hrBegin != D3DERR_DEVICENOTRESET) @@ -1166,7 +1161,7 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveShader(IDirect3DDevice9* pDevice, bCompletedAnyPass = true; } - HRESULT hrEnd = pEffectWrap->End(bEffectDeviceOperational && !bEncounteredDeviceLoss); + HRESULT hrEnd = pEffectWrap->End(bEffectDeviceOperational && !bEncounteredDeviceLoss); if (FAILED(hrEnd) && hrEnd != D3DERR_DEVICELOST && hrEnd != D3DERR_DEVICENOTRESET) WriteDebugEvent(SString("DrawIndexedPrimitiveShader: End failed %08x", hrEnd)); @@ -1209,7 +1204,7 @@ void CDirect3DEvents9::CloseActiveShader(bool bDeviceOperational) SResolvedShaderState shaderState; bool bHasShaderState = TryResolveShaderState(pShaderItem, shaderState); - + if (bHasShaderState) { if (shaderState.pInstance && !SharedUtil::IsReadablePointer(shaderState.pInstance, sizeof(void*))) @@ -1218,7 +1213,7 @@ void CDirect3DEvents9::CloseActiveShader(bool bDeviceOperational) bHasShaderState = false; } - ID3DXEffect* pD3DEffect = bHasShaderState ? shaderState.pEffect : nullptr; + ID3DXEffect* pD3DEffect = bHasShaderState ? shaderState.pEffect : nullptr; IDirect3DDevice9* pDevice = g_pGraphics ? g_pGraphics->GetDevice() : nullptr; bool bAllowDeviceWork = bDeviceOperational; @@ -1303,7 +1298,7 @@ bool AreVertexStreamsBigEnough(IDirect3DDevice9* pDevice, uint viMinBased, uint // ///////////////////////////////////////////////////////////// thread_local uint uiLastExceptionCode = 0; -int FilterException(uint exceptionCode) +int FilterException(uint exceptionCode) { uiLastExceptionCode = exceptionCode; if (exceptionCode == EXCEPTION_ACCESS_VIOLATION) @@ -1318,54 +1313,54 @@ int FilterException(uint exceptionCode) namespace { -void WriteDebugEventFormatted(const char* format, HRESULT value) -{ - char buffer[160]; - _snprintf_s(buffer, _countof(buffer), _TRUNCATE, format, value); - WriteDebugEvent(buffer); -} - -HRESULT CallSetRenderTargetWithGuard(IDirect3DDevice9* pDevice, DWORD renderTargetIndex, IDirect3DSurface9* pRenderTarget) -{ - HRESULT hr = D3D_OK; - __try - { - hr = pDevice->SetRenderTarget(renderTargetIndex, pRenderTarget); - } - __except (FilterException(GetExceptionCode())) + void WriteDebugEventFormatted(const char* format, HRESULT value) { - CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 15 * 1000000); + char buffer[160]; + _snprintf_s(buffer, _countof(buffer), _TRUNCATE, format, value); + WriteDebugEvent(buffer); } - return hr; -} -HRESULT CallSetDepthStencilSurfaceWithGuard(IDirect3DDevice9* pDevice, IDirect3DSurface9* pNewZStencil) -{ - HRESULT hr = D3D_OK; - __try - { - hr = pDevice->SetDepthStencilSurface(pNewZStencil); - } - __except (FilterException(GetExceptionCode())) + HRESULT CallSetRenderTargetWithGuard(IDirect3DDevice9* pDevice, DWORD renderTargetIndex, IDirect3DSurface9* pRenderTarget) { - CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 16 * 1000000); + HRESULT hr = D3D_OK; + __try + { + hr = pDevice->SetRenderTarget(renderTargetIndex, pRenderTarget); + } + __except (FilterException(GetExceptionCode())) + { + CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 15 * 1000000); + } + return hr; } - return hr; -} -HRESULT CallCreateAdditionalSwapChainWithGuard(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain) -{ - HRESULT hr = D3D_OK; - __try + HRESULT CallSetDepthStencilSurfaceWithGuard(IDirect3DDevice9* pDevice, IDirect3DSurface9* pNewZStencil) { - hr = pDevice->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain); + HRESULT hr = D3D_OK; + __try + { + hr = pDevice->SetDepthStencilSurface(pNewZStencil); + } + __except (FilterException(GetExceptionCode())) + { + CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 16 * 1000000); + } + return hr; } - __except (FilterException(GetExceptionCode())) + + HRESULT CallCreateAdditionalSwapChainWithGuard(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain) { - CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 17 * 1000000); + HRESULT hr = D3D_OK; + __try + { + hr = pDevice->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain); + } + __except (FilterException(GetExceptionCode())) + { + CCore::GetSingleton().OnCrashAverted((uiLastExceptionCode & 0xFFFF) + 17 * 1000000); + } + return hr; } - return hr; -} } ///////////////////////////////////////////////////////////// @@ -1379,8 +1374,8 @@ HRESULT CDirect3DEvents9::DrawPrimitiveGuarded(IDirect3DDevice9* pDevice, D3DPRI if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); - bool bDeviceTemporarilyLost = false; - HRESULT hrCooperativeLevel = D3DERR_INVALIDCALL; + bool bDeviceTemporarilyLost = false; + HRESULT hrCooperativeLevel = D3DERR_INVALIDCALL; if (!IsDeviceOperational(pDevice, &bDeviceTemporarilyLost, &hrCooperativeLevel)) { if (bDeviceTemporarilyLost) @@ -1404,7 +1399,7 @@ HRESULT CDirect3DEvents9::DrawPrimitiveGuarded(IDirect3DDevice9* pDevice, D3DPRI uint viMinBased = StartVertex; uint viMaxBased = NumVertices + StartVertex; - if (!AreVertexStreamsBigEnough(pDevice, viMinBased, viMaxBased)) + if (!AreVertexStreamsBigEnough(pDevice, viMinBased, viMaxBased)) return hr; } @@ -1432,8 +1427,8 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveGuarded(IDirect3DDevice9* pDevice, if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount); - bool bDeviceTemporarilyLost = false; - HRESULT hrCooperativeLevel = D3DERR_INVALIDCALL; + bool bDeviceTemporarilyLost = false; + HRESULT hrCooperativeLevel = D3DERR_INVALIDCALL; if (!IsDeviceOperational(pDevice, &bDeviceTemporarilyLost, &hrCooperativeLevel)) { if (bDeviceTemporarilyLost) @@ -1441,7 +1436,7 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveGuarded(IDirect3DDevice9* pDevice, if (hrCooperativeLevel != D3D_OK) return hrCooperativeLevel; - RunBorderlessToneMap(pDevice); + RunBorderlessToneMap(pDevice); return D3DERR_INVALIDCALL; } @@ -1517,8 +1512,8 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveUPGuarded(IDirect3DDevice9* pDevic CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) - return pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, - pVertexStreamZeroData, VertexStreamZeroStride); + return pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, + VertexStreamZeroStride); bool bDeviceTemporarilyLost = false; HRESULT hrCooperativeLevel = D3DERR_INVALIDCALL; @@ -1537,8 +1532,8 @@ HRESULT CDirect3DEvents9::DrawIndexedPrimitiveUPGuarded(IDirect3DDevice9* pDevic __try { - hr = pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, - pVertexStreamZeroData, VertexStreamZeroStride); + hr = pDevice->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, + VertexStreamZeroStride); } __except (FilterException(GetExceptionCode())) { @@ -1791,8 +1786,7 @@ HRESULT CDirect3DEvents9::UpdateSurfaceGuarded(IDirect3DDevice9* pDevice, IDirec // Catch access violations and device-loss states // ///////////////////////////////////////////////////////////// -HRESULT CDirect3DEvents9::UpdateTextureGuarded(IDirect3DDevice9* pDevice, IDirect3DBaseTexture9* pSourceTexture, - IDirect3DBaseTexture9* pDestinationTexture) +HRESULT CDirect3DEvents9::UpdateTextureGuarded(IDirect3DDevice9* pDevice, IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->UpdateTexture(pSourceTexture, pDestinationTexture); @@ -1831,8 +1825,7 @@ HRESULT CDirect3DEvents9::UpdateTextureGuarded(IDirect3DDevice9* pDevice, IDirec // Catch access violations and device-loss states // ///////////////////////////////////////////////////////////// -HRESULT CDirect3DEvents9::GetRenderTargetDataGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pRenderTarget, - IDirect3DSurface9* pDestSurface) +HRESULT CDirect3DEvents9::GetRenderTargetDataGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pRenderTarget, IDirect3DSurface9* pDestSurface) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->GetRenderTargetData(pRenderTarget, pDestSurface); @@ -1998,9 +1991,8 @@ HRESULT CDirect3DEvents9::CreateAdditionalSwapChainGuarded(IDirect3DDevice9* pDe // Catch access violations and device-loss states // ///////////////////////////////////////////////////////////// -HRESULT CDirect3DEvents9::CreateVolumeTextureGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, - HANDLE* pSharedHandle) +HRESULT CDirect3DEvents9::CreateVolumeTextureGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, + D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle); @@ -2039,8 +2031,8 @@ HRESULT CDirect3DEvents9::CreateVolumeTextureGuarded(IDirect3DDevice9* pDevice, // Catch access violations and device-loss states // ///////////////////////////////////////////////////////////// -HRESULT CDirect3DEvents9::CreateCubeTextureGuarded(IDirect3DDevice9* pDevice, UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, - D3DPOOL Pool, IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle) +HRESULT CDirect3DEvents9::CreateCubeTextureGuarded(IDirect3DDevice9* pDevice, UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, + IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle); @@ -2079,9 +2071,8 @@ HRESULT CDirect3DEvents9::CreateCubeTextureGuarded(IDirect3DDevice9* pDevice, UI // Catch access violations and device-loss states // ///////////////////////////////////////////////////////////// -HRESULT CDirect3DEvents9::CreateRenderTargetGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, - D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, - IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle) +HRESULT CDirect3DEvents9::CreateRenderTargetGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, + DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle) { if (ms_DiagnosticDebug == EDiagnosticDebug::D3D_6732) return pDevice->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle); @@ -2445,8 +2436,8 @@ HRESULT CDirect3DEvents9::CreateVertexDeclaration(IDirect3DDevice9* pDevice, CON *ppDecl = nullptr; - HRESULT hr = D3D_OK; - IDirect3DVertexDeclaration9* pOriginalDecl = nullptr; + HRESULT hr = D3D_OK; + IDirect3DVertexDeclaration9* pOriginalDecl = nullptr; hr = pDevice->CreateVertexDeclaration(pVertexElements, ppDecl); if (FAILED(hr)) @@ -2544,7 +2535,8 @@ ERenderFormat CDirect3DEvents9::DiscoverReadableDepthFormat(IDirect3DDevice9* pD D3DFORMAT DepthFormat = (D3DFORMAT)checkList[i]; // Can use this format? - if (D3D_OK != pD3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, displayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, DepthFormat)) + if (D3D_OK != + pD3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, displayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, DepthFormat)) continue; // Don't check for compatibility with multisampling, as we turn AA off when using readable depth buffer diff --git a/Client/core/DXHook/CDirect3DEvents9.h b/Client/core/DXHook/CDirect3DEvents9.h index 90152b5f76e..eca41e38b37 100644 --- a/Client/core/DXHook/CDirect3DEvents9.h +++ b/Client/core/DXHook/CDirect3DEvents9.h @@ -34,45 +34,39 @@ class CDirect3DEvents9 static HRESULT DrawPrimitiveGuarded(IDirect3DDevice9* pDevice, D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount); static HRESULT DrawIndexedPrimitiveGuarded(IDirect3DDevice9* pDevice, D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount); - static HRESULT DrawPrimitiveUPGuarded(IDirect3DDevice9* pDevice, D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, - CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); + static HRESULT DrawPrimitiveUPGuarded(IDirect3DDevice9* pDevice, D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, + UINT VertexStreamZeroStride); static HRESULT DrawIndexedPrimitiveUPGuarded(IDirect3DDevice9* pDevice, D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, - UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, - CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); - static HRESULT DrawRectPatchGuarded(IDirect3DDevice9* pDevice, UINT Handle, CONST float* pNumSegs, - CONST D3DRECTPATCH_INFO* pRectPatchInfo); - static HRESULT DrawTriPatchGuarded(IDirect3DDevice9* pDevice, UINT Handle, CONST float* pNumSegs, - CONST D3DTRIPATCH_INFO* pTriPatchInfo); - static HRESULT ProcessVerticesGuarded(IDirect3DDevice9* pDevice, UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, - IDirect3DVertexBuffer9* pDestBuffer, IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags); + UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, + UINT VertexStreamZeroStride); + static HRESULT DrawRectPatchGuarded(IDirect3DDevice9* pDevice, UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo); + static HRESULT DrawTriPatchGuarded(IDirect3DDevice9* pDevice, UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo); + static HRESULT ProcessVerticesGuarded(IDirect3DDevice9* pDevice, UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, + IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags); static HRESULT ClearGuarded(IDirect3DDevice9* pDevice, DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil); static HRESULT ColorFillGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pSurface, CONST RECT* pRect, D3DCOLOR color); static HRESULT UpdateSurfaceGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, CONST POINT* pDestPoint); - static HRESULT UpdateTextureGuarded(IDirect3DDevice9* pDevice, IDirect3DBaseTexture9* pSourceTexture, - IDirect3DBaseTexture9* pDestinationTexture); - static HRESULT GetRenderTargetDataGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pRenderTarget, - IDirect3DSurface9* pDestSurface); + static HRESULT UpdateTextureGuarded(IDirect3DDevice9* pDevice, IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture); + static HRESULT GetRenderTargetDataGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pRenderTarget, IDirect3DSurface9* pDestSurface); static HRESULT GetFrontBufferDataGuarded(IDirect3DDevice9* pDevice, UINT iSwapChain, IDirect3DSurface9* pDestSurface); static HRESULT SetRenderTargetGuarded(IDirect3DDevice9* pDevice, DWORD RenderTargetIndex, IDirect3DSurface9* pRenderTarget); static HRESULT SetDepthStencilSurfaceGuarded(IDirect3DDevice9* pDevice, IDirect3DSurface9* pNewZStencil); static HRESULT CreateAdditionalSwapChainGuarded(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters, - IDirect3DSwapChain9** pSwapChain); - static HRESULT CreateVolumeTextureGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, - D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle); + IDirect3DSwapChain9** pSwapChain); + static HRESULT CreateVolumeTextureGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, + D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle); static HRESULT CreateCubeTextureGuarded(IDirect3DDevice9* pDevice, UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle); static HRESULT CreateRenderTargetGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); - static HRESULT CreateDepthStencilSurfaceGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, - D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, - IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); + static HRESULT CreateDepthStencilSurfaceGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, + DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); static HRESULT CreateOffscreenPlainSurfaceGuarded(IDirect3DDevice9* pDevice, UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); static HRESULT PresentGuarded(IDirect3DDevice9* pDevice, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion); - static bool IsDeviceOperational(IDirect3DDevice9* pDevice, bool* pbTemporarilyLost = nullptr, - HRESULT* pHrCooperativeLevel = nullptr); + static bool IsDeviceOperational(IDirect3DDevice9* pDevice, bool* pbTemporarilyLost = nullptr, HRESULT* pHrCooperativeLevel = nullptr); static HRESULT CreateVertexBuffer(IDirect3DDevice9* pDevice, UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9** ppVertexBuffer, HANDLE* pSharedHandle); static HRESULT CreateIndexBuffer(IDirect3DDevice9* pDevice, UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9** ppIndexBuffer, diff --git a/Client/core/DXHook/CDirect3DHook9.cpp b/Client/core/DXHook/CDirect3DHook9.cpp index a8cc1c06174..339c8ee1590 100644 --- a/Client/core/DXHook/CDirect3DHook9.cpp +++ b/Client/core/DXHook/CDirect3DHook9.cpp @@ -87,18 +87,18 @@ IDirect3D9* CDirect3DHook9::API_Direct3DCreate9(UINT SDKVersion) CCore::GetSingleton().CreateGUI(); } - // D3DX_SDK_VERSION checks - // SDK required for shaders to work properly - // Accept the DirectX SDK shipped with August 2009 (42) or June 2010 (43) - #if (D3DX_SDK_VERSION != 42) && (D3DX_SDK_VERSION != 43) +// D3DX_SDK_VERSION checks +// SDK required for shaders to work properly +// Accept the DirectX SDK shipped with August 2009 (42) or June 2010 (43) +#if (D3DX_SDK_VERSION != 42) && (D3DX_SDK_VERSION != 43) WriteDebugEvent("D3DX_SDK_VERSION incorrect " QUOTE_DEFINE(D3DX_SDK_VERSION)); - #pragma message( "WARNING: Microsoft DirectX SDK (August 2009 or June 2010) includes missing" ) - #ifndef CI_BUILD - #ifndef MTA_DEBUG - #error "Microsoft DirectX SDK (August 2009 or June 2010) includes missing" - #endif + #pragma message("WARNING: Microsoft DirectX SDK (August 2009 or June 2010) includes missing") + #ifndef CI_BUILD + #ifndef MTA_DEBUG + #error "Microsoft DirectX SDK (August 2009 or June 2010) includes missing" #endif #endif +#endif if (!D3DXCheckVersion(D3D_SDK_VERSION, D3DX_SDK_VERSION)) { SString strMessage("D3DXCheckVersion FAILED (D3D_SDK_VERSION: %d D3DX_SDK_VERSION: %d SDKVersion: %d)", D3D_SDK_VERSION, D3DX_SDK_VERSION, @@ -126,8 +126,8 @@ IDirect3D9* CDirect3DHook9::API_Direct3DCreate9(UINT SDKVersion) "Please ensure the DirectX End-User Runtime and\n" "latest Windows Service Packs are installed correctly."), _("Error") + _E("CC50"), - MB_OK | MB_ICONERROR | MB_TOPMOST); // Could not initialize Direct3D9. Please ensure the DirectX End-User Runtime and latest - // Windows Service Packs are installed correctly. + MB_OK | MB_ICONERROR | MB_TOPMOST); // Could not initialize Direct3D9. Please ensure the DirectX End-User Runtime and latest + // Windows Service Packs are installed correctly. return NULL; } diff --git a/Client/core/DXHook/CProxyDirect3D9.cpp b/Client/core/DXHook/CProxyDirect3D9.cpp index d5b4d10c377..acc73034c2c 100644 --- a/Client/core/DXHook/CProxyDirect3D9.cpp +++ b/Client/core/DXHook/CProxyDirect3D9.cpp @@ -21,18 +21,18 @@ extern HINSTANCE g_hModule; namespace { -// Cached static Direct3D pointer for lockless fast-path access -std::atomic g_cachedStaticDirect3D{nullptr}; -std::atomic g_cachedDirect3DValid{false}; -// Cached adapter monitor for lockless fast-path access -std::atomic g_cachedAdapterMonitor{nullptr}; -std::atomic g_cachedAdapterMonitorValid{false}; - -IDirect3D9* GetFirstValidTrackedDirect3D(std::vector& trackedList) -{ - // Return first element without expensive COM validation (called frequently) - return trackedList.empty() ? nullptr : trackedList.front(); -} + // Cached static Direct3D pointer for lockless fast-path access + std::atomic g_cachedStaticDirect3D{nullptr}; + std::atomic g_cachedDirect3DValid{false}; + // Cached adapter monitor for lockless fast-path access + std::atomic g_cachedAdapterMonitor{nullptr}; + std::atomic g_cachedAdapterMonitorValid{false}; + + IDirect3D9* GetFirstValidTrackedDirect3D(std::vector& trackedList) + { + // Return first element without expensive COM validation (called frequently) + return trackedList.empty() ? nullptr : trackedList.front(); + } } // unnamed namespace HRESULT HandleCreateDeviceResult(HRESULT hResult, IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, @@ -44,9 +44,7 @@ bool CreateDeviceSecondCallCheck(HRESULT& hOutResult, IDirect3D9* pDirect3D, UIN D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); void ApplyBorderlessColorCorrection(CProxyDirect3DDevice9* proxyDevice, const D3DPRESENT_PARAMETERS& presentationParameters); -CProxyDirect3D9::CProxyDirect3D9(IDirect3D9* pInterface) - : m_pDevice(nullptr) - , m_lRefCount(1) +CProxyDirect3D9::CProxyDirect3D9(IDirect3D9* pInterface) : m_pDevice(nullptr), m_lRefCount(1) { WriteDebugEvent(SString("CProxyDirect3D9::CProxyDirect3D9 %08x", this)); @@ -243,22 +241,22 @@ HMONITOR CProxyDirect3D9::StaticGetAdapterMonitor(UINT Adapter) if (hMonitor) return hMonitor; } - + // Slow path: refresh cache under lock std::lock_guard lock(ms_Direct3D9ListMutex); - IDirect3D9* pDirect3D = GetFirstValidTrackedDirect3D(ms_CreatedDirect3D9List); + IDirect3D9* pDirect3D = GetFirstValidTrackedDirect3D(ms_CreatedDirect3D9List); if (!pDirect3D) return NULL; HMONITOR hMonitor = pDirect3D->GetAdapterMonitor(Adapter); - + // Cache result for default adapter if (Adapter == 0 && hMonitor) { g_cachedAdapterMonitor.store(hMonitor, std::memory_order_release); g_cachedAdapterMonitorValid.store(true, std::memory_order_release); } - + return hMonitor; } @@ -271,10 +269,10 @@ IDirect3D9* CProxyDirect3D9::StaticGetDirect3D() if (pDirect3D) return pDirect3D; } - + // Slow path: refresh cache under lock std::lock_guard lock(ms_Direct3D9ListMutex); - IDirect3D9* pDirect3D = GetFirstValidTrackedDirect3D(ms_CreatedDirect3D9List); + IDirect3D9* pDirect3D = GetFirstValidTrackedDirect3D(ms_CreatedDirect3D9List); if (pDirect3D) { g_cachedStaticDirect3D.store(pDirect3D, std::memory_order_release); @@ -325,22 +323,22 @@ HRESULT CProxyDirect3D9::CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND WriteDebugEvent(SString(" FullScreen_RefreshRateInHz:%d PresentationInterval:0x%08x", pPresentationParameters->FullScreen_RefreshRateInHz, pPresentationParameters->PresentationInterval)); - // Change the window title to MTA: San Andreas - #ifdef MTA_DEBUG +// Change the window title to MTA: San Andreas +#ifdef MTA_DEBUG SetWindowTextW(hFocusWindow, MbUTF8ToUTF16("MTA: San Andreas [DEBUG]").c_str()); - #else +#else SetWindowTextW(hFocusWindow, MbUTF8ToUTF16("MTA: San Andreas").c_str()); - #endif +#endif // Set dark titlebar if needed - int themeStatus = 0; + int themeStatus = 0; const SString appsUseLightTheme = GetSystemRegistryValue((uint)HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme", &themeStatus); BOOL darkTitleBar = FALSE; if (themeStatus > 0) { // Parse the registry value into a numeric flag - char* themeEnd = nullptr; + char* themeEnd = nullptr; const long themeNumeric = strtol(appsUseLightTheme.c_str(), &themeEnd, 10); if (themeEnd != appsUseLightTheme.c_str() && *themeEnd == '\0') { @@ -396,7 +394,7 @@ HRESULT CProxyDirect3D9::CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND AddReportLog(8755, SStringX("CProxyDirect3D9::CreateDevice - driver returned nullptr device"), 5); hResult = D3DERR_INVALIDDEVICE; } - else if (!IsValidComInterfacePointer(pCreatedDevice, ComPtrValidation::ValidationMode::ForceRefresh)) + else if (!IsValidComInterfacePointer(pCreatedDevice, ComPtrValidation::ValidationMode::ForceRefresh)) { SString message; message.Format("CProxyDirect3D9::CreateDevice - rejected invalid IDirect3DDevice9 pointer %p", pCreatedDevice); @@ -531,10 +529,10 @@ namespace ms_strExtraLogBuffer += strText.Replace("\n", " ") + "\n"; WriteDebugEvent(strText); } - #define WriteDebugEvent WriteDebugEventTest +#define WriteDebugEvent WriteDebugEventTest uint ms_uiCreationAttempts = 0; -} // namespace +} // namespace void ApplyBorderlessColorCorrection(CProxyDirect3DDevice9* proxyDevice, const D3DPRESENT_PARAMETERS& presentationParameters) { @@ -761,15 +759,15 @@ HRESULT DoCreateDevice(IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE DeviceTyp pPresentationParameters->SwapEffect = swapEffectList[iSwap]; pPresentationParameters->BackBufferFormat = format.rtFormatList[iRt]; pPresentationParameters->AutoDepthStencilFormat = format.depthFormatList[iDepth]; - #ifndef MTA_DEBUG +#ifndef MTA_DEBUG hResult = CreateDeviceInsist(2, 0, pDirect3D, Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); - #else +#else WriteDebugEvent("--------------------------------"); WriteDebugEvent(ToString(Adapter, DeviceType, hFocusWindow, BehaviorFlags, *pPresentationParameters)); WriteDebugEvent(SString(" 32 result: %08x", hResult)); hResult = -1; - #endif +#endif if (hResult == D3D_OK) { WriteDebugEvent(SString(" Pass #4 SUCCESS with: {Res:%d, Color:%d, Refresh:%d}", iRes, iColor, iRefresh)); @@ -927,9 +925,9 @@ void AddCapsReport(UINT Adapter, IDirect3D9* pDirect3D, IDirect3DDevice9* pD3DDe // Try create D3DVERTEXELEMENT9 VertexElements[] = {{0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, D3DDECL_END()}; VertexElements[0].Type = DeclTypesList[i].VertexType; - IDirect3DVertexDeclaration9* pD3DVertexDecl = nullptr; - hr = pD3DDevice9->CreateVertexDeclaration(VertexElements, &pD3DVertexDecl); - ReleaseInterface(pD3DVertexDecl, 8799, "AddCapsReport CreateVertexDeclaration"); + IDirect3DVertexDeclaration9* pD3DVertexDecl = nullptr; + hr = pD3DDevice9->CreateVertexDeclaration(VertexElements, &pD3DVertexDecl); + ReleaseInterface(pD3DVertexDecl, 8799, "AddCapsReport CreateVertexDeclaration"); // Check against device caps bool bCapsSaysOk = (DeviceCaps9.DeclTypes & DeclTypesList[i].CapsType) ? true : false; @@ -995,7 +993,7 @@ void AddCapsReport(UINT Adapter, IDirect3D9* pDirect3D, IDirect3DDevice9* pD3DDe bool CreateDeviceSecondCallCheck(HRESULT& hOutResult, IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) { - static uint uiCreateCount = 0; + static uint uiCreateCount = 0; static IDirect3D9* lastTrackedInterface = nullptr; if (!IsMainThread()) @@ -1041,12 +1039,12 @@ HRESULT HandleCreateDeviceResult(HRESULT hResult, IDirect3D9* pDirect3D, UINT Ad { // Log graphic card name D3DADAPTER_IDENTIFIER9 AdapterIdent{}; - HRESULT hr = pDirect3D->GetAdapterIdentifier(Adapter, 0, &AdapterIdent); + HRESULT hr = pDirect3D->GetAdapterIdentifier(Adapter, 0, &AdapterIdent); if (FAILED(hr)) WriteDebugEvent(SString("Warning: GetAdapterIdentifier failed: %08x", hr)); WriteDebugEvent(ToString(AdapterIdent)); - uint uiCurrentStatus = 0; // 0-unknown 1-fail 2-success after retry 3-success + uint uiCurrentStatus = 0; // 0-unknown 1-fail 2-success after retry 3-success if (hResult == D3D_OK) { @@ -1142,9 +1140,9 @@ HRESULT HandleCreateDeviceResult(HRESULT hResult, IDirect3D9* pDirect3D, UINT Ad // Calc log level to use uint uiDiagnosticLogLevel = 0; if (uiLastStatus == CREATE_DEVICE_FAIL && uiCurrentStatus != CREATE_DEVICE_FAIL) - uiDiagnosticLogLevel = 1; // Log and continue - If changing from fail status + uiDiagnosticLogLevel = 1; // Log and continue - If changing from fail status if (uiCurrentStatus == CREATE_DEVICE_FAIL) - uiDiagnosticLogLevel = 2; // Log and wait - If fail status + uiDiagnosticLogLevel = 2; // Log and wait - If fail status bool bDetectOptimus = (GetModuleHandle("nvd3d9wrap.dll") != NULL); @@ -1190,7 +1188,7 @@ namespace { DWORD BehaviorFlagsOrig = 0; D3DPRESENT_PARAMETERS presentationParametersOrig; -} // namespace +} // namespace //////////////////////////////////////////////// // @@ -1216,9 +1214,9 @@ void CCore::OnPreCreateDevice(IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE De WriteDebugEvent(SString("Previous CreateDevice failed with: %08x", uiPrevResult)); WriteDebugEvent(" Test unmodified:"); WriteDebugEvent(ToString(Adapter, DeviceType, hFocusWindow, BehaviorFlags, *pPresentationParameters)); - IDirect3DDevice9* pReturnedDeviceInterface = NULL; - HRESULT hResult = pDirect3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, &pReturnedDeviceInterface); - ReleaseInterface(pReturnedDeviceInterface, 8799, "CCore::OnPreCreateDevice temp release"); + IDirect3DDevice9* pReturnedDeviceInterface = NULL; + HRESULT hResult = pDirect3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, &pReturnedDeviceInterface); + ReleaseInterface(pReturnedDeviceInterface, 8799, "CCore::OnPreCreateDevice temp release"); WriteDebugEvent(SString(" Unmodified result is: %08x", hResult)); } @@ -1333,14 +1331,12 @@ HRESULT CCore::OnPostCreateDevice(HRESULT hResult, IDirect3D9* pDirect3D, UINT A IDirect3DDevice9* pCreatedDevice = *ppReturnedDeviceInterface; if (!pCreatedDevice) { - AddReportLog(8755, - "CCore::OnPostCreateDevice: CreateDeviceInsist returned nullptr device", 5); + AddReportLog(8755, "CCore::OnPostCreateDevice: CreateDeviceInsist returned nullptr device", 5); hResult = D3DERR_INVALIDDEVICE; } - else if (!IsValidComInterfacePointer(pCreatedDevice, ComPtrValidation::ValidationMode::ForceRefresh)) + else if (!IsValidComInterfacePointer(pCreatedDevice, ComPtrValidation::ValidationMode::ForceRefresh)) { - AddReportLog(8755, - SString("CCore::OnPostCreateDevice: rejected invalid IDirect3DDevice9 pointer %p", pCreatedDevice), 5); + AddReportLog(8755, SString("CCore::OnPostCreateDevice: rejected invalid IDirect3DDevice9 pointer %p", pCreatedDevice), 5); ReleaseInterface(pCreatedDevice, 8755, "CCore::OnPostCreateDevice invalid return"); *ppReturnedDeviceInterface = nullptr; hResult = D3DERR_INVALIDDEVICE; @@ -1355,16 +1351,16 @@ HRESULT CCore::OnPostCreateDevice(HRESULT hResult, IDirect3D9* pDirect3D, UINT A if (hResult == D3D_OK) AddCapsReport(Adapter, pDirect3D, *ppReturnedDeviceInterface, true); - // Change the window title to MTA: San Andreas - #ifdef MTA_DEBUG +// Change the window title to MTA: San Andreas +#ifdef MTA_DEBUG SetWindowTextW(hFocusWindow, MbUTF8ToUTF16("MTA: San Andreas [DEBUG]").c_str()); - #else +#else SetWindowTextW(hFocusWindow, MbUTF8ToUTF16("MTA: San Andreas").c_str()); - #endif +#endif // Log graphic card name D3DADAPTER_IDENTIFIER9 AdapterIdent{}; - HRESULT hr = pDirect3D->GetAdapterIdentifier(Adapter, 0, &AdapterIdent); + HRESULT hr = pDirect3D->GetAdapterIdentifier(Adapter, 0, &AdapterIdent); if (FAILED(hr)) WriteDebugEvent(SString("Warning: GetAdapterIdentifier failed: %08x", hr)); WriteDebugEvent(ToString(AdapterIdent)); @@ -1400,8 +1396,7 @@ HRESULT CCore::OnPostCreateDevice(HRESULT hResult, IDirect3D9* pDirect3D, UINT A } else { - AddReportLog(8755, - SString("CCore::OnPostCreateDevice - skipping Release on invalid original device pointer %p", pOriginalDevice), 5); + AddReportLog(8755, SString("CCore::OnPostCreateDevice - skipping Release on invalid original device pointer %p", pOriginalDevice), 5); } } @@ -1413,7 +1408,7 @@ HRESULT CCore::OnPostCreateDevice(HRESULT hResult, IDirect3D9* pDirect3D, UINT A WriteDebugEvent(SString(" Adapter:%d DeviceType:%d BehaviorFlags:0x%x ReadableDepth:%s", parameters.AdapterOrdinal, parameters.DeviceType, parameters.BehaviorFlags, ReadableDepthFormat ? std::string((char*)&ReadableDepthFormat, 4).c_str() : "None")); - ApplyBorderlessColorCorrection(static_cast(*ppReturnedDeviceInterface), *pPresentationParameters); + ApplyBorderlessColorCorrection(static_cast(*ppReturnedDeviceInterface), *pPresentationParameters); } bool bDetectOptimus = (GetModuleHandle("nvd3d9wrap.dll") != NULL); @@ -1421,9 +1416,9 @@ HRESULT CCore::OnPostCreateDevice(HRESULT hResult, IDirect3D9* pDirect3D, UINT A // Calc log level to use uint uiDiagnosticLogLevel = 0; if (GetApplicationSettingInt("nvhacks", "optimus") || bDetectOptimus) - uiDiagnosticLogLevel = 1; // Log and continue + uiDiagnosticLogLevel = 1; // Log and continue if (hResult != D3D_OK) - uiDiagnosticLogLevel = 2; // Log and wait - If fail status + uiDiagnosticLogLevel = 2; // Log and wait - If fail status // Do diagnostic log now if needed if (uiDiagnosticLogLevel) diff --git a/Client/core/DXHook/CProxyDirect3D9.h b/Client/core/DXHook/CProxyDirect3D9.h index 8471bc9188b..8251bc58b18 100644 --- a/Client/core/DXHook/CProxyDirect3D9.h +++ b/Client/core/DXHook/CProxyDirect3D9.h @@ -21,33 +21,33 @@ class CProxyDirect3D9 : public IDirect3D9 ~CProxyDirect3D9(); /*** IUnknown methods ***/ virtual HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - virtual ULONG __stdcall AddRef(); - virtual ULONG __stdcall Release(); + virtual ULONG __stdcall AddRef(); + virtual ULONG __stdcall Release(); /*** IDirect3D9 methods ***/ - virtual HRESULT __stdcall RegisterSoftwareDevice(void* pInitializeFunction); - virtual UINT __stdcall GetAdapterCount(); - virtual HRESULT __stdcall GetAdapterIdentifier(UINT Adapter, DWORD Flags, D3DADAPTER_IDENTIFIER9* pIdentifier); - virtual UINT __stdcall GetAdapterModeCount(UINT Adapter, D3DFORMAT Format); - virtual HRESULT __stdcall EnumAdapterModes(UINT Adapter, D3DFORMAT Format, UINT Mode, D3DDISPLAYMODE* pMode); - virtual HRESULT __stdcall GetAdapterDisplayMode(UINT Adapter, D3DDISPLAYMODE* pMode); - virtual HRESULT __stdcall CheckDeviceType(UINT Adapter, D3DDEVTYPE DevType, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, BOOL bWindowed); - virtual HRESULT __stdcall CheckDeviceFormat(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, - D3DFORMAT CheckFormat); - virtual HRESULT __stdcall CheckDeviceMultiSampleType(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SurfaceFormat, BOOL Windowed, - D3DMULTISAMPLE_TYPE MultiSampleType, DWORD* pQualityLevels); - virtual HRESULT __stdcall CheckDepthStencilMatch(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, D3DFORMAT RenderTargetFormat, - D3DFORMAT DepthStencilFormat); - virtual HRESULT __stdcall CheckDeviceFormatConversion(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SourceFormat, D3DFORMAT TargetFormat); - virtual HRESULT __stdcall GetDeviceCaps(UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS9* pCaps); + virtual HRESULT __stdcall RegisterSoftwareDevice(void* pInitializeFunction); + virtual UINT __stdcall GetAdapterCount(); + virtual HRESULT __stdcall GetAdapterIdentifier(UINT Adapter, DWORD Flags, D3DADAPTER_IDENTIFIER9* pIdentifier); + virtual UINT __stdcall GetAdapterModeCount(UINT Adapter, D3DFORMAT Format); + virtual HRESULT __stdcall EnumAdapterModes(UINT Adapter, D3DFORMAT Format, UINT Mode, D3DDISPLAYMODE* pMode); + virtual HRESULT __stdcall GetAdapterDisplayMode(UINT Adapter, D3DDISPLAYMODE* pMode); + virtual HRESULT __stdcall CheckDeviceType(UINT Adapter, D3DDEVTYPE DevType, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, BOOL bWindowed); + virtual HRESULT __stdcall CheckDeviceFormat(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, + D3DFORMAT CheckFormat); + virtual HRESULT __stdcall CheckDeviceMultiSampleType(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SurfaceFormat, BOOL Windowed, + D3DMULTISAMPLE_TYPE MultiSampleType, DWORD* pQualityLevels); + virtual HRESULT __stdcall CheckDepthStencilMatch(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, D3DFORMAT RenderTargetFormat, + D3DFORMAT DepthStencilFormat); + virtual HRESULT __stdcall CheckDeviceFormatConversion(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SourceFormat, D3DFORMAT TargetFormat); + virtual HRESULT __stdcall GetDeviceCaps(UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS9* pCaps); virtual HMONITOR __stdcall GetAdapterMonitor(UINT Adapter); - virtual HRESULT __stdcall CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, - D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); + virtual HRESULT __stdcall CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, + D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); static HMONITOR StaticGetAdapterMonitor(UINT Adapter); static IDirect3D9* StaticGetDirect3D(); private: - IDirect3D9* m_pDevice; + IDirect3D9* m_pDevice; std::atomic m_lRefCount; }; diff --git a/Client/core/DXHook/CProxyDirect3DDevice9.cpp b/Client/core/DXHook/CProxyDirect3DDevice9.cpp index 929be28d663..48df3cd4a62 100644 --- a/Client/core/DXHook/CProxyDirect3DDevice9.cpp +++ b/Client/core/DXHook/CProxyDirect3DDevice9.cpp @@ -27,173 +27,172 @@ void ApplyBorderlessColorCorrection(CProxyDirect3DDevice9* proxyDevice, const D3 namespace { - -} // unnamed namespace +} // unnamed namespace namespace BorderlessGamma { -const float kGammaMin = 0.5f; -const float kGammaMax = 2.0f; -const float kBrightnessMin = 0.5f; -const float kBrightnessMax = 2.0f; -const float kContrastMin = 0.5f; -const float kContrastMax = 2.0f; -const float kSaturationMin = 0.5f; -const float kSaturationMax = 2.0f; - -// Cache CVAR-derived values to avoid repeated string lookups on every frame. -struct CachedSettings -{ - std::mutex updateMutex; - std::atomic revision; - std::atomic source; - std::atomic gammaPower; - std::atomic brightnessScale; - std::atomic contrastScale; - std::atomic saturationScale; - std::atomic gammaEnabled; - std::atomic brightnessEnabled; - std::atomic contrastEnabled; - std::atomic saturationEnabled; - std::atomic applyWindowed; - std::atomic applyFullscreen; - - CachedSettings() - : revision(-1) - , source(nullptr) - , gammaPower(1.0f) - , brightnessScale(1.0f) - , contrastScale(1.0f) - , saturationScale(1.0f) - , gammaEnabled(false) - , brightnessEnabled(false) - , contrastEnabled(false) - , saturationEnabled(false) - , applyWindowed(false) - , applyFullscreen(false) + const float kGammaMin = 0.5f; + const float kGammaMax = 2.0f; + const float kBrightnessMin = 0.5f; + const float kBrightnessMax = 2.0f; + const float kContrastMin = 0.5f; + const float kContrastMax = 2.0f; + const float kSaturationMin = 0.5f; + const float kSaturationMax = 2.0f; + + // Cache CVAR-derived values to avoid repeated string lookups on every frame. + struct CachedSettings { - } -}; - -static CachedSettings g_cachedSettings; + std::mutex updateMutex; + std::atomic revision; + std::atomic source; + std::atomic gammaPower; + std::atomic brightnessScale; + std::atomic contrastScale; + std::atomic saturationScale; + std::atomic gammaEnabled; + std::atomic brightnessEnabled; + std::atomic contrastEnabled; + std::atomic saturationEnabled; + std::atomic applyWindowed; + std::atomic applyFullscreen; + + CachedSettings() + : revision(-1), + source(nullptr), + gammaPower(1.0f), + brightnessScale(1.0f), + contrastScale(1.0f), + saturationScale(1.0f), + gammaEnabled(false), + brightnessEnabled(false), + contrastEnabled(false), + saturationEnabled(false), + applyWindowed(false), + applyFullscreen(false) + { + } + }; -void RefreshCacheIfNeeded() -{ - CClientVariables* cvars = CClientVariables::GetSingletonPtr(); - const CClientVariables* currentSource = cvars; - const int currentRevision = cvars ? cvars->GetRevision() : -1; + static CachedSettings g_cachedSettings; - const CClientVariables* cachedSource = g_cachedSettings.source.load(std::memory_order_relaxed); - const int cachedRevision = g_cachedSettings.revision.load(std::memory_order_relaxed); + void RefreshCacheIfNeeded() + { + CClientVariables* cvars = CClientVariables::GetSingletonPtr(); + const CClientVariables* currentSource = cvars; + const int currentRevision = cvars ? cvars->GetRevision() : -1; - if (cachedSource == currentSource && cachedRevision == currentRevision) - return; + const CClientVariables* cachedSource = g_cachedSettings.source.load(std::memory_order_relaxed); + const int cachedRevision = g_cachedSettings.revision.load(std::memory_order_relaxed); - std::lock_guard guard(g_cachedSettings.updateMutex); + if (cachedSource == currentSource && cachedRevision == currentRevision) + return; - const CClientVariables* doubleCheckSource = g_cachedSettings.source.load(std::memory_order_relaxed); - const int doubleCheckRevision = g_cachedSettings.revision.load(std::memory_order_relaxed); - if (doubleCheckSource == currentSource && doubleCheckRevision == currentRevision) - return; + std::lock_guard guard(g_cachedSettings.updateMutex); - float gammaPower = 1.0f; - float brightnessScale = 1.0f; - float contrastScale = 1.0f; - float saturationScale = 1.0f; - bool gammaEnabled = false; - bool brightnessEnabled = false; - bool contrastEnabled = false; - bool saturationEnabled = false; - bool applyWindowed = false; - bool applyFullscreen = false; + const CClientVariables* doubleCheckSource = g_cachedSettings.source.load(std::memory_order_relaxed); + const int doubleCheckRevision = g_cachedSettings.revision.load(std::memory_order_relaxed); + if (doubleCheckSource == currentSource && doubleCheckRevision == currentRevision) + return; - if (cvars) - { - cvars->Get("borderless_gamma_power", gammaPower); - cvars->Get("borderless_brightness_scale", brightnessScale); - cvars->Get("borderless_contrast_scale", contrastScale); - cvars->Get("borderless_saturation_scale", saturationScale); - cvars->Get("borderless_gamma_enabled", gammaEnabled); - cvars->Get("borderless_brightness_enabled", brightnessEnabled); - cvars->Get("borderless_contrast_enabled", contrastEnabled); - cvars->Get("borderless_saturation_enabled", saturationEnabled); - cvars->Get("borderless_apply_windowed", applyWindowed); - cvars->Get("borderless_apply_fullscreen", applyFullscreen); - - if (!cvars->Exists("borderless_apply_windowed")) + float gammaPower = 1.0f; + float brightnessScale = 1.0f; + float contrastScale = 1.0f; + float saturationScale = 1.0f; + bool gammaEnabled = false; + bool brightnessEnabled = false; + bool contrastEnabled = false; + bool saturationEnabled = false; + bool applyWindowed = false; + bool applyFullscreen = false; + + if (cvars) { - bool legacyEnable = false; - cvars->Get("borderless_enable_srgb", legacyEnable); - applyWindowed = legacyEnable; + cvars->Get("borderless_gamma_power", gammaPower); + cvars->Get("borderless_brightness_scale", brightnessScale); + cvars->Get("borderless_contrast_scale", contrastScale); + cvars->Get("borderless_saturation_scale", saturationScale); + cvars->Get("borderless_gamma_enabled", gammaEnabled); + cvars->Get("borderless_brightness_enabled", brightnessEnabled); + cvars->Get("borderless_contrast_enabled", contrastEnabled); + cvars->Get("borderless_saturation_enabled", saturationEnabled); + cvars->Get("borderless_apply_windowed", applyWindowed); + cvars->Get("borderless_apply_fullscreen", applyFullscreen); + + if (!cvars->Exists("borderless_apply_windowed")) + { + bool legacyEnable = false; + cvars->Get("borderless_enable_srgb", legacyEnable); + applyWindowed = legacyEnable; + } + + if (!std::isfinite(gammaPower)) + gammaPower = 1.0f; + if (!std::isfinite(brightnessScale)) + brightnessScale = 1.0f; + if (!std::isfinite(contrastScale)) + contrastScale = 1.0f; + if (!std::isfinite(saturationScale)) + saturationScale = 1.0f; + + gammaPower = std::clamp(gammaPower, kGammaMin, kGammaMax); + brightnessScale = std::clamp(brightnessScale, kBrightnessMin, kBrightnessMax); + contrastScale = std::clamp(contrastScale, kContrastMin, kContrastMax); + saturationScale = std::clamp(saturationScale, kSaturationMin, kSaturationMax); } - if (!std::isfinite(gammaPower)) - gammaPower = 1.0f; - if (!std::isfinite(brightnessScale)) - brightnessScale = 1.0f; - if (!std::isfinite(contrastScale)) - contrastScale = 1.0f; - if (!std::isfinite(saturationScale)) - saturationScale = 1.0f; - - gammaPower = std::clamp(gammaPower, kGammaMin, kGammaMax); - brightnessScale = std::clamp(brightnessScale, kBrightnessMin, kBrightnessMax); - contrastScale = std::clamp(contrastScale, kContrastMin, kContrastMax); - saturationScale = std::clamp(saturationScale, kSaturationMin, kSaturationMax); + g_cachedSettings.gammaPower.store(gammaPower, std::memory_order_relaxed); + g_cachedSettings.brightnessScale.store(brightnessScale, std::memory_order_relaxed); + g_cachedSettings.contrastScale.store(contrastScale, std::memory_order_relaxed); + g_cachedSettings.saturationScale.store(saturationScale, std::memory_order_relaxed); + g_cachedSettings.gammaEnabled.store(gammaEnabled, std::memory_order_relaxed); + g_cachedSettings.brightnessEnabled.store(brightnessEnabled, std::memory_order_relaxed); + g_cachedSettings.contrastEnabled.store(contrastEnabled, std::memory_order_relaxed); + g_cachedSettings.saturationEnabled.store(saturationEnabled, std::memory_order_relaxed); + g_cachedSettings.applyWindowed.store(applyWindowed, std::memory_order_relaxed); + g_cachedSettings.applyFullscreen.store(applyFullscreen, std::memory_order_relaxed); + g_cachedSettings.source.store(currentSource, std::memory_order_relaxed); + g_cachedSettings.revision.store(currentRevision, std::memory_order_release); } - g_cachedSettings.gammaPower.store(gammaPower, std::memory_order_relaxed); - g_cachedSettings.brightnessScale.store(brightnessScale, std::memory_order_relaxed); - g_cachedSettings.contrastScale.store(contrastScale, std::memory_order_relaxed); - g_cachedSettings.saturationScale.store(saturationScale, std::memory_order_relaxed); - g_cachedSettings.gammaEnabled.store(gammaEnabled, std::memory_order_relaxed); - g_cachedSettings.brightnessEnabled.store(brightnessEnabled, std::memory_order_relaxed); - g_cachedSettings.contrastEnabled.store(contrastEnabled, std::memory_order_relaxed); - g_cachedSettings.saturationEnabled.store(saturationEnabled, std::memory_order_relaxed); - g_cachedSettings.applyWindowed.store(applyWindowed, std::memory_order_relaxed); - g_cachedSettings.applyFullscreen.store(applyFullscreen, std::memory_order_relaxed); - g_cachedSettings.source.store(currentSource, std::memory_order_relaxed); - g_cachedSettings.revision.store(currentRevision, std::memory_order_release); -} - -void FetchSettings(float& gammaPower, float& brightnessScale, float& contrastScale, float& saturationScale, bool& applyWindowed, bool& applyFullscreen) -{ - RefreshCacheIfNeeded(); - - const float cachedGammaPower = g_cachedSettings.gammaPower.load(std::memory_order_acquire); - const float cachedBrightness = g_cachedSettings.brightnessScale.load(std::memory_order_acquire); - const float cachedContrast = g_cachedSettings.contrastScale.load(std::memory_order_acquire); - const float cachedSaturation = g_cachedSettings.saturationScale.load(std::memory_order_acquire); - const bool gammaEnabled = g_cachedSettings.gammaEnabled.load(std::memory_order_acquire); - const bool brightnessEnabled = g_cachedSettings.brightnessEnabled.load(std::memory_order_acquire); - const bool contrastEnabled = g_cachedSettings.contrastEnabled.load(std::memory_order_acquire); - const bool saturationEnabled = g_cachedSettings.saturationEnabled.load(std::memory_order_acquire); - - gammaPower = gammaEnabled ? cachedGammaPower : 1.0f; - brightnessScale = brightnessEnabled ? cachedBrightness : 1.0f; - contrastScale = contrastEnabled ? cachedContrast : 1.0f; - saturationScale = saturationEnabled ? cachedSaturation : 1.0f; + void FetchSettings(float& gammaPower, float& brightnessScale, float& contrastScale, float& saturationScale, bool& applyWindowed, bool& applyFullscreen) + { + RefreshCacheIfNeeded(); + + const float cachedGammaPower = g_cachedSettings.gammaPower.load(std::memory_order_acquire); + const float cachedBrightness = g_cachedSettings.brightnessScale.load(std::memory_order_acquire); + const float cachedContrast = g_cachedSettings.contrastScale.load(std::memory_order_acquire); + const float cachedSaturation = g_cachedSettings.saturationScale.load(std::memory_order_acquire); + const bool gammaEnabled = g_cachedSettings.gammaEnabled.load(std::memory_order_acquire); + const bool brightnessEnabled = g_cachedSettings.brightnessEnabled.load(std::memory_order_acquire); + const bool contrastEnabled = g_cachedSettings.contrastEnabled.load(std::memory_order_acquire); + const bool saturationEnabled = g_cachedSettings.saturationEnabled.load(std::memory_order_acquire); + + gammaPower = gammaEnabled ? cachedGammaPower : 1.0f; + brightnessScale = brightnessEnabled ? cachedBrightness : 1.0f; + contrastScale = contrastEnabled ? cachedContrast : 1.0f; + saturationScale = saturationEnabled ? cachedSaturation : 1.0f; + + applyWindowed = g_cachedSettings.applyWindowed.load(std::memory_order_acquire); + applyFullscreen = g_cachedSettings.applyFullscreen.load(std::memory_order_acquire); + } - applyWindowed = g_cachedSettings.applyWindowed.load(std::memory_order_acquire); - applyFullscreen = g_cachedSettings.applyFullscreen.load(std::memory_order_acquire); -} + bool ShouldApplyAdjustments(float gammaPower, float brightnessScale, float contrastScale, float saturationScale) + { + constexpr float epsilon = 0.001f; + return std::fabs(gammaPower - 1.0f) > epsilon || std::fabs(brightnessScale - 1.0f) > epsilon || std::fabs(contrastScale - 1.0f) > epsilon || + std::fabs(saturationScale - 1.0f) > epsilon; + } -bool ShouldApplyAdjustments(float gammaPower, float brightnessScale, float contrastScale, float saturationScale) -{ - constexpr float epsilon = 0.001f; - return std::fabs(gammaPower - 1.0f) > epsilon || std::fabs(brightnessScale - 1.0f) > epsilon || std::fabs(contrastScale - 1.0f) > epsilon || - std::fabs(saturationScale - 1.0f) > epsilon; } -} // namespace BorderlessGamma - using namespace BorderlessGamma; -std::mutex g_proxyDeviceMutex; -std::mutex g_gammaStateMutex; -std::mutex g_deviceStateMutex; -std::atomic g_proxyRegistrationCounter{0}; -std::atomic g_gtaSceneActiveCount{0}; -uint64_t g_activeProxyRegistrationId = 0; +std::mutex g_proxyDeviceMutex; +std::mutex g_gammaStateMutex; +std::mutex g_deviceStateMutex; +std::atomic g_proxyRegistrationCounter{0}; +std::atomic g_gtaSceneActiveCount{0}; +uint64_t g_activeProxyRegistrationId = 0; std::atomic g_bInGTAScene{false}; CProxyDirect3DDevice9* g_pProxyDevice = NULL; @@ -204,37 +203,37 @@ CProxyDirect3DDevice9::SMemoryState g_StaticMemoryState; namespace { -uint64_t RegisterProxyDevice(CProxyDirect3DDevice9* instance) -{ - std::lock_guard guard(g_proxyDeviceMutex); - const uint64_t registrationId = g_proxyRegistrationCounter.fetch_add(1, std::memory_order_relaxed) + 1; - g_pProxyDevice = instance; - g_activeProxyRegistrationId = registrationId; + uint64_t RegisterProxyDevice(CProxyDirect3DDevice9* instance) { - std::lock_guard stateGuard(g_deviceStateMutex); - g_pDeviceState = instance ? &instance->DeviceState : nullptr; + std::lock_guard guard(g_proxyDeviceMutex); + const uint64_t registrationId = g_proxyRegistrationCounter.fetch_add(1, std::memory_order_relaxed) + 1; + g_pProxyDevice = instance; + g_activeProxyRegistrationId = registrationId; + { + std::lock_guard stateGuard(g_deviceStateMutex); + g_pDeviceState = instance ? &instance->DeviceState : nullptr; + } + return registrationId; } - return registrationId; -} -bool UnregisterProxyDevice(CProxyDirect3DDevice9* instance, uint64_t registrationId) -{ - std::lock_guard guard(g_proxyDeviceMutex); - if (g_pProxyDevice != instance) - return false; + bool UnregisterProxyDevice(CProxyDirect3DDevice9* instance, uint64_t registrationId) + { + std::lock_guard guard(g_proxyDeviceMutex); + if (g_pProxyDevice != instance) + return false; - if (g_activeProxyRegistrationId != registrationId) - return false; + if (g_activeProxyRegistrationId != registrationId) + return false; - g_pProxyDevice = nullptr; - g_activeProxyRegistrationId = 0; - { - std::lock_guard stateGuard(g_deviceStateMutex); - g_pDeviceState = nullptr; + g_pProxyDevice = nullptr; + g_activeProxyRegistrationId = 0; + { + std::lock_guard stateGuard(g_deviceStateMutex); + g_pDeviceState = nullptr; + } + return true; } - return true; -} -} // namespace +} // namespace void IncrementGTASceneState() { @@ -261,13 +260,8 @@ void ResetGTASceneState() // Proxy constructor and destructor. // Constructor performs heavy initialization; defer global registration until the end to avoid exposing a partially built object. CProxyDirect3DDevice9::CProxyDirect3DDevice9(IDirect3DDevice9* pDevice) - : m_pDevice(pDevice) - , m_pData(nullptr) - , m_lRefCount(1) - , m_registrationToken(0) - , m_lastTestCooperativeLevelResult(D3D_OK) + : m_pDevice(pDevice), m_pData(nullptr), m_lRefCount(1), m_registrationToken(0), m_lastTestCooperativeLevelResult(D3D_OK) { - struct DeviceRefGuard { IDirect3DDevice9* device; @@ -301,14 +295,14 @@ CProxyDirect3DDevice9::CProxyDirect3DDevice9(IDirect3DDevice9* pDevice) if (!pD3D9) { m_pDevice->GetDirect3D(&pD3D9); - bNeedRelease = true; // GetDirect3D increments reference count + bNeedRelease = true; // GetDirect3D increments reference count } if (pD3D9) { D3DADAPTER_IDENTIFIER9 adaptIdent; - HRESULT hr = pD3D9->GetAdapterIdentifier(iAdapter, 0, &adaptIdent); - + HRESULT hr = pD3D9->GetAdapterIdentifier(iAdapter, 0, &adaptIdent); + if (SUCCEEDED(hr)) { // GetAdapterIdentifier succeeded - use adapter info @@ -401,9 +395,9 @@ CProxyDirect3DDevice9::~CProxyDirect3DDevice9() { const bool bWasRegistered = UnregisterProxyDevice(this, m_registrationToken); - bool bRestoreGamma = false; - UINT lastSwapChain = 0; - D3DGAMMARAMP originalGammaRamp{}; + bool bRestoreGamma = false; + UINT lastSwapChain = 0; + D3DGAMMARAMP originalGammaRamp{}; if (bWasRegistered) { @@ -440,7 +434,6 @@ CProxyDirect3DDevice9::~CProxyDirect3DDevice9() m_pDevice->Release(); m_pDevice = nullptr; } - } /*** IUnknown methods ***/ @@ -448,9 +441,9 @@ HRESULT CProxyDirect3DDevice9::QueryInterface(REFIID riid, void** ppvObj) { if (!ppvObj) return E_POINTER; - + *ppvObj = nullptr; - + // Check if its for IUnknown or IDirect3DDevice9 if (riid == IID_IUnknown || riid == IID_IDirect3DDevice9) { @@ -458,7 +451,7 @@ HRESULT CProxyDirect3DDevice9::QueryInterface(REFIID riid, void** ppvObj) AddRef(); return S_OK; } - + // For any other interface, forward to underlying device // But this means the caller gets the underlying device, not our proxy return m_pDevice->QueryInterface(riid, ppvObj); @@ -466,17 +459,17 @@ HRESULT CProxyDirect3DDevice9::QueryInterface(REFIID riid, void** ppvObj) ULONG CProxyDirect3DDevice9::AddRef() { - // Only increment proxy reference count + // Only increment proxy reference count // We keep a single reference to the underlying device throughout the lifetime LONG lNewRefCount = m_lRefCount.fetch_add(1, std::memory_order_relaxed) + 1; return static_cast(lNewRefCount); } ULONG CProxyDirect3DDevice9::Release() -{ - // Only decrement proxy reference count +{ + // Only decrement proxy reference count LONG lNewRefCount = m_lRefCount.fetch_sub(1, std::memory_order_acq_rel) - 1; - + if (lNewRefCount == 0) { // Call event handler @@ -492,11 +485,11 @@ ULONG CProxyDirect3DDevice9::Release() HRESULT CProxyDirect3DDevice9::TestCooperativeLevel() { HRESULT hResult = m_pDevice->TestCooperativeLevel(); - + if (hResult != m_lastTestCooperativeLevelResult) { m_lastTestCooperativeLevelResult = hResult; - + // Additional safety for when transitioning to/from lost states if (hResult == D3DERR_DEVICELOST || hResult == D3DERR_DEVICENOTRESET) { @@ -504,7 +497,7 @@ HRESULT CProxyDirect3DDevice9::TestCooperativeLevel() Sleep(1); } } - + return hResult; } @@ -697,7 +690,6 @@ static bool WaitForGpuIdle(IDirect3DDevice9* pDevice) HRESULT CProxyDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParameters) { - // Validate input parameters if (!pPresentationParameters) { @@ -713,7 +705,7 @@ HRESULT CProxyDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParamet g_GammaState = SGammaState(); gammaStateCleared = true; } - + // Check cooperative level before attempting reset HRESULT hCoopLevel = m_pDevice->TestCooperativeLevel(); if (hCoopLevel == D3DERR_DEVICELOST) @@ -748,7 +740,7 @@ HRESULT CProxyDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParamet WaitForGpuIdle(m_pDevice); Sleep(1); - + // Call the real reset routine. hResult = DoResetDevice(m_pDevice, pPresentationParameters, presentationParametersOrig); @@ -804,7 +796,7 @@ HRESULT CProxyDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParamet // Ensure scene state is properly restored // Call our event handler. CDirect3DEvents9::OnRestore(m_pDevice); - + // Additional sync point for GPU driver if (BeginSceneWithoutProxy(m_pDevice, ESceneOwner::MTA)) { @@ -823,7 +815,6 @@ HRESULT CProxyDirect3DDevice9::Reset(D3DPRESENT_PARAMETERS* pPresentationParamet return hResult; } - HRESULT CProxyDirect3DDevice9::Present(CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion) { // Reset frame stat counters - using memset for efficiency @@ -1057,7 +1048,8 @@ HRESULT CProxyDirect3DDevice9::CreateRenderTarget(UINT Width, UINT Height, D3DFO HRESULT CProxyDirect3DDevice9::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle) { - return CDirect3DEvents9::CreateDepthStencilSurfaceGuarded(m_pDevice, Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle); + return CDirect3DEvents9::CreateDepthStencilSurfaceGuarded(m_pDevice, Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, + pSharedHandle); } HRESULT CProxyDirect3DDevice9::UpdateSurface(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, @@ -1433,9 +1425,8 @@ HRESULT CProxyDirect3DDevice9::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UIN HRESULT CProxyDirect3DDevice9::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount) { - SetCallType(SCallState::DRAW_INDEXED_PRIMITIVE, - {PrimitiveType, BaseVertexIndex, static_cast(MinVertexIndex), static_cast(NumVertices), static_cast(startIndex), - static_cast(primCount)}); + SetCallType(SCallState::DRAW_INDEXED_PRIMITIVE, {PrimitiveType, BaseVertexIndex, static_cast(MinVertexIndex), static_cast(NumVertices), + static_cast(startIndex), static_cast(primCount)}); HRESULT hr = CDirect3DEvents9::OnDrawIndexedPrimitive(m_pDevice, PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount); SetCallType(SCallState::NONE); return hr; @@ -1451,8 +1442,8 @@ HRESULT CProxyDirect3DDevice9::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE Primitive CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride) { - return CDirect3DEvents9::DrawIndexedPrimitiveUPGuarded(m_pDevice, PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, - IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); + return CDirect3DEvents9::DrawIndexedPrimitiveUPGuarded(m_pDevice, PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, + pVertexStreamZeroData, VertexStreamZeroStride); } HRESULT CProxyDirect3DDevice9::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, @@ -1759,8 +1750,7 @@ bool EndSceneWithoutProxy(IDirect3DDevice9* pDevice, ESceneOwner owner) return true; } -CScopedActiveProxyDevice::CScopedActiveProxyDevice() - : m_pProxy(AcquireActiveProxyDevice()) +CScopedActiveProxyDevice::CScopedActiveProxyDevice() : m_pProxy(AcquireActiveProxyDevice()) { } diff --git a/Client/core/DXHook/CProxyDirect3DDevice9.h b/Client/core/DXHook/CProxyDirect3DDevice9.h index 11ea3a3b5ae..7248f6f478a 100644 --- a/Client/core/DXHook/CProxyDirect3DDevice9.h +++ b/Client/core/DXHook/CProxyDirect3DDevice9.h @@ -23,30 +23,30 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 /*** IUnknown methods ***/ virtual HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - virtual ULONG __stdcall AddRef(); - virtual ULONG __stdcall Release(); + virtual ULONG __stdcall AddRef(); + virtual ULONG __stdcall Release(); /*** IDirect3DDevice9 methods ***/ virtual HRESULT __stdcall TestCooperativeLevel(); - virtual UINT __stdcall GetAvailableTextureMem(); + virtual UINT __stdcall GetAvailableTextureMem(); virtual HRESULT __stdcall EvictManagedResources(); virtual HRESULT __stdcall GetDirect3D(IDirect3D9 * *ppD3D9); virtual HRESULT __stdcall GetDeviceCaps(D3DCAPS9 * pCaps); virtual HRESULT __stdcall GetDisplayMode(UINT iSwapChain, D3DDISPLAYMODE * pMode); virtual HRESULT __stdcall GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS * pParameters); virtual HRESULT __stdcall SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9 * pCursorBitmap); - virtual void __stdcall SetCursorPosition(int X, int Y, DWORD Flags); - virtual BOOL __stdcall ShowCursor(BOOL bShow); + virtual void __stdcall SetCursorPosition(int X, int Y, DWORD Flags); + virtual BOOL __stdcall ShowCursor(BOOL bShow); virtual HRESULT __stdcall CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS * pPresentationParameters, IDirect3DSwapChain9 * *pSwapChain); virtual HRESULT __stdcall GetSwapChain(UINT iSwapChain, IDirect3DSwapChain9 * *pSwapChain); - virtual UINT __stdcall GetNumberOfSwapChains(); + virtual UINT __stdcall GetNumberOfSwapChains(); virtual HRESULT __stdcall Reset(D3DPRESENT_PARAMETERS * pPresentationParameters); virtual HRESULT __stdcall Present(CONST RECT * pSourceRect, CONST RECT * pDestRect, HWND hDestWindowOverride, CONST RGNDATA * pDirtyRegion); virtual HRESULT __stdcall GetBackBuffer(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 * *ppBackBuffer); virtual HRESULT __stdcall GetRasterStatus(UINT iSwapChain, D3DRASTER_STATUS * pRasterStatus); virtual HRESULT __stdcall SetDialogBoxMode(BOOL bEnableDialogs); - virtual VOID __stdcall SetGammaRamp(UINT iSwapChain, DWORD Flags, CONST D3DGAMMARAMP * pRamp); - virtual VOID __stdcall GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP * pRamp); + virtual VOID __stdcall SetGammaRamp(UINT iSwapChain, DWORD Flags, CONST D3DGAMMARAMP * pRamp); + virtual VOID __stdcall GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP * pRamp); virtual HRESULT __stdcall CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9 * *ppTexture, HANDLE * pSharedHandle); virtual HRESULT __stdcall CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, @@ -113,9 +113,9 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 virtual HRESULT __stdcall SetScissorRect(CONST RECT * pRect); virtual HRESULT __stdcall GetScissorRect(RECT * pRect); virtual HRESULT __stdcall SetSoftwareVertexProcessing(BOOL bSoftware); - virtual BOOL __stdcall GetSoftwareVertexProcessing(); + virtual BOOL __stdcall GetSoftwareVertexProcessing(); virtual HRESULT __stdcall SetNPatchMode(float nSegments); - virtual FLOAT __stdcall GetNPatchMode(); + virtual FLOAT __stdcall GetNPatchMode(); virtual HRESULT __stdcall DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount); virtual HRESULT __stdcall DrawIndexedPrimitive(D3DPRIMITIVETYPE, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount); @@ -179,8 +179,8 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 const static int D3DSAMP_MAX = 14; const static int D3DTS_MAX = 260; - #define DPAD(f,t) DWORD pad##f##_##t[(t)-(f)+1] - #define MPAD(f,t) D3DMATRIX pad##f##_##t[(t)-(f)+1] +#define DPAD(f, t) DWORD pad##f##_##t[(t) - (f) + 1] +#define MPAD(f, t) D3DMATRIX pad##f##_##t[(t) - (f) + 1] struct SD3DRenderState { @@ -190,127 +190,127 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 struct { DPAD(0, 6); - D3DZBUFFERTYPE ZENABLE; // = 7, /* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) */ - D3DFILLMODE FILLMODE; // = 8, /* D3DFILLMODE */ - D3DSHADEMODE SHADEMODE; // = 9, /* D3DSHADEMODE */ + D3DZBUFFERTYPE ZENABLE; // = 7, /* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) */ + D3DFILLMODE FILLMODE; // = 8, /* D3DFILLMODE */ + D3DSHADEMODE SHADEMODE; // = 9, /* D3DSHADEMODE */ DPAD(10, 13); - DWORD ZWRITEENABLE; // = 14, /* TRUE to enable z writes */ - DWORD ALPHATESTENABLE; // = 15, /* TRUE to enable alpha tests */ - DWORD LASTPIXEL; // = 16, /* TRUE for last-pixel on lines */ + DWORD ZWRITEENABLE; // = 14, /* TRUE to enable z writes */ + DWORD ALPHATESTENABLE; // = 15, /* TRUE to enable alpha tests */ + DWORD LASTPIXEL; // = 16, /* TRUE for last-pixel on lines */ DPAD(17, 18); - D3DBLEND SRCBLEND; // = 19, /* D3DBLEND */ - D3DBLEND DESTBLEND; // = 20, /* D3DBLEND */ + D3DBLEND SRCBLEND; // = 19, /* D3DBLEND */ + D3DBLEND DESTBLEND; // = 20, /* D3DBLEND */ DPAD(21, 21); - D3DCULL CULLMODE; // = 22, /* D3DCULL */ - D3DCMPFUNC ZFUNC; // = 23, /* D3DCMPFUNC */ - DWORD ALPHAREF; // = 24, /* D3DFIXED */ - D3DCMPFUNC ALPHAFUNC; // = 25, /* D3DCMPFUNC */ - DWORD DITHERENABLE; // = 26, /* TRUE to enable dithering */ - DWORD ALPHABLENDENABLE; // = 27, /* TRUE to enable alpha blending */ - DWORD FOGENABLE; // = 28, /* TRUE to enable fog blending */ - DWORD SPECULARENABLE; // = 29, /* TRUE to enable specular */ + D3DCULL CULLMODE; // = 22, /* D3DCULL */ + D3DCMPFUNC ZFUNC; // = 23, /* D3DCMPFUNC */ + DWORD ALPHAREF; // = 24, /* D3DFIXED */ + D3DCMPFUNC ALPHAFUNC; // = 25, /* D3DCMPFUNC */ + DWORD DITHERENABLE; // = 26, /* TRUE to enable dithering */ + DWORD ALPHABLENDENABLE; // = 27, /* TRUE to enable alpha blending */ + DWORD FOGENABLE; // = 28, /* TRUE to enable fog blending */ + DWORD SPECULARENABLE; // = 29, /* TRUE to enable specular */ DPAD(30, 33); - D3DCOLOR FOGCOLOR; // = 34, /* D3DCOLOR */ - D3DFOGMODE FOGTABLEMODE; // = 35, /* D3DFOGMODE */ - DWORD FOGSTART; // = 36, /* Fog start (for both vertex and pixel fog) */ - DWORD FOGEND; // = 37, /* Fog end */ - DWORD FOGDENSITY; // = 38, /* Fog density */ + D3DCOLOR FOGCOLOR; // = 34, /* D3DCOLOR */ + D3DFOGMODE FOGTABLEMODE; // = 35, /* D3DFOGMODE */ + DWORD FOGSTART; // = 36, /* Fog start (for both vertex and pixel fog) */ + DWORD FOGEND; // = 37, /* Fog end */ + DWORD FOGDENSITY; // = 38, /* Fog density */ DPAD(39, 47); - DWORD RANGEFOGENABLE; // = 48, /* Enables range-based fog */ + DWORD RANGEFOGENABLE; // = 48, /* Enables range-based fog */ DPAD(49, 51); - DWORD STENCILENABLE; // = 52, /* BOOL enable/disable stenciling */ - D3DSTENCILOP STENCILFAIL; // = 53, /* D3DSTENCILOP to do if stencil test fails */ - D3DSTENCILOP STENCILZFAIL; // = 54, /* D3DSTENCILOP to do if stencil test passes and Z test fails */ - D3DSTENCILOP STENCILPASS; // = 55, /* D3DSTENCILOP to do if both stencil and Z tests pass */ - D3DCMPFUNC STENCILFUNC; // = 56, /* D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true */ - DWORD STENCILREF; // = 57, /* Reference value used in stencil test */ - DWORD STENCILMASK; // = 58, /* Mask value used in stencil test */ - DWORD STENCILWRITEMASK; // = 59, /* Write mask applied to values written to stencil buffer */ - D3DCOLOR TEXTUREFACTOR; // = 60, /* D3DCOLOR used for multi-texture blend */ + DWORD STENCILENABLE; // = 52, /* BOOL enable/disable stenciling */ + D3DSTENCILOP STENCILFAIL; // = 53, /* D3DSTENCILOP to do if stencil test fails */ + D3DSTENCILOP STENCILZFAIL; // = 54, /* D3DSTENCILOP to do if stencil test passes and Z test fails */ + D3DSTENCILOP STENCILPASS; // = 55, /* D3DSTENCILOP to do if both stencil and Z tests pass */ + D3DCMPFUNC STENCILFUNC; // = 56, /* D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true */ + DWORD STENCILREF; // = 57, /* Reference value used in stencil test */ + DWORD STENCILMASK; // = 58, /* Mask value used in stencil test */ + DWORD STENCILWRITEMASK; // = 59, /* Write mask applied to values written to stencil buffer */ + D3DCOLOR TEXTUREFACTOR; // = 60, /* D3DCOLOR used for multi-texture blend */ DPAD(61, 127); - DWORD WRAP0; // = 128, /* wrap for 1st texture coord. set */ - DWORD WRAP1; // = 129, /* wrap for 2nd texture coord. set */ - DWORD WRAP2; // = 130, /* wrap for 3rd texture coord. set */ - DWORD WRAP3; // = 131, /* wrap for 4th texture coord. set */ - DWORD WRAP4; // = 132, /* wrap for 5th texture coord. set */ - DWORD WRAP5; // = 133, /* wrap for 6th texture coord. set */ - DWORD WRAP6; // = 134, /* wrap for 7th texture coord. set */ - DWORD WRAP7; // = 135, /* wrap for 8th texture coord. set */ - DWORD CLIPPING; // = 136, - DWORD LIGHTING; // = 137, + DWORD WRAP0; // = 128, /* wrap for 1st texture coord. set */ + DWORD WRAP1; // = 129, /* wrap for 2nd texture coord. set */ + DWORD WRAP2; // = 130, /* wrap for 3rd texture coord. set */ + DWORD WRAP3; // = 131, /* wrap for 4th texture coord. set */ + DWORD WRAP4; // = 132, /* wrap for 5th texture coord. set */ + DWORD WRAP5; // = 133, /* wrap for 6th texture coord. set */ + DWORD WRAP6; // = 134, /* wrap for 7th texture coord. set */ + DWORD WRAP7; // = 135, /* wrap for 8th texture coord. set */ + DWORD CLIPPING; // = 136, + DWORD LIGHTING; // = 137, DPAD(138, 138); - D3DCOLOR AMBIENT; // = 139, - DWORD FOGVERTEXMODE; // = 140, - DWORD COLORVERTEX; // = 141, - DWORD LOCALVIEWER; // = 142, - DWORD NORMALIZENORMALS; // = 143, + D3DCOLOR AMBIENT; // = 139, + DWORD FOGVERTEXMODE; // = 140, + DWORD COLORVERTEX; // = 141, + DWORD LOCALVIEWER; // = 142, + DWORD NORMALIZENORMALS; // = 143, DPAD(144, 144); - DWORD DIFFUSEMATERIALSOURCE; // = 145, - DWORD SPECULARMATERIALSOURCE; // = 146, - DWORD AMBIENTMATERIALSOURCE; // = 147, - DWORD EMISSIVEMATERIALSOURCE; // = 148, + DWORD DIFFUSEMATERIALSOURCE; // = 145, + DWORD SPECULARMATERIALSOURCE; // = 146, + DWORD AMBIENTMATERIALSOURCE; // = 147, + DWORD EMISSIVEMATERIALSOURCE; // = 148, DPAD(149, 150); - DWORD VERTEXBLEND; // = 151, - DWORD CLIPPLANEENABLE; // = 152, + DWORD VERTEXBLEND; // = 151, + DWORD CLIPPLANEENABLE; // = 152, DPAD(153, 153); - DWORD POINTSIZE; // = 154, /* float point size */ - DWORD POINTSIZE_MIN; // = 155, /* float point size min threshold */ - DWORD POINTSPRITEENABLE; // = 156, /* BOOL point texture coord control */ - DWORD POINTSCALEENABLE; // = 157, /* BOOL point size scale enable */ - DWORD POINTSCALE_A; // = 158, /* float point attenuation A value */ - DWORD POINTSCALE_B; // = 159, /* float point attenuation B value */ - DWORD POINTSCALE_C; // = 160, /* float point attenuation C value */ - DWORD MULTISAMPLEANTIALIAS; // = 161, // BOOL - set to do FSAA with multisample buffer - DWORD MULTISAMPLEMASK; // = 162, // DWORD -; //per-sample enable/disable - DWORD PATCHEDGESTYLE; // = 163, // Sets whether patch edges will use float style tessellation + DWORD POINTSIZE; // = 154, /* float point size */ + DWORD POINTSIZE_MIN; // = 155, /* float point size min threshold */ + DWORD POINTSPRITEENABLE; // = 156, /* BOOL point texture coord control */ + DWORD POINTSCALEENABLE; // = 157, /* BOOL point size scale enable */ + DWORD POINTSCALE_A; // = 158, /* float point attenuation A value */ + DWORD POINTSCALE_B; // = 159, /* float point attenuation B value */ + DWORD POINTSCALE_C; // = 160, /* float point attenuation C value */ + DWORD MULTISAMPLEANTIALIAS; // = 161, // BOOL - set to do FSAA with multisample buffer + DWORD MULTISAMPLEMASK; // = 162, // DWORD -; //per-sample enable/disable + DWORD PATCHEDGESTYLE; // = 163, // Sets whether patch edges will use float style tessellation DPAD(164, 164); - DWORD DEBUGMONITORTOKEN; // = 165, // DEBUG ONLY - token to debug monitor - DWORD POINTSIZE_MAX; // = 166, /* float point size max threshold */ - DWORD INDEXEDVERTEXBLENDENABLE; // = 167, - DWORD COLORWRITEENABLE; // = 168, // per-channel write enable + DWORD DEBUGMONITORTOKEN; // = 165, // DEBUG ONLY - token to debug monitor + DWORD POINTSIZE_MAX; // = 166, /* float point size max threshold */ + DWORD INDEXEDVERTEXBLENDENABLE; // = 167, + DWORD COLORWRITEENABLE; // = 168, // per-channel write enable DPAD(169, 169); - DWORD TWEENFACTOR; // = 170, // float tween factor - D3DBLENDOP BLENDOP; // = 171, // D3DBLENDOP setting - D3DDEGREETYPE POSITIONDEGREE; // = 172, // NPatch position interpolation degree. D3DDEGREE_LINEAR or D3DDEGREE_CUBIC (default) - D3DDEGREETYPE NORMALDEGREE; // = 173, // NPatch normal interpolation degree. D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC - DWORD SCISSORTESTENABLE; // = 174, - DWORD SLOPESCALEDEPTHBIAS; // = 175, - DWORD ANTIALIASEDLINEENABLE; // = 176, + DWORD TWEENFACTOR; // = 170, // float tween factor + D3DBLENDOP BLENDOP; // = 171, // D3DBLENDOP setting + D3DDEGREETYPE POSITIONDEGREE; // = 172, // NPatch position interpolation degree. D3DDEGREE_LINEAR or D3DDEGREE_CUBIC (default) + D3DDEGREETYPE NORMALDEGREE; // = 173, // NPatch normal interpolation degree. D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC + DWORD SCISSORTESTENABLE; // = 174, + DWORD SLOPESCALEDEPTHBIAS; // = 175, + DWORD ANTIALIASEDLINEENABLE; // = 176, DPAD(177, 177); - DWORD MINTESSELLATIONLEVEL; // = 178, - DWORD MAXTESSELLATIONLEVEL; // = 179, - DWORD ADAPTIVETESS_X; // = 180, - DWORD ADAPTIVETESS_Y; // = 181, - DWORD ADAPTIVETESS_Z; // = 182, - DWORD ADAPTIVETESS_W; // = 183, - DWORD ENABLEADAPTIVETESSELLATION; // = 184, - DWORD TWOSIDEDSTENCILMODE; // = 185, /* BOOL enable/disable 2 sided stenciling */ - D3DSTENCILOP CCW_STENCILFAIL; // = 186, /* D3DSTENCILOP to do if ccw stencil test fails */ - D3DSTENCILOP CCW_STENCILZFAIL; // = 187, /* D3DSTENCILOP to do if ccw stencil test passes and Z test fails */ - D3DSTENCILOP CCW_STENCILPASS; // = 188, /* D3DSTENCILOP to do if both ccw stencil and Z tests pass */ + DWORD MINTESSELLATIONLEVEL; // = 178, + DWORD MAXTESSELLATIONLEVEL; // = 179, + DWORD ADAPTIVETESS_X; // = 180, + DWORD ADAPTIVETESS_Y; // = 181, + DWORD ADAPTIVETESS_Z; // = 182, + DWORD ADAPTIVETESS_W; // = 183, + DWORD ENABLEADAPTIVETESSELLATION; // = 184, + DWORD TWOSIDEDSTENCILMODE; // = 185, /* BOOL enable/disable 2 sided stenciling */ + D3DSTENCILOP CCW_STENCILFAIL; // = 186, /* D3DSTENCILOP to do if ccw stencil test fails */ + D3DSTENCILOP CCW_STENCILZFAIL; // = 187, /* D3DSTENCILOP to do if ccw stencil test passes and Z test fails */ + D3DSTENCILOP CCW_STENCILPASS; // = 188, /* D3DSTENCILOP to do if both ccw stencil and Z tests pass */ D3DCMPFUNC - CCW_STENCILFUNC; // = 189, /* D3DCMPFUNC fn. ccw Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true */ - DWORD COLORWRITEENABLE1; // = 190, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS - // */ - DWORD COLORWRITEENABLE2; // = 191, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS - // */ - DWORD COLORWRITEENABLE3; // = 192, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS - // */ - D3DCOLOR BLENDFACTOR; // = 193, /* D3DCOLOR used for a constant blend factor during alpha blending for devices that support - // D3DPBLENDCAPS_BLENDFACTOR */ - DWORD SRGBWRITEENABLE; // = 194, /* Enable rendertarget writes to be DE-linearized to SRGB (for formats that expose - // D3DUSAGE_QUERY_SRGBWRITE) */ - DWORD DEPTHBIAS; // = 195, + CCW_STENCILFUNC; // = 189, /* D3DCMPFUNC fn. ccw Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true */ + DWORD COLORWRITEENABLE1; // = 190, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS + // */ + DWORD COLORWRITEENABLE2; // = 191, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS + // */ + DWORD COLORWRITEENABLE3; // = 192, /* Additional ColorWriteEnables for the devices that support D3DPMISCCAPS_INDEPENDENTWRITEMASKS + // */ + D3DCOLOR BLENDFACTOR; // = 193, /* D3DCOLOR used for a constant blend factor during alpha blending for devices that support + // D3DPBLENDCAPS_BLENDFACTOR */ + DWORD SRGBWRITEENABLE; // = 194, /* Enable rendertarget writes to be DE-linearized to SRGB (for formats that expose + // D3DUSAGE_QUERY_SRGBWRITE) */ + DWORD DEPTHBIAS; // = 195, DPAD(196, 197); - DWORD WRAP8; // = 198, /* Additional wrap states for vs_3_0+ attributes with D3DDECLUSAGE_TEXCOORD */ - DWORD WRAP9; // = 199, - DWORD WRAP10; // = 200, - DWORD WRAP11; // = 201, - DWORD WRAP12; // = 202, - DWORD WRAP13; // = 203, - DWORD WRAP14; // = 204, - DWORD WRAP15; // = 205, - DWORD SEPARATEALPHABLENDENABLE; // = 206, /* TRUE to enable a separate blending function for the alpha channel */ + DWORD WRAP8; // = 198, /* Additional wrap states for vs_3_0+ attributes with D3DDECLUSAGE_TEXCOORD */ + DWORD WRAP9; // = 199, + DWORD WRAP10; // = 200, + DWORD WRAP11; // = 201, + DWORD WRAP12; // = 202, + DWORD WRAP13; // = 203, + DWORD WRAP14; // = 204, + DWORD WRAP15; // = 205, + DWORD SEPARATEALPHABLENDENABLE; // = 206, /* TRUE to enable a separate blending function for the alpha channel */ DWORD SRCBLENDALPHA; // = 207, /* SRC blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE; //is TRUE */ DWORD DESTBLENDALPHA; // = 208, /* DST blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE; //is TRUE */ DWORD BLENDOPALPHA; // = 209, /* Blending operation for the alpha channel when DWORD SEPARATEDESTALPHAENABLE; //is TRUE */ @@ -326,27 +326,27 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 struct { DPAD(0, 0); - D3DTEXTUREOP COLOROP; // = 1, /* D3DTEXTUREOP - per-stage blending controls for color channels */ - DWORD COLORARG1; // = 2, /* D3DTA_* (texture arg) */ - DWORD COLORARG2; // = 3, /* D3DTA_* (texture arg) */ - D3DTEXTUREOP ALPHAOP; // = 4, /* D3DTEXTUREOP - per-stage blending controls for alpha channel */ - DWORD ALPHAARG1; // = 5, /* D3DTA_* (texture arg) */ - DWORD ALPHAARG2; // = 6, /* D3DTA_* (texture arg) */ - DWORD BUMPENVMAT00; // = 7, /* float (bump mapping matrix) */ - DWORD BUMPENVMAT01; // = 8, /* float (bump mapping matrix) */ - DWORD BUMPENVMAT10; // = 9, /* float (bump mapping matrix) */ - DWORD BUMPENVMAT11; // = 10, /* float (bump mapping matrix) */ - DWORD TEXCOORDINDEX; // = 11, /* identifies which set of texture coordinates index this texture */ + D3DTEXTUREOP COLOROP; // = 1, /* D3DTEXTUREOP - per-stage blending controls for color channels */ + DWORD COLORARG1; // = 2, /* D3DTA_* (texture arg) */ + DWORD COLORARG2; // = 3, /* D3DTA_* (texture arg) */ + D3DTEXTUREOP ALPHAOP; // = 4, /* D3DTEXTUREOP - per-stage blending controls for alpha channel */ + DWORD ALPHAARG1; // = 5, /* D3DTA_* (texture arg) */ + DWORD ALPHAARG2; // = 6, /* D3DTA_* (texture arg) */ + DWORD BUMPENVMAT00; // = 7, /* float (bump mapping matrix) */ + DWORD BUMPENVMAT01; // = 8, /* float (bump mapping matrix) */ + DWORD BUMPENVMAT10; // = 9, /* float (bump mapping matrix) */ + DWORD BUMPENVMAT11; // = 10, /* float (bump mapping matrix) */ + DWORD TEXCOORDINDEX; // = 11, /* identifies which set of texture coordinates index this texture */ DPAD(12, 21); - DWORD BUMPENVLSCALE; // = 22, /* float scale for bump map luminance */ - DWORD BUMPENVLOFFSET; // = 23, /* float offset for bump map luminance */ - D3DTEXTURETRANSFORMFLAGS TEXTURETRANSFORMFLAGS; // = 24, /* D3DTEXTURETRANSFORMFLAGS controls texture transform */ + DWORD BUMPENVLSCALE; // = 22, /* float scale for bump map luminance */ + DWORD BUMPENVLOFFSET; // = 23, /* float offset for bump map luminance */ + D3DTEXTURETRANSFORMFLAGS TEXTURETRANSFORMFLAGS; // = 24, /* D3DTEXTURETRANSFORMFLAGS controls texture transform */ DPAD(25, 25); - DWORD COLORARG0; // = 26, /* D3DTA_* third arg for triadic ops */ - DWORD ALPHAARG0; // = 27, /* D3DTA_* third arg for triadic ops */ - DWORD RESULTARG; // = 28, /* D3DTA_* arg for result (CURRENT or TEMP) */ + DWORD COLORARG0; // = 26, /* D3DTA_* third arg for triadic ops */ + DWORD ALPHAARG0; // = 27, /* D3DTA_* third arg for triadic ops */ + DWORD RESULTARG; // = 28, /* D3DTA_* arg for result (CURRENT or TEMP) */ DPAD(29, 31); - DWORD CONSTANT; // = 32, /* Per-stage constant D3DTA_CONSTANT */ + DWORD CONSTANT; // = 32, /* Per-stage constant D3DTA_CONSTANT */ }; }; }; @@ -359,23 +359,23 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 struct { DPAD(0, 0); - D3DTEXTUREADDRESS ADDRESSU; // = 1, /* D3DTEXTUREADDRESS for U coordinate */ - D3DTEXTUREADDRESS ADDRESSV; // = 2, /* D3DTEXTUREADDRESS for V coordinate */ - D3DTEXTUREADDRESS ADDRESSW; // = 3, /* D3DTEXTUREADDRESS for W coordinate */ - D3DCOLOR BORDERCOLOR; // = 4, /* D3DCOLOR */ - D3DTEXTUREFILTERTYPE MAGFILTER; // = 5, /* D3DTEXTUREFILTER filter to use for magnification */ - D3DTEXTUREFILTERTYPE MINFILTER; // = 6, /* D3DTEXTUREFILTER filter to use for minification */ - D3DTEXTUREFILTERTYPE MIPFILTER; // = 7, /* D3DTEXTUREFILTER filter to use between mipmaps during minification */ - DWORD MIPMAPLODBIAS; // = 8, /* float Mipmap LOD bias */ - DWORD MAXMIPLEVEL; // = 9, /* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) */ - DWORD MAXANISOTROPY; // = 10, /* DWORD maximum anisotropy */ - DWORD SRGBTEXTURE; // = 11, /* Default = 0 (which means Gamma 1.0, - // no correction required.) else correct for - // Gamma = 2.2 */ - DWORD ELEMENTINDEX; // = 12, /* When multi-element texture is assigned to sampler, this - // indicates which element index to use. Default = 0. */ - DWORD DMAPOFFSET; // = 13, /* Offset in vertices in the pre-sampled displacement map. - // Only valid for D3DDMAPSAMPLER sampler */ + D3DTEXTUREADDRESS ADDRESSU; // = 1, /* D3DTEXTUREADDRESS for U coordinate */ + D3DTEXTUREADDRESS ADDRESSV; // = 2, /* D3DTEXTUREADDRESS for V coordinate */ + D3DTEXTUREADDRESS ADDRESSW; // = 3, /* D3DTEXTUREADDRESS for W coordinate */ + D3DCOLOR BORDERCOLOR; // = 4, /* D3DCOLOR */ + D3DTEXTUREFILTERTYPE MAGFILTER; // = 5, /* D3DTEXTUREFILTER filter to use for magnification */ + D3DTEXTUREFILTERTYPE MINFILTER; // = 6, /* D3DTEXTUREFILTER filter to use for minification */ + D3DTEXTUREFILTERTYPE MIPFILTER; // = 7, /* D3DTEXTUREFILTER filter to use between mipmaps during minification */ + DWORD MIPMAPLODBIAS; // = 8, /* float Mipmap LOD bias */ + DWORD MAXMIPLEVEL; // = 9, /* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) */ + DWORD MAXANISOTROPY; // = 10, /* DWORD maximum anisotropy */ + DWORD SRGBTEXTURE; // = 11, /* Default = 0 (which means Gamma 1.0, + // no correction required.) else correct for + // Gamma = 2.2 */ + DWORD ELEMENTINDEX; // = 12, /* When multi-element texture is assigned to sampler, this + // indicates which element index to use. Default = 0. */ + DWORD DMAPOFFSET; // = 13, /* Offset in vertices in the pre-sampled displacement map. + // Only valid for D3DDMAPSAMPLER sampler */ }; }; }; @@ -387,9 +387,9 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 struct { D3DMATRIX DUMMY; - D3DMATRIX VIEWPROJ[2]; // D3D indices: 2 - 3 - D3DMATRIX TEXTUREn[8]; // D3D indices: 16 - 23 - D3DMATRIX WORLDn[4]; // D3D indices: 256 - 259 + D3DMATRIX VIEWPROJ[2]; // D3D indices: 2 - 3 + D3DMATRIX TEXTUREn[8]; // D3D indices: 16 - 23 + D3DMATRIX WORLDn[4]; // D3D indices: 256 - 259 D3DMATRIX& operator()(uint uiIndex) { // Map requested index to physical data @@ -413,22 +413,22 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 { D3DMATRIX DUMMY; // MPAD(0,1); - D3DMATRIX VIEW; // = 2, - D3DMATRIX PROJECTION; // = 3, + D3DMATRIX VIEW; // = 2, + D3DMATRIX PROJECTION; // = 3, // MPAD(4,15); - D3DMATRIX TEXTURE0; // = 16, - D3DMATRIX TEXTURE1; // = 17, - D3DMATRIX TEXTURE2; // = 18, - D3DMATRIX TEXTURE3; // = 19, - D3DMATRIX TEXTURE4; // = 20, - D3DMATRIX TEXTURE5; // = 21, - D3DMATRIX TEXTURE6; // = 22, - D3DMATRIX TEXTURE7; // = 23, + D3DMATRIX TEXTURE0; // = 16, + D3DMATRIX TEXTURE1; // = 17, + D3DMATRIX TEXTURE2; // = 18, + D3DMATRIX TEXTURE3; // = 19, + D3DMATRIX TEXTURE4; // = 20, + D3DMATRIX TEXTURE5; // = 21, + D3DMATRIX TEXTURE6; // = 22, + D3DMATRIX TEXTURE7; // = 23, // MPAD(24,255); - D3DMATRIX WORLD; // = 256, - D3DMATRIX WORLD1; // = 257, - D3DMATRIX WORLD2; // = 258, - D3DMATRIX WORLD3; // = 259, + D3DMATRIX WORLD; // = 256, + D3DMATRIX WORLD1; // = 257, + D3DMATRIX WORLD2; // = 258, + D3DMATRIX WORLD3; // = 259, }; }; }; @@ -562,7 +562,7 @@ interface CProxyDirect3DDevice9 : public IDirect3DDevice9 }; extern CProxyDirect3DDevice9::SD3DDeviceState* g_pDeviceState; -extern CProxyDirect3DDevice9::SMemoryState g_StaticMemoryState; +extern CProxyDirect3DDevice9::SMemoryState g_StaticMemoryState; // GTA scene tracking helpers void ResetGTASceneState(); @@ -591,7 +591,7 @@ class CScopedActiveProxyDevice CProxyDirect3DDevice9* operator->() const { return m_pProxy; } CProxyDirect3DDevice9* Get() const { return m_pProxy; } - explicit operator bool() const { return m_pProxy != nullptr; } + explicit operator bool() const { return m_pProxy != nullptr; } private: CProxyDirect3DDevice9* m_pProxy; @@ -600,14 +600,12 @@ class CScopedActiveProxyDevice // Add gamma state management struct SGammaState { - bool bOriginalGammaStored; - bool bLastWasBorderless; - D3DGAMMARAMP originalGammaRamp; - UINT lastSwapChain; - - SGammaState() : bOriginalGammaStored(false), bLastWasBorderless(false), originalGammaRamp{}, lastSwapChain(0) - { - } + bool bOriginalGammaStored; + bool bLastWasBorderless; + D3DGAMMARAMP originalGammaRamp; + UINT lastSwapChain; + + SGammaState() : bOriginalGammaStored(false), bLastWasBorderless(false), originalGammaRamp{}, lastSwapChain(0) {} }; extern SGammaState g_GammaState; diff --git a/Client/core/DXHook/CProxyDirect3DEffect.cpp b/Client/core/DXHook/CProxyDirect3DEffect.cpp index e2d2a7b9094..8d44955abe5 100644 --- a/Client/core/DXHook/CProxyDirect3DEffect.cpp +++ b/Client/core/DXHook/CProxyDirect3DEffect.cpp @@ -77,7 +77,7 @@ ULONG CProxyDirect3DEffect::Release() if (count == 0) { // now, the Original Object has deleted itself, so do we here - delete this; // destructor will be called automatically + delete this; // destructor will be called automatically } return count; diff --git a/Client/core/DXHook/CProxyDirect3DEffect.h b/Client/core/DXHook/CProxyDirect3DEffect.h index 31474780a2e..03b709ed1cc 100644 --- a/Client/core/DXHook/CProxyDirect3DEffect.h +++ b/Client/core/DXHook/CProxyDirect3DEffect.h @@ -15,8 +15,8 @@ class CProxyDirect3DEffect : public ID3DXEffect public: // ID3DXBaseEffect HRESULT __stdcall QueryInterface(REFIID iid, LPVOID* ppv); - ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } - ULONG __stdcall Release(); + ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } + ULONG __stdcall Release(); // Descs HRESULT __stdcall GetDesc(D3DXEFFECT_DESC* pDesc) { return m_pOriginal->GetDesc(pDesc); } @@ -113,10 +113,10 @@ class CProxyDirect3DEffect : public ID3DXEffect HRESULT __stdcall GetPool(LPD3DXEFFECTPOOL* ppPool) { return m_pOriginal->GetPool(ppPool); } // Selecting and setting a technique - HRESULT __stdcall SetTechnique(D3DXHANDLE hTechnique) { return m_pOriginal->SetTechnique(hTechnique); } + HRESULT __stdcall SetTechnique(D3DXHANDLE hTechnique) { return m_pOriginal->SetTechnique(hTechnique); } D3DXHANDLE __stdcall GetCurrentTechnique() { return m_pOriginal->GetCurrentTechnique(); } - HRESULT __stdcall ValidateTechnique(D3DXHANDLE hTechnique) { return m_pOriginal->ValidateTechnique(hTechnique); } - HRESULT __stdcall FindNextValidTechnique(D3DXHANDLE hTechnique, D3DXHANDLE* pTechnique) + HRESULT __stdcall ValidateTechnique(D3DXHANDLE hTechnique) { return m_pOriginal->ValidateTechnique(hTechnique); } + HRESULT __stdcall FindNextValidTechnique(D3DXHANDLE hTechnique, D3DXHANDLE* pTechnique) { return m_pOriginal->FindNextValidTechnique(hTechnique, pTechnique); } @@ -145,10 +145,10 @@ class CProxyDirect3DEffect : public ID3DXEffect HRESULT __stdcall GetStateManager(LPD3DXEFFECTSTATEMANAGER* ppManager) { return m_pOriginal->GetStateManager(ppManager); } // Parameter blocks - HRESULT __stdcall BeginParameterBlock() { return m_pOriginal->BeginParameterBlock(); } + HRESULT __stdcall BeginParameterBlock() { return m_pOriginal->BeginParameterBlock(); } D3DXHANDLE __stdcall EndParameterBlock() { return m_pOriginal->EndParameterBlock(); } - HRESULT __stdcall ApplyParameterBlock(D3DXHANDLE hParameterBlock) { return m_pOriginal->ApplyParameterBlock(hParameterBlock); } - HRESULT __stdcall DeleteParameterBlock(D3DXHANDLE hParameterBlock) { return m_pOriginal->DeleteParameterBlock(hParameterBlock); } + HRESULT __stdcall ApplyParameterBlock(D3DXHANDLE hParameterBlock) { return m_pOriginal->ApplyParameterBlock(hParameterBlock); } + HRESULT __stdcall DeleteParameterBlock(D3DXHANDLE hParameterBlock) { return m_pOriginal->DeleteParameterBlock(hParameterBlock); } // Cloning HRESULT __stdcall CloneEffect(LPDIRECT3DDEVICE9 pDevice, LPD3DXEFFECT* ppEffect); diff --git a/Client/core/DXHook/CProxyDirect3DIndexBuffer.cpp b/Client/core/DXHook/CProxyDirect3DIndexBuffer.cpp index 76a9112b2e5..34a55bcbe88 100644 --- a/Client/core/DXHook/CProxyDirect3DIndexBuffer.cpp +++ b/Client/core/DXHook/CProxyDirect3DIndexBuffer.cpp @@ -90,7 +90,7 @@ ULONG CProxyDirect3DIndexBuffer::Release() if (count == 0) { // now, the Original Object has deleted itself, so do we here - delete this; // destructor will be called automatically + delete this; // destructor will be called automatically } return count; diff --git a/Client/core/DXHook/CProxyDirect3DIndexBuffer.h b/Client/core/DXHook/CProxyDirect3DIndexBuffer.h index ab1a89efd73..4da4b16d289 100644 --- a/Client/core/DXHook/CProxyDirect3DIndexBuffer.h +++ b/Client/core/DXHook/CProxyDirect3DIndexBuffer.h @@ -16,8 +16,8 @@ class CProxyDirect3DIndexBuffer : public IDirect3DIndexBuffer9 public: /*** IUnknown methods ***/ HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } - ULONG __stdcall Release(); + ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } + ULONG __stdcall Release(); /*** IDirect3DResource9 methods ***/ HRESULT __stdcall GetDevice(IDirect3DDevice9** ppDevice) { return m_pOriginal->GetDevice(ppDevice); } @@ -27,9 +27,9 @@ class CProxyDirect3DIndexBuffer : public IDirect3DIndexBuffer9 } HRESULT __stdcall GetPrivateData(REFGUID refguid, void* pData, DWORD* pSizeOfData) { return m_pOriginal->GetPrivateData(refguid, pData, pSizeOfData); } HRESULT __stdcall FreePrivateData(REFGUID refguid) { return m_pOriginal->FreePrivateData(refguid); } - DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } - DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } - void __stdcall PreLoad() { return m_pOriginal->PreLoad(); } + DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } + DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } + void __stdcall PreLoad() { return m_pOriginal->PreLoad(); } D3DRESOURCETYPE __stdcall GetType() { return m_pOriginal->GetType(); } /*** IDirect3DIndexBuffer9 methods ***/ diff --git a/Client/core/DXHook/CProxyDirect3DTexture.cpp b/Client/core/DXHook/CProxyDirect3DTexture.cpp index 1c7429c20e5..1f767c9f9cf 100644 --- a/Client/core/DXHook/CProxyDirect3DTexture.cpp +++ b/Client/core/DXHook/CProxyDirect3DTexture.cpp @@ -88,7 +88,7 @@ ULONG CProxyDirect3DTexture::Release() if (count == 0) { // now, the Original Object has deleted itself, so do we here - delete this; // destructor will be called automatically + delete this; // destructor will be called automatically } return count; diff --git a/Client/core/DXHook/CProxyDirect3DTexture.h b/Client/core/DXHook/CProxyDirect3DTexture.h index fc8952b916d..1500e0e6ced 100644 --- a/Client/core/DXHook/CProxyDirect3DTexture.h +++ b/Client/core/DXHook/CProxyDirect3DTexture.h @@ -16,8 +16,8 @@ class CProxyDirect3DTexture : public IDirect3DTexture9 public: /*** IUnknown methods ***/ HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } - ULONG __stdcall Release(); + ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } + ULONG __stdcall Release(); /*** IDirect3DResource9 methods ***/ HRESULT __stdcall GetDevice(IDirect3DDevice9** ppDevice) { return m_pOriginal->GetDevice(ppDevice); } @@ -27,18 +27,18 @@ class CProxyDirect3DTexture : public IDirect3DTexture9 } HRESULT __stdcall GetPrivateData(REFGUID refguid, void* pData, DWORD* pSizeOfData) { return m_pOriginal->GetPrivateData(refguid, pData, pSizeOfData); } HRESULT __stdcall FreePrivateData(REFGUID refguid) { return m_pOriginal->FreePrivateData(refguid); } - DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } - DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } - void __stdcall PreLoad() { return m_pOriginal->PreLoad(); } + DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } + DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } + void __stdcall PreLoad() { return m_pOriginal->PreLoad(); } D3DRESOURCETYPE __stdcall GetType() { return m_pOriginal->GetType(); } /*** IDirect3DBaseTexture9 methods ***/ - DWORD __stdcall SetLOD(DWORD LODNew) { return m_pOriginal->SetLOD(LODNew); } - DWORD __stdcall GetLOD() { return m_pOriginal->GetLOD(); } - DWORD __stdcall GetLevelCount() { return m_pOriginal->GetLevelCount(); } + DWORD __stdcall SetLOD(DWORD LODNew) { return m_pOriginal->SetLOD(LODNew); } + DWORD __stdcall GetLOD() { return m_pOriginal->GetLOD(); } + DWORD __stdcall GetLevelCount() { return m_pOriginal->GetLevelCount(); } HRESULT __stdcall SetAutoGenFilterType(D3DTEXTUREFILTERTYPE FilterType) { return m_pOriginal->SetAutoGenFilterType(FilterType); } D3DTEXTUREFILTERTYPE - __stdcall GetAutoGenFilterType() { return m_pOriginal->GetAutoGenFilterType(); } + __stdcall GetAutoGenFilterType() { return m_pOriginal->GetAutoGenFilterType(); } void __stdcall GenerateMipSubLevels() { return m_pOriginal->GenerateMipSubLevels(); } /*** IDirect3DTexture9 methods ***/ diff --git a/Client/core/DXHook/CProxyDirect3DVertexBuffer.cpp b/Client/core/DXHook/CProxyDirect3DVertexBuffer.cpp index f67e9f7d3ff..f1d44107de4 100644 --- a/Client/core/DXHook/CProxyDirect3DVertexBuffer.cpp +++ b/Client/core/DXHook/CProxyDirect3DVertexBuffer.cpp @@ -126,14 +126,13 @@ HRESULT CProxyDirect3DVertexBuffer::Lock(UINT OffsetToLock, UINT SizeToLock, voi SharedUtil::CAutoCSLock fallbackGuard(m_fallbackCS); - if (m_bFallbackActive) { if (ppbData) *ppbData = nullptr; SString strMessage("Lock VertexBuffer: fallback still pending - refusing new lock (Offset:%x Size:%x Flags:%08x)", m_fallbackOffset, m_fallbackSize, - m_fallbackFlags); + m_fallbackFlags); WriteDebugEvent(strMessage); AddReportLog(8624, strMessage); CCore::GetSingleton().LogEvent(624, "Lock VertexBuffer", "", strMessage); @@ -159,8 +158,8 @@ HRESULT CProxyDirect3DVertexBuffer::Lock(UINT OffsetToLock, UINT SizeToLock, voi if (bPointerNullEvent) { - WriteDebugEvent(SString("Lock VertexBuffer: initial pointer null (Usage:%08x Flags:%08x Offset:%x Size:%x)", m_dwUsage, Flags, OffsetToLock, - SizeToLock)); + WriteDebugEvent( + SString("Lock VertexBuffer: initial pointer null (Usage:%08x Flags:%08x Offset:%x Size:%x)", m_dwUsage, Flags, OffsetToLock, SizeToLock)); // Retry once for dynamic buffers using DISCARD if ((m_dwUsage & D3DUSAGE_DYNAMIC) && (Flags & D3DLOCK_READONLY) == 0) @@ -230,8 +229,8 @@ HRESULT CProxyDirect3DVertexBuffer::Lock(UINT OffsetToLock, UINT SizeToLock, voi hr = D3D_OK; - WriteDebugEvent(SString("Lock VertexBuffer: engaged fallback buffer (Offset:%x Size:%x Flags:%08x)", m_fallbackOffset, m_fallbackSize, - m_fallbackFlags)); + WriteDebugEvent( + SString("Lock VertexBuffer: engaged fallback buffer (Offset:%x Size:%x Flags:%08x)", m_fallbackOffset, m_fallbackSize, m_fallbackFlags)); } } @@ -257,9 +256,9 @@ HRESULT CProxyDirect3DVertexBuffer::Lock(UINT OffsetToLock, UINT SizeToLock, voi SString strMessage( "Lock VertexBuffer [%s] hr:%x origHr:%x returnHr:%x pointerNull:%u retryAttempted:%u retrySucceeded:%u fallback:%u fallbackSize:%x fallbackFlags:%x" " unlockedAfterNull:%u Length:%x Usage:%x FVF:%x Pool:%x OffsetToLock:%x SizeToLock:%x Flags:%x retryFlags:%x", - info.szText, reportHr, originalHr, hr, static_cast(bPointerNullEvent), static_cast(bRetryAttempted), - static_cast(bRetrySucceeded), static_cast(bFallbackUsed), m_fallbackSize, m_fallbackFlags, static_cast(bUnlockedAfterNull), - m_iMemUsed, m_dwUsage, m_dwFVF, m_pool, OffsetToLock, SizeToLock, Flags, retryFlags); + info.szText, reportHr, originalHr, hr, static_cast(bPointerNullEvent), static_cast(bRetryAttempted), static_cast(bRetrySucceeded), + static_cast(bFallbackUsed), m_fallbackSize, m_fallbackFlags, static_cast(bUnlockedAfterNull), m_iMemUsed, m_dwUsage, m_dwFVF, m_pool, + OffsetToLock, SizeToLock, Flags, retryFlags); WriteDebugEvent(strMessage); AddReportLog(info.uiReportId, strMessage); CCore::GetSingleton().LogEvent(info.uiLogEventId, "Lock VertexBuffer", "", strMessage); @@ -322,8 +321,8 @@ HRESULT CProxyDirect3DVertexBuffer::Unlock() if (SUCCEEDED(lockHr)) m_pOriginal->Unlock(); - WriteDebugEvent(SString("Unlock VertexBuffer: failed to copy fallback data (lockHr:%x offset:%x size:%x flags:%08x)", lockHr, offset, size, - writeFlags)); + WriteDebugEvent( + SString("Unlock VertexBuffer: failed to copy fallback data (lockHr:%x offset:%x size:%x flags:%08x)", lockHr, offset, size, writeFlags)); copyResult = FAILED(lockHr) ? lockHr : D3DERR_INVALIDCALL; bShouldRetryLater = true; } @@ -339,7 +338,7 @@ HRESULT CProxyDirect3DVertexBuffer::Unlock() } WriteDebugEvent(SString("Unlock VertexBuffer: fallback completed (offset:%x size:%x flags:%08x retryLater:%u result:%x)", m_fallbackOffset, m_fallbackSize, - m_fallbackFlags, static_cast(bShouldRetryLater), copyResult)); + m_fallbackFlags, static_cast(bShouldRetryLater), copyResult)); m_bFallbackActive = bShouldRetryLater ? m_bFallbackActive : false; if (!m_bFallbackActive) diff --git a/Client/core/DXHook/CProxyDirect3DVertexBuffer.h b/Client/core/DXHook/CProxyDirect3DVertexBuffer.h index 91ea01b2ea7..e7e118e9b73 100644 --- a/Client/core/DXHook/CProxyDirect3DVertexBuffer.h +++ b/Client/core/DXHook/CProxyDirect3DVertexBuffer.h @@ -24,8 +24,8 @@ class CProxyDirect3DVertexBuffer : public IDirect3DVertexBuffer9 public: /*** IUnknown methods ***/ HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } - ULONG __stdcall Release(); + ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } + ULONG __stdcall Release(); /*** IDirect3DResource9 methods ***/ HRESULT __stdcall GetDevice(IDirect3DDevice9** ppDevice) { return m_pOriginal->GetDevice(ppDevice); } @@ -35,9 +35,9 @@ class CProxyDirect3DVertexBuffer : public IDirect3DVertexBuffer9 } HRESULT __stdcall GetPrivateData(REFGUID refguid, void* pData, DWORD* pSizeOfData) { return m_pOriginal->GetPrivateData(refguid, pData, pSizeOfData); } HRESULT __stdcall FreePrivateData(REFGUID refguid) { return m_pOriginal->FreePrivateData(refguid); } - DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } - DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } - void __stdcall PreLoad() { m_pOriginal->PreLoad(); } + DWORD __stdcall SetPriority(DWORD PriorityNew) { return m_pOriginal->SetPriority(PriorityNew); } + DWORD __stdcall GetPriority() { return m_pOriginal->GetPriority(); } + void __stdcall PreLoad() { m_pOriginal->PreLoad(); } D3DRESOURCETYPE __stdcall GetType() { return m_pOriginal->GetType(); } /*** IDirect3DVertexBuffer9 methods ***/ @@ -60,10 +60,10 @@ class CProxyDirect3DVertexBuffer : public IDirect3DVertexBuffer9 D3DPOOL m_pool; CProxyDirect3DDevice9::SResourceMemory* m_pStats; - bool m_bFallbackActive; - UINT m_fallbackOffset; - UINT m_fallbackSize; - DWORD m_fallbackFlags; - std::vector m_fallbackStorage; + bool m_bFallbackActive; + UINT m_fallbackOffset; + UINT m_fallbackSize; + DWORD m_fallbackFlags; + std::vector m_fallbackStorage; SharedUtil::CCriticalSection m_fallbackCS; }; diff --git a/Client/core/DXHook/CProxyDirect3DVertexDeclaration.cpp b/Client/core/DXHook/CProxyDirect3DVertexDeclaration.cpp index 73b60626e7f..edc719f7807 100644 --- a/Client/core/DXHook/CProxyDirect3DVertexDeclaration.cpp +++ b/Client/core/DXHook/CProxyDirect3DVertexDeclaration.cpp @@ -135,7 +135,7 @@ ULONG CProxyDirect3DVertexDeclaration::Release() if (count == 0) { // now, the Original Object has deleted itself, so do we here - delete this; // destructor will be called automatically + delete this; // destructor will be called automatically } return count; diff --git a/Client/core/DXHook/CProxyDirect3DVertexDeclaration.h b/Client/core/DXHook/CProxyDirect3DVertexDeclaration.h index 70c3c2830b1..6ba2613ba84 100644 --- a/Client/core/DXHook/CProxyDirect3DVertexDeclaration.h +++ b/Client/core/DXHook/CProxyDirect3DVertexDeclaration.h @@ -16,8 +16,8 @@ class CProxyDirect3DVertexDeclaration : public IDirect3DVertexDeclaration9 public: /*** IUnknown methods ***/ HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObj); - ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } - ULONG __stdcall Release(); + ULONG __stdcall AddRef() { return m_pOriginal->AddRef(); } + ULONG __stdcall Release(); /*** IDirect3DVertexDeclaration9 methods ***/ HRESULT __stdcall GetDevice(IDirect3DDevice9** ppDevice) { return m_pOriginal->GetDevice(ppDevice); } diff --git a/Client/core/DXHook/CProxyDirectInput8.cpp b/Client/core/DXHook/CProxyDirectInput8.cpp index 32b2eee9da7..cd4309c55b5 100644 --- a/Client/core/DXHook/CProxyDirectInput8.cpp +++ b/Client/core/DXHook/CProxyDirectInput8.cpp @@ -98,4 +98,4 @@ HRESULT CProxyDirectInput8::EnumDevicesBySemantics(LPCSTR a, LPDIACTIONFORMATA b HRESULT CProxyDirectInput8::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSA b, DWORD c, LPVOID d) { return m_pDevice->ConfigureDevices(a, b, c, d); -} \ No newline at end of file +} diff --git a/Client/core/DXHook/CProxyDirectInput8.h b/Client/core/DXHook/CProxyDirectInput8.h index ea1fe3b0c78..a5323f9abdc 100644 --- a/Client/core/DXHook/CProxyDirectInput8.h +++ b/Client/core/DXHook/CProxyDirectInput8.h @@ -23,8 +23,8 @@ class CProxyDirectInput8 : public IDirectInput8A ~CProxyDirectInput8(); /*** IUnknown methods ***/ virtual HRESULT __stdcall QueryInterface(REFIID riid, LPVOID* ppvObj); - virtual ULONG __stdcall AddRef(); - virtual ULONG __stdcall Release(); + virtual ULONG __stdcall AddRef(); + virtual ULONG __stdcall Release(); /*** IDirectInput8A methods ***/ virtual HRESULT __stdcall CreateDevice(REFGUID, LPDIRECTINPUTDEVICE8A*, LPUNKNOWN); diff --git a/Client/core/DXHook/CProxyDirectInputDevice8.h b/Client/core/DXHook/CProxyDirectInputDevice8.h index fd08f476165..a9795cad402 100644 --- a/Client/core/DXHook/CProxyDirectInputDevice8.h +++ b/Client/core/DXHook/CProxyDirectInputDevice8.h @@ -21,8 +21,8 @@ class CProxyDirectInputDevice8 : public IDirectInputDevice8A ~CProxyDirectInputDevice8(); /*** IUnknown methods ***/ virtual HRESULT __stdcall QueryInterface(REFIID riid, LPVOID* ppvObj); - virtual ULONG __stdcall AddRef(); - virtual ULONG __stdcall Release(); + virtual ULONG __stdcall AddRef(); + virtual ULONG __stdcall Release(); /*** IDirectInputDevice8A methods ***/ virtual HRESULT __stdcall GetCapabilities(LPDIDEVCAPS a); diff --git a/Client/core/DXHook/ComPtrValidation.h b/Client/core/DXHook/ComPtrValidation.h index 2b184f455fe..a7f37d51af1 100644 --- a/Client/core/DXHook/ComPtrValidation.h +++ b/Client/core/DXHook/ComPtrValidation.h @@ -11,159 +11,159 @@ namespace ComPtrValidation { -constexpr uint64_t kValidationThrottleMs = 200; -constexpr size_t kValidationCacheReserve = 256; + constexpr uint64_t kValidationThrottleMs = 200; + constexpr size_t kValidationCacheReserve = 256; -inline uint64_t GetMonotonicMilliseconds() -{ - using namespace std::chrono; - return static_cast(duration_cast(steady_clock::now().time_since_epoch()).count()); -} - -struct CacheEntry -{ - uint64_t lastCheckMs{0}; - bool valid{false}; -}; - -struct CacheStorage -{ - CacheStorage() + inline uint64_t GetMonotonicMilliseconds() { - cache.reserve(kValidationCacheReserve); - cache.max_load_factor(0.5f); + using namespace std::chrono; + return static_cast(duration_cast(steady_clock::now().time_since_epoch()).count()); } - std::unordered_map cache; -}; + struct CacheEntry + { + uint64_t lastCheckMs{0}; + bool valid{false}; + }; -inline std::atomic& InvalidationEpoch() -{ - static std::atomic s_epoch{0}; - return s_epoch; -} + struct CacheStorage + { + CacheStorage() + { + cache.reserve(kValidationCacheReserve); + cache.max_load_factor(0.5f); + } -inline std::shared_mutex& CacheMutex() -{ - static std::shared_mutex s_mutex; - return s_mutex; -} + std::unordered_map cache; + }; -inline std::unordered_map& Cache() -{ - static CacheStorage s_storage; - return s_storage.cache; -} + inline std::atomic& InvalidationEpoch() + { + static std::atomic s_epoch{0}; + return s_epoch; + } -inline void Invalidate(const void* pointer) -{ - if (!pointer) - return; + inline std::shared_mutex& CacheMutex() + { + static std::shared_mutex s_mutex; + return s_mutex; + } + inline std::unordered_map& Cache() { - std::unique_lock lock(CacheMutex()); - Cache().erase(pointer); + static CacheStorage s_storage; + return s_storage.cache; } - InvalidationEpoch().fetch_add(1, std::memory_order_acq_rel); -} -enum class ValidationMode -{ - Default, - ForceRefresh, -}; + inline void Invalidate(const void* pointer) + { + if (!pointer) + return; -template -bool ValidateSlow(T* pointer) -{ - if (!SharedUtil::IsReadablePointer(pointer, sizeof(void*))) - return false; + { + std::unique_lock lock(CacheMutex()); + Cache().erase(pointer); + } + InvalidationEpoch().fetch_add(1, std::memory_order_acq_rel); + } - void* const* vtablePtr = reinterpret_cast(pointer); - if (!vtablePtr) - return false; + enum class ValidationMode + { + Default, + ForceRefresh, + }; - void* const vtable = *vtablePtr; - if (!vtable) - return false; + template + bool ValidateSlow(T* pointer) + { + if (!SharedUtil::IsReadablePointer(pointer, sizeof(void*))) + return false; - constexpr size_t requiredBytes = sizeof(void*) * 3; - return SharedUtil::IsReadablePointer(vtable, requiredBytes); -} + void* const* vtablePtr = reinterpret_cast(pointer); + if (!vtablePtr) + return false; -struct ThreadCache -{ - const void* pointer{nullptr}; - CacheEntry entry{}; - uint64_t epoch{std::numeric_limits::max()}; -}; + void* const vtable = *vtablePtr; + if (!vtable) + return false; -template -bool Validate(T* pointer, ValidationMode mode = ValidationMode::Default) -{ - if (!pointer) - return true; + constexpr size_t requiredBytes = sizeof(void*) * 3; + return SharedUtil::IsReadablePointer(vtable, requiredBytes); + } - thread_local ThreadCache s_threadCache; + struct ThreadCache + { + const void* pointer{nullptr}; + CacheEntry entry{}; + uint64_t epoch{std::numeric_limits::max()}; + }; - for (;;) + template + bool Validate(T* pointer, ValidationMode mode = ValidationMode::Default) { - const uint64_t epoch = InvalidationEpoch().load(std::memory_order_acquire); - const uint64_t now = GetMonotonicMilliseconds(); + if (!pointer) + return true; - if (mode == ValidationMode::Default && s_threadCache.pointer == pointer && s_threadCache.epoch == epoch) - { - const uint64_t last = s_threadCache.entry.lastCheckMs; - const uint64_t elapsed = (now >= last) ? now - last : 0; - if (elapsed < kValidationThrottleMs) - { - if (InvalidationEpoch().load(std::memory_order_acquire) == epoch) - return s_threadCache.entry.valid; - continue; - } - } + thread_local ThreadCache s_threadCache; - if (mode == ValidationMode::Default) + for (;;) { - std::shared_lock lock(CacheMutex()); - auto& cache = Cache(); - const auto iter = cache.find(pointer); - if (iter != cache.end()) + const uint64_t epoch = InvalidationEpoch().load(std::memory_order_acquire); + const uint64_t now = GetMonotonicMilliseconds(); + + if (mode == ValidationMode::Default && s_threadCache.pointer == pointer && s_threadCache.epoch == epoch) { - const uint64_t last = iter->second.lastCheckMs; + const uint64_t last = s_threadCache.entry.lastCheckMs; const uint64_t elapsed = (now >= last) ? now - last : 0; if (elapsed < kValidationThrottleMs) { if (InvalidationEpoch().load(std::memory_order_acquire) == epoch) + return s_threadCache.entry.valid; + continue; + } + } + + if (mode == ValidationMode::Default) + { + std::shared_lock lock(CacheMutex()); + auto& cache = Cache(); + const auto iter = cache.find(pointer); + if (iter != cache.end()) + { + const uint64_t last = iter->second.lastCheckMs; + const uint64_t elapsed = (now >= last) ? now - last : 0; + if (elapsed < kValidationThrottleMs) { - s_threadCache.pointer = pointer; - s_threadCache.entry = iter->second; - s_threadCache.epoch = epoch; - return iter->second.valid; + if (InvalidationEpoch().load(std::memory_order_acquire) == epoch) + { + s_threadCache.pointer = pointer; + s_threadCache.entry = iter->second; + s_threadCache.epoch = epoch; + return iter->second.valid; + } + continue; } - continue; } } - } - const bool valid = ValidateSlow(pointer); - const CacheEntry newEntry{now, valid}; - { - std::unique_lock lock(CacheMutex()); - Cache()[pointer] = newEntry; - } + const bool valid = ValidateSlow(pointer); + const CacheEntry newEntry{now, valid}; + { + std::unique_lock lock(CacheMutex()); + Cache()[pointer] = newEntry; + } - if (InvalidationEpoch().load(std::memory_order_acquire) != epoch) - continue; + if (InvalidationEpoch().load(std::memory_order_acquire) != epoch) + continue; - s_threadCache.pointer = pointer; - s_threadCache.entry = newEntry; - s_threadCache.epoch = epoch; - return valid; + s_threadCache.pointer = pointer; + s_threadCache.entry = newEntry; + s_threadCache.epoch = epoch; + return valid; + } } -} -} // namespace ComPtrValidation +} template bool IsValidComInterfacePointer(T* pointer, ComPtrValidation::ValidationMode mode = ComPtrValidation::ValidationMode::Default) diff --git a/Client/core/FPSLimiter.cpp b/Client/core/FPSLimiter.cpp index 0d3817d93b4..8dddc05b7c5 100644 --- a/Client/core/FPSLimiter.cpp +++ b/Client/core/FPSLimiter.cpp @@ -16,7 +16,7 @@ namespace FPSLimiter { - constexpr std::uint16_t DEFAULT_FPS_VSYNC = 60; // Default user-defined FPS limit + constexpr std::uint16_t DEFAULT_FPS_VSYNC = 60; // Default user-defined FPS limit FPSLimiter::FPSLimiter() @@ -130,7 +130,7 @@ namespace FPSLimiter return validFps; } } - return DEFAULT_FPS_VSYNC; // Shouldn't happen, sane default + return DEFAULT_FPS_VSYNC; // Shouldn't happen, sane default } void FPSLimiter::CalculateCurrentFPSLimit() @@ -169,12 +169,12 @@ namespace FPSLimiter std::stringstream ss; ss << "FPSLimiter: FPS limit changed to " << (m_fpsTarget == 0 ? "unlimited" : std::to_string(m_fpsTarget)); ss << " (Enforced by: " << EnumToString(GetEnforcer()) << ")"; - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG ss << " [Server: " << (m_serverEnforcedFps == 0 ? "unlimited" : std::to_string(m_serverEnforcedFps)); ss << ", Client: " << (m_clientEnforcedFps == 0 ? "unlimited" : std::to_string(m_clientEnforcedFps)); ss << ", User: " << (m_userDefinedFps == 0 ? "unlimited" : std::to_string(m_userDefinedFps)); ss << ", VSync: " << (m_displayRefreshRate == 0 ? "unlimited" : std::to_string(m_displayRefreshRate)) << "]"; - #endif +#endif auto* pConsole = CCore::GetSingleton().GetConsole(); if (pConsole) CCore::GetSingleton().GetConsole()->Print(ss.str().c_str()); @@ -207,7 +207,7 @@ namespace FPSLimiter LARGE_INTEGER start, end; std::uint64_t tscStart = __rdtsc(); QueryPerformanceCounter(&start); - Sleep(10); // Short calibration period + Sleep(10); // Short calibration period QueryPerformanceCounter(&end); std::uint64_t tscEnd = __rdtsc(); @@ -229,7 +229,7 @@ namespace FPSLimiter { std::uint64_t lastMeasuredTSC = __rdtsc(); std::uint64_t remaining = targetTSC - lastMeasuredTSC; - if (remaining > 10000) // > ~3us at 3GHz + if (remaining > 10000) // > ~3us at 3GHz { // Long wait: check every ~1000 cycles do @@ -237,7 +237,7 @@ namespace FPSLimiter for (int i = 0; i < 250; ++i) _mm_pause(); lastMeasuredTSC = __rdtsc(); - } while (lastMeasuredTSC + 5000 < targetTSC); // Stop 5000 cycles early + } while (lastMeasuredTSC + 5000 < targetTSC); // Stop 5000 cycles early } // Final precision loop @@ -264,7 +264,7 @@ namespace FPSLimiter if (SharedUtil::TryGetProcAddress(ntdll, "NtSetTimerResolution", setRes)) { ULONG actualRes; - setRes(10000, TRUE, &actualRes); // 1ms in 100ns units + setRes(10000, TRUE, &actualRes); // 1ms in 100ns units resolutionSet = true; } } @@ -294,7 +294,7 @@ namespace FPSLimiter if (m_hTimer) { - double timerWaitMs = waitTimeMs - 1.0; // Leave margin for spin + double timerWaitMs = waitTimeMs - 1.0; // Leave margin for spin if (timerWaitMs > 0.5) { LARGE_INTEGER dueTime; @@ -364,4 +364,4 @@ namespace FPSLimiter ADD_ENUM(EnforcerType::Server, "server") IMPLEMENT_ENUM_END("EnforcerType"); -}; // namespace FPSLimiter +}; // namespace FPSLimiter diff --git a/Client/core/FPSLimiter.h b/Client/core/FPSLimiter.h index 032dc193e55..58f39f6406b 100644 --- a/Client/core/FPSLimiter.h +++ b/Client/core/FPSLimiter.h @@ -40,9 +40,9 @@ namespace FPSLimiter void SetUserDefinedFPS(std::uint16_t fps) override; void SetDisplayVSync(bool enabled) override; - void OnFPSLimitChange() override; // Event handler called when the active frame rate limit changes - void OnFrameStart() override; // Event handler called at the start of each frame - void OnFrameEnd() override; // Event handler called at the end of each frame + void OnFPSLimitChange() override; // Event handler called when the active frame rate limit changes + void OnFrameStart() override; // Event handler called at the start of each frame + void OnFrameEnd() override; // Event handler called at the end of each frame private: // Internal @@ -57,11 +57,11 @@ namespace FPSLimiter LARGE_INTEGER m_lastFrameTime; std::uint64_t m_lastFrameTSC; HANDLE m_hTimer; - std::uint16_t m_serverEnforcedFps; // Maximum FPS enforced by the server - std::uint16_t m_clientEnforcedFps; // Maximum FPS enforced by the client - std::uint16_t m_userDefinedFps; // Maximum FPS defined by the user (see `fps_limit` cvar) - std::uint16_t m_displayRefreshRate; // Refresh rate of the display aka VSync (see `vsync` cvar) - std::uint16_t m_fpsTarget; // Currently target FPS limit (0 = no limit) - bool m_appliedThisFrame; // Whether the FPS limit was applied in the current frame + std::uint16_t m_serverEnforcedFps; // Maximum FPS enforced by the server + std::uint16_t m_clientEnforcedFps; // Maximum FPS enforced by the client + std::uint16_t m_userDefinedFps; // Maximum FPS defined by the user (see `fps_limit` cvar) + std::uint16_t m_displayRefreshRate; // Refresh rate of the display aka VSync (see `vsync` cvar) + std::uint16_t m_fpsTarget; // Currently target FPS limit (0 = no limit) + bool m_appliedThisFrame; // Whether the FPS limit was applied in the current frame }; -} // namespace FPSLimiter +} diff --git a/Client/core/FastFailCrashHandler/WerCrashHandler.cpp b/Client/core/FastFailCrashHandler/WerCrashHandler.cpp index d5bf6c763ea..40f57f90441 100644 --- a/Client/core/FastFailCrashHandler/WerCrashHandler.cpp +++ b/Client/core/FastFailCrashHandler/WerCrashHandler.cpp @@ -60,8 +60,7 @@ namespace FormattedStackFrame result; for (const auto& mod : modules) { - if (mod.size <= (0xFFFFFFFFFFFFFFFF - mod.baseAddress) && - address >= mod.baseAddress && address < mod.baseAddress + mod.size) + if (mod.size <= (0xFFFFFFFFFFFFFFFF - mod.baseAddress) && address >= mod.baseAddress && address < mod.baseAddress + mod.size) { const DWORD64 offset = address - mod.baseAddress; result.text = SString("%s+0x%llX", mod.name.c_str(), static_cast(offset)); @@ -90,7 +89,7 @@ namespace const ULARGE_INTEGER uliWrite{ftWrite.dwLowDateTime, ftWrite.dwHighDateTime}; constexpr ULONGLONG kFileTimeUnitsPerSecond = 10000000ULL; - const ULONGLONG maxAge = maxAgeMinutes * 60 * kFileTimeUnitsPerSecond; + const ULONGLONG maxAge = maxAgeMinutes * 60 * kFileTimeUnitsPerSecond; return uliNow.QuadPart >= uliWrite.QuadPart && (uliNow.QuadPart - uliWrite.QuadPart) < maxAge; } @@ -144,8 +143,8 @@ namespace WerCrash } PMINIDUMP_DIRECTORY pExceptionDir = nullptr; - PVOID pExceptionStream = nullptr; - ULONG streamSize = 0; + PVOID pExceptionStream = nullptr; + ULONG streamSize = 0; if (MiniDumpReadDumpStream(pBase, ExceptionStream, &pExceptionDir, &pExceptionStream, &streamSize)) { @@ -156,8 +155,8 @@ namespace WerCrash regs.exceptionAddress = pExInfo->ExceptionRecord.ExceptionAddress; PMINIDUMP_DIRECTORY pThreadListDir = nullptr; - PVOID pThreadListStream = nullptr; - ULONG threadListSize = 0; + PVOID pThreadListStream = nullptr; + ULONG threadListSize = 0; if (MiniDumpReadDumpStream(pBase, ThreadListStream, &pThreadListDir, &pThreadListStream, &threadListSize)) { @@ -214,8 +213,8 @@ namespace WerCrash constexpr size_t kMaxFrames = 64; constexpr size_t kMinFramesBeforeRawScan = 3; constexpr size_t kRawStackScanBytes = 8192; - constexpr DWORD kMinCodeAddress = 0x00400000; - constexpr DWORD kMaxCodeAddress = 0x7FFFFFFF; + constexpr DWORD kMinCodeAddress = 0x00400000; + constexpr DWORD kMaxCodeAddress = 0x7FFFFFFF; const HANDLE hFile = CreateFileA(dumpPath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) @@ -245,9 +244,9 @@ namespace WerCrash } std::vector modules; - PMINIDUMP_DIRECTORY pModuleListDir = nullptr; - PVOID pModuleListStream = nullptr; - ULONG moduleListSize = 0; + PMINIDUMP_DIRECTORY pModuleListDir = nullptr; + PVOID pModuleListStream = nullptr; + ULONG moduleListSize = 0; if (MiniDumpReadDumpStream(pBase, ModuleListStream, &pModuleListDir, &pModuleListStream, &moduleListSize)) { @@ -257,7 +256,7 @@ namespace WerCrash modules.reserve(pModuleList->NumberOfModules); for (ULONG i = 0; i < pModuleList->NumberOfModules; i++) { - const auto& mod = pModuleList->Modules[i]; + const auto& mod = pModuleList->Modules[i]; MinidumpModuleInfo info; info.baseAddress = mod.BaseOfImage; info.size = mod.SizeOfImage; @@ -272,7 +271,7 @@ namespace WerCrash if (pModName->Length <= availableForString) { std::wstring wname(pModName->Buffer, pModName->Length / sizeof(wchar_t)); - auto lastSlash = wname.find_last_of(L"\\/"); + auto lastSlash = wname.find_last_of(L"\\/"); if (lastSlash != std::wstring::npos) wname = wname.substr(lastSlash + 1); @@ -289,9 +288,9 @@ namespace WerCrash } std::map> memoryRegions; - PMINIDUMP_DIRECTORY pMemoryListDir = nullptr; - PVOID pMemoryListStream = nullptr; - ULONG memoryListSize = 0; + PMINIDUMP_DIRECTORY pMemoryListDir = nullptr; + PVOID pMemoryListStream = nullptr; + ULONG memoryListSize = 0; if (MiniDumpReadDumpStream(pBase, MemoryListStream, &pMemoryListDir, &pMemoryListStream, &memoryListSize)) { @@ -310,13 +309,14 @@ namespace WerCrash } } - const auto readDword = [&memoryRegions](DWORD64 address) noexcept -> std::optional { + const auto readDword = [&memoryRegions](DWORD64 address) noexcept -> std::optional + { for (const auto& [baseAddr, data] : memoryRegions) { if (address >= baseAddr && address + sizeof(DWORD) <= baseAddr + data.size()) { const auto offset = static_cast(address - baseAddr); - DWORD value = 0; + DWORD value = 0; std::memcpy(&value, data.data() + offset, sizeof(DWORD)); return value; } @@ -324,17 +324,18 @@ namespace WerCrash return std::nullopt; }; - const auto isAddressInModule = [&modules](DWORD64 addr) noexcept -> bool { + const auto isAddressInModule = [&modules](DWORD64 addr) noexcept -> bool + { for (const auto& mod : modules) { - if (mod.size <= (0xFFFFFFFFFFFFFFFF - mod.baseAddress) && - addr >= mod.baseAddress && addr < mod.baseAddress + mod.size) + if (mod.size <= (0xFFFFFFFFFFFFFFFF - mod.baseAddress) && addr >= mod.baseAddress && addr < mod.baseAddress + mod.size) return true; } return false; }; - const auto isLikelyCodeAddress = [&](DWORD addr) noexcept -> bool { + const auto isLikelyCodeAddress = [&](DWORD addr) noexcept -> bool + { if (addr < kMinCodeAddress || addr > kMaxCodeAddress) return false; return isAddressInModule(addr); @@ -347,7 +348,7 @@ namespace WerCrash frames.push_back(regs.eip); seenAddresses.insert(regs.eip); - DWORD currentEbp = regs.ebp; + DWORD currentEbp = regs.ebp; std::set visitedFrames; for (size_t i = 0; i < kMaxFrames && currentEbp != 0; i++) @@ -379,7 +380,7 @@ namespace WerCrash if (frames.size() < kMinFramesBeforeRawScan) { DWORD64 stackPtr = regs.esp; - size_t bytesScanned = 0; + size_t bytesScanned = 0; while (bytesScanned < kRawStackScanBytes && frames.size() < kMaxFrames) { @@ -433,11 +434,10 @@ namespace WerCrash const auto addr = frames[i]; const auto formatted = FormatAddressWithModules(addr, modules); if (formatted.isDll) - stackTrace += SString("#%02u %s [0x%08X] - IDA Address: 0x%08X\n", - static_cast(i), formatted.text.c_str(), static_cast(addr), formatted.idaOffset); + stackTrace += SString("#%02u %s [0x%08X] - IDA Address: 0x%08X\n", static_cast(i), formatted.text.c_str(), + static_cast(addr), formatted.idaOffset); else - stackTrace += SString("#%02u %s [0x%08X]\n", - static_cast(i), formatted.text.c_str(), static_cast(addr)); + stackTrace += SString("#%02u %s [0x%08X]\n", static_cast(i), formatted.text.c_str(), static_cast(addr)); } UnmapViewOfFile(pBase); @@ -446,15 +446,14 @@ namespace WerCrash return stackTrace; } - void AppendWerInfoToDump(const SString& dumpPath, const SString& moduleName, DWORD offset, DWORD exceptionCode, - const MinidumpRegisters& regs) + void AppendWerInfoToDump(const SString& dumpPath, const SString& moduleName, DWORD offset, DWORD exceptionCode, const MinidumpRegisters& regs) { if (dumpPath.empty()) return; - const char* exceptionName = (exceptionCode == 0xC0000409) ? "Stack Buffer Overrun" - : (exceptionCode == 0xC0000374) ? "Heap Corruption" - : "Security Exception"; + const char* exceptionName = (exceptionCode == 0xC0000409) ? "Stack Buffer Overrun" + : (exceptionCode == 0xC0000374) ? "Heap Corruption" + : "Security Exception"; const DWORD idaAddress = (offset <= (0xFFFFFFFF - kDefaultDllBase)) ? (kDefaultDllBase + offset) : 0; SYSTEMTIME st{}; @@ -474,8 +473,7 @@ namespace WerCrash if (regs.valid) { werInfo += "\nRegisters:\n"; - werInfo += SString("EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X EDI=%08X\n", regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, - regs.edi); + werInfo += SString("EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X EDI=%08X\n", regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, regs.edi); werInfo += SString("EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n", regs.ebp, regs.esp, regs.eip, regs.eflags); werInfo += SString("CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n", regs.cs, regs.ds, regs.ss, regs.es, regs.fs, regs.gs); } @@ -486,7 +484,8 @@ namespace WerCrash std::vector buffer; buffer.reserve(sizeof(DWORD) * 6 + dataSize); - const auto appendDword = [&buffer](DWORD value) { + const auto appendDword = [&buffer](DWORD value) + { const auto* bytes = reinterpret_cast(&value); buffer.insert(buffer.end(), bytes, bytes + sizeof(DWORD)); }; @@ -502,8 +501,8 @@ namespace WerCrash FileAppend(dumpPath, buffer.data(), static_cast(buffer.size())); } - SString RenameWerDumpToMtaFormat(const SString& sourcePath, const SString& dumpDir, const SString& moduleName, - DWORD offset, DWORD exceptionCode, const MinidumpRegisters& regs) + SString RenameWerDumpToMtaFormat(const SString& sourcePath, const SString& dumpDir, const SString& moduleName, DWORD offset, DWORD exceptionCode, + const MinidumpRegisters& regs) { SYSTEMTIME st{}; GetLocalTime(&st); @@ -537,10 +536,9 @@ namespace WerCrash } } - SString newFilename = - SString("client_%s_%s_%08x_%x_%s_%08X_%04X_%03X_%s_%04d%02d%02d_%02d%02d.dmp", strMTAVersionFull.c_str(), cleanedModuleName.c_str(), - offset, exceptionCode & 0xffff, strPathCode.c_str(), uiServerIP, uiServerPort, uiServerDuration, strSerialPart.c_str(), st.wYear, - st.wMonth, st.wDay, st.wHour, st.wMinute); + SString newFilename = SString("client_%s_%s_%08x_%x_%s_%08X_%04X_%03X_%s_%04d%02d%02d_%02d%02d.dmp", strMTAVersionFull.c_str(), + cleanedModuleName.c_str(), offset, exceptionCode & 0xffff, strPathCode.c_str(), uiServerIP, uiServerPort, + uiServerDuration, strSerialPart.c_str(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute); SString newPath = PathJoin(dumpDir, newFilename); @@ -566,9 +564,9 @@ namespace WerCrash if (werDumpFiles.empty()) return {}; - SString selectedPath; + SString selectedPath; FILETIME selectedWrite{}; - bool hasSelected = false; + bool hasSelected = false; for (const auto& dumpFile : werDumpFiles) { @@ -582,7 +580,7 @@ namespace WerCrash continue; } - FILETIME ftWrite{}; + FILETIME ftWrite{}; const BOOL gotTime = GetFileTime(hFile, nullptr, nullptr, &ftWrite); CloseHandle(hFile); @@ -626,7 +624,7 @@ namespace WerCrash const SString sourceFilename = ExtractFilename(selectedPath); OutputDebugStringA(SString("FindAndRenameWerDump: Renaming %s\n", selectedPath.c_str())); const MinidumpRegisters regs = ExtractRegistersFromMinidump(selectedPath); - const SString newPath = RenameWerDumpToMtaFormat(selectedPath, dumpDir, moduleName, offset, exceptionCode, regs); + const SString newPath = RenameWerDumpToMtaFormat(selectedPath, dumpDir, moduleName, offset, exceptionCode, regs); if (newPath.empty()) { OutputDebugStringA(SString("FindAndRenameWerDump: Rename failed (error %lu)\n", GetLastError())); @@ -663,10 +661,11 @@ namespace WerCrash struct InternalModuleEntry { SString entry; - bool isMta; + bool isMta; }; - auto storeCurrentOnly = [&, prevChunkCount](bool truncatedFlag) { + auto storeCurrentOnly = [&, prevChunkCount](bool truncatedFlag) + { HMODULE hCurrent = nullptr; if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(&UpdateModuleBases), &hCurrent)) @@ -681,9 +680,8 @@ namespace WerCrash MODULEINFO modInfo = {}; if (GetModuleInformation(hProcess, hCurrent, &modInfo, sizeof(modInfo))) { - SString strEntry = SString("%s=%08X,%08X", filename.c_str(), - static_cast(reinterpret_cast(modInfo.lpBaseOfDll)), - modInfo.SizeOfImage); + SString strEntry = SString("%s=%08X,%08X", filename.c_str(), static_cast(reinterpret_cast(modInfo.lpBaseOfDll)), + modInfo.SizeOfImage); SetApplicationSetting("diagnostics", "module-bases", strEntry); for (int i = 1; i < prevChunkCount; ++i) SetApplicationSetting("diagnostics", SString("module-bases-%d", i), ""); @@ -749,28 +747,25 @@ namespace WerCrash continue; SString lower = filename.ToLower(); - bool isMta = lower.Contains("core") || lower.Contains("client") || lower.Contains("game_sa") || - lower.Contains("multiplayer") || lower.Contains("netc") || lower.Contains("gta_sa") || - lower.Contains("proxy_sa") || lower.Contains("cef") || lower.Contains("mta") || - lower.Contains("deathmatch") || lower.Contains("gui") || lower.Contains("xmll") || - lower.Contains("loader"); + bool isMta = lower.Contains("core") || lower.Contains("client") || lower.Contains("game_sa") || lower.Contains("multiplayer") || + lower.Contains("netc") || lower.Contains("gta_sa") || lower.Contains("proxy_sa") || lower.Contains("cef") || lower.Contains("mta") || + lower.Contains("deathmatch") || lower.Contains("gui") || lower.Contains("xmll") || lower.Contains("loader"); InternalModuleEntry m; - m.entry = SString("%s=%08X,%08X", filename.c_str(), - static_cast(reinterpret_cast(modInfo.lpBaseOfDll)), - modInfo.SizeOfImage); + m.entry = SString("%s=%08X,%08X", filename.c_str(), static_cast(reinterpret_cast(modInfo.lpBaseOfDll)), modInfo.SizeOfImage); m.isMta = isMta; entries.push_back(m); } const size_t maxValueLen = 60000; const size_t maxChunks = 256; - bool truncated = false; + bool truncated = false; std::vector chunks; chunks.reserve(prevChunkCount > 0 ? static_cast(prevChunkCount) : 6); - auto tryAppend = [&](const SString& entry) -> bool { + auto tryAppend = [&](const SString& entry) -> bool + { if (entry.length() > maxValueLen) { truncated = true; @@ -799,7 +794,8 @@ namespace WerCrash return true; }; - auto appendEntries = [&](bool mtaFirst) { + auto appendEntries = [&](bool mtaFirst) + { for (const auto& e : entries) { if (e.isMta != mtaFirst) @@ -833,7 +829,8 @@ namespace WerCrash return; } - auto setChunk = [&](size_t idx, const SString& value) { + auto setChunk = [&](size_t idx, const SString& value) + { if (idx == 0) SetApplicationSetting("diagnostics", "module-bases", value); else @@ -967,7 +964,7 @@ namespace WerCrash result.moduleBase = mod.base; result.rva = crashAddress - mod.base; - const bool isExe = result.moduleName.EndsWithI(".exe"); + const bool isExe = result.moduleName.EndsWithI(".exe"); const DWORD idaBase = isExe ? kDefaultExeBase : kDefaultDllBase; if (result.rva <= (0xFFFFFFFF - idaBase)) result.idaAddress = idaBase + result.rva; @@ -992,8 +989,7 @@ namespace WerCrash return result; } - const HANDLE hFile = CreateFileA(dumpPath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + const HANDLE hFile = CreateFileA(dumpPath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { result.debugFailReason = 1; @@ -1027,8 +1023,8 @@ namespace WerCrash } PMINIDUMP_DIRECTORY pModuleListDir = nullptr; - PVOID pModuleListStream = nullptr; - ULONG moduleListSize = 0; + PVOID pModuleListStream = nullptr; + ULONG moduleListSize = 0; if (MiniDumpReadDumpStream(pBase, ModuleListStream, &pModuleListDir, &pModuleListStream, &moduleListSize)) { @@ -1044,8 +1040,7 @@ namespace WerCrash auto* pModuleList = static_cast(pModuleListStream); if (pModuleList && pModuleList->NumberOfModules > 0 && pModuleList->NumberOfModules < 10000) { - const SIZE_T requiredSize = sizeof(MINIDUMP_MODULE_LIST) + - (static_cast(pModuleList->NumberOfModules) - 1) * sizeof(MINIDUMP_MODULE); + const SIZE_T requiredSize = sizeof(MINIDUMP_MODULE_LIST) + (static_cast(pModuleList->NumberOfModules) - 1) * sizeof(MINIDUMP_MODULE); if (moduleListSize < requiredSize) { result.debugFailReason = 2; @@ -1059,7 +1054,7 @@ namespace WerCrash for (ULONG i = 0; i < pModuleList->NumberOfModules; i++) { - const auto& mod = pModuleList->Modules[i]; + const auto& mod = pModuleList->Modules[i]; const DWORD64 modBase = mod.BaseOfImage; const DWORD32 modSize = mod.SizeOfImage; @@ -1069,9 +1064,7 @@ namespace WerCrash if (crashAddress >= modBase && crashAddress < modBase + modSize) { SString modName; - if (mod.ModuleNameRva != 0 && - mod.ModuleNameRva < mappedSize && - mod.ModuleNameRva <= mappedSize - sizeof(ULONG32)) + if (mod.ModuleNameRva != 0 && mod.ModuleNameRva < mappedSize && mod.ModuleNameRva <= mappedSize - sizeof(ULONG32)) { auto* pModName = reinterpret_cast(static_cast(pBase) + mod.ModuleNameRva); if (pModName->Length > 0 && pModName->Length < 1024) @@ -1085,7 +1078,7 @@ namespace WerCrash try { std::wstring wname(pModName->Buffer, pModName->Length / sizeof(wchar_t)); - auto lastSlash = wname.find_last_of(L"\\/"); + auto lastSlash = wname.find_last_of(L"\\/"); if (lastSlash != std::wstring::npos) wname = wname.substr(lastSlash + 1); std::string name(wname.begin(), wname.end()); @@ -1105,7 +1098,7 @@ namespace WerCrash result.moduleBase = static_cast(modBase); result.rva = crashAddress - static_cast(modBase); - const bool isExe = result.moduleName.EndsWithI(".exe"); + const bool isExe = result.moduleName.EndsWithI(".exe"); const DWORD idaBase = isExe ? kDefaultExeBase : kDefaultDllBase; if (result.rva <= (0xFFFFFFFF - idaBase)) result.idaAddress = idaBase + result.rva; diff --git a/Client/core/FastFailCrashHandler/WerCrashHandler.h b/Client/core/FastFailCrashHandler/WerCrashHandler.h index 0b3a46f193a..154edbfd735 100644 --- a/Client/core/FastFailCrashHandler/WerCrashHandler.h +++ b/Client/core/FastFailCrashHandler/WerCrashHandler.h @@ -27,21 +27,21 @@ namespace WerCrash struct MinidumpRegisters { - bool valid = false; - DWORD eax = 0, ebx = 0, ecx = 0, edx = 0; - DWORD esi = 0, edi = 0, ebp = 0, esp = 0, eip = 0; - DWORD eflags = 0; - WORD cs = 0, ds = 0, es = 0, fs = 0, gs = 0, ss = 0; - DWORD exceptionCode = 0; + bool valid = false; + DWORD eax = 0, ebx = 0, ecx = 0, edx = 0; + DWORD esi = 0, edi = 0, ebp = 0, esp = 0, eip = 0; + DWORD eflags = 0; + WORD cs = 0, ds = 0, es = 0, fs = 0, gs = 0, ss = 0; + DWORD exceptionCode = 0; DWORD64 exceptionAddress = 0; }; struct WerDumpResult { - SString path; - SString sourceFilename; + SString path; + SString sourceFilename; MinidumpRegisters regs; - SString stackTrace; + SString stackTrace; }; struct ModuleEntry @@ -65,17 +65,15 @@ namespace WerCrash }; [[nodiscard]] MinidumpRegisters ExtractRegistersFromMinidump(const SString& dumpPath); - [[nodiscard]] SString ExtractStackTraceFromMinidump(const SString& dumpPath, const MinidumpRegisters& regs); + [[nodiscard]] SString ExtractStackTraceFromMinidump(const SString& dumpPath, const MinidumpRegisters& regs); - void AppendWerInfoToDump(const SString& dumpPath, const SString& moduleName, DWORD offset, DWORD exceptionCode, - const MinidumpRegisters& regs); + void AppendWerInfoToDump(const SString& dumpPath, const SString& moduleName, DWORD offset, DWORD exceptionCode, const MinidumpRegisters& regs); - [[nodiscard]] SString RenameWerDumpToMtaFormat(const SString& sourcePath, const SString& dumpDir, - const SString& moduleName, DWORD offset, DWORD exceptionCode, - const MinidumpRegisters& regs); + [[nodiscard]] SString RenameWerDumpToMtaFormat(const SString& sourcePath, const SString& dumpDir, const SString& moduleName, DWORD offset, + DWORD exceptionCode, const MinidumpRegisters& regs); - [[nodiscard]] WerDumpResult FindAndRenameWerDump(const SString& dumpDir, const SString& moduleName, DWORD offset, - DWORD exceptionCode, const std::optional& processCreationTime); + [[nodiscard]] WerDumpResult FindAndRenameWerDump(const SString& dumpDir, const SString& moduleName, DWORD offset, DWORD exceptionCode, + const std::optional& processCreationTime); [[nodiscard]] bool IsFileRecentEnough(HANDLE hFile, std::uint64_t maxAgeMinutes = 15) noexcept; diff --git a/Client/core/Graphics/CGraphics.cpp b/Client/core/Graphics/CGraphics.cpp index 18aaacf862c..26f35113893 100644 --- a/Client/core/Graphics/CGraphics.cpp +++ b/Client/core/Graphics/CGraphics.cpp @@ -21,9 +21,9 @@ #include "CPrimitive3DBatcher.h" #include "CMaterialPrimitive3DBatcher.h" #include "CAspectRatioConverter.h" -extern CCore* g_pCore; -extern std::atomic g_bInGTAScene; -extern std::atomic g_bInMTAScene; +extern CCore* g_pCore; +extern std::atomic g_bInGTAScene; +extern std::atomic g_bInMTAScene; using namespace std; @@ -31,15 +31,15 @@ template <> CGraphics* CSingleton::m_pSingleton = NULL; const SColor g_rectEdgePixelsData[] = { - 0x00FFFF00, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // - 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, // - 0x00080008 // Plain pixels size info + 0x00FFFF00, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF, // + 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, // + 0x00080008 // Plain pixels size info }; CGraphics::CGraphics(CLocalGUI* pGUI) @@ -53,45 +53,45 @@ CGraphics::CGraphics(CLocalGUI* pGUI) m_ActiveBlendMode = EBlendMode::BLEND; m_CurDrawMode = EDrawMode::NONE; m_CurBlendMode = EBlendMode::BLEND; - auto renderItemManager = std::make_unique(); - auto tileBatcher = std::make_unique(); - auto line3DPreGUI = std::make_unique(true); - auto line3DPostFX = std::make_unique(true); - auto line3DPostGUI = std::make_unique(false); - auto materialLinePreGUI = std::make_unique(true); - auto materialLinePostFX = std::make_unique(true); - auto materialLinePostGUI = std::make_unique(false); - auto primitive3DPreGUI = std::make_unique(true); - auto primitive3DPostFX = std::make_unique(true); - auto primitive3DPostGUI = std::make_unique(false); - auto materialPrimitivePreGUI = std::make_unique(true, this); - auto materialPrimitivePostFX = std::make_unique(true, this); - auto materialPrimitivePostGUI = std::make_unique(false, this); - auto primitiveBatcher = std::make_unique(); - auto primitiveMaterialBatcher = std::make_unique(this); - auto screenGrabber = std::unique_ptr(NewScreenGrabber()); - auto pixelsManager = std::unique_ptr(NewPixelsManager()); - auto aspectRatioConverter = std::make_unique(); - - m_pRenderItemManager = renderItemManager.release(); - m_pTileBatcher = tileBatcher.release(); - m_pLine3DBatcherPreGUI = line3DPreGUI.release(); - m_pLine3DBatcherPostFX = line3DPostFX.release(); - m_pLine3DBatcherPostGUI = line3DPostGUI.release(); - m_pMaterialLine3DBatcherPreGUI = materialLinePreGUI.release(); - m_pMaterialLine3DBatcherPostFX = materialLinePostFX.release(); - m_pMaterialLine3DBatcherPostGUI = materialLinePostGUI.release(); - m_pPrimitive3DBatcherPreGUI = primitive3DPreGUI.release(); - m_pPrimitive3DBatcherPostFX = primitive3DPostFX.release(); - m_pPrimitive3DBatcherPostGUI = primitive3DPostGUI.release(); - m_pMaterialPrimitive3DBatcherPreGUI = materialPrimitivePreGUI.release(); - m_pMaterialPrimitive3DBatcherPostFX = materialPrimitivePostFX.release(); - m_pMaterialPrimitive3DBatcherPostGUI = materialPrimitivePostGUI.release(); - m_pPrimitiveBatcher = primitiveBatcher.release(); - m_pPrimitiveMaterialBatcher = primitiveMaterialBatcher.release(); - m_pScreenGrabber = screenGrabber.release(); - m_pPixelsManager = pixelsManager.release(); - m_pAspectRatioConverter = aspectRatioConverter.release(); + auto renderItemManager = std::make_unique(); + auto tileBatcher = std::make_unique(); + auto line3DPreGUI = std::make_unique(true); + auto line3DPostFX = std::make_unique(true); + auto line3DPostGUI = std::make_unique(false); + auto materialLinePreGUI = std::make_unique(true); + auto materialLinePostFX = std::make_unique(true); + auto materialLinePostGUI = std::make_unique(false); + auto primitive3DPreGUI = std::make_unique(true); + auto primitive3DPostFX = std::make_unique(true); + auto primitive3DPostGUI = std::make_unique(false); + auto materialPrimitivePreGUI = std::make_unique(true, this); + auto materialPrimitivePostFX = std::make_unique(true, this); + auto materialPrimitivePostGUI = std::make_unique(false, this); + auto primitiveBatcher = std::make_unique(); + auto primitiveMaterialBatcher = std::make_unique(this); + auto screenGrabber = std::unique_ptr(NewScreenGrabber()); + auto pixelsManager = std::unique_ptr(NewPixelsManager()); + auto aspectRatioConverter = std::make_unique(); + + m_pRenderItemManager = renderItemManager.release(); + m_pTileBatcher = tileBatcher.release(); + m_pLine3DBatcherPreGUI = line3DPreGUI.release(); + m_pLine3DBatcherPostFX = line3DPostFX.release(); + m_pLine3DBatcherPostGUI = line3DPostGUI.release(); + m_pMaterialLine3DBatcherPreGUI = materialLinePreGUI.release(); + m_pMaterialLine3DBatcherPostFX = materialLinePostFX.release(); + m_pMaterialLine3DBatcherPostGUI = materialLinePostGUI.release(); + m_pPrimitive3DBatcherPreGUI = primitive3DPreGUI.release(); + m_pPrimitive3DBatcherPostFX = primitive3DPostFX.release(); + m_pPrimitive3DBatcherPostGUI = primitive3DPostGUI.release(); + m_pMaterialPrimitive3DBatcherPreGUI = materialPrimitivePreGUI.release(); + m_pMaterialPrimitive3DBatcherPostFX = materialPrimitivePostFX.release(); + m_pMaterialPrimitive3DBatcherPostGUI = materialPrimitivePostGUI.release(); + m_pPrimitiveBatcher = primitiveBatcher.release(); + m_pPrimitiveMaterialBatcher = primitiveMaterialBatcher.release(); + m_pScreenGrabber = screenGrabber.release(); + m_pPixelsManager = pixelsManager.release(); + m_pAspectRatioConverter = aspectRatioConverter.release(); } CGraphics::~CGraphics() @@ -289,15 +289,15 @@ void CGraphics::DrawRectangleInternal(float fX, float fY, float fWidth, float fH int overrideWidth; int overrideHeight; } static sectionList[] = { - {{3, 3, 5, 5}, 0, 0, 0, 0}, // Center - {{3, 0, 5, 2}, 0, -2, 0, 2}, // Top - {{0, 0, 2, 2}, -2, -2, 2, 2}, // Top left - {{0, 3, 2, 5}, -2, 0, 2, 0}, // Left - {{0, 6, 2, 8}, -2, 2, 2, 2}, // Bottom left - {{3, 6, 5, 8}, 0, 2, 0, 2}, // Bottom - {{6, 6, 8, 8}, 2, 2, 2, 2}, // Bottom right - {{6, 3, 8, 5}, 2, 0, 2, 0}, // Right - {{6, 0, 8, 2}, 2, -2, 2, 2}, // Top right + {{3, 3, 5, 5}, 0, 0, 0, 0}, // Center + {{3, 0, 5, 2}, 0, -2, 0, 2}, // Top + {{0, 0, 2, 2}, -2, -2, 2, 2}, // Top left + {{0, 3, 2, 5}, -2, 0, 2, 0}, // Left + {{0, 6, 2, 8}, -2, 2, 2, 2}, // Bottom left + {{3, 6, 5, 8}, 0, 2, 0, 2}, // Bottom + {{6, 6, 8, 8}, 2, 2, 2, 2}, // Bottom right + {{6, 3, 8, 5}, 2, 0, 2, 0}, // Right + {{6, 0, 8, 2}, 2, -2, 2, 2}, // Top right }; D3DXMATRIX matrix; @@ -1256,7 +1256,7 @@ void CGraphics::DrawStringQueued(float fLeft, float fTop, float fRight, float fB else if (ulFormat & DT_VCENTER) fY = (fBottom + fTop - fTotalHeight) * 0.5f; else - fY = fTop; // DT_TOP + fY = fTop; // DT_TOP // Process each line SColor currentColor = dwColor; @@ -1290,7 +1290,7 @@ void CGraphics::DrawColorCodedTextLine(float fLeft, float fRight, float fY, SCol unsigned int uiSeekPos = 0; const wchar_t* wszSectionStart = wszSectionPos; SColor nextColor = currentColor; - while (*wszSectionPos != '\0') // find end of this section + while (*wszSectionPos != '\0') // find end of this section { if (IsColorCodeW(wszSectionPos)) { @@ -1344,7 +1344,7 @@ void CGraphics::DrawColorCodedTextLine(float fLeft, float fRight, float fY, SCol else if (ulFormat & DT_CENTER) fX = (fRight + fLeft - fTotalWidth) * 0.5f; else - fX = fLeft; // DT_LEFT + fX = fLeft; // DT_LEFT // Draw all the color sections for (std::list::const_iterator iter = sectionList.begin(); iter != sectionList.end(); ++iter) @@ -1765,7 +1765,7 @@ void CGraphics::DrawQueue(std::vector& Queue) void CGraphics::AddQueueItem(const sDrawQueueItem& Item, bool bPostGUI) { // Add it to the correct queue - if (bPostGUI && !CCore::GetSingleton().IsMenuVisible()) // Don't draw over the main menu. Ever. + if (bPostGUI && !CCore::GetSingleton().IsMenuVisible()) // Don't draw over the main menu. Ever. m_PostGUIQueue.push_back(Item); else m_PreGUIQueue.push_back(Item); @@ -1831,7 +1831,7 @@ void CGraphics::DrawQueueItem(const sDrawQueueItem& Item) const float fPosFracY = Item.Text.fTop - rect.top; D3DXMATRIX matrix; D3DXVECTOR2 scaling(Item.Text.fScaleX, Item.Text.fScaleY); - D3DXVECTOR2 translation(fPosFracX * Item.Text.fScaleX, fPosFracY * Item.Text.fScaleY); // Sub-pixel positioning + D3DXVECTOR2 translation(fPosFracX * Item.Text.fScaleX, fPosFracY * Item.Text.fScaleY); // Sub-pixel positioning D3DXVECTOR2 rotcenter(Item.Text.fRotationCenterX, Item.Text.fRotationCenterY); D3DXVECTOR2* pRotcenter = Item.Text.fRotation ? &rotcenter : NULL; D3DXMatrixTransformation2D(&matrix, NULL, 0.0f, &scaling, pRotcenter, DegreesToRadians(Item.Text.fRotation), &translation); @@ -1926,7 +1926,7 @@ ID3DXFont* CGraphics::MaybeGetBigFont(ID3DXFont* pDXFont, float& fScaleX, float& { // Adjust scale to compensate for higher res font fScaleX *= 0.25f; - if (&fScaleX != &fScaleY) // Check fScaleY is not the same variable + if (&fScaleX != &fScaleY) // Check fScaleY is not the same variable fScaleY *= 0.25f; return m_pBigDXFonts[i]; } @@ -1973,25 +1973,25 @@ void CGraphics::ClearDrawQueue(std::vector& Queue) void CGraphics::AddQueueRef(CRenderItem* pRenderItem) { pRenderItem->AddRef(); - m_iDebugQueueRefs++; // For debugging + m_iDebugQueueRefs++; // For debugging } void CGraphics::RemoveQueueRef(CRenderItem* pRenderItem) { pRenderItem->Release(); - m_iDebugQueueRefs--; // For debugging + m_iDebugQueueRefs--; // For debugging } void CGraphics::AddQueueRef(IUnknown* pUnknown) { pUnknown->AddRef(); - m_iDebugQueueRefs++; // For debugging + m_iDebugQueueRefs++; // For debugging } void CGraphics::RemoveQueueRef(IUnknown* pUnknown) { pUnknown->Release(); - m_iDebugQueueRefs--; // For debugging + m_iDebugQueueRefs--; // For debugging } // Notification that the render target will be changing @@ -2231,7 +2231,8 @@ void CGraphics::DrawProgressMessage(bool bPreserveBackbuffer) if (m_LastLostDeviceTimer.Get() < 1000) return; - const auto determineOwner = []() -> ESceneOwner { + const auto determineOwner = []() -> ESceneOwner + { if (g_bInMTAScene.load(std::memory_order_acquire)) return ESceneOwner::MTA; if (g_bInGTAScene.load(std::memory_order_acquire)) @@ -2244,7 +2245,8 @@ void CGraphics::DrawProgressMessage(bool bPreserveBackbuffer) auto inScene = [&]() { return currentOwner != ESceneOwner::None; }; - auto endCurrentScene = [&](const char* context) -> bool { + auto endCurrentScene = [&](const char* context) -> bool + { if (!inScene()) return true; if (!EndSceneWithoutProxy(m_pDevice, currentOwner)) @@ -2258,7 +2260,8 @@ void CGraphics::DrawProgressMessage(bool bPreserveBackbuffer) return true; }; - auto beginSceneAs = [&](ESceneOwner owner, const char* context) -> bool { + auto beginSceneAs = [&](ESceneOwner owner, const char* context) -> bool + { if (owner == ESceneOwner::None) return true; if (!BeginSceneWithoutProxy(m_pDevice, owner)) @@ -2691,7 +2694,7 @@ namespace for (int i = 0; i < (int)vertexList.size() - 1; i += 2) if ((from - vertexList[i]).LengthSquared() < 0.00001f) if ((to - vertexList[i + 1]).LengthSquared() < 0.00001f) - return; // Duplicated + return; // Duplicated // Add new line vertexList.push_back(from); @@ -2724,7 +2727,7 @@ namespace } return wireModel; } -} // namespace +} // namespace void CGraphics::DrawWiredSphere(CVector vecPosition, float fRadius, SColor color, float fLineWidth, int iterations) { diff --git a/Client/core/Graphics/CGraphics.h b/Client/core/Graphics/CGraphics.h index 0dac23e1d05..48319abcf6c 100644 --- a/Client/core/Graphics/CGraphics.h +++ b/Client/core/Graphics/CGraphics.h @@ -19,9 +19,9 @@ class CGraphics; #include "CSingleton.h" #include "CRenderItemManager.h" -#define DUMMY_PROGRESS_INITIAL_DELAY 1000 // Game stall time before spinner is displayed -#define DUMMY_PROGRESS_MIN_DISPLAY_TIME 1000 // Minimum time spinner is drawn (to prevent flicker) -#define DUMMY_PROGRESS_ANIMATION_INTERVAL 100 // Animation speed +#define DUMMY_PROGRESS_INITIAL_DELAY 1000 // Game stall time before spinner is displayed +#define DUMMY_PROGRESS_MIN_DISPLAY_TIME 1000 // Minimum time spinner is drawn (to prevent flicker) +#define DUMMY_PROGRESS_ANIMATION_INTERVAL 100 // Animation speed class CTileBatcher; class CLine3DBatcher; @@ -154,7 +154,8 @@ class CGraphics : public CGraphicsInterface, public CSingleton void DrawMaterialPrimitiveQueued(std::vector* vertices, D3DPRIMITIVETYPE type, CMaterialItem* pMaterial, bool bPostGUI); void DrawPrimitive3DQueued(std::vector* pVecVertices, D3DPRIMITIVETYPE eType, eRenderStage stage = eRenderStage::PRE_FX); - void DrawMaterialPrimitive3DQueued(std::vector* pVecVertices, D3DPRIMITIVETYPE eType, CMaterialItem* pMaterial, eRenderStage stage = eRenderStage::PRE_FX); + void DrawMaterialPrimitive3DQueued(std::vector* pVecVertices, D3DPRIMITIVETYPE eType, CMaterialItem* pMaterial, + eRenderStage stage = eRenderStage::PRE_FX); void DrawCircleQueued(float fX, float fY, float fRadius, float fStartAngle, float fStopAngle, unsigned long ulColor, unsigned long ulColorCenter, short siSegments, float fRatio, bool bPostGUI); @@ -239,7 +240,7 @@ class CGraphics : public CGraphicsInterface, public CSingleton CPrimitiveMaterialBatcher* m_pPrimitiveMaterialBatcher = nullptr; CPrimitive3DBatcher* m_pPrimitive3DBatcherPreGUI = nullptr; CPrimitive3DBatcher* m_pPrimitive3DBatcherPostFX = nullptr; - CPrimitive3DBatcher* m_pPrimitive3DBatcherPostGUI = nullptr; + CPrimitive3DBatcher* m_pPrimitive3DBatcherPostGUI = nullptr; CMaterialPrimitive3DBatcher* m_pMaterialPrimitive3DBatcherPreGUI = nullptr; CMaterialPrimitive3DBatcher* m_pMaterialPrimitive3DBatcherPostFX = nullptr; CMaterialPrimitive3DBatcher* m_pMaterialPrimitive3DBatcherPostGUI = nullptr; @@ -370,8 +371,8 @@ class CGraphics : public CGraphicsInterface, public CSingleton enum EMTARenderZone { MTA_RZONE_NONE, - MTA_RZONE_MAIN, // MTA rendering inside known areas. - MTA_RZONE_OUTSIDE, // MTA rendering outside known areas. i.e. During a keypress or GTA callback + MTA_RZONE_MAIN, // MTA rendering inside known areas. + MTA_RZONE_OUTSIDE, // MTA rendering outside known areas. i.e. During a keypress or GTA callback }; EMTARenderZone m_MTARenderZone; diff --git a/Client/core/Graphics/CLine3DBatcher.h b/Client/core/Graphics/CLine3DBatcher.h index 6320ab57331..abd21de68b8 100644 --- a/Client/core/Graphics/CLine3DBatcher.h +++ b/Client/core/Graphics/CLine3DBatcher.h @@ -16,12 +16,12 @@ struct SPDVertex DWORD color; }; -#define WRITE_PD_VERTEX(buf,fX,fY,fZ,dwColor) \ - buf->x = fX; \ - buf->y = fY; \ - buf->z = fZ; \ - buf->color = dwColor; \ - buf++; +#define WRITE_PD_VERTEX(buf, fX, fY, fZ, dwColor) \ + buf->x = fX; \ + buf->y = fY; \ + buf->z = fZ; \ + buf->color = dwColor; \ + buf++; struct SLine3DItem { diff --git a/Client/core/Graphics/CMaterialLine3DBatcher.cpp b/Client/core/Graphics/CMaterialLine3DBatcher.cpp index 26b1abf56a7..6b2e1a4a4c6 100644 --- a/Client/core/Graphics/CMaterialLine3DBatcher.cpp +++ b/Client/core/Graphics/CMaterialLine3DBatcher.cpp @@ -293,7 +293,7 @@ void CMaterialLine3DBatcher::DrawBatch(const CVector& vecCameraPos, uint* pBatch pShaderInstance->m_pEffectWrap->ApplyMappedHandles(); // Do shader passes - DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE + DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE uint uiNumPasses = 0; pShaderInstance->m_pEffectWrap->Begin(&uiNumPasses, dwFlags); diff --git a/Client/core/Graphics/CMaterialLine3DBatcher.h b/Client/core/Graphics/CMaterialLine3DBatcher.h index 8c3f1766c1e..1cce586df94 100644 --- a/Client/core/Graphics/CMaterialLine3DBatcher.h +++ b/Client/core/Graphics/CMaterialLine3DBatcher.h @@ -48,6 +48,6 @@ class CMaterialLine3DBatcher bool m_bPreGUI; IDirect3DDevice9* m_pDevice; std::vector m_LineList; - static SMaterialLine3DItem* ms_pLines; // Used in sort callback + static SMaterialLine3DItem* ms_pLines; // Used in sort callback ETextureAddress m_CurrentTextureAddress; }; diff --git a/Client/core/Graphics/CPixelsManager.cpp b/Client/core/Graphics/CPixelsManager.cpp index 84fdd720ede..796b0957ca8 100644 --- a/Client/core/Graphics/CPixelsManager.cpp +++ b/Client/core/Graphics/CPixelsManager.cpp @@ -790,7 +790,7 @@ bool CPixelsManager::ChangePixelsFormat(const CPixels& oldPixels, CPixels& newPi // Decode if (oldFormat == EPixelsFormat::JPEG) { - uint uiWidth, uiHeight; + uint uiWidth, uiHeight; std::string strError; if (JpegDecode(oldPixels.GetData(), oldPixels.GetSize(), &newPixels.buffer, uiWidth, uiHeight, &strError)) { diff --git a/Client/core/Graphics/CPixelsManager.h b/Client/core/Graphics/CPixelsManager.h index 088472a433c..fb80c65e948 100644 --- a/Client/core/Graphics/CPixelsManager.h +++ b/Client/core/Graphics/CPixelsManager.h @@ -9,7 +9,7 @@ *****************************************************************************/ #define XRGB_BYTES_PER_PIXEL (4) -#define SIZEOF_PLAIN_TAIL (4) +#define SIZEOF_PLAIN_TAIL (4) // // Scope release and zeroing of pointer diff --git a/Client/core/Graphics/CPixelsManager_VolumeTexture.cpp b/Client/core/Graphics/CPixelsManager_VolumeTexture.cpp index ca862470d58..4511ec30ffc 100644 --- a/Client/core/Graphics/CPixelsManager_VolumeTexture.cpp +++ b/Client/core/Graphics/CPixelsManager_VolumeTexture.cpp @@ -400,7 +400,7 @@ bool CPixelsManager::D3DXGetVolumePixels(IDirect3DVolumeTexture9* pD3DVolumeText bool bNeedToConvert = dxFileFormat == D3DXIFF_DDS; if (bNeedToConvert && Desc.Format == dxFormat && !bMipMaps) - bNeedToConvert = false; // No need to convert DDS if compression is the same and no mipmaps required + bNeedToConvert = false; // No need to convert DDS if compression is the same and no mipmaps required ID3DXBuffer* dxBuffer; CAutoReleaseMe Thanks2(dxBuffer); diff --git a/Client/core/Graphics/CRenderItem.EffectCloner.cpp b/Client/core/Graphics/CRenderItem.EffectCloner.cpp index 68da785af03..9bea77daf25 100644 --- a/Client/core/Graphics/CRenderItem.EffectCloner.cpp +++ b/Client/core/Graphics/CRenderItem.EffectCloner.cpp @@ -98,8 +98,8 @@ CEffectWrap* CEffectCloner::CreateD3DEffect(const SString& strFile, const SStrin if (!strReport.empty()) { - strReport += SString("[effects cur:%d created:%d dest:%d]", g_StaticMemoryState.Effect.iCurrentCount, - g_StaticMemoryState.Effect.iCreatedCount, g_StaticMemoryState.Effect.iDestroyedCount); + strReport += SString("[effects cur:%d created:%d dest:%d]", g_StaticMemoryState.Effect.iCurrentCount, g_StaticMemoryState.Effect.iCreatedCount, + g_StaticMemoryState.Effect.iDestroyedCount); AddReportLog(7544, SString("NewEffectTemplate (call:%d) %s %s", uiCallCount, *strReport, *strFile)); } if (!pEffectTemplate) @@ -171,7 +171,7 @@ void CEffectCloner::MaybeTidyUp(bool bForceDrasticMeasures) int iTicks = static_cast((1 - fTicksAlpha * fTicksAlpha) * 30 * 60 * 1000) + 1000; #ifdef MTA_DEBUG - iTicks /= 60; // Mins to seconds for debug + iTicks /= 60; // Mins to seconds for debug #endif // Valid Effect not used for a little while can go diff --git a/Client/core/Graphics/CRenderItem.EffectCloner.h b/Client/core/Graphics/CRenderItem.EffectCloner.h index a08b12972c3..8f8ad45df1b 100644 --- a/Client/core/Graphics/CRenderItem.EffectCloner.h +++ b/Client/core/Graphics/CRenderItem.EffectCloner.h @@ -57,6 +57,6 @@ class CEffectCloner CElapsedTime m_TidyupTimer; CRenderItemManager* m_pManager; - std::unordered_map m_ValidMap; // Active and files not changed since first created - std::vector m_OldList; // Active but files changed since first created + std::unordered_map m_ValidMap; // Active and files not changed since first created + std::vector m_OldList; // Active but files changed since first created }; diff --git a/Client/core/Graphics/CRenderItem.EffectParameters.cpp b/Client/core/Graphics/CRenderItem.EffectParameters.cpp index cb22d26884b..ba1d59d5646 100644 --- a/Client/core/Graphics/CRenderItem.EffectParameters.cpp +++ b/Client/core/Graphics/CRenderItem.EffectParameters.cpp @@ -29,10 +29,10 @@ IMPLEMENT_ENUM_END("state-group") const STypeMapping TypeMappingList[] = { {TYPE_INT, D3DXPC_SCALAR, D3DXPT_INT, RegMap::Int2Int, 1}, - {TYPE_D3DCOLOR, D3DXPC_SCALAR, D3DXPT_INT, RegMap::Int2Int, 1}, // Can be read as float4 or DWORD color + {TYPE_D3DCOLOR, D3DXPC_SCALAR, D3DXPT_INT, RegMap::Int2Int, 1}, // Can be read as float4 or DWORD color {TYPE_D3DCOLOR, D3DXPC_VECTOR, D3DXPT_FLOAT, RegMap::Int2Color, 4}, - {TYPE_IFLOAT, D3DXPC_SCALAR, D3DXPT_FLOAT, RegMap::Int2Float, 1}, // Can be read as float or as int on float memory - {TYPE_IFLOAT, D3DXPC_SCALAR, D3DXPT_INT, RegMap::Int2Int, 1}, // Can be read as float or as int on float memory + {TYPE_IFLOAT, D3DXPC_SCALAR, D3DXPT_FLOAT, RegMap::Int2Float, 1}, // Can be read as float or as int on float memory + {TYPE_IFLOAT, D3DXPC_SCALAR, D3DXPT_INT, RegMap::Int2Int, 1}, // Can be read as float or as int on float memory {TYPE_FLOAT, D3DXPC_SCALAR, D3DXPT_FLOAT, RegMap::Float2Float, 1}, {TYPE_D3DCOLORVALUE, D3DXPC_VECTOR, D3DXPT_FLOAT, RegMap::Color2Color, 4}, {TYPE_VECTOR3, D3DXPC_VECTOR, D3DXPT_FLOAT, RegMap::Vector2Vector, 3}, @@ -48,191 +48,190 @@ const STypeMapping TypeMappingList[] = { // Big list of D3D registers // -#define ADD_REGISTER(type,name) \ - {offsetof(USING_STRUCT, name), USING_LIST, #name, type} +#define ADD_REGISTER(type, name) {offsetof(USING_STRUCT, name), USING_LIST, #name, type} const SRegisterInfo BigRegisterInfoList[] = { #define USING_STRUCT CProxyDirect3DDevice9::SD3DRenderState -#define USING_LIST "RenderState" - ADD_REGISTER(TYPE_INT, ZENABLE), // = 7, /* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) */ - ADD_REGISTER(TYPE_INT, FILLMODE), // = 8, /* D3DFILLMODE */ - ADD_REGISTER(TYPE_INT, SHADEMODE), // = 9, /* D3DSHADEMODE */ - ADD_REGISTER(TYPE_INT, ZWRITEENABLE), // = 14, /* TRUE to enable z writes */ - ADD_REGISTER(TYPE_INT, ALPHATESTENABLE), // = 15, /* TRUE to enable alpha tests */ - ADD_REGISTER(TYPE_INT, LASTPIXEL), // = 16, /* TRUE for last-pixel on lines */ - ADD_REGISTER(TYPE_INT, SRCBLEND), // = 19, /* D3DBLEND */ - ADD_REGISTER(TYPE_INT, DESTBLEND), // = 20, /* D3DBLEND */ - ADD_REGISTER(TYPE_INT, CULLMODE), // = 22, /* D3DCULL */ - ADD_REGISTER(TYPE_INT, ZFUNC), // = 23, /* D3DCMPFUNC */ - ADD_REGISTER(TYPE_INT, ALPHAREF), // = 24, /* D3DFIXED */ - ADD_REGISTER(TYPE_INT, ALPHAFUNC), // = 25, /* D3DCMPFUNC */ - ADD_REGISTER(TYPE_INT, DITHERENABLE), // = 26, /* TRUE to enable dithering */ - ADD_REGISTER(TYPE_INT, ALPHABLENDENABLE), // = 27, /* TRUE to enable alpha blending */ - ADD_REGISTER(TYPE_INT, FOGENABLE), // = 28, /* TRUE to enable fog blending */ - ADD_REGISTER(TYPE_INT, SPECULARENABLE), // = 29, /* TRUE to enable specular */ - ADD_REGISTER(TYPE_D3DCOLOR, FOGCOLOR), // = 34, /* D3DCOLOR */ - ADD_REGISTER(TYPE_INT, FOGTABLEMODE), // = 35, /* D3DFOGMODE */ - ADD_REGISTER(TYPE_IFLOAT, FOGSTART), // = 36, /* Fog start (for both vertex and pixel fog) */ - ADD_REGISTER(TYPE_IFLOAT, FOGEND), // = 37, /* Fog end */ - ADD_REGISTER(TYPE_IFLOAT, FOGDENSITY), // = 38, /* Fog density */ - ADD_REGISTER(TYPE_INT, RANGEFOGENABLE), // = 48, /* Enables range-based fog */ - ADD_REGISTER(TYPE_INT, STENCILENABLE), // = 52, /* BOOL enable/disable stenciling */ - ADD_REGISTER(TYPE_INT, STENCILFAIL), // = 53, /* D3DSTENCILOP to do if stencil test fails */ - ADD_REGISTER(TYPE_INT, STENCILZFAIL), // = 54, /* D3DSTENCILOP to do if stencil test passes and Z test fails */ - ADD_REGISTER(TYPE_INT, STENCILPASS), // = 55, /* D3DSTENCILOP to do if both stencil and Z tests pass */ - ADD_REGISTER(TYPE_INT, STENCILFUNC), // = 56, /* D3DCMPFUNC fn. */ - ADD_REGISTER(TYPE_INT, STENCILREF), // = 57, /* Reference value used in stencil test */ - ADD_REGISTER(TYPE_INT, STENCILMASK), // = 58, /* Mask value used in stencil test */ - ADD_REGISTER(TYPE_INT, STENCILWRITEMASK), // = 59, /* Write mask applied to values written to stencil buffer */ - ADD_REGISTER(TYPE_D3DCOLOR, TEXTUREFACTOR), // = 60, /* D3DCOLOR used for multi-texture blend */ - ADD_REGISTER(TYPE_INT, WRAP0), // = 128, /* wrap for 1st texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP1), // = 129, /* wrap for 2nd texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP2), // = 130, /* wrap for 3rd texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP3), // = 131, /* wrap for 4th texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP4), // = 132, /* wrap for 5th texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP5), // = 133, /* wrap for 6th texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP6), // = 134, /* wrap for 7th texture coord. set */ - ADD_REGISTER(TYPE_INT, WRAP7), // = 135, /* wrap for 8th texture coord. set */ - ADD_REGISTER(TYPE_INT, CLIPPING), // = 136, - ADD_REGISTER(TYPE_INT, LIGHTING), // = 137, - ADD_REGISTER(TYPE_D3DCOLOR, AMBIENT), // = 139, - ADD_REGISTER(TYPE_INT, FOGVERTEXMODE), // = 140, - ADD_REGISTER(TYPE_INT, COLORVERTEX), // = 141, - ADD_REGISTER(TYPE_INT, LOCALVIEWER), // = 142, - ADD_REGISTER(TYPE_INT, NORMALIZENORMALS), // = 143, - ADD_REGISTER(TYPE_INT, DIFFUSEMATERIALSOURCE), // = 145, - ADD_REGISTER(TYPE_INT, SPECULARMATERIALSOURCE), // = 146, - ADD_REGISTER(TYPE_INT, AMBIENTMATERIALSOURCE), // = 147, - ADD_REGISTER(TYPE_INT, EMISSIVEMATERIALSOURCE), // = 148, - ADD_REGISTER(TYPE_INT, VERTEXBLEND), // = 151, - ADD_REGISTER(TYPE_INT, CLIPPLANEENABLE), // = 152, - ADD_REGISTER(TYPE_IFLOAT, POINTSIZE), // = 154, /* float point size */ - ADD_REGISTER(TYPE_IFLOAT, POINTSIZE_MIN), // = 155, /* float point size min threshold */ - ADD_REGISTER(TYPE_INT, POINTSPRITEENABLE), // = 156, /* BOOL point texture coord control */ - ADD_REGISTER(TYPE_INT, POINTSCALEENABLE), // = 157, /* BOOL point size scale enable */ - ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_A), // = 158, /* float point attenuation A value */ - ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_B), // = 159, /* float point attenuation B value */ - ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_C), // = 160, /* float point attenuation C value */ - ADD_REGISTER(TYPE_INT, MULTISAMPLEANTIALIAS), // = 161, // BOOL - set to do FSAA with multisample buffer - ADD_REGISTER(TYPE_INT, MULTISAMPLEMASK), // = 162, // DWORD - ) //per-sample enable/disable - ADD_REGISTER(TYPE_INT, PATCHEDGESTYLE), // = 163, // Sets whether patch edges will use float style tessellation - ADD_REGISTER(TYPE_INT, DEBUGMONITORTOKEN), // = 165, // DEBUG ONLY - token to debug monitor - ADD_REGISTER(TYPE_IFLOAT, POINTSIZE_MAX), // = 166, /* float point size max threshold */ - ADD_REGISTER(TYPE_INT, INDEXEDVERTEXBLENDENABLE), // = 167, - ADD_REGISTER(TYPE_INT, COLORWRITEENABLE), // = 168, // per-channel write enable - ADD_REGISTER(TYPE_IFLOAT, TWEENFACTOR), // = 170, // float tween factor - ADD_REGISTER(TYPE_INT, BLENDOP), // = 171, // D3DBLENDOP setting - ADD_REGISTER(TYPE_INT, POSITIONDEGREE), // = 172, // NPatch position interpolation degree. D3DDEGREE_LINEAR or D3DDEGREE_CUBIC (default) - ADD_REGISTER(TYPE_INT, NORMALDEGREE), // = 173, aa NPatch normal interpolation degree. D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC - ADD_REGISTER(TYPE_INT, SCISSORTESTENABLE), // = 174 - ADD_REGISTER(TYPE_INT, SLOPESCALEDEPTHBIAS), // = 175, - ADD_REGISTER(TYPE_INT, ANTIALIASEDLINEENABLE), // = 176, - ADD_REGISTER(TYPE_INT, MINTESSELLATIONLEVEL), // = 178, - ADD_REGISTER(TYPE_INT, MAXTESSELLATIONLEVEL), // = 179, - ADD_REGISTER(TYPE_INT, ADAPTIVETESS_X), // = 180, - ADD_REGISTER(TYPE_INT, ADAPTIVETESS_Y), // = 181, - ADD_REGISTER(TYPE_INT, ADAPTIVETESS_Z), // = 182, - ADD_REGISTER(TYPE_INT, ADAPTIVETESS_W), // = 183, - ADD_REGISTER(TYPE_INT, ENABLEADAPTIVETESSELLATION), // = 184, - ADD_REGISTER(TYPE_INT, TWOSIDEDSTENCILMODE), // = 185, /* BOOL enable/disable 2 sided stenciling */ - ADD_REGISTER(TYPE_INT, CCW_STENCILFAIL), // = 186, /* D3DSTENCILOP to do if ccw stencil test fails */ - ADD_REGISTER(TYPE_INT, CCW_STENCILZFAIL), // = 187, /* D3DSTENCILOP to do if ccw stencil test passes and Z test fails */ - ADD_REGISTER(TYPE_INT, CCW_STENCILPASS), // = 188, /* D3DSTENCILOP to do if both ccw stencil and Z tests pass */ - ADD_REGISTER(TYPE_INT, CCW_STENCILFUNC), // = 189, /* D3DCMPFUNC fn. */ - ADD_REGISTER(TYPE_INT, COLORWRITEENABLE1), // = 190, /* Additional ColorWriteEnables */ - ADD_REGISTER(TYPE_INT, COLORWRITEENABLE2), // = 191, /* Additional ColorWriteEnables */ - ADD_REGISTER(TYPE_INT, COLORWRITEENABLE3), // = 192, /* Additional ColorWriteEnables */ - ADD_REGISTER(TYPE_D3DCOLOR, BLENDFACTOR), // = 193, /* D3DCOLOR used for a constant blend factor during alpha blending*/ - ADD_REGISTER(TYPE_INT, SRGBWRITEENABLE), // = 194, /* Enable rendertarget writes to be DE-linearized to SRGB */ - ADD_REGISTER(TYPE_INT, DEPTHBIAS), // = 195, - ADD_REGISTER(TYPE_INT, WRAP8), // = 198, /* Additional wrap states for vs_3_0+ attributes with D3DDECLUSAGE_TEXCOORD */ - ADD_REGISTER(TYPE_INT, WRAP9), // = 199, - ADD_REGISTER(TYPE_INT, WRAP10), // = 200, - ADD_REGISTER(TYPE_INT, WRAP11), // = 201, - ADD_REGISTER(TYPE_INT, WRAP12), // = 202, - ADD_REGISTER(TYPE_INT, WRAP13), // = 203, - ADD_REGISTER(TYPE_INT, WRAP14), // = 204, - ADD_REGISTER(TYPE_INT, WRAP15), // = 205, - ADD_REGISTER(TYPE_INT, SEPARATEALPHABLENDENABLE), // = 206, /* TRUE to enable a separate blending function for the alpha channel */ - ADD_REGISTER(TYPE_INT, SRCBLENDALPHA), // = 207, /* SRC blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ - ADD_REGISTER(TYPE_INT, DESTBLENDALPHA), // = 208, /* DST blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ - ADD_REGISTER(TYPE_INT, BLENDOPALPHA), // = 209, /* Blending operation for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ -#undef USING_STRUCT -#undef USING_LIST +#define USING_LIST "RenderState" + ADD_REGISTER(TYPE_INT, ZENABLE), // = 7, /* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) */ + ADD_REGISTER(TYPE_INT, FILLMODE), // = 8, /* D3DFILLMODE */ + ADD_REGISTER(TYPE_INT, SHADEMODE), // = 9, /* D3DSHADEMODE */ + ADD_REGISTER(TYPE_INT, ZWRITEENABLE), // = 14, /* TRUE to enable z writes */ + ADD_REGISTER(TYPE_INT, ALPHATESTENABLE), // = 15, /* TRUE to enable alpha tests */ + ADD_REGISTER(TYPE_INT, LASTPIXEL), // = 16, /* TRUE for last-pixel on lines */ + ADD_REGISTER(TYPE_INT, SRCBLEND), // = 19, /* D3DBLEND */ + ADD_REGISTER(TYPE_INT, DESTBLEND), // = 20, /* D3DBLEND */ + ADD_REGISTER(TYPE_INT, CULLMODE), // = 22, /* D3DCULL */ + ADD_REGISTER(TYPE_INT, ZFUNC), // = 23, /* D3DCMPFUNC */ + ADD_REGISTER(TYPE_INT, ALPHAREF), // = 24, /* D3DFIXED */ + ADD_REGISTER(TYPE_INT, ALPHAFUNC), // = 25, /* D3DCMPFUNC */ + ADD_REGISTER(TYPE_INT, DITHERENABLE), // = 26, /* TRUE to enable dithering */ + ADD_REGISTER(TYPE_INT, ALPHABLENDENABLE), // = 27, /* TRUE to enable alpha blending */ + ADD_REGISTER(TYPE_INT, FOGENABLE), // = 28, /* TRUE to enable fog blending */ + ADD_REGISTER(TYPE_INT, SPECULARENABLE), // = 29, /* TRUE to enable specular */ + ADD_REGISTER(TYPE_D3DCOLOR, FOGCOLOR), // = 34, /* D3DCOLOR */ + ADD_REGISTER(TYPE_INT, FOGTABLEMODE), // = 35, /* D3DFOGMODE */ + ADD_REGISTER(TYPE_IFLOAT, FOGSTART), // = 36, /* Fog start (for both vertex and pixel fog) */ + ADD_REGISTER(TYPE_IFLOAT, FOGEND), // = 37, /* Fog end */ + ADD_REGISTER(TYPE_IFLOAT, FOGDENSITY), // = 38, /* Fog density */ + ADD_REGISTER(TYPE_INT, RANGEFOGENABLE), // = 48, /* Enables range-based fog */ + ADD_REGISTER(TYPE_INT, STENCILENABLE), // = 52, /* BOOL enable/disable stenciling */ + ADD_REGISTER(TYPE_INT, STENCILFAIL), // = 53, /* D3DSTENCILOP to do if stencil test fails */ + ADD_REGISTER(TYPE_INT, STENCILZFAIL), // = 54, /* D3DSTENCILOP to do if stencil test passes and Z test fails */ + ADD_REGISTER(TYPE_INT, STENCILPASS), // = 55, /* D3DSTENCILOP to do if both stencil and Z tests pass */ + ADD_REGISTER(TYPE_INT, STENCILFUNC), // = 56, /* D3DCMPFUNC fn. */ + ADD_REGISTER(TYPE_INT, STENCILREF), // = 57, /* Reference value used in stencil test */ + ADD_REGISTER(TYPE_INT, STENCILMASK), // = 58, /* Mask value used in stencil test */ + ADD_REGISTER(TYPE_INT, STENCILWRITEMASK), // = 59, /* Write mask applied to values written to stencil buffer */ + ADD_REGISTER(TYPE_D3DCOLOR, TEXTUREFACTOR), // = 60, /* D3DCOLOR used for multi-texture blend */ + ADD_REGISTER(TYPE_INT, WRAP0), // = 128, /* wrap for 1st texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP1), // = 129, /* wrap for 2nd texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP2), // = 130, /* wrap for 3rd texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP3), // = 131, /* wrap for 4th texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP4), // = 132, /* wrap for 5th texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP5), // = 133, /* wrap for 6th texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP6), // = 134, /* wrap for 7th texture coord. set */ + ADD_REGISTER(TYPE_INT, WRAP7), // = 135, /* wrap for 8th texture coord. set */ + ADD_REGISTER(TYPE_INT, CLIPPING), // = 136, + ADD_REGISTER(TYPE_INT, LIGHTING), // = 137, + ADD_REGISTER(TYPE_D3DCOLOR, AMBIENT), // = 139, + ADD_REGISTER(TYPE_INT, FOGVERTEXMODE), // = 140, + ADD_REGISTER(TYPE_INT, COLORVERTEX), // = 141, + ADD_REGISTER(TYPE_INT, LOCALVIEWER), // = 142, + ADD_REGISTER(TYPE_INT, NORMALIZENORMALS), // = 143, + ADD_REGISTER(TYPE_INT, DIFFUSEMATERIALSOURCE), // = 145, + ADD_REGISTER(TYPE_INT, SPECULARMATERIALSOURCE), // = 146, + ADD_REGISTER(TYPE_INT, AMBIENTMATERIALSOURCE), // = 147, + ADD_REGISTER(TYPE_INT, EMISSIVEMATERIALSOURCE), // = 148, + ADD_REGISTER(TYPE_INT, VERTEXBLEND), // = 151, + ADD_REGISTER(TYPE_INT, CLIPPLANEENABLE), // = 152, + ADD_REGISTER(TYPE_IFLOAT, POINTSIZE), // = 154, /* float point size */ + ADD_REGISTER(TYPE_IFLOAT, POINTSIZE_MIN), // = 155, /* float point size min threshold */ + ADD_REGISTER(TYPE_INT, POINTSPRITEENABLE), // = 156, /* BOOL point texture coord control */ + ADD_REGISTER(TYPE_INT, POINTSCALEENABLE), // = 157, /* BOOL point size scale enable */ + ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_A), // = 158, /* float point attenuation A value */ + ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_B), // = 159, /* float point attenuation B value */ + ADD_REGISTER(TYPE_IFLOAT, POINTSCALE_C), // = 160, /* float point attenuation C value */ + ADD_REGISTER(TYPE_INT, MULTISAMPLEANTIALIAS), // = 161, // BOOL - set to do FSAA with multisample buffer + ADD_REGISTER(TYPE_INT, MULTISAMPLEMASK), // = 162, // DWORD - ) //per-sample enable/disable + ADD_REGISTER(TYPE_INT, PATCHEDGESTYLE), // = 163, // Sets whether patch edges will use float style tessellation + ADD_REGISTER(TYPE_INT, DEBUGMONITORTOKEN), // = 165, // DEBUG ONLY - token to debug monitor + ADD_REGISTER(TYPE_IFLOAT, POINTSIZE_MAX), // = 166, /* float point size max threshold */ + ADD_REGISTER(TYPE_INT, INDEXEDVERTEXBLENDENABLE), // = 167, + ADD_REGISTER(TYPE_INT, COLORWRITEENABLE), // = 168, // per-channel write enable + ADD_REGISTER(TYPE_IFLOAT, TWEENFACTOR), // = 170, // float tween factor + ADD_REGISTER(TYPE_INT, BLENDOP), // = 171, // D3DBLENDOP setting + ADD_REGISTER(TYPE_INT, POSITIONDEGREE), // = 172, // NPatch position interpolation degree. D3DDEGREE_LINEAR or D3DDEGREE_CUBIC (default) + ADD_REGISTER(TYPE_INT, NORMALDEGREE), // = 173, aa NPatch normal interpolation degree. D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC + ADD_REGISTER(TYPE_INT, SCISSORTESTENABLE), // = 174 + ADD_REGISTER(TYPE_INT, SLOPESCALEDEPTHBIAS), // = 175, + ADD_REGISTER(TYPE_INT, ANTIALIASEDLINEENABLE), // = 176, + ADD_REGISTER(TYPE_INT, MINTESSELLATIONLEVEL), // = 178, + ADD_REGISTER(TYPE_INT, MAXTESSELLATIONLEVEL), // = 179, + ADD_REGISTER(TYPE_INT, ADAPTIVETESS_X), // = 180, + ADD_REGISTER(TYPE_INT, ADAPTIVETESS_Y), // = 181, + ADD_REGISTER(TYPE_INT, ADAPTIVETESS_Z), // = 182, + ADD_REGISTER(TYPE_INT, ADAPTIVETESS_W), // = 183, + ADD_REGISTER(TYPE_INT, ENABLEADAPTIVETESSELLATION), // = 184, + ADD_REGISTER(TYPE_INT, TWOSIDEDSTENCILMODE), // = 185, /* BOOL enable/disable 2 sided stenciling */ + ADD_REGISTER(TYPE_INT, CCW_STENCILFAIL), // = 186, /* D3DSTENCILOP to do if ccw stencil test fails */ + ADD_REGISTER(TYPE_INT, CCW_STENCILZFAIL), // = 187, /* D3DSTENCILOP to do if ccw stencil test passes and Z test fails */ + ADD_REGISTER(TYPE_INT, CCW_STENCILPASS), // = 188, /* D3DSTENCILOP to do if both ccw stencil and Z tests pass */ + ADD_REGISTER(TYPE_INT, CCW_STENCILFUNC), // = 189, /* D3DCMPFUNC fn. */ + ADD_REGISTER(TYPE_INT, COLORWRITEENABLE1), // = 190, /* Additional ColorWriteEnables */ + ADD_REGISTER(TYPE_INT, COLORWRITEENABLE2), // = 191, /* Additional ColorWriteEnables */ + ADD_REGISTER(TYPE_INT, COLORWRITEENABLE3), // = 192, /* Additional ColorWriteEnables */ + ADD_REGISTER(TYPE_D3DCOLOR, BLENDFACTOR), // = 193, /* D3DCOLOR used for a constant blend factor during alpha blending*/ + ADD_REGISTER(TYPE_INT, SRGBWRITEENABLE), // = 194, /* Enable rendertarget writes to be DE-linearized to SRGB */ + ADD_REGISTER(TYPE_INT, DEPTHBIAS), // = 195, + ADD_REGISTER(TYPE_INT, WRAP8), // = 198, /* Additional wrap states for vs_3_0+ attributes with D3DDECLUSAGE_TEXCOORD */ + ADD_REGISTER(TYPE_INT, WRAP9), // = 199, + ADD_REGISTER(TYPE_INT, WRAP10), // = 200, + ADD_REGISTER(TYPE_INT, WRAP11), // = 201, + ADD_REGISTER(TYPE_INT, WRAP12), // = 202, + ADD_REGISTER(TYPE_INT, WRAP13), // = 203, + ADD_REGISTER(TYPE_INT, WRAP14), // = 204, + ADD_REGISTER(TYPE_INT, WRAP15), // = 205, + ADD_REGISTER(TYPE_INT, SEPARATEALPHABLENDENABLE), // = 206, /* TRUE to enable a separate blending function for the alpha channel */ + ADD_REGISTER(TYPE_INT, SRCBLENDALPHA), // = 207, /* SRC blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ + ADD_REGISTER(TYPE_INT, DESTBLENDALPHA), // = 208, /* DST blend factor for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ + ADD_REGISTER(TYPE_INT, BLENDOPALPHA), // = 209, /* Blending operation for the alpha channel when DWORD SEPARATEDESTALPHAENABLE ) */ +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DStageState -#define USING_LIST "StageState" - ADD_REGISTER(TYPE_INT, COLOROP), // = 1, /* D3DTEXTUREOP - per-stage blending controls for color channels */ - ADD_REGISTER(TYPE_INT, COLORARG1), // = 2, /* D3DTA_* (texture arg) */ - ADD_REGISTER(TYPE_INT, COLORARG2), // = 3, /* D3DTA_* (texture arg) */ - ADD_REGISTER(TYPE_INT, ALPHAOP), // = 4, /* D3DTEXTUREOP - per-stage blending controls for alpha channel */ - ADD_REGISTER(TYPE_INT, ALPHAARG1), // = 5, /* D3DTA_* (texture arg) */ - ADD_REGISTER(TYPE_INT, ALPHAARG2), // = 6, /* D3DTA_* (texture arg) */ - ADD_REGISTER(TYPE_INT, BUMPENVMAT00), // = 7, /* float (bump mapping matrix) */ - ADD_REGISTER(TYPE_INT, BUMPENVMAT01), // = 8, /* float (bump mapping matrix) */ - ADD_REGISTER(TYPE_INT, BUMPENVMAT10), // = 9, /* float (bump mapping matrix) */ - ADD_REGISTER(TYPE_INT, BUMPENVMAT11), // = 10, /* float (bump mapping matrix) */ - ADD_REGISTER(TYPE_INT, TEXCOORDINDEX), // = 11, /* identifies which set of texture coordinates index this texture */ - ADD_REGISTER(TYPE_INT, BUMPENVLSCALE), // = 22, /* float scale for bump map luminance */ - ADD_REGISTER(TYPE_INT, BUMPENVLOFFSET), // = 23, /* float offset for bump map luminance */ - ADD_REGISTER(TYPE_INT, TEXTURETRANSFORMFLAGS), // = 24, /* D3DTEXTURETRANSFORMFLAGS controls texture transform */ - ADD_REGISTER(TYPE_INT, COLORARG0), // = 26, /* D3DTA_* third arg for triadic ops */ - ADD_REGISTER(TYPE_INT, ALPHAARG0), // = 27, /* D3DTA_* third arg for triadic ops */ - ADD_REGISTER(TYPE_INT, RESULTARG), // = 28, /* D3DTA_* arg for result (CURRENT or TEMP) */ - ADD_REGISTER(TYPE_INT, CONSTANT), // = 32, /* Per-stage constant D3DTA_CONSTANT */ -#undef USING_STRUCT -#undef USING_LIST +#define USING_LIST "StageState" + ADD_REGISTER(TYPE_INT, COLOROP), // = 1, /* D3DTEXTUREOP - per-stage blending controls for color channels */ + ADD_REGISTER(TYPE_INT, COLORARG1), // = 2, /* D3DTA_* (texture arg) */ + ADD_REGISTER(TYPE_INT, COLORARG2), // = 3, /* D3DTA_* (texture arg) */ + ADD_REGISTER(TYPE_INT, ALPHAOP), // = 4, /* D3DTEXTUREOP - per-stage blending controls for alpha channel */ + ADD_REGISTER(TYPE_INT, ALPHAARG1), // = 5, /* D3DTA_* (texture arg) */ + ADD_REGISTER(TYPE_INT, ALPHAARG2), // = 6, /* D3DTA_* (texture arg) */ + ADD_REGISTER(TYPE_INT, BUMPENVMAT00), // = 7, /* float (bump mapping matrix) */ + ADD_REGISTER(TYPE_INT, BUMPENVMAT01), // = 8, /* float (bump mapping matrix) */ + ADD_REGISTER(TYPE_INT, BUMPENVMAT10), // = 9, /* float (bump mapping matrix) */ + ADD_REGISTER(TYPE_INT, BUMPENVMAT11), // = 10, /* float (bump mapping matrix) */ + ADD_REGISTER(TYPE_INT, TEXCOORDINDEX), // = 11, /* identifies which set of texture coordinates index this texture */ + ADD_REGISTER(TYPE_INT, BUMPENVLSCALE), // = 22, /* float scale for bump map luminance */ + ADD_REGISTER(TYPE_INT, BUMPENVLOFFSET), // = 23, /* float offset for bump map luminance */ + ADD_REGISTER(TYPE_INT, TEXTURETRANSFORMFLAGS), // = 24, /* D3DTEXTURETRANSFORMFLAGS controls texture transform */ + ADD_REGISTER(TYPE_INT, COLORARG0), // = 26, /* D3DTA_* third arg for triadic ops */ + ADD_REGISTER(TYPE_INT, ALPHAARG0), // = 27, /* D3DTA_* third arg for triadic ops */ + ADD_REGISTER(TYPE_INT, RESULTARG), // = 28, /* D3DTA_* arg for result (CURRENT or TEMP) */ + ADD_REGISTER(TYPE_INT, CONSTANT), // = 32, /* Per-stage constant D3DTA_CONSTANT */ +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DSamplerState -#define USING_LIST "SamplerState" - ADD_REGISTER(TYPE_INT, ADDRESSU), // = 1, /* D3DTEXTUREADDRESS for U coordinate */ - ADD_REGISTER(TYPE_INT, ADDRESSV), // = 2, /* D3DTEXTUREADDRESS for V coordinate */ - ADD_REGISTER(TYPE_INT, ADDRESSW), // = 3, /* D3DTEXTUREADDRESS for W coordinate */ - ADD_REGISTER(TYPE_D3DCOLOR, BORDERCOLOR), // = 4, /* D3DCOLOR */ - ADD_REGISTER(TYPE_INT, MAGFILTER), // = 5, /* D3DTEXTUREFILTER filter to use for magnification */ - ADD_REGISTER(TYPE_INT, MINFILTER), // = 6, /* D3DTEXTUREFILTER filter to use for minification */ - ADD_REGISTER(TYPE_INT, MIPFILTER), // = 7, /* D3DTEXTUREFILTER filter to use between mipmaps during minification */ - ADD_REGISTER(TYPE_INT, MIPMAPLODBIAS), // = 8, /* float Mipmap LOD bias */ - ADD_REGISTER(TYPE_INT, MAXMIPLEVEL), // = 9, /* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) */ - ADD_REGISTER(TYPE_INT, MAXANISOTROPY), // = 10, /* DWORD maximum anisotropy */ - ADD_REGISTER(TYPE_INT, SRGBTEXTURE), // = 11, /* Default = 0 (which means Gamma 1.0, no correction required.) else correct for Gamma = 2.2 */ - ADD_REGISTER(TYPE_INT, ELEMENTINDEX), // = 12, When multi-element texture is assigned to sampler, this indicates which element index to use. - ADD_REGISTER(TYPE_INT, DMAPOFFSET), // = 13, /* Offset in vertices in the pre-sampled displacement map. */ -#undef USING_STRUCT -#undef USING_LIST +#define USING_LIST "SamplerState" + ADD_REGISTER(TYPE_INT, ADDRESSU), // = 1, /* D3DTEXTUREADDRESS for U coordinate */ + ADD_REGISTER(TYPE_INT, ADDRESSV), // = 2, /* D3DTEXTUREADDRESS for V coordinate */ + ADD_REGISTER(TYPE_INT, ADDRESSW), // = 3, /* D3DTEXTUREADDRESS for W coordinate */ + ADD_REGISTER(TYPE_D3DCOLOR, BORDERCOLOR), // = 4, /* D3DCOLOR */ + ADD_REGISTER(TYPE_INT, MAGFILTER), // = 5, /* D3DTEXTUREFILTER filter to use for magnification */ + ADD_REGISTER(TYPE_INT, MINFILTER), // = 6, /* D3DTEXTUREFILTER filter to use for minification */ + ADD_REGISTER(TYPE_INT, MIPFILTER), // = 7, /* D3DTEXTUREFILTER filter to use between mipmaps during minification */ + ADD_REGISTER(TYPE_INT, MIPMAPLODBIAS), // = 8, /* float Mipmap LOD bias */ + ADD_REGISTER(TYPE_INT, MAXMIPLEVEL), // = 9, /* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) */ + ADD_REGISTER(TYPE_INT, MAXANISOTROPY), // = 10, /* DWORD maximum anisotropy */ + ADD_REGISTER(TYPE_INT, SRGBTEXTURE), // = 11, /* Default = 0 (which means Gamma 1.0, no correction required.) else correct for Gamma = 2.2 */ + ADD_REGISTER(TYPE_INT, ELEMENTINDEX), // = 12, When multi-element texture is assigned to sampler, this indicates which element index to use. + ADD_REGISTER(TYPE_INT, DMAPOFFSET), // = 13, /* Offset in vertices in the pre-sampled displacement map. */ +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT D3DMATERIAL9 -#define USING_LIST "MaterialState" +#define USING_LIST "MaterialState" ADD_REGISTER(TYPE_D3DCOLORVALUE, Diffuse), /* Diffuse color RGBA */ ADD_REGISTER(TYPE_D3DCOLORVALUE, Ambient), /* Ambient color RGB */ ADD_REGISTER(TYPE_D3DCOLORVALUE, Specular), /* Specular 'shininess' */ ADD_REGISTER(TYPE_D3DCOLORVALUE, Emissive), /* Emissive color RGB */ ADD_REGISTER(TYPE_FLOAT, Power), /* Sharpness if specular highlight */ -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DTransformState -#define USING_LIST "TransformState" - ADD_REGISTER(TYPE_MATRIX, VIEW), // = 2, - ADD_REGISTER(TYPE_MATRIX, PROJECTION), // = 3, - ADD_REGISTER(TYPE_MATRIX, TEXTURE0), // = 16, - ADD_REGISTER(TYPE_MATRIX, TEXTURE1), // = 17, - ADD_REGISTER(TYPE_MATRIX, TEXTURE2), // = 18, - ADD_REGISTER(TYPE_MATRIX, TEXTURE3), // = 19, - ADD_REGISTER(TYPE_MATRIX, TEXTURE4), // = 20, - ADD_REGISTER(TYPE_MATRIX, TEXTURE5), // = 21, - ADD_REGISTER(TYPE_MATRIX, TEXTURE6), // = 22, - ADD_REGISTER(TYPE_MATRIX, TEXTURE7), // = 23, - ADD_REGISTER(TYPE_MATRIX, WORLD), // = 256, - ADD_REGISTER(TYPE_MATRIX, WORLD1), // = 257, - ADD_REGISTER(TYPE_MATRIX, WORLD2), // = 258, - ADD_REGISTER(TYPE_MATRIX, WORLD3), // = 259, -#undef USING_STRUCT -#undef USING_LIST +#define USING_LIST "TransformState" + ADD_REGISTER(TYPE_MATRIX, VIEW), // = 2, + ADD_REGISTER(TYPE_MATRIX, PROJECTION), // = 3, + ADD_REGISTER(TYPE_MATRIX, TEXTURE0), // = 16, + ADD_REGISTER(TYPE_MATRIX, TEXTURE1), // = 17, + ADD_REGISTER(TYPE_MATRIX, TEXTURE2), // = 18, + ADD_REGISTER(TYPE_MATRIX, TEXTURE3), // = 19, + ADD_REGISTER(TYPE_MATRIX, TEXTURE4), // = 20, + ADD_REGISTER(TYPE_MATRIX, TEXTURE5), // = 21, + ADD_REGISTER(TYPE_MATRIX, TEXTURE6), // = 22, + ADD_REGISTER(TYPE_MATRIX, TEXTURE7), // = 23, + ADD_REGISTER(TYPE_MATRIX, WORLD), // = 256, + ADD_REGISTER(TYPE_MATRIX, WORLD1), // = 257, + ADD_REGISTER(TYPE_MATRIX, WORLD2), // = 258, + ADD_REGISTER(TYPE_MATRIX, WORLD3), // = 259, +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT D3DLIGHT9 -#define USING_LIST "LightState" +#define USING_LIST "LightState" ADD_REGISTER(TYPE_INT, Type), /* Type of light source */ ADD_REGISTER(TYPE_D3DCOLORVALUE, Diffuse), /* Diffuse color of light */ ADD_REGISTER(TYPE_D3DCOLORVALUE, Specular), /* Specular color of light */ @@ -246,23 +245,23 @@ const SRegisterInfo BigRegisterInfoList[] = { ADD_REGISTER(TYPE_FLOAT, Attenuation2), /* Quadratic attenuation */ ADD_REGISTER(TYPE_FLOAT, Theta), /* Inner angle of spotlight cone */ ADD_REGISTER(TYPE_FLOAT, Phi), /* Outer angle of spotlight cone */ -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DLightEnableState -#define USING_LIST "LightEnableState" +#define USING_LIST "LightEnableState" ADD_REGISTER(TYPE_INT, Enable), -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DTextureState -#define USING_LIST "TextureState" +#define USING_LIST "TextureState" ADD_REGISTER(TYPE_TEXTURE, Texture), -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT D3DCAPS9 -#define USING_LIST "DeviceCaps" +#define USING_LIST "DeviceCaps" ADD_REGISTER(TYPE_INT, DeviceType), ADD_REGISTER(TYPE_INT, AdapterOrdinal), ADD_REGISTER(TYPE_INT, Caps), /* Caps from DX7 Draw */ @@ -279,12 +278,12 @@ const SRegisterInfo BigRegisterInfoList[] = { ADD_REGISTER(TYPE_INT, AlphaCmpCaps), ADD_REGISTER(TYPE_INT, ShadeCaps), ADD_REGISTER(TYPE_INT, TextureCaps), - ADD_REGISTER(TYPE_INT, TextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DTexture9's - ADD_REGISTER(TYPE_INT, CubeTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DCubeTexture9's - ADD_REGISTER(TYPE_INT, VolumeTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DVolumeTexture9's - ADD_REGISTER(TYPE_INT, TextureAddressCaps), // D3DPTADDRESSCAPS for IDirect3DTexture9's - ADD_REGISTER(TYPE_INT, VolumeTextureAddressCaps), // D3DPTADDRESSCAPS for IDirect3DVolumeTexture9's - ADD_REGISTER(TYPE_INT, LineCaps), // D3DLINECAPS + ADD_REGISTER(TYPE_INT, TextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DTexture9's + ADD_REGISTER(TYPE_INT, CubeTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DCubeTexture9's + ADD_REGISTER(TYPE_INT, VolumeTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DVolumeTexture9's + ADD_REGISTER(TYPE_INT, TextureAddressCaps), // D3DPTADDRESSCAPS for IDirect3DTexture9's + ADD_REGISTER(TYPE_INT, VolumeTextureAddressCaps), // D3DPTADDRESSCAPS for IDirect3DVolumeTexture9's + ADD_REGISTER(TYPE_INT, LineCaps), // D3DLINECAPS ADD_REGISTER(TYPE_INT, MaxTextureWidth), ADD_REGISTER(TYPE_INT, MaxTextureHeight), ADD_REGISTER(TYPE_INT, MaxVolumeExtent), @@ -308,23 +307,23 @@ const SRegisterInfo BigRegisterInfoList[] = { ADD_REGISTER(TYPE_INT, MaxVertexBlendMatrices), ADD_REGISTER(TYPE_INT, MaxVertexBlendMatrixIndex), ADD_REGISTER(TYPE_FLOAT, MaxPointSize), - ADD_REGISTER(TYPE_INT, MaxPrimitiveCount), // max number of primitives per DrawPrimitive call + ADD_REGISTER(TYPE_INT, MaxPrimitiveCount), // max number of primitives per DrawPrimitive call ADD_REGISTER(TYPE_INT, MaxVertexIndex), ADD_REGISTER(TYPE_INT, MaxStreams), - ADD_REGISTER(TYPE_INT, MaxStreamStride), // max stride for SetStreamSource + ADD_REGISTER(TYPE_INT, MaxStreamStride), // max stride for SetStreamSource ADD_REGISTER(TYPE_INT, VertexShaderVersion), - ADD_REGISTER(TYPE_INT, MaxVertexShaderConst), // number of vertex shader constant registers + ADD_REGISTER(TYPE_INT, MaxVertexShaderConst), // number of vertex shader constant registers ADD_REGISTER(TYPE_INT, PixelShaderVersion), - ADD_REGISTER(TYPE_FLOAT, PixelShader1xMaxValue), // max value storable in registers of ps.1.x shaders - ADD_REGISTER(TYPE_INT, DevCaps2), // Here are the DX9 specific ones + ADD_REGISTER(TYPE_FLOAT, PixelShader1xMaxValue), // max value storable in registers of ps.1.x shaders + ADD_REGISTER(TYPE_INT, DevCaps2), // Here are the DX9 specific ones ADD_REGISTER(TYPE_FLOAT, MaxNpatchTessellationLevel), ADD_REGISTER(TYPE_INT, Reserved5), - ADD_REGISTER(TYPE_INT, MasterAdapterOrdinal), // ordinal of master adaptor for adapter group - ADD_REGISTER(TYPE_INT, AdapterOrdinalInGroup), // ordinal inside the adapter group - ADD_REGISTER(TYPE_INT, NumberOfAdaptersInGroup), // number of adapters in this adapter group (only if master) - ADD_REGISTER(TYPE_INT, DeclTypes), // Data types, supported in vertex declarations - ADD_REGISTER(TYPE_INT, NumSimultaneousRTs), // Will be at least 1 - ADD_REGISTER(TYPE_INT, StretchRectFilterCaps), // Filter caps supported by StretchRect + ADD_REGISTER(TYPE_INT, MasterAdapterOrdinal), // ordinal of master adaptor for adapter group + ADD_REGISTER(TYPE_INT, AdapterOrdinalInGroup), // ordinal inside the adapter group + ADD_REGISTER(TYPE_INT, NumberOfAdaptersInGroup), // number of adapters in this adapter group (only if master) + ADD_REGISTER(TYPE_INT, DeclTypes), // Data types, supported in vertex declarations + ADD_REGISTER(TYPE_INT, NumSimultaneousRTs), // Will be at least 1 + ADD_REGISTER(TYPE_INT, StretchRectFilterCaps), // Filter caps supported by StretchRect ADD_REGISTER(TYPE_INT, VS20Caps.Caps), ADD_REGISTER(TYPE_INT, VS20Caps.DynamicFlowControlDepth), ADD_REGISTER(TYPE_INT, VS20Caps.NumTemps), @@ -334,25 +333,25 @@ const SRegisterInfo BigRegisterInfoList[] = { ADD_REGISTER(TYPE_INT, PS20Caps.NumTemps), ADD_REGISTER(TYPE_INT, PS20Caps.StaticFlowControlDepth), ADD_REGISTER(TYPE_INT, PS20Caps.NumInstructionSlots), - ADD_REGISTER(TYPE_INT, VertexTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DTexture9's for texture, used in vertex shaders - ADD_REGISTER(TYPE_INT, MaxVShaderInstructionsExecuted), // maximum number of vertex shader instructions that can be executed - ADD_REGISTER(TYPE_INT, MaxPShaderInstructionsExecuted), // maximum number of pixel shader instructions that can be executed + ADD_REGISTER(TYPE_INT, VertexTextureFilterCaps), // D3DPTFILTERCAPS for IDirect3DTexture9's for texture, used in vertex shaders + ADD_REGISTER(TYPE_INT, MaxVShaderInstructionsExecuted), // maximum number of vertex shader instructions that can be executed + ADD_REGISTER(TYPE_INT, MaxPShaderInstructionsExecuted), // maximum number of pixel shader instructions that can be executed ADD_REGISTER(TYPE_INT, MaxVertexShader30InstructionSlots), ADD_REGISTER(TYPE_INT, MaxPixelShader30InstructionSlots), -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST #define USING_STRUCT CProxyDirect3DDevice9::SD3DVertexDeclState -#define USING_LIST "VertexDeclState" - ADD_REGISTER(TYPE_INT, Position), // Does each vertex have these components ? +#define USING_LIST "VertexDeclState" + ADD_REGISTER(TYPE_INT, Position), // Does each vertex have these components ? ADD_REGISTER(TYPE_INT, PositionT), ADD_REGISTER(TYPE_INT, Normal), ADD_REGISTER(TYPE_INT, Color0), ADD_REGISTER(TYPE_INT, Color1), ADD_REGISTER(TYPE_INT, TexCoord0), ADD_REGISTER(TYPE_INT, TexCoord1), -#undef USING_STRUCT -#undef USING_LIST +#undef USING_STRUCT +#undef USING_LIST }; //////////////////////////////////////////////////////////////// @@ -1017,7 +1016,7 @@ SString CEffectParameters::GetAnnotationNameAndValue(D3DXHANDLE hParameter, uint if (!m_pD3DEffect) return ""; - D3DXHANDLE hAnnotation = m_pD3DEffect->GetAnnotation(hParameter, uiIndex); + D3DXHANDLE hAnnotation = m_pD3DEffect->GetAnnotation(hParameter, uiIndex); if (!hAnnotation) return ""; @@ -1156,8 +1155,8 @@ bool CEffectParameters::TryMappingParameterToRegister(D3DXHANDLE hParameter, con } // Extract prepended stage number, if any - SString strStagePart; - SString strName; + SString strStagePart; + SString strName; const bool bHasStagePart = strAnnotValue.Split(",", &strStagePart, &strName, -1); if (!bHasStagePart) strName = strAnnotValue; @@ -1168,7 +1167,7 @@ bool CEffectParameters::TryMappingParameterToRegister(D3DXHANDLE hParameter, con if (strName.empty()) continue; - int iStage = 0; + int iStage = 0; const bool bGroupUsesStage = DoesStateGroupUseStageIndex(stateGroup); if (bHasStagePart) { @@ -1181,7 +1180,7 @@ bool CEffectParameters::TryMappingParameterToRegister(D3DXHANDLE hParameter, con if (strStagePart.empty()) continue; - char* pParseEnd = nullptr; + char* pParseEnd = nullptr; const long parsedStage = strtol(strStagePart.c_str(), &pParseEnd, 10); if (!pParseEnd || *pParseEnd != '\0') continue; @@ -1231,7 +1230,7 @@ bool CEffectParameters::TryMappingParameterToRegister(D3DXHANDLE hParameter, con var.iSize = pTypeMapping->OutSize; AddStateMappedParameter(stateGroup, var); m_bUsesMappedHandles = true; - return true; // We have a weiner + return true; // We have a weiner } return false; diff --git a/Client/core/Graphics/CRenderItem.EffectParameters.h b/Client/core/Graphics/CRenderItem.EffectParameters.h index 88e59c364fc..0b80c38549b 100644 --- a/Client/core/Graphics/CRenderItem.EffectParameters.h +++ b/Client/core/Graphics/CRenderItem.EffectParameters.h @@ -24,13 +24,13 @@ DECLARE_ENUM(EStateGroup) enum EReadableAsType { - TYPE_INT, // int - TYPE_D3DCOLOR, // Can be read as float4 or DWORD color - TYPE_IFLOAT, // Can be read as float or as int on float memory - TYPE_D3DCOLORVALUE, // float4 - TYPE_FLOAT, // float - TYPE_VECTOR3, // float3 - TYPE_MATRIX, // float4x4 + TYPE_INT, // int + TYPE_D3DCOLOR, // Can be read as float4 or DWORD color + TYPE_IFLOAT, // Can be read as float or as int on float memory + TYPE_D3DCOLORVALUE, // float4 + TYPE_FLOAT, // float + TYPE_VECTOR3, // float3 + TYPE_MATRIX, // float4x4 TYPE_TEXTURE, }; @@ -50,7 +50,7 @@ namespace RegMap Matrix2Matrix, Texture2Texture, }; -} // namespace RegMap +} // Map effect parameter to something struct STypeMapping diff --git a/Client/core/Graphics/CRenderItem.EffectTemplate.cpp b/Client/core/Graphics/CRenderItem.EffectTemplate.cpp index 331846acc9f..9be0236a5a9 100644 --- a/Client/core/Graphics/CRenderItem.EffectTemplate.cpp +++ b/Client/core/Graphics/CRenderItem.EffectTemplate.cpp @@ -112,7 +112,7 @@ namespace return S_OK; } }; -} // namespace +} // namespace //////////////////////////////////////////////////////////////// // @@ -153,7 +153,7 @@ void CEffectTemplate::PreDestruct() int CEffectTemplate::GetTicksSinceLastUsed() { if (m_uiCloneCount != 0) - return 0; // Used right now + return 0; // Used right now CTickCount delta = CTickCount::Now(true) - m_TickCountLastUsed; return static_cast(delta.ToLongLong()) + 1; @@ -224,7 +224,7 @@ void CEffectTemplate::CreateUnderlyingData(const SString& strFile, const SString macroList.back().Definition = NULL; // Compile effect - DWORD dwFlags = D3DXFX_LARGEADDRESSAWARE; // D3DXSHADER_PARTIALPRECISION, D3DXSHADER_DEBUG, D3DXFX_NOT_CLONEABLE; + DWORD dwFlags = D3DXFX_LARGEADDRESSAWARE; // D3DXSHADER_PARTIALPRECISION, D3DXSHADER_DEBUG, D3DXFX_NOT_CLONEABLE; if (bDebug) dwFlags |= D3DXSHADER_DEBUG; diff --git a/Client/core/Graphics/CRenderItem.FileTexture.cpp b/Client/core/Graphics/CRenderItem.FileTexture.cpp index d8ccbddefdd..7f9d4aa148d 100644 --- a/Client/core/Graphics/CRenderItem.FileTexture.cpp +++ b/Client/core/Graphics/CRenderItem.FileTexture.cpp @@ -175,20 +175,20 @@ void CFileTextureItem::CreateUnderlyingData(const CPixels* pInPixels, bool bMipM D3DFORMAT D3DFormat = (D3DFORMAT)format; int iMipMaps = bMipMaps ? D3DX_DEFAULT : 1; - if (FAILED(D3DXCreateTextureFromFileInMemoryEx(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, - pPixels->GetData(), //__in LPCVOID pSrcData, - pPixels->GetSize(), //__in UINT SrcDataSize, - D3DX_DEFAULT, //__in UINT Width, - D3DX_DEFAULT, //__in UINT Height, - iMipMaps, //__in UINT MipLevels, - 0, //__in DWORD Usage, - D3DFormat, //__in D3DFORMAT Format, - D3DPOOL_MANAGED, //__in D3DPOOL Pool, - D3DX_DEFAULT, //__in DWORD Filter, - D3DX_DEFAULT, //__in DWORD MipFilter, - 0, //__in D3DCOLOR ColorKey, - &imageInfo, //__inout D3DXIMAGE_INFO *pSrcInfo, - NULL, //__out PALETTEENTRY *pPalette, + if (FAILED(D3DXCreateTextureFromFileInMemoryEx(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, + pPixels->GetData(), //__in LPCVOID pSrcData, + pPixels->GetSize(), //__in UINT SrcDataSize, + D3DX_DEFAULT, //__in UINT Width, + D3DX_DEFAULT, //__in UINT Height, + iMipMaps, //__in UINT MipLevels, + 0, //__in DWORD Usage, + D3DFormat, //__in D3DFORMAT Format, + D3DPOOL_MANAGED, //__in D3DPOOL Pool, + D3DX_DEFAULT, //__in DWORD Filter, + D3DX_DEFAULT, //__in DWORD MipFilter, + 0, //__in D3DCOLOR ColorKey, + &imageInfo, //__inout D3DXIMAGE_INFO *pSrcInfo, + NULL, //__out PALETTEENTRY *pPalette, (IDirect3DTexture9**)&m_pD3DTexture))) return; @@ -228,37 +228,37 @@ void CFileTextureItem::CreateUnderlyingData(bool bMipMaps, uint uiSizeX, uint ui if (textureType == D3DRTYPE_VOLUMETEXTURE) { - if (FAILED(D3DXCreateVolumeTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, - uiSizeX, //__in UINT Width, - uiSizeY, //__in UINT Height, - uiVolumeDepth, //__in UINT Depth, - iMipMaps, //__in UINT MipLevels, - 0, //__in DWORD Usage, - D3DFormat, //__in D3DFORMAT Format, - D3DPOOL_MANAGED, //__in D3DPOOL Pool, + if (FAILED(D3DXCreateVolumeTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, + uiSizeX, //__in UINT Width, + uiSizeY, //__in UINT Height, + uiVolumeDepth, //__in UINT Depth, + iMipMaps, //__in UINT MipLevels, + 0, //__in DWORD Usage, + D3DFormat, //__in D3DFORMAT Format, + D3DPOOL_MANAGED, //__in D3DPOOL Pool, (IDirect3DVolumeTexture9**)&m_pD3DTexture))) return; } else if (textureType == D3DRTYPE_CUBETEXTURE) { - if (FAILED(D3DXCreateCubeTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, - uiSizeX, //__in UINT Width, - iMipMaps, //__in UINT MipLevels, - 0, //__in DWORD Usage, - D3DFormat, //__in D3DFORMAT Format, - D3DPOOL_MANAGED, //__in D3DPOOL Pool, + if (FAILED(D3DXCreateCubeTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, + uiSizeX, //__in UINT Width, + iMipMaps, //__in UINT MipLevels, + 0, //__in DWORD Usage, + D3DFormat, //__in D3DFORMAT Format, + D3DPOOL_MANAGED, //__in D3DPOOL Pool, (IDirect3DCubeTexture9**)&m_pD3DTexture))) return; } else { - if (FAILED(D3DXCreateTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, - uiSizeX, //__in UINT Width, - uiSizeY, //__in UINT Height, - iMipMaps, //__in UINT MipLevels, - 0, //__in DWORD Usage, - D3DFormat, //__in D3DFORMAT Format, - D3DPOOL_MANAGED, //__in D3DPOOL Pool, + if (FAILED(D3DXCreateTexture(m_pDevice, //__in LPDIRECT3DDEVICE9 pDevice, + uiSizeX, //__in UINT Width, + uiSizeY, //__in UINT Height, + iMipMaps, //__in UINT MipLevels, + 0, //__in DWORD Usage, + D3DFormat, //__in D3DFORMAT Format, + D3DPOOL_MANAGED, //__in D3DPOOL Pool, (IDirect3DTexture9**)&m_pD3DTexture))) return; diff --git a/Client/core/Graphics/CRenderItem.Shader.cpp b/Client/core/Graphics/CRenderItem.Shader.cpp index b18e1b30b63..2510f6cfdc6 100644 --- a/Client/core/Graphics/CRenderItem.Shader.cpp +++ b/Client/core/Graphics/CRenderItem.Shader.cpp @@ -24,7 +24,7 @@ void CShaderItem::PostConstruct(CRenderItemManager* pManager, const SString& str float fPriority, float fMaxDistance, bool bLayered, bool bDebug, int iTypeMask, const EffectMacroList& macros) { m_fPriority = fPriority; - m_uiCreateTime = ms_uiCreateTimeCounter++; // Priority tie breaker + m_uiCreateTime = ms_uiCreateTimeCounter++; // Priority tie breaker m_fMaxDistanceSq = fMaxDistance * fMaxDistance; m_bLayered = bLayered; m_iTypeMask = iTypeMask; diff --git a/Client/core/Graphics/CRenderItemManager.cpp b/Client/core/Graphics/CRenderItemManager.cpp index d48415bdc68..2243c385adf 100644 --- a/Client/core/Graphics/CRenderItemManager.cpp +++ b/Client/core/Graphics/CRenderItemManager.cpp @@ -65,7 +65,7 @@ HRESULT CRenderItemManager::GetDeviceCooperativeLevel(const char* szContext, boo if (hrCoopLevel == D3D_OK) return hrCoopLevel; - if (bLogLost) // Expand (without log spam) later + if (bLogLost) // Expand (without log spam) later { (void)szContext; } @@ -200,7 +200,7 @@ CVectorGraphicItem* CRenderItemManager::CreateVectorGraphic(uint width, uint hei } UpdateMemoryUsage(); - + return pVectorItem; } @@ -226,7 +226,7 @@ CRenderTargetItem* CRenderItemManager::CreateRenderTarget(uint uiSizeX, uint uiS if (!pRenderTargetItem->IsValid()) { SAFE_RELEASE(pRenderTargetItem); - return nullptr; + return nullptr; } UpdateMemoryUsage(); @@ -252,7 +252,7 @@ CScreenSourceItem* CRenderItemManager::CreateScreenSource(uint uiSizeX, uint uiS if (!pScreenSourceItem->IsValid()) { SAFE_RELEASE(pScreenSourceItem); - return nullptr; + return nullptr; } UpdateMemoryUsage(); @@ -278,7 +278,7 @@ CWebBrowserItem* CRenderItemManager::CreateWebBrowser(uint uiSizeX, uint uiSizeY if (!pWebBrowserItem->IsValid()) { SAFE_RELEASE(pWebBrowserItem); - return nullptr; + return nullptr; } UpdateMemoryUsage(); @@ -307,7 +307,7 @@ CShaderItem* CRenderItemManager::CreateShader(const SString& strFile, const SStr if (!pShaderItem->IsValid()) { SAFE_RELEASE(pShaderItem); - return nullptr; + return nullptr; } return pShaderItem; @@ -331,7 +331,7 @@ CDxFontItem* CRenderItemManager::CreateDxFont(const SString& strFullFilePath, ui if (!pDxFontItem->IsValid()) { SAFE_RELEASE(pDxFontItem); - return nullptr; + return nullptr; } UpdateMemoryUsage(); @@ -357,7 +357,7 @@ CGuiFontItem* CRenderItemManager::CreateGuiFont(const SString& strFullFilePath, if (!pGuiFontItem->IsValid()) { SAFE_RELEASE(pGuiFontItem); - return nullptr; + return nullptr; } UpdateMemoryUsage(); @@ -450,8 +450,7 @@ void CRenderItemManager::UpdateBackBufferCopy() // Copy back buffer into our private render target D3DTEXTUREFILTERTYPE FilterType = D3DTEXF_LINEAR; - const HRESULT hr = - m_pDevice->StretchRect(pD3DBackBufferSurface, nullptr, m_pBackBufferCopy->m_pD3DRenderTargetSurface, nullptr, FilterType); + const HRESULT hr = m_pDevice->StretchRect(pD3DBackBufferSurface, nullptr, m_pBackBufferCopy->m_pD3DRenderTargetSurface, nullptr, FilterType); if (SUCCEEDED(hr)) { ++m_uiBackBufferCopyRevision; @@ -504,7 +503,7 @@ void CRenderItemManager::UpdateScreenSource(CScreenSourceItem* pScreenSourceItem if (m_pBackBufferCopy) { D3DTEXTUREFILTERTYPE FilterType = D3DTEXF_LINEAR; - m_pDevice->StretchRect(m_pBackBufferCopy->m_pD3DRenderTargetSurface, nullptr, pScreenSourceItem->m_pD3DRenderTargetSurface, nullptr, FilterType); + m_pDevice->StretchRect(m_pBackBufferCopy->m_pD3DRenderTargetSurface, nullptr, pScreenSourceItem->m_pD3DRenderTargetSurface, nullptr, FilterType); } } @@ -706,7 +705,7 @@ bool CRenderItemManager::ChangeRenderTarget(uint uiSizeX, uint uiSizeY, IDirect3 // Check if we need to change IDirect3DSurface9* pCurrentRenderTarget = nullptr; - HRESULT hrRenderTarget = m_pDevice->GetRenderTarget(0, &pCurrentRenderTarget); + HRESULT hrRenderTarget = m_pDevice->GetRenderTarget(0, &pCurrentRenderTarget); if (FAILED(hrRenderTarget) || !pCurrentRenderTarget) { SAFE_RELEASE(pCurrentRenderTarget); @@ -714,7 +713,7 @@ bool CRenderItemManager::ChangeRenderTarget(uint uiSizeX, uint uiSizeY, IDirect3 } IDirect3DSurface9* pCurrentZStencilSurface = nullptr; - HRESULT hrDepthStencil = m_pDevice->GetDepthStencilSurface(&pCurrentZStencilSurface); + HRESULT hrDepthStencil = m_pDevice->GetDepthStencilSurface(&pCurrentZStencilSurface); if (FAILED(hrDepthStencil) && hrDepthStencil != D3DERR_NOTFOUND) { SAFE_RELEASE(pCurrentRenderTarget); @@ -1002,7 +1001,7 @@ int CRenderItemManager::GetBitsPerPixel(D3DFORMAT Format) return 4; default: - return 32; // unknown - guess at 32 + return 32; // unknown - guess at 32 } } @@ -1229,7 +1228,7 @@ void CRenderItemManager::PreDrawWorld() assert(!m_pNonAADepthSurface2); const D3DPRESENT_PARAMETERS& pp = g_pDeviceState->CreationState.PresentationParameters; - HRESULT hr = D3D_OK; + HRESULT hr = D3D_OK; if (!m_bIsSwiftShader) { hr = m_pDevice->CreateRenderTarget(m_uiDefaultViewportSizeX, m_uiDefaultViewportSizeY, pp.BackBufferFormat, D3DMULTISAMPLE_NONE, 0, false, @@ -1324,7 +1323,7 @@ void CRenderItemManager::SaveReadableDepthBuffer() m_bUsingReadableDepthBuffer = false; const HRESULT hrDeviceState = GetDeviceCooperativeLevel("SaveReadableDepthBuffer"); - const bool bDeviceReady = (hrDeviceState == D3D_OK); + const bool bDeviceReady = (hrDeviceState == D3D_OK); // Ensure device operations are synchronous for GPU driver (especially Nvidia) compatibility if (bDeviceReady) @@ -1361,11 +1360,10 @@ void CRenderItemManager::SaveReadableDepthBuffer() SAFE_RELEASE(m_pSavedSceneDepthSurface); } } - + // Additional sync point for GPU driver // Force immediate execution of depth buffer state changes when we can safely begin a scene - if (bDeviceReady && !g_bInMTAScene.load(std::memory_order_acquire) && - !g_bInGTAScene.load(std::memory_order_acquire)) + if (bDeviceReady && !g_bInMTAScene.load(std::memory_order_acquire) && !g_bInGTAScene.load(std::memory_order_acquire)) { if (!BeginSceneWithoutProxy(m_pDevice, ESceneOwner::MTA)) { @@ -1389,7 +1387,7 @@ void CRenderItemManager::SaveReadableDepthBuffer() void CRenderItemManager::FlushNonAARenderTarget() { const HRESULT hrDeviceState = GetDeviceCooperativeLevel("FlushNonAARenderTarget"); - const bool bDeviceReady = (hrDeviceState == D3D_OK); + const bool bDeviceReady = (hrDeviceState == D3D_OK); if (m_pSavedSceneDepthSurface) { @@ -1491,8 +1489,7 @@ HRESULT CRenderItemManager::HandleStretchRect(IDirect3DSurface9* pSourceSurface, const HRESULT hrGetRenderTarget = m_pDevice->GetRenderTarget(0, &pActiveRenderTarget); if (SUCCEEDED(hrGetRenderTarget)) { - const HRESULT hrStretch = - m_pDevice->StretchRect(pActiveRenderTarget, pSourceRect, pDestSurface, pDestRect, (D3DTEXTUREFILTERTYPE)Filter); + const HRESULT hrStretch = m_pDevice->StretchRect(pActiveRenderTarget, pSourceRect, pDestSurface, pDestRect, (D3DTEXTUREFILTERTYPE)Filter); SAFE_RELEASE(pActiveRenderTarget); return hrStretch; } diff --git a/Client/core/Graphics/CRenderItemManager.h b/Client/core/Graphics/CRenderItemManager.h index 3a7925d6159..e5662205723 100644 --- a/Client/core/Graphics/CRenderItemManager.h +++ b/Client/core/Graphics/CRenderItemManager.h @@ -56,8 +56,8 @@ class CRenderItemManager : public CRenderItemManagerInterface virtual ERenderFormat GetDepthBufferFormat() { return m_depthBufferFormat; } virtual void SaveReadableDepthBuffer(); virtual void FlushNonAARenderTarget(); - virtual HRESULT HandleStretchRect(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, - CONST RECT* pDestRect, int Filter); + virtual HRESULT HandleStretchRect(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, CONST RECT* pDestRect, + int Filter); // CRenderItemManager void NotifyContructRenderItem(CRenderItem* pItem); diff --git a/Client/core/Graphics/CTileBatcher.cpp b/Client/core/Graphics/CTileBatcher.cpp index ced7c247fe7..c81393065c5 100644 --- a/Client/core/Graphics/CTileBatcher.cpp +++ b/Client/core/Graphics/CTileBatcher.cpp @@ -11,7 +11,7 @@ #include #include "CTileBatcher.h" -#define DEG2RAD(deg) ( (deg) * (6.2832f/360.f) ) +#define DEG2RAD(deg) ((deg) * (6.2832f / 360.f)) //////////////////////////////////////////////////////////////// // @@ -207,7 +207,7 @@ void CTileBatcher::Flush() pShaderInstance->m_pEffectWrap->ApplyMappedHandles(); // Do shader passes - DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE + DWORD dwFlags = D3DXFX_DONOTSAVESHADERSTATE; // D3DXFX_DONOTSAVE(SHADER|SAMPLER)STATE uint uiNumPasses = 0; pShaderInstance->m_pEffectWrap->Begin(&uiNumPasses, dwFlags, false); diff --git a/Client/core/Graphics/CTileBatcher.h b/Client/core/Graphics/CTileBatcher.h index b80b01fb8ff..74d24cc591c 100644 --- a/Client/core/Graphics/CTileBatcher.h +++ b/Client/core/Graphics/CTileBatcher.h @@ -17,22 +17,22 @@ struct SPDTVertex float u, v; }; -#define WRITE_PDT_VERTEX(buf,fX,fY,fZ,dwColor,fU,fV) \ - buf->x = fX; \ - buf->y = fY; \ - buf->z = fZ; \ - buf->color = dwColor; \ - buf->u = fU; \ - buf->v = fV; \ - buf++; +#define WRITE_PDT_VERTEX(buf, fX, fY, fZ, dwColor, fU, fV) \ + buf->x = fX; \ + buf->y = fY; \ + buf->z = fZ; \ + buf->color = dwColor; \ + buf->u = fU; \ + buf->v = fV; \ + buf++; -#define WRITE_QUAD_INDICES(buf,row0,row1) \ - *buf++ = (row0); \ - *buf++ = (row0) + 1; \ - *buf++ = (row1); \ - *buf++ = (row1); \ - *buf++ = (row0) + 1; \ - *buf++ = (row1) + 1; +#define WRITE_QUAD_INDICES(buf, row0, row1) \ + *buf++ = (row0); \ + *buf++ = (row0) + 1; \ + *buf++ = (row1); \ + *buf++ = (row1); \ + *buf++ = (row0) + 1; \ + *buf++ = (row1) + 1; // // Batches draws using the same material diff --git a/Client/core/Graphics/CVideoModeManager.cpp b/Client/core/Graphics/CVideoModeManager.cpp index e105544baa6..d951b193880 100644 --- a/Client/core/Graphics/CVideoModeManager.cpp +++ b/Client/core/Graphics/CVideoModeManager.cpp @@ -63,12 +63,12 @@ class CVideoModeManager : public CVideoModeManagerInterface CGameSettings* m_pGameSettings; ULONG m_ulMonitorCount; - int m_iCurrentVideoMode; // VideoMode this run + int m_iCurrentVideoMode; // VideoMode this run int m_iCurrentAdapter; bool m_bCurrentWindowed; bool m_bCurrentFullScreenMinimize; int m_iCurrentFullscreenStyle; - int m_iNextVideoMode; // VideoMode next run + int m_iNextVideoMode; // VideoMode next run int m_iNextAdapter; bool m_bNextWindowed; int m_iNextFullscreenStyle; @@ -254,7 +254,7 @@ void CVideoModeManager::PostReset(D3DPRESENT_PARAMETERS* pp) SetWindowLong(m_hDeviceWindow, GWL_STYLE, Style); - LONG ExStyle = 0; // WS_EX_WINDOWEDGE; + LONG ExStyle = 0; // WS_EX_WINDOWEDGE; SetWindowLong(m_hDeviceWindow, GWL_EXSTYLE, ExStyle); // Ensure client area of window is correct size @@ -628,7 +628,7 @@ bool CVideoModeManager::GameResMatchesCurrentAdapter() // Here we hope that the color depth is the same across all monitors HDC hdcPrimaryMonitor = GetDC(nullptr); - int iDesktopColorDepth = 32; // Default fallback + int iDesktopColorDepth = 32; // Default fallback if (hdcPrimaryMonitor) { diff --git a/Client/core/ServerBrowser/CServerBrowser.RemoteMasterServer.cpp b/Client/core/ServerBrowser/CServerBrowser.RemoteMasterServer.cpp index baf11b20987..b04002f230a 100644 --- a/Client/core/ServerBrowser/CServerBrowser.RemoteMasterServer.cpp +++ b/Client/core/ServerBrowser/CServerBrowser.RemoteMasterServer.cpp @@ -137,7 +137,7 @@ void CRemoteMasterServer::Refresh() if (pHTTP->QueueFile(m_strURL, NULL, this, &CRemoteMasterServer::StaticDownloadFinished, options)) { m_bPendingDownload = true; - AddRef(); // Keep alive + AddRef(); // Keep alive } else { @@ -184,7 +184,7 @@ void CRemoteMasterServer::StaticDownloadFinished(const SHttpDownloadResult& resu { CRemoteMasterServer* pRemoteMasterServer = (CRemoteMasterServer*)result.pObj; pRemoteMasterServer->DownloadFinished(result); - pRemoteMasterServer->Release(); // Unkeep alive + pRemoteMasterServer->Release(); // Unkeep alive } /////////////////////////////////////////////////////////////// @@ -351,8 +351,8 @@ bool CRemoteMasterServer::ParseListVer0(CServerListItemList& itemList) while (!stream.AtEnd(6) && usCount--) { - in_addr Address; // IP-address - unsigned short usQueryPort; // Query port + in_addr Address; // IP-address + unsigned short usQueryPort; // Query port stream.Read(Address.S_un.S_un_b.s_b1); stream.Read(Address.S_un.S_un_b.s_b2); @@ -448,12 +448,12 @@ bool CRemoteMasterServer::ParseListVer2(CServerListItemList& itemList) // Add all servers until we hit the count or run out of data while (!stream.AtEnd(6) && uiCount--) { - ushort usLength = 0; // Length of data for this server + ushort usLength = 0; // Length of data for this server stream.Read(usLength); uint uiSkipPos = stream.Tell() + usLength - 2; - in_addr Address; // IP-address - unsigned short usGamePort; // Game port + in_addr Address; // IP-address + unsigned short usGamePort; // Game port stream.Read(Address.S_un.S_addr); stream.Read(usGamePort); diff --git a/Client/core/ServerBrowser/CServerBrowser.cpp b/Client/core/ServerBrowser/CServerBrowser.cpp index 0b29e5669f4..a7633496c1e 100644 --- a/Client/core/ServerBrowser/CServerBrowser.cpp +++ b/Client/core/ServerBrowser/CServerBrowser.cpp @@ -23,37 +23,37 @@ extern CCore* g_pCore; template <> CServerBrowser* CSingleton::m_pSingleton = NULL; -#define SB_SPAN 0.85f // How much % of the screen the server browser should fill -#define SB_NAVBAR_SIZE_Y 40 // Navbar button size -#define SB_BUTTON_SIZE_X 26 -#define SB_BUTTON_SIZE_Y 26 -#define SB_SPACER 10 // Spacer between searchbar and navbar -#define SB_SMALL_SPACER 5 -#define SB_SEARCHBAR_COMBOBOX_SIZE_X 45 // Mow much the search type combobox occupies of searchbar +#define SB_SPAN 0.85f // How much % of the screen the server browser should fill +#define SB_NAVBAR_SIZE_Y 40 // Navbar button size +#define SB_BUTTON_SIZE_X 26 +#define SB_BUTTON_SIZE_Y 26 +#define SB_SPACER 10 // Spacer between searchbar and navbar +#define SB_SMALL_SPACER 5 +#define SB_SEARCHBAR_COMBOBOX_SIZE_X 45 // Mow much the search type combobox occupies of searchbar #define SB_SEARCHBAR_COMBOBOX_SIZE_Y 22 -#define SB_PLAYERLIST_SIZE_X 200 // Width of players list [NB. adjusted for low resolutions in CServerBrowser::CreateTab] -#define SB_BACK_BUTTON_SIZE_Y 40 // Size of the back butt -#define COMBOBOX_ARROW_SIZE_X 23 // Fixed CEGUI size of the 'combobox' arrow -#define TAB_SIZE_Y 25 // Fixed CEGUI size of the Tab in a tab panel +#define SB_PLAYERLIST_SIZE_X 200 // Width of players list [NB. adjusted for low resolutions in CServerBrowser::CreateTab] +#define SB_BACK_BUTTON_SIZE_Y 40 // Size of the back butt +#define COMBOBOX_ARROW_SIZE_X 23 // Fixed CEGUI size of the 'combobox' arrow +#define TAB_SIZE_Y 25 // Fixed CEGUI size of the Tab in a tab panel #define CONNECT_HISTORY_LIMIT 20 namespace { - constexpr unsigned long SERVER_BROWSER_CONFIG_SAVE_DELAY = 250UL; // Delay (ms) before committing queued config saves - constexpr unsigned long SERVER_BROWSER_CONFIG_SAVE_VISIBLE_GRACE = 5000UL; // Extra delay (ms) before writing while UI is visible - constexpr unsigned long SERVER_BROWSER_FILTER_UPDATE_DELAY = 50UL; // Delay (ms) before applying search filter changes - constexpr std::size_t SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE = 250U; // Servers processed per frame during deferred rebuild - constexpr std::size_t SERVER_BROWSER_SLOW_BATCH_MIN = 10; - constexpr std::size_t SERVER_BROWSER_SLOW_BATCH_DIVISOR = 6; - constexpr std::size_t SERVER_BROWSER_HIDDEN_REFRESH_MULTIPLIER = 6; - constexpr std::size_t SERVER_BROWSER_FAST_BATCH_MULTIPLIER = 2; - constexpr int SERVER_BROWSER_SPEED_SLOW = 0; - constexpr int SERVER_BROWSER_SPEED_DEFAULT = 1; - constexpr int SERVER_BROWSER_SPEED_FAST = 2; - constexpr unsigned long SERVER_BROWSER_LAZY_LAYOUT_INTERVAL_DEFAULT = 100UL; // Minimum ms between GUI ForceUpdate while refreshing - constexpr unsigned long SERVER_BROWSER_HIDDEN_REFRESH_DELAY = 200UL; // Delay (ms) before using hidden refresh acceleration - constexpr unsigned long SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS = 33; // Time budget per frame for refresh batching (increased for faster filtering) + constexpr unsigned long SERVER_BROWSER_CONFIG_SAVE_DELAY = 250UL; // Delay (ms) before committing queued config saves + constexpr unsigned long SERVER_BROWSER_CONFIG_SAVE_VISIBLE_GRACE = 5000UL; // Extra delay (ms) before writing while UI is visible + constexpr unsigned long SERVER_BROWSER_FILTER_UPDATE_DELAY = 50UL; // Delay (ms) before applying search filter changes + constexpr std::size_t SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE = 250U; // Servers processed per frame during deferred rebuild + constexpr std::size_t SERVER_BROWSER_SLOW_BATCH_MIN = 10; + constexpr std::size_t SERVER_BROWSER_SLOW_BATCH_DIVISOR = 6; + constexpr std::size_t SERVER_BROWSER_HIDDEN_REFRESH_MULTIPLIER = 6; + constexpr std::size_t SERVER_BROWSER_FAST_BATCH_MULTIPLIER = 2; + constexpr int SERVER_BROWSER_SPEED_SLOW = 0; + constexpr int SERVER_BROWSER_SPEED_DEFAULT = 1; + constexpr int SERVER_BROWSER_SPEED_FAST = 2; + constexpr unsigned long SERVER_BROWSER_LAZY_LAYOUT_INTERVAL_DEFAULT = 100UL; // Minimum ms between GUI ForceUpdate while refreshing + constexpr unsigned long SERVER_BROWSER_HIDDEN_REFRESH_DELAY = 200UL; // Delay (ms) before using hidden refresh acceleration + constexpr unsigned long SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS = 33; // Time budget per frame for refresh batching (increased for faster filtering) } // @@ -169,7 +169,7 @@ CServerBrowser::CServerBrowser() CVector2D resolution = CCore::GetSingleton().GetGUI()->GetResolution(); bool bCreateFrame = true; - if (resolution.fY <= 600) // Make our window bigger at small resolutions + if (resolution.fY <= 600) // Make our window bigger at small resolutions { m_WidgetSize = CVector2D(resolution.fX, resolution.fY); bCreateFrame = false; @@ -413,8 +413,8 @@ CServerBrowser::~CServerBrowser() if (m_pGeneralHelpWindow) { - m_pGeneralHelpWindow->SetVisible(false); - m_pGeneralHelpWindow->SetDeactivateHandler(GUI_CALLBACK()); // Avoid callbacks during destruction + m_pGeneralHelpWindow->SetVisible(false); + m_pGeneralHelpWindow->SetDeactivateHandler(GUI_CALLBACK()); // Avoid callbacks during destruction } if (m_pLockedIcon) @@ -619,7 +619,7 @@ void CServerBrowser::CreateTab(ServerBrowserType type, const char* szName) m_pServerList[type]->SetColumnWidth(m_hPing[type], 35, false); // We give Name and Gamemode 65% and 35% of the remaining length respectively - float fRemainingWidth = fWidth - 25 - 16 - 70 - 35 - 50; // All the fixed sizes plus 50 for the scrollbar + float fRemainingWidth = fWidth - 25 - 16 - 70 - 35 - 50; // All the fixed sizes plus 50 for the scrollbar m_pServerList[type]->SetColumnWidth(m_hGame[type], fRemainingWidth * 0.35, false); m_pServerList[type]->SetColumnWidth(m_hName[type], fRemainingWidth * 0.65, false); @@ -1027,13 +1027,13 @@ void CServerBrowser::StartRefresh(ServerBrowserType type) m_iSelectedServer[index] = -1; m_bPendingRefresh[index] = false; - + // Cancel any in-progress batch refresh to prevent iterator invalidation // when pList->Refresh() calls Clear() on the server list m_ListRefreshState[index].bActive = false; m_ListRefreshState[index].pList = nullptr; m_ListRefreshState[index].filterSnapshot.reset(); - + pList->Refresh(); m_bInitialRefreshDone[index] = true; } @@ -1148,7 +1148,7 @@ void CServerBrowser::SetVisible(bool bVisible) } } - bool bAutoRefresh = false; + bool bAutoRefresh = false; CVARS_GET("auto_refresh_browser", bAutoRefresh); ServerBrowserType currentType = GetCurrentServerBrowserType(); @@ -1280,7 +1280,7 @@ void CServerBrowser::UpdateHistoryList() CServerListItem* pServer = *it; if (pServer->strEndpoint == szAddress) { - if (pServer->strEndpoint != pServer->strName) // Do we have a real name for the server? + if (pServer->strEndpoint != pServer->strName) // Do we have a real name for the server? { for (std::size_t index = 0; index < std::size(m_pComboAddressHistory); ++index) { @@ -1295,11 +1295,11 @@ void CServerBrowser::UpdateHistoryList() void CServerBrowser::AddServerToList(CServerListItem* pServer, ServerBrowserType Type, const SFilterState& filterState) { - const bool bIncludeEmpty = filterState.includeEmpty; - const bool bIncludeFull = filterState.includeFull; - const bool bIncludeLocked = filterState.includeLocked; - const bool bIncludeOffline = filterState.includeOffline; - const bool bIncludeOtherVersions = filterState.includeOtherVersions; + const bool bIncludeEmpty = filterState.includeEmpty; + const bool bIncludeFull = filterState.includeFull; + const bool bIncludeLocked = filterState.includeLocked; + const bool bIncludeOffline = filterState.includeOffline; + const bool bIncludeOtherVersions = filterState.includeOtherVersions; const std::string& strServerSearchText = filterState.searchText; const int iCurrentSearchType = filterState.searchType; @@ -1354,9 +1354,9 @@ void CServerBrowser::AddServerToList(CServerListItem* pServer, ServerBrowserType bool bMasterServerOffline = (pServer->uiMasterServerSaysRestrictions == 0); bool bAllowLowQuality = bIsOffline || bMasterServerOffline; - if ((!bLowQuality || bAllowLowQuality) && (!bIsEmpty || bIncludeEmpty) && (!bIsFull || bIncludeFull) && - (!bIsLocked || bIncludeLocked) && (!bIsOffline || bIncludeOffline || bWasGoodNowFailing) && (!bIsOtherVersion || bIncludeOtherVersions) && - (!bIsBlockedVersion) && (!bIsBlockedServer) && (bServerSearchFound) && (!pServer->strVersion.empty() || bIsOffline)) + if ((!bLowQuality || bAllowLowQuality) && (!bIsEmpty || bIncludeEmpty) && (!bIsFull || bIncludeFull) && (!bIsLocked || bIncludeLocked) && + (!bIsOffline || bIncludeOffline || bWasGoodNowFailing) && (!bIsOtherVersion || bIncludeOtherVersions) && (!bIsBlockedVersion) && (!bIsBlockedServer) && + (bServerSearchFound) && (!pServer->strVersion.empty() || bIsOffline)) { bAddServer = true; } @@ -1396,7 +1396,8 @@ void CServerBrowser::AddServerToList(CServerListItem* pServer, ServerBrowserType const SString strVersionSortKey = pServer->strVersionSortKey + pServer->strTieBreakSortKey; const SString strVerified = pServer->isStatusVerified ? "" : "*"; - const SString strPlayers = (pServer->nMaxPlayers == 0) ? SStringX("0 / 0") : SString("%d / %d %s", pServer->nPlayers, pServer->nMaxPlayers, *strVerified); + const SString strPlayers = + (pServer->nMaxPlayers == 0) ? SStringX("0 / 0") : SString("%d / %d %s", pServer->nPlayers, pServer->nMaxPlayers, *strVerified); const SString strPlayersSortKey = SString("%04d-", pServer->nMaxPlayers ? pServer->nPlayers + 1 : 0) + pServer->strTieBreakSortKey; const SString strPing = pServer->nPing == 9999 ? SStringX("") : SString("%d", pServer->nPing); @@ -1609,7 +1610,7 @@ bool CServerBrowser::OnConnectClick(CGUIElement* pElement) strURI = "mtasa://" + strURI; SetAddressBarText(strURI); } - else if (strURI.substr(0, iProtocolEnd) != "mtasa") // Is it the mtasa:// protocol? Don't want noobs trying http etc + else if (strURI.substr(0, iProtocolEnd) != "mtasa") // Is it the mtasa:// protocol? Don't want noobs trying http etc { CCore::GetSingleton().ShowMessageBox(_("Unknown protocol") + _E("CC71"), _("Please use the mtasa:// protocol!"), MB_BUTTON_OK | MB_ICON_INFO); return true; @@ -1686,11 +1687,11 @@ bool CServerBrowser::ConnectToSelectedServer() // Password buffer SString strPassword = ""; - if (pServer->bPassworded) // The server is passworded, let's try and grab a saved password + if (pServer->bPassworded) // The server is passworded, let's try and grab a saved password { strPassword = GetServerPassword(pServer->GetEndpoint().c_str()); - if (strPassword.empty()) // No password could be found, popup password entry. + if (strPassword.empty()) // No password could be found, popup password entry. { if (CServerInfo* pServerInfo = CServerInfo::GetSingletonPtr()) { @@ -1726,12 +1727,10 @@ bool CServerBrowser::OnRefreshClick(CGUIElement* pElement) bool CServerBrowser::OnInfoClick(CGUIElement* pElement) { ServerBrowserType Type = GetCurrentServerBrowserType(); - + // First try to get the selected server from the list CServerListItem* pServer = FindSelectedServer(Type); - if (pServer && CServerListItem::StaticIsValid(pServer) && - pServer->Address.s_addr != 0 && pServer->usGamePort != 0 && - !pServer->strHost.empty()) + if (pServer && CServerListItem::StaticIsValid(pServer) && pServer->Address.s_addr != 0 && pServer->usGamePort != 0 && !pServer->strHost.empty()) { // Use the selected server's information directly const SString& strHost = pServer->strHost; @@ -1743,7 +1742,7 @@ bool CServerBrowser::OnInfoClick(CGUIElement* pElement) return true; } } - + // Fallback to using the address bar if no server is selected unsigned short usPort; std::string strHost, strNick, strPassword; @@ -1889,7 +1888,7 @@ bool CServerBrowser::OnHistoryDropListRemove(CGUIElement* pElementx) if (cursor.x < pos.fX + size.fX) if (cursor.y > pos.fY) if (cursor.y < pos.fY + size.fY) - m_bFocusTextEdit = true; // Focus the text edit next frame + m_bFocusTextEdit = true; // Focus the text edit next frame return true; } @@ -2016,9 +2015,8 @@ bool CServerBrowser::OnFilterChanged(CGUIElement* pElement) { for (std::size_t i = 0; i < std::size(m_pEditSearch); ++i) { - if (pElement == m_pEditSearch[i] || pElement == m_pIncludeEmpty[i] || pElement == m_pIncludeFull[i] || - pElement == m_pIncludeLocked[i] || (m_pIncludeOffline[i] && pElement == m_pIncludeOffline[i]) || - pElement == m_pIncludeOtherVersions[i]) + if (pElement == m_pEditSearch[i] || pElement == m_pIncludeEmpty[i] || pElement == m_pIncludeFull[i] || pElement == m_pIncludeLocked[i] || + (m_pIncludeOffline[i] && pElement == m_pIncludeOffline[i]) || pElement == m_pIncludeOtherVersions[i]) { detectedType = static_cast(i); break; @@ -2476,7 +2474,7 @@ void CServerBrowser::BeginServerListRefresh(ServerBrowserType type, bool bClearS state.bNeedsListClear = true; } // Check if sort order has changed - if so, need to restart the batch - unsigned int currentColumn = 0; + unsigned int currentColumn = 0; SortDirection currentDirection = SortDirections::None; m_pServerList[index]->GetSort(currentColumn, currentDirection); if (currentDirection != state.sortDirection || (currentDirection != SortDirections::None && currentColumn != state.uiSortColumn)) @@ -2523,7 +2521,7 @@ void CServerBrowser::BeginServerListRefresh(ServerBrowserType type, bool bClearS state.bClearServerList = bClearServerList; state.bNeedsListClear = state.pList->GetRevision() != m_pServerListRevision[index] || bClearServerList; state.bDidUpdateRowIndices = false; - unsigned int currentColumn = 0; + unsigned int currentColumn = 0; SortDirection currentDirection = SortDirections::None; m_pServerList[index]->GetSort(currentColumn, currentDirection); // If the UI gridlist currently reports no active sort, attempt to use @@ -2594,8 +2592,10 @@ bool CServerBrowser::ProcessServerListRefreshBatch(ServerBrowserType type, size_ const SFilterState& activeFilter = *state.filterSnapshot; const bool bHiddenBoost = ShouldUseHiddenRefreshAcceleration(); - const auto frameBudget = std::chrono::milliseconds{bHiddenBoost ? SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS * static_cast(SERVER_BROWSER_HIDDEN_REFRESH_MULTIPLIER) : SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS}; - const auto frameStart = std::chrono::steady_clock::now(); + const auto frameBudget = + std::chrono::milliseconds{bHiddenBoost ? SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS * static_cast(SERVER_BROWSER_HIDDEN_REFRESH_MULTIPLIER) + : SERVER_BROWSER_REFRESH_FRAME_BUDGET_MS}; + const auto frameStart = std::chrono::steady_clock::now(); size_t processed = 0; while (state.iterator != state.endIterator && processed < uiMaxSteps) @@ -2656,7 +2656,7 @@ bool CServerBrowser::ProcessServerListRefreshBatch(ServerBrowserType type, size_ if (processed > 0) { unsigned long ulNow = CClientTime::GetTime(); - auto layoutIntervalSetting = static_cast(SERVER_BROWSER_LAZY_LAYOUT_INTERVAL_DEFAULT); + auto layoutIntervalSetting = static_cast(SERVER_BROWSER_LAZY_LAYOUT_INTERVAL_DEFAULT); CVARS_GET("browser_layout_interval_ms", layoutIntervalSetting); const auto layoutInterval = std::chrono::milliseconds{layoutIntervalSetting}; if (ulNow >= m_ulNextListLayoutTime[index]) @@ -2673,9 +2673,8 @@ bool CServerBrowser::ProcessServerListRefreshBatch(ServerBrowserType type, size_ return false; } - const bool bIncludeOtherVersions = state.filterSnapshot ? state.filterSnapshot->includeOtherVersions : - (m_pIncludeOtherVersions[index] && - m_pIncludeOtherVersions[index]->GetSelected()); + const bool bIncludeOtherVersions = + state.filterSnapshot ? state.filterSnapshot->includeOtherVersions : (m_pIncludeOtherVersions[index] && m_pIncludeOtherVersions[index]->GetSelected()); if (bIncludeOtherVersions) m_pServerList[index]->SetColumnWidth(1, 34, false); else @@ -2771,12 +2770,11 @@ std::size_t CServerBrowser::GetListRefreshBatchSize() const switch (browserSpeed) { - case SERVER_BROWSER_SPEED_SLOW: // Very slow - return std::max(SERVER_BROWSER_SLOW_BATCH_MIN, - SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE / SERVER_BROWSER_SLOW_BATCH_DIVISOR); - case SERVER_BROWSER_SPEED_FAST: // Fast + case SERVER_BROWSER_SPEED_SLOW: // Very slow + return std::max(SERVER_BROWSER_SLOW_BATCH_MIN, SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE / SERVER_BROWSER_SLOW_BATCH_DIVISOR); + case SERVER_BROWSER_SPEED_FAST: // Fast return SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE * SERVER_BROWSER_FAST_BATCH_MULTIPLIER; - default: // Default + default: // Default return SERVER_BROWSER_FILTER_UPDATE_BATCH_SIZE; } } @@ -3003,7 +3001,7 @@ void CServerBrowser::UpdateSelectedServerPlayerList(ServerBrowserType Type) // Get number of players as defined in the gridlist const char* szPlayerCount = m_pServerList[Type]->GetItemText(iSelectedIndex, m_hPlayers[Type]); - int iNumPlayers = 0; + int iNumPlayers = 0; if (szPlayerCount && *szPlayerCount) { try @@ -3025,7 +3023,7 @@ void CServerBrowser::UpdateSelectedServerPlayerList(ServerBrowserType Type) // Find the selected server CServerListItem* const pServer = FindSelectedServer(Type); - const auto typeIndex = static_cast(Type); + const auto typeIndex = static_cast(Type); // If number of rows in player list is less than number of players in server item, if (iNumPlayers > iNumPlayerRows || (iNumPlayerRows == 1 && iNumPlayers == 1)) @@ -3056,11 +3054,10 @@ void CServerBrowser::UpdateSelectedServerPlayerList(ServerBrowserType Type) if (pServer && pServer->nPlayers && pServer->vecPlayers.empty()) { // Check if enough time has passed since last retry attempt - const auto now = std::chrono::milliseconds(CClientTime::GetTime()); + const auto now = std::chrono::milliseconds(CClientTime::GetTime()); constexpr auto PLAYER_LIST_RETRY_INTERVAL = std::chrono::milliseconds(2000); - if (pServer != m_pLastSelectedServerForPlayerList[typeIndex] || - now >= m_msLastPlayerListQueryRetryTime[typeIndex] + PLAYER_LIST_RETRY_INTERVAL) + if (pServer != m_pLastSelectedServerForPlayerList[typeIndex] || now >= m_msLastPlayerListQueryRetryTime[typeIndex] + PLAYER_LIST_RETRY_INTERVAL) { // New server or retry time has elapsed - send query m_pLastSelectedServerForPlayerList[typeIndex] = pServer; @@ -3156,13 +3153,13 @@ void CServerBrowser::UpdateFilteredPlayerCountStatus(ServerBrowserType Type, CSe if (uiVisibleTotalSlots > 0) { const SString strPlayersString = _tn("player", "players", uiVisiblePlayers); - SString strPlayersLine; + SString strPlayersLine; strPlayersLine.Format("%u %s %s ", uiVisiblePlayers, *strPlayersString, *_(("on"))); statusMessage += strPlayersLine; } const SString strServersString = _tn("server", "servers", uiVisibleServers); - SString strServersLine; + SString strServersLine; strServersLine.Format("%u %s", uiVisibleServers, *strServersString); statusMessage += strServersLine; @@ -3249,7 +3246,7 @@ bool CServerBrowser::OnServerListChangeRow(CGUIKeyEventArgs Args) if (iSelectedItem > 0) { m_pServerList[Type]->SetSelectedItem(iSelectedItem - 1, 1, true); - OnClick(m_pServerPlayerList[Type]); // hacky + OnClick(m_pServerPlayerList[Type]); // hacky } break; } @@ -3258,7 +3255,7 @@ bool CServerBrowser::OnServerListChangeRow(CGUIKeyEventArgs Args) if (iSelectedItem < (iMax - 1)) { m_pServerList[Type]->SetSelectedItem(iSelectedItem + 1, 1, true); - OnClick(m_pServerPlayerList[Type]); // hacky + OnClick(m_pServerPlayerList[Type]); // hacky } break; } @@ -3304,7 +3301,7 @@ bool CServerBrowser::OnServerListSortChanged(CGUIElement* pElement) { const auto i = std::distance(std::begin(m_pServerList), it); - unsigned int uiColumn = 0; + unsigned int uiColumn = 0; SortDirection dir = SortDirections::None; m_pServerList[i]->GetSort(uiColumn, dir); m_SortState[i] = {uiColumn, dir}; @@ -3325,7 +3322,7 @@ void CServerBrowser::UpdateSortState(ServerBrowserType type) if (index >= std::size(m_pServerList)) return; - unsigned int uiColumn = 0; + unsigned int uiColumn = 0; SortDirection dir = SortDirections::None; if (m_pServerList[index]) m_pServerList[index]->GetSort(uiColumn, dir); diff --git a/Client/core/ServerBrowser/CServerBrowser.h b/Client/core/ServerBrowser/CServerBrowser.h index a93c8e52b7d..a44f8753b96 100644 --- a/Client/core/ServerBrowser/CServerBrowser.h +++ b/Client/core/ServerBrowser/CServerBrowser.h @@ -14,13 +14,13 @@ class CServerBrowser; #pragma once // Amount of server lists/tabs (ServerBrowserType) -#define SERVER_BROWSER_TYPE_COUNT 4 +#define SERVER_BROWSER_TYPE_COUNT 4 // Amount of search types -#define SERVER_BROWSER_SEARCH_TYPE_COUNT 2 +#define SERVER_BROWSER_SEARCH_TYPE_COUNT 2 // Server browser list update interval (in ms) -#define SERVER_BROWSER_UPDATE_INTERVAL 1000 +#define SERVER_BROWSER_UPDATE_INTERVAL 1000 #include "CMainMenu.h" #include "CServerList.h" @@ -206,18 +206,18 @@ class CServerBrowser : public CSingleton enum { - DATA_PSERVER = 1, // Column which stores server pointer + DATA_PSERVER = 1, // Column which stores server pointer }; void CreateTab(ServerBrowserType type, const char* szName); void DeleteTab(ServerBrowserType type); - void UpdateServerList(ServerBrowserType Type, bool bClearServerList = false); - void UpdateHistoryList(); + void UpdateServerList(ServerBrowserType Type, bool bClearServerList = false); + void UpdateHistoryList(); [[nodiscard]] CServerList* GetServerList(ServerBrowserType Type); - void AddServerToList(CServerListItem* pServer, ServerBrowserType Type, const SFilterState& filterState); - bool RemoveSelectedServerFromRecentlyPlayedList(); - void UpdateFilteredPlayerCountStatus(ServerBrowserType Type, CServerList* pDataList = nullptr); + void AddServerToList(CServerListItem* pServer, ServerBrowserType Type, const SFilterState& filterState); + bool RemoveSelectedServerFromRecentlyPlayedList(); + void UpdateFilteredPlayerCountStatus(ServerBrowserType Type, CServerList* pDataList = nullptr); bool OnClick(CGUIElement* pElement); bool OnDoubleClick(CGUIElement* pElement); @@ -252,15 +252,15 @@ class CServerBrowser : public CSingleton void EnsureRefreshFor(ServerBrowserType type, bool bAutoRefreshEnabled, bool bForceOnFirstView); void StartRefresh(ServerBrowserType type); - void RequestConfigSave(bool bForceImmediate); - void ProcessPendingConfigSave(); - void RequestFilterRefresh(ServerBrowserType type, bool bImmediate); - void BeginServerListRefresh(ServerBrowserType type, bool bClearServerList, bool bForceRestart); - bool ProcessServerListRefreshBatch(ServerBrowserType type, std::size_t uiMaxSteps); - void ProcessPendingListRefreshes(); - void SuspendServerLists(); - void UpdateSortState(ServerBrowserType type); - void ApplyListSort(ServerBrowserType type, unsigned int uiColumn, SortDirection direction, bool bUpdateStoredState = false); + void RequestConfigSave(bool bForceImmediate); + void ProcessPendingConfigSave(); + void RequestFilterRefresh(ServerBrowserType type, bool bImmediate); + void BeginServerListRefresh(ServerBrowserType type, bool bClearServerList, bool bForceRestart); + bool ProcessServerListRefreshBatch(ServerBrowserType type, std::size_t uiMaxSteps); + void ProcessPendingListRefreshes(); + void SuspendServerLists(); + void UpdateSortState(ServerBrowserType type); + void ApplyListSort(ServerBrowserType type, unsigned int uiColumn, SortDirection direction, bool bUpdateStoredState = false); [[nodiscard]] bool IsListRefreshInProgress(ServerBrowserType type) const; [[nodiscard]] std::size_t GetListRefreshBatchSize() const; [[nodiscard]] std::size_t GetHiddenListRefreshBatchSize() const; @@ -282,15 +282,15 @@ class CServerBrowser : public CSingleton struct SListRefreshState { - bool bActive = false; - bool bClearServerList = false; - bool bNeedsListClear = false; - bool bDidUpdateRowIndices = false; - uint uiSortColumn = 0; - SortDirection sortDirection = SortDirections::None; - CServerList* pList = nullptr; - CServerListIterator iterator; - CServerListIterator endIterator; + bool bActive = false; + bool bClearServerList = false; + bool bNeedsListClear = false; + bool bDidUpdateRowIndices = false; + uint uiSortColumn = 0; + SortDirection sortDirection = SortDirections::None; + CServerList* pList = nullptr; + CServerListIterator iterator; + CServerListIterator endIterator; std::optional filterSnapshot; }; @@ -323,22 +323,22 @@ class CServerBrowser : public CSingleton CGUIWindow* m_pGeneralHelpWindow; long long m_llLastGeneralHelpTime; - bool m_bInitialRefreshDone[SERVER_BROWSER_TYPE_COUNT]; - bool m_bPendingRefresh[SERVER_BROWSER_TYPE_COUNT]; - bool m_bHistoryListDirty; - bool m_bPendingFilterUpdate[SERVER_BROWSER_TYPE_COUNT]; + bool m_bInitialRefreshDone[SERVER_BROWSER_TYPE_COUNT]; + bool m_bPendingRefresh[SERVER_BROWSER_TYPE_COUNT]; + bool m_bHistoryListDirty; + bool m_bPendingFilterUpdate[SERVER_BROWSER_TYPE_COUNT]; unsigned long m_ulNextFilterUpdateTime[SERVER_BROWSER_TYPE_COUNT]; SFilterState m_FilterState[SERVER_BROWSER_TYPE_COUNT]; SSortState m_SortState[SERVER_BROWSER_TYPE_COUNT]; - bool m_bPendingConfigSave; - unsigned long m_ulNextConfigSaveTime; + bool m_bPendingConfigSave; + unsigned long m_ulNextConfigSaveTime; SListRefreshState m_ListRefreshState[SERVER_BROWSER_TYPE_COUNT]; - unsigned long m_ulNextListLayoutTime[SERVER_BROWSER_TYPE_COUNT] = {}; - unsigned long m_ulHiddenRefreshBoostEnableTime = 0; - int m_iIgnoreSortCallbacks = 0; + unsigned long m_ulNextListLayoutTime[SERVER_BROWSER_TYPE_COUNT] = {}; + unsigned long m_ulHiddenRefreshBoostEnableTime = 0; + int m_iIgnoreSortCallbacks = 0; // Player list retry tracking - retry queries for servers that haven't responded with player data - CServerListItem* m_pLastSelectedServerForPlayerList[SERVER_BROWSER_TYPE_COUNT] = {}; + CServerListItem* m_pLastSelectedServerForPlayerList[SERVER_BROWSER_TYPE_COUNT] = {}; std::chrono::milliseconds m_msLastPlayerListQueryRetryTime[SERVER_BROWSER_TYPE_COUNT] = {}; }; diff --git a/Client/core/ServerBrowser/CServerCache.cpp b/Client/core/ServerBrowser/CServerCache.cpp index d3f8bba3270..2db9056ceb7 100644 --- a/Client/core/ServerBrowser/CServerCache.cpp +++ b/Client/core/ServerBrowser/CServerCache.cpp @@ -25,24 +25,24 @@ namespace struct CCachedInfo { - CValueInt nPlayers; // Current players - CValueInt nMaxPlayers; // Maximum players - CValueInt nPing; // Ping time - CValueInt bPassworded; // Password protected + CValueInt nPlayers; // Current players + CValueInt nMaxPlayers; // Maximum players + CValueInt nPing; // Ping time + CValueInt bPassworded; // Password protected CValueInt bKeepFlag; CValueInt uiCacheNoReplyCount; CValueInt usHttpPort; CValueInt ucSpecialFlags; - SString strName; // Server name - SString strGameMode; // Game mode - SString strMap; // Map name - SString strVersion; // Version + SString strName; // Server name + SString strGameMode; // Game mode + SString strMap; // Map name + SString strVersion; // Version }; // Variables used for saving the server cache file on a separate thread static bool ms_bIsSaving = false; static std::map ms_ServerCachedMap; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -289,7 +289,6 @@ void CServerCache::StaticSaveServerCache() CDataInfoSet dataSet; for (const auto& [key, info] : ms_ServerCachedMap) { - // Only exclude servers that have failed multiple consecutive query attempts if (info.uiCacheNoReplyCount > 3) continue; @@ -452,7 +451,7 @@ void CServerCache::GetServerListCachedInfo(CServerList* pList) CServerListItem* pItem = *it; if (!pItem) continue; - CCachedKey key; + CCachedKey key; key.ulIp = pItem->Address.s_addr; key.usGamePort = pItem->usGamePort; if (CCachedInfo* pInfo = MapFind(m_ServerCachedMap, key)) @@ -494,7 +493,6 @@ bool CServerCache::GenerateServerList(CServerList* pList, bool bAllowNonRespondi for (const auto& [key, info] : m_ServerCachedMap) { - // When master server is offline, include all cached servers. Otherwise exclude servers that // have consistently failed to respond (uiCacheNoReplyCount > 3). New servers without response data // should still be included since they may not have been queried yet. diff --git a/Client/core/ServerBrowser/CServerInfo.cpp b/Client/core/ServerBrowser/CServerInfo.cpp index fc70e72df6e..acef9c7c1e0 100644 --- a/Client/core/ServerBrowser/CServerInfo.cpp +++ b/Client/core/ServerBrowser/CServerInfo.cpp @@ -48,7 +48,7 @@ CServerInfo::CServerInfo() unsigned int LabelPosX = LabelTitlePosX + LabelTitleSizeX + 2; unsigned int LabelSizeX = INFO_WINDOW_DEFAULTWIDTH; unsigned int LabelSizeY = 15; - unsigned int DrawPosY = 10; // Start position + unsigned int DrawPosY = 10; // Start position // Server Name m_pServerNameLabelTitle = reinterpret_cast(pManager->CreateLabel(m_pWindow, _("Name:"))); m_pServerNameLabelTitle->SetPosition(CVector2D(LabelTitlePosX, DrawPosY += INFO_LABEL_VSPACING + LabelSizeY), false); @@ -178,7 +178,7 @@ CServerInfo::CServerInfo() m_pCheckboxAutojoin->AutoSize(m_pCheckboxAutojoin->GetText().c_str(), 20.0f, LabelSizeY); m_pCheckboxAutojoin->SetPosition( CVector2D((INFO_WINDOW_DEFAULTWIDTH - m_pCheckboxAutojoin->GetSize().fX) / 2, DrawPosY - INFO_WINDOW_VSPACING - LabelSizeY * 2), - false); // Horizontally center align + false); // Horizontally center align } CServerInfo::~CServerInfo() @@ -373,8 +373,7 @@ void CServerInfo::SetServerInformation(const char* szHost, unsigned short usPort strAddressHost = szHost; m_Server.strHost = strAddressHost; m_Server.strEndpoint = SString("%s:%u", *strAddressHost, m_Server.usGamePort); - m_Server.strEndpointSortKey = - SString("%02x%02x%02x%02x-%04x", addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3], m_Server.usGamePort); + m_Server.strEndpointSortKey = SString("%02x%02x%02x%02x-%04x", addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3], m_Server.usGamePort); if (pInitialServerListItem && CServerListItem::StaticIsValid(pInitialServerListItem)) { @@ -457,8 +456,7 @@ void CServerInfo::DoPulse() { ResetServerGUI(&m_Server); - if (m_pCurrentWindowType == eWindowTypes::SERVER_INFO_QUEUE && m_pCheckboxAutojoin->GetSelected() && - m_Server.nPlayers < m_Server.nMaxPlayers) + if (m_pCurrentWindowType == eWindowTypes::SERVER_INFO_QUEUE && m_pCheckboxAutojoin->GetSelected() && m_Server.nPlayers < m_Server.nMaxPlayers) { Connect(); return; @@ -535,12 +533,12 @@ void CServerInfo::Connect() std::string strPassword = m_strPassword; if (m_pCurrentWindowType == eWindowTypes::SERVER_INFO_PASSWORD) strPassword = m_pEnterPasswordEdit->GetText(); - else if (m_Server.bPassworded) // If we're not in a passworded window, but the server is passworded + else if (m_Server.bPassworded) // If we're not in a passworded window, but the server is passworded { // Try to grab a saved password strPassword = g_pCore->GetLocalGUI()->GetMainMenu()->GetServerBrowser()->GetServerPassword(m_Server.GetEndpoint().c_str()); - if (strPassword.empty()) // No password could be found, repopup the window in password mode. + if (strPassword.empty()) // No password could be found, repopup the window in password mode. { Show(eWindowTypes::SERVER_INFO_PASSWORD, m_Server.strHost.c_str(), m_Server.usGamePort, "", &m_Server); return; @@ -561,7 +559,7 @@ void CServerInfo::ResetServerGUI(CServerListItem* pServer) m_pGamemodeLabel->SetText(pServer->strGameMode.c_str()); m_pMapLabel->SetText(pServer->strMap.c_str()); m_pPlayersLabel->SetText(SString("%d / %d %s", pServer->nPlayers, pServer->nMaxPlayers, *strVerified).c_str()); - + m_pPasswordedLabel->SetText(pServer->bPassworded ? _("Yes") : _("No")); m_pLatencyLabel->SetText(SString("%i", pServer->nPing)); diff --git a/Client/core/ServerBrowser/CServerInfo.h b/Client/core/ServerBrowser/CServerInfo.h index a8de728e21d..4495310eb73 100644 --- a/Client/core/ServerBrowser/CServerInfo.h +++ b/Client/core/ServerBrowser/CServerInfo.h @@ -17,14 +17,14 @@ class CServerInfo; #define SERVER_UPDATE_INTERVAL 2500 // Dimensions for our window -#define INFO_WINDOW_DEFAULTWIDTH 370.0f +#define INFO_WINDOW_DEFAULTWIDTH 370.0f #define INFO_WINDOW_DEFAULTHEIGHT 400.0f #define INFO_WINDOW_HSPACING 20 -#define INFO_LABEL_VSPACING 0 +#define INFO_LABEL_VSPACING 0 #define INFO_WINDOW_VSPACING 10 -#define INFO_BUTTON_HEIGHT 25 -#define INFO_BUTTON_WIDTH 110 +#define INFO_BUTTON_HEIGHT 25 +#define INFO_BUTTON_WIDTH 110 #include "CServerList.h" #include "CSingleton.h" diff --git a/Client/core/ServerBrowser/CServerList.cpp b/Client/core/ServerBrowser/CServerList.cpp index 5fcc3d9912f..7a15b49b56f 100644 --- a/Client/core/ServerBrowser/CServerList.cpp +++ b/Client/core/ServerBrowser/CServerList.cpp @@ -126,10 +126,10 @@ void CServerList::Pulse() CServerListItem* pServer = *i; if (!pServer) continue; - uint uiPrevRevision = pServer->uiRevision; - std::string strResult = pServer->Pulse((int)(uiQueriesSent /*+ uiQueriesResent*/) < iNumQueries, bRemoveNonResponding); + uint uiPrevRevision = pServer->uiRevision; + std::string strResult = pServer->Pulse((int)(uiQueriesSent /*+ uiQueriesResent*/) < iNumQueries, bRemoveNonResponding); if (uiPrevRevision != pServer->uiRevision) - m_bUpdated |= true; // Flag GUI update + m_bUpdated |= true; // Flag GUI update if (strResult == "SentQuery") uiQueriesSent++; else if (strResult == "ResentQuery") @@ -194,7 +194,7 @@ bool CServerList::Remove(in_addr Address, ushort usGamePort) } void CServerList::Refresh() -{ // Assumes we already have a (saved) list of servers, so we just need to refresh +{ // Assumes we already have a (saved) list of servers, so we just need to refresh // Reinitialize each server list item for (auto it = m_Servers.begin(); it != m_Servers.end(); ++it) @@ -232,7 +232,7 @@ void CServerListInternet::SuspendActivity() } void CServerListInternet::Refresh() -{ // Gets the server list from the master server and refreshes +{ // Gets the server list from the master server and refreshes m_ElapsedTime.Reset(); // Load from cache first to ensure servers are always available instantly @@ -297,7 +297,7 @@ void CServerList::RetryNonRespondingServers() } void CServerListInternet::Pulse() -{ // We also need to take care of the master server list here +{ // We also need to take care of the master server list here unsigned long ulTime = m_ElapsedTime.Get(); if (m_iPass == 1) @@ -405,7 +405,7 @@ void CServerListLAN::Pulse() } void CServerListLAN::Refresh() -{ // Gets the server list from LAN-broadcasting servers +{ // Gets the server list from LAN-broadcasting servers m_iPass = 1; m_bUpdated = true; @@ -483,7 +483,7 @@ void CServerListLAN::Discover() } std::string CServerListItem::Pulse(bool bCanSendQuery, bool bRemoveNonResponding) -{ // Queries the server on it's query port (ASE protocol) +{ // Queries the server on it's query port (ASE protocol) // and returns whether it is done scanning if (bScanned || bSkipped) return "Done"; @@ -505,8 +505,8 @@ std::string CServerListItem::Pulse(bool bCanSendQuery, bool bRemoveNonResponding bMaybeOffline = false; SetDataQuality(SERVER_INFO_QUERY); uiCacheNoReplyCount = 0; - uiRevision++; // To flag browser gui update - GetServerCache()->SetServerCachedInfo(this); // Save parsed info in the cache + uiRevision++; // To flag browser gui update + GetServerCache()->SetServerCachedInfo(this); // Save parsed info in the cache return "ParsedQuery"; } @@ -544,18 +544,18 @@ std::string CServerListItem::Pulse(bool bCanSendQuery, bool bRemoveNonResponding if (bRemoveNonResponding) { - bMaybeOffline = true; // Flag to help 'Include offline' browser option + bMaybeOffline = true; // Flag to help 'Include offline' browser option // Don't zero nPlayers - preserve last known count from master list or previous query // Only zero vecPlayers since we don't have the actual player list vecPlayers.clear(); } - uiRevision++; // To flag browser gui update + uiRevision++; // To flag browser gui update if (uiQueryRetryCount < GetMaxRetries()) { // Try again uiQueryRetryCount++; - uiRevision++; // To flag browser gui update + uiRevision++; // To flag browser gui update if (GetDataQuality() > SERVER_INFO_ASE_0) GetServerCache()->SetServerCachedInfo(this); Query(); @@ -565,12 +565,12 @@ std::string CServerListItem::Pulse(bool bCanSendQuery, bool bRemoveNonResponding { // Give up queryReceiver.InvalidateSocket(); - uiRevision++; // To flag browser gui update + uiRevision++; // To flag browser gui update if (bRemoveNonResponding) { - uiCacheNoReplyCount++; // Keep a persistent count of failures. (When uiCacheNoReplyCount gets to 3, the server is removed from - // the Server Cache) + uiCacheNoReplyCount++; // Keep a persistent count of failures. (When uiCacheNoReplyCount gets to 3, the server is removed from + // the Server Cache) bSkipped = true; if (GetDataQuality() > SERVER_INFO_ASE_0) GetServerCache()->SetServerCachedInfo(this); @@ -595,7 +595,7 @@ unsigned short CServerListItem::GetQueryPort() } void CServerListItem::Query() -{ // Performs a query according to ASE protocol +{ // Performs a query according to ASE protocol queryReceiver.RequestQuery(Address, GetQueryPort()); } @@ -962,22 +962,22 @@ void CServerListItemList::Sort(unsigned int uiColumn, int direction) switch (uiColumn) { - case 1: // Version + case 1: // Version m_List.sort(asc ? CompareVersionAsc : CompareVersionDesc); break; - case 2: // Locked + case 2: // Locked m_List.sort(asc ? CompareLockedAsc : CompareLockedDesc); break; - case 3: // Name + case 3: // Name m_List.sort(asc ? CompareNameAsc : CompareNameDesc); break; - case 4: // Players + case 4: // Players m_List.sort(asc ? ComparePlayersAsc : ComparePlayersDesc); break; - case 5: // Ping + case 5: // Ping m_List.sort(asc ? ComparePingAsc : ComparePingDesc); break; - case 6: // Gamemode + case 6: // Gamemode m_List.sort(asc ? CompareGameModeAsc : CompareGameModeDesc); break; default: diff --git a/Client/core/ServerBrowser/CServerList.h b/Client/core/ServerBrowser/CServerList.h index 3125dd47b69..c1bd07a67f3 100644 --- a/Client/core/ServerBrowser/CServerList.h +++ b/Client/core/ServerBrowser/CServerList.h @@ -23,22 +23,22 @@ class CMasterServerManagerInterface; #include "CSingleton.h" // Master server list URL -#define SERVER_LIST_MASTER_URL "https://master.multitheftauto.com/ase/mta/" +#define SERVER_LIST_MASTER_URL "https://master.multitheftauto.com/ase/mta/" // Query response data buffer -#define SERVER_LIST_QUERY_BUFFER 4096 +#define SERVER_LIST_QUERY_BUFFER 4096 // Master server list timeout (in ms) -#define SERVER_LIST_MASTER_TIMEOUT 10000 +#define SERVER_LIST_MASTER_TIMEOUT 10000 // Maximum amount of server queries per pulse (so the list gradually streams in) -#define SERVER_LIST_QUERIES_PER_PULSE 2 +#define SERVER_LIST_QUERIES_PER_PULSE 2 // LAN packet broadcasting interval (in ms) -#define SERVER_LIST_BROADCAST_REFRESH 2000 +#define SERVER_LIST_BROADCAST_REFRESH 2000 // Timeout for one server in the server list to respond to a query (in ms) -#define SERVER_LIST_ITEM_TIMEOUT 8000 +#define SERVER_LIST_ITEM_TIMEOUT 8000 enum { @@ -177,16 +177,16 @@ class CServerListItem void CancelPendingQuery(); unsigned short GetQueryPort(); - in_addr AddressCopy; // Copy to ensure it doesn't get changed without us knowing + in_addr AddressCopy; // Copy to ensure it doesn't get changed without us knowing unsigned short usGamePortCopy; - in_addr Address; // IP-address - unsigned short usGamePort; // Game port - unsigned short nPlayers; // Current players - unsigned short nMaxPlayers; // Maximum players - unsigned short nPing; // Ping time - bool isStatusVerified; // Ping status verified - bool bPassworded; // Password protected - bool bSerials; // Serial verification on + in_addr Address; // IP-address + unsigned short usGamePort; // Game port + unsigned short nPlayers; // Current players + unsigned short nMaxPlayers; // Maximum players + unsigned short nPing; // Ping time + bool isStatusVerified; // Ping status verified + bool bPassworded; // Password protected + bool bSerials; // Serial verification on bool bScanned; bool bSkipped; bool bMaybeOffline; @@ -199,24 +199,24 @@ class CServerListItem bool bKeepFlag; int iRowIndex[SERVER_BROWSER_TYPE_COUNT]; // Row index for each server browser tab - placed here for cache locality - SString strGameName; // Game name. Always 'mta' - SString strVersion; // Game version - SString strName; // Server name - SString strSearchableName; // Server name to use for searches - SString strHost; // Server host as IP - SString strHostName; // Server host as name - SString strGameMode; // Gamemode - SString strMap; // Map name - SString strEndpoint; // IP:port as a string - - int m_iBuildType; // 9=release - int m_iBuildNumber; // 00000 and up + SString strGameName; // Game name. Always 'mta' + SString strVersion; // Game version + SString strName; // Server name + SString strSearchableName; // Server name to use for searches + SString strHost; // Server host as IP + SString strHostName; // Server host as name + SString strGameMode; // Gamemode + SString strMap; // Map name + SString strEndpoint; // IP:port as a string + + int m_iBuildType; // 9=release + int m_iBuildNumber; // 00000 and up ushort m_usHttpPort; uchar m_ucSpecialFlags; - SString strNameSortKey; // Server name as a sortable string - SString strVersionSortKey; // Game version as a sortable string - SString strEndpointSortKey; // IP:port as a sortable string + SString strNameSortKey; // Server name as a sortable string + SString strVersionSortKey; // Game version as a sortable string + SString strEndpointSortKey; // IP:port as a sortable string uint uiTieBreakPosition; SString strTieBreakSortKey; diff --git a/Client/core/StackTraceHelpers.h b/Client/core/StackTraceHelpers.h index 23d1ddb2105..ef07ddac82c 100644 --- a/Client/core/StackTraceHelpers.h +++ b/Client/core/StackTraceHelpers.h @@ -76,7 +76,7 @@ namespace StackTraceHelpers return 0; MEMORY_BASIC_INFORMATION mbi{}; - const auto addr32 = static_cast(address); + const auto addr32 = static_cast(address); if (VirtualQuery(reinterpret_cast(static_cast(addr32)), &mbi, sizeof(mbi)) == 0) [[unlikely]] return 0; @@ -90,18 +90,10 @@ namespace StackTraceHelpers { if (useDbgHelp) { - return StackWalkRoutines{ - .readMemory = &LocalReadProcessMemory, - .functionTableAccess = SymFunctionTableAccess64, - .moduleBase = SymGetModuleBase64 - }; + return StackWalkRoutines{.readMemory = &LocalReadProcessMemory, .functionTableAccess = SymFunctionTableAccess64, .moduleBase = SymGetModuleBase64}; } - return StackWalkRoutines{ - .readMemory = &LocalReadProcessMemory, - .functionTableAccess = nullptr, - .moduleBase = &LocalGetModuleBase - }; + return StackWalkRoutines{.readMemory = &LocalReadProcessMemory, .functionTableAccess = nullptr, .moduleBase = &LocalGetModuleBase}; } struct ModuleAddressInfo @@ -142,15 +134,10 @@ namespace StackTraceHelpers } const std::string_view modulePathView{modulePath.data(), pathLen}; - const auto lastSlash = modulePathView.find_last_of("\\/"); - const std::string_view moduleName = (lastSlash != std::string_view::npos) - ? modulePathView.substr(lastSlash + 1) - : modulePathView; - - ModuleAddressInfo info{ - .name = std::string{moduleName}, - .base = static_cast(reinterpret_cast(mbi.AllocationBase)) - }; + const auto lastSlash = modulePathView.find_last_of("\\/"); + const std::string_view moduleName = (lastSlash != std::string_view::npos) ? modulePathView.substr(lastSlash + 1) : modulePathView; + + ModuleAddressInfo info{.name = std::string{moduleName}, .base = static_cast(reinterpret_cast(mbi.AllocationBase))}; return info; } @@ -188,4 +175,4 @@ namespace StackTraceHelpers return ""; } } -} // namespace StackTraceHelpers +} diff --git a/Client/core/StdInc.h b/Client/core/StdInc.h index 59978d2f207..ed062056554 100644 --- a/Client/core/StdInc.h +++ b/Client/core/StdInc.h @@ -1,7 +1,7 @@ // Pragmas -#pragma warning (disable:4995) -#pragma warning (disable:4244) +#pragma warning(disable : 4995) +#pragma warning(disable : 4244) // #define WIN32_LEAN_AND_MEAN #include diff --git a/Client/core/resource.h b/Client/core/resource.h index ffb6873a394..e4d6b6aad53 100644 --- a/Client/core/resource.h +++ b/Client/core/resource.h @@ -2,15 +2,15 @@ // Microsoft Visual C++ generated include file. // Used by core.rc // -#define IDI_ICON1 101 +#define IDI_ICON1 101 // Next default values for new objects // #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif + #ifndef APSTUDIO_READONLY_SYMBOLS + #define _APS_NEXT_RESOURCE_VALUE 102 + #define _APS_NEXT_COMMAND_VALUE 40001 + #define _APS_NEXT_CONTROL_VALUE 1001 + #define _APS_NEXT_SYMED_VALUE 101 + #endif #endif diff --git a/Client/game_sa/C3DMarkerSA.h b/Client/game_sa/C3DMarkerSA.h index 3807252b750..3d606ff170b 100644 --- a/Client/game_sa/C3DMarkerSA.h +++ b/Client/game_sa/C3DMarkerSA.h @@ -17,33 +17,33 @@ class C3DMarkerSAInterface { public: - CMatrix_Padded m_mat; // local space to world space transform // 0 - DWORD dwPad, dwPad2; // not sure why we need these, it appears to be this way though (eAi) // 64/68 - RpClump* m_pRwObject; // 72 - DWORD* m_pMaterial; // 76 + CMatrix_Padded m_mat; // local space to world space transform // 0 + DWORD dwPad, dwPad2; // not sure why we need these, it appears to be this way though (eAi) // 64/68 + RpClump* m_pRwObject; // 72 + DWORD* m_pMaterial; // 76 - WORD m_nType; // 80 - bool m_bIsUsed; // has this marker been allocated this frame? // 82 - DWORD m_nIdentifier; // 84 + WORD m_nType; // 80 + bool m_bIsUsed; // has this marker been allocated this frame? // 82 + DWORD m_nIdentifier; // 84 - DWORD rwColour; // 88 - WORD m_nPulsePeriod; // 92 - short m_nRotateRate; // deg per frame (in either direction) // 94 - DWORD m_nStartTime; // 96 - float m_fPulseFraction; // 100 - float m_fStdSize; // 104 - float m_fSize; // 108 - float m_fBrightness; // 112 - float m_fCameraRange; // 116 + DWORD rwColour; // 88 + WORD m_nPulsePeriod; // 92 + short m_nRotateRate; // deg per frame (in either direction) // 94 + DWORD m_nStartTime; // 96 + float m_fPulseFraction; // 100 + float m_fStdSize; // 104 + float m_fSize; // 108 + float m_fBrightness; // 112 + float m_fCameraRange; // 116 - CVector m_normal; // Normal of the object point at // 120 + CVector m_normal; // Normal of the object point at // 120 // the following variables remember the last time we read the heigh of the // map. Using this we don't have to do this every frame and we can still have moving markers. - WORD m_LastMapReadX, m_LastMapReadY; // 132 / 134 - float m_LastMapReadResultZ; // 136 - float m_roofHeight; // 140 - CVector m_lastPosition; // 144 - DWORD m_OnScreenTestTime; // time last screen check was done // 156 + WORD m_LastMapReadX, m_LastMapReadY; // 132 / 134 + float m_LastMapReadResultZ; // 136 + float m_roofHeight; // 140 + CVector m_lastPosition; // 144 + DWORD m_OnScreenTestTime; // time last screen check was done // 156 }; class C3DMarkerSA : public C3DMarker @@ -60,12 +60,12 @@ class C3DMarkerSA : public C3DMarker void SetMatrix(CMatrix* pMatrix); void SetPosition(CVector* vecPosition); CVector* GetPosition(); - DWORD GetType(); // need enum? - void SetType(DWORD dwType); // doesn't work propperly (not virtualed) + DWORD GetType(); // need enum? + void SetType(DWORD dwType); // doesn't work propperly (not virtualed) bool IsActive(); DWORD GetIdentifier(); SharedUtil::SColor GetColor(); - void SetColor(const SharedUtil::SColor color); // actually BGRA + void SetColor(const SharedUtil::SColor color); // actually BGRA void SetPulsePeriod(WORD wPulsePeriod); void SetRotateRate(short RotateRate); float GetSize(); @@ -73,7 +73,7 @@ class C3DMarkerSA : public C3DMarker float GetBrightness(); void SetBrightness(float fBrightness); void SetCameraRange(float fCameraRange); - void SetPulseFraction(float fPulseFraction); // doesn't work propperly (not virtualed) + void SetPulseFraction(float fPulseFraction); // doesn't work propperly (not virtualed) float GetPulseFraction(); void Disable(); void Reset(); diff --git a/Client/game_sa/C3DMarkersSA.cpp b/Client/game_sa/C3DMarkersSA.cpp index 6ea73c83101..a40c2055526 100644 --- a/Client/game_sa/C3DMarkersSA.cpp +++ b/Client/game_sa/C3DMarkersSA.cpp @@ -104,7 +104,7 @@ C3DMarker* C3DMarkersSA::FindMarker(DWORD Identifier) void C3DMarkersSA::ReinitMarkers() { - using Function_ShutdownMarkers = void(__cdecl *)(); + using Function_ShutdownMarkers = void(__cdecl*)(); auto shutdownMarkers = reinterpret_cast(0x722710); using Function_InitMarkers = void(__cdecl*)(); diff --git a/Client/game_sa/C3DMarkersSA.h b/Client/game_sa/C3DMarkersSA.h index 13f8dd21dde..0387026789d 100644 --- a/Client/game_sa/C3DMarkersSA.h +++ b/Client/game_sa/C3DMarkersSA.h @@ -14,10 +14,10 @@ #include #include "C3DMarkerSA.h" -#define FUNC_PlaceMarker 0x725120 -#define ARRAY_3D_MARKERS 0xC7DD58 +#define FUNC_PlaceMarker 0x725120 +#define ARRAY_3D_MARKERS 0xC7DD58 -#define MAX_3D_MARKERS 32 +#define MAX_3D_MARKERS 32 class C3DMarkersSA : public C3DMarkers { diff --git a/Client/game_sa/CAEAudioHardwareSA.h b/Client/game_sa/CAEAudioHardwareSA.h index 8f6210d9945..8ab5f343dae 100644 --- a/Client/game_sa/CAEAudioHardwareSA.h +++ b/Client/game_sa/CAEAudioHardwareSA.h @@ -13,10 +13,10 @@ #include -#define FUNC_CAEAudioHardware__IsSoundBankLoaded 0x4D88C0 -#define FUNC_CAEAudioHardware__LoadSoundBank 0x4D88A0 +#define FUNC_CAEAudioHardware__IsSoundBankLoaded 0x4D88C0 +#define FUNC_CAEAudioHardware__LoadSoundBank 0x4D88A0 -#define CLASS_CAEAudioHardware 0xB5F8B8 +#define CLASS_CAEAudioHardware 0xB5F8B8 class CAEAudioHardwareSAInterface { diff --git a/Client/game_sa/CAERadioTrackManagerSA.h b/Client/game_sa/CAERadioTrackManagerSA.h index 00f66a7f0a0..c86423e1a6b 100644 --- a/Client/game_sa/CAERadioTrackManagerSA.h +++ b/Client/game_sa/CAERadioTrackManagerSA.h @@ -13,15 +13,15 @@ #include -#define FUNC_GetCurrentRadioStationID 0x4E83F0 -#define FUNC_IsVehicleRadioActive 0x4E9800 -#define FUNC_GetRadioStationName 0x4E9E10 -#define FUNC_IsRadioOn 0x4E8350 -#define FUNC_SetBassSetting 0x4E82F0 -#define FUNC_Reset 0x4E7F80 -#define FUNC_StartRadio 0x4EB3C0 +#define FUNC_GetCurrentRadioStationID 0x4E83F0 +#define FUNC_IsVehicleRadioActive 0x4E9800 +#define FUNC_GetRadioStationName 0x4E9E10 +#define FUNC_IsRadioOn 0x4E8350 +#define FUNC_SetBassSetting 0x4E82F0 +#define FUNC_Reset 0x4E7F80 +#define FUNC_StartRadio 0x4EB3C0 -#define CLASS_CAERadioTrackManager 0x8CB6F8 +#define CLASS_CAERadioTrackManager 0x8CB6F8 enum class eRadioTrackMode { @@ -119,5 +119,5 @@ class CAERadioTrackManagerSA : public CAERadioTrackManager void SetBassSetting(DWORD dwBass); void Reset(); void StartRadio(BYTE bStationID, BYTE bUnknown); - bool IsStationLoading() const; + bool IsStationLoading() const; }; diff --git a/Client/game_sa/CAESoundManagerSA.h b/Client/game_sa/CAESoundManagerSA.h index 882929d410d..eab09198450 100644 --- a/Client/game_sa/CAESoundManagerSA.h +++ b/Client/game_sa/CAESoundManagerSA.h @@ -13,24 +13,24 @@ #include #include "CAudioEngineSA.h" -#define CLASS_CAESoundManager 0xB62CB0 +#define CLASS_CAESoundManager 0xB62CB0 class CAESoundManagerSAInterface { - int16_t m_wNumAvailableChannels; // + 0x0000 // = CAEAudioHardware::GetNumAvailableChannels(...), [10, 300] - int16_t m_wChannel; // + 0x0002 // = CAEAudioHardware::AllocateChannels(...), could be -1 - CAESound m_aSound[300]; // + 0x0004 - int16_t* m_aChannelSoundTable; // + 0x87F4 // = new short[m_wNumAvailableChannels] - int16_t* m_aChannelSoundPosition; // + 0x87F8 // = new short[m_wNumAvailableChannels] - int16_t* m_aChannelSoundUncancellable; // + 0x87FC // = new short[m_wNumAvailableChannels] - int16_t m_wSoundLength[300]; // + 0x8800 // = -1 (0xFFFF) when initialized - int16_t m_wSoundLoopStartTime[300]; // + 0x8A58 // = -1 (0xFFFF) when initialized - uint32_t m_uiUpdateTime; // + 0x8CB0 - int8_t m_bPauseTimeInUse; // + 0x8CB4 - int8_t m_bPaused; // + 0x8CB5 + int16_t m_wNumAvailableChannels; // + 0x0000 // = CAEAudioHardware::GetNumAvailableChannels(...), [10, 300] + int16_t m_wChannel; // + 0x0002 // = CAEAudioHardware::AllocateChannels(...), could be -1 + CAESound m_aSound[300]; // + 0x0004 + int16_t* m_aChannelSoundTable; // + 0x87F4 // = new short[m_wNumAvailableChannels] + int16_t* m_aChannelSoundPosition; // + 0x87F8 // = new short[m_wNumAvailableChannels] + int16_t* m_aChannelSoundUncancellable; // + 0x87FC // = new short[m_wNumAvailableChannels] + int16_t m_wSoundLength[300]; // + 0x8800 // = -1 (0xFFFF) when initialized + int16_t m_wSoundLoopStartTime[300]; // + 0x8A58 // = -1 (0xFFFF) when initialized + uint32_t m_uiUpdateTime; // + 0x8CB0 + int8_t m_bPauseTimeInUse; // + 0x8CB4 + int8_t m_bPaused; // + 0x8CB5 int8_t field_8CB6; int8_t field_8CB7; - uint32_t m_uiPauseUpdateTime; // + 0x8CB8 + uint32_t m_uiPauseUpdateTime; // + 0x8CB8 }; static_assert(sizeof(CAESoundManagerSAInterface) == 0x8CBC, "Invalid size for CAESoundManagerSAInterface"); diff --git a/Client/game_sa/CAEVehicleAudioEntitySA.h b/Client/game_sa/CAEVehicleAudioEntitySA.h index 5294597b029..b9dc54e9605 100644 --- a/Client/game_sa/CAEVehicleAudioEntitySA.h +++ b/Client/game_sa/CAEVehicleAudioEntitySA.h @@ -15,11 +15,11 @@ #include #include "CAudioEngineSA.h" -#define FUNC_CAEVehicleAudioEntity__JustGotInVehicleAsDriver 0x4F5700 -#define FUNC_CAEVehicleAudioEntity__TurnOnRadioForVehicle 0x4F5B20 -#define FUNC_CAEVehicleAudioEntity__JustGotOutOfVehicleAsDriver 0x4FCF40 -#define FUNC_CAEVehicleAudioEntity__ProcessAIProp 0x4FDFD0 -#define FUNC_CAEVehicleAudioEntity__ProcessAIHeli 0x4FEE20 +#define FUNC_CAEVehicleAudioEntity__JustGotInVehicleAsDriver 0x4F5700 +#define FUNC_CAEVehicleAudioEntity__TurnOnRadioForVehicle 0x4F5B20 +#define FUNC_CAEVehicleAudioEntity__JustGotOutOfVehicleAsDriver 0x4FCF40 +#define FUNC_CAEVehicleAudioEntity__ProcessAIProp 0x4FDFD0 +#define FUNC_CAEVehicleAudioEntity__ProcessAIHeli 0x4FEE20 class CVehicleSAInterface; @@ -53,83 +53,83 @@ static_assert(sizeof(CAETwinLoopSoundEntity) == 0xA8, "Invalid size for CAETwinL class CAEVehicleAudioEntitySAInterface : public CAEAudioEntity { public: - void AddAudioEvent(int eventId, float volume) { ((void(__thiscall*)(CAEVehicleAudioEntitySAInterface*, int, float))0x4F6420)(this, eventId, volume); } - bool TerminateAudio() { return ((bool(__thiscall*)(CAEVehicleAudioEntitySAInterface*))0x4FB8C0)(this); } - bool SoundJoin() { return ((bool(__thiscall*)(CAEVehicleAudioEntitySAInterface*))0x4F5700)(this); } + void AddAudioEvent(int eventId, float volume) { ((void(__thiscall*)(CAEVehicleAudioEntitySAInterface*, int, float))0x4F6420)(this, eventId, volume); } + bool TerminateAudio() { return ((bool(__thiscall*)(CAEVehicleAudioEntitySAInterface*))0x4FB8C0)(this); } + bool SoundJoin() { return ((bool(__thiscall*)(CAEVehicleAudioEntitySAInterface*))0x4F5700)(this); } int16_t InitAudio(CVehicleSAInterface* vehicle) { return ((int16_t(__thiscall*)(CAEVehicleAudioEntitySAInterface*, CVehicleSAInterface*))0x4F7670)(this, vehicle); } - short unk1; // +124 - char unk2[2]; // +126 - tVehicleAudioSettings m_nSettings; // +128 - bool m_bEnabled; // +164 - bool m_bPlayerDriver; // +165 - bool m_bPlayerPassenger; // +166 - bool m_bVehicleRadioPaused; // +167 - bool m_bSoundsStopped; // +168 - char m_nEngineState; // +169 - char unk3; // +170 - char unk4; // +171 - int unk5; // +172 - bool m_bInhibitAccForLowSpeed; // +176 - char unk6; // +177 - short m_wRainDropCounter; // +178 - short unk7; // +180 - char pad1[2]; // +182 - int unk8; // +184 - char unk9; // +188 - bool m_bDisableHeliEngineSounds; // +189 - char unk10; // +190 - bool m_bSirenOrAlarmPlaying; // +191 - bool m_bHornPlaying; // +192 - char pad2[3]; // +193 - float m_fSirenVolume; // +196 - bool m_bModelWithSiren; // +200 - char pad3[3]; // +201 - unsigned int m_dwBoatHitWaveLastPlayedTime; // +204 - unsigned int m_dwTimeToInhibitAcc; // +208 - unsigned int m_dwTimeToInhibitCrz; // +212 - float m_fGeneralVehicleSoundVolume; // +216 - short m_wEngineDecelerateSoundBankId; // +220 - short m_wEngineAccelerateSoundBankId; // +222 - short m_wEngineBankSlotId; // +224 - short unk11; // +226 - tVehicleSound m_aEngineSounds[12]; // +228 - int unk12; // +324 - short unk13; // +328 - short unk14; // +330 - short unk15; // +332 - short unk16; // +334 - int unk17; // some time in ms (@0x4F5638) // +336 - short unk18; // +340 - short m_wSkidSoundType; // +342 - CAESound* unk19; // +344 - short m_wRoadNoiseSoundType; // +348 - char pad4[2]; // +350 - CAESound* m_pRoadNoiseSound; // +352 - short m_wFlatTyreSoundType; // +356 - char pad5[2]; // +358 - CAESound* m_pFlatTyreSound; // +360 - short m_wReverseGearSoundType; // +364 - char pad6[2]; // +366 - CAESound* m_pReverseGearSound; // +368 - char pad7[4]; // +372 - CAESound* m_pHornTonSound; // +376 - CAESound* m_pSirenSound; // +380 - CAESound* m_pPoliceSirenSound; // +384 - CAETwinLoopSoundEntity m_nTwinLoopSoundEntity; // +388 - float unk20; // +556 - float unk21; // +560 - float unk22; // +564 - float unk23; // +568 - float unk24; // +572 - int unk25; // +576 - bool m_bNitroSoundPresent; // +580 - char unk26; // +581 - float unk27; // +582 + short unk1; // +124 + char unk2[2]; // +126 + tVehicleAudioSettings m_nSettings; // +128 + bool m_bEnabled; // +164 + bool m_bPlayerDriver; // +165 + bool m_bPlayerPassenger; // +166 + bool m_bVehicleRadioPaused; // +167 + bool m_bSoundsStopped; // +168 + char m_nEngineState; // +169 + char unk3; // +170 + char unk4; // +171 + int unk5; // +172 + bool m_bInhibitAccForLowSpeed; // +176 + char unk6; // +177 + short m_wRainDropCounter; // +178 + short unk7; // +180 + char pad1[2]; // +182 + int unk8; // +184 + char unk9; // +188 + bool m_bDisableHeliEngineSounds; // +189 + char unk10; // +190 + bool m_bSirenOrAlarmPlaying; // +191 + bool m_bHornPlaying; // +192 + char pad2[3]; // +193 + float m_fSirenVolume; // +196 + bool m_bModelWithSiren; // +200 + char pad3[3]; // +201 + unsigned int m_dwBoatHitWaveLastPlayedTime; // +204 + unsigned int m_dwTimeToInhibitAcc; // +208 + unsigned int m_dwTimeToInhibitCrz; // +212 + float m_fGeneralVehicleSoundVolume; // +216 + short m_wEngineDecelerateSoundBankId; // +220 + short m_wEngineAccelerateSoundBankId; // +222 + short m_wEngineBankSlotId; // +224 + short unk11; // +226 + tVehicleSound m_aEngineSounds[12]; // +228 + int unk12; // +324 + short unk13; // +328 + short unk14; // +330 + short unk15; // +332 + short unk16; // +334 + int unk17; // some time in ms (@0x4F5638) // +336 + short unk18; // +340 + short m_wSkidSoundType; // +342 + CAESound* unk19; // +344 + short m_wRoadNoiseSoundType; // +348 + char pad4[2]; // +350 + CAESound* m_pRoadNoiseSound; // +352 + short m_wFlatTyreSoundType; // +356 + char pad5[2]; // +358 + CAESound* m_pFlatTyreSound; // +360 + short m_wReverseGearSoundType; // +364 + char pad6[2]; // +366 + CAESound* m_pReverseGearSound; // +368 + char pad7[4]; // +372 + CAESound* m_pHornTonSound; // +376 + CAESound* m_pSirenSound; // +380 + CAESound* m_pPoliceSirenSound; // +384 + CAETwinLoopSoundEntity m_nTwinLoopSoundEntity; // +388 + float unk20; // +556 + float unk21; // +560 + float unk22; // +564 + float unk23; // +568 + float unk24; // +572 + int unk25; // +576 + bool m_bNitroSoundPresent; // +580 + char unk26; // +581 + float unk27; // +582 }; static_assert(sizeof(CAEVehicleAudioEntitySAInterface) == 0x24C, "Invalid size for CAEVehicleAudioEntitySAInterface"); @@ -137,10 +137,10 @@ class CAEVehicleAudioEntitySA : public CAEVehicleAudioEntity { public: CAEVehicleAudioEntitySA(CAEVehicleAudioEntitySAInterface* pInterface); - void JustGotInVehicleAsDriver(); - void JustGotOutOfVehicleAsDriver(); - void TurnOnRadioForVehicle(); - void StopVehicleEngineSound(unsigned char ucSlot); + void JustGotInVehicleAsDriver(); + void JustGotOutOfVehicleAsDriver(); + void TurnOnRadioForVehicle(); + void StopVehicleEngineSound(unsigned char ucSlot); CAEVehicleAudioEntitySAInterface* GetInterface() { return m_pInterface; }; private: diff --git a/Client/game_sa/CAEWeaponAudioEntitySA.h b/Client/game_sa/CAEWeaponAudioEntitySA.h index 0f35260de07..d4534638a93 100644 --- a/Client/game_sa/CAEWeaponAudioEntitySA.h +++ b/Client/game_sa/CAEWeaponAudioEntitySA.h @@ -40,12 +40,12 @@ class CAEWeaponAudioEntitySAInterface : public CAEAudioEntity eMiniGunState m_miniGunState; eChainsawState m_chainsawState; - std::uint32_t m_lastFlamethrowerFireTimeInMS; - std::uint32_t m_lastSpraycanFireTimeInMS; - std::uint32_t m_lastFireExtinguisherFireTimeInMS; - std::uint32_t m_lastMinigunFireTimeInMS; - std::uint32_t m_lastChainsawFireTimeInMS; - std::uint32_t m_lastGunFireTimeInMS; + std::uint32_t m_lastFlamethrowerFireTimeInMS; + std::uint32_t m_lastSpraycanFireTimeInMS; + std::uint32_t m_lastFireExtinguisherFireTimeInMS; + std::uint32_t m_lastMinigunFireTimeInMS; + std::uint32_t m_lastChainsawFireTimeInMS; + std::uint32_t m_lastGunFireTimeInMS; CAESound* m_flameThrowerIdleGasLoopSound{}; }; diff --git a/Client/game_sa/CAnimBlendAssociationSA.h b/Client/game_sa/CAnimBlendAssociationSA.h index 871fc177cf3..4d74bbf8a24 100644 --- a/Client/game_sa/CAnimBlendAssociationSA.h +++ b/Client/game_sa/CAnimBlendAssociationSA.h @@ -34,14 +34,14 @@ class AnimBlendFrameData { struct { - unsigned char m_bf1 : 1; // doesn't seem to be used - unsigned char m_IsIFrameOrientationToAffectedByNodes : 1; // m_IFrame orientation will be affected - unsigned char m_IsIFrameTranslationToAffectedByNodes : 1; // m_IFrame translation will be affected + unsigned char m_bf1 : 1; // doesn't seem to be used + unsigned char m_IsIFrameOrientationToAffectedByNodes : 1; // m_IFrame orientation will be affected + unsigned char m_IsIFrameTranslationToAffectedByNodes : 1; // m_IFrame translation will be affected unsigned char m_bIsInitialized : 1; unsigned char m_bUpdateSkinnedWith3dVelocityExtraction : 1; - unsigned char m_bCheckBlendNodeClumpKeyFrames : 1; // key frames of CAninBlendNode bones will be checked + unsigned char m_bCheckBlendNodeClumpKeyFrames : 1; // key frames of CAninBlendNode bones will be checked unsigned char m_bIsCompressed : 1; - unsigned char m_bUpdatingFrame : 1; // doesn't seem to be used + unsigned char m_bUpdatingFrame : 1; // doesn't seem to be used }; unsigned char m_nFlags; }; @@ -86,49 +86,49 @@ class CAnimBlendAssociationSAInterface DWORD* vTable; RwListEntry listEntry; unsigned short cNumBlendNodes; - short sAnimGroup; // 14 - CAnimBlendNodeSAInterface* pAnimBlendNodeArray; // CAnimBlendNode pp? // 16 - CAnimBlendHierarchySAInterface* pAnimHierarchy; // 20 - float fBlendAmount; // 24 - float fBlendDelta; // 28 - float fCurrentTime; // 32 - float fSpeed; // 36 - float fTimeStep; // 40 - short sAnimID; // 44 + short sAnimGroup; // 14 + CAnimBlendNodeSAInterface* pAnimBlendNodeArray; // CAnimBlendNode pp? // 16 + CAnimBlendHierarchySAInterface* pAnimHierarchy; // 20 + float fBlendAmount; // 24 + float fBlendDelta; // 28 + float fCurrentTime; // 32 + float fSpeed; // 36 + float fTimeStep; // 40 + short sAnimID; // 44 union { struct { - unsigned short m_bPlaying : 1; // Anim will stop playing if flag is not set - unsigned short m_bLooped : 1; // Anim will always restart when it completes - unsigned short m_bFreezeLastFrame : 1; // Anim will freeze on last frame + unsigned short m_bPlaying : 1; // Anim will stop playing if flag is not set + unsigned short m_bLooped : 1; // Anim will always restart when it completes + unsigned short m_bFreezeLastFrame : 1; // Anim will freeze on last frame // When this flag is Set, IF m_bLooped == false, m_bPlaying == true, and anim progress >= total anim time // THEN m_bFreezeLastFrame is set to TRUE and m_fBlendDelta is set to -4.0. // Result: https://i.imgur.com/idw0jsX.png unsigned short m_bLockLastFrame : 1; - unsigned short m_bPartial : 1; // Partial anims run along other anims - unsigned short m_bEnableMovement : 1; // blends all playing anims together if set + unsigned short m_bPartial : 1; // Partial anims run along other anims + unsigned short m_bEnableMovement : 1; // blends all playing anims together if set // Camera will not move with ped, and ped will go back to the initial position when anim is over unsigned short m_bLockLastX : 1; - unsigned short m_bLockLastY : 1; // only applies if m_bLockLastX is set + unsigned short m_bLockLastY : 1; // only applies if m_bLockLastX is set - unsigned short m_bf9 : 1; // doesn't seem to be used - unsigned short m_bf10 : 1; // doesn't seem to be used + unsigned short m_bf9 : 1; // doesn't seem to be used + unsigned short m_bf10 : 1; // doesn't seem to be used // If set to TRUE, then result: // Before = https://i.imgur.com/c8T7xNK.png | AFTER = https://i.imgur.com/4gqlA4n.png unsigned short m_bAddAnimBlendToTotalBlend : 1; - unsigned short m_bf12 : 1; // doesn't seem to be used - unsigned short m_bSecondaryTaskAnim : 1; // doesn't seem to be used + unsigned short m_bf12 : 1; // doesn't seem to be used + unsigned short m_bSecondaryTaskAnim : 1; // doesn't seem to be used // Anim will play. Translation values will be ignored for anim (m_bEnableTranslation // is ignored if set), and it only applies to some anims though unsigned short m_bFreezeTranslation : 1; - unsigned short m_bBlockReferenced : 1; // anim block can't be unloaded if it's referenced by an anim. + unsigned short m_bBlockReferenced : 1; // anim block can't be unloaded if it's referenced by an anim. // Anim will not be destroyed. It will be played simultaneously with other anims // (multiple anims at once) if you set this flag while sitting in a car, you'll still be @@ -138,10 +138,10 @@ class CAnimBlendAssociationSAInterface }; unsigned short m_nFlags; }; - unsigned int uiCallbackType; // 48: 1 means finished and 2 means delete - DWORD* pCallbackFunc; // 52 - DWORD* pCallbackData; // 56 - // Total: 60 bytes + unsigned int uiCallbackType; // 48: 1 means finished and 2 means delete + DWORD* pCallbackFunc; // 52 + DWORD* pCallbackData; // 56 + // Total: 60 bytes }; static_assert(sizeof(CAnimBlendAssociationSAInterface) == 0x3C, "Incorrect class size: CAnimBlendAssociationSAInterface"); @@ -150,16 +150,16 @@ class CAnimBlendAssociationSA : public CAnimBlendAssociation public: CAnimBlendAssociationSA(CAnimBlendAssociationSAInterface* pInterface) { m_pInterface = pInterface; } - CAnimBlendAssociationSAInterface* Constructor(CAnimBlendStaticAssociationSAInterface& StaticAssociationByReference); - CAnimBlendAssociationSAInterface* Constructor(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); - CAnimBlendAssociationSAInterface* InitializeForCustomAnimation(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); - void Init(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); - void AllocateAnimBlendNodeArray(int count); - void FreeAnimBlendNodeArray(); - CAnimBlendAssociationSAInterface* GetInterface() { return m_pInterface; } - eAnimGroup GetAnimGroup() { return static_cast(m_pInterface->sAnimGroup); } - eAnimID GetAnimID() { return static_cast(m_pInterface->sAnimID); } - std::unique_ptr GetAnimHierarchy(); + CAnimBlendAssociationSAInterface* Constructor(CAnimBlendStaticAssociationSAInterface& StaticAssociationByReference); + CAnimBlendAssociationSAInterface* Constructor(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); + CAnimBlendAssociationSAInterface* InitializeForCustomAnimation(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); + void Init(RpClump* pClump, CAnimBlendHierarchySAInterface* pAnimHierarchy); + void AllocateAnimBlendNodeArray(int count); + void FreeAnimBlendNodeArray(); + CAnimBlendAssociationSAInterface* GetInterface() { return m_pInterface; } + eAnimGroup GetAnimGroup() { return static_cast(m_pInterface->sAnimGroup); } + eAnimID GetAnimID() { return static_cast(m_pInterface->sAnimID); } + std::unique_ptr GetAnimHierarchy(); const std::unique_ptr GetAnimHierarchy() const noexcept; float GetBlendAmount() { return m_pInterface->fBlendAmount; } diff --git a/Client/game_sa/CAnimBlendSequenceSA.h b/Client/game_sa/CAnimBlendSequenceSA.h index 4b9bafca943..9eaffe4a315 100644 --- a/Client/game_sa/CAnimBlendSequenceSA.h +++ b/Client/game_sa/CAnimBlendSequenceSA.h @@ -22,8 +22,8 @@ class CAnimBlendSequenceSAInterface public: union { - uint16_t m_boneId; // m_boneId is set if ( sFlags & 0x10u ) is true - uint32_t m_hash; // otherwise m_hash is set + uint16_t m_boneId; // m_boneId is set if ( sFlags & 0x10u ) is true + uint32_t m_hash; // otherwise m_hash is set }; unsigned short sFlags; unsigned short sNumKeyFrames; diff --git a/Client/game_sa/CAnimBlockSA.h b/Client/game_sa/CAnimBlockSA.h index 7967874de85..3a872e16e83 100644 --- a/Client/game_sa/CAnimBlockSA.h +++ b/Client/game_sa/CAnimBlockSA.h @@ -15,13 +15,13 @@ class CAnimBlendAssocGroupSA; -class CAnimBlockSAInterface // 32 bytes +class CAnimBlockSAInterface // 32 bytes { public: - int GetIndex(); // hacky, i know + int GetIndex(); // hacky, i know char szName[16]; - bool bLoaded; // ? + bool bLoaded; // ? BYTE pad[1]; unsigned short usRefs; int idOffset; diff --git a/Client/game_sa/CAnimManagerSA.h b/Client/game_sa/CAnimManagerSA.h index 2268270044a..3e2d0a293d9 100644 --- a/Client/game_sa/CAnimManagerSA.h +++ b/Client/game_sa/CAnimManagerSA.h @@ -17,58 +17,58 @@ #include #include -#define FUNC_CAnimManager_Initialize 0x5bf6b0 -#define FUNC_CAnimManager_Shutdown 0x4d4130 -#define FUNC_CAnimManager_GetAnimationBlock_int 0x406f90 -#define FUNC_CAnimManager_GetAnimationBlock_str 0x4d3940 -#define FUNC_CAnimManager_GetAnimationBlockIndex 0x4d3990 -#define FUNC_CAnimManager_RegisterAnimBlock 0x4d3e50 -#define FUNC_CAnimManager_GetAnimBlendAssoc 0x45b0e0 -#define FUNC_CAnimManager_GetFirstAssocGroup 0x4d39b0 -#define FUNC_CAnimManager_GetAnimation_int 0x4cde50 -#define FUNC_CAnimManager_GetAnimation_str_block 0x4d42f0 -#define FUNC_CAnimManager_GetAnimation_int_block 0x4d39f0 -#define FUNC_CAnimManager_GetAnimGroupName 0x4d3a20 -#define FUNC_CAnimManager_GetAnimBlockName 0x4d3a30 -#define FUNC_CAnimManager_AddAnimBlockRef 0x4d3fb0 -#define FUNC_CAnimManager_RemoveAnimBlockRef 0x4d3fd0 -#define FUNC_CAnimManager_RemoveAnimBlockRefWithoutDelete 0x4d3ff0 -#define FUNC_CAnimManager_GetNumRefsToAnimBlock 0x4d4010 -#define FUNC_CAnimManager_RemoveAnimBlock 0x4d3f40 -#define FUNC_CAnimManager_RemoveLastAnimFile 0x4d3ed0 -#define FUNC_CAnimManager_AddAnimation 0x4d3aa0 -#define FUNC_CAnimManager_AddAnimation_hier 0x4d4330 -#define FUNC_CAnimManager_BlendAnimation 0x4d4610 -#define FUNC_CAnimManager_BlendAnimation_hier 0x4d4410 -#define FUNC_CAnimManager_AddAnimationAndSync 0x4d3b30 -#define FUNC_CAnimManager_CreateAnimAssociation 0x4d3a40 -#define FUNC_CAnimManager_GetAnimAssociation 0x4d3a60 -#define FUNC_CAnimManager_GetAnimAssociation_str 0x4d3a80 -#define FUNC_CAnimManager_AddAnimAssocDefinition 0x4d3ba0 -#define FUNC_CAnimManager_ReadAnimAssociationDefinitions 0x5bc910 -#define FUNC_CAnimManager_CreateAnimAssocGroups 0x4d3cc0 -#define FUNC_CAnimManager_UncompressAnimation 0x4d41c0 -#define FUNC_CAnimManager_RemoveFromUncompressedCache 0x4d42a0 -#define FUNC_CAnimManager_LoadAnimFile 0x4d55d0 -#define FUNC_CAnimManager_LoadAnimFile_stream 0x4d47f0 -#define FUNC_CAnimManager_LoadAnimFiles 0x4d5620 -#define FUNC_CAnimManager_AllocateKeyFramesMemory 0x72F420 -#define FUNC_CAnimManager_FreeKeyFramesMemory 0x72F430 -#define ARRAY_CAnimManager_AnimAssocGroups 0xb4ea34 -#define ARRAY_CAnimManager_Animations 0xb4ea40 -#define ARRAY_CAnimManager_AnimBlocks 0xb5d4a0 -#define VAR_CAnimManager_NumAnimAssocDefinitions 0xb4ea28 -#define VAR_CAnimManager_NumAnimations 0xb4ea2c -#define VAR_CAnimManager_NumAnimBlocks 0xb4ea30 +#define FUNC_CAnimManager_Initialize 0x5bf6b0 +#define FUNC_CAnimManager_Shutdown 0x4d4130 +#define FUNC_CAnimManager_GetAnimationBlock_int 0x406f90 +#define FUNC_CAnimManager_GetAnimationBlock_str 0x4d3940 +#define FUNC_CAnimManager_GetAnimationBlockIndex 0x4d3990 +#define FUNC_CAnimManager_RegisterAnimBlock 0x4d3e50 +#define FUNC_CAnimManager_GetAnimBlendAssoc 0x45b0e0 +#define FUNC_CAnimManager_GetFirstAssocGroup 0x4d39b0 +#define FUNC_CAnimManager_GetAnimation_int 0x4cde50 +#define FUNC_CAnimManager_GetAnimation_str_block 0x4d42f0 +#define FUNC_CAnimManager_GetAnimation_int_block 0x4d39f0 +#define FUNC_CAnimManager_GetAnimGroupName 0x4d3a20 +#define FUNC_CAnimManager_GetAnimBlockName 0x4d3a30 +#define FUNC_CAnimManager_AddAnimBlockRef 0x4d3fb0 +#define FUNC_CAnimManager_RemoveAnimBlockRef 0x4d3fd0 +#define FUNC_CAnimManager_RemoveAnimBlockRefWithoutDelete 0x4d3ff0 +#define FUNC_CAnimManager_GetNumRefsToAnimBlock 0x4d4010 +#define FUNC_CAnimManager_RemoveAnimBlock 0x4d3f40 +#define FUNC_CAnimManager_RemoveLastAnimFile 0x4d3ed0 +#define FUNC_CAnimManager_AddAnimation 0x4d3aa0 +#define FUNC_CAnimManager_AddAnimation_hier 0x4d4330 +#define FUNC_CAnimManager_BlendAnimation 0x4d4610 +#define FUNC_CAnimManager_BlendAnimation_hier 0x4d4410 +#define FUNC_CAnimManager_AddAnimationAndSync 0x4d3b30 +#define FUNC_CAnimManager_CreateAnimAssociation 0x4d3a40 +#define FUNC_CAnimManager_GetAnimAssociation 0x4d3a60 +#define FUNC_CAnimManager_GetAnimAssociation_str 0x4d3a80 +#define FUNC_CAnimManager_AddAnimAssocDefinition 0x4d3ba0 +#define FUNC_CAnimManager_ReadAnimAssociationDefinitions 0x5bc910 +#define FUNC_CAnimManager_CreateAnimAssocGroups 0x4d3cc0 +#define FUNC_CAnimManager_UncompressAnimation 0x4d41c0 +#define FUNC_CAnimManager_RemoveFromUncompressedCache 0x4d42a0 +#define FUNC_CAnimManager_LoadAnimFile 0x4d55d0 +#define FUNC_CAnimManager_LoadAnimFile_stream 0x4d47f0 +#define FUNC_CAnimManager_LoadAnimFiles 0x4d5620 +#define FUNC_CAnimManager_AllocateKeyFramesMemory 0x72F420 +#define FUNC_CAnimManager_FreeKeyFramesMemory 0x72F430 +#define ARRAY_CAnimManager_AnimAssocGroups 0xb4ea34 +#define ARRAY_CAnimManager_Animations 0xb4ea40 +#define ARRAY_CAnimManager_AnimBlocks 0xb5d4a0 +#define VAR_CAnimManager_NumAnimAssocDefinitions 0xb4ea28 +#define VAR_CAnimManager_NumAnimations 0xb4ea2c +#define VAR_CAnimManager_NumAnimBlocks 0xb4ea30 // Non members -#define FUNC_HasAnimGroupLoaded 0x45b130 -#define FUNC_RpAnimBlendClumpGetFirstAssociation 0x4d15e0 -#define FUNC_RpAnimBlendClumpGetAssociation_str 0x4d6870 -#define FUNC_RpAnimBlendClumpGetAssociation_int 0x4d68b0 -#define FUNC_RpAnimBlendGetNextAssociation 0x4d6ab0 -#define FUNC_RpAnimBlendClumpGetNumAssociations 0x4d6b60 -#define FUNC_RpAnimBlendClumpUpdateAnimations 0x4d34f0 +#define FUNC_HasAnimGroupLoaded 0x45b130 +#define FUNC_RpAnimBlendClumpGetFirstAssociation 0x4d15e0 +#define FUNC_RpAnimBlendClumpGetAssociation_str 0x4d6870 +#define FUNC_RpAnimBlendClumpGetAssociation_int 0x4d68b0 +#define FUNC_RpAnimBlendGetNextAssociation 0x4d6ab0 +#define FUNC_RpAnimBlendClumpGetNumAssociations 0x4d6b60 +#define FUNC_RpAnimBlendClumpUpdateAnimations 0x4d34f0 class CAnimManagerSA : public CAnimManager { diff --git a/Client/game_sa/CAudioContainerLookupTableSA.h b/Client/game_sa/CAudioContainerLookupTableSA.h index 077c865aa35..52dde675c58 100644 --- a/Client/game_sa/CAudioContainerLookupTableSA.h +++ b/Client/game_sa/CAudioContainerLookupTableSA.h @@ -34,5 +34,5 @@ struct SAudioLookupEntrySA uint8 filter[3]; uint32 offset; uint32 length; -}; // size = 12 = 0xC +}; // size = 12 = 0xC static_assert(sizeof(SAudioLookupEntrySA) == 0xC, "Invalid size for SAudioLookupEntrySA"); diff --git a/Client/game_sa/CAudioContainerSA.cpp b/Client/game_sa/CAudioContainerSA.cpp index 404744382be..a5e466cd799 100644 --- a/Client/game_sa/CAudioContainerSA.cpp +++ b/Client/game_sa/CAudioContainerSA.cpp @@ -54,20 +54,20 @@ bool CAudioContainerSA::GetAudioData(eAudioLookupIndex lookupIndex, int bankInde // Add the RIFF Wave header since BASS does not support raw data SRiffWavePCMHeader waveHeader; - waveHeader.chunkId = EndianSwap32(0x52494646); // "RIFF" in ASCII, big-Endian + waveHeader.chunkId = EndianSwap32(0x52494646); // "RIFF" in ASCII, big-Endian waveHeader.chunkSize = 36 + rawAudioLength; - waveHeader.format = EndianSwap32(0x57415645); // "WAVE" in ASCII, big-Endian + waveHeader.format = EndianSwap32(0x57415645); // "WAVE" in ASCII, big-Endian - waveHeader.subchunk1Id = EndianSwap32(0x666d7420); // "fmt " in ASCII, big-Endian - waveHeader.subchunk1Size = 16; // 16 for PCM - waveHeader.audioFormat = 0x1; // PCM - waveHeader.numChannels = 1; // Mono + waveHeader.subchunk1Id = EndianSwap32(0x666d7420); // "fmt " in ASCII, big-Endian + waveHeader.subchunk1Size = 16; // 16 for PCM + waveHeader.audioFormat = 0x1; // PCM + waveHeader.numChannels = 1; // Mono waveHeader.sampleRate = iSampleRate; - waveHeader.bitsPerSample = 16; // 16-Bit PCM + waveHeader.bitsPerSample = 16; // 16-Bit PCM waveHeader.byteRate = waveHeader.sampleRate * waveHeader.numChannels * waveHeader.bitsPerSample / 8; waveHeader.blockAlign = waveHeader.numChannels * waveHeader.bitsPerSample / 8; - waveHeader.subchunk2Id = EndianSwap32(0x64617461); // "data" in ASCII, big-endian + waveHeader.subchunk2Id = EndianSwap32(0x64617461); // "data" in ASCII, big-endian waveHeader.subchunk2Size = rawAudioLength; // Allocate a second buffer as we've to insert the wave pcm header at the beginning @@ -115,7 +115,7 @@ bool CAudioContainerSA::GetRawAudioData(eAudioLookupIndex lookupIndex, int bankI return false; unsigned int rawLength; - if (audioIndex + 1 < bankHeader.numSounds) // hacky fix: audioIndex starts at 0 + if (audioIndex + 1 < bankHeader.numSounds) // hacky fix: audioIndex starts at 0 { SAudioEntrySA* nextAudioEntry = &bankHeader.sounds[audioIndex + 1]; if (!nextAudioEntry) @@ -142,8 +142,7 @@ bool CAudioContainerSA::GetRawAudioData(eAudioLookupIndex lookupIndex, int bankI iSampleRateOut = audioEntry->sampleRate; // Seek to the correct offset and read - archive.seekg(lookupEntry->offset + sizeof(SAudioBankHeaderSA) + - audioEntry->offset); // Or just archive.seekg ( archive.tellg() + audioEntry->offset ) + archive.seekg(lookupEntry->offset + sizeof(SAudioBankHeaderSA) + audioEntry->offset); // Or just archive.seekg ( archive.tellg() + audioEntry->offset ) archive.read(reinterpret_cast(buffer), rawLength); return !archive.fail(); diff --git a/Client/game_sa/CAudioContainerSA.h b/Client/game_sa/CAudioContainerSA.h index 9f412c0de19..a2376dd356a 100644 --- a/Client/game_sa/CAudioContainerSA.h +++ b/Client/game_sa/CAudioContainerSA.h @@ -17,8 +17,8 @@ class CAudioContainerLookupTableSA; #define VALIDATE_BUFFER_SIZE 4096 -#define NUM_BEAT_ENTRIES 1000 -#define NUM_LENGTH_ENTRIES 8 +#define NUM_BEAT_ENTRIES 1000 +#define NUM_LENGTH_ENTRIES 8 struct SAudioEntrySA { @@ -32,27 +32,27 @@ static_assert(sizeof(SAudioEntrySA) == 0xC, "Invalid size for SAudioLookupEntryS struct SAudioBankHeaderSA { int numSounds; - SAudioEntrySA sounds[400]; // Todo: optimize this (dynamic allocation) + SAudioEntrySA sounds[400]; // Todo: optimize this (dynamic allocation) }; struct SRiffWavePCMHeader { - uint32 chunkId; // big-endian // 0 - uint32 chunkSize; // 4 - uint32 format; // big-endian // 8 - - uint32 subchunk1Id; // big-endian // 12 - uint32 subchunk1Size; // 16 - uint16 audioFormat; // 20 - uint16 numChannels; // 22 - uint32 sampleRate; // 24 - uint32 byteRate; // 28 - uint16 blockAlign; // 32 - uint16 bitsPerSample; // 34 - - uint32 subchunk2Id; // big-endian // 36 - uint32 subchunk2Size; // 40 -}; // size = 44 = 0x2C + uint32 chunkId; // big-endian // 0 + uint32 chunkSize; // 4 + uint32 format; // big-endian // 8 + + uint32 subchunk1Id; // big-endian // 12 + uint32 subchunk1Size; // 16 + uint16 audioFormat; // 20 + uint16 numChannels; // 22 + uint32 sampleRate; // 24 + uint32 byteRate; // 28 + uint16 blockAlign; // 32 + uint16 bitsPerSample; // 34 + + uint32 subchunk2Id; // big-endian // 36 + uint32 subchunk2Size; // 40 +}; // size = 44 = 0x2C static_assert(sizeof(SRiffWavePCMHeader) == 0x2C, "Invalid size for SRiffWavePCMHeader"); // Documentation by SAAT // diff --git a/Client/game_sa/CAudioEngineSA.cpp b/Client/game_sa/CAudioEngineSA.cpp index b84cc33b13d..024920d9f19 100644 --- a/Client/game_sa/CAudioEngineSA.cpp +++ b/Client/game_sa/CAudioEngineSA.cpp @@ -18,11 +18,11 @@ extern CGameSA* pGame; -#define HOOKPOS_CAEAmbienceTrackManager_CheckForPause 0x4D6E21 +#define HOOKPOS_CAEAmbienceTrackManager_CheckForPause 0x4D6E21 DWORD RETURN_CAEAmbienceTrackManager_CheckForPause = 0x4D6E27; void HOOK_CAEAmbienceTrackManager_CheckForPause(); -#define HOOKPOS_CAESoundManager_RequestNewSound 0x4EFB10 +#define HOOKPOS_CAESoundManager_RequestNewSound 0x4EFB10 DWORD RETURN_CAESoundManager_RequestNewSound = 0x4EFB15; void HOOK_CAESoundManager_RequestNewSound(); @@ -44,13 +44,13 @@ CAudioEngineSA::CAudioEngineSA(CAudioEngineSAInterface* pInterface) HookInstall(HOOKPOS_CAEAmbienceTrackManager_CheckForPause, (DWORD)HOOK_CAEAmbienceTrackManager_CheckForPause, 6); // Make room for hook - MemPut(0x4EFB15 + 0, 0x0F); // movsx eax, si + MemPut(0x4EFB15 + 0, 0x0F); // movsx eax, si MemPut(0x4EFB15 + 1, 0xBF); MemPut(0x4EFB15 + 2, 0xC6); - MemPut(0x4EFB15 + 3, 0x6B); // imul eax, 74h + MemPut(0x4EFB15 + 3, 0x6B); // imul eax, 74h MemPut(0x4EFB15 + 4, 0xC0); MemPut(0x4EFB15 + 5, 0x74); - MemPut(0x4EFB29, 0xEB); // Move jump forward one byte + MemPut(0x4EFB29, 0xEB); // Move jump forward one byte HookInstall(HOOKPOS_CAESoundManager_RequestNewSound, (DWORD)HOOK_CAESoundManager_RequestNewSound, 5); } @@ -59,7 +59,7 @@ void CAudioEngineSA::StopRadio() m_bRadioOn = false; // DWORD dwFunc = FUNC_StopRadio; - DWORD dwFunc = 0x4E9823; // Some function CAudio::StopRadio jumps to immediately + DWORD dwFunc = 0x4E9823; // Some function CAudio::StopRadio jumps to immediately // clang-format off __asm @@ -162,7 +162,7 @@ void CAudioEngineSA::StartRadio(unsigned int station) // 13 = camera take picture void CAudioEngineSA::PlayFrontEndSound(DWORD dwEventID) { - if (*(DWORD*)VAR_AudioEventVolumes != 0 && dwEventID <= 101) // may prevent a crash + if (*(DWORD*)VAR_AudioEventVolumes != 0 && dwEventID <= 101) // may prevent a crash { DWORD dwFunc = FUNC_ReportFrontendAudioEvent; float fSpeed = 1.0f; @@ -227,14 +227,14 @@ void CAudioEngineSA::SetMusicMasterVolume(BYTE bVolume) { // unmute -> mute StopRadio(); - m_bRadioOn = true; // StopRadio was only called to stop the radio stream. Radio is logically still on + m_bRadioOn = true; // StopRadio was only called to stop the radio stream. Radio is logically still on } } } void CAudioEngineSA::PlayBeatTrack(short iTrack) { - if (*(DWORD*)VAR_AudioEventVolumes != 0) // may prevent a crash + if (*(DWORD*)VAR_AudioEventVolumes != 0) // may prevent a crash { DWORD dwFunc = FUNC_PreloadBeatTrack; DWORD dwTrack = iTrack; @@ -261,7 +261,7 @@ void CAudioEngineSA::PlayBeatTrack(short iTrack) void CAudioEngineSA::ClearMissionAudio(int slot) { - DWORD dwFunc = 0x5072F0; // CAudioEngine::ClearMissionAudio(unsigned char) + DWORD dwFunc = 0x5072F0; // CAudioEngine::ClearMissionAudio(unsigned char) // clang-format off __asm { @@ -274,7 +274,7 @@ void CAudioEngineSA::ClearMissionAudio(int slot) bool CAudioEngineSA::IsMissionAudioSampleFinished(int slot) { - DWORD dwFunc = 0x5072C0; // CAudioEngine::IsMissionAudioSampleFinished + DWORD dwFunc = 0x5072C0; // CAudioEngine::IsMissionAudioSampleFinished bool cret = 0; // clang-format off __asm @@ -290,7 +290,7 @@ bool CAudioEngineSA::IsMissionAudioSampleFinished(int slot) void CAudioEngineSA::PreloadMissionAudio(unsigned short usAudioEvent, int slot) { - DWORD dwFunc = 0x507290; // CAudioEngine__PreloadMissionAudio + DWORD dwFunc = 0x507290; // CAudioEngine__PreloadMissionAudio DWORD AudioEvent = usAudioEvent; // clang-format off __asm @@ -305,7 +305,7 @@ void CAudioEngineSA::PreloadMissionAudio(unsigned short usAudioEvent, int slot) unsigned char CAudioEngineSA::GetMissionAudioLoadingStatus(int slot) { - DWORD dwFunc = 0x5072A0; // get load status + DWORD dwFunc = 0x5072A0; // get load status unsigned char cret = 0; // clang-format off __asm @@ -329,7 +329,7 @@ void CAudioEngineSA::AttachMissionAudioToPhysical(CPhysical* physical, int slot) entity = pPhysical->GetInterface(); } - DWORD dwFunc = 0x507330; // AttachMissionAudioToPhysical + DWORD dwFunc = 0x507330; // AttachMissionAudioToPhysical // clang-format off __asm { @@ -343,7 +343,7 @@ void CAudioEngineSA::AttachMissionAudioToPhysical(CPhysical* physical, int slot) void CAudioEngineSA::SetMissionAudioPosition(CVector* position, int slot) { - DWORD dwFunc = 0x507300; // CAudioEngine__SetMissionAudioPosition + DWORD dwFunc = 0x507300; // CAudioEngine__SetMissionAudioPosition // clang-format off __asm { @@ -359,7 +359,7 @@ bool CAudioEngineSA::PlayLoadedMissionAudio(int slot) { if (GetMissionAudioLoadingStatus(slot) == 1) { - DWORD dwFunc = 0x5072B0; // CAudioEngine::PlayLoadedMissionAudio(unsigned char) + DWORD dwFunc = 0x5072B0; // CAudioEngine::PlayLoadedMissionAudio(unsigned char) // clang-format off __asm { @@ -440,9 +440,9 @@ void CAudioEngineSA::UpdateAmbientSoundSettings() { // Update gunfire setting if (IsAmbientSoundEnabled(AMBIENT_SOUND_GUNFIRE)) - MemPut(0x507814, 0x85); // Enable gunfire (default) + MemPut(0x507814, 0x85); // Enable gunfire (default) else - MemPut(0x507814, 0x33); // No gunfire + MemPut(0x507814, 0x33); // No gunfire } static bool IsAmbientSoundGeneralEnabled() diff --git a/Client/game_sa/CAudioEngineSA.h b/Client/game_sa/CAudioEngineSA.h index 2b9d77b8662..f86f5d8b0ce 100644 --- a/Client/game_sa/CAudioEngineSA.h +++ b/Client/game_sa/CAudioEngineSA.h @@ -13,29 +13,29 @@ #include -#define FUNC_ReportFrontendAudioEvent 0x506EA0 -#define FUNC_PreloadBeatTrack 0x507F40 -#define FUNC_PlayPreloadedBeatTrack 0x507180 +#define FUNC_ReportFrontendAudioEvent 0x506EA0 +#define FUNC_PreloadBeatTrack 0x507F40 +#define FUNC_PlayPreloadedBeatTrack 0x507180 -#define FUNC_SetEffectsMasterVolume 0x506E10 -#define FUNC_SetMusicMasterVolume 0x506DE0 +#define FUNC_SetEffectsMasterVolume 0x506E10 +#define FUNC_SetMusicMasterVolume 0x506DE0 -#define FUNC_ReportMissionAudioEvent_Vehicle 0x507390 -#define FUNC_ReportMissionAudioEvent_Vector 0x507340 -#define FUNC_PauseAllSounds 0x507430 -#define FUNC_ResumeAllSounds 0x507440 -#define FUNC_StopRadio 0x506F70 -#define FUNC_StartRadio2 0x507DC0 +#define FUNC_ReportMissionAudioEvent_Vehicle 0x507390 +#define FUNC_ReportMissionAudioEvent_Vector 0x507340 +#define FUNC_PauseAllSounds 0x507430 +#define FUNC_ResumeAllSounds 0x507440 +#define FUNC_StopRadio 0x506F70 +#define FUNC_StartRadio2 0x507DC0 -#define VAR_AudioEventVolumes 0xBD00F8 // m_pAudioEventVolumes +#define VAR_AudioEventVolumes 0xBD00F8 // m_pAudioEventVolumes -#define CLASS_CAudioEngine 0xB6BC90 -#define CLASS_AERadioTrackManager 0x8CB6F8 -#define CLASS_AECutsceneTrackManager 0x8AE554 -#define FUNC_CAudioEngine_ReportBulletHit 0x506ec0 -#define FUNC_CAudioEngine_ReportWeaponEvent 0x506f40 +#define CLASS_CAudioEngine 0xB6BC90 +#define CLASS_AERadioTrackManager 0x8CB6F8 +#define CLASS_AECutsceneTrackManager 0x8AE554 +#define FUNC_CAudioEngine_ReportBulletHit 0x506ec0 +#define FUNC_CAudioEngine_ReportWeaponEvent 0x506f40 -#define FUNC_CAESound__Stop 0x4EF1C0 +#define FUNC_CAESound__Stop 0x4EF1C0 class CAudioEngineSAInterface { @@ -50,33 +50,33 @@ class CAEAudioEntity public: CAEAudioEntityVTBL* vtbl; CEntitySAInterface* pEntity; - char m_tempSound[0x74]; // CAESound + char m_tempSound[0x74]; // CAESound }; static_assert(sizeof(CAEAudioEntity) == 0x7C, "Invalid size for CAEAudioEntity"); class CAESound { public: - ushort usGroup; // +0 - ushort usIndex; // +2 - CAEAudioEntity* pAudioEntity; // +4 - CEntitySAInterface* pGameEntity; // +8 Either a player or NULL - unsigned int m_dwEvent; // +12 - float m_fMaxVolume; // +16 - float m_fVolume; // +20 - float m_fSoundDistance; // +24 - float m_fSpeed; // +28 - float unk1; // +32 - CVector m_vCurrPosn; // +36 - CVector m_vPrevPosn; // +48 - int m_dwLastFrameUpdate; // +60 - int m_dwCurrTimeUpdate; // +64 - int m_dwPrevTimeUpdate; // +68 - float m_fCurrCamDist; // +72 - float m_fPrevCamDist; // +76 - float m_fTimeScale; // +80 - char unk2; // +84 = 31488 - char unk3; // +85 = 1005 + ushort usGroup; // +0 + ushort usIndex; // +2 + CAEAudioEntity* pAudioEntity; // +4 + CEntitySAInterface* pGameEntity; // +8 Either a player or NULL + unsigned int m_dwEvent; // +12 + float m_fMaxVolume; // +16 + float m_fVolume; // +20 + float m_fSoundDistance; // +24 + float m_fSpeed; // +28 + float unk1; // +32 + CVector m_vCurrPosn; // +36 + CVector m_vPrevPosn; // +48 + int m_dwLastFrameUpdate; // +60 + int m_dwCurrTimeUpdate; // +64 + int m_dwPrevTimeUpdate; // +68 + float m_fCurrCamDist; // +72 + float m_fPrevCamDist; // +76 + float m_fTimeScale; // +80 + char unk2; // +84 = 31488 + char unk3; // +85 = 1005 union { unsigned short m_wEnvironmentFlags; @@ -97,17 +97,17 @@ class CAESound unsigned short m_bForcedFront : 1; }; }; - unsigned short m_wIsUsed; // +88 - short unk4; // +90 = 1005 - short m_wCurrentPlayPosition; // +92 - short unk5; // +94 = 0 - float m_fFinalVolume; // +96 - float m_fFrequency; // +100 - short m_wPlayingState; // +104 - char unk6[2]; // +106 - float m_fSoundHeadRoom; // +108 - short m_wSoundLength; // +112 - short unk8; // +114 + unsigned short m_wIsUsed; // +88 + short unk4; // +90 = 1005 + short m_wCurrentPlayPosition; // +92 + short unk5; // +94 = 0 + float m_fFinalVolume; // +96 + float m_fFrequency; // +100 + short m_wPlayingState; // +104 + char unk6[2]; // +106 + float m_fSoundHeadRoom; // +108 + short m_wSoundLength; // +112 + short unk8; // +114 }; static_assert(sizeof(CAESound) == 0x74, "Invalid size for CAESound"); @@ -118,7 +118,7 @@ class CAudioEngineSA : public CAudioEngine void PlayFrontEndSound(DWORD dwSound); void PlayBeatTrack(short iTrack); - void SetEffectsMasterVolume(BYTE bVolume); // 64 = max volume + void SetEffectsMasterVolume(BYTE bVolume); // 64 = max volume void SetMusicMasterVolume(BYTE bVolume); void ClearMissionAudio(int slot = 1); void PreloadMissionAudio(unsigned short usAudioEvent, int slot = 1); diff --git a/Client/game_sa/CAutomobileSA.cpp b/Client/game_sa/CAutomobileSA.cpp index 6f796d64c4b..a328b79f00c 100644 --- a/Client/game_sa/CAutomobileSA.cpp +++ b/Client/game_sa/CAutomobileSA.cpp @@ -44,7 +44,7 @@ void CAutomobileSAInterface::SetPanelDamage(std::uint8_t panelId, bool breakGlas { case DT_PANEL_DAMAGED: { - if ((pHandlingData->uiModelFlags & 0x10000000) != 0) // check bouncePanels flag + if ((pHandlingData->uiModelFlags & 0x10000000) != 0) // check bouncePanels flag return; if (node != eCarNodes::WINDSCREEN && node != eCarNodes::WING_LF && node != eCarNodes::WING_RF) @@ -60,7 +60,7 @@ void CAutomobileSAInterface::SetPanelDamage(std::uint8_t panelId, bool breakGlas } } - SetComponentVisibility(frame, 2); // ATOMIC_IS_DAM_STATE + SetComponentVisibility(frame, 2); // ATOMIC_IS_DAM_STATE break; } case DT_PANEL_OPENED: @@ -68,7 +68,7 @@ void CAutomobileSAInterface::SetPanelDamage(std::uint8_t panelId, bool breakGlas if (panelId == WINDSCREEN_PANEL) m_VehicleAudioEntity.AddAudioEvent(91, 0.0f); - SetComponentVisibility(frame, 2); // ATOMIC_IS_DAM_STATE + SetComponentVisibility(frame, 2); // ATOMIC_IS_DAM_STATE break; } case DT_PANEL_OPENED_DAMAGED: @@ -76,13 +76,13 @@ void CAutomobileSAInterface::SetPanelDamage(std::uint8_t panelId, bool breakGlas if (panelId == WINDSCREEN_PANEL) { if (breakGlass) - ((void(__cdecl*)(CAutomobileSAInterface*, bool))0x71C2B0)(this, false); // Call CGlass::CarWindscreenShatters + ((void(__cdecl*)(CAutomobileSAInterface*, bool))0x71C2B0)(this, false); // Call CGlass::CarWindscreenShatters } if (spawnFlyingComponent && (panelId != WINDSCREEN_PANEL || (panelId == WINDSCREEN_PANEL && !breakGlass))) SpawnFlyingComponent(node, eCarComponentCollisionTypes::COL_NODE_PANEL); - SetComponentVisibility(frame, 0); // ATOMIC_IS_NOT_PRESENT + SetComponentVisibility(frame, 0); // ATOMIC_IS_NOT_PRESENT break; } } diff --git a/Client/game_sa/CAutomobileSA.h b/Client/game_sa/CAutomobileSA.h index 3aa3a6286dd..a76dfeace77 100644 --- a/Client/game_sa/CAutomobileSA.h +++ b/Client/game_sa/CAutomobileSA.h @@ -16,10 +16,10 @@ #include "CDoorSA.h" #include "CVehicleSA.h" -#define FUNC_CAutomobile_SetTaxiLight 0x6A3740 +#define FUNC_CAutomobile_SetTaxiLight 0x6A3740 -#define MAX_PASSENGER_COUNT 8 -#define MAX_DOORS 6 // also in CDamageManager +#define MAX_PASSENGER_COUNT 8 +#define MAX_DOORS 6 // also in CDamageManager class CBouncingPanelSAInterface { @@ -44,7 +44,7 @@ class CAutomobileSAInterface : public CVehicleSAInterface CObjectSAInterface* SpawnFlyingComponent(const eCarNodes& nodeId, const eCarComponentCollisionTypes& collType) { - return ((CObjectSAInterface*(__thiscall*)(CAutomobileSAInterface*, eCarNodes, eCarComponentCollisionTypes))0x6a8580)(this, nodeId, collType); + return ((CObjectSAInterface * (__thiscall*)(CAutomobileSAInterface*, eCarNodes, eCarComponentCollisionTypes))0x6a8580)(this, nodeId, collType); } CDamageManagerSAInterface m_damageManager; @@ -81,7 +81,7 @@ class CAutomobileSAInterface : public CVehicleSAInterface float m_fCarTraction; float m_fNitroValue; int field_8A4; - int m_fRotationBalance; // used in CHeli::TestSniperCollision + int m_fRotationBalance; // used in CHeli::TestSniperCollision float m_fMoveDirection; int field_8B4[6]; int field_8C8[6]; diff --git a/Client/game_sa/CBikeSA.h b/Client/game_sa/CBikeSA.h index 8cf4ad282cc..124d6a5162f 100644 --- a/Client/game_sa/CBikeSA.h +++ b/Client/game_sa/CBikeSA.h @@ -47,7 +47,7 @@ class CBikeSAInterface : public CVehicleSAInterface public: RwFrame* m_apModelNodes[static_cast(eBikeNodes::NUM_NODES)]; int8 m_bLeanMatrixCalculated; - int8 pad0[3]; // Maybe prev value is int32 + int8 pad0[3]; // Maybe prev value is int32 int8 m_mLeanMatrix[72]; int8 m_cDamageFlags; int8 pad1[27]; diff --git a/Client/game_sa/CBoatSA.h b/Client/game_sa/CBoatSA.h index d7def954e13..1cfd591755f 100644 --- a/Client/game_sa/CBoatSA.h +++ b/Client/game_sa/CBoatSA.h @@ -35,23 +35,23 @@ enum class eBoatNodes class CBoatSAInterface : public CVehicleSAInterface { public: - uint32 pad1[3]; // 1440 - uint32 BoatFlags; // 1452 - RwFrame* pBoatParts[static_cast(eBoatNodes::NUM_NODES)]; // 1456 - uint32 pad2[3]; // 1500 - uint16 pad3; // 1512 - uint8 pad4[2]; // 1514 - uint32 pad5[3]; // 1516 - tBoatHandlingDataSA* pBoatHandlingData; // 1528 - uint32 pad6[5]; // 1532 - CVector vecUnk1; // 1552 - CVector vecUnk2; // 1564 - class CParticleFx* pBoatPropellerSplashParticle; // 1576 - uint32 pad7[4]; // 1580 - uint8 pad8; // 1596 - uint8 ucPadUsingBoat; // 1597 [[ see class CPad - uint8 pad9[2]; // 1598 - uint32 pad10[106]; // 1600 + uint32 pad1[3]; // 1440 + uint32 BoatFlags; // 1452 + RwFrame* pBoatParts[static_cast(eBoatNodes::NUM_NODES)]; // 1456 + uint32 pad2[3]; // 1500 + uint16 pad3; // 1512 + uint8 pad4[2]; // 1514 + uint32 pad5[3]; // 1516 + tBoatHandlingDataSA* pBoatHandlingData; // 1528 + uint32 pad6[5]; // 1532 + CVector vecUnk1; // 1552 + CVector vecUnk2; // 1564 + class CParticleFx* pBoatPropellerSplashParticle; // 1576 + uint32 pad7[4]; // 1580 + uint8 pad8; // 1596 + uint8 ucPadUsingBoat; // 1597 [[ see class CPad + uint8 pad9[2]; // 1598 + uint32 pad10[106]; // 1600 }; class CBoatSA final : public virtual CBoat, public virtual CVehicleSA diff --git a/Client/game_sa/CBuildingRemovalSA.cpp b/Client/game_sa/CBuildingRemovalSA.cpp index bc9aa3a4c2a..1ca4783affe 100644 --- a/Client/game_sa/CBuildingRemovalSA.cpp +++ b/Client/game_sa/CBuildingRemovalSA.cpp @@ -41,8 +41,8 @@ void CBuildingRemovalSA::RemoveBuilding(uint16_t usModelToRemove, float fRange, bool bFound = false; uint uiAmount = 0; // Init loop variables - std::pair::iterator, std::multimap::iterator> - iterators = m_pDataBuildings->equal_range(usModelToRemove); + std::pair::iterator, std::multimap::iterator> iterators = + m_pDataBuildings->equal_range(usModelToRemove); std::multimap::const_iterator iter = iterators.first; for (; iter != iterators.second; ++iter) { @@ -269,7 +269,7 @@ bool CBuildingRemovalSA::RestoreBuilding(uint16_t usModelToRestore, float fRange iter++; } std::pair::iterator, std::multimap::iterator> - dataBuildingIterators = m_pDataBuildings->equal_range(usModelToRestore); + dataBuildingIterators = m_pDataBuildings->equal_range(usModelToRestore); std::multimap::const_iterator iterator = dataBuildingIterators.first; for (; iterator != dataBuildingIterators.second; ++iterator) { @@ -300,8 +300,8 @@ bool CBuildingRemovalSA::RestoreBuilding(uint16_t usModelToRestore, float fRange } } - std::pair::iterator, std::multimap::iterator> - binaryBuildingIterators = m_pBinaryBuildings->equal_range(usModelToRestore); + std::pair::iterator, std::multimap::iterator> binaryBuildingIterators = + m_pBinaryBuildings->equal_range(usModelToRestore); std::multimap::const_iterator iteratorBinary = binaryBuildingIterators.first; for (; iteratorBinary != binaryBuildingIterators.second; ++iteratorBinary) { @@ -433,7 +433,7 @@ bool CBuildingRemovalSA::IsEntityRemoved(CEntitySAInterface* pInterface) void CBuildingRemovalSA::ClearRemovedBuildingLists(uint* pOutAmount) { // Ensure no memory leaks by deleting items. - uint uiAmount = 0; + uint uiAmount = 0; std::multimap::const_iterator iter = m_pBuildingRemovals->begin(); for (; iter != m_pBuildingRemovals->end();) @@ -651,8 +651,8 @@ void CBuildingRemovalSA::RemoveWorldBuildingFromLists(CEntitySAInterface* pInter } { // Init some variables - std::pair::iterator, std::multimap::iterator> - dataIterators = m_pDataBuildings->equal_range(pInterface->m_nModelIndex); + std::pair::iterator, std::multimap::iterator> dataIterators = + m_pDataBuildings->equal_range(pInterface->m_nModelIndex); std::multimap::const_iterator iterator = dataIterators.first; for (; iterator != dataIterators.second;) { @@ -675,8 +675,8 @@ void CBuildingRemovalSA::RemoveWorldBuildingFromLists(CEntitySAInterface* pInter } { // Init some variables - std::pair::iterator, std::multimap::iterator> - binaryIterators = m_pBinaryBuildings->equal_range(pInterface->m_nModelIndex); + std::pair::iterator, std::multimap::iterator> binaryIterators = + m_pBinaryBuildings->equal_range(pInterface->m_nModelIndex); std::multimap::const_iterator iteratorBinary = binaryIterators.first; for (; iteratorBinary != binaryIterators.second;) { @@ -719,7 +719,7 @@ void CBuildingRemovalSA::DropCaches() m_pBinaryBuildings->clear(); m_pDataBuildings->clear(); - for (auto &pRemoval : *m_pBuildingRemovals) + for (auto& pRemoval : *m_pBuildingRemovals) { pRemoval.second->m_pDataRemoveList->clear(); pRemoval.second->m_pBinaryRemoveList->clear(); diff --git a/Client/game_sa/CBuildingRemovalSA.h b/Client/game_sa/CBuildingRemovalSA.h index 9796f0b38bf..eb8537e85c3 100644 --- a/Client/game_sa/CBuildingRemovalSA.h +++ b/Client/game_sa/CBuildingRemovalSA.h @@ -34,12 +34,12 @@ class CBuildingRemovalSA : public CBuildingRemoval bool IsObjectRemoved(CEntitySAInterface* pInterface) override; bool IsDataModelRemoved(uint16_t usModelID) override; bool IsEntityRemoved(CEntitySAInterface* pInterface) override; - void DropCaches(); + void DropCaches(); private: - std::multimap* m_pBuildingRemovals; - std::multimap* m_pDataBuildings; - std::multimap* m_pBinaryBuildings; - std::map m_pRemovedEntities; - std::map m_pAddedEntities; + std::multimap* m_pBuildingRemovals; + std::multimap* m_pDataBuildings; + std::multimap* m_pBinaryBuildings; + std::map m_pRemovedEntities; + std::map m_pAddedEntities; }; diff --git a/Client/game_sa/CBuildingsPoolSA.h b/Client/game_sa/CBuildingsPoolSA.h index 033b39b870c..4d8b33cc476 100644 --- a/Client/game_sa/CBuildingsPoolSA.h +++ b/Client/game_sa/CBuildingsPoolSA.h @@ -26,10 +26,10 @@ class CBuildingsPoolSA : public CBuildingsPool void RemoveBuilding(CBuilding* pBuilding); bool HasFreeBuildingSlot(); - void RemoveAllWithBackup() override; - void RestoreBackup() override; - bool Resize(int size) override; - int GetSize() const override { return (*m_ppBuildingPoolInterface)->m_nSize; }; + void RemoveAllWithBackup() override; + void RestoreBackup() override; + bool Resize(int size) override; + int GetSize() const override { return (*m_ppBuildingPoolInterface)->m_nSize; }; CClientEntity* GetClientBuilding(CBuildingSAInterface* pGameInterface) const noexcept; private: diff --git a/Client/game_sa/CCamSA.cpp b/Client/game_sa/CCamSA.cpp index cc3e4ebe5dd..4d491c08318 100644 --- a/Client/game_sa/CCamSA.cpp +++ b/Client/game_sa/CCamSA.cpp @@ -35,16 +35,15 @@ extern CGameSA* pGame; CEntity* CCamSA::GetTargetEntity() const { - if (!m_pInterface) return nullptr; if (!pGame) return nullptr; - + CEntitySAInterface* pInterface = m_pInterface->CamTargetEntity; if (pInterface) - { + { CPools* pPools = pGame->GetPools(); if (pPools) return pPools->GetEntity((DWORD*)pInterface); @@ -56,13 +55,13 @@ void CCamSA::SetTargetEntity(CEntity* pEntity) { if (!m_pInterface) return; - + if (pEntity) { auto pEntityInterface = pEntity->GetInterface(); if (!pEntityInterface) return; - + m_pInterface->CamTargetEntity = pEntityInterface; } else @@ -97,11 +96,11 @@ void CCamSA::SetDirection(float fHorizontal, float fVertical) { if (!m_pInterface) return; - + // Validate input float values if (!std::isfinite(fHorizontal) || !std::isfinite(fVertical)) return; - + m_pInterface->m_fHorizontalAngle = WrapAngleRad(fHorizontal); m_pInterface->m_fVerticalAngle = WrapAngleRad(fVertical); -} \ No newline at end of file +} diff --git a/Client/game_sa/CCamSA.h b/Client/game_sa/CCamSA.h index 113521c505d..90284b66f9c 100644 --- a/Client/game_sa/CCamSA.h +++ b/Client/game_sa/CCamSA.h @@ -17,142 +17,142 @@ #include "CPedSA.h" const int NUMBER_OF_VECTORS_FOR_AVERAGE = 2; -#define CAM_NUM_TARGET_HISTORY 4 +#define CAM_NUM_TARGET_HISTORY 4 class CCamSAInterface { public: - bool bBelowMinDist; // used for follow ped mode - bool bBehindPlayerDesired; // used for follow ped mode + bool bBelowMinDist; // used for follow ped mode + bool bBehindPlayerDesired; // used for follow ped mode bool m_bCamLookingAtVector; bool m_bCollisionChecksOn; - bool m_bFixingBeta; // used for camera on a string // 4 + bool m_bFixingBeta; // used for camera on a string // 4 bool m_bTheHeightFixerVehicleIsATrain; bool LookBehindCamWasInFront; bool LookingBehind; - bool LookingLeft; // 8 + bool LookingLeft; // 8 bool LookingRight; - bool ResetStatics; // for interpolation type stuff to work + bool ResetStatics; // for interpolation type stuff to work bool Rotating; - short Mode; // CameraMode // 12 - unsigned int m_uiFinishTime; // 14 + short Mode; // CameraMode // 12 + unsigned int m_uiFinishTime; // 14 - int m_iDoCollisionChecksOnFrameNum; // 18 + int m_iDoCollisionChecksOnFrameNum; // 18 int m_iDoCollisionCheckEveryNumOfFrames; int m_iFrameNumWereAt; - int m_iRunningVectorArrayPos; // 32 + int m_iRunningVectorArrayPos; // 32 int m_iRunningVectorCounter; - int DirectionWasLooking; // 40 + int DirectionWasLooking; // 40 - float f_max_role_angle; //=DEGTORAD(5.0f); // 44 - float f_Roll; // used for adding a slight roll to the camera in the - float f_rollSpeed; // camera on a string mode - float m_fSyphonModeTargetZOffSet; // 56 + float f_max_role_angle; //=DEGTORAD(5.0f); // 44 + float f_Roll; // used for adding a slight roll to the camera in the + float f_rollSpeed; // camera on a string mode + float m_fSyphonModeTargetZOffSet; // 56 float m_fAmountFractionObscured; - float m_fAlphaSpeedOverOneFrame; // 64 + float m_fAlphaSpeedOverOneFrame; // 64 float m_fBetaSpeedOverOneFrame; - float m_fBufferedTargetBeta; // 72 + float m_fBufferedTargetBeta; // 72 float m_fBufferedTargetOrientation; - float m_fBufferedTargetOrientationSpeed; // 80 + float m_fBufferedTargetOrientationSpeed; // 80 float m_fCamBufferedHeight; float m_fCamBufferedHeightSpeed; - float m_fCloseInPedHeightOffset; // 92 + float m_fCloseInPedHeightOffset; // 92 float m_fCloseInPedHeightOffsetSpeed; float m_fCloseInCarHeightOffset; - float m_fCloseInCarHeightOffsetSpeed; // 104 + float m_fCloseInCarHeightOffsetSpeed; // 104 float m_fDimensionOfHighestNearCar; - float m_fDistanceBeforeChanges; // 112 + float m_fDistanceBeforeChanges; // 112 float m_fFovSpeedOverOneFrame; - float m_fMinDistAwayFromCamWhenInterPolating; // 120 + float m_fMinDistAwayFromCamWhenInterPolating; // 120 float m_fPedBetweenCameraHeightOffset; - float m_fPlayerInFrontSyphonAngleOffSet; // 128 + float m_fPlayerInFrontSyphonAngleOffSet; // 128 float m_fRadiusForDead; - float m_fRealGroundDist; // used for follow ped mode // 136 + float m_fRealGroundDist; // used for follow ped mode // 136 float m_fTargetBeta; float m_fTimeElapsedFloat; - float m_fTilt; // 148 - float m_fTiltSpeed; // 152 - - float m_fTransitionBeta; // 156 - float m_fTrueBeta; // 160 - float m_fTrueAlpha; // 164 - float m_fInitialPlayerOrientation; // used for first person // 168 - - float m_fVerticalAngle; // alpha // 172 - float AlphaSpeed; // 176 - float FOV; // 180 - float FOVSpeed; // 184 - float m_fHorizontalAngle; // beta // 188 - float BetaSpeed; // 192 - float Distance; // 196 + float m_fTilt; // 148 + float m_fTiltSpeed; // 152 + + float m_fTransitionBeta; // 156 + float m_fTrueBeta; // 160 + float m_fTrueAlpha; // 164 + float m_fInitialPlayerOrientation; // used for first person // 168 + + float m_fVerticalAngle; // alpha // 172 + float AlphaSpeed; // 176 + float FOV; // 180 + float FOVSpeed; // 184 + float m_fHorizontalAngle; // beta // 188 + float BetaSpeed; // 192 + float Distance; // 196 float DistanceSpeed; - float CA_MIN_DISTANCE; // 204 + float CA_MIN_DISTANCE; // 204 float CA_MAX_DISTANCE; float SpeedVar; - float m_fCameraHeightMultiplier; // used by TwoPlayer_Separate_Cars_TopDown // 216 + float m_fCameraHeightMultiplier; // used by TwoPlayer_Separate_Cars_TopDown // 216 // ped onfoot zoom distance - float m_fTargetZoomGroundOne; // 220 + float m_fTargetZoomGroundOne; // 220 float m_fTargetZoomGroundTwo; - float m_fTargetZoomGroundThree; // 228 + float m_fTargetZoomGroundThree; // 228 // ped onfoot alpha angle offset float m_fTargetZoomOneZExtra; float m_fTargetZoomTwoZExtra; - float m_fTargetZoomTwoInteriorZExtra; // extra one for interior - float m_fTargetZoomThreeZExtra; // 244 + float m_fTargetZoomTwoInteriorZExtra; // extra one for interior + float m_fTargetZoomThreeZExtra; // 244 - float m_fTargetZoomZCloseIn; // 248 + float m_fTargetZoomZCloseIn; // 248 float m_fMinRealGroundDist; float m_fTargetCloseInDist; // For targetting in cooperative mode. - float Beta_Targeting; // 260 + float Beta_Targeting; // 260 float X_Targetting, Y_Targetting; - int CarWeAreFocussingOn; // which car is closer to the camera in 2 player cooperative mode with separate cars. // 272 - float CarWeAreFocussingOnI; // interpolated version + int CarWeAreFocussingOn; // which car is closer to the camera in 2 player cooperative mode with separate cars. // 272 + float CarWeAreFocussingOnI; // interpolated version - float m_fCamBumpedHorz; // 280 + float m_fCamBumpedHorz; // 280 float m_fCamBumpedVert; - int m_nCamBumpedTime; // 288 + int m_nCamBumpedTime; // 288 static int CAM_BUMPED_SWING_PERIOD; static int CAM_BUMPED_END_TIME; static float CAM_BUMPED_DAMP_RATE; static float CAM_BUMPED_MOVE_MULT; - CVector m_cvecSourceSpeedOverOneFrame; // 292 - CVector m_cvecTargetSpeedOverOneFrame; // 304 - CVector m_cvecUpOverOneFrame; // 316 + CVector m_cvecSourceSpeedOverOneFrame; // 292 + CVector m_cvecTargetSpeedOverOneFrame; // 304 + CVector m_cvecUpOverOneFrame; // 316 - CVector m_cvecTargetCoorsForFudgeInter; // 328 - CVector m_cvecCamFixedModeVector; // 340 - CVector m_cvecCamFixedModeSource; // 352 - CVector m_cvecCamFixedModeUpOffSet; // 364 - CVector m_vecLastAboveWaterCamPosition; // 376 //helper for when the player has gone under the water + CVector m_cvecTargetCoorsForFudgeInter; // 328 + CVector m_cvecCamFixedModeVector; // 340 + CVector m_cvecCamFixedModeSource; // 352 + CVector m_cvecCamFixedModeUpOffSet; // 364 + CVector m_vecLastAboveWaterCamPosition; // 376 //helper for when the player has gone under the water - CVector m_vecBufferedPlayerBodyOffset; // 388 + CVector m_vecBufferedPlayerBodyOffset; // 388 // The three vectors that determine this camera for this frame - CVector Front; // 400 // Direction of looking in - CVector Source; // Coors in world space - CVector SourceBeforeLookBehind; // 424 - CVector Up; // Just that - CVector m_arrPreviousVectors[NUMBER_OF_VECTORS_FOR_AVERAGE]; // used to average stuff // 448 + CVector Front; // 400 // Direction of looking in + CVector Source; // Coors in world space + CVector SourceBeforeLookBehind; // 424 + CVector Up; // Just that + CVector m_arrPreviousVectors[NUMBER_OF_VECTORS_FOR_AVERAGE]; // used to average stuff // 448 - CVector m_aTargetHistoryPos[CAM_NUM_TARGET_HISTORY]; // 472 - DWORD m_nTargetHistoryTime[CAM_NUM_TARGET_HISTORY]; // 520 - DWORD m_nCurrentHistoryPoints; // 536 + CVector m_aTargetHistoryPos[CAM_NUM_TARGET_HISTORY]; // 472 + DWORD m_nTargetHistoryTime[CAM_NUM_TARGET_HISTORY]; // 520 + DWORD m_nCurrentHistoryPoints; // 536 CEntitySAInterface* CamTargetEntity; public: - float m_fCameraDistance; // 544 + float m_fCameraDistance; // 544 float m_fIdealAlpha; - float m_fPlayerVelocity; // 552 + float m_fPlayerVelocity; // 552 // CVector TempRight; - CAutomobileSAInterface* m_pLastCarEntered; // So interpolation works - CPedSAInterface* m_pLastPedLookedAt; // So interpolation works - bool m_bFirstPersonRunAboutActive; // 564 + CAutomobileSAInterface* m_pLastCarEntered; // So interpolation works + CPedSAInterface* m_pLastPedLookedAt; // So interpolation works + bool m_bFirstPersonRunAboutActive; // 564 }; static_assert(sizeof(CCamSAInterface) == 0x238, "Invalid size for CCamSAInterface"); @@ -162,75 +162,54 @@ class CCamSA : public CCam CCamSAInterface* m_pInterface; public: - CCamSA(CCamSAInterface* pInterface) : m_pInterface(pInterface) + CCamSA(CCamSAInterface* pInterface) : m_pInterface(pInterface) { if (!pInterface) { m_pInterface = nullptr; } } - + CCamSAInterface* GetInterface() { return m_pInterface; } - CVector* GetFront() const override - { - return m_pInterface ? &m_pInterface->Front : nullptr; - } - - CVector* GetUp() const override - { - return m_pInterface ? &m_pInterface->Up : nullptr; - } - - CVector* GetSource() const override - { - return m_pInterface ? &m_pInterface->Source : nullptr; - } - - unsigned int GetMode() const override - { - return m_pInterface ? static_cast(m_pInterface->Mode) : 0; - } - - float GetFOV() const override - { + CVector* GetFront() const override { return m_pInterface ? &m_pInterface->Front : nullptr; } + + CVector* GetUp() const override { return m_pInterface ? &m_pInterface->Up : nullptr; } + + CVector* GetSource() const override { return m_pInterface ? &m_pInterface->Source : nullptr; } + + unsigned int GetMode() const override { return m_pInterface ? static_cast(m_pInterface->Mode) : 0; } + + float GetFOV() const override + { if (!m_pInterface) - return 70.0f; // Default FOV - + return 70.0f; // Default FOV + float fov = m_pInterface->FOV; return std::isfinite(fov) ? fov : 70.0f; } - - void SetFOV(float fFOV) override - { + + void SetFOV(float fFOV) override + { if (!m_pInterface) return; - + // Validate FOV range if (!std::isfinite(fFOV) || fFOV <= 0.0f || fFOV >= 180.0f) return; - - m_pInterface->FOV = fFOV; + + m_pInterface->FOV = fFOV; } void GetDirection(float& fHorizontal, float& fVertical) override; void SetDirection(float fHorizontal, float fVertical) override; - CVector* GetFixedModeSource() const override - { - return m_pInterface ? &m_pInterface->m_cvecCamFixedModeSource : nullptr; - } - - CVector* GetFixedModeVector() const override - { - return m_pInterface ? &m_pInterface->m_cvecCamFixedModeVector : nullptr; - } - - CVector* GetTargetHistoryPos() const override - { - return m_pInterface ? m_pInterface->m_aTargetHistoryPos : nullptr; - } + CVector* GetFixedModeSource() const override { return m_pInterface ? &m_pInterface->m_cvecCamFixedModeSource : nullptr; } + + CVector* GetFixedModeVector() const override { return m_pInterface ? &m_pInterface->m_cvecCamFixedModeVector : nullptr; } + + CVector* GetTargetHistoryPos() const override { return m_pInterface ? m_pInterface->m_aTargetHistoryPos : nullptr; } CEntity* GetTargetEntity() const override; void SetTargetEntity(CEntity* pEntity) override; -}; \ No newline at end of file +}; diff --git a/Client/game_sa/CCameraSA.cpp b/Client/game_sa/CCameraSA.cpp index dffdf6a4ed8..b40d4a93e4b 100644 --- a/Client/game_sa/CCameraSA.cpp +++ b/Client/game_sa/CCameraSA.cpp @@ -48,11 +48,11 @@ enum class CameraClipFlags : uint8_t static std::atomic s_cameraClipMask{static_cast(CameraClipFlags::Objects) | static_cast(CameraClipFlags::Vehicles)}; -#define VAR_CameraClipVehicles 0x8A5B14 -#define VAR_CameraClipDynamicObjects 0x8A5B15 -#define VAR_CameraClipStaticObjects 0x8A5B16 +#define VAR_CameraClipVehicles 0x8A5B14 +#define VAR_CameraClipDynamicObjects 0x8A5B15 +#define VAR_CameraClipStaticObjects 0x8A5B16 -#define HOOKPOS_Camera_CollisionDetection 0x520190 +#define HOOKPOS_Camera_CollisionDetection 0x520190 DWORD RETURN_Camera_CollisionDetection = 0x520195; void HOOK_Camera_CollisionDetection(); @@ -66,12 +66,13 @@ CCameraSA::CCameraSA(CCameraSAInterface* cameraInterface) Cams[i] = nullptr; return; } - + internalInterface = cameraInterface; - + for (int i = 0; i < MAX_CAMS; i++) { - try { + try + { Cams[i] = new CCamSA(&internalInterface->Cams[i]); } catch (...) @@ -86,9 +87,9 @@ CCameraSA::CCameraSA(CCameraSAInterface* cameraInterface) throw; } } - + s_cameraClipMask.store(static_cast(CameraClipFlags::Objects) | static_cast(CameraClipFlags::Vehicles), std::memory_order_relaxed); - + HookInstall(HOOKPOS_Camera_CollisionDetection, (DWORD)HOOK_Camera_CollisionDetection, 5); } @@ -110,7 +111,7 @@ void CCameraSA::Restore() if (!cameraInterface) return; - DWORD dwFunc = FUNC_Restore; + DWORD dwFunc = FUNC_Restore; // clang-format off __asm { @@ -125,7 +126,7 @@ void CCameraSA::RestoreWithJumpCut() CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return; - DWORD dwFunc = 0x50BD40; + DWORD dwFunc = 0x50BD40; // clang-format off __asm { @@ -150,7 +151,7 @@ void CCameraSA::TakeControl(CEntity* entity, eCamMode CamMode, int CamSwitchStyl { if (!entity) return; - + CEntitySA* pEntitySA = dynamic_cast(entity); if (!pEntitySA) return; @@ -158,7 +159,7 @@ void CCameraSA::TakeControl(CEntity* entity, eCamMode CamMode, int CamSwitchStyl CEntitySAInterface* entityInterface = pEntitySA->GetInterface(); if (!entityInterface) return; - + CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return; @@ -186,7 +187,7 @@ void CCameraSA::TakeControl(CVector* position, int CamSwitchStyle) { if (!position) return; - + CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return; @@ -291,14 +292,14 @@ CMatrix* CCameraSA::GetMatrix(CMatrix* matrix) { if (!matrix) return nullptr; - + CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) { *matrix = CMatrix(); return matrix; } - + CMatrix_Padded* pCamMatrix = &cameraInterface->m_cameraMatrix; if (pCamMatrix) { @@ -343,24 +344,24 @@ void CCameraSA::Find3rdPersonCamTargetVector(float fDistance, CVector* vecGunMuz { if (!vecGunMuzzle || !vecSource || !vecTarget) return; - + // Validate float parameter to prevent NaN/infinity issues if (!std::isfinite(fDistance) || fDistance < 0.0f) return; - - float fOriginX = vecGunMuzzle->fX; - float fOriginY = vecGunMuzzle->fY; - float fOriginZ = vecGunMuzzle->fZ; + + float fOriginX = vecGunMuzzle->fX; + float fOriginY = vecGunMuzzle->fY; + float fOriginZ = vecGunMuzzle->fZ; if (!std::isfinite(fOriginX) || !std::isfinite(fOriginY) || !std::isfinite(fOriginZ)) return; - + DWORD dwFunc = FUNC_Find3rdPersonCamTargetVector; CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return; - + // clang-format off __asm { @@ -382,8 +383,8 @@ float CCameraSA::Find3rdPersonQuickAimPitch() if (!cameraInterface) return 0.0f; - float fReturn; - DWORD dwFunc = FUNC_Find3rdPersonQuickAimPitch; + float fReturn; + DWORD dwFunc = FUNC_Find3rdPersonQuickAimPitch; // clang-format off __asm { @@ -446,7 +447,7 @@ bool CCameraSA::IsFading() CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return false; - bool bRet = false; + bool bRet = false; // clang-format off __asm { @@ -464,7 +465,7 @@ int CCameraSA::GetFadingDirection() CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return 0; - int dwRet = false; + int dwRet = false; // clang-format off __asm { @@ -485,18 +486,18 @@ void CCameraSA::Fade(float fFadeOutTime, int iOutOrIn) fFadeOutTime = 0.0f; else if (fFadeOutTime > 60.0f) fFadeOutTime = 60.0f; - + if (iOutOrIn < 0) iOutOrIn = 0; else if (iOutOrIn > 1) iOutOrIn = 1; - + DWORD dwFunc = FUNC_Fade; CCameraSAInterface* cameraInterface = GetInterface(); - + if (!cameraInterface) return; - + // clang-format off __asm { @@ -514,9 +515,9 @@ void CCameraSA::SetFadeColor(unsigned char ucRed, unsigned char ucGreen, unsigne CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return; - DWORD dwRed = ucRed; - DWORD dwGreen = ucGreen; - DWORD dwBlue = ucBlue; + DWORD dwRed = ucRed; + DWORD dwGreen = ucGreen; + DWORD dwBlue = ucBlue; // clang-format off __asm { @@ -539,15 +540,15 @@ RwMatrix* CCameraSA::GetLTM() CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface) return nullptr; - + if (!cameraInterface->m_pRwCamera) return nullptr; - + if (!cameraInterface->m_pRwCamera->object.object.parent) return nullptr; // RwFrameGetLTM - return ((RwMatrix*(_cdecl*)(void*))0x7F0990)(cameraInterface->m_pRwCamera->object.object.parent); + return ((RwMatrix * (_cdecl*)(void*))0x7F0990)(cameraInterface->m_pRwCamera->object.object.parent); } CEntity* CCameraSA::GetTargetEntity() @@ -705,35 +706,35 @@ bool CCameraSA::GetTransitionMatrix(CMatrix& matrix) const CCameraSAInterface* cameraInterface = GetInterface(); if (!cameraInterface || !IsInTransition()) return false; - + CVector source = cameraInterface->SourceDuringInter; CVector target = cameraInterface->TargetDuringInter; CVector up = cameraInterface->UpDuringInter; if (!IsFiniteVector(source) || !IsFiniteVector(target) || !IsFiniteVector(up)) return false; - + CVector forward = target - source; if (forward.Length() < FLOAT_EPSILON) forward = CVector(0.0f, 1.0f, 0.0f); else forward.Normalize(); - + CVector right = CVector(forward.fY, -forward.fX, 0.0f); if (right.Length() < FLOAT_EPSILON) right = CVector(1.0f, 0.0f, 0.0f); else right.Normalize(); - + CVector correctedUp = right; correctedUp.CrossProduct(&forward); correctedUp.Normalize(); - + matrix.vPos = source; matrix.vFront = forward; matrix.vRight = -right; matrix.vUp = correctedUp; matrix.OrthoNormalize(CMatrix::AXIS_FRONT, CMatrix::AXIS_UP); - + return true; } diff --git a/Client/game_sa/CCameraSA.h b/Client/game_sa/CCameraSA.h index 4ac94f8cd31..c8e4abaf21b 100644 --- a/Client/game_sa/CCameraSA.h +++ b/Client/game_sa/CCameraSA.h @@ -17,29 +17,29 @@ #include "CGarageSA.h" #include "CEntitySA.h" -#define FUNC_TakeControl 0x50C7C0 -#define FUNC_TakeControlNoEntity 0x50C8B0 -#define FUNC_Restore 0x50B930 +#define FUNC_TakeControl 0x50C7C0 +#define FUNC_TakeControlNoEntity 0x50C8B0 +#define FUNC_Restore 0x50B930 -#define FUNC_Find3rdPersonCamTargetVector 0x514970 -#define FUNC_Find3rdPersonQuickAimPitch 0x50AD40 -#define FUNC_GetFadingDirection 0x50ADF0 -#define FUNC_GetFading 0x50ADE0 -#define FUNC_Fade 0x50AC20 -#define FUNC_SetFadeColour 0x50BF00 -#define FUNC_ShakeCam 0x50A9F0 +#define FUNC_Find3rdPersonCamTargetVector 0x514970 +#define FUNC_Find3rdPersonQuickAimPitch 0x50AD40 +#define FUNC_GetFadingDirection 0x50ADF0 +#define FUNC_GetFading 0x50ADE0 +#define FUNC_Fade 0x50AC20 +#define FUNC_SetFadeColour 0x50BF00 +#define FUNC_ShakeCam 0x50A9F0 -#define VAR_CameraRotation 0xB6F178 // used for controling where the player faces -#define VAR_VehicleCameraView 0xB6F0DC -#define VAR_PedCameraView 0xB6F0F0 +#define VAR_CameraRotation 0xB6F178 // used for controling where the player faces +#define VAR_VehicleCameraView 0xB6F0DC +#define VAR_PedCameraView 0xB6F0F0 -#define MAX_CAMS 3 +#define MAX_CAMS 3 -#define MAX_NUM_OF_NODES 800 // for trains +#define MAX_NUM_OF_NODES 800 // for trains /*** R* Defines ***/ #define NUMBER_OF_VECTORS_FOR_AVERAGE 2 -#define MAX_NUM_OF_SPLINETYPES (4) +#define MAX_NUM_OF_SPLINETYPES (4) /*** END R* Defines ***/ /*** BEGIN PURE R* CLASSES ***/ @@ -51,15 +51,15 @@ class CCamPathSplines { MAXPATHLENGTH = 800 }; - float* m_arr_PathData; // FLOAT m_arr_PathData[MAXPATHLENGTH]; + float* m_arr_PathData; // FLOAT m_arr_PathData[MAXPATHLENGTH]; }; class CQueuedMode { public: - short Mode; // CameraMode - float Duration; // How long for (<0.0f -> indefinately) - short MinZoom, MaxZoom; // How far is player allowed to zoom in & out + short Mode; // CameraMode + float Duration; // How long for (<0.0f -> indefinately) + short MinZoom, MaxZoom; // How far is player allowed to zoom in & out }; class CTrainCamNode @@ -67,9 +67,9 @@ class CTrainCamNode public: CVector m_cvecCamPosition; CVector m_cvecPointToLookAt; - CVector m_cvecMinPointInRange; // this is the minimum required distance the train has to be to the camera to + CVector m_cvecMinPointInRange; // this is the minimum required distance the train has to be to the camera to // allow a switch to the node cam - CVector m_cvecMaxPointInRange; // this is the minimum required distance the train has to be to from the camera + CVector m_cvecMaxPointInRange; // this is the minimum required distance the train has to be to from the camera float m_fDesiredFOV; float m_fNearClip; // to switch from the the node cam @@ -88,7 +88,7 @@ class CCameraSAInterface : public CPlaceableSAInterface bool m_bCameraJustRestored; bool m_bcutsceneFinished; bool m_bCullZoneChecksOn; - bool m_bFirstPersonBeingUsed; // To indicate if the m_bFirstPersonBeingUsed viewer is being used. + bool m_bFirstPersonBeingUsed; // To indicate if the m_bFirstPersonBeingUsed viewer is being used. bool m_bJustJumpedOutOf1stPersonBecauseOfTarget; bool m_bIdleOn; bool m_bInATunnelAndABigVehicle; @@ -98,8 +98,8 @@ class CCameraSAInterface : public CPlaceableSAInterface bool m_bPlayerIsInGarage; bool m_bPlayerWasOnBike; bool m_bJustCameOutOfGarage; - bool m_bJustInitalised; // Just so the speed thingy doesn't go mad right at the start - unsigned char m_bJust_Switched; // Variable to indicate that we have jumped somewhere, Raymond needs this for the audio engine + bool m_bJustInitalised; // Just so the speed thingy doesn't go mad right at the start + unsigned char m_bJust_Switched; // Variable to indicate that we have jumped somewhere, Raymond needs this for the audio engine bool m_bLookingAtPlayer; bool m_bLookingAtVector; bool m_bMoveCamToAvoidGeom; @@ -109,14 +109,14 @@ class CCameraSAInterface : public CPlaceableSAInterface bool m_bUseNearClipScript; bool m_bStartInterScript; unsigned char m_bStartingSpline; - bool m_bTargetJustBeenOnTrain; // this variable is needed to be able to restore the camera + bool m_bTargetJustBeenOnTrain; // this variable is needed to be able to restore the camera bool m_bTargetJustCameOffTrain; bool m_bUseSpecialFovTrain; bool m_bUseTransitionBeta; bool m_bUseScriptZoomValuePed; bool m_bUseScriptZoomValueCar; bool m_bWaitForInterpolToFinish; - bool m_bItsOkToLookJustAtThePlayer; // Used when interpolating + bool m_bItsOkToLookJustAtThePlayer; // Used when interpolating bool m_bWantsToSwitchWidescreenOff; bool m_WideScreenOn; bool m_1rstPersonRunCloseToAWall; @@ -138,42 +138,42 @@ class CCameraSAInterface : public CPlaceableSAInterface bool m_vecDoingSpecialInterPolation; bool m_bScriptParametersSetForInterPol; - bool m_bFading; // to indicate that we are fading + bool m_bFading; // to indicate that we are fading bool m_bMusicFading; bool m_bMusicFadedOut; bool m_bFailedCullZoneTestPreviously; - bool m_FadeTargetIsSplashScreen; // used as hack for fading - bool WorldViewerBeingUsed; // To indicate if the world viewer is being used. - - unsigned char m_uiTransitionJUSTStarted; // This is the first frame of a transition. - unsigned char m_uiTransitionState; // 0:one mode 1:transition - unsigned char ActiveCam; // Which one at the moment (0 or 1) - // Their is a fudge at the end when the renderware matrix will receive either - // the active camera or the worldviewer camera - unsigned int m_uiCamShakeStart; // When did the camera shake start. + bool m_FadeTargetIsSplashScreen; // used as hack for fading + bool WorldViewerBeingUsed; // To indicate if the world viewer is being used. + + unsigned char m_uiTransitionJUSTStarted; // This is the first frame of a transition. + unsigned char m_uiTransitionState; // 0:one mode 1:transition + unsigned char ActiveCam; // Which one at the moment (0 or 1) + // Their is a fudge at the end when the renderware matrix will receive either + // the active camera or the worldviewer camera + unsigned int m_uiCamShakeStart; // When did the camera shake start. unsigned int m_uiFirstPersonCamLastInputTime; unsigned int m_uiLongestTimeInMill; unsigned int m_uiNumberOfTrainCamNodes; unsigned int m_uiTimeLastChange; unsigned int m_uiTimeWeLeftIdle_StillNoInput; unsigned int m_uiTimeWeEnteredIdle; - unsigned int m_uiTimeTransitionStart; // When was the transition started ? - unsigned int m_uiTransitionDuration; // How long does the transition take ? + unsigned int m_uiTimeTransitionStart; // When was the transition started ? + unsigned int m_uiTransitionDuration; // How long does the transition take ? unsigned int m_uiTransitionDurationTargetCoors; int m_BlurBlue; int m_BlurGreen; int m_BlurRed; int m_BlurType; - int m_iWorkOutSpeedThisNumFrames; // duh - int m_iNumFramesSoFar; // counter - int m_iCurrentTrainCamNode; // variable indicating which camera node we are at for the train - int m_motionBlur; // to indicate that we are fading + int m_iWorkOutSpeedThisNumFrames; // duh + int m_iNumFramesSoFar; // counter + int m_iCurrentTrainCamNode; // variable indicating which camera node we are at for the train + int m_motionBlur; // to indicate that we are fading int m_imotionBlurAddAlpha; int m_iCheckCullZoneThisNumFrames; int m_iZoneCullFrameNumWereAt; - int WhoIsInControlOfTheCamera; // to discern between obbe and scripts + int WhoIsInControlOfTheCamera; // to discern between obbe and scripts // float CarZoomIndicator; // float CarZoomValue; @@ -183,23 +183,23 @@ class CCameraSAInterface : public CPlaceableSAInterface // float m_fPedZoomValue; // float m_fPedZoomValueSmooth; // float m_fPedZoomValueScript; - int m_nCarZoom; // store zoom index - float m_fCarZoomBase; // store base zoom distance from index - float m_fCarZoomTotal; // store total zoom after modded by camera modes - float m_fCarZoomSmoothed; // buffered version of the var above + int m_nCarZoom; // store zoom index + float m_fCarZoomBase; // store base zoom distance from index + float m_fCarZoomTotal; // store total zoom after modded by camera modes + float m_fCarZoomSmoothed; // buffered version of the var above float m_fCarZoomValueScript; - int m_nPedZoom; // store zoom index - float m_fPedZoomBase; // store base zoom distance from index - float m_fPedZoomTotal; // store total zoom after modded by camera modes - float m_fPedZoomSmoothed; // buffered version of the var above + int m_nPedZoom; // store zoom index + float m_fPedZoomBase; // store base zoom distance from index + float m_fPedZoomTotal; // store total zoom after modded by camera modes + float m_fPedZoomSmoothed; // buffered version of the var above float m_fPedZoomValueScript; float CamFrontXNorm, CamFrontYNorm; float DistanceToWater; float HeightOfNearestWater; float FOVDuringInter; - float LODDistMultiplier; // This takes into account the FOV and the standard LOD multiplier Smaller aperture->bigger LOD multipliers. - float GenerationDistMultiplier; // This takes into account the FOV but noy the standard LOD multiplier + float LODDistMultiplier; // This takes into account the FOV and the standard LOD multiplier Smaller aperture->bigger LOD multipliers. + float GenerationDistMultiplier; // This takes into account the FOV but noy the standard LOD multiplier float m_fAlphaSpeedAtStartInter; float m_fAlphaWhenInterPol; @@ -213,47 +213,47 @@ class CCameraSAInterface : public CPlaceableSAInterface float m_fStartingAlphaForInterPol; float m_PedOrientForBehindOrInFront; - float m_CameraAverageSpeed; // this is an average depending on how many frames we work it out - float m_CameraSpeedSoFar; // this is a running total - float m_fCamShakeForce; // How severe is the camera shake. + float m_CameraAverageSpeed; // this is an average depending on how many frames we work it out + float m_CameraSpeedSoFar; // this is a running total + float m_fCamShakeForce; // How severe is the camera shake. float m_fFovForTrain; float m_fFOV_Wide_Screen; float m_fNearClipScript; - float m_fOldBetaDiff; // Needed for interpolation between 2 modes - float m_fPositionAlongSpline; // Variable used to indicate how far along the spline we are 0-1 for started to completed respectively + float m_fOldBetaDiff; // Needed for interpolation between 2 modes + float m_fPositionAlongSpline; // Variable used to indicate how far along the spline we are 0-1 for started to completed respectively float m_ScreenReductionPercentage; float m_ScreenReductionSpeed; float m_AlphaForPlayerAnim1rstPerson; - float Orientation; // The orientation of the camera. Used for peds walking. - float PlayerExhaustion; // How tired is player (inaccurate sniping) 0.0f-1.0f - // The following things are used by the sound code to - // play reverb depending on the surroundings. From a point - // in front of the camera the disance is measured to the - // nearest obstacle (building) - float SoundDistUp; //, SoundDistLeft, SoundDistRight; // These ones are buffered and should be used by the audio - float SoundDistUpAsRead; //, SoundDistLeftAsRead, SoundDistRightAsRead; - float SoundDistUpAsReadOld; //, SoundDistLeftAsReadOld, SoundDistRightAsReadOld; - // Very rough distance to the nearest water for the sound to use - // Front vector X&Y normalised to 1. Used by loads of stuff. + float Orientation; // The orientation of the camera. Used for peds walking. + float PlayerExhaustion; // How tired is player (inaccurate sniping) 0.0f-1.0f + // The following things are used by the sound code to + // play reverb depending on the surroundings. From a point + // in front of the camera the disance is measured to the + // nearest obstacle (building) + float SoundDistUp; //, SoundDistLeft, SoundDistRight; // These ones are buffered and should be used by the audio + float SoundDistUpAsRead; //, SoundDistLeftAsRead, SoundDistRightAsRead; + float SoundDistUpAsReadOld; //, SoundDistLeftAsReadOld, SoundDistRightAsReadOld; + // Very rough distance to the nearest water for the sound to use + // Front vector X&Y normalised to 1. Used by loads of stuff. float m_fAvoidTheGeometryProbsTimer; short m_nAvoidTheGeometryProbsDirn; - float m_fWideScreenReductionAmount; // 0 for not reduced 1 for fully reduced (Variable for Les) + float m_fWideScreenReductionAmount; // 0 for not reduced 1 for fully reduced (Variable for Les) float m_fStartingFOVForInterPol; // These ones are static so that they don't get cleared in CCamera::Init() - static float m_fMouseAccelHorzntl; // acceleration multiplier for 1st person controls - static float m_fMouseAccelVertical; // acceleration multiplier for 1st person controls + static float m_fMouseAccelHorzntl; // acceleration multiplier for 1st person controls + static float m_fMouseAccelVertical; // acceleration multiplier for 1st person controls static float m_f3rdPersonCHairMultX; static float m_f3rdPersonCHairMultY; - CCamSAInterface Cams[3]; // The actual cameras (usually only one of the two is active) - // And to complicate this we have a third camera, this camera is - // used for debugging when we want to have a look at the world. - // We can't change the camera mode because other objects depend on their + CCamSAInterface Cams[3]; // The actual cameras (usually only one of the two is active) + // And to complicate this we have a third camera, this camera is + // used for debugging when we want to have a look at the world. + // We can't change the camera mode because other objects depend on their // #########################################// // DATA NOT UPDATED FOR SA BELOW HERE!!!!! // @@ -266,10 +266,10 @@ class CCameraSAInterface : public CPlaceableSAInterface // for the sniper mode and rocket launcher mode. // This one overwrites the m_PlayerMode above. CQueuedMode PlayerWeaponMode; - CVector m_PreviousCameraPosition; // needed to work out speed - CVector m_RealPreviousCameraPosition; // This cane be used by stuff outside the camera code. The one above is the same as the current coordinates - // outwidth the camera code. an active camera for range finding etc - CVector m_cvecAimingTargetCoors; // Coors to look at with Gordons aiming thing + CVector m_PreviousCameraPosition; // needed to work out speed + CVector m_RealPreviousCameraPosition; // This cane be used by stuff outside the camera code. The one above is the same as the current coordinates + // outwidth the camera code. an active camera for range finding etc + CVector m_cvecAimingTargetCoors; // Coors to look at with Gordons aiming thing // The player camera that is waiting to be used // This camera can replace the default camera where this is // needed (in tricky situations like tunnels for instance) @@ -290,9 +290,9 @@ class CCameraSAInterface : public CPlaceableSAInterface CVector m_vecGameCamPos; CVector SourceDuringInter, TargetDuringInter, UpDuringInter; - CVector m_vecAttachedCamOffset; // for attaching the camera to a ped or vehicle (set by level designers for use in cutscenes) + CVector m_vecAttachedCamOffset; // for attaching the camera to a ped or vehicle (set by level designers for use in cutscenes) CVector m_vecAttachedCamLookAt; - float m_fAttachedCamAngle; // for giving the attached camera a tilt. + float m_fAttachedCamAngle; // for giving the attached camera a tilt. // RenderWare camera pointer RwCamera* m_pRwCamera; @@ -300,7 +300,7 @@ class CCameraSAInterface : public CPlaceableSAInterface CEntitySAInterface* pTargetEntity; CEntitySAInterface* pAttachedEntity; // CVector CutScene; - CCamPathSplines m_arrPathArray[MAX_NUM_OF_SPLINETYPES]; // These only get created when the script calls the load splines function + CCamPathSplines m_arrPathArray[MAX_NUM_OF_SPLINETYPES]; // These only get created when the script calls the load splines function // maybe this shouldn't be here depends if GTA_TRAIN is defined (its not) // CTrainCamNode m_arrTrainCamNode[MAX_NUM_OF_NODES]; @@ -343,7 +343,7 @@ class CCameraSAInterface : public CPlaceableSAInterface CVector m_vecOldFrontForInter; CVector m_vecOldUpForInter; float m_vecOldFOVForInter; - float m_fFLOATingFade; // variable representing the FLOAT version of CDraw::Fade. Necessary to stop loss of precision + float m_fFLOATingFade; // variable representing the FLOAT version of CDraw::Fade. Necessary to stop loss of precision float m_fFLOATingFadeMusic; float m_fTimeToFadeOut; float m_fTimeToFadeMusic; @@ -382,45 +382,45 @@ class CCameraSA : public CCamera ~CCameraSA(); CCameraSAInterface* GetInterface() const noexcept { return internalInterface; } - + // CCamera interface implementation - void TakeControl(CEntity* entity, eCamMode CamMode, int CamSwitchStyle) override; - void TakeControl(CVector* position, int CamSwitchStyle) override; - void Restore() override; - void RestoreWithJumpCut() override; - CMatrix* GetMatrix(CMatrix* matrix) override; - void SetMatrix(CMatrix* matrix) override; - void Find3rdPersonCamTargetVector(float fDistance, CVector* vecGunMuzzle, CVector* vecSource, CVector* vecTarget) override; - float Find3rdPersonQuickAimPitch() override; - BYTE GetActiveCam() override; - CCam* GetCam(BYTE bCameraID) override; - void SetWidescreen(bool bWidescreen) override; - bool GetWidescreen() override; - bool IsFading() override; - int GetFadingDirection() override; - void Fade(float fFadeOutTime, int iOutOrIn) override; - void SetFadeColor(unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue) override; - float GetCameraRotation() override; - RwMatrix* GetLTM() override; - CEntity* GetTargetEntity() override; - void SetCameraClip(bool bObjects, bool bVehicles) override; - void GetCameraClip(bool& bObjects, bool& bVehicles) override; - BYTE GetCameraVehicleViewMode() override; - BYTE GetCameraPedViewMode() override; - void SetCameraVehicleViewMode(BYTE dwCamMode) override; - void SetCameraPedViewMode(BYTE dwCamMode) override; - void SetShakeForce(float fShakeForce) override; - float GetShakeForce() override; - void ShakeCamera(float radius, float x, float y, float z) noexcept override; - void ResetShakeCamera() noexcept override; - std::uint8_t GetTransitionState() const override; - bool IsInTransition() const override; - float GetTransitionFOV() const override; - bool GetTransitionMatrix(CMatrix& matrix) const override; + void TakeControl(CEntity* entity, eCamMode CamMode, int CamSwitchStyle) override; + void TakeControl(CVector* position, int CamSwitchStyle) override; + void Restore() override; + void RestoreWithJumpCut() override; + CMatrix* GetMatrix(CMatrix* matrix) override; + void SetMatrix(CMatrix* matrix) override; + void Find3rdPersonCamTargetVector(float fDistance, CVector* vecGunMuzzle, CVector* vecSource, CVector* vecTarget) override; + float Find3rdPersonQuickAimPitch() override; + BYTE GetActiveCam() override; + CCam* GetCam(BYTE bCameraID) override; + void SetWidescreen(bool bWidescreen) override; + bool GetWidescreen() override; + bool IsFading() override; + int GetFadingDirection() override; + void Fade(float fFadeOutTime, int iOutOrIn) override; + void SetFadeColor(unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue) override; + float GetCameraRotation() override; + RwMatrix* GetLTM() override; + CEntity* GetTargetEntity() override; + void SetCameraClip(bool bObjects, bool bVehicles) override; + void GetCameraClip(bool& bObjects, bool& bVehicles) override; + BYTE GetCameraVehicleViewMode() override; + BYTE GetCameraPedViewMode() override; + void SetCameraVehicleViewMode(BYTE dwCamMode) override; + void SetCameraPedViewMode(BYTE dwCamMode) override; + void SetShakeForce(float fShakeForce) override; + float GetShakeForce() override; + void ShakeCamera(float radius, float x, float y, float z) noexcept override; + void ResetShakeCamera() noexcept override; + std::uint8_t GetTransitionState() const override; + bool IsInTransition() const override; + float GetTransitionFOV() const override; + bool GetTransitionMatrix(CMatrix& matrix) const override; // Additional overload not in base interface virtual CCam* GetCam(CCamSAInterface* camInterface); - + // Additional methods - void RestoreLastGoodState(); + void RestoreLastGoodState(); }; diff --git a/Client/game_sa/CCarEnterExitSA.h b/Client/game_sa/CCarEnterExitSA.h index f8bb9e621f2..58eb9c31b3a 100644 --- a/Client/game_sa/CCarEnterExitSA.h +++ b/Client/game_sa/CCarEnterExitSA.h @@ -13,11 +13,11 @@ #include -#define FUNC_GetNearestCarDoor 0x6528F0 -#define FUNC_GetNearestCarPassengerDoor 0x650BB0 -#define FUNC_ComputeTargetDoorToExit 0x64F110 -#define FUNC_IsRoomForPedToLeaveCar 0x6504C0 -#define FUNC_GetPositionToOpenCarDoor 0x64E740 +#define FUNC_GetNearestCarDoor 0x6528F0 +#define FUNC_GetNearestCarPassengerDoor 0x650BB0 +#define FUNC_ComputeTargetDoorToExit 0x64F110 +#define FUNC_IsRoomForPedToLeaveCar 0x6504C0 +#define FUNC_GetPositionToOpenCarDoor 0x64E740 class CCarEnterExitSA : public CCarEnterExit { diff --git a/Client/game_sa/CCheckpointSA.cpp b/Client/game_sa/CCheckpointSA.cpp index 56b7781a2de..3952621b853 100644 --- a/Client/game_sa/CCheckpointSA.cpp +++ b/Client/game_sa/CCheckpointSA.cpp @@ -153,12 +153,14 @@ static void __cdecl RenderTargetArrow(CCheckpointSAInterface* pCheckpoint) CVector* direction = checkpoint->GetPointDirection(); SColor color = checkpoint->GetTargetArrowColor(); - ((void(__cdecl*)(float, float, float, float, std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t, float, float, float))C3dMarkers_DirectionArrowSet)(position->fX, position->fY, position->fZ, checkpoint->GetTargetArrowSize(), color.R, color.G, color.B, color.A, -direction->fX, -direction->fY, -direction->fZ); + ((void(__cdecl*)(float, float, float, float, std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t, float, float, float))C3dMarkers_DirectionArrowSet)( + position->fX, position->fY, position->fZ, checkpoint->GetTargetArrowSize(), color.R, color.G, color.B, color.A, -direction->fX, -direction->fY, + -direction->fZ); } #define HOOKPOS_CCheckpoint__Render 0x725E56 #define HOOKSIZE_CCheckpoint__Render 5 -static constexpr intptr_t RETURN_CCheckpoint__Render = 0x725E5B; +static constexpr intptr_t RETURN_CCheckpoint__Render = 0x725E5B; static void __declspec(naked) HOOK_CCheckpoint__Render() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CCheckpointSA.h b/Client/game_sa/CCheckpointSA.h index 933934b2baa..454baa6cc35 100644 --- a/Client/game_sa/CCheckpointSA.h +++ b/Client/game_sa/CCheckpointSA.h @@ -25,7 +25,7 @@ class CCheckpointSAInterface DWORD m_nIdentifier; DWORD rwColour; WORD m_nPulsePeriod; - short m_nRotateRate; // deg per frame (in either direction) + short m_nRotateRate; // deg per frame (in either direction) CVector m_pos; CVector m_pointDir; float m_fPulseFraction; @@ -52,8 +52,8 @@ class CCheckpointSA : public CCheckpoint CVector* GetPosition(); void SetPointDirection(CVector* vecPointDirection); CVector* GetPointDirection(); - DWORD GetType(); // need enum? - void SetType(WORD wType); // doesn't work propperly (not virtualed) + DWORD GetType(); // need enum? + void SetType(WORD wType); // doesn't work propperly (not virtualed) bool IsActive(); void Activate(); DWORD GetIdentifier(); @@ -65,7 +65,7 @@ class CCheckpointSA : public CCheckpoint float GetSize(); void SetSize(float fSize); void SetCameraRange(float fCameraRange); - void SetPulseFraction(float fPulseFraction); // doesn't work propperly (not virtualed) + void SetPulseFraction(float fPulseFraction); // doesn't work propperly (not virtualed) float GetPulseFraction(); void Remove(); SColor GetTargetArrowColor() const noexcept override { return m_targetArrowColor; }; diff --git a/Client/game_sa/CCheckpointsSA.h b/Client/game_sa/CCheckpointsSA.h index b8f44914bf2..d1cfa913a62 100644 --- a/Client/game_sa/CCheckpointsSA.h +++ b/Client/game_sa/CCheckpointsSA.h @@ -18,10 +18,10 @@ class CVector; // 00722c40 public: static class CCheckpoint * __cdecl CCheckpoints::PlaceMarker(unsigned int,unsigned short,class CVector &,class CVector &,float,unsigned // char,unsigned char,unsigned char,unsigned char,unsigned short,float,short) -#define FUNC_CCheckpoints__PlaceMarker 0x722c40 +#define FUNC_CCheckpoints__PlaceMarker 0x722c40 -#define MAX_CHECKPOINTS 32 -#define ARRAY_CHECKPOINTS 0xC7F158 +#define MAX_CHECKPOINTS 32 +#define ARRAY_CHECKPOINTS 0xC7F158 class CCheckpointsSA : public CCheckpoints { diff --git a/Client/game_sa/CClockSA.h b/Client/game_sa/CClockSA.h index 44d0cf5c840..b7d128cef17 100644 --- a/Client/game_sa/CClockSA.h +++ b/Client/game_sa/CClockSA.h @@ -13,9 +13,9 @@ #include -#define VAR_TimeMinutes 0xB70152 -#define VAR_TimeHours 0xB70153 -#define VAR_TimeOfLastMinuteChange 0xB70158 +#define VAR_TimeMinutes 0xB70152 +#define VAR_TimeHours 0xB70153 +#define VAR_TimeOfLastMinuteChange 0xB70158 class CClockSA : public CClock { diff --git a/Client/game_sa/CColModelGuard.h b/Client/game_sa/CColModelGuard.h index 30218947932..6d029cc995b 100644 --- a/Client/game_sa/CColModelGuard.h +++ b/Client/game_sa/CColModelGuard.h @@ -13,18 +13,16 @@ #include "CModelInfoSA.h" - // Guard: Protects collision model from streaming GC class CColModelGuard { public: - // Increment ref count for pModelInfo's collision explicit CColModelGuard(CModelInfoSA* pModelInfo) : m_pModelInfo(pModelInfo), m_bValid(false), m_pColModel(nullptr), m_pColData(nullptr) { if (!m_pModelInfo) return; - + // Check and protect collision atomically if (m_pModelInfo->IsCollisionLoaded()) { @@ -113,19 +111,19 @@ class CColModelGuard // Check if collision is protected [[nodiscard]] bool IsValid() const noexcept { return m_bValid; } - // Get collision data (check IsValid first) - // Returns cached pointer or nullptr + // Get collision data (check IsValid first) + // Returns cached pointer or nullptr [[nodiscard]] CColDataSA* GetColData() const noexcept { return m_bValid ? m_pColData : nullptr; } - // Get collision model (check IsValid first) - // Returns cached pointer or nullptr + // Get collision model (check IsValid first) + // Returns cached pointer or nullptr [[nodiscard]] CColModelSAInterface* GetColModel() const noexcept { return m_bValid ? m_pColModel : nullptr; } explicit operator bool() const noexcept { return m_bValid; } private: - CModelInfoSA* m_pModelInfo; - bool m_bValid; - CColModelSAInterface* m_pColModel; // Cached during construction - CColDataSA* m_pColData; // Cached during construction + CModelInfoSA* m_pModelInfo; + bool m_bValid; + CColModelSAInterface* m_pColModel; // Cached during construction + CColDataSA* m_pColData; // Cached during construction }; diff --git a/Client/game_sa/CColModelSA.cpp b/Client/game_sa/CColModelSA.cpp index 1a969036978..420d8732d33 100644 --- a/Client/game_sa/CColModelSA.cpp +++ b/Client/game_sa/CColModelSA.cpp @@ -17,7 +17,7 @@ CColModelSA::CColModelSA() m_pInterface = new CColModelSAInterface; DWORD dwThis = (DWORD)m_pInterface; DWORD dwFunc = FUNC_CColModel_Constructor; - + try { // clang-format off @@ -28,13 +28,14 @@ CColModelSA::CColModelSA() } // clang-format on } - catch (...) - { - // Clean up on constructor failure - delete m_pInterface; - m_pInterface = nullptr; - throw; - } m_bDestroyInterface = true; + catch (...) + { + // Clean up on constructor failure + delete m_pInterface; + m_pInterface = nullptr; + throw; + } + m_bDestroyInterface = true; m_bValid = true; } @@ -48,12 +49,12 @@ CColModelSA::CColModelSA(CColModelSAInterface* pInterface) CColModelSA::~CColModelSA() { m_bValid = false; - + if (m_bDestroyInterface && m_pInterface) { DWORD dwThis = (DWORD)m_pInterface; DWORD dwFunc = FUNC_CColModel_Destructor; - + try { // clang-format off @@ -68,7 +69,7 @@ CColModelSA::~CColModelSA() { // Ensure cleanup completes on exception } - + delete m_pInterface; m_pInterface = nullptr; } diff --git a/Client/game_sa/CColModelSA.h b/Client/game_sa/CColModelSA.h index 74271e28391..c655085ed13 100644 --- a/Client/game_sa/CColModelSA.h +++ b/Client/game_sa/CColModelSA.h @@ -16,8 +16,8 @@ #include #include "CCompressedVectorSA.h" -#define FUNC_CColModel_Constructor 0x40FB60 -#define FUNC_CColModel_Destructor 0x40F700 +#define FUNC_CColModel_Constructor 0x40FB60 +#define FUNC_CColModel_Destructor 0x40F700 struct CBoxSA { @@ -65,12 +65,9 @@ struct CSphereSA { CVector m_center; float m_radius; - + // Validate radius is finite and non-negative - bool IsValidRadius() const - { - return std::isfinite(m_radius) && m_radius >= 0.0f && m_radius < 1000000.0f; - } + bool IsValidRadius() const { return std::isfinite(m_radius) && m_radius >= 0.0f && m_radius < 1000000.0f; } }; static_assert(sizeof(CSphereSA) == 0x10, "Invalid size for CSphereSA"); @@ -103,16 +100,10 @@ struct CColSphereSA : CSphereSA std::uint8_t m_light{}; CColSphereSA() = default; - CColSphereSA(const CSphereSA& sp) : - CSphereSA{ sp } - { - } - + CColSphereSA(const CSphereSA& sp) : CSphereSA{sp} {} + // Validate material enum is in valid range - bool IsValidMaterial() const - { - return static_cast(m_material) < static_cast(EColSurfaceValue::SIZE); - } + bool IsValidMaterial() const { return static_cast(m_material) < static_cast(EColSurfaceValue::SIZE); } }; static_assert(sizeof(CColSphereSA) == 0x14, "Invalid size for CColSphereSA"); @@ -121,20 +112,12 @@ struct CColTriangleSA std::uint16_t m_indices[3]; EColSurface m_material; CColLighting m_lighting; - + // Validate material enum is in valid range - bool IsValidMaterial() const - { - return static_cast(m_material) < static_cast(EColSurfaceValue::SIZE); - } - + bool IsValidMaterial() const { return static_cast(m_material) < static_cast(EColSurfaceValue::SIZE); } + // Validate indices are within vertex count bounds - bool IsValidIndices(std::uint16_t numVertices) const - { - return m_indices[0] < numVertices && - m_indices[1] < numVertices && - m_indices[2] < numVertices; - } + bool IsValidIndices(std::uint16_t numVertices) const { return m_indices[0] < numVertices && m_indices[1] < numVertices && m_indices[2] < numVertices; } }; static_assert(sizeof(CColTriangleSA) == 0x8, "Invalid size for CColTriangleSA"); diff --git a/Client/game_sa/CColPointSA.h b/Client/game_sa/CColPointSA.h index 247e0e5c258..e2ab73ab304 100644 --- a/Client/game_sa/CColPointSA.h +++ b/Client/game_sa/CColPointSA.h @@ -17,19 +17,19 @@ class CColPointSAInterface { public: - CVector Position; // 0 - float fUnknown1; // 12 - CVector Normal; // 16 - float fUnknown2; // 28 - EColSurface ucSurfaceTypeA; // 32 - uint8 ucPieceTypeA; // 33 - CColLighting lightingA; // 34 - EColSurface ucSurfaceTypeB; // 35 - uint8 ucPieceTypeB; // 36 - CColLighting lightingB; // 37 - uint8 pad1; // 38 - uint8 pad2; // 39 - float fDepth; // 40 + CVector Position; // 0 + float fUnknown1; // 12 + CVector Normal; // 16 + float fUnknown2; // 28 + EColSurface ucSurfaceTypeA; // 32 + uint8 ucPieceTypeA; // 33 + CColLighting lightingA; // 34 + EColSurface ucSurfaceTypeB; // 35 + uint8 ucPieceTypeB; // 36 + CColLighting lightingB; // 37 + uint8 pad1; // 38 + uint8 pad2; // 39 + float fDepth; // 40 }; static_assert(sizeof(CColPointSAInterface) == 0x2C, "Invalid size for CColPointSAInterface"); diff --git a/Client/game_sa/CColStoreSA.cpp b/Client/game_sa/CColStoreSA.cpp index 73fb5e5ab91..7cf9d7f8c27 100644 --- a/Client/game_sa/CColStoreSA.cpp +++ b/Client/game_sa/CColStoreSA.cpp @@ -62,16 +62,16 @@ void CColStoreSA::EnsureCollisionIsInMemory(const CVector& position) // Race condition: MTA can trigger streaming/collision operations before GTA completes initialization. // GTA calls CTimer::Initialise at 0x53BDE6 during startup, which sets _timerFunction at 0x56189E. // If called before GTA reaches GS_INIT_PLAYING_GAME, the timer isn't initialized > crash at 0x5619E9 (CTimer::Suspend) - + if (!pGame || pGame->GetSystemState() < SystemState::GS_INIT_PLAYING_GAME) return; // GTA not ready yet - skip (will retry on next streaming update) - + // Just in case constexpr auto ADDR_timerFunction = 0xB7CB28; - const auto timerFunction = *reinterpret_cast(ADDR_timerFunction); + const auto timerFunction = *reinterpret_cast(ADDR_timerFunction); if (!timerFunction) return; // Timer not initialized yet - skip - + // SA function signature: void __cdecl CColStore::EnsureCollisionIsInMemory(const CVector2D&) // CVector implicitly converts to CVector2D (uses x, y components only) using Signature = void(__cdecl*)(const CVector&); diff --git a/Client/game_sa/CCollisionSA.h b/Client/game_sa/CCollisionSA.h index e17a8f97dff..97209b3dd0a 100644 --- a/Client/game_sa/CCollisionSA.h +++ b/Client/game_sa/CCollisionSA.h @@ -13,7 +13,8 @@ #include "game/CCollision.h" -class CCollisionSA : CCollision { +class CCollisionSA : CCollision +{ public: bool TestLineSphere(const CColLineSA& line, const CColSphereSA& sphere) const override; }; diff --git a/Client/game_sa/CControllerConfigManagerSA.cpp b/Client/game_sa/CControllerConfigManagerSA.cpp index f2ca5f1bd37..e242e6429cd 100644 --- a/Client/game_sa/CControllerConfigManagerSA.cpp +++ b/Client/game_sa/CControllerConfigManagerSA.cpp @@ -12,11 +12,11 @@ #include "StdInc.h" #include "CControllerConfigManagerSA.h" -#define VAR_InputType ( ( BYTE * ) ( 0xB6EC2E ) ) -#define VAR_MouseInverted ( ( BYTE * ) ( 0xBA6745 ) ) -#define VAR_FlyWithMouse ( ( BYTE * ) ( 0xC1CC03 ) ) -#define VAR_SteerWithMouse ( ( BYTE * ) ( 0xC1CC02 ) ) -#define VAR_VerticalAimSensitivity ( ( float * ) ( 0xB6EC18 ) ) +#define VAR_InputType ((BYTE*)(0xB6EC2E)) +#define VAR_MouseInverted ((BYTE*)(0xBA6745)) +#define VAR_FlyWithMouse ((BYTE*)(0xC1CC03)) +#define VAR_SteerWithMouse ((BYTE*)(0xC1CC02)) +#define VAR_VerticalAimSensitivity ((float*)(0xB6EC18)) #define VAR_HorizontalMouseSensitivity 0xB6EC1C static const float VERTICAL_AIM_SENSITIVITY_MIN = 0.000312f; @@ -29,7 +29,7 @@ CControllerConfigManagerSA::CControllerConfigManagerSA() // Get initial settings m_bSteerWithMouse = *VAR_FlyWithMouse != 0; m_bFlyWithMouse = *VAR_SteerWithMouse != 0; - MemSet((void*)0x5BC7B4, 0x90, 10); // Stop vertical aim sensitivity value reset + MemSet((void*)0x5BC7B4, 0x90, 10); // Stop vertical aim sensitivity value reset } void CControllerConfigManagerSA::SetControllerKeyAssociatedWithAction(eControllerAction action, int iKey, eControllerType controllerType) @@ -139,7 +139,7 @@ void CControllerConfigManagerSA::ApplySteerAndFlyWithMouseSettings() float CControllerConfigManagerSA::GetVerticalAimSensitivity() { float fRawValue = GetVerticalAimSensitivityRawValue(); - return UnlerpClamped(VERTICAL_AIM_SENSITIVITY_MIN, fRawValue, VERTICAL_AIM_SENSITIVITY_MAX); // Remap to 0-1 + return UnlerpClamped(VERTICAL_AIM_SENSITIVITY_MIN, fRawValue, VERTICAL_AIM_SENSITIVITY_MAX); // Remap to 0-1 } void CControllerConfigManagerSA::SetVerticalAimSensitivity(float fSensitivity) @@ -163,9 +163,9 @@ void CControllerConfigManagerSA::SetVerticalAimSensitivitySameAsHorizontal(bool { std::uintptr_t varToUse = enabled ? VAR_HorizontalMouseSensitivity : reinterpret_cast(VAR_VerticalAimSensitivity); - MemPut(0x50F048, varToUse); // CCam::Process_1rstPersonPedOnPC - MemPut(0x50FB28, varToUse); // CCam::Process_FollowPedWithMouse - MemPut(0x510C28, varToUse); // CCam::Process_M16_1stPerson - MemPut(0x511E0A, varToUse); // CCam::Process_Rocket - MemPut(0x52228E, varToUse); // CCam::Process_AimWeapon + MemPut(0x50F048, varToUse); // CCam::Process_1rstPersonPedOnPC + MemPut(0x50FB28, varToUse); // CCam::Process_FollowPedWithMouse + MemPut(0x510C28, varToUse); // CCam::Process_M16_1stPerson + MemPut(0x511E0A, varToUse); // CCam::Process_Rocket + MemPut(0x52228E, varToUse); // CCam::Process_AimWeapon } diff --git a/Client/game_sa/CControllerConfigManagerSA.h b/Client/game_sa/CControllerConfigManagerSA.h index 9461843325d..496f7a0718b 100644 --- a/Client/game_sa/CControllerConfigManagerSA.h +++ b/Client/game_sa/CControllerConfigManagerSA.h @@ -13,12 +13,12 @@ #include -#define FUNC_SetControllerKeyAssociatedWithAction 0x530490 -#define FUNC_GetControllerKeyAssociatedWithAction 0x52F4F0 -#define FUNC_GetNumOfSettingsForAction 0x52F4A0 -#define FUNC_ClearSettingsAssociatedWithAction 0x52FD70 +#define FUNC_SetControllerKeyAssociatedWithAction 0x530490 +#define FUNC_GetControllerKeyAssociatedWithAction 0x52F4F0 +#define FUNC_GetNumOfSettingsForAction 0x52F4A0 +#define FUNC_ClearSettingsAssociatedWithAction 0x52FD70 -#define CLASS_CControllerConfigManager 0xB70198 +#define CLASS_CControllerConfigManager 0xB70198 class CControllerConfigManagerSA : public CControllerConfigManager { diff --git a/Client/game_sa/CCoronasSA.cpp b/Client/game_sa/CCoronasSA.cpp index 3b5ea191127..a908bcf7b41 100644 --- a/Client/game_sa/CCoronasSA.cpp +++ b/Client/game_sa/CCoronasSA.cpp @@ -86,18 +86,18 @@ RwTexture* CCoronasSA::GetTexture(CoronaType type) // Validate enum is within valid range if (static_cast(type) >= MAX_CORONA_TEXTURES) [[unlikely]] return nullptr; - + // Read texture pointer from array with validation DWORD* pTextureArray = reinterpret_cast(ARRAY_CORONA_TEXTURES); if (!pTextureArray) [[unlikely]] return nullptr; - + DWORD textureAddr = pTextureArray[static_cast(type)]; if (!textureAddr) [[unlikely]] return nullptr; - + RwTexture* pTexture = reinterpret_cast(textureAddr); - + return pTexture; } diff --git a/Client/game_sa/CCoronasSA.h b/Client/game_sa/CCoronasSA.h index e0e3297d1b4..3a5e039f611 100644 --- a/Client/game_sa/CCoronasSA.h +++ b/Client/game_sa/CCoronasSA.h @@ -18,12 +18,12 @@ class CRegisteredCorona; class CRegisteredCoronaSA; struct RwTexture; -#define FUNC_DoSunAndMoon 0x6FC5A0 +#define FUNC_DoSunAndMoon 0x6FC5A0 -#define MAX_CORONAS 64 -#define MAX_CORONA_TEXTURES 9 -#define ARRAY_CORONAS 0xC3E058 // also in CRegisteredCoronasSA.h -#define ARRAY_CORONA_TEXTURES 0xC3E000 +#define MAX_CORONAS 64 +#define MAX_CORONA_TEXTURES 9 +#define ARRAY_CORONAS 0xC3E058 // also in CRegisteredCoronasSA.h +#define ARRAY_CORONA_TEXTURES 0xC3E000 class CCoronasSA : public CCoronas { diff --git a/Client/game_sa/CDamageManagerSA.cpp b/Client/game_sa/CDamageManagerSA.cpp index b1cb441b3cd..a8e79783d37 100644 --- a/Client/game_sa/CDamageManagerSA.cpp +++ b/Client/game_sa/CDamageManagerSA.cpp @@ -146,8 +146,7 @@ void CDamageManagerSA::SetPanelStatus(BYTE bPanel, BYTE bPanelStatus, bool spawn } // clang-format on } - else - reinterpret_cast(internalEntityInterface)->SetPanelDamage(bPanel, breakGlass, spawnFlyingComponent); + else reinterpret_cast(internalEntityInterface)->SetPanelDamage(bPanel, breakGlass, spawnFlyingComponent); } } } @@ -273,19 +272,19 @@ int CDamageManagerSA::GetCarNodeIndexFromPanel(std::uint8_t panelId) noexcept switch (panelId) { case 0: - index = 15; // PANEL_WING_LF + index = 15; // PANEL_WING_LF break; case 1: - index = 14; // PANEL_WING_RF + index = 14; // PANEL_WING_RF break; case 4: - index = 18; // PANEL_WINDSCREEN + index = 18; // PANEL_WINDSCREEN break; case 5: - index = 12; // BUMP_FRONT + index = 12; // BUMP_FRONT break; case 6: - index = 13; // BUMP_REAR + index = 13; // BUMP_REAR break; } diff --git a/Client/game_sa/CDamageManagerSA.h b/Client/game_sa/CDamageManagerSA.h index cf1b66bc1a8..cccaf35f143 100644 --- a/Client/game_sa/CDamageManagerSA.h +++ b/Client/game_sa/CDamageManagerSA.h @@ -21,10 +21,10 @@ #define FUNC_GetAeroplaneCompStatus 0x6C2300 #define FUNC_FuckCarCompletely 0x6c25d0 -#define MAX_DOORS 6 // also in CAutomobile -#define MAX_WHEELS 4 +#define MAX_DOORS 6 // also in CAutomobile +#define MAX_WHEELS 4 -class CDamageManagerSAInterface // 28 bytes due to the way its packed (24 containing actual data) +class CDamageManagerSAInterface // 28 bytes due to the way its packed (24 containing actual data) { public: std::uint8_t GetPanelStatus(std::uint8_t panelId) @@ -36,11 +36,11 @@ class CDamageManagerSAInterface // 28 bytes due to the way its packed } float fWheelDamageEffect; - BYTE bEngineStatus; // old - wont be used + BYTE bEngineStatus; // old - wont be used BYTE Wheel[MAX_WHEELS]; BYTE Door[MAX_DOORS]; - DWORD Lights; // 2 bits per light - DWORD Panels; // 4 bits per panel + DWORD Lights; // 2 bits per light + DWORD Panels; // 4 bits per panel }; static_assert(sizeof(CDamageManagerSAInterface) == 0x18, "Invalid size for CDamageManagerSAInterface"); diff --git a/Client/game_sa/CDirectorySA.cpp b/Client/game_sa/CDirectorySA.cpp index d1e231d53c5..2600c9a4e72 100644 --- a/Client/game_sa/CDirectorySA.cpp +++ b/Client/game_sa/CDirectorySA.cpp @@ -96,7 +96,6 @@ bool CDirectorySAInterface::SetModelStreamingSize(std::uint16_t modelId, std::ui return true; } - std::uint16_t CDirectorySAInterface::GetModelStreamingSize(std::uint16_t modelId) { DirectoryInfoSA* entry = GetModelEntry(modelId); diff --git a/Client/game_sa/CDirectorySA.h b/Client/game_sa/CDirectorySA.h index 49d8812145a..13e0f4e3d23 100644 --- a/Client/game_sa/CDirectorySA.h +++ b/Client/game_sa/CDirectorySA.h @@ -20,18 +20,18 @@ struct DirectoryInfoSA class CDirectorySAInterface { - public: - bool AddEntry(DirectoryInfoSA& entry); - bool RemoveEntry(const char* fileName); +public: + bool AddEntry(DirectoryInfoSA& entry); + bool RemoveEntry(const char* fileName); - DirectoryInfoSA* GetModelEntry(const char* fileName); - DirectoryInfoSA* GetModelEntry(std::uint16_t modelId); - bool SetModelStreamingSize(std::uint16_t modelId, std::uint16_t size); - std::uint16_t GetModelStreamingSize(std::uint16_t modelId); + DirectoryInfoSA* GetModelEntry(const char* fileName); + DirectoryInfoSA* GetModelEntry(std::uint16_t modelId); + bool SetModelStreamingSize(std::uint16_t modelId, std::uint16_t size); + std::uint16_t GetModelStreamingSize(std::uint16_t modelId); - private: - DirectoryInfoSA* m_entries{}; - std::uint32_t m_capacity{}; - std::uint32_t m_numEntries{}; - bool m_ownsEntries{}; +private: + DirectoryInfoSA* m_entries{}; + std::uint32_t m_capacity{}; + std::uint32_t m_numEntries{}; + bool m_ownsEntries{}; }; diff --git a/Client/game_sa/CDoorSA.h b/Client/game_sa/CDoorSA.h index 7286227d91e..33d0775c07e 100644 --- a/Client/game_sa/CDoorSA.h +++ b/Client/game_sa/CDoorSA.h @@ -13,10 +13,10 @@ #include -#define FUNC_GetAngleOpenRatio 0x6f47e0 -#define FUNC_IsClosed 0x6f4800 -#define FUNC_IsFullyOpen 0x6f4820 -#define FUNC_Open 0x6f4790 +#define FUNC_GetAngleOpenRatio 0x6f47e0 +#define FUNC_IsClosed 0x6f4800 +#define FUNC_IsFullyOpen 0x6f4820 +#define FUNC_Open 0x6f4790 class CDoorSAInterface { @@ -45,9 +45,9 @@ class CDoorSA : public CDoor void SetInterface(CDoorSAInterface* doorInterface) { internalInterface = doorInterface; } CDoorSAInterface* GetInterface() { return internalInterface; }; - float GetAngleOpenRatio(); - bool IsClosed(); - bool IsFullyOpen(); - void Open(float fOpenRatio); + float GetAngleOpenRatio(); + bool IsClosed(); + bool IsFullyOpen(); + void Open(float fOpenRatio); DoorState GetDoorState() { return (DoorState)GetInterface()->m_nDoorState; }; }; diff --git a/Client/game_sa/CDummyPoolSA.h b/Client/game_sa/CDummyPoolSA.h index 5b954a5a4a5..2cecf7ae8c3 100644 --- a/Client/game_sa/CDummyPoolSA.h +++ b/Client/game_sa/CDummyPoolSA.h @@ -33,7 +33,7 @@ class CDummyPoolSA final : public CDummyPool void UpdateLodsOffestInPool(const std::uint32_t offset); private: - CPoolSAInterface** m_ppDummyPoolInterface; + CPoolSAInterface** m_ppDummyPoolInterface; using building_buffer_t = std::uint8_t[sizeof(CEntitySAInterface)]; using pool_backup_t = std::array, MAX_DUMMIES_DEFAULT>; diff --git a/Client/game_sa/CDynamicPool.h b/Client/game_sa/CDynamicPool.h index f99388f58ec..dbc93db74c4 100644 --- a/Client/game_sa/CDynamicPool.h +++ b/Client/game_sa/CDynamicPool.h @@ -120,7 +120,8 @@ class CDynamicPool return size; } - bool SetCapacity(std::size_t newSize) { + bool SetCapacity(std::size_t newSize) + { if (newSize == 0) return false; @@ -163,7 +164,7 @@ class CDynamicPool return true; } } - + return true; } diff --git a/Client/game_sa/CEntitySA.cpp b/Client/game_sa/CEntitySA.cpp index 54d9c660b0d..30a9fc813ed 100644 --- a/Client/game_sa/CEntitySA.cpp +++ b/Client/game_sa/CEntitySA.cpp @@ -62,7 +62,7 @@ CRect* CEntitySAInterface::GetBoundRect_(CRect* pRect) TransformFromObjectSpace(point, vecMax); rect.StretchToPoint(point.fX, point.fY); *pRect = rect; - pRect->FixIncorrectTopLeft(); // Fix #1613: custom map collision crashes in CPhysical class (infinite loop) + pRect->FixIncorrectTopLeft(); // Fix #1613: custom map collision crashes in CPhysical class (infinite loop) return pRect; } @@ -100,8 +100,7 @@ bool CEntitySA::SetScaleInternal(const CVector& scale) void CEntitySA::SetPosition(float fX, float fY, float fZ) { // Remove & add to world? - if (std::isnan(fX) || std::isnan(fY) || std::isnan(fZ) || - std::isinf(fX) || std::isinf(fY) || std::isinf(fZ)) + if (std::isnan(fX) || std::isnan(fY) || std::isnan(fZ) || std::isinf(fX) || std::isinf(fY) || std::isinf(fZ)) return; CVector* vecPos; @@ -145,8 +144,7 @@ void CEntitySA::SetPosition(float fX, float fY, float fZ) void CEntitySA::Teleport(float fX, float fY, float fZ) { - if (std::isnan(fX) || std::isnan(fY) || std::isnan(fZ) || - std::isinf(fX) || std::isinf(fY) || std::isinf(fZ)) + if (std::isnan(fX) || std::isnan(fY) || std::isnan(fZ) || std::isinf(fX) || std::isinf(fY) || std::isinf(fZ)) return; if (m_pInterface->matrix) @@ -174,7 +172,7 @@ void CEntitySA::SetupLighting() void CEntitySA::Render() { // This function may use m_pInterface->Render() - DWORD dwFunc = 0x59F180; // m_pInterface->vtbl->Render; + DWORD dwFunc = 0x59F180; // m_pInterface->vtbl->Render; DWORD dwThis = (DWORD)m_pInterface; // clang-format off __asm @@ -352,7 +350,7 @@ void CEntitySA::SetMatrix(CMatrix* matrix) pGame->GetWorld()->Remove(this, CEntity_SetMatrix); DWORD dwThis = (DWORD)m_pInterface; - DWORD dwFunc = 0x446F90; // CEntity::UpdateRwMatrix + DWORD dwFunc = 0x446F90; // CEntity::UpdateRwMatrix // clang-format off __asm { @@ -361,7 +359,7 @@ void CEntitySA::SetMatrix(CMatrix* matrix) } // clang-format on - dwFunc = 0x532B00; // CEntity::UpdateRwFrame + dwFunc = 0x532B00; // CEntity::UpdateRwFrame // clang-format off __asm { @@ -418,7 +416,7 @@ eEntityStatus CEntitySA::GetEntityStatus() RwFrame* CEntitySA::GetFrameFromId(int id) { // CClumpModelInfo::GetFrameFromId - return ((RwFrame*(_cdecl*)(RpClump*, int))0x4C53C0)(m_pInterface->m_pRwObject, id); + return ((RwFrame * (_cdecl*)(RpClump*, int))0x4C53C0)(m_pInterface->m_pRwObject, id); } RpClump* CEntitySA::GetRpClump() @@ -429,7 +427,7 @@ RpClump* CEntitySA::GetRpClump() RwMatrix* CEntitySA::GetLTMFromId(int id) { // RwFrameGetLTM - return ((RwMatrix*(_cdecl*)(RwFrame*))0x7F0990)(GetFrameFromId(id)); + return ((RwMatrix * (_cdecl*)(RwFrame*))0x7F0990)(GetFrameFromId(id)); } void CEntitySA::SetAlpha(DWORD dwAlpha) @@ -629,7 +627,7 @@ bool CEntitySA::SetBoneRotation(eBone boneId, float yaw, float pitch, float roll return false; RtQuat* boneOrientation = &frameData->m_pIFrame->orientation; - RwV3d angles = { yaw, roll, pitch }; + RwV3d angles = {yaw, roll, pitch}; BoneNode_cSAInterface::EulerToQuat(&angles, boneOrientation); CEntitySAInterface* theInterface = GetInterface(); if (theInterface) diff --git a/Client/game_sa/CEntitySA.h b/Client/game_sa/CEntitySA.h index 815193338ca..ef69c6fbf27 100644 --- a/Client/game_sa/CEntitySA.h +++ b/Client/game_sa/CEntitySA.h @@ -16,17 +16,17 @@ #include #include -#define FUNC_GetDistanceFromCentreOfMassToBaseOfModel 0x536BE0 +#define FUNC_GetDistanceFromCentreOfMassToBaseOfModel 0x536BE0 -#define FUNC_SetRwObjectAlpha 0x5332C0 +#define FUNC_SetRwObjectAlpha 0x5332C0 -#define FUNC_CMatrix__ConvertToEulerAngles 0x59A840 -#define FUNC_CMatrix__ConvertFromEulerAngles 0x59AA40 +#define FUNC_CMatrix__ConvertToEulerAngles 0x59A840 +#define FUNC_CMatrix__ConvertFromEulerAngles 0x59AA40 -#define FUNC_IsVisible 0x536BC0 +#define FUNC_IsVisible 0x536BC0 // not in CEntity really -#define FUNC_RpAnimBlendClumpGetAssociation 0x4D6870 +#define FUNC_RpAnimBlendClumpGetAssociation 0x4D6870 class CPhysicalSAInterface; class CRect; @@ -52,8 +52,8 @@ class CMatrixEx { public: CMatrix_Padded matrix; - CMatrix* pMatrix; // usually not initialized - void* haveRwMatrix; // unknown pointer + CMatrix* pMatrix; // usually not initialized + void* haveRwMatrix; // unknown pointer }; class XYZ @@ -106,69 +106,68 @@ class CEntitySAInterface : public CPlaceableSAInterface virtual void FlagToDestroyWhenNextProcessed() = 0; public: - RpClump* m_pRwObject; // 24 + RpClump* m_pRwObject; // 24 /********** BEGIN CFLAGS **************/ - unsigned long bUsesCollision : 1; // does entity use collision - unsigned long bCollisionProcessed : 1; // has object been processed by a ProcessEntityCollision function - unsigned long bIsStatic : 1; // is entity static - unsigned long bHasContacted : 1; // has entity processed some contact forces - unsigned long bIsStuck : 1; // is entity stuck - unsigned long bIsInSafePosition : 1; // is entity in a collision free safe position - unsigned long bWasPostponed : 1; // was entity control processing postponed - unsigned long bIsVisible : 1; // is the entity visible - - unsigned long bIsBIGBuilding : 1; // Set if this entity is a big building - unsigned long bRenderDamaged : 1; // use damaged LOD models for objects with applicable damage - unsigned long bStreamingDontDelete : 1; // Dont let the streaming remove this - unsigned long bRemoveFromWorld : 1; // remove this entity next time it should be processed - unsigned long bHasHitWall : 1; // has collided with a building (changes subsequent collisions) - unsigned long bImBeingRendered : 1; // don't delete me because I'm being rendered - unsigned long bDrawLast : 1; // draw object last - unsigned long bDistanceFade : 1; // Fade entity because it is far away + unsigned long bUsesCollision : 1; // does entity use collision + unsigned long bCollisionProcessed : 1; // has object been processed by a ProcessEntityCollision function + unsigned long bIsStatic : 1; // is entity static + unsigned long bHasContacted : 1; // has entity processed some contact forces + unsigned long bIsStuck : 1; // is entity stuck + unsigned long bIsInSafePosition : 1; // is entity in a collision free safe position + unsigned long bWasPostponed : 1; // was entity control processing postponed + unsigned long bIsVisible : 1; // is the entity visible + + unsigned long bIsBIGBuilding : 1; // Set if this entity is a big building + unsigned long bRenderDamaged : 1; // use damaged LOD models for objects with applicable damage + unsigned long bStreamingDontDelete : 1; // Dont let the streaming remove this + unsigned long bRemoveFromWorld : 1; // remove this entity next time it should be processed + unsigned long bHasHitWall : 1; // has collided with a building (changes subsequent collisions) + unsigned long bImBeingRendered : 1; // don't delete me because I'm being rendered + unsigned long bDrawLast : 1; // draw object last + unsigned long bDistanceFade : 1; // Fade entity because it is far away unsigned long bDontCastShadowsOn : 1; // Dont cast shadows on this object unsigned long bOffscreen : 1; // offscreen flag. This can only be trusted when it is set to true - unsigned long - bIsStaticWaitingForCollision : 1; // this is used by script created entities - they are static until the collision is loaded below them - unsigned long bDontStream : 1; // tell the streaming not to stream me - unsigned long bUnderwater : 1; // this object is underwater change drawing order - unsigned long bHasPreRenderEffects : 1; // Object has a prerender effects attached to it - unsigned long bIsTempBuilding : 1; // whether or not the building is temporary (i.e. can be created and deleted more than once) - unsigned long bDontUpdateHierarchy : 1; // Don't update the aniamtion hierarchy this frame - - unsigned long bHasRoadsignText : 1; // entity is roadsign and has some 2deffect text stuff to be rendered + unsigned long bIsStaticWaitingForCollision : 1; // this is used by script created entities - they are static until the collision is loaded below them + unsigned long bDontStream : 1; // tell the streaming not to stream me + unsigned long bUnderwater : 1; // this object is underwater change drawing order + unsigned long bHasPreRenderEffects : 1; // Object has a prerender effects attached to it + unsigned long bIsTempBuilding : 1; // whether or not the building is temporary (i.e. can be created and deleted more than once) + unsigned long bDontUpdateHierarchy : 1; // Don't update the aniamtion hierarchy this frame + + unsigned long bHasRoadsignText : 1; // entity is roadsign and has some 2deffect text stuff to be rendered unsigned long bDisplayedSuperLowLOD : 1; - unsigned long bIsProcObject : 1; // set object has been generate by procedural object generator - unsigned long bBackfaceCulled : 1; // has backface culling on - unsigned long bLightObject : 1; // light object with directional lights - unsigned long bUnimportantStream : 1; // set that this object is unimportant, if streaming is having problems - unsigned long bTunnel : 1; // Is this model part of a tunnel - unsigned long bTunnelTransition : 1; // This model should be rendered from within and outside of the tunnel + unsigned long bIsProcObject : 1; // set object has been generate by procedural object generator + unsigned long bBackfaceCulled : 1; // has backface culling on + unsigned long bLightObject : 1; // light object with directional lights + unsigned long bUnimportantStream : 1; // set that this object is unimportant, if streaming is having problems + unsigned long bTunnel : 1; // Is this model part of a tunnel + unsigned long bTunnelTransition : 1; // This model should be rendered from within and outside of the tunnel /********** END CFLAGS **************/ - WORD RandomSeed; // 32 - WORD m_nModelIndex; // 34 - CReferences* pReferences; // 36 + WORD RandomSeed; // 32 + WORD m_nModelIndex; // 34 + CReferences* pReferences; // 36 - DWORD* m_pLastRenderedLink; // CLink* m_pLastRenderedLink; +40 + DWORD* m_pLastRenderedLink; // CLink* m_pLastRenderedLink; +40 - WORD m_nScanCode; // 44 - BYTE m_iplIndex; // used to define which IPL file object is in +46 - BYTE m_areaCode; // used to define what objects are visible at this point +47 + WORD m_nScanCode; // 44 + BYTE m_iplIndex; // used to define which IPL file object is in +46 + BYTE m_areaCode; // used to define what objects are visible at this point +47 // LOD shit - CEntitySAInterface* m_pLod; // 48 + CEntitySAInterface* m_pLod; // 48 // num child higher level LODs - BYTE numLodChildren; // 52 + BYTE numLodChildren; // 52 // num child higher level LODs that have been rendered - signed char numLodChildrenRendered; // 53 + signed char numLodChildrenRendered; // 53 //********* BEGIN CEntityInfo **********// - BYTE nType : 3; // what type is the entity // 54 (2 == Vehicle) - BYTE nStatus : 5; // control status // 54 + BYTE nType : 3; // what type is the entity // 54 (2 == Vehicle) + BYTE nStatus : 5; // control status // 54 //********* END CEntityInfo **********// - uint8 m_pad0; // 55 + uint8 m_pad0; // 55 CRect* GetBoundRect_(CRect* pRect); void TransformFromObjectSpace(CVector& outPosn, CVector const& offset); @@ -181,7 +180,7 @@ class CEntitySAInterface : public CPlaceableSAInterface // Functions to hide member variable misuse // - void SetLod(CEntitySAInterface* pLod) noexcept { m_pLod = pLod; }; + void SetLod(CEntitySAInterface* pLod) noexcept { m_pLod = pLod; }; CEntitySAInterface* GetLod() const noexcept { return m_pLod; }; // Sets @@ -219,7 +218,8 @@ class CEntitySAInterface : public CPlaceableSAInterface ((CStencilShadow_dtorByOwner)0x711730)(this); }; - void RemoveRWObjectWithReferencesCleanup() { + void RemoveRWObjectWithReferencesCleanup() + { DeleteRwObject(); ResolveReferences(); RemoveShadows(); @@ -249,7 +249,7 @@ class CEntitySA : public virtual CEntity void SetupLighting(); void Render(); void SetOrientation(float fX, float fY, float fZ); - void FixBoatOrientation(); // eAi you might want to rename this + void FixBoatOrientation(); // eAi you might want to rename this void SetPosition(CVector* vecPosition); void SetUnderwater(bool bUnderwater); @@ -282,8 +282,8 @@ class CEntitySA : public virtual CEntity RpClump* GetRpClump(); - bool BeingDeleted; // to prevent it trying to delete twice - bool DoNotRemoveFromGame; // when deleted, if this is true, it won't be removed from the game + bool BeingDeleted; // to prevent it trying to delete twice + bool DoNotRemoveFromGame; // when deleted, if this is true, it won't be removed from the game void SetDoNotRemoveFromGameWhenDeleted(bool bDoNotRemoveFromGame) { DoNotRemoveFromGame = bDoNotRemoveFromGame; }; bool IsStatic() { return m_pInterface->bIsStatic; } diff --git a/Client/game_sa/CEventDamageSA.h b/Client/game_sa/CEventDamageSA.h index 949fad4c061..92e0d0e51cd 100644 --- a/Client/game_sa/CEventDamageSA.h +++ b/Client/game_sa/CEventDamageSA.h @@ -18,44 +18,44 @@ class CEntitySAInterface; enum eWeaponType; enum ePedPieceTypes; -#define FUNC_CEventDamage_Constructor 0x4ad830 -#define FUNC_CEventDamage_Destructor 0x4ad960 -#define FUNC_CEventDamage_HasKilledPed 0x4ABCA0 -#define FUNC_CEventDamage_GetDamageApplied 0x4ABCE0 -#define FUNC_CEventDamage_GetAnimGroup 0x4B8060 -#define FUNC_CEventDamage_GetAnimId 0x4B8070 -#define FUNC_CEventDamage_GetAnimAdded 0x4b80a0 -#define FUNC_CEventDamage_ComputeDeathAnim 0x4B3A60 -#define FUNC_CEventDamage_ComputeDamageAnim 0x4b3fc0 -#define FUNC_CEventDamage_AffectsPed 0x4b35a0 +#define FUNC_CEventDamage_Constructor 0x4ad830 +#define FUNC_CEventDamage_Destructor 0x4ad960 +#define FUNC_CEventDamage_HasKilledPed 0x4ABCA0 +#define FUNC_CEventDamage_GetDamageApplied 0x4ABCE0 +#define FUNC_CEventDamage_GetAnimGroup 0x4B8060 +#define FUNC_CEventDamage_GetAnimId 0x4B8070 +#define FUNC_CEventDamage_GetAnimAdded 0x4b80a0 +#define FUNC_CEventDamage_ComputeDeathAnim 0x4B3A60 +#define FUNC_CEventDamage_ComputeDamageAnim 0x4b3fc0 +#define FUNC_CEventDamage_AffectsPed 0x4b35a0 class CEventDamageSAInterface { public: - DWORD vmt; // 0 - DWORD ticks; // 4 - BYTE unk8; // 8 - BYTE unk9; // 9 - BYTE unkA; // Ah - BYTE unkB; // Bh - BYTE unkC; // Ch - BYTE unkD; // Dh - WORD unkE; // Eh - WORD unk10; // 10h - WORD unk12; // 12h - CEntitySAInterface* pInflictor; // 14h - DWORD damageTime; // 18h - eWeaponType weaponUsed; // 1Ch - ePedPieceTypes pedPieceType; // 20h - BYTE ucDirection; // 24h - BYTE ucFlags; // 25h - BYTE unk26; // 26h - BYTE unk27; // 27h - DWORD dwAnimGroup; // 28h - DWORD dwAnimID; // 2Ch - float fAnimBlend; // 30h - float fAnimSpeed; // 34h - CPedDamageResponseSAInterface damageResponseData; // 38h + DWORD vmt; // 0 + DWORD ticks; // 4 + BYTE unk8; // 8 + BYTE unk9; // 9 + BYTE unkA; // Ah + BYTE unkB; // Bh + BYTE unkC; // Ch + BYTE unkD; // Dh + WORD unkE; // Eh + WORD unk10; // 10h + WORD unk12; // 12h + CEntitySAInterface* pInflictor; // 14h + DWORD damageTime; // 18h + eWeaponType weaponUsed; // 1Ch + ePedPieceTypes pedPieceType; // 20h + BYTE ucDirection; // 24h + BYTE ucFlags; // 25h + BYTE unk26; // 26h + BYTE unk27; // 27h + DWORD dwAnimGroup; // 28h + DWORD dwAnimID; // 2Ch + float fAnimBlend; // 30h + float fAnimSpeed; // 34h + CPedDamageResponseSAInterface damageResponseData; // 38h }; class CEventDamageSA : public CEventDamage diff --git a/Client/game_sa/CExplosionManagerSA.h b/Client/game_sa/CExplosionManagerSA.h index db6c6c2e9e6..0795e9f898f 100644 --- a/Client/game_sa/CExplosionManagerSA.h +++ b/Client/game_sa/CExplosionManagerSA.h @@ -16,10 +16,10 @@ class CExplosion; class CExplosionSA; -#define FUNC_CExplosion_AddExplosion 0x736A50 +#define FUNC_CExplosion_AddExplosion 0x736A50 -#define ARRAY_Explosions 0xC88950 -#define MAX_EXPLOSIONS 48 +#define ARRAY_Explosions 0xC88950 +#define MAX_EXPLOSIONS 48 class CExplosionManagerSA : public CExplosionManager { diff --git a/Client/game_sa/CExplosionSA.h b/Client/game_sa/CExplosionSA.h index 1d19925153d..54790c4298b 100644 --- a/Client/game_sa/CExplosionSA.h +++ b/Client/game_sa/CExplosionSA.h @@ -16,7 +16,7 @@ class CEntitySAInterface; -class CExplosionSAInterface // 124 bytes, ok +class CExplosionSAInterface // 124 bytes, ok { public: eExplosionType m_ExplosionType; @@ -24,15 +24,15 @@ class CExplosionSAInterface // 124 bytes, ok float m_fExplosionRadius; float m_fExplosionPropagationRate; CEntitySAInterface* m_pEntExplosionOwner; - CEntitySAInterface* m_pExplodingEntity; // 28 + CEntitySAInterface* m_pExplodingEntity; // 28 DWORD m_TimeExpires; float m_DamagePercentage; - BYTE m_cExplosionActive; // 36 + BYTE m_cExplosionActive; // 36 BYTE m_nTriggerExplosionSfx; BYTE m_bMakeSound; - float m_ParticleTimer; // 40 - DWORD m_ActivationTime; // 44 - float m_fExplosionForce; // 48 + float m_ParticleTimer; // 40 + DWORD m_ActivationTime; // 44 + float m_fExplosionForce; // 48 float m_fGroundZ; DWORD m_fuelTime; CVector m_fuelDir[3]; diff --git a/Client/game_sa/CFileLoaderSA.cpp b/Client/game_sa/CFileLoaderSA.cpp index fccb30b4917..3b726c9202b 100644 --- a/Client/game_sa/CFileLoaderSA.cpp +++ b/Client/game_sa/CFileLoaderSA.cpp @@ -66,7 +66,8 @@ void GetNameAndDamage(const char* nodeName, char (&outName)[OutBuffSize], bool& { const auto nodeNameLen = strlen(nodeName); - const auto NodeNameEndsWith = [=](const char* with) { + const auto NodeNameEndsWith = [=](const char* with) + { const auto withLen = strlen(with); // dassert(withLen <= nodeNameLen); return withLen <= nodeNameLen /*dont bother checking otherwise, because it might cause a crash*/ @@ -75,7 +76,8 @@ void GetNameAndDamage(const char* nodeName, char (&outName)[OutBuffSize], bool& // Copy `nodeName` into `outName` with `off` trimmed from the end // Eg.: `dmg_dam` with `off = 4` becomes `dmg` - const auto TerminatedCopy = [&](size_t off) { + const auto TerminatedCopy = [&](size_t off) + { dassert(nodeNameLen >= off && nodeNameLen - off < OutBuffSize); const size_t copyLen = std::min(nodeNameLen - off, OutBuffSize - 1); strncpy_s(outName, nodeName, copyLen); @@ -242,11 +244,12 @@ CEntitySAInterface* CFileLoader_LoadObjectInstance(const char* szLine) SFileObjectInstance inst; // Use safer scanf with width specifier to prevent buffer overflow - int result = sscanf(szLine, "%d %23s %d %f %f %f %f %f %f %f %d", &inst.modelID, szModelName, &inst.interiorID, &inst.position.fX, &inst.position.fY, &inst.position.fZ, - &inst.rotation.fX, &inst.rotation.fY, &inst.rotation.fZ, &inst.rotation.fW, &inst.lod); - + int result = sscanf(szLine, "%d %23s %d %f %f %f %f %f %f %f %d", &inst.modelID, szModelName, &inst.interiorID, &inst.position.fX, &inst.position.fY, + &inst.position.fZ, &inst.rotation.fX, &inst.rotation.fY, &inst.rotation.fZ, &inst.rotation.fW, &inst.lod); + // Check if all expected fields were parsed - if (result != 11) { + if (result != 11) + { // Return null or handle error appropriately return nullptr; } diff --git a/Client/game_sa/CFireManagerSA.cpp b/Client/game_sa/CFireManagerSA.cpp index ea4a8a45ccf..2243b84e4d2 100644 --- a/Client/game_sa/CFireManagerSA.cpp +++ b/Client/game_sa/CFireManagerSA.cpp @@ -19,8 +19,7 @@ extern CGameSA* pGame; CFireManagerSA::CFireManagerSA() { for (int i = 0; i < MAX_FIRES; i++) - Fires[i] = new CFireSA( - (CFireSAInterface*)(CLASS_CFireManager + 40 * i)); // + 4 because thats the position of CFire array in CFireManager (see source) + Fires[i] = new CFireSA((CFireSAInterface*)(CLASS_CFireManager + 40 * i)); // + 4 because thats the position of CFire array in CFireManager (see source) } CFireManagerSA::~CFireManagerSA() diff --git a/Client/game_sa/CFireManagerSA.h b/Client/game_sa/CFireManagerSA.h index 8f0315ccafe..f1d4da3e23d 100644 --- a/Client/game_sa/CFireManagerSA.h +++ b/Client/game_sa/CFireManagerSA.h @@ -17,13 +17,13 @@ class CEntity; class CFireSA; class CFireSAInterface; -#define FUNC_ExtinguishPoint 0x539450 +#define FUNC_ExtinguishPoint 0x539450 -#define ARRAY_CFire (VAR_CFireCount + 4) -#define CLASS_CFireManager 0xB71F80 +#define ARRAY_CFire (VAR_CFireCount + 4) +#define CLASS_CFireManager 0xB71F80 -#define DEFAULT_FIRE_PARTICLE_SIZE 1.8 -#define MAX_FIRES 60 +#define DEFAULT_FIRE_PARTICLE_SIZE 1.8 +#define MAX_FIRES 60 class CFireManagerSA : public CFireManager { diff --git a/Client/game_sa/CFireSA.cpp b/Client/game_sa/CFireSA.cpp index 88c4838fb73..1c67be69842 100644 --- a/Client/game_sa/CFireSA.cpp +++ b/Client/game_sa/CFireSA.cpp @@ -238,9 +238,9 @@ static void AbortFireTask(CEntitySAInterface* entityOnFire, DWORD returnAddress) taskManager->RemoveTaskSecondary(TASK_SECONDARY_PARTIAL_ANIM, TASK_SIMPLE_PLAYER_ON_FIRE); } -#define HOOKPOS_CFire_Extinguish 0x539429 +#define HOOKPOS_CFire_Extinguish 0x539429 #define HOOKSIZE_CFire_Extinguish 6 -static constexpr intptr_t CONTINUE_CFire_Extinguish = 0x53942F; +static constexpr intptr_t CONTINUE_CFire_Extinguish = 0x53942F; static void __declspec(naked) HOOK_CFire_Extinguish() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CFireSA.h b/Client/game_sa/CFireSA.h index 6a3e66a58ed..67a5e74eaac 100644 --- a/Client/game_sa/CFireSA.h +++ b/Client/game_sa/CFireSA.h @@ -17,8 +17,8 @@ class CEntitySAInterface; class FxSystem_c; -#define FUNC_Extinguish 0x5393F0 -#define FUNC_CreateFxSysForStrength 0x539360 +#define FUNC_Extinguish 0x5393F0 +#define FUNC_CreateFxSysForStrength 0x539360 class CFireSAInterface { diff --git a/Client/game_sa/CFontSA.cpp b/Client/game_sa/CFontSA.cpp index 437083b4f87..05c90827fb4 100644 --- a/Client/game_sa/CFontSA.cpp +++ b/Client/game_sa/CFontSA.cpp @@ -14,7 +14,7 @@ void CFontSA::PrintChar(float x, float y, char character) { - // Call CFont::PrintChar + // Call CFont::PrintChar ((void(_cdecl*)(float, float, char))0x718A10)(x, y, character); } diff --git a/Client/game_sa/CFontSA.h b/Client/game_sa/CFontSA.h index 2d724be8bfa..6651f42895e 100644 --- a/Client/game_sa/CFontSA.h +++ b/Client/game_sa/CFontSA.h @@ -65,7 +65,7 @@ class CFontSA static void SetRightJustifyWrap(float wrap); static void SetDropShadowPosition(std::int16_t offset); - static void SetEdge(std::int16_t edgeSize); // outline + static void SetEdge(std::int16_t edgeSize); // outline static void SetProportional(bool enable); diff --git a/Client/game_sa/CFxManagerSA.h b/Client/game_sa/CFxManagerSA.h index 5a8238bb2b3..c1f72389143 100644 --- a/Client/game_sa/CFxManagerSA.h +++ b/Client/game_sa/CFxManagerSA.h @@ -12,9 +12,9 @@ #include -#define FUNC_FxManager_c__CreateFxSystem 0x4A9BE0 -#define FUNC_FxManager_c__DestroyFxSystem 0x4A9810 -#define FUNC_FxManager_c__GetSystemByName 0x4A9360 +#define FUNC_FxManager_c__CreateFxSystem 0x4A9BE0 +#define FUNC_FxManager_c__DestroyFxSystem 0x4A9810 +#define FUNC_FxManager_c__GetSystemByName 0x4A9360 class CFxSystemBPSAInterface; class CFxSystemSAInterface; @@ -28,32 +28,32 @@ class CFxMemoryPoolSAInterface int unk; }; -class CFxManagerSAInterface // FxManager_c +class CFxManagerSAInterface // FxManager_c { public: // List_c - CFxSystemBPSAInterface* pFirstFxBlueprint; // 0x00 - CFxSystemBPSAInterface* pUnknownFxBlueprint; // 0x04 - unsigned int uiBlueprintCount; // 0x08 + CFxSystemBPSAInterface* pFirstFxBlueprint; // 0x00 + CFxSystemBPSAInterface* pUnknownFxBlueprint; // 0x04 + unsigned int uiBlueprintCount; // 0x08 // List_c - CFxSystemSAInterface* pFirstFxSystem; // 0x0C - CFxSystemSAInterface* pUnknownFxSystem; // 0x10 - unsigned int uiFxSystemCount; // 0x14 + CFxSystemSAInterface* pFirstFxSystem; // 0x0C + CFxSystemSAInterface* pUnknownFxSystem; // 0x10 + unsigned int uiFxSystemCount; // 0x14 void* pUnk; // List_c - CFxEmitterSAInterface* pFirstFxEmitter; // 0x18 - CFxEmitterSAInterface* pUnknownFxEmitter; // 0x1C - unsigned int uiFxEmitterCount; // 0x20 + CFxEmitterSAInterface* pFirstFxEmitter; // 0x18 + CFxEmitterSAInterface* pUnknownFxEmitter; // 0x1C + unsigned int uiFxEmitterCount; // 0x20 - int iTxdSlot; // 0x24 - CVector* pvecWindDirection; // 0x28 - float fWindStrength; // 0x2C - int unk[21]; // 0x30 (at least partially) Frustrum info - int iCurrentMatrix; // 0x88 - RwMatrix* apmatMatrices[8]; // 0x8C - CFxMemoryPoolSAInterface fxMemoryPool; // 0xAC + int iTxdSlot; // 0x24 + CVector* pvecWindDirection; // 0x28 + float fWindStrength; // 0x2C + int unk[21]; // 0x30 (at least partially) Frustrum info + int iCurrentMatrix; // 0x88 + RwMatrix* apmatMatrices[8]; // 0x8C + CFxMemoryPoolSAInterface fxMemoryPool; // 0xAC }; static_assert(sizeof(CFxManagerSAInterface) == 0xB8, "Invalid size for CFxManagerSAInterface"); diff --git a/Client/game_sa/CFxSA.cpp b/Client/game_sa/CFxSA.cpp index 8a509ec27fd..55681ebd10d 100644 --- a/Client/game_sa/CFxSA.cpp +++ b/Client/game_sa/CFxSA.cpp @@ -193,7 +193,7 @@ void CFxSA::TriggerGunshot(CEntity* pEntity, CVector& vecPosition, CVector& vecD CVector* pvecDirection = &vecDirection; DWORD dwThis = (DWORD)m_pInterface; DWORD dwFunc = FUNC_CFx_TriggerGunshot; - // clang-format off + // clang-format off __asm { mov ecx, dwThis @@ -203,7 +203,7 @@ void CFxSA::TriggerGunshot(CEntity* pEntity, CVector& vecPosition, CVector& vecD push dwEntity call dwFunc } - // clang-format on + // clang-format on } void CFxSA::TriggerTankFire(CVector& vecPosition, CVector& vecDirection) @@ -268,10 +268,11 @@ void CFxSA::TriggerFootSplash(CVector& vecPosition) // clang-format on } -void CFxSA::AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife) +void CFxSA::AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, + bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife) { // Init our own FxPrtMult struct - FxPrtMult_c fxPrt{{fR,fG,fB,fA}, fSize, 0, fLife}; + FxPrtMult_c fxPrt{{fR, fG, fB, fA}, fSize, 0, fLife}; CVector newDirection; FxSystem_c* fxParticleSystem; @@ -354,6 +355,7 @@ void CFxSA::AddParticle(FxParticleSystems eFxParticle, const CVector& vecPositio newDirection.fZ = (rand() % 10000) * 0.0001f * 4 - 2 + newDirection.fZ; // Call FxSystem_c::AddParticle - ((int(__thiscall*)(FxSystem_c*, const CVector*, const CVector*, float, FxPrtMult_c*, float, float, float, int))FUNC_FXSystem_c_AddParticle)(fxParticleSystem, &vecPosition, &newDirection, 0, &fxPrt, -1.0f, fBrightness, 0, 0); + ((int(__thiscall*)(FxSystem_c*, const CVector*, const CVector*, float, FxPrtMult_c*, float, float, float, int))FUNC_FXSystem_c_AddParticle)( + fxParticleSystem, &vecPosition, &newDirection, 0, &fxPrt, -1.0f, fBrightness, 0, 0); } } diff --git a/Client/game_sa/CFxSA.h b/Client/game_sa/CFxSA.h index efb7d0403f8..f846c0d444a 100644 --- a/Client/game_sa/CFxSA.h +++ b/Client/game_sa/CFxSA.h @@ -16,21 +16,21 @@ struct RwColor; class FxSystem_c; -#define FUNC_CFx_AddBlood 0x49eb00 -#define FUNC_CFx_AddWood 0x49ee10 -#define FUNC_CFx_AddSparks 0x49f040 -#define FUNC_CFx_AddTyreBurst 0x49f300 -#define FUNC_CFx_AddBulletImpact 0x49f3d0 -#define FUNC_CFx_AddPunchImpact 0x49f670 -#define FUNC_CFx_AddDebris 0x49f750 -#define FUNC_CFx_AddGlass 0x49f970 -#define FUNC_CFx_TriggerWaterHydrant 0x4a0d70 -#define FUNC_CFx_TriggerGunshot 0x4a0de0 -#define FUNC_CFx_TriggerTankFire 0x4a0fa0 -#define FUNC_CFx_TriggerWaterSplash 0x4a1070 -#define FUNC_CFx_TriggerBulletSplash 0x4a10e0 -#define FUNC_CFx_TriggerFootSplash 0x4a1150 -#define FUNC_FXSystem_c_AddParticle 0x4AA440 +#define FUNC_CFx_AddBlood 0x49eb00 +#define FUNC_CFx_AddWood 0x49ee10 +#define FUNC_CFx_AddSparks 0x49f040 +#define FUNC_CFx_AddTyreBurst 0x49f300 +#define FUNC_CFx_AddBulletImpact 0x49f3d0 +#define FUNC_CFx_AddPunchImpact 0x49f670 +#define FUNC_CFx_AddDebris 0x49f750 +#define FUNC_CFx_AddGlass 0x49f970 +#define FUNC_CFx_TriggerWaterHydrant 0x4a0d70 +#define FUNC_CFx_TriggerGunshot 0x4a0de0 +#define FUNC_CFx_TriggerTankFire 0x4a0fa0 +#define FUNC_CFx_TriggerWaterSplash 0x4a1070 +#define FUNC_CFx_TriggerBulletSplash 0x4a10e0 +#define FUNC_CFx_TriggerFootSplash 0x4a1150 +#define FUNC_FXSystem_c_AddParticle 0x4AA440 class CFxSAInterface { @@ -76,7 +76,8 @@ class CFxSA : public CFx void TriggerWaterSplash(CVector& vecPosition); void TriggerBulletSplash(CVector& vecPosition); void TriggerFootSplash(CVector& vecPosition); - void AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife); + void AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, + bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife); private: CFxSAInterface* m_pInterface; diff --git a/Client/game_sa/CFxSystemBPSA.h b/Client/game_sa/CFxSystemBPSA.h index c0e24460b83..5283dfacfbd 100644 --- a/Client/game_sa/CFxSystemBPSA.h +++ b/Client/game_sa/CFxSystemBPSA.h @@ -17,18 +17,18 @@ class CFxSystemBPSAInterface { public: // inherited from ListItem_c - CFxSystemBPSAInterface* pPrevious; // 0x00 - CFxSystemBPSAInterface* pNext; // 0x04 + CFxSystemBPSAInterface* pPrevious; // 0x00 + CFxSystemBPSAInterface* pNext; // 0x04 // Actual members - char* szNameHash; // 0x08 - float fLength; // 0x0C - float fLoopIntervalMinimum; // 0x10 - float fLoopIntervalLength; // 0x14 - ushort usCullDistance; // 0x18 - char cPlayMode; // 0x1A - char cNumOfPrims; // 0x1B - CFxEmitterBPSAInterface** pPrims; // 0x1C (pPrims[0] to pPrims[cNumOfPrims-1]) - void* pBoundingSphere; // 0x20 + char* szNameHash; // 0x08 + float fLength; // 0x0C + float fLoopIntervalMinimum; // 0x10 + float fLoopIntervalLength; // 0x14 + ushort usCullDistance; // 0x18 + char cPlayMode; // 0x1A + char cNumOfPrims; // 0x1B + CFxEmitterBPSAInterface** pPrims; // 0x1C (pPrims[0] to pPrims[cNumOfPrims-1]) + void* pBoundingSphere; // 0x20 }; static_assert(sizeof(CFxSystemBPSAInterface) == 0x24, "Invalid size for CFxSystemBPSAInterface"); diff --git a/Client/game_sa/CFxSystemSA.cpp b/Client/game_sa/CFxSystemSA.cpp index 6770bb273f7..78c3eaed5b0 100644 --- a/Client/game_sa/CFxSystemSA.cpp +++ b/Client/game_sa/CFxSystemSA.cpp @@ -164,10 +164,10 @@ __declspec(noinline) void OnMY_FxSystem_c_Update_MidA_Post() } // Hook info -#define HOOKCHECK_FxSystem_c_Update_MidA 0x83 -#define HOOKPOS_FxSystem_c_Update_MidA 0x04AAF70 -#define HOOKSIZE_FxSystem_c_Update_MidA 5 -DWORD RETURN_FxSystem_c_Update_MidA = 0x04AAF75; +#define HOOKCHECK_FxSystem_c_Update_MidA 0x83 +#define HOOKPOS_FxSystem_c_Update_MidA 0x04AAF70 +#define HOOKSIZE_FxSystem_c_Update_MidA 5 +DWORD RETURN_FxSystem_c_Update_MidA = 0x04AAF75; static void __declspec(naked) HOOK_FxSystem_c_Update_MidA() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -236,10 +236,10 @@ __declspec(noinline) void OnMY_FxSystem_c_Update_MidB_Post() } // Hook info -#define HOOKCHECK_FxSystem_c_Update_MidB 0x83 -#define HOOKPOS_FxSystem_c_Update_MidB 0x04AB21D -#define HOOKSIZE_FxSystem_c_Update_MidB 7 -DWORD RETURN_FxSystem_c_Update_MidB = 0x04AB224; +#define HOOKCHECK_FxSystem_c_Update_MidB 0x83 +#define HOOKPOS_FxSystem_c_Update_MidB 0x04AB21D +#define HOOKSIZE_FxSystem_c_Update_MidB 7 +DWORD RETURN_FxSystem_c_Update_MidB = 0x04AB224; static void __declspec(naked) HOOK_FxSystem_c_Update_MidB() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CFxSystemSA.h b/Client/game_sa/CFxSystemSA.h index 42a4cf04dfa..5a4bd2685ea 100644 --- a/Client/game_sa/CFxSystemSA.h +++ b/Client/game_sa/CFxSystemSA.h @@ -19,8 +19,8 @@ #define VAR_FxSystemUpdateCullDistMultiplier 0x4AB032 #define VAR_FxCreateParticleCullDistMultiplierA 0x4A4247 #define VAR_FxCreateParticleCullDistMultiplierB 0x4A4255 -#define FX_SYSTEM_UPDATE_CULL_DIST_MULTIPLIER_DEFAULT ( 1 / 256.f ) -#define FX_CREATE_PARTICLE_CULL_DIST_MULTIPLIER_DEFAULT ( 1 / 64.f ) +#define FX_SYSTEM_UPDATE_CULL_DIST_MULTIPLIER_DEFAULT (1 / 256.f) +#define FX_CREATE_PARTICLE_CULL_DIST_MULTIPLIER_DEFAULT (1 / 64.f) class CAEFireAudioEntitySAInterface { @@ -29,39 +29,39 @@ class CAEFireAudioEntitySAInterface // todo: reverse this structure and CAEAudioEntity std::int32_t pad1[0x21]; - void* audio; // 0x84 // TODO: Reverse what this __exactly__ is + void* audio; // 0x84 // TODO: Reverse what this __exactly__ is }; static_assert(sizeof(CAEFireAudioEntitySAInterface) == 0x88, "Invalid size for CAEFireAudioEntitySAInterface"); class FxInfoSAInterface; class CFxSystemBPSAInterface; -class CFxSystemSAInterface // Internal SA Name: FxSystem_c +class CFxSystemSAInterface // Internal SA Name: FxSystem_c { public: // Based upon ListItem_c - CFxSystemSAInterface* pPrevious; // 0x00 - CFxSystemSAInterface* pNext; // 0x04 + CFxSystemSAInterface* pPrevious; // 0x00 + CFxSystemSAInterface* pNext; // 0x04 // Actual members - CFxSystemBPSAInterface* pBlueprint; // 0x08 - RwMatrix* pmatUnknown; // 0x10 - RwMatrix matPosition; // 0x0C - char cPlayStatus; // 0x50 - char cUnknownFlag; // 0x51 - char cConstTime; // 0x52 - char pad; // 0x53 - int unk2[2]; // 0x54 - short sConstTimeMult; // 0x5C - short sRateMult; // 0x5E (This controls how often the effect is renewed) - short sTimeMult; // 0x60 (This controls how fast the effect plays) - char cFlags; // 0x62 - char pad2; // 0x63 - int unk3; // 0x64 - CVector vecVelocity; // 0x68 - void* pSphere; // 0x74 - void** ppParticleEmitters; // 0x78 (Array of particle emitters, amount is defined by the blueprint) - CAEFireAudioEntitySAInterface audioEntity; // 0x7C + CFxSystemBPSAInterface* pBlueprint; // 0x08 + RwMatrix* pmatUnknown; // 0x10 + RwMatrix matPosition; // 0x0C + char cPlayStatus; // 0x50 + char cUnknownFlag; // 0x51 + char cConstTime; // 0x52 + char pad; // 0x53 + int unk2[2]; // 0x54 + short sConstTimeMult; // 0x5C + short sRateMult; // 0x5E (This controls how often the effect is renewed) + short sTimeMult; // 0x60 (This controls how fast the effect plays) + char cFlags; // 0x62 + char pad2; // 0x63 + int unk3; // 0x64 + CVector vecVelocity; // 0x68 + void* pSphere; // 0x74 + void** ppParticleEmitters; // 0x78 (Array of particle emitters, amount is defined by the blueprint) + CAEFireAudioEntitySAInterface audioEntity; // 0x7C }; static_assert(sizeof(CFxSystemSAInterface) == 0x104, "Invalid size for CFxSystemSAInterface"); @@ -103,44 +103,44 @@ class CFxSystemSA : public CFxSystem class FxInfoManagerSAInterface { public: - uint32_t m_nNumInfos; // 0x00 - FxInfoSAInterface* m_pInfos; // 0x04 - uint8_t m_nFirstMovementInfo; // 0x08 - uint8_t m_nFirstRenderInfo; // 0x09 + uint32_t m_nNumInfos; // 0x00 + FxInfoSAInterface* m_pInfos; // 0x04 + uint8_t m_nFirstMovementInfo; // 0x08 + uint8_t m_nFirstRenderInfo; // 0x09 }; static_assert(sizeof(FxInfoManagerSAInterface) == 0xC, "Invalid size for FxInfoManagerSAInterface"); class FxPrimBPSAInterface { public: - void* vtbl; // 0x00 - uint8_t field_4; // 0x04 - uint8_t m_nSrcBlendId; // 0x05 - uint8_t m_nDstBlendId; // 0x06 - uint8_t m_bAlphaOn; // 0x07 - void* m_pCompressedInitialMatrix; // 0x08 - RwTexture* m_apTextures[4]; // 0x0C - void* field_1C; // 0x1C - uint32_t particlesList[3]; // 0x20 -- List_c - FxInfoManagerSAInterface m_infoManager; // 0x2C + void* vtbl; // 0x00 + uint8_t field_4; // 0x04 + uint8_t m_nSrcBlendId; // 0x05 + uint8_t m_nDstBlendId; // 0x06 + uint8_t m_bAlphaOn; // 0x07 + void* m_pCompressedInitialMatrix; // 0x08 + RwTexture* m_apTextures[4]; // 0x0C + void* field_1C; // 0x1C + uint32_t particlesList[3]; // 0x20 -- List_c + FxInfoManagerSAInterface m_infoManager; // 0x2C }; static_assert(sizeof(FxPrimBPSAInterface) == 0x38, "Invalid size for FxPrimBPSAInterface"); class CFxEmitterBPSAInterface : public FxPrimBPSAInterface { public: - uint16_t m_nLodStart; // 0x38 - uint16_t m_nLodEnd; // 0x3A - bool m_bHasInfoFlatData; // 0x3C - bool m_bHasInfoHeatHazeData; // 0x3C + uint16_t m_nLodStart; // 0x38 + uint16_t m_nLodEnd; // 0x3A + bool m_bHasInfoFlatData; // 0x3C + bool m_bHasInfoHeatHazeData; // 0x3C }; static_assert(sizeof(CFxEmitterBPSAInterface) == 0x40, "Invalid size for CFxEmitterBPSAInterface"); class CFxEmitterSAInterface { public: - void* vtbl; // 0x00 - CFxEmitterBPSAInterface* pBlueprint; // 0x04 - CFxSystemSAInterface* pOwner; // 0x08 + void* vtbl; // 0x00 + CFxEmitterBPSAInterface* pBlueprint; // 0x04 + CFxSystemSAInterface* pOwner; // 0x08 // TODO the rest }; diff --git a/Client/game_sa/CGameSA.cpp b/Client/game_sa/CGameSA.cpp index e1b11579dd1..b5e55ef021c 100644 --- a/Client/game_sa/CGameSA.cpp +++ b/Client/game_sa/CGameSA.cpp @@ -64,9 +64,9 @@ extern CGameSA* pGame; -unsigned int& CGameSA::ClumpOffset = *(unsigned int*)0xB5F878; +unsigned int& CGameSA::ClumpOffset = *(unsigned int*)0xB5F878; -unsigned int OBJECTDYNAMICINFO_MAX = *(uint32_t*)0x59FB4C != 0x90909090 ? *(uint32_t*)0x59FB4C : 160; // default: 160 +unsigned int OBJECTDYNAMICINFO_MAX = *(uint32_t*)0x59FB4C != 0x90909090 ? *(uint32_t*)0x59FB4C : 160; // default: 160 /** * \todo allow the addon to change the size of the pools (see 0x4C0270 - CPools::Initialise) (in start game?) @@ -213,24 +213,24 @@ CGameSA::CGameSA() m_Cheats[CHEAT_HEALTARMORMONEY] = new SCheatSA((BYTE*)VAR_HealthArmorMoney, false); // Change pool sizes here - m_Pools->SetPoolCapacity(TASK_POOL, 5000); // Default is 500 - m_Pools->SetPoolCapacity(OBJECT_POOL, MAX_OBJECTS); // Default is 350 - m_Pools->SetPoolCapacity(EVENT_POOL, 5000); // Default is 200 - m_Pools->SetPoolCapacity(COL_MODEL_POOL, 12000); // Default is 10150 - m_Pools->SetPoolCapacity(ENV_MAP_MATERIAL_POOL, 16000); // Default is 4096 - m_Pools->SetPoolCapacity(ENV_MAP_ATOMIC_POOL, 4000); // Default is 1024 - m_Pools->SetPoolCapacity(SPEC_MAP_MATERIAL_POOL, 16000); // Default is 4096 - m_Pools->SetPoolCapacity(ENTRY_INFO_NODE_POOL, MAX_ENTRY_INFO_NODES); // Default is 500 - m_Pools->SetPoolCapacity(POINTER_SINGLE_LINK_POOL, MAX_POINTER_SINGLE_LINKS); // Default is 70000 - m_Pools->SetPoolCapacity(POINTER_DOUBLE_LINK_POOL, MAX_POINTER_DOUBLE_LINKS); // Default is 3200 + m_Pools->SetPoolCapacity(TASK_POOL, 5000); // Default is 500 + m_Pools->SetPoolCapacity(OBJECT_POOL, MAX_OBJECTS); // Default is 350 + m_Pools->SetPoolCapacity(EVENT_POOL, 5000); // Default is 200 + m_Pools->SetPoolCapacity(COL_MODEL_POOL, 12000); // Default is 10150 + m_Pools->SetPoolCapacity(ENV_MAP_MATERIAL_POOL, 16000); // Default is 4096 + m_Pools->SetPoolCapacity(ENV_MAP_ATOMIC_POOL, 4000); // Default is 1024 + m_Pools->SetPoolCapacity(SPEC_MAP_MATERIAL_POOL, 16000); // Default is 4096 + m_Pools->SetPoolCapacity(ENTRY_INFO_NODE_POOL, MAX_ENTRY_INFO_NODES); // Default is 500 + m_Pools->SetPoolCapacity(POINTER_SINGLE_LINK_POOL, MAX_POINTER_SINGLE_LINKS); // Default is 70000 + m_Pools->SetPoolCapacity(POINTER_DOUBLE_LINK_POOL, MAX_POINTER_DOUBLE_LINKS); // Default is 3200 dassert(m_Pools->GetPoolCapacity(POINTER_SINGLE_LINK_POOL) == MAX_POINTER_SINGLE_LINKS); // Increase streaming object instances list size - MemPut(0x05B8E55, MAX_RWOBJECT_INSTANCES * 12); // Default is 1000 * 12 - MemPut(0x05B8EB0, MAX_RWOBJECT_INSTANCES * 12); // Default is 1000 * 12 + MemPut(0x05B8E55, MAX_RWOBJECT_INSTANCES * 12); // Default is 1000 * 12 + MemPut(0x05B8EB0, MAX_RWOBJECT_INSTANCES * 12); // Default is 1000 * 12 // Increase matrix array size - MemPut(0x054F3A1, MAX_OBJECTS * 3); // Default is 900 + MemPut(0x054F3A1, MAX_OBJECTS * 3); // Default is 900 CEntitySAInterface::StaticSetHooks(); CPhysicalSAInterface::StaticSetHooks(); @@ -356,7 +356,7 @@ CWeaponInfo* CGameSA::GetWeaponInfo(eWeaponType weapon, eWeaponSkill skill) void CGameSA::Pause(bool bPaused) { - MemPutFast(0xB7CB49, bPaused); // CTimer::m_UserPause + MemPutFast(0xB7CB49, bPaused); // CTimer::m_UserPause } CModelInfo* CGameSA::GetModelInfo(DWORD dwModelID, bool bCanBeInvalid) @@ -379,8 +379,8 @@ CModelInfo* CGameSA::GetModelInfo(DWORD dwModelID, bool bCanBeInvalid) void CGameSA::StartGame() { SetSystemState(SystemState::GS_INIT_PLAYING_GAME); - MemPutFast(0xB7CB49, 0); // CTimer::m_UserPause - MemPutFast(0xBA67A4, 0); // FrontEndMenuManager + 0x5C + MemPutFast(0xB7CB49, 0); // CTimer::m_UserPause + MemPutFast(0xBA67A4, 0); // FrontEndMenuManager + 0x5C } /** @@ -389,12 +389,12 @@ void CGameSA::StartGame() */ void CGameSA::SetSystemState(SystemState State) { - MemPutFast(0xC8D4C0, (DWORD)State); // gGameState + MemPutFast(0xC8D4C0, (DWORD)State); // gGameState } SystemState CGameSA::GetSystemState() { - return *(SystemState*)0xC8D4C0; // gGameState + return *(SystemState*)0xC8D4C0; // gGameState } /** @@ -454,7 +454,7 @@ void CGameSA::Reset() m_pCamera->SetFadeColor(0, 0, 0); m_pCamera->Fade(0, FADE_OUT); - Pause(false); // We don't have to pause as the fadeout will stop the sound. Pausing it will make the fadein next start ugly + Pause(false); // We don't have to pause as the fadeout will stop the sound. Pausing it will make the fadein next start ugly m_pHud->Disable(false); // Restore the HUD @@ -483,10 +483,10 @@ void CGameSA::Terminate() // Initiate the destruction delete this; - // Dump any memory leaks if DETECT_LEAK is defined - #ifdef DETECT_LEAKS +// Dump any memory leaks if DETECT_LEAK is defined +#ifdef DETECT_LEAKS DumpUnfreed(); - #endif +#endif } void CGameSA::Initialize() @@ -540,47 +540,47 @@ eGameVersion CGameSA::FindGameVersion() float CGameSA::GetFPS() { - return *(float*)0xB7CB50; // CTimer::game_FPS + return *(float*)0xB7CB50; // CTimer::game_FPS } float CGameSA::GetTimeStep() { - return *(float*)0xB7CB5C; // CTimer::ms_fTimeStep + return *(float*)0xB7CB5C; // CTimer::ms_fTimeStep } float CGameSA::GetOldTimeStep() { - return *(float*)0xB7CB54; // CTimer::ms_fOldTimeStep + return *(float*)0xB7CB54; // CTimer::ms_fOldTimeStep } float CGameSA::GetTimeScale() { - return *(float*)0xB7CB64; // CTimer::ms_fTimeScale + return *(float*)0xB7CB64; // CTimer::ms_fTimeScale } void CGameSA::SetTimeScale(float fTimeScale) { - MemPutFast(0xB7CB64, fTimeScale); // CTimer::ms_fTimeScale + MemPutFast(0xB7CB64, fTimeScale); // CTimer::ms_fTimeScale } unsigned char CGameSA::GetBlurLevel() { - return *(unsigned char*)0x8D5104; // CPostEffects::m_SpeedFXAlpha + return *(unsigned char*)0x8D5104; // CPostEffects::m_SpeedFXAlpha } void CGameSA::SetBlurLevel(unsigned char ucLevel) { - MemPutFast(0x8D5104, ucLevel); // CPostEffects::m_SpeedFXAlpha + MemPutFast(0x8D5104, ucLevel); // CPostEffects::m_SpeedFXAlpha } unsigned long CGameSA::GetMinuteDuration() { - return *(unsigned long*)0xB7015C; // CClock::ms_nMillisecondsPerGameMinute + return *(unsigned long*)0xB7015C; // CClock::ms_nMillisecondsPerGameMinute } void CGameSA::SetMinuteDuration(unsigned long ulTime) { - MemPutFast(0xB7015C, ulTime); // CClock::ms_nMillisecondsPerGameMinute + MemPutFast(0xB7015C, ulTime); // CClock::ms_nMillisecondsPerGameMinute } bool CGameSA::IsCheatEnabled(const char* szCheatName) @@ -709,7 +709,7 @@ void CGameSA::SetCoronaZTestEnabled(bool isEnabled) m_isCoronaZTestEnabled = isEnabled; } -void CGameSA::SetWaterCreaturesEnabled(bool isEnabled) +void CGameSA::SetWaterCreaturesEnabled(bool isEnabled) { if (isEnabled == m_areWaterCreaturesEnabled) return; @@ -734,20 +734,20 @@ void CGameSA::SetTunnelWeatherBlendEnabled(bool isEnabled) if (isEnabled == m_isTunnelWeatherBlendEnabled) return; // CWeather::UpdateInTunnelness - DWORD functionAddress = 0x72B630; + DWORD functionAddress = 0x72B630; if (isEnabled) { // Restore original bytes: 83 EC 20 - MemPut(functionAddress, 0x83); // Restore 83 - MemPut(functionAddress + 1, 0xEC); // Restore EC - MemPut(functionAddress + 2, 0x20); // Restore 20 + MemPut(functionAddress, 0x83); // Restore 83 + MemPut(functionAddress + 1, 0xEC); // Restore EC + MemPut(functionAddress + 2, 0x20); // Restore 20 } else { // Patch CWeather::UpdateInTunnelness (Found By AlexTMjugador) - MemPut(functionAddress, 0xC3); // Write C3 (RET) - MemPut(functionAddress + 1, 0x90); // Write 90 (NOP) - MemPut(functionAddress + 2, 0x90); // Write 90 (NOP) + MemPut(functionAddress, 0xC3); // Write C3 (RET) + MemPut(functionAddress + 1, 0x90); // Write 90 (NOP) + MemPut(functionAddress + 2, 0x90); // Write 90 (NOP) } m_isTunnelWeatherBlendEnabled = isEnabled; } @@ -792,13 +792,13 @@ void CGameSA::SetFireballDestructEnabled(bool isEnabled) if (isEnabled) { BYTE originalCodes[7] = {0x81, 0x66, 0x1C, 0x7E, 0xFF, 0xFF, 0xFF}; - MemCpy((void*)0x6CCE45, &originalCodes, 7); // CPlane::BlowUpCar - MemCpy((void*)0x6C6E01, &originalCodes, 7); // CHeli::BlowUpCar + MemCpy((void*)0x6CCE45, &originalCodes, 7); // CPlane::BlowUpCar + MemCpy((void*)0x6C6E01, &originalCodes, 7); // CHeli::BlowUpCar } else { - MemSet((void*)0x6CCE45, 0x90, 7); // CPlane::BlowUpCar - MemSet((void*)0x6C6E01, 0x90, 7); // CHeli::BlowUpCar + MemSet((void*)0x6CCE45, 0x90, 7); // CPlane::BlowUpCar + MemSet((void*)0x6C6E01, 0x90, 7); // CHeli::BlowUpCar } m_isFireballDestructEnabled = isEnabled; @@ -812,8 +812,8 @@ void CGameSA::SetExtendedWaterCannonsEnabled(bool isEnabled) // Allocate memory for new bigger array or use default aCannons array void* aCannons = isEnabled ? malloc(MAX_WATER_CANNONS * SIZE_CWaterCannon) : (void*)ARRAY_aCannons; - int newLimit = isEnabled ? MAX_WATER_CANNONS : NUM_CWaterCannon_DefaultLimit; // default: 3 - MemSetFast(aCannons, 0, newLimit * SIZE_CWaterCannon); // clear aCannons array + int newLimit = isEnabled ? MAX_WATER_CANNONS : NUM_CWaterCannon_DefaultLimit; // default: 3 + MemSetFast(aCannons, 0, newLimit * SIZE_CWaterCannon); // clear aCannons array // Get current limit int currentLimit = *(int*)NUM_WaterCannon_Limit; @@ -826,8 +826,10 @@ void CGameSA::SetExtendedWaterCannonsEnabled(bool isEnabled) { char* currentCannon = (char*)currentACannons + i * SIZE_CWaterCannon; - ((void(__thiscall*)(int, void*, bool))FUNC_CAESoundManager_CancelSoundsOwnedByAudioEntity)(STRUCT_CAESoundManager, currentCannon + NUM_CWaterCannon_Audio_Offset, true); // CAESoundManager::CancelSoundsOwnedByAudioEntity to prevent random crashes from CAESound::UpdateParameters - ((void(__thiscall*)(void*))FUNC_CWaterCannon_Destructor)(currentCannon); // CWaterCannon::~CWaterCannon + ((void(__thiscall*)(int, void*, bool))FUNC_CAESoundManager_CancelSoundsOwnedByAudioEntity)( + STRUCT_CAESoundManager, currentCannon + NUM_CWaterCannon_Audio_Offset, + true); // CAESoundManager::CancelSoundsOwnedByAudioEntity to prevent random crashes from CAESound::UpdateParameters + ((void(__thiscall*)(void*))FUNC_CWaterCannon_Destructor)(currentCannon); // CWaterCannon::~CWaterCannon } // Call CWaterCannon constructor & CWaterCannon::Init @@ -835,20 +837,20 @@ void CGameSA::SetExtendedWaterCannonsEnabled(bool isEnabled) { char* currentCannon = (char*)aCannons + i * SIZE_CWaterCannon; - ((void(__thiscall*)(void*))FUNC_CWaterCannon_Constructor)(currentCannon); // CWaterCannon::CWaterCannon - ((void(__thiscall*)(void*))FUNC_CWaterCannon_Init)(currentCannon); // CWaterCannon::Init + ((void(__thiscall*)(void*))FUNC_CWaterCannon_Constructor)(currentCannon); // CWaterCannon::CWaterCannon + ((void(__thiscall*)(void*))FUNC_CWaterCannon_Init)(currentCannon); // CWaterCannon::Init } // Patch references to array - MemPut((void*)0x728C83, aCannons); // CWaterCannons::Init - MemPut((void*)0x728CCB, aCannons); // CWaterCannons::UpdateOne - MemPut((void*)0x728CEB, aCannons); // CWaterCannons::UpdateOne - MemPut((void*)0x728D0D, aCannons); // CWaterCannons::UpdateOne - MemPut((void*)0x728D71, aCannons); // CWaterCannons::UpdateOne - MemPutFast((void*)0x729B33, aCannons); // CWaterCannons::Render - MemPut((void*)0x72A3C5, aCannons); // CWaterCannons::UpdateOne - MemPut((void*)0x855432, aCannons); // 0x855431 - MemPut((void*)0x856BFD, aCannons); // 0x856BFC + MemPut((void*)0x728C83, aCannons); // CWaterCannons::Init + MemPut((void*)0x728CCB, aCannons); // CWaterCannons::UpdateOne + MemPut((void*)0x728CEB, aCannons); // CWaterCannons::UpdateOne + MemPut((void*)0x728D0D, aCannons); // CWaterCannons::UpdateOne + MemPut((void*)0x728D71, aCannons); // CWaterCannons::UpdateOne + MemPutFast((void*)0x729B33, aCannons); // CWaterCannons::Render + MemPut((void*)0x72A3C5, aCannons); // CWaterCannons::UpdateOne + MemPut((void*)0x855432, aCannons); // 0x855431 + MemPut((void*)0x856BFD, aCannons); // 0x856BFC const auto ucNewLimit = static_cast(newLimit); @@ -900,14 +902,14 @@ void CGameSA::SetIgnoreFireStateEnabled(bool isEnabled) { // All these patches disable fire state checks (m_pFire != nullptr) // Related crash protection is handled by checks in TaskSA.cpp and CTaskManagementSystemSA.cpp - MemSet((void*)0x6511B9, 0x90, 10); // CCarEnterExit::IsVehicleStealable - fire check - MemSet((void*)0x643A95, 0x90, 14); // CTaskComplexEnterCar::CreateFirstSubTask - fire check - MemSet((void*)0x6900B5, 0x90, 14); // CTaskComplexCopInCar::ControlSubTask - fire check - MemSet((void*)0x64F3DB, 0x90, 14); // CCarEnterExit::IsPlayerToQuitCarEnter - fire check - MemSet((void*)0x685A7F, 0x90, 14); // CTaskSimplePlayerOnFoot::ProcessPlayerWeapon - fire check - - MemSet((void*)0x53A899, 0x90, 5); // CFire::ProcessFire - MemSet((void*)0x53A990, 0x90, 5); // CFire::ProcessFire + MemSet((void*)0x6511B9, 0x90, 10); // CCarEnterExit::IsVehicleStealable - fire check + MemSet((void*)0x643A95, 0x90, 14); // CTaskComplexEnterCar::CreateFirstSubTask - fire check + MemSet((void*)0x6900B5, 0x90, 14); // CTaskComplexCopInCar::ControlSubTask - fire check + MemSet((void*)0x64F3DB, 0x90, 14); // CCarEnterExit::IsPlayerToQuitCarEnter - fire check + MemSet((void*)0x685A7F, 0x90, 14); // CTaskSimplePlayerOnFoot::ProcessPlayerWeapon - fire check + + MemSet((void*)0x53A899, 0x90, 5); // CFire::ProcessFire + MemSet((void*)0x53A990, 0x90, 5); // CFire::ProcessFire } else { @@ -933,8 +935,8 @@ void CGameSA::SetVehicleBurnExplosionsEnabled(bool isEnabled) if (isEnabled) { - MemCpy((void*)0x6A74EA, "\xE8\x61\xF5\x08\x00", 5); // CAutomobile::ProcessCarOnFireAndExplode - MemCpy((void*)0x737929, "\xE8\x22\xF1\xFF\xFF", 5); // CExplosion::Update + MemCpy((void*)0x6A74EA, "\xE8\x61\xF5\x08\x00", 5); // CAutomobile::ProcessCarOnFireAndExplode + MemCpy((void*)0x737929, "\xE8\x22\xF1\xFF\xFF", 5); // CExplosion::Update } else { @@ -1165,7 +1167,7 @@ void CGameSA::ResetAlphaTransparencies() // Note #2: Some players do not need this to disable VSync. (Possibly because their video card driver settings override it somewhere) void CGameSA::DisableVSync() { - MemPutFast(0xBAB318, 0); // CLoadingScreen::m_bActive + MemPutFast(0xBAB318, 0); // CLoadingScreen::m_bActive } CWeapon* CGameSA::CreateWeapon() { @@ -1185,9 +1187,9 @@ void CGameSA::SetWeaponRenderEnabled(bool enabled) if (!enabled) { // Disable calls to CVisibilityPlugins::RenderWeaponPedsForPC - MemSet((void*)0x53EAC4, 0x90, 5); // Idle - MemSet((void*)0x705322, 0x90, 5); // CPostEffects::Render - MemSet((void*)0x7271E3, 0x90, 5); // CMirrors::BeforeMainRender + MemSet((void*)0x53EAC4, 0x90, 5); // Idle + MemSet((void*)0x705322, 0x90, 5); // CPostEffects::Render + MemSet((void*)0x7271E3, 0x90, 5); // CMirrors::BeforeMainRender } else { diff --git a/Client/game_sa/CGameSA.h b/Client/game_sa/CGameSA.h index 7ef64b44c48..782c13ffe4e 100644 --- a/Client/game_sa/CGameSA.h +++ b/Client/game_sa/CGameSA.h @@ -24,65 +24,65 @@ class CAnimBlendClumpDataSAInterface; class CObjectGroupPhysicalPropertiesSA; class CTaskManagementSystemSA; -extern unsigned int OBJECTDYNAMICINFO_MAX; // default: 160 - -#define CLASS_CPlayerInfo 0xB7CD98 -#define CLASS_CCamera 0xB6F028 -#define CLASS_CPad 0xB73458 -#define CLASS_CFx 0xa9ae00 -#define CLASS_CFxManager 0xA9AE80 -#define CLASS_CMenuManager 0xBA6748 -#define CLASS_RwCamera 0xB6F97C - -#define ARRAY_WeaponInfo 0xC8AAB8 -#define CLASSSIZE_WeaponInfo 112 -#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE -#define NUM_WeaponInfosOtherSkill 11 -#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3*NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) - -#define MODELINFO_DFF_MAX 20000 -#define MODELINFO_TXD_MAX 25000 -#define MODELINFO_MAX 26000 // Actual max is 25755 - -#define VAR_FlyingCarsEnabled 0x969160 -#define VAR_ExtraBunnyhopEnabled 0x969161 -#define VAR_HoveringCarsEnabled 0x969152 -#define VAR_ExtraJumpEnabled 0x96916C -#define VAR_TankModeEnabled 0x969164 -#define VAR_NoReloadEnabled 0x969178 -#define VAR_PerfectHandling 0x96914C -#define VAR_AllCarsHaveNitro 0x969165 -#define VAR_BoatsCanFly 0x969153 -#define VAR_InfiniteOxygen 0x96916E -#define VAR_FasterClock 0x96913B -#define VAR_FasterGameplay 0x96913C -#define VAR_SlowerGameplay 0x96913D -#define VAR_AlwaysMidnight 0x969167 -#define VAR_FullWeaponAiming 0x969179 -#define VAR_InfiniteHealth 0x96916D -#define VAR_NeverWanted 0x969171 -#define VAR_HealthArmorMoney 0x969133 -#define VAR_WalkUnderwater 0x6C2759 - -#define CHEAT_HOVERINGCARS "hovercars" -#define CHEAT_FLYINGCARS "aircars" -#define CHEAT_EXTRABUNNYHOP "extrabunny" -#define CHEAT_EXTRAJUMP "extrajump" -#define CHEAT_TANKMODE "tankmode" -#define CHEAT_NORELOAD "noreload" -#define CHEAT_PERFECTHANDLING "perfecthandling" -#define CHEAT_ALLCARSHAVENITRO "allcarshavenitro" -#define CHEAT_BOATSCANFLY "airboats" -#define CHEAT_INFINITEOXYGEN "infiniteoxygen" -#define CHEAT_WALKUNDERWATER "walkunderwater" -#define CHEAT_FASTERCLOCK "fasterclock" -#define CHEAT_FASTERGAMEPLAY "fastergameplay" -#define CHEAT_SLOWERGAMEPLAY "slowergameplay" -#define CHEAT_ALWAYSMIDNIGHT "alwaysmidnight" -#define CHEAT_FULLWEAPONAIMING "fullweaponaiming" -#define CHEAT_INFINITEHEALTH "infinitehealth" -#define CHEAT_NEVERWANTED "neverwanted" -#define CHEAT_HEALTARMORMONEY "healtharmormoney" +extern unsigned int OBJECTDYNAMICINFO_MAX; // default: 160 + +#define CLASS_CPlayerInfo 0xB7CD98 +#define CLASS_CCamera 0xB6F028 +#define CLASS_CPad 0xB73458 +#define CLASS_CFx 0xa9ae00 +#define CLASS_CFxManager 0xA9AE80 +#define CLASS_CMenuManager 0xBA6748 +#define CLASS_RwCamera 0xB6F97C + +#define ARRAY_WeaponInfo 0xC8AAB8 +#define CLASSSIZE_WeaponInfo 112 +#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE +#define NUM_WeaponInfosOtherSkill 11 +#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3 * NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) + +#define MODELINFO_DFF_MAX 20000 +#define MODELINFO_TXD_MAX 25000 +#define MODELINFO_MAX 26000 // Actual max is 25755 + +#define VAR_FlyingCarsEnabled 0x969160 +#define VAR_ExtraBunnyhopEnabled 0x969161 +#define VAR_HoveringCarsEnabled 0x969152 +#define VAR_ExtraJumpEnabled 0x96916C +#define VAR_TankModeEnabled 0x969164 +#define VAR_NoReloadEnabled 0x969178 +#define VAR_PerfectHandling 0x96914C +#define VAR_AllCarsHaveNitro 0x969165 +#define VAR_BoatsCanFly 0x969153 +#define VAR_InfiniteOxygen 0x96916E +#define VAR_FasterClock 0x96913B +#define VAR_FasterGameplay 0x96913C +#define VAR_SlowerGameplay 0x96913D +#define VAR_AlwaysMidnight 0x969167 +#define VAR_FullWeaponAiming 0x969179 +#define VAR_InfiniteHealth 0x96916D +#define VAR_NeverWanted 0x969171 +#define VAR_HealthArmorMoney 0x969133 +#define VAR_WalkUnderwater 0x6C2759 + +#define CHEAT_HOVERINGCARS "hovercars" +#define CHEAT_FLYINGCARS "aircars" +#define CHEAT_EXTRABUNNYHOP "extrabunny" +#define CHEAT_EXTRAJUMP "extrajump" +#define CHEAT_TANKMODE "tankmode" +#define CHEAT_NORELOAD "noreload" +#define CHEAT_PERFECTHANDLING "perfecthandling" +#define CHEAT_ALLCARSHAVENITRO "allcarshavenitro" +#define CHEAT_BOATSCANFLY "airboats" +#define CHEAT_INFINITEOXYGEN "infiniteoxygen" +#define CHEAT_WALKUNDERWATER "walkunderwater" +#define CHEAT_FASTERCLOCK "fasterclock" +#define CHEAT_FASTERGAMEPLAY "fastergameplay" +#define CHEAT_SLOWERGAMEPLAY "slowergameplay" +#define CHEAT_ALWAYSMIDNIGHT "alwaysmidnight" +#define CHEAT_FULLWEAPONAIMING "fullweaponaiming" +#define CHEAT_INFINITEHEALTH "infinitehealth" +#define CHEAT_NEVERWANTED "neverwanted" +#define CHEAT_HEALTARMORMONEY "healtharmormoney" #define FUNC_CAESoundManager_CancelSoundsOwnedByAudioEntity 0x4EFCD0 #define STRUCT_CAESoundManager 0xB62CB0 @@ -96,13 +96,13 @@ extern unsigned int OBJECTDYNAMICINFO_MAX; // default: 160 #define NUM_CWaterCannon_Audio_Offset 0x32C #define NUM_CWaterCannon_DefaultLimit 3 -constexpr int MAX_WATER_CANNONS = 30; // extended CWaterCannon limit, it can be increased +constexpr int MAX_WATER_CANNONS = 30; // extended CWaterCannon limit, it can be increased struct SCheatSA { - BYTE* m_byAddress; // Cheat Address - bool m_bEnabled; // Cheat State - bool m_bCanBeSet; // Cheat can be set with setWorldSpecialPropertyEnabled + BYTE* m_byAddress; // Cheat Address + bool m_bEnabled; // Cheat State + bool m_bCanBeSet; // Cheat can be set with setWorldSpecialPropertyEnabled SCheatSA(BYTE* Address, bool bCanBeSet = true) { m_byAddress = Address; @@ -176,10 +176,7 @@ class CGameSA : public CGame CBuildingRemoval* GetBuildingRemoval() { return m_pBuildingRemoval; } CRenderer* GetRenderer() const noexcept override { return m_pRenderer.get(); } - CVehicleAudioSettingsManager* GetVehicleAudioSettingsManager() const noexcept override - { - return m_pVehicleAudioSettingsManager.get(); - } + CVehicleAudioSettingsManager* GetVehicleAudioSettingsManager() const noexcept override { return m_pVehicleAudioSettingsManager.get(); } CWeaponInfo* GetWeaponInfo(eWeaponType weapon, eWeaponSkill skill = WEAPONSKILL_STD); CModelInfo* GetModelInfo(DWORD dwModelID, bool bCanBeInvalid = false); @@ -195,15 +192,15 @@ class CGameSA : public CGame uint32_t GetBaseIDforSCM() override { return *(uint32_t*)(0x46A574 + 2); } uint32_t GetCountOfAllFileIDs() override { return (*(char**)(0x5B8AFA + 2) - *(char**)(0x5B8B08 + 6)) / sizeof(CStreamingInfo); } - DWORD GetSystemTime() { return *(DWORD*)0xB7CB84; } // CTimer::m_snTimeInMilliseconds - int GetSystemFrameCounter() const { return *(int*)0xB7CB4C; } // CTimer::m_FrameCounter + DWORD GetSystemTime() { return *(DWORD*)0xB7CB84; } // CTimer::m_snTimeInMilliseconds + int GetSystemFrameCounter() const { return *(int*)0xB7CB4C; } // CTimer::m_FrameCounter - bool IsAtMenu() { return *(unsigned long*)0xBA677B != 0; } // FrontEndMenuManager + 0x33 + bool IsAtMenu() { return *(unsigned long*)0xBA677B != 0; } // FrontEndMenuManager + 0x33 - void StartGame(); - void SetSystemState(SystemState State); - SystemState GetSystemState(); - void Pause(bool bPaused); + void StartGame(); + void SetSystemState(SystemState State); + SystemState GetSystemState(); + void Pause(bool bPaused); void Initialize(); void Reset(); @@ -364,7 +361,7 @@ class CGameSA : public CGame std::unique_ptr m_pVehicleAudioSettingsManager; - std::unique_ptr m_pRenderer; + std::unique_ptr m_pRenderer; CPad* m_pPad; CAERadioTrackManager* m_pCAERadioTrackManager; @@ -373,7 +370,7 @@ class CGameSA : public CGame CAESoundManager* m_pAESoundManager; CAudioContainer* m_pAudioContainer; CStats* m_pStats; - CTaskManagementSystemSA* m_pTaskManagementSystem; // not used outside the game_sa + CTaskManagementSystemSA* m_pTaskManagementSystem; // not used outside the game_sa CTasks* m_pTasks; CGameSettings* m_pSettings; CCarEnterExit* m_pCarEnterExit; @@ -387,7 +384,7 @@ class CGameSA : public CGame int m_iCheckStatus; bool m_bUnderworldWarp; bool m_isCoronaZTestEnabled{true}; - bool m_isTunnelWeatherBlendEnabled{true}; + bool m_isTunnelWeatherBlendEnabled{true}; bool m_areWaterCreaturesEnabled{true}; bool m_isBurnFlippedCarsEnabled{true}; bool m_isFireballDestructEnabled{true}; @@ -397,7 +394,7 @@ class CGameSA : public CGame bool m_isIgnoreFireStateEnabled{false}; bool m_isVehicleBurnExplosionsEnabled{true}; - static unsigned int& ClumpOffset; + static unsigned int& ClumpOffset; std::map m_Cheats; diff --git a/Client/game_sa/CGarageSA.h b/Client/game_sa/CGarageSA.h index cf8d2424419..55126c938af 100644 --- a/Client/game_sa/CGarageSA.h +++ b/Client/game_sa/CGarageSA.h @@ -17,20 +17,20 @@ class CGarageSAInterface { public: - CVector vecPosition; // 0 - float DirectionA_X, DirectionA_Y; // 12 - float DirectionB_X, DirectionB_Y; // 20 - float Height, Width, Depth; // 28 - float Left, Right, Front, Back; // 40 - float DoorPosition; // 56 - DWORD pad; // 60 - DWORD pad2; // 64 - char Name[8]; // 68 - BYTE Type; // 76 - BYTE DoorState; // 77 - BYTE DoorFlags; // 78 - BYTE OriginalType; // 79 - BYTE pad3[132]; // 80 + CVector vecPosition; // 0 + float DirectionA_X, DirectionA_Y; // 12 + float DirectionB_X, DirectionB_Y; // 20 + float Height, Width, Depth; // 28 + float Left, Right, Front, Back; // 40 + float DoorPosition; // 56 + DWORD pad; // 60 + DWORD pad2; // 64 + char Name[8]; // 68 + BYTE Type; // 76 + BYTE DoorState; // 77 + BYTE DoorFlags; // 78 + BYTE OriginalType; // 79 + BYTE pad3[132]; // 80 }; class CGarageSA : public CGarage diff --git a/Client/game_sa/CHandlingEntrySA.cpp b/Client/game_sa/CHandlingEntrySA.cpp index a68163bc182..10d8c0b8206 100644 --- a/Client/game_sa/CHandlingEntrySA.cpp +++ b/Client/game_sa/CHandlingEntrySA.cpp @@ -52,7 +52,7 @@ void CHandlingEntrySA::Recalculate() noexcept if (!m_HandlingSA) return; - // Copy our stored field to GTA's + // Copy our stored field to GTA's MemCpyFast(m_HandlingSA.get(), &m_Handling, sizeof(m_Handling)); ((void(_stdcall*)(tHandlingDataSA*))FUNC_HandlingDataMgr_ConvertDataToGameUnits)(m_HandlingSA.get()); } diff --git a/Client/game_sa/CHandlingEntrySA.h b/Client/game_sa/CHandlingEntrySA.h index 2f515b1a04e..ab17d26dfe6 100644 --- a/Client/game_sa/CHandlingEntrySA.h +++ b/Client/game_sa/CHandlingEntrySA.h @@ -21,67 +21,67 @@ class CTransmissionSAInterface { public: - float fUnknown[18]; // +40 + float fUnknown[18]; // +40 - unsigned char ucDriveType : 8; // +112 - unsigned char ucEngineType : 8; // +113 - unsigned char ucNumberOfGears : 8; // +114 - unsigned char ucUnknown : 8; // +115 + unsigned char ucDriveType : 8; // +112 + unsigned char ucEngineType : 8; // +113 + unsigned char ucNumberOfGears : 8; // +114 + unsigned char ucUnknown : 8; // +115 - unsigned int uiHandlingFlags; // +116 + unsigned int uiHandlingFlags; // +116 - float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) - float fEngineInertia; // +124 - float fMaxVelocity; // +128 + float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) + float fEngineInertia; // +124 + float fMaxVelocity; // +128 - float fUnknown2[3]; // +132 + float fUnknown2[3]; // +132 }; struct tHandlingDataSA { - int iVehicleID; // +0 + int iVehicleID; // +0 - float fMass; // +4 + float fMass; // +4 - float fUnknown1; // +8 Automatically calculated + float fUnknown1; // +8 Automatically calculated - float fTurnMass; // +12 - float fDragCoeff; // +16 - CVector vecCenterOfMass; // +20 - unsigned int uiPercentSubmerged; // +32 + float fTurnMass; // +12 + float fDragCoeff; // +16 + CVector vecCenterOfMass; // +20 + unsigned int uiPercentSubmerged; // +32 - float fUnknown2; // +36 Automatically calculated + float fUnknown2; // +36 Automatically calculated - float fTractionMultiplier; // +40 + float fTractionMultiplier; // +40 - CTransmissionSAInterface Transmission; // +44 - float fBrakeDeceleration; // +148 - float fBrakeBias; // +152 - bool bABS; // +156 - char fUnknown[3]; // +157 + CTransmissionSAInterface Transmission; // +44 + float fBrakeDeceleration; // +148 + float fBrakeBias; // +152 + bool bABS; // +156 + char fUnknown[3]; // +157 - float fSteeringLock; // +160 - float fTractionLoss; // +164 - float fTractionBias; // +168 + float fSteeringLock; // +160 + float fTractionLoss; // +164 + float fTractionBias; // +168 - float fSuspensionForceLevel; // +172 - float fSuspensionDamping; // +176 - float fSuspensionHighSpdDamping; // +180 - float fSuspensionUpperLimit; // +184 - float fSuspensionLowerLimit; // +188 - float fSuspensionFrontRearBias; // +192 - float fSuspensionAntiDiveMultiplier; // +196 + float fSuspensionForceLevel; // +172 + float fSuspensionDamping; // +176 + float fSuspensionHighSpdDamping; // +180 + float fSuspensionUpperLimit; // +184 + float fSuspensionLowerLimit; // +188 + float fSuspensionFrontRearBias; // +192 + float fSuspensionAntiDiveMultiplier; // +196 - float fCollisionDamageMultiplier; // +200 + float fCollisionDamageMultiplier; // +200 - unsigned int uiModelFlags; // +204 - unsigned int uiHandlingFlags; // +208 - float fSeatOffsetDistance; // +212 - unsigned int uiMonetary; // +216 + unsigned int uiModelFlags; // +204 + unsigned int uiHandlingFlags; // +208 + float fSeatOffsetDistance; // +212 + unsigned int uiMonetary; // +216 - unsigned char ucHeadLight : 8; // +220 - unsigned char ucTailLight : 8; // +221 - unsigned char ucAnimGroup : 8; // +222 + unsigned char ucHeadLight : 8; // +220 + unsigned char ucTailLight : 8; // +221 + unsigned char ucAnimGroup : 8; // +222 }; class CHandlingEntrySA : public CHandlingEntry @@ -93,7 +93,7 @@ class CHandlingEntrySA : public CHandlingEntry // Constructor for original entries CHandlingEntrySA(const tHandlingDataSA* const pOriginal); - virtual ~CHandlingEntrySA(){}; + virtual ~CHandlingEntrySA() {}; // Use this to copy data from an another handling class to this void Assign(const CHandlingEntry* const pEntry) noexcept; diff --git a/Client/game_sa/CHandlingManagerSA.cpp b/Client/game_sa/CHandlingManagerSA.cpp index 874b3e1f0b0..609b9fc8cd7 100644 --- a/Client/game_sa/CHandlingManagerSA.cpp +++ b/Client/game_sa/CHandlingManagerSA.cpp @@ -22,11 +22,11 @@ extern CCoreInterface* g_pCore; extern CGameSA* pGame; -#define ARRAY_HANDLINGDATA 0xC2B9DC +#define ARRAY_HANDLINGDATA 0xC2B9DC -#define Func_Calculate 0x6F5080 -#define Var_fTurnMassMultiplier 0x858B8C -#define Var_fBasicDragCoeff 0x858C58 +#define Func_Calculate 0x6F5080 +#define Var_fTurnMassMultiplier 0x858B8C +#define Var_fBasicDragCoeff 0x858C58 #define DUMP_HANDLING_DATA 0 @@ -158,39 +158,39 @@ CHandlingManagerSA::CHandlingManagerSA() HookInstall(Func_Calculate, (DWORD)Hook_Calculate, 5); #endif - m_HandlingNames["mass"] = HandlingProperty::HANDLING_MASS; // works (mass > 0) - m_HandlingNames["turnMass"] = HandlingProperty::HANDLING_TURNMASS; // works - m_HandlingNames["dragCoeff"] = HandlingProperty::HANDLING_DRAGCOEFF; // works - m_HandlingNames["centerOfMass"] = HandlingProperty::HANDLING_CENTEROFMASS; // works - m_HandlingNames["percentSubmerged"] = HandlingProperty::HANDLING_PERCENTSUBMERGED; // works - m_HandlingNames["tractionMultiplier"] = HandlingProperty::HANDLING_TRACTIONMULTIPLIER; // works - m_HandlingNames["driveType"] = HandlingProperty::HANDLING_DRIVETYPE; // works - m_HandlingNames["engineType"] = HandlingProperty::HANDLING_ENGINETYPE; // works - m_HandlingNames["numberOfGears"] = HandlingProperty::HANDLING_NUMOFGEARS; // works - m_HandlingNames["engineAcceleration"] = HandlingProperty::HANDLING_ENGINEACCELERATION; // works - m_HandlingNames["engineInertia"] = HandlingProperty::HANDLING_ENGINEINERTIA; // works - m_HandlingNames["maxVelocity"] = HandlingProperty::HANDLING_MAXVELOCITY; // works - m_HandlingNames["brakeDeceleration"] = HandlingProperty::HANDLING_BRAKEDECELERATION; // works - m_HandlingNames["brakeBias"] = HandlingProperty::HANDLING_BRAKEBIAS; // works - m_HandlingNames["ABS"] = HandlingProperty::HANDLING_ABS; // has no effect in vanilla gta either - m_HandlingNames["steeringLock"] = HandlingProperty::HANDLING_STEERINGLOCK; // works - m_HandlingNames["tractionLoss"] = HandlingProperty::HANDLING_TRACTIONLOSS; // works - m_HandlingNames["tractionBias"] = HandlingProperty::HANDLING_TRACTIONBIAS; // works - m_HandlingNames["suspensionForceLevel"] = HandlingProperty::HANDLING_SUSPENSION_FORCELEVEL; // works - m_HandlingNames["suspensionDamping"] = HandlingProperty::HANDLING_SUSPENSION_DAMPING; // works - m_HandlingNames["suspensionHighSpeedDamping"] = HandlingProperty::HANDLING_SUSPENSION_HIGHSPEEDDAMPING; // works - m_HandlingNames["suspensionUpperLimit"] = HandlingProperty::HANDLING_SUSPENSION_UPPER_LIMIT; // works - m_HandlingNames["suspensionLowerLimit"] = HandlingProperty::HANDLING_SUSPENSION_LOWER_LIMIT; // works - m_HandlingNames["suspensionFrontRearBias"] = HandlingProperty::HANDLING_SUSPENSION_FRONTREARBIAS; // works - m_HandlingNames["suspensionAntiDiveMultiplier"] = HandlingProperty::HANDLING_SUSPENSION_ANTIDIVEMULTIPLIER; // works - m_HandlingNames["collisionDamageMultiplier"] = HandlingProperty::HANDLING_COLLISIONDAMAGEMULTIPLIER; // works - m_HandlingNames["seatOffsetDistance"] = HandlingProperty::HANDLING_SEATOFFSETDISTANCE; // works - m_HandlingNames["monetary"] = HandlingProperty::HANDLING_MONETARY; // useless as it only influences SP stats (value of damaged property) - m_HandlingNames["handlingFlags"] = HandlingProperty::HANDLING_HANDLINGFLAGS; // works - m_HandlingNames["modelFlags"] = HandlingProperty::HANDLING_MODELFLAGS; // works - m_HandlingNames["headLight"] = HandlingProperty::HANDLING_HEADLIGHT; // doesn't work - m_HandlingNames["tailLight"] = HandlingProperty::HANDLING_TAILLIGHT; // doesn't seem to work* - m_HandlingNames["animGroup"] = HandlingProperty::HANDLING_ANIMGROUP; // works model based + m_HandlingNames["mass"] = HandlingProperty::HANDLING_MASS; // works (mass > 0) + m_HandlingNames["turnMass"] = HandlingProperty::HANDLING_TURNMASS; // works + m_HandlingNames["dragCoeff"] = HandlingProperty::HANDLING_DRAGCOEFF; // works + m_HandlingNames["centerOfMass"] = HandlingProperty::HANDLING_CENTEROFMASS; // works + m_HandlingNames["percentSubmerged"] = HandlingProperty::HANDLING_PERCENTSUBMERGED; // works + m_HandlingNames["tractionMultiplier"] = HandlingProperty::HANDLING_TRACTIONMULTIPLIER; // works + m_HandlingNames["driveType"] = HandlingProperty::HANDLING_DRIVETYPE; // works + m_HandlingNames["engineType"] = HandlingProperty::HANDLING_ENGINETYPE; // works + m_HandlingNames["numberOfGears"] = HandlingProperty::HANDLING_NUMOFGEARS; // works + m_HandlingNames["engineAcceleration"] = HandlingProperty::HANDLING_ENGINEACCELERATION; // works + m_HandlingNames["engineInertia"] = HandlingProperty::HANDLING_ENGINEINERTIA; // works + m_HandlingNames["maxVelocity"] = HandlingProperty::HANDLING_MAXVELOCITY; // works + m_HandlingNames["brakeDeceleration"] = HandlingProperty::HANDLING_BRAKEDECELERATION; // works + m_HandlingNames["brakeBias"] = HandlingProperty::HANDLING_BRAKEBIAS; // works + m_HandlingNames["ABS"] = HandlingProperty::HANDLING_ABS; // has no effect in vanilla gta either + m_HandlingNames["steeringLock"] = HandlingProperty::HANDLING_STEERINGLOCK; // works + m_HandlingNames["tractionLoss"] = HandlingProperty::HANDLING_TRACTIONLOSS; // works + m_HandlingNames["tractionBias"] = HandlingProperty::HANDLING_TRACTIONBIAS; // works + m_HandlingNames["suspensionForceLevel"] = HandlingProperty::HANDLING_SUSPENSION_FORCELEVEL; // works + m_HandlingNames["suspensionDamping"] = HandlingProperty::HANDLING_SUSPENSION_DAMPING; // works + m_HandlingNames["suspensionHighSpeedDamping"] = HandlingProperty::HANDLING_SUSPENSION_HIGHSPEEDDAMPING; // works + m_HandlingNames["suspensionUpperLimit"] = HandlingProperty::HANDLING_SUSPENSION_UPPER_LIMIT; // works + m_HandlingNames["suspensionLowerLimit"] = HandlingProperty::HANDLING_SUSPENSION_LOWER_LIMIT; // works + m_HandlingNames["suspensionFrontRearBias"] = HandlingProperty::HANDLING_SUSPENSION_FRONTREARBIAS; // works + m_HandlingNames["suspensionAntiDiveMultiplier"] = HandlingProperty::HANDLING_SUSPENSION_ANTIDIVEMULTIPLIER; // works + m_HandlingNames["collisionDamageMultiplier"] = HandlingProperty::HANDLING_COLLISIONDAMAGEMULTIPLIER; // works + m_HandlingNames["seatOffsetDistance"] = HandlingProperty::HANDLING_SEATOFFSETDISTANCE; // works + m_HandlingNames["monetary"] = HandlingProperty::HANDLING_MONETARY; // useless as it only influences SP stats (value of damaged property) + m_HandlingNames["handlingFlags"] = HandlingProperty::HANDLING_HANDLINGFLAGS; // works + m_HandlingNames["modelFlags"] = HandlingProperty::HANDLING_MODELFLAGS; // works + m_HandlingNames["headLight"] = HandlingProperty::HANDLING_HEADLIGHT; // doesn't work + m_HandlingNames["tailLight"] = HandlingProperty::HANDLING_TAILLIGHT; // doesn't seem to work* + m_HandlingNames["animGroup"] = HandlingProperty::HANDLING_ANIMGROUP; // works model based } CHandlingManagerSA::~CHandlingManagerSA() @@ -8278,28 +8278,28 @@ void CHandlingManagerSA::InitializeDefaultHandlings() noexcept m_OriginalHandlingData[209].ucTailLight = 1; m_OriginalHandlingData[209].ucAnimGroup = 0; - m_OriginalHandlingData[210] = m_OriginalHandlingData[69]; // HT_HOTRINA = HT_HOTRING + m_OriginalHandlingData[210] = m_OriginalHandlingData[69]; // HT_HOTRINA = HT_HOTRING m_OriginalHandlingData[210].iVehicleID = 210; - m_OriginalHandlingData[211] = m_OriginalHandlingData[69]; // HT_HOTRINB = HT_HOTRING + m_OriginalHandlingData[211] = m_OriginalHandlingData[69]; // HT_HOTRINB = HT_HOTRING m_OriginalHandlingData[211].iVehicleID = 211; - m_OriginalHandlingData[212] = m_OriginalHandlingData[103]; // HT_SADLSHIT = HT_SADLER + m_OriginalHandlingData[212] = m_OriginalHandlingData[103]; // HT_SADLSHIT = HT_SADLER m_OriginalHandlingData[212].iVehicleID = 212; - m_OriginalHandlingData[213] = m_OriginalHandlingData[52]; // HT_GLENSHIT = HT_GLENDALE + m_OriginalHandlingData[213] = m_OriginalHandlingData[52]; // HT_GLENSHIT = HT_GLENDALE m_OriginalHandlingData[213].iVehicleID = 213; - m_OriginalHandlingData[214] = m_OriginalHandlingData[163]; // HT_FAGGIO = HT_PIZZABOY + m_OriginalHandlingData[214] = m_OriginalHandlingData[163]; // HT_FAGGIO = HT_PIZZABOY m_OriginalHandlingData[214].iVehicleID = 214; - m_OriginalHandlingData[215] = m_OriginalHandlingData[7]; // HT_FIRELA = HT_FIRETRUK + m_OriginalHandlingData[215] = m_OriginalHandlingData[7]; // HT_FIRELA = HT_FIRETRUK m_OriginalHandlingData[215].iVehicleID = 215; - m_OriginalHandlingData[216] = m_OriginalHandlingData[65]; // HT_RNCHLURE = HT_RANCHER + m_OriginalHandlingData[216] = m_OriginalHandlingData[65]; // HT_RNCHLURE = HT_RANCHER m_OriginalHandlingData[216].iVehicleID = 216; - m_OriginalHandlingData[217] = m_OriginalHandlingData[126]; // HT_FREIBOX = HT_FREIFLAT + m_OriginalHandlingData[217] = m_OriginalHandlingData[126]; // HT_FREIBOX = HT_FREIFLAT m_OriginalHandlingData[217].iVehicleID = 217; // Aircrafts handling @@ -9129,7 +9129,7 @@ void CHandlingManagerSA::InitializeDefaultHandlings() noexcept m_OriginalBikeHandlingData[12].fWheelieStabMult = 0.5f; m_OriginalBikeHandlingData[12].fStoppieStabMult = 0.3f; - m_OriginalBikeHandlingData[13] = m_OriginalBikeHandlingData[1]; // HT_FAGGIO = HT_PIZZABOY + m_OriginalBikeHandlingData[13] = m_OriginalBikeHandlingData[1]; // HT_FAGGIO = HT_PIZZABOY m_OriginalBikeHandlingData[13].iVehicleID = 214; } diff --git a/Client/game_sa/CHeliSA.h b/Client/game_sa/CHeliSA.h index 67579883e61..eebba976146 100644 --- a/Client/game_sa/CHeliSA.h +++ b/Client/game_sa/CHeliSA.h @@ -16,37 +16,37 @@ class CHeliSAInterface : public CAutomobileSAInterface { public: - std::uint8_t m_nHeliFlags; // 0x988 - std::uint8_t ___pad1[3]; // 0x989 - float m_fLeftRightSkid; // 0x98C - float m_fSteeringUpDown; // 0x990 - float m_fSteeringLeftRight; // 0x994 - float m_fAccelerationBreakStatus; // 0x998 - std::int32_t field_99C; // 0x99C - float m_fRotorZ; // 0x9A0 - float m_fSecondRotorZ; // 0x9A4 - float m_fMaxAltitude; // 0x9A8 - std::int32_t field_9AC; // 0x9AC - float m_fMinAltitude; // 0x9B0 - std::int32_t field_9B4; // 0x9B4 - std::uint8_t field_9B8; // 0x9B8 - std::uint8_t m_nNumSwatOccupants; // 0x9B9 - std::uint8_t m_anSwatIDs[4]; // 0x9BA - std::uint8_t ___pad2[2]; // 0x9BE - std::uint32_t field_9C0[4]; // 0x9C0 - std::int32_t field_9D0; // 0x9D0 - FxSystem_c** m_pParticlesList; // 0x9D4 - std::uint8_t field_9D8[24]; // 0x9D8 - std::int32_t field_9F0; // 0x9F0 - CVector m_vecSearchLightTarget; // 0x9F4 - float m_fSearchLightIntensity; // 0xA00 - std::int32_t field_A04; // 0xA04 - std::int32_t field_A08; // 0xA08 - FxSystem_c** m_ppGunflashFx; // 0xA0C - std::uint8_t m_nFiringMultiplier; // 0xA10 - bool m_bSearchLightEnabled; // 0xA11 - std::uint8_t ___pad3[2]; // 0xA12 - std::int32_t field_A14; // 0xA14 + std::uint8_t m_nHeliFlags; // 0x988 + std::uint8_t ___pad1[3]; // 0x989 + float m_fLeftRightSkid; // 0x98C + float m_fSteeringUpDown; // 0x990 + float m_fSteeringLeftRight; // 0x994 + float m_fAccelerationBreakStatus; // 0x998 + std::int32_t field_99C; // 0x99C + float m_fRotorZ; // 0x9A0 + float m_fSecondRotorZ; // 0x9A4 + float m_fMaxAltitude; // 0x9A8 + std::int32_t field_9AC; // 0x9AC + float m_fMinAltitude; // 0x9B0 + std::int32_t field_9B4; // 0x9B4 + std::uint8_t field_9B8; // 0x9B8 + std::uint8_t m_nNumSwatOccupants; // 0x9B9 + std::uint8_t m_anSwatIDs[4]; // 0x9BA + std::uint8_t ___pad2[2]; // 0x9BE + std::uint32_t field_9C0[4]; // 0x9C0 + std::int32_t field_9D0; // 0x9D0 + FxSystem_c** m_pParticlesList; // 0x9D4 + std::uint8_t field_9D8[24]; // 0x9D8 + std::int32_t field_9F0; // 0x9F0 + CVector m_vecSearchLightTarget; // 0x9F4 + float m_fSearchLightIntensity; // 0xA00 + std::int32_t field_A04; // 0xA04 + std::int32_t field_A08; // 0xA08 + FxSystem_c** m_ppGunflashFx; // 0xA0C + std::uint8_t m_nFiringMultiplier; // 0xA10 + bool m_bSearchLightEnabled; // 0xA11 + std::uint8_t ___pad3[2]; // 0xA12 + std::int32_t field_A14; // 0xA14 }; static_assert(sizeof(CHeliSAInterface) == 0xA18, "Invalid size for CHeliSAInterface"); diff --git a/Client/game_sa/CHudSA.cpp b/Client/game_sa/CHudSA.cpp index 2e6fb802ae0..e361afdd8ca 100644 --- a/Client/game_sa/CHudSA.cpp +++ b/Client/game_sa/CHudSA.cpp @@ -24,7 +24,7 @@ char szZoneName[50] = {'\0'}; static ComponentProperties componentProperties; -RsGlobal* CHudSA::rsGlobal = reinterpret_cast(VAR_RSGlobal); +RsGlobal* CHudSA::rsGlobal = reinterpret_cast(VAR_RSGlobal); std::int16_t* CHudSA::itemToFlash = reinterpret_cast(VAR_ItemToFlash); float CHudSA::calcStreetchX = 0.0f; @@ -43,14 +43,22 @@ std::unordered_map defaultComponentProperties {HUD_BREATH, {CHudSA::GetHUDColour(eHudColour::LIGHT_BLUE)}}, {HUD_ARMOUR, {CHudSA::GetHUDColour(eHudColour::LIGHT_GRAY)}}, {HUD_CLOCK, {CHudSA::GetHUDColour(eHudColour::LIGHT_GRAY), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_RIGHT, eFontStyle::FONT_PRICEDOWN, 2}}, - {HUD_MONEY, {CHudSA::GetHUDColour(eHudColour::GREEN), CHudSA::GetHUDColour(eHudColour::RED), false, false, COLOR_BLACK, eFontAlignment::ALIGN_RIGHT, eFontStyle::FONT_PRICEDOWN, 2}}, - {HUD_AMMO, {CHudSA::GetHUDColour(eHudColour::LIGHT_BLUE), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_SUBTITLES, 1, 0, true}}, - {HUD_VEHICLE_NAME, {CHudSA::GetHUDColour(eHudColour::GREEN), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_MENU, 2, 0, true}}, - {HUD_AREA_NAME, {CHudSA::GetHUDColour(eHudColour::LIGHT_BLUE), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_GOTHIC, 2, 0, true}}, - {HUD_RADIO, {CHudSA::GetHUDColour(eHudColour::GOLD), CHudSA::GetHUDColour(eHudColour::DARK_GRAY), false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_MENU, 1, 0, true}}, + {HUD_MONEY, + {CHudSA::GetHUDColour(eHudColour::GREEN), CHudSA::GetHUDColour(eHudColour::RED), false, false, COLOR_BLACK, eFontAlignment::ALIGN_RIGHT, + eFontStyle::FONT_PRICEDOWN, 2}}, + {HUD_AMMO, + {CHudSA::GetHUDColour(eHudColour::LIGHT_BLUE), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_SUBTITLES, 1, 0, true}}, + {HUD_VEHICLE_NAME, + {CHudSA::GetHUDColour(eHudColour::GREEN), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_MENU, 2, 0, true}}, + {HUD_AREA_NAME, + {CHudSA::GetHUDColour(eHudColour::LIGHT_BLUE), {}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, eFontStyle::FONT_GOTHIC, 2, 0, true}}, + {HUD_RADIO, + {CHudSA::GetHUDColour(eHudColour::GOLD), CHudSA::GetHUDColour(eHudColour::DARK_GRAY), false, false, COLOR_BLACK, eFontAlignment::ALIGN_CENTER, + eFontStyle::FONT_MENU, 1, 0, true}}, {HUD_WEAPON, {RwColor{255, 255, 255, 255}, RwColor{255, 255, 255, 255}}}, - {HUD_WANTED, {CHudSA::GetHUDColour(eHudColour::GOLD), RwColor{0, 0, 0, 170}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_RIGHT, eFontStyle::FONT_GOTHIC, 1, 0, true}} -}; + {HUD_WANTED, + {CHudSA::GetHUDColour(eHudColour::GOLD), RwColor{0, 0, 0, 170}, false, false, COLOR_BLACK, eFontAlignment::ALIGN_RIGHT, eFontStyle::FONT_GOTHIC, 1, 0, + true}}}; CHudSA::CHudSA() { @@ -193,7 +201,7 @@ bool CHudSA::IsComponentVisible(eHudComponent component) uchar* pSrc = (uchar*)(&pComponent->disabledData); uchar* pDest = (uchar*)(pComponent->uiDataAddr); if (memcmp(pDest, pSrc, pComponent->uiDataSize) == 0) - return false; // Matches disabled bytes + return false; // Matches disabled bytes return true; } return false; @@ -302,8 +310,8 @@ bool CHudSA::IsCrosshairVisible() eCamMode cameraViewMode = static_cast(camera->GetCam(camera->GetActiveCam())->GetMode()); // Get player - CPed* playerPed = pGame->GetPedContext(); - CWeapon* weapon = nullptr; + CPed* playerPed = pGame->GetPedContext(); + CWeapon* weapon = nullptr; eWeaponType weaponType; // Get player current weapon @@ -315,24 +323,29 @@ bool CHudSA::IsCrosshairVisible() } // Special aiming - if (cameraViewMode == MODE_SNIPER || cameraViewMode == MODE_1STPERSON || cameraViewMode == MODE_ROCKETLAUNCHER || cameraViewMode == MODE_ROCKETLAUNCHER_HS || cameraViewMode == MODE_M16_1STPERSON || cameraViewMode == MODE_HELICANNON_1STPERSON || cameraViewMode == MODE_CAMERA) + if (cameraViewMode == MODE_SNIPER || cameraViewMode == MODE_1STPERSON || cameraViewMode == MODE_ROCKETLAUNCHER || + cameraViewMode == MODE_ROCKETLAUNCHER_HS || cameraViewMode == MODE_M16_1STPERSON || cameraViewMode == MODE_HELICANNON_1STPERSON || + cameraViewMode == MODE_CAMERA) { if (weapon && cameraViewMode != MODE_1STPERSON && pGame->GetWeaponInfo(weaponType, WEAPONSKILL_STD)->GetFireType() != FIRETYPE_MELEE) specialAiming = true; } // Simple aiming - if (cameraViewMode == MODE_M16_1STPERSON_RUNABOUT || cameraViewMode == MODE_ROCKETLAUNCHER_RUNABOUT || cameraViewMode == MODE_ROCKETLAUNCHER_RUNABOUT_HS || cameraViewMode == MODE_SNIPER_RUNABOUT) + if (cameraViewMode == MODE_M16_1STPERSON_RUNABOUT || cameraViewMode == MODE_ROCKETLAUNCHER_RUNABOUT || cameraViewMode == MODE_ROCKETLAUNCHER_RUNABOUT_HS || + cameraViewMode == MODE_SNIPER_RUNABOUT) simpleAiming = true; if ((playerPed && weapon) && !playerPed->GetTargetedObject() && playerPed->GetPedInterface()->pPlayerData->m_bFreeAiming) { CTaskSimpleUseGun* taskUseGun = playerPed->GetPedIntelligence()->GetTaskUseGun(); - if ((!taskUseGun || !taskUseGun->GetSkipAim()) && (cameraViewMode == MODE_AIMWEAPON || cameraViewMode == MODE_AIMWEAPON_FROMCAR || cameraViewMode == MODE_AIMWEAPON_ATTACHED)) + if ((!taskUseGun || !taskUseGun->GetSkipAim()) && + (cameraViewMode == MODE_AIMWEAPON || cameraViewMode == MODE_AIMWEAPON_FROMCAR || cameraViewMode == MODE_AIMWEAPON_ATTACHED)) { if (playerPed->GetPedState() != PedState::PED_ENTER_CAR && playerPed->GetPedState() != PedState::PED_CARJACK) { - if ((weaponType >= WEAPONTYPE_PISTOL && weaponType <= WEAPONTYPE_M4) || weaponType == WEAPONTYPE_TEC9 || weaponType == WEAPONTYPE_COUNTRYRIFLE || weaponType == WEAPONTYPE_MINIGUN || weaponType == WEAPONTYPE_FLAMETHROWER) + if ((weaponType >= WEAPONTYPE_PISTOL && weaponType <= WEAPONTYPE_M4) || weaponType == WEAPONTYPE_TEC9 || + weaponType == WEAPONTYPE_COUNTRYRIFLE || weaponType == WEAPONTYPE_MINIGUN || weaponType == WEAPONTYPE_FLAMETHROWER) simpleAiming = cameraViewMode != MODE_AIMWEAPON || camera->GetTransitionState() == 0; } } @@ -544,7 +557,7 @@ void CHudSA::ResetComponentPlacement(const eHudComponent& component, bool resetS } void CHudSA::SetComponentColor(const eHudComponent& component, std::uint32_t color, bool secondColor) noexcept -{ +{ SColor newColor = TOCOLOR2SCOLOR(color); auto& compRef = GetHudComponentRef(component); @@ -608,7 +621,7 @@ SColor CHudSA::GetComponentSecondaryColor(const eHudComponent& component) const SColor CHudSA::GetComponentFontDropColor(const eHudComponent& component) const { - const auto& ref = GetHudComponentRef(component); + const auto& ref = GetHudComponentRef(component); const RwColor& color = CFontSA::GetDropColor(); return SColorRGBA(color.r, color.g, color.b, color.a); } @@ -617,7 +630,7 @@ void CHudSA::RenderHealthBar(int x, int y) { // Flash each 8 frames bool isValidFrame = (pGame->GetSystemFrameCounter() & 8) == 0; - if (*itemToFlash == 4 && isValidFrame) // 4 = HEALTH_BAR + if (*itemToFlash == 4 && isValidFrame) // 4 = HEALTH_BAR return; CPed* playerPed = pGame->GetPedContext(); @@ -645,18 +658,20 @@ void CHudSA::RenderHealthBar(int x, int y) float statModifier = ((float(__cdecl*)(int))FUNC_CStats_GetFatAndMuscleModifier)(10); float totalWidth = (barWidth * maxHealth) / statModifier; - float posX = useCustomPosition ? componentProperties.hpBar.placement.customX : (barWidth - totalWidth + x); - float posY = useCustomPosition ? componentProperties.hpBar.placement.customY : y; - std::uint32_t barHeight = static_cast(useCustomSize ? componentProperties.hpBar.placement.customHeight : componentProperties.hpBar.placement.height); + float posX = useCustomPosition ? componentProperties.hpBar.placement.customX : (barWidth - totalWidth + x); + float posY = useCustomPosition ? componentProperties.hpBar.placement.customY : y; + std::uint32_t barHeight = + static_cast(useCustomSize ? componentProperties.hpBar.placement.customHeight : componentProperties.hpBar.placement.height); // call CSprite2d::DrawBarChart - DrawBarChart(posX, posY, static_cast(totalWidth), barHeight, playerPed->GetHealth() * 100.0f / maxHealth, false, componentProperties.hpBar.drawPercentage, componentProperties.hpBar.drawBlackBorder, componentProperties.hpBar.fillColor, COLOR_BLACK); + DrawBarChart(posX, posY, static_cast(totalWidth), barHeight, playerPed->GetHealth() * 100.0f / maxHealth, false, + componentProperties.hpBar.drawPercentage, componentProperties.hpBar.drawBlackBorder, componentProperties.hpBar.fillColor, COLOR_BLACK); } void CHudSA::RenderBreathBar(int x, int y) { // Flash each 8 frames - if (*itemToFlash == 10 && (pGame->GetSystemFrameCounter() & 8) == 0) // 10 = BREATH_BAR + if (*itemToFlash == 10 && (pGame->GetSystemFrameCounter() & 8) == 0) // 10 = BREATH_BAR return; CPed* playerPed = pGame->GetPedContext(); @@ -678,19 +693,22 @@ void CHudSA::RenderBreathBar(int x, int y) bool useCustomPosition = componentProperties.breathBar.placement.useCustomPosition; bool useCustomSize = componentProperties.breathBar.placement.useCustomSize; - float posX = useCustomPosition ? componentProperties.breathBar.placement.customX : x; - float posY = useCustomPosition ? componentProperties.breathBar.placement.customY : y; - std::uint16_t barWidth = static_cast(useCustomSize ? componentProperties.breathBar.placement.customWidth : componentProperties.breathBar.placement.width); - std::uint32_t barHeight = static_cast(useCustomSize ? componentProperties.breathBar.placement.customHeight : componentProperties.breathBar.placement.height); + float posX = useCustomPosition ? componentProperties.breathBar.placement.customX : x; + float posY = useCustomPosition ? componentProperties.breathBar.placement.customY : y; + std::uint16_t barWidth = + static_cast(useCustomSize ? componentProperties.breathBar.placement.customWidth : componentProperties.breathBar.placement.width); + std::uint32_t barHeight = + static_cast(useCustomSize ? componentProperties.breathBar.placement.customHeight : componentProperties.breathBar.placement.height); // call CSprite2d::DrawBarChart - DrawBarChart(posX, posY, barWidth, barHeight, playerPed->GetOxygenLevel() / statModifier * 100.0f, false, componentProperties.breathBar.drawPercentage, componentProperties.breathBar.drawBlackBorder, componentProperties.breathBar.fillColor, COLOR_BLACK); + DrawBarChart(posX, posY, barWidth, barHeight, playerPed->GetOxygenLevel() / statModifier * 100.0f, false, componentProperties.breathBar.drawPercentage, + componentProperties.breathBar.drawBlackBorder, componentProperties.breathBar.fillColor, COLOR_BLACK); } void CHudSA::RenderArmorBar(int x, int y) { // Flash each 8 frames - if (*itemToFlash == 3 && (pGame->GetSystemFrameCounter() & 8) == 0) // 3 = ARMOR_BAR + if (*itemToFlash == 3 && (pGame->GetSystemFrameCounter() & 8) == 0) // 3 = ARMOR_BAR return; CPed* playerPed = pGame->GetPedContext(); @@ -709,13 +727,17 @@ void CHudSA::RenderArmorBar(int x, int y) bool useCustomPosition = componentProperties.hpBar.placement.useCustomPosition; bool useCustomSize = componentProperties.hpBar.placement.useCustomSize; - float posX = useCustomPosition ? componentProperties.armorBar.placement.customX : x; - float posY = useCustomPosition ? componentProperties.armorBar.placement.customY : y; - std::uint16_t barWidth = static_cast(useCustomSize ? componentProperties.armorBar.placement.customWidth : componentProperties.armorBar.placement.width); - std::uint32_t barHeight = static_cast(useCustomSize ? componentProperties.armorBar.placement.customHeight : componentProperties.armorBar.placement.height); + float posX = useCustomPosition ? componentProperties.armorBar.placement.customX : x; + float posY = useCustomPosition ? componentProperties.armorBar.placement.customY : y; + std::uint16_t barWidth = + static_cast(useCustomSize ? componentProperties.armorBar.placement.customWidth : componentProperties.armorBar.placement.width); + std::uint32_t barHeight = + static_cast(useCustomSize ? componentProperties.armorBar.placement.customHeight : componentProperties.armorBar.placement.height); // call CSprite2d::DrawBarChart - DrawBarChart(posX, posY, barWidth, barHeight, playerPed->GetArmor() / static_cast(pGame->GetPlayerInfo()->GetMaxArmor()) * 100.0f, false, componentProperties.armorBar.drawPercentage, componentProperties.armorBar.drawBlackBorder, componentProperties.armorBar.fillColor, COLOR_BLACK); + DrawBarChart(posX, posY, barWidth, barHeight, playerPed->GetArmor() / static_cast(pGame->GetPlayerInfo()->GetMaxArmor()) * 100.0f, false, + componentProperties.armorBar.drawPercentage, componentProperties.armorBar.drawBlackBorder, componentProperties.armorBar.fillColor, + COLOR_BLACK); } void CHudSA::RenderText(float x, float y, const char* text, SHudComponentData& properties, bool useSecondColor, bool drawFromBottom, bool scaleForLanguage) @@ -749,7 +771,9 @@ void CHudSA::RenderText(float x, float y, const char* text, SHudComponentData& p if (!properties.useCustomAlpha) { CFontSA::SetDropColor(RwColor{properties.dropColor.r, properties.dropColor.g, properties.dropColor.b, CFontSA::GetColor().a}); - CFontSA::SetColor(useSecondColor ? RwColor{properties.fillColorSecondary.r, properties.fillColorSecondary.g, properties.fillColorSecondary.b, CFontSA::GetColor().a} : RwColor{properties.fillColor.r, properties.fillColor.g, properties.fillColor.b, CFontSA::GetColor().a}); + CFontSA::SetColor( + useSecondColor ? RwColor{properties.fillColorSecondary.r, properties.fillColorSecondary.g, properties.fillColorSecondary.b, CFontSA::GetColor().a} + : RwColor{properties.fillColor.r, properties.fillColor.g, properties.fillColor.b, CFontSA::GetColor().a}); } else { @@ -847,7 +871,8 @@ void __fastcall CHudSA::RenderWeaponIcon_Sprite(void* sprite, void*, CRect* rect ((void(__thiscall*)(void*, CRect*, RwColor*))FUNC_CSprite2d_Draw)(sprite, rect, color); } -void CHudSA::RenderWeaponIcon_XLU(CVector pos, CVector2D halfSize, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint16_t intensity, float rhw, std::uint8_t a, std::uint8_t uDir, std::uint8_t vDir) +void CHudSA::RenderWeaponIcon_XLU(CVector pos, CVector2D halfSize, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint16_t intensity, float rhw, + std::uint8_t a, std::uint8_t uDir, std::uint8_t vDir) { // Use custom position/size? SHudComponentData& properties = componentProperties.weaponIcon; @@ -888,7 +913,8 @@ void CHudSA::RenderWeaponIcon_XLU(CVector pos, CVector2D halfSize, std::uint8_t } // Call CSprite::RenderOneXLUSprite - ((void(__cdecl*)(CVector, CVector2D, std::uint8_t, std::uint8_t, std::uint8_t, std::uint16_t, float, std::uint8_t, std::uint8_t, std::uint8_t))FUNC_CSprite_RenderOneXLUSprite)(pos, halfSize, r, g, b, intensity, rhw, a, uDir, vDir); + ((void(__cdecl*)(CVector, CVector2D, std::uint8_t, std::uint8_t, std::uint8_t, std::uint16_t, float, std::uint8_t, std::uint8_t, + std::uint8_t))FUNC_CSprite_RenderOneXLUSprite)(pos, halfSize, r, g, b, intensity, rhw, a, uDir, vDir); } void CHudSA::RenderWanted(bool empty, float x, float y, const char* strLevel) @@ -897,7 +923,7 @@ void CHudSA::RenderWanted(bool empty, float x, float y, const char* strLevel) } static constexpr std::uintptr_t CONTINUE_RenderWanted = 0x58DFD8; -static void __declspec(naked) HOOK_RenderWanted() +static void __declspec(naked) HOOK_RenderWanted() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CHudSA.h b/Client/game_sa/CHudSA.h index 9584ccd71b3..520bd053a0c 100644 --- a/Client/game_sa/CHudSA.h +++ b/Client/game_sa/CHudSA.h @@ -17,43 +17,43 @@ #include "CFontSA.h" #include "CRect.h" -#define FUNC_Draw 0x58FAE0 +#define FUNC_Draw 0x58FAE0 -#define VAR_DisableClock 0xBAA400 +#define VAR_DisableClock 0xBAA400 // X -#define VAR_AspectRatioMultX 0x859520 +#define VAR_AspectRatioMultX 0x859520 // Y -#define VAR_AspectRatioMult 0x859524 - -#define VAR_CameraCrosshairScale 0x866C74 - -#define FUNC_DrawAmmo 0x5893B0 -#define FUNC_DrawWeaponIcon 0x58D7D0 -#define FUNC_RenderHealthBar 0x589270 -#define FUNC_RenderBreathBar 0x589190 -#define FUNC_RenderArmorBar 0x5890A0 - -#define FUNC_DrawVitalStats 0x589650 -#define FUNC_DrawVehicleName 0x58AEA0 -#define FUNC_DrawHelpText 0x58B6E0 -#define FUNC_DrawAreaName 0x58AA50 -#define FUNC_DrawRadar 0x58A330 -#define FUNC_DrawRadarPlanB 0x58A335 -#define FUNC_DrawRadioName 0x4E9E50 -#define FUNC_DrawWantedLevel 0x58D9A0 -#define FUNC_DrawCrosshair 0x58E020 +#define VAR_AspectRatioMult 0x859524 + +#define VAR_CameraCrosshairScale 0x866C74 + +#define FUNC_DrawAmmo 0x5893B0 +#define FUNC_DrawWeaponIcon 0x58D7D0 +#define FUNC_RenderHealthBar 0x589270 +#define FUNC_RenderBreathBar 0x589190 +#define FUNC_RenderArmorBar 0x5890A0 + +#define FUNC_DrawVitalStats 0x589650 +#define FUNC_DrawVehicleName 0x58AEA0 +#define FUNC_DrawHelpText 0x58B6E0 +#define FUNC_DrawAreaName 0x58AA50 +#define FUNC_DrawRadar 0x58A330 +#define FUNC_DrawRadarPlanB 0x58A335 +#define FUNC_DrawRadioName 0x4E9E50 +#define FUNC_DrawWantedLevel 0x58D9A0 +#define FUNC_DrawCrosshair 0x58E020 #define FUNC_CStats_GetFatAndMuscleModifier 0x559AF0 #define FUNC_CSprite2d_DrawBarChart 0x728640 -#define FUNC_CSprite2d_Draw 0x728350 +#define FUNC_CSprite2d_Draw 0x728350 #define FUNC_CSprite_RenderOneXLUSprite 0x70D000 -#define FUNC_CRadar_DrawMap 0x586B00 -#define FUNC_CRadar_DrawBlips 0x588050 +#define FUNC_CRadar_DrawMap 0x586B00 +#define FUNC_CRadar_DrawBlips 0x588050 -#define CODE_ShowMoney 0x58F47D -#define CODE_ShowRadarAltimeter 0x58A5A6 +#define CODE_ShowMoney 0x58F47D +#define CODE_ShowRadarAltimeter 0x58A5A6 #define VAR_CTheScripts_bDrawCrossHair 0xA44490 #define VAR_RSGlobal 0xC17040 @@ -97,68 +97,62 @@ struct RsGlobal std::int32_t frameLimit; bool quit; void* ps; - std::uint8_t keyboard[12]; // RsInputDevice - std::uint8_t mouse[12]; // RsInputDevice - std::uint8_t pad[12]; // RsInputDevice + std::uint8_t keyboard[12]; // RsInputDevice + std::uint8_t mouse[12]; // RsInputDevice + std::uint8_t pad[12]; // RsInputDevice }; struct SComponentPlacement { // Original position & size - float x{0.0f}, y{0.0f}; // for getter function only + float x{0.0f}, y{0.0f}; // for getter function only float width{0.0f}, height{0.0f}; - float stringWidth{0.0f}, stringHeight{0.0f}; // for getter function only + float stringWidth{0.0f}, stringHeight{0.0f}; // for getter function only // Custom position & size float customX{0.0f}, customY{0.0f}; float customWidth{0.0f}, customHeight{0.0f}; - bool useCustomPosition{false}; - bool useCustomSize{false}; - bool setDefaultXY{false}; + bool useCustomPosition{false}; + bool useCustomSize{false}; + bool setDefaultXY{false}; }; struct SHudComponentData { SComponentPlacement placement{}; RwColor fillColor{}; - RwColor fillColorSecondary{0,0,0,255}; + RwColor fillColorSecondary{0, 0, 0, 255}; // Bar bool drawBlackBorder{true}; bool drawPercentage{false}; // Text - RwColor dropColor{0,0,0,255}; - eFontAlignment alignment{}; - eFontStyle style{}; - std::int16_t textOutline{0}; - std::int16_t textShadow{0}; - bool proportional{false}; - bool useCustomAlpha{false}; - - SHudComponentData( - RwColor fill = {}, - RwColor fillSecondary = {0, 0, 0, 255}, - bool blackBorder = true, - bool percentage = false, - RwColor drop = {}, - eFontAlignment align = eFontAlignment::ALIGN_LEFT, - eFontStyle fontStyle = eFontStyle::FONT_PRICEDOWN, - std::int16_t outline = 0, - std::int16_t shadow = 0, - bool prop = false, - bool useCustomAlpha = false) : fillColor(fill), - fillColorSecondary(fillSecondary), - drawBlackBorder(blackBorder), - drawPercentage(percentage), - dropColor(drop), - alignment(align), - style(fontStyle), - textOutline(outline), - textShadow(shadow), + RwColor dropColor{0, 0, 0, 255}; + eFontAlignment alignment{}; + eFontStyle style{}; + std::int16_t textOutline{0}; + std::int16_t textShadow{0}; + bool proportional{false}; + bool useCustomAlpha{false}; + + SHudComponentData(RwColor fill = {}, RwColor fillSecondary = {0, 0, 0, 255}, bool blackBorder = true, bool percentage = false, RwColor drop = {}, + eFontAlignment align = eFontAlignment::ALIGN_LEFT, eFontStyle fontStyle = eFontStyle::FONT_PRICEDOWN, std::int16_t outline = 0, + std::int16_t shadow = 0, bool prop = false, bool useCustomAlpha = false) + : fillColor(fill), + fillColorSecondary(fillSecondary), + drawBlackBorder(blackBorder), + drawPercentage(percentage), + dropColor(drop), + alignment(align), + style(fontStyle), + textOutline(outline), + textShadow(shadow), proportional(prop), - useCustomAlpha(useCustomAlpha) {} + useCustomAlpha(useCustomAlpha) + { + } }; struct ComponentProperties @@ -196,8 +190,14 @@ class CHudSA : public CHud void SetComponentPlacementPosition(SComponentPlacement& placement, const CVector2D& position) noexcept; void SetComponentPlacementSize(SComponentPlacement& placement, const CVector2D& size) noexcept; - void SetComponentPosition(const eHudComponent& component, const CVector2D& position) noexcept override { SetComponentPlacementPosition(GetHudComponentRef(component).placement, position); } - void SetComponentSize(const eHudComponent& component, const CVector2D& size) noexcept override { SetComponentPlacementSize(GetHudComponentRef(component).placement, size); } + void SetComponentPosition(const eHudComponent& component, const CVector2D& position) noexcept override + { + SetComponentPlacementPosition(GetHudComponentRef(component).placement, position); + } + void SetComponentSize(const eHudComponent& component, const CVector2D& size) noexcept override + { + SetComponentPlacementSize(GetHudComponentRef(component).placement, size); + } void ResetComponentPlacement(const eHudComponent& component, bool resetSize) noexcept override; @@ -209,19 +209,40 @@ class CHudSA : public CHud void SetHealthBarBlinkingValue(float minHealth) noexcept override { blinkingBarHPValue = minHealth; } void SetComponentFontDropColor(const eHudComponent& component, std::uint32_t color) noexcept override; - void SetComponentFontOutline(const eHudComponent& component, float outline) noexcept override { GetHudComponentRef(component).textOutline = static_cast(outline); } - void SetComponentFontShadow(const eHudComponent& component, float shadow) noexcept override { GetHudComponentRef(component).textShadow = static_cast(shadow); } + void SetComponentFontOutline(const eHudComponent& component, float outline) noexcept override + { + GetHudComponentRef(component).textOutline = static_cast(outline); + } + void SetComponentFontShadow(const eHudComponent& component, float shadow) noexcept override + { + GetHudComponentRef(component).textShadow = static_cast(shadow); + } void SetComponentFontStyle(const eHudComponent& component, const eFontStyle& style) noexcept override { GetHudComponentRef(component).style = style; } - void SetComponentFontAlignment(const eHudComponent& component, const eFontAlignment& alignment) noexcept override { GetHudComponentRef(component).alignment = alignment; } - void SetComponentFontProportional(const eHudComponent& component, bool proportional) noexcept override { GetHudComponentRef(component).proportional = proportional; } - - void SetComponentUseCustomAlpha(const eHudComponent& component, bool useCustomAlpha) noexcept override { GetHudComponentRef(component).useCustomAlpha = useCustomAlpha; } + void SetComponentFontAlignment(const eHudComponent& component, const eFontAlignment& alignment) noexcept override + { + GetHudComponentRef(component).alignment = alignment; + } + void SetComponentFontProportional(const eHudComponent& component, bool proportional) noexcept override + { + GetHudComponentRef(component).proportional = proportional; + } + + void SetComponentUseCustomAlpha(const eHudComponent& component, bool useCustomAlpha) noexcept override + { + GetHudComponentRef(component).useCustomAlpha = useCustomAlpha; + } void ResetComponentFontOutline(const eHudComponent& component) noexcept override { ResetComponentFontData(component, eHudComponentProperty::TEXT_OUTLINE); } void ResetComponentFontShadow(const eHudComponent& component) noexcept override { ResetComponentFontData(component, eHudComponentProperty::TEXT_SHADOW); } void ResetComponentFontStyle(const eHudComponent& component) noexcept override { ResetComponentFontData(component, eHudComponentProperty::TEXT_STYLE); } - void ResetComponentFontAlignment(const eHudComponent& component) noexcept override { ResetComponentFontData(component, eHudComponentProperty::TEXT_ALIGNMENT); } - void ResetComponentFontProportional(const eHudComponent& component) noexcept override { ResetComponentFontData(component, eHudComponentProperty::TEXT_PROPORTIONAL); } + void ResetComponentFontAlignment(const eHudComponent& component) noexcept override + { + ResetComponentFontData(component, eHudComponentProperty::TEXT_ALIGNMENT); + } + void ResetComponentFontProportional(const eHudComponent& component) noexcept override + { + ResetComponentFontData(component, eHudComponentProperty::TEXT_PROPORTIONAL); + } CVector2D GetComponentPosition(const eHudComponent& component) const noexcept override; CVector2D GetComponentSize(const eHudComponent& component) const noexcept override; @@ -258,10 +279,11 @@ class CHudSA : public CHud void UpdateStreetchCalculations(); void ResetComponent(SComponentPlacement& placement, bool resetSize) noexcept; void ResetComponentFontData(const eHudComponent& component, const eHudComponentProperty& property) noexcept; - + SHudComponentData& GetHudComponentRef(const eHudComponent& component) const noexcept; - static void RenderText(float x, float y, const char* text, SHudComponentData& properties, bool useSecondColor = false, bool drawFromBottom = false, bool scaleForLanguage = false); + static void RenderText(float x, float y, const char* text, SHudComponentData& properties, bool useSecondColor = false, bool drawFromBottom = false, + bool scaleForLanguage = false); static void RenderClock(float x, float y, const char* strTime); static void RenderMoney(float x, float y, const char* strMoney); static void RenderAmmo(float x, float y, const char* strAmmo); @@ -270,7 +292,8 @@ class CHudSA : public CHud static void RenderRadioName(float x, float y, const char* strRadio); static void __fastcall RenderWeaponIcon_Sprite(void* sprite, void*, CRect* rect, RwColor* color); - static void RenderWeaponIcon_XLU(CVector pos, CVector2D halfSize, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint16_t intensity, float rhw, std::uint8_t a, std::uint8_t uDir, std::uint8_t vDir); + static void RenderWeaponIcon_XLU(CVector pos, CVector2D halfSize, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint16_t intensity, float rhw, + std::uint8_t a, std::uint8_t uDir, std::uint8_t vDir); static void RenderWanted(bool empty, float x, float y, const char* strLevel); @@ -281,7 +304,7 @@ class CHudSA : public CHud float* m_pfCameraCrosshairScale; float m_fSniperCrosshairScale; - static RsGlobal* rsGlobal; + static RsGlobal* rsGlobal; static std::int16_t* itemToFlash; static float calcStreetchX; diff --git a/Client/game_sa/CIplSA.h b/Client/game_sa/CIplSA.h index e6ca52cfa31..fb734833801 100644 --- a/Client/game_sa/CIplSA.h +++ b/Client/game_sa/CIplSA.h @@ -17,8 +17,8 @@ class CIplSAInterface { public: - CRect rect; - char name[16]; + CRect rect; + char name[16]; uint16_t unk; uint16_t minBuildId; uint16_t maxBuildId; diff --git a/Client/game_sa/CIplStoreSA.h b/Client/game_sa/CIplStoreSA.h index ec0a2693290..699bce1fcdd 100644 --- a/Client/game_sa/CIplStoreSA.h +++ b/Client/game_sa/CIplStoreSA.h @@ -23,7 +23,7 @@ class CIplStoreSA : public CIplStore ~CIplStoreSA() = default; void SetDynamicIplStreamingEnabled(bool state); - void SetDynamicIplStreamingEnabled(bool state, std::function filter); + void SetDynamicIplStreamingEnabled(bool state, std::function filter); private: void UnloadAndDisableStreaming(int iplId); diff --git a/Client/game_sa/CKeyGenSA.h b/Client/game_sa/CKeyGenSA.h index c402e5c34f4..2838346063b 100644 --- a/Client/game_sa/CKeyGenSA.h +++ b/Client/game_sa/CKeyGenSA.h @@ -13,10 +13,10 @@ #include -#define FUNC_CKeyGen_GetKey_len 0x53ced0 -#define FUNC_CKeyGen_GetKey 0x53cf00 -#define FUNC_CKeyGen_GetUppercaseKey 0x53cf30 -#define FUNC_CKeyGen_AppendStringToKey 0x53cf70 +#define FUNC_CKeyGen_GetKey_len 0x53ced0 +#define FUNC_CKeyGen_GetKey 0x53cf00 +#define FUNC_CKeyGen_GetUppercaseKey 0x53cf30 +#define FUNC_CKeyGen_AppendStringToKey 0x53cf70 class CKeyGenSA : public CKeyGen { diff --git a/Client/game_sa/CMarkerSA.cpp b/Client/game_sa/CMarkerSA.cpp index f8e45d12910..6c504532323 100644 --- a/Client/game_sa/CMarkerSA.cpp +++ b/Client/game_sa/CMarkerSA.cpp @@ -30,7 +30,7 @@ void CMarkerSA::Init() internalInterface->bBlipFade = false; internalInterface->nBlipDisplayFlag = (BYTE)MarkerDisplay::MARKER_DISPLAY_BLIPONLY; internalInterface->nBlipSprite = (BYTE)RadarSprite::RADAR_SPRITE_NONE; - #define COORD_BLIP_APPEARANCE_NORMAL 0 +#define COORD_BLIP_APPEARANCE_NORMAL 0 internalInterface->nCoordBlipAppearance = COORD_BLIP_APPEARANCE_NORMAL; internalInterface->pEntryExit = nullptr; } diff --git a/Client/game_sa/CMarkerSA.h b/Client/game_sa/CMarkerSA.h index 75e26637520..18d4c0e0d17 100644 --- a/Client/game_sa/CMarkerSA.h +++ b/Client/game_sa/CMarkerSA.h @@ -23,7 +23,7 @@ class CMarkerSAInterface // The following parameter is used when Blip Type is CAR, CHAR or OBJECT long PoolIndex; // The following parameter is used when Blip Type is COORDS - CVector position; // vec2DBlip; + CVector position; // vec2DBlip; WORD ReferenceIndex; diff --git a/Client/game_sa/CMatrixSA.h b/Client/game_sa/CMatrixSA.h index 7b41c3ea754..349615493d8 100644 --- a/Client/game_sa/CMatrixSA.h +++ b/Client/game_sa/CMatrixSA.h @@ -27,12 +27,12 @@ class CMatrixSAInterface public: RwMatrix* m_pAttachMatrix = nullptr; - bool m_bOwnsAttachedMatrix = false; // do we need to delete attaching matrix at detaching + bool m_bOwnsAttachedMatrix = false; // do we need to delete attaching matrix at detaching CMatrixSAInterface() : m_right{}, flags{}, m_forward{}, pad1{}, m_up{}, pad2{}, m_pos{}, pad3{} {}; CMatrixSAInterface(CMatrixSAInterface const& matrix); - CMatrixSAInterface(RwMatrix* matrix, bool temporary); // like previous + attach - ~CMatrixSAInterface(); // destructor detaches matrix if attached + CMatrixSAInterface(RwMatrix* matrix, bool temporary); // like previous + attach + ~CMatrixSAInterface(); // destructor detaches matrix if attached void ConvertToEulerAngles(float& x, float& y, float& z, std::int32_t flags); void ConvertFromEulerAngles(float x, float y, float z, std::int32_t flags); diff --git a/Client/game_sa/CModelInfoSA.cpp b/Client/game_sa/CModelInfoSA.cpp index b90e46c5b23..2f54d12e86c 100644 --- a/Client/game_sa/CModelInfoSA.cpp +++ b/Client/game_sa/CModelInfoSA.cpp @@ -28,15 +28,15 @@ extern CGameSA* pGame; CBaseModelInfoSAInterface** CModelInfoSAInterface::ms_modelInfoPtrs = (CBaseModelInfoSAInterface**)ARRAY_ModelInfo; CBaseModelInfoSAInterface** ppModelInfo = (CBaseModelInfoSAInterface**)ARRAY_ModelInfo; -std::map CModelInfoSA::ms_RestreamTxdIDMap; -std::map CModelInfoSA::ms_ModelDefaultLodDistanceMap; -std::map CModelInfoSA::ms_ModelDefaultFlagsMap; -std::map CModelInfoSA::ms_ModelDefaultAlphaTransparencyMap; +std::map CModelInfoSA::ms_RestreamTxdIDMap; +std::map CModelInfoSA::ms_ModelDefaultLodDistanceMap; +std::map CModelInfoSA::ms_ModelDefaultFlagsMap; +std::map CModelInfoSA::ms_ModelDefaultAlphaTransparencyMap; std::unordered_map> CModelInfoSA::ms_ModelDefaultDummiesPosition; -std::map CModelInfoSA::ms_ModelDefaultModelTimeInfo; -std::unordered_map CModelInfoSA::ms_OriginalObjectPropertiesGroups; -std::unordered_map> CModelInfoSA::ms_VehicleModelDefaultWheelSizes; -std::map CModelInfoSA::ms_DefaultTxdIDMap; +std::map CModelInfoSA::ms_ModelDefaultModelTimeInfo; +std::unordered_map CModelInfoSA::ms_OriginalObjectPropertiesGroups; +std::unordered_map> CModelInfoSA::ms_VehicleModelDefaultWheelSizes; +std::map CModelInfoSA::ms_DefaultTxdIDMap; void CModelInfoSA::ClearModelDefaults(DWORD modelId) { @@ -459,7 +459,7 @@ char* CModelInfoSA::GetNameIfVehicle() DWORD ModelID = m_dwModelID; DWORD dwReturn = 0; - // clang-format off + // clang-format off __asm { push eax @@ -482,7 +482,7 @@ char* CModelInfoSA::GetNameIfVehicle() pop ebx pop eax } - // clang-format on + // clang-format on return (char*)dwReturn; } @@ -694,8 +694,8 @@ void CModelInfoSA::SetFlags(unsigned short usFlags) MapSet(ms_ModelDefaultFlagsMap, m_dwModelID, m_pInterface->usFlags); // Don't change bIsColLoaded flag - usFlags &= 0xFF7F; // Disable flag in input - usFlags |= m_pInterface->usFlags & 0x80; // Apply current bIsColLoaded flag + usFlags &= 0xFF7F; // Disable flag in input + usFlags |= m_pInterface->usFlags & 0x80; // Apply current bIsColLoaded flag m_pInterface->usFlags = usFlags; } @@ -715,7 +715,7 @@ void CModelInfoSA::SetIdeFlags(unsigned int uiFlags) // Default value is 0xC0 (bIsColLoaded + bIsBackfaceCulled) // But bIsColLoaded should not be changed - m_pInterface->usFlags &= 0x80; // Reset all flags except bIsColLoaded + m_pInterface->usFlags &= 0x80; // Reset all flags except bIsColLoaded m_pInterface->bIsBackfaceCulled = true; // setBaseModelInfoFlags @@ -1185,7 +1185,7 @@ void CModelInfoSA::StaticResetModelTimes() { for (auto it = ms_ModelDefaultModelTimeInfo.begin(); it != ms_ModelDefaultModelTimeInfo.end();) { - const DWORD modelId = it->first; + const DWORD modelId = it->first; CBaseModelInfoSAInterface* pInterface = ppModelInfo[modelId]; if (!IsValidModelInfoPtr(pInterface)) { @@ -1199,7 +1199,7 @@ void CModelInfoSA::StaticResetModelTimes() it = ms_ModelDefaultModelTimeInfo.erase(it); continue; } - const eModelInfoType modelType = ((eModelInfoType(*)())funcAddr)(); + const eModelInfoType modelType = ((eModelInfoType (*)())funcAddr)(); if (modelType != eModelInfoType::TIME) { it = ms_ModelDefaultModelTimeInfo.erase(it); @@ -1325,7 +1325,7 @@ void CModelInfoSA::StaticFlushPendingRestreamIPL() // In other words, it does not affect elements created by MTA. // It's mostly a reimplementation of SA's DeleteAllRwObjects, except that it filters by model ID. - reinterpret_cast(FUNC_FlushRequestList)(); + reinterpret_cast(FUNC_FlushRequestList)(); std::unordered_set processedTxdIDs; std::unordered_set pendingTxdIDs; @@ -1339,16 +1339,18 @@ void CModelInfoSA::StaticFlushPendingRestreamIPL() constexpr int kRepeatSectorStride = 3; // StreamRepeatSectors uses stride of 3, we access element [2] // Helper to validate entity vtable - checks if DeleteRwObject points to expected address - auto isValidEntity = [](CEntitySAInterface* pEntity) -> bool { + auto isValidEntity = [](CEntitySAInterface* pEntity) -> bool + { constexpr std::size_t kDeleteRwObjectVtblOffset = 8; constexpr std::size_t kExpectedDeleteRwObject = 0x00534030; - auto* vtbl = static_cast(pEntity->GetVTBL()); + auto* vtbl = static_cast(pEntity->GetVTBL()); return vtbl[kDeleteRwObjectVtblOffset] == kExpectedDeleteRwObject; }; // Process entities from a sector list // Note: validateVtable should be true for StreamSectors but false for StreamRepeatSectors - auto processSectorList = [&](DWORD* pSectorEntry, bool validateVtable, int sectorIndex) { + auto processSectorList = [&](DWORD* pSectorEntry, bool validateVtable, int sectorIndex) + { while (pSectorEntry) { auto* pEntity = reinterpret_cast(pSectorEntry[0]); @@ -1361,10 +1363,9 @@ void CModelInfoSA::StaticFlushPendingRestreamIPL() // Vtable validation for StreamSectors if (validateVtable && !isValidEntity(pEntity)) { - OutputDebugString(SString("Entity 0x%08x (with model %d) at ARRAY_StreamSectors[%d,%d] is invalid\n", - pEntity, pEntity->m_nModelIndex, - sectorIndex / 2 % NUM_StreamSectorRows, sectorIndex / 2 / NUM_StreamSectorCols)); - pSectorEntry = reinterpret_cast(pSectorEntry[1]); + OutputDebugString(SString("Entity 0x%08x (with model %d) at ARRAY_StreamSectors[%d,%d] is invalid\n", pEntity, pEntity->m_nModelIndex, + sectorIndex / 2 % NUM_StreamSectorRows, sectorIndex / 2 / NUM_StreamSectorCols)); + pSectorEntry = reinterpret_cast(pSectorEntry[1]); continue; } @@ -1429,9 +1430,9 @@ void CModelInfoSA::StaticFlushPendingRestreamIPL() // Increment retry counter ONLY for pending TXD IDs (entities being rendered) // Don't increment for: unprocessed (will be erased below) // Note: processedTxdIDs that are also in pendingTxdIDs stay in map and need counter incremented - constexpr int kMaxRetryFrames = 300; // ~5 seconds at 60fps + constexpr int kMaxRetryFrames = 300; // ~5 seconds at 60fps std::unordered_set timedOutTxdIDs; - for (auto it = ms_RestreamTxdIDMap.begin(); it != ms_RestreamTxdIDMap.end(); ) + for (auto it = ms_RestreamTxdIDMap.begin(); it != ms_RestreamTxdIDMap.end();) { // Skip if unprocessed - those will be erased below after model unload attempt if (unprocessedTxdIDs.count(it->first)) @@ -1485,7 +1486,8 @@ void CModelInfoSA::StaticFlushPendingRestreamIPL() { const auto maxModelId = static_cast(pGame->GetBaseIDforTXD()); - auto tryQueueModelUnload = [&](DWORD modelId) { + auto tryQueueModelUnload = [&](DWORD modelId) + { auto* pStreamingInfo = pGame->GetStreaming()->GetStreamingInfo(modelId); if (!pStreamingInfo || pStreamingInfo->loadState == eModelLoadState::LOADSTATE_NOT_LOADED) return; @@ -1580,7 +1582,7 @@ void CModelInfoSA::RemoveRef(bool bRemoveExtraGTARef) CBaseModelInfoSAInterface* pInterface = GetInterface(); if (pInterface && pInterface->usNumberOfRefs > 1) { - DWORD dwFunction = FUNC_RemoveRef; + DWORD dwFunction = FUNC_RemoveRef; _asm { mov ecx, pInterface @@ -1721,10 +1723,8 @@ void CModelInfoSA::SetCustomCarPlateText(const char* szText) } // clang-format on - if (szText) - strncpy(szStoredText, szText, 8); - else - szStoredText[0] = '\0'; + if (szText) strncpy(szStoredText, szText, 8); + else szStoredText[0] = '\0'; } unsigned int CModelInfoSA::GetNumRemaps() @@ -1963,7 +1963,7 @@ void CModelInfoSA::ResetVehicleDummies(bool bRemoveFromDummiesMap) auto iter = ms_ModelDefaultDummiesPosition.find(m_dwModelID); if (iter == ms_ModelDefaultDummiesPosition.end()) - return; // Early out in case the model doesn't have any dummies modified + return; // Early out in case the model doesn't have any dummies modified auto* pVehicleModel = static_cast(GetInterface()); if (!pVehicleModel || !pVehicleModel->pVisualInfo) @@ -2724,8 +2724,8 @@ void CModelInfoSA::DeallocateModel() // Block deletion while refs > 0 to avoid null pointer crash. if (pInterfaceToDelete->usNumberOfRefs > 0) { - AddReportLog(5550, SString("Blocked DeallocateModel for model %u with %u active refs to prevent crash at 0x4C4BB0", - m_dwModelID, static_cast(pInterfaceToDelete->usNumberOfRefs))); + AddReportLog(5550, SString("Blocked DeallocateModel for model %u with %u active refs to prevent crash at 0x4C4BB0", m_dwModelID, + static_cast(pInterfaceToDelete->usNumberOfRefs))); m_pInterface = pInterfaceToDelete; @@ -2753,12 +2753,12 @@ void CModelInfoSA::DeallocateModel() // Capture model type and damageability BEFORE nulling the array entry. eModelInfoType modelType = eModelInfoType::UNKNOWN; - bool isDamageableAtomic = false; + bool isDamageableAtomic = false; if (pInterfaceToDelete->VFTBL) { DWORD typeFunc = pInterfaceToDelete->VFTBL->GetModelType; if (IsValidGtaSaCodePtr(typeFunc)) - modelType = ((eModelInfoType(*)())typeFunc)(); + modelType = ((eModelInfoType (*)())typeFunc)(); if (modelType == eModelInfoType::ATOMIC || modelType == eModelInfoType::LOD_ATOMIC) { @@ -2825,8 +2825,7 @@ void CModelInfoSA::DeallocateModel() delete reinterpret_cast(pInterfaceToDelete); break; default: - AddReportLog(5551, SString("Unknown model type %d for model %u - memory leaked to prevent corruption", - static_cast(modelType), m_dwModelID)); + AddReportLog(5551, SString("Unknown model type %d for model %u - memory leaked to prevent corruption", static_cast(modelType), m_dwModelID)); return; } @@ -2858,9 +2857,9 @@ __declspec(noinline) void OnMY_NodeNameStreamRead(RwStream* stream, char* pDest, } // Hook info -#define HOOKPOS_NodeNameStreamRead 0x072FA68 -#define HOOKSIZE_NodeNameStreamRead 15 -DWORD RETURN_NodeNameStreamRead = 0x072FA77; +#define HOOKPOS_NodeNameStreamRead 0x072FA68 +#define HOOKSIZE_NodeNameStreamRead 15 +DWORD RETURN_NodeNameStreamRead = 0x072FA77; static void __declspec(naked) HOOK_NodeNameStreamRead() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -3076,7 +3075,7 @@ eModelInfoType CModelInfoSA::GetModelType() if (!IsValidGtaSaCodePtr(funcAddr)) return eModelInfoType::UNKNOWN; - return ((eModelInfoType(*)())funcAddr)(); + return ((eModelInfoType (*)())funcAddr)(); } bool CModelInfoSA::IsTowableBy(CModelInfo* towingModel) diff --git a/Client/game_sa/CModelInfoSA.h b/Client/game_sa/CModelInfoSA.h index 063bbb802da..cb9c3163c13 100644 --- a/Client/game_sa/CModelInfoSA.h +++ b/Client/game_sa/CModelInfoSA.h @@ -21,50 +21,50 @@ class CPedModelInfoSAInterface; struct CColModelSAInterface; struct RpMaterial; -#define RpGetFrame(__c) ((RwFrame*)(((RwObject *)(__c))->parent)) +#define RpGetFrame(__c) ((RwFrame*)(((RwObject*)(__c))->parent)) // #define ARRAY_ModelLoaded 0x8E4CD0 // ##SA## static void* CStreaming__ms_aInfoForModel = *(void**)(0x5B8B08 + 6); static void* ARRAY_ModelLoaded = (char*)CStreaming__ms_aInfoForModel + 0x10; -#define FUNC_CStreaming__HasModelLoaded 0x4044C0 +#define FUNC_CStreaming__HasModelLoaded 0x4044C0 -#define NUM_INVALID_PTR_THRESHOLD 0x10000 +#define NUM_INVALID_PTR_THRESHOLD 0x10000 // CModelInfo/ARRAY_ModelInfo __thiscall to load/replace vehicle models -#define FUNC_LoadVehicleModel 0x4C95C0 -#define FUNC_LoadWeaponModel 0x4C9910 -#define FUNC_LoadPedModel 0x4C7340 +#define FUNC_LoadVehicleModel 0x4C95C0 +#define FUNC_LoadWeaponModel 0x4C9910 +#define FUNC_LoadPedModel 0x4C7340 -#define DWORD_AtomicsReplacerModelID 0xB71840 -#define FUNC_AtomicsReplacer 0x537150 +#define DWORD_AtomicsReplacerModelID 0xB71840 +#define FUNC_AtomicsReplacer 0x537150 // #define ARRAY_ModelInfo 0xA9B0C8 static void* ARRAY_ModelInfo = *(void**)(0x403DA4 + 3); -#define CLASS_CText 0xC1B340 -#define FUNC_CText_Get 0x6A0050 -#define FUNC_GetBoundingBox 0x4082F0 - -#define FUNC_RemoveRef 0x4C4BB0 -#define FUNC_IsBoatModel 0x4c5a70 -#define FUNC_IsCarModel 0x4c5aa0 -#define FUNC_IsTrainModel 0x4c5ad0 -#define FUNC_IsHeliModel 0x4c5b00 -#define FUNC_IsPlaneModel 0x4c5b30 -#define FUNC_IsBikeModel 0x4c5b60 -#define FUNC_IsFakePlaneModel 0x4c5b90 -#define FUNC_IsMonsterTruckModel 0x4c5bc0 -#define FUNC_IsQuadBikeModel 0x4c5bf0 -#define FUNC_IsBmxModel 0x4c5c20 -#define FUNC_IsTrailerModel 0x4c5c50 -#define FUNC_IsVehicleModelType 0x4c5c80 -#define FUNC_RemoveModel 0x4089a0 -#define FUNC_FlushRequestList 0x40E4E0 -#define FUNC_RequestVehicleUpgrade 0x408C70 - -#define FUNC_CVehicleModelInfo__GetNumRemaps 0x4C86B0 - -#define VAR_CTempColModels_ModelPed1 0x968DF0 +#define CLASS_CText 0xC1B340 +#define FUNC_CText_Get 0x6A0050 +#define FUNC_GetBoundingBox 0x4082F0 + +#define FUNC_RemoveRef 0x4C4BB0 +#define FUNC_IsBoatModel 0x4c5a70 +#define FUNC_IsCarModel 0x4c5aa0 +#define FUNC_IsTrainModel 0x4c5ad0 +#define FUNC_IsHeliModel 0x4c5b00 +#define FUNC_IsPlaneModel 0x4c5b30 +#define FUNC_IsBikeModel 0x4c5b60 +#define FUNC_IsFakePlaneModel 0x4c5b90 +#define FUNC_IsMonsterTruckModel 0x4c5bc0 +#define FUNC_IsQuadBikeModel 0x4c5bf0 +#define FUNC_IsBmxModel 0x4c5c20 +#define FUNC_IsTrailerModel 0x4c5c50 +#define FUNC_IsVehicleModelType 0x4c5c80 +#define FUNC_RemoveModel 0x4089a0 +#define FUNC_FlushRequestList 0x40E4E0 +#define FUNC_RequestVehicleUpgrade 0x408C70 + +#define FUNC_CVehicleModelInfo__GetNumRemaps 0x4C86B0 + +#define VAR_CTempColModels_ModelPed1 0x968DF0 class CBaseModelInfoSAInterface; class CModelInfoSAInterface @@ -82,25 +82,25 @@ class CBaseModelInfo_SA_VTBL { public: DWORD Destructor; - DWORD AsAtomicModelInfoPtr; // () - DWORD AsDamageAtomicModelInfoPtr; // () - DWORD AsLodAtomicModelInfoPtr; // () - DWORD GetModelType; // () - Not defined in the base - DWORD GetTimeInfo; // () - DWORD Init; // () - DWORD Shutdown; // () - DWORD DeleteRwObject; // () - Not defined in the base - DWORD GetRwModelType; // () - Not defined in the base - DWORD CreateInstance_; // (RwMatrix*) - Not defined in the base - DWORD CreateInstance; // () - Not defined in the base - DWORD SetAnimFile; // (char const*) - DWORD ConvertAnimFileIndex; // () - DWORD GetAnimFileIndex; // () + DWORD AsAtomicModelInfoPtr; // () + DWORD AsDamageAtomicModelInfoPtr; // () + DWORD AsLodAtomicModelInfoPtr; // () + DWORD GetModelType; // () - Not defined in the base + DWORD GetTimeInfo; // () + DWORD Init; // () + DWORD Shutdown; // () + DWORD DeleteRwObject; // () - Not defined in the base + DWORD GetRwModelType; // () - Not defined in the base + DWORD CreateInstance_; // (RwMatrix*) - Not defined in the base + DWORD CreateInstance; // () - Not defined in the base + DWORD SetAnimFile; // (char const*) + DWORD ConvertAnimFileIndex; // () + DWORD GetAnimFileIndex; // () }; class CAtomicModelInfo_SA_VTBL : public CBaseModelInfo_SA_VTBL { - DWORD SetAtomic; // (RpAtomic*) + DWORD SetAtomic; // (RpAtomic*) }; class CDamageAtomicModelInfo_SA_VTBL : public CAtomicModelInfo_SA_VTBL @@ -121,7 +121,7 @@ class CLodTimeModelInfo_SA_VTBL : public CLodAtomicModelInfo_SA_VTBL class CClumpModelInfo_SA_VTBL : public CBaseModelInfo_SA_VTBL { - DWORD SetClump; // (RpClump*) + DWORD SetClump; // (RpClump*) }; class CWeaponModelInfo_SA_VTBL : public CClumpModelInfo_SA_VTBL @@ -145,33 +145,33 @@ enum class eModelSpecialType : unsigned char GLASS_2 = 5, TAG = 6, GARAGE_DOOR = 7, - CRANE = 9, // Not present in IDE but used in gta - UNKNOW_1 = 10, // Read only + CRANE = 9, // Not present in IDE but used in gta + UNKNOW_1 = 10, // Read only BREAKABLE_STATUE = 11, }; class CBaseModelInfoSAInterface { public: - CBaseModelInfo_SA_VTBL* VFTBL; // +0 + CBaseModelInfo_SA_VTBL* VFTBL; // +0 - unsigned long ulHashKey; // +4 Generated by CKeyGen::GetUppercaseKey(char const *) called by CBaseModelInfo::SetModelName(char const *) - unsigned short usNumberOfRefs : 16; // +8 - unsigned short usTextureDictionary : 16; // +10 - unsigned char ucAlpha : 8; // +12 + unsigned long ulHashKey; // +4 Generated by CKeyGen::GetUppercaseKey(char const *) called by CBaseModelInfo::SetModelName(char const *) + unsigned short usNumberOfRefs : 16; // +8 + unsigned short usTextureDictionary : 16; // +10 + unsigned char ucAlpha : 8; // +12 - unsigned char ucNumOf2DEffects : 8; // +13 - unsigned short usUnknown : 16; // +14 Something with 2d effects + unsigned char ucNumOf2DEffects : 8; // +13 + unsigned short usUnknown : 16; // +14 Something with 2d effects - unsigned short usDynamicIndex : 16; // +16 + unsigned short usDynamicIndex : 16; // +16 // Flags used by CBaseModelInfo union { struct { - unsigned char bHasBeenPreRendered : 1; // we use this because we need to apply changes only once - unsigned char bAlphaTransparency : 1; // bDrawLast + unsigned char bHasBeenPreRendered : 1; // we use this because we need to apply changes only once + unsigned char bAlphaTransparency : 1; // bDrawLast unsigned char bAdditiveRender : 1; unsigned char bDontWriteZBuffer : 1; unsigned char bDontCastShadowsOn : 1; @@ -182,16 +182,16 @@ class CBaseModelInfoSAInterface unsigned char bHasComplexHierarchy : 1; unsigned char bDontCollideWithFlyer : 1; eModelSpecialType eSpecialModelType : 4; - unsigned char bWetRoadReflection : 1; // Used for tags + unsigned char bWetRoadReflection : 1; // Used for tags }; unsigned short usFlags; }; - CColModelSAInterface* pColModel; // +20 CColModel: public CBoundingBox + CColModelSAInterface* pColModel; // +20 CColModel: public CBoundingBox - float fLodDistanceUnscaled; // +24 Scaled is this value multiplied with flt_B6F118 - RwObject* pRwObject; // +28 + float fLodDistanceUnscaled; // +24 Scaled is this value multiplied with flt_B6F118 + RwObject* pRwObject; // +28 // CWeaponModelInfo: // +36 = Weapon info as int @@ -239,8 +239,8 @@ static_assert(sizeof(CBaseModelInfoSAInterface) == 0x20, "Invalid size for CBase struct CTimeInfoSAInterface { - CTimeInfoSAInterface() : m_nTimeOn(20), m_nTimeOff(6), m_wOtherTimeModel(0){}; - CTimeInfoSAInterface(char timeOn, char timeOff, short OtherTimeModel) : m_nTimeOn(timeOn), m_nTimeOff(timeOff), m_wOtherTimeModel(OtherTimeModel){}; + CTimeInfoSAInterface() : m_nTimeOn(20), m_nTimeOff(6), m_wOtherTimeModel(0) {}; + CTimeInfoSAInterface(char timeOn, char timeOff, short OtherTimeModel) : m_nTimeOn(timeOn), m_nTimeOff(timeOff), m_wOtherTimeModel(OtherTimeModel) {}; char m_nTimeOn; char m_nTimeOff; short m_wOtherTimeModel; @@ -276,7 +276,7 @@ class CDamageableModelInfoSAInterface : public CBaseModelInfoSAInterface void* m_damagedAtomic; }; -class CVehicleModelVisualInfoSAInterface // Not sure about this name. If somebody knows more, please change +class CVehicleModelVisualInfoSAInterface // Not sure about this name. If somebody knows more, please change { public: CVector vecDummies[15]; @@ -313,7 +313,7 @@ class CVehicleModelInfoSAInterface : public CClumpModelInfoSAInterface std::int16_t vehFrequency; std::uint32_t componentRules; float bikeSteeringAngle; - CVehicleModelVisualInfoSAInterface* pVisualInfo; // vehicleStruct + CVehicleModelVisualInfoSAInterface* pVisualInfo; // vehicleStruct std::uint8_t field_60[464]; RpMaterial** m_dirtMaterials; std::size_t m_numDirtMaterials; @@ -331,35 +331,35 @@ class CVehicleModelInfoSAInterface : public CClumpModelInfoSAInterface std::uint8_t upgrades[36]; std::uint8_t anRemapTXDs[8]; std::uint8_t field_302[2]; - void* pAnimBlock; // CAnimBlock* + void* pAnimBlock; // CAnimBlock* }; static_assert(sizeof(CVehicleModelInfoSAInterface) == 0x308, "Invalid size of CVehicleModelInfoSAInterface class"); class CModelInfoSA : public CModelInfo { protected: - CBaseModelInfoSAInterface* m_pInterface; - DWORD m_dwModelID; - DWORD m_dwParentID; - DWORD m_dwReferences; - DWORD m_dwPendingInterfaceRef; - CColModel* m_pCustomColModel; - CColModelSAInterface* m_pOriginalColModelInterface; - std::uint32_t m_colRefCount = 0; - unsigned short m_usColSlot = 0xFFFF; - std::uint16_t m_originalFlags = 0; - RpClump* m_pCustomClump; - static std::map ms_RestreamTxdIDMap; - static std::map ms_ModelDefaultLodDistanceMap; - static std::map ms_ModelDefaultFlagsMap; - static std::map ms_ModelDefaultAlphaTransparencyMap; + CBaseModelInfoSAInterface* m_pInterface; + DWORD m_dwModelID; + DWORD m_dwParentID; + DWORD m_dwReferences; + DWORD m_dwPendingInterfaceRef; + CColModel* m_pCustomColModel; + CColModelSAInterface* m_pOriginalColModelInterface; + std::uint32_t m_colRefCount = 0; + unsigned short m_usColSlot = 0xFFFF; + std::uint16_t m_originalFlags = 0; + RpClump* m_pCustomClump; + static std::map ms_RestreamTxdIDMap; + static std::map ms_ModelDefaultLodDistanceMap; + static std::map ms_ModelDefaultFlagsMap; + static std::map ms_ModelDefaultAlphaTransparencyMap; static std::unordered_map> ms_ModelDefaultDummiesPosition; static std::map ms_ModelDefaultModelTimeInfo; - static std::unordered_map ms_OriginalObjectPropertiesGroups; - static std::unordered_map> ms_VehicleModelDefaultWheelSizes; - static std::map ms_DefaultTxdIDMap; - SVehicleSupportedUpgrades m_ModelSupportedUpgrades; - static void ClearModelDefaults(DWORD modelId); + static std::unordered_map ms_OriginalObjectPropertiesGroups; + static std::unordered_map> ms_VehicleModelDefaultWheelSizes; + static std::map ms_DefaultTxdIDMap; + SVehicleSupportedUpgrades m_ModelSupportedUpgrades; + static void ClearModelDefaults(DWORD modelId); public: CModelInfoSA(); @@ -389,41 +389,41 @@ class CModelInfoSA : public CModelInfo char* GetNameIfVehicle(); - BYTE GetVehicleType() const noexcept; - void Request(EModelRequestType requestType, const char* szTag); - void Remove(); - bool UnloadUnused(); - bool IsLoaded(); - bool DoIsLoaded(); - unsigned short GetFlags(); - unsigned short GetOriginalFlags(); - void SetIdeFlags(unsigned int uiFlags); - void SetIdeFlag(eModelIdeFlag eIdeFlag, bool bState); - bool GetIdeFlag(eModelIdeFlag eIdeFlag); - void SetFlags(unsigned short usFlags); - static void StaticResetFlags(); - CBoundingBox* GetBoundingBox(); + BYTE GetVehicleType() const noexcept; + void Request(EModelRequestType requestType, const char* szTag); + void Remove(); + bool UnloadUnused(); + bool IsLoaded(); + bool DoIsLoaded(); + unsigned short GetFlags(); + unsigned short GetOriginalFlags(); + void SetIdeFlags(unsigned int uiFlags); + void SetIdeFlag(eModelIdeFlag eIdeFlag, bool bState); + bool GetIdeFlag(eModelIdeFlag eIdeFlag); + void SetFlags(unsigned short usFlags); + static void StaticResetFlags(); + CBoundingBox* GetBoundingBox(); [[nodiscard]] bool IsCollisionLoaded() const noexcept; [[nodiscard]] bool IsRwObjectLoaded() const noexcept; - void WaitForModelFullyLoaded(std::chrono::milliseconds timeout); - bool IsValid(); - bool IsAllocatedInArchive() const noexcept; - float GetDistanceFromCentreOfMassToBaseOfModel(); - unsigned short GetTextureDictionaryID(); - void SetTextureDictionaryID(unsigned short usID); - void ResetTextureDictionaryID(); - static void StaticResetTextureDictionaries(); - float GetLODDistance(); - float GetOriginalLODDistance(); - void SetLODDistance(float fDistance, bool bOverrideMaxDistance = false); - static void StaticResetLodDistances(); - void RestreamIPL(); - static void StaticFlushPendingRestreamIPL(); - static void StaticSetHooks(); - bool GetTime(char& cHourOn, char& cHourOff); - bool SetTime(char cHourOn, char cHourOff); - static void StaticResetModelTimes(); - static void ClearModelDefaults(); + void WaitForModelFullyLoaded(std::chrono::milliseconds timeout); + bool IsValid(); + bool IsAllocatedInArchive() const noexcept; + float GetDistanceFromCentreOfMassToBaseOfModel(); + unsigned short GetTextureDictionaryID(); + void SetTextureDictionaryID(unsigned short usID); + void ResetTextureDictionaryID(); + static void StaticResetTextureDictionaries(); + float GetLODDistance(); + float GetOriginalLODDistance(); + void SetLODDistance(float fDistance, bool bOverrideMaxDistance = false); + static void StaticResetLodDistances(); + void RestreamIPL(); + static void StaticFlushPendingRestreamIPL(); + static void StaticSetHooks(); + bool GetTime(char& cHourOn, char& cHourOff); + bool SetTime(char cHourOn, char cHourOff); + static void StaticResetModelTimes(); + static void ClearModelDefaults(); void SetAlphaTransparencyEnabled(bool bEnabled); bool IsAlphaTransparencyEnabled(); diff --git a/Client/game_sa/CObjectGroupPhysicalPropertiesSA.h b/Client/game_sa/CObjectGroupPhysicalPropertiesSA.h index 1ff405b9e74..d5d8c9c9806 100644 --- a/Client/game_sa/CObjectGroupPhysicalPropertiesSA.h +++ b/Client/game_sa/CObjectGroupPhysicalPropertiesSA.h @@ -61,42 +61,42 @@ class CObjectGroupPhysicalPropertiesSA : public CObjectGroupPhysicalProperties void RestoreDefault(); static void RestoreDefaultValues(); - void SetMass(float fMass); - float GetMass() const; - void SetTurnMass(float fTurnMass); - float GetTurnMass() const; - void SetAirResistance(float fAirResistance); - float GetAirResistance() const; - void SetElasticity(float fElasticity); - float GetElasticity() const; - void SetBuoyancy(float fBuoyancy); - float GetBuoyancy() const; - void SetUprootLimit(float fUprootLimit); - float GetUprootLimit() const; - void SetCollisionDamageMultiplier(float fColMult); - float GetCollisionDamageMultiplier() const; - void SetCollisionDamageEffect(ObjectGroupPhysicalProperties::DamageEffect ucDamageEffect); + void SetMass(float fMass); + float GetMass() const; + void SetTurnMass(float fTurnMass); + float GetTurnMass() const; + void SetAirResistance(float fAirResistance); + float GetAirResistance() const; + void SetElasticity(float fElasticity); + float GetElasticity() const; + void SetBuoyancy(float fBuoyancy); + float GetBuoyancy() const; + void SetUprootLimit(float fUprootLimit); + float GetUprootLimit() const; + void SetCollisionDamageMultiplier(float fColMult); + float GetCollisionDamageMultiplier() const; + void SetCollisionDamageEffect(ObjectGroupPhysicalProperties::DamageEffect ucDamageEffect); ObjectGroupPhysicalProperties::DamageEffect GetCollisionDamageEffect() const; - void SetCollisionSpecialResponseCase(ObjectGroupPhysicalProperties::CollisionResponse ucResponseCase); + void SetCollisionSpecialResponseCase(ObjectGroupPhysicalProperties::CollisionResponse ucResponseCase); ObjectGroupPhysicalProperties::CollisionResponse GetCollisionSpecialResponseCase() const; - void SetCameraAvoidObject(bool bAvoid); - bool GetCameraAvoidObject() const; - void SetCausesExplosion(bool bExplodes); - bool GetCausesExplosion() const; - void SetFxType(ObjectGroupPhysicalProperties::FxType eFxType); + void SetCameraAvoidObject(bool bAvoid); + bool GetCameraAvoidObject() const; + void SetCausesExplosion(bool bExplodes); + bool GetCausesExplosion() const; + void SetFxType(ObjectGroupPhysicalProperties::FxType eFxType); ObjectGroupPhysicalProperties::FxType GetFxType() const; - void SetFxOffset(CVector vecOffset); - CVector GetFxOffset() const; - bool SetFxParticleSystem(CFxSystemBPSAInterface* pBlueprint); - void RemoveFxParticleSystem(); - void SetSmashMultiplier(float fMult); - float GetSmashMultiplier() const; - void SetBreakVelocity(CVector vecVelocity); - CVector GetBreakVelocity() const; - void SetBreakVelocityRandomness(float fRand); - float GetBreakVelocityRandomness() const; - void SetBreakMode(ObjectGroupPhysicalProperties::BreakMode eBreakMode); + void SetFxOffset(CVector vecOffset); + CVector GetFxOffset() const; + bool SetFxParticleSystem(CFxSystemBPSAInterface* pBlueprint); + void RemoveFxParticleSystem(); + void SetSmashMultiplier(float fMult); + float GetSmashMultiplier() const; + void SetBreakVelocity(CVector vecVelocity); + CVector GetBreakVelocity() const; + void SetBreakVelocityRandomness(float fRand); + float GetBreakVelocityRandomness() const; + void SetBreakMode(ObjectGroupPhysicalProperties::BreakMode eBreakMode); ObjectGroupPhysicalProperties::BreakMode GetBreakMode() const; - void SetSparksOnImpact(bool bSparks); - bool GetSparksOnImpact() const; + void SetSparksOnImpact(bool bSparks); + bool GetSparksOnImpact() const; }; diff --git a/Client/game_sa/CObjectSA.cpp b/Client/game_sa/CObjectSA.cpp index 7a3c255d1cb..afff035c334 100644 --- a/Client/game_sa/CObjectSA.cpp +++ b/Client/game_sa/CObjectSA.cpp @@ -26,7 +26,7 @@ static void CObject_PreRender(CObjectSAInterface* objectInterface) objectEntity->pEntity->SetPreRenderRequired(true); } -const std::uintptr_t RETURN_CCObject_PreRender = 0x59FD56; +const std::uintptr_t RETURN_CCObject_PreRender = 0x59FD56; static void __declspec(naked) HOOK_CCObject_PreRender() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -66,10 +66,10 @@ struct CFileObjectInstance float rx; float ry; float rz; - float rr; // = 1 + float rr; // = 1 DWORD modelId; DWORD areaNumber; - long flags; // = -1 + long flags; // = -1 }; CObjectSA::CObjectSA(CObjectSAInterface* objectInterface) @@ -185,7 +185,7 @@ void CObjectSA::Break() DWORD dwFunc = 0x5A0D90; DWORD dwThis = (DWORD)GetInterface(); - float fHitVelocity = 1000.0f; // has no direct influence, but should be high enough to trigger the break (effect) + float fHitVelocity = 1000.0f; // has no direct influence, but should be high enough to trigger the break (effect) // clang-format off __asm diff --git a/Client/game_sa/CObjectSA.h b/Client/game_sa/CObjectSA.h index 8b1d18b35e6..91e5636b38c 100644 --- a/Client/game_sa/CObjectSA.h +++ b/Client/game_sa/CObjectSA.h @@ -16,33 +16,33 @@ class CFireSAInterface; -#define FUNC_CObject_Create 0x5A1F60 -#define FUNC_CObject_Explode 0x5A1340 +#define FUNC_CObject_Create 0x5A1F60 +#define FUNC_CObject_Explode 0x5A1340 #define FUNC_CGlass_WindowRespondsToCollision 0x71BC40 class CObjectInfo { public: - float fMass; // 0 - float fTurnMass; // 4 - float fAirResistance; // 8 - float fElasticity; // 12 - float fBuoyancy; // 16 - float fUprootLimit; // 20 - float fColDamageMultiplier; // 24 - uint8 ucColDamageEffect; // 28 - uint8 ucSpecialColResponseCase; // 29 - uint8 ucCameraAvoidObject; // 30 - uint8 ucCausesExplosion; // 31 - uint8 ucFxType; // 32 - uint8 pad1[3]; // 33 - CVector vecFxOffset; // 36 - void* pFxSystem; // ret from CParticleData::GetDataFromName // 48 - float fSmashMultiplier; // 52 - CVector vecBreakVelocity; // 56 - float fBreakVelocityRand; // 68 - uint32 uiGunBreakMode; // 72 - uint32 uiSparksOnImpact; // 76 + float fMass; // 0 + float fTurnMass; // 4 + float fAirResistance; // 8 + float fElasticity; // 12 + float fBuoyancy; // 16 + float fUprootLimit; // 20 + float fColDamageMultiplier; // 24 + uint8 ucColDamageEffect; // 28 + uint8 ucSpecialColResponseCase; // 29 + uint8 ucCameraAvoidObject; // 30 + uint8 ucCausesExplosion; // 31 + uint8 ucFxType; // 32 + uint8 pad1[3]; // 33 + CVector vecFxOffset; // 36 + void* pFxSystem; // ret from CParticleData::GetDataFromName // 48 + float fSmashMultiplier; // 52 + CVector vecBreakVelocity; // 56 + float fBreakVelocityRand; // 68 + uint32 uiGunBreakMode; // 72 + uint32 uiSparksOnImpact; // 76 }; // TODO: Find out correct size // static_assert(sizeof(CObjectInfo) == 0x50, "Invalid size for CObjectInfo"); @@ -50,13 +50,13 @@ class CObjectInfo class CObjectSAInterface : public CPhysicalSAInterface { public: - void* pObjectList; // 312 - uint8 pad1; // 316 - uint8 pad2; // 317 - uint16 pad3; // 318 + void* pObjectList; // 312 + uint8 pad1; // 316 + uint8 pad2; // 317 + uint16 pad3; // 318 // flags - uint32 b0x01 : 1; // 320 + uint32 b0x01 : 1; // 320 uint32 b0x02 : 1; uint32 b0x04 : 1; uint32 b0x08 : 1; @@ -65,16 +65,16 @@ class CObjectSAInterface : public CPhysicalSAInterface uint32 bExploded : 1; uint32 b0x80 : 1; - uint32 b0x100 : 1; // 321 + uint32 b0x100 : 1; // 321 uint32 b0x200 : 1; uint32 b0x400 : 1; - uint32 bIsTrainNearCrossing : 1; // Train crossing will be opened if flag is set (distance < 120.0f) + uint32 bIsTrainNearCrossing : 1; // Train crossing will be opened if flag is set (distance < 120.0f) uint32 b0x1000 : 1; uint32 b0x2000 : 1; uint32 bIsDoorMoving : 1; uint32 bIsDoorOpen : 1; - uint32 b0x10000 : 1; // 322 + uint32 b0x10000 : 1; // 322 uint32 bUpdateScale : 1; uint32 b0x40000 : 1; uint32 b0x80000 : 1; @@ -83,7 +83,7 @@ class CObjectSAInterface : public CPhysicalSAInterface uint32 b0x400000 : 1; uint32 b0x800000 : 1; - uint32 b0x1000000 : 1; // 323 + uint32 b0x1000000 : 1; // 323 uint32 b0x2000000 : 1; uint32 b0x4000000 : 1; uint32 b0x8000000 : 1; @@ -92,29 +92,29 @@ class CObjectSAInterface : public CPhysicalSAInterface uint32 b0x40000000 : 1; uint32 b0x80000000 : 1; - uint8 ucColDamageEffect; // 324 - uint8 pad4; // 325 - uint8 pad5; // 326 - uint8 pad6; // 327 - uint8 pad7; // 328 - uint8 pad8; // 329 - uint16 pad9; // 330 - uint8 pad10; // 332 - uint8 pad11; // 333 - uint8 pad12; // 334 - uint8 pad13; // 335 - uint32 uiObjectRemovalTime; // 336 - float fHealth; // 340 - uint32 pad15; // 344 - float fScale; // 348 - CObjectInfo* pObjectInfo; // 352 - CFireSAInterface* pFire; // 356 - uint16 pad17; // 360 - uint16 pad18; // 362 - uint32 pad19; // 364 - CEntitySAInterface* pLinkedObjectDummy; // 368 CDummyObject - Is used for dynamic objects like garage doors, train crossings etc. - uint32 pad21; // 372 - uint32 pad22; // 376 + uint8 ucColDamageEffect; // 324 + uint8 pad4; // 325 + uint8 pad5; // 326 + uint8 pad6; // 327 + uint8 pad7; // 328 + uint8 pad8; // 329 + uint16 pad9; // 330 + uint8 pad10; // 332 + uint8 pad11; // 333 + uint8 pad12; // 334 + uint8 pad13; // 335 + uint32 uiObjectRemovalTime; // 336 + float fHealth; // 340 + uint32 pad15; // 344 + float fScale; // 348 + CObjectInfo* pObjectInfo; // 352 + CFireSAInterface* pFire; // 356 + uint16 pad17; // 360 + uint16 pad18; // 362 + uint32 pad19; // 364 + CEntitySAInterface* pLinkedObjectDummy; // 368 CDummyObject - Is used for dynamic objects like garage doors, train crossings etc. + uint32 pad21; // 372 + uint32 pad22; // 376 }; static_assert(sizeof(CObjectSAInterface) == 0x17C, "Invalid size for CObjectSAInterface"); diff --git a/Client/game_sa/CPadSA.cpp b/Client/game_sa/CPadSA.cpp index b0e8401ad4d..aa30afb5263 100644 --- a/Client/game_sa/CPadSA.cpp +++ b/Client/game_sa/CPadSA.cpp @@ -62,7 +62,7 @@ void CPadSA::Disable(bool bDisable) void CPadSA::Clear() { - CControllerState cs; // create a null controller (class is inited to null) + CControllerState cs; // create a null controller (class is inited to null) SetCurrentControllerState(&cs); SetLastControllerState(&cs); } diff --git a/Client/game_sa/CPadSA.h b/Client/game_sa/CPadSA.h index cae84ef592c..3b9e0cca010 100644 --- a/Client/game_sa/CPadSA.h +++ b/Client/game_sa/CPadSA.h @@ -13,19 +13,19 @@ #include -#define MAX_HORN_HISTORY 5 -#define STEERINGBUFFERLENGTH 10 +#define MAX_HORN_HISTORY 5 +#define STEERINGBUFFERLENGTH 10 -#define FUNC_CPad_UpdatePads 0x541DD0 +#define FUNC_CPad_UpdatePads 0x541DD0 class CPadSAInterface { public: - CControllerState NewState; // 0 - CControllerState OldState; // 48 + CControllerState NewState; // 0 + CControllerState OldState; // 48 - signed short SteeringLeftRightBuffer[STEERINGBUFFERLENGTH]; // 96 - signed long DrunkDrivingBufferUsed; // 116 + signed short SteeringLeftRightBuffer[STEERINGBUFFERLENGTH]; // 96 + signed long DrunkDrivingBufferUsed; // 116 // 120 CControllerState PCTempKeyState; @@ -34,24 +34,24 @@ class CPadSAInterface // 216 CControllerState PCTempMouseState; // 264 - BYTE Phase; // needed for switching into right state (analogue, pressure sensitive etc) - WORD Mode; // Configuration of keys as selected by the player - signed short ShakeDur; // How long will shake go on for (in msecs) - WORD DisablePlayerControls; // If TRUE then the player cannot move, shoot, etc. - BYTE ShakeFreq; // What is the frequency of the shake - bool bHornHistory[MAX_HORN_HISTORY]; // Store last 4 states of the horn key TRUE on else FALSE - BYTE iCurrHornHistory; // Where to store new history value - BYTE JustOutOfFrontEnd; // Number of frames we want some of the controls disabled for. - bool bApplyBrakes; // If TRUE then apply the brakes to the player's vehicle - bool bDisablePlayerEnterCar; // Script can set this so that the Enter Car button can be used to pick up objects - bool bDisablePlayerDuck; // Script can set this - bool bDisablePlayerFireWeapon; // Script can set this - bool bDisablePlayerFireWeaponWithL1; // Script can set this - for Judith's mission where L1 is needed to pick up objects - bool bDisablePlayerCycleWeapon; // Script can set this - bool bDisablePlayerJump; // Script can set this - bool bDisablePlayerDisplayVitalStats; // Script can set this - DWORD LastTimeTouched; // The time the last input was applied by the player - signed long AverageWeapon; // Average value of the weapon button (analogue) since last reset + BYTE Phase; // needed for switching into right state (analogue, pressure sensitive etc) + WORD Mode; // Configuration of keys as selected by the player + signed short ShakeDur; // How long will shake go on for (in msecs) + WORD DisablePlayerControls; // If TRUE then the player cannot move, shoot, etc. + BYTE ShakeFreq; // What is the frequency of the shake + bool bHornHistory[MAX_HORN_HISTORY]; // Store last 4 states of the horn key TRUE on else FALSE + BYTE iCurrHornHistory; // Where to store new history value + BYTE JustOutOfFrontEnd; // Number of frames we want some of the controls disabled for. + bool bApplyBrakes; // If TRUE then apply the brakes to the player's vehicle + bool bDisablePlayerEnterCar; // Script can set this so that the Enter Car button can be used to pick up objects + bool bDisablePlayerDuck; // Script can set this + bool bDisablePlayerFireWeapon; // Script can set this + bool bDisablePlayerFireWeaponWithL1; // Script can set this - for Judith's mission where L1 is needed to pick up objects + bool bDisablePlayerCycleWeapon; // Script can set this + bool bDisablePlayerJump; // Script can set this + bool bDisablePlayerDisplayVitalStats; // Script can set this + DWORD LastTimeTouched; // The time the last input was applied by the player + signed long AverageWeapon; // Average value of the weapon button (analogue) since last reset signed long AverageEntries; DWORD NoShakeBeforeThis; diff --git a/Client/game_sa/CPedDamageResponseCalculatorSA.h b/Client/game_sa/CPedDamageResponseCalculatorSA.h index 40f70ccd339..713348b539c 100644 --- a/Client/game_sa/CPedDamageResponseCalculatorSA.h +++ b/Client/game_sa/CPedDamageResponseCalculatorSA.h @@ -19,9 +19,9 @@ class CEntitySAInterface; class CPed; class CPedDamageResponse; -#define FUNC_CPedDamageResponseCalculator_Constructor 0x4ad3f0 -#define FUNC_CPedDamageResponseCalculator_Destructor 0x4ad420 -#define FUNC_CPedDamageResponseCalculator_ComputeDamageResponse 0x4b5ac0 +#define FUNC_CPedDamageResponseCalculator_Constructor 0x4ad3f0 +#define FUNC_CPedDamageResponseCalculator_Destructor 0x4ad420 +#define FUNC_CPedDamageResponseCalculator_ComputeDamageResponse 0x4b5ac0 class CPedDamageResponseCalculatorSAInterface { @@ -30,7 +30,7 @@ class CPedDamageResponseCalculatorSAInterface float fDamage; ePedPieceTypes bodyPart; eWeaponType weaponType; - bool bSpeak; // refers to a CPed::Say call (the dying scream?) + bool bSpeak; // refers to a CPed::Say call (the dying scream?) }; class CPedDamageResponseCalculatorSA : public CPedDamageResponseCalculator diff --git a/Client/game_sa/CPedIKSA.h b/Client/game_sa/CPedIKSA.h index 19aca735d6e..b1558928f2a 100644 --- a/Client/game_sa/CPedIKSA.h +++ b/Client/game_sa/CPedIKSA.h @@ -49,7 +49,7 @@ typedef struct class CPedIKSAInterface { public: - CPedSAInterface* ThisPed; // 528 + CPedSAInterface* ThisPed; // 528 LimbOrientation m_torsoOrien; float m_fSlopePitch; float m_fSlopePitchLimitMult; diff --git a/Client/game_sa/CPedIntelligenceSA.h b/Client/game_sa/CPedIntelligenceSA.h index c6333f13ecd..2b0293cf8a2 100644 --- a/Client/game_sa/CPedIntelligenceSA.h +++ b/Client/game_sa/CPedIntelligenceSA.h @@ -16,7 +16,7 @@ class CPedSAInterface; class CTaskManagerSA; -#define FUNC_CPedIntelligence_TestForStealthKill 0x601E00 +#define FUNC_CPedIntelligence_TestForStealthKill 0x601E00 class CFightManagerInterface { @@ -33,11 +33,11 @@ class CPedIntelligenceSAInterface public: // CEventHandlerHistory @ + 56 CPedSAInterface* pPed; - DWORD taskManager; // +4 (really CTaskManagerSAInterface) + DWORD taskManager; // +4 (really CTaskManagerSAInterface) BYTE bPad[16]; - CFightManagerInterface* fightInterface; // +24 + CFightManagerInterface* fightInterface; // +24 BYTE bPad2[184]; - DWORD vehicleScanner; // +212 (really CVehicleScannerSAInterface) + DWORD vehicleScanner; // +212 (really CVehicleScannerSAInterface) }; class CPedIntelligenceSA : public CPedIntelligence diff --git a/Client/game_sa/CPedModelInfoSA.h b/Client/game_sa/CPedModelInfoSA.h index f2d311688eb..df1229ae552 100644 --- a/Client/game_sa/CPedModelInfoSA.h +++ b/Client/game_sa/CPedModelInfoSA.h @@ -17,9 +17,9 @@ class ePedStats; typedef long AssocGroupID; -#define FUNC_SetMotionAnimGroup 0x5b3580 -#define FUNC_CPedModelInfo_Constructor 0x4c57a0 -#define VAR_CPedModelInfo_VTBL 0x85bdc0 +#define FUNC_SetMotionAnimGroup 0x5b3580 +#define FUNC_CPedModelInfo_Constructor 0x4c57a0 +#define VAR_CPedModelInfo_VTBL 0x85bdc0 // CPedModelInfo: // +36 = Motion anim group (AssocGroupID, long) @@ -41,22 +41,22 @@ class CPedModelInfoSAInterface : public CBaseModelInfoSAInterface public: CPedModelInfoSAInterface(); - BYTE pad[4]; // 32 - AssocGroupID motionAnimGroup; // 36 Motion anim group (AssocGroupID, long) - DWORD pedType; // 40 Default ped type (long) - ePedStats* pedStats; // 44 Default ped stats (ePedStats) - BYTE bCanDriveCars; // 48 Can drive cars (byte) - BYTE pad2[1]; // 49 - short pedFlags; // 50 Ped flags (short) - CColModel* pHitColModel; // 52 Hit col model (CColModel*) - BYTE bFirstRadioStation; // 56 First radio station - BYTE bSecondRadioStation; // 57 Second radio station - BYTE bIsInRace; // 58 Race (byte) - BYTE pad3[1]; // 59 - short sVoiceType; // 60 Voice type - short sFirstVoice; // 62 First voice - short sLastVoice; // 64 Last voice - short sNextVoice; // 66 Next voice + BYTE pad[4]; // 32 + AssocGroupID motionAnimGroup; // 36 Motion anim group (AssocGroupID, long) + DWORD pedType; // 40 Default ped type (long) + ePedStats* pedStats; // 44 Default ped stats (ePedStats) + BYTE bCanDriveCars; // 48 Can drive cars (byte) + BYTE pad2[1]; // 49 + short pedFlags; // 50 Ped flags (short) + CColModel* pHitColModel; // 52 Hit col model (CColModel*) + BYTE bFirstRadioStation; // 56 First radio station + BYTE bSecondRadioStation; // 57 Second radio station + BYTE bIsInRace; // 58 Race (byte) + BYTE pad3[1]; // 59 + short sVoiceType; // 60 Voice type + short sFirstVoice; // 62 First voice + short sLastVoice; // 64 Last voice + short sNextVoice; // 66 Next voice }; class CPedModelInfoSA : public CModelInfoSA, public CPedModelInfo diff --git a/Client/game_sa/CPedSA.cpp b/Client/game_sa/CPedSA.cpp index b70f192f0e9..0bd0f13ec42 100644 --- a/Client/game_sa/CPedSA.cpp +++ b/Client/game_sa/CPedSA.cpp @@ -56,9 +56,9 @@ void CPedSA::Init() for (std::size_t i = 0; i < WEAPONSLOT_MAX; i++) m_weapons[i] = std::make_unique(&(pedInterface->Weapons[i]), this, static_cast(i)); - #ifdef PedIK_SA - this->m_pPedIK = new Cm_pPedIKSA(&(pedInterface->m_pPedIK)); - #endif +#ifdef PedIK_SA + this->m_pPedIK = new Cm_pPedIKSA(&(pedInterface->m_pPedIK)); +#endif } void CPedSA::SetModelIndex(std::uint32_t modelIndex) @@ -85,7 +85,8 @@ bool CPedSA::AddProjectile(eWeaponType weaponType, CVector origin, float force, if (!projectileInfo) return false; - return projectileInfo->AddProjectile(static_cast(this), weaponType, origin, force, const_cast(target), const_cast(targetEntity)); + return projectileInfo->AddProjectile(static_cast(this), weaponType, origin, force, const_cast(target), + const_cast(targetEntity)); } void CPedSA::DetachPedFromEntity() @@ -98,13 +99,15 @@ bool CPedSA::InternalAttachEntityToEntity(DWORD entityInteface, const CVector* p { // sDirection and fRotationLimit only apply to first-person shooting (bChangeCamera) CPedSAInterface* pedInterface = GetPedInterface(); - auto pedType = static_cast(pedInterface->bPedType); + auto pedType = static_cast(pedInterface->bPedType); // Hack the CPed type(?) to non-player so the camera doesn't get changed pedInterface->bPedType = 2; // CEntity *__thiscall CPed::AttachPedToEntity(CPed *this, CEntity *a2, float arg4, float a4, float a5, __int16 a6, int a7, eWeaponType a3) - ((CEntitySAInterface*(__thiscall*)(CEntitySAInterface*, CEntitySAInterface*, float, float, float, std::uint16_t, int, eWeaponType))FUNC_AttachPedToEntity)(m_pInterface, reinterpret_cast(entityInteface), position->fX, position->fY, position->fZ, 0, 0, WEAPONTYPE_UNARMED); + ((CEntitySAInterface * (__thiscall*)(CEntitySAInterface*, CEntitySAInterface*, float, float, float, std::uint16_t, int, eWeaponType)) + FUNC_AttachPedToEntity)(m_pInterface, reinterpret_cast(entityInteface), position->fX, position->fY, position->fZ, 0, 0, + WEAPONTYPE_UNARMED); // Hack the CPed type(?) to whatever it was set to pedInterface->bPedType = pedType; @@ -134,14 +137,15 @@ void CPedSA::Respawn(CVector* position, bool cameraCut) MemSet((void*)0x4422EA, 0x90, 20); // void __cdecl CGameLogic::RestorePlayerStuffDuringResurrection(CPlayerPed *player, __int128 a2) - ((void(__cdecl*)(CEntitySAInterface*, float, float, float, float))FUNC_RestorePlayerStuffDuringResurrection)(m_pInterface, position->fX, position->fY, position->fZ, 1.0f); + ((void(__cdecl*)(CEntitySAInterface*, float, float, float, float))FUNC_RestorePlayerStuffDuringResurrection)(m_pInterface, position->fX, position->fY, + position->fZ, 1.0f); - #ifdef SortOutStreamingAndMemory // Disabled to see if it reduces crashes - float angle = 10.0f; // angle for CRenderer::RequestObjectsInDirection +#ifdef SortOutStreamingAndMemory // Disabled to see if it reduces crashes + float angle = 10.0f; // angle for CRenderer::RequestObjectsInDirection - // void __cdecl CGameLogic::SortOutStreamingAndMemory(CVector *translation, float angle) - ((void(__cdecl*)(CVector*, float))FUNC_SortOutStreamingAndMemory)(position, angle); - #endif + // void __cdecl CGameLogic::SortOutStreamingAndMemory(CVector *translation, float angle) + ((void(__cdecl*)(CVector*, float))FUNC_SortOutStreamingAndMemory)(position, angle); +#endif // BYTE *__thiscall CPed::RemoveGogglesModel(CPed *this) ((std::uint8_t*(__thiscall*)(CEntitySAInterface*))FUNC_RemoveGogglesModel)(m_pInterface); @@ -166,7 +170,7 @@ CWeapon* CPedSA::GiveWeapon(eWeaponType weaponType, std::uint32_t ammo, eWeaponS modelInfo->Request(BLOCKING, "CPedSA::GiveWeapon"); modelInfo->MakeCustomModel(); } - + // If the weapon is satchels, load the detonator too if (weaponType == WEAPONTYPE_REMOTE_SATCHEL_CHARGE) GiveWeapon(WEAPONTYPE_DETONATOR, 1, WEAPONSKILL_STD); @@ -175,7 +179,8 @@ CWeapon* CPedSA::GiveWeapon(eWeaponType weaponType, std::uint32_t ammo, eWeaponS // eWeaponType __thiscall CPed::GiveWeapon(CPed *this, eWeaponType weaponID, signed int ammo, int a4) // Last argument is unused - eWeaponSlot weaponSlot = ((eWeaponSlot(__thiscall*)(CEntitySAInterface*, eWeaponType, std::uint32_t, int))FUNC_GiveWeapon)(m_pInterface, weaponType, ammo, 1); + eWeaponSlot weaponSlot = + ((eWeaponSlot(__thiscall*)(CEntitySAInterface*, eWeaponType, std::uint32_t, int))FUNC_GiveWeapon)(m_pInterface, weaponType, ammo, 1); return GetWeapon(weaponSlot); } @@ -214,7 +219,7 @@ void CPedSA::RemoveWeaponModel(std::uint32_t model) void CPedSA::ClearWeapon(eWeaponType weaponType) { // BYTE *__thiscall CPed::ClearWeapon(CPed *this, eWeaponType a2) - ((std::uint8_t * (__thiscall*)(CEntitySAInterface*, eWeaponType)) FUNC_ClearWeapon)(m_pInterface, weaponType); + ((std::uint8_t*(__thiscall*)(CEntitySAInterface*, eWeaponType))FUNC_ClearWeapon)(m_pInterface, weaponType); } void CPedSA::SetIsStanding(bool standing) @@ -302,7 +307,7 @@ CVector* CPedSA::GetTransformedBonePosition(eBone bone, CVector* position) // for a broken model. if (entity->m_pRwObject) // RwV3D *__thiscall CPed::GetTransformedBonePosition(CPed *this, RwV3D *pointsIn, int boneId, char bUpdateBones) - ((RwV3d*(__thiscall*)(CEntitySAInterface*, CVector*, eBone, bool))FUNC_GetTransformedBonePosition)(entity, position, bone, true); + ((RwV3d * (__thiscall*)(CEntitySAInterface*, CVector*, eBone, bool)) FUNC_GetTransformedBonePosition)(entity, position, bone, true); // Clamp to a sane range as this function can occasionally return massive values, // which causes ProcessLineOfSight to effectively freeze @@ -350,7 +355,7 @@ void CPedSA::SetClothesTextureAndModel(const char* texture, const char* model, i // int __fastcall CPedClothesDesc::SetTextureAndModel(DWORD* this, int unknown, char* textureName, char* modelName, eClothesTexturePart texturePart) // Second argument is unused in CKeyGen::GetUppercaseKey - void(__fastcall* CPedClothesDesc__SetTextureAndModel)(CPedClothesDesc*, int, const char*, const char*, int) = nullptr; + void(__fastcall * CPedClothesDesc__SetTextureAndModel)(CPedClothesDesc*, int, const char*, const char*, int) = nullptr; CPedClothesDesc__SetTextureAndModel = reinterpret_cast(FUNC_CPedClothesDesc__SetTextureAndModel); CPedClothesDesc__SetTextureAndModel(clothes, 0, texture, model, textureType); } @@ -401,7 +406,7 @@ void CPedSA::SetFootBlood(std::uint32_t footBlood) std::uint32_t CPedSA::GetFootBlood() const { CPedSAInterface* pedInterface = GetPedInterface(); - + // If the foot blood flag is activated, return the amount of foot blood return pedInterface->pedFlags.bDoBloodyFootprints ? pedInterface->timeWhenDead : 0; } @@ -517,7 +522,8 @@ float CPedSA::GetCurrentWeaponRange() const void CPedSA::AddWeaponAudioEvent(EPedWeaponAudioEventType audioEventType) { // void __thiscall CAEPedWeaponAudioEntity::AddAudioEvent(CAEPedWeaponAudioEntity *this, int audioEventId) - ((void(__thiscall*)(CPedWeaponAudioEntitySAInterface*, std::uint16_t))FUNC_CAEPedWeaponAudioEntity__AddAudioEvent)(&GetPedInterface()->weaponAudioEntity, static_cast(audioEventType)); + ((void(__thiscall*)(CPedWeaponAudioEntitySAInterface*, std::uint16_t))FUNC_CAEPedWeaponAudioEntity__AddAudioEvent)( + &GetPedInterface()->weaponAudioEntity, static_cast(audioEventType)); } bool CPedSA::IsDoingGangDriveby() const @@ -542,17 +548,18 @@ void CPedSA::SetOxygenLevel(float oxygen) void CPedSA::Say(const ePedSpeechContext& speechId, float probability) { // Call CPed::Say - ((void(__thiscall*)(CPedSAInterface*, ePedSpeechContext, int, float, bool, bool, bool))FUNC_CPed_Say)(GetPedInterface(), speechId, 0, probability, false, false, false); + ((void(__thiscall*)(CPedSAInterface*, ePedSpeechContext, int, float, bool, bool, bool))FUNC_CPed_Say)(GetPedInterface(), speechId, 0, probability, false, + false, false); } void CPedSA::GetAttachedSatchels(std::vector& satchelsList) const { // Array of projectiles objects - auto** projectilesArray = reinterpret_cast(ARRAY_CProjectile); - CProjectileSAInterface* projectileInterface = nullptr; + auto** projectilesArray = reinterpret_cast(ARRAY_CProjectile); + CProjectileSAInterface* projectileInterface = nullptr; // Array of projectiles infos - auto* projectilesInfoArray = reinterpret_cast(ARRAY_CProjectileInfo); + auto* projectilesInfoArray = reinterpret_cast(ARRAY_CProjectileInfo); CProjectileInfoSAInterface* projectileInfoInterface = nullptr; satchelsList.reserve(PROJECTILE_COUNT); @@ -596,11 +603,11 @@ void CPedSA::SetInWaterFlags(bool inWater) // Check if they have already been applied. // //////////////////////////////////////////////////////////////// -#define HOOKPOS_CPed_PreRenderAfterTest 0x5E65A0 +#define HOOKPOS_CPed_PreRenderAfterTest 0x5E65A0 #define HOOKSIZE_CPed_PreRenderAfterTest 15 static constexpr std::uintptr_t RETURN_CPed_PreRenderAfterTest = 0x5E65AF; static constexpr std::uintptr_t RETURN_CPed_PreRenderAfterTestSkip = 0x5E6658; -static void __declspec(naked) HOOK_CPed_PreRenderAfterTest() +static void __declspec(naked) HOOK_CPed_PreRenderAfterTest() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -639,11 +646,11 @@ static void __declspec(naked) HOOK_CPed_PreRenderAfterTest() // Check if it should not be called because we only wanted to do the extra rotations // //////////////////////////////////////////////////////////////// -#define HOOKPOS_CPed_PreRenderAfterTest_Mid 0x5E6669 +#define HOOKPOS_CPed_PreRenderAfterTest_Mid 0x5E6669 #define HOOKSIZE_CPed_PreRenderAfterTest_Mid 5 static constexpr std::uintptr_t RETURN_CPed_PreRenderAfterTest_Mid = 0x5E666E; static constexpr std::uintptr_t RETURN_CPed_PreRenderAfterTest_MidSkip = 0x5E766F; -static void __declspec(naked) HOOK_CPed_PreRenderAfterTest_Mid() +static void __declspec(naked) HOOK_CPed_PreRenderAfterTest_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CPedSA.h b/Client/game_sa/CPedSA.h index 34e2de6f414..a45397f1e97 100644 --- a/Client/game_sa/CPedSA.h +++ b/Client/game_sa/CPedSA.h @@ -27,99 +27,99 @@ class CPlayerPedDataSAInterface; class CVehicleSAInterface; // CPed -#define FUNC_AttachPedToEntity 0x5E7CB0 // CPed::AttachPedToEntity -#define FUNC_DetachPedFromEntity 0x5E7EC0 // CPed::DettachPedFromEntity -#define FUNC_SetModelIndex 0x5E4880 // CPed::SetModelIndex -#define FUNC_SetIsStanding 0x4ABBE0 // CPed::SetIsStanding -#define FUNC_SetCurrentWeapon 0x5E61F0 // CPed::SetCurrentWeapon -#define FUNC_GiveWeapon 0x5E6080 // CPed::GiveWeapon -#define FUNC_ClearWeapon 0x5E62B0 // CPed::ClearWeapon -#define FUNC_RemoveWeaponModel 0x5E3990 // CPed::RemoveWeaponModel -#define FUNC_GetBonePosition 0x5E4280 // CPed::GetBonePosition -#define FUNC_GetTransformedBonePosition 0x5E01C0 // CPed::GetTransformedBonePosition -#define FUNC_TakeOffGoggles 0x5E6010 // CPed::TakeOffGoggles -#define FUNC_PutOnGoggles 0x5E3AE0 // CPed::PutOnGoggles -#define FUNC_RemoveGogglesModel 0x5DF170 // CPed::RemoveGogglesModel -#define FUNC_CPed_RemoveBodyPart 0x5F0140 // CPed::RemoveBodyPart -#define FUNC_PreRenderAfterTest 0x5E65A0 // CPed::PreRenderAfterTest +#define FUNC_AttachPedToEntity 0x5E7CB0 // CPed::AttachPedToEntity +#define FUNC_DetachPedFromEntity 0x5E7EC0 // CPed::DettachPedFromEntity +#define FUNC_SetModelIndex 0x5E4880 // CPed::SetModelIndex +#define FUNC_SetIsStanding 0x4ABBE0 // CPed::SetIsStanding +#define FUNC_SetCurrentWeapon 0x5E61F0 // CPed::SetCurrentWeapon +#define FUNC_GiveWeapon 0x5E6080 // CPed::GiveWeapon +#define FUNC_ClearWeapon 0x5E62B0 // CPed::ClearWeapon +#define FUNC_RemoveWeaponModel 0x5E3990 // CPed::RemoveWeaponModel +#define FUNC_GetBonePosition 0x5E4280 // CPed::GetBonePosition +#define FUNC_GetTransformedBonePosition 0x5E01C0 // CPed::GetTransformedBonePosition +#define FUNC_TakeOffGoggles 0x5E6010 // CPed::TakeOffGoggles +#define FUNC_PutOnGoggles 0x5E3AE0 // CPed::PutOnGoggles +#define FUNC_RemoveGogglesModel 0x5DF170 // CPed::RemoveGogglesModel +#define FUNC_CPed_RemoveBodyPart 0x5F0140 // CPed::RemoveBodyPart +#define FUNC_PreRenderAfterTest 0x5E65A0 // CPed::PreRenderAfterTest #define FUNC_CPed_Say 0x5EFFE0 // CPlayerPed -#define FUNC_MakeChangesForNewWeapon_Slot 0x60D000 // CPlayerPed::MakeChangesForNewWeapon +#define FUNC_MakeChangesForNewWeapon_Slot 0x60D000 // CPlayerPed::MakeChangesForNewWeapon // CPedClothesDesc && CClothes -#define FUNC_CPedClothesDesc__SetTextureAndModel 0x5A8080 // CPedClothesDesc::SetTextureAndModel -#define FUNC_CClothes__RebuildPlayer 0x5A82C0 // CClothes::RebuildPlayer +#define FUNC_CPedClothesDesc__SetTextureAndModel 0x5A8080 // CPedClothesDesc::SetTextureAndModel +#define FUNC_CClothes__RebuildPlayer 0x5A82C0 // CClothes::RebuildPlayer // CAEPedWeaponAudioEntity -#define FUNC_CAEPedWeaponAudioEntity__AddAudioEvent 0x4E69F0 // CAEPedWeaponAudioEntity::AddAudioEvent +#define FUNC_CAEPedWeaponAudioEntity__AddAudioEvent 0x4E69F0 // CAEPedWeaponAudioEntity::AddAudioEvent // CGameLogic -#define FUNC_RestorePlayerStuffDuringResurrection 0x442060 // CGameLogic::RestorePlayerStuffDuringResurrection -#define FUNC_SortOutStreamingAndMemory 0x441440 // CGameLogic::SortOutStreamingAndMemory +#define FUNC_RestorePlayerStuffDuringResurrection 0x442060 // CGameLogic::RestorePlayerStuffDuringResurrection +#define FUNC_SortOutStreamingAndMemory 0x441440 // CGameLogic::SortOutStreamingAndMemory class CPedFlags { public: // m_nPedFlags - unsigned int bIsStanding : 1; // is ped standing on something - unsigned int bWasStanding : 1; // was ped standing on something - unsigned int bIsLooking : 1; // is ped looking at something or in a direction - unsigned int bIsRestoringLook : 1; // is ped restoring head postion from a look - unsigned int bIsAimingGun : 1; // is ped aiming gun - unsigned int bIsRestoringGun : 1; // is ped moving gun back to default posn - unsigned int bCanPointGunAtTarget : 1; // can ped point gun at target - unsigned int bIsTalking : 1; // is ped talking(see Chat()) - - unsigned int bInVehicle : 1; // is in a vehicle - unsigned int bIsInTheAir : 1; // is in the air - unsigned int bIsLanding : 1; // is landing after being in the air - unsigned int bHitSomethingLastFrame : 1; // has been in a collision last fram - unsigned int bIsNearCar : 1; // has been in a collision last fram - unsigned int bRenderPedInCar : 1; // has been in a collision last fram - unsigned int bUpdateAnimHeading : 1; // update ped heading due to heading change during anim sequence - unsigned int bRemoveHead : 1; // waiting on AntiSpazTimer to remove head - - unsigned int bFiringWeapon : 1; // is pulling trigger - unsigned int bHasACamera : 1; // does ped possess a camera to document accidents - unsigned int bPedIsBleeding : 1; // Ped loses a lot of blood if true - unsigned int bStopAndShoot : 1; // Ped cannot reach target to attack with fist, need to use gun - unsigned int bIsPedDieAnimPlaying : 1; // is ped die animation finished so can dead now - unsigned int bStayInSamePlace : 1; // when set, ped stays put - unsigned int bKindaStayInSamePlace : 1; // when set, ped doesn't seek out opponent or cover large distances. Will still shuffle and look for cover - unsigned int bBeingChasedByPolice : 1; // use nodes for routefind - - unsigned int bNotAllowedToDuck : 1; // Is this ped allowed to duck at all? - unsigned int bCrouchWhenShooting : 1; // duck behind cars etc - unsigned int bIsDucking : 1; // duck behind cars etc - unsigned int bGetUpAnimStarted : 1; // don't want to play getup anim if under something - unsigned int bDoBloodyFootprints : 1; // unsigned int bIsLeader :1; + unsigned int bIsStanding : 1; // is ped standing on something + unsigned int bWasStanding : 1; // was ped standing on something + unsigned int bIsLooking : 1; // is ped looking at something or in a direction + unsigned int bIsRestoringLook : 1; // is ped restoring head postion from a look + unsigned int bIsAimingGun : 1; // is ped aiming gun + unsigned int bIsRestoringGun : 1; // is ped moving gun back to default posn + unsigned int bCanPointGunAtTarget : 1; // can ped point gun at target + unsigned int bIsTalking : 1; // is ped talking(see Chat()) + + unsigned int bInVehicle : 1; // is in a vehicle + unsigned int bIsInTheAir : 1; // is in the air + unsigned int bIsLanding : 1; // is landing after being in the air + unsigned int bHitSomethingLastFrame : 1; // has been in a collision last fram + unsigned int bIsNearCar : 1; // has been in a collision last fram + unsigned int bRenderPedInCar : 1; // has been in a collision last fram + unsigned int bUpdateAnimHeading : 1; // update ped heading due to heading change during anim sequence + unsigned int bRemoveHead : 1; // waiting on AntiSpazTimer to remove head + + unsigned int bFiringWeapon : 1; // is pulling trigger + unsigned int bHasACamera : 1; // does ped possess a camera to document accidents + unsigned int bPedIsBleeding : 1; // Ped loses a lot of blood if true + unsigned int bStopAndShoot : 1; // Ped cannot reach target to attack with fist, need to use gun + unsigned int bIsPedDieAnimPlaying : 1; // is ped die animation finished so can dead now + unsigned int bStayInSamePlace : 1; // when set, ped stays put + unsigned int bKindaStayInSamePlace : 1; // when set, ped doesn't seek out opponent or cover large distances. Will still shuffle and look for cover + unsigned int bBeingChasedByPolice : 1; // use nodes for routefind + + unsigned int bNotAllowedToDuck : 1; // Is this ped allowed to duck at all? + unsigned int bCrouchWhenShooting : 1; // duck behind cars etc + unsigned int bIsDucking : 1; // duck behind cars etc + unsigned int bGetUpAnimStarted : 1; // don't want to play getup anim if under something + unsigned int bDoBloodyFootprints : 1; // unsigned int bIsLeader :1; unsigned int bDontDragMeOutCar : 1; - unsigned int bStillOnValidPoly : 1; // set if the polygon the ped is on is still valid for collision + unsigned int bStillOnValidPoly : 1; // set if the polygon the ped is on is still valid for collision unsigned int bAllowMedicsToReviveMe : 1; // m_nSecondPedFlags unsigned int bResetWalkAnims : 1; - unsigned int bOnBoat : 1; // flee but only using nodes - unsigned int bBusJacked : 1; // flee but only using nodes - unsigned int bFadeOut : 1; // set if you want ped to fade out - unsigned int bKnockedUpIntoAir : 1; // has ped been knocked up into the air by a car collision - unsigned int bHitSteepSlope : 1; // has ped collided/is standing on a steep slope (surface type) - unsigned int bCullExtraFarAway : 1; // special ped only gets culled if it's extra far away (for roadblocks) - unsigned int bTryingToReachDryLand : 1; // has ped just exited boat and trying to get to dry land + unsigned int bOnBoat : 1; // flee but only using nodes + unsigned int bBusJacked : 1; // flee but only using nodes + unsigned int bFadeOut : 1; // set if you want ped to fade out + unsigned int bKnockedUpIntoAir : 1; // has ped been knocked up into the air by a car collision + unsigned int bHitSteepSlope : 1; // has ped collided/is standing on a steep slope (surface type) + unsigned int bCullExtraFarAway : 1; // special ped only gets culled if it's extra far away (for roadblocks) + unsigned int bTryingToReachDryLand : 1; // has ped just exited boat and trying to get to dry land unsigned int bCollidedWithMyVehicle : 1; - unsigned int bRichFromMugging : 1; // ped has lots of cash cause they've been mugging people - unsigned int bChrisCriminal : 1; // Is a criminal as killed during Chris' police mission (should be counted as such) - unsigned int bShakeFist : 1; // test shake hand at look entity - unsigned int bNoCriticalHits : 1; // ped cannot be killed by a single bullet - unsigned int bHasAlreadyBeenRecorded : 1; // Used for replays - unsigned int bUpdateMatricesRequired : 1; // if PedIK has altered bones so matrices need updated this frame - unsigned int bFleeWhenStanding : 1; // - - unsigned int bMiamiViceCop : 1; // - unsigned int bMoneyHasBeenGivenByScript : 1; // - unsigned int bHasBeenPhotographed : 1; // + unsigned int bRichFromMugging : 1; // ped has lots of cash cause they've been mugging people + unsigned int bChrisCriminal : 1; // Is a criminal as killed during Chris' police mission (should be counted as such) + unsigned int bShakeFist : 1; // test shake hand at look entity + unsigned int bNoCriticalHits : 1; // ped cannot be killed by a single bullet + unsigned int bHasAlreadyBeenRecorded : 1; // Used for replays + unsigned int bUpdateMatricesRequired : 1; // if PedIK has altered bones so matrices need updated this frame + unsigned int bFleeWhenStanding : 1; // + + unsigned int bMiamiViceCop : 1; // + unsigned int bMoneyHasBeenGivenByScript : 1; // + unsigned int bHasBeenPhotographed : 1; // unsigned int bIsDrowning : 1; unsigned int bDrownsInWater : 1; unsigned int bHeadStuckInCollision : 1; @@ -129,7 +129,7 @@ class CPedFlags unsigned int bDontFight : 1; unsigned int bDoomAim : 1; unsigned int bCanBeShotInVehicle : 1; - unsigned int bPushedAlongByCar : 1; // ped is getting pushed along by car collision (so don't take damage from horz velocity) + unsigned int bPushedAlongByCar : 1; // ped is getting pushed along by car collision (so don't take damage from horz velocity) unsigned int bNeverEverTargetThisPed : 1; unsigned int bThisPedIsATargetPriority : 1; unsigned int bCrouchWhenScared : 1; @@ -148,11 +148,11 @@ class CPedFlags unsigned int bKilledByStealth : 1; unsigned int bDoesntDropWeaponsWhenDead : 1; unsigned int bCalledPreRender : 1; - unsigned int bBloodPuddleCreated : 1; // Has a static puddle of blood been created yet + unsigned int bBloodPuddleCreated : 1; // Has a static puddle of blood been created yet unsigned int bPartOfAttackWave : 1; unsigned int bClearRadarBlipOnDeath : 1; - unsigned int bNeverLeavesGroup : 1; // flag that we want to test 3 extra spheres on col model - unsigned int bTestForBlockedPositions : 1; // this sets these indicator flags for various posisions on the front of the ped + unsigned int bNeverLeavesGroup : 1; // flag that we want to test 3 extra spheres on col model + unsigned int bTestForBlockedPositions : 1; // this sets these indicator flags for various posisions on the front of the ped unsigned int bRightArmBlocked : 1; unsigned int bLeftArmBlocked : 1; @@ -166,29 +166,29 @@ class CPedFlags unsigned int bWaitingForScriptBrainToLoad : 1; unsigned int bHasGroupDriveTask : 1; unsigned int bCanExitCar : 1; - unsigned int CantBeKnockedOffBike : 2; // 0=Default(harder for mission peds) 1=Never 2=Always normal(also for mission peds) + unsigned int CantBeKnockedOffBike : 2; // 0=Default(harder for mission peds) 1=Never 2=Always normal(also for mission peds) unsigned int bHasBeenRendered : 1; unsigned int bIsCached : 1; - unsigned int bPushOtherPeds : 1; // GETS RESET EVERY FRAME - SET IN TASK: want to push other peds around (eg. leader of a group or ped trying to - // get in a car) + unsigned int bPushOtherPeds : 1; // GETS RESET EVERY FRAME - SET IN TASK: want to push other peds around (eg. leader of a group or ped trying to + // get in a car) // m_nFourthPedFlags unsigned int bHasBulletProofVest : 1; unsigned int bUsingMobilePhone : 1; unsigned int bUpperBodyDamageAnimsOnly : 1; unsigned int bStuckUnderCar : 1; - unsigned int bKeepTasksAfterCleanUp : 1; // If true ped will carry on with task even after cleanup + unsigned int bKeepTasksAfterCleanUp : 1; // If true ped will carry on with task even after cleanup unsigned int bIsDyingStuck : 1; - unsigned int bIgnoreHeightCheckOnGotoPointTask : 1; // set when walking round buildings, reset when task quits + unsigned int bIgnoreHeightCheckOnGotoPointTask : 1; // set when walking round buildings, reset when task quits unsigned int bForceDieInCar : 1; unsigned int bCheckColAboveHead : 1; unsigned int bIgnoreWeaponRange : 1; unsigned int bDruggedUp : 1; - unsigned int bWantedByPolice : 1; // if this is set, the cops will always go after this ped when they are doing a KillCriminal task + unsigned int bWantedByPolice : 1; // if this is set, the cops will always go after this ped when they are doing a KillCriminal task unsigned int bSignalAfterKill : 1; unsigned int bCanClimbOntoBoat : 1; - unsigned int bPedHitWallLastFrame : 1; // useful to store this so that AI knows (normal will still be available) + unsigned int bPedHitWallLastFrame : 1; // useful to store this so that AI knows (normal will still be available) unsigned int bIgnoreHeightDifferenceFollowingNodes : 1; unsigned int bMoveAnimSpeedHasBeenSetByTask : 1; @@ -196,7 +196,7 @@ class CPedFlags unsigned int bJustGotOffTrain : 1; unsigned int bDeathPickupsPersist : 1; unsigned int bTestForShotInVehicle : 1; - unsigned int bUsedForReplay : 1; // This ped is controlled by replay and should be removed when replay is done. + unsigned int bUsedForReplay : 1; // This ped is controlled by replay and should be removed when replay is done. }; class CPedAcquaintanceSAInterface @@ -229,117 +229,117 @@ static_assert(sizeof(CPedStatSAInterface) == 0x34, "Invalid size for CPedStatSAI class CPedSAInterface : public CPhysicalSAInterface { public: - CPedSoundEntitySAInterface pedAudio; // CAEPedAudioEntity - CPedSoundSAInterface pedSound; // CAEPedSpeechAudioEntity - CPedWeaponAudioEntitySAInterface weaponAudioEntity; // CAEPedWeaponAudioEntity - - std::uint8_t unk_43C[36]; - CPedSAInterface* roadRageWith; - std::uint8_t unk_464[8]; - - CPedFlags pedFlags; - CPedIntelligenceSAInterface* pPedIntelligence; - CPlayerPedDataSAInterface* pPlayerData; - - std::uint8_t createdBy; - void* pedNodes[19]; // AnimBlendFrameData* - int iMoveAnimGroup; - CVector2D vecAnimMovingShiftLocal; - CPedAcquaintanceSAInterface pedAcquaintance; - - RpClump* pWeaponObject; - RwFrame* pGunflashObject; - RpClump* pGogglesObject; - bool* pGogglesState; - - std::int16_t weaponGunflashStateRightHand; - std::int16_t weaponGunFlashAlphaProgMP1; - std::int16_t weaponGunflashStateLeftHand; - std::int16_t weaponGunFlashAlphaProgMP2; - - CPedIKSAInterface pedIK; - int unk_52C; - - int pedState; - PedMoveState::Enum moveState; - int swimmingMoveState; - - int unk_53C; - float fHealth; - float fMaxHealth; - float fArmor; - - std::uint32_t timeTillWeNeedThisPed; - CVector2D vecAnimMovingShift; - float fCurrentRotation; - float fTargetRotation; - float fRotationSpeed; - float fMoveAnim; - - CEntitySAInterface* pContactEntity; // m_standingOnEntity - CVector unk_56C; - CVector unk_578; - CEntitySAInterface* pLastContactEntity; // m_contactEntity - - CVehicleSAInterface* pLastVehicle; - CVehicleSAInterface* pVehicle; - CVehicleSAInterface* vehicleDeadInFrontOf; - - int unk_594; - int bPedType; // ped type? 0 = player, >1 = ped? - CPedStatSAInterface* pPedStats; - CWeaponSAInterface Weapons[WEAPONSLOT_MAX]; - eWeaponType savedWeapon; - eWeaponType delayedWeapon; - std::uint32_t delayedWeaponAmmo; - std::uint8_t bCurrentWeaponSlot; - std::uint8_t weaponShootingRate; - std::uint8_t weaponAccuracy; - - CEntitySAInterface* pTargetedObject; - int unk_720; - int unk_724; - int unk_728; - - eWeaponSkill weaponSkill; - eFightingStyle bFightingStyle; - std::uint8_t bFightingStyleExtra; - std::uint8_t bPad7; - - CFireSAInterface* pFireOnPed; - float fireDamageMult; - - CEntitySAInterface* pLookAtEntity; - float fLookHeading; - - std::uint32_t weaponModelID; - int unk_744; - std::uint32_t lookTime; - int unk_74C; - std::uint32_t timeWhenDead; // death time in MS - std::uint8_t bodyPartToRemove; - std::int16_t unk_755; - std::int16_t moneyCount; - std::int16_t unk_758; - int unk_75C; - std::uint8_t lastWeaponDamage; - std::uint8_t unk_761[3]; - CEntitySAInterface* lastDamagedEntity; - std::int16_t unk_768; - - CVector vecTurretOffset; - float fTurretAngleA; - float fTurretAngleB; - std::uint32_t turretPosnMode; - std::uint32_t turretAmmo; - - void* pCoverPoint; // CCoverPoint* - void* pEnex; // CEntryExit* - float fRemovalDistMultiplier; - std::int16_t specialModelIndex; // StreamedScriptBrainToLoad - - std::int16_t unk_796; - int unk_798; + CPedSoundEntitySAInterface pedAudio; // CAEPedAudioEntity + CPedSoundSAInterface pedSound; // CAEPedSpeechAudioEntity + CPedWeaponAudioEntitySAInterface weaponAudioEntity; // CAEPedWeaponAudioEntity + + std::uint8_t unk_43C[36]; + CPedSAInterface* roadRageWith; + std::uint8_t unk_464[8]; + + CPedFlags pedFlags; + CPedIntelligenceSAInterface* pPedIntelligence; + CPlayerPedDataSAInterface* pPlayerData; + + std::uint8_t createdBy; + void* pedNodes[19]; // AnimBlendFrameData* + int iMoveAnimGroup; + CVector2D vecAnimMovingShiftLocal; + CPedAcquaintanceSAInterface pedAcquaintance; + + RpClump* pWeaponObject; + RwFrame* pGunflashObject; + RpClump* pGogglesObject; + bool* pGogglesState; + + std::int16_t weaponGunflashStateRightHand; + std::int16_t weaponGunFlashAlphaProgMP1; + std::int16_t weaponGunflashStateLeftHand; + std::int16_t weaponGunFlashAlphaProgMP2; + + CPedIKSAInterface pedIK; + int unk_52C; + + int pedState; + PedMoveState::Enum moveState; + int swimmingMoveState; + + int unk_53C; + float fHealth; + float fMaxHealth; + float fArmor; + + std::uint32_t timeTillWeNeedThisPed; + CVector2D vecAnimMovingShift; + float fCurrentRotation; + float fTargetRotation; + float fRotationSpeed; + float fMoveAnim; + + CEntitySAInterface* pContactEntity; // m_standingOnEntity + CVector unk_56C; + CVector unk_578; + CEntitySAInterface* pLastContactEntity; // m_contactEntity + + CVehicleSAInterface* pLastVehicle; + CVehicleSAInterface* pVehicle; + CVehicleSAInterface* vehicleDeadInFrontOf; + + int unk_594; + int bPedType; // ped type? 0 = player, >1 = ped? + CPedStatSAInterface* pPedStats; + CWeaponSAInterface Weapons[WEAPONSLOT_MAX]; + eWeaponType savedWeapon; + eWeaponType delayedWeapon; + std::uint32_t delayedWeaponAmmo; + std::uint8_t bCurrentWeaponSlot; + std::uint8_t weaponShootingRate; + std::uint8_t weaponAccuracy; + + CEntitySAInterface* pTargetedObject; + int unk_720; + int unk_724; + int unk_728; + + eWeaponSkill weaponSkill; + eFightingStyle bFightingStyle; + std::uint8_t bFightingStyleExtra; + std::uint8_t bPad7; + + CFireSAInterface* pFireOnPed; + float fireDamageMult; + + CEntitySAInterface* pLookAtEntity; + float fLookHeading; + + std::uint32_t weaponModelID; + int unk_744; + std::uint32_t lookTime; + int unk_74C; + std::uint32_t timeWhenDead; // death time in MS + std::uint8_t bodyPartToRemove; + std::int16_t unk_755; + std::int16_t moneyCount; + std::int16_t unk_758; + int unk_75C; + std::uint8_t lastWeaponDamage; + std::uint8_t unk_761[3]; + CEntitySAInterface* lastDamagedEntity; + std::int16_t unk_768; + + CVector vecTurretOffset; + float fTurretAngleA; + float fTurretAngleB; + std::uint32_t turretPosnMode; + std::uint32_t turretAmmo; + + void* pCoverPoint; // CCoverPoint* + void* pEnex; // CEntryExit* + float fRemovalDistMultiplier; + std::int16_t specialModelIndex; // StreamedScriptBrainToLoad + + std::int16_t unk_796; + int unk_798; }; static_assert(sizeof(CPedSAInterface) == 0x79C, "Invalid size for CPedSAInterface"); @@ -355,7 +355,7 @@ class CPedSA : public virtual CPed, public virtual CPhysicalSA CPedSAInterface* GetPedInterface() const noexcept { return static_cast(m_pInterface); } void Init(); - + void SetModelIndex(std::uint32_t modelIndex) override; bool InternalAttachEntityToEntity(DWORD entityInterface, const CVector* position, const CVector* rotation) override; @@ -384,8 +384,8 @@ class CPedSA : public virtual CPed, public virtual CPhysicalSA void SetIsStanding(bool standing) override; - std::uint32_t GetType() const noexcept override { return m_type; } - void SetType(std::uint32_t type) noexcept { m_type = type; } + std::uint32_t GetType() const noexcept override { return m_type; } + void SetType(std::uint32_t type) noexcept { m_type = type; } CPedIntelligence* GetPedIntelligence() const noexcept override { return m_pedIntelligence.get(); } CPedSound* GetPedSound() const noexcept override { return m_pedSound.get(); } @@ -409,7 +409,7 @@ class CPedSA : public virtual CPed, public virtual CPhysicalSA bool IsInWater() const override; std::uint32_t GetCantBeKnockedOffBike() const override { return GetPedInterface()->pedFlags.CantBeKnockedOffBike; } - void SetCantBeKnockedOffBike(std::uint32_t cantBeKnockedOffBike) override { GetPedInterface()->pedFlags.CantBeKnockedOffBike = cantBeKnockedOffBike; } + void SetCantBeKnockedOffBike(std::uint32_t cantBeKnockedOffBike) override { GetPedInterface()->pedFlags.CantBeKnockedOffBike = cantBeKnockedOffBike; } bool IsWearingGoggles() const override { return GetPedInterface()->pGogglesObject != nullptr; } void SetGogglesState(bool isWearingThem) override; @@ -425,14 +425,14 @@ class CPedSA : public virtual CPed, public virtual CPhysicalSA PedMoveState::Enum GetMoveState() const override { return GetPedInterface()->moveState; } - bool GetCanBeShotInVehicle() const override{ return GetPedInterface()->pedFlags.bCanBeShotInVehicle; } + bool GetCanBeShotInVehicle() const override { return GetPedInterface()->pedFlags.bCanBeShotInVehicle; } bool GetTestForShotInVehicle() const override { return GetPedInterface()->pedFlags.bTestForShotInVehicle; } void SetCanBeShotInVehicle(bool shot) override { GetPedInterface()->pedFlags.bCanBeShotInVehicle = shot; } void SetTestForShotInVehicle(bool test) override { GetPedInterface()->pedFlags.bTestForShotInVehicle = test; } std::uint8_t GetOccupiedSeat() const noexcept override { return m_occupiedSeat; } - void SetOccupiedSeat(std::uint8_t seat) noexcept override { m_occupiedSeat = seat; } + void SetOccupiedSeat(std::uint8_t seat) noexcept override { m_occupiedSeat = seat; } void RemoveBodyPart(std::uint8_t boneID, std::uint8_t direction) override; @@ -471,16 +471,16 @@ class CPedSA : public virtual CPed, public virtual CPhysicalSA std::unique_ptr GetPedIK() override { return std::make_unique(GetPedIKInterface()); } CEntitySAInterface* GetTargetedObject() const override { return GetPedInterface()->pTargetedObject; } - PedState GetPedState() const override { return static_cast(GetPedInterface()->pedState); } + PedState GetPedState() const override { return static_cast(GetPedInterface()->pedState); } - void GetAttachedSatchels(std::vector &satchelsList) const override; + void GetAttachedSatchels(std::vector& satchelsList) const override; void SetInWaterFlags(bool inWater) override; static void StaticSetHooks(); private: - void ApplySwimAndSlopeRotations(); + void ApplySwimAndSlopeRotations(); protected: int m_iCustomMoveAnim{0}; diff --git a/Client/game_sa/CPedSoundSA.h b/Client/game_sa/CPedSoundSA.h index 84abf355d37..00f91c6667f 100644 --- a/Client/game_sa/CPedSoundSA.h +++ b/Client/game_sa/CPedSoundSA.h @@ -18,20 +18,20 @@ class CPedSAInterface; -#define FUNC_CAEPedSound__GetVoice 0x4E3CD0 // 4E3CD0 ; public: static short __cdecl CAEPedSound::GetVoice(char *,short) -#define FUNC_CAEPedSound__GetAudioPedType 0x4E3C60 // 4E3C60 ; public: static short __cdecl CAEPedSound::GetAudioPedType(char *) -#define FUNC_CAEPedSound__SetPed 0x4E68D0 // 4E69D0 ; public: void __thiscall CAEPedSound::SetPed(CPedSAInterface *) -#define FUNC_CAEPedSound__EnablePedSpeech 0x4e3f70 -#define FUNC_CAEPedSound__DisablePedSpeech 0x4e56d0 -#define FUNC_CAEPedSound__IsSpeedDisabled 0x4e34d0 +#define FUNC_CAEPedSound__GetVoice 0x4E3CD0 // 4E3CD0 ; public: static short __cdecl CAEPedSound::GetVoice(char *,short) +#define FUNC_CAEPedSound__GetAudioPedType 0x4E3C60 // 4E3C60 ; public: static short __cdecl CAEPedSound::GetAudioPedType(char *) +#define FUNC_CAEPedSound__SetPed 0x4E68D0 // 4E69D0 ; public: void __thiscall CAEPedSound::SetPed(CPedSAInterface *) +#define FUNC_CAEPedSound__EnablePedSpeech 0x4e3f70 +#define FUNC_CAEPedSound__DisablePedSpeech 0x4e56d0 +#define FUNC_CAEPedSound__IsSpeedDisabled 0x4e34d0 -#define VAR_CAEPedSound__VoiceTypeNames 0x8C8108 // Array of 6 pointers to strings +#define VAR_CAEPedSound__VoiceTypeNames 0x8C8108 // Array of 6 pointers to strings -#define VAR_CAEPedSound__VoiceNames_GEN 0x8AE6A8 // 20 bytes per voice name -#define VAR_CAEPedSound__VoiceNames_EMG 0x8BA0D8 -#define VAR_CAEPedSound__VoiceNames_PLAYER 0x8BBD40 -#define VAR_CAEPedSound__VoiceNames_GANG 0x8BE1A8 -#define VAR_CAEPedSound__VoiceNames_GFD 0x8C4120 +#define VAR_CAEPedSound__VoiceNames_GEN 0x8AE6A8 // 20 bytes per voice name +#define VAR_CAEPedSound__VoiceNames_EMG 0x8BA0D8 +#define VAR_CAEPedSound__VoiceNames_PLAYER 0x8BBD40 +#define VAR_CAEPedSound__VoiceNames_GANG 0x8BE1A8 +#define VAR_CAEPedSound__VoiceNames_GFD 0x8C4120 #define NUM_PED_VOICE_TYPES 5 @@ -45,11 +45,11 @@ enum ePedVoiceType : std::uint16_t PED_TYPE_SPC }; -#define NUM_GEN_VOICES 209 -#define NUM_EMG_VOICES 46 -#define NUM_PLAYER_VOICES 20 -#define NUM_GANG_VOICES 52 -#define NUM_GFD_VOICES 18 +#define NUM_GEN_VOICES 209 +#define NUM_EMG_VOICES 46 +#define NUM_PLAYER_VOICES 20 +#define NUM_GANG_VOICES 52 +#define NUM_GFD_VOICES 18 typedef struct { @@ -114,7 +114,7 @@ static_assert(sizeof(CPedSoundEntitySAInterface) == 0x15C, "Invalid size for CPe class CPedWeaponAudioEntitySAInterface : public CAEWeaponAudioEntitySAInterface { public: - bool m_bIsInitialised; + bool m_bIsInitialised; CPedSAInterface* m_ped; }; static_assert(sizeof(CPedWeaponAudioEntitySAInterface) == 0xA8, "Invalid size for CPedWeaponAudioEntitySAInterface"); diff --git a/Client/game_sa/CPhysicalSA.cpp b/Client/game_sa/CPhysicalSA.cpp index 09341a20d83..5960d471a52 100644 --- a/Client/game_sa/CPhysicalSA.cpp +++ b/Client/game_sa/CPhysicalSA.cpp @@ -31,7 +31,7 @@ CRect* CPhysicalSAInterface::GetBoundRect_(CRect* pRect) float fRadius = pModelInfo->pColModel->m_sphere.m_radius; *pRect = CRect(boundCentre.fX - fRadius, boundCentre.fY - fRadius, boundCentre.fX + fRadius, boundCentre.fY + fRadius); - pRect->FixIncorrectTopLeft(); // Fix #1613: custom map collision crashes in CPhysical class (infinite loop) + pRect->FixIncorrectTopLeft(); // Fix #1613: custom map collision crashes in CPhysical class (infinite loop) return pRect; } diff --git a/Client/game_sa/CPhysicalSA.h b/Client/game_sa/CPhysicalSA.h index c1de3599375..c81fc318639 100644 --- a/Client/game_sa/CPhysicalSA.h +++ b/Client/game_sa/CPhysicalSA.h @@ -18,26 +18,26 @@ class CColPointSAInterface; -#define FUNC_GetMoveSpeed 0x404460 -#define FUNC_GetTurnSpeed 0x470030 -#define FUNC_ProcessCollision 0x54DFB0 -#define FUNC_AttachEntityToEntity 0x54D570 -#define FUNC_DetatchEntityFromEntity 0x5442F0 -#define FUNC_CPhysical_AddToMovingList 0x542800 -#define FUNC_CPhysical_RemoveFromMovingList 0x542860 +#define FUNC_GetMoveSpeed 0x404460 +#define FUNC_GetTurnSpeed 0x470030 +#define FUNC_ProcessCollision 0x54DFB0 +#define FUNC_AttachEntityToEntity 0x54D570 +#define FUNC_DetatchEntityFromEntity 0x5442F0 +#define FUNC_CPhysical_AddToMovingList 0x542800 +#define FUNC_CPhysical_RemoveFromMovingList 0x542860 -#define PHYSICAL_MAXNOOFCOLLISIONRECORDS 6 -#define PHYSICAL_MAXMASS 99999.0 +#define PHYSICAL_MAXNOOFCOLLISIONRECORDS 6 +#define PHYSICAL_MAXMASS 99999.0 class CPhysicalSAInterface : public CEntitySAInterface { virtual std::int32_t ProcessEntityCollision(CEntitySAInterface* entity, CColPointSAInterface* colPoint) = 0; public: - float pad1; // 56 - uint32 pad2; // 60 + float pad1; // 56 + uint32 pad2; // 60 - uint32 b0x01 : 1; // 64 + uint32 b0x01 : 1; // 64 uint32 bApplyGravity : 1; uint32 bDisableFriction : 1; uint32 bCollidable : 1; @@ -46,17 +46,17 @@ class CPhysicalSAInterface : public CEntitySAInterface uint32 b0x40 : 1; uint32 b0x80 : 1; - uint32 bSubmergedInWater : 1; // 65 + uint32 bSubmergedInWater : 1; // 65 uint32 bOnSolidSurface : 1; uint32 bBroken : 1; - uint32 b0x800 : 1; // ref @ 0x6F5CF0 - uint32 b0x1000 : 1; // - uint32 bDontApplySpeed : 1; // - uint32 b0x4000 : 1; // - uint32 b0x8000 : 1; // - - uint32 b0x10000 : 1; // 66 - uint32 b0x20000 : 1; // ref @ CPhysical__processCollision + uint32 b0x800 : 1; // ref @ 0x6F5CF0 + uint32 b0x1000 : 1; // + uint32 bDontApplySpeed : 1; // + uint32 b0x4000 : 1; // + uint32 b0x8000 : 1; // + + uint32 b0x10000 : 1; // 66 + uint32 b0x20000 : 1; // ref @ CPhysical__processCollision uint32 bBulletProof : 1; uint32 bFireProof : 1; uint32 bCollisionProof : 1; @@ -64,7 +64,7 @@ class CPhysicalSAInterface : public CEntitySAInterface uint32 bInvulnerable : 1; uint32 bExplosionProof : 1; - uint32 b0x1000000 : 1; // 67 + uint32 b0x1000000 : 1; // 67 uint32 bAttachedToEntity : 1; uint32 b0x4000000 : 1; uint32 bTouchingWater : 1; @@ -73,44 +73,44 @@ class CPhysicalSAInterface : public CEntitySAInterface uint32 b0x40000000 : 1; uint32 b0x80000000 : 1; - CVector m_vecLinearVelocity; // 68 - CVector m_vecAngularVelocity; // 80 - CVector m_vecCollisionLinearVelocity; // 92 - CVector m_vecCollisionAngularVelocity; // 104 - CVector m_vecOffsetUnk5; // 116 - CVector m_vecOffsetUnk6; // 128 - float m_fMass; // 140 - float m_fTurnMass; // 144 - float m_pad1; // 148 - float m_fAirResistance; // 152 - float m_fElasticity; // 156 - float m_fBuoyancyConstant; // 160 - CVector m_vecCenterOfMass; // 164 - uint32* m_pCollisionList; // 176 - uint32* m_pMovingList; // 180 - uint8 m_ucColFlag1; // 184 - uint8 m_ucCollisionState; // 185 - uint8 m_ucCollisionContactSurfaceType; // 186 - uint8 m_ucColFlag4; // 187 - CEntity* pLastContactedEntity[4]; // 188 - float m_field_cc; // 204 - float m_pad4c; // 208 - float m_pad4d; // 212 - float m_fDamageImpulseMagnitude; // 216 - CEntitySAInterface* m_pCollidedEntity; // 220 - CVector m_vecCollisionImpactVelocity; // 224 - CVector m_vecCollisionPosition; // 236 - uint16 m_usPieceType; // 248 - uint16 m_pad3; // 250 - CEntitySAInterface* m_pAttachedEntity; // 252 - CVector m_vecAttachedOffset; // 256 - CVector m_vecAttachedRotation; // 268 - CVector m_vecUnk; // 280 - uint32 m_pad4; // 292 - CPtrNodeDoubleLink* m_pControlCodeNodeLink; // 296 - float m_fLighting; // 300 surface brightness - float m_fLighting2; // 304 dynamic lighting (unused, always set to 0 in the GTA code) - class CShadowDataSA* m_pShadowData; // 308 + CVector m_vecLinearVelocity; // 68 + CVector m_vecAngularVelocity; // 80 + CVector m_vecCollisionLinearVelocity; // 92 + CVector m_vecCollisionAngularVelocity; // 104 + CVector m_vecOffsetUnk5; // 116 + CVector m_vecOffsetUnk6; // 128 + float m_fMass; // 140 + float m_fTurnMass; // 144 + float m_pad1; // 148 + float m_fAirResistance; // 152 + float m_fElasticity; // 156 + float m_fBuoyancyConstant; // 160 + CVector m_vecCenterOfMass; // 164 + uint32* m_pCollisionList; // 176 + uint32* m_pMovingList; // 180 + uint8 m_ucColFlag1; // 184 + uint8 m_ucCollisionState; // 185 + uint8 m_ucCollisionContactSurfaceType; // 186 + uint8 m_ucColFlag4; // 187 + CEntity* pLastContactedEntity[4]; // 188 + float m_field_cc; // 204 + float m_pad4c; // 208 + float m_pad4d; // 212 + float m_fDamageImpulseMagnitude; // 216 + CEntitySAInterface* m_pCollidedEntity; // 220 + CVector m_vecCollisionImpactVelocity; // 224 + CVector m_vecCollisionPosition; // 236 + uint16 m_usPieceType; // 248 + uint16 m_pad3; // 250 + CEntitySAInterface* m_pAttachedEntity; // 252 + CVector m_vecAttachedOffset; // 256 + CVector m_vecAttachedRotation; // 268 + CVector m_vecUnk; // 280 + uint32 m_pad4; // 292 + CPtrNodeDoubleLink* m_pControlCodeNodeLink; // 296 + float m_fLighting; // 300 surface brightness + float m_fLighting2; // 304 dynamic lighting (unused, always set to 0 in the GTA code) + class CShadowDataSA* m_pShadowData; // 308 CRect* GetBoundRect_(CRect* pRect); static void StaticSetHooks(); diff --git a/Client/game_sa/CPickupSA.h b/Client/game_sa/CPickupSA.h index 20ebb55b835..fd0bcc7937a 100644 --- a/Client/game_sa/CPickupSA.h +++ b/Client/game_sa/CPickupSA.h @@ -17,26 +17,26 @@ class CObjectSAInterface; class CObjectSA; -#define FUNC_GIVEUSAPICKUP 0x4567e0 -#define FUNC_CPickup_Remove 0x4556C0 +#define FUNC_GIVEUSAPICKUP 0x4567e0 +#define FUNC_CPickup_Remove 0x4556C0 class CPickupSAInterface { public: - float CurrentValue; // For the revenue pickups 0 - CObjectSAInterface* pObject; // 4 - long MonetaryValue; // 8 - DWORD RegenerationTime; // 12 - short CoorsX, CoorsY, CoorsZ; // 16 // 18 // 20 - WORD MoneyPerDay; // 22 - WORD MI; // 24 - WORD ReferenceIndex; // 26 - BYTE Type; // 28 - BYTE State : 1; // 29 + float CurrentValue; // For the revenue pickups 0 + CObjectSAInterface* pObject; // 4 + long MonetaryValue; // 8 + DWORD RegenerationTime; // 12 + short CoorsX, CoorsY, CoorsZ; // 16 // 18 // 20 + WORD MoneyPerDay; // 22 + WORD MI; // 24 + WORD ReferenceIndex; // 26 + BYTE Type; // 28 + BYTE State : 1; // 29 BYTE bNoAmmo : 1; BYTE bHelpMessageDisplayed : 1; - BYTE bIsPickupNearby : 1; // If the pickup is nearby it will get an object and it will get updated. - BYTE TextIndex : 3; // What text label do we print out above it. + BYTE bIsPickupNearby : 1; // If the pickup is nearby it will get an object and it will get updated. + BYTE TextIndex : 3; // What text label do we print out above it. }; class CPickupSA : public CPickup @@ -47,29 +47,29 @@ class CPickupSA : public CPickup public: CPickupSA(CPickupSAInterface* pickupInterface); - CPickupSAInterface* GetInterface() { return internalInterface; }; // not to be exported + CPickupSAInterface* GetInterface() { return internalInterface; }; // not to be exported CObject* GetObject() { return object; }; void SetPosition(CVector* vecPosition); CVector* GetPosition(CVector* vecPosition); PickupType GetType(); - void SetType(PickupType type); - float GetCurrentValue(); - void SetCurrentValue(float fCurrentValue); - void SetRegenerationTime(DWORD dwTime); - void SetMoneyPerDay(WORD wMoneyPerDay); - WORD GetMoneyPerDay(); - WORD GetModel(); - void SetModel(WORD wModelIndex); // do not export + void SetType(PickupType type); + float GetCurrentValue(); + void SetCurrentValue(float fCurrentValue); + void SetRegenerationTime(DWORD dwTime); + void SetMoneyPerDay(WORD wMoneyPerDay); + WORD GetMoneyPerDay(); + WORD GetModel(); + void SetModel(WORD wModelIndex); // do not export PickupState GetState(); - void SetState(PickupState bState); - BYTE GetAmmo(); - void SetAmmo(BYTE bAmmo); - long GetMonetaryValue(); - void SetMonetaryValue(long lMonetaryValue); - BYTE IsNearby(); - bool GiveUsAPickUpObject(int ForcedObjectIndex = -1); - void GetRidOfObjects(); - void Remove(); + void SetState(PickupState bState); + BYTE GetAmmo(); + void SetAmmo(BYTE bAmmo); + long GetMonetaryValue(); + void SetMonetaryValue(long lMonetaryValue); + BYTE IsNearby(); + bool GiveUsAPickUpObject(int ForcedObjectIndex = -1); + void GetRidOfObjects(); + void Remove(); }; diff --git a/Client/game_sa/CPickupsSA.cpp b/Client/game_sa/CPickupsSA.cpp index 71bcee5a96f..c7faf6d9e4f 100644 --- a/Client/game_sa/CPickupsSA.cpp +++ b/Client/game_sa/CPickupsSA.cpp @@ -74,7 +74,7 @@ CPickup* CPickupsSA::CreatePickup(CVector* position, DWORD ModelIndex, PickupTyp } if (FreeSlot >= MAX_PICKUPS) - { // In that case use the first PICKUP_ONCE_TIMEOUT + { // In that case use the first PICKUP_ONCE_TIMEOUT FreeSlot = 0; while (FreeSlot < MAX_PICKUPS && Pickups[FreeSlot]->GetInterface()->Type != (BYTE)PickupType::PICKUP_ONCE_TIMEOUT && Pickups[FreeSlot]->GetInterface()->Type != (BYTE)PickupType::PICKUP_ONCE_TIMEOUT_SLOW) @@ -85,8 +85,8 @@ CPickup* CPickupsSA::CreatePickup(CVector* position, DWORD ModelIndex, PickupTyp // We need to tidy up the objects that go with this pickup if (FreeSlot >= MAX_PICKUPS) - { // Couldn't find one. Let's just hope we don't break anything in the scripts. - // ASSERTMSG(0, "Ran out of pickups"); + { // Couldn't find one. Let's just hope we don't break anything in the scripts. + // ASSERTMSG(0, "Ran out of pickups"); return (CPickup*)NULL; } else @@ -118,17 +118,17 @@ CPickup* CPickupsSA::CreatePickup(CVector* position, DWORD ModelIndex, PickupTyp } if (Type == PickupType::PICKUP_MONEY) { - pickup->SetRegenerationTime(pGame->GetSystemTime() + 30000); // Money stays for 30 secs + pickup->SetRegenerationTime(pGame->GetSystemTime() + 30000); // Money stays for 30 secs } if (Type == PickupType::PICKUP_MINE_INACTIVE || Type == PickupType::PICKUP_MINE_ARMED) { pickup->SetType(PickupType::PICKUP_MINE_INACTIVE); - pickup->SetRegenerationTime(pGame->GetSystemTime() + 1500); // Mines get activated after 2 secs + pickup->SetRegenerationTime(pGame->GetSystemTime() + 1500); // Mines get activated after 2 secs } if (Type == PickupType::PICKUP_NAUTICAL_MINE_INACTIVE || Type == PickupType::PICKUP_NAUTICAL_MINE_ARMED) { pickup->SetType(PickupType::PICKUP_NAUTICAL_MINE_INACTIVE); - pickup->GetInterface()->RegenerationTime = pGame->GetSystemTime() + 1500; // Mines get activated after 2 secs + pickup->GetInterface()->RegenerationTime = pGame->GetSystemTime() + 1500; // Mines get activated after 2 secs } pickup->SetModel((WORD)ModelIndex); diff --git a/Client/game_sa/CPickupsSA.h b/Client/game_sa/CPickupsSA.h index 5c5b82a4462..9025f806abe 100644 --- a/Client/game_sa/CPickupsSA.h +++ b/Client/game_sa/CPickupsSA.h @@ -15,11 +15,11 @@ class CPickupSA; -#define MAX_PICKUPS 620 -#define MAX_PICKUPS_ALWAYS_UPDATED 16 +#define MAX_PICKUPS 620 +#define MAX_PICKUPS_ALWAYS_UPDATED 16 -#define ARRAY_PICKUPS 0x9788C0 -#define FUNC_CPickups__Update 0x458DE0 +#define ARRAY_PICKUPS 0x9788C0 +#define FUNC_CPickups__Update 0x458DE0 class CPickupsSA : public CPickups { diff --git a/Client/game_sa/CPlaceableSA.h b/Client/game_sa/CPlaceableSA.h index d2b713da734..858263e1de6 100644 --- a/Client/game_sa/CPlaceableSA.h +++ b/Client/game_sa/CPlaceableSA.h @@ -10,7 +10,7 @@ #include #include -class CSimpleTransformSAInterface // 16 bytes +class CSimpleTransformSAInterface // 16 bytes { public: CVector m_translate; @@ -33,6 +33,6 @@ class CPlaceableSAInterface public: CSimpleTransformSAInterface m_transform; - CMatrix_Padded* matrix; // This is actually XYZ*, change later + CMatrix_Padded* matrix; // This is actually XYZ*, change later }; static_assert(sizeof(CPlaceableSAInterface) == 0x18, "Invalid size for CPlaceableSAInterface"); diff --git a/Client/game_sa/CPlaneSA.h b/Client/game_sa/CPlaneSA.h index 9d311a1ccd5..e59b7f50641 100644 --- a/Client/game_sa/CPlaneSA.h +++ b/Client/game_sa/CPlaneSA.h @@ -26,7 +26,7 @@ class CPlaneSAInterface : public CAutomobileSAInterface float m_fAccelerationBreakStatusPrev; float m_fSteeringFactor; float field_9A0; - float m_planeCreationHeading; // The heading when plane is created or placed on road properly + float m_planeCreationHeading; // The heading when plane is created or placed on road properly float m_maxAltitude; float m_altitude; float m_minAltitude; @@ -34,7 +34,7 @@ class CPlaneSAInterface : public CAutomobileSAInterface float m_planeHeadingPrev; float m_forwardZ; uint32_t m_nStartedFlyingTime; - float m_fPropSpeed; // Rotor speed 0x09C4 + float m_fPropSpeed; // Rotor speed 0x09C4 float field_9C8; float m_fLandingGearStatus; int32_t m_planeDamageWave; diff --git a/Client/game_sa/CPlantManagerSA.cpp b/Client/game_sa/CPlantManagerSA.cpp index aef1849aae9..f7e5b2f9d8a 100644 --- a/Client/game_sa/CPlantManagerSA.cpp +++ b/Client/game_sa/CPlantManagerSA.cpp @@ -9,14 +9,15 @@ class CPlantColEntEntry { public: CEntitySAInterface* m_Entity; - CPlantLocTri** m_Objects; - uint16 m_numTriangles; - CPlantColEntEntry* m_NextEntry; - CPlantColEntEntry* m_PrevEntry; + CPlantLocTri** m_Objects; + uint16 m_numTriangles; + CPlantColEntEntry* m_NextEntry; + CPlantColEntEntry* m_PrevEntry; public: - void ReleaseEntry() { - using CPlantColEntEntry_ReleaseEntry = void* ( __thiscall *)(CPlantColEntEntry*); + void ReleaseEntry() + { + using CPlantColEntEntry_ReleaseEntry = void*(__thiscall*)(CPlantColEntEntry*); ((CPlantColEntEntry_ReleaseEntry)0x5DB8A0)(this); }; }; diff --git a/Client/game_sa/CPlayerInfoSA.h b/Client/game_sa/CPlayerInfoSA.h index ed618d5ad83..bcad187ce8e 100644 --- a/Client/game_sa/CPlayerInfoSA.h +++ b/Client/game_sa/CPlayerInfoSA.h @@ -25,7 +25,7 @@ class CPlayerCrossHairSAInterface { public: bool bActivated; - float TargetX, TargetY; // -1 ... 1 on screen + float TargetX, TargetY; // -1 ... 1 on screen }; // Note: Information below may be incorrect. Please check before using. @@ -34,50 +34,50 @@ class CPlayerCrossHairSAInterface class CPlayerPedDataSAInterface { public: - CWantedSAInterface* m_Wanted; // 0 - CPedClothesDesc* m_pClothes; // 4 + CWantedSAInterface* m_Wanted; // 0 + CPedClothesDesc* m_pClothes; // 4 - CPedSAInterface* m_ArrestingOfficer; // actually CCopPed * // 8 + CPedSAInterface* m_ArrestingOfficer; // actually CCopPed * // 8 - CVector2D m_vecFightMovement; // 12 - float m_moveBlendRatio; // 20 + CVector2D m_vecFightMovement; // 12 + float m_moveBlendRatio; // 20 float m_fTimeCanRun; float m_fSprintEnergy; - BYTE m_nChosenWeapon; // 28 - BYTE m_nCarDangerCounter; // 29 - BYTE m_pad0; // 30 - BYTE m_pad1; // 31 - long m_nStandStillTimer; // 32 - DWORD m_nHitAnimDelayTimer; // 36 - float m_fAttackButtonCounter; // 40 - CAutomobileSAInterface* m_pDangerCar; // 44 + BYTE m_nChosenWeapon; // 28 + BYTE m_nCarDangerCounter; // 29 + BYTE m_pad0; // 30 + BYTE m_pad1; // 31 + long m_nStandStillTimer; // 32 + DWORD m_nHitAnimDelayTimer; // 36 + float m_fAttackButtonCounter; // 40 + CAutomobileSAInterface* m_pDangerCar; // 44 - DWORD m_bStoppedMoving : 1; // 48 + DWORD m_bStoppedMoving : 1; // 48 DWORD m_bAdrenaline : 1; - DWORD m_bHaveTargetSelected : 1; // Needed to work out whether we lost target this frame + DWORD m_bHaveTargetSelected : 1; // Needed to work out whether we lost target this frame DWORD m_bFreeAiming : 1; DWORD bCanBeDamaged : 1; - DWORD bAllMeleeAttackPtsBlocked : 1; // if all of m_pMeleeAttackers[] is blocked by collision, just attack straight ahead - DWORD m_JustBeenSnacking : 1; // If this bit is true we have just bought something from a vending machine - DWORD m_bRequireHandleBreath : 1; // + DWORD bAllMeleeAttackPtsBlocked : 1; // if all of m_pMeleeAttackers[] is blocked by collision, just attack straight ahead + DWORD m_JustBeenSnacking : 1; // If this bit is true we have just bought something from a vending machine + DWORD m_bRequireHandleBreath : 1; // // The player runs a group. Player is the leader. Player can go up to gang-members and make them join his group. // 50 - DWORD m_GroupStuffDisabled : 1; // 52 // if this is true the player can't recrout or give his group commands. - DWORD m_GroupAlwaysFollow : 1; // The group is told to always follow the player (used for girlfriend missions) - DWORD m_GroupNeverFollow : 1; // The group is told to always follow the player (used for girlfriend missions) - DWORD m_bInVehicleDontAllowWeaponChange : 1; // stop weapon change once driveby weapon has been given - DWORD m_bRenderWeapon : 1; // set to false during cutscenes so that knuckledusters are not rendered + DWORD m_GroupStuffDisabled : 1; // 52 // if this is true the player can't recrout or give his group commands. + DWORD m_GroupAlwaysFollow : 1; // The group is told to always follow the player (used for girlfriend missions) + DWORD m_GroupNeverFollow : 1; // The group is told to always follow the player (used for girlfriend missions) + DWORD m_bInVehicleDontAllowWeaponChange : 1; // stop weapon change once driveby weapon has been given + DWORD m_bRenderWeapon : 1; // set to false during cutscenes so that knuckledusters are not rendered - long m_PlayerGroup; // 60 + long m_PlayerGroup; // 60 - DWORD m_AdrenalineEndTime; // 64 - BYTE m_nDrunkenness; // 68 - bool m_bFadeDrunkenness; // 69 - BYTE m_nDrugLevel; // 70 - BYTE m_nScriptLimitToGangSize; // 71 + DWORD m_AdrenalineEndTime; // 64 + BYTE m_nDrunkenness; // 68 + bool m_bFadeDrunkenness; // 69 + BYTE m_nDrugLevel; // 70 + BYTE m_nScriptLimitToGangSize; // 71 - float m_fBreath; // for holding breath (ie underwater) // 72 + float m_fBreath; // for holding breath (ie underwater) // 72 // once a set of melee weapon anims have been loaded and referenced for the player // we need to remember what we've referenced @@ -90,7 +90,7 @@ class CPlayerPedDataSAInterface float m_fSkateBoardSpeed; float m_fSkateBoardLean; - DWORD* m_pSpecialAtomic; // was rpAtomic + DWORD* m_pSpecialAtomic; // was rpAtomic float m_fGunSpinSpeed; float m_fGunSpinAngle; @@ -139,48 +139,48 @@ class CPlayerInfoSAInterface PLAYERSTATE_LEFTGAME }; - class CPlayerPedSAInterface* pPed; // Pointer to the player ped (should always be set) - CPlayerPedDataSAInterface PlayerPedData; // instance of player variables - CVehicleSAInterface* pRemoteVehicle; // Pointer to vehicle player is driving remotely at the moment.(NULL if on foot) - CVehicleSAInterface* pSpecCar; // which car is using the special collision model - long Score; // Points for this player - long DisplayScore; // Points as they would be displayed - long CollectablesPickedUp; // How many bags of sugar do we have - long TotalNumCollectables; // How many bags of sugar are there to be had in the game + class CPlayerPedSAInterface* pPed; // Pointer to the player ped (should always be set) + CPlayerPedDataSAInterface PlayerPedData; // instance of player variables + CVehicleSAInterface* pRemoteVehicle; // Pointer to vehicle player is driving remotely at the moment.(NULL if on foot) + CVehicleSAInterface* pSpecCar; // which car is using the special collision model + long Score; // Points for this player + long DisplayScore; // Points as they would be displayed + long CollectablesPickedUp; // How many bags of sugar do we have + long TotalNumCollectables; // How many bags of sugar are there to be had in the game - DWORD nLastBumpPlayerCarTimer; // Keeps track of when the last ped bumped into the player car + DWORD nLastBumpPlayerCarTimer; // Keeps track of when the last ped bumped into the player car - DWORD TaxiTimer; // Keeps track of how long the player has been in a taxi with a passenger (in msecs) - DWORD vehicle_time_counter; // keeps track of how long player has been in car for driving skill - bool bTaxiTimerScore; // If TRUE then add 1 to score for each second that the player is driving a taxi - bool m_bTryingToExitCar; // if player holds exit car button, want to trigger getout once car slowed enough - // with a passenger + DWORD TaxiTimer; // Keeps track of how long the player has been in a taxi with a passenger (in msecs) + DWORD vehicle_time_counter; // keeps track of how long player has been in car for driving skill + bool bTaxiTimerScore; // If TRUE then add 1 to score for each second that the player is driving a taxi + bool m_bTryingToExitCar; // if player holds exit car button, want to trigger getout once car slowed enough + // with a passenger - CVehicleSAInterface* pLastTargetVehicle; // Last vehicle player tried to enter. + CVehicleSAInterface* pLastTargetVehicle; // Last vehicle player tried to enter. - BYTE PlayerState; // What's going on. + BYTE PlayerState; // What's going on. bool bAfterRemoteVehicleExplosion; bool bCreateRemoteVehicleExplosion; bool bFadeAfterRemoteVehicleExplosion; DWORD TimeOfRemoteVehicleExplosion; - DWORD LastTimeEnergyLost; // To make numbers flash on the HUD + DWORD LastTimeEnergyLost; // To make numbers flash on the HUD DWORD LastTimeArmourLost; - DWORD LastTimeBigGunFired; // Tank guns etc - DWORD TimesUpsideDownInARow; // Make car blow up if car upside down - DWORD TimesStuckInARow; // Make car blow up if player cannot get out. + DWORD LastTimeBigGunFired; // Tank guns etc + DWORD TimesUpsideDownInARow; // Make car blow up if car upside down + DWORD TimesStuckInARow; // Make car blow up if player cannot get out. // working counters to calculate how long player managed stuff - DWORD nCarTwoWheelCounter; // how long has player's car been on two wheels + DWORD nCarTwoWheelCounter; // how long has player's car been on two wheels float fCarTwoWheelDist; - DWORD nCarLess3WheelCounter; // how long has player's car been on less than 3 wheels - DWORD nBikeRearWheelCounter; // how long has player's bike been on rear wheel only + DWORD nCarLess3WheelCounter; // how long has player's car been on less than 3 wheels + DWORD nBikeRearWheelCounter; // how long has player's bike been on rear wheel only float fBikeRearWheelDist; - DWORD nBikeFrontWheelCounter; // how long has player's bike been on front wheel only + DWORD nBikeFrontWheelCounter; // how long has player's bike been on front wheel only float fBikeFrontWheelDist; - DWORD nTempBufferCounter; // so wheels can leave the ground for a few frames without stopping above counters + DWORD nTempBufferCounter; // so wheels can leave the ground for a few frames without stopping above counters // best values for the script to check - will be zero most of the time, only value // when finished trick - script should retreve value then reset to zero DWORD nBestCarTwoWheelsTimeMs; @@ -191,14 +191,14 @@ class CPlayerInfoSAInterface float fBestBikeStoppieDistM; WORD CarDensityForCurrentZone; - float RoadDensityAroundPlayer; // 1.0f for an average city. + float RoadDensityAroundPlayer; // 1.0f for an average city. DWORD TimeOfLastCarExplosionCaused; long ExplosionMultiplier; - long HavocCaused; // A counter going up when the player does bad stuff. - short TimeLastEaten; // A counter that starts at 5000, increases by 1 every minute + long HavocCaused; // A counter going up when the player does bad stuff. + short TimeLastEaten; // A counter that starts at 5000, increases by 1 every minute - float CurrentChaseValue; // How 'ill' is the chase at the moment + float CurrentChaseValue; // How 'ill' is the chase at the moment // 'Special' abilities that gets awarded during the game bool DoesNotGetTired; @@ -208,8 +208,8 @@ class CPlayerInfoSAInterface BYTE MaxArmour; // Get-out-of-jail-free & Free-medical-care cards - bool bGetOutOfJailFree; // Player doesn't lose money/weapons next time arrested - bool bFreeHealthCare; // Player doesn't lose money nexed time patched up at hospital + bool bGetOutOfJailFree; // Player doesn't lose money/weapons next time arrested + bool bFreeHealthCare; // Player doesn't lose money nexed time patched up at hospital bool bCanDoDriveBy; @@ -235,7 +235,7 @@ class CPlayerInfoSA : public CPlayerInfo CPlayerInfoSA(CPlayerInfoSAInterface* playerInfoInterface) { internalInterface = playerInfoInterface; - wanted = NULL; // we can't init it yet, as our interface hasn't been inited yet + wanted = NULL; // we can't init it yet, as our interface hasn't been inited yet } ~CPlayerInfoSA() @@ -261,13 +261,13 @@ class CPlayerInfoSA : public CPlayerInfo byte GetCamDrunkLevel(); void SetCamDrunkLevel(byte level); - DWORD GetCarTwoWheelCounter() { return internalInterface->nCarTwoWheelCounter; } - float GetCarTwoWheelDist() { return internalInterface->fCarTwoWheelDist; } - DWORD GetCarLess3WheelCounter() { return internalInterface->nCarLess3WheelCounter; } - DWORD GetBikeRearWheelCounter() { return internalInterface->nBikeRearWheelCounter; } - float GetBikeRearWheelDist() { return internalInterface->fBikeRearWheelDist; } - DWORD GetBikeFrontWheelCounter() { return internalInterface->nBikeFrontWheelCounter; } - float GetBikeFrontWheelDist() { return internalInterface->fBikeFrontWheelDist; } + DWORD GetCarTwoWheelCounter() { return internalInterface->nCarTwoWheelCounter; } + float GetCarTwoWheelDist() { return internalInterface->fCarTwoWheelDist; } + DWORD GetCarLess3WheelCounter() { return internalInterface->nCarLess3WheelCounter; } + DWORD GetBikeRearWheelCounter() { return internalInterface->nBikeRearWheelCounter; } + float GetBikeRearWheelDist() { return internalInterface->fBikeRearWheelDist; } + DWORD GetBikeFrontWheelCounter() { return internalInterface->nBikeFrontWheelCounter; } + float GetBikeFrontWheelDist() { return internalInterface->fBikeFrontWheelDist; } std::uint8_t GetMaxHealth() const { return internalInterface->MaxHealth; } std::uint8_t GetMaxArmor() const { return internalInterface->MaxArmour; } }; diff --git a/Client/game_sa/CPlayerPedSA.cpp b/Client/game_sa/CPlayerPedSA.cpp index 9e5faf32423..80df2469a41 100644 --- a/Client/game_sa/CPlayerPedSA.cpp +++ b/Client/game_sa/CPlayerPedSA.cpp @@ -54,7 +54,7 @@ CPlayerPedSA::CPlayerPedSA(unsigned int nModelIndex) SetInterface((CEntitySAInterface*)dwPedPointer); - Init(); // init our interfaces + Init(); // init our interfaces CPoolsSA* pools = (CPoolsSA*)pGame->GetPools(); CWorldSA* world = (CWorldSA*)pGame->GetWorld(); @@ -267,7 +267,7 @@ void CPlayerPedSA::SetMoveAnim(eMoveAnim iAnimGroup) if (pAnimBlock && !pAnimBlock->IsLoaded()) { pAnimBlock->Request(BLOCKING, true); - MapInsert(ms_DoneAnimBlockRefMap, strBlockName); // Request() adds a ref for us + MapInsert(ms_DoneAnimBlockRefMap, strBlockName); // Request() adds a ref for us } // Load fail? @@ -446,9 +446,9 @@ __declspec(noinline) int _cdecl OnCPlayerPed_ProcessAnimGroups_Mid(CPlayerPedSAI } // Hook info -#define HOOKPOS_CPlayerPed_ProcessAnimGroups_Mid 0x0609A44 -#define HOOKSIZE_CPlayerPed_ProcessAnimGroups_Mid 6 -DWORD RETURN_CPlayerPed_ProcessAnimGroups_Mid = 0x0609A4A; +#define HOOKPOS_CPlayerPed_ProcessAnimGroups_Mid 0x0609A44 +#define HOOKSIZE_CPlayerPed_ProcessAnimGroups_Mid 6 +DWORD RETURN_CPlayerPed_ProcessAnimGroups_Mid = 0x0609A4A; static void __declspec(naked) HOOK_CPlayerPed_ProcessAnimGroups_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -502,9 +502,9 @@ __declspec(noinline) int _cdecl OnCClothes_GetDefaultPlayerMotionGroup(int iReqM } // Hook info -#define HOOKPOS_CClothes_GetDefaultPlayerMotionGroup 0x05A81B0 -#define HOOKSIZE_CClothes_GetDefaultPlayerMotionGroup 5 -DWORD RETURN_CClothes_GetDefaultPlayerMotionGroup = 0x05A81B5; +#define HOOKPOS_CClothes_GetDefaultPlayerMotionGroup 0x05A81B0 +#define HOOKSIZE_CClothes_GetDefaultPlayerMotionGroup 5 +DWORD RETURN_CClothes_GetDefaultPlayerMotionGroup = 0x05A81B5; static void __declspec(naked) HOOK_CClothes_GetDefaultPlayerMotionGroup() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CPlayerPedSA.h b/Client/game_sa/CPlayerPedSA.h index 90e62ade8cd..df001965606 100644 --- a/Client/game_sa/CPlayerPedSA.h +++ b/Client/game_sa/CPlayerPedSA.h @@ -15,18 +15,18 @@ #include "CPedSA.h" #include "CWantedSA.h" -#define FUNC_SetInitialState 0x60CD20 -#define FUNC_ClearWeaponTarget 0x533B30 +#define FUNC_SetInitialState 0x60CD20 +#define FUNC_ClearWeaponTarget 0x533B30 -#define FUNC_CPedOperatorNew 0x5E4720 // ##SA## -#define FUNC_CPlayerPedConstructor 0x60D5B0 // ##SA## +#define FUNC_CPedOperatorNew 0x5E4720 // ##SA## +#define FUNC_CPlayerPedConstructor 0x60D5B0 // ##SA## -#define FUNC_CPlayerPedDestructor 0x6093B0 // ##SA## -#define FUNC_CPlayerPedOperatorDelete 0x5E4760 // ##SA## +#define FUNC_CPlayerPedDestructor 0x6093B0 // ##SA## +#define FUNC_CPlayerPedOperatorDelete 0x5E4760 // ##SA## -#define FUNC_CPlayerPed_ReApplyMoveAnims 0x609650 +#define FUNC_CPlayerPed_ReApplyMoveAnims 0x609650 -#define SIZEOF_CPLAYERPED 1956 +#define SIZEOF_CPLAYERPED 1956 class CPlayerPedSAInterface : public CPedSAInterface { @@ -56,7 +56,7 @@ class CPlayerPedSA : public virtual CPlayerPed, public virtual CPedSA void SetMoveAnim(eMoveAnim iAnimGroup); CEntity* GetTargetedEntity() const override; - void SetTargetedEntity(CEntity* targetEntity) override; + void SetTargetedEntity(CEntity* targetEntity) override; CPlayerPedSAInterface* GetPlayerPedInterface() const noexcept { return static_cast(m_pInterface); }; diff --git a/Client/game_sa/CPoolSAInterface.h b/Client/game_sa/CPoolSAInterface.h index f2d531c7013..fa714e40e15 100644 --- a/Client/game_sa/CPoolSAInterface.h +++ b/Client/game_sa/CPoolSAInterface.h @@ -77,8 +77,8 @@ class CPoolSAInterface B* Allocate() { - m_nFirstFree++; // Continue after the last allocated slot - const auto sz = m_nSize; // Storing size to avoid reloads from memory - should help out the optimizer + m_nFirstFree++; // Continue after the last allocated slot + const auto sz = m_nSize; // Storing size to avoid reloads from memory - should help out the optimizer for (auto i = 0u; i < sz; i++) { const auto slot = (m_nFirstFree + i) % sz; @@ -123,8 +123,8 @@ class CPoolSAInterface void Delete(uint index) { Release(index); } std::int32_t Size() const noexcept { return m_nSize; }; - bool IsEmpty(std::int32_t objectIndex) const { return m_byteMap[objectIndex].bEmpty; } - bool IsContains(std::int32_t index) const + bool IsEmpty(std::int32_t objectIndex) const { return m_byteMap[objectIndex].bEmpty; } + bool IsContains(std::int32_t index) const { if (m_nSize <= index) return false; @@ -166,8 +166,5 @@ struct SVectorPoolData size_t count; public: - SVectorPoolData(size_t defaultSize) : count(0) - { - entities.resize(defaultSize, {nullptr, nullptr}); - } + SVectorPoolData(size_t defaultSize) : count(0) { entities.resize(defaultSize, {nullptr, nullptr}); } }; diff --git a/Client/game_sa/CPoolsSA.cpp b/Client/game_sa/CPoolsSA.cpp index 62406dc4b56..f2d4dc46953 100644 --- a/Client/game_sa/CPoolsSA.cpp +++ b/Client/game_sa/CPoolsSA.cpp @@ -467,7 +467,7 @@ CPed* CPoolsSA::AddPed(CClientPed* pClientPed, DWORD* pGameInterface) void CPoolsSA::RemovePed(CPed* pPed, bool bDelete) { - static bool bIsDeletingPedAlready = false; // to prevent delete being called twice + static bool bIsDeletingPedAlready = false; // to prevent delete being called twice if (!bIsDeletingPedAlready) { @@ -628,8 +628,8 @@ CClientEntity* CPoolsSA::GetClientEntity(DWORD* pGameInterface) static void CreateMissionTrain(const CVector& vecPos, bool bDirection, std::uint32_t uiTrainType, CTrainSAInterface** ppTrainBeginning, CTrainSAInterface** ppTrainEnd, int iNodeIndex, int iTrackId, bool bMissionTrain) noexcept { - auto createMissionTrain = reinterpret_cast(FUNC_CTrain_CreateMissionTrain); + auto createMissionTrain = reinterpret_cast( + FUNC_CTrain_CreateMissionTrain); createMissionTrain(vecPos, bDirection, uiTrainType, ppTrainBeginning, ppTrainEnd, iNodeIndex, iTrackId, bMissionTrain); } @@ -784,7 +784,8 @@ uint CPoolsSA::GetModelIdFromClump(RpClump* pRpClump) unsigned int NUMBER_OF_MODELS = pGame->GetBaseIDforTXD(); - auto isValidPtr = [](const void* ptr) noexcept -> bool { + auto isValidPtr = [](const void* ptr) noexcept -> bool + { if (!ptr) return false; @@ -831,17 +832,17 @@ int CPoolsSA::GetPoolDefaultCapacity(ePools pool) case PED_POOL: return 140; case OBJECT_POOL: - return 350; // Modded to 700 @ CGameSA.cpp + return 350; // Modded to 700 @ CGameSA.cpp case DUMMY_POOL: return 2500; case VEHICLE_POOL: return 110; case COL_MODEL_POOL: - return 10150; // Modded to 12000 @ CGameSA.cpp + return 10150; // Modded to 12000 @ CGameSA.cpp case TASK_POOL: - return 500; // Modded to 5000 @ CGameSA.cpp + return 500; // Modded to 5000 @ CGameSA.cpp case EVENT_POOL: - return 200; // Modded to 5000 @ CGameSA.cpp + return 200; // Modded to 5000 @ CGameSA.cpp case TASK_ALLOCATOR_POOL: return 16; case PED_INTELLIGENCE_POOL: @@ -849,7 +850,7 @@ int CPoolsSA::GetPoolDefaultCapacity(ePools pool) case PED_ATTRACTOR_POOL: return 64; case ENTRY_INFO_NODE_POOL: - return 500; // Modded to 4096 @ CGameSA.cpp + return 500; // Modded to 4096 @ CGameSA.cpp case NODE_ROUTE_POOL: return 64; case PATROL_ROUTE_POOL: @@ -857,15 +858,15 @@ int CPoolsSA::GetPoolDefaultCapacity(ePools pool) case POINT_ROUTE_POOL: return 64; case POINTER_DOUBLE_LINK_POOL: - return 3200; // Modded to 8000 @ CGameSA.cpp + return 3200; // Modded to 8000 @ CGameSA.cpp case POINTER_SINGLE_LINK_POOL: return 70000; case ENV_MAP_MATERIAL_POOL: - return 4096; // Modded to 16000 @ CGameSA.cpp + return 4096; // Modded to 16000 @ CGameSA.cpp case ENV_MAP_ATOMIC_POOL: - return 1024; // Modded to 8000 @ CGameSA.cpp + return 1024; // Modded to 8000 @ CGameSA.cpp case SPEC_MAP_MATERIAL_POOL: - return 4096; // Modded to 16000 @ CGameSA.cpp + return 4096; // Modded to 16000 @ CGameSA.cpp } return 0; } @@ -1025,25 +1026,25 @@ void CPoolsSA::SetPoolCapacity(ePools pool, int iValue) break; case TASK_ALLOCATOR_POOL: cPtr = 0x55124E; - break; // 0 - 127 + break; // 0 - 127 case PED_INTELLIGENCE_POOL: iPtr = 0x551283; break; case PED_ATTRACTOR_POOL: cPtr = 0x5512BB; - break; // 0 - 127 + break; // 0 - 127 case ENTRY_INFO_NODE_POOL: iPtr = 0x550FBA; break; case NODE_ROUTE_POOL: cPtr = 0x551218; - break; // 0 - 127 + break; // 0 - 127 case PATROL_ROUTE_POOL: cPtr = 0x5511E4; - break; // 0 - 127 + break; // 0 - 127 case POINT_ROUTE_POOL: cPtr = 0x5511AF; - break; // 0 - 127 + break; // 0 - 127 case POINTER_DOUBLE_LINK_POOL: iPtr = 0x550F82; break; diff --git a/Client/game_sa/CPoolsSA.h b/Client/game_sa/CPoolsSA.h index 524b7035c58..98bb9fd6cbf 100644 --- a/Client/game_sa/CPoolsSA.h +++ b/Client/game_sa/CPoolsSA.h @@ -43,7 +43,7 @@ class CPoolsSA : public CPools SClientEntity* GetVehicle(DWORD* pGameInterface); SClientEntity* GetVehicle(size_t pos) { return &m_vehiclePool.arrayOfClientEntities[pos]; }; unsigned long GetVehicleCount() { return m_vehiclePool.ulCount; }; - void DeleteAllVehicles(); + void DeleteAllVehicles(); // Objects pool CObject* AddObject(CClientObject* pClientObject, DWORD dwModelID, bool bLowLod, bool bBreakingDisabled); @@ -70,7 +70,7 @@ class CPoolsSA : public CPools SClientEntity* GetPed(DWORD* pGameInterface); SClientEntity* GetPed(size_t pos) { return &m_pedPool.arrayOfClientEntities[pos]; }; CPed* GetPedFromRef(DWORD dwGameRef); - CPedSAInterface* GetPedInterface(DWORD dwGameRef); // game_sa specific + CPedSAInterface* GetPedInterface(DWORD dwGameRef); // game_sa specific unsigned long GetPedCount() { return m_pedPool.ulCount; } void DeleteAllPeds(); @@ -95,24 +95,24 @@ class CPoolsSA : public CPools void ResetPedPoolCount() { m_pedPool.ulCount = 0; } void InvalidateLocalPlayerClientEntity(); - CBuildingsPool& GetBuildingsPool() noexcept override { return m_BuildingsPool; }; - CDummyPool& GetDummyPool() noexcept { return m_DummyPool; }; - CTxdPool& GetTxdPool() noexcept { return m_TxdPool; }; + CBuildingsPool& GetBuildingsPool() noexcept override { return m_BuildingsPool; }; + CDummyPool& GetDummyPool() noexcept { return m_DummyPool; }; + CTxdPool& GetTxdPool() noexcept { return m_TxdPool; }; CPtrNodeSingleLinkPool& GetPtrNodeSingleLinkPool() noexcept override { return m_PtrNodeSingleLinkPool; }; private: // Pools - SPoolData m_vehiclePool; - SPoolData m_pedPool; - SPoolData m_objectPool; + SPoolData m_vehiclePool; + SPoolData m_pedPool; + SPoolData m_objectPool; - CPoolSAInterface** m_ppPedPoolInterface; - CPoolSAInterface** m_ppObjectPoolInterface; - CPoolSAInterface** m_ppVehiclePoolInterface; + CPoolSAInterface** m_ppPedPoolInterface; + CPoolSAInterface** m_ppObjectPoolInterface; + CPoolSAInterface** m_ppVehiclePoolInterface; - CBuildingsPoolSA m_BuildingsPool; - CDummyPoolSA m_DummyPool; - CTxdPoolSA m_TxdPool; + CBuildingsPoolSA m_BuildingsPool; + CDummyPoolSA m_DummyPool; + CTxdPoolSA m_TxdPool; CPtrNodeSingleLinkPoolSA m_PtrNodeSingleLinkPool; bool m_bGetVehicleEnabled; @@ -121,44 +121,44 @@ class CPoolsSA : public CPools #define FUNC_GetPed 0x54ff90 #define CLASS_CPool_Vehicle 0xB74494 -#define CLASS_CPool_Ped 0xB74490 -#define CLASS_CPool_Object 0xB7449C - -#define CLASS_CBuildingPool 0xb74498 -#define CLASS_CPedPool 0xb74490 -#define CLASS_CObjectPool 0xb7449c -#define CLASS_CDummyPool 0xb744a0 -#define CLASS_CVehiclePool 0xb74494 -#define CLASS_CColModelPool 0xb744a4 -#define CLASS_CTaskPool 0xb744a8 -#define CLASS_CEventPool 0xb744ac -#define CLASS_CTaskAllocatorPool 0xb744bc -#define CLASS_CPedIntelligencePool 0xb744c0 -#define CLASS_CPedAttractorPool 0xb744c4 -#define CLASS_CEntryInfoNodePool 0xb7448c -#define CLASS_CNodeRoutePool 0xb744b8 -#define CLASS_CPatrolRoutePool 0xb744b4 -#define CLASS_CPointRoutePool 0xb744b0 +#define CLASS_CPool_Ped 0xB74490 +#define CLASS_CPool_Object 0xB7449C + +#define CLASS_CBuildingPool 0xb74498 +#define CLASS_CPedPool 0xb74490 +#define CLASS_CObjectPool 0xb7449c +#define CLASS_CDummyPool 0xb744a0 +#define CLASS_CVehiclePool 0xb74494 +#define CLASS_CColModelPool 0xb744a4 +#define CLASS_CTaskPool 0xb744a8 +#define CLASS_CEventPool 0xb744ac +#define CLASS_CTaskAllocatorPool 0xb744bc +#define CLASS_CPedIntelligencePool 0xb744c0 +#define CLASS_CPedAttractorPool 0xb744c4 +#define CLASS_CEntryInfoNodePool 0xb7448c +#define CLASS_CNodeRoutePool 0xb744b8 +#define CLASS_CPatrolRoutePool 0xb744b4 +#define CLASS_CPointRoutePool 0xb744b0 #define CLASS_CPtrNodeDoubleLinkPool 0xB74488 #define CLASS_CPtrNodeSingleLinkPool 0xB74484 -#define FUNC_CBuildingPool_GetNoOfUsedSpaces 0x550620 -#define FUNC_CPedPool_GetNoOfUsedSpaces 0x5504A0 -#define FUNC_CObjectPool_GetNoOfUsedSpaces 0x54F6B0 -#define FUNC_CDummyPool_GetNoOfUsedSpaces 0x5507A0 -#define FUNC_CVehiclePool_GetNoOfUsedSpaces 0x42CCF0 -#define FUNC_CColModelPool_GetNoOfUsedSpaces 0x550870 -#define FUNC_CTaskPool_GetNoOfUsedSpaces 0x550940 -#define FUNC_CEventPool_GetNoOfUsedSpaces 0x550A10 -#define FUNC_CTaskAllocatorPool_GetNoOfUsedSpaces 0x550d50 -#define FUNC_CPedIntelligencePool_GetNoOfUsedSpaces 0x550E20 -#define FUNC_CPedAttractorPool_GetNoOfUsedSpaces 0x550ef0 -#define FUNC_CEntryInfoNodePool_GetNoOfUsedSpaces 0x5503d0 -#define FUNC_CNodeRoutePool_GetNoOfUsedSpaces 0x550c80 -#define FUNC_CPatrolRoutePool_GetNoOfUsedSpaces 0x550bb0 -#define FUNC_CPointRoutePool_GetNoOfUsedSpaces 0x550ae0 +#define FUNC_CBuildingPool_GetNoOfUsedSpaces 0x550620 +#define FUNC_CPedPool_GetNoOfUsedSpaces 0x5504A0 +#define FUNC_CObjectPool_GetNoOfUsedSpaces 0x54F6B0 +#define FUNC_CDummyPool_GetNoOfUsedSpaces 0x5507A0 +#define FUNC_CVehiclePool_GetNoOfUsedSpaces 0x42CCF0 +#define FUNC_CColModelPool_GetNoOfUsedSpaces 0x550870 +#define FUNC_CTaskPool_GetNoOfUsedSpaces 0x550940 +#define FUNC_CEventPool_GetNoOfUsedSpaces 0x550A10 +#define FUNC_CTaskAllocatorPool_GetNoOfUsedSpaces 0x550d50 +#define FUNC_CPedIntelligencePool_GetNoOfUsedSpaces 0x550E20 +#define FUNC_CPedAttractorPool_GetNoOfUsedSpaces 0x550ef0 +#define FUNC_CEntryInfoNodePool_GetNoOfUsedSpaces 0x5503d0 +#define FUNC_CNodeRoutePool_GetNoOfUsedSpaces 0x550c80 +#define FUNC_CPatrolRoutePool_GetNoOfUsedSpaces 0x550bb0 +#define FUNC_CPointRoutePool_GetNoOfUsedSpaces 0x550ae0 #define FUNC_CPtrNodeSingleLinkPool_GetNoOfUsedSpaces 0x550230 #define FUNC_CPtrNodeDoubleLinkPool_GetNoOfUsedSpaces 0x550300 #define FUNC_CTrain_CreateMissionTrain 0x6F7550 -#define VAR_TrainModelArray 0x8D44F8 +#define VAR_TrainModelArray 0x8D44F8 diff --git a/Client/game_sa/CProjectileInfoSA.h b/Client/game_sa/CProjectileInfoSA.h index 5bcb33c6290..17649c33bea 100644 --- a/Client/game_sa/CProjectileInfoSA.h +++ b/Client/game_sa/CProjectileInfoSA.h @@ -14,16 +14,16 @@ #include #include "CProjectileSA.h" -#define PROJECTILE_COUNT 32 -#define PROJECTILE_INFO_COUNT 32 +#define PROJECTILE_COUNT 32 +#define PROJECTILE_INFO_COUNT 32 -#define FUNC_RemoveAllProjectiles 0x7399B0 //##SA## -#define FUNC_RemoveProjectile 0x7388F0 //##SA## -#define FUNC_RemoveIfThisIsAProjectile 0x739A40 //##SA## -#define FUNC_AddProjectile 0x737C80 //##SA## +#define FUNC_RemoveAllProjectiles 0x7399B0 // ##SA## +#define FUNC_RemoveProjectile 0x7388F0 // ##SA## +#define FUNC_RemoveIfThisIsAProjectile 0x739A40 // ##SA## +#define FUNC_AddProjectile 0x737C80 // ##SA## -#define ARRAY_CProjectile 0xC89110 //##SA## -#define ARRAY_CProjectileInfo 0xC891A8 //##SA## +#define ARRAY_CProjectile 0xC89110 // ##SA## +#define ARRAY_CProjectileInfo 0xC891A8 // ##SA## // #pragma pack(push,1) class CProjectileInfoSAInterface diff --git a/Client/game_sa/CProjectileSA.h b/Client/game_sa/CProjectileSA.h index 3a9d2caaf6f..4e46d38a2ee 100644 --- a/Client/game_sa/CProjectileSA.h +++ b/Client/game_sa/CProjectileSA.h @@ -14,7 +14,7 @@ #include #include "CObjectSA.h" -class CProjectileSAInterface : public CObjectSAInterface // entirely inherited from CObject +class CProjectileSAInterface : public CObjectSAInterface // entirely inherited from CObject { public: bool IsProjectableVTBL() const { return GetVTBL() == (void*)0x867030; }; @@ -30,7 +30,7 @@ class CProjectileSA : public virtual CProjectile, public virtual CObjectSA public: CProjectileSA(class CProjectileSAInterface* projectileInterface); ~CProjectileSA(); - void Destroy(bool bBlow = true); + void Destroy(bool bBlow = true); CProjectileSAInterface* GetProjectileInterface() const { return static_cast(m_pInterface); }; bool CalculateImpactPosition(CEntitySAInterface* pCollidedWith, CVector vecInputStart, CVector& vecInputEnd); diff --git a/Client/game_sa/CPtrNodeDoubleListSA.h b/Client/game_sa/CPtrNodeDoubleListSA.h index 93ac1ccd109..edc7279aea9 100644 --- a/Client/game_sa/CPtrNodeDoubleListSA.h +++ b/Client/game_sa/CPtrNodeDoubleListSA.h @@ -10,11 +10,11 @@ #pragma once -template +template class CPtrNodeDoubleLink { public: - T* pItem; + T* pItem; CPtrNodeDoubleLink* pNext; CPtrNodeDoubleLink* pPrev; }; diff --git a/Client/game_sa/CPtrNodeSingleLinkPoolSA.cpp b/Client/game_sa/CPtrNodeSingleLinkPoolSA.cpp index 853ccb1e7d5..84cfcd2b8c3 100644 --- a/Client/game_sa/CPtrNodeSingleLinkPoolSA.cpp +++ b/Client/game_sa/CPtrNodeSingleLinkPoolSA.cpp @@ -20,15 +20,15 @@ CPtrNodeSingleLinkPoolSA::CPtrNodeSingleLinkPoolSA() m_customPool = new CPtrNodeSingleLinkPoolSA::pool_t(); } -constexpr std::uint32_t HOOKPOS_SingleLinkNodeConstructor = 0x552380; -constexpr std::size_t HOOKSIZE_SingleLinkNodeConstructor = 6; +constexpr std::uint32_t HOOKPOS_SingleLinkNodeConstructor = 0x552380; +constexpr std::size_t HOOKSIZE_SingleLinkNodeConstructor = 6; static CPtrNodeSingleLinkPoolSA::pool_item_t* __cdecl HOOK_SingleLinkNodeConstructor() { return CPtrNodeSingleLinkPoolSA::GetPoolInstance()->AllocateItem(); } -constexpr std::uint32_t HOOKPOS_SingleLinkNodeDestructor = 0x552390; -constexpr std::size_t HOOKSIZE_SingleLinkNodeDestructor = 6; +constexpr std::uint32_t HOOKPOS_SingleLinkNodeDestructor = 0x552390; +constexpr std::size_t HOOKSIZE_SingleLinkNodeDestructor = 6; static CPtrNodeSingleLinkPoolSA::pool_item_t* __cdecl HOOK_SingleLinkNodeDestructor(CPtrNodeSingleLinkPoolSA::pool_item_t* item) { CPtrNodeSingleLinkPoolSA::GetPoolInstance()->RemoveItem(item); @@ -37,9 +37,9 @@ static CPtrNodeSingleLinkPoolSA::pool_item_t* __cdecl HOOK_SingleLinkNodeDestruc } // Replace pool->RemoveItem here -constexpr std::uint32_t HOOKPOS_CPtrListSingleLink_Flush = 0x55243B; -constexpr std::size_t HOOKSIZE_CPtrListSingleLink_Flush = 6; -constexpr std::uint32_t CONTINUE_CPtrListSingleLink_Flush = 0x55245B; +constexpr std::uint32_t HOOKPOS_CPtrListSingleLink_Flush = 0x55243B; +constexpr std::size_t HOOKSIZE_CPtrListSingleLink_Flush = 6; +constexpr std::uint32_t CONTINUE_CPtrListSingleLink_Flush = 0x55245B; static void __declspec(naked) HOOK_CPtrListSingleLink_Flush() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -69,4 +69,3 @@ void CPtrNodeSingleLinkPoolSA::StaticSetHooks() // Skip the original pool initialization MemCpy((void*)0x550F26, "\xEB\x2D", 2); } - diff --git a/Client/game_sa/CPtrNodeSingleLinkPoolSA.h b/Client/game_sa/CPtrNodeSingleLinkPoolSA.h index 1043f704c76..0ee39783a09 100644 --- a/Client/game_sa/CPtrNodeSingleLinkPoolSA.h +++ b/Client/game_sa/CPtrNodeSingleLinkPoolSA.h @@ -10,7 +10,7 @@ *****************************************************************************/ #pragma once - + #include "CPoolSAInterface.h" #include "CDynamicPool.h" #include "CPtrNodeSingleListSA.h" @@ -30,8 +30,9 @@ class CPtrNodeSingleLinkPoolSA final : public CPtrNodeSingleLinkPool bool Resize(std::size_t newSize) override { return m_customPool->SetCapacity(newSize); }; void ResetCapacity() override { m_customPool->SetCapacity(MAX_POINTER_SINGLE_LINKS); }; - static auto* GetPoolInstance() { return m_customPool; } - static void StaticSetHooks(); + static auto* GetPoolInstance() { return m_customPool; } + static void StaticSetHooks(); + private: static pool_t* m_customPool; }; diff --git a/Client/game_sa/CQuadTreeNodeSA.h b/Client/game_sa/CQuadTreeNodeSA.h index 81d47c43e55..beefe0dc767 100644 --- a/Client/game_sa/CQuadTreeNodeSA.h +++ b/Client/game_sa/CQuadTreeNodeSA.h @@ -14,7 +14,7 @@ #include "CPtrNodeSingleListSA.h" #include "CRect.h" -template +template class CQuadTreeNodesSAInterface { public: @@ -22,13 +22,13 @@ class CQuadTreeNodesSAInterface char AddItem(T* item, CRect* boudingBox); private: - float m_fX; - float m_fY; - float m_fW; - float m_fH; + float m_fX; + float m_fY; + float m_fW; + float m_fH; CPtrNodeSingleListSAInterface m_pItemList; - CQuadTreeNodesSAInterface* m_childrens[4]; - uint32_t m_level; + CQuadTreeNodesSAInterface* m_childrens[4]; + uint32_t m_level; }; static_assert(sizeof(CQuadTreeNodesSAInterface) == 0x28, "Wrong CQuadTreeNodesSAInterface size"); diff --git a/Client/game_sa/CRadarSA.h b/Client/game_sa/CRadarSA.h index db1fdb1d9ec..d060b0b9152 100644 --- a/Client/game_sa/CRadarSA.h +++ b/Client/game_sa/CRadarSA.h @@ -14,11 +14,11 @@ #include #include "CMarkerSA.h" -#define ARRAY_CMarker 0xBA86F0 -#define MAX_MARKERS 175 +#define ARRAY_CMarker 0xBA86F0 +#define MAX_MARKERS 175 -#define FUNC_DrawAreaOnRadar 0x5853d0 -#define FUNC_SetCoordBlip 0x583820 +#define FUNC_DrawAreaOnRadar 0x5853d0 +#define FUNC_SetCoordBlip 0x583820 class CRadarSA : public CRadar { diff --git a/Client/game_sa/CRegisteredCoronaSA.cpp b/Client/game_sa/CRegisteredCoronaSA.cpp index de80f549a88..959114b26ce 100644 --- a/Client/game_sa/CRegisteredCoronaSA.cpp +++ b/Client/game_sa/CRegisteredCoronaSA.cpp @@ -124,7 +124,7 @@ void CRegisteredCoronaSA::Init(DWORD Identifier) internalInterface->FlareType = 0; internalInterface->ReflectionType = 0; internalInterface->JustCreated = 1; - internalInterface->RegisteredThisFrame = 1; // won't appear in-game without this + internalInterface->RegisteredThisFrame = 1; // won't appear in-game without this } void CRegisteredCoronaSA::Refresh() diff --git a/Client/game_sa/CRegisteredCoronaSA.h b/Client/game_sa/CRegisteredCoronaSA.h index 2c9ac27705e..f44a15863b5 100644 --- a/Client/game_sa/CRegisteredCoronaSA.h +++ b/Client/game_sa/CRegisteredCoronaSA.h @@ -16,35 +16,35 @@ class CEntitySAInterface; -#define ARRAY_CORONAS 0xC3E058 +#define ARRAY_CORONAS 0xC3E058 -class CRegisteredCoronaSAInterface // coronas are 104 bytes long, and theres 56 of them +class CRegisteredCoronaSAInterface // coronas are 104 bytes long, and theres 56 of them { public: - CVector Coordinates; // Where is it exactly. - DWORD Identifier; // Should be unique for each corona. Address or something (0 = empty) - RwTexture* pTex; // Pointer to the actual texture to be rendered - float Size; // How big is this fellow - float NormalAngle; // Is corona normal (if relevant) facing the camera? - float Range; // How far away is this guy still visible - float PullTowardsCam; // How far away is the z value pulled towards camera. - float HeightAboveGround; // Stired so that we don't have to do a ProcessVerticalLine every frame - // The following fields are used for trails behind coronas (glowy lights) - float FadeSpeed; // The speed the corona fades in and out ##SA## - BYTE Red, Green, Blue; // Rendering colour. - BYTE Intensity; // 255 = full - BYTE FadedIntensity; // Intensity that lags behind the given intenisty and fades out if the LOS is blocked - BYTE RegisteredThisFrame; // Has this guy been registered by game code this frame - BYTE FlareType; // What type of flare to render - BYTE ReflectionType; // What type of reflection during wet weather - BYTE LOSCheck : 1; // Do we check the LOS or do we render at the right Z value - BYTE OffScreen : 1; // Set by the rendering code to be used by the update code - BYTE JustCreated; // If this guy has been created this frame we won't delete it (It hasn't had the time to get its OffScreen cleared) ##SA - // removed from packed byte ## - BYTE NeonFade : 1; // Does the guy fade out when closer to cam - BYTE OnlyFromBelow : 1; // This corona is only visible if the camera is below it. ##SA## + CVector Coordinates; // Where is it exactly. + DWORD Identifier; // Should be unique for each corona. Address or something (0 = empty) + RwTexture* pTex; // Pointer to the actual texture to be rendered + float Size; // How big is this fellow + float NormalAngle; // Is corona normal (if relevant) facing the camera? + float Range; // How far away is this guy still visible + float PullTowardsCam; // How far away is the z value pulled towards camera. + float HeightAboveGround; // Stired so that we don't have to do a ProcessVerticalLine every frame + // The following fields are used for trails behind coronas (glowy lights) + float FadeSpeed; // The speed the corona fades in and out ##SA## + BYTE Red, Green, Blue; // Rendering colour. + BYTE Intensity; // 255 = full + BYTE FadedIntensity; // Intensity that lags behind the given intenisty and fades out if the LOS is blocked + BYTE RegisteredThisFrame; // Has this guy been registered by game code this frame + BYTE FlareType; // What type of flare to render + BYTE ReflectionType; // What type of reflection during wet weather + BYTE LOSCheck : 1; // Do we check the LOS or do we render at the right Z value + BYTE OffScreen : 1; // Set by the rendering code to be used by the update code + BYTE JustCreated; // If this guy has been created this frame we won't delete it (It hasn't had the time to get its OffScreen cleared) ##SA + // removed from packed byte ## + BYTE NeonFade : 1; // Does the guy fade out when closer to cam + BYTE OnlyFromBelow : 1; // This corona is only visible if the camera is below it. ##SA## BYTE bHasValidHeightAboveGround : 1; - BYTE WhiteCore : 1; // This corona rendered with a small white core. + BYTE WhiteCore : 1; // This corona rendered with a small white core. BYTE bIsAttachedToEntity : 1; CEntitySAInterface* pEntityAttachedTo; diff --git a/Client/game_sa/CRenderWareSA.ClothesReplacing.cpp b/Client/game_sa/CRenderWareSA.ClothesReplacing.cpp index ac98aff6e9b..7103193c9ae 100644 --- a/Client/game_sa/CRenderWareSA.ClothesReplacing.cpp +++ b/Client/game_sa/CRenderWareSA.ClothesReplacing.cpp @@ -20,13 +20,13 @@ namespace ushort usNext; ushort usPrev; - ushort uiUnknown1; // Parent ? - uchar uiUnknown2; // 0x12 when loading, 0x02 when finished loading + ushort uiUnknown1; // Parent ? + uchar uiUnknown2; // 0x12 when loading, 0x02 when finished loading uchar ucImgId; int iBlockOffset; int iBlockCount; - uint uiLoadflag; // 0-not loaded 2-requested 3-loaded 1-processed + uint uiLoadflag; // 0-not loaded 2-requested 3-loaded 1-processed }; std::unordered_map ms_ReplacementClothesFileDataMap; @@ -59,7 +59,7 @@ namespace auto blockDiv = std::div(size, 2048); return (blockDiv.quot + (blockDiv.rem ? 1 : 0)); } -} // namespace +} // namespace //////////////////////////////////////////////////////////////// // @@ -219,8 +219,8 @@ __declspec(noinline) bool _cdecl OnCStreaming_RequestModel_Mid(int flags, SImgGT if (ms_ReplacementClothesFileDataMap.empty() && ms_ClothesFileDataMap.empty()) return false; - static std::map blockOffsetToFileIdMap; - std::map blockOffsetToFileNameMap; + static std::map blockOffsetToFileIdMap; + std::map blockOffsetToFileNameMap; if (blockOffsetToFileIdMap.empty() || ms_ClothesFileDataMap.size() > 0) { @@ -260,8 +260,8 @@ __declspec(noinline) bool _cdecl OnCStreaming_RequestModel_Mid(int flags, SImgGT if (!replacementFileData) return false; - // If bLoadingBigModel is set, try to get it unset - #define VAR_CStreaming_bLoadingBigModel 0x08E4A58 + // If bLoadingBigModel is set, try to get it unset +#define VAR_CStreaming_bLoadingBigModel 0x08E4A58 BYTE& bLoadingBigModel = *(BYTE*)VAR_CStreaming_bLoadingBigModel; if (bLoadingBigModel) { @@ -285,10 +285,10 @@ __declspec(noinline) bool _cdecl OnCStreaming_RequestModel_Mid(int flags, SImgGT } // Hook info -#define HOOKPOS_CStreaming_RequestModel_Mid 0x040895A -#define HOOKSIZE_CStreaming_RequestModel_Mid 5 -DWORD RETURN_CStreaming_RequestModel_MidA = 0x0408960; -DWORD RETURN_CStreaming_RequestModel_MidB = 0x0408990; +#define HOOKPOS_CStreaming_RequestModel_Mid 0x040895A +#define HOOKSIZE_CStreaming_RequestModel_Mid 5 +DWORD RETURN_CStreaming_RequestModel_MidA = 0x0408960; +DWORD RETURN_CStreaming_RequestModel_MidB = 0x0408990; static void __declspec(naked) HOOK_CStreaming_RequestModel_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CRenderWareSA.ShaderMatching.cpp b/Client/game_sa/CRenderWareSA.ShaderMatching.cpp index fa97ce209cf..b8a2c3bb407 100644 --- a/Client/game_sa/CRenderWareSA.ShaderMatching.cpp +++ b/Client/game_sa/CRenderWareSA.ShaderMatching.cpp @@ -74,19 +74,19 @@ void CMatchChannelManager::InsertTexture(STexInfo* pTexInfo) { if (!pTexInfo) return; - + // Find/create TexNameInfo STexNameInfo* pTexNameInfo = MapFindRef(m_AllTextureList, pTexInfo->strTextureName); if (!pTexNameInfo) { // Create TexNameInfo STexNameInfo* pNewTexNameInfo = new STexNameInfo(pTexInfo->strTextureName); - + try { MapSet(m_AllTextureList, pTexInfo->strTextureName, pNewTexNameInfo); pTexNameInfo = MapFindRef(m_AllTextureList, pTexInfo->strTextureName); - + if (!pTexNameInfo) [[unlikely]] { delete pNewTexNameInfo; @@ -126,9 +126,9 @@ void CMatchChannelManager::RemoveTexture(STexInfo* pTexInfo) { if (!pTexInfo) return; - + STexNameInfo* pTexNameInfo = pTexInfo->pAssociatedTexNameInfo; - + if (!pTexNameInfo) [[unlikely]] return; @@ -276,12 +276,12 @@ SShaderInfoLayers* CMatchChannelManager::GetShaderForTexAndEntity(STexInfo* pTex { if (!pTexInfo) return nullptr; - + if (m_bChangesPending) FlushChanges(); STexNameInfo* pTexNameInfo = pTexInfo->pAssociatedTexNameInfo; - + if (!pTexNameInfo) return nullptr; @@ -301,7 +301,7 @@ SShaderInfoLayers* CMatchChannelManager::GetShaderForTexAndEntity(STexInfo* pTex pTexShaderReplacement = UpdateTexShaderReplacement(pTexNameInfo, pClientEntity, iEntityType); } - #ifdef SHADER_DEBUG_CHECKS +#ifdef SHADER_DEBUG_CHECKS if (pTexNameInfo->iDebugCounter1++ > 400) { // Check cached shader is correct @@ -327,7 +327,7 @@ SShaderInfoLayers* CMatchChannelManager::GetShaderForTexAndEntity(STexInfo* pTex FinalizeLayers(shaderLayersCheck1); assert(pTexShaderReplacement->shaderLayers == shaderLayersCheck1); } - #endif +#endif // Return layers for this entity return &pTexShaderReplacement->shaderLayers; @@ -341,7 +341,7 @@ SShaderInfoLayers* CMatchChannelManager::GetShaderForTexAndEntity(STexInfo* pTex UpdateTexShaderReplacementNoEntity(pTexNameInfo, texNoEntityShader, iEntityType); } - #ifdef SHADER_DEBUG_CHECKS +#ifdef SHADER_DEBUG_CHECKS if (pTexNameInfo->iDebugCounter2++ > 400) { // Check cached shader is correct @@ -351,7 +351,7 @@ SShaderInfoLayers* CMatchChannelManager::GetShaderForTexAndEntity(STexInfo* pTex FinalizeLayers(shaderLayersCheck2); assert(texNoEntityShader.shaderLayers == shaderLayersCheck2); } - #endif +#endif // Return layers for any entity return &texNoEntityShader.shaderLayers; @@ -425,7 +425,7 @@ void CMatchChannelManager::RemoveClientEntityRefs(CClientEntityBase* pClientEnti { if (!pChannel) continue; - + for (STexNameInfo* pTexNameInfo : pChannel->m_MatchedTextureList) { if (pTexNameInfo) @@ -495,7 +495,7 @@ void CMatchChannelManager::RemoveShaderRefs(CSHADERDUMMY* pShaderData) CMatchChannel* pChannel = *iter; if (!pChannel) continue; - + for (CFastHashSet::iterator iter = pChannel->m_MatchedTextureList.begin(); iter != pChannel->m_MatchedTextureList.end(); ++iter) { if (*iter) @@ -677,7 +677,7 @@ void CMatchChannelManager::ProcessRematchTexturesQueue() { pChannel->RemoveTexture(pTexNameInfo); MapRemove(pTexNameInfo->matchChannelList, pChannel); - pTexNameInfo->ResetReplacementResults(); // Do this here as it won't get picked up in RecalcEverything now + pTexNameInfo->ResetReplacementResults(); // Do this here as it won't get picked up in RecalcEverything now } // Rematch against texture list diff --git a/Client/game_sa/CRenderWareSA.ShaderMatching.h b/Client/game_sa/CRenderWareSA.ShaderMatching.h index 092c60ce33c..2c9f1d18203 100644 --- a/Client/game_sa/CRenderWareSA.ShaderMatching.h +++ b/Client/game_sa/CRenderWareSA.ShaderMatching.h @@ -24,7 +24,9 @@ SString GetDebugTagStr(CClientEntityBase* pClientEntity); SString GetDebugTagStr(SShaderInfo* pShaderInfo); SString GetDebugTagStr(CMatchChannel* pChannel); #else - #define OutputDebug(x) {} + #define OutputDebug(x) \ + { \ + } #endif // @@ -94,7 +96,7 @@ struct SWildcardMatchChain return true; } - std::vector matchTypeList; // List of additive and subtractive wildcard match strings + std::vector matchTypeList; // List of additive and subtractive wildcard match strings }; //////////////////////////////////////////////////////////////// @@ -160,19 +162,19 @@ class CMatchChannel ////////////////////////////////////////////// void AddShaderAndEntity(const CShaderAndEntityPair& key) { - #ifdef SHADER_DEBUG_OUTPUT +#ifdef SHADER_DEBUG_OUTPUT if (!MapContains(m_ShaderAndEntityList, key)) OutputDebug(SString(" +Channel:%s adds (ShaderEntity:%s)", GetDebugTag(this), GetDebugTag(key))); - #endif +#endif MapInsert(m_ShaderAndEntityList, key); } void RemoveShaderAndEntity(const CShaderAndEntityPair& key) { - #ifdef SHADER_DEBUG_OUTPUT +#ifdef SHADER_DEBUG_OUTPUT if (MapContains(m_ShaderAndEntityList, key)) OutputDebug(SString(" -Channel:%s removes (ShaderEntity:%s)", GetDebugTag(this), GetDebugTag(key))); - #endif +#endif MapRemove(m_ShaderAndEntityList, key); } @@ -211,19 +213,19 @@ class CMatchChannel ////////////////////////////////////////////// void AddTexture(STexNameInfo* pTexNameInfo) { - #ifdef SHADER_DEBUG_OUTPUT +#ifdef SHADER_DEBUG_OUTPUT if (!MapContains(m_MatchedTextureList, pTexNameInfo)) OutputDebug(SString(" +Channel:%s adds Tex:%s", GetDebugTag(this), GetDebugTag(pTexNameInfo))); - #endif +#endif MapInsert(m_MatchedTextureList, pTexNameInfo); } void RemoveTexture(STexNameInfo* pTexNameInfo) { - #ifdef SHADER_DEBUG_OUTPUT +#ifdef SHADER_DEBUG_OUTPUT if (MapContains(m_MatchedTextureList, pTexNameInfo)) OutputDebug(SString(" -Channel:%s removes Tex:%s", GetDebugTag(this), GetDebugTag(pTexNameInfo))); - #endif +#endif MapRemove(m_MatchedTextureList, pTexNameInfo); } @@ -232,19 +234,19 @@ class CMatchChannel ////////////////////////////////////////////// void SetMatchChain(const SWildcardMatchChain& matchChain) { - #ifdef SHADER_DEBUG_OUTPUT +#ifdef SHADER_DEBUG_OUTPUT if (!(m_MatchChain == matchChain)) OutputDebug(SString(" Channel:%s SetMatchChain:%s", GetDebugTag(this), GetDebugTag(matchChain))); - #endif +#endif m_MatchChain = matchChain; } const SWildcardMatchChain& GetMatchChain() const { return m_MatchChain; } - SWildcardMatchChain m_MatchChain; // String matches this channel represents - CFastHashSet m_MatchedTextureList; // All textures whose name matches the match chain + SWildcardMatchChain m_MatchChain; // String matches this channel represents + CFastHashSet m_MatchedTextureList; // All textures whose name matches the match chain std::set m_ShaderAndEntityList; - bool m_bResetReplacements; // Flag to indicate texture replacements should be reset + bool m_bResetReplacements; // Flag to indicate texture replacements should be reset uint m_uiId; static uint ms_uiIdCounter; }; @@ -266,7 +268,7 @@ class CMatchChannelManager void RemoveClientEntityRefs(CClientEntityBase* pClientEntity); void RemoveShaderRefs(CSHADERDUMMY* pShaderData); void GetShaderReplacementStats(SShaderReplacementStats& outStats); - void CleanupInvalidatedShaderCache(); // Cleanup deferred invalidated entries + void CleanupInvalidatedShaderCache(); // Cleanup deferred invalidated entries protected: void CalcShaderForTexAndEntity(SShaderInfoLayers& outShaderLayers, STexNameInfo* pTexNameInfo, CClientEntityBase* pClientEntity, int iEntityType, diff --git a/Client/game_sa/CRenderWareSA.ShaderSupport.cpp b/Client/game_sa/CRenderWareSA.ShaderSupport.cpp index 5490ab4eb29..415f6ea87d1 100644 --- a/Client/game_sa/CRenderWareSA.ShaderSupport.cpp +++ b/Client/game_sa/CRenderWareSA.ShaderSupport.cpp @@ -19,13 +19,13 @@ extern CCoreInterface* g_pCore; extern CGameSA* pGame; -#define ADDR_CCustomCarPlateMgr_CreatePlateTexture_TextureSetName 0x06FDF40 -#define ADDR_CCustomRoadsignMgr_CreateRoadsignTexture_TextureSetName 0x06FED49 -#define ADDR_CClothesBuilder_ConstructTextures_Start 0x05A6040 -#define ADDR_CClothesBuilder_ConstructTextures_End 0x05A6520 -#define ADDR_CVehicle_DoHeadLightBeam_RenderPrimitive 0x06E13CD -#define ADDR_CHeli_SearchLightCone_RenderPrimitive 0x06C62AD -#define ADDR_CWaterCannon_Render_RenderPrimitive 0x072956B +#define ADDR_CCustomCarPlateMgr_CreatePlateTexture_TextureSetName 0x06FDF40 +#define ADDR_CCustomRoadsignMgr_CreateRoadsignTexture_TextureSetName 0x06FED49 +#define ADDR_CClothesBuilder_ConstructTextures_Start 0x05A6040 +#define ADDR_CClothesBuilder_ConstructTextures_End 0x05A6520 +#define ADDR_CVehicle_DoHeadLightBeam_RenderPrimitive 0x06E13CD +#define ADDR_CHeli_SearchLightCone_RenderPrimitive 0x06C62AD +#define ADDR_CWaterCannon_Render_RenderPrimitive 0x072956B enum { @@ -47,9 +47,9 @@ int CRenderWareSA::ms_iRenderingType = 0; //////////////////////////////////////////////////////////////// // Hooks for creating txd create and destroy events -#define HOOKPOS_CTxdStore_SetupTxdParent 0x731D55 +#define HOOKPOS_CTxdStore_SetupTxdParent 0x731D55 DWORD RETURN_CTxdStore_SetupTxdParent = 0x731D5B; -#define HOOKPOS_CTxdStore_RemoveTxd 0x731E90 +#define HOOKPOS_CTxdStore_RemoveTxd 0x731E90 DWORD RETURN_CTxdStore_RemoveTxd = 0x731E96; // @@ -196,18 +196,18 @@ void CRenderWareSA::PulseWorldTextureWatch() for (std::vector::iterator iter = textureList.begin(); iter != textureList.end(); iter++) { - RwTexture* texture = *iter; - + RwTexture* texture = *iter; + // Validate texture pointer (TXD could unload mid-iteration) if (!texture || !SharedUtil::IsReadablePointer(texture, sizeof(RwTexture))) continue; - + const char* szTextureName = texture->name; - + // Check raster pointer - CD3DDUMMY* pD3DData = (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) - ? (CD3DDUMMY*)texture->raster->renderResource : NULL; - + CD3DDUMMY* pD3DData = + (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) ? (CD3DDUMMY*)texture->raster->renderResource : NULL; + if (!MapContains(m_SpecialTextures, texture)) StreamingAddedTexture(action.usTxdId, szTextureName, pD3DData); } @@ -293,7 +293,7 @@ void CRenderWareSA::RemoveStreamingTexture(unsigned short usTxdId, CD3DDUMMY* pD return; typedef std::multimap::iterator IterType; - std::pair range = m_TexInfoMap.equal_range(usTxdId); + std::pair range = m_TexInfoMap.equal_range(usTxdId); for (IterType iter = range.first; iter != range.second;) { STexInfo* pTexInfo = iter->second; @@ -346,13 +346,13 @@ void CRenderWareSA::ScriptAddedTxd(RwTexDictionary* pTxd) GetTxdTextures(textureList, pTxd); for (std::vector::iterator iter = textureList.begin(); iter != textureList.end(); iter++) { - RwTexture* texture = *iter; + RwTexture* texture = *iter; if (!texture || !SharedUtil::IsReadablePointer(texture, sizeof(RwTexture))) continue; const char* szTextureName = texture->name; - CD3DDUMMY* pD3DData = (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) - ? (CD3DDUMMY*)texture->raster->renderResource : NULL; + CD3DDUMMY* pD3DData = + (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) ? (CD3DDUMMY*)texture->raster->renderResource : NULL; if (!pD3DData || !szTextureName[0]) continue; @@ -408,8 +408,8 @@ void CRenderWareSA::SpecialAddedTexture(RwTexture* texture, const char* szTextur if (!szTextureName || !szTextureName[0]) return; - CD3DDUMMY* pD3DData = (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) - ? (CD3DDUMMY*)texture->raster->renderResource : NULL; + CD3DDUMMY* pD3DData = + (texture->raster && SharedUtil::IsReadablePointer(texture->raster, sizeof(RwRaster))) ? (CD3DDUMMY*)texture->raster->renderResource : NULL; if (!pD3DData) return; @@ -585,9 +585,9 @@ void CRenderWareSA::AppendAdditiveMatch(CSHADERDUMMY* pShaderData, CClientEntity // renames textures (e.g., "#emap"). We register both patterns so the shader matches either. // Handles: "remap", "remap*", "*remap*", "vehicleremap", etc. SString strLower = strTextureNameMatch.ToLower(); - bool bHasRemap = strLower.Contains("remap"); - bool bHasWhite = strLower.Contains("white"); - + bool bHasRemap = strLower.Contains("remap"); + bool bHasWhite = strLower.Contains("white"); + // Check for "remap" anywhere in the pattern (case-insensitive) if (bHasRemap) { @@ -595,9 +595,9 @@ void CRenderWareSA::AppendAdditiveMatch(CSHADERDUMMY* pShaderData, CClientEntity // Only register if actually different (avoid duplicates) if (strInternalPattern != strTextureNameMatch) { - m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strInternalPattern, fShaderPriority, bShaderLayered, iTypeMask, uiShaderCreateTime, - bShaderUsesVertexShader, bAppendLayers); - + m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strInternalPattern, fShaderPriority, bShaderLayered, iTypeMask, + uiShaderCreateTime, bShaderUsesVertexShader, bAppendLayers); + // If pattern also contains "white", register the doubly-transformed variant // e.g., "white_remap*" -> "@hite_#emap*" if (bHasWhite) @@ -605,8 +605,8 @@ void CRenderWareSA::AppendAdditiveMatch(CSHADERDUMMY* pShaderData, CClientEntity SString strBothInternal = strInternalPattern.ReplaceI("white", "@hite"); if (strBothInternal != strInternalPattern) { - m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strBothInternal, fShaderPriority, bShaderLayered, iTypeMask, uiShaderCreateTime, - bShaderUsesVertexShader, bAppendLayers); + m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strBothInternal, fShaderPriority, bShaderLayered, iTypeMask, + uiShaderCreateTime, bShaderUsesVertexShader, bAppendLayers); } } } @@ -617,8 +617,8 @@ void CRenderWareSA::AppendAdditiveMatch(CSHADERDUMMY* pShaderData, CClientEntity SString strInternalPattern = strTextureNameMatch.ReplaceI("white", "@hite"); if (strInternalPattern != strTextureNameMatch) { - m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strInternalPattern, fShaderPriority, bShaderLayered, iTypeMask, uiShaderCreateTime, - bShaderUsesVertexShader, bAppendLayers); + m_pMatchChannelManager->AppendAdditiveMatch(pShaderData, pClientEntity, strInternalPattern, fShaderPriority, bShaderLayered, iTypeMask, + uiShaderCreateTime, bShaderUsesVertexShader, bAppendLayers); } } @@ -650,16 +650,16 @@ void CRenderWareSA::AppendSubtractiveMatch(CSHADERDUMMY* pShaderData, CClientEnt // Also register with internal texture name variant (same logic as AppendAdditiveMatch) SString strLower = strTextureNameMatch.ToLower(); - bool bHasRemap = strLower.Contains("remap"); - bool bHasWhite = strLower.Contains("white"); - + bool bHasRemap = strLower.Contains("remap"); + bool bHasWhite = strLower.Contains("white"); + if (bHasRemap) { SString strInternalPattern = strTextureNameMatch.ReplaceI("remap", "#emap"); if (strInternalPattern != strTextureNameMatch) { m_pMatchChannelManager->AppendSubtractiveMatch(pShaderData, pClientEntity, strInternalPattern); - + // If pattern also contains "white", register the doubly-transformed variant if (bHasWhite) { @@ -694,7 +694,7 @@ void CRenderWareSA::OnTextureStreamIn(STexInfo* pTexInfo) { if (!pTexInfo) return; - + // Insert into all channels that match the name m_pMatchChannelManager->InsertTexture(pTexInfo); } @@ -710,7 +710,7 @@ void CRenderWareSA::OnTextureStreamOut(STexInfo* pTexInfo) { if (!pTexInfo) return; - + m_pMatchChannelManager->RemoveTexture(pTexInfo); } @@ -838,19 +838,19 @@ void CRenderWareSA::SetGTAVertexShadersEnabled(bool bEnable) if (bEnable) { // Allow GTA vertex shaders (default) - MemPut(pSkinAtomic + 0, 0x8B); // mov eax, [edi+20h] + MemPut(pSkinAtomic + 0, 0x8B); // mov eax, [edi+20h] MemPut(pSkinAtomic + 1, 0x47); MemPut(pSkinAtomic + 2, 0x20); - MemPut(pSkinAtomic + 3, 0x85); // test eax, eax + MemPut(pSkinAtomic + 3, 0x85); // test eax, eax MemPut(pSkinAtomic + 4, 0xC0); } else { // Disallow GTA vertex shaders // This forces the current skin buffer to use software blending from now on - MemPut(pSkinAtomic + 0, 0x33); // xor eax, eax + MemPut(pSkinAtomic + 0, 0x33); // xor eax, eax MemPut(pSkinAtomic + 1, 0xC0); - MemPut(pSkinAtomic + 2, 0x89); // mov dword ptr [edi+20h], eax + MemPut(pSkinAtomic + 2, 0x89); // mov dword ptr [edi+20h], eax MemPut(pSkinAtomic + 3, 0x47); MemPut(pSkinAtomic + 4, 0x20); } @@ -878,9 +878,9 @@ __declspec(noinline) void OnMY_RwTextureSetName(DWORD dwAddrCalledFrom, RwTextur } // Hook info -#define HOOKPOS_RwTextureSetName 0x7F38A0 -#define HOOKSIZE_RwTextureSetName 9 -DWORD RETURN_RwTextureSetName = 0x7F38A9; +#define HOOKPOS_RwTextureSetName 0x7F38A0 +#define HOOKSIZE_RwTextureSetName 9 +DWORD RETURN_RwTextureSetName = 0x7F38A9; static void __declspec(naked) HOOK_RwTextureSetName() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -916,9 +916,9 @@ __declspec(noinline) void OnMY_RwTextureDestroy_Mid(RwTexture* pTexture) } // Hook info -#define HOOKPOS_RwTextureDestroy_Mid 0x07F3834 -#define HOOKSIZE_RwTextureDestroy_Mid 5 -DWORD RETURN_RwTextureDestroy_Mid = 0x07F3839; +#define HOOKPOS_RwTextureDestroy_Mid 0x07F3834 +#define HOOKSIZE_RwTextureDestroy_Mid 5 +DWORD RETURN_RwTextureDestroy_Mid = 0x07F3839; static void __declspec(naked) HOOK_RwTextureDestroy_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -950,7 +950,7 @@ __declspec(noinline) void OnMY_RwIm3DRenderIndexedPrimitive_Pre(DWORD dwAddrCall if (dwAddrCalledFrom == ADDR_CVehicle_DoHeadLightBeam_RenderPrimitive || dwAddrCalledFrom == ADDR_CHeli_SearchLightCone_RenderPrimitive || dwAddrCalledFrom == ADDR_CWaterCannon_Render_RenderPrimitive) { - CRenderWareSA::ms_iRenderingType = RT_NONE; // Treat these items like world models + CRenderWareSA::ms_iRenderingType = RT_NONE; // Treat these items like world models } else { @@ -964,9 +964,9 @@ __declspec(noinline) void OnMY_RwIm3DRenderIndexedPrimitive_Post(DWORD dwAddrCal } // Hook info -#define HOOKPOS_RwIm3DRenderIndexedPrimitive 0x07EF550 -#define HOOKSIZE_RwIm3DRenderIndexedPrimitive 5 -DWORD RETURN_RwIm3DRenderIndexedPrimitive = 0x07EF555; +#define HOOKPOS_RwIm3DRenderIndexedPrimitive 0x07EF550 +#define HOOKSIZE_RwIm3DRenderIndexedPrimitive 5 +DWORD RETURN_RwIm3DRenderIndexedPrimitive = 0x07EF555; static void __declspec(naked) HOOK_RwIm3DRenderIndexedPrimitive() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1018,9 +1018,9 @@ __declspec(noinline) void OnMY_RwIm3DRenderPrimitive_Post(DWORD dwAddrCalledFrom } // Hook info -#define HOOKPOS_RwIm3DRenderPrimitive 0x07EF6B0 -#define HOOKSIZE_RwIm3DRenderPrimitive 6 -DWORD RETURN_RwIm3DRenderPrimitive = 0x07EF6B6; +#define HOOKPOS_RwIm3DRenderPrimitive 0x07EF6B0 +#define HOOKSIZE_RwIm3DRenderPrimitive 6 +DWORD RETURN_RwIm3DRenderPrimitive = 0x07EF6B6; static void __declspec(naked) HOOK_RwIm3DRenderPrimitive() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1072,9 +1072,9 @@ __declspec(noinline) void OnMY_RwIm2DRenderIndexedPrimitive_Post(DWORD dwAddrCal } // Hook info -#define HOOKPOS_RwIm2DRenderIndexedPrimitive 0x0734EA1 -#define HOOKSIZE_RwIm2DRenderIndexedPrimitive 5 -DWORD RETURN_RwIm2DRenderIndexedPrimitive = 0x0403927; +#define HOOKPOS_RwIm2DRenderIndexedPrimitive 0x0734EA1 +#define HOOKSIZE_RwIm2DRenderIndexedPrimitive 5 +DWORD RETURN_RwIm2DRenderIndexedPrimitive = 0x0403927; static void __declspec(naked) HOOK_RwIm2DRenderIndexedPrimitive() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1127,9 +1127,9 @@ __declspec(noinline) void OnMY_RwIm2DRenderPrimitive_Post(DWORD dwAddrCalledFrom } // Hook info -#define HOOKPOS_RwIm2DRenderPrimitive 0x0734E90 -#define HOOKSIZE_RwIm2DRenderPrimitive 5 -DWORD RETURN_RwIm2DRenderPrimitive = 0x0734E95; +#define HOOKPOS_RwIm2DRenderPrimitive 0x0734E90 +#define HOOKSIZE_RwIm2DRenderPrimitive 5 +DWORD RETURN_RwIm2DRenderPrimitive = 0x0734E95; static void __declspec(naked) HOOK_RwIm2DRenderPrimitive() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CRenderWareSA.ShaderSupport.h b/Client/game_sa/CRenderWareSA.ShaderSupport.h index 57d56d30da6..201503cd7f2 100644 --- a/Client/game_sa/CRenderWareSA.ShaderSupport.h +++ b/Client/game_sa/CRenderWareSA.ShaderSupport.h @@ -20,10 +20,10 @@ #endif // Various dodgy pointer values -#define FAKE_D3DTEXTURE_EMPTY_KEY ( (CD3DDUMMY*)-1 ) -#define FAKE_D3DTEXTURE_DELETED_KEY ( (CD3DDUMMY*)-2 ) -#define FAKE_D3DTEXTURE_NO_TEXTURE ( (CD3DDUMMY*)-9 ) -#define FAKE_RWTEXTURE_NO_TEXTURE ( (RwTexture*)-10 ) +#define FAKE_D3DTEXTURE_EMPTY_KEY ((CD3DDUMMY*)-1) +#define FAKE_D3DTEXTURE_DELETED_KEY ((CD3DDUMMY*)-2) +#define FAKE_D3DTEXTURE_NO_TEXTURE ((CD3DDUMMY*)-9) +#define FAKE_RWTEXTURE_NO_TEXTURE ((RwTexture*)-10) #define FAKE_NAME_NO_TEXTURE "unnamed" // CFastHashMap key funcs for CD3DDUMMY* - must be declared before CFastHashMap is used @@ -56,8 +56,8 @@ struct STexTag [[nodiscard]] bool operator==(RwTexture* pTex) const { return !m_bUsingTxdId && pTex == m_pTex; } const bool m_bUsingTxdId; - const ushort m_usTxdId; // Streamed textures are identified using the TXD id - const RwTexture* m_pTex; // Custom textures are identified using the RwTexture pointer + const ushort m_usTxdId; // Streamed textures are identified using the TXD id + const RwTexture* m_pTex; // Custom textures are identified using the RwTexture pointer }; struct SOrderValue @@ -70,7 +70,7 @@ struct SOrderValue return fOrderPriority < other.fOrderPriority || (fOrderPriority == other.fOrderPriority && uiShaderCreateTime < other.uiShaderCreateTime); } - const float fOrderPriority; // Lower is higher priority + const float fOrderPriority; // Lower is higher priority const uint uiShaderCreateTime; }; @@ -105,7 +105,7 @@ struct STexInfo { } STexTag texTag; - const SString strTextureName; // Always lower case + const SString strTextureName; // Always lower case CD3DDUMMY* const pD3DData; STexNameInfo* pAssociatedTexNameInfo; }; @@ -133,7 +133,7 @@ struct SShaderInfoLayers { SShaderInfoInstance pBase; std::vector layerList; - SShaderItemLayers output; // For renderer + SShaderItemLayers output; // For renderer #ifdef SHADER_DEBUG_CHECKS [[nodiscard]] bool operator==(const SShaderInfoLayers& other) const @@ -206,11 +206,11 @@ struct STexNameInfo return texNoEntityShaders[idx]; } - const SString strTextureName; // Always lower case + const SString strTextureName; // Always lower case CFastHashSet usedByTexInfoList; CFastHashSet matchChannelList; - STexShaderReplacement texNoEntityShaders[5]; // 0 - world 1-ped 2-vehicle 3-object 4-other + STexShaderReplacement texNoEntityShaders[5]; // 0 - world 1-ped 2-vehicle 3-object 4-other CFastHashMap texEntityShaderMap; #ifdef SHADER_DEBUG_CHECKS diff --git a/Client/game_sa/CRenderWareSA.StreamingMemory.cpp b/Client/game_sa/CRenderWareSA.StreamingMemory.cpp index 45a66903cf9..d7a6eaa6f17 100644 --- a/Client/game_sa/CRenderWareSA.StreamingMemory.cpp +++ b/Client/game_sa/CRenderWareSA.StreamingMemory.cpp @@ -23,75 +23,75 @@ extern CGameSA* pGame; namespace StreamingMemory { -constexpr std::uint32_t kMinBytesToClean = 64U * 1024U; -constexpr std::uint32_t kMaxReasonableEstimate = 512U * 1024U * 1024U; // 512 MB + constexpr std::uint32_t kMinBytesToClean = 64U * 1024U; + constexpr std::uint32_t kMaxReasonableEstimate = 512U * 1024U * 1024U; // 512 MB -void PrepareStreamingMemoryForSize(std::uint32_t estimatedBytes) -{ - if (estimatedBytes < kMinBytesToClean) - return; - - if (!pGame) - return; + void PrepareStreamingMemoryForSize(std::uint32_t estimatedBytes) + { + if (estimatedBytes < kMinBytesToClean) + return; - auto* pStreaming = pGame->GetStreaming(); - if (!pStreaming) - return; + if (!pGame) + return; - std::uint32_t memoryLimitKB = 0; - __try - { - memoryLimitKB = *reinterpret_cast(VAR_CStreaming_memoryAvailableKB); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - return; - } - if (memoryLimitKB == 0) - return; + auto* pStreaming = pGame->GetStreaming(); + if (!pStreaming) + return; - std::uint64_t memoryLimitBytes64 = static_cast(memoryLimitKB) * 1024ULL; - if (memoryLimitBytes64 > std::numeric_limits::max()) - memoryLimitBytes64 = std::numeric_limits::max(); - const std::uint32_t memoryLimitBytes = static_cast(memoryLimitBytes64); + std::uint32_t memoryLimitKB = 0; + __try + { + memoryLimitKB = *reinterpret_cast(VAR_CStreaming_memoryAvailableKB); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return; + } + if (memoryLimitKB == 0) + return; - if (memoryLimitBytes <= 1) - return; + std::uint64_t memoryLimitBytes64 = static_cast(memoryLimitKB) * 1024ULL; + if (memoryLimitBytes64 > std::numeric_limits::max()) + memoryLimitBytes64 = std::numeric_limits::max(); + const std::uint32_t memoryLimitBytes = static_cast(memoryLimitBytes64); - std::uint32_t bytesToClean = std::min(estimatedBytes, kMaxReasonableEstimate); - if (bytesToClean >= memoryLimitBytes) - { - const std::uint32_t maxClean = static_cast((static_cast(memoryLimitBytes) * 3) / 4); - bytesToClean = std::min(maxClean, memoryLimitBytes - 1); - } + if (memoryLimitBytes <= 1) + return; - if (bytesToClean == 0) - return; + std::uint32_t bytesToClean = std::min(estimatedBytes, kMaxReasonableEstimate); + if (bytesToClean >= memoryLimitBytes) + { + const std::uint32_t maxClean = static_cast((static_cast(memoryLimitBytes) * 3) / 4); + bytesToClean = std::min(maxClean, memoryLimitBytes - 1); + } - std::uint32_t memoryUsedBytes = 0; - __try - { - memoryUsedBytes = *reinterpret_cast(VAR_CStreaming_memoryUsed); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - return; - } - if (memoryUsedBytes < memoryLimitBytes) - { - const std::uint32_t freeBytes = memoryLimitBytes - memoryUsedBytes; - if (freeBytes >= bytesToClean) + if (bytesToClean == 0) return; - } - __try - { - pStreaming->MakeSpaceFor(bytesToClean); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - return; + std::uint32_t memoryUsedBytes = 0; + __try + { + memoryUsedBytes = *reinterpret_cast(VAR_CStreaming_memoryUsed); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return; + } + if (memoryUsedBytes < memoryLimitBytes) + { + const std::uint32_t freeBytes = memoryLimitBytes - memoryUsedBytes; + if (freeBytes >= bytesToClean) + return; + } + + __try + { + pStreaming->MakeSpaceFor(bytesToClean); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return; + } } -} } diff --git a/Client/game_sa/CRenderWareSA.TextureReplacing.cpp b/Client/game_sa/CRenderWareSA.TextureReplacing.cpp index 7bfa7ba6713..f25ea1aca1c 100644 --- a/Client/game_sa/CRenderWareSA.TextureReplacing.cpp +++ b/Client/game_sa/CRenderWareSA.TextureReplacing.cpp @@ -12,9 +12,10 @@ // 3. Re-link textures if race detected (prevents white textures) // 4. Re-acquire ref before using TXD pointers after checks -// The logic in CRenderWareSA.TextureReplacing.cpp is very peculiar and must be kept to work best (and most safely) with GTA's streaming system (Which we barely control). -// Changing something can have a domino effect, with effects not immediately obvious. The logic as present during the git blame date of this comment is a result of very painful trial and error. -// Future contributors need to be aware of the rules of engagement, and need to have researched relevant parts of the SA engine and RW. +// The logic in CRenderWareSA.TextureReplacing.cpp is very peculiar and must be kept to work best (and most safely) with GTA's streaming system (Which we barely +// control). Changing something can have a domino effect, with effects not immediately obvious. The logic as present during the git blame date of this comment +// is a result of very painful trial and error. Future contributors need to be aware of the rules of engagement, and need to have researched relevant parts of +// the SA engine and RW. #include "StdInc.h" #include "CGameSA.h" @@ -31,24 +32,24 @@ #include #include #include -#include +#include extern CGameSA* pGame; struct CModelTexturesInfo { - unsigned short usTxdId = 0; - RwTexDictionary* pTxd = nullptr; - std::unordered_set originalTextures; + unsigned short usTxdId = 0; + RwTexDictionary* pTxd = nullptr; + std::unordered_set originalTextures; std::unordered_map originalTexturesByName; - std::vector usedByReplacements; - bool bReapplyingTextures = false; - bool bHasLeakedTextures = false; - SString strDebugLabel; + std::vector usedByReplacements; + bool bReapplyingTextures = false; + bool bHasLeakedTextures = false; + SString strDebugLabel; }; static std::map ms_ModelTexturesInfoMap; -static uint32_t ms_uiTextureReplacingSession = 1; // Incremented at disconnect/reconnect boundaries +static uint32_t ms_uiTextureReplacingSession = 1; // Incremented at disconnect/reconnect boundaries namespace { @@ -93,10 +94,7 @@ namespace SReplacementTextures* pReplacement; unsigned short usTxdId; - bool operator==(const ReplacementShaderKey& rhs) const noexcept - { - return pReplacement == rhs.pReplacement && usTxdId == rhs.usTxdId; - } + bool operator==(const ReplacementShaderKey& rhs) const noexcept { return pReplacement == rhs.pReplacement && usTxdId == rhs.usTxdId; } }; struct ReplacementShaderKeyHash @@ -116,8 +114,8 @@ namespace // Shared isolated TXD slots for requested models (clones with same parent share one TXD) struct SSharedIsolatedTxd { - unsigned short usTxdId = 0; - unsigned short usParentTxdId = 0; + unsigned short usTxdId = 0; + unsigned short usParentTxdId = 0; std::unordered_set modelIds; }; @@ -125,8 +123,8 @@ namespace std::unordered_map g_SharedIsolatedTxdByParentTxd; // Maps model ID -> parent TXD ID (reverse lookup for cleanup) std::unordered_map g_ModelParentTxdForIsolation; - std::unordered_set g_OrphanedIsolatedTxdSlots; - std::unordered_set g_PendingSharedIsolatedTxdParents; + std::unordered_set g_OrphanedIsolatedTxdSlots; + std::unordered_set g_PendingSharedIsolatedTxdParents; // TXD slots at safety-cap during cleanup; tracked for diagnostics std::unordered_set g_PermanentlyLeakedTxdSlots; @@ -160,7 +158,7 @@ namespace return it == g_ShaderRegs.end() ? 0u : it->second.size(); } - template + template void ForEachShaderReg(SReplacementTextures* pReplacement, unsigned short usTxdId, Fn&& fn) { auto it = g_ShaderRegs.find(ReplacementShaderKey{pReplacement, usTxdId}); @@ -178,11 +176,11 @@ namespace std::string GetSafeTextureName(const RwTexture* pTexture) { const auto* name = pTexture->name; - const auto len = strnlen(name, RW_TEXTURE_NAME_LENGTH); + const auto len = strnlen(name, RW_TEXTURE_NAME_LENGTH); return std::string(name, len); } - template + template void SwapPopRemove(std::vector& vec, const T& value) { auto it = std::find(vec.begin(), vec.end(), value); @@ -255,8 +253,7 @@ namespace return out; } - RwTexture* FindReadableMasterForRaster(const std::unordered_map& masterRasterMap, - const std::vector& masters, + RwTexture* FindReadableMasterForRaster(const std::unordered_map& masterRasterMap, const std::vector& masters, RwRaster* raster) { if (!raster) @@ -283,29 +280,29 @@ namespace { info.originalTextures.clear(); info.originalTexturesByName.clear(); - + if (!pTxd) return; - + std::vector allTextures; CRenderWareSA::GetTxdTextures(allTextures, pTxd); - + for (RwTexture* pTex : allTextures) { if (pTex) info.originalTextures.insert(pTex); } - + // Build name map for lookup after replacements for (RwTexture* pTex : info.originalTextures) { if (!IsReadableTexture(pTex)) continue; - + const std::size_t nameLen = strnlen(pTex->name, RW_TEXTURE_NAME_LENGTH); if (nameLen >= RW_TEXTURE_NAME_LENGTH) continue; - + info.originalTexturesByName[std::string(pTex->name, nameLen)] = pTex; } } @@ -333,8 +330,8 @@ namespace RwListEntry* pNext = pTexture->TXDList.next; RwListEntry* pPrev = pTexture->TXDList.prev; - if (pNext && pPrev && pNext != &pTexture->TXDList && pPrev != &pTexture->TXDList && - pNext->prev == &pTexture->TXDList && pPrev->next == &pTexture->TXDList) + if (pNext && pPrev && pNext != &pTexture->TXDList && pPrev != &pTexture->TXDList && pNext->prev == &pTexture->TXDList && + pPrev->next == &pTexture->TXDList) { pPrev->next = pNext; pNext->prev = pPrev; @@ -394,7 +391,7 @@ namespace outMap.reserve(32); constexpr std::size_t kMaxTextures = 8192; - std::size_t count = 0; + std::size_t count = 0; while (pNode != pRoot) { @@ -471,9 +468,10 @@ namespace auto* pTxdPoolSA = static_cast(&txdPool); constexpr unsigned short kInvalidTxdId = static_cast(-1); - constexpr int kMaxDepth = 32; // Prevent infinite loops + constexpr int kMaxDepth = 32; // Prevent infinite loops - auto ContainsVehicleTxdInParentChain = [&](unsigned short startTxdId) -> bool { + auto ContainsVehicleTxdInParentChain = [&](unsigned short startTxdId) -> bool + { unsigned short usTxdId = startTxdId; for (int depth = 0; depth < kMaxDepth; ++depth) { @@ -517,10 +515,8 @@ namespace return false; } - void CleanupStalePerTxd(SReplacementTextures::SPerTxd& perTxdInfo, RwTexDictionary* pDeadTxd, - SReplacementTextures* pReplacementTextures, - const std::unordered_set* pMasterTextures, - std::unordered_set& outCopiesToDestroy, + void CleanupStalePerTxd(SReplacementTextures::SPerTxd& perTxdInfo, RwTexDictionary* pDeadTxd, SReplacementTextures* pReplacementTextures, + const std::unordered_set* pMasterTextures, std::unordered_set& outCopiesToDestroy, std::unordered_set& outOriginalsToDestroy) { const bool bDeadTxdValid = pDeadTxd != nullptr; @@ -557,7 +553,7 @@ namespace bool bIsActuallyCopy = perTxdInfo.bTexturesAreCopies; if (!bIsActuallyCopy && pReplacementTextures && pMasterTextures) bIsActuallyCopy = pMasterTextures->find(pTexture) == pMasterTextures->end(); - + if (bIsActuallyCopy) outCopiesToDestroy.insert(pTexture); } @@ -600,7 +596,7 @@ namespace return; constexpr int MAX_MATERIALS = 10000; - int materialCount = materials.entries; + int materialCount = materials.entries; if (materialCount > MAX_MATERIALS) return; @@ -642,7 +638,7 @@ namespace if (!pRwObject) return false; - const unsigned char rwType = pRwObject->type; + const unsigned char rwType = pRwObject->type; const eModelInfoType modelType = pModelInfo->GetModelType(); if (modelType == eModelInfoType::UNKNOWN) @@ -778,7 +774,7 @@ namespace if (itShared != g_SharedIsolatedTxdByParentTxd.end()) { const unsigned short sharedTxdId = itShared->second.usTxdId; - auto* slot = pTxdPoolSA->GetTextureDictonarySlot(sharedTxdId); + auto* slot = pTxdPoolSA->GetTextureDictonarySlot(sharedTxdId); if (slot && slot->rwTexDictonary && slot->usParentIndex == usParentTxdId) { if (pModelInfo->GetTextureDictionaryID() != sharedTxdId) @@ -787,7 +783,7 @@ namespace } } } - + // Model's parent changed or shared TXD became invalid - remove from old registration auto itOldShared = g_SharedIsolatedTxdByParentTxd.find(registeredParentTxdId); if (itOldShared != g_SharedIsolatedTxdByParentTxd.end()) @@ -811,8 +807,9 @@ namespace if (!pReplacement) continue; - auto itOldPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), - [oldIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == oldIsolatedTxdId; }); + auto itOldPerTxd = + std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), + [oldIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == oldIsolatedTxdId; }); if (itOldPerTxd != pReplacement->perTxdList.end()) { @@ -851,7 +848,7 @@ namespace if (itOldShared->second.modelIds.empty()) { const unsigned short oldTxdId = itOldShared->second.usTxdId; - auto* oldSlot = pTxdPoolSA->GetTextureDictonarySlot(oldTxdId); + auto* oldSlot = pTxdPoolSA->GetTextureDictonarySlot(oldTxdId); if (oldSlot && oldSlot->rwTexDictonary && oldSlot->usParentIndex == registeredParentTxdId) { // Clear shader system entries before TXD destruction @@ -864,17 +861,16 @@ namespace // Orphan remaining textures using two-phase approach for linked list safety: // 1. Collect all texture pointers first (avoids modification during iteration) // 2. Use SafeOrphanTexture which properly unlinks via RW API - RwTexDictionary* pTxd = oldSlot->rwTexDictonary; - RwListEntry* pRoot = &pTxd->textures.root; - RwListEntry* pNode = pRoot->next; - constexpr std::size_t kMaxOrphanTextures = 8192; + RwTexDictionary* pTxd = oldSlot->rwTexDictonary; + RwListEntry* pRoot = &pTxd->textures.root; + RwListEntry* pNode = pRoot->next; + constexpr std::size_t kMaxOrphanTextures = 8192; std::vector texturesToOrphan; texturesToOrphan.reserve(64); std::size_t count = 0; while (pNode && pNode != pRoot && count < kMaxOrphanTextures) { - RwTexture* pTex = reinterpret_cast( - reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); + RwTexture* pTex = reinterpret_cast(reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); if (pTex && pTex->txd == pTxd) texturesToOrphan.push_back(pTex); pNode = pNode->next; @@ -931,7 +927,7 @@ namespace { // Model has a valid isolated TXD with correct parent - try to adopt it auto itExistingShared = g_SharedIsolatedTxdByParentTxd.find(usParentTxdId); - + if (itExistingShared == g_SharedIsolatedTxdByParentTxd.end()) { // No shared TXD tracked for this parent - adopt model's TXD as the shared one @@ -945,7 +941,7 @@ namespace g_PendingSharedIsolatedTxdParents.insert(usParentTxdId); return true; } - + if (itExistingShared->second.usTxdId == usModelTxdId) { // Model already points to our tracked shared TXD - just register it @@ -953,11 +949,11 @@ namespace g_ModelParentTxdForIsolation.emplace(usModelId, usParentTxdId); return true; } - + // Model has a different isolated TXD than our tracked shared one // Fall through to reset and join the authoritative tracked shared TXD } - + // Reset model to parent TXD before attempting to join/create shared TXD pModelInfo->SetTextureDictionaryID(usParentTxdId); } @@ -967,7 +963,7 @@ namespace if (itShared != g_SharedIsolatedTxdByParentTxd.end()) { const unsigned short sharedTxdId = itShared->second.usTxdId; - auto* slot = pTxdPoolSA->GetTextureDictonarySlot(sharedTxdId); + auto* slot = pTxdPoolSA->GetTextureDictonarySlot(sharedTxdId); if (slot && slot->rwTexDictonary && slot->usParentIndex == usParentTxdId) { // Valid shared TXD exists - join it @@ -993,15 +989,14 @@ namespace joinModelType = eModelInfoType::CLUMP; } - if (joinModelType == eModelInfoType::PED || joinModelType == eModelInfoType::WEAPON || - joinModelType == eModelInfoType::VEHICLE || joinModelType == eModelInfoType::CLUMP) + if (joinModelType == eModelInfoType::PED || joinModelType == eModelInfoType::WEAPON || joinModelType == eModelInfoType::VEHICLE || + joinModelType == eModelInfoType::CLUMP) { auto* pRenderWareSA = pGame->GetRenderWareSA(); if (pRenderWareSA) pRenderWareSA->RebindClumpTexturesToTxd(reinterpret_cast(pRwObject), sharedTxdId); } - else if (joinModelType == eModelInfoType::ATOMIC || joinModelType == eModelInfoType::LOD_ATOMIC || - joinModelType == eModelInfoType::TIME) + else if (joinModelType == eModelInfoType::ATOMIC || joinModelType == eModelInfoType::LOD_ATOMIC || joinModelType == eModelInfoType::TIME) { auto* pAtomic = reinterpret_cast(pRwObject); if (pAtomic && pAtomic->geometry) @@ -1010,7 +1005,7 @@ namespace if (materials.materials && materials.entries > 0) { constexpr int kMaxMaterials = 10000; - const int materialCount = materials.entries; + const int materialCount = materials.entries; if (materialCount <= kMaxMaterials) { for (int idx = 0; idx < materialCount; ++idx) @@ -1023,7 +1018,7 @@ namespace if (!szTexName[0] || strnlen(szTexName, RW_TEXTURE_NAME_LENGTH) >= RW_TEXTURE_NAME_LENGTH) continue; - auto itTex = joinTxdMap.find(szTexName); + auto itTex = joinTxdMap.find(szTexName); RwTexture* pNewTex = (itTex != joinTxdMap.end()) ? itTex->second : nullptr; if (!pNewTex) @@ -1051,7 +1046,7 @@ namespace // Shared TXD slot is stale (destroyed or parent mismatch). Restore all // models using it back to their parent TXD before cleaning up the slot. // First build swap maps to restore materials, as materials may point to stale TXD textures. - TxdTextureMap staleParentTxdMap; + TxdTextureMap staleParentTxdMap; RwTexDictionary* pStaleParentTxd = CTxdStore_GetTxd(usParentTxdId); if (pStaleParentTxd) BuildTxdTextureMapFast(pStaleParentTxd, staleParentTxdMap); @@ -1073,8 +1068,7 @@ namespace } // Swap materials back to parent textures before reverting TXD ID - if (pOtherModel->GetTextureDictionaryID() == sharedTxdId && - itStaleInfo != ms_ModelTexturesInfoMap.end() && pStaleParentTxd) + if (pOtherModel->GetTextureDictionaryID() == sharedTxdId && itStaleInfo != ms_ModelTexturesInfoMap.end() && pStaleParentTxd) { for (SReplacementTextures* pReplacement : itStaleInfo->second.usedByReplacements) { @@ -1082,7 +1076,7 @@ namespace continue; auto itPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), - [sharedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == sharedTxdId; }); + [sharedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == sharedTxdId; }); if (itPerTxd != pReplacement->perTxdList.end()) { @@ -1134,17 +1128,16 @@ namespace // Orphan remaining textures using two-phase approach for linked list safety: // 1. Collect all texture pointers first (avoids modification during iteration) // 2. Use SafeOrphanTexture which properly unlinks via RW API - RwTexDictionary* pTxd = slot->rwTexDictonary; - RwListEntry* pRoot = &pTxd->textures.root; - RwListEntry* pNode = pRoot->next; - constexpr std::size_t kMaxOrphanTextures = 8192; + RwTexDictionary* pTxd = slot->rwTexDictonary; + RwListEntry* pRoot = &pTxd->textures.root; + RwListEntry* pNode = pRoot->next; + constexpr std::size_t kMaxOrphanTextures = 8192; std::vector texturesToOrphan; texturesToOrphan.reserve(64); std::size_t count = 0; while (pNode && pNode != pRoot && count < kMaxOrphanTextures) { - RwTexture* pTex = reinterpret_cast( - reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); + RwTexture* pTex = reinterpret_cast(reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); if (pTex && pTex->txd == pTxd) texturesToOrphan.push_back(pTex); pNode = pNode->next; @@ -1208,7 +1201,8 @@ namespace if (pTxdPoolSA->AllocateTextureDictonarySlot(usNewTxdId, txdName) == static_cast(-1)) { - AddReportLog(9401, SString("EnsureIsolatedTxdForRequestedModel: AllocateTextureDictonarySlot failed for parentTxd %u txdId=%u", usParentTxdId, usNewTxdId)); + AddReportLog( + 9401, SString("EnsureIsolatedTxdForRequestedModel: AllocateTextureDictonarySlot failed for parentTxd %u txdId=%u", usParentTxdId, usNewTxdId)); return false; } @@ -1224,7 +1218,8 @@ namespace // Associate the TXD with the slot and set parent linkage if (!pTxdPoolSA->SetTextureDictonarySlot(usNewTxdId, pChildTxd, usParentTxdId)) { - AddReportLog(9401, SString("EnsureIsolatedTxdForRequestedModel: SetTextureDictonarySlot failed for parentTxd %u txdId=%u", usParentTxdId, usNewTxdId)); + AddReportLog(9401, + SString("EnsureIsolatedTxdForRequestedModel: SetTextureDictonarySlot failed for parentTxd %u txdId=%u", usParentTxdId, usNewTxdId)); RwTexDictionaryDestroy(pChildTxd); pTxdPoolSA->RemoveTextureDictonarySlot(usNewTxdId); return false; @@ -1246,7 +1241,8 @@ namespace CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); if (!pStreamInfo) { - AddReportLog(9401, SString("EnsureIsolatedTxdForRequestedModel: GetStreamingInfo failed for parentTxd %u streamId=%u", usParentTxdId, usTxdStreamId)); + AddReportLog(9401, + SString("EnsureIsolatedTxdForRequestedModel: GetStreamingInfo failed for parentTxd %u streamId=%u", usParentTxdId, usTxdStreamId)); pTxdPoolSA->RemoveTextureDictonarySlot(usNewTxdId); return false; } @@ -1367,7 +1363,7 @@ void CRenderWareSA::ProcessPendingIsolatedTxdParents() RwTexDictionary* pTxd = CTxdStore_GetTxd(childTxdId); if (pTxd) { - TxdTextureMap txdTextureMap; + TxdTextureMap txdTextureMap; RwTexDictionary* pParentTxd = CTxdStore_GetTxd(parentTxdId); if (pParentTxd) BuildTxdTextureMapFast(pParentTxd, txdTextureMap); @@ -1383,7 +1379,7 @@ void CRenderWareSA::ProcessPendingIsolatedTxdParents() if (materials.materials && materials.entries > 0) { constexpr int kMaxMaterials = 10000; - const int materialCount = materials.entries; + const int materialCount = materials.entries; if (materialCount <= kMaxMaterials) { for (int idx = 0; idx < materialCount; ++idx) @@ -1455,7 +1451,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId if (it != ms_ModelTexturesInfoMap.end()) { CModelTexturesInfo& info = it->second; - RwTexDictionary* pCurrentTxd = CTxdStore_GetTxd(usTxdId); + RwTexDictionary* pCurrentTxd = CTxdStore_GetTxd(usTxdId); if (info.bReapplyingTextures) { @@ -1468,12 +1464,13 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId } const bool bIsStaleEntry = (info.pTxd != pCurrentTxd) || (!info.pTxd && !pCurrentTxd); - + if (bIsStaleEntry) { - unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); + unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); CStreamingInfo* pStreamInfoBusyCheck = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bBusy = pStreamInfoBusyCheck && (pStreamInfoBusyCheck->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfoBusyCheck->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bBusy = pStreamInfoBusyCheck && (pStreamInfoBusyCheck->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfoBusyCheck->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusy && !pCurrentTxd) return nullptr; @@ -1490,7 +1487,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId } std::vector>> replacementsToReapply; - std::vector originalUsed; + std::vector originalUsed; for (SReplacementTextures* pReplacement : info.usedByReplacements) { if (pReplacement) @@ -1541,7 +1538,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId BuildTxdTextureMapFast(pCurrentTxd, freshTxdMap); TxdTextureMap parentTxdMap; - auto& txdPool = pGame->GetPools()->GetTxdPool(); + auto& txdPool = pGame->GetPools()->GetTxdPool(); if (auto* pTxdPoolSA = static_cast(&txdPool)) { if (auto* pTxdSlot = pTxdPoolSA->GetTextureDictonarySlot(usTxdId)) @@ -1604,8 +1601,8 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId for (SReplacementTextures* pReplacement : info.usedByReplacements) { - auto itPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), - [usTxdId](const SReplacementTextures::SPerTxd& item) { return item.usTxdId == usTxdId; }); + auto itPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), + [usTxdId](const SReplacementTextures::SPerTxd& item) { return item.usTxdId == usTxdId; }); if (itPerTxd != pReplacement->perTxdList.end()) { @@ -1620,7 +1617,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId continue; RwTexture* pFresh = nullptr; - auto itFresh = freshTxdMap.find(pTex->name); + auto itFresh = freshTxdMap.find(pTex->name); if (itFresh != freshTxdMap.end() && IsReadableTexture(itFresh->second)) pFresh = itFresh->second; @@ -1658,7 +1655,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId } ForEachShaderReg(pReplacement, itPerTxd->usTxdId, - [txdId = itPerTxd->usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(txdId, pD3D); }); + [txdId = itPerTxd->usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(txdId, pD3D); }); ClearShaderRegs(pReplacement, itPerTxd->usTxdId); CleanupStalePerTxd(*itPerTxd, info.pTxd, pReplacement, nullptr, copiesToDestroy, originalsToDestroy); @@ -1668,7 +1665,6 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId } pReplacement->usedInTxdIds.erase(usTxdId); - } // Destroy copies (nullify raster to prevent double-free of shared raster) @@ -1728,10 +1724,11 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId } else { - unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); + unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bLoaded = pStreamInfo && pStreamInfo->loadState == eModelLoadState::LOADSTATE_LOADED; - bool bBusyStream = pStreamInfo && (pStreamInfo->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfo->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bLoaded = pStreamInfo && pStreamInfo->loadState == eModelLoadState::LOADSTATE_LOADED; + bool bBusyStream = pStreamInfo && (pStreamInfo->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfo->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusyStream) { restoreState(); @@ -1754,7 +1751,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId MapRemove(ms_ModelTexturesInfoMap, usTxdId); return nullptr; } - + pCurrentTxd = CTxdStore_GetTxd(usTxdId); if (pCurrentTxd) @@ -1776,7 +1773,8 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId else { CStreamingInfo* pStreamInfoRetry = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bBusyRetry = pStreamInfoRetry && (pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bBusyRetry = pStreamInfoRetry && (pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusyRetry) { restoreState(); @@ -1797,7 +1795,8 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId else { CStreamingInfo* pStreamInfoRetry2 = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bBusy = pStreamInfoRetry2 && (pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bBusy = pStreamInfoRetry2 && (pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusy) { restoreState(); @@ -1852,11 +1851,11 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId g_bInTxdReapply = true; RwTexDictionary* txdAtStart = pCurrentTxd; - bool bTxdAlreadyPopulated = false; + bool bTxdAlreadyPopulated = false; for (auto& reapplyEntry : replacementsToReapply) { - SReplacementTextures* pReplacement = reapplyEntry.first; + SReplacementTextures* pReplacement = reapplyEntry.first; const std::vector& modelIds = reapplyEntry.second; if (bTxdAlreadyPopulated) @@ -1868,7 +1867,7 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId break; unsigned short firstModelId = modelIds[0]; - const bool applied = pRenderWareSA->ModelInfoTXDAddTextures(pReplacement, firstModelId); + const bool applied = pRenderWareSA->ModelInfoTXDAddTextures(pReplacement, firstModelId); if (applied) { bTxdAlreadyPopulated = true; @@ -1900,9 +1899,9 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId // spawns, its TXD won't be loaded via normal streaming. Load it on-demand here. if (!pTxd) { - unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); + unsigned int uiTxdStreamId = usTxdId + pGame->GetBaseIDforTXD(); CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bLoaded = pStreamInfo && pStreamInfo->loadState == eModelLoadState::LOADSTATE_LOADED; + bool bLoaded = pStreamInfo && pStreamInfo->loadState == eModelLoadState::LOADSTATE_LOADED; if (!bLoaded) { pGame->GetStreaming()->RequestModel(uiTxdStreamId, 0x16); @@ -1913,7 +1912,8 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId if (!pTxd) { CStreamingInfo* pStreamInfoRetry = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bBusy = pStreamInfoRetry && (pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bBusy = pStreamInfoRetry && (pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfoRetry->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusy) return nullptr; @@ -1923,7 +1923,8 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId if (!pTxd) { CStreamingInfo* pStreamInfoRetry2 = pGame->GetStreaming()->GetStreamingInfo(uiTxdStreamId); - bool bBusyRetry = pStreamInfoRetry2 && (pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_READING || pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_FINISHING); + bool bBusyRetry = pStreamInfoRetry2 && (pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_READING || + pStreamInfoRetry2->loadState == eModelLoadState::LOADSTATE_FINISHING); if (bBusyRetry) return nullptr; @@ -1944,17 +1945,18 @@ CModelTexturesInfo* CRenderWareSA::GetModelTexturesInfo(unsigned short usModelId if (!pTxd) { - AddReportLog(9401, SString("GetModelTexturesInfo: CTxdStore_GetTxd returned null for model %u txdId=%u (after TXD streaming request)", usModelId, usTxdId)); + AddReportLog(9401, + SString("GetModelTexturesInfo: CTxdStore_GetTxd returned null for model %u txdId=%u (after TXD streaming request)", usModelId, usTxdId)); return nullptr; } - auto itInserted = ms_ModelTexturesInfoMap.emplace(usTxdId, CModelTexturesInfo{}); + auto itInserted = ms_ModelTexturesInfoMap.emplace(usTxdId, CModelTexturesInfo{}); CModelTexturesInfo& newInfo = itInserted.first->second; newInfo.usTxdId = usTxdId; newInfo.pTxd = pTxd; PopulateOriginalTextures(newInfo, pTxd); - + return &newInfo; } @@ -2072,7 +2074,7 @@ bool CRenderWareSA::ModelInfoTXDLoadTextures(SReplacementTextures* pReplacementT *pOutError = "[ModelInfoTXDLoadTextures] TXD parsed successfully but contains no valid textures"; return false; } - + return true; } @@ -2081,7 +2083,8 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe { if (!pGame || !pReplacementTextures) { - AddReportLog(9401, SString("ModelInfoTXDAddTextures: Failed early - pGame=%p pReplacementTextures=%p model=%u", pGame, pReplacementTextures, usModelId)); + AddReportLog(9401, + SString("ModelInfoTXDAddTextures: Failed early - pGame=%p pReplacementTextures=%p model=%u", pGame, pReplacementTextures, usModelId)); return false; } @@ -2093,12 +2096,13 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe const unsigned short usParentModelId = pModelInfo->GetParentID(); if (usParentModelId != 0) { - auto* pParentInfo = static_cast(pGame->GetModelInfo(usParentModelId)); + auto* pParentInfo = static_cast(pGame->GetModelInfo(usParentModelId)); const unsigned short usParentTxdId = pParentInfo ? pParentInfo->GetTextureDictionaryID() : 0; const bool bIsolatedOk = EnsureIsolatedTxdForRequestedModel(usModelId); if (!bIsolatedOk) - AddReportLog(9401, SString("ModelInfoTXDAddTextures: EnsureIsolatedTxdForRequestedModel failed for model %u (parent=%u parentTxd=%u)", usModelId, usParentModelId, usParentTxdId)); + AddReportLog(9401, SString("ModelInfoTXDAddTextures: EnsureIsolatedTxdForRequestedModel failed for model %u (parent=%u parentTxd=%u)", + usModelId, usParentModelId, usParentTxdId)); } } } @@ -2121,13 +2125,14 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe AddReportLog(9401, SString("ModelInfoTXDAddTextures: No model info for model %u", usModelId)); return false; } - + pModelInfo->Request(BLOCKING, "CRenderWareSA::ModelInfoTXDAddTextures"); - + pInfo = GetModelTexturesInfo(usModelId, "ModelInfoTXDAddTextures-after-blocking"); if (!pInfo) { - AddReportLog(9401, SString("ModelInfoTXDAddTextures: GetModelTexturesInfo failed after blocking request for model %u (txdId=%u)", usModelId, pModelInfo->GetTextureDictionaryID())); + AddReportLog(9401, SString("ModelInfoTXDAddTextures: GetModelTexturesInfo failed after blocking request for model %u (txdId=%u)", usModelId, + pModelInfo->GetTextureDictionaryID())); return false; } } @@ -2152,22 +2157,22 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe bNeedTxdUpdate = true; } - bool bReplacementPresent = false; - bool bBuiltTxdTextureMap = false; - TxdTextureMap txdTextureMap; + bool bReplacementPresent = false; + bool bBuiltTxdTextureMap = false; + TxdTextureMap txdTextureMap; RwTexDictionary* pTxdToCheck = nullptr; - + if (pReplacementTextures->usedInTxdIds.find(pInfo->usTxdId) != pReplacementTextures->usedInTxdIds.end()) { auto itPerTxd = std::find_if(pReplacementTextures->perTxdList.begin(), pReplacementTextures->perTxdList.end(), - [pInfo](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == pInfo->usTxdId; }); + [pInfo](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == pInfo->usTxdId; }); if (itPerTxd != pReplacementTextures->perTxdList.end()) { pTxdToCheck = pCurrentTxd ? pCurrentTxd : pInfo->pTxd; const std::unordered_set* pOriginalTextures = &pInfo->originalTextures; - std::unordered_set currentOriginalTextures; + std::unordered_set currentOriginalTextures; if (bNeedTxdUpdate && pCurrentTxd) { CRenderWareSA::GetTxdTextures(currentOriginalTextures, pCurrentTxd); @@ -2196,7 +2201,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe bBuiltTxdTextureMap = true; } - auto itFound = txdTextureMap.find(pTex->name); + auto itFound = txdTextureMap.find(pTex->name); RwTexture* pFound = (itFound != txdTextureMap.end()) ? itFound->second : nullptr; if (pFound && pOriginalTextures->find(pFound) == pOriginalTextures->end()) { @@ -2211,15 +2216,15 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe { if (bNeedTxdUpdate && pCurrentTxd) pInfo->pTxd = pCurrentTxd; - + pReplacementTextures->usedInModelIds.insert(usModelId); return true; } - + if (itPerTxd != pReplacementTextures->perTxdList.end()) { ForEachShaderReg(pReplacementTextures, itPerTxd->usTxdId, - [usTxdId = itPerTxd->usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); + [usTxdId = itPerTxd->usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); ClearShaderRegs(pReplacementTextures, itPerTxd->usTxdId); if (!bNeedTxdUpdate) @@ -2237,7 +2242,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe TextureSwapMap swapMap; swapMap.reserve(itPerTxd->usingTextures.size()); const bool bCurrentTxdOk = pCurrentTxd != nullptr; - + const bool bCanReuseMap = bBuiltTxdTextureMap && pTxdToCheck == pCurrentTxd; if (bCurrentTxdOk && !bCanReuseMap) { @@ -2275,8 +2280,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe continue; RwTexture* pFreshOriginal = nullptr; - if (bCurrentTxdOk && - strnlen(pStaleReplacement->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) + if (bCurrentTxdOk && strnlen(pStaleReplacement->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) { auto itFound = currentTxdTextureMap.find(pStaleReplacement->name); pFreshOriginal = (itFound != currentTxdTextureMap.end()) ? itFound->second : nullptr; @@ -2337,7 +2341,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe if (texturesStillReferenced.find(pTexture) != texturesStillReferenced.end()) continue; - + if (CanDestroyOrphanedTexture(pTexture)) { SafeDestroyTexture(pTexture); @@ -2391,15 +2395,22 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe continue; uiTexturesWithValidRaster++; - auto NextPow2 = [](uint32_t v) { uint32_t p = 1; while (p < v && p < MAX_TEXTURE_DIMENSION) p <<= 1; return p; }; - + auto NextPow2 = [](uint32_t v) + { + uint32_t p = 1; + while (p < v && p < MAX_TEXTURE_DIMENSION) + p <<= 1; + return p; + }; + uint64_t size = (uint64_t)NextPow2(pNewTexture->raster->width) * (uint64_t)NextPow2(pNewTexture->raster->height) * 4; - + if (pNewTexture->raster->numLevels > 1) size += size / 3; - if (size > MAX_VRAM_SIZE) size = MAX_VRAM_SIZE; - + if (size > MAX_VRAM_SIZE) + size = MAX_VRAM_SIZE; + if ((uint64_t)uiTotalSize + size > MAX_VRAM_SIZE) uiTotalSize = MAX_VRAM_SIZE; else @@ -2409,7 +2420,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe if (uiTexturesWithValidRaster > 0 && uiTotalSize == 0) uiTotalSize = 1024 * 1024; - + if (uiTotalSize > 0) { pGame->GetStreaming()->MakeSpaceFor(uiTotalSize); @@ -2423,7 +2434,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe if (!IsReadableTexture(pNewTexture)) continue; - RwRaster* pRaster = pNewTexture->raster; + RwRaster* pRaster = pNewTexture->raster; const bool bRasterOk = pRaster != nullptr; if (bRasterOk && (pRaster->width == 0 || pRaster->height == 0)) @@ -2459,11 +2470,11 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe const auto masterTextures = MakeTextureSet(pReplacementTextures->textures); RwTexDictionary* const pTargetTxd = pInfo->pTxd; - const bool bTargetTxdOk = pTargetTxd != nullptr; - TxdTextureMap targetTxdTextureMap; + const bool bTargetTxdOk = pTargetTxd != nullptr; + TxdTextureMap targetTxdTextureMap; BuildTxdTextureMapFast(pTargetTxd, targetTxdTextureMap); - TxdTextureMap parentTxdTextureMapForAdd; + TxdTextureMap parentTxdTextureMapForAdd; RwTexDictionary* pParentTxdForAdd = nullptr; if (bTargetTxdOk) { @@ -2496,9 +2507,9 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe if (strnlen(pNewTexture->name, RW_TEXTURE_NAME_LENGTH) >= RW_TEXTURE_NAME_LENGTH) continue; - auto itExisting = targetTxdTextureMap.find(pNewTexture->name); + auto itExisting = targetTxdTextureMap.find(pNewTexture->name); RwTexture* pExistingTexture = (itExisting != targetTxdTextureMap.end()) ? itExisting->second : nullptr; - bool bExistingFromParent = false; + bool bExistingFromParent = false; if (!pExistingTexture && !parentTxdTextureMapForAdd.empty()) { @@ -2515,7 +2526,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe const char* szInternalName = GetInternalTextureName(pNewTexture->name); if (szInternalName && strcmp(szInternalName, pNewTexture->name) != 0) { - auto itInternal = targetTxdTextureMap.find(szInternalName); + auto itInternal = targetTxdTextureMap.find(szInternalName); RwTexture* pInternalTexture = (itInternal != targetTxdTextureMap.end()) ? itInternal->second : nullptr; if (!pInternalTexture && !parentTxdTextureMapForAdd.empty()) @@ -2542,13 +2553,13 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe pCopyTex->TXDList.next = &pCopyTex->TXDList; pCopyTex->TXDList.prev = &pCopyTex->TXDList; pCopyTex->txd = nullptr; - + strncpy(pCopyTex->name, szInternalName, RW_TEXTURE_NAME_LENGTH - 1); pCopyTex->name[RW_TEXTURE_NAME_LENGTH - 1] = '\0'; strncpy(pCopyTex->mask, pNewTexture->mask, RW_TEXTURE_NAME_LENGTH - 1); pCopyTex->mask[RW_TEXTURE_NAME_LENGTH - 1] = '\0'; pCopyTex->flags = pNewTexture->flags; - + pNewTexture = pCopyTex; perTxdInfo.usingTextures[idx] = pCopyTex; } @@ -2630,8 +2641,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe dassert(!RwTexDictionaryContainsTexture(pTargetTxd, pNewTexture)); if (!bTargetTxdOk || !RwTexDictionaryAddTexture(pTargetTxd, pNewTexture)) { - SString strError("RwTexDictionaryAddTexture failed for texture: %s in TXD %u", - pNewTexture->name, pInfo->usTxdId); + SString strError("RwTexDictionaryAddTexture failed for texture: %s in TXD %u", pNewTexture->name, pInfo->usTxdId); WriteDebugEvent(strError); AddReportLog(9401, strError); @@ -2654,7 +2664,7 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe targetTxdTextureMap[pExistingTexture->name] = pExistingTexture; } } - + // Destroy copies to prevent leaks (never destroy masters) bool bIsCopyTexture = perTxdInfo.bTexturesAreCopies || masterTextures.find(pNewTexture) == masterTextures.end(); @@ -2679,8 +2689,10 @@ bool CRenderWareSA::ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTe if (!anyAdded) { - SString strDebug = SString("ModelInfoTXDAddTextures: No textures were added to TXD %d for model %d (pTargetTxd=%p bTargetTxdOk=%d usingTextures.size=%u textures.size=%u)", - pInfo->usTxdId, usModelId, pTargetTxd, bTargetTxdOk ? 1 : 0, (unsigned)perTxdInfo.usingTextures.size(), (unsigned)pReplacementTextures->textures.size()); + SString strDebug = SString( + "ModelInfoTXDAddTextures: No textures were added to TXD %d for model %d (pTargetTxd=%p bTargetTxdOk=%d usingTextures.size=%u textures.size=%u)", + pInfo->usTxdId, usModelId, pTargetTxd, bTargetTxdOk ? 1 : 0, (unsigned)perTxdInfo.usingTextures.size(), + (unsigned)pReplacementTextures->textures.size()); WriteDebugEvent(strDebug); AddReportLog(9401, strDebug); @@ -2746,7 +2758,7 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) return; const unsigned short usParentTxdId = itModelReg->second; - auto itShared = g_SharedIsolatedTxdByParentTxd.find(usParentTxdId); + auto itShared = g_SharedIsolatedTxdByParentTxd.find(usParentTxdId); if (itShared == g_SharedIsolatedTxdByParentTxd.end()) { g_ModelParentTxdForIsolation.erase(itModelReg); @@ -2756,7 +2768,7 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) const unsigned short usIsolatedTxdId = itShared->second.usTxdId; RwTexDictionary* pParentTxd = CTxdStore_GetTxd(usParentTxdId); - TxdTextureMap parentTxdTextureMap; + TxdTextureMap parentTxdTextureMap; if (pParentTxd) BuildTxdTextureMapFast(pParentTxd, parentTxdTextureMap); @@ -2777,7 +2789,7 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) continue; auto itPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), - [usIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == usIsolatedTxdId; }); + [usIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == usIsolatedTxdId; }); if (itPerTxd != pReplacement->perTxdList.end()) { @@ -2791,8 +2803,7 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) // First try stored original (non-isolated TXDs or re-replacement scenarios) RwTexture* pOriginalTex = (idx < itPerTxd->replacedOriginals.size()) ? itPerTxd->replacedOriginals[idx] : nullptr; - if (!pOriginalTex && pParentTxd && - strnlen(pReplacementTex->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) + if (!pOriginalTex && pParentTxd && strnlen(pReplacementTex->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) { auto itParent = parentTxdTextureMap.find(pReplacementTex->name); if (itParent != parentTxdTextureMap.end()) @@ -2848,12 +2859,11 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) continue; // Remove per-TXD shader regs and streaming texinfos - ForEachShaderReg(pReplacement, usIsolatedTxdId, - [usIsolatedTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usIsolatedTxdId, pD3D); }); + ForEachShaderReg(pReplacement, usIsolatedTxdId, [usIsolatedTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usIsolatedTxdId, pD3D); }); ClearShaderRegs(pReplacement, usIsolatedTxdId); auto itPerTxd = std::find_if(pReplacement->perTxdList.begin(), pReplacement->perTxdList.end(), - [usIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == usIsolatedTxdId; }); + [usIsolatedTxdId](const SReplacementTextures::SPerTxd& entry) { return entry.usTxdId == usIsolatedTxdId; }); if (itPerTxd != pReplacement->perTxdList.end()) { @@ -2895,24 +2905,23 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) if (pTxdForOrphan) { std::vector remainingTextures; - RwListEntry* const pRoot = &pTxdForOrphan->textures.root; - RwListEntry* pNode = pRoot->next; - + RwListEntry* const pRoot = &pTxdForOrphan->textures.root; + RwListEntry* pNode = pRoot->next; + constexpr std::size_t kMaxOrphanTextures = 8192; - std::size_t count = 0; - + std::size_t count = 0; + while (pNode && pNode != pRoot && count < kMaxOrphanTextures) { - RwTexture* pTex = reinterpret_cast( - reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); - + RwTexture* pTex = reinterpret_cast(reinterpret_cast(pNode) - offsetof(RwTexture, TXDList)); + if (pTex && pTex->txd == pTxdForOrphan) remainingTextures.push_back(pTex); - + pNode = pNode->next; ++count; } - + const bool bProcessedAll = (pNode == nullptr || pNode == pRoot); for (RwTexture* pTex : remainingTextures) { @@ -2943,7 +2952,7 @@ void CRenderWareSA::CleanupIsolatedTxdForModel(unsigned short usModelId) // Only do this when actually removing - if orphaned, keep it marked as loaded so SA // doesn't try to stream it from disk. const std::uint32_t usTxdStreamId = usIsolatedTxdId + pGame->GetBaseIDforTXD(); - CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); + CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); if (pStreamInfo) { pStreamInfo->prevId = static_cast(-1); @@ -3016,13 +3025,14 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen const auto masterRasterMap = MakeRasterMap(pReplacementTextures->textures); // Track destroyed textures across all perTxdInfo iterations to prevent double-free - std::unordered_set destroyedTextures; - std::unordered_set leakedTextures; // Still in TXD - must not destroy + std::unordered_set destroyedTextures; + std::unordered_set leakedTextures; // Still in TXD - must not destroy std::unordered_set txdsWithLeakedTextures; std::unordered_set processedTxdIds; std::unordered_set cleanedTxdIds; - auto markLeakedTxd = [&](unsigned short txdId, CModelTexturesInfo* pInfo) { + auto markLeakedTxd = [&](unsigned short txdId, CModelTexturesInfo* pInfo) + { txdsWithLeakedTextures.insert(txdId); if (pInfo) pInfo->bHasLeakedTextures = true; @@ -3044,8 +3054,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (!pInfo) { - ForEachShaderReg(pReplacementTextures, usTxdId, - [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); + ForEachShaderReg(pReplacementTextures, usTxdId, [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); ClearShaderRegs(pReplacementTextures, usTxdId); for (RwTexture* pTex : perTxdInfo.usingTextures) // Track leaked masters @@ -3083,7 +3092,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen } } } - + perTxdInfo.usingTextures.clear(); perTxdInfo.replacedOriginals.clear(); @@ -3098,9 +3107,9 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen dassert(std::find(pInfo->usedByReplacements.begin(), pInfo->usedByReplacements.end(), pReplacementTextures) != pInfo->usedByReplacements.end()); RwTexDictionary* pCurrentTxd = CTxdStore_GetTxd(usTxdId); - const bool bCurrentTxdOk = pCurrentTxd != nullptr; - const bool bCachedTxdOk = pInfo->pTxd != nullptr; - bool bTxdIsValid = (pInfo->pTxd == pCurrentTxd) && bCachedTxdOk && bCurrentTxdOk; + const bool bCurrentTxdOk = pCurrentTxd != nullptr; + const bool bCachedTxdOk = pInfo->pTxd != nullptr; + bool bTxdIsValid = (pInfo->pTxd == pCurrentTxd) && bCachedTxdOk && bCurrentTxdOk; if (!bTxdIsValid && !pInfo->pTxd && bCurrentTxdOk) { @@ -3113,8 +3122,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen bKeepTxdAlive = true; markLeakedTxd(usTxdId, pInfo); - ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, - [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); + ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); ClearShaderRegs(pReplacementTextures, perTxdInfo.usTxdId); std::unordered_set copiesToDestroy; @@ -3156,11 +3164,10 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (IsReadableTexture(pMaster)) { leakedTextures.insert(pMaster); - } } } - + (void)originalsToDestroy; ListRemove(pInfo->usedByReplacements, pReplacementTextures); @@ -3188,8 +3195,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen bKeepTxdAlive = true; markLeakedTxd(usTxdId, pInfo); - ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, - [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); + ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); ClearShaderRegs(pReplacementTextures, perTxdInfo.usTxdId); for (RwTexture* pTex : perTxdInfo.usingTextures) // Leak to avoid white textures @@ -3253,15 +3259,14 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen continue; } - ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, - [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); + ForEachShaderReg(pReplacementTextures, perTxdInfo.usTxdId, [usTxdId](CD3DDUMMY* pD3D) { RemoveShaderEntryByD3DData(usTxdId, pD3D); }); ClearShaderRegs(pReplacementTextures, perTxdInfo.usTxdId); TxdTextureMap txdTextureMap; // O(1) lookups during restoration BuildTxdTextureMapFast(pInfo->pTxd, txdTextureMap); TxdTextureMap parentTxdTextureMap; - auto& txdPool = pGame->GetPools()->GetTxdPool(); + auto& txdPool = pGame->GetPools()->GetTxdPool(); if (auto* pTxdPoolSA = static_cast(&txdPool)) { if (auto* pTxdSlot = pTxdPoolSA->GetTextureDictonarySlot(perTxdInfo.usTxdId)) @@ -3296,8 +3301,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen RwTexture* pOriginalTexture = (idx < perTxdInfo.replacedOriginals.size()) ? perTxdInfo.replacedOriginals[idx] : nullptr; - if (!pOriginalTexture && !parentTxdTextureMap.empty() && - strnlen(pOldTexture->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) + if (!pOriginalTexture && !parentTxdTextureMap.empty() && strnlen(pOldTexture->name, RW_TEXTURE_NAME_LENGTH) < RW_TEXTURE_NAME_LENGTH) { auto itParent = parentTxdTextureMap.find(pOldTexture->name); if (itParent != parentTxdTextureMap.end() && IsReadableTexture(itParent->second)) @@ -3332,8 +3336,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen { if (!RwTexDictionaryAddTexture(pInfo->pTxd, pOriginalTexture)) { - SString strError("RwTexDictionaryAddTexture failed restoring texture: %s in TXD %u", - pOriginalTexture->name, pInfo->usTxdId); + SString strError("RwTexDictionaryAddTexture failed restoring texture: %s in TXD %u", pOriginalTexture->name, pInfo->usTxdId); WriteDebugEvent(strError); AddReportLog(9401, strError); } @@ -3347,7 +3350,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (!swapMap.empty()) { - std::vector targetModels; + std::vector targetModels; std::unordered_set seenModels; targetModels.reserve(pReplacementTextures->usedInModelIds.size()); @@ -3437,9 +3440,9 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen } continue; } - + dassert(!RwTexDictionaryContainsTexture(pInfo->pTxd, pOldTexture)); - + // Copy: bTexturesAreCopies or not in master list bool bIsActuallyCopy = perTxdInfo.bTexturesAreCopies; if (!bIsActuallyCopy && pReplacementTextures) @@ -3447,11 +3450,9 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen // If not in master list, it's a renamed copy bIsActuallyCopy = (masterTextures.find(pOldTexture) == masterTextures.end()); } - + // Only destroy orphaned copies (prevent double-free via destroyedTextures check) - if (bIsActuallyCopy && - destroyedTextures.find(pOldTexture) == destroyedTextures.end() && - CanDestroyOrphanedTexture(pOldTexture)) + if (bIsActuallyCopy && destroyedTextures.find(pOldTexture) == destroyedTextures.end() && CanDestroyOrphanedTexture(pOldTexture)) { destroyedTextures.insert(pOldTexture); SafeDestroyTexture(pOldTexture); @@ -3459,14 +3460,12 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen } perTxdInfo.usingTextures.clear(); - + // Safety loop for edge cases (with new tracking, entries should be in originalTextures) for (RwTexture* pReplacedTexture : perTxdInfo.replacedOriginals) { - if (pReplacedTexture && - destroyedTextures.find(pReplacedTexture) == destroyedTextures.end() && - pInfo->originalTextures.find(pReplacedTexture) == pInfo->originalTextures.end() && - CanDestroyOrphanedTexture(pReplacedTexture)) + if (pReplacedTexture && destroyedTextures.find(pReplacedTexture) == destroyedTextures.end() && + pInfo->originalTextures.find(pReplacedTexture) == pInfo->originalTextures.end() && CanDestroyOrphanedTexture(pReplacedTexture)) { destroyedTextures.insert(pReplacedTexture); // Skip originalTextures.erase() to avoid heap corruption risk @@ -3479,7 +3478,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen // Don't erase from originalTextures with freed pointers (heap corruption risk) // Track restoration failures std::unordered_set failedRestorations; - + txdTextureMap.clear(); if (pInfo->pTxd) { @@ -3494,7 +3493,6 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (IsReadableTexture(pOrig)) { leakedTextures.insert(pOrig); - } } ListRemove(pInfo->usedByReplacements, pReplacementTextures); @@ -3515,7 +3513,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen } continue; } - + for (RwTexture* pOriginalTexture : pInfo->originalTextures) { // Skip null/invalid textures (can happen during shutdown) @@ -3544,11 +3542,10 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen { if (!pInfo->pTxd || !RwTexDictionaryAddTexture(pInfo->pTxd, pOriginalTexture)) { - SString strError("RwTexDictionaryAddTexture failed ensuring original texture: %s in TXD %u", - pOriginalTexture->name, pInfo->usTxdId); + SString strError("RwTexDictionaryAddTexture failed ensuring original texture: %s in TXD %u", pOriginalTexture->name, pInfo->usTxdId); WriteDebugEvent(strError); AddReportLog(9401, strError); - + failedRestorations.insert(pOriginalTexture); } else @@ -3558,7 +3555,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen // Originals keep shader registration (never removed) } } - + // Don't destroy failed originals (leak safe, destroy corrupts) (void)failedRestorations; @@ -3567,38 +3564,39 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (pInfo->usedByReplacements.empty()) { // txd should now contain the same textures as 'originalTextures' - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG std::vector currentTextures; if (pInfo->pTxd) GetTxdTextures(currentTextures, pInfo->pTxd); - - auto formatTextures = [](const auto& textures) -> std::string { + + auto formatTextures = [](const auto& textures) -> std::string + { std::ostringstream result; - size_t i = 0; - size_t count = textures.size(); + size_t i = 0; + size_t count = textures.size(); for (const auto* pTex : textures) { const bool isValid = pTex != nullptr; const bool isLast = (i == count - 1); - + if (isValid) result << pTex->name << "[0x" << std::hex << pTex << std::dec << "]"; else result << "INVALID[0x" << std::hex << pTex << std::dec << "]"; - + if (!isLast) result << ", "; ++i; } return result.str(); }; - + // Allow size mismatch in case texture removal was skipped due to invalid pointers if (currentTextures.size() != pInfo->originalTextures.size()) { std::ostringstream debugMsg; - debugMsg << "TXD " << pInfo->usTxdId << ": texture count mismatch (current=" - << currentTextures.size() << ", expected=" << pInfo->originalTextures.size() << ")\n"; + debugMsg << "TXD " << pInfo->usTxdId << ": texture count mismatch (current=" << currentTextures.size() + << ", expected=" << pInfo->originalTextures.size() << ")\n"; debugMsg << " Current textures: " << formatTextures(currentTextures); debugMsg << "\n Expected textures: " << formatTextures(pInfo->originalTextures); debugMsg << "\n"; @@ -3613,30 +3611,28 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen continue; if (std::find(currentTextures.begin(), currentTextures.end(), pOriginalTexture) == currentTextures.end()) { - const char* texName = pOriginalTexture ? pOriginalTexture->name : "INVALID"; + const char* texName = pOriginalTexture ? pOriginalTexture->name : "INVALID"; std::ostringstream oss; - oss << "Original texture not found in TXD " << pInfo->usTxdId - << " - texture '" << texName << "' [0x" << std::hex << pOriginalTexture << std::dec - << "] was removed or replaced unexpectedly"; + oss << "Original texture not found in TXD " << pInfo->usTxdId << " - texture '" << texName << "' [0x" << std::hex << pOriginalTexture + << std::dec << "] was removed or replaced unexpectedly"; const std::string assertMsg = oss.str(); assert(false && assertMsg.c_str()); } } - + // Second pass: remove original textures from current list to find extras for (auto* pOriginalTexture : pInfo->originalTextures) { if (pOriginalTexture) ListRemove(currentTextures, pOriginalTexture); } - + // Remaining textures indicate leak if (!currentTextures.empty()) { std::ostringstream oss; - oss << "Extra textures remain in TXD " << pInfo->usTxdId - << " after removing all originals - indicates texture leak. Remaining: " - << formatTextures(currentTextures); + oss << "Extra textures remain in TXD " << pInfo->usTxdId + << " after removing all originals - indicates texture leak. Remaining: " << formatTextures(currentTextures); const std::string assertMsg = oss.str(); assert(false && assertMsg.c_str()); } @@ -3646,12 +3642,11 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen if (refsCount <= 0 && !bKeepTxdAlive) { std::ostringstream oss; - oss << "TXD " << pInfo->usTxdId << " has invalid ref count " - << refsCount << " - should be > 0 before cleanup"; + oss << "TXD " << pInfo->usTxdId << " has invalid ref count " << refsCount << " - should be > 0 before cleanup"; const std::string assertMsg = oss.str(); assert(false && assertMsg.c_str()); } - #endif +#endif // Remove info const bool bHasLeaks = bKeepTxdAlive || txdsWithLeakedTextures.count(usTxdId) > 0 || pInfo->bHasLeakedTextures; pInfo->bHasLeakedTextures = pInfo->bHasLeakedTextures || bHasLeaks; @@ -3706,7 +3701,8 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen // 1) TXD pointer is valid and matches current CTxdStore pointer // 2) Current TXD texture list matches originalTextures exactly (by pointer identity) // This is the only safe proof that no leaked replacement textures remain linked. - const auto canProveNoLeaks = [&]() -> bool { + const auto canProveNoLeaks = [&]() -> bool + { if (!pInfo->pTxd) return false; @@ -3752,8 +3748,7 @@ void CRenderWareSA::ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacemen continue; // Skip unreadable or already processed textures - if (destroyedTextures.find(pTexture) != destroyedTextures.end() || - leakedTextures.find(pTexture) != leakedTextures.end()) + if (destroyedTextures.find(pTexture) != destroyedTextures.end() || leakedTextures.find(pTexture) != leakedTextures.end()) { continue; } @@ -3848,7 +3843,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() // but keep loadState as LOADED since refs are still held. // Move to permanent leak set for diagnostics. const std::uint32_t usTxdStreamId = txdId + pGame->GetBaseIDforTXD(); - CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); + CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); if (pStreamInfo) { // Clear archive/offset/size to prevent any streaming attempts, @@ -3870,7 +3865,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() // Reset streaming infor before removing the slot const std::uint32_t usTxdStreamId = txdId + pGame->GetBaseIDforTXD(); - CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); + CStreamingInfo* pStreamInfo = pGame->GetStreaming()->GetStreamingInfo(usTxdStreamId); if (pStreamInfo) { // Reset all streaming fields to clean defaults @@ -3911,15 +3906,12 @@ void CRenderWareSA::StaticResetModelTextureReplacing() std::vector deferredLeakRetry(g_PendingLeakedTxdRefs.begin(), g_PendingLeakedTxdRefs.end()); g_PendingLeakedTxdRefs.clear(); - auto noteUncleaned = [&](unsigned short txdId) { - g_PendingLeakedTxdRefs.insert(txdId); - }; + auto noteUncleaned = [&](unsigned short txdId) { g_PendingLeakedTxdRefs.insert(txdId); }; - auto noteCleaned = [&](unsigned short txdId) { - g_PendingLeakedTxdRefs.erase(txdId); - }; + auto noteCleaned = [&](unsigned short txdId) { g_PendingLeakedTxdRefs.erase(txdId); }; - auto enumerateTxdTexturesBounded = [](RwTexDictionary* pTxd, std::vector& outTextures) -> bool { + auto enumerateTxdTexturesBounded = [](RwTexDictionary* pTxd, std::vector& outTextures) -> bool + { outTextures.clear(); if (!pTxd) @@ -3932,7 +3924,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() return false; constexpr std::size_t kMaxMopUpTextures = 8192; - std::size_t count = 0; + std::size_t count = 0; while (pNode != pRoot) { @@ -3956,7 +3948,8 @@ void CRenderWareSA::StaticResetModelTextureReplacing() return true; }; - auto tryMopUpTxd = [&](unsigned short txdId, CModelTexturesInfo* pInfo, bool isDeferred) { + auto tryMopUpTxd = [&](unsigned short txdId, CModelTexturesInfo* pInfo, bool isDeferred) + { if (isDeferred) { if (ms_ModelTexturesInfoMap.find(txdId) != ms_ModelTexturesInfoMap.end()) @@ -3972,7 +3965,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() } RwTexDictionary* pTxd = CTxdStore_GetTxd(txdId); - const bool bTxdOk = pTxd != nullptr; + const bool bTxdOk = pTxd != nullptr; if (!bTxdOk) { @@ -3990,10 +3983,10 @@ void CRenderWareSA::StaticResetModelTextureReplacing() // Safety ref prevents race during orphan operation CTxdStore_AddRef(txdId); - + // Enumerate and orphan textures (bounded traversal to avoid corruption hangs) std::vector currentTextures; - const bool enumerationSucceeded = enumerateTxdTexturesBounded(pTxd, currentTextures); + const bool enumerationSucceeded = enumerateTxdTexturesBounded(pTxd, currentTextures); if (!enumerationSucceeded) { @@ -4042,23 +4035,23 @@ void CRenderWareSA::StaticResetModelTextureReplacing() ++relinkedCount; } } - + CTxdStore_RemoveRef(txdId); noteUncleaned(txdId); return; } - + // Release refs if (pInfo) pInfo->bHasLeakedTextures = false; // Release safety ref first CTxdStore_RemoveRef(txdId); - + // Release our original ref const char* tag = isDeferred ? "StaticResetModelTextureReplacing-mopup-deferred" : "StaticResetModelTextureReplacing-mopup"; CRenderWareSA::DebugTxdRemoveRef(txdId, tag); - + int refsAfterDrop = CTxdStore_GetNumRefs(txdId); if (refsAfterDrop == 0) { @@ -4068,7 +4061,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() else { CTxdStore_AddRef(txdId); - + int relinkedCount = 0; for (RwTexture* pTex : currentTextures) { @@ -4078,7 +4071,7 @@ void CRenderWareSA::StaticResetModelTextureReplacing() ++relinkedCount; } } - + if (pInfo) pInfo->bHasLeakedTextures = true; noteUncleaned(txdId); @@ -4119,12 +4112,12 @@ void CRenderWareSA::StaticResetModelTextureReplacing() for (auto& entry : ms_ModelTexturesInfoMap) { CModelTexturesInfo& info = entry.second; - + // Release ref if no leaked textures linked if (!info.bHasLeakedTextures && CTxdStore_GetNumRefs(info.usTxdId) > 0) CRenderWareSA::DebugTxdRemoveRef(info.usTxdId, "StaticResetModelTextureReplacing-final-clean"); } - + // Leaked TXD refs kept; GTA's streaming reset frees them ms_ModelTexturesInfoMap.clear(); } @@ -4140,7 +4133,7 @@ void CRenderWareSA::StaticResetShaderSupport() return; const unsigned short usBaseTxdId = pGame->GetBaseIDforTXD(); - + // Safety limit to prevent freeze on corrupted/huge maps constexpr size_t MAX_CLEANUP_ITERATIONS = 50000; if (m_TexInfoMap.size() > MAX_CLEANUP_ITERATIONS) @@ -4156,24 +4149,24 @@ void CRenderWareSA::StaticResetShaderSupport() m_D3DDataTexInfoMap.clear(); return; } - + // Remove custom shader entries from m_TexInfoMap (preserves GTA base textures) for (auto iter = m_TexInfoMap.begin(); iter != m_TexInfoMap.end();) { STexInfo* pTexInfo = iter->second; - + if (!pTexInfo) { iter = m_TexInfoMap.erase(iter); continue; } - + // Remove: custom TXD entries (ID >= base) and script-loaded textures // Keep: GTA base textures and FAKE_NO_TEXTURE singleton const bool bIsCustomTxdEntry = pTexInfo->texTag.m_bUsingTxdId && pTexInfo->texTag.m_usTxdId >= usBaseTxdId; const bool bIsScriptTexture = !pTexInfo->texTag.m_bUsingTxdId && (pTexInfo->texTag.m_pTex != FAKE_RWTEXTURE_NO_TEXTURE); const bool bShouldRemove = bIsCustomTxdEntry || bIsScriptTexture; - + if (bShouldRemove) { OnTextureStreamOut(pTexInfo); diff --git a/Client/game_sa/CRenderWareSA.TxdRightSizing.cpp b/Client/game_sa/CRenderWareSA.TxdRightSizing.cpp index 6f5c6e9ed8c..1cae32bb517 100644 --- a/Client/game_sa/CRenderWareSA.TxdRightSizing.cpp +++ b/Client/game_sa/CRenderWareSA.TxdRightSizing.cpp @@ -243,14 +243,13 @@ RwTexture* CRenderWareSA::RightSizeTexture(RwTexture* pTexture, uint uiSizeLimit header.TextureFormat.vAddressing = (pTexture->flags & 0xf000) >> 12; memcpy(header.TextureFormat.name, pTexture->name, 32); memcpy(header.TextureFormat.maskName, pTexture->mask, 32); - header.RasterFormat.rasterFormat = (pRaster->format & 0x0f) - << 8; // ( dxt1 = 0x00000100 or 0x00000200 / dxt3 = 0x00000300 ) | 0x00008000 mipmaps? + header.RasterFormat.rasterFormat = (pRaster->format & 0x0f) << 8; // ( dxt1 = 0x00000100 or 0x00000200 / dxt3 = 0x00000300 ) | 0x00008000 mipmaps? header.RasterFormat.d3dFormat = pD3DRaster->format; header.RasterFormat.width = static_cast(uiReqWidth); header.RasterFormat.height = static_cast(uiReqHeight); header.RasterFormat.depth = static_cast(pRaster->depth); header.RasterFormat.numLevels = 1; - header.RasterFormat.rasterType = pRaster->type; // dxt1 = 4 / dxt3 = 4 + header.RasterFormat.rasterType = pRaster->type; // dxt1 = 4 / dxt3 = 4 header.RasterFormat.alpha = bHasAlpha; header.RasterFormat.cubeTexture = bIsCubeTexture; header.RasterFormat.autoMipMaps = false; @@ -260,7 +259,7 @@ RwTexture* CRenderWareSA::RightSizeTexture(RwTexture* pTexture, uint uiSizeLimit CBuffer nativeData; CBufferWriteStream stream(nativeData); stream.Write(1); - stream.Write(0); // Size ignored + stream.Write(0); // Size ignored stream.Write(0x1803FFFF); stream.WriteBytes(&header, sizeof(header)); stream.Write(newPixelBuffer.GetSize()); diff --git a/Client/game_sa/CRenderWareSA.cpp b/Client/game_sa/CRenderWareSA.cpp index 168b4bf5899..3db8d60c2bb 100644 --- a/Client/game_sa/CRenderWareSA.cpp +++ b/Client/game_sa/CRenderWareSA.cpp @@ -50,16 +50,16 @@ void CRenderWareSA::DebugTxdRemoveRef(unsigned short usTxdId, const char* /*tag* // RwFrameForAllObjects struct and callback used to replace dynamic vehicle parts struct SReplaceParts { - const char* szName; // name of the part you want to replace (e.g. 'door_lf' or 'door_rf') - unsigned char ucIndex; // index counter for internal usage (0 is the 'ok' part model, 1 is the 'dam' part model) - RpAtomicContainer* pReplacements; // replacement atomics - unsigned int uiReplacements; // number of replacements + const char* szName; // name of the part you want to replace (e.g. 'door_lf' or 'door_rf') + unsigned char ucIndex; // index counter for internal usage (0 is the 'ok' part model, 1 is the 'dam' part model) + RpAtomicContainer* pReplacements; // replacement atomics + unsigned int uiReplacements; // number of replacements }; static RwObject* ReplacePartsCB(RwObject* object, SReplaceParts* data) { if (!object) [[unlikely]] return object; - + RpAtomic* Atomic = (RpAtomic*)object; char szAtomicName[16] = {0}; @@ -94,7 +94,7 @@ static bool AddAllAtomicsCB(RpAtomic* atomic, void* pClump) { if (!atomic || !pClump) [[unlikely]] return false; - + RpClump* data = reinterpret_cast(pClump); RwFrame* pFrame = RpGetFrame(data); @@ -108,10 +108,10 @@ static bool AddAllAtomicsCB(RpAtomic* atomic, void* pClump) // RpClumpForAllAtomics struct and callback used to replace all wheels with a given wheel model struct SReplaceWheels { - const char* szName; // name of the new wheel model - RpClump* pClump; // the vehicle's clump - RpAtomicContainer* pReplacements; // replacement atomics - unsigned int uiReplacements; // number of replacements + const char* szName; // name of the new wheel model + RpClump* pClump; // the vehicle's clump + RpAtomicContainer* pReplacements; // replacement atomics + unsigned int uiReplacements; // number of replacements }; static bool ReplaceWheelsCB(RpAtomic* atomic, void* pData) { @@ -152,15 +152,15 @@ static bool ReplaceWheelsCB(RpAtomic* atomic, void* pData) // RpClumpForAllAtomics struct and callback used to replace all atomics for a vehicle struct SReplaceAll { - RpClump* pClump; // the vehicle's clump - RpAtomicContainer* pReplacements; // replacement atomics - unsigned int uiReplacements; // number of replacements + RpClump* pClump; // the vehicle's clump + RpAtomicContainer* pReplacements; // replacement atomics + unsigned int uiReplacements; // number of replacements }; static bool ReplaceAllCB(RpAtomic* atomic, void* pData) { if (!atomic || !pData) [[unlikely]] return false; - + SReplaceAll* data = reinterpret_cast(pData); RwFrame* Frame = RpGetFrame(atomic); if (Frame == NULL) @@ -200,14 +200,14 @@ static bool ReplaceAllCB(RpAtomic* atomic, void* pData) // Load atomics from clump into container (caller manages lifetime) struct SLoadAtomics { - RpAtomicContainer* pReplacements; // replacement atomics - unsigned int uiReplacements; // number of replacements + RpAtomicContainer* pReplacements; // replacement atomics + unsigned int uiReplacements; // number of replacements }; static bool LoadAtomicsCB(RpAtomic* atomic, void* pData) { if (!atomic || !pData) [[unlikely]] return false; - + SLoadAtomics* data = reinterpret_cast(pData); RwFrame* Frame = RpGetFrame(atomic); @@ -435,7 +435,7 @@ RpClump* CRenderWareSA::ReadDFF(const SString& strFilename, const SString& buffe if (modelInfo) { if (auto* modelInfoInterface = modelInfo->GetInterface()) - ((void(__thiscall*)(CBaseModelInfoSAInterface*))0x4C4C40)(modelInfoInterface); // CBaseModelInfo::DeleteCollisionModel + ((void(__thiscall*)(CBaseModelInfoSAInterface*))0x4C4C40)(modelInfoInterface); // CBaseModelInfo::DeleteCollisionModel } // rockstar's collision hack @@ -473,19 +473,17 @@ void CRenderWareSA::GetClumpAtomicList(RpClump* pClump, std::vector& // Track visited atomics to detect cycles from corrupted linked lists. struct VisitedTracker { - std::vector* pList; + std::vector* pList; std::unordered_set visited; - std::size_t iterations; - bool bStop; - std::size_t maxAtomics; - - VisitedTracker(std::vector* list, std::size_t maxCount) - : pList(list), iterations(0), bStop(false), maxAtomics(maxCount) - { - } + std::size_t iterations; + bool bStop; + std::size_t maxAtomics; + + VisitedTracker(std::vector* list, std::size_t maxCount) : pList(list), iterations(0), bStop(false), maxAtomics(maxCount) {} }; - auto ForAllAtomicsCB = [](RpAtomic* pAtomic, void* pData) -> bool { + auto ForAllAtomicsCB = [](RpAtomic* pAtomic, void* pData) -> bool + { auto* t = reinterpret_cast(pData); if (t->bStop) @@ -664,7 +662,7 @@ namespace continue; RwTexture* pNewTexture = nullptr; - auto itFound = txdTextureMap.find(szTextureName); + auto itFound = txdTextureMap.find(szTextureName); if (itFound != txdTextureMap.end()) pNewTexture = itFound->second; @@ -767,12 +765,12 @@ bool CRenderWareSA::ReplaceModel(RpClump* pNew, unsigned short usModelID, DWORD if (!pModelInfoInterface) { CBaseModelInfoSAInterface* fallback = nullptr; - auto* arrayEntry = ((CBaseModelInfoSAInterface**)ARRAY_ModelInfo)[usModelID]; + auto* arrayEntry = ((CBaseModelInfoSAInterface**)ARRAY_ModelInfo)[usModelID]; if (arrayEntry && SharedUtil::IsReadablePointer(arrayEntry, sizeof(*arrayEntry))) fallback = arrayEntry; else if (pInterfaceAfterSet && SharedUtil::IsReadablePointer(pInterfaceAfterSet, sizeof(*pInterfaceAfterSet))) fallback = pInterfaceAfterSet; - bool restored = false; + bool restored = false; const bool oldClumpReadable = pOldClump && SharedUtil::IsReadablePointer(pOldClump, sizeof(*pOldClump)); if (fallback && oldClumpReadable && SharedUtil::IsReadablePointer(fallback->VFTBL, sizeof(*fallback->VFTBL))) { @@ -849,23 +847,16 @@ CColModel* CRenderWareSA::ReadCOL(const SString& buffer) // Validate version field contains valid COL magic number // Version is 4-char fixed string (not null-terminated): "COLL", "COL2", "COL3", "COL4" - constexpr std::array, 4> validVersions = {{ - {'C', 'O', 'L', 'L'}, - {'C', 'O', 'L', '2'}, - {'C', 'O', 'L', '3'}, - {'C', 'O', 'L', '4'} - }}; - + constexpr std::array, 4> validVersions = {{{'C', 'O', 'L', 'L'}, {'C', 'O', 'L', '2'}, {'C', 'O', 'L', '3'}, {'C', 'O', 'L', '4'}}}; + const bool isValidVersion = std::any_of(validVersions.begin(), validVersions.end(), - [&header](const auto& valid) { - return std::equal(valid.begin(), valid.end(), header.version); - }); + [&header](const auto& valid) { return std::equal(valid.begin(), valid.end(), header.version); }); if (!isValidVersion) [[unlikely]] { // Explicitly limit to 4 characters - AddReportLog(8622, SString("ReadCOL: Invalid version '%c%c%c%c' - expected COLL, COL2, COL3, or COL4", - header.version[0], header.version[1], header.version[2], header.version[3])); + AddReportLog(8622, SString("ReadCOL: Invalid version '%c%c%c%c' - expected COLL, COL2, COL3, or COL4", header.version[0], header.version[1], + header.version[2], header.version[3])); return nullptr; } @@ -914,7 +905,7 @@ unsigned int CRenderWareSA::LoadAtomics(RpClump* pClump, RpAtomicContainer* pAto { if (!pClump || !pAtomics) [[unlikely]] return 0; - + // iterate through all atomics in the clump SLoadAtomics data = {0}; data.pReplacements = pAtomics; @@ -947,7 +938,7 @@ bool CRenderWareSA::ReplaceAllAtomicsInModel(RpClump* pNew, unsigned short usMod { if (!pNew) [[unlikely]] return false; - + CModelInfo* pModelInfo = pGame->GetModelInfo(usModelID); if (pModelInfo) @@ -965,7 +956,7 @@ bool CRenderWareSA::ReplaceAllAtomicsInModel(RpClump* pNew, unsigned short usMod } // Replace the atomics - SAtomicsReplacer data; + SAtomicsReplacer data; CBaseModelInfoSAInterface* pModelInfoInterface = pModelInfo->GetInterface(); if (!pModelInfoInterface) { @@ -1094,9 +1085,7 @@ void CRenderWareSA::DestroyTexture(RwTexture* pTex) bool CRenderWareSA::RwTexDictionaryRemoveTexture(RwTexDictionary* pTXD, RwTexture* pTex) { - if (!pTex || !pTXD || - !SharedUtil::IsReadablePointer(pTex, sizeof(RwTexture)) || - !SharedUtil::IsReadablePointer(pTXD, sizeof(RwTexDictionary))) + if (!pTex || !pTXD || !SharedUtil::IsReadablePointer(pTex, sizeof(RwTexture)) || !SharedUtil::IsReadablePointer(pTXD, sizeof(RwTexDictionary))) return false; if (pTex->txd != pTXD) @@ -1105,9 +1094,7 @@ bool CRenderWareSA::RwTexDictionaryRemoveTexture(RwTexDictionary* pTXD, RwTextur RwListEntry* pNext = pTex->TXDList.next; RwListEntry* pPrev = pTex->TXDList.prev; - if (!pNext || !pPrev || - !SharedUtil::IsReadablePointer(pNext, sizeof(RwListEntry)) || - !SharedUtil::IsReadablePointer(pPrev, sizeof(RwListEntry))) + if (!pNext || !pPrev || !SharedUtil::IsReadablePointer(pNext, sizeof(RwListEntry)) || !SharedUtil::IsReadablePointer(pPrev, sizeof(RwListEntry))) return false; if (pNext->prev != &pTex->TXDList || pPrev->next != &pTex->TXDList) @@ -1128,11 +1115,9 @@ short CRenderWareSA::CTxdStore_GetTxdRefcount(unsigned short usTxdID) bool CRenderWareSA::RwTexDictionaryContainsTexture(RwTexDictionary* pTXD, RwTexture* pTex) { - if (!pTex || !pTXD || - !SharedUtil::IsReadablePointer(pTex, sizeof(RwTexture)) || - !SharedUtil::IsReadablePointer(pTXD, sizeof(RwTexDictionary))) + if (!pTex || !pTXD || !SharedUtil::IsReadablePointer(pTex, sizeof(RwTexture)) || !SharedUtil::IsReadablePointer(pTXD, sizeof(RwTexDictionary))) return false; - + return pTex->txd == pTXD; } @@ -1217,10 +1202,10 @@ namespace { struct TextureMapping { - const char* externalPrefix; // e.g., "remap" - const char* internalPrefix; // e.g., "#emap" - size_t externalLength; // strlen(externalPrefix) - size_t internalLength; // strlen(internalPrefix) + const char* externalPrefix; // e.g., "remap" + const char* internalPrefix; // e.g., "#emap" + size_t externalLength; // strlen(externalPrefix) + size_t internalLength; // strlen(internalPrefix) }; // Static mappings for texture name transformations @@ -1228,11 +1213,8 @@ namespace // This specifically handles vehicle paintjob textures. // Note: This may false positive on non-vehicle textures with matching prefixes, // but the fallback lookup pattern (try original first, then transformed) mitigates this. - constexpr std::array kTextureMappings = {{ - {"remap", "#emap", 5, 5}, - {"white", "@hite", 5, 5} - }}; - + constexpr std::array kTextureMappings = {{{"remap", "#emap", 5, 5}, {"white", "@hite", 5, 5}}}; + // Thread-local buffers for transformed texture names (avoids allocation) // Note: These are overwritten on each call - do not store the returned pointer // for use after another call to these functions. @@ -1265,11 +1247,10 @@ const char* CRenderWareSA::GetInternalTextureName(const char* szExternalName) { // Build internal name: internal prefix + rest of original name const char* szSuffix = szExternalName + mapping.externalLength; - + // Build the transformed name (only snprintf is safe for it) - snprintf(s_szInternalNameBuffer, sizeof(s_szInternalNameBuffer), "%s%s", - mapping.internalPrefix, szSuffix); - + snprintf(s_szInternalNameBuffer, sizeof(s_szInternalNameBuffer), "%s%s", mapping.internalPrefix, szSuffix); + return s_szInternalNameBuffer; } } @@ -1301,11 +1282,10 @@ const char* CRenderWareSA::GetExternalTextureName(const char* szInternalName) { // Build external name: external prefix + rest of original name const char* szSuffix = szInternalName + mapping.internalLength; - + // Build the transformed name (only snprintf is safe for it) - snprintf(s_szExternalNameBuffer, sizeof(s_szExternalNameBuffer), "%s%s", - mapping.externalPrefix, szSuffix); - + snprintf(s_szExternalNameBuffer, sizeof(s_szExternalNameBuffer), "%s%s", mapping.externalPrefix, szSuffix); + return s_szExternalNameBuffer; } } @@ -1372,7 +1352,7 @@ void CRenderWareSA::GetModelTextureNames(std::vector& outNameList, usho bLoadedModel = true; pGame->GetModelInfo(usModelId)->Request(BLOCKING, "CRenderWareSA::GetModelTextureNames"); pTXD = CTxdStore_GetTxd(usTxdId); - + // Revalidate TXD pointer after load - it may still be NULL or have been GC'd if (!pTXD) { @@ -1425,7 +1405,7 @@ bool CRenderWareSA::GetModelTextures(std::vectorGetModelInfo(usModelId)->Request(BLOCKING, "CRenderWareSA::GetModelTextures"); pTXD = CTxdStore_GetTxd(usTxdId); - + // Revalidate TXD pointer after load - it may still be NULL or have been GC'd if (!pTXD) { @@ -1453,7 +1433,7 @@ bool CRenderWareSA::GetModelTextures(std::vectorname); - bool bValidTexture = false; + bool bValidTexture = false; if (bExcludeTextures) { diff --git a/Client/game_sa/CRenderWareSA.h b/Client/game_sa/CRenderWareSA.h index 52b4cd4d6e9..6ed0e050363 100644 --- a/Client/game_sa/CRenderWareSA.h +++ b/Client/game_sa/CRenderWareSA.h @@ -30,7 +30,8 @@ class CRenderWareSA : public CRenderWare CRenderWareSA(); ~CRenderWareSA(); void Initialize(); - bool ModelInfoTXDLoadTextures(SReplacementTextures* pReplacementTextures, const SString& strFilename, const SString& buffer, bool bFilteringEnabled, SString* pOutError = nullptr) override; + bool ModelInfoTXDLoadTextures(SReplacementTextures* pReplacementTextures, const SString& strFilename, const SString& buffer, bool bFilteringEnabled, + SString* pOutError = nullptr) override; bool ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTextures, unsigned short usModelId); void ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacementTextures); void CleanupIsolatedTxdForModel(unsigned short usModelId) override; @@ -96,16 +97,16 @@ class CRenderWareSA : public CRenderWare // szName should be without the part suffix (e.g. 'door_lf' or 'door_rf', and not 'door_lf_dummy') bool ReplacePartModels(RpClump* pClump, RpAtomicContainer* pAtomics, unsigned int uiAtomics, const char* szName); - unsigned short GetTXDIDForModelID(unsigned short usModelID); - void PulseWorldTextureWatch(); - void ProcessPendingIsolatedTxdParents(); - void GetModelTextureNames(std::vector& outNameList, unsigned short usModelID); - bool GetModelTextures(std::vector>& outTextureList, unsigned short usModelID, std::vector vTextureNames); - void GetTxdTextures(std::vector& outTextureList, unsigned short usTxdId); - static void GetTxdTextures(std::vector& outTextureList, RwTexDictionary* pTXD); - static void GetTxdTextures(std::unordered_set& outTextureSet, RwTexDictionary* pTXD); - const char* GetTextureName(CD3DDUMMY* pD3DData); - void SetRenderingClientEntity(CClientEntityBase* pClientEntity, unsigned short usModelId, int iTypeMask); + unsigned short GetTXDIDForModelID(unsigned short usModelID); + void PulseWorldTextureWatch(); + void ProcessPendingIsolatedTxdParents(); + void GetModelTextureNames(std::vector& outNameList, unsigned short usModelID); + bool GetModelTextures(std::vector>& outTextureList, unsigned short usModelID, std::vector vTextureNames); + void GetTxdTextures(std::vector& outTextureList, unsigned short usTxdId); + static void GetTxdTextures(std::vector& outTextureList, RwTexDictionary* pTXD); + static void GetTxdTextures(std::unordered_set& outTextureSet, RwTexDictionary* pTXD); + const char* GetTextureName(CD3DDUMMY* pD3DData); + void SetRenderingClientEntity(CClientEntityBase* pClientEntity, unsigned short usModelId, int iTypeMask); SShaderItemLayers* GetAppliedShaderForD3DData(CD3DDUMMY* pD3DData); void AppendAdditiveMatch(CSHADERDUMMY* pShaderData, CClientEntityBase* pClientEntity, const char* strTextureNameMatch, float fShaderPriority, bool bShaderLayered, int iTypeMask, unsigned int uiShaderCreateTime, bool bShaderUsesVertexShader, bool bAppendLayers); @@ -171,18 +172,18 @@ class CRenderWareSA : public CRenderWare void SetGTAVertexShadersEnabled(bool bEnable); // Watched world textures - std::multimap m_TexInfoMap; - CFastHashMap m_D3DDataTexInfoMap; - CClientEntityBase* m_pRenderingClientEntity; - unsigned short m_usRenderingEntityModelId; - int m_iRenderingEntityType; - CMatchChannelManager* m_pMatchChannelManager; - int m_uiReplacementRequestCounter; - int m_uiReplacementMatchCounter; - int m_uiNumReplacementRequests; - int m_uiNumReplacementMatches; - CElapsedTime m_GTAVertexShadersDisabledTimer; - bool m_bGTAVertexShadersEnabled; - std::set m_SpecialTextures; - static int ms_iRenderingType; + std::multimap m_TexInfoMap; + CFastHashMap m_D3DDataTexInfoMap; + CClientEntityBase* m_pRenderingClientEntity; + unsigned short m_usRenderingEntityModelId; + int m_iRenderingEntityType; + CMatchChannelManager* m_pMatchChannelManager; + int m_uiReplacementRequestCounter; + int m_uiReplacementMatchCounter; + int m_uiNumReplacementRequests; + int m_uiNumReplacementMatches; + CElapsedTime m_GTAVertexShadersDisabledTimer; + bool m_bGTAVertexShadersEnabled; + std::set m_SpecialTextures; + static int ms_iRenderingType; }; diff --git a/Client/game_sa/CRendererSA.cpp b/Client/game_sa/CRendererSA.cpp index b4803aff9ca..eed6fe73ffc 100644 --- a/Client/game_sa/CRendererSA.cpp +++ b/Client/game_sa/CRendererSA.cpp @@ -15,8 +15,8 @@ #include "CMatrix.h" #include "gamesa_renderware.h" -#define SetLightColoursForPedsCarsAndObjects(fMult) ((RpLight*(__cdecl*)(float))0x735D90)(fMult) -#define SetAmbientColours() ((RpLight*(__cdecl*)())0x735D30)() +#define SetLightColoursForPedsCarsAndObjects(fMult) ((RpLight * (__cdecl*)(float))0x735D90)(fMult) +#define SetAmbientColours() ((RpLight * (__cdecl*)())0x735D30)() CRendererSA::CRendererSA() { @@ -81,11 +81,11 @@ void CRendererSA::RenderModel(CModelInfo* pModelInfo, const CMatrix& matrix, flo // Restore ambient light SetAmbientColours(); } - catch (...) - { - // Release reference on rendering exception - pModelInfo->RemoveRef(); - throw; - } // Release reference - allow GC + catch (...) + { + // Release reference on rendering exception + pModelInfo->RemoveRef(); + throw; + } // Release reference - allow GC pModelInfo->RemoveRef(); } diff --git a/Client/game_sa/CRopesSA.cpp b/Client/game_sa/CRopesSA.cpp index 3687f0c84fb..a15e949396a 100644 --- a/Client/game_sa/CRopesSA.cpp +++ b/Client/game_sa/CRopesSA.cpp @@ -14,7 +14,7 @@ DWORD dwDurationAddress = 0x558D1El; -CRopesSAInterface (&CRopesSA::ms_aRopes)[8] = *(CRopesSAInterface(*)[8])0xB768B8; +CRopesSAInterface (&CRopesSA::ms_aRopes)[8] = *(CRopesSAInterface (*)[8])0xB768B8; int CRopesSA::CreateRopeForSwatPed(const CVector& vecPosition, DWORD dwDuration) { diff --git a/Client/game_sa/CRopesSA.h b/Client/game_sa/CRopesSA.h index ea6f3081233..2d038f9ba82 100644 --- a/Client/game_sa/CRopesSA.h +++ b/Client/game_sa/CRopesSA.h @@ -14,9 +14,9 @@ #include #include -#define ROPES_COUNT 8 +#define ROPES_COUNT 8 -#define FUNC_CRopes_CreateRopeForSwatPed 0x558d10 +#define FUNC_CRopes_CreateRopeForSwatPed 0x558d10 class CRopesSAInterface { diff --git a/Client/game_sa/CSettingsSA.cpp b/Client/game_sa/CSettingsSA.cpp index 31034cd52a8..1d418770524 100644 --- a/Client/game_sa/CSettingsSA.cpp +++ b/Client/game_sa/CSettingsSA.cpp @@ -26,9 +26,9 @@ static const float MOUSE_SENSITIVITY_MIN = 0.000312f; static const float MOUSE_SENSITIVITY_DEFAULT = 0.0025f; static const float MOUSE_SENSITIVITY_MAX = MOUSE_SENSITIVITY_DEFAULT * 2 - MOUSE_SENSITIVITY_MIN; -#define VAR_CurVideoMode (*((uint*)(0x08D6220))) +#define VAR_CurVideoMode (*((uint*)(0x08D6220))) #define VAR_SavedVideoMode (*((uint*)(0x0BA6820))) -#define VAR_CurAdapter (*((uint*)(0x0C920F4))) +#define VAR_CurAdapter (*((uint*)(0x0C920F4))) #define HOOKPOS_GetFxQuality 0x49EA50 void HOOK_GetFxQuality(); @@ -53,7 +53,7 @@ CSettingsSA::CSettingsSA() HookInstall(HOOKPOS_StoreShadowForVehicle, (DWORD)HOOK_StoreShadowForVehicle, 9); m_iDesktopWidth = 0; m_iDesktopHeight = 0; - MemPut(0x6FF420, 0xC3); // Truncate CalculateAspectRatio + MemPut(0x6FF420, 0xC3); // Truncate CalculateAspectRatio MemPut(0x732926, &ms_fVehicleLODDistance); MemPut(0x732940, &ms_fTrainPlaneLODDistance); @@ -82,7 +82,7 @@ unsigned int CSettingsSA::GetNumVideoModes() VideoMode* CSettingsSA::GetVideoModeInfo(VideoMode* modeInfo, unsigned int modeIndex) { // RwEngineGetVideoModeInfo - return ((VideoMode*(__cdecl*)(VideoMode*, unsigned int))0x7F2CF0)(modeInfo, modeIndex); + return ((VideoMode * (__cdecl*)(VideoMode*, unsigned int))0x7F2CF0)(modeInfo, modeIndex); } unsigned int CSettingsSA::GetCurrentVideoMode() @@ -194,7 +194,7 @@ float CSettingsSA::GetDrawDistance() void CSettingsSA::SetDrawDistance(float fDistance) { - MemPutFast(0x8CD800, fDistance); // CRenderer::ms_lodDistScale + MemPutFast(0x8CD800, fDistance); // CRenderer::ms_lodDistScale m_pInterface->fDrawDistance = fDistance; } @@ -223,7 +223,7 @@ void CSettingsSA::SetFXQuality(unsigned int fxQualityId) float CSettingsSA::GetMouseSensitivity() { float fRawValue = *(float*)VAR_fMouseSensitivity; - return UnlerpClamped(MOUSE_SENSITIVITY_MIN, fRawValue, MOUSE_SENSITIVITY_MAX); // Remap to 0-1 + return UnlerpClamped(MOUSE_SENSITIVITY_MIN, fRawValue, MOUSE_SENSITIVITY_MAX); // Remap to 0-1 } void CSettingsSA::SetMouseSensitivity(float fSensitivity) @@ -293,7 +293,6 @@ void CSettingsSA::SetVolumetricShadowsEnabled(bool bEnable) MemPut(0x5E682A + 1, bEnable); } - bool CSettingsSA::GetVolumetricShadowsEnabledByVideoSetting() const noexcept { bool volumetricShadow; @@ -335,7 +334,6 @@ bool CSettingsSA::ResetDynamicPedShadows() noexcept return true; } - // // Volumetric shadow hooks // @@ -354,11 +352,11 @@ __declspec(noinline) void _cdecl MaybeAlterFxQualityValue(DWORD dwAddrCalledFrom // These vehicles seem to have problems with volumetric shadows, so force blob shadows switch (usCallingForVehicleModel) { - case 460: // Skimmer - case 511: // Beagle - case 572: // Mower - case 590: // Box Freight - case 592: // Andromada + case 460: // Skimmer + case 511: // Beagle + case 572: // Mower + case 590: // Box Freight + case 592: // Andromada dwFxQualityValue = 0; } usCallingForVehicleModel = 0; @@ -366,9 +364,9 @@ __declspec(noinline) void _cdecl MaybeAlterFxQualityValue(DWORD dwAddrCalledFrom else // Handle all calls from CPed::PreRenderAfterTest if (dwAddrCalledFrom > 0x5E65A0 && dwAddrCalledFrom < 0x5E7680) - { - dwFxQualityValue = pGame->GetSettings()->IsDynamicPedShadowsEnabled() ? 2 : 0; - } + { + dwFxQualityValue = pGame->GetSettings()->IsDynamicPedShadowsEnabled() ? 2 : 0; + } } // Hooked from 0x49EA50 @@ -451,7 +449,7 @@ void CSettingsSA::SetAspectRatio(eAspectRatio aspectRatio, bool bAdjustmentEnabl { fValue = 16 / 10.f; } - else // ASPECT_RATIO_16_9 + else // ASPECT_RATIO_16_9 { fValue = 16 / 9.f; } @@ -502,7 +500,7 @@ void CSettingsSA::SetRadarMode(eRadarMode hudMode) //////////////////////////////////////////////// float ms_fFOV = 70; float ms_fFOVCar = 70; -float ms_fFOVCarMax = 100; // at high vehicle velocity +float ms_fFOVCarMax = 100; // at high vehicle velocity bool ms_bFOVPlayerFromScript = false; bool ms_bFOVVehicleFromScript = false; @@ -976,11 +974,11 @@ __declspec(noinline) int OnMY_SelectDevice() } // Hook info -#define HOOKPOS_SelectDevice 0x0746219 +#define HOOKPOS_SelectDevice 0x0746219 #define HOOKSIZE_SelectDevice 6 -DWORD RETURN_SelectDeviceSingle = 0x0746273; -DWORD RETURN_SelectDeviceMultiHide = 0x074622C; -DWORD RETURN_SelectDeviceMultiShow = 0x0746227; +DWORD RETURN_SelectDeviceSingle = 0x0746273; +DWORD RETURN_SelectDeviceMultiHide = 0x074622C; +DWORD RETURN_SelectDeviceMultiShow = 0x0746227; static void __declspec(naked) HOOK_SelectDevice() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CSettingsSA.h b/Client/game_sa/CSettingsSA.h index 8e1443d1171..a21369ee52d 100644 --- a/Client/game_sa/CSettingsSA.h +++ b/Client/game_sa/CSettingsSA.h @@ -15,67 +15,67 @@ #include -#define CLASS_CMenuManager 0xBA6748 +#define CLASS_CMenuManager 0xBA6748 -#define FUNC_CMenuManager_Save 0x57C660 +#define FUNC_CMenuManager_Save 0x57C660 -#define VAR_ucFxQuality 0xA9AE54 -#define VAR_fMouseSensitivity 0xB6EC1C -#define VAR_RadarMode 0xBA676C +#define VAR_ucFxQuality 0xA9AE54 +#define VAR_fMouseSensitivity 0xB6EC1C +#define VAR_RadarMode 0xBA676C -#define CLASS_CAudioEngine 0xB6BC90 +#define CLASS_CAudioEngine 0xB6BC90 #define FUNC_CAudioEngine_SetEffectsMasterVolume 0x506E10 -#define FUNC_CAudioEngine_SetMusicMasterVolume 0x506DE0 +#define FUNC_CAudioEngine_SetMusicMasterVolume 0x506DE0 -#define CLASS_CGamma 0xC92134 +#define CLASS_CGamma 0xC92134 #define FUNC_CGamma_SetGamma 0x747200 -#define FUNC_SetAntiAliasing 0x7F8A90 +#define FUNC_SetAntiAliasing 0x7F8A90 -#define DEFAULT_VEHICLE_LOD_DISTANCE ( 70.0f ) -#define DEFAULT_PEDS_LOD_DISTANCE ( 60.0f ) +#define DEFAULT_VEHICLE_LOD_DISTANCE (70.0f) +#define DEFAULT_PEDS_LOD_DISTANCE (60.0f) // Default train distance is 150, so make it relative to default vehicle distance -#define TRAIN_LOD_DISTANCE_MULTIPLIER ( 2.14f ) -#define MAX_VEHICLE_LOD_DISTANCE ( 500.0f ) -#define MAX_PEDS_LOD_DISTANCE ( 500.0f ) -#define DEFAULT_BLUR_LEVEL ( 36 ) +#define TRAIN_LOD_DISTANCE_MULTIPLIER (2.14f) +#define MAX_VEHICLE_LOD_DISTANCE (500.0f) +#define MAX_PEDS_LOD_DISTANCE (500.0f) +#define DEFAULT_BLUR_LEVEL (36) -struct CSettingsSAInterface // see code around 0x57CE9A for where these are +struct CSettingsSAInterface // see code around 0x57CE9A for where these are { BYTE pad1[4]; - float fStatsScrollSpeed; // 0x4 + float fStatsScrollSpeed; // 0x4 BYTE pad2[0x34]; DWORD dwBrightness; float fDrawDistance; - bool bSubtitles; // 0x44 + bool bSubtitles; // 0x44 bool pad3[5]; - bool bLegend; // 0x4A - bool bUseWideScreen; // 0x4B - bool bFrameLimiter; // 0x4C - bool bRadioAutotune; // 0x4D + bool bLegend; // 0x4A + bool bUseWideScreen; // 0x4B + bool bFrameLimiter; // 0x4C + bool bRadioAutotune; // 0x4D bool pad4; - BYTE ucSfxVolume; // 0x4F - BYTE ucRadioVolume; // 0x50 - bool bRadioEqualizer; // 0x51 - BYTE ucRadioStation; // 0x52 + BYTE ucSfxVolume; // 0x4F + BYTE ucRadioVolume; // 0x50 + bool bRadioEqualizer; // 0x51 + BYTE ucRadioStation; // 0x52 BYTE pad5[0x5D]; - BYTE ucUsertrackMode; // 0xB0 - bool bInvertPadX1; // 0xB1 - bool bInvertPadY1; // 0xB2 - bool bInvertPadX2; // 0xB3 - bool bInvertPadY2; // 0xB4 - bool bSwapPadAxis1; // 0xB5 - bool bSwapPadAxis2; // 0xB6 + BYTE ucUsertrackMode; // 0xB0 + bool bInvertPadX1; // 0xB1 + bool bInvertPadY1; // 0xB2 + bool bInvertPadX2; // 0xB3 + bool bInvertPadY2; // 0xB4 + bool bSwapPadAxis1; // 0xB5 + bool bSwapPadAxis2; // 0xB6 BYTE pad6[0xD]; - bool bMipMapping; // 0xC4 (setting appears to have no effect in gta 1.0) - bool bUsertrackAutoScan; // 0xC5 + bool bMipMapping; // 0xC4 (setting appears to have no effect in gta 1.0) + bool bUsertrackAutoScan; // 0xC5 BYTE pad7[0x2]; - DWORD dwAntiAliasing; // 0xC8 - DWORD dwFrontendAA; // 0xCC (anti-aliasing value in the single-player settings menu. Useless for MTA). - bool bUseKeyboardAndMouse; // 0xD0 + DWORD dwAntiAliasing; // 0xC8 + DWORD dwFrontendAA; // 0xCC (anti-aliasing value in the single-player settings menu. Useless for MTA). + bool bUseKeyboardAndMouse; // 0xD0 BYTE pad8[3]; - DWORD dwVideoMode; // 0xD4 - DWORD dwPrevVideoMode; // 0xD8 + DWORD dwVideoMode; // 0xD4 + DWORD dwPrevVideoMode; // 0xD8 }; class CSettingsSA : public CGameSettings @@ -141,7 +141,7 @@ class CSettingsSA : public CGameSettings bool IsVolumetricShadowsEnabled() const noexcept; bool GetVolumetricShadowsEnabledByVideoSetting() const noexcept; bool ResetVolumetricShadows() noexcept; - + void SetVolumetricShadowsEnabled(bool bEnable); void SetVolumetricShadowsSuspended(bool bSuspended); diff --git a/Client/game_sa/CStatsSA.h b/Client/game_sa/CStatsSA.h index ea7e6d6a72a..37a393f91b6 100644 --- a/Client/game_sa/CStatsSA.h +++ b/Client/game_sa/CStatsSA.h @@ -13,10 +13,10 @@ #include -#define FUNC_GetStatValue 0x558E40 -#define FUNC_ModifyStat 0x55D090 -#define FUNC_SetStatValue 0x55A070 -#define FUNC_CWeaponInfo_GetSkillStatIndex 0x743CD0 +#define FUNC_GetStatValue 0x558E40 +#define FUNC_ModifyStat 0x55D090 +#define FUNC_SetStatValue 0x55A070 +#define FUNC_CWeaponInfo_GetSkillStatIndex 0x743CD0 class CStatsSA : public CStats { diff --git a/Client/game_sa/CStreamingGC.cpp b/Client/game_sa/CStreamingGC.cpp index 5398f6e27fa..0896e209637 100644 --- a/Client/game_sa/CStreamingGC.cpp +++ b/Client/game_sa/CStreamingGC.cpp @@ -17,8 +17,8 @@ extern CGameSA* pGame; // Static member initialization std::unordered_map CStreamingGC::ms_protectedModels; -std::mutex CStreamingGC::ms_mutex; -bool CStreamingGC::ms_bInitialized = false; +std::mutex CStreamingGC::ms_mutex; +bool CStreamingGC::ms_bInitialized = false; void CStreamingGC::Initialize() { @@ -28,7 +28,7 @@ void CStreamingGC::Initialize() // CStreamingGC provides Guard-based protection using model reference counting // Protected models have their reference count increased via ModelAddRef - + LogEvent(6645, "StreamingGC", "Initialize", "StreamingGC protection system initialized"); ms_bInitialized = true; } @@ -39,7 +39,7 @@ void CStreamingGC::Shutdown() return; std::lock_guard lock(ms_mutex); - + // Release all references before clearing if (!pGame) { @@ -61,7 +61,7 @@ void CStreamingGC::Shutdown() // Continue releasing remaining references on exception } } - + ms_protectedModels.clear(); ms_bInitialized = false; } @@ -76,7 +76,7 @@ bool CStreamingGC::ProtectModel(std::uint32_t modelId) return false; std::lock_guard lock(ms_mutex); - + auto findResult = ms_protectedModels.find(modelId); if (findResult != ms_protectedModels.end()) { @@ -104,12 +104,12 @@ bool CStreamingGC::ProtectModel(std::uint32_t modelId) } else { - // Attempted to protect unloaded model - #if MTA_DEBUG +// Attempted to protect unloaded model +#if MTA_DEBUG OutputDebugString(SString("CStreamingGC::ProtectModel: Ignored attempt to protect unloaded model %d", modelId)); - #endif +#endif } - + return false; } @@ -123,7 +123,7 @@ bool CStreamingGC::UnprotectModel(std::uint32_t modelId) return false; std::lock_guard lock(ms_mutex); - + // Only remove ref if currently protected auto findResult = ms_protectedModels.find(modelId); if (findResult != ms_protectedModels.end()) [[likely]] @@ -172,7 +172,7 @@ std::size_t CStreamingGC::GetProtectedCount() void CStreamingGC::ClearAllProtections() { std::lock_guard lock(ms_mutex); - + // Release all references before clearing if (pGame) { @@ -190,7 +190,7 @@ void CStreamingGC::ClearAllProtections() } } } - + ms_protectedModels.clear(); } @@ -206,7 +206,7 @@ bool CStreamingGC::OnRemoveModel(std::uint32_t modelId) { // Validate model ID is within valid range if (modelId >= MODELINFO_MAX) [[unlikely]] - return true; // Allow removal of invalid model IDs + return true; // Allow removal of invalid model IDs return !IsModelProtected(modelId); } diff --git a/Client/game_sa/CStreamingGC.h b/Client/game_sa/CStreamingGC.h index b44b4fc3eb9..a2bfd8f4f20 100644 --- a/Client/game_sa/CStreamingGC.h +++ b/Client/game_sa/CStreamingGC.h @@ -84,6 +84,6 @@ class CStreamingGC private: static std::unordered_map ms_protectedModels; - static std::mutex ms_mutex; - static bool ms_bInitialized; + static std::mutex ms_mutex; + static bool ms_bInitialized; }; diff --git a/Client/game_sa/CStreamingSA.cpp b/Client/game_sa/CStreamingSA.cpp index 114c12d5839..a43080f92ac 100644 --- a/Client/game_sa/CStreamingSA.cpp +++ b/Client/game_sa/CStreamingSA.cpp @@ -21,7 +21,7 @@ extern CCoreInterface* g_pCore; extern CGameSA* pGame; // count: 26316 in unmodified game -CStreamingInfo (&CStreamingSA::ms_aInfoForModel)[26316] = *(CStreamingInfo(*)[26316])0x8E4CC0; +CStreamingInfo (&CStreamingSA::ms_aInfoForModel)[26316] = *(CStreamingInfo (*)[26316])0x8E4CC0; HANDLE* phStreamingThread = (HANDLE*)0x8E4008; uint32(&CStreamingSA::ms_streamingHalfOfBufferSizeBlocks) = *(uint32*)0x8E4CA8; void* (&CStreamingSA::ms_pStreamingBuffer)[2] = *(void* (*)[2])0x8E4CAC; @@ -62,10 +62,10 @@ namespace void Record() { - #define VAR_CStreaming_bLoadingBigModel 0x08E4A58 - #define VAR_CStreaming_numPriorityRequests 0x08E4BA0 - #define VAR_CStreaming_numModelsRequested 0x08E4CB8 - #define VAR_CStreaming_memoryUsed 0x08E4CB4 +#define VAR_CStreaming_bLoadingBigModel 0x08E4A58 +#define VAR_CStreaming_numPriorityRequests 0x08E4BA0 +#define VAR_CStreaming_numModelsRequested 0x08E4CB8 +#define VAR_CStreaming_memoryUsed 0x08E4CB4 bLoadingBigModel = *(BYTE*)VAR_CStreaming_bLoadingBigModel != 0; numPriorityRequests = *(DWORD*)VAR_CStreaming_numPriorityRequests; @@ -74,11 +74,11 @@ namespace } }; - constexpr size_t RESERVED_STREAMS_NUM = 10; // GTA3 + 9 SFX archives(FEET, GENRL, PAIN_A, SCRIPT, SPC_EA, SPC_FA, SPC_GA, SPC_NA, SPC_PA) + constexpr size_t RESERVED_STREAMS_NUM = 10; // GTA3 + 9 SFX archives(FEET, GENRL, PAIN_A, SCRIPT, SPC_EA, SPC_FA, SPC_GA, SPC_NA, SPC_PA) constexpr size_t MAX_STREAMS_NUM = 255; constexpr size_t MAX_IMAGES_NUM = MAX_STREAMS_NUM - RESERVED_STREAMS_NUM; - constexpr size_t MIN_IMAGES_NUM = 6; // GTA3(yes, it is presented twice), GTA_INT, CARREC, SCRIPT, CUTSCENE, PLAYER -} // namespace + constexpr size_t MIN_IMAGES_NUM = 6; // GTA3(yes, it is presented twice), GTA_INT, CARREC, SCRIPT, CUTSCENE, PLAYER +} // namespace bool IsUpgradeModelId(DWORD dwModelID) { @@ -91,16 +91,13 @@ CStreamingSA::CStreamingSA() SetArchivesNum(VAR_DefaultMaxArchives); // Copy the default data - HANDLE (&defaultStreamingHandlers)[32] = *(HANDLE(*)[32])0x8E4010; - SStreamName (&defaultStreamingNames)[32] = *(SStreamName(*)[32])0x8E4098; - CArchiveInfo (&defaultAchiveInfo)[8] = *(CArchiveInfo(*)[8])0x8E48D8; - - std::memcpy(m_StreamHandles.data(), defaultStreamingHandlers, - sizeof(HANDLE) * std::min(m_StreamHandles.size(), (size_t)VAR_DefaultStreamHandlersMaxCount)); - std::memcpy(m_StreamNames.data(), defaultStreamingNames, - sizeof(SStreamName) * std::min(m_StreamNames.size(), (size_t)VAR_DefaultStreamHandlersMaxCount)); - std::memcpy(m_Imgs.data(), defaultAchiveInfo, - sizeof(CArchiveInfo) * std::min(m_Imgs.size(), (size_t)VAR_DefaultMaxArchives)); + HANDLE(&defaultStreamingHandlers)[32] = *(HANDLE(*)[32])0x8E4010; + SStreamName(&defaultStreamingNames)[32] = *(SStreamName(*)[32])0x8E4098; + CArchiveInfo(&defaultAchiveInfo)[8] = *(CArchiveInfo(*)[8])0x8E48D8; + + std::memcpy(m_StreamHandles.data(), defaultStreamingHandlers, sizeof(HANDLE) * std::min(m_StreamHandles.size(), (size_t)VAR_DefaultStreamHandlersMaxCount)); + std::memcpy(m_StreamNames.data(), defaultStreamingNames, sizeof(SStreamName) * std::min(m_StreamNames.size(), (size_t)VAR_DefaultStreamHandlersMaxCount)); + std::memcpy(m_Imgs.data(), defaultAchiveInfo, sizeof(CArchiveInfo) * std::min(m_Imgs.size(), (size_t)VAR_DefaultMaxArchives)); } void CStreamingSA::SetArchivesNum(size_t imagesNum) @@ -122,7 +119,7 @@ void CStreamingSA::SetArchivesNum(size_t imagesNum) return; } - const auto pImgs = m_Imgs.data(); + const auto pImgs = m_Imgs.data(); const size_t uiImgsSize = sizeof(CArchiveInfo) * m_Imgs.size(); // CStreaming::AddImageToList @@ -208,24 +205,24 @@ void CStreamingSA::SetArchivesNum(size_t imagesNum) // _openStream DWORD dwExeCodePtr = (DWORD)0x01564A94; - MemPutFast((void*)(dwExeCodePtr), (WORD)0x048B); // mov eax, _streamHandles[esi*4] + MemPutFast((void*)(dwExeCodePtr), (WORD)0x048B); // mov eax, _streamHandles[esi*4] MemPutFast((void*)(dwExeCodePtr + 2), (BYTE)0xB5); MemPutFast((void*)(dwExeCodePtr + 3), (DWORD)pStreamHandles); MemPutFast((void*)(dwExeCodePtr + 7), (WORD)0xC085); MemPutFast((void*)(dwExeCodePtr + 9), (WORD)0x840F); - MemPutFast((void*)(dwExeCodePtr + 11), (DWORD)(0x01564B31 - (dwExeCodePtr+15))); + MemPutFast((void*)(dwExeCodePtr + 11), (DWORD)(0x01564B31 - (dwExeCodePtr + 15))); MemPutFast((void*)(dwExeCodePtr + 15), (BYTE)0x46); MemPutFast((void*)(dwExeCodePtr + 16), (WORD)0xFE81); - MemPutFast((void*)(dwExeCodePtr + 18), (DWORD)(handlesNum - 1)); // MAX_NUMBER_OF_STREAM_HANDLES + MemPutFast((void*)(dwExeCodePtr + 18), (DWORD)(handlesNum - 1)); // MAX_NUMBER_OF_STREAM_HANDLES MemPutFast((void*)(dwExeCodePtr + 22), (BYTE)0x7C); - MemPutFast((void*)(dwExeCodePtr + 23), (BYTE)(dwExeCodePtr - (dwExeCodePtr+24))); + MemPutFast((void*)(dwExeCodePtr + 23), (BYTE)(dwExeCodePtr - (dwExeCodePtr + 24))); MemPutFast((void*)(dwExeCodePtr + 24), (BYTE)0xE9); - MemPutFast((void*)(dwExeCodePtr + 25), (DWORD)(0x01564B31 - (dwExeCodePtr+29))); + MemPutFast((void*)(dwExeCodePtr + 25), (DWORD)(0x01564B31 - (dwExeCodePtr + 29))); // end of loop creation MemPutFast((void*)0x1564B74, (DWORD)pStreamHandles); @@ -478,7 +475,7 @@ unsigned char CStreamingSA::AddArchive(const wchar_t* szFilePath) // Create new stream handler const auto streamCreateFlags = *(DWORD*)0x8E3FE0; HANDLE hFile = CreateFileW(szFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - streamCreateFlags | FILE_ATTRIBUTE_READONLY | FILE_FLAG_RANDOM_ACCESS, NULL); + streamCreateFlags | FILE_ATTRIBUTE_READONLY | FILE_FLAG_RANDOM_ACCESS, NULL); if (hFile == INVALID_HANDLE_VALUE) return INVALID_ARCHIVE_ID; @@ -506,7 +503,7 @@ void CStreamingSA::RemoveArchive(unsigned char ucArchiveID) bool CStreamingSA::SetStreamingBufferSize(uint32 numBlocks) { - numBlocks += numBlocks % 2; // Make sure number is even by "rounding" it upwards. [Otherwise it can't be split in half properly] + numBlocks += numBlocks % 2; // Make sure number is even by "rounding" it upwards. [Otherwise it can't be split in half properly] // Check if the size is the same already if (numBlocks == ms_streamingHalfOfBufferSizeBlocks * 2) @@ -519,14 +516,15 @@ bool CStreamingSA::SetStreamingBufferSize(uint32 numBlocks) // NOTE: Due to a bug in the `MallocAlign` code the function will just *crash* instead of returning nullptr on alloc. failure :D typedef void*(__cdecl * Function_CMemoryMgr_MallocAlign)(uint32 uiCount, uint32 uiAlign); void* pNewBuffer = ((Function_CMemoryMgr_MallocAlign)(0x72F4C0))(numBlocks * 2048, 2048); - if (!pNewBuffer) // ...so this code is useless for now + if (!pNewBuffer) // ...so this code is useless for now return false; int pointer = *(int*)0x8E3FFC; SGtaStream(&streaming)[5] = *(SGtaStream(*)[5])(pointer); // Wait while streaming thread ends tasks - while (streaming[0].bInUse || streaming[1].bInUse); + while (streaming[0].bInUse || streaming[1].bInUse) + ; // Suspend streaming thread [otherwise data might become corrupted] SuspendThread(*phStreamingThread); diff --git a/Client/game_sa/CStreamingSA.h b/Client/game_sa/CStreamingSA.h index a7a4598860a..00fe6727b3f 100644 --- a/Client/game_sa/CStreamingSA.h +++ b/Client/game_sa/CStreamingSA.h @@ -13,20 +13,20 @@ #include -#define VAR_DefaultStreamHandlersMaxCount 32 -#define VAR_DefaultMaxArchives 8 +#define VAR_DefaultStreamHandlersMaxCount 32 +#define VAR_DefaultMaxArchives 8 -#define FUNC_CStreaming__RequestModel 0x4087E0 -#define FUNC_LoadAllRequestedModels 0x40EA10 -#define FUNC_CStreaming__HasVehicleUpgradeLoaded 0x407820 -#define FUNC_CStreaming_RequestSpecialModel 0x409d10 -#define FUNC_CStreaming_LoadScene 0x40EB70 -#define FUNC_CStreaming_LoadSceneCollision 0x40ED80 +#define FUNC_CStreaming__RequestModel 0x4087E0 +#define FUNC_LoadAllRequestedModels 0x40EA10 +#define FUNC_CStreaming__HasVehicleUpgradeLoaded 0x407820 +#define FUNC_CStreaming_RequestSpecialModel 0x409d10 +#define FUNC_CStreaming_LoadScene 0x40EB70 +#define FUNC_CStreaming_LoadSceneCollision 0x40ED80 struct CArchiveInfo { char szName[40]; - BYTE bUnknow = 1; // Only in player.img is 0. Maybe, it is DWORD value + BYTE bUnknow = 1; // Only in player.img is 0. Maybe, it is DWORD value BYTE bUnused[3]; DWORD uiStreamHandleId{}; }; @@ -74,7 +74,7 @@ class CStreamingSA final : public CStreaming unsigned char AddArchive(const wchar_t* szFilePath); void RemoveArchive(unsigned char ucStreamHandler); bool SetStreamingBufferSize(uint32 uiSize); - uint32 GetStreamingBufferSize() { return ms_streamingHalfOfBufferSizeBlocks * 2048 * 2; }; // In bytes + uint32 GetStreamingBufferSize() { return ms_streamingHalfOfBufferSizeBlocks * 2048 * 2; }; // In bytes void MakeSpaceFor(std::uint32_t memoryToCleanInBytes) override; std::uint32_t GetMemoryUsed() const override; @@ -86,10 +86,10 @@ class CStreamingSA final : public CStreaming void AllocateArchive(); std::vector m_Imgs; - std::vector m_StreamHandles; - std::vector m_StreamNames; + std::vector m_StreamHandles; + std::vector m_StreamNames; static void* (&ms_pStreamingBuffer)[2]; static uint32(&ms_streamingHalfOfBufferSizeBlocks); - static CStreamingInfo (&ms_aInfoForModel)[26316]; // count: 26316 in unmodified game + static CStreamingInfo (&ms_aInfoForModel)[26316]; // count: 26316 in unmodified game }; diff --git a/Client/game_sa/CTaskManagementSystemSA.cpp b/Client/game_sa/CTaskManagementSystemSA.cpp index 16b4878d5f5..f92e70506a8 100644 --- a/Client/game_sa/CTaskManagementSystemSA.cpp +++ b/Client/game_sa/CTaskManagementSystemSA.cpp @@ -114,7 +114,7 @@ CTaskSA* CTaskManagementSystemSA::GetTask(CTaskSAInterface* pTaskInterface) // GTA SA base is around 0x400000-0x900000 range constexpr DWORD GTA_BASE_MIN = 0x400000; constexpr DWORD GTA_BASE_MAX = 0x900000; - DWORD dwVTableAddr = reinterpret_cast(pVTBL); + DWORD dwVTableAddr = reinterpret_cast(pVTBL); if (dwVTableAddr < GTA_BASE_MIN || dwVTableAddr > GTA_BASE_MAX) return nullptr; diff --git a/Client/game_sa/CTaskManagementSystemSA.h b/Client/game_sa/CTaskManagementSystemSA.h index 98894375c42..d0777bd975a 100644 --- a/Client/game_sa/CTaskManagementSystemSA.h +++ b/Client/game_sa/CTaskManagementSystemSA.h @@ -14,7 +14,7 @@ class CTaskSA; class CTaskSAInterface; -#define FUNC_CTask_Operator_Delete 0x61A5B0 +#define FUNC_CTask_Operator_Delete 0x61A5B0 class CTaskManagementSystemSA { diff --git a/Client/game_sa/CTaskManagerSA.cpp b/Client/game_sa/CTaskManagerSA.cpp index c2e29a0e534..a1ce4e2e4cb 100644 --- a/Client/game_sa/CTaskManagerSA.cpp +++ b/Client/game_sa/CTaskManagerSA.cpp @@ -26,7 +26,7 @@ CTaskManagerSA::CTaskManagerSA(CTaskManagerSAInterface* taskManagerInterface, CP void CTaskManagerSA::RemoveTask(const int iTaskPriority) { - if (iTaskPriority != TASK_PRIORITY_DEFAULT) // TASK_PRIORITY_DEFAULT removed = crash + if (iTaskPriority != TASK_PRIORITY_DEFAULT) // TASK_PRIORITY_DEFAULT removed = crash { SetTask(NULL, iTaskPriority); } diff --git a/Client/game_sa/CTaskManagerSA.h b/Client/game_sa/CTaskManagerSA.h index 897e7ef7663..c22d99bac36 100644 --- a/Client/game_sa/CTaskManagerSA.h +++ b/Client/game_sa/CTaskManagerSA.h @@ -17,15 +17,15 @@ class CTaskSAInterface; class CTaskManagementSystemSA; class CTaskSA; -#define FUNC_SetTask 0x681AF0 -#define FUNC_GetActiveTask 0x681720 -#define FUNC_GetSimplestActiveTask 0x6819D0 -#define FUNC_GetSimplestTask 0x681A00 -#define FUNC_FindActiveTaskByType 0x681740 -#define FUNC_FindTaskByType 0x6817D0 -#define FUNC_SetTaskSecondary 0x681B60 -#define FUNC_ClearTaskEventResponse 0x681BD0 -#define FUNC_HasTaskSecondary 0x681820 +#define FUNC_SetTask 0x681AF0 +#define FUNC_GetActiveTask 0x681720 +#define FUNC_GetSimplestActiveTask 0x6819D0 +#define FUNC_GetSimplestTask 0x681A00 +#define FUNC_FindActiveTaskByType 0x681740 +#define FUNC_FindTaskByType 0x6817D0 +#define FUNC_SetTaskSecondary 0x681B60 +#define FUNC_ClearTaskEventResponse 0x681BD0 +#define FUNC_HasTaskSecondary 0x681820 // pointer for this at +1148+4? (see 0x568A20) class CTaskManagerSAInterface @@ -59,8 +59,8 @@ class CTaskManagerSA : public CTaskManager void RemoveTaskSecondary(const int iTaskPriority); bool RemoveTaskSecondary(const int taskPriority, const int taskType); void SetTaskSecondary(CTaskSA* pTaskSecondary, const int iType); - CTask* GetTaskSecondary(const int iType); // code it - bool HasTaskSecondary(const CTask* pTaskSecondary); // code it + CTask* GetTaskSecondary(const int iType); // code it + bool HasTaskSecondary(const CTask* pTaskSecondary); // code it void ClearTaskEventResponse(); void Flush(const int iPriority); }; diff --git a/Client/game_sa/CTasksSA.cpp b/Client/game_sa/CTasksSA.cpp index 16b66d3f67f..301f80b2e05 100644 --- a/Client/game_sa/CTasksSA.cpp +++ b/Client/game_sa/CTasksSA.cpp @@ -124,8 +124,8 @@ CTaskSimpleChoking* CTasksSA::CreateTaskSimpleChoking(CPed* pAttacker, bool bIsT return pTask; } -CTaskSimpleClimb* CTasksSA::CreateTaskSimpleClimb(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, eClimbHeights nHeight, - const bool bForceClimb) +CTaskSimpleClimb* CTasksSA::CreateTaskSimpleClimb(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, + eClimbHeights nHeight, const bool bForceClimb) { CTaskSimpleClimbSA* pTask = NewTask(pClimbEnt, vecTarget, fHeading, nSurfaceType, nHeight, bForceClimb); m_pTaskManagementSystem->AddTask(pTask); @@ -278,10 +278,10 @@ __declspec(noinline) void _cdecl OnCEventHandler_ComputeDamageResponse_Mid(CPedS } // Hook info -#define HOOKPOS_CEventHandler_ComputeDamageResponse_Mid 0x4C0593 -#define HOOKSIZE_CEventHandler_ComputeDamageResponse_Mid 5 -DWORD RETURN_CEventHandler_ComputeDamageResponse_Mid = 0x4C0598; -DWORD CTaskSimpleBeHit_constructor = FUNC_CTaskSimpleBeHit__Constructor; +#define HOOKPOS_CEventHandler_ComputeDamageResponse_Mid 0x4C0593 +#define HOOKSIZE_CEventHandler_ComputeDamageResponse_Mid 5 +DWORD RETURN_CEventHandler_ComputeDamageResponse_Mid = 0x4C0598; +DWORD CTaskSimpleBeHit_constructor = FUNC_CTaskSimpleBeHit__Constructor; static void __declspec(naked) HOOK_CEventHandler_ComputeDamageResponse_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/game_sa/CTasksSA.h b/Client/game_sa/CTasksSA.h index fd1d06c5b12..65c0fd65dcf 100644 --- a/Client/game_sa/CTasksSA.h +++ b/Client/game_sa/CTasksSA.h @@ -71,8 +71,8 @@ class CTasksSA : public CTasks CTaskSimpleDuck* CreateTaskSimpleDuck(eDuckControlTypes nDuckControl, unsigned short nLengthOfDuck = 0, unsigned short nUseShotsWhizzingEvents = -1); CTaskSimpleChoking* CreateTaskSimpleChoking(CPed* pAttacker, bool bIsTearGas); - CTaskSimpleClimb* CreateTaskSimpleClimb(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, eClimbHeights nHeight = CLIMB_GRAB, - const bool bForceClimb = false); + CTaskSimpleClimb* CreateTaskSimpleClimb(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, + eClimbHeights nHeight = CLIMB_GRAB, const bool bForceClimb = false); CTaskSimpleJetPack* CreateTaskSimpleJetpack(const CVector* pVecTargetPos = NULL, float fCruiseHeight = 10.0f, int nHoverTime = 0); CTaskSimpleRunAnim* CreateTaskSimpleRunAnim(const AssocGroupId animGroup, const AnimationId animID, const float fBlendDelta, const int iTaskType, diff --git a/Client/game_sa/CTrainSA.h b/Client/game_sa/CTrainSA.h index daa367b2cf6..202cb8ce937 100644 --- a/Client/game_sa/CTrainSA.h +++ b/Client/game_sa/CTrainSA.h @@ -55,19 +55,19 @@ class CTrainSAInterface : public CVehicleSAInterface char _pad1[2]; public: - float m_fTrainSpeed; // 1.0 - train derails - float m_fTrainRailDistance; // Distance along rail starting from first rail node (determines train position when on rails) + float m_fTrainSpeed; // 1.0 - train derails + float m_fTrainRailDistance; // Distance along rail starting from first rail node (determines train position when on rails) float m_fDistanceToNextCarriage; - float m_fTrainGas; // gas pedal pressed: 255.0, moving forward: 0.0, moving back: -255.0 - float m_fTrainBrake; // 255.0 - braking + float m_fTrainGas; // gas pedal pressed: 255.0, moving forward: 0.0, moving back: -255.0 + float m_fTrainBrake; // 255.0 - braking union { struct { - unsigned short b01 : 1; // initialised with 1 - unsigned short bStoppedAtStation : 1; // Only the first created train on the chain gets this set to true, others get it set to false. + unsigned short b01 : 1; // initialised with 1 + unsigned short bStoppedAtStation : 1; // Only the first created train on the chain gets this set to true, others get it set to false. unsigned short bPassengersCanEnterAndLeave : 1; - unsigned short bIsTheChainEngine : 1; // front carriage + unsigned short bIsTheChainEngine : 1; // front carriage unsigned short bIsLastCarriage : 1; unsigned short bMissionTrain : 1; unsigned short bClockwiseDirection : 1; @@ -91,11 +91,11 @@ class CTrainSAInterface : public CVehicleSAInterface public: int m_nTimeWhenCreated; - short field_5C8; // initialized with 0, not referenced + short field_5C8; // initialized with 0, not referenced eTrainPassengersGenerationState m_nPassengersGenerationState; - unsigned char m_nNumPassengersToLeave : 4; // 0 to 4 - unsigned char m_nNumPassengersToEnter : 4; // 0 to 4 - CPedSAInterface* m_pTemporaryPassenger; // we tell peds to enter train and then delete them + unsigned char m_nNumPassengersToLeave : 4; // 0 to 4 + unsigned char m_nNumPassengersToEnter : 4; // 0 to 4 + CPedSAInterface* m_pTemporaryPassenger; // we tell peds to enter train and then delete them CTrainSAInterface* m_prevCarriage; CTrainSAInterface* m_nextCarriage; CDoorSAInterface m_aDoors[MAX_DOORS]; diff --git a/Client/game_sa/CTxdPoolSA.h b/Client/game_sa/CTxdPoolSA.h index 7e1e2c48a77..fd8d73b0d41 100644 --- a/Client/game_sa/CTxdPoolSA.h +++ b/Client/game_sa/CTxdPoolSA.h @@ -28,7 +28,7 @@ class CTxdPoolSA final : public CTxdPool // Access/modification helpers for slots we create CTextureDictonarySAInterface* GetTextureDictonarySlot(std::uint32_t uiTxdId) noexcept; - bool SetTextureDictonarySlot(std::uint32_t uiTxdId, RwTexDictionary* pTxd, std::uint16_t usParentIndex) noexcept; + bool SetTextureDictonarySlot(std::uint32_t uiTxdId, RwTexDictionary* pTxd, std::uint16_t usParentIndex) noexcept; private: CPoolSAInterface** m_ppTxdPoolInterface; diff --git a/Client/game_sa/CVehicleAudioSettingsEntrySA.h b/Client/game_sa/CVehicleAudioSettingsEntrySA.h index 319e1614617..24298d6e40a 100644 --- a/Client/game_sa/CVehicleAudioSettingsEntrySA.h +++ b/Client/game_sa/CVehicleAudioSettingsEntrySA.h @@ -18,48 +18,51 @@ struct tVehicleAudioSettings { VehicleSoundType m_eVehicleSoundType; - int16 m_nEngineOnSoundBankId; - int16 m_nEngineOffSoundBankId; - int8 m_nBassSetting; // 0 or 1 or 2 - float m_fBassEq; - float field_C; - int8 m_nHornToneSoundInBank; - float m_fHornHigh; - char m_nDoorSound; - char m_EngineUpgrade; - char m_nRadioID; - char m_nRadioType; - char m_nVehTypeForAudio; - float m_fHornVolumeDelta; + int16 m_nEngineOnSoundBankId; + int16 m_nEngineOffSoundBankId; + int8 m_nBassSetting; // 0 or 1 or 2 + float m_fBassEq; + float field_C; + int8 m_nHornToneSoundInBank; + float m_fHornHigh; + char m_nDoorSound; + char m_EngineUpgrade; + char m_nRadioID; + char m_nRadioType; + char m_nVehTypeForAudio; + float m_fHornVolumeDelta; }; static_assert(sizeof(tVehicleAudioSettings) == 0x24, "Invalid size for tVehicleAudioSettings"); class CVehicleAudioSettingsEntrySA final : public CVehicleAudioSettingsEntry { public: - CVehicleAudioSettingsEntrySA(): m_Settings{} {}; + CVehicleAudioSettingsEntrySA() : m_Settings{} {}; CVehicleAudioSettingsEntrySA(tVehicleAudioSettings* pSettings) { m_Settings = *pSettings; }; ~CVehicleAudioSettingsEntrySA() = default; const tVehicleAudioSettings& GetInterface() const noexcept { return m_Settings; }; void Assign(const tVehicleAudioSettings& settings) noexcept { m_Settings = settings; } - void Assign(const CVehicleAudioSettingsEntry& settings) noexcept { m_Settings = static_cast(settings).GetInterface(); }; + void Assign(const CVehicleAudioSettingsEntry& settings) noexcept + { + m_Settings = static_cast(settings).GetInterface(); + }; - VehicleSoundType GetSoundType() const noexcept override { return m_Settings.m_eVehicleSoundType; }; - short GetEngineOnSoundBankID() const noexcept override { return m_Settings.m_nEngineOnSoundBankId; }; - short GetEngineOffSoundBankID() const noexcept override { return m_Settings.m_nEngineOffSoundBankId; }; - char GetBassSetting() const noexcept override { return m_Settings.m_nBassSetting; }; - float GetBassEq() const noexcept override { return m_Settings.m_fBassEq; }; - float GetFieldC() const noexcept override { return m_Settings.field_C; }; - char GetHornTon() const noexcept override { return m_Settings.m_nHornToneSoundInBank; }; - float GetHornHign() const noexcept override { return m_Settings.m_fHornHigh; }; - char GetEngineUpgrade() const noexcept override { return m_Settings.m_EngineUpgrade; }; - char GetDoorSound() const noexcept override { return m_Settings.m_nDoorSound; }; - char GetRadioNum() const noexcept override { return m_Settings.m_nRadioID; }; - char GetRadioType() const noexcept override { return m_Settings.m_nRadioType; }; - char GetVehicleTypeForAudio() const noexcept override { return m_Settings.m_nVehTypeForAudio; }; - float GetHornVolumeDelta() const noexcept override { return m_Settings.m_fHornVolumeDelta; }; + VehicleSoundType GetSoundType() const noexcept override { return m_Settings.m_eVehicleSoundType; }; + short GetEngineOnSoundBankID() const noexcept override { return m_Settings.m_nEngineOnSoundBankId; }; + short GetEngineOffSoundBankID() const noexcept override { return m_Settings.m_nEngineOffSoundBankId; }; + char GetBassSetting() const noexcept override { return m_Settings.m_nBassSetting; }; + float GetBassEq() const noexcept override { return m_Settings.m_fBassEq; }; + float GetFieldC() const noexcept override { return m_Settings.field_C; }; + char GetHornTon() const noexcept override { return m_Settings.m_nHornToneSoundInBank; }; + float GetHornHign() const noexcept override { return m_Settings.m_fHornHigh; }; + char GetEngineUpgrade() const noexcept override { return m_Settings.m_EngineUpgrade; }; + char GetDoorSound() const noexcept override { return m_Settings.m_nDoorSound; }; + char GetRadioNum() const noexcept override { return m_Settings.m_nRadioID; }; + char GetRadioType() const noexcept override { return m_Settings.m_nRadioType; }; + char GetVehicleTypeForAudio() const noexcept override { return m_Settings.m_nVehTypeForAudio; }; + float GetHornVolumeDelta() const noexcept override { return m_Settings.m_fHornVolumeDelta; }; void SetSoundType(VehicleSoundType value) noexcept override { m_Settings.m_eVehicleSoundType = value; }; void SetEngineOnSoundBankID(short value) noexcept override { m_Settings.m_nEngineOnSoundBankId = value; }; diff --git a/Client/game_sa/CVehicleAudioSettingsManagerSA.cpp b/Client/game_sa/CVehicleAudioSettingsManagerSA.cpp index a47cdeed003..99eb0b99b10 100644 --- a/Client/game_sa/CVehicleAudioSettingsManagerSA.cpp +++ b/Client/game_sa/CVehicleAudioSettingsManagerSA.cpp @@ -14,7 +14,7 @@ #include const auto (&ORIGINAL_AUDIO_SETTINGS)[VEHICLES_COUNT] = *reinterpret_cast(0x860AF0); -tVehicleAudioSettings const * pNextVehicleAudioSettings = nullptr; +tVehicleAudioSettings const* pNextVehicleAudioSettings = nullptr; CVehicleAudioSettingsManagerSA::CVehicleAudioSettingsManagerSA() { @@ -23,7 +23,7 @@ CVehicleAudioSettingsManagerSA::CVehicleAudioSettingsManagerSA() std::unique_ptr CVehicleAudioSettingsManagerSA::CreateVehicleAudioSettingsData(uint32_t modelId) { - auto settings = std::make_unique(); + auto settings = std::make_unique(); const auto& fromSetting = GetVehicleModelAudioSettingsData(modelId); settings->Assign(fromSetting); return settings; @@ -58,7 +58,7 @@ void CVehicleAudioSettingsManagerSA::ResetAudioSettingsData() noexcept void CVehicleAudioSettingsManagerSA::StaticSetHooks() noexcept { - // Replace + // Replace // 8D 34 B5 F0 0A 86 00 ; lea esi, _VehicleAudioProperties.m_eVehicleSoundType[esi*4] // to // 8b 35 XX XX XX XX ; mov esi, [pNextVehicleAudioSettings] diff --git a/Client/game_sa/CVehicleAudioSettingsManagerSA.h b/Client/game_sa/CVehicleAudioSettingsManagerSA.h index ddd15140954..c7e2b936b48 100644 --- a/Client/game_sa/CVehicleAudioSettingsManagerSA.h +++ b/Client/game_sa/CVehicleAudioSettingsManagerSA.h @@ -24,7 +24,7 @@ class CVehicleAudioSettingsManagerSA final : public CVehicleAudioSettingsManager CVehicleAudioSettingsManagerSA(); std::unique_ptr CreateVehicleAudioSettingsData(uint32_t modelId) override; - CVehicleAudioSettingsEntry& GetVehicleModelAudioSettingsData(uint32_t modelId) noexcept override; + CVehicleAudioSettingsEntry& GetVehicleModelAudioSettingsData(uint32_t modelId) noexcept override; void ResetModelSettings(uint32_t modelId) noexcept override; void ResetAudioSettingsData() noexcept override; diff --git a/Client/game_sa/CVehicleSA.cpp b/Client/game_sa/CVehicleSA.cpp index ee02bb2750b..cc5d6c1e3b4 100644 --- a/Client/game_sa/CVehicleSA.cpp +++ b/Client/game_sa/CVehicleSA.cpp @@ -59,7 +59,7 @@ static void __declspec(naked) HOOK_Vehicle_PreRender(void) // clang-format on } -static float& fTimeStep = *(float*)(0xB7CB5C); +static float& fTimeStep = *(float*)(0xB7CB5C); static bool __fastcall CanProcessFlyingCarStuff(CAutomobileSAInterface* vehicleInterface) { SClientEntity* vehicle = pGame->GetPools()->GetVehicle((DWORD*)vehicleInterface); @@ -68,12 +68,12 @@ static bool __fastcall CanProcessFlyingCarStuff(CAutomobileSAInterface* vehicleI if (vehicle->pEntity->GetVehicleRotorState()) { - if (g_pCore->GetMultiplayer()->IsVehicleEngineAutoStartEnabled()) // keep default behavior + if (g_pCore->GetMultiplayer()->IsVehicleEngineAutoStartEnabled()) // keep default behavior return true; if (vehicle->pEntity->GetEntityStatus() != eEntityStatus::STATUS_PHYSICS && !vehicle->pEntity->IsBeingDriven()) { - vehicle->pEntity->SetEntityStatus(eEntityStatus::STATUS_PHYSICS); // this will make rotors spin without driver when engine is on + vehicle->pEntity->SetEntityStatus(eEntityStatus::STATUS_PHYSICS); // this will make rotors spin without driver when engine is on return false; } if (!vehicle->pEntity->IsEngineOn()) @@ -81,11 +81,11 @@ static bool __fastcall CanProcessFlyingCarStuff(CAutomobileSAInterface* vehicleI // Smoothly change rotors speed to 0 float speed = vehicle->pEntity->GetHeliRotorSpeed(); if (speed > 0) - vehicle->pEntity->SetHeliRotorSpeed(std::max(0.0f, speed - fTimeStep * 0.00055f)); // 0x6C4EB7 + vehicle->pEntity->SetHeliRotorSpeed(std::max(0.0f, speed - fTimeStep * 0.00055f)); // 0x6C4EB7 speed = vehicle->pEntity->GetPlaneRotorSpeed(); if (speed > 0) - vehicle->pEntity->SetPlaneRotorSpeed(std::max(0.0f, speed - fTimeStep * 0.003f)); // 0x6CC145 + vehicle->pEntity->SetPlaneRotorSpeed(std::max(0.0f, speed - fTimeStep * 0.003f)); // 0x6CC145 return false; } @@ -94,8 +94,8 @@ static bool __fastcall CanProcessFlyingCarStuff(CAutomobileSAInterface* vehicleI return false; } -static constexpr DWORD CONTINUE_CHeli_ProcessFlyingCarStuff = 0x6C4E82; -static constexpr DWORD RETURN_CHeli_ProcessFlyingCarStuff = 0x6C5404; +static constexpr DWORD CONTINUE_CHeli_ProcessFlyingCarStuff = 0x6C4E82; +static constexpr DWORD RETURN_CHeli_ProcessFlyingCarStuff = 0x6C5404; static void __declspec(naked) HOOK_CHeli_ProcessFlyingCarStuff() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -120,8 +120,8 @@ static void __declspec(naked) HOOK_CHeli_ProcessFlyingCarStuff() // clang-format on } -static constexpr DWORD CONTINUE_CPlane_ProcessFlyingCarStuff = 0x6CB7D7; -static constexpr DWORD RETURN_CPlane_ProcessFlyingCarStuff = 0x6CC482; +static constexpr DWORD CONTINUE_CPlane_ProcessFlyingCarStuff = 0x6CB7D7; +static constexpr DWORD RETURN_CPlane_ProcessFlyingCarStuff = 0x6CC482; static void __declspec(naked) HOOK_CPlane_ProcessFlyingCarStuff() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -207,8 +207,11 @@ namespace } // Get all atomics for this frame (even if they are invisible) - void GetAllAtomicObjects(RwFrame* frame, std::vector& result) { RwFrameForAllObjects(frame, (void*)GetAllAtomicObjectCB, &result); } -} // namespace + void GetAllAtomicObjects(RwFrame* frame, std::vector& result) + { + RwFrameForAllObjects(frame, (void*)GetAllAtomicObjectCB, &result); + } +} // namespace void CVehicleSA::Init() { @@ -326,7 +329,7 @@ CVehicleSA::~CVehicleSA() } DWORD dwThis = (DWORD)m_pInterface; - DWORD dwFunc = 0x6D2460; // CVehicle::ExtinguishCarFire + DWORD dwFunc = 0x6D2460; // CVehicle::ExtinguishCarFire // clang-format off __asm { @@ -625,7 +628,7 @@ void CVehicleSA::SetPlaneRotorSpeed(float fSpeed) } bool CVehicleSA::SetVehicleWheelRotation(float fWheelRot1, float fWheelRot2, float fWheelRot3, float fWheelRot4) noexcept -{ +{ VehicleClass m_eVehicleType = static_cast(GetVehicleInterface()->m_vehicleSubClass); switch (m_eVehicleType) { @@ -655,7 +658,7 @@ bool CVehicleSA::SetVehicleWheelRotation(float fWheelRot1, float fWheelRot2, flo return false; } -float CVehicleSA::GetPlaneRotorSpeed() +float CVehicleSA::GetPlaneRotorSpeed() { auto pInterface = static_cast(GetInterface()); return pInterface->m_fPropSpeed; @@ -1002,14 +1005,14 @@ void CVehicleSA::SetColor(SharedUtil::SColor color1, SharedUtil::SColor color2, { m_RGBColorsFixed[i] = m_RGBColors[i]; const SharedUtil::SColor color = m_RGBColorsFixed[i]; - if (color == 0xFF00FF // 255, 0, 255 - || color == 0x00FFFF // 0, 0, 255 - || color == 0xFF00AF // 255, 0, 175 - || color == 0xFFAF00 // 255, 175, 0 - || color == 0xB9FF00 // 185, 255, 0 - || color == 0x00FFC8 // 0, 255, 200 - || color == 0xFF3C00 // 255, 60, 0 - || color == 0x3CFF00) // 60, 255, 0 + if (color == 0xFF00FF // 255, 0, 255 + || color == 0x00FFFF // 0, 0, 255 + || color == 0xFF00AF // 255, 0, 175 + || color == 0xFFAF00 // 255, 175, 0 + || color == 0xB9FF00 // 185, 255, 0 + || color == 0x00FFC8 // 0, 255, 200 + || color == 0xFF3C00 // 255, 60, 0 + || color == 0x3CFF00) // 60, 255, 0 m_RGBColorsFixed[i].ulARGB |= 0x010101; } } @@ -1470,7 +1473,7 @@ void CVehicleSA::RecalculateHandling() pInt->dwHandlingFlags = uiHandlingFlags; pInt->m_fMass = m_pHandlingData->GetInterface()->fMass; - pInt->m_fTurnMass = m_pHandlingData->GetInterface()->fTurnMass; // * pGame->GetHandlingManager()->GetTurnMassMultiplier(); + pInt->m_fTurnMass = m_pHandlingData->GetInterface()->fTurnMass; // * pGame->GetHandlingManager()->GetTurnMassMultiplier(); pInt->m_vecCenterOfMass = m_pHandlingData->GetInterface()->vecCenterOfMass; pInt->m_fBuoyancyConstant = m_pHandlingData->GetInterface()->fUnknown2; /*if (m_pHandlingData->GetInterface()->fDragCoeff >= pGame->GetHandlingManager()->GetBasicDragCoeff()) @@ -1602,7 +1605,7 @@ bool CVehicleSA::SpawnFlyingComponent(const eCarNodes& nodeIndex, const eCarComp if (nodeIndex == eCarNodes::NONE) return false; - DWORD nodesOffset = OFFSET_CAutomobile_Nodes; + DWORD nodesOffset = OFFSET_CAutomobile_Nodes; RwFrame* defaultBikeChassisFrame = nullptr; // CBike, CBmx, CBoat and CTrain don't inherit CAutomobile so let's do it manually! @@ -1818,7 +1821,7 @@ void* CVehicleSA::GetPrivateSuspensionLines() return nullptr; CBaseModelInfoSAInterface* pInterface = pModelInfo->GetInterface(); - CColDataSA* pColData = (pInterface && pInterface->pColModel) ? pInterface->pColModel->m_data : nullptr; + CColDataSA* pColData = (pInterface && pInterface->pColModel) ? pInterface->pColModel->m_data : nullptr; if (pModelInfo->IsMonsterTruck()) { // Monster truck suspension data is 0x90 BYTES rather than 0x80 (some extra stuff I guess) @@ -2057,7 +2060,7 @@ namespace // clang-format on } } -} // namespace +} // namespace SVehicleFrame* CVehicleSA::GetVehicleComponent(const SString& vehicleComponent) { @@ -2287,7 +2290,7 @@ bool CVehicleSA::SetComponentVisible(const SString& vehicleComponent, bool bRequ { // Make all atomics invisible for (uint i = 0; i < atomicList.size(); i++) - atomicList[i]->flags &= ~0x05; // Mimic what GTA seems to do - Not sure what the bottom bit is for + atomicList[i]->flags &= ~0x05; // Mimic what GTA seems to do - Not sure what the bottom bit is for } return true; } diff --git a/Client/game_sa/CVehicleSA.h b/Client/game_sa/CVehicleSA.h index 19f179cc857..46e7617e3fb 100644 --- a/Client/game_sa/CVehicleSA.h +++ b/Client/game_sa/CVehicleSA.h @@ -30,43 +30,43 @@ class CTrainSAInterface; struct CColModelSAInterface; struct RwTexture; -#define SIZEOF_CHELI 2584 +#define SIZEOF_CHELI 2584 // Suspension line sizes for different vehicle types -#define MAX_SUSPENSION_LINES 6 -#define SUSPENSION_SIZE_STANDARD 0x20 // Standard wheel: 32 bytes -#define SUSPENSION_SIZE_BIKE 0x80 // Bike: 128 bytes (2 wheels with extra data) -#define SUSPENSION_SIZE_MONSTER_TRUCK 0x90 // Monster truck: 144 bytes - -#define FUNC_CCarCtrlCreateCarForScript 0x431f80 -#define FUNC_CVehicle_AddVehicleUpgrade 0x6E3290 -#define FUNC_CVehicle_RemoveVehicleUpgrade 0x6DF930 -#define FUNC_CVehicle_GetBaseVehicleType 0x411D50 -#define FUNC_CVehicle_IsUpsideDown 0x6D1D90 -#define FUNC_CVehicle_SetEngineOn 0x41BDD0 -#define FUNC_CVehicle_IsPassenger 0x6D1BD0 -#define FUNC_CTrain_FindPositionOnTrackFromCoors 0x6F6CC0 - -#define FUNC_CVehicle_QueryPickedUpEntityWithWinch 0x6d3cf0 -#define FUNC_CVehicle_PickUpEntityWithWinch 0x6d3cd0 -#define FUNC_CVehicle_ReleasePickedUpEntityWithWinch 0x6d3cb0 -#define FUNC_CVehicle_SetRopeHeightForHeli 0x6d3d30 - -#define FUNC_CVehicle__SetRemapTexDictionary 0x6D0BC0 -#define FUNC_CVehicle__GetRemapIndex 0x6D0B70 -#define FUNC_CVehicle__SetRemap 0x6D0C00 -#define FUNC_CVehicle_CustomCarPlate_TextureCreate 0x6D10E0 - -#define FUNC_CVehicle_SetWindowOpenFlag 0x6D3080 -#define FUNC_CVehicle_ClearWindowOpenFlag 0x6D30B0 +#define MAX_SUSPENSION_LINES 6 +#define SUSPENSION_SIZE_STANDARD 0x20 // Standard wheel: 32 bytes +#define SUSPENSION_SIZE_BIKE 0x80 // Bike: 128 bytes (2 wheels with extra data) +#define SUSPENSION_SIZE_MONSTER_TRUCK 0x90 // Monster truck: 144 bytes + +#define FUNC_CCarCtrlCreateCarForScript 0x431f80 +#define FUNC_CVehicle_AddVehicleUpgrade 0x6E3290 +#define FUNC_CVehicle_RemoveVehicleUpgrade 0x6DF930 +#define FUNC_CVehicle_GetBaseVehicleType 0x411D50 +#define FUNC_CVehicle_IsUpsideDown 0x6D1D90 +#define FUNC_CVehicle_SetEngineOn 0x41BDD0 +#define FUNC_CVehicle_IsPassenger 0x6D1BD0 +#define FUNC_CTrain_FindPositionOnTrackFromCoors 0x6F6CC0 + +#define FUNC_CVehicle_QueryPickedUpEntityWithWinch 0x6d3cf0 +#define FUNC_CVehicle_PickUpEntityWithWinch 0x6d3cd0 +#define FUNC_CVehicle_ReleasePickedUpEntityWithWinch 0x6d3cb0 +#define FUNC_CVehicle_SetRopeHeightForHeli 0x6d3d30 + +#define FUNC_CVehicle__SetRemapTexDictionary 0x6D0BC0 +#define FUNC_CVehicle__GetRemapIndex 0x6D0B70 +#define FUNC_CVehicle__SetRemap 0x6D0C00 +#define FUNC_CVehicle_CustomCarPlate_TextureCreate 0x6D10E0 + +#define FUNC_CVehicle_SetWindowOpenFlag 0x6D3080 +#define FUNC_CVehicle_ClearWindowOpenFlag 0x6D30B0 // from CBike -#define FUNC_Bike_PlaceOnRoadProperly 0x6BEEB0 -#define FUNC_Automobile_PlaceOnRoadProperly 0x6AF420 -#define FUNC_CBike_Fix 0x6B7050 +#define FUNC_Bike_PlaceOnRoadProperly 0x6BEEB0 +#define FUNC_Automobile_PlaceOnRoadProperly 0x6AF420 +#define FUNC_CBike_Fix 0x6B7050 // from CPlane -#define FUNC_CPlane__Fix 0x6CABB0 +#define FUNC_CPlane__Fix 0x6CABB0 // from CAutomobile #define FUNC_CAutomobile__Fix 0x6A3440 @@ -74,35 +74,35 @@ struct RwTexture; #define FUNC_CAutomobile__UpdateMovingCollision 0x6a1460 // from CHeli -#define FUNC_CHeli__Fix 0x6C4530 +#define FUNC_CHeli__Fix 0x6C4530 // from CQuadBike -#define FUNC_CQuadBike__Fix 0x6CE2B0 +#define FUNC_CQuadBike__Fix 0x6CE2B0 -#define VARS_CarCounts 0x969094 // 5 values for each vehicle type +#define VARS_CarCounts 0x969094 // 5 values for each vehicle type -#define MAX_PASSENGERS 8 +#define MAX_PASSENGERS 8 -#define NUM_RAILTRACKS 4 -#define ARRAY_NumRailTrackNodes 0xC38014 // NUM_RAILTRACKS dwords -#define ARRAY_RailTrackNodePointers 0xC38024 // NUM_RAILTRACKS pointers to arrays of SRailNode +#define NUM_RAILTRACKS 4 +#define ARRAY_NumRailTrackNodes 0xC38014 // NUM_RAILTRACKS dwords +#define ARRAY_RailTrackNodePointers 0xC38024 // NUM_RAILTRACKS pointers to arrays of SRailNode -#define VAR_CVehicle_SpecialColModels 0xc1cc78 +#define VAR_CVehicle_SpecialColModels 0xc1cc78 #define FUNC_CAutomobile__GetDoorAngleOpenRatio 0x6A2270 #define FUNC_CTrain__GetDoorAngleOpenRatio 0x6F59C0 -#define HANDLING_NOS_Flag 0x00080000 -#define HANDLING_Hydraulics_Flag 0x00020000 +#define HANDLING_NOS_Flag 0x00080000 +#define HANDLING_Hydraulics_Flag 0x00020000 -#define VAR_CVehicle_Variation1 0x8A6458 -#define VAR_CVehicle_Variation2 0x8A6459 +#define VAR_CVehicle_Variation1 0x8A6458 +#define VAR_CVehicle_Variation2 0x8A6459 // for vehicle sun glare #define FUNC_CAutomobile_OnVehiclePreRender 0x6ABCFD #define FUNC_CVehicle_DoSunGlare 0x6DD6F0 -#define FUNC_CHeli_ProcessFlyingCarStuff 0x6C4E7D +#define FUNC_CHeli_ProcessFlyingCarStuff 0x6C4E7D #define FUNC_CPlane_ProcessFlyingCarStuff 0x6CB7D2 // CClumpModelInfo::GetFrameFromName @@ -113,91 +113,91 @@ struct RwTexture; // CBike::m_apModelNodes // CBoat::pBoatParts #define OFFSET_CAutomobile_Nodes 0x648 -#define OFFSET_CTrain_Nodes 0x668 -#define OFFSET_CBike_Nodes 0x5A0 -#define OFFSET_CBoat_Nodes 0x5B0 +#define OFFSET_CTrain_Nodes 0x668 +#define OFFSET_CBike_Nodes 0x5A0 +#define OFFSET_CBoat_Nodes 0x5B0 struct SRailNodeSA { - short sX; // x coordinate times 8 - short sY; // y coordinate times 8 - short sZ; // z coordinate times 8 - WORD sRailDistance; // on-rail distance times 3.33333334 + short sX; // x coordinate times 8 + short sY; // y coordinate times 8 + short sZ; // z coordinate times 8 + WORD sRailDistance; // on-rail distance times 3.33333334 WORD padding; }; struct CVehicleFlags { - unsigned char bIsLawEnforcer : 1; // Is this guy chasing the player at the moment - unsigned char bIsAmbulanceOnDuty : 1; // Ambulance trying to get to an accident - unsigned char bIsFireTruckOnDuty : 1; // Firetruck trying to get to a fire - unsigned char bIsLocked : 1; // Is this guy locked by the script (cannot be removed) - unsigned char bEngineOn : 1; // For sound purposes. Parked cars have their engines switched off (so do destroyed cars) - unsigned char bIsHandbrakeOn : 1; // How's the handbrake doing ? - unsigned char bLightsOn : 1; // Are the lights switched on ? - unsigned char bFreebies : 1; // Any freebies left in this vehicle ? - - unsigned char bIsVan : 1; // Is this vehicle a van (doors at back of vehicle) - unsigned char bIsBus : 1; // Is this vehicle a bus - unsigned char bIsBig : 1; // Is this vehicle a bus - unsigned char bLowVehicle : 1; // Need this for sporty type cars to use low getting-in/out anims - unsigned char bComedyControls : 1; // Will make the car hard to control (hopefully in a funny way) - unsigned char bWarnedPeds : 1; // Has scan and warn peds of danger been processed? - unsigned char bCraneMessageDone : 1; // A crane message has been printed for this car allready + unsigned char bIsLawEnforcer : 1; // Is this guy chasing the player at the moment + unsigned char bIsAmbulanceOnDuty : 1; // Ambulance trying to get to an accident + unsigned char bIsFireTruckOnDuty : 1; // Firetruck trying to get to a fire + unsigned char bIsLocked : 1; // Is this guy locked by the script (cannot be removed) + unsigned char bEngineOn : 1; // For sound purposes. Parked cars have their engines switched off (so do destroyed cars) + unsigned char bIsHandbrakeOn : 1; // How's the handbrake doing ? + unsigned char bLightsOn : 1; // Are the lights switched on ? + unsigned char bFreebies : 1; // Any freebies left in this vehicle ? + + unsigned char bIsVan : 1; // Is this vehicle a van (doors at back of vehicle) + unsigned char bIsBus : 1; // Is this vehicle a bus + unsigned char bIsBig : 1; // Is this vehicle a bus + unsigned char bLowVehicle : 1; // Need this for sporty type cars to use low getting-in/out anims + unsigned char bComedyControls : 1; // Will make the car hard to control (hopefully in a funny way) + unsigned char bWarnedPeds : 1; // Has scan and warn peds of danger been processed? + unsigned char bCraneMessageDone : 1; // A crane message has been printed for this car allready // unsigned char bExtendedRange: 1; // This vehicle needs to be a bit further away to get deleted - unsigned char bTakeLessDamage : 1; // This vehicle is stronger (takes about 1/4 of damage) - - unsigned char bIsDamaged : 1; // This vehicle has been damaged and is displaying all its components - unsigned char bHasBeenOwnedByPlayer : 1; // To work out whether stealing it is a crime - unsigned char bFadeOut : 1; // Fade vehicle out - unsigned char bIsBeingCarJacked : 1; // Fade vehicle out - unsigned char bCreateRoadBlockPeds : 1; // If this vehicle gets close enough we will create peds (coppers or gang members) round it - unsigned char bCanBeDamaged : 1; // Set to FALSE during cut scenes to avoid explosions + unsigned char bTakeLessDamage : 1; // This vehicle is stronger (takes about 1/4 of damage) + + unsigned char bIsDamaged : 1; // This vehicle has been damaged and is displaying all its components + unsigned char bHasBeenOwnedByPlayer : 1; // To work out whether stealing it is a crime + unsigned char bFadeOut : 1; // Fade vehicle out + unsigned char bIsBeingCarJacked : 1; // Fade vehicle out + unsigned char bCreateRoadBlockPeds : 1; // If this vehicle gets close enough we will create peds (coppers or gang members) round it + unsigned char bCanBeDamaged : 1; // Set to FALSE during cut scenes to avoid explosions // unsigned char bUsingSpecialColModel : 1; // Is player vehicle using special collision model, stored in player strucure - unsigned char bOccupantsHaveBeenGenerated : 1; // Is true if the occupants have already been generated. (Shouldn't happen again) - unsigned char bGunSwitchedOff : 1; // Level designers can use this to switch off guns on boats + unsigned char bOccupantsHaveBeenGenerated : 1; // Is true if the occupants have already been generated. (Shouldn't happen again) + unsigned char bGunSwitchedOff : 1; // Level designers can use this to switch off guns on boats - unsigned char bVehicleColProcessed : 1; // Has ProcessEntityCollision been processed for this car? - unsigned char bIsCarParkVehicle : 1; // Car has been created using the special CAR_PARK script command - unsigned char bHasAlreadyBeenRecorded : 1; // Used for replays + unsigned char bVehicleColProcessed : 1; // Has ProcessEntityCollision been processed for this car? + unsigned char bIsCarParkVehicle : 1; // Car has been created using the special CAR_PARK script command + unsigned char bHasAlreadyBeenRecorded : 1; // Used for replays unsigned char bPartOfConvoy : 1; - unsigned char bHeliMinimumTilt : 1; // This heli should have almost no tilt really - unsigned char bAudioChangingGear : 1; // sounds like vehicle is changing gear - unsigned char bIsDrowning : 1; // is vehicle occupants taking damage in water (i.e. vehicle is dead in water) - unsigned char bTyresDontBurst : 1; // If this is set the tyres are invincible + unsigned char bHeliMinimumTilt : 1; // This heli should have almost no tilt really + unsigned char bAudioChangingGear : 1; // sounds like vehicle is changing gear + unsigned char bIsDrowning : 1; // is vehicle occupants taking damage in water (i.e. vehicle is dead in water) + unsigned char bTyresDontBurst : 1; // If this is set the tyres are invincible - unsigned char bCreatedAsPoliceVehicle : 1; // True if this guy was created as a police vehicle (enforcer, policecar, miamivice car etc) - unsigned char bRestingOnPhysical : 1; // Dont go static cause car is sitting on a physical object that might get removed + unsigned char bCreatedAsPoliceVehicle : 1; // True if this guy was created as a police vehicle (enforcer, policecar, miamivice car etc) + unsigned char bRestingOnPhysical : 1; // Dont go static cause car is sitting on a physical object that might get removed unsigned char bParking : 1; unsigned char bCanPark : 1; - unsigned char bFireGun : 1; // Does the ai of this vehicle want to fire it's gun? - unsigned char bDriverLastFrame : 1; // Was there a driver present last frame ? - unsigned char bNeverUseSmallerRemovalRange : 1; // Some vehicles (like planes) we don't want to remove just behind the camera. - unsigned char bIsRCVehicle : 1; // Is this a remote controlled (small) vehicle. True whether the player or AI controls it. - - unsigned char bAlwaysSkidMarks : 1; // This vehicle leaves skidmarks regardless of the wheels' states. - unsigned char bEngineBroken : 1; // Engine doesn't work. Player can get in but the vehicle won't drive - unsigned char bVehicleCanBeTargetted : 1; // The ped driving this vehicle can be targetted, (for Torenos plane mission) - unsigned char bPartOfAttackWave : 1; // This car is used in an attack during a gang war - unsigned char bWinchCanPickMeUp : 1; // This car cannot be picked up by any ropes. - unsigned char bImpounded : 1; // Has this vehicle been in a police impounding garage - unsigned char bVehicleCanBeTargettedByHS : 1; // Heat seeking missiles will not target this vehicle. - unsigned char bSirenOrAlarm : 1; // Set to TRUE if siren or alarm active, else FALSE + unsigned char bFireGun : 1; // Does the ai of this vehicle want to fire it's gun? + unsigned char bDriverLastFrame : 1; // Was there a driver present last frame ? + unsigned char bNeverUseSmallerRemovalRange : 1; // Some vehicles (like planes) we don't want to remove just behind the camera. + unsigned char bIsRCVehicle : 1; // Is this a remote controlled (small) vehicle. True whether the player or AI controls it. + + unsigned char bAlwaysSkidMarks : 1; // This vehicle leaves skidmarks regardless of the wheels' states. + unsigned char bEngineBroken : 1; // Engine doesn't work. Player can get in but the vehicle won't drive + unsigned char bVehicleCanBeTargetted : 1; // The ped driving this vehicle can be targetted, (for Torenos plane mission) + unsigned char bPartOfAttackWave : 1; // This car is used in an attack during a gang war + unsigned char bWinchCanPickMeUp : 1; // This car cannot be picked up by any ropes. + unsigned char bImpounded : 1; // Has this vehicle been in a police impounding garage + unsigned char bVehicleCanBeTargettedByHS : 1; // Heat seeking missiles will not target this vehicle. + unsigned char bSirenOrAlarm : 1; // Set to TRUE if siren or alarm active, else FALSE unsigned char bHasGangLeaningOn : 1; - unsigned char bGangMembersForRoadBlock : 1; // Will generate gang members if NumPedsForRoadBlock > 0 - unsigned char bDoesProvideCover : 1; // If this is false this particular vehicle can not be used to take cover behind. - unsigned char bMadDriver : 1; // This vehicle is driving like a lunatic - unsigned char bUpgradedStereo : 1; // This vehicle has an upgraded stereo - unsigned char bConsideredByPlayer : 1; // This vehicle is considered by the player to enter - unsigned char bPetrolTankIsWeakPoint : 1; // If false shootong the petrol tank will NOT Blow up the car - unsigned char bDisableParticles : 1; // Disable particles from this car. Used in garage. - - unsigned char bHasBeenResprayed : 1; // Has been resprayed in a respray garage. Reset after it has been checked. - unsigned char bUseCarCheats : 1; // If this is true will set the car cheat stuff up in ProcessControl() - unsigned char bDontSetColourWhenRemapping : 1; // If the texture gets remapped we don't want to change the colour with it. - unsigned char bUsedForReplay : 1; // This car is controlled by replay and should be removed when replay is done. + unsigned char bGangMembersForRoadBlock : 1; // Will generate gang members if NumPedsForRoadBlock > 0 + unsigned char bDoesProvideCover : 1; // If this is false this particular vehicle can not be used to take cover behind. + unsigned char bMadDriver : 1; // This vehicle is driving like a lunatic + unsigned char bUpgradedStereo : 1; // This vehicle has an upgraded stereo + unsigned char bConsideredByPlayer : 1; // This vehicle is considered by the player to enter + unsigned char bPetrolTankIsWeakPoint : 1; // If false shootong the petrol tank will NOT Blow up the car + unsigned char bDisableParticles : 1; // Disable particles from this car. Used in garage. + + unsigned char bHasBeenResprayed : 1; // Has been resprayed in a respray garage. Reset after it has been checked. + unsigned char bUseCarCheats : 1; // If this is true will set the car cheat stuff up in ProcessControl() + unsigned char bDontSetColourWhenRemapping : 1; // If the texture gets remapped we don't want to change the colour with it. + unsigned char bUsedForReplay : 1; // This car is controlled by replay and should be removed when replay is done. }; struct CTransmissionGear @@ -228,7 +228,7 @@ class CAutoPilot BYTE pad[56]; }; -#define MAX_UPGRADES_ATTACHED 15 // perhaps? +#define MAX_UPGRADES_ATTACHED 15 // perhaps? class CVehicleSAInterface : public CPhysicalSAInterface { @@ -292,32 +292,30 @@ class CVehicleSAInterface : public CPhysicalSAInterface ((void(__thiscall*)(CVehicleSAInterface*, RwFrame*, std::uint32_t))0x6D2700)(this, component, state); } - bool IsPassenger(CPedSAInterface* ped) const { - return ((bool(__thiscall*)(CVehicleSAInterface const*, CPedSAInterface*))0x6D1BD0)(this, ped); - } + bool IsPassenger(CPedSAInterface* ped) const { return ((bool(__thiscall*)(CVehicleSAInterface const*, CPedSAInterface*))0x6D1BD0)(this, ped); } - CAEVehicleAudioEntitySAInterface m_VehicleAudioEntity; // 312 + CAEVehicleAudioEntitySAInterface m_VehicleAudioEntity; // 312 - tHandlingDataSA* pHandlingData; // +900 - tFlyingHandlingDataSA* pFlyingHandlingData; // +904 - DWORD dwHandlingFlags; // +908 + tHandlingDataSA* pHandlingData; // +900 + tFlyingHandlingDataSA* pFlyingHandlingData; // +904 + DWORD dwHandlingFlags; // +908 int pad52321[21]; - DWORD dwUnknown1201; // +996 - DWORD dwUnknown1202; // +1000 - unsigned int hFlagsLocal; // +1004 + DWORD dwUnknown1201; // +996 + DWORD dwUnknown1202; // +1000 + unsigned int hFlagsLocal; // +1004 - CAutoPilot AutoPilot; // +1008 - CVehicleFlags m_nVehicleFlags; // +1064? - unsigned int m_TimeOfCreation; // GetTimeInMilliseconds when this vehicle was created. + CAutoPilot AutoPilot; // +1008 + CVehicleFlags m_nVehicleFlags; // +1064? + unsigned int m_TimeOfCreation; // GetTimeInMilliseconds when this vehicle was created. unsigned char m_colour1, m_colour2, m_colour3, m_colour4; char m_comp1, m_comp2; - short m_upgrades[MAX_UPGRADES_ATTACHED]; // 1082 - float m_fWheelScale; // 1112 + short m_upgrades[MAX_UPGRADES_ATTACHED]; // 1082 + float m_fWheelScale; // 1112 - unsigned short CarAlarmState; // 1116 - unsigned short ForcedRandomSeed; // if this is non-zero the random wander gets deterministic + unsigned short CarAlarmState; // 1116 + unsigned short ForcedRandomSeed; // if this is non-zero the random wander gets deterministic CPedSAInterface* pDriver; CPedSAInterface* pPassengers[MAX_PASSENGERS]; @@ -327,38 +325,38 @@ class CVehicleSAInterface : public CPhysicalSAInterface unsigned char m_nGettingOutFlags; unsigned char m_nMaxPassengers; unsigned char m_windowsOpenFlags; - char m_nNitroBoosts; // +1162 + char m_nNitroBoosts; // +1162 // float m_fNitroTimer; // +2212 - unsigned char m_nSpecialColModel; - CEntity* pEntityWeAreOnForVisibilityCheck; - CFireSAInterface* m_pFire; + unsigned char m_nSpecialColModel; + CEntity* pEntityWeAreOnForVisibilityCheck; + CFireSAInterface* m_pFire; - float m_fSteerAngle; // +1172 - float m_f2ndSteerAngle; // used for steering 2nd set of wheels or elevators etc.. - float m_fGasPedal; // 0...1 // +1180 - float m_fBrakePedal; // 0...1 + float m_fSteerAngle; // +1172 + float m_f2ndSteerAngle; // used for steering 2nd set of wheels or elevators etc.. + float m_fGasPedal; // 0...1 // +1180 + float m_fBrakePedal; // 0...1 - unsigned char VehicleCreatedBy; // Contains information on whether this vehicle can be deleted - // or not. Probably only need this or IsLocked. + unsigned char VehicleCreatedBy; // Contains information on whether this vehicle can be deleted + // or not. Probably only need this or IsLocked. short ExtendedRemovalRange; - unsigned char BombOnBoard : 3; // 0 = None. 1 = Timed. 2 = On ignition, 3 = remotely set ? 4 = Timed Bomb has been activated. 5 = On ignition has - // been activated. - unsigned char OverrideLights : 2; // uses enum NO_CAR_LIGHT_OVERRIDE, FORCE_CAR_LIGHTS_OFF, FORCE_CAR_LIGHTS_ON - unsigned char WinchType : 2; // Does this vehicle use a winch? - unsigned char m_GunsCycleIndex : 2; // Cycle through alternate gun hardpoints on planes/helis - unsigned char m_OrdnanceCycleIndex : 2; // Cycle through alternate ordnance hardpoints on planes/helis + unsigned char BombOnBoard : 3; // 0 = None. 1 = Timed. 2 = On ignition, 3 = remotely set ? 4 = Timed Bomb has been activated. 5 = On ignition has + // been activated. + unsigned char OverrideLights : 2; // uses enum NO_CAR_LIGHT_OVERRIDE, FORCE_CAR_LIGHTS_OFF, FORCE_CAR_LIGHTS_ON + unsigned char WinchType : 2; // Does this vehicle use a winch? + unsigned char m_GunsCycleIndex : 2; // Cycle through alternate gun hardpoints on planes/helis + unsigned char m_OrdnanceCycleIndex : 2; // Cycle through alternate ordnance hardpoints on planes/helis - unsigned char nUsedForCover; // Has n number of cops hiding/attempting to hid behind it - unsigned char AmmoInClip; // Used to make the guns on boat do a reload. + unsigned char nUsedForCover; // Has n number of cops hiding/attempting to hid behind it + unsigned char AmmoInClip; // Used to make the guns on boat do a reload. unsigned char PacMansCollected; unsigned char PedsPositionForRoadBlock; unsigned char NumPedsForRoadBlock; // 1200 - float nBodyDirtLevel; // Dirt level of vehicle body texture: 0.0f=fully clean, 15.0f=maximum dirt visible, it may be altered at any time while - // vehicle's cycle of lige + float nBodyDirtLevel; // Dirt level of vehicle body texture: 0.0f=fully clean, 15.0f=maximum dirt visible, it may be altered at any time while + // vehicle's cycle of lige // values used by transmission unsigned char m_nCurrentGear; @@ -368,24 +366,24 @@ class CVehicleSAInterface : public CPhysicalSAInterface float m_fWheelSpinForAudio; // 1216 - float m_nHealth; // 1000.0f = full health. 0 -> explode + float m_nHealth; // 1000.0f = full health. 0 -> explode - CVehicleSAInterface* m_towingVehicle; // 1220 - CVehicleSAInterface* m_trailerVehicle; // 1224 + CVehicleSAInterface* m_towingVehicle; // 1220 + CVehicleSAInterface* m_trailerVehicle; // 1224 - CPedSAInterface* m_bombPlanter; // 1228 - uint32_t m_deleteAfterTime; // 1232 - uint32_t m_lastGunFireTime; // 1236 - uint32_t m_lastBlowUpTime; // 1240 - uint16_t m_policeChaseLeaveCarTimer; // 1244 - uint16_t m_delayedExplosionTimer; // 1246 - void* m_responsibleForDetonation; // 1248 - float m_frontGroundZ; // 1252 - float m_rearGroundZ; // 1256 + CPedSAInterface* m_bombPlanter; // 1228 + uint32_t m_deleteAfterTime; // 1232 + uint32_t m_lastGunFireTime; // 1236 + uint32_t m_lastBlowUpTime; // 1240 + uint16_t m_policeChaseLeaveCarTimer; // 1244 + uint16_t m_delayedExplosionTimer; // 1246 + void* m_responsibleForDetonation; // 1248 + float m_frontGroundZ; // 1252 + float m_rearGroundZ; // 1256 /*** BEGIN SECTION that was added by us ***/ - uint8_t _padding1262[8]; // 1260 - CVehicle* m_pVehicle; // 1268 + uint8_t _padding1262[8]; // 1260 + CVehicle* m_pVehicle; // 1268 /*** END SECTION that was added by us ***/ // 1272 @@ -413,7 +411,7 @@ class CVehicleSAInterface : public CPhysicalSAInterface // 1424 VehicleClass m_vehicleClass; - uint32_t m_vehicleSubClass; + uint32_t m_vehicleSubClass; int16_t m_peviousRemapTxd; int16_t m_remapTxd; @@ -584,7 +582,7 @@ class CVehicleSA : public virtual CVehicle, public virtual CPhysicalSA bool GetVehicleRotorState() const noexcept override { return m_rotorState; } float GetPlaneRotorSpeed(); - unsigned long GetExplodeTime() { return *reinterpret_cast(reinterpret_cast(m_pInterface) + 1240); }; + unsigned long GetExplodeTime() { return *reinterpret_cast(reinterpret_cast(m_pInterface) + 1240); }; char GetNitroCount() { return GetVehicleInterface()->m_nNitroBoosts; } float GetNitroLevel(); @@ -646,9 +644,9 @@ class CVehicleSA : public virtual CVehicle, public virtual CPhysicalSA SharedUtil::SColor GetHeadLightColor() { return m_HeadLightColor; } void SetHeadLightColor(const SharedUtil::SColor color) { m_HeadLightColor = color; } - bool SpawnFlyingComponent(const eCarNodes& nodeIndex, const eCarComponentCollisionTypes& collisionType, std::int32_t removalTime = -1); - void SetWheelVisibility(eWheelPosition wheel, bool bVisible); - CVector GetWheelPosition(eWheelPosition wheel); + bool SpawnFlyingComponent(const eCarNodes& nodeIndex, const eCarComponentCollisionTypes& collisionType, std::int32_t removalTime = -1); + void SetWheelVisibility(eWheelPosition wheel, bool bVisible); + CVector GetWheelPosition(eWheelPosition wheel); bool IsHeliSearchLightVisible(); void SetHeliSearchLightVisible(bool bVisible); diff --git a/Client/game_sa/CVisibilityPluginsSA.h b/Client/game_sa/CVisibilityPluginsSA.h index 5daf372ea77..a7cbf2d8c54 100644 --- a/Client/game_sa/CVisibilityPluginsSA.h +++ b/Client/game_sa/CVisibilityPluginsSA.h @@ -13,8 +13,8 @@ #include -#define FUNC_CVisiblityPlugins_SetClumpAlpha 0x732B00 -#define FUNC_CVisibilityPlugins_GetAtomicId 0x732370 +#define FUNC_CVisiblityPlugins_SetClumpAlpha 0x732B00 +#define FUNC_CVisibilityPlugins_GetAtomicId 0x732370 class CVisibilityPluginsSA : public CVisibilityPlugins { diff --git a/Client/game_sa/CWantedSA.h b/Client/game_sa/CWantedSA.h index 2e8b623d058..bcc888b9467 100644 --- a/Client/game_sa/CWantedSA.h +++ b/Client/game_sa/CWantedSA.h @@ -17,17 +17,17 @@ class CPedSAInterface; -#define FUNC_SetMaximumWantedLevel 0x561E70 -#define FUNC_SetWantedLevel 0x562470 -#define FUNC_SetWantedLevelNoDrop 0x562570 +#define FUNC_SetMaximumWantedLevel 0x561E70 +#define FUNC_SetWantedLevel 0x562470 +#define FUNC_SetWantedLevelNoDrop 0x562570 -#define MAX_CRIMES_QD 16 -#define MAX_COPS_PURSUIT 10 +#define MAX_CRIMES_QD 16 +#define MAX_COPS_PURSUIT 10 class CCrimeBeingQd { public: - DWORD CrimeType; // was eCrimeType + DWORD CrimeType; // was eCrimeType long CrimeID; DWORD TimeOfQing; CVector Coors; @@ -43,18 +43,18 @@ class CWantedSAInterface DWORD m_LastTimeWantedDecreased; DWORD m_LastTimeWantedLevelChanged; DWORD m_TimeOfParole; - float m_fMultiplier; // New crimes have their wanted level contribution multiplied by this + float m_fMultiplier; // New crimes have their wanted level contribution multiplied by this BYTE m_nCopsInPursuit; BYTE m_nMaxCopsInPursuit; BYTE m_nMaxCopCarsInPursuit; BYTE m_nCopsBeatingSuspect; - WORD m_nChanceOnRoadBlock; // /127 for each new roadsegment - BYTE m_PoliceBackOff : 1; // If this is set the police will leave player alone (for cut-scenes) - BYTE m_PoliceBackOffGarage : 1; // If this is set the police will leave player alone (for garages) - BYTE m_EverybodyBackOff : 1; // If this is set then everybody (including police) will leave the player alone (for cut-scenes) - BYTE m_swatRequired : 1; // These three booleans are needed so that the - BYTE m_fbiRequired : 1; // streaming required vehicle stuff can be overrided + WORD m_nChanceOnRoadBlock; // /127 for each new roadsegment + BYTE m_PoliceBackOff : 1; // If this is set the police will leave player alone (for cut-scenes) + BYTE m_PoliceBackOffGarage : 1; // If this is set the police will leave player alone (for garages) + BYTE m_EverybodyBackOff : 1; // If this is set then everybody (including police) will leave the player alone (for cut-scenes) + BYTE m_swatRequired : 1; // These three booleans are needed so that the + BYTE m_fbiRequired : 1; // streaming required vehicle stuff can be overrided BYTE m_armyRequired : 1; DWORD current_chase_time; DWORD current_chase_time_counter; @@ -65,9 +65,9 @@ class CWantedSAInterface CCrimeBeingQd CrimesBeingQd[MAX_CRIMES_QD]; - CPedSAInterface* m_pCopsInPursuit[MAX_COPS_PURSUIT]; // was CCopPed + CPedSAInterface* m_pCopsInPursuit[MAX_COPS_PURSUIT]; // was CCopPed - DWORD m_PoliceScannerAudioEntity; // was CAEPoliceScannerAudioEntity + DWORD m_PoliceScannerAudioEntity; // was CAEPoliceScannerAudioEntity }; class CWantedSA : public CWanted diff --git a/Client/game_sa/CWaterManagerSA.cpp b/Client/game_sa/CWaterManagerSA.cpp index 8cb1e441d75..433e05fde87 100644 --- a/Client/game_sa/CWaterManagerSA.cpp +++ b/Client/game_sa/CWaterManagerSA.cpp @@ -23,9 +23,9 @@ extern int ms_iNumNonDefaultAndNonZeroVertices; using namespace std; -#define POLYENTRY_TYPE(entry) ( (entry)->m_wValue >> 14 ) -#define POLYENTRY_ID(entry) ( (entry)->m_wValue & 0x3FFF ) -#define MAKE_POLYENTRY(type, id) (WORD)( ((type) << 14) | (id) ) +#define POLYENTRY_TYPE(entry) ((entry)->m_wValue >> 14) +#define POLYENTRY_ID(entry) ((entry)->m_wValue & 0x3FFF) +#define MAKE_POLYENTRY(type, id) (WORD)(((type) << 14) | (id)) // These are code references in SA to the various data pools. We relocate these pools // to our own buffers to have more space, and thus have to update all references. @@ -361,21 +361,21 @@ void CWaterManagerSA::RelocatePools() } } - // - // Fix outside world water blocks disappearing when using long draw distances - // +// +// Fix outside world water blocks disappearing when using long draw distances +// - // GTA default is 70 blocks. We increase this to 512 which is 2^9 - #define OUTSIDE_WORLD_BLOCKS_BITS 9 +// GTA default is 70 blocks. We increase this to 512 which is 2^9 +#define OUTSIDE_WORLD_BLOCKS_BITS 9 static short ms_BlocksToBeRenderedOutsideWorldX[1 << OUTSIDE_WORLD_BLOCKS_BITS]; static short ms_BlocksToBeRenderedOutsideWorldY[1 << OUTSIDE_WORLD_BLOCKS_BITS]; - BYTE part1[] = {0xC1, 0xF8, OUTSIDE_WORLD_BLOCKS_BITS + 1, // sar eax,13 = 2^(10-1) = 512 - 0x7A, 0x19}; // jp part2 Effectively jump always + BYTE part1[] = {0xC1, 0xF8, OUTSIDE_WORLD_BLOCKS_BITS + 1, // sar eax,13 = 2^(10-1) = 512 + 0x7A, 0x19}; // jp part2 Effectively jump always - BYTE part2[] = {0x72, 0xFB, // jc exit Jump if at limit - 0xA1, 0xEC, 0x15, 0xC2, 0x00, // mov eax,NumBlocks Restore eax - 0x73, 0xDE}; // jnc dothing Effectively jump always + BYTE part2[] = {0x72, 0xFB, // jc exit Jump if at limit + 0xA1, 0xEC, 0x15, 0xC2, 0x00, // mov eax,NumBlocks Restore eax + 0x73, 0xDE}; // jnc dothing Effectively jump always MemCpy((void*)0x6E6CE9, part1, sizeof(part1)); MemCpy((void*)0x6E6D07, part2, sizeof(part2)); @@ -396,7 +396,7 @@ void CWaterManagerSA::RelocatePools() // pool; however in MTA, we can dynamically delete water polys, // creating gaps. These hooks make SA skip empty pool slots. -DWORD dwHook6E9E23continue = 0x6E9E29; +DWORD dwHook6E9E23continue = 0x6E9E29; static void __declspec(naked) Hook6E9E23() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -419,8 +419,8 @@ static void __declspec(naked) Hook6E9E23() // clang-format on } -DWORD dwHook6EFCD7continue = 0x6EFCDD; -DWORD dwHook6EFCD7skip = 0x6EFE5E; +DWORD dwHook6EFCD7continue = 0x6EFCDD; +DWORD dwHook6EFCD7skip = 0x6EFE5E; static void __declspec(naked) Hook6EFCD7() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -443,7 +443,7 @@ static void __declspec(naked) Hook6EFCD7() // clang-format on } -DWORD dwHook6EFBD8continue = 0x6EFBDE; +DWORD dwHook6EFBD8continue = 0x6EFBDE; static void __declspec(naked) Hook6EFBD8() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -659,7 +659,7 @@ CWaterPoly* CWaterManagerSA::CreateQuad(const CVector& vecBL, const CVector& vec pInterface->m_wVertexIDs[0] = pV1->GetID(); pInterface->m_wVertexIDs[1] = pV2->GetID(); pInterface->m_wVertexIDs[2] = pV3->GetID(); - pInterface->m_wVertexIDs[3] = pV4->GetID(); // This is ok + pInterface->m_wVertexIDs[3] = pV4->GetID(); // This is ok pInterface->m_wFlags = WATER_VISIBLE; if (bShallow) pInterface->m_wFlags |= WATER_SHALLOW; diff --git a/Client/game_sa/CWaterManagerSA.h b/Client/game_sa/CWaterManagerSA.h index cf249e19e67..db189607c24 100644 --- a/Client/game_sa/CWaterManagerSA.h +++ b/Client/game_sa/CWaterManagerSA.h @@ -15,17 +15,18 @@ #include #include "CWaterSA.h" -#define DEFAULT_WATER_LEVEL 0.0f -#define DEFAULT_WAVE_LEVEL 0.0f - -#define FUNC_ReadWaterConfiguration 0x6EAE80 // () -#define FUNC_CreateWaterVertex 0x6E5A40 // (word x, word y, float z, float unknown, float height, word flow) -#define FUNC_CreateWaterQuad 0x6E7EF0 // (word x1, word y1, float z1, float unknown1, float height1, word flow1, word x2, ..., word x3, ..., word x4, ..., word flags) -#define FUNC_CreateWaterTriangle 0x6E7D40 // (word x1, word y1, float z1, float unknown1, float height1, word flow1, word x2, ..., word x3, ..., word flags) -#define FUNC_BuildWaterIndex 0x6E7B30 // () -#define FUNC_AddWaterPolyToZone 0x6E5750 // (zoneColumn, zoneRow, polyID, polyType) -#define FUNC_GetWaterLevel 0x6EB690 -#define FUNC_TestLineAgainstWater 0x6E61B0 +#define DEFAULT_WATER_LEVEL 0.0f +#define DEFAULT_WAVE_LEVEL 0.0f + +#define FUNC_ReadWaterConfiguration 0x6EAE80 // () +#define FUNC_CreateWaterVertex 0x6E5A40 // (word x, word y, float z, float unknown, float height, word flow) +#define FUNC_CreateWaterQuad \ + 0x6E7EF0 // (word x1, word y1, float z1, float unknown1, float height1, word flow1, word x2, ..., word x3, ..., word x4, ..., word flags) +#define FUNC_CreateWaterTriangle 0x6E7D40 // (word x1, word y1, float z1, float unknown1, float height1, word flow1, word x2, ..., word x3, ..., word flags) +#define FUNC_BuildWaterIndex 0x6E7B30 // () +#define FUNC_AddWaterPolyToZone 0x6E5750 // (zoneColumn, zoneRow, polyID, polyType) +#define FUNC_GetWaterLevel 0x6EB690 +#define FUNC_TestLineAgainstWater 0x6E61B0 typedef void(__cdecl* ReadWaterConfiguration_t)(); typedef WORD(__cdecl* CreateWaterVertex_t)(long lX, long lY, float fZ, float fUnknown, float fHeight, WORD wFlow); @@ -33,27 +34,27 @@ typedef void(__cdecl* BuildWaterIndex_t)(); typedef bool(__cdecl* TestLineAgainstWater_t)(float fStartX, float fStartY, float fStartZ, float fEndX, float fEndY, float fEndZ, CVector* pvecCollision); typedef bool(__cdecl* GetWaterLevel_t)(float fX, float fY, float fZ, float* pfLevel, bool bCheckWaves, CVector* pvecUnknown); -#define VAR_NumWaterVertices 0xC2288C -#define VAR_NumWaterQuads 0xC22888 -#define VAR_NumWaterTriangles 0xC22884 -#define VAR_NumWaterZonePolys 0xC215F0 -#define VAR_WaveLevel 0xC812E8 - -#define NUM_DefWaterVertices 0x3FD // Sizes of pools reserved in gta_sa.exe -#define NUM_DefWaterQuads 0x12D -#define NUM_DefWaterTriangles 0x6 -#define NUM_DefWaterZonePolys 0x2BC -#define NUM_NewWaterVertices 0x600 // Sizes of replacement pools in MTA -#define NUM_NewWaterQuads 0x200 -#define NUM_NewWaterTriangles 0x20 -#define NUM_NewWaterZonePolys 0x400 -#define NUM_WaterZones (12 * 12) - -#define ARRAY_WaterVertices 0xC22910 -#define ARRAY_WaterQuads 0xC21C90 -#define ARRAY_WaterTriangles 0xC22854 -#define ARRAY_WaterZones 0xC21B70 -#define ARRAY_WaterZonePolys 0xC215F8 +#define VAR_NumWaterVertices 0xC2288C +#define VAR_NumWaterQuads 0xC22888 +#define VAR_NumWaterTriangles 0xC22884 +#define VAR_NumWaterZonePolys 0xC215F0 +#define VAR_WaveLevel 0xC812E8 + +#define NUM_DefWaterVertices 0x3FD // Sizes of pools reserved in gta_sa.exe +#define NUM_DefWaterQuads 0x12D +#define NUM_DefWaterTriangles 0x6 +#define NUM_DefWaterZonePolys 0x2BC +#define NUM_NewWaterVertices 0x600 // Sizes of replacement pools in MTA +#define NUM_NewWaterQuads 0x200 +#define NUM_NewWaterTriangles 0x20 +#define NUM_NewWaterZonePolys 0x400 +#define NUM_WaterZones (12 * 12) + +#define ARRAY_WaterVertices 0xC22910 +#define ARRAY_WaterQuads 0xC21C90 +#define ARRAY_WaterTriangles 0xC22854 +#define ARRAY_WaterZones 0xC21B70 +#define ARRAY_WaterZonePolys 0xC215F8 // ------------------------------- // SA interfaces diff --git a/Client/game_sa/CWeaponInfoSA.h b/Client/game_sa/CWeaponInfoSA.h index 29a28deb63a..d362132fbcd 100644 --- a/Client/game_sa/CWeaponInfoSA.h +++ b/Client/game_sa/CWeaponInfoSA.h @@ -17,8 +17,8 @@ class CEntitySAInterface; // Flame shot array for flamethrower flames and maybe molotovs -#define ARRAY_CFlameShotInfo 0xC89690 -#define MAX_FLAME_SHOT_INFOS 100 +#define ARRAY_CFlameShotInfo 0xC89690 +#define MAX_FLAME_SHOT_INFOS 100 #define FUNC_CWeaponInfo_GetWeaponReloadTime 0x743D70 class CFlameShotInfo @@ -36,18 +36,18 @@ class CFlameShotInfo }; static_assert(sizeof(CFlameShotInfo) == 0x2c, "Invalid size for CFlameShotInfo"); -class CWeaponInfoSAInterface // 112 byte long class +class CWeaponInfoSAInterface // 112 byte long class { public: - eFireType m_eFireType; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) + eFireType m_eFireType; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) - float m_fTargetRange; // max targeting range - float m_fWeaponRange; // absolute gun range / default melee attack range - int m_modelId; // modelinfo id - int m_modelId2; // second modelinfo id + float m_fTargetRange; // max targeting range + float m_fWeaponRange; // absolute gun range / default melee attack range + int m_modelId; // modelinfo id + int m_modelId2; // second modelinfo id eWeaponSlot m_nWeaponSlot; - int m_nFlags; // flags defining characteristics + int m_nFlags; // flags defining characteristics // instead of storing pointers directly to anims, use anim association groups // NOTE: this is used for stealth kill anims for melee weapons @@ -56,39 +56,39 @@ class CWeaponInfoSAInterface // 112 byte long class ////////////////////////////////// // Gun Data ///////////////////////////////// - short m_nAmmo; // ammo in one clip - short m_nDamage; // damage inflicted per hit - CVector m_vecFireOffset; // offset from weapon origin to projectile starting point + short m_nAmmo; // ammo in one clip + short m_nDamage; // damage inflicted per hit + CVector m_vecFireOffset; // offset from weapon origin to projectile starting point // skill settings - eWeaponSkill m_SkillLevel; // what's the skill level of this weapontype - int m_nReqStatLevel; // what stat level is required for this skill level - float m_fAccuracy; // modify accuracy of weapon - float m_fMoveSpeed; // how fast can move with weapon + eWeaponSkill m_SkillLevel; // what's the skill level of this weapontype + int m_nReqStatLevel; // what stat level is required for this skill level + float m_fAccuracy; // modify accuracy of weapon + float m_fMoveSpeed; // how fast can move with weapon // anim timings - float m_animLoopStart; // start of animation loop - float m_animLoopEnd; // end of animation loop - float m_animFireTime; // time in animation when weapon should be fired + float m_animLoopStart; // start of animation loop + float m_animLoopEnd; // end of animation loop + float m_animFireTime; // time in animation when weapon should be fired - float m_anim2LoopStart; // start of animation2 loop - float m_anim2LoopEnd; // end of animation2 loop - float m_anim2FireTime; // time in animation2 when weapon should be fired + float m_anim2LoopStart; // start of animation2 loop + float m_anim2LoopEnd; // end of animation2 loop + float m_anim2FireTime; // time in animation2 when weapon should be fired - float m_animBreakoutTime; // time after which player can break out of attack and run off + float m_animBreakoutTime; // time after which player can break out of attack and run off // projectile/area effect specific info - float m_fSpeed; // speed of projectile - float m_fRadius; // radius affected - float m_fLifeSpan; // time taken for shot to dissipate - float m_fSpread; // angle inside which shots are created + float m_fSpeed; // speed of projectile + float m_fRadius; // radius affected + float m_fLifeSpan; // time taken for shot to dissipate + float m_fSpread; // angle inside which shots are created - short m_nAimOffsetIndex; // index into array of aiming offsets + short m_nAimOffsetIndex; // index into array of aiming offsets ////////////////////////////////// // Melee Data ///////////////////////////////// - BYTE m_defaultCombo; // base combo for this melee weapon - BYTE m_nCombosAvailable; // how many further combos are available + BYTE m_defaultCombo; // base combo for this melee weapon + BYTE m_nCombosAvailable; // how many further combos are available int GetWeaponReloadTime() { return ((int(__thiscall*)(CWeaponInfoSAInterface*))FUNC_CWeaponInfo_GetWeaponReloadTime)(this); } }; @@ -106,10 +106,10 @@ class CWeaponInfoSA : public CWeaponInfo // DO NOT USE. void SetFlags(int iFlags) { m_pInterface->m_nFlags = iFlags; } // END - void SetFlag(DWORD flag) { m_pInterface->m_nFlags |= flag; } - void ClearFlag(DWORD flag) { m_pInterface->m_nFlags &= ~flag; } - bool IsFlagSet(DWORD flag) { return ((m_pInterface->m_nFlags & flag) > 0 ? true : false); } - int GetFlags() { return m_pInterface->m_nFlags; } + void SetFlag(DWORD flag) { m_pInterface->m_nFlags |= flag; } + void ClearFlag(DWORD flag) { m_pInterface->m_nFlags &= ~flag; } + bool IsFlagSet(DWORD flag) { return ((m_pInterface->m_nFlags & flag) > 0 ? true : false); } + int GetFlags() { return m_pInterface->m_nFlags; } eWeaponModel GetModel() { return (eWeaponModel)m_pInterface->m_modelId; } eWeaponModel GetModel2() { return (eWeaponModel)m_pInterface->m_modelId2; } diff --git a/Client/game_sa/CWeaponSA.h b/Client/game_sa/CWeaponSA.h index 9ef7124493a..5282981d411 100644 --- a/Client/game_sa/CWeaponSA.h +++ b/Client/game_sa/CWeaponSA.h @@ -23,9 +23,9 @@ class CWeaponSAInterface std::uint32_t m_ammoInClip{0}; std::uint32_t m_ammoTotal{0}; std::uint32_t m_timeToNextShootInMS{0}; - bool m_firstPersonEnabled{false}; // Unused - bool m_dontPlaceInHand{false}; // Used in case of goggles - FxSystem_c* m_fxSystem{nullptr}; // Fx system (flamethrower, spraycan, extinguisher) + bool m_firstPersonEnabled{false}; // Unused + bool m_dontPlaceInHand{false}; // Used in case of goggles + FxSystem_c* m_fxSystem{nullptr}; // Fx system (flamethrower, spraycan, extinguisher) void Shutdown() { ((void(__thiscall*)(CWeaponSAInterface*))0x73A380)(this); } void Initialize(eWeaponType weaponType, std::uint32_t ammo, CPedSAInterface* ped) diff --git a/Client/game_sa/CWeaponStatManagerSA.cpp b/Client/game_sa/CWeaponStatManagerSA.cpp index e976a61250f..d7f420be5cd 100644 --- a/Client/game_sa/CWeaponStatManagerSA.cpp +++ b/Client/game_sa/CWeaponStatManagerSA.cpp @@ -518,8 +518,8 @@ void CWeaponStatManagerSA::Init() OriginalNormalWeaponData[33].default_combo = 4; OriginalNormalWeaponData[33].combos_available = 1; // 34 - Sniper - OriginalNormalWeaponData[34].weapon_range = 300.0f; // Default is actually 100; - OriginalNormalWeaponData[34].target_range = 250.0f; // Default is actually 50; + OriginalNormalWeaponData[34].weapon_range = 300.0f; // Default is actually 100; + OriginalNormalWeaponData[34].target_range = 250.0f; // Default is actually 50; OriginalNormalWeaponData[34].accuracy = 1.0f; OriginalNormalWeaponData[34].damage = 125; OriginalNormalWeaponData[34].life_span = 0.0f; diff --git a/Client/game_sa/CWeaponStatManagerSA.h b/Client/game_sa/CWeaponStatManagerSA.h index 8446598e2b1..c1b6344f706 100644 --- a/Client/game_sa/CWeaponStatManagerSA.h +++ b/Client/game_sa/CWeaponStatManagerSA.h @@ -15,24 +15,24 @@ #include "CWeaponStatSA.h" // Straight out of CGameSA.h -#define CLASSSIZE_WeaponInfo 112 // ##SA## -#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE -#define NUM_WeaponInfosOtherSkill 11 -#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3*NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) +#define CLASSSIZE_WeaponInfo 112 // ##SA## +#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE +#define NUM_WeaponInfosOtherSkill 11 +#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3 * NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) #define WEAPON_STAT_MAX 112 struct sWeaponInfo { - eFireType fire_type; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) + eFireType fire_type; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) - float target_range; // max targeting range - float weapon_range; // absolute gun range / default melee attack range - int model; // modelinfo id - int model2; // second modelinfo id + float target_range; // max targeting range + float weapon_range; // absolute gun range / default melee attack range + int model; // modelinfo id + int model2; // second modelinfo id eWeaponSlot weapon_slot; - int flags; // flags defining characteristics + int flags; // flags defining characteristics // instead of storing pointers directly to anims, use anim association groups // NOTE: this is used for stealth kill anims for melee weapons @@ -41,39 +41,39 @@ struct sWeaponInfo ////////////////////////////////// // Gun Data ///////////////////////////////// - short maximum_clip_ammo; // ammo in one clip - short damage; // damage inflicted per hit - CVector fire_offset; // offset from weapon origin to projectile starting point + short maximum_clip_ammo; // ammo in one clip + short damage; // damage inflicted per hit + CVector fire_offset; // offset from weapon origin to projectile starting point // skill settings - eWeaponSkill skill_level; // what's the skill level of this weapontype - int required_skill_level; // what stat level is required for this skill level - float accuracy; // modify accuracy of weapon - float move_speed; // how fast can move with weapon + eWeaponSkill skill_level; // what's the skill level of this weapontype + int required_skill_level; // what stat level is required for this skill level + float accuracy; // modify accuracy of weapon + float move_speed; // how fast can move with weapon // anim timings - float anim_loop_start; // start of animation loop - float anim_loop_stop; // end of animation loop - float anim_loop_bullet_fire; // time in animation when weapon should be fired + float anim_loop_start; // start of animation loop + float anim_loop_stop; // end of animation loop + float anim_loop_bullet_fire; // time in animation when weapon should be fired - float anim2_loop_start; // start of animation2 loop - float anim2_loop_stop; // end of animation2 loop - float anim2_loop_bullet_fire; // time in animation2 when weapon should be fired + float anim2_loop_start; // start of animation2 loop + float anim2_loop_stop; // end of animation2 loop + float anim2_loop_bullet_fire; // time in animation2 when weapon should be fired - float anim_breakout_time; // time after which player can break out of attack and run off + float anim_breakout_time; // time after which player can break out of attack and run off // projectile/area effect specific info - float firing_speed; // speed of projectile - float radius; // radius affected - float life_span; // time taken for shot to dissipate - float spread; // angle inside which shots are created + float firing_speed; // speed of projectile + float radius; // radius affected + float life_span; // time taken for shot to dissipate + float spread; // angle inside which shots are created - short aim_offset; // index into array of aiming offsets + short aim_offset; // index into array of aiming offsets ////////////////////////////////// // Melee Data ///////////////////////////////// - BYTE default_combo; // base combo for this melee weapon - BYTE combos_available; // how many further combos are available + BYTE default_combo; // base combo for this melee weapon + BYTE combos_available; // how many further combos are available }; class CWeaponStatManagerSA : public CWeaponStatManager diff --git a/Client/game_sa/CWeaponStatSA.h b/Client/game_sa/CWeaponStatSA.h index d89aeff1fd3..960e6671c19 100644 --- a/Client/game_sa/CWeaponStatSA.h +++ b/Client/game_sa/CWeaponStatSA.h @@ -15,7 +15,7 @@ class CWeaponStatSA : public CWeaponStat { public: - CWeaponStatSA(){}; + CWeaponStatSA() {}; CWeaponStatSA(eWeaponType weaponType, eWeaponSkill skillLevel); CWeaponStatSA(CWeaponInfoSA* pWeaponInfo, eWeaponType weaponType, eWeaponSkill skillLevel); ~CWeaponStatSA(); diff --git a/Client/game_sa/CWeatherSA.cpp b/Client/game_sa/CWeatherSA.cpp index 7ebc51469f9..270a0d5be80 100644 --- a/Client/game_sa/CWeatherSA.cpp +++ b/Client/game_sa/CWeatherSA.cpp @@ -16,23 +16,23 @@ static float WEATHER_FAKE_ACCUMULATOR; unsigned char CWeatherSA::Get() { - return *(unsigned char*)0xC81318; // CWeather::ForcedWeatherType + return *(unsigned char*)0xC81318; // CWeather::ForcedWeatherType } void CWeatherSA::Set(unsigned char primary, unsigned char secondary) { - MemPutFast(0xC81320, primary); // CWeather::OldWeatherType - MemPutFast(0xC8131C, secondary); // CWeather::NewWeatherType + MemPutFast(0xC81320, primary); // CWeather::OldWeatherType + MemPutFast(0xC8131C, secondary); // CWeather::NewWeatherType } void CWeatherSA::Release() { - MemPutFast(0xC81318, 0xFF); // CWeather::ForcedWeatherType + MemPutFast(0xC81318, 0xFF); // CWeather::ForcedWeatherType } float CWeatherSA::GetAmountOfRain() { - return *(float*)0xC81324; // CWeather::Rain + return *(float*)0xC81324; // CWeather::Rain } void CWeatherSA::SetAmountOfRain(float fAmount) @@ -44,12 +44,12 @@ void CWeatherSA::SetAmountOfRain(float fAmount) MemSet((void*)0x72BC72, 0x90, 5); // Set the amount of rain - MemPutFast(0xC81324, fAmount); // CWeather::Rain + MemPutFast(0xC81324, fAmount); // CWeather::Rain } void CWeatherSA::ResetAmountOfRain() { - BYTE originalMov[5] = {0xA3, 0x24, 0x13, 0xC8, 0x00}; // 0x72BC72 + BYTE originalMov[5] = {0xA3, 0x24, 0x13, 0xC8, 0x00}; // 0x72BC72 MemCpy((LPVOID)0x72BC72, &originalMov, 5); static constexpr DWORD originalAddr = 0x00C81324; diff --git a/Client/game_sa/CWorldSA.cpp b/Client/game_sa/CWorldSA.cpp index f63df29ea57..b67adf8b702 100644 --- a/Client/game_sa/CWorldSA.cpp +++ b/Client/game_sa/CWorldSA.cpp @@ -265,7 +265,6 @@ void ConvertMatrixToEulerAngles(const CMatrix_Padded& matrixPadded, float& fX, f // clang-format on } - auto CWorldSA::ProcessLineAgainstMesh(CEntitySAInterface* targetEntity, CVector start, CVector end) -> SProcessLineOfSightMaterialInfoResult { assert(targetEntity); @@ -274,21 +273,22 @@ auto CWorldSA::ProcessLineAgainstMesh(CEntitySAInterface* targetEntity, CVector struct Context { - float minHitDistSq{}; //< [squared] hit distance from the line segment's origin - CVector originOS, endOS, dirOS; //< Line origin, end and dir [in object space] - CMatrix entMat, entInvMat; //< The hit entity's matrix, and it's inverse - RpTriangle* hitTri{}; //< The triangle hit - RpAtomic* hitAtomic{}; //< The atomic of the hit triangle's geometry - RpGeometry* hitGeo{}; //< The geometry of the hit triangle - CVector hitBary{}; //< Barycentric coordinates [on the hit triangle] of the hit - CVector hitPosOS{}; //< Hit position in object space - CEntitySAInterface* entity{}; //< The hit entity + float minHitDistSq{}; //< [squared] hit distance from the line segment's origin + CVector originOS, endOS, dirOS; //< Line origin, end and dir [in object space] + CMatrix entMat, entInvMat; //< The hit entity's matrix, and it's inverse + RpTriangle* hitTri{}; //< The triangle hit + RpAtomic* hitAtomic{}; //< The atomic of the hit triangle's geometry + RpGeometry* hitGeo{}; //< The geometry of the hit triangle + CVector hitBary{}; //< Barycentric coordinates [on the hit triangle] of the hit + CVector hitPosOS{}; //< Hit position in object space + CEntitySAInterface* entity{}; //< The hit entity } c = {}; c.entity = targetEntity; - if (!c.entity->m_pRwObject) { - return ret; // isValid will be false in this case + if (!c.entity->m_pRwObject) + { + return ret; // isValid will be false in this case } // Get matrix, and it's inverse @@ -305,50 +305,50 @@ auto CWorldSA::ProcessLineAgainstMesh(CEntitySAInterface* targetEntity, CVector c.originOS = c.entInvMat.TransformVector(start); c.endOS = c.entInvMat.TransformVector(end); c.dirOS = c.endOS - c.originOS; - c.minHitDistSq = c.dirOS.LengthSquared(); // By setting it to this value we avoid collisions that would be detected after the line segment + c.minHitDistSq = c.dirOS.LengthSquared(); // By setting it to this value we avoid collisions that would be detected after the line segment // [but are still ont the ray] // Do raycast against the DFF to get hit position material UV and name // This is very slow // Perhaps we could parallelize it somehow? [OpenMP?] const auto ProcessOneAtomic = [](RpAtomic* a, void* data) - { - Context* const c = static_cast(data); - RwFrame* const f = RpAtomicGetFrame(a); + { + Context* const c = static_cast(data); + RwFrame* const f = RpAtomicGetFrame(a); - const auto GetFrameCMatrix = [](RwFrame* f) - { - CMatrix out; - pGame->GetRenderWare()->RwMatrixToCMatrix(*RwFrameGetMatrix(f), out); - return out; - }; + const auto GetFrameCMatrix = [](RwFrame* f) + { + CMatrix out; + pGame->GetRenderWare()->RwMatrixToCMatrix(*RwFrameGetMatrix(f), out); + return out; + }; - // Atomic not visible - if (!a->renderCallback || !(a->object.object.flags & 0x04 /*rpATOMICRENDER*/)) - { - return true; - } + // Atomic not visible + if (!a->renderCallback || !(a->object.object.flags & 0x04 /*rpATOMICRENDER*/)) + { + return true; + } - // Sometimes atomics have no geometry [I don't think that should be possible, but okay] - RpGeometry* const geo = a->geometry; - if (!geo) - { - return true; - } + // Sometimes atomics have no geometry [I don't think that should be possible, but okay] + RpGeometry* const geo = a->geometry; + if (!geo) + { + return true; + } - // Calculate transformation by traversing the hierarchy from the bottom (this frame) -> top (root frame) - CMatrix localToObjTransform{}; - for (RwFrame* i = f; i && i != i->root; i = RwFrameGetParent(i)) - { - localToObjTransform = GetFrameCMatrix(i) * localToObjTransform; - } - const CMatrix objToLocalTransform = localToObjTransform.Inverse(); + // Calculate transformation by traversing the hierarchy from the bottom (this frame) -> top (root frame) + CMatrix localToObjTransform{}; + for (RwFrame* i = f; i && i != i->root; i = RwFrameGetParent(i)) + { + localToObjTransform = GetFrameCMatrix(i) * localToObjTransform; + } + const CMatrix objToLocalTransform = localToObjTransform.Inverse(); - const auto ObjectToLocalSpace = [&](const CVector& in) { return objToLocalTransform.TransformVector(in); }; + const auto ObjectToLocalSpace = [&](const CVector& in) { return objToLocalTransform.TransformVector(in); }; - // Transform from object space, into local (the frame's) space - const CVector localOrigin = ObjectToLocalSpace(c->originOS); - const CVector localEnd = ObjectToLocalSpace(c->endOS); + // Transform from object space, into local (the frame's) space + const CVector localOrigin = ObjectToLocalSpace(c->originOS); + const CVector localEnd = ObjectToLocalSpace(c->endOS); #if 0 if (!CCollisionSA::TestLineSphere( @@ -358,42 +358,42 @@ auto CWorldSA::ProcessLineAgainstMesh(CEntitySAInterface* targetEntity, CVector return true; // Line segment doesn't touch bsp } #endif - const CVector localDir = localEnd - localOrigin; + const CVector localDir = localEnd - localOrigin; - const CVector* const verts = reinterpret_cast(geo->morph_target->verts); // It's fine, trust me bro - for (auto i = geo->triangles_size; i-- > 0;) - { - RpTriangle* const tri = &geo->triangles[i]; + const CVector* const verts = reinterpret_cast(geo->morph_target->verts); // It's fine, trust me bro + for (auto i = geo->triangles_size; i-- > 0;) + { + RpTriangle* const tri = &geo->triangles[i]; - // Process the line against the triangle - CVector hitBary, hitPos; - if (!localOrigin.IntersectsSegmentTriangle(localDir, verts[tri->verts[0]], verts[tri->verts[1]], verts[tri->verts[2]], &hitPos, &hitBary)) - { - continue; // No intersection at all - } + // Process the line against the triangle + CVector hitBary, hitPos; + if (!localOrigin.IntersectsSegmentTriangle(localDir, verts[tri->verts[0]], verts[tri->verts[1]], verts[tri->verts[2]], &hitPos, &hitBary)) + { + continue; // No intersection at all + } - // Intersection, check if it's closer than the previous one - const float hitDistSq = (hitPos - localOrigin).LengthSquared(); - if (c->minHitDistSq > hitDistSq) - { - c->minHitDistSq = hitDistSq; - c->hitGeo = geo; - c->hitAtomic = a; - c->hitTri = tri; - c->hitBary = hitBary; - c->hitPosOS = localToObjTransform.TransformVector(hitPos); // Transform back into object space - } + // Intersection, check if it's closer than the previous one + const float hitDistSq = (hitPos - localOrigin).LengthSquared(); + if (c->minHitDistSq > hitDistSq) + { + c->minHitDistSq = hitDistSq; + c->hitGeo = geo; + c->hitAtomic = a; + c->hitTri = tri; + c->hitBary = hitBary; + c->hitPosOS = localToObjTransform.TransformVector(hitPos); // Transform back into object space } + } - return true; - }; + return true; + }; if (c.entity->m_pRwObject->object.type == 2 /*rpCLUMP*/) { RpClumpForAllAtomics(c.entity->m_pRwObject, ProcessOneAtomic, &c); } else - { // Object is a single atomic, so process directly + { // Object is a single atomic, so process directly ProcessOneAtomic(reinterpret_cast(c.entity->m_pRwObject), &c); } @@ -432,8 +432,8 @@ auto CWorldSA::ProcessLineAgainstMesh(CEntitySAInterface* targetEntity, CVector bool CWorldSA::ProcessLineOfSight(const CVector* vecStart, const CVector* vecEnd, CColPoint** colCollision, CEntity** CollisionEntity, const SLineOfSightFlags flags, SLineOfSightBuildingResult* pBuildingResult, SProcessLineOfSightMaterialInfoResult* outMatInfo) { - DWORD dwPadding[100]; // stops the function missbehaving and overwriting the return address - dwPadding[0] = 0; // prevent the warning and eventual compiler optimizations from removing it + DWORD dwPadding[100]; // stops the function missbehaving and overwriting the return address + dwPadding[0] = 0; // prevent the warning and eventual compiler optimizations from removing it CColPointSA* pColPointSA = new CColPointSA(); CColPointSAInterface* pColPointSAInterface = pColPointSA->GetInterface(); @@ -551,14 +551,17 @@ bool CWorldSA::ProcessLineOfSight(const CVector* vecStart, const CVector* vecEnd return bReturn; } -CEntity* CWorldSA::TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, bool checkPeds, bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) +CEntity* CWorldSA::TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, + bool checkPeds, bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) { - auto entity = ((CEntitySAInterface*(__cdecl*)(CVector, float, CEntitySAInterface*, bool, bool, bool, bool, bool, bool))FUNC_CWorld_TestSphereAgainstWorld)(sphereCenter, radius, ignoredEntity ? ignoredEntity->GetInterface() : nullptr, checkBuildings, checkVehicles, checkPeds, checkObjects, checkDummies, cameraIgnore); + auto entity = ((CEntitySAInterface * (__cdecl*)(CVector, float, CEntitySAInterface*, bool, bool, bool, bool, bool, bool)) + FUNC_CWorld_TestSphereAgainstWorld)(sphereCenter, radius, ignoredEntity ? ignoredEntity->GetInterface() : nullptr, checkBuildings, + checkVehicles, checkPeds, checkObjects, checkDummies, cameraIgnore); if (!entity) return nullptr; - + result.collisionDetected = true; - result.modelID = entity->m_nModelIndex; + result.modelID = entity->m_nModelIndex; if (entity->matrix) { result.entityPosition = entity->matrix->vPos; @@ -715,27 +718,27 @@ void CWorldSA::SetOcclusionsEnabled(bool bEnabled) { if (!bEnabled) { - MemPut(FUNC_COcclusion_ProcessBeforeRendering, 0xC3); // retn + MemPut(FUNC_COcclusion_ProcessBeforeRendering, 0xC3); // retn MemPutFast(VAR_COcclusion_NumActiveOccluders, 0); - MemCpy((void*)CALL_CCullZones_FindTunnelAttributesForCoors, "\xB8\x80\x28\x00\x00", 5); // mov eax, 0x2880 + MemCpy((void*)CALL_CCullZones_FindTunnelAttributesForCoors, "\xB8\x80\x28\x00\x00", 5); // mov eax, 0x2880 } else { - MemPut(FUNC_COcclusion_ProcessBeforeRendering, 0x51); // Standard value - MemCpy((void*)CALL_CCullZones_FindTunnelAttributesForCoors, "\xE8\xDE\x82\x1D\x00", 5); // call 0x72D9F0 + MemPut(FUNC_COcclusion_ProcessBeforeRendering, 0x51); // Standard value + MemCpy((void*)CALL_CCullZones_FindTunnelAttributesForCoors, "\xE8\xDE\x82\x1D\x00", 5); // call 0x72D9F0 } } bool CWorldSA::GetOcclusionsEnabled() { - if (*(BYTE*)FUNC_COcclusion_ProcessBeforeRendering == 0x51) // Is standard value ? + if (*(BYTE*)FUNC_COcclusion_ProcessBeforeRendering == 0x51) // Is standard value ? return true; return false; } void CWorldSA::FindWorldPositionForRailTrackPosition(float fRailTrackPosition, int iTrackId, CVector* pOutVecPosition) { - DWORD dwFunc = FUNC_CWorld_FindPositionForTrackPosition; // __cdecl + DWORD dwFunc = FUNC_CWorld_FindPositionForTrackPosition; // __cdecl // clang-format off __asm @@ -770,7 +773,7 @@ int CWorldSA::FindClosestRailTrackNode(const CVector& vecPosition, uchar& ucOutT SRailNodeSA& railNode = aTrackNodes[ucTrackId][i]; float fDistance = sqrtf(powf(vecPosition.fZ - railNode.sZ * 0.125f, 2) + powf(vecPosition.fY - railNode.sY * 0.125f, 2) + - powf(vecPosition.fX - railNode.sX * 0.125f, 2)); + powf(vecPosition.fX - railNode.sX * 0.125f, 2)); if (fDistance < fMinDistance) { fMinDistance = fDistance; @@ -934,4 +937,4 @@ namespace 0x10, 0x10, 0x00, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x04, 0x10, 0x10, 0x00, 0x0a, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x01, 0x10, 0x10, 0x00, 0x12, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x01, 0x90, 0x01, 0x00, 0x22, 0x00, 0x00}; static_assert(sizeof(CSurfaceType) == sizeof(aOriginalSurfaceInfo), "invalid size of aOriginalSurfaceInfo"); -} // namespace +} // namespace diff --git a/Client/game_sa/CWorldSA.h b/Client/game_sa/CWorldSA.h index 684cd311afc..6f6d6befd08 100644 --- a/Client/game_sa/CWorldSA.h +++ b/Client/game_sa/CWorldSA.h @@ -13,31 +13,31 @@ #include -#define FUNC_Add 0x563220 -#define FUNC_Remove 0x563280 -#define FUNC_ProcessLineOfSight 0x56BA00 -#define FUNC_FindGroundZFor3DCoord 0x5696C0 -#define FUNC_IsLineOfSightClear 0x56A490 -#define FUNC_HasCollisionBeenLoaded 0x410CE0 -#define FUNC_RemoveBuildingsNotInArea 0x4094B0 -#define FUNC_RemoveReferencesToDeletedObject 0x565510 -#define FUNC_COcclusion_ProcessBeforeRendering 0x7201C0 -#define VAR_COcclusion_NumActiveOccluders 0xC73CC0 -#define CALL_CCullZones_FindTunnelAttributesForCoors 0x55570D -#define FUNC_CWorld_FindPositionForTrackPosition 0x6F59E0 -#define FUNC_CWorld_TestSphereAgainstWorld 0x569E20 +#define FUNC_Add 0x563220 +#define FUNC_Remove 0x563280 +#define FUNC_ProcessLineOfSight 0x56BA00 +#define FUNC_FindGroundZFor3DCoord 0x5696C0 +#define FUNC_IsLineOfSightClear 0x56A490 +#define FUNC_HasCollisionBeenLoaded 0x410CE0 +#define FUNC_RemoveBuildingsNotInArea 0x4094B0 +#define FUNC_RemoveReferencesToDeletedObject 0x565510 +#define FUNC_COcclusion_ProcessBeforeRendering 0x7201C0 +#define VAR_COcclusion_NumActiveOccluders 0xC73CC0 +#define CALL_CCullZones_FindTunnelAttributesForCoors 0x55570D +#define FUNC_CWorld_FindPositionForTrackPosition 0x6F59E0 +#define FUNC_CWorld_TestSphereAgainstWorld 0x569E20 -#define VAR_IgnoredEntity 0xB7CD68 -#define VAR_currArea 0xB72914 -#define ARRAY_StreamSectors 0xB7D0B8 -#define NUM_StreamSectorRows 120 -#define NUM_StreamSectorCols 120 -#define ARRAY_StreamRepeatSectors 0xB992B8 -#define NUM_StreamRepeatSectorRows 16 -#define NUM_StreamRepeatSectorCols 16 -#define VAR_fJetpackMaxHeight 0x8703D8 -#define VTBL_CBUILDING 0x8585C8 -#define VAR_CWorld_bIncludeCarTires 0xB7CD70 +#define VAR_IgnoredEntity 0xB7CD68 +#define VAR_currArea 0xB72914 +#define ARRAY_StreamSectors 0xB7D0B8 +#define NUM_StreamSectorRows 120 +#define NUM_StreamSectorCols 120 +#define ARRAY_StreamRepeatSectors 0xB992B8 +#define NUM_StreamRepeatSectorRows 16 +#define NUM_StreamRepeatSectorCols 16 +#define VAR_fJetpackMaxHeight 0x8703D8 +#define VTBL_CBUILDING 0x8585C8 +#define VAR_CWorld_bIncludeCarTires 0xB7CD70 class CWorldSA : public CWorld { @@ -75,9 +75,10 @@ class CWorldSA : public CWorld void ResetAllSurfaceInfo() override; bool ResetSurfaceInfo(short sSurfaceID) override; - CEntity* TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, bool checkPeds, bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) override; + CEntity* TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, bool checkPeds, + bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) override; private: - float m_fAircraftMaxHeight; - CSurfaceType* m_pSurfaceInfo; + float m_fAircraftMaxHeight; + CSurfaceType* m_pSurfaceInfo; }; diff --git a/Client/game_sa/HeapTrace.cpp b/Client/game_sa/HeapTrace.cpp index b7513725be6..8b9ce5bc4f0 100644 --- a/Client/game_sa/HeapTrace.cpp +++ b/Client/game_sa/HeapTrace.cpp @@ -13,7 +13,7 @@ #include "HeapTrace.h" #ifdef DETECT_LEAKS -#include + #include using namespace std; struct ALLOC_INFO diff --git a/Client/game_sa/HookSystem.h b/Client/game_sa/HookSystem.h index 01d39be2c09..5dfdc3aac79 100644 --- a/Client/game_sa/HookSystem.h +++ b/Client/game_sa/HookSystem.h @@ -11,32 +11,35 @@ #pragma once -#define MAX_JUMPCODE_SIZE 20 +#define MAX_JUMPCODE_SIZE 20 #include "gamesa_init.h" #include -#pragma warning(disable : 4102) // unreferenced label +#pragma warning(disable : 4102) // unreferenced label // This macro adds an unreferenced label to your '__declspec(naked)' hook functions, to // point to the value of __LOCAL_SIZE, which will be examined by an external tool after // compilation, and it must be zero. -// +// // The Microsoft Visual C++ compiler (MSVC) expects you, the developer, to allocate space for // local variables on the stack frame in custom prolog code. In the MSVC implementation of the // C++17 language standard, the compiler started to use local space for certain statements, // for which we will never support any sort of local space, in naked hook functions. // https://learn.microsoft.com/en-us/cpp/cpp/considerations-for-writing-prolog-epilog-code // https://developercommunity.visualstudio.com/t/stack-access-broken-in-naked-function/549628 -// +// // IMPORTANT: We can't use static_assert because __LOCAL_SIZE is not a compile-time constant. // If you're going to change this macro, then copy your changes to the copy in multiplayer_sa. -#define MTA_VERIFY_HOOK_LOCAL_SIZE \ -{ \ - __asm { push eax }; \ - __asm { _localSize: mov eax, __LOCAL_SIZE }; \ - __asm { pop eax }; \ -} +#define MTA_VERIFY_HOOK_LOCAL_SIZE \ + { \ + __asm { push eax } \ + ; \ + __asm { _localSize: mov eax, __LOCAL_SIZE } \ + ; \ + __asm { pop eax } \ + ; \ + } template void* FunctionPointerToVoidP(T func) @@ -70,8 +73,7 @@ bool HookInstall(DWORD dwInstallAddress, T dwHookHandler, int iJmpCodeSize = 5) } // Auto detect requirement of US/EU hook installation -#define EZHookInstall(type) \ - HookInstall(HOOKPOS_##type, (DWORD)HOOK_##type, HOOKSIZE_##type); +#define EZHookInstall(type) HookInstall(HOOKPOS_##type, (DWORD)HOOK_##type, HOOKSIZE_##type); // Structure for holding hook info struct SHookInfo @@ -85,7 +87,7 @@ struct SHookInfo uint uiSize; }; -#define MAKE_HOOK_INFO(type) SHookInfo ( HOOKPOS_##type, HOOK_##type, HOOKSIZE_##type ) +#define MAKE_HOOK_INFO(type) SHookInfo(HOOKPOS_##type, HOOK_##type, HOOKSIZE_##type) // Structure for holding poke info struct SPokeInfo diff --git a/Client/game_sa/MemSA.h b/Client/game_sa/MemSA.h index 9e540c1a3ed..134d9590b10 100644 --- a/Client/game_sa/MemSA.h +++ b/Client/game_sa/MemSA.h @@ -15,17 +15,17 @@ namespace MemSA { size_t msize(const void* p) { - using gta_msize = size_t (__cdecl*)(const void*); + using gta_msize = size_t(__cdecl*)(const void*); return ((gta_msize)0x828C4A)(p); }; void* malloc(size_t count) { - using gta_malloc = void* (__cdecl*)(size_t a1); + using gta_malloc = void*(__cdecl*)(size_t a1); return ((gta_malloc)0x824257)(count); }; - template + template T* malloc_struct(size_t count) { return static_cast(MemSA::malloc(sizeof(T) * count)); @@ -33,7 +33,7 @@ namespace MemSA void free(void* p) { - using gta_free = void (__cdecl*)(void* p); + using gta_free = void(__cdecl*)(void* p); return ((gta_free)0x82413F)(p); }; } diff --git a/Client/game_sa/StdInc.h b/Client/game_sa/StdInc.h index ca886bdb1c3..bf0db98479d 100644 --- a/Client/game_sa/StdInc.h +++ b/Client/game_sa/StdInc.h @@ -3,11 +3,11 @@ // illegal instruction size // The instruction did not have a form with the specified size. The smallest legal size was used. -#pragma warning (disable:4409) +#pragma warning(disable : 4409) // 'class1' : inherits 'class2::member' via dominance // Two or more members have the same name. The one in class2 is inherited because it is a base class for the other classes that contained this member. -#pragma warning (disable:4250) +#pragma warning(disable : 4250) #include diff --git a/Client/game_sa/TaskAttackSA.h b/Client/game_sa/TaskAttackSA.h index 8c9ea026cd4..9e6293e2f56 100644 --- a/Client/game_sa/TaskAttackSA.h +++ b/Client/game_sa/TaskAttackSA.h @@ -17,34 +17,34 @@ class CWeaponInfo; -#define FUNC_CTaskSimpleGangDriveBy__Constructor 0x6217d0 -#define FUNC_CTaskSimpleUseGun__Constructor 0x61de60 -#define FUNC_CTaskSimpleUseGun_ControlGun 0x61e040 -#define FUNC_CTaskSimpleUseGun_ControlGunMove 0x61e0c0 -#define FUNC_CTaskSimpleUseGun_Reset 0x624dc0 -#define FUNC_CTaskSimpleFight__Constructor 0x61c470 -#define FUNC_CTaskSimpleUseGun_SetPedPosition 0x624ED0 -#define FUNC_CTaskSimpleUseGun_FireGun 0x61EB10 -#define FUNC_CTaskSimpleUseGun_GetTaskType 0x61DF20 -#define FUNC_CTaskSimpleUseGun_MakeAbortable 0x624E30 -#define FUNC_CTaskSimpleUseGun_ProcessPed 0x62A380 -#define FUNC_CTaskSimpleUseGun_AbortIK 0x61DFA0 -#define FUNC_CTaskSimpleUseGun_AimGun 0x61ED10 -#define FUNC_CTaskSimpleUseGun_ClearAnim 0x61E190 -#define FUNC_CTaskSimpleUseGun_GetCurrentCommand 0x4ABE30 -#define FUNC_CTaskSimpleUseGun_GetDoneFiring 0x61C220 -#define FUNC_CTaskSimpleUseGun_GetIsFinished 0x61C240 -#define FUNC_CTaskSimpleUseGun_IsLineOfSightBlocked 0x61C250 -#define FUNC_CTaskSimpleUseGun_GetIsFiring 0x509950 -#define FUNC_CTaskSimpleUseGun_GetIsReloading 0x609340 -#define FUNC_CTaskSimpleUseGun_GetSkipAim 0x588840 -#define FUNC_CTaskSimpleUseGun_PlayerPassiveControlGun 0x61E0A0 -#define FUNC_CTaskSimpleUseGun_RemoveStanceAnims 0x61E8E0 -#define FUNC_CTaskSimpleUseGun_RequirePistolWhip 0x61E200 -#define FUNC_CTaskSimpleUseGun_SetBurstLength 0x61C210 -#define FUNC_CTaskSimpleUseGun_SetMoveAnim 0x61E3F0 -#define FUNC_CTaskSimpleUseGun_StartAnim 0x624F30 -#define FUNC_CTaskSimpleUseGun_StartCountDown 0x61E160 +#define FUNC_CTaskSimpleGangDriveBy__Constructor 0x6217d0 +#define FUNC_CTaskSimpleUseGun__Constructor 0x61de60 +#define FUNC_CTaskSimpleUseGun_ControlGun 0x61e040 +#define FUNC_CTaskSimpleUseGun_ControlGunMove 0x61e0c0 +#define FUNC_CTaskSimpleUseGun_Reset 0x624dc0 +#define FUNC_CTaskSimpleFight__Constructor 0x61c470 +#define FUNC_CTaskSimpleUseGun_SetPedPosition 0x624ED0 +#define FUNC_CTaskSimpleUseGun_FireGun 0x61EB10 +#define FUNC_CTaskSimpleUseGun_GetTaskType 0x61DF20 +#define FUNC_CTaskSimpleUseGun_MakeAbortable 0x624E30 +#define FUNC_CTaskSimpleUseGun_ProcessPed 0x62A380 +#define FUNC_CTaskSimpleUseGun_AbortIK 0x61DFA0 +#define FUNC_CTaskSimpleUseGun_AimGun 0x61ED10 +#define FUNC_CTaskSimpleUseGun_ClearAnim 0x61E190 +#define FUNC_CTaskSimpleUseGun_GetCurrentCommand 0x4ABE30 +#define FUNC_CTaskSimpleUseGun_GetDoneFiring 0x61C220 +#define FUNC_CTaskSimpleUseGun_GetIsFinished 0x61C240 +#define FUNC_CTaskSimpleUseGun_IsLineOfSightBlocked 0x61C250 +#define FUNC_CTaskSimpleUseGun_GetIsFiring 0x509950 +#define FUNC_CTaskSimpleUseGun_GetIsReloading 0x609340 +#define FUNC_CTaskSimpleUseGun_GetSkipAim 0x588840 +#define FUNC_CTaskSimpleUseGun_PlayerPassiveControlGun 0x61E0A0 +#define FUNC_CTaskSimpleUseGun_RemoveStanceAnims 0x61E8E0 +#define FUNC_CTaskSimpleUseGun_RequirePistolWhip 0x61E200 +#define FUNC_CTaskSimpleUseGun_SetBurstLength 0x61C210 +#define FUNC_CTaskSimpleUseGun_SetMoveAnim 0x61E3F0 +#define FUNC_CTaskSimpleUseGun_StartAnim 0x624F30 +#define FUNC_CTaskSimpleUseGun_StartCountDown 0x61E160 // temporary class CAnimBlendAssociation; @@ -68,9 +68,9 @@ class CTaskSimpleGangDriveBySAInterface : public CTaskSimpleSAInterface bool m_bFromScriptCommand; char m_nNextCommand; - char m_nLastCommand; // active command + char m_nLastCommand; // active command char m_nBurstShots; - char m_nDrivebyStyle; // what type of driveby are we doing + char m_nDrivebyStyle; // what type of driveby are we doing char m_nFrequencyPercentage; char m_nFakeShootDirn; short m_nAttackTimer; @@ -78,7 +78,7 @@ class CTaskSimpleGangDriveBySAInterface : public CTaskSimpleSAInterface unsigned int m_nLOSCheckTime; bool m_nLOSBlocked; - float m_fAbortRange; // range from target at which this task will be aborted + float m_fAbortRange; // range from target at which this task will be aborted AnimationId m_nRequiredAnim; AssocGroupId m_nRequiredAnimGroup; @@ -92,23 +92,23 @@ class CTaskSimpleGangDriveBySAInterface : public CTaskSimpleSAInterface class CTaskSimpleGangDriveBySA : public virtual CTaskSimpleSA, public virtual CTaskSimpleGangDriveBy { public: - CTaskSimpleGangDriveBySA(){}; + CTaskSimpleGangDriveBySA() {}; CTaskSimpleGangDriveBySA(CEntity* pTargetEntity, const CVector* pVecTarget, float fAbortRange, char FrequencyPercentage, char nDrivebyStyle, bool bSeatRHS); }; class CTaskSimpleUseGunSAInterface : public CTaskSimpleSAInterface { public: - unsigned char m_bIsFinished; // 0x08 + unsigned char m_bIsFinished; // 0x08 unsigned char m_bIsInControl; unsigned char m_bMoveControl; unsigned char m_bFiredGun; - unsigned char m_bBlockedLOS; // 0x0C + unsigned char m_bBlockedLOS; // 0x0C unsigned char m_nFireGunThisFrame; - unsigned char m_bSkipAim; // 0x0E + unsigned char m_bSkipAim; // 0x0E char m_nNextCommand; - char m_nLastCommand; // active command (2 or 3) == is firing + char m_nLastCommand; // active command (2 or 3) == is firing CVector2D m_vecMoveCommand; CEntity* m_pTargetEntity; @@ -116,8 +116,8 @@ class CTaskSimpleUseGunSAInterface : public CTaskSimpleSAInterface CAnimBlendAssociation* m_pAnim; - CWeaponInfo* m_pWeaponInfo; // 0x30 - short m_nBurstLength; // 0x34 + CWeaponInfo* m_pWeaponInfo; // 0x30 + short m_nBurstLength; // 0x34 short m_nBurstShots; unsigned char m_nCountDownFrames; @@ -130,7 +130,7 @@ class CTaskSimpleUseGunSAInterface : public CTaskSimpleSAInterface class CTaskSimpleUseGunSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleUseGun { public: - CTaskSimpleUseGunSA(){}; + CTaskSimpleUseGunSA() {}; CTaskSimpleUseGunSA(CEntity* pTargetEntity, CVector vecTarget, char nCommand, short nBurstLength = 1, unsigned char bAimImmediate = false); bool ControlGun(CPed* pPed, CEntity* pTargetEntity, char nCommand); @@ -188,6 +188,6 @@ class CTaskSimpleFightSAInterface : public CTaskSimpleSAInterface class CTaskSimpleFightSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleFight { public: - CTaskSimpleFightSA(){}; + CTaskSimpleFightSA() {}; CTaskSimpleFightSA(CEntity* pTargetEntity, int nCommand, unsigned int nIdlePeriod = 10000); }; diff --git a/Client/game_sa/TaskBasicSA.cpp b/Client/game_sa/TaskBasicSA.cpp index 2ce818f01d3..fd7073bc614 100644 --- a/Client/game_sa/TaskBasicSA.cpp +++ b/Client/game_sa/TaskBasicSA.cpp @@ -13,7 +13,6 @@ #include "TaskBasicSA.h" #include "CPedSA.h" - CTaskSimpleRunNamedAnimSAInterface* CTaskSimpleRunNamedAnimSA::GetAnimationInterface() noexcept { return reinterpret_cast(this->GetInterface()); diff --git a/Client/game_sa/TaskBasicSA.h b/Client/game_sa/TaskBasicSA.h index 76654708759..a76660a6af8 100644 --- a/Client/game_sa/TaskBasicSA.h +++ b/Client/game_sa/TaskBasicSA.h @@ -19,17 +19,17 @@ class CVehicleSAInterface; class CObjectSAInterface; -#define FUNC_CTaskComplexUseMobilePhone__Constructor 0x6348A0 -#define FUNC_CTaskSimpleRunAnim__Constructor 0x61A900 -#define FUNC_CTaskSimpleRunNamedAnim__Constructor 0x61A990 -#define FUNC_CTaskComplexDie__Constructor 0x630040 -#define FUNC_CTaskSimpleStealthKill__Constructor 0x6225F0 -#define FUNC_CTaskSimpleDead__Constructor 0x630590 -#define FUNC_CTaskSimpleBeHit__Constructor 0x620780 -#define FUNC_CTaskComplexSunbathe__Constructor 0x631F80 -#define FUNC_CTASKSimplePlayerOnFoot__Constructor 0x685750 -#define FUNC_CTASKComplexFacial__Constructor 0x690D20 -#define VTBL_CTaskSimpleCarFallOut 0x86EFD0 +#define FUNC_CTaskComplexUseMobilePhone__Constructor 0x6348A0 +#define FUNC_CTaskSimpleRunAnim__Constructor 0x61A900 +#define FUNC_CTaskSimpleRunNamedAnim__Constructor 0x61A990 +#define FUNC_CTaskComplexDie__Constructor 0x630040 +#define FUNC_CTaskSimpleStealthKill__Constructor 0x6225F0 +#define FUNC_CTaskSimpleDead__Constructor 0x630590 +#define FUNC_CTaskSimpleBeHit__Constructor 0x620780 +#define FUNC_CTaskComplexSunbathe__Constructor 0x631F80 +#define FUNC_CTASKSimplePlayerOnFoot__Constructor 0x685750 +#define FUNC_CTASKComplexFacial__Constructor 0x690D20 +#define VTBL_CTaskSimpleCarFallOut 0x86EFD0 /////////////////////// // Use a mobile phone @@ -47,8 +47,8 @@ class CTaskComplexUseMobilePhoneSAInterface : public CTaskComplexSAInterface class CTaskComplexUseMobilePhoneSA : public virtual CTaskComplexSA, public virtual CTaskComplexUseMobilePhone { public: - CTaskComplexUseMobilePhoneSA(){}; - CTaskComplexUseMobilePhoneSA(const int iDuration); // Default is -1 + CTaskComplexUseMobilePhoneSA() {}; + CTaskComplexUseMobilePhoneSA(const int iDuration); // Default is -1 }; // temporary @@ -77,18 +77,18 @@ class CTaskSimpleAnimSAInterface : public CTaskSimpleSAInterface class CTaskSimpleAnimSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleAnim { public: - CTaskSimpleAnimSA(){}; + CTaskSimpleAnimSA() {}; }; class CTaskSimpleRunAnimSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleRunAnim { public: - CTaskSimpleRunAnimSA(){}; + CTaskSimpleRunAnimSA() {}; CTaskSimpleRunAnimSA(const AssocGroupId animGroup, const AnimationId animID, const float fBlendDelta, const int iTaskType, const char* pTaskName, const bool bHoldLastFrame = false); }; -#define ANIM_NAMELEN 24 +#define ANIM_NAMELEN 24 #define ANIMBLOCK_NAMELEN 16 class CTaskSimpleRunNamedAnimSAInterface : public CTaskSimpleAnimSAInterface @@ -109,7 +109,7 @@ class CTaskSimpleRunNamedAnimSAInterface : public CTaskSimpleAnimSAInterface class CTaskSimpleRunNamedAnimSA : public virtual CTaskSimpleAnimSA, public virtual CTaskSimpleRunNamedAnim { public: - CTaskSimpleRunNamedAnimSA(){}; + CTaskSimpleRunNamedAnimSA() {}; CTaskSimpleRunNamedAnimSA(const char* pAnimName, const char* pAnimGroupName, const int flags, const float fBlendDelta, const int iTime = -1, const bool bDontInterrupt = false, const bool bRunInSequence = false, const bool bOffsetPed = false, const bool bHoldLastFrame = false); @@ -129,7 +129,7 @@ class CTaskComplexDieSAInterface : public CTaskComplexSAInterface class CTaskComplexDieSA : public virtual CTaskComplexSA, public virtual CTaskComplexDie { public: - CTaskComplexDieSA(){}; + CTaskComplexDieSA() {}; CTaskComplexDieSA(const eWeaponType eMeansOfDeath /*=WEAPONTYPE_UNARMED*/, const AssocGroupId animGroup = 0 /*ANIM_STD_PED*/, const AnimationId anim = 0 /*ANIM_STD_KO_FRONT*/, const float fBlendDelta = 4.0f, const float fAnimSpeed = 0.0f, const bool bBeingKilledByStealth = false, const bool bFallingToDeath = false, const int iFallToDeathDir = 0, @@ -144,7 +144,7 @@ class CTaskSimpleStealthKillInterface : public CTaskSimpleSAInterface class CTaskSimpleStealthKillSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleStealthKill { public: - CTaskSimpleStealthKillSA(){}; + CTaskSimpleStealthKillSA() {}; CTaskSimpleStealthKillSA(bool bKiller, class CPed* pPed, const AssocGroupId animGroup); }; @@ -158,40 +158,40 @@ class CTaskSimpleDeadSAInterface : public CTaskSimpleSAInterface class CTaskSimpleDeadSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleDead { public: - CTaskSimpleDeadSA(){}; + CTaskSimpleDeadSA() {}; CTaskSimpleDeadSA(unsigned int uiDeathTimeMS, bool bUnk2); }; class CTaskSimpleBeHitSAInterface : public CTaskSimpleSAInterface { public: - CPed* pPedAttacker; // 0x08 - uchar a; // 0x0c - uchar b; // 0x0d - uchar c; // 0x0e - uchar d; // 0x0f - uint e; // 0x10 inited with 0x000000BF - uint f; // 0x14 inited with 0 - uint hitBodyPart; // 0x18 - uint weaponType; // 0x1C - uint hitBodySide; // 0x20 - uint g; // 0x24 inited with 0 + CPed* pPedAttacker; // 0x08 + uchar a; // 0x0c + uchar b; // 0x0d + uchar c; // 0x0e + uchar d; // 0x0f + uint e; // 0x10 inited with 0x000000BF + uint f; // 0x14 inited with 0 + uint hitBodyPart; // 0x18 + uint weaponType; // 0x1C + uint hitBodySide; // 0x20 + uint g; // 0x24 inited with 0 }; class CTaskSimpleBeHitSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleBeHit { public: - CTaskSimpleBeHitSA(){}; + CTaskSimpleBeHitSA() {}; CTaskSimpleBeHitSA(CPed* pPedAttacker, ePedPieceTypes hitBodyPart, int hitBodySide, int weaponId); }; class CTaskSimpleCarFallOutSAInterface : public CTaskSimpleSAInterface { public: - uint a; // 0x08 - uint b; // 0x0c - CVehicleSAInterface* pVehicle; // 0x10 - uint doorIndex; // 0x14 + uint a; // 0x08 + uint b; // 0x0c + CVehicleSAInterface* pVehicle; // 0x10 + uint doorIndex; // 0x14 }; class CAnimBlock; @@ -216,7 +216,7 @@ class CTaskComplexSunbatheSAInterface : public CTaskComplexSAInterface class CTaskComplexSunbatheSA : public virtual CTaskComplexSA, public virtual CTaskComplexSunbathe { public: - CTaskComplexSunbatheSA(){}; + CTaskComplexSunbatheSA() {}; CTaskComplexSunbatheSA(class CObject* pTowel, const bool bStartStanding); void SetEndTime(DWORD dwTime); diff --git a/Client/game_sa/TaskCarAccessoriesSA.h b/Client/game_sa/TaskCarAccessoriesSA.h index 00cd1c96727..a02748e3e1a 100644 --- a/Client/game_sa/TaskCarAccessoriesSA.h +++ b/Client/game_sa/TaskCarAccessoriesSA.h @@ -20,11 +20,11 @@ class CAnimBlendAssociation; typedef DWORD CTaskUtilityLineUpPedWithCar; -#define FUNC_CTaskSimpleCarSetPedInAsDriver__Constructor 0x6470E0 -#define FUNC_CTaskSimpleCarSetPedInAsPassenger__Constructor 0x646FE0 -#define FUNC_CTaskSimpleCarSetPedOut__Constructor 0x6478B0 +#define FUNC_CTaskSimpleCarSetPedInAsDriver__Constructor 0x6470E0 +#define FUNC_CTaskSimpleCarSetPedInAsPassenger__Constructor 0x646FE0 +#define FUNC_CTaskSimpleCarSetPedOut__Constructor 0x6478B0 -#define FUNC_CTaskSimpleCarSetPedOut__PositionPedOutOfCollision 0x6479B0 +#define FUNC_CTaskSimpleCarSetPedOut__PositionPedOutOfCollision 0x6479B0 // ############################################################################## // ## Name: CTaskSimpleCarSetPedInAsDriver @@ -47,7 +47,7 @@ class CTaskSimpleCarSetPedInAsDriverSAInterface : public CTaskSimpleSAInterface class CTaskSimpleCarSetPedInAsDriverSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleCarSetPedInAsDriver { public: - CTaskSimpleCarSetPedInAsDriverSA(){}; + CTaskSimpleCarSetPedInAsDriverSA() {}; CTaskSimpleCarSetPedInAsDriverSA(CVehicle* pTargetVehicle, CTaskUtilityLineUpPedWithCar* pUtility); void SetIsWarpingPedIntoCar(); @@ -76,7 +76,7 @@ class CTaskSimpleCarSetPedInAsPassengerSAInterface : public CTaskSimpleSAInterfa class CTaskSimpleCarSetPedInAsPassengerSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleCarSetPedInAsPassenger { public: - CTaskSimpleCarSetPedInAsPassengerSA(){}; + CTaskSimpleCarSetPedInAsPassengerSA() {}; CTaskSimpleCarSetPedInAsPassengerSA(CVehicle* pTargetVehicle, int iTargetDoor, CTaskUtilityLineUpPedWithCar* pUtility); void SetIsWarpingPedIntoCar(); @@ -92,11 +92,11 @@ class CTaskSimpleCarSetPedInAsPassengerSA : public virtual CTaskSimpleSA, public class CTaskSimpleCarSetPedOutSAInterface : public CTaskSimpleSAInterface { public: - CVehicleSAInterface* m_pTargetVehicle; // 8 - int m_iTargetDoor; // 12 - bool m_bSwitchOffEngine; // 16 + CVehicleSAInterface* m_pTargetVehicle; // 8 + int m_iTargetDoor; // 12 + bool m_bSwitchOffEngine; // 16 bool m_bWarpingOutOfCar; - bool m_bFallingOutOfCar; // jumping or falling off car or bike + bool m_bFallingOutOfCar; // jumping or falling off car or bike bool m_bKnockedOffBike; unsigned char m_nDoorFlagsToClear; unsigned char m_nNumGettingInToClear; @@ -105,7 +105,7 @@ class CTaskSimpleCarSetPedOutSAInterface : public CTaskSimpleSAInterface class CTaskSimpleCarSetPedOutSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleCarSetPedOut { public: - CTaskSimpleCarSetPedOutSA(){}; + CTaskSimpleCarSetPedOutSA() {}; CTaskSimpleCarSetPedOutSA(CVehicle* pTargetVehicle, int iTargetDoor, bool bSwitchOffEngine = false); void SetIsWarpingPedOutOfCar(); diff --git a/Client/game_sa/TaskCarSA.h b/Client/game_sa/TaskCarSA.h index d9752c6d371..c8ae39a1f1a 100644 --- a/Client/game_sa/TaskCarSA.h +++ b/Client/game_sa/TaskCarSA.h @@ -20,10 +20,10 @@ class CAnimBlendAssociation; typedef DWORD CTaskUtilityLineUpPedWithCar; typedef DWORD AnimationId; -#define FUNC_CTaskComplexEnterCarAsDriver__Constructor 0x6402F0 -#define FUNC_CTaskComplexEnterCarAsPassenger__Constructor 0x640340 -#define FUNC_CTaskComplexEnterBoatAsDriver__Constructor 0x63B5E0 -#define FUNC_CTaskComplexLeaveCar__Constructor 0x63B8C0 +#define FUNC_CTaskComplexEnterCarAsDriver__Constructor 0x6402F0 +#define FUNC_CTaskComplexEnterCarAsPassenger__Constructor 0x640340 +#define FUNC_CTaskComplexEnterBoatAsDriver__Constructor 0x63B5E0 +#define FUNC_CTaskComplexLeaveCar__Constructor 0x63B8C0 // ############################################################################## // ## Name: CTaskComplexEnterCar @@ -62,7 +62,7 @@ class CTaskComplexEnterCarSAInterface : public CTaskComplexSAInterface class CTaskComplexEnterCarSA : public virtual CTaskComplexSA { public: - CTaskComplexEnterCarSA(){}; + CTaskComplexEnterCarSA() {}; CTaskComplexEnterCarSA(CVehicle* pTargetVehicle, const bool bAsDriver, const bool bQuitAfterOpeningDoor, const bool bQuitAfterDraggingPedOut, const bool bCarryOnAfterFallingOff = false); @@ -97,7 +97,7 @@ class CTaskComplexEnterCarAsDriverSAInterface : public CTaskComplexEnterCarSAInt class CTaskComplexEnterCarAsDriverSA : public virtual CTaskComplexEnterCarSA, public virtual CTaskComplexEnterCarAsDriver { public: - CTaskComplexEnterCarAsDriverSA(){}; + CTaskComplexEnterCarAsDriverSA() {}; CTaskComplexEnterCarAsDriverSA(CVehicle* pTargetVehicle); // from CTaskComplexEnterCarSA @@ -119,7 +119,7 @@ class CTaskComplexEnterCarAsPassengerSAInterface : public CTaskComplexEnterCarSA class CTaskComplexEnterCarAsPassengerSA : public virtual CTaskComplexEnterCarSA, public virtual CTaskComplexEnterCarAsPassenger { public: - CTaskComplexEnterCarAsPassengerSA(){}; + CTaskComplexEnterCarAsPassengerSA() {}; CTaskComplexEnterCarAsPassengerSA(CVehicle* pTargetVehicle, const int iTargetSeat = 0, const bool bCarryOnAfterFallingOff = false); // from CTaskComplexEnterCarSA @@ -141,7 +141,7 @@ class CTaskComplexEnterBoatAsDriverSAInterface : public CTaskComplexSAInterface class CTaskComplexEnterBoatAsDriverSA : public virtual CTaskComplexSA, public virtual CTaskComplexEnterBoatAsDriver { public: - CTaskComplexEnterBoatAsDriverSA(){}; + CTaskComplexEnterBoatAsDriverSA() {}; CTaskComplexEnterBoatAsDriverSA(CVehicle* pTargetVehicle); }; @@ -174,7 +174,7 @@ class CTaskComplexLeaveCarSAInterface : public CTaskComplexSAInterface class CTaskComplexLeaveCarSA : public virtual CTaskComplexSA, public virtual CTaskComplexLeaveCar { public: - CTaskComplexLeaveCarSA(){}; + CTaskComplexLeaveCarSA() {}; CTaskComplexLeaveCarSA(CVehicle* pTargetVehicle, const int iTargetDoor = 0, const int iDelayTime = 0, const bool bSensibleLeaveCar = true, const bool bForceGetOut = false); diff --git a/Client/game_sa/TaskGoToSA.cpp b/Client/game_sa/TaskGoToSA.cpp index fc5967a7edb..b74a6d6b690 100644 --- a/Client/game_sa/TaskGoToSA.cpp +++ b/Client/game_sa/TaskGoToSA.cpp @@ -24,7 +24,7 @@ int CTaskComplexWanderSA::GetWanderType() DWORD dwFunc = ((TaskComplexWanderVTBL*)pTaskInterface->VTBL)->GetWanderType; int iReturn = NO_WANDER_TYPE; - if (dwFunc && dwFunc != 0x82263A) // some tasks have no wander type 0x82263A is purecal (assert?) + if (dwFunc && dwFunc != 0x82263A) // some tasks have no wander type 0x82263A is purecal (assert?) { // clang-format off __asm diff --git a/Client/game_sa/TaskGoToSA.h b/Client/game_sa/TaskGoToSA.h index e10fa3bd611..b78157fed9a 100644 --- a/Client/game_sa/TaskGoToSA.h +++ b/Client/game_sa/TaskGoToSA.h @@ -19,10 +19,10 @@ class CAnimBlendAssociation; typedef DWORD CTaskUtilityLineUpPedWithCar; -#define FUNC_CTaskComplexWanderStandard__Constructor 0x48E4F0 -#define FUNC_CTaskComplexWanderStandard__Destructor 0x48E600 +#define FUNC_CTaskComplexWanderStandard__Constructor 0x48E4F0 +#define FUNC_CTaskComplexWanderStandard__Destructor 0x48E600 -#define FUNC_CTaskSimpleCarSetPedOut__PositionPedOutOfCollision 0x6479B0 +#define FUNC_CTaskSimpleCarSetPedOut__PositionPedOutOfCollision 0x6479B0 class TaskComplexWanderVTBL : public TaskComplexVTBL { @@ -62,7 +62,7 @@ class CTaskComplexWanderSAInterface : public CTaskComplexSAInterface class CTaskComplexWanderSA : public virtual CTaskComplexSA, public virtual CTaskComplexWander { public: - CTaskComplexWanderSA(){}; + CTaskComplexWanderSA() {}; CNodeAddress* GetNextNode(); CNodeAddress* GetLastNode(); @@ -86,6 +86,6 @@ class CTaskComplexWanderStandardSAInterface : public CTaskComplexWanderSAInterfa class CTaskComplexWanderStandardSA : public virtual CTaskComplexWanderSA, public virtual CTaskComplexWanderStandard { public: - CTaskComplexWanderStandardSA(){}; + CTaskComplexWanderStandardSA() {}; CTaskComplexWanderStandardSA(const int iMoveState, const unsigned char iDir, const bool bWanderSensibly = true); }; diff --git a/Client/game_sa/TaskIKSA.cpp b/Client/game_sa/TaskIKSA.cpp index 53045775d8b..4eb2c089dc3 100644 --- a/Client/game_sa/TaskIKSA.cpp +++ b/Client/game_sa/TaskIKSA.cpp @@ -118,7 +118,7 @@ void CTaskSimpleIKManagerSA::RemoveIKChainTask(int slotID) { // Grab the task CTask* pTask = m_pTaskManagementSystem->GetTask(pInterface->m_pIKChainTasks[slotID]); - assert(pTask); // Leave this here temporarily for debugging (shouldn't ever be null) + assert(pTask); // Leave this here temporarily for debugging (shouldn't ever be null) pTask->Destroy(); pInterface->m_pIKChainTasks[slotID] = NULL; } @@ -142,7 +142,7 @@ CTaskSimpleIKChain* CTaskSimpleIKManagerSA::GetTaskAtSlot(int slotID) { // Grab the task CTask* pTask = m_pTaskManagementSystem->GetTask(pInterface->m_pIKChainTasks[slotID]); - assert(pTask); // Leave this here temporarily for debugging (shouldn't ever be null) + assert(pTask); // Leave this here temporarily for debugging (shouldn't ever be null) return dynamic_cast(pTask); } return NULL; diff --git a/Client/game_sa/TaskIKSA.h b/Client/game_sa/TaskIKSA.h index 7fd3efccc9e..eba305f32db 100644 --- a/Client/game_sa/TaskIKSA.h +++ b/Client/game_sa/TaskIKSA.h @@ -17,11 +17,11 @@ typedef DWORD IKChain_c; -#define FUNC_CTaskSimpleIKChain__Constructor 0x6339C0 -#define FUNC_CTaskSimpleIKLookAt__Constructor 0x633E00 -#define FUNC_CTaskSimpleIKManager__Constructor 0x6337F0 +#define FUNC_CTaskSimpleIKChain__Constructor 0x6339C0 +#define FUNC_CTaskSimpleIKLookAt__Constructor 0x633E00 +#define FUNC_CTaskSimpleIKManager__Constructor 0x6337F0 -#define FUNC_CTaskSimpleTriggerLookAt__Constructor 0x634440 +#define FUNC_CTaskSimpleTriggerLookAt__Constructor 0x634440 // ############################################################################## // ## Name: CTaskSimpleIKChain @@ -58,7 +58,7 @@ class CTaskSimpleIKChainSAInterface : public CTaskSimpleSAInterface class CTaskSimpleIKChainSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleIKChain { public: - CTaskSimpleIKChainSA(){}; + CTaskSimpleIKChainSA() {}; CTaskSimpleIKChainSA(char* idString, int effectorBoneTag, CVector effectorVec, int pivotBoneTag, CEntity* pEntity, int offsetBoneTag, CVector offsetPos, float speed, int time = 99999999, int blendTime = 1000); }; @@ -78,7 +78,7 @@ class CTaskSimpleIKLookAtSAInterface : public CTaskSimpleIKChainSAInterface class CTaskSimpleIKLookAtSA : public virtual CTaskSimpleIKChainSA, public virtual CTaskSimpleIKLookAt { public: - CTaskSimpleIKLookAtSA(){}; + CTaskSimpleIKLookAtSA() {}; CTaskSimpleIKLookAtSA(char* idString, CEntity* pEntity, int time, int offsetBoneTag, CVector offsetPos, unsigned char useTorso = false, float speed = 0.25f, int blendTime = 1000, int m_priority = 3); }; @@ -154,7 +154,7 @@ class CTaskSimpleTriggerLookAtSAInterface : public CTaskSimpleSAInterface class CTaskSimpleTriggerLookAtSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleTriggerLookAt { public: - CTaskSimpleTriggerLookAtSA(){}; + CTaskSimpleTriggerLookAtSA() {}; CTaskSimpleTriggerLookAtSA(CEntity* pEntity, int time, int offsetBoneTag, CVector offsetPos, unsigned char useTorso = false, float speed = 0.25f, int blendTime = 1000, int priority = 3); }; diff --git a/Client/game_sa/TaskJumpFallSA.cpp b/Client/game_sa/TaskJumpFallSA.cpp index 97c97aafde6..f065d2374a5 100644 --- a/Client/game_sa/TaskJumpFallSA.cpp +++ b/Client/game_sa/TaskJumpFallSA.cpp @@ -12,8 +12,8 @@ #include "StdInc.h" #include "TaskJumpFallSA.h" -CTaskSimpleClimbSA::CTaskSimpleClimbSA(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, eClimbHeights nHeight, - const bool bForceClimb) +CTaskSimpleClimbSA::CTaskSimpleClimbSA(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, + eClimbHeights nHeight, const bool bForceClimb) { CreateTaskInterface(sizeof(CTaskSimpleClimbSAInterface)); if (!IsValid()) diff --git a/Client/game_sa/TaskJumpFallSA.h b/Client/game_sa/TaskJumpFallSA.h index 61f211ec61a..f2eab7c6fd1 100644 --- a/Client/game_sa/TaskJumpFallSA.h +++ b/Client/game_sa/TaskJumpFallSA.h @@ -20,24 +20,24 @@ class CAnimBlendAssociation; class FxSystem_c; -#define FUNC_CTaskSimpleClimb__Constructor 0x67A110 -#define FUNC_CTaskSimpleJetPack__Constructor 0x67B4E0 +#define FUNC_CTaskSimpleClimb__Constructor 0x67A110 +#define FUNC_CTaskSimpleJetPack__Constructor 0x67B4E0 class CTaskSimpleClimbSAInterface : public CTaskSimpleSAInterface { public: - bool m_bIsFinished; - bool m_bChangeAnimation; - bool m_bChangePosition; - bool m_bForceClimb; - bool m_bInvalidClimb; - eClimbHeights m_nHeightForAnim; - eClimbHeights m_nHeightForPos; - unsigned char m_nSurfaceType; - char m_nFallAfterVault; - float m_fHandholdHeading; - CVector m_vecHandholdPos; - CEntitySAInterface* m_pClimbEnt; + bool m_bIsFinished; + bool m_bChangeAnimation; + bool m_bChangePosition; + bool m_bForceClimb; + bool m_bInvalidClimb; + eClimbHeights m_nHeightForAnim; + eClimbHeights m_nHeightForPos; + unsigned char m_nSurfaceType; + char m_nFallAfterVault; + float m_fHandholdHeading; + CVector m_vecHandholdPos; + CEntitySAInterface* m_pClimbEnt; short m_nGetToPosCounter; CAnimBlendAssociation* m_pAnim; @@ -46,7 +46,7 @@ class CTaskSimpleClimbSAInterface : public CTaskSimpleSAInterface class CTaskSimpleClimbSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleClimb { public: - CTaskSimpleClimbSA(){}; + CTaskSimpleClimbSA() {}; CTaskSimpleClimbSA(CEntitySAInterface* pClimbEnt, const CVector& vecTarget, float fHeading, unsigned char nSurfaceType, eClimbHeights nHeight = CLIMB_GRAB, const bool bForceClimb = false); @@ -100,7 +100,7 @@ class CTaskSimpleJetPackSAInterface : public CTaskSimpleSAInterface class CTaskSimpleJetPackSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleJetPack { public: - CTaskSimpleJetPackSA(){}; + CTaskSimpleJetPackSA() {}; CTaskSimpleJetPackSA(const CVector* pVecTargetPos, float fCruiseHeight = 10.0f, int nHoverTime = 0); bool IsFinished() const override { return static_cast(GetInterface())->m_bIsFinished; } diff --git a/Client/game_sa/TaskPhysicalResponseSA.h b/Client/game_sa/TaskPhysicalResponseSA.h index 1983be056a5..4b16fbab9c1 100644 --- a/Client/game_sa/TaskPhysicalResponseSA.h +++ b/Client/game_sa/TaskPhysicalResponseSA.h @@ -14,8 +14,8 @@ #include #include "TaskSA.h" -#define FUNC_CTaskSimpleChoking__Constructor 0x6202C0 -#define FUNC_CTaskSimpleChoking__UpdateChoke 0x620660 +#define FUNC_CTaskSimpleChoking__Constructor 0x6202C0 +#define FUNC_CTaskSimpleChoking__UpdateChoke 0x620660 class CTaskSimpleChokingSAInterface : public CTaskSimpleSAInterface { @@ -31,7 +31,7 @@ class CTaskSimpleChokingSAInterface : public CTaskSimpleSAInterface class CTaskSimpleChokingSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleChoking { public: - CTaskSimpleChokingSA(){}; + CTaskSimpleChokingSA() {}; CTaskSimpleChokingSA(CPed* pAttacker, bool bIsTearGas); CPed* GetAttacker(); diff --git a/Client/game_sa/TaskSA.cpp b/Client/game_sa/TaskSA.cpp index d2df518c7e1..1184e8be9d9 100644 --- a/Client/game_sa/TaskSA.cpp +++ b/Client/game_sa/TaskSA.cpp @@ -131,7 +131,7 @@ int CTaskSA::GetTaskType() DWORD dwFunc = pTaskInterface->VTBL->GetTaskType; int iReturn = 9999; - if (dwFunc && dwFunc != 0x82263A) // some functions have no task type 0x82263A is purecal (assert?) + if (dwFunc && dwFunc != 0x82263A) // some functions have no task type 0x82263A is purecal (assert?) { // clang-format off __asm @@ -178,7 +178,7 @@ bool CTaskSA::MakeAbortable(CPed* pPed, const int iPriority, const CEvent* pEven DWORD dwThisInterface = (DWORD)GetInterface(); DWORD dwFunc = GetInterface()->VTBL->MakeAbortable; bool bReturn = 0; - if (dwFunc != 0x82263A && dwFunc) // 82263A = purecall + if (dwFunc != 0x82263A && dwFunc) // 82263A = purecall { // clang-format off __asm @@ -209,8 +209,8 @@ const char* CTaskSA::GetTaskName() void CTaskSA::Destroy() { - if (m_bBeingDestroyed) // we want to make sure we don't delete this twice or we get crashes :) - return; // our hook in CTaskManagementSystem will try to delete this otherwise + if (m_bBeingDestroyed) // we want to make sure we don't delete this twice or we get crashes :) + return; // our hook in CTaskManagementSystem will try to delete this otherwise m_bBeingDestroyed = true; DWORD dwThisInterface = (DWORD)GetInterface(); @@ -246,8 +246,8 @@ void CTaskSA::Destroy() void CTaskSA::DestroyJustThis() { - if (m_bBeingDestroyed) // we want to make sure we don't delete this twice or we get crashes :) - return; // our hook in CTaskManagementSystem will try to delete this otherwise + if (m_bBeingDestroyed) // we want to make sure we don't delete this twice or we get crashes :) + return; // our hook in CTaskManagementSystem will try to delete this otherwise m_bBeingDestroyed = true; delete this; diff --git a/Client/game_sa/TaskSA.h b/Client/game_sa/TaskSA.h index 60e0333f9d3..649dab12460 100644 --- a/Client/game_sa/TaskSA.h +++ b/Client/game_sa/TaskSA.h @@ -14,14 +14,14 @@ #include #include "TaskNamesSA.h" -#define FUNC_CTask__Operator_New 0x61A5A0 -#define FUNC_CTask__Operator_Delete 0x61A5B0 +#define FUNC_CTask__Operator_New 0x61A5A0 +#define FUNC_CTask__Operator_Delete 0x61A5B0 class CTaskTimer { public: - DWORD dwTimeStart; // ? - DWORD dwTimeEnd; // ? + DWORD dwTimeStart; // ? + DWORD dwTimeEnd; // ? bool bSet; bool bStopped; }; @@ -57,7 +57,7 @@ class TaskComplexVTBL : public TaskVTBL class CTaskSAInterface { public: - TaskVTBL* VTBL; // cast to either TaskSimpleVTBL or TaskComplexVTBL + TaskVTBL* VTBL; // cast to either TaskSimpleVTBL or TaskComplexVTBL CTaskSAInterface* m_pParent; }; @@ -66,7 +66,7 @@ class CTaskSA : public virtual CTask private: // our variable(s) CTaskSAInterface* TaskInterface; - CTaskSA* Parent; // if the task was setup through an external source, this isn't going to be correct + CTaskSA* Parent; // if the task was setup through an external source, this isn't going to be correct bool m_bBeingDestroyed; public: @@ -84,10 +84,10 @@ class CTaskSA : public virtual CTask const char* GetTaskName(); // our function(s) - void SetInterface(CTaskSAInterface* pInterface) { TaskInterface = pInterface; }; + void SetInterface(CTaskSAInterface* pInterface) { TaskInterface = pInterface; }; CTaskSAInterface* GetInterface() noexcept { return TaskInterface; } const CTaskSAInterface* GetInterface() const noexcept { return TaskInterface; } - bool IsValid() { return GetInterface() != NULL; } + bool IsValid() { return GetInterface() != NULL; } void CreateTaskInterface(size_t nSize); @@ -111,7 +111,7 @@ class CTaskSimpleSAInterface : public CTaskSAInterface class CTaskSimpleSA : public virtual CTaskSA, public virtual CTaskSimple { public: - CTaskSimpleSA(){}; + CTaskSimpleSA() {}; bool ProcessPed(CPed* pPed); bool SetPedPosition(CPed* pPed); @@ -126,7 +126,7 @@ class CTaskComplexSAInterface : public CTaskSAInterface class CTaskComplexSA : public virtual CTaskSA, public virtual CTaskComplex { public: - CTaskComplexSA(){}; + CTaskComplexSA() {}; void SetSubTask(CTask* pSubTask); CTask* CreateNextSubTask(CPed* pPed); diff --git a/Client/game_sa/TaskSecondarySA.h b/Client/game_sa/TaskSecondarySA.h index 963386b0c96..1aa57b79b60 100644 --- a/Client/game_sa/TaskSecondarySA.h +++ b/Client/game_sa/TaskSecondarySA.h @@ -18,7 +18,7 @@ // typedef int CAnimBlendAssociation ; typedef DWORD IKChain_c; -#define FUNC_CTaskSimpleDuck__Constructor 0x691FC0 +#define FUNC_CTaskSimpleDuck__Constructor 0x691FC0 // ############################################################################## // ## Name: CTaskSimpleDuck @@ -31,13 +31,13 @@ class CTaskSimpleDuckSAInterface : public CTaskSimpleSAInterface unsigned int m_nStartTime; unsigned short m_nLengthOfDuck; short m_nShotWhizzingCounter; - int* m_pDuckAnim; // was CAnimBlendAssociation - int* m_pMoveAnim; // was CAnimBlendAssociation + int* m_pDuckAnim; // was CAnimBlendAssociation + int* m_pMoveAnim; // was CAnimBlendAssociation bool m_bIsFinished; bool m_bIsAborting; - bool m_bNeedToSetDuckFlag; // incase bIsDucking flag gets cleared elsewhere - so we know to stop duck task - bool m_bIsInControl; // if duck task is being controlled by another task then it requires continuous control + bool m_bNeedToSetDuckFlag; // incase bIsDucking flag gets cleared elsewhere - so we know to stop duck task + bool m_bIsInControl; // if duck task is being controlled by another task then it requires continuous control CVector2D m_vecMoveCommand; unsigned char m_nDuckControlType; @@ -48,6 +48,6 @@ class CTaskSimpleDuckSAInterface : public CTaskSimpleSAInterface class CTaskSimpleDuckSA : public virtual CTaskSimpleSA, public virtual CTaskSimpleDuck { public: - CTaskSimpleDuckSA(){}; + CTaskSimpleDuckSA() {}; CTaskSimpleDuckSA(eDuckControlTypes nDuckControl, unsigned short nLengthOfDuck = 0, short nUseShotsWhizzingEvents = -1); }; diff --git a/Client/game_sa/TaskSimpleSwimSA.cpp b/Client/game_sa/TaskSimpleSwimSA.cpp index d562f037006..98e9e36600c 100644 --- a/Client/game_sa/TaskSimpleSwimSA.cpp +++ b/Client/game_sa/TaskSimpleSwimSA.cpp @@ -18,5 +18,6 @@ CTaskSimpleSwimSA::CTaskSimpleSwimSA(CPed* ped, CVector* pos) return; // Call the constructor - ((void(__thiscall*)(CTaskSimpleSwimSAInterface*, CVector*, CPedSAInterface*))0x688930)(static_cast(GetInterface()), pos, ped ? ped->GetPedInterface() : nullptr); + ((void(__thiscall*)(CTaskSimpleSwimSAInterface*, CVector*, CPedSAInterface*))0x688930)(static_cast(GetInterface()), pos, + ped ? ped->GetPedInterface() : nullptr); } diff --git a/Client/game_sa/TaskSimpleSwimSA.h b/Client/game_sa/TaskSimpleSwimSA.h index 14ed311b1b0..2faea864ffc 100644 --- a/Client/game_sa/TaskSimpleSwimSA.h +++ b/Client/game_sa/TaskSimpleSwimSA.h @@ -41,7 +41,7 @@ class CTaskSimpleSwimSAInterface : public CTaskSimpleSAInterface float m_randomMoveBlendRatio; float m_swimStopTime; std::uint32_t m_timeStep; - void* m_fxSystem; // FxSystem_cSAInterface* + void* m_fxSystem; // FxSystem_cSAInterface* bool m_triggerWaterSplash; std::uint8_t m_field61[3]; }; @@ -53,7 +53,7 @@ class CTaskSimpleSwimSA : public virtual CTaskSimpleSA, public virtual CTaskSimp CTaskSimpleSwimSA(CPed* ped, CVector* pos); const CTaskSimpleSwimSAInterface* GetTaskInterface() const { return static_cast(GetInterface()); } - CTaskSimpleSwimSAInterface* GetTaskInterface() { return static_cast(GetInterface()); } + CTaskSimpleSwimSAInterface* GetTaskInterface() { return static_cast(GetInterface()); } swimState GetSwimState() const override { return GetTaskInterface()->m_swimState; } }; diff --git a/Client/game_sa/gamesa_renderware.h b/Client/game_sa/gamesa_renderware.h index c5f14526b05..9455a59da76 100644 --- a/Client/game_sa/gamesa_renderware.h +++ b/Client/game_sa/gamesa_renderware.h @@ -22,8 +22,8 @@ struct CColModelSAInterface; /*****************************************************************************/ /* RenderWare macros */ -#define RpGetFrame(__c) ((RwFrame*)(((RwObject *)(__c))->parent)) -#define RpSetFrame(__c,__f) ((((RwObject *)(__c))->parent) = (void *)(__f)) +#define RpGetFrame(__c) ((RwFrame*)(((RwObject*)(__c))->parent)) +#define RpSetFrame(__c, __f) ((((RwObject*)(__c))->parent) = (void*)(__f)) /* RenderWare function defines */ typedef RpAtomic*(__cdecl* RpAtomicCreate_t)(); @@ -114,9 +114,9 @@ typedef RtQuat*(__cdecl* RtQuatRotate_t)(RtQuat* quat, const RwV3d* axis, float /*****************************************************************************/ #ifdef RWFUNC_IMPLEMENT - #define RWFUNC(a,b) a = b; + #define RWFUNC(a, b) a = b; #else - #define RWFUNC(a,b) extern a; + #define RWFUNC(a, b) extern a; #endif // US Versions @@ -206,14 +206,14 @@ RWFUNC(RtQuatRotate_t RtQuatRotate, (RtQuatRotate_t)0xDEAD) /*****************************************************************************/ typedef bool(__cdecl* SetTextureDict_t)(unsigned short id); -typedef bool(__cdecl* LoadClumpFile_t)(RwStream* stream, unsigned int id); // (stream, model id) -typedef bool(__cdecl* LoadModel_t)(RwBuffer* filename, unsigned int id); // (memory chunk, model id) +typedef bool(__cdecl* LoadClumpFile_t)(RwStream* stream, unsigned int id); // (stream, model id) +typedef bool(__cdecl* LoadModel_t)(RwBuffer* filename, unsigned int id); // (memory chunk, model id) typedef void(__cdecl* LoadCollisionModel_t)(unsigned char*, CColModelSAInterface*, const char*); typedef void(__cdecl* LoadCollisionModelVer2_t)(unsigned char*, unsigned int, CColModelSAInterface*, const char*); typedef void(__cdecl* LoadCollisionModelVer3_t)(unsigned char*, unsigned int, CColModelSAInterface*, - const char*); // buf, bufsize, ccolmodel&, keyname + const char*); // buf, bufsize, ccolmodel&, keyname typedef void(__cdecl* LoadCollisionModelVer4_t)(unsigned char*, unsigned int, CColModelSAInterface*, - const char*); // buf, bufsize, ccolmodel&, keyname + const char*); // buf, bufsize, ccolmodel&, keyname typedef bool(__cdecl* CTxdStore_LoadTxd_t)(unsigned int id, RwStream* filename); typedef void(__cdecl* CTxdStore_RemoveTxd_t)(unsigned int id); typedef void(__cdecl* CTxdStore_RemoveRef_t)(unsigned int id); diff --git a/Client/game_sa/gamesa_renderware.hpp b/Client/game_sa/gamesa_renderware.hpp index 12e312725b4..dd6d5f442df 100644 --- a/Client/game_sa/gamesa_renderware.hpp +++ b/Client/game_sa/gamesa_renderware.hpp @@ -91,7 +91,7 @@ void InitRwFunctions() RpHAnimIDGetIndex = (RpHAnimIDGetIndex_t)0x7C51A0; RpHAnimHierarchyGetMatrixArray = (RpHAnimHierarchyGetMatrixArray_t)0x7C5120; RtQuatRotate = (RtQuatRotate_t)0x7EB7C0; - + SetTextureDict = (SetTextureDict_t)0x007319C0; LoadClumpFile = (LoadClumpFile_t)0x005371F0; LoadModel = (LoadModel_t)0x0040C6B0; diff --git a/Client/gui/CGUIButton_Impl.h b/Client/gui/CGUIButton_Impl.h index e611af86fae..e215bf3f460 100644 --- a/Client/gui/CGUIButton_Impl.h +++ b/Client/gui/CGUIButton_Impl.h @@ -22,5 +22,5 @@ class CGUIButton_Impl : public CGUIButton, public CGUIElement_Impl eCGUIType GetType() { return CGUI_BUTTON; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" }; diff --git a/Client/gui/CGUICheckBox_Impl.h b/Client/gui/CGUICheckBox_Impl.h index 3755f600788..7a926cedd98 100644 --- a/Client/gui/CGUICheckBox_Impl.h +++ b/Client/gui/CGUICheckBox_Impl.h @@ -25,5 +25,5 @@ class CGUICheckBox_Impl : public CGUICheckBox, public CGUIElement_Impl eCGUIType GetType() { return CGUI_CHECKBOX; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" }; diff --git a/Client/gui/CGUIComboBox_Impl.cpp b/Client/gui/CGUIComboBox_Impl.cpp index e56c074d6d6..3289595a206 100644 --- a/Client/gui/CGUIComboBox_Impl.cpp +++ b/Client/gui/CGUIComboBox_Impl.cpp @@ -83,7 +83,7 @@ bool CGUIComboBox_Impl::RemoveItem(int index) try { CEGUI::ListboxItem* pItem = reinterpret_cast(m_pWindow)->getListboxItemFromIndex(index); - if (pItem->isSelected()) // if this is currently selected, let's update the editbox. + if (pItem->isSelected()) // if this is currently selected, let's update the editbox. { m_pWindow->setText(storedCaption); } @@ -178,7 +178,7 @@ bool CGUIComboBox_Impl::SetItemText(int index, const char* szText) { CEGUI::ListboxItem* pItem = reinterpret_cast(m_pWindow)->getListboxItemFromIndex(index); pItem->setText(CGUI_Impl::GetUTFString(szText), NULL); - if (pItem->isSelected()) // if this is currently selected, let's update the editbox. + if (pItem->isSelected()) // if this is currently selected, let's update the editbox. { m_pWindow->setText(CGUI_Impl::GetUTFString(szText)); } diff --git a/Client/gui/CGUIComboBox_Impl.h b/Client/gui/CGUIComboBox_Impl.h index cd84a8e647b..9d4613f1537 100644 --- a/Client/gui/CGUIComboBox_Impl.h +++ b/Client/gui/CGUIComboBox_Impl.h @@ -44,7 +44,7 @@ class CGUIComboBox_Impl : public CGUIComboBox, public CGUIElement_Impl void ShowDropList(); void HideDropList(); - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" protected: CFastHashMap m_Items; diff --git a/Client/gui/CGUIEdit_Impl.h b/Client/gui/CGUIEdit_Impl.h index 8edfbff1175..966324c51f0 100644 --- a/Client/gui/CGUIEdit_Impl.h +++ b/Client/gui/CGUIEdit_Impl.h @@ -47,7 +47,7 @@ class CGUIEdit_Impl : public CGUIEdit, public CGUIElement_Impl, public CGUITabLi eCGUIType GetType() { return CGUI_EDIT; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" protected: bool Event_OnTextChanged(const CEGUI::EventArgs& e); diff --git a/Client/gui/CGUIElement_Impl.cpp b/Client/gui/CGUIElement_Impl.cpp index 4b11ec51e9f..4e9fa9a6807 100644 --- a/Client/gui/CGUIElement_Impl.cpp +++ b/Client/gui/CGUIElement_Impl.cpp @@ -14,9 +14,9 @@ // Define no-drawing zones, a.k.a. the inside borders in the FrameWindow of BlueLook in pixels // If something is drawn inside of these areas, the theme border is drawn on top of it -#define CGUI_NODRAW_LEFT 9.0f -#define CGUI_NODRAW_RIGHT 9.0f -#define CGUI_NODRAW_TOP 9.0f +#define CGUI_NODRAW_LEFT 9.0f +#define CGUI_NODRAW_RIGHT 9.0f +#define CGUI_NODRAW_TOP 9.0f #define CGUI_NODRAW_BOTTOM 9.0f CGUIElement_Impl::CGUIElement_Impl() @@ -220,7 +220,7 @@ void CGUIElement_Impl::AutoSize(const char* Text, float fPaddingX, float fPaddin const CEGUI::Font* pFont = m_pWindow->getFont(); m_pWindow->setSize(CEGUI::Absolute, CEGUI::Size(pFont->getTextExtent(CGUI_Impl::GetUTFString(Text ? Text : GetText())) + fPaddingX, - pFont->getFontHeight() + fPaddingY)); // Add hack factor to height to allow for long characters such as 'g' or 'j' + pFont->getFontHeight() + fPaddingY)); // Add hack factor to height to allow for long characters such as 'g' or 'j' } void CGUIElement_Impl::SetMinimumSize(const CVector2D& vecSize) diff --git a/Client/gui/CGUIElement_Impl.h b/Client/gui/CGUIElement_Impl.h index 84a4ac7b25b..33c6bdd9834 100644 --- a/Client/gui/CGUIElement_Impl.h +++ b/Client/gui/CGUIElement_Impl.h @@ -20,7 +20,7 @@ namespace CEGUI { class Window; class EventArgs; -} // namespace CEGUI +} class CGUI_Impl; class CGUIElement_Impl : public CGUIElement diff --git a/Client/gui/CGUIElement_Inc.h b/Client/gui/CGUIElement_Inc.h index 026b07d86f5..250fa22cfba 100644 --- a/Client/gui/CGUIElement_Inc.h +++ b/Client/gui/CGUIElement_Inc.h @@ -98,7 +98,7 @@ void SetHeight(float fY, bool bRelative = false) CGUIElement_Impl::SetHeight(fY, bRelative); }; -#ifndef EXCLUDE_SET_SIZE // WTF? TODO: Refactor this +#ifndef EXCLUDE_SET_SIZE // WTF? TODO: Refactor this void SetSize(const CVector2D& vecSize, bool bRelative = false) { CGUIElement_Impl::SetSize(vecSize, bRelative); diff --git a/Client/gui/CGUIFont_Impl.cpp b/Client/gui/CGUIFont_Impl.cpp index 731140a077c..7ab80996f40 100644 --- a/Client/gui/CGUIFont_Impl.cpp +++ b/Client/gui/CGUIFont_Impl.cpp @@ -96,8 +96,8 @@ float CGUIFont_Impl::GetCharacterWidth(int iChar, float fScale) float CGUIFont_Impl::GetFontHeight(float fScale) { - float fHeight = m_pFont->getFontHeight(fScale); // average height.. not the maximum height for long characters such as 'g' or 'j' - fHeight += 2.0f; // so hack it + float fHeight = m_pFont->getFontHeight(fScale); // average height.. not the maximum height for long characters such as 'g' or 'j' + fHeight += 2.0f; // so hack it return fHeight; } diff --git a/Client/gui/CGUIGridList_Impl.cpp b/Client/gui/CGUIGridList_Impl.cpp index 121b66c7f80..7145fbbcd99 100644 --- a/Client/gui/CGUIGridList_Impl.cpp +++ b/Client/gui/CGUIGridList_Impl.cpp @@ -13,9 +13,9 @@ namespace { - constexpr const char kGridListName[] = "CGUI/MultiColumnList"; - constexpr const char kGridListNoFrameName[] = "CGUI/MultiColumnList"; // MultiColumnListNoFrame - constexpr const char kGridListSpacer[] = " "; + constexpr const char kGridListName[] = "CGUI/MultiColumnList"; + constexpr const char kGridListNoFrameName[] = "CGUI/MultiColumnList"; // MultiColumnListNoFrame + constexpr const char kGridListSpacer[] = " "; constexpr std::size_t kGridListSpacerLength = (sizeof(kGridListSpacer) / sizeof(char)) - 1; constexpr std::size_t kGridListMaxTextLength = 256; @@ -274,7 +274,7 @@ int CGUIGridList_Impl::AddRow(bool fast, std::vector >* int CGUIGridList_Impl::SetRowItemsText(int iRow, std::vector >* m_items) { - const int sortColumn = reinterpret_cast(m_pWindow)->getSortColumn() + 1; // MTA columns start at 1, CEGUI at 0 + const int sortColumn = reinterpret_cast(m_pWindow)->getSortColumn() + 1; // MTA columns start at 1, CEGUI at 0 int column = 1; for (const auto& [text, isNumber] : *m_items) @@ -447,8 +447,8 @@ int CGUIGridList_Impl::SetItemText(int iRow, int hColumn, const char* szText, bo try { CEGUI::MultiColumnList* list = reinterpret_cast(m_pWindow); - const int columnIndex = GetColumnIndex(hColumn); - CGUIListItem_Impl* pItem = reinterpret_cast(GetItem(iRow, hColumn)); + const int columnIndex = GetColumnIndex(hColumn); + CGUIListItem_Impl* pItem = reinterpret_cast(GetItem(iRow, hColumn)); if (!pItem) { @@ -780,8 +780,8 @@ void CGUIGridList_Impl::SetSelectedItem(int iRow, int hColumn, bool bReset) void CGUIGridList_Impl::Sort(unsigned int uiColumn, SortDirection direction) { CEGUI::MultiColumnList* pList = reinterpret_cast(m_pWindow); - const unsigned int columnCount = static_cast(pList->getColumnCount()); - const unsigned int column = NormalizeSortColumn(uiColumn, columnCount); + const unsigned int columnCount = static_cast(pList->getColumnCount()); + const unsigned int column = NormalizeSortColumn(uiColumn, columnCount); if (column == 0) return; @@ -840,8 +840,8 @@ void CGUIGridList_Impl::UpdateSortIndicator(unsigned int uiColumn, SortDirection try { CEGUI::MultiColumnList* pList = reinterpret_cast(m_pWindow); - const auto columnCount = static_cast(pList->getColumnCount()); - const int targetIndex = (uiColumn > 0) ? static_cast(uiColumn - 1) : -1; + const auto columnCount = static_cast(pList->getColumnCount()); + const int targetIndex = (uiColumn > 0) ? static_cast(uiColumn - 1) : -1; for (auto i = 0; i < columnCount; ++i) { diff --git a/Client/gui/CGUIGridList_Impl.h b/Client/gui/CGUIGridList_Impl.h index e859c4da438..ec696a98ac3 100644 --- a/Client/gui/CGUIGridList_Impl.h +++ b/Client/gui/CGUIGridList_Impl.h @@ -48,13 +48,13 @@ class CGUIGridList_Impl : public CGUIGridList, public CGUIElement_Impl void SetItemColor(int iRow, int hColumn, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue, unsigned char ucAlpha); bool GetItemColor(int iRow, int hColumn, unsigned char& ucRed, unsigned char& ucGreen, unsigned char& ucBlue, unsigned char& ucAlpha); - void SetHorizontalScrollBar(bool bEnabled); - void SetVerticalScrollBar(bool bEnabled); - void SetSortingEnabled(bool bEnabled); - bool IsSortingEnabled(); - void SetAutoSortSuppressed(bool bSuppressed); + void SetHorizontalScrollBar(bool bEnabled); + void SetVerticalScrollBar(bool bEnabled); + void SetSortingEnabled(bool bEnabled); + bool IsSortingEnabled(); + void SetAutoSortSuppressed(bool bSuppressed); [[nodiscard]] bool IsAutoSortSuppressed() const; - void SetItemImage(int iRow, int hColumn, CGUIStaticImage* pImage); + void SetItemImage(int iRow, int hColumn, CGUIStaticImage* pImage); float GetHorizontalScrollPosition(); float GetVerticalScrollPosition(); @@ -87,7 +87,7 @@ class CGUIGridList_Impl : public CGUIGridList, public CGUIElement_Impl void SetIgnoreTextSpacer(bool bIgnoreTextSpacer) { m_bIgnoreTextSpacer = bIgnoreTextSpacer; }; eCGUIType GetType() { return CGUI_GRIDLIST; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: bool Event_OnSortColumn(const CEGUI::EventArgs& e); diff --git a/Client/gui/CGUILabel_Impl.h b/Client/gui/CGUILabel_Impl.h index b4960c17b8f..c40eb598116 100644 --- a/Client/gui/CGUILabel_Impl.h +++ b/Client/gui/CGUILabel_Impl.h @@ -43,7 +43,7 @@ class CGUILabel_Impl : public CGUILabel, public CGUIElement_Impl eCGUIType GetType() { return CGUI_LABEL; }; - #define EXCLUDE_SET_TEXT - #include "CGUIElement_Inc.h" - #undef EXCLUDE_SET_TEXT +#define EXCLUDE_SET_TEXT +#include "CGUIElement_Inc.h" +#undef EXCLUDE_SET_TEXT }; diff --git a/Client/gui/CGUIMemo_Impl.h b/Client/gui/CGUIMemo_Impl.h index 650d495f2df..7ae3d421931 100644 --- a/Client/gui/CGUIMemo_Impl.h +++ b/Client/gui/CGUIMemo_Impl.h @@ -45,7 +45,7 @@ class CGUIMemo_Impl : public CGUIMemo, public CGUIElement_Impl, public CGUITabLi eCGUIType GetType() { return CGUI_MEMO; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: bool Event_TextChanged(const CEGUI::EventArgs& e); diff --git a/Client/gui/CGUIMessageBox_Impl.cpp b/Client/gui/CGUIMessageBox_Impl.cpp index 6e7c90a7694..ab74df595e5 100644 --- a/Client/gui/CGUIMessageBox_Impl.cpp +++ b/Client/gui/CGUIMessageBox_Impl.cpp @@ -12,15 +12,15 @@ #include "StdInc.h" #include "../core/CFilePathTranslator.h" -#define MESSAGEBOX_WIDTH 400.0f -#define MESSAGEBOX_HEIGHT 150.0f -#define MESSAGEBOX_SPACER 20 -#define MESSAGEBOX_ICON_SIZE 42 +#define MESSAGEBOX_WIDTH 400.0f +#define MESSAGEBOX_HEIGHT 150.0f +#define MESSAGEBOX_SPACER 20 +#define MESSAGEBOX_ICON_SIZE 42 CGUIMessageBox_Impl::CGUIMessageBox_Impl(CGUI_Impl* pGUI, const char* szTitle, const char* szCaption, unsigned int uiFlags) { // Initialize - m_bAutoDestroy = true; // TODO: If any buttons.. + m_bAutoDestroy = true; // TODO: If any buttons.. m_pIcon = NULL; m_pButton = NULL; m_pLabelCaption = NULL; @@ -32,7 +32,7 @@ CGUIMessageBox_Impl::CGUIMessageBox_Impl(CGUI_Impl* pGUI, const char* szTitle, c m_pWindow->SetCloseButtonEnabled(false); m_pWindow->SetSizingEnabled(false); m_pWindow->SetPosition(CVector2D(ScreenSize.fX * 0.5f - MESSAGEBOX_WIDTH * 0.5f, ScreenSize.fY * 0.5f - MESSAGEBOX_HEIGHT * 0.5f)); - m_pWindow->SetSize(CVector2D(MESSAGEBOX_WIDTH, MESSAGEBOX_HEIGHT)); // relative 0.35, 0.225 + m_pWindow->SetSize(CVector2D(MESSAGEBOX_WIDTH, MESSAGEBOX_HEIGHT)); // relative 0.35, 0.225 // Create the icon m_pIcon = pGUI->CreateStaticImage(m_pWindow); diff --git a/Client/gui/CGUIProgressBar_Impl.h b/Client/gui/CGUIProgressBar_Impl.h index 38a041b5101..8d37c70d5cd 100644 --- a/Client/gui/CGUIProgressBar_Impl.h +++ b/Client/gui/CGUIProgressBar_Impl.h @@ -25,7 +25,7 @@ class CGUIProgressBar_Impl : public CGUIProgressBar, public CGUIElement_Impl eCGUIType GetType() { return CGUI_PROGRESSBAR; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: }; diff --git a/Client/gui/CGUIRadioButton_Impl.h b/Client/gui/CGUIRadioButton_Impl.h index e9e189599f5..be22ac5cb0e 100644 --- a/Client/gui/CGUIRadioButton_Impl.h +++ b/Client/gui/CGUIRadioButton_Impl.h @@ -25,7 +25,7 @@ class CGUIRadioButton_Impl : public CGUIRadioButton, public CGUIElement_Impl eCGUIType GetType() { return CGUI_RADIOBUTTON; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: }; diff --git a/Client/gui/CGUIScrollBar_Impl.cpp b/Client/gui/CGUIScrollBar_Impl.cpp index 1ed723cfd6d..c895a374149 100644 --- a/Client/gui/CGUIScrollBar_Impl.cpp +++ b/Client/gui/CGUIScrollBar_Impl.cpp @@ -11,12 +11,12 @@ #include "StdInc.h" -#define CGUISCROLLBAR_HORIZONTAL_NAME "CGUI/HorizontalScrollbar" -#define CGUISCROLLBAR_VERTICAL_NAME "CGUI/VerticalScrollbar" +#define CGUISCROLLBAR_HORIZONTAL_NAME "CGUI/HorizontalScrollbar" +#define CGUISCROLLBAR_VERTICAL_NAME "CGUI/VerticalScrollbar" CGUIScrollBar_Impl::CGUIScrollBar_Impl(CGUI_Impl* pGUI, bool bHorizontal, CGUIElement* pParent) { - SetManager(pGUI); + SetManager(pGUI); // Get an unique identifier for CEGUI (gah, there's gotta be an another way) char szUnique[CGUI_CHAR_SIZE]; diff --git a/Client/gui/CGUIScrollBar_Impl.h b/Client/gui/CGUIScrollBar_Impl.h index a996595a888..8aa653b5fe7 100644 --- a/Client/gui/CGUIScrollBar_Impl.h +++ b/Client/gui/CGUIScrollBar_Impl.h @@ -27,7 +27,7 @@ class CGUIScrollBar_Impl : public CGUIScrollBar, public CGUIElement_Impl eCGUIType GetType() { return CGUI_SCROLLBAR; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: bool Event_OnScroll(const CEGUI::EventArgs& e); diff --git a/Client/gui/CGUIScrollPane_Impl.h b/Client/gui/CGUIScrollPane_Impl.h index 1c2b036828b..91bc11c8c52 100644 --- a/Client/gui/CGUIScrollPane_Impl.h +++ b/Client/gui/CGUIScrollPane_Impl.h @@ -37,7 +37,7 @@ class CGUIScrollPane_Impl : public CGUIScrollPane, public CGUIElement_Impl, publ eCGUIType GetType() { return CGUI_SCROLLPANE; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: class CGUI_Impl* m_pGUI; diff --git a/Client/gui/CGUIStaticImage_Impl.h b/Client/gui/CGUIStaticImage_Impl.h index b01dcd8a9ef..7ebb54a1419 100644 --- a/Client/gui/CGUIStaticImage_Impl.h +++ b/Client/gui/CGUIStaticImage_Impl.h @@ -45,5 +45,5 @@ class CGUIStaticImage_Impl : public CGUIStaticImage, public CGUIElement_Impl, pu CEGUI::Imageset* m_pImageset; const CEGUI::Image* m_pImage; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" }; diff --git a/Client/gui/CGUITabList.h b/Client/gui/CGUITabList.h index dcbab3d4b90..9bb9a75da66 100644 --- a/Client/gui/CGUITabList.h +++ b/Client/gui/CGUITabList.h @@ -16,8 +16,8 @@ typedef std::list::const_iterator CGUITabIterator; class CGUITabList { public: - CGUITabList(){}; - ~CGUITabList(){}; + CGUITabList() {}; + ~CGUITabList() {}; void AddItem(CGUITabListItem* pItem) { m_Items.push_back(pItem); }; void RemoveItem(CGUITabListItem* pItem) { m_Items.remove(pItem); }; diff --git a/Client/gui/CGUITabPanel_Impl.h b/Client/gui/CGUITabPanel_Impl.h index a0b7b9f3229..b12c001ded6 100644 --- a/Client/gui/CGUITabPanel_Impl.h +++ b/Client/gui/CGUITabPanel_Impl.h @@ -42,7 +42,7 @@ class CGUITabPanel_Impl : public CGUITabPanel, public CGUIElement_Impl void SetSelectionHandler(GUI_CALLBACK Callback); - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" private: class CGUI_Impl* m_pGUI; diff --git a/Client/gui/CGUITab_Impl.h b/Client/gui/CGUITab_Impl.h index 507b6facbe1..fd30a87c56c 100644 --- a/Client/gui/CGUITab_Impl.h +++ b/Client/gui/CGUITab_Impl.h @@ -26,7 +26,7 @@ class CGUITab_Impl : public CGUITab, public CGUIElement_Impl, public CGUITabList #define SETVISIBLE_HACK #define SETENABLED_HACK - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" #undef SETENABLED_HACK #undef SETVISIBLE_HACK diff --git a/Client/gui/CGUITexture_Impl.h b/Client/gui/CGUITexture_Impl.h index 23b2199467e..4477da9aafe 100644 --- a/Client/gui/CGUITexture_Impl.h +++ b/Client/gui/CGUITexture_Impl.h @@ -17,7 +17,7 @@ namespace CEGUI { class Texture; class Renderer; -} // namespace CEGUI +} class CGUITexture_Impl : public CGUITexture { diff --git a/Client/gui/CGUIWebBrowser_Impl.cpp b/Client/gui/CGUIWebBrowser_Impl.cpp index 9e480f52f26..0de25b12306 100644 --- a/Client/gui/CGUIWebBrowser_Impl.cpp +++ b/Client/gui/CGUIWebBrowser_Impl.cpp @@ -108,7 +108,7 @@ void CGUIWebBrowser_Impl::LoadFromWebView(CWebViewInterface* pWebView) // Define an image and get its pointer m_pImageset->defineImage(szUnique, CEGUI::Point(0, 0), CEGUI::Size(pCEGUITexture->getWidth(), pCEGUITexture->getHeight()), CEGUI::Point(0, 0)); m_pImage = const_cast( - &m_pImageset->getImage(szUnique)); // const_cast here is a huge hack, but is okay here since all images generated here are unique + &m_pImageset->getImage(szUnique)); // const_cast here is a huge hack, but is okay here since all images generated here are unique // Set the image just loaded as the image to be drawn for the widget reinterpret_cast(m_pWindow)->setImage(m_pImage); diff --git a/Client/gui/CGUIWebBrowser_Impl.h b/Client/gui/CGUIWebBrowser_Impl.h index 99e2e69ebf3..7de13f501c6 100644 --- a/Client/gui/CGUIWebBrowser_Impl.h +++ b/Client/gui/CGUIWebBrowser_Impl.h @@ -60,9 +60,9 @@ class CGUIWebBrowser_Impl : public CGUIWebBrowser, public CGUIElement_Impl CWebViewInterface* m_pWebView; - #define EXCLUDE_SET_SIZE // WTF? TODO: Refactor this - #include "CGUIElement_Inc.h" - #undef EXCLUDE_SET_SIZE +#define EXCLUDE_SET_SIZE // WTF? TODO: Refactor this +#include "CGUIElement_Inc.h" +#undef EXCLUDE_SET_SIZE }; // The purpose of this class is to provide an externally managed DirectX texture @@ -75,12 +75,12 @@ class CGUIWebBrowserTexture : public CEGUI::DirectX9Texture virtual ushort getHeight() const override; // Override with empty function (--> eliminate the functinions from DirectX9Texture) - virtual void loadFromFile(const CEGUI::String& filename, const CEGUI::String& resourceGroup) override{}; - virtual void loadFromMemory(const void* buffPtr, uint buffWidth, uint buffHeight) override{}; + virtual void loadFromFile(const CEGUI::String& filename, const CEGUI::String& resourceGroup) override {}; + virtual void loadFromMemory(const void* buffPtr, uint buffWidth, uint buffHeight) override {}; virtual LPDIRECT3DTEXTURE9 getD3DTexture() const override; - virtual void preD3DReset(){}; - virtual void postD3DReset(){}; + virtual void preD3DReset() {}; + virtual void postD3DReset() {}; private: CWebViewInterface* m_pWebView; diff --git a/Client/gui/CGUIWindow_Impl.h b/Client/gui/CGUIWindow_Impl.h index d7ec871be6e..881b83b5f7e 100644 --- a/Client/gui/CGUIWindow_Impl.h +++ b/Client/gui/CGUIWindow_Impl.h @@ -35,7 +35,7 @@ class CGUIWindow_Impl : public CGUIWindow, public CGUIElement_Impl, public CGUIT eCGUIType GetType() { return CGUI_WINDOW; }; - #include "CGUIElement_Inc.h" +#include "CGUIElement_Inc.h" protected: bool Event_OnCloseClick(const CEGUI::EventArgs& e); diff --git a/Client/gui/CGUI_Impl.cpp b/Client/gui/CGUI_Impl.cpp index cbda388493d..0c5d41a412a 100644 --- a/Client/gui/CGUI_Impl.cpp +++ b/Client/gui/CGUI_Impl.cpp @@ -34,46 +34,46 @@ void CGUI_Impl::DestroyElementRecursive(CGUIElement* pElement) delete pElement; } -#define CGUI_MTA_DEFAULT_FONT "tahoma.ttf" // %WINDIR%/font/<...> -#define CGUI_MTA_DEFAULT_FONT_BOLD "tahomabd.ttf" // %WINDIR%/font/<...> -#define CGUI_MTA_CLEAR_FONT "verdana.ttf" // %WINDIR%/font/<...> - -#define CGUI_MTA_DEFAULT_REG "Tahoma (TrueType)" -#define CGUI_MTA_DEFAULT_REG_BOLD "Tahoma Bold (TrueType)" -#define CGUI_MTA_CLEAR_REG "Verdana (TrueType)" - -#define CGUI_MTA_SUBSTITUTE_FONT "cgui/unifont.ttf" // GTA/MTA/<...> -#define CGUI_MTA_SANS_FONT "cgui/sans.ttf" // GTA/MTA/<...> -#define CGUI_SA_HEADER_FONT "cgui/saheader.ttf" // GTA/MTA/<...> -#define CGUI_SA_GOTHIC_FONT "cgui/sagothic.ttf" // GTA/MTA/<...> -#define CGUI_SA_HEADER_SIZE 26 -#define CGUI_SA_GOTHIC_SIZE 47 -#define CGUI_MTA_SANS_FONT_SIZE 9 - -CGUI_Impl::CGUI_Impl(IDirect3DDevice9* pDevice) : - m_HasSchemeLoaded(false), - m_fCurrentServerCursorAlpha(1.0f), - m_pDevice(pDevice), - m_pRenderer(nullptr), - m_pSystem(nullptr), - m_pFontManager(nullptr), - m_pImageSetManager(nullptr), - m_pSchemeManager(nullptr), - m_pWindowManager(nullptr), - m_pTop(nullptr), - m_pCursor(nullptr), - m_pDefaultFont(nullptr), - m_pSmallFont(nullptr), - m_pBoldFont(nullptr), - m_pClearFont(nullptr), - m_pSAHeaderFont(nullptr), - m_pSAGothicFont(nullptr), - m_pSansFont(nullptr), - m_pUniFont(nullptr), - m_nextRedrawHandle(1), - m_ulPreviousUnique(0), - m_eInputMode(INPUTMODE_NO_BINDS_ON_EDIT), - m_Channel(INPUT_CORE) +#define CGUI_MTA_DEFAULT_FONT "tahoma.ttf" // %WINDIR%/font/<...> +#define CGUI_MTA_DEFAULT_FONT_BOLD "tahomabd.ttf" // %WINDIR%/font/<...> +#define CGUI_MTA_CLEAR_FONT "verdana.ttf" // %WINDIR%/font/<...> + +#define CGUI_MTA_DEFAULT_REG "Tahoma (TrueType)" +#define CGUI_MTA_DEFAULT_REG_BOLD "Tahoma Bold (TrueType)" +#define CGUI_MTA_CLEAR_REG "Verdana (TrueType)" + +#define CGUI_MTA_SUBSTITUTE_FONT "cgui/unifont.ttf" // GTA/MTA/<...> +#define CGUI_MTA_SANS_FONT "cgui/sans.ttf" // GTA/MTA/<...> +#define CGUI_SA_HEADER_FONT "cgui/saheader.ttf" // GTA/MTA/<...> +#define CGUI_SA_GOTHIC_FONT "cgui/sagothic.ttf" // GTA/MTA/<...> +#define CGUI_SA_HEADER_SIZE 26 +#define CGUI_SA_GOTHIC_SIZE 47 +#define CGUI_MTA_SANS_FONT_SIZE 9 + +CGUI_Impl::CGUI_Impl(IDirect3DDevice9* pDevice) + : m_HasSchemeLoaded(false), + m_fCurrentServerCursorAlpha(1.0f), + m_pDevice(pDevice), + m_pRenderer(nullptr), + m_pSystem(nullptr), + m_pFontManager(nullptr), + m_pImageSetManager(nullptr), + m_pSchemeManager(nullptr), + m_pWindowManager(nullptr), + m_pTop(nullptr), + m_pCursor(nullptr), + m_pDefaultFont(nullptr), + m_pSmallFont(nullptr), + m_pBoldFont(nullptr), + m_pClearFont(nullptr), + m_pSAHeaderFont(nullptr), + m_pSAGothicFont(nullptr), + m_pSansFont(nullptr), + m_pUniFont(nullptr), + m_nextRedrawHandle(1), + m_ulPreviousUnique(0), + m_eInputMode(INPUTMODE_NO_BINDS_ON_EDIT), + m_Channel(INPUT_CORE) { m_RenderOkTimer.SetMaxIncrement(100); @@ -142,7 +142,7 @@ CGUI_Impl::~CGUI_Impl() delete m_pSAHeaderFont; delete m_pSAGothicFont; delete m_pSansFont; - + // Clean up CEGUI system - this automatically deletes the renderer delete CEGUI::System::getSingletonPtr(); // DO NOT delete m_pRenderer - it's already deleted by System destructor @@ -384,13 +384,13 @@ eInputMode CGUI_Impl::GetGUIInputMode() CEGUI::String CGUI_Impl::GetUTFString(const char* szInput) { - CEGUI::String strUTF = (CEGUI::utf8*)szInput; // Convert into a CEGUI String + CEGUI::String strUTF = (CEGUI::utf8*)szInput; // Convert into a CEGUI String return strUTF; } CEGUI::String CGUI_Impl::GetUTFString(const std::string& strInput) { - CEGUI::String strUTF = (CEGUI::utf8*)strInput.c_str(); // Convert into a CEGUI String + CEGUI::String strUTF = (CEGUI::utf8*)strInput.c_str(); // Convert into a CEGUI String return strUTF; } @@ -860,7 +860,7 @@ bool CGUI_Impl::Event_KeyDown(const CEGUI::EventArgs& Args) CEGUI::Window* Wnd = reinterpret_cast(KeyboardArgs.window); if (Wnd->getType() == "CGUI/Editbox" || Wnd->getType() == "CGUI/MultiLineEditbox") { - SString clipboardUtf8 = SharedUtil::GetClipboardText(); + SString clipboardUtf8 = SharedUtil::GetClipboardText(); std::wstring strClipboardText; try { @@ -1416,13 +1416,13 @@ bool CGUI_Impl::Event_RedrawRequested(const CEGUI::EventArgs& Args) // Get the master window (walks up parent hierarchy for child widgets) CEGUI::Window* pMasterWindow = GetMasterWindow(e.window); - + CGUIElement* pElement = reinterpret_cast(pMasterWindow->getUserData()); if (pElement) { AddToRedrawQueue(pElement); } - + // Immediate redraw of event source for visual responsiveness e.window->forceRedraw(); diff --git a/Client/gui/CGUI_Impl.h b/Client/gui/CGUI_Impl.h index cc564d3593c..b6f1da31e16 100644 --- a/Client/gui/CGUI_Impl.h +++ b/Client/gui/CGUI_Impl.h @@ -58,7 +58,7 @@ namespace CEGUI class EventArgs; class GUISheet; typedef GUISheet DefaultWindow; -} // namespace CEGUI +} class CGUI_Impl : public CGUI, public CGUITabList { @@ -87,7 +87,7 @@ class CGUI_Impl : public CGUI, public CGUITabList eInputMode GetGUIInputMode(); static CEGUI::String GetUTFString(const char* szInput); static CEGUI::String GetUTFString(const std::string& strInput); - static CEGUI::String GetUTFString(const CEGUI::String& strInput); // Not defined + static CEGUI::String GetUTFString(const CEGUI::String& strInput); // Not defined // CGUIMessageBox* CreateMessageBox(const char* szTitle, const char* szMessage, unsigned int uiFlags); @@ -331,9 +331,9 @@ class CGUI_Impl : public CGUI, public CGUITabList CGUIFont_Impl* m_pSansFont; CGUIFont_Impl* m_pUniFont; - std::unordered_set m_RedrawQueue; + std::unordered_set m_RedrawQueue; std::unordered_map m_RedrawRegistry; - std::uint32_t m_nextRedrawHandle; + std::uint32_t m_nextRedrawHandle; std::uint32_t RegisterRedrawHandle(CGUIElement_Impl* pElement); void ReleaseRedrawHandle(std::uint32_t handle); diff --git a/Client/launch/Main.cpp b/Client/launch/Main.cpp index 6a6e3d51578..391dbe36356 100644 --- a/Client/launch/Main.cpp +++ b/Client/launch/Main.cpp @@ -12,21 +12,21 @@ #include "StdInc.h" // C++ STL -#include // std::array for safe command buffer -#include // std::bit_cast for safe function pointer conversion -#include // std::expected/std::unexpected for error handling -#include // std::format for string formatting -#include // std::ranges::copy/copy_n for safe copying -#include // std::span for memory view with bounds checking -#include // std::string_view for string parameters and constants -#include // std::is_trivially_copyable_v for compile-time checks -#include // std::forward for perfect forwarding +#include // std::array for safe command buffer +#include // std::bit_cast for safe function pointer conversion +#include // std::expected/std::unexpected for error handling +#include // std::format for string formatting +#include // std::ranges::copy/copy_n for safe copying +#include // std::span for memory view with bounds checking +#include // std::string_view for string parameters and constants +#include // std::is_trivially_copyable_v for compile-time checks +#include // std::forward for perfect forwarding // C STL -#include // std::strlen for C string length +#include // std::strlen for C string length // Platform-specific headers -#include // GetModuleInformation, MODULEINFO +#include // GetModuleInformation, MODULEINFO /* IMPORTANT @@ -43,17 +43,17 @@ namespace mta::launcher { enum class LoadResult : std::uint32_t { - Success = 0, - PathError = 1, - LoadError = 2, + Success = 0, + PathError = 1, + LoadError = 2, FunctionError = 3 }; enum class DllLoadError : std::uint32_t { FileNotFound = 1, - InvalidPath = 2, - LoadFailed = 3 + InvalidPath = 2, + LoadFailed = 3 }; // concepts for type safety @@ -71,20 +71,15 @@ namespace mta::launcher { DWORD saved_error_; -public: - LastErrorPreserver() noexcept : saved_error_(GetLastError()) - { - } - - ~LastErrorPreserver() noexcept - { - SetLastError(saved_error_); - } - - LastErrorPreserver(const LastErrorPreserver&) = delete; + public: + LastErrorPreserver() noexcept : saved_error_(GetLastError()) {} + + ~LastErrorPreserver() noexcept { SetLastError(saved_error_); } + + LastErrorPreserver(const LastErrorPreserver&) = delete; LastErrorPreserver& operator=(const LastErrorPreserver&) = delete; - LastErrorPreserver(LastErrorPreserver&&) = delete; - LastErrorPreserver& operator=(LastErrorPreserver&&) = delete; + LastErrorPreserver(LastErrorPreserver&&) = delete; + LastErrorPreserver& operator=(LastErrorPreserver&&) = delete; }; // RAII scope_exit with perfect forwarding @@ -93,19 +88,14 @@ namespace mta::launcher { F f; - explicit scope_exit(F&& func) noexcept : f(std::forward(func)) - { - } - - ~scope_exit() noexcept - { - f(); - } + explicit scope_exit(F&& func) noexcept : f(std::forward(func)) {} + + ~scope_exit() noexcept { f(); } - scope_exit(const scope_exit&) = delete; + scope_exit(const scope_exit&) = delete; scope_exit& operator=(const scope_exit&) = delete; - scope_exit(scope_exit&&) = delete; - scope_exit& operator=(scope_exit&&) = delete; + scope_exit(scope_exit&&) = delete; + scope_exit& operator=(scope_exit&&) = delete; }; template @@ -120,7 +110,7 @@ namespace mta::launcher std::wstring original_dir; bool changed = false; -public: + public: DllDirectoryGuard() { LastErrorPreserver error_guard; @@ -129,10 +119,12 @@ namespace mta::launcher { try { - original_dir.resize_and_overwrite(len, [](wchar_t* buf, std::size_t n) -> std::size_t { - DWORD copied = GetDllDirectoryW(static_cast(n), buf); - return copied < n ? copied : 0; - }); + original_dir.resize_and_overwrite(len, + [](wchar_t* buf, std::size_t n) -> std::size_t + { + DWORD copied = GetDllDirectoryW(static_cast(n), buf); + return copied < n ? copied : 0; + }); } catch (...) { @@ -159,10 +151,10 @@ namespace mta::launcher SetDllDirectoryW(original_dir.empty() ? nullptr : original_dir.c_str()); } - DllDirectoryGuard(const DllDirectoryGuard&) = delete; + DllDirectoryGuard(const DllDirectoryGuard&) = delete; DllDirectoryGuard& operator=(const DllDirectoryGuard&) = delete; - DllDirectoryGuard(DllDirectoryGuard&&) = delete; - DllDirectoryGuard& operator=(DllDirectoryGuard&&) = delete; + DllDirectoryGuard(DllDirectoryGuard&&) = delete; + DllDirectoryGuard& operator=(DllDirectoryGuard&&) = delete; }; // COM initialization with error handling @@ -189,15 +181,17 @@ namespace mta::launcher std::wstring dll_name_w; try { - dll_name_w.resize_and_overwrite(dll_name.size() * 2, [&dll_name](wchar_t* buf, std::size_t n) -> std::size_t { - SString temp{dll_name.data(), dll_name.size()}; - WString wide = FromUTF8(temp); - if (wide.empty()) - return 0; - std::size_t len = std::min(n, wide.length()); - std::ranges::copy_n(wide.c_str(), len, buf); - return len; - }); + dll_name_w.resize_and_overwrite(dll_name.size() * 2, + [&dll_name](wchar_t* buf, std::size_t n) -> std::size_t + { + SString temp{dll_name.data(), dll_name.size()}; + WString wide = FromUTF8(temp); + if (wide.empty()) + return 0; + std::size_t len = std::min(n, wide.length()); + std::ranges::copy_n(wide.c_str(), len, buf); + return len; + }); } catch (...) { @@ -249,7 +243,7 @@ namespace mta::launcher } // Command line handling - constexpr std::size_t MAX_CMD = 8192; + constexpr std::size_t MAX_CMD = 8192; static_assert(ValidBufferSize); std::array safe_cmd{}; @@ -314,7 +308,7 @@ namespace mta::launcher AddReportLog(5730, std::format("Launcher Main: MTA directory not found from: '{}'", launch_path)); return std::unexpected(LoadResult::PathError); } -} // namespace mta::launcher +} // namespace mta::launcher int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { @@ -337,7 +331,7 @@ int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _ [[maybe_unused]] HRESULT hr = SetCurrentProcessExplicitAppUserModelID(L"Multi Theft Auto " MTA_STR(MTASA_VERSION_MAJOR) L"." MTA_STR(MTASA_VERSION_MINOR)); // Path discovery - SString launch_path = GetLaunchPath(); + SString launch_path = GetLaunchPath(); auto mta_path_result = FindMtaPath(launch_path); if (!mta_path_result) [[unlikely]] @@ -356,7 +350,7 @@ int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _ if (!module_result) [[unlikely]] { DWORD error = GetLastError(); - SString msg = std::format("Launcher Main: Failed to load: '{}'\n\n{}", dll_path, GetSystemErrorMessage(error)); + SString msg = std::format("Launcher Main: Failed to load: '{}'\n\n{}", dll_path, GetSystemErrorMessage(error)); AddReportLog(5711, msg); // Pattern matching @@ -378,10 +372,12 @@ int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _ HMODULE module = module_result.value(); // RAII module cleanup - auto module_cleanup = make_scope_exit([module]() noexcept { - if (module) - FreeLibrary(module); - }); + auto module_cleanup = make_scope_exit( + [module]() noexcept + { + if (module) + FreeLibrary(module); + }); // Execution with concepts auto exec_result = ExecuteDoWinMain(module, hInstance, hPrevInstance, lpCmdLine, nCmdShow); diff --git a/Client/launch/Multi Theft Auto.h b/Client/launch/Multi Theft Auto.h index 68c2c2ad284..8242869421a 100644 --- a/Client/launch/Multi Theft Auto.h +++ b/Client/launch/Multi Theft Auto.h @@ -1,5 +1,5 @@ ///////////////////////////////////////////////////////////////////////////// // Header File for : Multi Theft Auto -#define ID_ICON 101 +#define ID_ICON 101 ///////////////////////////////////////////////////////////////////////////// diff --git a/Client/launch/resource.h b/Client/launch/resource.h index fc507efb3f7..18e8c03853d 100644 --- a/Client/launch/resource.h +++ b/Client/launch/resource.h @@ -2,15 +2,15 @@ // Microsoft Visual C++ generated include file. // Used by launch.rc // -#define IDI_ICON1 110 +#define IDI_ICON1 110 // Next default values for new objects // #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 115 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1010 -#define _APS_NEXT_SYMED_VALUE 101 -#endif + #ifndef APSTUDIO_READONLY_SYMBOLS + #define _APS_NEXT_RESOURCE_VALUE 115 + #define _APS_NEXT_COMMAND_VALUE 40001 + #define _APS_NEXT_CONTROL_VALUE 1010 + #define _APS_NEXT_SYMED_VALUE 101 + #endif #endif diff --git a/Client/loader-proxy/main.cpp b/Client/loader-proxy/main.cpp index 9652ad87ac1..25b5fb9fcbe 100644 --- a/Client/loader-proxy/main.cpp +++ b/Client/loader-proxy/main.cpp @@ -123,7 +123,7 @@ VOID OnGameLaunch() // Log current working directory wchar_t inheritedCwd[32768]{}; - DWORD inheritedCwdLen = GetCurrentDirectoryW(32768, inheritedCwd); + DWORD inheritedCwdLen = GetCurrentDirectoryW(32768, inheritedCwd); if (inheritedCwdLen > 0) { AddLaunchLog("loader-proxy OnGameLaunch - Inherited CWD: %S", inheritedCwd); @@ -139,34 +139,34 @@ VOID OnGameLaunch() // - Read from gta_path.txt file written by parent process // - Check MTA_GTA_PATH environment variable // - Use current_path() as fallback - + // Parse CEF command-line switch std::array gtaPathFromCmdLine{}; - DWORD cmdLinePathLen = 0; + DWORD cmdLinePathLen = 0; std::array mtaBasePathFromCmdLine{}; - DWORD mtaBasePathLen = 0; + DWORD mtaBasePathLen = 0; { const LPWSTR cmdLine = GetCommandLineW(); if (cmdLine) { AddLaunchLog("loader-proxy OnGameLaunch - Full command line: %S", cmdLine); - + // Parse for --mta-gta-path= // CEF command-line format: --switch=value or --switch=\"value with spaces\" constexpr std::wstring_view switchPrefix = L"--mta-gta-path="; if (const wchar_t* switchPos = wcsstr(cmdLine, switchPrefix.data())) { const wchar_t* const pathStartBase = switchPos + switchPrefix.length(); - const wchar_t* pathStart = pathStartBase; - + const wchar_t* pathStart = pathStartBase; + // Skip opening quote if present if (*pathStart == L'"') pathStart++; - + // Find end of path (closing quote or space) const wchar_t* pathEnd = pathStart; - const bool isQuoted = (pathStartBase[0] == L'"'); - + const bool isQuoted = (pathStartBase[0] == L'"'); + while (*pathEnd != L'\0') { if (isQuoted && *pathEnd == L'"') @@ -179,7 +179,7 @@ VOID OnGameLaunch() } pathEnd++; } - + const size_t pathLen = pathEnd - pathStart; if (pathLen > 0 && pathLen < gtaPathFromCmdLine.size()) { @@ -202,16 +202,16 @@ VOID OnGameLaunch() if (const wchar_t* mtaSwitchPos = wcsstr(cmdLine, mtaSwitchPrefix.data())) { const wchar_t* const mtaPathStartBase = mtaSwitchPos + mtaSwitchPrefix.length(); - const wchar_t* mtaPathStart = mtaPathStartBase; - + const wchar_t* mtaPathStart = mtaPathStartBase; + // Skip opening quote if present if (*mtaPathStart == L'"') mtaPathStart++; - + // Find end of path (closing quote or space) const wchar_t* mtaPathEnd = mtaPathStart; - const bool mtaIsQuoted = (mtaPathStartBase[0] == L'"'); - + const bool mtaIsQuoted = (mtaPathStartBase[0] == L'"'); + while (*mtaPathEnd != L'\0') { if (mtaIsQuoted && *mtaPathEnd == L'"') @@ -224,7 +224,7 @@ VOID OnGameLaunch() } mtaPathEnd++; } - + const size_t mtaPathLength = mtaPathEnd - mtaPathStart; if (mtaPathLength > 0 && mtaPathLength < mtaBasePathFromCmdLine.size()) { @@ -235,15 +235,15 @@ VOID OnGameLaunch() } } } - + // Read from file std::array gtaPathFromFile{}; - DWORD filePathLen = 0; - const fs::path gtaPathFile = fs::current_path(ec) / L".." / L".." / L"MTA" / L"CEF" / L"gta_path.txt"; + DWORD filePathLen = 0; + const fs::path gtaPathFile = fs::current_path(ec) / L".." / L".." / L"MTA" / L"CEF" / L"gta_path.txt"; if (FILE* pFile = nullptr; _wfopen_s(&pFile, gtaPathFile.c_str(), L"r") == 0 && pFile) { std::array buffer{}; - const size_t bytesRead = fread(buffer.data(), 1, buffer.size() - 1, pFile); + const size_t bytesRead = fread(buffer.data(), 1, buffer.size() - 1, pFile); fclose(pFile); if (bytesRead > 0) { @@ -255,12 +255,13 @@ VOID OnGameLaunch() } } } - + // Check environment variable std::array gtaPathFromEnv{}; - const DWORD envLen = GetEnvironmentVariableW(L"MTA_GTA_PATH", gtaPathFromEnv.data(), static_cast(gtaPathFromEnv.size())); - - const fs::path gtaDirectory = [&]() -> fs::path { + const DWORD envLen = GetEnvironmentVariableW(L"MTA_GTA_PATH", gtaPathFromEnv.data(), static_cast(gtaPathFromEnv.size())); + + const fs::path gtaDirectory = [&]() -> fs::path + { // CEF command-line switch if (cmdLinePathLen > 0 && cmdLinePathLen < gtaPathFromCmdLine.size()) { @@ -382,7 +383,8 @@ VOID OnGameLaunch() // Check if the MTA subdirectory exists. // Use --mta-base-path from command-line if available, // otherwise fall back to parent process path - const fs::path mtaRootDirectory = [&]() -> fs::path { + const fs::path mtaRootDirectory = [&]() -> fs::path + { if (bIsCefSubprocess && mtaBasePathLen > 0 && mtaBasePathLen < mtaBasePathFromCmdLine.size()) { AddLaunchLog("Using MTA base path from CEF command-line switch: %S", mtaBasePathFromCmdLine.data()); diff --git a/Client/loader/CInstallManager.cpp b/Client/loader/CInstallManager.cpp index 3b3f790a2b2..b1eb0880474 100644 --- a/Client/loader/CInstallManager.cpp +++ b/Client/loader/CInstallManager.cpp @@ -46,20 +46,32 @@ namespace } // Comms between 'Admin' and 'User' processes - void SendStringToUserProcess(const SString& strText) { SetApplicationSetting("admin2user_comms", strText); } + void SendStringToUserProcess(const SString& strText) + { + SetApplicationSetting("admin2user_comms", strText); + } - SString ReceiveStringFromAdminProcess() { return GetApplicationSetting("admin2user_comms"); } + SString ReceiveStringFromAdminProcess() + { + return GetApplicationSetting("admin2user_comms"); + } - bool IsBlockingUserProcess() { return GetApplicationSetting("admin2user_comms") == "user_waiting"; } + bool IsBlockingUserProcess() + { + return GetApplicationSetting("admin2user_comms") == "user_waiting"; + } - void SetIsBlockingUserProcess() { SetApplicationSetting("admin2user_comms", "user_waiting"); } + void SetIsBlockingUserProcess() + { + SetApplicationSetting("admin2user_comms", "user_waiting"); + } void ClearIsBlockingUserProcess() { if (IsBlockingUserProcess()) SetApplicationSetting("admin2user_comms", ""); } -} // namespace +} // namespace ////////////////////////////////////////////////////////// // @@ -86,124 +98,124 @@ CInstallManager* GetInstallManager() ////////////////////////////////////////////////////////// void CInstallManager::InitSequencer() { - #define CR "\n" - SString strSource = CR "initial: " // *** Starts here by default - CR " CALL CheckOnRestartCommand " ////// Start of 'update game' ////// - CR " IF LastResult != ok GOTO update_end: " // - CR " " // - CR " CALL MaybeSwitchToTempExe " // If update files comes with an .exe, switch to that for the install - CR " " // - CR "copy_files: " // - CR " CALL InstallFiles " // Try to install update files - CR " IF LastResult == ok GOTO update_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If install failed, try as admin - CR " " // - CR "copy_files_admin: " // - CR " CALL InstallFiles " // Try to install update files - CR " IF LastResult == ok GOTO update_end_admin: " // - CR " " // - CR " CALL ShowCopyFailDialog " // If install failed as admin, show message box - CR " IF LastResult == retry GOTO copy_files_admin: " // - CR " " // - CR "update_end_admin: " // - CR " CALL ChangeFromAdmin " // - CR " " // - CR "update_end: " ////// End of 'update game' ////// - CR " CALL SwitchBackFromTempExe " // - CR " " // - CR "newlayout_check:" ////// Start of 'new layout check' ////// - CR " CALL ProcessLayoutChecks " // - CR " IF LastResult == ok GOTO newlayout_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO newlayout_check: " // - CR " CALL Quit " // - CR " " // - CR "newlayout_end: " ////// End of 'new layout check' ////// - CR " " // - CR "langfile_check: " ////// Start of 'Lang file fix' ////// - CR " CALL ProcessLangFileChecks " // Make changes to comply with requirements - CR " IF LastResult == ok GOTO langfile_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO langfile_check: " // - CR " CALL Quit " // - CR " " // - CR "langfile_end: " ////// End of 'Lang file fix' ////// - CR " " // - CR "prepare_launch_location:" ////// Start of 'prepare launch location' ////// - CR " CALL PrepareLaunchLocation " // - CR " IF LastResult == ok GOTO prepare_launch_location_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO prepare_launch_location: " // - CR " CALL Quit " // - CR " " // - CR "prepare_launch_location_end:" ////// End of 'prepare launch location' ////// - CR " " // - CR "gta_patch_check:" ////// Start of 'gta patch check' ////// - CR " CALL ProcessGtaPatchCheck " // - CR " IF LastResult != ok GOTO do_quit: " // Switching to admin has zero impact - CR " " // - CR "gta_patch_check_end:" ////// End of 'gta patch check' ////// - CR " " // - CR "gta_dll_check:" ////// Start of 'gta dll check' ////// - CR " CALL ProcessGtaDllCheck " // - CR " IF LastResult == ok GOTO gta_dll_end: " // - CR " IF LastResult == quit GOTO do_quit: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO gta_dll_check: " // - CR " CALL Quit " // - CR " " // - CR "gta_dll_end: " ////// End of 'gta dll check' ////// - CR " " // - CR "gta_version_check:" ////// Start of 'gta version check' ////// - CR " CALL ProcessGtaVersionCheck " // - CR " IF LastResult == ok GOTO gta_version_end: " // - CR " IF LastResult == quit GOTO do_quit: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO gta_version_check: " // - CR " CALL Quit " // - CR " " // - CR "gta_version_end: " ////// End of 'gta version check' ////// - CR " " // - CR "service_check: " ////// Start of 'Service checks' ////// - CR " CALL ProcessServiceChecks " // Make changes to comply with service requirements - CR " IF LastResult == ok GOTO service_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO service_check: " // - CR " CALL Quit " // - CR " " // - CR "service_end: " ////// End of 'Service checks' ////// - CR " " // - CR "appcompat_check: " ////// Start of 'AppCompat checks' ////// - CR " CALL ProcessAppCompatChecks " // Make changes to comply with appcompat requirements - CR " IF LastResult == ok GOTO appcompat_end: " // - CR " " // - CR " CALL ChangeToAdmin " // If changes failed, try as admin - CR " IF LastResult == ok GOTO appcompat_check: " // - CR " CALL Quit " // - CR " " // - CR "appcompat_end: " ////// End of 'AppCompat checks' ////// - CR " " // - CR " CALL ChangeFromAdmin " // - CR " CALL InstallNewsItems " // Install pending news - CR " CALL CheckForWerCrash " // Check for fail-fast crashes detected by WER - CR " IF LastResult == crashed GOTO crashed: " // WER crash detected -> show dialog - CR " GOTO launch: " // - CR " " // - CR "do_quit: " // Quit ensuring termination of both user & admin instance - CR " CALL ChangeFromAdmin " // - CR " CALL Quit " // - CR " " // - CR "crashed: " // *** Starts here when install_stage=crashed is passed - CR " CALL ShowCrashFailDialog " // Shows immediate crash dialog from fresh launcher process - CR " IF LastResult == ok GOTO initial: " // User clicked "Yes" to restart -> go to normal launch - CR " CALL Quit " // User clicked "No" -> exit launcher +#define CR "\n" + SString strSource = CR "initial: " // *** Starts here by default + CR " CALL CheckOnRestartCommand " ////// Start of 'update game' ////// + CR " IF LastResult != ok GOTO update_end: " // + CR " " // + CR " CALL MaybeSwitchToTempExe " // If update files comes with an .exe, switch to that for the install + CR " " // + CR "copy_files: " // + CR " CALL InstallFiles " // Try to install update files + CR " IF LastResult == ok GOTO update_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If install failed, try as admin + CR " " // + CR "copy_files_admin: " // + CR " CALL InstallFiles " // Try to install update files + CR " IF LastResult == ok GOTO update_end_admin: " // + CR " " // + CR " CALL ShowCopyFailDialog " // If install failed as admin, show message box + CR " IF LastResult == retry GOTO copy_files_admin: " // + CR " " // + CR "update_end_admin: " // + CR " CALL ChangeFromAdmin " // + CR " " // + CR "update_end: " ////// End of 'update game' ////// + CR " CALL SwitchBackFromTempExe " // + CR " " // + CR "newlayout_check:" ////// Start of 'new layout check' ////// + CR " CALL ProcessLayoutChecks " // + CR " IF LastResult == ok GOTO newlayout_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO newlayout_check: " // + CR " CALL Quit " // + CR " " // + CR "newlayout_end: " ////// End of 'new layout check' ////// + CR " " // + CR "langfile_check: " ////// Start of 'Lang file fix' ////// + CR " CALL ProcessLangFileChecks " // Make changes to comply with requirements + CR " IF LastResult == ok GOTO langfile_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO langfile_check: " // + CR " CALL Quit " // + CR " " // + CR "langfile_end: " ////// End of 'Lang file fix' ////// + CR " " // + CR "prepare_launch_location:" ////// Start of 'prepare launch location' ////// + CR " CALL PrepareLaunchLocation " // + CR " IF LastResult == ok GOTO prepare_launch_location_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO prepare_launch_location: " // + CR " CALL Quit " // + CR " " // + CR "prepare_launch_location_end:" ////// End of 'prepare launch location' ////// + CR " " // + CR "gta_patch_check:" ////// Start of 'gta patch check' ////// + CR " CALL ProcessGtaPatchCheck " // + CR " IF LastResult != ok GOTO do_quit: " // Switching to admin has zero impact + CR " " // + CR "gta_patch_check_end:" ////// End of 'gta patch check' ////// + CR " " // + CR "gta_dll_check:" ////// Start of 'gta dll check' ////// + CR " CALL ProcessGtaDllCheck " // + CR " IF LastResult == ok GOTO gta_dll_end: " // + CR " IF LastResult == quit GOTO do_quit: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO gta_dll_check: " // + CR " CALL Quit " // + CR " " // + CR "gta_dll_end: " ////// End of 'gta dll check' ////// + CR " " // + CR "gta_version_check:" ////// Start of 'gta version check' ////// + CR " CALL ProcessGtaVersionCheck " // + CR " IF LastResult == ok GOTO gta_version_end: " // + CR " IF LastResult == quit GOTO do_quit: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO gta_version_check: " // + CR " CALL Quit " // + CR " " // + CR "gta_version_end: " ////// End of 'gta version check' ////// + CR " " // + CR "service_check: " ////// Start of 'Service checks' ////// + CR " CALL ProcessServiceChecks " // Make changes to comply with service requirements + CR " IF LastResult == ok GOTO service_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO service_check: " // + CR " CALL Quit " // + CR " " // + CR "service_end: " ////// End of 'Service checks' ////// + CR " " // + CR "appcompat_check: " ////// Start of 'AppCompat checks' ////// + CR " CALL ProcessAppCompatChecks " // Make changes to comply with appcompat requirements + CR " IF LastResult == ok GOTO appcompat_end: " // + CR " " // + CR " CALL ChangeToAdmin " // If changes failed, try as admin + CR " IF LastResult == ok GOTO appcompat_check: " // + CR " CALL Quit " // + CR " " // + CR "appcompat_end: " ////// End of 'AppCompat checks' ////// + CR " " // + CR " CALL ChangeFromAdmin " // + CR " CALL InstallNewsItems " // Install pending news + CR " CALL CheckForWerCrash " // Check for fail-fast crashes detected by WER + CR " IF LastResult == crashed GOTO crashed: " // WER crash detected -> show dialog + CR " GOTO launch: " // + CR " " // + CR "do_quit: " // Quit ensuring termination of both user & admin instance + CR " CALL ChangeFromAdmin " // + CR " CALL Quit " // + CR " " // + CR "crashed: " // *** Starts here when install_stage=crashed is passed + CR " CALL ShowCrashFailDialog " // Shows immediate crash dialog from fresh launcher process + CR " IF LastResult == ok GOTO initial: " // User clicked "Yes" to restart -> go to normal launch + CR " CALL Quit " // User clicked "No" -> exit launcher // // Flow when game crashes: // 1. core.dll crash handler saves crash info to settings @@ -211,7 +223,7 @@ void CInstallManager::InitSequencer() // 3. New launcher lands HERE at "crashed:" label // 4. Shows dialog with crash info from settings // 5. User chooses restart or quit - CR " " // + CR " " // CR "launch: "; m_pSequencer = new CSequencerType(); @@ -384,7 +396,7 @@ SString CInstallManager::_ChangeToAdmin() UpdateSettingsForReportLog(); RestoreSequencerFromSnapshot(ReceiveStringFromAdminProcess()); ClearIsBlockingUserProcess(); - return "ok"; // This will appear as the result for _ChangeFromAdmin + return "ok"; // This will appear as the result for _ChangeFromAdmin } CreateSingleInstanceMutex(); ClearIsBlockingUserProcess(); @@ -454,7 +466,7 @@ SString CInstallManager::_ShowCrashFailDialog() SetApplicationSetting("diagnostics", "last-crash-code", ""); const bool debuggerCapturePending = (GetApplicationSetting("diagnostics", "debugger-crash-capture") == "1"); - + if (strReason == "direct3ddevice-reset") { strMessage += _("** The crash was caused by a graphics driver error **\n\n** Please update your graphics drivers **"); @@ -532,10 +544,9 @@ SString CInstallManager::_CheckForWerCrash() } const SString existingReason = GetApplicationSetting("diagnostics", "last-crash-reason"); - const DWORD existingCode = static_cast(GetApplicationSettingInt("diagnostics", "last-crash-code")); + const DWORD existingCode = static_cast(GetApplicationSettingInt("diagnostics", "last-crash-code")); - if ((existingCode == EXCEPTION_STACK_BUFFER_OVERRUN || existingCode == EXCEPTION_HEAP_CORRUPTION) - && !existingReason.empty()) + if ((existingCode == EXCEPTION_STACK_BUFFER_OVERRUN || existingCode == EXCEPTION_HEAP_CORRUPTION) && !existingReason.empty()) { OutputDebugStringA(SString("_CheckForWerCrash: Already have crash info, code=0x%08X\n", existingCode)); bWerCrashAlreadyHandled = true; @@ -558,8 +569,7 @@ SString CInstallManager::_CheckForWerCrash() break; const SString fullPath = PathJoin(werDumpPath, dumpFile); - HANDLE hFile = CreateFileA(fullPath, GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE hFile = CreateFileA(fullPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) break; @@ -569,15 +579,15 @@ SString CInstallManager::_CheckForWerCrash() if (isRecent) { - const auto regs = WerCrash::ExtractRegistersFromMinidump(fullPath); + const auto regs = WerCrash::ExtractRegistersFromMinidump(fullPath); const DWORD exceptionCode = regs.valid ? regs.exceptionCode : EXCEPTION_STACK_BUFFER_OVERRUN; const char* exceptionName = (exceptionCode == EXCEPTION_STACK_BUFFER_OVERRUN) ? "Stack Buffer Overrun" - : (exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" - : "Security Exception"; + : (exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" + : "Security Exception"; SString moduleName = "unknown"; - DWORD moduleOffset = 0; - DWORD idaAddress = 0; + DWORD moduleOffset = 0; + DWORD idaAddress = 0; if (regs.valid) { const auto resolved = WerCrash::ResolveAddressFromMinidump(fullPath, regs.eip); @@ -607,8 +617,7 @@ SString CInstallManager::_CheckForWerCrash() SYSTEMTIME st{}; GetLocalTime(&st); - const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, - *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); + const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); const SString crashReason = SString( "Security Exception - %s (0x%08X) detected.\n" @@ -617,11 +626,7 @@ SString CInstallManager::_CheckForWerCrash() "IDA Address: %s\n" "This crash bypassed normal crash handling.\n" "Crash dump: %s", - exceptionName, exceptionCode, - moduleName.c_str(), - moduleOffset, - idaAddressStr.c_str(), - ExtractFilename(usedDumpPath).c_str()); + exceptionName, exceptionCode, moduleName.c_str(), moduleOffset, idaAddressStr.c_str(), ExtractFilename(usedDumpPath).c_str()); SString coreLogEntry; coreLogEntry += SString("Version = %s\n", strMTAVersionFull.c_str()); @@ -637,9 +642,8 @@ SString CInstallManager::_CheckForWerCrash() "EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n" "EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n" "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n\n", - regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, - regs.edi, regs.ebp, regs.esp, regs.eip, regs.eflags, - regs.cs, regs.ds, regs.ss, regs.es, regs.fs, regs.gs); + regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, regs.edi, regs.ebp, regs.esp, regs.eip, regs.eflags, regs.cs, regs.ds, regs.ss, regs.es, + regs.fs, regs.gs); } if (!stackTrace.empty()) @@ -706,8 +710,7 @@ SString CInstallManager::_CheckForWerCrash() } const SString fullPath = PathJoin(werDumpPath, dumpFile); - HANDLE hFile = CreateFileA(fullPath, GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE hFile = CreateFileA(fullPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { @@ -722,15 +725,15 @@ SString CInstallManager::_CheckForWerCrash() { OutputDebugStringA(SString("_CheckForWerCrash: Processing WER dump file directly: %s\n", dumpFile.c_str())); - const auto regs = WerCrash::ExtractRegistersFromMinidump(fullPath); + const auto regs = WerCrash::ExtractRegistersFromMinidump(fullPath); const DWORD exceptionCode = regs.valid ? regs.exceptionCode : EXCEPTION_STACK_BUFFER_OVERRUN; const char* exceptionName = (exceptionCode == EXCEPTION_STACK_BUFFER_OVERRUN) ? "Stack Buffer Overrun" - : (exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" - : "Security Exception"; + : (exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" + : "Security Exception"; SString moduleName = "unknown"; - DWORD moduleOffset = 0; - DWORD idaAddress = 0; + DWORD moduleOffset = 0; + DWORD idaAddress = 0; if (regs.valid) { const auto resolved = WerCrash::ResolveAddressFromMinidump(fullPath, regs.eip); @@ -760,8 +763,7 @@ SString CInstallManager::_CheckForWerCrash() SYSTEMTIME st{}; GetLocalTime(&st); - const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, - *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); + const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); const SString crashReason = SString( "Security Exception - %s (0x%08X) detected.\n" @@ -770,11 +772,7 @@ SString CInstallManager::_CheckForWerCrash() "IDA Address: %s\n" "This crash bypassed normal crash handling.\n" "Crash dump: %s", - exceptionName, exceptionCode, - moduleName.c_str(), - moduleOffset, - idaAddressStr.c_str(), - ExtractFilename(usedDumpPath).c_str()); + exceptionName, exceptionCode, moduleName.c_str(), moduleOffset, idaAddressStr.c_str(), ExtractFilename(usedDumpPath).c_str()); SString coreLogEntry; coreLogEntry += SString("Version = %s\n", strMTAVersionFull.c_str()); @@ -790,9 +788,8 @@ SString CInstallManager::_CheckForWerCrash() "EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n" "EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n" "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n\n", - regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, - regs.edi, regs.ebp, regs.esp, regs.eip, regs.eflags, - regs.cs, regs.ds, regs.ss, regs.es, regs.fs, regs.gs); + regs.eax, regs.ebx, regs.ecx, regs.edx, regs.esi, regs.edi, regs.ebp, regs.esp, regs.eip, regs.eflags, regs.cs, regs.ds, regs.ss, + regs.es, regs.fs, regs.gs); } if (!stackTrace.empty()) @@ -844,13 +841,13 @@ SString CInstallManager::_CheckForWerCrash() } const char* exceptionName = (werInfo.exceptionCode == EXCEPTION_STACK_BUFFER_OVERRUN) ? "Stack Buffer Overrun" - : (werInfo.exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" - : "Security Exception"; + : (werInfo.exceptionCode == EXCEPTION_HEAP_CORRUPTION) ? "Heap Corruption" + : "Security Exception"; - OutputDebugStringA(SString("_CheckForWerCrash: DETECTED! code=0x%08X module=%s offset=%s\n", - werInfo.exceptionCode, werInfo.moduleName.c_str(), werInfo.faultOffset.c_str())); + OutputDebugStringA(SString("_CheckForWerCrash: DETECTED! code=0x%08X module=%s offset=%s\n", werInfo.exceptionCode, werInfo.moduleName.c_str(), + werInfo.faultOffset.c_str())); - DWORD offsetValue = 0; + DWORD offsetValue = 0; SString offsetStr; if (!werInfo.faultOffset.empty()) { @@ -867,8 +864,8 @@ SString CInstallManager::_CheckForWerCrash() offsetText = SString("0x%s", offsetStr.c_str()); constexpr DWORD IDA_DEFAULT_DLL_BASE = 0x10000000; - const DWORD idaAddress = IDA_DEFAULT_DLL_BASE + offsetValue; - SString idaAddressStr; + const DWORD idaAddress = IDA_DEFAULT_DLL_BASE + offsetValue; + SString idaAddressStr; if (offsetValue == 0) idaAddressStr = "unknown"; else @@ -886,33 +883,27 @@ SString CInstallManager::_CheckForWerCrash() SetApplicationSetting("diagnostics", "last-wer-dump-shown", dumpResult.sourceFilename); const SString crashReason = dumpResult.path.empty() - ? SString( - "Security Exception - %s (0x%08X) detected.\n" - "Module: %s\n" - "Offset: %s\n" - "IDA Address: %s (assuming default DLL base 0x10000000)\n" - "This crash bypassed normal crash handling.", - exceptionName, werInfo.exceptionCode, - werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), - offsetText.c_str(), - idaAddressStr.c_str()) - : SString( - "Security Exception - %s (0x%08X) detected.\n" - "Module: %s\n" - "Offset: %s\n" - "IDA Address: %s (assuming default DLL base 0x10000000)\n" - "Crash dump: %s", - exceptionName, werInfo.exceptionCode, - werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), - offsetText.c_str(), - idaAddressStr.c_str(), - ExtractFilename(dumpResult.path).c_str()); + ? SString( + "Security Exception - %s (0x%08X) detected.\n" + "Module: %s\n" + "Offset: %s\n" + "IDA Address: %s (assuming default DLL base 0x10000000)\n" + "This crash bypassed normal crash handling.", + exceptionName, werInfo.exceptionCode, werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), + offsetText.c_str(), idaAddressStr.c_str()) + : SString( + "Security Exception - %s (0x%08X) detected.\n" + "Module: %s\n" + "Offset: %s\n" + "IDA Address: %s (assuming default DLL base 0x10000000)\n" + "Crash dump: %s", + exceptionName, werInfo.exceptionCode, werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), + offsetText.c_str(), idaAddressStr.c_str(), ExtractFilename(dumpResult.path).c_str()); SYSTEMTIME st{}; GetLocalTime(&st); - const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, - *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); + const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); SString coreLogEntry; coreLogEntry += SString("Version = %s\n", strMTAVersionFull.c_str()); @@ -928,9 +919,9 @@ SString CInstallManager::_CheckForWerCrash() "EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n" "EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n" "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n\n", - dumpResult.regs.eax, dumpResult.regs.ebx, dumpResult.regs.ecx, dumpResult.regs.edx, dumpResult.regs.esi, - dumpResult.regs.edi, dumpResult.regs.ebp, dumpResult.regs.esp, dumpResult.regs.eip, dumpResult.regs.eflags, - dumpResult.regs.cs, dumpResult.regs.ds, dumpResult.regs.ss, dumpResult.regs.es, dumpResult.regs.fs, dumpResult.regs.gs); + dumpResult.regs.eax, dumpResult.regs.ebx, dumpResult.regs.ecx, dumpResult.regs.edx, dumpResult.regs.esi, dumpResult.regs.edi, dumpResult.regs.ebp, + dumpResult.regs.esp, dumpResult.regs.eip, dumpResult.regs.eflags, dumpResult.regs.cs, dumpResult.regs.ds, dumpResult.regs.ss, dumpResult.regs.es, + dumpResult.regs.fs, dumpResult.regs.gs); } if (!dumpResult.stackTrace.empty()) @@ -1007,7 +998,7 @@ SString CInstallManager::_MaybeSwitchToTempExe() { ReleaseSingleInstanceMutex(); if (ShellExecuteNonBlocking("open", GetLauncherPathFilename(), GetSequencerSnapshot())) - ExitProcess(0); // All done here + ExitProcess(0); // All done here CreateSingleInstanceMutex(); return "fail"; } @@ -1030,7 +1021,7 @@ SString CInstallManager::_SwitchBackFromTempExe() ReleaseSingleInstanceMutex(); if (ShellExecuteNonBlocking("open", GetLauncherPathFilename(), GetSequencerSnapshot())) - ExitProcess(0); // All done here + ExitProcess(0); // All done here CreateSingleInstanceMutex(); return "fail"; } @@ -1448,7 +1439,7 @@ SString CInstallManager::_ProcessLayoutChecks() SString strMTADataPath = i ? GetMTADataPathCommon() : GetMTADataPath(); if (!DirectoryExists(strMTADataPath)) - ShowLayoutError("[Data directory not present]"); // Can't find directory + ShowLayoutError("[Data directory not present]"); // Can't find directory SString strTestFilePath = PathJoin(strMTADataPath, "testdir", "testfile.txt"); @@ -1457,7 +1448,7 @@ SString CInstallManager::_ProcessLayoutChecks() SString strContent = "test"; if (!FileSave(strTestFilePath, strContent)) - ShowLayoutError("[Data directory not writable]"); // Can't save file + ShowLayoutError("[Data directory not writable]"); // Can't save file FileDelete(strTestFilePath); RemoveDirectory(ExtractPath(strTestFilePath)); @@ -1467,7 +1458,7 @@ SString CInstallManager::_ProcessLayoutChecks() // Check reg key exists { if (GetRegistryValue("", "Last Install Location").empty()) - ShowLayoutError("[Registry key not present]"); // Can't find reg key + ShowLayoutError("[Registry key not present]"); // Can't find reg key } #endif @@ -1479,7 +1470,7 @@ SString CInstallManager::_ProcessLayoutChecks() SetRegistryValue("testkeypath", "testname", strValue); SString strValueCheck = GetRegistryValue("testkeypath", "testname"); if (strValueCheck != strValue) - ShowLayoutError("[Registry key not writable]"); // Can't write reg key + ShowLayoutError("[Registry key not writable]"); // Can't write reg key RemoveRegistryKey("testkeypath"); } @@ -1492,7 +1483,7 @@ SString CInstallManager::_ProcessLayoutChecks() SString strContent = "test"; if (!FileSave(strTestFilePath, strContent)) - ShowLayoutError("[Install directory not writable]"); // Can't save file + ShowLayoutError("[Install directory not writable]"); // Can't save file FileDelete(strTestFilePath); } @@ -1692,7 +1683,7 @@ SString CInstallManager::_ProcessServiceChecks() ////////////////////////////////////////////////////////// SString CInstallManager::_ProcessAppCompatChecks() { - BOOL bIsWOW64 = false; // 64bit OS + BOOL bIsWOW64 = false; // 64bit OS IsWow64Process(GetCurrentProcess(), &bIsWOW64); uint uiHKLMFlags = bIsWOW64 ? KEY_WOW64_64KEY : 0; WString strGTAExePathFilename = GetGameExecutablePath().wstring(); @@ -1805,7 +1796,7 @@ SString CInstallManager::_ProcessAppCompatChecks() WriteDebugEvent(SString("GameUX ServiceLocation was '%s'", *ToUTF8(strUrlValue))); if (strUrlValue.ContainsI(L":")) { - strUrlValue = L"disabled"; // Can be anything not containing `:` + strUrlValue = L"disabled"; // Can be anything not containing `:` if (!WriteCompatibilityEntries(strUrlItem, strUrlKey, HKEY_CURRENT_USER, 0, strUrlValue)) bTryAdmin = true; } diff --git a/Client/loader/CInstallManager.h b/Client/loader/CInstallManager.h index 328cf7c07c1..9b80b0f7b31 100644 --- a/Client/loader/CInstallManager.h +++ b/Client/loader/CInstallManager.h @@ -13,9 +13,9 @@ #include "CSequencer.h" // Common command line keys -#define INSTALL_STAGE "install_stage" -#define INSTALL_LOCATION "install_loc" -#define HIDE_PROGRESS "hide_prog" +#define INSTALL_STAGE "install_stage" +#define INSTALL_LOCATION "install_loc" +#define HIDE_PROGRESS "hide_prog" typedef CBadLang CSequencerType; diff --git a/Client/loader/CSequencer.h b/Client/loader/CSequencer.h index d679a44ad57..5041cf0fbe2 100644 --- a/Client/loader/CSequencer.h +++ b/Client/loader/CSequencer.h @@ -166,9 +166,9 @@ class CBadLang SString strLabel = GetVariable("_pc_label"); int iOffset = GetVariableInt("_pc_offset"); m_uiCurrLine = m_LineList.size(); - for (uint i = 0; i < m_LineList.size(); i++) // Find label + for (uint i = 0; i < m_LineList.size(); i++) // Find label if (m_LineList[i].BeginsWith(strLabel)) - for (; i < m_LineList.size(); i++) // Find offset + for (; i < m_LineList.size(); i++) // Find offset if (IsLineValid(m_LineList[i]) && !iOffset--) { m_uiCurrLine = i; diff --git a/Client/loader/D3DStuff.cpp b/Client/loader/D3DStuff.cpp index 8f5ba714940..ca4401a2e91 100644 --- a/Client/loader/D3DStuff.cpp +++ b/Client/loader/D3DStuff.cpp @@ -17,7 +17,6 @@ #include #include - namespace { SString GUIDToString(const GUID& g) @@ -65,7 +64,7 @@ namespace using EnableHandlersFn = BOOL(WINAPI*)(void); std::atomic g_enableHandlersImpl{nullptr}; std::atomic g_enableHandlersPending{false}; -} // namespace +} // namespace // Loader is built without core crash handler code; defer to the implementation once core.dll is loaded. extern "C" BOOL BUGSUTIL_DLLINTERFACE __stdcall EnableAllHandlersAfterInitialization(void) noexcept @@ -139,8 +138,8 @@ bool NvOptimusDetect() bool bFoundOptimus = false; for (NvU32 i = 0; i < uiGpuCount; i++) { - NV_SYSTEM_TYPE SystemType = (NV_SYSTEM_TYPE)-1; // 1-Laptop 2-Desktop - NV_GPU_TYPE GpuType = (NV_GPU_TYPE)-1; // 1-Integrated 2-Discrete + NV_SYSTEM_TYPE SystemType = (NV_SYSTEM_TYPE)-1; // 1-Laptop 2-Desktop + NV_GPU_TYPE GpuType = (NV_GPU_TYPE)-1; // 1-Integrated 2-Discrete NvAPI_ShortString szName = "-"; NvAPI_GPU_GetSystemType(nvGPUHandle[i], &SystemType); @@ -255,12 +254,11 @@ void BeginD3DStuff() SetApplicationSettingInt("nvhacks", "optimus-export-enablement", 0); SetApplicationSettingInt("nvhacks", "optimus-force-windowed", 0); } - + // Crash handler enablement now occurs inside the game process once the // Direct3D device is fully created (see CGraphics::OnDeviceCreate). } - ////////////////////////////////////////////////////////// // // EndD3DStuff diff --git a/Client/loader/Dialogs.cpp b/Client/loader/Dialogs.cpp index a2aa1b8376a..4bda6d12a39 100644 --- a/Client/loader/Dialogs.cpp +++ b/Client/loader/Dialogs.cpp @@ -22,12 +22,12 @@ // Define STN_CLICKED if not already defined #ifndef STN_CLICKED -#define STN_CLICKED 0 + #define STN_CLICKED 0 #endif // Define IDC_SEND_DUMP_LABEL if not in resource.h yet #ifndef IDC_SEND_DUMP_LABEL -#define IDC_SEND_DUMP_LABEL 1040 + #define IDC_SEND_DUMP_LABEL 1040 #endif static std::atomic bCancelPressed{false}; @@ -42,15 +42,16 @@ static HWND hwndOptimusDialog = nullptr; static HWND hwndNoAvDialog = nullptr; // Constants for crash dialog timeout -namespace { +namespace +{ inline constexpr DWORD MAX_WAIT_TIME = 30000; static_assert(MAX_WAIT_TIME > 0 && MAX_WAIT_TIME <= 60000, "Timeout must be between 0 and 60 seconds"); - - inline constexpr std::string_view ERROR_MSG_PREFIX = "ShowCrashedDialog: CreateDialogW failed with error "; - inline constexpr std::string_view CRASH_MSG_DIALOG_FAIL = "MTA has crashed. (Failed to create crash dialog)"; - inline constexpr std::string_view CRASH_TITLE_FATAL = "MTA: San Andreas - Fatal Error"; + + inline constexpr std::string_view ERROR_MSG_PREFIX = "ShowCrashedDialog: CreateDialogW failed with error "; + inline constexpr std::string_view CRASH_MSG_DIALOG_FAIL = "MTA has crashed. (Failed to create crash dialog)"; + inline constexpr std::string_view CRASH_TITLE_FATAL = "MTA: San Andreas - Fatal Error"; inline constexpr std::wstring_view DEFAULT_ERROR_MSG = L"An error occurred. No details available."; - inline constexpr size_t MAX_CRASH_MESSAGE_LENGTH = 65536; + inline constexpr size_t MAX_CRASH_MESSAGE_LENGTH = 65536; static_assert(ERROR_MSG_PREFIX.size() <= INT_MAX, "ERROR_MSG_PREFIX too long for int cast"); } @@ -213,7 +214,7 @@ int CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) // Validate message source if (lParam != 0 && !IsWindow(reinterpret_cast(lParam))) break; - + switch (LOWORD(wParam)) { case IDCANCEL: @@ -223,10 +224,12 @@ int CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) if (HWND hwndCheck = GetDlgItem(hwnd, IDC_SEND_DUMP_CHECK)) { LRESULT res = SendMessageA(hwndCheck, BM_GETCHECK, 0, 0); - try { + try + { SetApplicationSetting("diagnostics", "send-dumps", (res == BST_CHECKED) ? "yes" : "no"); } - catch (...) { + catch (...) + { } } } @@ -239,10 +242,12 @@ int CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) if (HWND hwndCheck = GetDlgItem(hwnd, IDC_SEND_DUMP_CHECK)) { LRESULT res = SendMessageA(hwndCheck, BM_GETCHECK, 0, 0); - try { + try + { SetApplicationSetting("diagnostics", "send-dumps", (res == BST_CHECKED) ? "yes" : "no"); } - catch (...) { + catch (...) + { } } } @@ -273,7 +278,7 @@ void ShowProgressDialog(HINSTANCE hInstance, const SString& strTitle, bool bAllo HideSplash(); bCancelPressed = false; hwndProgressDialog = CreateDialogW(hInstance, MAKEINTRESOURCEW(IDD_PROGRESS_DIALOG), 0, DialogProc); - dassert((GetWindowLong(hwndProgressDialog, GWL_STYLE) & WS_VISIBLE) == 0); // Should be Visible: False + dassert((GetWindowLong(hwndProgressDialog, GWL_STYLE) & WS_VISIBLE) == 0); // Should be Visible: False InitDialogStrings(hwndProgressDialog, g_ProgressDialogItems); SetWindowTextW(hwndProgressDialog, FromUTF8(strTitle)); ShowWindow(GetDlgItem(hwndProgressDialog, IDCANCEL), bAllowCancel ? SW_SHOW : SW_HIDE); @@ -357,14 +362,15 @@ void StopPseudoProgress() [[nodiscard]] SString ShowCrashedDialog(HINSTANCE hInstance, const SString& strMessage) { using namespace std::string_view_literals; - - if (auto validHandle = std::optional{hInstance ? hInstance : GetModuleHandle(nullptr)}; - !validHandle || !*validHandle) [[unlikely]] + + if (auto validHandle = std::optional{hInstance ? hInstance : GetModuleHandle(nullptr)}; !validHandle || !*validHandle) [[unlikely]] { - try { + try + { MessageBoxA(nullptr, "MTA has crashed."sv.data(), "MTA: San Andreas"sv.data(), MB_OK | MB_ICONERROR | MB_TOPMOST); } - catch (...) { + catch (...) + { } return "quit"; } @@ -372,133 +378,157 @@ void StopPseudoProgress() { hInstance = *validHandle; } - - const auto strSanitizedMessage = [&message = std::as_const(strMessage)]() noexcept -> SString { - try { - if constexpr (MAX_CRASH_MESSAGE_LENGTH > 0) { + + const auto strSanitizedMessage = [&message = std::as_const(strMessage)]() noexcept -> SString + { + try + { + if constexpr (MAX_CRASH_MESSAGE_LENGTH > 0) + { const auto messageLength = std::clamp(std::size(message), size_t{0}, MAX_CRASH_MESSAGE_LENGTH); if (std::size(message) > MAX_CRASH_MESSAGE_LENGTH) return message.substr(0, messageLength); else return message; - } else { + } + else + { return message; } } - catch (...) { + catch (...) + { return SString{}; } }(); - + struct ReentranceGuard final { std::atomic& flag; - bool isValid{true}; - - explicit ReentranceGuard(std::atomic& f) noexcept : flag(f), - isValid(!flag.exchange(true, std::memory_order_acquire)) - { - } - + bool isValid{true}; + + explicit ReentranceGuard(std::atomic& f) noexcept : flag(f), isValid(!flag.exchange(true, std::memory_order_acquire)) {} + ~ReentranceGuard() noexcept { if (isValid) [[likely]] flag.store(false, std::memory_order_release); } - + [[nodiscard]] explicit operator bool() const noexcept { return isValid; } - + ReentranceGuard(const ReentranceGuard&) = delete; ReentranceGuard& operator=(const ReentranceGuard&) = delete; ReentranceGuard(ReentranceGuard&&) = delete; ReentranceGuard& operator=(ReentranceGuard&&) = delete; }; - + static std::atomic bInShowCrashedDialog{false}; - - try { + + try + { ReentranceGuard guard{bInShowCrashedDialog}; - + if (!guard) [[unlikely]] { - try { - MessageBoxA(nullptr, "MTA has crashed."sv.data(), "MTA: San Andreas"sv.data(), - MB_OK | MB_ICONERROR | MB_TOPMOST | MB_SETFOREGROUND); + try + { + MessageBoxA(nullptr, "MTA has crashed."sv.data(), "MTA: San Andreas"sv.data(), MB_OK | MB_ICONERROR | MB_TOPMOST | MB_SETFOREGROUND); } - catch (...) { + catch (...) + { } return "quit"; } - - if ([[maybe_unused]] const auto displayResult = ChangeDisplaySettings(nullptr, 0); true) { + + if ([[maybe_unused]] const auto displayResult = ChangeDisplaySettings(nullptr, 0); true) + { constexpr auto displaySettingsDelay = 300; Sleep(displaySettingsDelay); } - + if (!hwndCrashedDialog) { - try { + try + { SuspendSplash(); } - catch (...) { + catch (...) + { } - + // Reset button states bCancelPressed.store(false, std::memory_order_release); bOkPressed.store(false, std::memory_order_release); - + hwndCrashedDialog = CreateDialogW(hInstance, MAKEINTRESOURCEW(IDD_CRASHED_DIALOG), nullptr, DialogProc); - + if (!hwndCrashedDialog) [[unlikely]] { - [[nodiscard]] const auto logError = [lastError = static_cast(GetLastError())]() noexcept { - try { + [[nodiscard]] const auto logError = [lastError = static_cast(GetLastError())]() noexcept + { + try + { constexpr auto errorCode = 9001; AddReportLog(errorCode, SString("ShowCrashedDialog: CreateDialogW failed with error %u", lastError)); } - catch (...) {} + catch (...) + { + } }; - - [[nodiscard]] constexpr auto setDumpSetting = []() noexcept -> void { - try { + + [[nodiscard]] constexpr auto setDumpSetting = []() noexcept -> void + { + try + { SetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data(), "yes"sv.data()); } - catch (...) {} + catch (...) + { + } }; - - [[nodiscard]] constexpr auto cleanup = []() noexcept -> void { - try { + + [[nodiscard]] constexpr auto cleanup = []() noexcept -> void + { + try + { ResumeSplash(); } - catch (...) {} - try { - MessageBoxA(nullptr, CRASH_MSG_DIALOG_FAIL.data(), CRASH_TITLE_FATAL.data(), - MB_OK | MB_ICONERROR | MB_TOPMOST); + catch (...) + { + } + try + { + MessageBoxA(nullptr, CRASH_MSG_DIALOG_FAIL.data(), CRASH_TITLE_FATAL.data(), MB_OK | MB_ICONERROR | MB_TOPMOST); + } + catch (...) + { } - catch (...) {} }; - + std::invoke(logError); std::invoke(setDumpSetting); std::invoke(cleanup); return "quit"; } - try { + try + { InitDialogStrings(hwndCrashedDialog, g_CrashedDialogItems); } - catch (...) { + catch (...) + { } if (auto hwndCrashInfo = GetDlgItem(hwndCrashedDialog, IDC_CRASH_INFO_EDIT); hwndCrashInfo) { - try { + try + { if (const bool isEmpty = std::empty(strSanitizedMessage); isEmpty) [[unlikely]] { SetWindowTextW(hwndCrashInfo, DEFAULT_ERROR_MSG.data()); } else { - if (const auto wszMessage = FromUTF8(strSanitizedMessage); - wszMessage && (wszMessage[0] != L'\0')) [[likely]] + if (const auto wszMessage = FromUTF8(strSanitizedMessage); wszMessage && (wszMessage[0] != L'\0')) [[likely]] { SetWindowTextW(hwndCrashInfo, wszMessage); } @@ -508,89 +538,102 @@ void StopPseudoProgress() } } } - catch (...) { + catch (...) + { } } if (const auto hwndCheckbox = GetDlgItem(hwndCrashedDialog, IDC_SEND_DUMP_CHECK); hwndCheckbox) { - try { - const auto settingValue = std::invoke([]() noexcept -> SString { - try { - return GetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data()); - } - catch (...) { - return "yes"; - } - }); - + try + { + const auto settingValue = std::invoke( + []() noexcept -> SString + { + try + { + return GetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data()); + } + catch (...) + { + return "yes"; + } + }); + const std::array checkStates = {BST_UNCHECKED, BST_CHECKED}; - const auto shouldCheck = !std::empty(settingValue) && settingValue != "no"sv.data(); - SendDlgItemMessage(hwndCrashedDialog, IDC_SEND_DUMP_CHECK, BM_SETCHECK, - checkStates[shouldCheck], 0); + const auto shouldCheck = !std::empty(settingValue) && settingValue != "no"sv.data(); + SendDlgItemMessage(hwndCrashedDialog, IDC_SEND_DUMP_CHECK, BM_SETCHECK, checkStates[shouldCheck], 0); } - catch (...) { + catch (...) + { } } } if (!hwndCrashedDialog) [[unlikely]] { - try { + try + { SetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data(), "yes"sv.data()); } - catch (...) { + catch (...) + { } return "quit"; } - try { + try + { SetForegroundWindow(hwndCrashedDialog); SetWindowPos(hwndCrashedDialog, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); } - catch (...) { + catch (...) + { } - + const auto dwStartTime = static_cast(GetTickCount32()); - - [[nodiscard]] constexpr auto handleTimeout = []() noexcept -> void { - try { + + [[nodiscard]] constexpr auto handleTimeout = []() noexcept -> void + { + try + { SetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data(), "yes"sv.data()); } - catch (...) { + catch (...) + { } }; - - [[nodiscard]] constexpr auto calculateElapsed = [](const DWORD current, const DWORD start) noexcept -> DWORD { - if constexpr (sizeof(DWORD) == 4) { - return (current >= start) - ? (current - start) - : (std::numeric_limits::max() - start + current + 1); - } else { + + [[nodiscard]] constexpr auto calculateElapsed = [](const DWORD current, const DWORD start) noexcept -> DWORD + { + if constexpr (sizeof(DWORD) == 4) + { + return (current >= start) ? (current - start) : (std::numeric_limits::max() - start + current + 1); + } + else + { return current - start; } }; - + for (;;) { - const auto [cancelPressed, okPressed] = std::pair{bCancelPressed.load(std::memory_order_acquire), - bOkPressed.load(std::memory_order_acquire)}; + const auto [cancelPressed, okPressed] = std::pair{bCancelPressed.load(std::memory_order_acquire), bOkPressed.load(std::memory_order_acquire)}; if (cancelPressed || okPressed) break; - - if (const auto dwCurrentTime = static_cast(GetTickCount32()); - calculateElapsed(dwCurrentTime, dwStartTime) > MAX_WAIT_TIME) [[unlikely]] + + if (const auto dwCurrentTime = static_cast(GetTickCount32()); calculateElapsed(dwCurrentTime, dwStartTime) > MAX_WAIT_TIME) [[unlikely]] { std::invoke(handleTimeout); (void)bCancelPressed.exchange(true, std::memory_order_release); break; } constexpr auto maxMessagesPerIteration = 100; - auto msg = MSG{}; - auto messageCount = decltype(maxMessagesPerIteration){0}; - + auto msg = MSG{}; + auto messageCount = decltype(maxMessagesPerIteration){0}; + while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { if (std::exchange(messageCount, messageCount + 1) >= maxMessagesPerIteration) [[unlikely]] break; - + // Block WM_QUIT and other termination messages during crash dialog. // The crash dialog MUST only close via explicit user button press (IDOK/IDCANCEL). // External quit requests (from CallFunction:Quit, PostQuitMessage, etc.) are suppressed @@ -601,15 +644,17 @@ void StopPseudoProgress() // This prevents external quit requests from closing the crash dialog continue; } - + if (msg.hwnd && !IsWindow(msg.hwnd)) [[unlikely]] continue; - - try { + + try + { TranslateMessage(&msg); DispatchMessage(&msg); } - catch (...) { + catch (...) + { } } if (!hwndCrashedDialog || !IsWindow(hwndCrashedDialog)) [[unlikely]] @@ -617,28 +662,32 @@ void StopPseudoProgress() (void)bCancelPressed.exchange(true, std::memory_order_release); break; } - + { constexpr auto sleepDuration = 10; - try { + try + { Sleep(sleepDuration); } - catch (...) { + catch (...) + { (void)bCancelPressed.exchange(true, std::memory_order_release); break; } } - } - + } + const auto okWasPressed = bOkPressed.load(std::memory_order_acquire); return okWasPressed ? "ok" : "quit"; } catch (...) { - try { + try + { SetApplicationSetting("diagnostics"sv.data(), "send-dumps"sv.data(), "yes"sv.data()); } - catch (...) { + catch (...) + { } return "quit"; } @@ -660,22 +709,19 @@ void HideCrashedDialog() void ShowOOMMessageBox([[maybe_unused]] HINSTANCE hInstance) { - static constexpr const char* fallbackMessage = - "The crash you experienced is due to memory abuse by servers. Contact server owner or MTA support."; + static constexpr const char* fallbackMessage = "The crash you experienced is due to memory abuse by servers. Contact server owner or MTA support."; static constexpr const char* fallbackTitle = "MTA: San Andreas - Out of Memory Crash"; - const char* message = _("The crash you experienced is due to memory abuse by servers.\n\n" - "Even with plenty of RAM, this is a x86 game with address space limits up to 3.6GB " - "and some highly unoptimized servers with a lot of mods (or just a few poorly written scripts) " - "can make this happen, as well as lag your game.\n\n" - "Contact the server owner or MTA support in the MTA official discord (https://discord.gg/mtasa) for more information."); - + const char* message = + _("The crash you experienced is due to memory abuse by servers.\n\n" + "Even with plenty of RAM, this is a x86 game with address space limits up to 3.6GB " + "and some highly unoptimized servers with a lot of mods (or just a few poorly written scripts) " + "can make this happen, as well as lag your game.\n\n" + "Contact the server owner or MTA support in the MTA official discord (https://discord.gg/mtasa) for more information."); + const char* title = _("MTA: San Andreas - Out of Memory Information"); - MessageBoxA(NULL, - message ? message : fallbackMessage, - title ? title : fallbackTitle, - MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND); + MessageBoxA(NULL, message ? message : fallbackMessage, title ? title : fallbackTitle, MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND); } /////////////////////////////////////////////////////////////// @@ -709,7 +755,7 @@ void ShowGraphicsDllDialog(HINSTANCE hInstance, const std::vector(time(NULL) / 3600LL); @@ -958,7 +1004,7 @@ void ShowNoAvDialog(HINSTANCE hInstance, bool bEnableScaremongering) bOtherPressed = false; iOtherCode = IDC_BUTTON_HELP; hwndNoAvDialog = CreateDialogW(hInstance, MAKEINTRESOURCEW(IDD_NOAV_DIALOG), 0, DialogProc); - dassert((GetWindowLongW(hwndNoAvDialog, GWL_STYLE) & WS_VISIBLE) == 0); // Should be Visible: False + dassert((GetWindowLongW(hwndNoAvDialog, GWL_STYLE) & WS_VISIBLE) == 0); // Should be Visible: False InitDialogStrings(hwndNoAvDialog, g_NoAvDialogItems); const int textSourceItemId = bEnableScaremongering ? IDC_NOAV_OPT_BOTNET : IDC_NOAV_OPT_SKIP; { @@ -967,7 +1013,7 @@ void ShowNoAvDialog(HINSTANCE hInstance, bool bEnableScaremongering) SetWindowTextW(GetDlgItem(hwndNoAvDialog, IDC_CHECK_NOT_AGAIN), text); } } - ShowWindow(hwndNoAvDialog, SW_SHOW); // Show after all changes are complete + ShowWindow(hwndNoAvDialog, SW_SHOW); // Show after all changes are complete SetForegroundWindow(hwndNoAvDialog); SetWindowPos(hwndNoAvDialog, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); @@ -1019,8 +1065,8 @@ void HideNoAvDialog() /////////////////////////////////////////////////////////////// void TestDialogs() { -#if 0 -#if 1 + #if 0 + #if 1 ShowProgressDialog( g_hInstance, _("Searching for Grand Theft Auto San Andreas"), true ); for ( uint i = 0 ; i < 100 ; i++ ) { @@ -1064,40 +1110,40 @@ void TestDialogs() Sleep( 10 ); } HideProgressDialog(); -#endif + #endif -#if 1 + #if 1 ShowCrashedDialog( g_hInstance, "test2" ); HideCrashedDialog(); -#endif + #endif -#if 1 + #if 1 SetApplicationSetting("diagnostics", "d3d9-dll-last-hash", "123"); std::vector offenders{GraphicsLibrary{"dummy"}}; ShowGraphicsDllDialog(g_hInstance, offenders); HideGraphicsDllDialog(); -#endif + #endif -#if 1 + #if 1 ShowOptimusDialog( g_hInstance ); HideOptimusDialog(); -#endif + #endif -#if 1 + #if 1 // Friendly option SetApplicationSettingInt( "noav-last-asked-time", 1 ); SetApplicationSettingInt( "noav-user-says-skip", 0 ); ShowNoAvDialog( g_hInstance, true ); HideNoAvDialog(); -#endif + #endif -#if 1 + #if 1 // Scaremongering option option SetApplicationSettingInt( "noav-last-asked-time", 1 ); SetApplicationSettingInt( "noav-user-says-skip", 0 ); ShowNoAvDialog( g_hInstance, false ); HideNoAvDialog(); -#endif -#endif + #endif + #endif } #endif diff --git a/Client/loader/Dialogs.h b/Client/loader/Dialogs.h index c44ca49bef6..3af8861b4a4 100644 --- a/Client/loader/Dialogs.h +++ b/Client/loader/Dialogs.h @@ -30,7 +30,7 @@ void ShowOOMMessageBox(HINSTANCE hInstance); struct GraphicsLibrary { - SString stem; // filename without the final extension + SString stem; // filename without the final extension SString absoluteFilePath; SString md5Hash; SString appLastHash; diff --git a/Client/loader/GameExecutablePatcher.cpp b/Client/loader/GameExecutablePatcher.cpp index 3183fe7c6a5..fc36d506fff 100644 --- a/Client/loader/GameExecutablePatcher.cpp +++ b/Client/loader/GameExecutablePatcher.cpp @@ -153,8 +153,8 @@ class WindowsAeroPatch final */ class LibraryRedirectionPatch final { - static constexpr auto LIBRARY_NAME_BEFORE = "WINMM.dll"; // Do not correct this value. It must be equal to the one in the original binary. - static constexpr auto LIBRARY_NAME_AFTER = LOADER_PROXY_DLL_NAME; // This must be equal to the library produced by 'Loader Proxy' project. + static constexpr auto LIBRARY_NAME_BEFORE = "WINMM.dll"; // Do not correct this value. It must be equal to the one in the original binary. + static constexpr auto LIBRARY_NAME_AFTER = LOADER_PROXY_DLL_NAME; // This must be equal to the library produced by 'Loader Proxy' project. static auto GetImportDescriptor(PatchableExecutable& pe) -> IMAGE_IMPORT_DESCRIPTOR* { @@ -278,8 +278,8 @@ class HighPerformanceGraphicsPatch final item.rvaName = EXPORT_DIRECTORY_VA + offset; auto value = reinterpret_cast(base + offset); - std::copy(item.name.data(), item.name.data() + item.name.size() + 1, value); // Plus one for null byte. - offset += item.name.size() + 1; // Length plus null byte. + std::copy(item.name.data(), item.name.data() + item.name.size() + 1, value); // Plus one for null byte. + offset += item.name.size() + 1; // Length plus null byte. } // Write export name RVAs. diff --git a/Client/loader/Install.cpp b/Client/loader/Install.cpp index 4a59fe7993a..2806ed8cddc 100644 --- a/Client/loader/Install.cpp +++ b/Client/loader/Install.cpp @@ -572,7 +572,7 @@ static int RunInstall() { SString archiveDirectory, archiveFileName; sourceRoot.Split("\\", &archiveDirectory, &archiveFileName, -1); - archiveFileName = archiveFileName.SubStr(1).SplitLeft("_tmp_", nullptr, -1); // Cut archive name out of '__tmp_' + archiveFileName = archiveFileName.SubStr(1).SplitLeft("_tmp_", nullptr, -1); // Cut archive name out of '__tmp_' archivePath = MakeGenericPath(PathJoin(archiveDirectory, archiveFileName)); } @@ -803,7 +803,8 @@ static int RunInstall() else OutputDebugLine(SString("RunInstall: Updated %zu files", files.size())); - const auto Rollback = [&]() { + const auto Rollback = [&]() + { if (size_t disasterCounter = RunRollback(files); disasterCounter > 0) { // Do not delete the backup directory if we need it for recovery. diff --git a/Client/loader/Main.cpp b/Client/loader/Main.cpp index 8b01ea323c7..b17a70a6e93 100644 --- a/Client/loader/Main.cpp +++ b/Client/loader/Main.cpp @@ -31,56 +31,59 @@ #define MAYBE_UNUSED #endif -namespace { +namespace +{ // Error codes enum for better maintainability - enum ErrorCode : int { + enum ErrorCode : int + { ERROR_NULL_INSTANCE = -1, ERROR_NULL_INSTALL_MANAGER = -2, ERROR_LAUNCH_EXCEPTION = -3, ERROR_INSTALL_CONTINUE = -4 }; - + // Command line constants constexpr size_t MAX_CMD_LINE_LENGTH = 4096; - + // Report log IDs constexpr int LOG_ID_END = 1044; constexpr int LOG_ID_CONTINUE_EXCEPTION = 1045; constexpr int LOG_ID_LAUNCH_EXCEPTION = 1046; - - // Compile-time checks + + // Compile-time checks static_assert(MAX_CMD_LINE_LENGTH > 0, "Command line buffer size must be positive"); static_assert(MAX_CMD_LINE_LENGTH <= 65536, "Command line buffer size seems unreasonably large"); static_assert(sizeof(DWORD) >= sizeof(int), "DWORD must be at least as large as int"); - class Utf8FileHooksGuard { + class Utf8FileHooksGuard + { private: bool m_released = false; - + public: - Utf8FileHooksGuard() { - AddUtf8FileHooks(); - } - - ~Utf8FileHooksGuard() noexcept { - if (!m_released) { + Utf8FileHooksGuard() { AddUtf8FileHooks(); } + + ~Utf8FileHooksGuard() noexcept + { + if (!m_released) + { RemoveUtf8FileHooks(); } } - + // Called when we want to keep hooks active (early return with error) - void release() noexcept { - m_released = true; - } - + void release() noexcept { m_released = true; } + // Called when we want to remove hooks early (on GetInstallManager failure) - void removeNow() noexcept { - if (!m_released) { + void removeNow() noexcept + { + if (!m_released) + { RemoveUtf8FileHooks(); m_released = true; } } - + // Disable copy and move Utf8FileHooksGuard(const Utf8FileHooksGuard&) = delete; Utf8FileHooksGuard& operator=(const Utf8FileHooksGuard&) = delete; @@ -88,83 +91,98 @@ namespace { Utf8FileHooksGuard& operator=(Utf8FileHooksGuard&&) = delete; }; - inline void SafeCopyCommandLine(LPSTR lpCmdLine, char* safeCmdLine, size_t bufferSize) noexcept { + inline void SafeCopyCommandLine(LPSTR lpCmdLine, char* safeCmdLine, size_t bufferSize) noexcept + { // Preconditions (only in debug builds) assert(safeCmdLine != nullptr && "Destination buffer must not be null"); assert(bufferSize > 0 && "Buffer size must be positive"); - - if (!safeCmdLine || bufferSize == 0) { + + if (!safeCmdLine || bufferSize == 0) + { return; } - + // If source is null, destination remains zero-initialized - if (!lpCmdLine) { + if (!lpCmdLine) + { return; } - + const size_t maxCopyLen = bufferSize - 1; const size_t cmdLineLen = strnlen(lpCmdLine, maxCopyLen); - + memcpy(safeCmdLine, lpCmdLine, cmdLineLen); safeCmdLine[cmdLineLen] = '\0'; } - inline DWORD GetSafeProcessId() noexcept { - try { + inline DWORD GetSafeProcessId() noexcept + { + try + { return GetCurrentProcessId(); } - catch (...) { + catch (...) + { return 0; } } - CInstallManager* PerformEarlyInitialization(const char* safeCmdLine) { + CInstallManager* PerformEarlyInitialization(const char* safeCmdLine) + { auto* pInstallManager = GetInstallManager(); - if (!pInstallManager) { + if (!pInstallManager) + { return nullptr; } // Let install manager figure out what MTASA path to use // This must be called before ConfigureWerDumpPath which uses CalcMTASAPath pInstallManager->SetMTASAPathSource(safeCmdLine); - + ConfigureWerDumpPath(); // Start logging.....now BeginEventLog(); - + // Start localization if possible InitLocalization(false); - + // Handle commands from the installer HandleSpecialLaunchOptions(); - + // Check MTA is launched only once HandleDuplicateLaunching(); - + return pInstallManager; } - SString ContinueUpdateProcedure(CInstallManager* pInstallManager) { - if (!pInstallManager) { + SString ContinueUpdateProcedure(CInstallManager* pInstallManager) + { + if (!pInstallManager) + { return SString(); } - - try { + + try + { return pInstallManager->Continue(); } - catch (...) { + catch (...) + { AddReportLog(LOG_ID_CONTINUE_EXCEPTION, "Exception in InstallManager::Continue()"); return SString(); } } - // Launch the game with exception handling - int LaunchGameSafely(const SString& strCmdLine) { - try { + // Launch the game with exception handling + int LaunchGameSafely(const SString& strCmdLine) + { + try + { return LaunchGame(strCmdLine); } - catch (...) { + catch (...) + { AddReportLog(LOG_ID_LAUNCH_EXCEPTION, "Exception in LaunchGame()"); return static_cast(ERROR_LAUNCH_EXCEPTION); } @@ -183,17 +201,17 @@ namespace { // (Which may then call it again as admin) // /////////////////////////////////////////////////////////////// -MTAEXPORT int DoWinMain(HINSTANCE hLauncherInstance, MAYBE_UNUSED HINSTANCE hPrevInstance, - LPSTR lpCmdLine, MAYBE_UNUSED int nCmdShow) +MTAEXPORT int DoWinMain(HINSTANCE hLauncherInstance, MAYBE_UNUSED HINSTANCE hPrevInstance, LPSTR lpCmdLine, MAYBE_UNUSED int nCmdShow) { - // Silence unused parameter warnings for older compilers - #if __cplusplus < 201703L - (void)hPrevInstance; - (void)nCmdShow; - #endif +// Silence unused parameter warnings for older compilers +#if __cplusplus < 201703L + (void)hPrevInstance; + (void)nCmdShow; +#endif // Check for null parameters before use - if (!hLauncherInstance) { + if (!hLauncherInstance) + { return static_cast(ERROR_NULL_INSTANCE); } @@ -203,32 +221,33 @@ MTAEXPORT int DoWinMain(HINSTANCE hLauncherInstance, MAYBE_UNUSED HINSTANCE hPre // Log the command line we're receiving { char debugBuf[512]; - _snprintf_s(debugBuf, sizeof(debugBuf), _TRUNCATE, - "========================================\nMain.cpp - Command line received: '%s'\n========================================\n", - safeCmdLine); + _snprintf_s(debugBuf, sizeof(debugBuf), _TRUNCATE, + "========================================\nMain.cpp - Command line received: '%s'\n========================================\n", + safeCmdLine); OutputDebugStringA(debugBuf); } // RAII guard for UTF8 file hooks Utf8FileHooksGuard utf8Guard; - #if defined(MTA_DEBUG) +#if defined(MTA_DEBUG) SharedUtil_Tests(); - #endif +#endif // // Init // auto* pInstallManager = PerformEarlyInitialization(safeCmdLine); - if (!pInstallManager) { + if (!pInstallManager) + { // Remove hooks when install manager fails utf8Guard.removeNow(); return static_cast(ERROR_NULL_INSTALL_MANAGER); } HINSTANCE hInstanceToUse = hLauncherInstance; - + // Show logo ShowSplash(hInstanceToUse); @@ -238,7 +257,6 @@ MTAEXPORT int DoWinMain(HINSTANCE hLauncherInstance, MAYBE_UNUSED HINSTANCE hPre // Find GTA path to use ValidateGTAPath(); - // Continue any update procedure SString strCmdLine = ContinueUpdateProcedure(pInstallManager); @@ -251,9 +269,9 @@ MTAEXPORT int DoWinMain(HINSTANCE hLauncherInstance, MAYBE_UNUSED HINSTANCE hPre // Stuff HandleCustomStartMessage(); - #if !defined(MTA_DEBUG) && MTASA_VERSION_TYPE != VERSION_TYPE_CUSTOM +#if !defined(MTA_DEBUG) && MTASA_VERSION_TYPE != VERSION_TYPE_CUSTOM ForbodenProgramsMessage(); - #endif +#endif CycleEventLog(); BsodDetectionPreLaunch(); diff --git a/Client/loader/Main.h b/Client/loader/Main.h index 520bd7b01de..af3d82247e5 100644 --- a/Client/loader/Main.h +++ b/Client/loader/Main.h @@ -20,15 +20,15 @@ #define MTA_EXE_NAME_RELEASE "Multi Theft Auto.exe" #ifdef MTA_DEBUG - #define MTA_EXE_NAME "Multi Theft Auto_d.exe" - #define MTA_DLL_NAME "core_d.dll" - #define CHECK_DM_LUA_NAME "mods\\deathmatch\\lua5.1c_d.dll" - #define CHECK_DM_CLIENT_NAME "mods\\deathmatch\\Client_d.dll" - #define LOADER_PROXY_DLL_NAME "mtasa_d.dll" + #define MTA_EXE_NAME "Multi Theft Auto_d.exe" + #define MTA_DLL_NAME "core_d.dll" + #define CHECK_DM_LUA_NAME "mods\\deathmatch\\lua5.1c_d.dll" + #define CHECK_DM_CLIENT_NAME "mods\\deathmatch\\Client_d.dll" + #define LOADER_PROXY_DLL_NAME "mtasa_d.dll" #else - #define MTA_EXE_NAME "Multi Theft Auto.exe" - #define MTA_DLL_NAME "core.dll" - #define CHECK_DM_LUA_NAME "mods\\deathmatch\\lua5.1c.dll" - #define CHECK_DM_CLIENT_NAME "mods\\deathmatch\\Client.dll" - #define LOADER_PROXY_DLL_NAME "mtasa.dll" + #define MTA_EXE_NAME "Multi Theft Auto.exe" + #define MTA_DLL_NAME "core.dll" + #define CHECK_DM_LUA_NAME "mods\\deathmatch\\lua5.1c.dll" + #define CHECK_DM_CLIENT_NAME "mods\\deathmatch\\Client.dll" + #define LOADER_PROXY_DLL_NAME "mtasa.dll" #endif diff --git a/Client/loader/MainFunctions.cpp b/Client/loader/MainFunctions.cpp index ed90affbaa6..a6da5faaad1 100644 --- a/Client/loader/MainFunctions.cpp +++ b/Client/loader/MainFunctions.cpp @@ -49,12 +49,11 @@ namespace return false; const DWORD kInformationalCrashCodes[] = { - 0x40000015u, // STATUS_FATAL_APP_EXIT - 0x40010004u, // DBG_TERMINATE_PROCESS + 0x40000015u, // STATUS_FATAL_APP_EXIT + 0x40010004u, // DBG_TERMINATE_PROCESS }; - if (std::any_of(std::begin(kInformationalCrashCodes), std::end(kInformationalCrashCodes), - [exitCode](DWORD code) { return exitCode == code; })) + if (std::any_of(std::begin(kInformationalCrashCodes), std::end(kInformationalCrashCodes), [exitCode](DWORD code) { return exitCode == code; })) { return true; } @@ -69,16 +68,15 @@ namespace struct DebuggerCrashCapture { - DWORD exceptionCode = 0; - DWORD threadId = 0; - CONTEXT threadContext{}; - bool captured = false; - SString dumpPath; + DWORD exceptionCode = 0; + DWORD threadId = 0; + CONTEXT threadContext{}; + bool captured = false; + SString dumpPath; ModuleCrashInfo moduleInfo; // Resolved at capture time while process is alive }; -static void WriteFailFastDump(HANDLE hProcess, DWORD processId, DWORD threadId, - PEXCEPTION_RECORD pExceptionRecord, PCONTEXT pContext, +static void WriteFailFastDump(HANDLE hProcess, DWORD processId, DWORD threadId, PEXCEPTION_RECORD pExceptionRecord, PCONTEXT pContext, DebuggerCrashCapture& capture) { SString dumpDir = CalcMTASAPath("mta\\dumps\\private"); @@ -86,12 +84,10 @@ static void WriteFailFastDump(HANDLE hProcess, DWORD processId, DWORD threadId, SYSTEMTIME st; GetLocalTime(&st); - SString dumpFile = SString("failfast_%04d%02d%02d_%02d%02d%02d.dmp", - st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); + SString dumpFile = SString("failfast_%04d%02d%02d_%02d%02d%02d.dmp", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); SString dumpPath = PathJoin(dumpDir, dumpFile); - HANDLE hFile = CreateFileA(dumpPath, GENERIC_WRITE, 0, nullptr, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE hFile = CreateFileA(dumpPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { WriteDebugEvent(SString("Failed to create dump file: %s (error %lu)", dumpPath.c_str(), GetLastError())); @@ -99,7 +95,7 @@ static void WriteFailFastDump(HANDLE hProcess, DWORD processId, DWORD threadId, } MINIDUMP_EXCEPTION_INFORMATION mei{}; - EXCEPTION_POINTERS ep{}; + EXCEPTION_POINTERS ep{}; ep.ExceptionRecord = pExceptionRecord; ep.ContextRecord = pContext; mei.ThreadId = threadId; @@ -154,9 +150,9 @@ using WerDumpResult = WerCrash::WerDumpResult; static DWORD RunDebuggerLoop(HANDLE hProcess, DWORD processId, DebuggerCrashCapture& capture) { DEBUG_EVENT debugEvent{}; - DWORD continueStatus = DBG_CONTINUE; - DWORD exitCode = 0; - bool processExited = false; + DWORD continueStatus = DBG_CONTINUE; + DWORD exitCode = 0; + bool processExited = false; while (!processExited) { @@ -182,8 +178,7 @@ static DWORD RunDebuggerLoop(HANDLE hProcess, DWORD processId, DebuggerCrashCapt capture.exceptionCode = exCode; capture.threadId = debugEvent.dwThreadId; - HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, - FALSE, debugEvent.dwThreadId); + HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, debugEvent.dwThreadId); if (hThread) { capture.threadContext.ContextFlags = CONTEXT_ALL; @@ -193,15 +188,13 @@ static DWORD RunDebuggerLoop(HANDLE hProcess, DWORD processId, DebuggerCrashCapt // Resolve crash address to module NOW while process is still alive // This provides fallback if registry-based resolution fails - capture.moduleInfo = ResolveModuleCrashAddress( - capture.threadContext.Eip, hProcess); + capture.moduleInfo = ResolveModuleCrashAddress(capture.threadContext.Eip, hProcess); - WriteFailFastDump(hProcess, processId, debugEvent.dwThreadId, - &debugEvent.u.Exception.ExceptionRecord, - &capture.threadContext, capture); + WriteFailFastDump(hProcess, processId, debugEvent.dwThreadId, &debugEvent.u.Exception.ExceptionRecord, &capture.threadContext, + capture); - WriteDebugEvent(SString("Captured fail-fast 0x%08X: EIP=0x%08X ESP=0x%08X", - exCode, capture.threadContext.Eip, capture.threadContext.Esp)); + WriteDebugEvent( + SString("Captured fail-fast 0x%08X: EIP=0x%08X ESP=0x%08X", exCode, capture.threadContext.Eip, capture.threadContext.Esp)); } CloseHandle(hThread); } @@ -247,7 +240,7 @@ enum class CrashArtifactState : unsigned char Fresh, }; -constexpr auto kCrashArtifactStaleTolerance = std::chrono::seconds(2); +constexpr auto kCrashArtifactStaleTolerance = std::chrono::seconds(2); static constexpr std::size_t kCrashArtifactCount = 3; [[nodiscard]] static constexpr const char* CrashArtifactStateToString(CrashArtifactState state) noexcept @@ -263,8 +256,7 @@ static constexpr std::size_t kCrashArtifactCount = 3; } } -[[nodiscard]] static CrashArtifactState InspectCrashArtifact(const SString& path, - const std::optional& processCreationTime) noexcept +[[nodiscard]] static CrashArtifactState InspectCrashArtifact(const SString& path, const std::optional& processCreationTime) noexcept { WIN32_FILE_ATTRIBUTE_DATA attributes{}; if (!GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &attributes)) @@ -273,8 +265,7 @@ static constexpr std::size_t kCrashArtifactCount = 3; if (!processCreationTime.has_value()) return CrashArtifactState::Fresh; - if (const auto lastWrite = FileTimeToDuration(attributes.ftLastWriteTime); - lastWrite + kCrashArtifactStaleTolerance < *processCreationTime) + if (const auto lastWrite = FileTimeToDuration(attributes.ftLastWriteTime); lastWrite + kCrashArtifactStaleTolerance < *processCreationTime) return CrashArtifactState::Stale; return CrashArtifactState::Fresh; @@ -290,19 +281,17 @@ static constexpr std::size_t kCrashArtifactCount = 3; void CheckLibVersions() { #if MTASA_VERSION_TYPE >= VERSION_TYPE_UNTESTED - const char* moduleList[] = { - "MTA\\loader.dll", - "MTA\\cgui.dll", - "MTA\\core.dll", - "MTA\\game_sa.dll", - "MTA\\multiplayer_sa.dll", - "MTA\\netc.dll", - "MTA\\xmll.dll", - "MTA\\game_sa.dll", - "MTA\\" LOADER_PROXY_DLL_NAME, - "mods\\deathmatch\\client.dll", - "mods\\deathmatch\\pcre3.dll" - }; + const char* moduleList[] = {"MTA\\loader.dll", + "MTA\\cgui.dll", + "MTA\\core.dll", + "MTA\\game_sa.dll", + "MTA\\multiplayer_sa.dll", + "MTA\\netc.dll", + "MTA\\xmll.dll", + "MTA\\game_sa.dll", + "MTA\\" LOADER_PROXY_DLL_NAME, + "mods\\deathmatch\\client.dll", + "mods\\deathmatch\\pcre3.dll"}; SString strReqFileVersion; for (uint i = 0; i < NUMELMS(moduleList); i++) @@ -311,18 +300,17 @@ void CheckLibVersions() // Skip _d suffix for LOADER_PROXY_DLL_NAME and netc.dll as they don't use _d if (strFilename.find(LOADER_PROXY_DLL_NAME) == std::string::npos && strFilename.find("netc.dll") == std::string::npos) { -#ifdef MTA_DEBUG + #ifdef MTA_DEBUG strFilename = ExtractBeforeExtension(strFilename) + "_d." + ExtractExtension(strFilename); -#endif + #endif } SString fullPath = CalcMTASAPath(strFilename); if (!ValidatePath(fullPath)) { - DisplayErrorMessageBox(SStringX(_("Invalid module path detected.\n") + SString("\n[%s]\n", *strFilename)), - _E("CL49"), "invalid-module-path"); + DisplayErrorMessageBox(SStringX(_("Invalid module path detected.\n") + SString("\n[%s]\n", *strFilename)), _E("CL49"), "invalid-module-path"); ExitProcess(EXIT_ERROR); } - + SLibVersionInfo fileInfo; if (FileExists(fullPath)) { @@ -330,12 +318,10 @@ void CheckLibVersions() if (GetLibVersionInfo(fullPath, &fileInfo)) { // Validate version numbers - if (fileInfo.dwFileVersionMS > 0 && fileInfo.dwFileVersionMS < MAXDWORD && - fileInfo.dwFileVersionLS > 0 && fileInfo.dwFileVersionLS < MAXDWORD) + if (fileInfo.dwFileVersionMS > 0 && fileInfo.dwFileVersionMS < MAXDWORD && fileInfo.dwFileVersionLS > 0 && fileInfo.dwFileVersionLS < MAXDWORD) { - strFileVersion = SString("%d.%d.%d.%d", - fileInfo.dwFileVersionMS >> 16, fileInfo.dwFileVersionMS & 0xFFFF, - fileInfo.dwFileVersionLS >> 16, fileInfo.dwFileVersionLS & 0xFFFF); + strFileVersion = SString("%d.%d.%d.%d", fileInfo.dwFileVersionMS >> 16, fileInfo.dwFileVersionMS & 0xFFFF, fileInfo.dwFileVersionLS >> 16, + fileInfo.dwFileVersionLS & 0xFFFF); } } @@ -346,16 +332,15 @@ void CheckLibVersions() else if (strReqFileVersion != strFileVersion) { DisplayErrorMessageBox(SStringX(_("File version mismatch error. Reinstall MTA:SA if you experience problems.\n") + - SString("\n[%s %s/%s]\n", *strFilename, *strFileVersion, *strReqFileVersion)), - _E("CL40"), "bad-file-version"); + SString("\n[%s %s/%s]\n", *strFilename, *strFileVersion, *strReqFileVersion)), + _E("CL40"), "bad-file-version"); break; } } else { - DisplayErrorMessageBox(SStringX(_("Some files are missing. Reinstall MTA:SA if you experience problems.\n") + - SString("\n[%s]\n", *strFilename)), - _E("CL41"), "missing-file"); + DisplayErrorMessageBox(SStringX(_("Some files are missing. Reinstall MTA:SA if you experience problems.\n") + SString("\n[%s]\n", *strFilename)), + _E("CL41"), "missing-file"); break; } } @@ -364,8 +349,7 @@ void CheckLibVersions() // Check for Windows 'Safe Mode' if (GetSystemMetrics(SM_CLEANBOOT) != 0) { - DisplayErrorMessageBox(SStringX(_("MTA:SA is not compatible with Windows 'Safe Mode'.\n\nPlease restart your PC.\n")), - _E("CL42"), "safe-mode"); + DisplayErrorMessageBox(SStringX(_("MTA:SA is not compatible with Windows 'Safe Mode'.\n\nPlease restart your PC.\n")), _E("CL42"), "safe-mode"); ExitProcess(EXIT_ERROR); } } @@ -373,10 +357,10 @@ void CheckLibVersions() // Enum declarations for WSC health DECLARE_ENUM(WSC_SECURITY_PROVIDER_HEALTH) IMPLEMENT_ENUM_BEGIN(WSC_SECURITY_PROVIDER_HEALTH) - ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_GOOD, "good") - ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_NOTMONITORED, "not_monitored") - ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_POOR, "poor") - ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_SNOOZE, "snooze") +ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_GOOD, "good") +ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_NOTMONITORED, "not_monitored") +ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_POOR, "poor") +ADD_ENUM(WSC_SECURITY_PROVIDER_HEALTH_SNOOZE, "snooze") IMPLEMENT_ENUM_END("wsc_health") // Simplified localization dummy class @@ -386,8 +370,7 @@ class CLocalizationDummy final : public CLocalizationInterface SString Translate(const SString& strMessage) override { return strMessage; } SString TranslateWithContext(const SString& strContext, const SString& strMessage) override { return strMessage; } SString TranslatePlural(const SString& strSingular, const SString& strPlural, int iNum) override { return strPlural; } - SString TranslatePluralWithContext(const SString& strContext, const SString& strSingular, - const SString& strPlural, int iNum) override { return strPlural; } + SString TranslatePluralWithContext(const SString& strContext, const SString& strSingular, const SString& strPlural, int iNum) override { return strPlural; } std::vector GetAvailableLocales() override { return {}; } bool IsLocalized() override { return false; } SString GetLanguageDirectory(CLanguage* pLanguage = nullptr) override { return ""; } @@ -408,16 +391,17 @@ CLocalizationInterface* g_pLocalization = new CLocalizationDummy(); void InitLocalization(bool bShowErrors) { static bool bInitialized = false; - if (bInitialized) return; + if (bInitialized) + return; // Check for core.dll const SString strCoreDLL = PathJoin(GetLaunchPath(), "mta", MTA_DLL_NAME); if (!FileExists(strCoreDLL)) { - if (!bShowErrors) return; - DisplayErrorMessageBox("Load failed. Please ensure that the file " MTA_DLL_NAME - " is in the modules directory within the MTA root directory.", - _E("CL23"), "core-missing"); + if (!bShowErrors) + return; + DisplayErrorMessageBox("Load failed. Please ensure that the file " MTA_DLL_NAME " is in the modules directory within the MTA root directory.", + _E("CL23"), "core-missing"); ExitProcess(EXIT_ERROR); } @@ -426,8 +410,8 @@ void InitLocalization(bool bShowErrors) SetDllDirectory(PathJoin(strMTASAPath, "mta")); // See if xinput is loadable (XInput9_1_0.dll or xinput1_3.dll) - const DWORD dwPrevMode = SetErrorMode(SEM_FAILCRITICALERRORS); - const char* xinputModules[] = {"XInput9_1_0", "xinput1_3"}; + const DWORD dwPrevMode = SetErrorMode(SEM_FAILCRITICALERRORS); + const char* xinputModules[] = {"XInput9_1_0", "xinput1_3"}; for (uint i = 0; i < NUMELMS(xinputModules); ++i) { @@ -436,7 +420,7 @@ void InitLocalization(bool bShowErrors) HMODULE hXInputModule = LoadLibrary(strDllName); if (hXInputModule) { - FreeLibrary(hXInputModule); // Exists already - no need to copy + FreeLibrary(hXInputModule); // Exists already - no need to copy } else { @@ -455,15 +439,16 @@ void InitLocalization(bool bShowErrors) } // Load core.dll - if (bShowErrors) SetErrorMode(dwPrevMode); + if (bShowErrors) + SetErrorMode(dwPrevMode); HMODULE hCoreModule = LoadLibraryEx(strCoreDLL, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); SetErrorMode(dwPrevMode); if (!hCoreModule) { - if (!bShowErrors) return; - DisplayErrorMessageBox("Loading core failed. Please ensure that the latest DirectX is correctly installed.", - _E("CL24"), "core-not-loadable"); + if (!bShowErrors) + return; + DisplayErrorMessageBox("Loading core failed. Please ensure that the latest DirectX is correctly installed.", _E("CL24"), "core-not-loadable"); ExitProcess(EXIT_ERROR); } @@ -495,7 +480,7 @@ void InitLocalization(bool bShowErrors) } // Create localization interface - typedef CLocalizationInterface*(__cdecl* CreateLocalizationFunc)(SString); + typedef CLocalizationInterface*(__cdecl * CreateLocalizationFunc)(SString); auto pFunc = reinterpret_cast(static_cast(GetProcAddress(hCoreModule, "L10n_CreateLocalization"))); if (!pFunc) @@ -503,8 +488,8 @@ void InitLocalization(bool bShowErrors) FreeLibrary(hCoreModule); if (bShowErrors) { - DisplayErrorMessageBox("Loading localization failed. Please ensure that MTA San Andreas 1.6\\MTA\\locale is accessible.", - _E("CL26"), "localization-not-loadable"); + DisplayErrorMessageBox("Loading localization failed. Please ensure that MTA San Andreas 1.6\\MTA\\locale is accessible.", _E("CL26"), + "localization-not-loadable"); } return; } @@ -515,8 +500,8 @@ void InitLocalization(bool bShowErrors) FreeLibrary(hCoreModule); if (bShowErrors) { - DisplayErrorMessageBox("Loading localization failed. Please ensure that MTA San Andreas 1.6\\MTA\\locale is accessible.", - _E("CL26"), "localization-not-loadable"); + DisplayErrorMessageBox("Loading localization failed. Please ensure that MTA San Andreas 1.6\\MTA\\locale is accessible.", _E("CL26"), + "localization-not-loadable"); } return; } @@ -527,9 +512,9 @@ void InitLocalization(bool bShowErrors) // NOTE: hCoreModule is intentionally kept loaded as it contains the localization implementation bInitialized = true; - #ifdef MTA_DEBUG - TestDialogs(); - #endif +#ifdef MTA_DEBUG + TestDialogs(); +#endif } ////////////////////////////////////////////////////////// @@ -672,25 +657,23 @@ void HandleNotUsedMainMenu() std::vector matchTextList; const char* szProductName; const char* szTrouble; - } procItems[] = { - {{"\\Evolve"}, "Evolve", "not-used-menu-evolve"}, - {{"\\GbpSv.exe", "Diebold\\Warsaw"}, "GAS Tecnologia - G-Buster Browser Defense", "not-used-menu-gbpsv"} - }; + } procItems[] = {{{"\\Evolve"}, "Evolve", "not-used-menu-evolve"}, + {{"\\GbpSv.exe", "Diebold\\Warsaw"}, "GAS Tecnologia - G-Buster Browser Defense", "not-used-menu-gbpsv"}}; - bool foundProblemProcess = false; + bool foundProblemProcess = false; const size_t MAX_PROCESS_CHECKS = 100; - size_t processesChecked = 0; - + size_t processesChecked = 0; + for (uint i = 0; i < NUMELMS(procItems) && !foundProblemProcess; i++) { auto processList = MyEnumProcesses(true); - + if (processList.size() > 1000) { WriteDebugEvent("Too many processes to check"); break; } - + for (auto processId : processList) { if (++processesChecked > MAX_PROCESS_CHECKS) @@ -698,9 +681,9 @@ void HandleNotUsedMainMenu() WriteDebugEvent("Process check limit reached in HandleNotUsedMainMenu"); break; } - + SString strProcessFilename = GetProcessPathFilename(processId); - + // Validate process path if (!strProcessFilename.empty() && strProcessFilename.length() < MAX_PATH) { @@ -717,7 +700,8 @@ void HandleNotUsedMainMenu() } } } - if (foundProblemProcess) break; + if (foundProblemProcess) + break; } } } @@ -741,9 +725,10 @@ void HandleCustomStartMessage() if (strStartMessage.BeginsWith("vdetect")) { SString strFilename = strStartMessage.SplitRight("name="); - strStartMessage = _("WARNING\n\n" - "MTA:SA has detected unusual activity.\n" - "Please run a virus scan to ensure your system is secure.\n\n"); + strStartMessage = + _("WARNING\n\n" + "MTA:SA has detected unusual activity.\n" + "Please run a virus scan to ensure your system is secure.\n\n"); strStartMessage += SString(_("The detected file was: %s\n"), *strFilename); } @@ -766,7 +751,7 @@ void ConfigureWerDumpPath() // Get loader's own path directly - this is the install root where Multi Theft Auto.exe lives wchar_t loaderPath[MAX_PATH * 2]; - DWORD len = GetModuleFileNameW(NULL, loaderPath, NUMELMS(loaderPath)); + DWORD len = GetModuleFileNameW(NULL, loaderPath, NUMELMS(loaderPath)); if (len == 0 || len >= NUMELMS(loaderPath)) return; @@ -797,8 +782,7 @@ void ConfigureWerDumpPath() HMODULE hWer = LoadLibraryW(L"wer.dll"); if (hWer) { - auto pfnWerRegisterAppLocalDump = reinterpret_cast( - GetProcAddress(hWer, "WerRegisterAppLocalDump")); + auto pfnWerRegisterAppLocalDump = reinterpret_cast(GetProcAddress(hWer, "WerRegisterAppLocalDump")); if (pfnWerRegisterAppLocalDump) { @@ -812,25 +796,22 @@ void ConfigureWerDumpPath() // if WerRegisterAppLocalDump failed. // Note: WER LocalDumps only reads from HKLM, not HKCU (per Microsoft documentation). // Without admin privileges, we cannot update HKLM and stale entries from previous installs may persist. - const wchar_t* exeNames[] = { - L"gta_sa.exe", - loaderConfigured ? nullptr : L"Multi Theft Auto.exe" - }; + const wchar_t* exeNames[] = {L"gta_sa.exe", loaderConfigured ? nullptr : L"Multi Theft Auto.exe"}; for (const wchar_t* exeName : exeNames) { if (!exeName) continue; - SString regSubPath = SString("SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\%S", exeName); + SString regSubPath = SString("SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\%S", exeName); std::wstring regSubPathW = MbUTF8ToUTF16(regSubPath); HKEY hKey = nullptr; // Use KEY_WOW64_64KEY to write to the 64-bit registry view. // WER is a 64-bit system service that reads from the native 64-bit registry, // not the WOW6432Node that 32-bit apps normally access. - LONG result = RegCreateKeyExW(HKEY_LOCAL_MACHINE, regSubPathW.c_str(), 0, nullptr, - REG_OPTION_NON_VOLATILE, KEY_SET_VALUE | KEY_WOW64_64KEY, nullptr, &hKey, nullptr); + LONG result = RegCreateKeyExW(HKEY_LOCAL_MACHINE, regSubPathW.c_str(), 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE | KEY_WOW64_64KEY, nullptr, + &hKey, nullptr); if (result == ERROR_SUCCESS) { DWORD dumpType = 1; @@ -839,8 +820,7 @@ void ConfigureWerDumpPath() DWORD dumpCount = 10; RegSetValueExW(hKey, L"DumpCount", 0, REG_DWORD, reinterpret_cast(&dumpCount), sizeof(dumpCount)); - RegSetValueExW(hKey, L"DumpFolder", 0, REG_EXPAND_SZ, - reinterpret_cast(dumpPathW.c_str()), + RegSetValueExW(hKey, L"DumpFolder", 0, REG_EXPAND_SZ, reinterpret_cast(dumpPathW.c_str()), static_cast((dumpPathW.length() + 1) * sizeof(wchar_t))); RegCloseKey(hKey); @@ -878,7 +858,7 @@ void PreLaunchWatchDogs() #ifndef MTA_DEBUG if (WatchDogIsSectionOpen("L0")) { - WatchDogSetUncleanStop(true); // Flag to maybe do things differently if MTA exit code on last run was not 0 + WatchDogSetUncleanStop(true); // Flag to maybe do things differently if MTA exit code on last run was not 0 CheckAndShowFileOpenFailureMessage(); } else @@ -890,7 +870,7 @@ void PreLaunchWatchDogs() if (FileExists(strCrashFlagFilename)) { FileDelete(strCrashFlagFilename); - WatchDogSetLastRunCrash(true); // Flag to maybe do things differently if MTA crashed last run + WatchDogSetLastRunCrash(true); // Flag to maybe do things differently if MTA crashed last run } else { @@ -935,11 +915,11 @@ void PreLaunchWatchDogs() { int iChainLimit; if (WatchDogIsSectionOpen(WD_SECTION_POST_INSTALL)) - iChainLimit = 1; // Low limit if just installed + iChainLimit = 1; // Low limit if just installed else if (GetApplicationSettingInt("times-connected") == 0) - iChainLimit = 2; // Medium limit if have never connected in the past + iChainLimit = 2; // Medium limit if have never connected in the past else - iChainLimit = 3; // Normal limit + iChainLimit = 3; // Normal limit WatchDogCompletedSection(WD_SECTION_NOT_USED_MAIN_MENU); WatchDogIncCounter(WD_COUNTER_CRASH_CHAIN_BEFORE_USED_MAIN_MENU); @@ -957,8 +937,8 @@ void PreLaunchWatchDogs() // Clear down freeze on quit detection WatchDogCompletedSection("Q0"); - WatchDogBeginSection("L0"); // Gets closed if MTA exits with a return code of 0 - WatchDogBeginSection("L1"); // Gets closed when GTA is launched + WatchDogBeginSection("L0"); // Gets closed if MTA exits with a return code of 0 + WatchDogBeginSection("L1"); // Gets closed when GTA is launched SetApplicationSetting("diagnostics", "gta-fopen-fail", ""); SetApplicationSetting("diagnostics", "last-crash-reason", ""); SetApplicationSetting("diagnostics", "last-crash-module", ""); @@ -991,9 +971,9 @@ void HandleIfGTAIsAlreadyRunning() { if (IsGTARunning()) { - if (MessageBoxUTF8(0, - _("An instance of GTA: San Andreas is already running. It needs to be terminated before MTA:SA can be started. Do you want to do that now?"), - _("Information") + _E("CL10"), MB_YESNO | MB_ICONQUESTION | MB_TOPMOST) == IDYES) + if (MessageBoxUTF8( + 0, _("An instance of GTA: San Andreas is already running. It needs to be terminated before MTA:SA can be started. Do you want to do that now?"), + _("Information") + _E("CL10"), MB_YESNO | MB_ICONQUESTION | MB_TOPMOST) == IDYES) { TerminateOtherMTAIfRunning(); TerminateGTAIfRunning(); @@ -1053,15 +1033,17 @@ void HandleSpecialLaunchOptions() void HandleDuplicateLaunching() { LPSTR lpCmdLine = GetCommandLine(); - if (!lpCmdLine) ExitProcess(EXIT_ERROR); + if (!lpCmdLine) + ExitProcess(EXIT_ERROR); // Validate command line length const size_t cmdLineLen = strlen(lpCmdLine); - if (cmdLineLen >= 32768) ExitProcess(EXIT_ERROR); // Max Windows command line length + if (cmdLineLen >= 32768) + ExitProcess(EXIT_ERROR); // Max Windows command line length bool bIsCrashDialog = (cmdLineLen > 0 && strstr(lpCmdLine, "install_stage=crashed") != NULL); - int recheckTime = 2000; // 2 seconds recheck time + int recheckTime = 2000; // 2 seconds recheck time // We can only do certain things if MTA is already running // Unless this is a crash dialog launch, which needs to run alongside the crashed instance @@ -1074,15 +1056,17 @@ void HandleDuplicateLaunching() { // Command line args present, so pass it on HWND hwMTAWindow = FindWindow(NULL, "MTA: San Andreas"); - #ifdef MTA_DEBUG - if (!hwMTAWindow) hwMTAWindow = FindWindow(NULL, "MTA: San Andreas [DEBUG]"); - #endif +#ifdef MTA_DEBUG + if (!hwMTAWindow) + hwMTAWindow = FindWindow(NULL, "MTA: San Andreas [DEBUG]"); +#endif if (hwMTAWindow) { // Parse URI from command line LPWSTR szCommandLine = GetCommandLineW(); - if (!szCommandLine) continue; + if (!szCommandLine) + continue; int numArgs = 0; LPWSTR* aCommandLineArgs = CommandLineToArgvW(szCommandLine, &numArgs); @@ -1091,10 +1075,11 @@ void HandleDuplicateLaunching() { for (int i = 1; i < numArgs; ++i) { - if (!aCommandLineArgs[i]) continue; + if (!aCommandLineArgs[i]) + continue; WString wideArg = aCommandLineArgs[i]; - if (wideArg.length() > 8 && wideArg.length() < 2048 && // Max MTA connect URI length + if (wideArg.length() > 8 && wideArg.length() < 2048 && // Max MTA connect URI length WStringX(wideArg).BeginsWith(L"mtasa://")) { SString strConnectInfo = ToUTF8(wideArg); @@ -1106,13 +1091,12 @@ void HandleDuplicateLaunching() if (strConnectInfo.Contains("..") || strConnectInfo.Contains("\\\\")) continue; - COPYDATASTRUCT cdStruct = {URI_CONNECT, static_cast(strConnectInfo.length() + 1), - const_cast(strConnectInfo.c_str())}; + COPYDATASTRUCT cdStruct = {URI_CONNECT, static_cast(strConnectInfo.length() + 1), const_cast(strConnectInfo.c_str())}; // Use SendMessageTimeout to prevent hanging DWORD_PTR dwResult = 0; - SendMessageTimeout(hwMTAWindow, WM_COPYDATA, NULL, reinterpret_cast(&cdStruct), SMTO_ABORTIFHUNG | SMTO_BLOCK, - 5000, &dwResult); + SendMessageTimeout(hwMTAWindow, WM_COPYDATA, NULL, reinterpret_cast(&cdStruct), SMTO_ABORTIFHUNG | SMTO_BLOCK, 5000, + &dwResult); break; } } @@ -1128,10 +1112,11 @@ void HandleDuplicateLaunching() } else { - const SString strMessage = _("Trouble restarting MTA:SA\n\n" - "If the problem persists, open Task Manager and\n" - "stop the 'gta_sa.exe' and 'Multi Theft Auto.exe' processes\n\n\n" - "Try to launch MTA:SA again?"); + const SString strMessage = + _("Trouble restarting MTA:SA\n\n" + "If the problem persists, open Task Manager and\n" + "stop the 'gta_sa.exe' and 'Multi Theft Auto.exe' processes\n\n\n" + "Try to launch MTA:SA again?"); if (MessageBoxUTF8(0, strMessage, _("Error") + _E("CL04"), MB_ICONWARNING | MB_YESNO | MB_TOPMOST) == IDYES) { @@ -1152,13 +1137,15 @@ void HandleDuplicateLaunching() // No command line args, so just bring to front if (!IsGTARunning() && !IsOtherMTARunning()) { - MessageBoxUTF8(0, _("Another instance of MTA is already running.\n\n" - "If this problem persists, please restart your computer"), - _("Error") + _E("CL05"), MB_ICONERROR | MB_TOPMOST); + MessageBoxUTF8(0, + _("Another instance of MTA is already running.\n\n" + "If this problem persists, please restart your computer"), + _("Error") + _E("CL05"), MB_ICONERROR | MB_TOPMOST); } - else if (MessageBoxUTF8(0, _("Another instance of MTA is already running.\n\n" - "Do you want to terminate it?"), - _("Error") + _E("CL06"), MB_ICONQUESTION | MB_YESNO | MB_TOPMOST) == IDYES) + else if (MessageBoxUTF8(0, + _("Another instance of MTA is already running.\n\n" + "Do you want to terminate it?"), + _("Error") + _E("CL06"), MB_ICONQUESTION | MB_YESNO | MB_TOPMOST) == IDYES) { TerminateGTAIfRunning(); TerminateOtherMTAIfRunning(); @@ -1193,16 +1180,15 @@ void ValidateGTAPath() if (result == GAME_PATH_MISSING) { - DisplayErrorMessageBox(_("Registry entries are missing. Please reinstall Multi Theft Auto: San Andreas."), - _E("CL12"), "reg-entries-missing"); + DisplayErrorMessageBox(_("Registry entries are missing. Please reinstall Multi Theft Auto: San Andreas."), _E("CL12"), "reg-entries-missing"); ExitProcess(EXIT_ERROR); } else if (result == GAME_PATH_UNICODE_CHARS) { DisplayErrorMessageBox(_("The path to your installation of GTA: San Andreas contains unsupported (unicode) characters. " - "Please move your Grand Theft Auto: San Andreas installation to a compatible path that contains " - "only standard ASCII characters and reinstall Multi Theft Auto: San Andreas."), - _E("CL13")); + "Please move your Grand Theft Auto: San Andreas installation to a compatible path that contains " + "only standard ASCII characters and reinstall Multi Theft Auto: San Andreas."), + _E("CL13")); ExitProcess(EXIT_ERROR); } @@ -1213,10 +1199,10 @@ void ValidateGTAPath() if (strGTAPath.Contains(";") || strMTASAPath.Contains(";")) { DisplayErrorMessageBox(_("The path to your installation of 'MTA:SA' or 'GTA: San Andreas'\n" - "contains a ';' (semicolon).\n\n" - "If you experience problems when running MTA:SA,\n" - "move your installation(s) to a path that does not contain a semicolon."), - _E("CL15"), "path-semicolon"); + "contains a ';' (semicolon).\n\n" + "If you experience problems when running MTA:SA,\n" + "move your installation(s) to a path that does not contain a semicolon."), + _E("CL15"), "path-semicolon"); } } @@ -1232,13 +1218,16 @@ void CheckAntiVirusStatus() std::vector enabledList, disabledList; GetWMIAntiVirusStatus(enabledList, disabledList); - if (enabledList.size() > 100) enabledList.resize(100); - if (disabledList.size() > 100) disabledList.resize(100); + if (enabledList.size() > 100) + enabledList.resize(100); + if (disabledList.size() > 100) + disabledList.resize(100); WSC_SECURITY_PROVIDER_HEALTH health = static_cast(-1); // Get windows defender status - static const auto WscGetHealth = []() -> decltype(&WscGetSecurityProviderHealth) { + static const auto WscGetHealth = []() -> decltype(&WscGetSecurityProviderHealth) + { if (HMODULE wscapi = LoadLibraryW(L"Wscapi.dll")) { auto function = static_cast(GetProcAddress(wscapi, "WscGetSecurityProviderHealth")); @@ -1253,18 +1242,20 @@ void CheckAntiVirusStatus() } SString strStatus; - strStatus.reserve(512); // Pre-allocate to prevent reallocation + strStatus.reserve(512); // Pre-allocate to prevent reallocation strStatus += SString("AV health: %s (%d)", *EnumToString(health), static_cast(health)); const size_t maxStatusItems = 10; for (size_t i = 0; i < enabledList.size() && i < maxStatusItems; ++i) { - if (strStatus.length() > 400) break; // Prevent status string from growing too large + if (strStatus.length() > 400) + break; // Prevent status string from growing too large strStatus += SString(" [Ena%zu:%s]", i, *enabledList[i]); } for (size_t i = 0; i < disabledList.size() && i < maxStatusItems; ++i) { - if (strStatus.length() > 400) break; // Prevent status string from growing too large + if (strStatus.length() > 400) + break; // Prevent status string from growing too large strStatus += SString(" [Dis%zu:%s]", i, *disabledList[i]); } @@ -1277,22 +1268,18 @@ void CheckAntiVirusStatus() if (showWarning) { // Check for AV in loaded modules - static const char* avProducts[] = { - "antivirus", "anti-virus", "Avast", "AVG", "Avira", "NOD32", "ESET", - "F-Secure", "Faronics", "Kaspersky", "McAfee", "Norton", "Symantec", - "Panda", "Trend Micro" - }; + static const char* avProducts[] = {"antivirus", "anti-virus", "Avast", "AVG", "Avira", "NOD32", "ESET", "F-Secure", + "Faronics", "Kaspersky", "McAfee", "Norton", "Symantec", "Panda", "Trend Micro"}; // Check for AV in loaded modules std::array modules; - DWORD cbNeeded; + DWORD cbNeeded; - if (EnumProcessModules(GetCurrentProcess(), modules.data(), - static_cast(sizeof(modules)), &cbNeeded)) + if (EnumProcessModules(GetCurrentProcess(), modules.data(), static_cast(sizeof(modules)), &cbNeeded)) { - DWORD moduleCount = cbNeeded / sizeof(HMODULE); + DWORD moduleCount = cbNeeded / sizeof(HMODULE); const DWORD maxModules = static_cast(modules.size()); - + if (cbNeeded > 0 && cbNeeded < MAXDWORD && (cbNeeded % sizeof(HMODULE)) == 0) { if (moduleCount > maxModules) @@ -1303,24 +1290,23 @@ void CheckAntiVirusStatus() for (DWORD i = 0; i < moduleCount && showWarning; ++i) { - if (!modules[i]) continue; + if (!modules[i]) + continue; WCHAR modulePath[MAX_PATH * 2] = L""; - DWORD pathLen = GetModuleFileNameExW(GetCurrentProcess(), modules[i], - modulePath, NUMELMS(modulePath) - 1); - + DWORD pathLen = GetModuleFileNameExW(GetCurrentProcess(), modules[i], modulePath, NUMELMS(modulePath) - 1); + // Ensure null-termination if (pathLen > 0 && pathLen < NUMELMS(modulePath)) { modulePath[pathLen] = L'\0'; - + SLibVersionInfo libInfo; if (GetLibVersionInfo(ToUTF8(modulePath), &libInfo)) { for (uint j = 0; j < NUMELMS(avProducts); ++j) { - if (libInfo.strCompanyName.ContainsI(avProducts[j]) || - libInfo.strProductName.ContainsI(avProducts[j])) + if (libInfo.strCompanyName.ContainsI(avProducts[j]) || libInfo.strProductName.ContainsI(avProducts[j])) { showWarning = false; WriteDebugEvent(SString("AV (module) found: %s", *ToUTF8(modulePath))); @@ -1337,43 +1323,43 @@ void CheckAntiVirusStatus() } } - // Check for running processes for AV - if (showWarning) - { - auto processList = MyEnumProcesses(true); - - const size_t maxProcessesToCheck = 500; - size_t processesChecked = 0; - - for (auto processId : processList) - { - if (++processesChecked > maxProcessesToCheck) + // Check for running processes for AV + if (showWarning) { - WriteDebugEvent("Process check limit reached"); - break; - } - - SString processPath = GetProcessPathFilename(processId); - if (!processPath.empty() && ValidatePath(processPath)) - { - SLibVersionInfo libInfo; - if (GetLibVersionInfo(processPath, &libInfo)) + auto processList = MyEnumProcesses(true); + + const size_t maxProcessesToCheck = 500; + size_t processesChecked = 0; + + for (auto processId : processList) { - for (uint i = 0; i < NUMELMS(avProducts); ++i) + if (++processesChecked > maxProcessesToCheck) { - if (libInfo.strCompanyName.ContainsI(avProducts[i]) || - libInfo.strProductName.ContainsI(avProducts[i])) + WriteDebugEvent("Process check limit reached"); + break; + } + + SString processPath = GetProcessPathFilename(processId); + if (!processPath.empty() && ValidatePath(processPath)) + { + SLibVersionInfo libInfo; + if (GetLibVersionInfo(processPath, &libInfo)) { - showWarning = false; - WriteDebugEvent(SString("AV (process) found: %s", *processPath)); - break; + for (uint i = 0; i < NUMELMS(avProducts); ++i) + { + if (libInfo.strCompanyName.ContainsI(avProducts[i]) || libInfo.strProductName.ContainsI(avProducts[i])) + { + showWarning = false; + WriteDebugEvent(SString("AV (process) found: %s", *processPath)); + break; + } + } } } + if (!showWarning) + break; } } - if (!showWarning) break; - } - } } ShowNoAvDialog(g_hInstance, showWarning); @@ -1400,7 +1386,7 @@ void CheckDataFiles() } // No-op known incompatible/broken d3d9.dll versions from the launch directory - // By using file version we account for variants as well. The array is extendable, but primarily for D3D9.dll 6.3.9600.17415 (MTA top 5 crash) + // By using file version we account for variants as well. The array is extendable, but primarily for D3D9.dll 6.3.9600.17415 (MTA top 5 crash) { struct SIncompatibleVersion { @@ -1423,11 +1409,12 @@ void CheckDataFiles() { bChecked = true; - // Check all 3 game roots + // Check all 3 game roots const std::vector directoriesToCheck = { - GetLaunchPath(), // MTA installation folder root - strGTAPath, // Real GTA:SA installation folder root. As chosen by DiscoverGTAPath() - PathJoin(GetMTADataPath(), "GTA San Andreas"), // Proxy-mirror that MTA uses for core GTA data files (C:\ProgramData\MTA San Andreas All\\GTA San Andreas) + GetLaunchPath(), // MTA installation folder root + strGTAPath, // Real GTA:SA installation folder root. As chosen by DiscoverGTAPath() + PathJoin(GetMTADataPath(), "GTA San Andreas"), // Proxy-mirror that MTA uses for core GTA data files (C:\ProgramData\MTA San Andreas All\\GTA San Andreas) }; for (const SString& directory : directoriesToCheck) @@ -1448,10 +1435,8 @@ void CheckDataFiles() bool bIsIncompatible = false; for (const SIncompatibleVersion& entry : incompatibleVersions) { - if (versionInfo.GetFileVersionMajor() == entry.iMajor && - versionInfo.GetFileVersionMinor() == entry.iMinor && - versionInfo.GetFileVersionBuild() == entry.iBuild && - versionInfo.GetFileVersionRelease() == entry.iRelease) + if (versionInfo.GetFileVersionMajor() == entry.iMajor && versionInfo.GetFileVersionMinor() == entry.iMinor && + versionInfo.GetFileVersionBuild() == entry.iBuild && versionInfo.GetFileVersionRelease() == entry.iRelease) { bIsIncompatible = true; break; @@ -1496,38 +1481,36 @@ void CheckDataFiles() } // Check for essential MTA files - static const char* dataFiles[] = { - "MTA\\cgui\\images\\background_logo.png", - "MTA\\cgui\\images\\radarset\\up.png", - "MTA\\cgui\\images\\busy_spinner.png", - "MTA\\data\\gta_sa_diff.dat", - "MTA\\D3DX9_42.dll", - "MTA\\D3DCompiler_42.dll", - "MTA\\d3dcompiler_43.dll", - "MTA\\d3dcompiler_47.dll", - "MTA\\bass.dll", - "MTA\\bass_ac3.dll", - "MTA\\bassflac.dll", - "MTA\\bassmix.dll", - "MTA\\basswebm.dll", - "MTA\\bass_aac.dll", - "MTA\\bass_fx.dll", - "MTA\\bassmidi.dll", - "MTA\\bassopus.dll", - "MTA\\basswma.dll", - "MTA\\tags.dll", - "MTA\\sa.dat", - "MTA\\xinput1_3_mta.dll", - "MTA\\XInput9_1_0_mta.dll" - }; + static const char* dataFiles[] = {"MTA\\cgui\\images\\background_logo.png", + "MTA\\cgui\\images\\radarset\\up.png", + "MTA\\cgui\\images\\busy_spinner.png", + "MTA\\data\\gta_sa_diff.dat", + "MTA\\D3DX9_42.dll", + "MTA\\D3DCompiler_42.dll", + "MTA\\d3dcompiler_43.dll", + "MTA\\d3dcompiler_47.dll", + "MTA\\bass.dll", + "MTA\\bass_ac3.dll", + "MTA\\bassflac.dll", + "MTA\\bassmix.dll", + "MTA\\basswebm.dll", + "MTA\\bass_aac.dll", + "MTA\\bass_fx.dll", + "MTA\\bassmidi.dll", + "MTA\\bassopus.dll", + "MTA\\basswma.dll", + "MTA\\tags.dll", + "MTA\\sa.dat", + "MTA\\xinput1_3_mta.dll", + "MTA\\XInput9_1_0_mta.dll"}; for (uint i = 0; i < NUMELMS(dataFiles); ++i) { const SString filePath = PathJoin(strMTASAPath, dataFiles[i]); if (!ValidatePath(filePath) || !FileExists(filePath)) { - DisplayErrorMessageBox(_("Load failed. Please ensure that the latest data files have been installed correctly."), - _E("CL16"), "mta-datafiles-missing"); + DisplayErrorMessageBox(_("Load failed. Please ensure that the latest data files have been installed correctly."), _E("CL16"), + "mta-datafiles-missing"); ExitProcess(EXIT_ERROR); } } @@ -1535,31 +1518,26 @@ void CheckDataFiles() // Check for client deathmatch module if (!FileExists(PathJoin(strMTASAPath, CHECK_DM_CLIENT_NAME))) { - DisplayErrorMessageBox(SString(_("Load failed. Please ensure that %s is installed correctly."), CHECK_DM_CLIENT_NAME), - _E("CL18"), "client-missing"); + DisplayErrorMessageBox(SString(_("Load failed. Please ensure that %s is installed correctly."), CHECK_DM_CLIENT_NAME), _E("CL18"), "client-missing"); ExitProcess(EXIT_ERROR); } // Check for GTA executable - if (!FileExists(PathJoin(strGTAPath, GTA_EXE_NAME)) && - !FileExists(PathJoin(strGTAPath, STEAM_GTA_EXE_NAME))) + if (!FileExists(PathJoin(strGTAPath, GTA_EXE_NAME)) && !FileExists(PathJoin(strGTAPath, STEAM_GTA_EXE_NAME))) { - DisplayErrorMessageBox(SString(_("Load failed. Could not find gta_sa.exe in %s."), strGTAPath.c_str()), - _E("CL20"), "gta_sa-missing"); + DisplayErrorMessageBox(SString(_("Load failed. Could not find gta_sa.exe in %s."), strGTAPath.c_str()), _E("CL20"), "gta_sa-missing"); ExitProcess(EXIT_ERROR); } // Check for conflicting files - static const char* dllConflicts[] = { - "xmll.dll", "cgui.dll", "netc.dll", "libcurl.dll", "pthread.dll" - }; + static const char* dllConflicts[] = {"xmll.dll", "cgui.dll", "netc.dll", "libcurl.dll", "pthread.dll"}; for (uint i = 0; i < NUMELMS(dllConflicts); ++i) { if (FileExists(PathJoin(strGTAPath, dllConflicts[i]))) { - DisplayErrorMessageBox(SString(_("Load failed. %s exists in the GTA directory. Please delete before continuing."), dllConflicts[i]), - _E("CL21"), "file-clash"); + DisplayErrorMessageBox(SString(_("Load failed. %s exists in the GTA directory. Please delete before continuing."), dllConflicts[i]), _E("CL21"), + "file-clash"); ExitProcess(EXIT_ERROR); } } @@ -1589,25 +1567,15 @@ void CheckDataFiles() }; static const IntegrityCheck integrityCheckList[] = { - {"DE5C08577EAA65309974F9860E303F53", "bass.dll"}, - {"1D5A1AEF041255DEA49CD4780CAE4CCC", "bass_aac.dll"}, - {"8A1AC2AAD7F1691943635CA42F7F2940", "bass_ac3.dll"}, - {"61C38C1FD091375F2A30EC631DF337E6", "bass_fx.dll"}, - {"F47DCE69DAFAA06A55A4BC1F07F80C8A", "bassflac.dll"}, - {"49A603ED114982787FC0A301C0E93FDB", "bassmidi.dll"}, - {"064398B1A74B4EF35902F0C218142133", "bassmix.dll"}, - {"9CFA31A873FF89C2CC491B9974FC5C65", "bassopus.dll"}, - {"B35714019BBFF0D0CEE0AFA2637A77A7", "basswebm.dll"}, - {"1507C60C02E159B5FB247FEC6B209B09", "basswma.dll"}, - {"C6A44FC3CF2F5801561804272217B14D", "D3DX9_42.dll"}, - {"D439E8EDD8C93D7ADE9C04BCFE9197C6", "sa.dat"}, - {"B33B21DB610116262D906305CE65C354", "D3DCompiler_42.dll"}, - {"4B3932359373F11CBC542CC96D9A9285", "tags.dll"}, - {"0B3DD892007FB366D1F52F2247C046F5", "d3dcompiler_43.dll"}, - {"D5D8C8561C6DDA7EF0D7D6ABB0D772F4", "xinput1_3_mta.dll"}, - {"2C0C596EE071B93CE15130BD5EE9CD31", "d3dcompiler_47.dll"}, - {"F1CA5A1E77965777AC26A81EAF345A7A", "XInput9_1_0_mta.dll"} - }; + {"DE5C08577EAA65309974F9860E303F53", "bass.dll"}, {"1D5A1AEF041255DEA49CD4780CAE4CCC", "bass_aac.dll"}, + {"8A1AC2AAD7F1691943635CA42F7F2940", "bass_ac3.dll"}, {"61C38C1FD091375F2A30EC631DF337E6", "bass_fx.dll"}, + {"F47DCE69DAFAA06A55A4BC1F07F80C8A", "bassflac.dll"}, {"49A603ED114982787FC0A301C0E93FDB", "bassmidi.dll"}, + {"064398B1A74B4EF35902F0C218142133", "bassmix.dll"}, {"9CFA31A873FF89C2CC491B9974FC5C65", "bassopus.dll"}, + {"B35714019BBFF0D0CEE0AFA2637A77A7", "basswebm.dll"}, {"1507C60C02E159B5FB247FEC6B209B09", "basswma.dll"}, + {"C6A44FC3CF2F5801561804272217B14D", "D3DX9_42.dll"}, {"D439E8EDD8C93D7ADE9C04BCFE9197C6", "sa.dat"}, + {"B33B21DB610116262D906305CE65C354", "D3DCompiler_42.dll"}, {"4B3932359373F11CBC542CC96D9A9285", "tags.dll"}, + {"0B3DD892007FB366D1F52F2247C046F5", "d3dcompiler_43.dll"}, {"D5D8C8561C6DDA7EF0D7D6ABB0D772F4", "xinput1_3_mta.dll"}, + {"2C0C596EE071B93CE15130BD5EE9CD31", "d3dcompiler_47.dll"}, {"F1CA5A1E77965777AC26A81EAF345A7A", "XInput9_1_0_mta.dll"}}; for (uint i = 0; i < NUMELMS(integrityCheckList); ++i) { @@ -1615,16 +1583,14 @@ void CheckDataFiles() const SString filePath = PathJoin(strMTASAPath, "mta", check.fileName); if (!ValidatePath(filePath) || !FileExists(filePath)) { - DisplayErrorMessageBox(SString(_("Data file %s is missing. Possible virus activity."), check.fileName), - _E("CL30"), "maybe-virus2"); + DisplayErrorMessageBox(SString(_("Data file %s is missing. Possible virus activity."), check.fileName), _E("CL30"), "maybe-virus2"); break; } const SString computed = CMD5Hasher::CalculateHexString(filePath); if (!computed.CompareI(check.hash)) { - DisplayErrorMessageBox(SString(_("Data file %s is modified. Possible virus activity."), check.fileName), - _E("CL30"), "maybe-virus2"); + DisplayErrorMessageBox(SString(_("Data file %s is modified. Possible virus activity."), check.fileName), _E("CL30"), "maybe-virus2"); break; } } @@ -1634,8 +1600,8 @@ void CheckDataFiles() std::vector mtaAsiFiles = FindFiles(PathJoin(strMTASAPath, "mta", "*.asi"), true, false); const size_t MAX_ASI_FILES = 100; - bool bFoundInGTADir = !gtaAsiFiles.empty() && gtaAsiFiles.size() < MAX_ASI_FILES; - bool bFoundInMTADir = !mtaAsiFiles.empty() && mtaAsiFiles.size() < MAX_ASI_FILES; + bool bFoundInGTADir = !gtaAsiFiles.empty() && gtaAsiFiles.size() < MAX_ASI_FILES; + bool bFoundInMTADir = !mtaAsiFiles.empty() && mtaAsiFiles.size() < MAX_ASI_FILES; if (bFoundInGTADir || bFoundInMTADir) { @@ -1646,39 +1612,38 @@ void CheckDataFiles() WriteDebugEvent(SString("Warning: ASI file detected in GTA dir: %s", *gtaAsiFiles[i])); } } - + DisplayErrorMessageBox(_(".asi files are in the installation directory.\n\n" - "Remove these .asi files if you experience problems."), - _E("CL28"), "asi-files"); + "Remove these .asi files if you experience problems."), + _E("CL28"), "asi-files"); } // Check for graphics libraries in the GTA/MTA install directory { - const std::pair directoriesToCheck[] = { - {"", strGTAPath}, - {"mta-", PathJoin(strMTASAPath, "mta")} - }; + const std::pair directoriesToCheck[] = {{"", strGTAPath}, {"mta-", PathJoin(strMTASAPath, "mta")}}; std::vector offenders; for (const std::pair& directory : directoriesToCheck) { - if (!ValidatePath(directory.second)) continue; + if (!ValidatePath(directory.second)) + continue; for (const char* libraryName : {"d3d9", "dxgi"}) { GraphicsLibrary library(libraryName); library.absoluteFilePath = PathJoin(directory.second, library.stem + ".dll"); - if (library.absoluteFilePath.length() > MAX_PATH) continue; - if (!FileExists(library.absoluteFilePath)) continue; + if (library.absoluteFilePath.length() > MAX_PATH) + continue; + if (!FileExists(library.absoluteFilePath)) + continue; library.appLastHash = SString("%s%s-dll-last-hash", directory.first, library.stem.c_str()); library.appDontRemind = SString("%s%s-dll-not-again", directory.first, library.stem.c_str()); library.md5Hash = CMD5Hasher::CalculateHexString(library.absoluteFilePath); - WriteDebugEvent(SString("Detected graphics library %s (md5: %s)", - library.absoluteFilePath.c_str(), library.md5Hash.c_str())); + WriteDebugEvent(SString("Detected graphics library %s (md5: %s)", library.absoluteFilePath.c_str(), library.md5Hash.c_str())); bool isProblematic = true; if (GetApplicationSetting("diagnostics", library.appLastHash) == library.md5Hash) @@ -1727,8 +1692,7 @@ void CheckDataFiles() // ////////////////////////////////////////////////////////// BOOL StartGtaProcess(const SString& lpApplicationName, const SString& lpCommandLine, const SString& lpCurrentDirectory, - LPPROCESS_INFORMATION lpProcessInformation, DWORD& dwOutError, SString& strOutErrorContext, - bool bAsDebugger = false) + LPPROCESS_INFORMATION lpProcessInformation, DWORD& dwOutError, SString& strOutErrorContext, bool bAsDebugger = false) { STARTUPINFOW startupInfo{}; startupInfo.cb = sizeof(startupInfo); @@ -1810,8 +1774,8 @@ int LaunchGame(SString strCmdLine) CheckAndShowUpgradeProblems(); CheckAndShowImgProblems(); - const SString strGTAPath = GetGTAPath(); - const SString strMTASAPath = GetMTASAPath(); + const SString strGTAPath = GetGTAPath(); + const SString strMTASAPath = GetMTASAPath(); const SString strGTAEXEPath = UTF8FilePath(GetGameExecutablePath()); if (!ValidatePath(strGTAPath) || !ValidatePath(strMTASAPath) || !ValidatePath(strGTAEXEPath)) @@ -1832,17 +1796,17 @@ int LaunchGame(SString strCmdLine) BeginD3DStuff(); LogSettings(); - WatchDogBeginSection("L2"); // Gets closed when loading screen is shown - WatchDogBeginSection("L3"); // Gets closed when loading screen is shown, or a startup problem is handled elsewhere - WatchDogBeginSection(WD_SECTION_NOT_USED_MAIN_MENU); // Gets closed when the main menu is used + WatchDogBeginSection("L2"); // Gets closed when loading screen is shown + WatchDogBeginSection("L3"); // Gets closed when loading screen is shown, or a startup problem is handled elsewhere + WatchDogBeginSection(WD_SECTION_NOT_USED_MAIN_MENU); // Gets closed when the main menu is used // Extract 'done-admin' flag from command line SString sanitizedCmdLine = strCmdLine; - const bool bDoneAdmin = sanitizedCmdLine.Contains("/done-admin"); - sanitizedCmdLine = sanitizedCmdLine.Replace(" /done-admin", ""); + const bool bDoneAdmin = sanitizedCmdLine.Contains("/done-admin"); + sanitizedCmdLine = sanitizedCmdLine.Replace(" /done-admin", ""); // Validate command line length - if (sanitizedCmdLine.length() > 2048) // Max MTA connect URI length + if (sanitizedCmdLine.length() > 2048) // Max MTA connect URI length { sanitizedCmdLine = sanitizedCmdLine.Left(2048); } @@ -1858,14 +1822,14 @@ int LaunchGame(SString strCmdLine) // Note: Our Debugger mode (DEBUG_ONLY_THIS_PROCESS) can capture fail-fast crashes // (like 0xC0000374, 0xC0000409, Subcode: 0x7 FAST_FAIL_FATAL_APP_EXIT, "abort" signal @ minkernel\crts\ucrt\src\appcrt\startup\abort.cpp) // .. with full context, but it interferes with core.dll's normal crash handler. Only enable for diagnostics. - PROCESS_INFORMATION piLoadee = {}; - DWORD dwError = 0; - SString strErrorContext; - bool bLaunchedAsDebugger = false; + PROCESS_INFORMATION piLoadee = {}; + DWORD dwError = 0; + SString strErrorContext; + bool bLaunchedAsDebugger = false; DebuggerCrashCapture debugCapture{}; const SString debuggerFlagValue = GetApplicationSetting("diagnostics", "debugger-crash-capture"); - const bool bUseDebuggerMode = (debuggerFlagValue == "1"); + const bool bUseDebuggerMode = (debuggerFlagValue == "1"); WriteDebugEvent(SString("[7200] Loader - Debugger flag check: value='%s' useDebugger=%d", debuggerFlagValue.c_str(), bUseDebuggerMode ? 1 : 0)); if (bUseDebuggerMode) @@ -1899,8 +1863,7 @@ int LaunchGame(SString strCmdLine) std::optional gtaCreationTime; if (HANDLE processHandle = piLoadee.hProcess; processHandle && processHandle != INVALID_HANDLE_VALUE) { - if (FILETIME ftCreate{}, ftExit{}, ftKernel{}, ftUser{}; - GetProcessTimes(processHandle, &ftCreate, &ftExit, &ftKernel, &ftUser)) + if (FILETIME ftCreate{}, ftExit{}, ftKernel{}, ftUser{}; GetProcessTimes(processHandle, &ftCreate, &ftExit, &ftKernel, &ftUser)) { gtaCreationTime = FileTimeToDuration(ftCreate); } @@ -1937,11 +1900,11 @@ int LaunchGame(SString strCmdLine) { // Wait for game window DWORD status = WAIT_TIMEOUT; - for (uint i = 0; i < 20 && status == WAIT_TIMEOUT; ++i) // Max 20 iterations + for (uint i = 0; i < 20 && status == WAIT_TIMEOUT; ++i) // Max 20 iterations { - status = WaitForSingleObject(piLoadee.hProcess, 1000); // 1 second timeout + status = WaitForSingleObject(piLoadee.hProcess, 1000); // 1 second timeout - if (!WatchDogIsSectionOpen("L3")) // Gets closed when loading screen is shown + if (!WatchDogIsSectionOpen("L3")) // Gets closed when loading screen is shown { WriteDebugEvent("Loader - L3 closed"); break; @@ -1950,7 +1913,7 @@ int LaunchGame(SString strCmdLine) // Check for device selection dialog if (IsDeviceSelectionDialogOpen(piLoadee.dwProcessId) && i > 0) { - --i; // Don't count this iteration + --i; // Don't count this iteration Sleep(100); } } @@ -1961,7 +1924,7 @@ int LaunchGame(SString strCmdLine) if (status == WAIT_TIMEOUT) { CStuckProcessDetector detector(piLoadee.hProcess, 5000); - while (status == WAIT_TIMEOUT && WatchDogIsSectionOpen("L3")) // Gets closed when loading screen is shown + while (status == WAIT_TIMEOUT && WatchDogIsSectionOpen("L3")) // Gets closed when loading screen is shown { if (detector.UpdateIsStuck()) { @@ -1973,7 +1936,7 @@ int LaunchGame(SString strCmdLine) } break; } - status = WaitForSingleObject(piLoadee.hProcess, 1000); // 1 second timeout + status = WaitForSingleObject(piLoadee.hProcess, 1000); // 1 second timeout } } @@ -1985,16 +1948,16 @@ int LaunchGame(SString strCmdLine) // If core is closing and gta_sa.exe process memory usage is not changing, terminate CStuckProcessDetector detector(piLoadee.hProcess, 5000); - while (status == WAIT_TIMEOUT && WatchDogIsSectionOpen("Q0")) // Gets closed when quit is detected as frozen + while (status == WAIT_TIMEOUT && WatchDogIsSectionOpen("Q0")) // Gets closed when quit is detected as frozen { if (detector.UpdateIsStuck()) { WriteDebugEvent("Detected stuck process at quit"); - #ifndef MTA_DEBUG +#ifndef MTA_DEBUG TerminateProcess(piLoadee.hProcess, 1); status = WAIT_FAILED; break; - #endif +#endif } status = WaitForSingleObject(piLoadee.hProcess, 1000); } @@ -2017,30 +1980,27 @@ int LaunchGame(SString strCmdLine) if (IsCrashExitCode(rawExitCode)) { - const std::array artifactPaths{ - CalcMTASAPath("mta\\core.log"), - CalcMTASAPath("mta\\core.log.flag"), - CalcMTASAPath("mta\\core.dmp") - }; + const std::array artifactPaths{CalcMTASAPath("mta\\core.log"), CalcMTASAPath("mta\\core.log.flag"), + CalcMTASAPath("mta\\core.dmp")}; - const auto artifactStates = [&] { + const auto artifactStates = [&] + { std::array states{}; std::transform(artifactPaths.cbegin(), artifactPaths.cend(), states.begin(), [&](const SString& path) { return InspectCrashArtifact(path, gtaCreationTime); }); return states; }(); - const auto artifactLabels = [&] { + const auto artifactLabels = [&] + { std::array labels{}; std::transform(artifactStates.cbegin(), artifactStates.cend(), labels.begin(), [](const CrashArtifactState state) { return CrashArtifactStateToString(state); }); return labels; }(); - if (const bool allArtifactsFresh = std::all_of(artifactStates.cbegin(), artifactStates.cend(), - [](const CrashArtifactState state) { - return state == CrashArtifactState::Fresh; - }); + if (const bool allArtifactsFresh = + std::all_of(artifactStates.cbegin(), artifactStates.cend(), [](const CrashArtifactState state) { return state == CrashArtifactState::Fresh; }); !allArtifactsFresh) { const auto [coreLogLabel, coreLogFlagLabel, coreDumpLabel] = artifactLabels; @@ -2050,25 +2010,16 @@ int LaunchGame(SString strCmdLine) AddReportLog(3147, SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s " "EIP=0x%08X ESP=0x%08X EBP=0x%08X EAX=0x%08X dump=%s)", - static_cast(rawExitCode), - coreLogLabel, - coreLogFlagLabel, - coreDumpLabel, - debugCapture.threadContext.Eip, - debugCapture.threadContext.Esp, - debugCapture.threadContext.Ebp, - debugCapture.threadContext.Eax, + static_cast(rawExitCode), coreLogLabel, coreLogFlagLabel, coreDumpLabel, debugCapture.threadContext.Eip, + debugCapture.threadContext.Esp, debugCapture.threadContext.Ebp, debugCapture.threadContext.Eax, debugCapture.dumpPath.empty() ? "none" : ExtractFilename(debugCapture.dumpPath).c_str())); // Use the pre-resolved module info from capture time (when process was alive) // This ensures we have module info even for early crashes before registry storage if (debugCapture.moduleInfo.resolved) { - AddReportLog(3148, SString("Crash in %s: RVA=0x%08X IDA=0x%08X (base=0x%08X)", - debugCapture.moduleInfo.moduleName.c_str(), - debugCapture.moduleInfo.rva, - debugCapture.moduleInfo.idaAddress, - debugCapture.moduleInfo.moduleBase)); + AddReportLog(3148, SString("Crash in %s: RVA=0x%08X IDA=0x%08X (base=0x%08X)", debugCapture.moduleInfo.moduleName.c_str(), + debugCapture.moduleInfo.rva, debugCapture.moduleInfo.idaAddress, debugCapture.moduleInfo.moduleBase)); } } else @@ -2079,8 +2030,8 @@ int LaunchGame(SString strCmdLine) { // WER faultOffset is already the RVA (offset within the module) // We can directly compute IDA address: IDA_BASE + RVA - DWORD rva = 0; - SString offsetStr; + DWORD rva = 0; + SString offsetStr; const bool hasValidOffset = !werInfo.faultOffset.empty(); if (hasValidOffset) @@ -2098,8 +2049,8 @@ int LaunchGame(SString strCmdLine) offsetText = SString("0x%s", offsetStr.c_str()); constexpr DWORD IDA_DEFAULT_DLL_BASE = 0x10000000; - const DWORD idaAddress = IDA_DEFAULT_DLL_BASE + rva; - SString idaAddressText; + const DWORD idaAddress = IDA_DEFAULT_DLL_BASE + rva; + SString idaAddressText; if (hasValidOffset && rva != 0) idaAddressText = SString("0x%08X", idaAddress); else @@ -2121,8 +2072,9 @@ int LaunchGame(SString strCmdLine) // Set up crash info for dialog with register details if (!dumpResult.path.empty()) { - const char* exceptionName = (werInfo.exceptionCode == 0xC0000409) ? "Stack Buffer Overrun" : - (werInfo.exceptionCode == 0xC0000374) ? "Heap Corruption" : "Security Exception"; + const char* exceptionName = (werInfo.exceptionCode == 0xC0000409) ? "Stack Buffer Overrun" + : (werInfo.exceptionCode == 0xC0000374) ? "Heap Corruption" + : "Security Exception"; SString crashReason = SString( "Security Exception - %s (0x%08X) detected.\n" @@ -2130,11 +2082,8 @@ int LaunchGame(SString strCmdLine) "Offset: %s\n" "IDA Address: %s (assuming default DLL base 0x10000000)\n" "Crash dump: %s", - exceptionName, werInfo.exceptionCode, - werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), - offsetText.c_str(), - idaAddressText.c_str(), - ExtractFilename(dumpResult.path).c_str()); + exceptionName, werInfo.exceptionCode, werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), offsetText.c_str(), + idaAddressText.c_str(), ExtractFilename(dumpResult.path).c_str()); SetApplicationSetting("diagnostics", "last-crash-reason", crashReason); SetApplicationSettingInt("diagnostics", "last-crash-code", werInfo.exceptionCode); @@ -2146,8 +2095,8 @@ int LaunchGame(SString strCmdLine) // Build core.log entry SYSTEMTIME st{}; GetLocalTime(&st); - const auto strMTAVersionFull = SString("%s.%s", MTA_DM_BUILDTAG_LONG, - *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); + const auto strMTAVersionFull = + SString("%s.%s", MTA_DM_BUILDTAG_LONG, *GetApplicationSetting("mta-version-ext").SplitRight(".", nullptr, -2)); SString coreLogEntry; coreLogEntry += SString("Version = %s\n", strMTAVersionFull.c_str()); @@ -2163,9 +2112,9 @@ int LaunchGame(SString strCmdLine) "EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n" "EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n" "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n\n", - dumpResult.regs.eax, dumpResult.regs.ebx, dumpResult.regs.ecx, dumpResult.regs.edx, dumpResult.regs.esi, - dumpResult.regs.edi, dumpResult.regs.ebp, dumpResult.regs.esp, dumpResult.regs.eip, dumpResult.regs.eflags, - dumpResult.regs.cs, dumpResult.regs.ds, dumpResult.regs.ss, dumpResult.regs.es, dumpResult.regs.fs, dumpResult.regs.gs); + dumpResult.regs.eax, dumpResult.regs.ebx, dumpResult.regs.ecx, dumpResult.regs.edx, dumpResult.regs.esi, dumpResult.regs.edi, + dumpResult.regs.ebp, dumpResult.regs.esp, dumpResult.regs.eip, dumpResult.regs.eflags, dumpResult.regs.cs, dumpResult.regs.ds, + dumpResult.regs.ss, dumpResult.regs.es, dumpResult.regs.fs, dumpResult.regs.gs); } if (!dumpResult.stackTrace.empty()) @@ -2197,34 +2146,21 @@ int LaunchGame(SString strCmdLine) AddReportLog(3147, SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s module=%s offset=%s) " "-> IDA=0x%08X", - static_cast(rawExitCode), - coreLogLabel, - coreLogFlagLabel, - dumpLabel, - werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), - werInfo.faultOffset.c_str(), - idaAddress)); + static_cast(rawExitCode), coreLogLabel, coreLogFlagLabel, dumpLabel, + werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), werInfo.faultOffset.c_str(), idaAddress)); } else { - AddReportLog(3147, - SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s module=%s offset=%s)", - static_cast(rawExitCode), - coreLogLabel, - coreLogFlagLabel, - dumpLabel, - werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), - werInfo.faultOffset.empty() ? "unknown" : werInfo.faultOffset.c_str())); + AddReportLog(3147, SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s module=%s offset=%s)", + static_cast(rawExitCode), coreLogLabel, coreLogFlagLabel, dumpLabel, + werInfo.moduleName.empty() ? "unknown" : werInfo.moduleName.c_str(), + werInfo.faultOffset.empty() ? "unknown" : werInfo.faultOffset.c_str())); } } else { - AddReportLog(3147, - SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s)", - static_cast(rawExitCode), - coreLogLabel, - coreLogFlagLabel, - coreDumpLabel)); + AddReportLog(3147, SString("Loader observed crash exit 0x%08X (core.log=%s core.log.flag=%s core.dmp=%s)", + static_cast(rawExitCode), coreLogLabel, coreLogFlagLabel, coreDumpLabel)); } if (IsFailFastException(rawExitCode)) @@ -2309,17 +2245,17 @@ void HandleOnQuitCommand() } } - SString strOperation = vecParts[0]; - SString strFile = vecParts[1]; + SString strOperation = vecParts[0]; + SString strFile = vecParts[1]; SString strParameters = vecParts[2]; - SString strDirectory = vecParts[3]; - SString strShowCmd = vecParts[4]; + SString strDirectory = vecParts[3]; + SString strShowCmd = vecParts[4]; // Process operation type if (strOperation == "restart") { strOperation = "open"; - strFile = PathJoin(strMTASAPath, MTA_EXE_NAME); + strFile = PathJoin(strMTASAPath, MTA_EXE_NAME); if (!FileExists(strFile)) { @@ -2393,7 +2329,7 @@ void HandleOnQuitCommand() if (!strOperation.empty() && !strFile.empty()) { WriteDebugEvent(SString("Executing OnQuitCommand: op=%s, file=%s", *strOperation, *strFile)); - ShellExecuteNonBlocking(strOperation.empty() ? NULL : strOperation.c_str(), strFile.c_str(), - strParameters.empty() ? NULL : strParameters.c_str(), strDirectory.empty() ? NULL : strDirectory.c_str(), nShowCmd); + ShellExecuteNonBlocking(strOperation.empty() ? NULL : strOperation.c_str(), strFile.c_str(), strParameters.empty() ? NULL : strParameters.c_str(), + strDirectory.empty() ? NULL : strDirectory.c_str(), nShowCmd); } } diff --git a/Client/loader/MainFunctions.h b/Client/loader/MainFunctions.h index 686acdc52c8..ae32f14aaf0 100644 --- a/Client/loader/MainFunctions.h +++ b/Client/loader/MainFunctions.h @@ -28,5 +28,5 @@ void CheckDataFiles(); void CheckLibVersions(); int LaunchGame(SString strCmdLine); -#define EXIT_OK (0) -#define EXIT_ERROR (1) +#define EXIT_OK (0) +#define EXIT_ERROR (1) diff --git a/Client/loader/SplashWindow.cpp b/Client/loader/SplashWindow.cpp index 53012cf9a89..ceff13bae39 100644 --- a/Client/loader/SplashWindow.cpp +++ b/Client/loader/SplashWindow.cpp @@ -24,7 +24,7 @@ using hrc = std::chrono::high_resolution_clock; /////////////////////////////////////////////////////////////////////////// // // Splash window logic. -// +// /////////////////////////////////////////////////////////////////////////// class Splash final @@ -111,7 +111,7 @@ bool Splash::CreateSplashWindow(HINSTANCE instance) windowClass.style = 0; windowClass.hInstance = instance; windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); - windowClass.hIcon = LoadIconA(GetModuleHandle(nullptr), MAKEINTRESOURCE(110)); // IDI_ICON1 from Launcher + windowClass.hIcon = LoadIconA(GetModuleHandle(nullptr), MAKEINTRESOURCE(110)); // IDI_ICON1 from Launcher windowClass.lpszClassName = TEXT("SplashWindow"); if (!RegisterClass(&windowClass)) @@ -144,7 +144,7 @@ bool Splash::CreateSplashWindow(HINSTANCE instance) m_barX = {}; m_barY = ScaleToDpi(197, dpi); m_barWidth = m_width; - m_barHeight = ScaleToDpi(5, dpi) + 1; // We add 1 pixel because scaling can cause the bar to be too small. + m_barHeight = ScaleToDpi(5, dpi) + 1; // We add 1 pixel because scaling can cause the bar to be too small. m_windowClass = windowClass; m_window = window; diff --git a/Client/loader/Utils.cpp b/Client/loader/Utils.cpp index f2ff344b1d6..8e320a5d4eb 100644 --- a/Client/loader/Utils.cpp +++ b/Client/loader/Utils.cpp @@ -23,7 +23,7 @@ #include #include #include -#pragma comment (lib, "wintrust") +#pragma comment(lib, "wintrust") namespace fs = std::filesystem; @@ -86,7 +86,7 @@ WString devicePathToWin32Path(const WString& strDevicePath) while (*p++) ; - } while (!bFound && *p); // end of string + } while (!bFound && *p); // end of string } return pszFilename; } @@ -532,7 +532,8 @@ static const SString DoUserAssistedSearch() noexcept { SString result; - MessageBox(nullptr, _("Start Grand Theft Auto: San Andreas.\nEnsure the game is placed in the 'Program Files (x86)' folder."), _("Searching for GTA: San Andreas"), MB_OK | MB_ICONINFORMATION); + MessageBox(nullptr, _("Start Grand Theft Auto: San Andreas.\nEnsure the game is placed in the 'Program Files (x86)' folder."), + _("Searching for GTA: San Andreas"), MB_OK | MB_ICONINFORMATION); while (true) { @@ -545,7 +546,10 @@ static const SString DoUserAssistedSearch() noexcept return result; } - if (MessageBox(nullptr, _("Sorry, game not found.\nStart Grand Theft Auto: San Andreas and click retry.\nEnsure the game is placed in the 'Program Files (x86)' folder."), _("Searching for GTA: San Andreas"), MB_RETRYCANCEL | MB_ICONWARNING) == IDCANCEL) + if (MessageBox(nullptr, + _("Sorry, game not found.\nStart Grand Theft Auto: San Andreas and click retry.\nEnsure the game is placed in the 'Program Files (x86)' " + "folder."), + _("Searching for GTA: San Andreas"), MB_RETRYCANCEL | MB_ICONWARNING) == IDCANCEL) return result; } } @@ -564,7 +568,7 @@ ePathResult GetGamePath(SString& strOutResult, bool bFindIfMissing) // Try HKLM "SOFTWARE\\Multi Theft Auto: San Andreas All\\Common\\" pathList.push_back(GetCommonRegistryValue("", "GTA:SA Path")); - + WriteDebugEvent(SString("GetGamePath: Registry returned '%s'", pathList[0].c_str())); // Unicode character check on first one @@ -1166,13 +1170,13 @@ bool Is32bitProcess(DWORD processID) if (bOk) { if (bIsWow64 == FALSE) - return false; // 64 bit O/S and process not running under WOW64, so it must be a 64 bit process + return false; // 64 bit O/S and process not running under WOW64, so it must be a 64 bit process return true; } } } - return false; // Can't determine. Guess it's 64 bit + return false; // Can't determine. Guess it's 64 bit } /////////////////////////////////////////////////////////////////////////// @@ -1332,8 +1336,8 @@ int GetFileAge(const SString& strPathFilename) /////////////////////////////////////////////////////////////////////////// void CleanDownloadCache() { - const uint uiMaxCleanTime = 5; // Limit clean time (seconds) - const uint uiCleanFileAge = 60 * 60 * 24 * 7; // Delete files older than this + const uint uiMaxCleanTime = 5; // Limit clean time (seconds) + const uint uiCleanFileAge = 60 * 60 * 24 * 7; // Delete files older than this const time_t tMaxEndTime = time(NULL) + uiMaxCleanTime; @@ -1415,7 +1419,7 @@ void DirectoryCopy(SString strSrcBase, SString strDestBase, bool bShowProgressDi bool bCheckFreeSpace = false; long long llFreeBytesAvailable = GetDiskFreeSpace(strDestBase); if (llFreeBytesAvailable != 0) - bCheckFreeSpace = (llFreeBytesAvailable < (iMinFreeSpaceMB + 10000) * 0x100000LL); // Only check if initial freespace is less than 10GB + bCheckFreeSpace = (llFreeBytesAvailable < (iMinFreeSpaceMB + 10000) * 0x100000LL); // Only check if initial freespace is less than 10GB if (bShowProgressDialog) ShowProgressDialog(g_hInstance, _("Copying files..."), true); @@ -1522,7 +1526,7 @@ void MaybeShowCopySettingsDialog() if (!FileExists(strPreviousConfig)) return; - HideSplash(); // Hide standard MTA splash + HideSplash(); // Hide standard MTA splash // Show dialog SString strMessage; @@ -2282,8 +2286,8 @@ int WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, PVOID pvNothing) ////////////////////////////////////////////////////////// WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) { - constexpr DWORD EXCEPTION_STACK_BUFFER_OVERRUN = 0xC0000409; - constexpr DWORD EXCEPTION_HEAP_CORRUPTION = 0xC0000374; + constexpr DWORD EXCEPTION_STACK_BUFFER_OVERRUN = 0xC0000409; + constexpr DWORD EXCEPTION_HEAP_CORRUPTION = 0xC0000374; constexpr ULONGLONG FILETIME_UNITS_PER_SECOND = 10000000ULL; constexpr ULONGLONG MAX_CRASH_AGE_MINUTES = 15; @@ -2307,7 +2311,7 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) for (const SString& werArchivePath : werArchivePaths) { SString searchPattern = PathJoin(werArchivePath, "AppCrash_gta_sa.exe_*"); - auto reportDirs = FindFiles(searchPattern, false, true, true); + auto reportDirs = FindFiles(searchPattern, false, true, true); for (const SString& dir : reportDirs) { allReportDirs.push_back({werArchivePath, dir}); @@ -2327,10 +2331,9 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) { const SString& werArchivePath = it->first; const SString& reportDir = it->second; - SString reportPath = PathJoin(werArchivePath, reportDir, "Report.wer"); + SString reportPath = PathJoin(werArchivePath, reportDir, "Report.wer"); - HANDLE hFile = CreateFileA(reportPath, GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE hFile = CreateFileA(reportPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) continue; @@ -2353,17 +2356,15 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) } wchar_t wbuffer[8192]{}; - DWORD bytesRead = 0; + DWORD bytesRead = 0; SetFilePointer(hFile, 0, nullptr, FILE_BEGIN); ReadFile(hFile, wbuffer, sizeof(wbuffer) - sizeof(wchar_t), &bytesRead, nullptr); CloseHandle(hFile); std::wstring content(wbuffer, bytesRead / sizeof(wchar_t)); - bool hasStackOverrun = content.find(L"c0000409") != std::wstring::npos || - content.find(L"C0000409") != std::wstring::npos; - bool hasHeapCorruption = content.find(L"c0000374") != std::wstring::npos || - content.find(L"C0000374") != std::wstring::npos; + bool hasStackOverrun = content.find(L"c0000409") != std::wstring::npos || content.find(L"C0000409") != std::wstring::npos; + bool hasHeapCorruption = content.find(L"c0000374") != std::wstring::npos || content.find(L"C0000374") != std::wstring::npos; if (!hasStackOverrun && !hasHeapCorruption) continue; @@ -2373,9 +2374,10 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) if (targetExceptionCode != 0 && foundCode != targetExceptionCode) continue; - auto parseField = [&content](const wchar_t* fieldName) -> SString { + auto parseField = [&content](const wchar_t* fieldName) -> SString + { std::wstring searchKey = std::wstring(fieldName) + L".Value="; - size_t pos = content.find(searchKey); + size_t pos = content.find(searchKey); if (pos == std::wstring::npos) return ""; pos += searchKey.length(); @@ -2391,14 +2393,14 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) SString werOffset = parseField(L"Sig[6]"); SString evtModule, evtOffset; - HANDLE hEventLog = OpenEventLogW(nullptr, L"Application"); + HANDLE hEventLog = OpenEventLogW(nullptr, L"Application"); if (hEventLog) { std::vector buffer(65536); - DWORD evtBytesRead = 0, minBytes = 0; + DWORD evtBytesRead = 0, minBytes = 0; - if (ReadEventLogW(hEventLog, EVENTLOG_BACKWARDS_READ | EVENTLOG_SEQUENTIAL_READ, - 0, buffer.data(), static_cast(buffer.size()), &evtBytesRead, &minBytes)) + if (ReadEventLogW(hEventLog, EVENTLOG_BACKWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, buffer.data(), static_cast(buffer.size()), &evtBytesRead, + &minBytes)) { auto* record = reinterpret_cast(buffer.data()); DWORD totalRead = 0; @@ -2407,28 +2409,27 @@ WerCrashInfo QueryWerCrashInfo(DWORD targetExceptionCode) { if (record->EventID == 1000) { - auto* source = reinterpret_cast( - reinterpret_cast(record) + sizeof(EVENTLOGRECORD)); + auto* source = reinterpret_cast(reinterpret_cast(record) + sizeof(EVENTLOGRECORD)); if (wcscmp(source, L"Application Error") == 0) { constexpr LONGLONG UNIX_EPOCH_DIFF = 11644473600LL; - ULARGE_INTEGER eventTime; + ULARGE_INTEGER eventTime; eventTime.QuadPart = (static_cast(record->TimeGenerated) + UNIX_EPOCH_DIFF) * FILETIME_UNITS_PER_SECOND; - ULONGLONG timeDiff = (uliWrite.QuadPart > eventTime.QuadPart) ? - (uliWrite.QuadPart - eventTime.QuadPart) : (eventTime.QuadPart - uliWrite.QuadPart); + ULONGLONG timeDiff = + (uliWrite.QuadPart > eventTime.QuadPart) ? (uliWrite.QuadPart - eventTime.QuadPart) : (eventTime.QuadPart - uliWrite.QuadPart); if (timeDiff < 2ULL * 60 * FILETIME_UNITS_PER_SECOND) { - auto* strPtr = reinterpret_cast( - reinterpret_cast(record) + record->StringOffset); + auto* strPtr = reinterpret_cast(reinterpret_cast(record) + record->StringOffset); std::vector eventStrings; for (WORD s = 0; s < record->NumStrings && s < 10; ++s) { eventStrings.emplace_back(SString("%ls", strPtr)); - while (*strPtr) ++strPtr; + while (*strPtr) + ++strPtr; ++strPtr; } @@ -2514,7 +2515,7 @@ ModuleCrashInfo ResolveModuleCrashAddress(DWORD crashAddress) }; std::vector modules; - std::vector entries; + std::vector entries; strModuleBases.Split(";", entries, true); for (const SString& entry : entries) @@ -2576,7 +2577,7 @@ ModuleCrashInfo ResolveModuleCrashAddress(DWORD crashAddress) result.rva = crashAddress - mod.base; // IDA default base varies: DLLs at 0x10000000, EXEs at 0x00400000 - const bool isExe = result.moduleName.EndsWithI(".exe"); + const bool isExe = result.moduleName.EndsWithI(".exe"); const DWORD idaBase = isExe ? 0x00400000 : 0x10000000; result.idaAddress = idaBase + result.rva; result.resolved = true; @@ -2608,7 +2609,7 @@ ModuleCrashInfo ResolveModuleCrashAddress(DWORD crashAddress, HANDLE hProcess) return result; HMODULE hMods[512]; - DWORD cbNeeded = 0; + DWORD cbNeeded = 0; if (!EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) return result; @@ -2652,7 +2653,7 @@ ModuleCrashInfo ResolveModuleCrashAddress(DWORD crashAddress, HANDLE hProcess) result.moduleBase = modBase; result.rva = crashAddress - modBase; - const bool isExe = result.moduleName.EndsWithI(".exe"); + const bool isExe = result.moduleName.EndsWithI(".exe"); const DWORD idaBase = isExe ? 0x00400000 : 0x10000000; result.idaAddress = idaBase + result.rva; result.resolved = true; diff --git a/Client/loader/Utils.h b/Client/loader/Utils.h index 686cbf76df0..a3eb08c2686 100644 --- a/Client/loader/Utils.h +++ b/Client/loader/Utils.h @@ -172,8 +172,8 @@ struct ModuleCrashInfo SString moduleName; DWORD moduleBase = 0; DWORD crashAddress = 0; - DWORD rva = 0; // Relative Virtual Address (crash - base) - DWORD idaAddress = 0; // IDA-friendly address (0x10000000 + rva for DLLs) + DWORD rva = 0; // Relative Virtual Address (crash - base) + DWORD idaAddress = 0; // IDA-friendly address (0x10000000 + rva for DLLs) bool resolved = false; }; @@ -262,7 +262,7 @@ class CStuckProcessDetector }; // For NtQuerySystemInformation -#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L) +#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L) #define SystemProcessImageNameInformation ((SYSTEM_INFORMATION_CLASS)88) typedef struct _SYSTEM_PROCESS_IMAGE_NAME_INFORMATION { diff --git a/Client/loader/resource.h b/Client/loader/resource.h index 5bfadc97cff..151e2c71ac5 100644 --- a/Client/loader/resource.h +++ b/Client/loader/resource.h @@ -2,54 +2,54 @@ // Microsoft Visual C++ generated include file. // Used by loader.rc // -#define IDB_BITMAP1 105 -#define IDB_BITMAP2 106 -#define IDD_PROGRESS_DIALOG 111 -#define IDD_CRASHED_DIALOG 114 -#define IDD_D3DDLL_DIALOG 115 -#define IDD_OPTIMUS_DIALOG 116 -#define IDD_NOAV_DIALOG 117 -#define IDC_PROGRESS_BAR 1001 -#define IDC_PROGRESS_STATIC 1002 -#define IDC_SEND_DUMP_CHECK 1004 -#define IDC_SEND_DESC_STATIC 1006 -#define IDC_RESTART_QUESTION_STATIC 1007 -#define IDC_CRASH_INFO_EDIT 1009 -#define IDC_EDIT_GRAPHICS_DLL_PATH 1011 -#define IDC_CHECK_NOT_AGAIN 1012 -#define IDC_BUTTON_SHOW_DIR 1013 -#define IDC_RADIO1 1014 -#define IDC_RADIO2 1015 -#define IDC_RADIO3 1016 -#define IDC_RADIO4 1017 -#define IDC_BUTTON_HELP 1022 -#define IDC_CHECK_FORCE_WINDOWED 1023 -#define IDC_STATIC_BODY1 1026 -#define IDC_NOAV_TEXT1 1026 -#define IDC_SPLASHBITMAP 1026 -#define IDC_STATIC_BODY2 1027 -#define IDC_NOAV_TEXT2 1027 -#define IDC_CRASH_HEAD 1028 -#define IDC_D3DDLL_TEXT1 1029 -#define IDC_D3DDLL_TEXT2 1030 -#define IDC_OPTIMUS_TEXT1 1031 -#define IDC_OPTIMUS_TEXT2 1032 -#define IDC_OPTIMUS_TEXT3 1033 -#define IDC_NOAV_OPT_BOTNET 1034 -#define IDC_NOAV_OPT_SKIP 1035 -#define IDC_APPLY_AUTOMATIC_CHANGES 1036 -#define IDC_NO_ACTION 1037 -#define IDC_CHECK_REMEMBER 1038 -#define IDC_OPTIMUS_TEXT4 1039 -#define IDC_SEND_DUMP_LABEL 1040 +#define IDB_BITMAP1 105 +#define IDB_BITMAP2 106 +#define IDD_PROGRESS_DIALOG 111 +#define IDD_CRASHED_DIALOG 114 +#define IDD_D3DDLL_DIALOG 115 +#define IDD_OPTIMUS_DIALOG 116 +#define IDD_NOAV_DIALOG 117 +#define IDC_PROGRESS_BAR 1001 +#define IDC_PROGRESS_STATIC 1002 +#define IDC_SEND_DUMP_CHECK 1004 +#define IDC_SEND_DESC_STATIC 1006 +#define IDC_RESTART_QUESTION_STATIC 1007 +#define IDC_CRASH_INFO_EDIT 1009 +#define IDC_EDIT_GRAPHICS_DLL_PATH 1011 +#define IDC_CHECK_NOT_AGAIN 1012 +#define IDC_BUTTON_SHOW_DIR 1013 +#define IDC_RADIO1 1014 +#define IDC_RADIO2 1015 +#define IDC_RADIO3 1016 +#define IDC_RADIO4 1017 +#define IDC_BUTTON_HELP 1022 +#define IDC_CHECK_FORCE_WINDOWED 1023 +#define IDC_STATIC_BODY1 1026 +#define IDC_NOAV_TEXT1 1026 +#define IDC_SPLASHBITMAP 1026 +#define IDC_STATIC_BODY2 1027 +#define IDC_NOAV_TEXT2 1027 +#define IDC_CRASH_HEAD 1028 +#define IDC_D3DDLL_TEXT1 1029 +#define IDC_D3DDLL_TEXT2 1030 +#define IDC_OPTIMUS_TEXT1 1031 +#define IDC_OPTIMUS_TEXT2 1032 +#define IDC_OPTIMUS_TEXT3 1033 +#define IDC_NOAV_OPT_BOTNET 1034 +#define IDC_NOAV_OPT_SKIP 1035 +#define IDC_APPLY_AUTOMATIC_CHANGES 1036 +#define IDC_NO_ACTION 1037 +#define IDC_CHECK_REMEMBER 1038 +#define IDC_OPTIMUS_TEXT4 1039 +#define IDC_SEND_DUMP_LABEL 1040 // Next default values for new objects // #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 118 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1041 -#define _APS_NEXT_SYMED_VALUE 101 -#endif + #ifndef APSTUDIO_READONLY_SYMBOLS + #define _APS_NEXT_RESOURCE_VALUE 118 + #define _APS_NEXT_COMMAND_VALUE 40001 + #define _APS_NEXT_CONTROL_VALUE 1041 + #define _APS_NEXT_SYMED_VALUE 101 + #endif #endif diff --git a/Client/mods/deathmatch/CClient.cpp b/Client/mods/deathmatch/CClient.cpp index 1ed3d4fc796..44ff7e9cf60 100644 --- a/Client/mods/deathmatch/CClient.cpp +++ b/Client/mods/deathmatch/CClient.cpp @@ -32,10 +32,11 @@ int CClient::ClientInitialize(const char* szArguments, CCoreInterface* pCore) #if defined(MTA_DM_EXPIRE_DAYS) // Make public client test builds expire - // Unused relic from 10+ years ago (as of 2025) but could still be used. Defined by net. + // Unused relic from 10+ years ago (as of 2025) but could still be used. Defined by net. if (GetDaysUntilExpire() < -1) { - MessageBox(NULL, _("This version has expired."), (std::string("MTA: San Andreas ") + MTA_DM_BUILDTAG_LONG + _E("CD64")).c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST); + MessageBox(NULL, _("This version has expired."), (std::string("MTA: San Andreas ") + MTA_DM_BUILDTAG_LONG + _E("CD64")).c_str(), + MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST); TerminateProcess(GetCurrentProcess(), 1); } #endif diff --git a/Client/mods/deathmatch/CVoiceRecorder.cpp b/Client/mods/deathmatch/CVoiceRecorder.cpp index d0d39c7f5d3..cc90fc23bbd 100644 --- a/Client/mods/deathmatch/CVoiceRecorder.cpp +++ b/Client/mods/deathmatch/CVoiceRecorder.cpp @@ -56,7 +56,7 @@ void CVoiceRecorder::Init(bool bEnabled, unsigned int uiServerSampleRate, unsign { m_bEnabled = bEnabled; - if (!bEnabled) // If we aren't enabled, don't bother continuing + if (!bEnabled) // If we aren't enabled, don't bother continuing return; std::lock_guard lock(m_Mutex); @@ -322,7 +322,7 @@ void CVoiceRecorder::DoPulse() } } - if (m_VoiceState == VOICESTATE_RECORDING_LAST_PACKET) // End of voice data (for events) + if (m_VoiceState == VOICESTATE_RECORDING_LAST_PACKET) // End of voice data (for events) { m_VoiceState = VOICESTATE_AWAITING_INPUT; diff --git a/Client/mods/deathmatch/CVoiceRecorder.h b/Client/mods/deathmatch/CVoiceRecorder.h index 4c625da7b3c..acdb3242062 100644 --- a/Client/mods/deathmatch/CVoiceRecorder.h +++ b/Client/mods/deathmatch/CVoiceRecorder.h @@ -11,9 +11,9 @@ #pragma once -#define VOICE_BUFFER_LENGTH 200000 -#define VOICE_FREQUENCY 44100 -#define VOICE_SAMPLE_SIZE 2 +#define VOICE_BUFFER_LENGTH 200000 +#define VOICE_FREQUENCY 44100 +#define VOICE_SAMPLE_SIZE 2 #define FRAME_OUTGOING_BUFFER_COUNT 100 #define FRAME_INCOMING_BUFFER_COUNT 100 diff --git a/Client/mods/deathmatch/ClientCommands.cpp b/Client/mods/deathmatch/ClientCommands.cpp index 84529b4c9d5..5130f900626 100644 --- a/Client/mods/deathmatch/ClientCommands.cpp +++ b/Client/mods/deathmatch/ClientCommands.cpp @@ -18,14 +18,14 @@ using std::list; using std::vector; #ifdef MTA_DEBUG -#include -#include -#include -#include + #include + #include + #include + #include #endif // Hide the "conversion from 'unsigned long' to 'DWORD*' of greater size" warning -#pragma warning(disable:4312) +#pragma warning(disable : 4312) extern CClientGame* g_pClientGame; @@ -771,7 +771,7 @@ void COMMAND_ServerInfo(const char* szCmdLine) g_pCore->GetConsole()->Print(*strSpacer); } -#if defined (MTA_DEBUG) || defined (MTA_BETA) +#if defined(MTA_DEBUG) || defined(MTA_BETA) void COMMAND_ShowSyncing(const char* szCmdLine) { diff --git a/Client/mods/deathmatch/logic/CBassAudio.cpp b/Client/mods/deathmatch/logic/CBassAudio.cpp index 41ea3be88b0..37e2b343ac3 100644 --- a/Client/mods/deathmatch/logic/CBassAudio.cpp +++ b/Client/mods/deathmatch/logic/CBassAudio.cpp @@ -40,20 +40,20 @@ namespace // Track failed audio file loads to prevent spam and performance hit std::mutex ms_FailedFilesMutex; std::unordered_map ms_FailedAudioFiles; - constexpr DWORD FAILED_LOAD_RETRY_DELAY = 10000; // 10 seconds before retrying a failed file - constexpr size_t MAX_FAILED_FILES_CACHE_SIZE = 1000; + constexpr DWORD FAILED_LOAD_RETRY_DELAY = 10000; // 10 seconds before retrying a failed file + constexpr size_t MAX_FAILED_FILES_CACHE_SIZE = 1000; // Track active streaming threads to ensure they complete before DLL unload - std::atomic ms_iActiveStreamingThreads{0}; - std::atomic ms_bShuttingDown{false}; - std::mutex ms_StreamingThreadMutex; + std::atomic ms_iActiveStreamingThreads{0}; + std::atomic ms_bShuttingDown{false}; + std::mutex ms_StreamingThreadMutex; std::condition_variable ms_StreamingThreadCV; // Get callback id for this CBassAudio void* AddCallbackId(CBassAudio* pBassAudio) { std::lock_guard lock(ms_CallbackMutex); - void* uiId = (void*)(++ms_uiNextCallbackId ? ms_uiNextCallbackId : ++ms_uiNextCallbackId); + void* uiId = (void*)(++ms_uiNextCallbackId ? ms_uiNextCallbackId : ++ms_uiNextCallbackId); MapSet(ms_CallbackIdMap, uiId, pBassAudio); return uiId; } @@ -73,8 +73,11 @@ namespace } // Finish with pointer - void UnlockCallbackId() { ms_CallbackMutex.unlock(); } -} // namespace + void UnlockCallbackId() + { + ms_CallbackMutex.unlock(); + } +} // namespace // Signal streaming threads that we're shutting down - they should exit ASAP after their blocking call returns void SignalStreamingThreadsToStop() @@ -160,7 +163,7 @@ bool CBassAudio::BeginLoadingMedia() // Calc the flags long lFlags = BASS_STREAM_AUTOFREE | BASS_SAMPLE_SOFTWARE; -#if 0 // Everything sounds better in ste-reo +#if 0 // Everything sounds better in ste-reo if ( m_b3D ) lFlags |= BASS_SAMPLE_MONO; #endif @@ -202,7 +205,7 @@ bool CBassAudio::BeginLoadingMedia() if (!m_pBuffer) { std::lock_guard lock(ms_FailedFilesMutex); - const auto it = ms_FailedAudioFiles.find(m_strPath); + const auto it = ms_FailedAudioFiles.find(m_strPath); if (it != ms_FailedAudioFiles.end()) { const DWORD dwTimeSinceFailure = dwCurrentTime - it->second; @@ -230,14 +233,14 @@ bool CBassAudio::BeginLoadingMedia() m_pSound = BASS_StreamCreateFile(false, FromUTF8(m_strPath), 0, 0, lCreateFlags | BASS_UNICODE); if (!m_pSound) m_pSound = BASS_MusicLoad(false, FromUTF8(m_strPath), 0, 0, BASS_MUSIC_RAMP | BASS_MUSIC_PRESCAN | BASS_STREAM_DECODE | BASS_UNICODE, - 0); // Try again + 0); // Try again if (!m_pSound && m_b3D) { // Last try if 3D - check cache first to avoid spammed mono conversion attempts bool bShouldTry = false; { std::lock_guard lock(ms_FailedFilesMutex); - const auto it = ms_FailedAudioFiles.find(m_strPath); + const auto it = ms_FailedAudioFiles.find(m_strPath); if (it == ms_FailedAudioFiles.end() || (dwCurrentTime - it->second) >= FAILED_LOAD_RETRY_DELAY) { bShouldTry = true; @@ -246,7 +249,7 @@ bool CBassAudio::BeginLoadingMedia() ms_FailedAudioFiles[m_strPath] = dwCurrentTime; } } - + if (bShouldTry) { m_pSound = ConvertFileToMono(m_strPath); @@ -272,7 +275,7 @@ bool CBassAudio::BeginLoadingMedia() { // Remove oldest entry DWORD maxAge = 0; - auto itOldest = ms_FailedAudioFiles.begin(); + auto itOldest = ms_FailedAudioFiles.begin(); for (auto it = ms_FailedAudioFiles.begin(); it != ms_FailedAudioFiles.end(); ++it) { // Find oldest entry @@ -452,84 +455,83 @@ int CBassAudio::ErrorGetCode() // HSTREAM CBassAudio::ConvertFileToMono(const SString& strPath) { - HSTREAM decoder = - BASS_StreamCreateFile(false, FromUTF8(strPath), 0, 0, BASS_STREAM_DECODE | BASS_SAMPLE_MONO | BASS_UNICODE); // open file for decoding + HSTREAM decoder = BASS_StreamCreateFile(false, FromUTF8(strPath), 0, 0, BASS_STREAM_DECODE | BASS_SAMPLE_MONO | BASS_UNICODE); // open file for decoding if (!decoder) - return 0; // failed - + return 0; // failed + QWORD lengthQW = BASS_ChannelGetLength(decoder, BASS_POS_BYTE); if (lengthQW == static_cast(-1) || lengthQW == 0) { BASS_StreamFree(decoder); - return 0; // invalid length + return 0; // invalid length } - + if (lengthQW > 0xFFFFFFFF) { BASS_StreamFree(decoder); - return 0; // file too large for mono conversion + return 0; // file too large for mono conversion } - - DWORD length = static_cast(lengthQW); // Safe cast after validation - void* data = malloc(length); // allocate buffer for decoded data + + DWORD length = static_cast(lengthQW); // Safe cast after validation + void* data = malloc(length); // allocate buffer for decoded data if (!data) { BASS_StreamFree(decoder); - return 0; // allocation failed + return 0; // allocation failed } - + BASS_CHANNELINFO ci; - if (!BASS_ChannelGetInfo(decoder, &ci)) // get sample format + if (!BASS_ChannelGetInfo(decoder, &ci)) // get sample format { free(data); BASS_StreamFree(decoder); - return 0; // failed to get channel info + return 0; // failed to get channel info } - - if (ci.chans > 1) // not mono, downmix... + + if (ci.chans > 1) // not mono, downmix... { - HSTREAM mixer = BASS_Mixer_StreamCreate(ci.freq, 1, BASS_STREAM_DECODE | BASS_MIXER_END); // create mono mixer + HSTREAM mixer = BASS_Mixer_StreamCreate(ci.freq, 1, BASS_STREAM_DECODE | BASS_MIXER_END); // create mono mixer if (!mixer) { free(data); BASS_StreamFree(decoder); - return 0; // mixer creation failed + return 0; // mixer creation failed } - if (!BASS_Mixer_StreamAddChannel( - mixer, decoder, BASS_MIXER_DOWNMIX | BASS_MIXER_NORAMPIN | BASS_STREAM_AUTOFREE)) // plug-in the decoder (auto-free with the mixer) + if (!BASS_Mixer_StreamAddChannel(mixer, decoder, + BASS_MIXER_DOWNMIX | BASS_MIXER_NORAMPIN | BASS_STREAM_AUTOFREE)) // plug-in the decoder (auto-free with the mixer) { free(data); BASS_StreamFree(mixer); BASS_StreamFree(decoder); - return 0; // failed to add channel + return 0; // failed to add channel } - decoder = mixer; // decode from the mixer + decoder = mixer; // decode from the mixer } - - DWORD decodedLength = BASS_ChannelGetData(decoder, data, length); // decode data - BASS_StreamFree(decoder); // free the decoder/mixer - + + DWORD decodedLength = BASS_ChannelGetData(decoder, data, length); // decode data + BASS_StreamFree(decoder); // free the decoder/mixer + if (decodedLength == static_cast(-1)) { free(data); - return 0; // decode failed + return 0; // decode failed } - - HSTREAM stream = BASS_StreamCreate(ci.freq, 1, BASS_STREAM_AUTOFREE, STREAMPROC_PUSH, NULL); // create stream + + HSTREAM stream = BASS_StreamCreate(ci.freq, 1, BASS_STREAM_AUTOFREE, STREAMPROC_PUSH, NULL); // create stream if (!stream) { free(data); - return 0; // stream creation failed + return 0; // stream creation failed } - - if (!BASS_StreamPutData(stream, data, decodedLength)) // set the stream data + + if (!BASS_StreamPutData(stream, data, decodedLength)) // set the stream data { free(data); BASS_StreamFree(stream); - return 0; // failed to put data + return 0; // failed to put data } - - free(data); // free the buffer + + free(data); // free the buffer return stream; } @@ -710,12 +712,12 @@ void CBassAudio::CompleteStreamConnect(HSTREAM pSound) { for (; *szIcy; szIcy += strlen(szIcy) + 1) { - if (!strnicmp(szIcy, "icy-name:", 9)) // ICY / HTTP + if (!strnicmp(szIcy, "icy-name:", 9)) // ICY / HTTP { m_strStreamName = szIcy + 9; break; } - else if (!strnicmp(szIcy, "title=", 6)) // WMA + else if (!strnicmp(szIcy, "title=", 6)) // WMA { m_strStreamName = szIcy + 6; break; @@ -738,7 +740,7 @@ void CBassAudio::CompleteStreamConnect(HSTREAM pSound) } // set sync for stream titles - m_hSyncMeta = BASS_ChannelSetSync(pSound, BASS_SYNC_META, 0, &MetaSync, m_uiCallbackId); // Shoutcast + m_hSyncMeta = BASS_ChannelSetSync(pSound, BASS_SYNC_META, 0, &MetaSync, m_uiCallbackId); // Shoutcast // g_pCore->GetConsole()->Printf ( "BASS ERROR %d in BASS_SYNC_META", BASS_ErrorGetCode() ); // BASS_ChannelSetSync(pSound,BASS_SYNC_OGG_CHANGE,0,&MetaSync,this); // Icecast/OGG // g_pCore->GetConsole()->Printf ( "BASS ERROR %d in BASS_SYNC_OGG_CHANGE", BASS_ErrorGetCode() ); @@ -829,7 +831,7 @@ bool CBassAudio::SetPlayPosition(double dPosition) QWORD byteLength = BASS_ChannelGetLength(m_pSound, BASS_POS_BYTE); if (byteLength == static_cast(-1) || byteLength == 0) return false; - + // Make sure position is in range QWORD bytePosition = BASS_ChannelSeconds2Bytes(m_pSound, dPosition); return BASS_ChannelSetPosition(m_pSound, Clamp(0, bytePosition, byteLength - 1), BASS_POS_BYTE); @@ -1081,17 +1083,17 @@ float CBassAudio::GetSoundBPM() const DWORD dwCurrentTime = GetTickCount32(); { std::lock_guard lock(ms_FailedFilesMutex); - const auto it = ms_FailedAudioFiles.find(m_strPath); + const auto it = ms_FailedAudioFiles.find(m_strPath); if (it != ms_FailedAudioFiles.end()) { const DWORD dwTimeSinceFailure = dwCurrentTime - it->second; if (dwTimeSinceFailure < FAILED_LOAD_RETRY_DELAY) { - return 0.0f; // File failed recently, don't retry + return 0.0f; // File failed recently, don't retry } } } - + float fData = 0.0f; // open the same file as played but for bpm decoding detection diff --git a/Client/mods/deathmatch/logic/CBassAudio.h b/Client/mods/deathmatch/logic/CBassAudio.h index d34d7b3fadd..b94f055d151 100644 --- a/Client/mods/deathmatch/logic/CBassAudio.h +++ b/Client/mods/deathmatch/logic/CBassAudio.h @@ -7,7 +7,7 @@ * *****************************************************************************/ -#define CUT_OFF 5.0f // Cut off point at which volume is regarded as 0 in the function e^-x +#define CUT_OFF 5.0f // Cut off point at which volume is regarded as 0 in the function e^-x enum eSoundEventType { diff --git a/Client/mods/deathmatch/logic/CCallback.h b/Client/mods/deathmatch/logic/CCallback.h index 6f309b34b19..7a7dce47505 100644 --- a/Client/mods/deathmatch/logic/CCallback.h +++ b/Client/mods/deathmatch/logic/CCallback.h @@ -15,7 +15,7 @@ template class CCallbackInterface { public: - virtual ~CCallbackInterface(){}; + virtual ~CCallbackInterface() {}; virtual Ret operator()(Arguments) const = 0; }; @@ -42,7 +42,7 @@ class CCallbackMethod : public CCallbackInterface typedef Ret (T::*F)(Arguments); public: - CCallbackMethod(F pfnMethod, T* pClass) : m_pfnMethod(pfnMethod), m_pClass(pClass){}; + CCallbackMethod(F pfnMethod, T* pClass) : m_pfnMethod(pfnMethod), m_pClass(pClass) {}; virtual Ret operator()(Arguments Args) const { return (m_pClass->*m_pfnMethod)(Args); } diff --git a/Client/mods/deathmatch/logic/CClientBuilding.cpp b/Client/mods/deathmatch/logic/CClientBuilding.cpp index 9890a64f879..bbff9a5685d 100644 --- a/Client/mods/deathmatch/logic/CClientBuilding.cpp +++ b/Client/mods/deathmatch/logic/CClientBuilding.cpp @@ -139,8 +139,8 @@ void CClientBuilding::Create() if (!m_pBuilding) return; - if (m_bDoubleSidedInit) - m_pBuilding->SetBackfaceCulled(!m_bDoubleSided); + if (m_bDoubleSidedInit) + m_pBuilding->SetBackfaceCulled(!m_bDoubleSided); if (!m_usesCollision) { diff --git a/Client/mods/deathmatch/logic/CClientBuilding.h b/Client/mods/deathmatch/logic/CClientBuilding.h index aadef38f7ea..9e05c384a28 100644 --- a/Client/mods/deathmatch/logic/CClientBuilding.h +++ b/Client/mods/deathmatch/logic/CClientBuilding.h @@ -20,7 +20,7 @@ class CClientBuilding : public CClientEntity friend class CClientBuildingManager; public: - CClientBuilding(class CClientManager* pManager, ElementID ID, uint16_t usModelId, const CVector &pos, const CVector &rot, uint8_t interior); + CClientBuilding(class CClientManager* pManager, ElementID ID, uint16_t usModelId, const CVector& pos, const CVector& rot, uint8_t interior); ~CClientBuilding(); void Unlink(); @@ -50,16 +50,15 @@ class CClientBuilding : public CClientEntity bool IsValid() const noexcept { return m_pBuilding != nullptr; }; - CClientBuilding* GetLowLodBuilding() const noexcept { return m_pLowBuilding; }; - bool SetLowLodBuilding(CClientBuilding* pLod = nullptr); - bool IsLod() const noexcept { return m_pHighBuilding != nullptr; }; + bool SetLowLodBuilding(CClientBuilding* pLod = nullptr); + bool IsLod() const noexcept { return m_pHighBuilding != nullptr; }; float GetDistanceFromCentreOfMassToBaseOfModel(); private: - CClientBuilding* GetHighLodBuilding() const { return m_pHighBuilding; }; - void SetHighLodBuilding(CClientBuilding* pHighBuilding = nullptr) { m_pHighBuilding = pHighBuilding; }; + CClientBuilding* GetHighLodBuilding() const { return m_pHighBuilding; }; + void SetHighLodBuilding(CClientBuilding* pHighBuilding = nullptr) { m_pHighBuilding = pHighBuilding; }; void Recreate() { diff --git a/Client/mods/deathmatch/logic/CClientBuildingManager.cpp b/Client/mods/deathmatch/logic/CClientBuildingManager.cpp index 627f432e094..9a0b735ab0b 100644 --- a/Client/mods/deathmatch/logic/CClientBuildingManager.cpp +++ b/Client/mods/deathmatch/logic/CClientBuildingManager.cpp @@ -10,7 +10,7 @@ #include "StdInc.h" -constexpr float WORLD_DISTANCE_FROM_CENTER = 3000.0f; +constexpr float WORLD_DISTANCE_FROM_CENTER = 3000.0f; constexpr size_t PRESERVED_POOL_SIZE = 2000; constexpr size_t RESIZE_POOL_STEP = 5000; @@ -62,8 +62,8 @@ bool CClientBuildingManager::IsValidModel(uint16_t modelId) if (modelId >= static_cast(g_pGame->GetBaseIDforTXD())) return false; - // Clothes and hands cause artefacts - if (384 <= modelId && modelId <= 397) + // Clothes and hands cause artefacts + if (384 <= modelId && modelId <= 397) return false; CModelInfo* pModelInfo = g_pGame->GetModelInfo(modelId); diff --git a/Client/mods/deathmatch/logic/CClientCamera.cpp b/Client/mods/deathmatch/logic/CClientCamera.cpp index f3561c56819..fd417b35b60 100644 --- a/Client/mods/deathmatch/logic/CClientCamera.cpp +++ b/Client/mods/deathmatch/logic/CClientCamera.cpp @@ -17,14 +17,14 @@ #define PI_2 6.283185307179586476925286766559f // Camera FOV constants -constexpr const std::uintptr_t VAR_CurrentCameraFOV = 0x8D5038; // CCamera::CurrentFOV +constexpr const std::uintptr_t VAR_CurrentCameraFOV = 0x8D5038; // CCamera::CurrentFOV namespace { - constexpr float kPi = 3.1415926535897932384626433832795f; - constexpr float kMatrixTolerance = 1e-4f; - constexpr float kAngleTolerance = 1e-4f; - constexpr float kRollLookupStep = 15.0f; + constexpr float kPi = 3.1415926535897932384626433832795f; + constexpr float kMatrixTolerance = 1e-4f; + constexpr float kAngleTolerance = 1e-4f; + constexpr float kRollLookupStep = 15.0f; constexpr std::size_t kRollLookupSize = static_cast(360.0f / kRollLookupStep); struct RollLookupEntry @@ -34,7 +34,8 @@ namespace float sinValue; }; - const std::array kRollLookup = []() { + const std::array kRollLookup = []() + { std::array table = {}; for (std::size_t i = 0; i < kRollLookupSize; ++i) { @@ -92,9 +93,9 @@ namespace inline bool RequiresOrthonormalization(const CMatrix& matrix) noexcept { constexpr float lengthTarget = 1.0f; - const bool frontValid = AlmostEqual(matrix.vFront.LengthSquared(), lengthTarget, 1e-3f); - const bool upValid = AlmostEqual(matrix.vUp.LengthSquared(), lengthTarget, 1e-3f); - const bool orthogonal = AlmostEqual(matrix.vFront.DotProduct(&matrix.vUp), 0.0f, 1e-3f); + const bool frontValid = AlmostEqual(matrix.vFront.LengthSquared(), lengthTarget, 1e-3f); + const bool upValid = AlmostEqual(matrix.vUp.LengthSquared(), lengthTarget, 1e-3f); + const bool orthogonal = AlmostEqual(matrix.vFront.DotProduct(&matrix.vUp), 0.0f, 1e-3f); return !(frontValid && upValid && orthogonal); } @@ -787,7 +788,7 @@ CClientEntity* CClientCamera::GetTargetEntity() CClientEntity* pReturn = NULL; if (m_pCamera) { - CCam* pCam = m_pCamera->GetCam(m_pCamera->GetActiveCam()); + CCam* pCam = m_pCamera->GetCam(m_pCamera->GetActiveCam()); if (!pCam) return nullptr; @@ -864,7 +865,7 @@ CMatrix CClientCamera::GetGtaMatrix() const matResult.vFront = *pCam->GetFront(); matResult.vUp = *pCam->GetUp(); matResult.vPos = *pCam->GetSource(); - matResult.vRight = -matResult.vRight; // Camera has this the other way + matResult.vRight = -matResult.vRight; // Camera has this the other way matResult.OrthoNormalize(CMatrix::AXIS_FRONT, CMatrix::AXIS_UP); return matResult; } @@ -877,9 +878,7 @@ void CClientCamera::SetGtaMatrix(const CMatrix& matInNew, CCam* pCam) const if (!m_pCamera) return; - auto isFiniteVector = [](const CVector& vec) { - return std::isfinite(vec.fX) && std::isfinite(vec.fY) && std::isfinite(vec.fZ); - }; + auto isFiniteVector = [](const CVector& vec) { return std::isfinite(vec.fX) && std::isfinite(vec.fY) && std::isfinite(vec.fZ); }; if (!isFiniteVector(matInNew.vFront) || !isFiniteVector(matInNew.vUp) || !isFiniteVector(matInNew.vRight) || !isFiniteVector(matInNew.vPos)) return; @@ -890,7 +889,7 @@ void CClientCamera::SetGtaMatrix(const CMatrix& matInNew, CCam* pCam) const CMatrix matNew = matInNew; EnsureOrthonormal(matNew); - matNew.vRight = -matNew.vRight; // Camera has this the other way + matNew.vRight = -matNew.vRight; // Camera has this the other way m_pCamera->SetMatrix(&matNew); *targetCam->GetUp() = matNew.vUp; *targetCam->GetFront() = matNew.vFront; @@ -1003,7 +1002,7 @@ CMatrix CClientCamera::GetInterpolatedCameraMatrix() const CMatrix matrix; if (m_pCamera && m_pCamera->GetTransitionMatrix(matrix)) return matrix; - + return CMatrix(); } @@ -1011,9 +1010,9 @@ float CClientCamera::GetAccurateFOV() const { if (!m_pCamera) return DEFAULT_FOV; - + if (IsInCameraTransition()) return m_pCamera->GetTransitionFOV(); - + return *(float*)VAR_CurrentCameraFOV; } diff --git a/Client/mods/deathmatch/logic/CClientCamera.h b/Client/mods/deathmatch/logic/CClientCamera.h index b329b55e738..f217fd39ecf 100644 --- a/Client/mods/deathmatch/logic/CClientCamera.h +++ b/Client/mods/deathmatch/logic/CClientCamera.h @@ -38,7 +38,7 @@ class CClientCamera final : public CClientEntity friend class CClientManager; public: - void Unlink(){}; + void Unlink() {}; void DoPulse(); eClientEntityType GetType() const { return CCLIENTCAMERA; }; @@ -61,8 +61,8 @@ class CClientCamera final : public CClientEntity m_fFOV = fFOV; } - void SetOrbitTarget(const CVector& vecPosition); - void AttachTo(CClientEntity* pElement); + void SetOrbitTarget(const CVector& vecPosition); + void AttachTo(CClientEntity* pElement); void FadeIn(float fTime); void FadeOut(float fTime, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue); @@ -105,10 +105,10 @@ class CClientCamera final : public CClientEntity CMatrix GetGtaMatrix() const; void SetGtaMatrix(const CMatrix& matInNew, CCam* pCam = NULL) const; - void SetFocusToLocalPlayerImpl(); - void InvalidateCachedTransforms() const; - void SetCenterOfWorldCached(const CVector* pPosition, float fRotationRadians); - void UpdateCenterOfWorldFromFixedMatrix(); + void SetFocusToLocalPlayerImpl(); + void InvalidateCachedTransforms() const; + void SetCenterOfWorldCached(const CVector* pPosition, float fRotationRadians); + void UpdateCenterOfWorldFromFixedMatrix(); const CMatrix& AcquirePulseMatrix() const; const CVector& AcquirePulseEuler(const CMatrix& matrix) const; diff --git a/Client/mods/deathmatch/logic/CClientColCircle.cpp b/Client/mods/deathmatch/logic/CClientColCircle.cpp index 8641eaf12b5..4ddb65e901e 100644 --- a/Client/mods/deathmatch/logic/CClientColCircle.cpp +++ b/Client/mods/deathmatch/logic/CClientColCircle.cpp @@ -70,7 +70,7 @@ void CClientColCircle::DebugRender(const CVector& vecPosition, float fDrawRadius // Draw Slices { CVector vecMult(m_fRadius, m_fRadius, fHeight); - CVector vecAdd(vecOrigin.fX, vecOrigin.fY, vecBase.fZ + 4); // Extra bit so a slice is on the same Z coord as the camera + CVector vecAdd(vecOrigin.fX, vecOrigin.fY, vecBase.fZ + 4); // Extra bit so a slice is on the same Z coord as the camera for (uint s = iSkipEndSlices; s < uiNumSlices - iSkipEndSlices; s++) { diff --git a/Client/mods/deathmatch/logic/CClientColModel.h b/Client/mods/deathmatch/logic/CClientColModel.h index 081d5e44aae..01f98a278d8 100644 --- a/Client/mods/deathmatch/logic/CClientColModel.h +++ b/Client/mods/deathmatch/logic/CClientColModel.h @@ -36,9 +36,9 @@ class CClientColModel final : public CClientEntity static bool IsCOLData(const SString& strData); // Sorta a hack that these are required by CClientEntity... - void Unlink(){}; + void Unlink() {}; void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; private: bool LoadFromFile(SString filePath); diff --git a/Client/mods/deathmatch/logic/CClientColPolygon.cpp b/Client/mods/deathmatch/logic/CClientColPolygon.cpp index afe63491184..59338f5cc64 100644 --- a/Client/mods/deathmatch/logic/CClientColPolygon.cpp +++ b/Client/mods/deathmatch/logic/CClientColPolygon.cpp @@ -195,7 +195,7 @@ void CClientColPolygon::DebugRender(const CVector& vecPosition, float fDrawRadiu for (uint s = iSkipEndSlices; s < uiNumSlices - iSkipEndSlices; s++) { float fZ = vecPosition.fZ - fDrawRadius + fDrawRadius * 2.0f * (s / (float)(uiNumSlices - 1)); - fZ += 4; // Extra bit so a slice is on the same Z coord as the camera + fZ += 4; // Extra bit so a slice is on the same Z coord as the camera if (m_fFloor <= fZ && fZ <= m_fCeil) { for (uint i = 0; i < uiNumPoints; i++) diff --git a/Client/mods/deathmatch/logic/CClientColRectangle.cpp b/Client/mods/deathmatch/logic/CClientColRectangle.cpp index 9aac4f72b2e..6daa0ea2b6d 100644 --- a/Client/mods/deathmatch/logic/CClientColRectangle.cpp +++ b/Client/mods/deathmatch/logic/CClientColRectangle.cpp @@ -67,7 +67,7 @@ void CClientColRectangle::DebugRender(const CVector& vecPosition, float fDrawRad static const CVector cornerPoints[] = {CVector(0, 0, 1), CVector(1, 0, 1), CVector(1, 1, 1), CVector(0, 1, 1)}; CVector vecMult = vecSize; - CVector vecAdd = vecBase + CVector(0, 0, 4); // Extra bit so a slice is on the same Z coord as the camera + CVector vecAdd = vecBase + CVector(0, 0, 4); // Extra bit so a slice is on the same Z coord as the camera for (uint s = iSkipEndSlicesZ; s < uiNumSlicesZ - iSkipEndSlicesZ; s++) { @@ -94,7 +94,7 @@ void CClientColRectangle::DebugRender(const CVector& vecPosition, float fDrawRad for (uint i = 0; i < NUMELMS(cornerPoints); i++) { if (!(i & 1)) - continue; // No end cap + continue; // No end cap const CVector& vecBegin = cornerPoints[i] * vecMult + vecAdd; const CVector& vecEnd = cornerPoints[(i + 1) % 4] * vecMult + vecAdd; pGraphics->DrawLine3DQueued(vecBegin, vecEnd, fLineWidth, color, eRenderStage::POST_FX); @@ -115,7 +115,7 @@ void CClientColRectangle::DebugRender(const CVector& vecPosition, float fDrawRad for (uint i = 0; i < NUMELMS(cornerPoints); i++) { if (!(i & 1)) - continue; // No end cap + continue; // No end cap const CVector& vecBegin = cornerPoints[i] * vecMult + vecAdd; const CVector& vecEnd = cornerPoints[(i + 1) % 4] * vecMult + vecAdd; pGraphics->DrawLine3DQueued(vecBegin, vecEnd, fLineWidth, color, eRenderStage::POST_FX); diff --git a/Client/mods/deathmatch/logic/CClientCommon.h b/Client/mods/deathmatch/logic/CClientCommon.h index a01416ac1d5..74b356f4b65 100644 --- a/Client/mods/deathmatch/logic/CClientCommon.h +++ b/Client/mods/deathmatch/logic/CClientCommon.h @@ -11,32 +11,32 @@ #pragma once // Defines the maximum amount of mimics (fake players) -#define MAX_MIMICS 50 +#define MAX_MIMICS 50 // Defines the maximum amount of real players -#define MAX_NET_PLAYERS_REAL 250 +#define MAX_NET_PLAYERS_REAL 250 // Defines the maximum amount of players inside the game (includes mimics) -#define MAX_NET_PLAYERS (MAX_NET_PLAYERS_REAL + MAX_MIMICS) +#define MAX_NET_PLAYERS (MAX_NET_PLAYERS_REAL + MAX_MIMICS) // Defines the min/max size for the player nick (who the hell came up with 22?) -#define MIN_PLAYER_NICK_LENGTH 1 -#define MAX_PLAYER_NICK_LENGTH 22 +#define MIN_PLAYER_NICK_LENGTH 1 +#define MAX_PLAYER_NICK_LENGTH 22 // Defines the min/max size for the player nametag (who the hell came up with 22?) -#define MIN_PLAYER_NAMETAG_LENGTH 1 -#define MAX_PLAYER_NAMETAG_LENGTH 64 +#define MIN_PLAYER_NAMETAG_LENGTH 1 +#define MAX_PLAYER_NAMETAG_LENGTH 64 -#define MAX_TEAM_NAME_LENGTH 255 +#define MAX_TEAM_NAME_LENGTH 255 // Defines the minimum fade time for a transfer -#define MIN_TRANSFER_TIME 1500 +#define MIN_TRANSFER_TIME 1500 // Defines the maximum size for a player name // #define MAX_PLAYER_NAME_LENGTH 32 // Defines the maximum size for a HTTP Download URL -#define MAX_HTTP_DOWNLOAD_URL 512 +#define MAX_HTTP_DOWNLOAD_URL 512 // Defines the maximum size for a HTTP Download URL (with file / directory information appended) #define MAX_HTTP_DOWNLOAD_URL_WITH_FILE 768 @@ -48,8 +48,8 @@ enum eHTTPDownloadType HTTP_DOWNLOAD_ENABLED_URL }; -#define CHATCOLOR_DEFAULT 235, 221, 178 -#define CHATCOLOR_INFO 255, 100, 100 +#define CHATCOLOR_DEFAULT 235, 221, 178 +#define CHATCOLOR_INFO 255, 100, 100 // Interfaces to Blue extern CCoreInterface* g_pCore; diff --git a/Client/mods/deathmatch/logic/CClientDFF.cpp b/Client/mods/deathmatch/logic/CClientDFF.cpp index 3de11df6bc2..96f5a50a53d 100644 --- a/Client/mods/deathmatch/logic/CClientDFF.cpp +++ b/Client/mods/deathmatch/logic/CClientDFF.cpp @@ -50,7 +50,7 @@ RpClump* CClientDFF::GetLoadedClump(ushort usModelId) m_pManager->GetModelRequestManager()->RequestBlocking(usModelId, "CClientDFF::LoadDFF"); // Attempt loading it - if (!m_bIsRawData) // We have file + if (!m_bIsRawData) // We have file { if (g_pCore->GetNetwork()->CheckFile("dff", m_strDffFilename)) { @@ -58,7 +58,7 @@ RpClump* CClientDFF::GetLoadedClump(ushort usModelId) info.pClump = g_pGame->GetRenderWare()->ReadDFF(m_strDffFilename, SString(), usModelId, CClientVehicleManager::IsValidModel(usModelId)); } } - else // We have raw data + else // We have raw data { info.pClump = g_pGame->GetRenderWare()->ReadDFF(NULL, m_RawDataBuffer, usModelId, CClientVehicleManager::IsValidModel(usModelId)); diff --git a/Client/mods/deathmatch/logic/CClientDFF.h b/Client/mods/deathmatch/logic/CClientDFF.h index 22fc3ebef9f..f9d981dfa35 100644 --- a/Client/mods/deathmatch/logic/CClientDFF.h +++ b/Client/mods/deathmatch/logic/CClientDFF.h @@ -48,9 +48,9 @@ class CClientDFF final : public CClientEntity static bool IsDFFData(const SString& strData); // Sorta a hack that these are required by CClientEntity... - void Unlink(){}; + void Unlink() {}; void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; private: bool LoadFromFile(SString filePath); diff --git a/Client/mods/deathmatch/logic/CClientDisplayManager.cpp b/Client/mods/deathmatch/logic/CClientDisplayManager.cpp index 651b1d2efa1..357aabb8703 100644 --- a/Client/mods/deathmatch/logic/CClientDisplayManager.cpp +++ b/Client/mods/deathmatch/logic/CClientDisplayManager.cpp @@ -17,7 +17,7 @@ std::shared_ptr CClientDisplayManager::Get(unsigned long ulID) // Find the display with the given id auto iter = m_List.begin(); - for (; iter != m_List.end(); iter++) // Iterate weak_ptr list + for (; iter != m_List.end(); iter++) // Iterate weak_ptr list { if (const auto& display = (*iter).lock()) // Make sure the shared_ptr still exists { @@ -26,7 +26,6 @@ std::shared_ptr CClientDisplayManager::Get(unsigned long ulID) return display; } } - } return NULL; @@ -56,9 +55,9 @@ void CClientDisplayManager::DoPulse() // Clean up expired weak_ptr m_List.remove_if([](const std::weak_ptr& wp) { return wp.expired(); }); - for (; iter != m_List.end(); iter++) // Iterate weak_ptr list + for (; iter != m_List.end(); iter++) // Iterate weak_ptr list { - if (const auto& display = (*iter).lock()) // Make sure the shared_ptr still exists + if (const auto& display = (*iter).lock()) // Make sure the shared_ptr still exists { display->Render(); } diff --git a/Client/mods/deathmatch/logic/CClientDisplayManager.h b/Client/mods/deathmatch/logic/CClientDisplayManager.h index eac7e290842..9b87a15c327 100644 --- a/Client/mods/deathmatch/logic/CClientDisplayManager.h +++ b/Client/mods/deathmatch/logic/CClientDisplayManager.h @@ -31,7 +31,7 @@ class CClientDisplayManager void DoPulse(); - unsigned int Count() { return static_cast(m_List.size()); }; + unsigned int Count() { return static_cast(m_List.size()); }; std::shared_ptr Get(unsigned long ulID); void DrawText2D(const char* szCaption, const CVector& vecPosition, float fScale = 1.0f, RGBA rgbaColor = 0xFFFFFFFF); @@ -43,4 +43,3 @@ class CClientDisplayManager std::list> m_List; }; - diff --git a/Client/mods/deathmatch/logic/CClientEffectManager.cpp b/Client/mods/deathmatch/logic/CClientEffectManager.cpp index 0b5fbf92f5b..7eb18f5575f 100644 --- a/Client/mods/deathmatch/logic/CClientEffectManager.cpp +++ b/Client/mods/deathmatch/logic/CClientEffectManager.cpp @@ -37,7 +37,7 @@ CClientEffect* CClientEffectManager::Create(const SString& strEffectName, const CFxSystem* pFxSA = g_pGame->GetFxManager()->CreateFxSystem(strEffectName, vecPosition, NULL, true, bSoundEnable); if (pFxSA == NULL) - return NULL; // GTA was unable to create the effect (e.g. wrong effect name) + return NULL; // GTA was unable to create the effect (e.g. wrong effect name) CClientEffect* pFx = new CClientEffect(m_pManager, pFxSA, strEffectName, ID); m_Effects.push_back(pFx); @@ -86,7 +86,7 @@ void CClientEffectManager::SAEffectDestroyed(void* pFxSAInterface) g_pGame->GetFxManager()->OnFxSystemSAInterfaceDestroyed((CFxSystemSAInterface*)pFxSAInterface); if (pFx == NULL) - return; // We didn't create that effect + return; // We didn't create that effect pFx->SetFxSystem(NULL); g_pClientGame->GetElementDeleter()->Delete(pFx); diff --git a/Client/mods/deathmatch/logic/CClientEntity.cpp b/Client/mods/deathmatch/logic/CClientEntity.cpp index 4585bf2779c..5a500492e66 100644 --- a/Client/mods/deathmatch/logic/CClientEntity.cpp +++ b/Client/mods/deathmatch/logic/CClientEntity.cpp @@ -14,7 +14,7 @@ using std::list; extern CClientGame* g_pClientGame; -#pragma warning( disable : 4355 ) // warning C4355: 'this' : used in base member initializer list +#pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list CClientEntity::CClientEntity(ElementID ID) : ClassInit(this) { @@ -308,8 +308,8 @@ CLuaArguments* CClientEntity::GetAllCustomData(CLuaArguments* table) for (auto it = m_pCustomData->IterBegin(); it != m_pCustomData->IterEnd(); it++) { - table->PushString(it->first); // key - table->PushArgument(it->second.Variable); // value + table->PushString(it->first); // key + table->PushArgument(it->second.Variable); // value } return table; @@ -515,7 +515,7 @@ void CClientEntity::DeleteCustomData(const CStringName& name) CLuaArguments Arguments; Arguments.PushString(name); Arguments.PushArgument(oldVariable); - Arguments.PushArgument(CLuaArgument()); // Use nil as the new value to indicate the data has been removed + Arguments.PushArgument(CLuaArgument()); // Use nil as the new value to indicate the data has been removed CallEvent("onClientElementDataChange", Arguments, true); } } @@ -792,7 +792,7 @@ void CClientEntity::CallEventNoParent(const char* szName, const CLuaArguments& A if (!m_Children.empty()) { CElementListSnapshotRef pChildrenSnapshot = GetChildrenListSnapshot(); - for (CClientEntity* pEntity : *pChildrenSnapshot) + for (CClientEntity* pEntity : *pChildrenSnapshot) { if (!pEntity->IsBeingDeleted()) { @@ -1105,7 +1105,7 @@ bool CClientEntity::IsAttachedToElement(CClientEntity* pEntity, bool bRecursive) return true; if (!std::get(history.insert(pCurrent))) - break; // This should not be possible, but you never know + break; // This should not be possible, but you never know } return false; diff --git a/Client/mods/deathmatch/logic/CClientEntity.h b/Client/mods/deathmatch/logic/CClientEntity.h index 3d345a9fd28..ad2c6aa68e6 100644 --- a/Client/mods/deathmatch/logic/CClientEntity.h +++ b/Client/mods/deathmatch/logic/CClientEntity.h @@ -24,20 +24,20 @@ class CLuaFunctionRef; class CClientManager; -#define IS_PED(entity) ((entity)->GetType()==CCLIENTPLAYER||(entity)->GetType()==CCLIENTPED) -#define IS_PLAYER(entity) ((entity)->GetType()==CCLIENTPLAYER) -#define IS_REMOTE_PLAYER(player) (IS_PLAYER(player)&&!(player)->IsLocalPlayer()) -#define IS_RADARMARKER(entity) ((entity)->GetType()==CCLIENTRADARMARKER) -#define IS_VEHICLE(entity) ((entity)->GetType()==CCLIENTVEHICLE) -#define IS_OBJECT(entity) ((entity)->GetType()==CCLIENTOBJECT) -#define IS_MARKER(entity) ((entity)->GetType()==CCLIENTMARKER) -#define IS_PICKUP(entity) ((entity)->GetType()==CCLIENTPICKUP) -#define IS_RADAR_AREA(entity) ((entity)->GetType()==CCLIENTRADARAREA) -#define IS_COLSHAPE(entity) ((entity)->GetType()==CCLIENTCOLSHAPE) -#define IS_PROJECTILE(entity) ((entity)->GetType()==CCLIENTPROJECTILE) -#define IS_GUI(entity) ((entity)->GetType()==CCLIENTGUI) -#define IS_IFP(entity) ((entity)->GetType()==CCLIENTIFP) -#define CHECK_CGUI(entity,type) (((CClientGUIElement*)entity)->GetCGUIElement()->GetType()==(type)) +#define IS_PED(entity) ((entity)->GetType() == CCLIENTPLAYER || (entity)->GetType() == CCLIENTPED) +#define IS_PLAYER(entity) ((entity)->GetType() == CCLIENTPLAYER) +#define IS_REMOTE_PLAYER(player) (IS_PLAYER(player) && !(player)->IsLocalPlayer()) +#define IS_RADARMARKER(entity) ((entity)->GetType() == CCLIENTRADARMARKER) +#define IS_VEHICLE(entity) ((entity)->GetType() == CCLIENTVEHICLE) +#define IS_OBJECT(entity) ((entity)->GetType() == CCLIENTOBJECT) +#define IS_MARKER(entity) ((entity)->GetType() == CCLIENTMARKER) +#define IS_PICKUP(entity) ((entity)->GetType() == CCLIENTPICKUP) +#define IS_RADAR_AREA(entity) ((entity)->GetType() == CCLIENTRADARAREA) +#define IS_COLSHAPE(entity) ((entity)->GetType() == CCLIENTCOLSHAPE) +#define IS_PROJECTILE(entity) ((entity)->GetType() == CCLIENTPROJECTILE) +#define IS_GUI(entity) ((entity)->GetType() == CCLIENTGUI) +#define IS_IFP(entity) ((entity)->GetType() == CCLIENTIFP) +#define CHECK_CGUI(entity, type) (((CClientGUIElement*)entity)->GetCGUIElement()->GetType() == (type)) enum eClientEntityType { @@ -58,7 +58,7 @@ enum eClientEntityType CCLIENTGUI, CCLIENTSPAWNPOINT_DEPRECATED, CCLIENTCOLSHAPE, - CCLIENTDUMMY, // anything user-defined + CCLIENTDUMMY, // anything user-defined SCRIPTFILE, CCLIENTDFF, CCLIENTCOL, @@ -229,7 +229,7 @@ class CClientEntity : public CClientEntityBase virtual inline unsigned short GetDimension() { return m_usDimension; } virtual void SetDimension(unsigned short usDimension); - virtual void ModelRequestCallback(CModelInfo* pModelInfo){}; + virtual void ModelRequestCallback(CModelInfo* pModelInfo) {}; virtual bool IsOutOfBounds(); CModelInfo* GetModelInfo() { return m_pModelInfo; }; @@ -361,7 +361,7 @@ class CClientEntity : public CClientEntityBase CVector m_vecAttachedPosition; CVector m_vecAttachedRotation; std::vector m_AttachedEntities; - bool m_bDisallowAttaching; // Protect against attaching in destructor + bool m_bDisallowAttaching; // Protect against attaching in destructor bool m_bBeingDeleted; bool m_bSystemEntity; @@ -378,8 +378,8 @@ class CClientEntity : public CClientEntityBase bool m_bWorldIgnored; bool m_bCallPropagationEnabled; bool m_bDisallowCollisions; - bool m_canBeDestroyedByScript = true; // If true, destroyElement function will - // have no effect on this element + bool m_canBeDestroyedByScript = true; // If true, destroyElement function will + // have no effect on this element public: // Optimization for getElementsByType starting at root static void StartupEntitiesFromRoot(); diff --git a/Client/mods/deathmatch/logic/CClientEntityRefManager.h b/Client/mods/deathmatch/logic/CClientEntityRefManager.h index a12c5989362..5211c7b36c0 100644 --- a/Client/mods/deathmatch/logic/CClientEntityRefManager.h +++ b/Client/mods/deathmatch/logic/CClientEntityRefManager.h @@ -9,11 +9,9 @@ *****************************************************************************/ #ifdef MTA_DEBUG - #define ENTITY_REF_DEBUG( ptr, desc ) \ - SString ( "%08x %s", (int)ptr, desc ) + #define ENTITY_REF_DEBUG(ptr, desc) SString("%08x %s", (int)ptr, desc) #else - #define ENTITY_REF_DEBUG( ptr, desc ) \ - NULL + #define ENTITY_REF_DEBUG(ptr, desc) NULL #endif // diff --git a/Client/mods/deathmatch/logic/CClientExplosionManager.cpp b/Client/mods/deathmatch/logic/CClientExplosionManager.cpp index 29807b3887c..9ee6a90b001 100644 --- a/Client/mods/deathmatch/logic/CClientExplosionManager.cpp +++ b/Client/mods/deathmatch/logic/CClientExplosionManager.cpp @@ -41,7 +41,8 @@ bool CClientExplosionManager::Hook_StaticExplosionCreation(CEntity* pGameExplodi eWeaponType CClientExplosionManager::GetWeaponTypeFromExplosionType(const eExplosionType explosionType) { - switch (explosionType) { + switch (explosionType) + { case EXP_TYPE_GRENADE: return WEAPONTYPE_GRENADE; case EXP_TYPE_MOLOTOV: diff --git a/Client/mods/deathmatch/logic/CClientExplosionManager.h b/Client/mods/deathmatch/logic/CClientExplosionManager.h index 3931c0ae5fa..ea90478db95 100644 --- a/Client/mods/deathmatch/logic/CClientExplosionManager.h +++ b/Client/mods/deathmatch/logic/CClientExplosionManager.h @@ -34,6 +34,6 @@ class CClientExplosionManager CClientEntityPtr m_pLastCreator; private: - CClientManager* m_pManager; - eWeaponType GetWeaponTypeFromExplosionType(const eExplosionType explosionType); + CClientManager* m_pManager; + eWeaponType GetWeaponTypeFromExplosionType(const eExplosionType explosionType); }; diff --git a/Client/mods/deathmatch/logic/CClientGUIElement.h b/Client/mods/deathmatch/logic/CClientGUIElement.h index 51d58cf5aaf..a984ab59272 100644 --- a/Client/mods/deathmatch/logic/CClientGUIElement.h +++ b/Client/mods/deathmatch/logic/CClientGUIElement.h @@ -18,30 +18,30 @@ class CClientGUIElement; #define MAX_EVENT_NAME 256 -#define CGUI_GET_CCLIENTGUIELEMENT(x) static_cast < CClientGUIElement* > ( x->GetUserData () ) -#define CGUI_SET_CCLIENTGUIELEMENT(x,y) x->SetUserData ( reinterpret_cast < void* > ( y ) ) +#define CGUI_GET_CCLIENTGUIELEMENT(x) static_cast(x->GetUserData()) +#define CGUI_SET_CCLIENTGUIELEMENT(x, y) x->SetUserData(reinterpret_cast(y)) // use just for events, for all gui specific stuff use the funcs in the CGUI* classes // supports 2 events -#define IS_CGUIELEMENT_BUTTON(entity) ((entity)->GetCGUIType()==CGUI_BUTTON) -#define IS_CGUIELEMENT_CHECKBOX(entity) ((entity)->GetCGUIType()==CGUI_CHECKBOX) -#define IS_CGUIELEMENT_EDIT(entity) ((entity)->GetCGUIType()==CGUI_EDIT) -#define IS_CGUIELEMENT_GRIDLIST(entity) ((entity)->GetCGUIType()==CGUI_GRIDLIST) -#define IS_CGUIELEMENT_LABEL(entity) ((entity)->GetCGUIType()==CGUI_LABEL) -#define IS_CGUIELEMENT_MEMO(entity) ((entity)->GetCGUIType()==CGUI_MEMO) -#define IS_CGUIELEMENT_PROGRESSBAR(entity) ((entity)->GetCGUIType()==CGUI_PROGRESSBAR) -#define IS_CGUIELEMENT_SCROLLBAR(entity) ((entity)->GetCGUIType()==CGUI_SCROLLBAR) -#define IS_CGUIELEMENT_SCROLLPANE(entity) ((entity)->GetCGUIType()==CGUI_SCROLLPANE) -#define IS_CGUIELEMENT_RADIOBUTTON(entity) ((entity)->GetCGUIType()==CGUI_RADIOBUTTON) -#define IS_CGUIELEMENT_STATICIMAGE(entity) ((entity)->GetCGUIType()==CGUI_STATICIMAGE) -#define IS_CGUIELEMENT_TAB(entity) ((entity)->GetCGUIType()==CGUI_TAB) -#define IS_CGUIELEMENT_TABPANEL(entity) ((entity)->GetCGUIType()==CGUI_TABPANEL) -#define IS_CGUIELEMENT_COMBOBOX(entity) ((entity)->GetCGUIType()==CGUI_COMBOBOX) -#define IS_CGUIELEMENT_WINDOW(entity) ((entity)->GetCGUIType()==CGUI_WINDOW) - -#define IS_CGUIELEMENT_VALID_PARENT(entity) (IS_CGUIELEMENT_SCROLLPANE(entity) || IS_CGUIELEMENT_WINDOW(entity) || IS_CGUIELEMENT_TAB(entity) ) +#define IS_CGUIELEMENT_BUTTON(entity) ((entity)->GetCGUIType() == CGUI_BUTTON) +#define IS_CGUIELEMENT_CHECKBOX(entity) ((entity)->GetCGUIType() == CGUI_CHECKBOX) +#define IS_CGUIELEMENT_EDIT(entity) ((entity)->GetCGUIType() == CGUI_EDIT) +#define IS_CGUIELEMENT_GRIDLIST(entity) ((entity)->GetCGUIType() == CGUI_GRIDLIST) +#define IS_CGUIELEMENT_LABEL(entity) ((entity)->GetCGUIType() == CGUI_LABEL) +#define IS_CGUIELEMENT_MEMO(entity) ((entity)->GetCGUIType() == CGUI_MEMO) +#define IS_CGUIELEMENT_PROGRESSBAR(entity) ((entity)->GetCGUIType() == CGUI_PROGRESSBAR) +#define IS_CGUIELEMENT_SCROLLBAR(entity) ((entity)->GetCGUIType() == CGUI_SCROLLBAR) +#define IS_CGUIELEMENT_SCROLLPANE(entity) ((entity)->GetCGUIType() == CGUI_SCROLLPANE) +#define IS_CGUIELEMENT_RADIOBUTTON(entity) ((entity)->GetCGUIType() == CGUI_RADIOBUTTON) +#define IS_CGUIELEMENT_STATICIMAGE(entity) ((entity)->GetCGUIType() == CGUI_STATICIMAGE) +#define IS_CGUIELEMENT_TAB(entity) ((entity)->GetCGUIType() == CGUI_TAB) +#define IS_CGUIELEMENT_TABPANEL(entity) ((entity)->GetCGUIType() == CGUI_TABPANEL) +#define IS_CGUIELEMENT_COMBOBOX(entity) ((entity)->GetCGUIType() == CGUI_COMBOBOX) +#define IS_CGUIELEMENT_WINDOW(entity) ((entity)->GetCGUIType() == CGUI_WINDOW) + +#define IS_CGUIELEMENT_VALID_PARENT(entity) (IS_CGUIELEMENT_SCROLLPANE(entity) || IS_CGUIELEMENT_WINDOW(entity) || IS_CGUIELEMENT_TAB(entity)) class CClientGUIElement : public CClientEntity { @@ -66,7 +66,7 @@ class CClientGUIElement : public CClientEntity CLuaMain* GetVirtualMachine() { return m_pLuaMain; } // dummy overrides - void SetPosition(const CVector& vecDummy){}; + void SetPosition(const CVector& vecDummy) {}; void GetPosition(CVector& vecDummy) const {}; // cgui element access diff --git a/Client/mods/deathmatch/logic/CClientGame.cpp b/Client/mods/deathmatch/logic/CClientGame.cpp index 3de95d070c0..47d7461cdd0 100644 --- a/Client/mods/deathmatch/logic/CClientGame.cpp +++ b/Client/mods/deathmatch/logic/CClientGame.cpp @@ -120,7 +120,7 @@ CClientGame::CClientGame(bool bLocalPlay) : m_ServerInfo(new CServerInfo()) m_lMoney = 0; m_dwWanted = 0; m_timeLastDiscordStateUpdate = 0; - m_lastWeaponSlot = WEAPONSLOT_MAX; // last stored weapon slot, for weapon slot syncing to server (sets to invalid value) + m_lastWeaponSlot = WEAPONSLOT_MAX; // last stored weapon slot, for weapon slot syncing to server (sets to invalid value) ResetAmmoInClip(); m_bFocused = g_pCore->IsFocused(); @@ -557,7 +557,7 @@ CClientGame::~CClientGame() // StaticReset calls. TXD destructors need intact bookkeeping to clean up propery. // Destroy our stuff - SAFE_DELETE(m_pManager); // Will trigger onClientResourceStop + SAFE_DELETE(m_pManager); // Will trigger onClientResourceStop SAFE_DELETE(m_pNametags); SAFE_DELETE(m_pSyncDebug); @@ -953,8 +953,8 @@ void CClientGame::DoPulsePostFrame() // Draw network trouble message if required if (m_pNetAPI->IsNetworkTrouble()) { - int iPosX = uiWidth / 2; // Half way across - int iPosY = uiHeight * 45 / 100; // 45/100 down + int iPosX = uiWidth / 2; // Half way across + int iPosY = uiHeight * 45 / 100; // 45/100 down g_pCore->GetGraphics()->DrawString(iPosX, iPosY, iPosX, iPosY, COLOR_ARGB(255, 255, 0, 0), "*** NETWORK TROUBLE ***", 2.0f, 2.0f, DT_NOCLIP | DT_CENTER); } @@ -1404,7 +1404,7 @@ void CClientGame::DoPulses() { case RID_RSA_PUBLIC_KEY_MISMATCH: strError = _("Disconnected: unknown protocol error"); - strErrorCode = _E("CD10"); // encryption key mismatch + strErrorCode = _E("CD10"); // encryption key mismatch break; case RID_REMOTE_DISCONNECTION_NOTIFICATION: strError = _("Disconnected: disconnected remotely"); @@ -1470,7 +1470,7 @@ void CClientGame::DoPulses() m_pLocalPlayer->UpdateVehicleInOut(); UpdatePlayerTarget(); UpdatePlayerWeapons(); - UpdateTrailers(); // Test: Does it always work without this check? + UpdateTrailers(); // Test: Does it always work without this check? UpdateStunts(); // Clear last damager if more than 2 seconds old if (CClientTime::GetTime() - m_ulDamageTime > 2000) @@ -2226,16 +2226,16 @@ bool CClientGame::KeyStrokeHandler(const SString& strKey, bool bState, bool bIsC if (g_pCore->IsMenuVisible() || (g_pCore->GetConsole()->IsInputActive() && bIsConsoleInputKey) || (pFocusedBrowser && !pFocusedBrowser->IsLocal() && !isMouseKey)) - bIgnore = true; // Ignore this keydown and the matching keyup + bIgnore = true; // Ignore this keydown and the matching keyup else - MapInsert(m_AllowKeyUpMap, strKey); // Use this keydown and the matching keyup + MapInsert(m_AllowKeyUpMap, strKey); // Use this keydown and the matching keyup } else { if (!MapContains(m_AllowKeyUpMap, strKey)) - bIgnore = true; // Ignore this keyup + bIgnore = true; // Ignore this keyup else - MapRemove(m_AllowKeyUpMap, strKey); // Use this keyup + MapRemove(m_AllowKeyUpMap, strKey); // Use this keyup } if (!bIgnore) @@ -3098,7 +3098,7 @@ void CClientGame::UpdateMimics() } // Simulate lag (or not) - if (!m_bMimicLag || CClientTime::GetTime() >= m_ulLastMimicLag + 200) // TICK_RATE ) + if (!m_bMimicLag || CClientTime::GetTime() >= m_ulLastMimicLag + 200) // TICK_RATE ) { m_ulLastMimicLag = CClientTime::GetTime(); @@ -3496,7 +3496,7 @@ void CClientGame::Event_OnIngame() // Reset anything from last game ResetMapInfo(); - g_pGame->GetWaterManager()->Reset(); // Deletes all custom water elements, ResetMapInfo only reverts changes to water level + g_pGame->GetWaterManager()->Reset(); // Deletes all custom water elements, ResetMapInfo only reverts changes to water level g_pGame->GetWaterManager()->SetWaterDrawnLast(true); m_pCamera->SetCameraClip(true, true); @@ -4324,7 +4324,7 @@ bool CClientGame::DamageHandler(CPed* pDamagePed, CEventDamage* pEvent) CClientPlayer* pInflictingPlayer = DynamicCast(pInflictingEntity); if (pInflictingPlayer && !pInflictingPlayer->IsLocalPlayer()) { - bool bBulletSyncShot = (g_iDamageEventLimit != -1); // Called from discharge weapon + bool bBulletSyncShot = (g_iDamageEventLimit != -1); // Called from discharge weapon bool bBulletSyncWeapon = GetWeaponTypeUsesBulletSync(weaponUsed); if (bBulletSyncShot) @@ -4609,7 +4609,7 @@ void CClientGame::DeathHandler(CPed* pKilledPedSA, unsigned char ucDeathReason, { // Set explosion damage data so DoWastedCheck uses correct parameters SetExplosionDamageData(); - return; // Local player death is handled by DoWastedCheck + return; // Local player death is handled by DoWastedCheck } // Not required for remote players. Local player is handled in DoPulses->DoWastedCheck @@ -5083,7 +5083,7 @@ bool CClientGame::PreWeaponFire(CPlayerPed* pPlayerPed, bool bStopIfUsingBulletS if (pPlayer && !pPlayer->IsLocalPlayer()) { if (bStopIfUsingBulletSync && pPlayer->IsCurrentWeaponUsingBulletSync()) - return false; // Don't apply shot compensation & tell caller to not do bullet trace + return false; // Don't apply shot compensation & tell caller to not do bullet trace if (bShotCompensation) { @@ -6900,7 +6900,7 @@ void CClientGame::Restream(std::optional option) m_pManager->GetVehicleManager()->RestreamAllVehicles(); } - + if (option == RestreamOption::ALL || option == RestreamOption::PEDS) { for (const auto& model : m_pManager->GetModelManager()->GetModelsByType(eClientModelType::PED)) diff --git a/Client/mods/deathmatch/logic/CClientGame.h b/Client/mods/deathmatch/logic/CClientGame.h index 8337c22ea27..bad7247c905 100644 --- a/Client/mods/deathmatch/logic/CClientGame.h +++ b/Client/mods/deathmatch/logic/CClientGame.h @@ -130,7 +130,7 @@ class CClientGame SCRIPTFILE, WATER, WEAPON, - _DATABASE_CONNECTION, // server only + _DATABASE_CONNECTION, // server only TRAIN_TRACK, ROOT, UNKNOWN, @@ -193,7 +193,7 @@ class CClientGame QUIT_CONNECTION_DESYNC, QUIT_TIMEOUT, }; - + enum { GLITCH_QUICKRELOAD, @@ -405,22 +405,23 @@ class CClientGame AnimationId animId = 15); void SendPedWastedPacket(CClientPed* Ped, ElementID damagerID = INVALID_ELEMENT_ID, unsigned char ucWeapon = 0xFF, unsigned char ucBodyPiece = 0xFF, AssocGroupId animGroup = 0, AnimationId animID = 15); - - void ClearDamageData() noexcept { + + void ClearDamageData() noexcept + { m_DamagerID = INVALID_ELEMENT_ID; m_ucDamageWeapon = WEAPONTYPE_INVALID; m_ucDamageBodyPiece = BODYPART_INVALID; m_ulDamageTime = 0; m_serverProcessedDeath = true; } - - void ResetDeathProcessingFlag() noexcept { - m_serverProcessedDeath = false; - } - - void SetScriptedDeathData() { + + void ResetDeathProcessingFlag() noexcept { m_serverProcessedDeath = false; } + + void SetScriptedDeathData() + { auto* localPlayer = GetLocalPlayer(); - if (!localPlayer) { + if (!localPlayer) + { m_DamagerID = INVALID_ELEMENT_ID; m_ucDamageWeapon = WEAPONTYPE_INVALID; m_ucDamageBodyPiece = BODYPART_INVALID; @@ -428,15 +429,16 @@ class CClientGame m_serverProcessedDeath = false; return; } - + m_DamagerID = INVALID_ELEMENT_ID; m_ucDamageWeapon = TryGetCurrentWeapon(localPlayer); m_ucDamageBodyPiece = BODYPART_TORSO; m_ulDamageTime = CClientTime::GetTime(); m_serverProcessedDeath = false; } - - void SetExplosionDamageData() noexcept { + + void SetExplosionDamageData() noexcept + { m_DamagerID = INVALID_ELEMENT_ID; m_ucDamageWeapon = WEAPONTYPE_EXPLOSION; m_ucDamageBodyPiece = BODYPART_TORSO; @@ -510,8 +512,8 @@ class CClientGame void ReinitMarkers(); void OnWindowFocusChange(bool state); - - void SetAllowMultiCommandHandlers(MultiCommandHandlerPolicy policy) noexcept { m_allowMultiCommandHandlers = policy; } + + void SetAllowMultiCommandHandlers(MultiCommandHandlerPolicy policy) noexcept { m_allowMultiCommandHandlers = policy; } MultiCommandHandlerPolicy GetAllowMultiCommandHandlers() const noexcept { return m_allowMultiCommandHandlers; } private: @@ -636,7 +638,8 @@ class CClientGame RpClump* pClump); bool ProcessCollisionHandler(CEntitySAInterface* pThisInterface, CEntitySAInterface* pOtherInterface); bool VehicleCollisionHandler(CVehicleSAInterface*& pCollidingVehicle, CEntitySAInterface* pCollidedVehicle, int iModelIndex, float fDamageImpulseMag, - float fCollidingDamageImpulseMag, uint16 usPieceType, CVector vecCollisionPos, CVector vecCollisionVelocity, bool isProjectile); + float fCollidingDamageImpulseMag, uint16 usPieceType, CVector vecCollisionPos, CVector vecCollisionVelocity, + bool isProjectile); bool VehicleDamageHandler(CEntitySAInterface* pVehicleInterface, float fLoss, CEntitySAInterface* pAttackerInterface, eWeaponType weaponType, const CVector& vecDamagePos, uchar ucTyre); bool HeliKillHandler(CVehicleSAInterface* pHeli, CEntitySAInterface* pHitInterface); @@ -675,7 +678,8 @@ class CClientGame bool VerifySADataFiles(int iEnableClientChecks = 0); void DebugElementRender(); - void SendExplosionSync(const CVector& vecPosition, eExplosionType Type, CClientEntity* pOrigin = nullptr, std::optional vehicleBlowState = std::nullopt); + void SendExplosionSync(const CVector& vecPosition, eExplosionType Type, CClientEntity* pOrigin = nullptr, + std::optional vehicleBlowState = std::nullopt); void SendFireSync(CFire* pFire); void SendProjectileSync(CClientProjectile* pProjectile); @@ -812,7 +816,7 @@ class CClientGame unsigned char m_ucDamageBodyPiece; unsigned long m_ulDamageTime; bool m_bDamageSent; - bool m_serverProcessedDeath{false}; // Flag to track server-processed deaths + bool m_serverProcessedDeath{false}; // Flag to track server-processed deaths eWeaponSlot m_lastWeaponSlot; SFixedArray m_wasWeaponAmmoInClip; @@ -853,7 +857,7 @@ class CClientGame long long m_llLastTransgressionTime; SString m_strLastDiagnosticStatus; - bool m_bBeingDeleted; // To enable speedy disconnect + bool m_bBeingDeleted; // To enable speedy disconnect bool m_bWasMinimized; bool m_bFocused; @@ -919,9 +923,9 @@ class CClientGame AnimAssociations_type m_mapOfCustomAnimationAssociations; // Key is the task and value is the CClientPed* RunNamedAnimTask_type m_mapOfRunNamedAnimTasks; - + MultiCommandHandlerPolicy m_allowMultiCommandHandlers; - + long long m_timeLastDiscordStateUpdate; }; diff --git a/Client/mods/deathmatch/logic/CClientIFP.cpp b/Client/mods/deathmatch/logic/CClientIFP.cpp index 5694d2c3379..9b36b5a97fc 100644 --- a/Client/mods/deathmatch/logic/CClientIFP.cpp +++ b/Client/mods/deathmatch/logic/CClientIFP.cpp @@ -551,7 +551,7 @@ void CClientIFP::CopyDummyKeyFrameByBoneID(BYTE* pKeyFrames, DWORD dwBoneID) { switch (dwBoneID) { - case eBoneType::NORMAL: // Normal or Root, both are same + case eBoneType::NORMAL: // Normal or Root, both are same { // This is a root frame. It contains translation as well, but it's compressed just like quaternion BYTE FrameData[16] = {0x1F, 0x00, 0x00, 0x00, 0x53, 0x0B, 0x4D, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00}; @@ -1102,7 +1102,7 @@ CAnimBlendHierarchySAInterface* CClientIFP::GetAnimationHierarchy(const SString& { const unsigned int uiAnimationNameHash = HashString(strAnimationName.ToLower()); auto it = std::find_if(m_pVecAnimations->begin(), m_pVecAnimations->end(), - [&uiAnimationNameHash](SAnimation const& Animation) { return Animation.uiNameHash == uiAnimationNameHash; }); + [&uiAnimationNameHash](SAnimation const& Animation) { return Animation.uiNameHash == uiAnimationNameHash; }); if (it != m_pVecAnimations->end()) { return it->pHierarchy->GetInterface(); diff --git a/Client/mods/deathmatch/logic/CClientIFP.h b/Client/mods/deathmatch/logic/CClientIFP.h index 233030f1016..6218ff5182b 100644 --- a/Client/mods/deathmatch/logic/CClientIFP.h +++ b/Client/mods/deathmatch/logic/CClientIFP.h @@ -151,7 +151,7 @@ class CClientIFP final : public CClientEntity, CFileReader char Name[24]; std::int32_t TotalObjects; std::int32_t FrameSize; - std::int32_t isCompressed; // The value is always 1 + std::int32_t isCompressed; // The value is always 1 }; struct SSequenceHeaderV2 @@ -165,7 +165,7 @@ class CClientIFP final : public CClientEntity, CFileReader enum eBoneType { UNKNOWN = -1, - NORMAL = 0, // Normal or Root, both are same + NORMAL = 0, // Normal or Root, both are same PELVIS = 1, SPINE = 2, SPINE1 = 3, @@ -216,7 +216,7 @@ class CClientIFP final : public CClientEntity, CFileReader // Sorta a hack that these are required by CClientEntity... void Unlink(); void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; private: bool ReadIFPByVersion(); diff --git a/Client/mods/deathmatch/logic/CClientIMG.cpp b/Client/mods/deathmatch/logic/CClientIMG.cpp index 4082bc5e154..26f31baf0af 100644 --- a/Client/mods/deathmatch/logic/CClientIMG.cpp +++ b/Client/mods/deathmatch/logic/CClientIMG.cpp @@ -209,7 +209,7 @@ bool CClientIMG::LinkModel(unsigned int uiModelID, size_t uiFileID) return false; if (pCurrInfo->archiveId == m_ucArchiveID) - return true; // Already linked + return true; // Already linked m_restoreInfo.emplace_back(uiModelID, pCurrInfo->offsetInBlocks, pCurrInfo->sizeInBlocks, pCurrInfo->archiveId); diff --git a/Client/mods/deathmatch/logic/CClientIMG.h b/Client/mods/deathmatch/logic/CClientIMG.h index 2074e64fbc0..7408c3407cd 100644 --- a/Client/mods/deathmatch/logic/CClientIMG.h +++ b/Client/mods/deathmatch/logic/CClientIMG.h @@ -52,7 +52,7 @@ class CClientIMG : public CClientEntity void Unlink(); void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; eClientEntityType GetType() const { return CCLIENTIMG; } unsigned char GetArchiveID() const { return m_ucArchiveID; } @@ -81,7 +81,7 @@ class CClientIMG : public CClientEntity fs::path m_filePath; unsigned char m_ucArchiveID; std::vector m_fileInfos; - size_t m_LargestFileSizeBlocks; // The size of the largest file [in streaming blocks/sectors] + size_t m_LargestFileSizeBlocks; // The size of the largest file [in streaming blocks/sectors] std::vector m_restoreInfo; }; diff --git a/Client/mods/deathmatch/logic/CClientIMGManager.cpp b/Client/mods/deathmatch/logic/CClientIMGManager.cpp index 7fe1851d1df..a428a48c861 100644 --- a/Client/mods/deathmatch/logic/CClientIMGManager.cpp +++ b/Client/mods/deathmatch/logic/CClientIMGManager.cpp @@ -22,7 +22,7 @@ CClientIMGManager::CClientIMGManager(CClientManager* pManager) // TODO: In the default gta3.img the biggest file is 1260 sectors, so to be fail safe, we double it // ideally, we'd just take this value from the game, but there's no clean/easy way to do that [without loading the img archives] // so, for now, this is good enough - m_LargestFileSizeBlocks = m_GTALargestFileSizeBlocks = 1260 * 2; + m_LargestFileSizeBlocks = m_GTALargestFileSizeBlocks = 1260 * 2; } CClientIMGManager::~CClientIMGManager() diff --git a/Client/mods/deathmatch/logic/CClientIMGManager.h b/Client/mods/deathmatch/logic/CClientIMGManager.h index a16239e88b1..dd34beb01c3 100644 --- a/Client/mods/deathmatch/logic/CClientIMGManager.h +++ b/Client/mods/deathmatch/logic/CClientIMGManager.h @@ -37,11 +37,11 @@ class CClientIMGManager private: size_t CalculateLargestFile() const; - void AddToList(CClientIMG* pIMG) { m_List.push_back(pIMG); } - void RemoveFromList(CClientIMG* pIMG); + void AddToList(CClientIMG* pIMG) { m_List.push_back(pIMG); } + void RemoveFromList(CClientIMG* pIMG); std::list m_List; bool m_bRemoveFromList; uint32 m_GTALargestFileSizeBlocks; - uint32 m_LargestFileSizeBlocks; // Size of the largest file [in streaming blocks/sectors] in any of the loaded imgs + uint32 m_LargestFileSizeBlocks; // Size of the largest file [in streaming blocks/sectors] in any of the loaded imgs }; diff --git a/Client/mods/deathmatch/logic/CClientManager.cpp b/Client/mods/deathmatch/logic/CClientManager.cpp index e3a808555b4..bf79bf9ec93 100644 --- a/Client/mods/deathmatch/logic/CClientManager.cpp +++ b/Client/mods/deathmatch/logic/CClientManager.cpp @@ -201,7 +201,7 @@ void CClientManager::DoPulse(bool bDoStandardPulses, bool bDoVehicleManagerPulse are no longer a frame behind when attached to other entities. m_pMarkerManager->DoPulse (); */ m_pRadarAreaManager->DoPulse( - false); // DoPulse, but do not render (we render them from a hook to avoid render issues - the mask not blocking the edges) + false); // DoPulse, but do not render (we render them from a hook to avoid render issues - the mask not blocking the edges) } if (bDoVehicleManagerPulse) diff --git a/Client/mods/deathmatch/logic/CClientManager.h b/Client/mods/deathmatch/logic/CClientManager.h index 12aee3816cf..26f93f0015b 100644 --- a/Client/mods/deathmatch/logic/CClientManager.h +++ b/Client/mods/deathmatch/logic/CClientManager.h @@ -99,7 +99,10 @@ class CClientManager CClientIMGManager* GetIMGManager() { return m_pImgManager; } CClientBuildingManager* GetBuildingManager() const noexcept { return m_pBuildingManager; } - bool IsGameLoaded() { return g_pGame->GetSystemState() == SystemState::GS_PLAYING_GAME && !m_bGameUnloadedFlag && g_pCore->GetNetwork()->GetServerBitStreamVersion(); } + bool IsGameLoaded() + { + return g_pGame->GetSystemState() == SystemState::GS_PLAYING_GAME && !m_bGameUnloadedFlag && g_pCore->GetNetwork()->GetServerBitStreamVersion(); + } bool IsBeingDeleted() { return m_bBeingDeleted; } void SetGameUnloadedFlag() { m_bGameUnloadedFlag = true; } diff --git a/Client/mods/deathmatch/logic/CClientMarker.cpp b/Client/mods/deathmatch/logic/CClientMarker.cpp index 20bd915661a..72c300dad04 100644 --- a/Client/mods/deathmatch/logic/CClientMarker.cpp +++ b/Client/mods/deathmatch/logic/CClientMarker.cpp @@ -13,7 +13,7 @@ extern CClientGame* g_pClientGame; #ifndef M_PI -#define M_PI 3.14159265358979323846 + #define M_PI 3.14159265358979323846 #endif unsigned int CClientMarker::m_uiStreamedInMarkers = 0; @@ -318,11 +318,11 @@ void CClientMarker::SetSize(float fSize) { CClientColTube* pShape = static_cast(m_pCollision); pShape->SetRadius(fSize); - pShape->SetHeight(fSize <= 1.5 ? fSize + 1 : fSize); + pShape->SetHeight(fSize <= 1.5 ? fSize + 1 : fSize); break; } } - + m_pMarker->SetSize(fSize); } @@ -425,16 +425,16 @@ void CClientMarker::Callback_OnCollision(CClientColShape& shape, CClientEntity& // Call the marker hit event CLuaArguments arguments; - arguments.PushElement(&entity); // Hit element - arguments.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? + arguments.PushElement(&entity); // Hit element + arguments.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? CallEvent("onClientMarkerHit", arguments, true); if (!IS_PLAYER(&entity)) return; CLuaArguments arguments2; - arguments2.PushElement(this); // marker - arguments2.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? + arguments2.PushElement(this); // marker + arguments2.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? entity.CallEvent("onClientPlayerMarkerHit", arguments2, false); } @@ -445,16 +445,16 @@ void CClientMarker::Callback_OnLeave(CClientColShape& shape, CClientEntity& enti // Call the marker leave event CLuaArguments arguments; - arguments.PushElement(&entity); // Hit element - arguments.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? + arguments.PushElement(&entity); // Hit element + arguments.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? CallEvent("onClientMarkerLeave", arguments, true); if (!IS_PLAYER(&entity)) return; CLuaArguments arguments2; - arguments2.PushElement(this); // marker - arguments2.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? + arguments2.PushElement(this); // marker + arguments2.PushBoolean(GetDimension() == entity.GetDimension()); // Matching dimension? entity.CallEvent("onPlayerMarkerLeave", arguments2, false); } diff --git a/Client/mods/deathmatch/logic/CClientModel.cpp b/Client/mods/deathmatch/logic/CClientModel.cpp index ce094ed027b..c8c37d59290 100644 --- a/Client/mods/deathmatch/logic/CClientModel.cpp +++ b/Client/mods/deathmatch/logic/CClientModel.cpp @@ -155,17 +155,19 @@ void CClientModel::RestoreDFF(CModelInfo* pModelInfo) if (!g_pClientGame || !g_pClientGame->GetManager()) return; - const int modelId = m_iModelID; + const int modelId = m_iModelID; const auto modelType = m_eModelType; - auto callElementChangeEvent = [](auto &element, unsigned short usParentID, auto modelId) { + auto callElementChangeEvent = [](auto& element, unsigned short usParentID, auto modelId) + { CLuaArguments Arguments; Arguments.PushNumber(modelId); Arguments.PushNumber(usParentID); element.CallEvent("onClientElementModelChange", Arguments, true); }; - auto copyPtrs = [](auto begin, auto end) { + auto copyPtrs = [](auto begin, auto end) + { using T = typename std::iterator_traits::value_type; std::vector out; for (auto it = begin; it != end; ++it) @@ -173,7 +175,9 @@ void CClientModel::RestoreDFF(CModelInfo* pModelInfo) return out; }; - auto unloadModelsAndCallEvents = [modelId, callElementChangeEvent, copyPtrs](auto iterBegin, auto iterEnd, unsigned short usParentID, auto setElementModelLambda) { + auto unloadModelsAndCallEvents = + [modelId, callElementChangeEvent, copyPtrs](auto iterBegin, auto iterEnd, unsigned short usParentID, auto setElementModelLambda) + { auto items = copyPtrs(iterBegin, iterEnd); for (auto ptr : items) { @@ -193,7 +197,8 @@ void CClientModel::RestoreDFF(CModelInfo* pModelInfo) } }; - auto unloadModelsAndCallEventsNonStreamed = [modelId, callElementChangeEvent, copyPtrs](auto iterBegin, auto iterEnd, unsigned short usParentID, auto setElementModelLambda) + auto unloadModelsAndCallEventsNonStreamed = + [modelId, callElementChangeEvent, copyPtrs](auto iterBegin, auto iterEnd, unsigned short usParentID, auto setElementModelLambda) { auto items = copyPtrs(iterBegin, iterEnd); for (auto ptr : items) @@ -232,12 +237,13 @@ void CClientModel::RestoreDFF(CModelInfo* pModelInfo) CClientPickupManager* pPickupManager = g_pClientGame->GetManager()->GetPickupManager(); - unloadModelsAndCallEvents(pPickupManager->IterBegin(), pPickupManager->IterEnd(), usParentID, [usParentID](auto& element) { element.SetModel(usParentID); }); + unloadModelsAndCallEvents(pPickupManager->IterBegin(), pPickupManager->IterEnd(), usParentID, + [usParentID](auto& element) { element.SetModel(usParentID); }); CClientBuildingManager* pBuildingsManager = g_pClientGame->GetManager()->GetBuildingManager(); auto& buildingsList = pBuildingsManager->GetBuildings(); unloadModelsAndCallEventsNonStreamed(buildingsList.begin(), buildingsList.end(), usParentID, - [usParentID](auto& element) { element.SetModel(usParentID); }); + [usParentID](auto& element) { element.SetModel(usParentID); }); g_pClientGame->GetManager()->GetColModelManager()->RestoreModel(modelId); break; @@ -256,7 +262,7 @@ void CClientModel::RestoreDFF(CModelInfo* pModelInfo) g_pClientGame->GetManager()->GetDFFManager()->RestoreModel(modelId); } -bool CClientModel::AllocateTXD(std::string &strTxdName) +bool CClientModel::AllocateTXD(std::string& strTxdName) { if (m_iModelID < MAX_MODEL_DFF_ID) return false; diff --git a/Client/mods/deathmatch/logic/CClientModel.h b/Client/mods/deathmatch/logic/CClientModel.h index 759890e0e57..86f6ce4ab3a 100644 --- a/Client/mods/deathmatch/logic/CClientModel.h +++ b/Client/mods/deathmatch/logic/CClientModel.h @@ -55,5 +55,5 @@ class CClientModel final int m_iModelID; eClientModelType m_eModelType; bool m_bAllocatedByUs = false; - CResource* m_pParentResource = nullptr; // Resource that allocated model + CResource* m_pParentResource = nullptr; // Resource that allocated model }; diff --git a/Client/mods/deathmatch/logic/CClientModelCacheManager.cpp b/Client/mods/deathmatch/logic/CClientModelCacheManager.cpp index 5619834a8a2..d2889c18868 100644 --- a/Client/mods/deathmatch/logic/CClientModelCacheManager.cpp +++ b/Client/mods/deathmatch/logic/CClientModelCacheManager.cpp @@ -10,18 +10,18 @@ #include "StdInc.h" #include "../../../core/CModelCacheManager.h" -#define PED_STREAM_IN_DISTANCE (250) -#define VEHICLE_STREAM_IN_DISTANCE (250) -#define STREAMER_STREAM_OUT_EXTRA_DISTANCE (50) +#define PED_STREAM_IN_DISTANCE (250) +#define VEHICLE_STREAM_IN_DISTANCE (250) +#define STREAMER_STREAM_OUT_EXTRA_DISTANCE (50) -#define PED_MAX_STREAM_DISTANCE ( PED_STREAM_IN_DISTANCE + STREAMER_STREAM_OUT_EXTRA_DISTANCE ) -#define PED_MAX_STREAM_DISTANCE_SQ ( PED_MAX_STREAM_DISTANCE * PED_MAX_STREAM_DISTANCE ) +#define PED_MAX_STREAM_DISTANCE (PED_STREAM_IN_DISTANCE + STREAMER_STREAM_OUT_EXTRA_DISTANCE) +#define PED_MAX_STREAM_DISTANCE_SQ (PED_MAX_STREAM_DISTANCE * PED_MAX_STREAM_DISTANCE) -#define VEHICLE_MAX_STREAM_DISTANCE ( VEHICLE_STREAM_IN_DISTANCE + STREAMER_STREAM_OUT_EXTRA_DISTANCE ) -#define VEHICLE_MAX_STREAM_DISTANCE_SQ ( VEHICLE_MAX_STREAM_DISTANCE * VEHICLE_MAX_STREAM_DISTANCE ) +#define VEHICLE_MAX_STREAM_DISTANCE (VEHICLE_STREAM_IN_DISTANCE + STREAMER_STREAM_OUT_EXTRA_DISTANCE) +#define VEHICLE_MAX_STREAM_DISTANCE_SQ (VEHICLE_MAX_STREAM_DISTANCE * VEHICLE_MAX_STREAM_DISTANCE) -#define PED_MAX_VELOCITY (10) -#define VEHICLE_MAX_VELOCITY (10) +#define PED_MAX_VELOCITY (10) +#define VEHICLE_MAX_VELOCITY (10) /////////////////////////////////////////////////////////////// // diff --git a/Client/mods/deathmatch/logic/CClientModelManager.cpp b/Client/mods/deathmatch/logic/CClientModelManager.cpp index b35e5f3a70d..f1e1b2656fe 100644 --- a/Client/mods/deathmatch/logic/CClientModelManager.cpp +++ b/Client/mods/deathmatch/logic/CClientModelManager.cpp @@ -92,10 +92,10 @@ bool CClientModelManager::TryAdd(const std::shared_ptr& pModel) bool CClientModelManager::Remove(const std::shared_ptr& pModel) { int modelId = pModel->GetModelID(); - + if (modelId < 0 || modelId >= static_cast(g_pGame->GetBaseIDforCOL())) return false; - + std::shared_ptr model; { std::lock_guard lock(m_idMutex); @@ -172,7 +172,7 @@ int CClientModelManager::GetFreeTxdModelID() return static_cast(MAX_MODEL_DFF_ID + usTxdId); } -std::shared_ptr CClientModelManager::FindModelByID(int iModelID) +std::shared_ptr CClientModelManager::FindModelByID(int iModelID) { int32_t iMaxModelId = g_pGame->GetBaseIDforCOL(); diff --git a/Client/mods/deathmatch/logic/CClientModelManager.h b/Client/mods/deathmatch/logic/CClientModelManager.h index 4e1c7d31a27..2bcb47edc4c 100644 --- a/Client/mods/deathmatch/logic/CClientModelManager.h +++ b/Client/mods/deathmatch/logic/CClientModelManager.h @@ -37,9 +37,9 @@ class CClientModelManager bool TryAdd(const std::shared_ptr& pModel); bool Remove(const std::shared_ptr& pModel); - int GetFirstFreeModelID(void); + int GetFirstFreeModelID(void); void ReleaseModelID(int iModelID); - int GetFreeTxdModelID(); + int GetFreeTxdModelID(); std::shared_ptr FindModelByID(int iModelID); std::shared_ptr Request(CClientManager* pManager, int iModelID, eClientModelType eType); diff --git a/Client/mods/deathmatch/logic/CClientObject.cpp b/Client/mods/deathmatch/logic/CClientObject.cpp index 8137a191a2e..06ad4c862d3 100644 --- a/Client/mods/deathmatch/logic/CClientObject.cpp +++ b/Client/mods/deathmatch/logic/CClientObject.cpp @@ -14,7 +14,7 @@ #define CCLIENTOBJECT_MAX 250 #ifndef M_PI -#define M_PI 3.14159265358979323846 + #define M_PI 3.14159265358979323846 #endif CClientObject::CClientObject(CClientManager* pManager, ElementID ID, unsigned short usModel, bool bLowLod) @@ -136,7 +136,7 @@ void CClientObject::GetRotationDegrees(CVector& vecRotation) const void CClientObject::GetRotationRadians(CVector& vecRotation) const { - if (m_pObject && m_pAttachedToEntity) // Temp fix for static objects-> + if (m_pObject && m_pAttachedToEntity) // Temp fix for static objects-> { // We've been returning the rotation that got set last so far (::m_vecRotation).. // but we need to get the real rotation for when the game moves the objects.. @@ -526,9 +526,9 @@ void CClientObject::Create() // Apply our data to the object m_pObject->Teleport(m_vecPosition.fX, m_vecPosition.fY, m_vecPosition.fZ); m_pObject->SetOrientation(m_vecRotation.fX, m_vecRotation.fY, m_vecRotation.fZ); - #ifndef MTA_BUILDINGS +#ifndef MTA_BUILDINGS m_pObject->ProcessCollision(); - #endif +#endif m_pObject->SetupLighting(); m_pObject->SetFrozen(m_bIsFrozen); diff --git a/Client/mods/deathmatch/logic/CClientObject.h b/Client/mods/deathmatch/logic/CClientObject.h index 03b37fbfbcc..dce385eb6a1 100644 --- a/Client/mods/deathmatch/logic/CClientObject.h +++ b/Client/mods/deathmatch/logic/CClientObject.h @@ -161,10 +161,10 @@ class CClientObject : public CClientStreamElement CVector m_vecMoveSpeed; CVector m_vecTurnSpeed; - const bool m_bIsLowLod; // true if this object is low LOD - CClientObject* m_pLowLodObject; // Pointer to low LOD version of this object - std::vector m_HighLodObjectList; // List of objects that use this object as a low LOD version - bool m_IsHiddenLowLod; // true if this object is low LOD and should not be drawn + const bool m_bIsLowLod; // true if this object is low LOD + CClientObject* m_pLowLodObject; // Pointer to low LOD version of this object + std::vector m_HighLodObjectList; // List of objects that use this object as a low LOD version + bool m_IsHiddenLowLod; // true if this object is low LOD and should not be drawn std::shared_ptr m_clientModel; public: diff --git a/Client/mods/deathmatch/logic/CClientObjectManager.cpp b/Client/mods/deathmatch/logic/CClientObjectManager.cpp index c59483b4db2..8c7ec0036cf 100644 --- a/Client/mods/deathmatch/logic/CClientObjectManager.cpp +++ b/Client/mods/deathmatch/logic/CClientObjectManager.cpp @@ -272,8 +272,7 @@ bool CClientObjectManager::IsHardObjectLimitReached() "CClientObjectManager reached limit -" " ENTRY_INFO_NODES:%d/%d" " POINTER_DOUBLE_LINKS:%d/%d", - m_iEntryInfoNodeEntries, MAX_ENTRY_INFO_NODES_MTA, - m_iPointerNodeDoubleLinkEntries, MAX_POINTER_DOUBLE_LINKS_MTA); + m_iEntryInfoNodeEntries, MAX_ENTRY_INFO_NODES_MTA, m_iPointerNodeDoubleLinkEntries, MAX_POINTER_DOUBLE_LINKS_MTA); g_pCore->GetConsole()->Echo(strMessage); AddReportLog(7430, strMessage); } diff --git a/Client/mods/deathmatch/logic/CClientPad.cpp b/Client/mods/deathmatch/logic/CClientPad.cpp index 5f5b45f0204..d87e0c8130f 100644 --- a/Client/mods/deathmatch/logic/CClientPad.cpp +++ b/Client/mods/deathmatch/logic/CClientPad.cpp @@ -227,7 +227,7 @@ void CClientPad::DoPulse(CClientPed* pPed) { if (!bInVehicle) { - cs.ButtonCircle = (m_fStates[0]) ? 255 : 0; // Fire + cs.ButtonCircle = (m_fStates[0]) ? 255 : 0; // Fire cs.LeftStickY = (short)(((m_fStates[3] && m_fStates[4]) || (!m_fStates[3] && !m_fStates[4])) ? 0 : (m_fStates[3]) ? m_fStates[3] * -128 @@ -237,27 +237,27 @@ void CClientPad::DoPulse(CClientPed* pPed) : (m_fStates[5]) ? m_fStates[5] * -128 : m_fStates[6] * 128); - cs.ButtonTriangle = (m_fStates[9]) ? 255 : 0; // Get in/out and alternative fighting styles + cs.ButtonTriangle = (m_fStates[9]) ? 255 : 0; // Get in/out and alternative fighting styles - cs.ButtonSquare = (m_fStates[11]) ? 255 : 0; // Jump + cs.ButtonSquare = (m_fStates[11]) ? 255 : 0; // Jump - cs.ButtonCross = (m_fStates[12]) ? 255 : 0; // Sprint + cs.ButtonCross = (m_fStates[12]) ? 255 : 0; // Sprint - cs.ShockButtonR = (m_fStates[13]) ? 255 : 0; // Look Behind + cs.ShockButtonR = (m_fStates[13]) ? 255 : 0; // Look Behind - cs.ShockButtonL = (m_fStates[14]) ? 255 : 0; // Crouch + cs.ShockButtonL = (m_fStates[14]) ? 255 : 0; // Crouch - cs.LeftShoulder1 = (m_fStates[15]) ? 255 : 0; // Action + cs.LeftShoulder1 = (m_fStates[15]) ? 255 : 0; // Action - cs.m_bPedWalk = (m_fStates[16]) ? 255 : 0; // Walk + cs.m_bPedWalk = (m_fStates[16]) ? 255 : 0; // Walk - cs.RightShoulder1 = (m_fStates[39]) ? 255 : 0; // Aim Weapon + cs.RightShoulder1 = (m_fStates[39]) ? 255 : 0; // Aim Weapon } else { - cs.ButtonCircle = (m_fStates[17]) ? 255 : 0; // Fire + cs.ButtonCircle = (m_fStates[17]) ? 255 : 0; // Fire - cs.LeftShoulder1 = (m_fStates[18]) ? 255 : 0; // Secondary Fire + cs.LeftShoulder1 = (m_fStates[18]) ? 255 : 0; // Secondary Fire cs.LeftStickX = (short)(((m_fStates[19] && m_fStates[20]) || (!m_fStates[19] && !m_fStates[20])) ? 0 : (m_fStates[19]) ? m_fStates[19] * -128 : m_fStates[20] * 128); @@ -266,17 +266,17 @@ void CClientPad::DoPulse(CClientPed* pPed) : (m_fStates[21]) ? m_fStates[21] * -128 : m_fStates[22] * 128); - cs.ButtonCross = (short)((m_fStates[23] * 255)); // Accelerate + cs.ButtonCross = (short)((m_fStates[23] * 255)); // Accelerate - cs.ButtonSquare = (short)((m_fStates[24] * 255)); // Reverse + cs.ButtonSquare = (short)((m_fStates[24] * 255)); // Reverse - cs.ShockButtonL = (m_fStates[28]) ? 255 : 0; // Horn + cs.ShockButtonL = (m_fStates[28]) ? 255 : 0; // Horn - cs.RightShoulder1 = (m_fStates[30]) ? 255 : 0; // Handbrake + cs.RightShoulder1 = (m_fStates[30]) ? 255 : 0; // Handbrake - cs.LeftShoulder2 = (m_fStates[31] || m_fStates[33]) ? 255 : 0; // Look Left + cs.LeftShoulder2 = (m_fStates[31] || m_fStates[33]) ? 255 : 0; // Look Left - cs.RightShoulder2 = (m_fStates[32] || m_fStates[33]) ? 255 : 0; // Look Right + cs.RightShoulder2 = (m_fStates[32] || m_fStates[33]) ? 255 : 0; // Look Right cs.RightStickX = (short)(((m_fStates[35] && m_fStates[36]) || (!m_fStates[35] && !m_fStates[36])) ? 0 : (m_fStates[35]) ? m_fStates[35] * 128 @@ -303,69 +303,69 @@ bool CClientPad::GetControlState(const char* szName, CControllerState& State, bo { case 0: return State.ButtonCircle == 255; - break; // fire + break; // fire case 1: return State.RightShoulder2 == 255; - break; // next wep + break; // next wep case 2: return State.LeftShoulder2 == 255; - break; // previous wep + break; // previous wep case 3: return State.LeftStickY == -128; - break; // forwards + break; // forwards case 4: return State.LeftStickY == 128; - break; // backwards + break; // backwards case 5: return State.LeftStickX == -128; - break; // left + break; // left case 6: return State.LeftStickX == 128; - break; // right + break; // right case 7: return State.LeftShoulder2 == 255; - break; // zoom in + break; // zoom in case 8: return State.RightShoulder2 == 255; - break; // zoom out + break; // zoom out case 9: - return State.ButtonTriangle == 255; // enter_exit + return State.ButtonTriangle == 255; // enter_exit case 10: - return State.Select == 255; // change_cam + return State.Select == 255; // change_cam case 11: return State.ButtonSquare == 255; - break; // jump + break; // jump case 12: return State.ButtonCross == 255; - break; // sprint + break; // sprint case 13: return State.ShockButtonR == 255; - break; // look behind + break; // look behind case 14: return State.ShockButtonL == 255; - break; // crouch + break; // crouch case 15: return State.LeftShoulder1 == 255; - break; // action + break; // action case 16: return State.m_bPedWalk > 0; - break; // walk + break; // walk // vehicle keys case 39: return State.RightShoulder1 == 255; - break; // aim + break; // aim case 40: return State.DPadRight == 255; - break; // conv yes + break; // conv yes case 41: return State.DPadLeft == 255; - break; // conv no + break; // conv no case 42: return State.DPadUp == 255; - break; // group forward + break; // group forward case 43: return State.DPadDown == 255; - break; // group backward + break; // group backward default: break; } @@ -376,69 +376,69 @@ bool CClientPad::GetControlState(const char* szName, CControllerState& State, bo { case 17: return State.ButtonCircle == 255; - break; // fire + break; // fire case 18: return State.LeftShoulder1 == 255; - break; // secondary fire + break; // secondary fire case 19: return State.LeftStickX == -128; - break; // left + break; // left case 20: return State.LeftStickX == 128; - break; // right + break; // right case 21: return State.LeftStickY == -128; - break; // forward + break; // forward case 22: return State.LeftStickY == 128; - break; // backward + break; // backward case 23: return State.ButtonCross == 255; - break; // accel + break; // accel case 24: return State.ButtonSquare == 255; - break; // reverse + break; // reverse case 25: return State.DPadUp == 255; - break; // radio next + break; // radio next case 26: return State.DPadDown == 255; - break; // radio prev + break; // radio prev case 27: return State.m_bRadioTrackSkip == 255; - break; // track skip + break; // track skip case 28: return State.ShockButtonL == 255; - break; // horn + break; // horn case 29: return State.ShockButtonR == 255; - break; // sub-mission + break; // sub-mission case 30: return State.RightShoulder1 == 255; - break; // handbrake + break; // handbrake case 31: return State.LeftShoulder2 == 255; - break; // look left + break; // look left case 32: return State.RightShoulder2 == 255; - break; // look right + break; // look right case 33: - return State.LeftShoulder2 == 255 && State.RightShoulder2 == 255; // look behind + return State.LeftShoulder2 == 255 && State.RightShoulder2 == 255; // look behind case 34: return false; - break; // mouse look + break; // mouse look case 35: return State.RightStickX == 128; - break; // control left + break; // control left case 36: return State.RightStickX == -128; - break; // control right + break; // control right case 37: return State.RightStickY == 128; - break; // control down + break; // control down case 38: return State.RightStickY == -128; - break; // control up + break; // control up default: break; } @@ -483,46 +483,46 @@ bool CClientPad::GetAnalogControlState(const char* szName, CControllerState& cs, { case 0: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Left + return true; // Left case 1: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Right + return true; // Right case 2: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Up + return true; // Up case 3: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Down + return true; // Down case 4: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Left + return true; // Left case 5: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Right + return true; // Right case 6: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Up + return true; // Up case 7: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Down + return true; // Down case 8: fState = m_sScriptedStates[uiIndex] / 255.0f; - return true; // Accel + return true; // Accel case 9: fState = m_sScriptedStates[uiIndex] / 255.0f; - return true; // Reverse + return true; // Reverse case 10: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Special Left + return true; // Special Left case 11: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Special Right + return true; // Special Right case 12: fState = m_sScriptedStates[uiIndex] / -128.0f; - return true; // Special Up + return true; // Special Up case 13: fState = m_sScriptedStates[uiIndex] / 128.0f; - return true; // Special Down + return true; // Special Down default: return false; } @@ -533,16 +533,16 @@ bool CClientPad::GetAnalogControlState(const char* szName, CControllerState& cs, { case 0: fState = cs.LeftStickX < 0 ? cs.LeftStickX / -128.0f : 0; - return true; // Left + return true; // Left case 1: fState = cs.LeftStickX > 0 ? cs.LeftStickX / 128.0f : 0; - return true; // Right + return true; // Right case 2: fState = cs.LeftStickY < 0 ? cs.LeftStickY / -128.0f : 0; - return true; // Up + return true; // Up case 3: fState = cs.LeftStickY > 0 ? cs.LeftStickY / 128.0f : 0; - return true; // Down + return true; // Down default: fState = 0; return true; @@ -554,34 +554,34 @@ bool CClientPad::GetAnalogControlState(const char* szName, CControllerState& cs, { case 4: fState = cs.LeftStickX < 0 ? cs.LeftStickX / -128.0f : 0; - return true; // Left + return true; // Left case 5: fState = cs.LeftStickX > 0 ? cs.LeftStickX / 128.0f : 0; - return true; // Right + return true; // Right case 6: fState = cs.LeftStickY < 0 ? cs.LeftStickY / -128.0f : 0; - return true; // Up + return true; // Up case 7: fState = cs.LeftStickY > 0 ? cs.LeftStickY / 128.0f : 0; - return true; // Down + return true; // Down case 8: fState = cs.ButtonCross > 0 ? cs.ButtonCross / 255.0f : 0; - return true; // Accel + return true; // Accel case 9: fState = cs.ButtonSquare > 0 ? cs.ButtonSquare / 255.0f : 0; - return true; // Reverse + return true; // Reverse case 10: fState = cs.RightStickX < 0 ? cs.RightStickX / -128.0f : 0; - return true; // Special Left + return true; // Special Left case 11: fState = cs.RightStickX > 0 ? cs.RightStickX / 128.0f : 0; - return true; // Special Right + return true; // Special Right case 12: fState = cs.RightStickY < 0 ? cs.RightStickY / -128.0f : 0; - return true; // Special Up + return true; // Special Up case 13: fState = cs.RightStickY > 0 ? cs.RightStickY / 128.0f : 0; - return true; // Special Down + return true; // Special Down default: fState = 0; return true; @@ -606,81 +606,81 @@ bool CClientPad::SetAnalogControlState(const char* szName, float fState, bool bF m_sScriptedStates[1] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[1] = false; - return true; // Left + return true; // Left case 1: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[0] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[0] = false; - return true; // Right + return true; // Right case 2: m_sScriptedStates[uiIndex] = (short)(fState * -128.0f); m_sScriptedStates[3] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[3] = false; - return true; // Up + return true; // Up case 3: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[2] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[2] = false; - return true; // Down + return true; // Down case 4: m_sScriptedStates[uiIndex] = (short)(fState * -128.0f); m_sScriptedStates[5] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[5] = false; - return true; // Vehicle Left + return true; // Vehicle Left case 5: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[4] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[4] = false; - return true; // Vehicle Right + return true; // Vehicle Right case 6: m_sScriptedStates[uiIndex] = (short)(fState * -128.0f); m_sScriptedStates[7] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[7] = false; - return true; // Up + return true; // Up case 7: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[6] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[6] = false; - return true; // Down + return true; // Down case 8: m_sScriptedStates[uiIndex] = (short)(fState * 255.0f); m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; - return true; // Accel + return true; // Accel case 9: m_sScriptedStates[uiIndex] = (short)(fState * 255.0f); m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; - return true; // Reverse + return true; // Reverse case 10: m_sScriptedStates[uiIndex] = (short)(fState * -128.0f); m_sScriptedStates[11] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[11] = false; - return true; // Special Left + return true; // Special Left case 11: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[10] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[10] = false; - return true; // Special Right + return true; // Special Right case 12: m_sScriptedStates[uiIndex] = (short)(fState * -128.0f); m_sScriptedStates[13] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[13] = false; - return true; // Special Up + return true; // Special Up case 13: m_sScriptedStates[uiIndex] = (short)(fState * 128.0f); m_sScriptedStates[12] = 0; m_bScriptedStatesNextFrameOverride[uiIndex] = bFrameForced; m_bScriptedStatesNextFrameOverride[12] = false; - return true; // Special Down + return true; // Special Down default: return false; } @@ -704,37 +704,37 @@ void CClientPad::ProcessSetAnalogControlState(CControllerState& cs, bool bOnFoot { unsigned int uiIndex = 0; - ProcessControl(cs.LeftStickX, uiIndex); // Left + ProcessControl(cs.LeftStickX, uiIndex); // Left uiIndex++; - ProcessControl(cs.LeftStickX, uiIndex); // Right + ProcessControl(cs.LeftStickX, uiIndex); // Right uiIndex++; - ProcessControl(cs.LeftStickY, uiIndex); // Up + ProcessControl(cs.LeftStickY, uiIndex); // Up uiIndex++; - ProcessControl(cs.LeftStickY, uiIndex); // Down + ProcessControl(cs.LeftStickY, uiIndex); // Down } else { unsigned int uiIndex = 4; - ProcessControl(cs.LeftStickX, uiIndex); // Left + ProcessControl(cs.LeftStickX, uiIndex); // Left uiIndex++; - ProcessControl(cs.LeftStickX, uiIndex); // Right + ProcessControl(cs.LeftStickX, uiIndex); // Right uiIndex++; - ProcessControl(cs.LeftStickY, uiIndex); // Up + ProcessControl(cs.LeftStickY, uiIndex); // Up uiIndex++; - ProcessControl(cs.LeftStickY, uiIndex); // Down + ProcessControl(cs.LeftStickY, uiIndex); // Down uiIndex++; - ProcessControl(cs.ButtonCross, uiIndex); // Accel + ProcessControl(cs.ButtonCross, uiIndex); // Accel uiIndex++; - ProcessControl(cs.ButtonSquare, uiIndex); // Brake + ProcessControl(cs.ButtonSquare, uiIndex); // Brake uiIndex++; - ProcessControl(cs.RightStickX, uiIndex); // Special Left + ProcessControl(cs.RightStickX, uiIndex); // Special Left uiIndex++; - ProcessControl(cs.RightStickX, uiIndex); // Special Right + ProcessControl(cs.RightStickX, uiIndex); // Special Right uiIndex++; - ProcessControl(cs.RightStickY, uiIndex); // Special Up + ProcessControl(cs.RightStickY, uiIndex); // Special Up uiIndex++; - ProcessControl(cs.RightStickY, uiIndex); // Special Down + ProcessControl(cs.RightStickY, uiIndex); // Special Down } } @@ -802,7 +802,7 @@ void CClientPad::ProcessAllToggledControls(CControllerState& cs, bool bOnFoot) // Clear pad data for a disabled control. Returns true if control was actually disabled. bool CClientPad::ProcessToggledControl(const char* szName, CControllerState& cs, bool bOnFoot, bool bEnabled) { - if (bEnabled) // We don't need to disable anything if it the control is enabled. + if (bEnabled) // We don't need to disable anything if it the control is enabled. return false; unsigned int uiIndex; @@ -814,16 +814,16 @@ bool CClientPad::ProcessToggledControl(const char* szName, CControllerState& cs, { case 0: cs.LeftStickX = (cs.LeftStickX < 0) ? 0 : cs.LeftStickX; - return true; // Left + return true; // Left case 1: cs.LeftStickX = (cs.LeftStickX > 0) ? 0 : cs.LeftStickX; - return true; // Right + return true; // Right case 2: cs.LeftStickY = (cs.LeftStickY < 0) ? 0 : cs.LeftStickY; - return true; // Up + return true; // Up case 3: cs.LeftStickY = (cs.LeftStickY > 0) ? 0 : cs.LeftStickY; - return true; // Down + return true; // Down default: return false; } @@ -834,34 +834,34 @@ bool CClientPad::ProcessToggledControl(const char* szName, CControllerState& cs, { case 4: cs.LeftStickX = (cs.LeftStickX < 0) ? 0 : cs.LeftStickX; - return true; // Left + return true; // Left case 5: cs.LeftStickX = (cs.LeftStickX > 0) ? 0 : cs.LeftStickX; - return true; // Right + return true; // Right case 6: cs.LeftStickY = (cs.LeftStickY < 0) ? 0 : cs.LeftStickY; - return true; // Up + return true; // Up case 7: cs.LeftStickY = (cs.LeftStickY > 0) ? 0 : cs.LeftStickY; - return true; // Down + return true; // Down case 8: cs.ButtonCross = 0; - return true; // Accel + return true; // Accel case 9: cs.ButtonSquare = 0; - return true; // Reverse + return true; // Reverse case 10: cs.RightStickX = (cs.RightStickX < 0) ? 0 : cs.RightStickX; - return true; // Special Left + return true; // Special Left case 11: cs.RightStickX = (cs.RightStickX > 0) ? 0 : cs.RightStickX; - return true; // Special Right + return true; // Special Right case 12: cs.RightStickY = (cs.RightStickY < 0) ? 0 : cs.RightStickY; - return true; // Special Up + return true; // Special Up case 13: cs.RightStickY = (cs.RightStickY > 0) ? 0 : cs.RightStickY; - return true; // Special Down + return true; // Special Down default: return false; } diff --git a/Client/mods/deathmatch/logic/CClientPad.h b/Client/mods/deathmatch/logic/CClientPad.h index 348fe5a29be..af18331d077 100644 --- a/Client/mods/deathmatch/logic/CClientPad.h +++ b/Client/mods/deathmatch/logic/CClientPad.h @@ -10,7 +10,7 @@ #pragma once -#define MAX_GTA_CONTROLS 44 +#define MAX_GTA_CONTROLS 44 #define MAX_GTA_ANALOG_CONTROLS 14 class CClientPed; diff --git a/Client/mods/deathmatch/logic/CClientPed.cpp b/Client/mods/deathmatch/logic/CClientPed.cpp index da5f34282fa..ab48ed872f0 100644 --- a/Client/mods/deathmatch/logic/CClientPed.cpp +++ b/Client/mods/deathmatch/logic/CClientPed.cpp @@ -45,8 +45,8 @@ extern CClientGame* g_pClientGame; #define INVALID_VALUE 0xFFFFFFFF -#define PED_INTERPOLATION_WARP_THRESHOLD 5 // Minimal threshold -#define PED_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED 5 // Units to increment the threshold per speed unit +#define PED_INTERPOLATION_WARP_THRESHOLD 5 // Minimal threshold +#define PED_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED 5 // Units to increment the threshold per speed unit enum eAnimGroups { @@ -134,7 +134,7 @@ void CClientPed::Init(CClientManager* pManager, unsigned long ulModelID, bool bI m_armorLocked = false; m_ulLastOnScreenTime = 0; m_pLoadedModelInfo = NULL; - m_pOutOfVehicleWeaponSlot = WEAPONSLOT_MAX; // WEAPONSLOT_MAX = invalid + m_pOutOfVehicleWeaponSlot = WEAPONSLOT_MAX; // WEAPONSLOT_MAX = invalid m_bRadioOn = false; m_ucRadioChannel = 1; m_fBeginAimX = 0.0f; @@ -166,7 +166,7 @@ void CClientPed::Init(CClientManager* pManager, unsigned long ulModelID, bool bI m_fMoveSpeed = 0.0f; m_bCanBeKnockedOffBike = true; m_bBleeding = false; - RemoveAllWeapons(); // Set all our weapon values to unarmed + RemoveAllWeapons(); // Set all our weapon values to unarmed m_bHasJetPack = false; m_FightingStyle = STYLE_GRAB_KICK; m_MoveAnim = MOVE_DEFAULT; @@ -177,8 +177,8 @@ void CClientPed::Init(CClientManager* pManager, unsigned long ulModelID, bool bI m_ulLastTimeBeganAiming = 0; m_ulLastTimeEndedAiming = 0; m_ulLastTimeBeganCrouch = 0; - m_ulLastTimeBeganStand = 0; // Standing after crouching - m_ulLastTimeMovedWhileCrouched = 0; // Moved while crouching + m_ulLastTimeBeganStand = 0; // Standing after crouching + m_ulLastTimeMovedWhileCrouched = 0; // Moved while crouching m_bRecreatingModel = false; m_pCurrentContactEntity = NULL; m_bSunbathing = false; @@ -279,7 +279,7 @@ void CClientPed::Init(CClientManager* pManager, unsigned long ulModelID, bool bI m_stats = m_remoteDataStorage->Stats(); // ### remember if you want to set Int flags, subtract STATS_OFFSET from the enum ID ### - SetStat(MAX_HEALTH, 569.0f); // Default max_health stat + SetStat(MAX_HEALTH, 569.0f); // Default max_health stat SetArmor(0.0f); } @@ -673,7 +673,7 @@ void CClientPed::SetRotationDegrees(const CVector& vecRotation) // HACK: set again the z rotation to work on ground SetCurrentRotation(vecTemp.fZ); if (!IS_PLAYER(this)) - SetCameraRotation(vecTemp.fZ); // This is incorrect and kept for backward compatibility + SetCameraRotation(vecTemp.fZ); // This is incorrect and kept for backward compatibility } void CClientPed::SetRotationRadians(const CVector& vecRotation) @@ -682,7 +682,7 @@ void CClientPed::SetRotationRadians(const CVector& vecRotation) CMatrix matTemp; GetMatrix(matTemp); g_pMultiplayer->ConvertEulerAnglesToMatrix(matTemp, vecRotation.fX, vecRotation.fY, - vecRotation.fZ); // This is incorrect and kept for backward compatibility + vecRotation.fZ); // This is incorrect and kept for backward compatibility SetMatrix(matTemp); } @@ -2421,7 +2421,7 @@ eMovementState CClientPed::GetMovementState() const char* szSimpleTaskName = GetTaskManager()->GetSimplestActiveTask()->GetTaskName(); // Check tasks - if (strcmp(szSimpleTaskName, "TASK_SIMPLE_CLIMB") == 0) // Is he climbing? + if (strcmp(szSimpleTaskName, "TASK_SIMPLE_CLIMB") == 0) // Is he climbing? { CTaskSimpleClimb* climbingTask = dynamic_cast(GetTaskManager()->GetSimplestActiveTask()); if (climbingTask && climbingTask->GetHeightForPos() == eClimbHeights::CLIMB_GRAB) @@ -2429,13 +2429,13 @@ eMovementState CClientPed::GetMovementState() return MOVEMENTSTATE_CLIMB; } - else if (strcmp(szComplexTaskName, "TASK_COMPLEX_JUMP") == 0) // Is he jumping? + else if (strcmp(szComplexTaskName, "TASK_COMPLEX_JUMP") == 0) // Is he jumping? return MOVEMENTSTATE_JUMP; - else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_GO_TO_POINT") == 0) // Entering vehicle (walking to the doors)? + else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_GO_TO_POINT") == 0) // Entering vehicle (walking to the doors)? return MOVEMENTSTATE_WALK_TO_POINT; - else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_SWIM") == 0) // Is he swimming? + else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_SWIM") == 0) // Is he swimming? return MOVEMENTSTATE_SWIM; - else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_JETPACK") == 0) // Is he flying? + else if (strcmp(szSimpleTaskName, "TASK_SIMPLE_JETPACK") == 0) // Is he flying? { if (cs.ButtonCross != 0) return MOVEMENTSTATE_ASCENT_JETPACK; @@ -2446,7 +2446,8 @@ eMovementState CClientPed::GetMovementState() } // Check movement state - if (!IsOnGround() && !GetContactEntity() && !m_pPlayerPed->IsStandingOnEntity() && !m_pPlayerPed->IsInWater() && (strcmp(szSimpleTaskName, "TASK_SIMPLE_IN_AIR") == 0 || strcmp(szSimpleTaskName, "TASK_SIMPLE_FALL") == 0)) // Is he falling? + if (!IsOnGround() && !GetContactEntity() && !m_pPlayerPed->IsStandingOnEntity() && !m_pPlayerPed->IsInWater() && + (strcmp(szSimpleTaskName, "TASK_SIMPLE_IN_AIR") == 0 || strcmp(szSimpleTaskName, "TASK_SIMPLE_FALL") == 0)) // Is he falling? return MOVEMENTSTATE_FALL; // Sometimes it returns 'fall' or 'walk', so it's better to return false instead @@ -2470,7 +2471,8 @@ eMovementState CClientPed::GetMovementState() case PedMoveState::PEDMOVE_SPRINT: return MOVEMENTSTATE_SPRINT; case PedMoveState::PEDMOVE_RUN: - return walking ? MOVEMENTSTATE_WALK : MOVEMENTSTATE_JOG; // FileEX: It should be MOVEMENTSTATE_RUN, but we're keeping JOG for backward compatibility (PEDMOVE_JOG is unused in SA) + return walking ? MOVEMENTSTATE_WALK : MOVEMENTSTATE_JOG; // FileEX: It should be MOVEMENTSTATE_RUN, but we're keeping JOG for backward + // compatibility (PEDMOVE_JOG is unused in SA) } } else @@ -3126,7 +3128,7 @@ void CClientPed::ApplyControllerStateFixes(CControllerState& Current) { // Disable double crouching (another anim cut) if (g_pClientGame->IsUsingAlternatePulseOrder()) - Current.ShockButtonL = 255; // Do this differently if we have changed the pulse order + Current.ShockButtonL = 255; // Do this differently if we have changed the pulse order else Current.ShockButtonL = 0; } @@ -3238,7 +3240,7 @@ void CClientPed::ApplyControllerStateFixes(CControllerState& Current) CTask* pTask = m_pTaskManager->GetSimplestActiveTask(); if ((pTask && pTask->GetTaskType() == TASK_SIMPLE_PLAYER_ON_FOOT) && (GetWeapon()->GetSlot() == WEAPONSLOT_TYPE_UNARMED) && (Current.RightShoulder1 != 0) && (Current.ButtonSquare != 0) && (Current.ButtonCross != 0)) - { // We are block jogging + { // We are block jogging if (Current.LeftStickY > 0) // We're pressing target+jump+sprint+backwards. Using the backwards key in this situation is prone to bugs, swap it with forwards Current.LeftStickY = -Current.LeftStickY; @@ -3326,7 +3328,7 @@ float CClientPed::GetCurrentRotation() CVector vecRotation = m_matFrozen.GetRotation(); return vecRotation.fZ; } - + if (m_pPlayerPed) { return m_pPlayerPed->GetCurrentRotation(); @@ -4497,7 +4499,8 @@ void CClientPed::_GetIntoVehicle(CClientVehicle* pVehicle, unsigned int uiSeat, pTask = m_pTaskManager->GetTask(TASK_PRIORITY_EVENT_RESPONSE_NONTEMP); auto usVehicleModel = static_cast(pVehicle->GetModel()); if (((pTask && pTask->GetTaskType() == TASK_COMPLEX_IN_WATER) || pVehicle->IsOnWater()) && - (usVehicleModel == VehicleType::VT_SKIMMER || usVehicleModel == VehicleType::VT_SEASPAR || usVehicleModel == VehicleType::VT_LEVIATHN || usVehicleModel == VehicleType::VT_VORTEX)) + (usVehicleModel == VehicleType::VT_SKIMMER || usVehicleModel == VehicleType::VT_SEASPAR || usVehicleModel == VehicleType::VT_LEVIATHN || + usVehicleModel == VehicleType::VT_VORTEX)) { CVector vecDoorPos; unsigned int uiDoor; @@ -4775,7 +4778,7 @@ bool CClientPed::GetShotData(CVector* pvecOrigin, CVector* pvecTarget, CVector* float fRotation = GetCurrentRotation(); // Grab the target range of the current weapon - float fSkill = 1000.0f; // GetStat ( g_pGame->GetStats ( )->GetSkillStatIndex ( pWeapon->GetType ( ) ) ); + float fSkill = 1000.0f; // GetStat ( g_pGame->GetStats ( )->GetSkillStatIndex ( pWeapon->GetType ( ) ) ); CWeaponStat* pCurrentWeaponInfo = g_pGame->GetWeaponStatManager()->GetWeaponStatsFromSkillLevel(pWeapon->GetType(), fSkill); float fRange = pCurrentWeaponInfo->GetWeaponRange(); @@ -4809,19 +4812,19 @@ bool CClientPed::GetShotData(CVector* pvecOrigin, CVector* pvecTarget, CVector* // Always use the gun muzzle as origin vecOrigin = vecGunMuzzle; - if (false && HasAkimboPointingUpwards()) // Upwards pointing akimbo's + if (false && HasAkimboPointingUpwards()) // Upwards pointing akimbo's { // Disabled temporarily until we actually get working akimbos vecTarget = vecOrigin; vecTarget.fZ += fRange; } - else if (Controller.RightShoulder1 == 255) // First-person weapons, crosshair active: sync the crosshair + else if (Controller.RightShoulder1 == 255) // First-person weapons, crosshair active: sync the crosshair { g_pGame->GetCamera()->Find3rdPersonCamTargetVector(fRange, &vecGunMuzzle, &vecOrigin, &vecTarget); // Apply shoot through walls fix vecOrigin = AdjustShotOriginForWalls(vecOrigin, vecTarget, 0.5f); } - else if (pVehicle) // Drive-by/vehicle weapons: camera origin as origin, performing collision tests + else if (pVehicle) // Drive-by/vehicle weapons: camera origin as origin, performing collision tests { CColPoint* pCollision; CMatrix mat; @@ -4856,7 +4859,7 @@ bool CClientPed::GetShotData(CVector* pvecOrigin, CVector* pvecTarget, CVector* } } } - else // Always use only the last reported shot data for remote players? + else // Always use only the last reported shot data for remote players? { vecOrigin = m_shotSyncData->m_vecShotOrigin; vecTarget = m_shotSyncData->m_vecShotTarget; @@ -5068,7 +5071,7 @@ bool CClientPed::IsLeavingVehicle() { switch (pTask->GetTaskType()) { - case TASK_COMPLEX_LEAVE_CAR: // We only use this task + case TASK_COMPLEX_LEAVE_CAR: // We only use this task case TASK_COMPLEX_LEAVE_CAR_AND_DIE: case TASK_COMPLEX_LEAVE_CAR_AND_FLEE: case TASK_COMPLEX_LEAVE_CAR_AND_WANDER: @@ -5818,9 +5821,9 @@ void CClientPed::RunNamedAnimation(std::unique_ptr& pBlock, const ch Saml1er: Setting flags to 0x10 will tell GTA:SA that animation needs to be decompressed. If not, animation will either crash or do some weird things. */ - int flags = 0x10; // Stops jaw fucking up, some speaking flag maybe + int flags = 0x10; // Stops jaw fucking up, some speaking flag maybe if (bLoop) - flags |= 0x2; // flag that triggers the loop (Maccer) + flags |= 0x2; // flag that triggers the loop (Maccer) if (bUpdatePosition) { // 0x40 enables position updating on Y-coord, 0x80 on X. (Maccer) @@ -5837,7 +5840,7 @@ void CClientPed::RunNamedAnimation(std::unique_ptr& pBlock, const ch } if (!bFreezeLastFrame) - flags |= 0x08; // flag determines whether to freeze player when anim ends. Really annoying (Maccer) + flags |= 0x08; // flag determines whether to freeze player when anim ends. Really annoying (Maccer) float fBlendDelta = 1 / std::max((float)iBlend, 1.0f) * 1000; CTask* pTask = g_pGame->GetTasks()->CreateTaskSimpleRunNamedAnim(szAnimName, pBlock->GetName(), flags, fBlendDelta, iTime, !bInterruptable, bRunInSequence, bOffsetPed, bHoldLastFrame); @@ -5912,7 +5915,8 @@ void CClientPed::RunAnimationFromCache() std::string animName = m_AnimationCache.strName; // Run our animation - RunNamedAnimation(m_pAnimationBlock, animName.c_str(), m_AnimationCache.iTime, m_AnimationCache.iBlend, m_AnimationCache.bLoop, m_AnimationCache.bUpdatePosition, m_AnimationCache.bInterruptable, m_AnimationCache.bFreezeLastFrame); + RunNamedAnimation(m_pAnimationBlock, animName.c_str(), m_AnimationCache.iTime, m_AnimationCache.iBlend, m_AnimationCache.bLoop, + m_AnimationCache.bUpdatePosition, m_AnimationCache.bInterruptable, m_AnimationCache.bFreezeLastFrame); // Set anim progress & speed m_AnimationCache.progressWaitForStreamIn = true; @@ -5932,7 +5936,7 @@ void CClientPed::UpdateAnimationProgressAndSpeed() float progress = 0.0f; float elapsedTime = static_cast(GetTimestamp() - m_AnimationCache.startTime) / 1000.0f; - if (m_AnimationCache.bFreezeLastFrame) // time and loop is ignored if freezeLastFrame is true + if (m_AnimationCache.bFreezeLastFrame) // time and loop is ignored if freezeLastFrame is true progress = (elapsedTime / animLength) * m_AnimationCache.speed; else { @@ -6166,7 +6170,8 @@ bool CClientPed::ShouldBeStealthAiming() { // We need to be either crouched, walking or standing SBindableGTAControl* pWalkControl = pKeyBinds->GetBindableFromControl("walk"); - if (m_pPlayerPed->GetMoveState() == PedMoveState::PEDMOVE_STILL || m_pPlayerPed->GetMoveState() == PedMoveState::PEDMOVE_WALK || pWalkControl && pWalkControl->bState) + if (m_pPlayerPed->GetMoveState() == PedMoveState::PEDMOVE_STILL || m_pPlayerPed->GetMoveState() == PedMoveState::PEDMOVE_WALK || + pWalkControl && pWalkControl->bState) { // Do we have a target ped? CClientPed* pTargetPed = GetTargetedPed(); @@ -6545,12 +6550,12 @@ bool CClientPed::EnterVehicle(CClientVehicle* pVehicle, bool bPassenger, std::op return false; // Are we already sending an in/out request or not allowed to create a new in/out? - if (m_bNoNewVehicleTask // Are we permitted to even enter a vehicle? - || m_VehicleInOutID != INVALID_ELEMENT_ID // Make sure we're not already processing a vehicle enter (would refer to valid ID if we were) - || m_bIsGettingJacked // Make sure we're not currently getting carjacked && - || m_bIsGettingIntoVehicle // We can't enter a vehicle we're currently entering... - || m_bIsGettingOutOfVehicle // We can't enter a vehicle we're currently leaving... - || CClientTime::GetTime() < m_ulLastVehicleInOutTime + VEHICLE_INOUT_DELAY // We are trying to enter the vehicle to soon + if (m_bNoNewVehicleTask // Are we permitted to even enter a vehicle? + || m_VehicleInOutID != INVALID_ELEMENT_ID // Make sure we're not already processing a vehicle enter (would refer to valid ID if we were) + || m_bIsGettingJacked // Make sure we're not currently getting carjacked && + || m_bIsGettingIntoVehicle // We can't enter a vehicle we're currently entering... + || m_bIsGettingOutOfVehicle // We can't enter a vehicle we're currently leaving... + || CClientTime::GetTime() < m_ulLastVehicleInOutTime + VEHICLE_INOUT_DELAY // We are trying to enter the vehicle to soon ) { return false; @@ -6595,16 +6600,17 @@ bool CClientPed::EnterVehicle(CClientVehicle* pVehicle, bool bPassenger, std::op // Stop if the ped is swimming and the vehicle model cannot be entered from water (fixes #1990) auto vehicleModel = static_cast(pVehicle->GetModel()); - if (IsInWater() && !(vehicleModel == VehicleType::VT_SKIMMER || vehicleModel == VehicleType::VT_SEASPAR || vehicleModel == VehicleType::VT_LEVIATHN || vehicleModel == VehicleType::VT_VORTEX)) + if (IsInWater() && !(vehicleModel == VehicleType::VT_SKIMMER || vehicleModel == VehicleType::VT_SEASPAR || vehicleModel == VehicleType::VT_LEVIATHN || + vehicleModel == VehicleType::VT_VORTEX)) return false; // If the Jump task is playing and we are in water - I know right // Kill the task. CTask* pTask = GetCurrentPrimaryTask(); - if (pTask && pTask->GetTaskType() == TASK_COMPLEX_JUMP) // Kill jump task - breaks warp in entry and doesn't really matter + if (pTask && pTask->GetTaskType() == TASK_COMPLEX_JUMP) // Kill jump task - breaks warp in entry and doesn't really matter { - if (pVehicle->IsInWater() || IsInWater()) // Make sure we are about to warp in (this bug only happens when someone jumps into water with a vehicle) - KillTask(3, true); // Kill jump task if we are about to warp in + if (pVehicle->IsInWater() || IsInWater()) // Make sure we are about to warp in (this bug only happens when someone jumps into water with a vehicle) + KillTask(3, true); // Kill jump task if we are about to warp in } // Make sure we don't have any other primary tasks running, otherwise our 'enter-vehicle' @@ -6612,10 +6618,10 @@ bool CClientPed::EnterVehicle(CClientVehicle* pVehicle, bool bPassenger, std::op if (GetCurrentPrimaryTask()) return false; - if (IsClimbing() // Make sure we're not currently climbing - || HasJetPack() // Make sure we don't have a jetpack - || IsUsingGun() // Make sure we're not using a gun (have the gun task active) - we stop it in UpdatePlayerTasks anyway - || IsRunningAnimation() // Make sure we aren't running an animation + if (IsClimbing() // Make sure we're not currently climbing + || HasJetPack() // Make sure we don't have a jetpack + || IsUsingGun() // Make sure we're not using a gun (have the gun task active) - we stop it in UpdatePlayerTasks anyway + || IsRunningAnimation() // Make sure we aren't running an animation ) { return false; @@ -6661,9 +6667,9 @@ bool CClientPed::EnterVehicle(CClientVehicle* pVehicle, bool bPassenger, std::op // Call the onClientVehicleStartEnter event for the ped // Check if it is cancelled before sending packet CLuaArguments Arguments; - Arguments.PushElement(this); // player / ped - Arguments.PushNumber(uiSeat); // seat - Arguments.PushNumber(uiDoor); // door + Arguments.PushElement(this); // player / ped + Arguments.PushNumber(uiSeat); // seat + Arguments.PushNumber(uiDoor); // door if (!pVehicle->CallEvent("onClientVehicleStartEnter", Arguments, true)) { @@ -6761,12 +6767,12 @@ bool CClientPed::ExitVehicle() } // Are we already sending an in/out request or not allowed to create a new in/out? - if (m_bNoNewVehicleTask // Are we permitted to even enter a vehicle? - || m_VehicleInOutID != INVALID_ELEMENT_ID // Make sure we're not already processing a vehicle enter (would refer to valid ID if we were) - || m_bIsGettingJacked // Make sure we're not currently getting carjacked && - || m_bIsGettingIntoVehicle // We can't enter a vehicle we're currently entering... - || m_bIsGettingOutOfVehicle // We can't enter a vehicle we're currently leaving... - || CClientTime::GetTime() < m_ulLastVehicleInOutTime + VEHICLE_INOUT_DELAY // We are trying to enter the vehicle to soon + if (m_bNoNewVehicleTask // Are we permitted to even enter a vehicle? + || m_VehicleInOutID != INVALID_ELEMENT_ID // Make sure we're not already processing a vehicle enter (would refer to valid ID if we were) + || m_bIsGettingJacked // Make sure we're not currently getting carjacked && + || m_bIsGettingIntoVehicle // We can't enter a vehicle we're currently entering... + || m_bIsGettingOutOfVehicle // We can't enter a vehicle we're currently leaving... + || CClientTime::GetTime() < m_ulLastVehicleInOutTime + VEHICLE_INOUT_DELAY // We are trying to enter the vehicle to soon ) { return false; @@ -6794,11 +6800,11 @@ bool CClientPed::ExitVehicle() // Call the onClientVehicleStartExit event for the ped // Check if it is cancelled before making the ped exit the vehicle CLuaArguments arguments; - arguments.PushElement(this); // player / ped - arguments.PushNumber(m_ucVehicleInOutSeat); // seat - arguments.PushNumber(0); // door + arguments.PushElement(this); // player / ped + arguments.PushNumber(m_ucVehicleInOutSeat); // seat + arguments.PushNumber(0); // door - if (!pOccupiedVehicle->CallEvent("onClientVehicleStartExit", arguments, true)) // Event has been cancelled + if (!pOccupiedVehicle->CallEvent("onClientVehicleStartExit", arguments, true)) // Event has been cancelled return false; // Make ped exit vehicle @@ -6885,8 +6891,8 @@ void CClientPed::UpdateVehicleInOut() // Call the onClientVehicleEnter event for the ped // Check if it is cancelled before allowing the ped to enter the vehicle CLuaArguments arguments; - arguments.PushElement(this); // player / ped - arguments.PushNumber(m_ucVehicleInOutSeat); // seat + arguments.PushElement(this); // player / ped + arguments.PushNumber(m_ucVehicleInOutSeat); // seat if (!vehicle->CallEvent("onClientVehicleEnter", arguments, true)) { @@ -6911,8 +6917,8 @@ void CClientPed::UpdateVehicleInOut() // Call the onClientVehicleExit event for the ped CLuaArguments arguments; - arguments.PushElement(this); // player / ped - arguments.PushNumber(m_ucVehicleInOutSeat); // seat + arguments.PushElement(this); // player / ped + arguments.PushNumber(m_ucVehicleInOutSeat); // seat networkVehicle->CallEvent("onClientVehicleExit", arguments, true); m_bIsGettingOutOfVehicle = false; @@ -7269,4 +7275,3 @@ void CClientPed::RunSwimTask() const inWaterTask->SetAsPedTask(m_pPlayerPed, TASK_PRIORITY_EVENT_RESPONSE_NONTEMP, true); } - \ No newline at end of file diff --git a/Client/mods/deathmatch/logic/CClientPed.h b/Client/mods/deathmatch/logic/CClientPed.h index da46fe8f165..8bab35d9849 100644 --- a/Client/mods/deathmatch/logic/CClientPed.h +++ b/Client/mods/deathmatch/logic/CClientPed.h @@ -68,23 +68,23 @@ enum eBodyPart enum eMovementState { MOVEMENTSTATE_UNKNOWN, - MOVEMENTSTATE_STAND, // Standing still - MOVEMENTSTATE_WALK, // Walking - MOVEMENTSTATE_POWERWALK, // Walking quickly - MOVEMENTSTATE_JOG, // Jogging (Unused) - MOVEMENTSTATE_SPRINT, // Sprinting - MOVEMENTSTATE_CROUCH, // Crouching still - MOVEMENTSTATE_CRAWL, // Crouch-moving - MOVEMENTSTATE_ROLL, // Crouch-rolling - MOVEMENTSTATE_JUMP, // Jumping - MOVEMENTSTATE_FALL, // Falling - MOVEMENTSTATE_CLIMB, // Climbing - MOVEMENTSTATE_SWIM, // Swimming - MOVEMENTSTATE_WALK_TO_POINT, // Entering vehicle (walking to the door) - MOVEMENTSTATE_ASCENT_JETPACK, // Ascending with jetpack - MOVEMENTSTATE_DESCENT_JETPACK, // Descending with jetpack - MOVEMENTSTATE_JETPACK, // Jetpack flying - MOVEMENTSTATE_HANGING, // Hanging from the whall during climbing task + MOVEMENTSTATE_STAND, // Standing still + MOVEMENTSTATE_WALK, // Walking + MOVEMENTSTATE_POWERWALK, // Walking quickly + MOVEMENTSTATE_JOG, // Jogging (Unused) + MOVEMENTSTATE_SPRINT, // Sprinting + MOVEMENTSTATE_CROUCH, // Crouching still + MOVEMENTSTATE_CRAWL, // Crouch-moving + MOVEMENTSTATE_ROLL, // Crouch-rolling + MOVEMENTSTATE_JUMP, // Jumping + MOVEMENTSTATE_FALL, // Falling + MOVEMENTSTATE_CLIMB, // Climbing + MOVEMENTSTATE_SWIM, // Swimming + MOVEMENTSTATE_WALK_TO_POINT, // Entering vehicle (walking to the door) + MOVEMENTSTATE_ASCENT_JETPACK, // Ascending with jetpack + MOVEMENTSTATE_DESCENT_JETPACK, // Descending with jetpack + MOVEMENTSTATE_JETPACK, // Jetpack flying + MOVEMENTSTATE_HANGING, // Hanging from the whall during climbing task }; enum eDeathAnims @@ -153,7 +153,7 @@ struct SAnimationCache class CClientObject; // To hide the ugly "pointer truncation from DWORD* to unsigned long warning -#pragma warning(disable:4311) +#pragma warning(disable : 4311) class CClientPed : public CClientStreamElement, public CAntiCheatModule { @@ -244,12 +244,12 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule bool GetCanBeKnockedOffBike(); void SetCanBeKnockedOffBike(bool bCanBeKnockedOffBike); - bool IsInVehicle() const noexcept { return GetOccupiedVehicle() != NULL; }; + bool IsInVehicle() const noexcept { return GetOccupiedVehicle() != NULL; }; CClientVehicle* GetOccupiedVehicle() noexcept { return m_pOccupiedVehicle; }; const CClientVehicle* GetOccupiedVehicle() const noexcept { return m_pOccupiedVehicle; }; - unsigned int GetOccupiedVehicleSeat() const noexcept { return m_uiOccupiedVehicleSeat; }; + unsigned int GetOccupiedVehicleSeat() const noexcept { return m_uiOccupiedVehicleSeat; }; CClientVehicle* GetOccupyingVehicle() noexcept { return m_pOccupyingVehicle; }; const CClientVehicle* GetOccupyingVehicle() const noexcept { return m_pOccupyingVehicle; }; @@ -410,7 +410,7 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule std::list::iterator ProjectilesEnd() { return m_Projectiles.end(); } unsigned int CountProjectiles(eWeaponType weaponType = WEAPONTYPE_UNARMED); - std::list& GetProjectiles() noexcept { return m_Projectiles; } + std::list& GetProjectiles() noexcept { return m_Projectiles; } const std::list& GetProjectiles() const noexcept { return m_Projectiles; } void RemoveAllProjectiles(); @@ -434,21 +434,21 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule unsigned char GetAlpha() const noexcept { return m_ucAlpha; } void SetAlpha(unsigned char ucAlpha); - bool HasTargetPosition() const noexcept { return m_interp.pos.ulFinishTime != 0; } - CClientEntity* GetTargetOriginSource() noexcept { return m_interp.pTargetOriginSource; } + bool HasTargetPosition() const noexcept { return m_interp.pos.ulFinishTime != 0; } + CClientEntity* GetTargetOriginSource() noexcept { return m_interp.pTargetOriginSource; } const CClientEntity* GetTargetOriginSource() const noexcept { return m_interp.pTargetOriginSource; } - void GetTargetPosition(CVector& vecPosition); - void SetTargetPosition(const CVector& vecPosition, unsigned long ulDelay, CClientEntity* pTargetOriginSource = NULL); - void RemoveTargetPosition(); - void UpdateTargetPosition(); - void UpdateUnderFloorFix(const CVector& vecTargetPosition, const CVector& vecOrigin); + void GetTargetPosition(CVector& vecPosition); + void SetTargetPosition(const CVector& vecPosition, unsigned long ulDelay, CClientEntity* pTargetOriginSource = NULL); + void RemoveTargetPosition(); + void UpdateTargetPosition(); + void UpdateUnderFloorFix(const CVector& vecTargetPosition, const CVector& vecOrigin); CClientEntity* GetTargetedEntity(); CClientPed* GetTargetedPed(); CClientEntity* GetCurrentContactEntity() noexcept { return m_pCurrentContactEntity; } const CClientEntity* GetCurrentContactEntity() const noexcept { return m_pCurrentContactEntity; } - void SetCurrentContactEntity(CClientEntity* pEntity) noexcept { m_pCurrentContactEntity = pEntity; } + void SetCurrentContactEntity(CClientEntity* pEntity) noexcept { m_pCurrentContactEntity = pEntity; } bool IsSunbathing(); void SetSunbathing(bool bSunbathing, bool bStartStanding = true); @@ -525,20 +525,16 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule void DereferenceCustomAnimationBlock() { m_pCustomAnimationIFP = nullptr; } std::shared_ptr GetCustomAnimationIFP() const noexcept { return m_pCustomAnimationIFP; } - bool IsCustomAnimationPlaying() noexcept - { - return (m_bRequestedAnimation || m_AnimationCache.bLoop) - && m_pAnimationBlock && m_bisCurrentAnimationCustom; - } + bool IsCustomAnimationPlaying() noexcept { return (m_bRequestedAnimation || m_AnimationCache.bLoop) && m_pAnimationBlock && m_bisCurrentAnimationCustom; } void SetCustomAnimationUntriggerable() noexcept { m_bRequestedAnimation = false; m_AnimationCache.bLoop = false; } - bool IsNextAnimationCustom() const noexcept { return m_bisNextAnimationCustom; } - void SetNextAnimationCustom(const std::shared_ptr& pIFP, const SString& strAnimationName); - void SetCurrentAnimationCustom(bool bCustom) noexcept { m_bisCurrentAnimationCustom = bCustom; } - bool IsCurrentAnimationCustom() const noexcept { return m_bisCurrentAnimationCustom; } + bool IsNextAnimationCustom() const noexcept { return m_bisNextAnimationCustom; } + void SetNextAnimationCustom(const std::shared_ptr& pIFP, const SString& strAnimationName); + void SetCurrentAnimationCustom(bool bCustom) noexcept { m_bisCurrentAnimationCustom = bCustom; } + bool IsCurrentAnimationCustom() const noexcept { return m_bisCurrentAnimationCustom; } CIFPAnimations* GetIFPAnimationsPointer() noexcept { return m_pIFPAnimations; } const CIFPAnimations* GetIFPAnimationsPointer() const noexcept { return m_pIFPAnimations; } @@ -568,7 +564,7 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule void RunClimbingTask(); CTaskSimpleSwim* GetSwimmingTask() const; - void RunSwimTask() const; + void RunSwimTask() const; protected: // This constructor is for peds managed by a player. These are unknown to the ped manager. @@ -652,8 +648,8 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule CStatsData* m_stats; CControllerState* m_currentControllerState; CControllerState* m_lastControllerState; - CControllerState m_rawControllerState; // copy of lastControllerState before CClientPed::ApplyControllerStateFixes is applied (modifies states to - // prevent stuff like rapid input glitch) + CControllerState m_rawControllerState; // copy of lastControllerState before CClientPed::ApplyControllerStateFixes is applied (modifies states to + // prevent stuff like rapid input glitch) CRemoteDataStorage* m_remoteDataStorage; unsigned long m_ulLastTimeFired; unsigned long m_ulLastTimeBeganAiming; @@ -693,7 +689,7 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule CClientEntityPtr m_pTargetedEntity; std::list m_SyncBuffer; bool m_bDucked; - bool m_bWasDucked; // For knowing when to register standing up + bool m_bWasDucked; // For knowing when to register standing up bool m_bIsChoking; bool m_bWearingGoggles; bool m_bVisible; @@ -797,16 +793,16 @@ class CClientPed : public CClientStreamElement, public CAntiCheatModule bool m_bWarpInToVehicleRequired = false; // Enter/exit variables - unsigned long m_ulLastVehicleInOutTime; // Last tick where we sent an enter/exit request - bool m_bIsGettingOutOfVehicle; // Indicates we are exiting a vehicle - bool m_bIsGettingIntoVehicle; // Indicates we are entering a vehicle - bool m_bIsJackingVehicle; // Indicates we are jacking a vehicle - bool m_bIsGettingJacked; // Indicates we are getting jacked - ElementID m_VehicleInOutID; // ElementID of vehicle received from server - unsigned char m_ucVehicleInOutSeat; // Seat ID we are entering/exiting received from server - bool m_bNoNewVehicleTask; // When set, we are not allowed to initiate a new enter/exit task because we are waiting for server reply - ElementID m_NoNewVehicleTaskReasonID; // ElementID of the vehicle that we are waiting on - CClientPed* m_pGettingJackedBy; // The ped that is jacking us + unsigned long m_ulLastVehicleInOutTime; // Last tick where we sent an enter/exit request + bool m_bIsGettingOutOfVehicle; // Indicates we are exiting a vehicle + bool m_bIsGettingIntoVehicle; // Indicates we are entering a vehicle + bool m_bIsJackingVehicle; // Indicates we are jacking a vehicle + bool m_bIsGettingJacked; // Indicates we are getting jacked + ElementID m_VehicleInOutID; // ElementID of vehicle received from server + unsigned char m_ucVehicleInOutSeat; // Seat ID we are entering/exiting received from server + bool m_bNoNewVehicleTask; // When set, we are not allowed to initiate a new enter/exit task because we are waiting for server reply + ElementID m_NoNewVehicleTaskReasonID; // ElementID of the vehicle that we are waiting on + CClientPed* m_pGettingJackedBy; // The ped that is jacking us std::shared_ptr m_clientModel; diff --git a/Client/mods/deathmatch/logic/CClientPedManager.cpp b/Client/mods/deathmatch/logic/CClientPedManager.cpp index 878b002a6d9..fd5d25b30b8 100644 --- a/Client/mods/deathmatch/logic/CClientPedManager.cpp +++ b/Client/mods/deathmatch/logic/CClientPedManager.cpp @@ -263,58 +263,58 @@ bool CClientPedManager::IsValidWeaponModel(DWORD dwModel) switch (dwModel) { case 0: - case 321: // Regular_Dildo - case 322: // Vibrator - case 323: // White_Dildo - // 324 // Vibrator_unused - case 325: // Flowers - case 326: // Cane - // 327 - // 328 - // 329 - // 330 - case 331: // Brass_Knuckles - // 332 - case 333: // Golf_Club - case 334: // Night_Strick - case 335: // Knife - case 336: // Baseball_Bat - case 337: // Shovel - case 338: // Pool_Cue - case 339: // Katana - // 340 - case 341: // Chainsaw - case 342: // Grenade - case 343: // Tear_Gas - case 344: // Molotov_Cocktail - // 345 // Missile - case 346: // Pistol - case 347: // Silenced_Pistol - case 348: // Desert_Eagle - case 349: // Shotgun - case 350: // Sawn-Off_Shotgun - case 351: // Combat_Shotgun - case 352: // Uzi - case 353: // MP5 - // 354 // Hydra_Flare - case 355: // AK47 - case 356: // M4 - case 357: // Country_Rifle - case 358: // Sniper_Rifle - case 359: // Rocket_Launcher - case 360: // Heat_Seeking_Rocket_Launcher - case 361: // Flamethrower - case 362: // Minigun - case 363: // Satchel_Charge - case 364: // Detonator - case 365: // Spray_Can - case 366: // Fire_Extinguisher - case 367: // Camera - case 368: // Night_Vision_Goggles - case 369: // Infra-Red_Goggles + case 321: // Regular_Dildo + case 322: // Vibrator + case 323: // White_Dildo + // 324 // Vibrator_unused + case 325: // Flowers + case 326: // Cane + // 327 + // 328 + // 329 + // 330 + case 331: // Brass_Knuckles + // 332 + case 333: // Golf_Club + case 334: // Night_Strick + case 335: // Knife + case 336: // Baseball_Bat + case 337: // Shovel + case 338: // Pool_Cue + case 339: // Katana + // 340 + case 341: // Chainsaw + case 342: // Grenade + case 343: // Tear_Gas + case 344: // Molotov_Cocktail + // 345 // Missile + case 346: // Pistol + case 347: // Silenced_Pistol + case 348: // Desert_Eagle + case 349: // Shotgun + case 350: // Sawn-Off_Shotgun + case 351: // Combat_Shotgun + case 352: // Uzi + case 353: // MP5 + // 354 // Hydra_Flare + case 355: // AK47 + case 356: // M4 + case 357: // Country_Rifle + case 358: // Sniper_Rifle + case 359: // Rocket_Launcher + case 360: // Heat_Seeking_Rocket_Launcher + case 361: // Flamethrower + case 362: // Minigun + case 363: // Satchel_Charge + case 364: // Detonator + case 365: // Spray_Can + case 366: // Fire_Extinguisher + case 367: // Camera + case 368: // Night_Vision_Goggles + case 369: // Infra-Red_Goggles // 370 // Jet_Pack - case 371: // Parachute - case 372: // Tec-9 + case 371: // Parachute + case 372: // Tec-9 { return true; } diff --git a/Client/mods/deathmatch/logic/CClientPerfStat.LibMemory.cpp b/Client/mods/deathmatch/logic/CClientPerfStat.LibMemory.cpp index 161898daee9..c42416d740b 100644 --- a/Client/mods/deathmatch/logic/CClientPerfStat.LibMemory.cpp +++ b/Client/mods/deathmatch/logic/CClientPerfStat.LibMemory.cpp @@ -42,7 +42,7 @@ namespace CDynamicLibrary* pLibrary; PFNGETALLOCSTATS pfnGetAllocStats; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -219,14 +219,14 @@ void CClientPerfStatLibMemoryImpl::GetLibMemoryStats(CClientPerfStatResult* pRes CLibraryInfo info; bool bModDir = libs[i].bModDir; info.strName = libs[i].szName; - #if MTA_DEBUG +#if MTA_DEBUG info.strName += "_d"; - #endif - #ifdef WIN32 +#endif +#ifdef WIN32 info.strName += ".dll"; - #else +#else info.strName += ".so"; - #endif +#endif info.pLibrary = new CDynamicLibrary(); SString strPathFilename; diff --git a/Client/mods/deathmatch/logic/CClientPerfStat.LuaMemory.cpp b/Client/mods/deathmatch/logic/CClientPerfStat.LuaMemory.cpp index 16da963a6d6..f2a2d1b6849 100644 --- a/Client/mods/deathmatch/logic/CClientPerfStat.LuaMemory.cpp +++ b/Client/mods/deathmatch/logic/CClientPerfStat.LuaMemory.cpp @@ -36,7 +36,7 @@ namespace public: CLuaMainMemoryMap LuaMainMemoryMap; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -296,7 +296,7 @@ void CClientPerfStatLuaMemoryImpl::GetLuaMemoryStats(CClientPerfStatResult* pRes int ScreenSourceCount = g_pClientGame->GetManager()->GetRenderElementManager()->GetScreenSourceCount(); int WebBrowserCount = g_pClientGame->GetManager()->GetRenderElementManager()->GetWebBrowserCount(); int VectorGraphicCount = g_pClientGame->GetManager()->GetRenderElementManager()->GetVectorGraphicCount(); - TextItemCount = std::max(TextItemCount - 4, 0); // Remove count for radar items + TextItemCount = std::max(TextItemCount - 4, 0); // Remove count for radar items row[c++] = !TextItemCount ? SStringX("-") : SString("%d", TextItemCount); row[c++] = !DxFontCount ? SStringX("-") : SString("%d", DxFontCount); row[c++] = !GuiFontCount ? SStringX("-") : SString("%d", GuiFontCount); diff --git a/Client/mods/deathmatch/logic/CClientPerfStat.LuaTiming.cpp b/Client/mods/deathmatch/logic/CClientPerfStat.LuaTiming.cpp index 75883e48bad..122f1da96df 100644 --- a/Client/mods/deathmatch/logic/CClientPerfStat.LuaTiming.cpp +++ b/Client/mods/deathmatch/logic/CClientPerfStat.LuaTiming.cpp @@ -31,8 +31,8 @@ namespace struct CTimingPair { - CTiming acc; // Accumulator for current period - CTiming prev; // Result for previous period + CTiming acc; // Accumulator for current period + CTiming prev; // Result for previous period void Pulse(CTimingPair* above) { @@ -46,10 +46,10 @@ namespace class CTimingBlock { public: - CTimingPair s5; // 5 second period - CTimingPair s60; // 60 - CTimingPair m5; // 300 - CTimingPair m60; // 3600 + CTimingPair s5; // 5 second period + CTimingPair s60; // 60 + CTimingPair m5; // 300 + CTimingPair m60; // 3600 void Pulse1s(int flags) { @@ -100,7 +100,7 @@ namespace } } }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -269,13 +269,13 @@ void CClientPerfStatLuaTimingImpl::DoPulse() int flags = 0; m_SecondCounter++; - if (m_SecondCounter % 5 == 0) // 1 second + if (m_SecondCounter % 5 == 0) // 1 second flags |= 1; - if (m_SecondCounter % 60 == 0) // 60 seconds + if (m_SecondCounter % 60 == 0) // 60 seconds flags |= 2; - if (m_SecondCounter % (60 * 5) == 0) // 5 mins + if (m_SecondCounter % (60 * 5) == 0) // 5 mins flags |= 4; - if (m_SecondCounter % (60 * 60) == 0) // 60 mins + if (m_SecondCounter % (60 * 60) == 0) // 60 mins flags |= 8; AllLuaTiming.Pulse1s(flags); diff --git a/Client/mods/deathmatch/logic/CClientPerfStat.PacketUsage.cpp b/Client/mods/deathmatch/logic/CClientPerfStat.PacketUsage.cpp index 677f4542814..b557a822a78 100644 --- a/Client/mods/deathmatch/logic/CClientPerfStat.PacketUsage.cpp +++ b/Client/mods/deathmatch/logic/CClientPerfStat.PacketUsage.cpp @@ -247,7 +247,7 @@ void CClientPerfStatPacketUsageImpl::GetStats(CClientPerfStatResult* pResult, co row[c++] = SString("%d", (statInDelta.iCount + 4) / 5); row[c++] = SString("%d", (statInDelta.iTotalBytes + 4) / 5); row[c++] = SString("%2.2f%%", - statInDelta.totalTime / 50000.f); // Number of microseconds in sample period ( 5sec * 1000000 ) into percent ( * 100 ) + statInDelta.totalTime / 50000.f); // Number of microseconds in sample period ( 5sec * 1000000 ) into percent ( * 100 ) } else { diff --git a/Client/mods/deathmatch/logic/CClientPickup.cpp b/Client/mods/deathmatch/logic/CClientPickup.cpp index 022517af863..9211b2cc987 100644 --- a/Client/mods/deathmatch/logic/CClientPickup.cpp +++ b/Client/mods/deathmatch/logic/CClientPickup.cpp @@ -179,7 +179,7 @@ bool CClientPickup::Create() // Store our pickup's object m_pObject = m_pPickup->GetObject(); - + // Validate the object was stored correctly if (!m_pObject) { @@ -245,17 +245,17 @@ void CClientPickup::Callback_OnCollision(CClientColShape& Shape, CClientEntity& { if (IS_PLAYER(&Entity)) { - bool bMatchingDimensions = (GetDimension() == Entity.GetDimension()); // Matching dimensions? + bool bMatchingDimensions = (GetDimension() == Entity.GetDimension()); // Matching dimensions? // Call the pickup hit event (source = pickup that was hit) CLuaArguments Arguments; - Arguments.PushElement(&Entity); // The element that hit the pickup + Arguments.PushElement(&Entity); // The element that hit the pickup Arguments.PushBoolean(bMatchingDimensions); CallEvent("onClientPickupHit", Arguments, true); // Call the player pickup hit (source = player that hit the pickup) CLuaArguments Arguments2; - Arguments2.PushElement(this); // The pickup that was hit + Arguments2.PushElement(this); // The pickup that was hit Arguments2.PushBoolean(bMatchingDimensions); Entity.CallEvent("onClientPlayerPickupHit", Arguments2, true); } @@ -265,17 +265,17 @@ void CClientPickup::Callback_OnLeave(CClientColShape& Shape, CClientEntity& Enti { if (IS_PLAYER(&Entity)) { - bool bMatchingDimensions = (GetDimension() == Entity.GetDimension()); // Matching dimensions? + bool bMatchingDimensions = (GetDimension() == Entity.GetDimension()); // Matching dimensions? // Call the pickup leave event (source = the pickup that was left) CLuaArguments Arguments; - Arguments.PushElement(&Entity); // The element that left the pickup + Arguments.PushElement(&Entity); // The element that left the pickup Arguments.PushBoolean(bMatchingDimensions); CallEvent("onClientPickupLeave", Arguments, true); // Call the player pickup leave event (source = the player that left the pickup) CLuaArguments Arguments2; - Arguments2.PushElement(this); // The pickup that was left (this) + Arguments2.PushElement(this); // The pickup that was left (this) Arguments2.PushBoolean(bMatchingDimensions); Entity.CallEvent("onClientPlayerPickupLeave", Arguments2, true); } diff --git a/Client/mods/deathmatch/logic/CClientPickupManager.cpp b/Client/mods/deathmatch/logic/CClientPickupManager.cpp index 6d5a4a0ba68..6cc7b07c3ca 100644 --- a/Client/mods/deathmatch/logic/CClientPickupManager.cpp +++ b/Client/mods/deathmatch/logic/CClientPickupManager.cpp @@ -14,11 +14,11 @@ using std::list; static const SFixedArray g_usWeaponModels = {{ - 0, 331, 333, 334, 335, 336, 337, 338, 339, 341, // 9 - 321, 322, 323, 324, 325, 326, 342, 343, 344, 0, // 19 - 0, 0, 346, 347, 348, 349, 350, 351, 352, 353, // 29 - 355, 356, 372, 357, 358, 359, 360, 361, 362, 363, // 39 - 364, 365, 366, 367, 368, 369, 371 // 46 + 0, 331, 333, 334, 335, 336, 337, 338, 339, 341, // 9 + 321, 322, 323, 324, 325, 326, 342, 343, 344, 0, // 19 + 0, 0, 346, 347, 348, 349, 350, 351, 352, 353, // 29 + 355, 356, 372, 357, 358, 359, 360, 361, 362, 363, // 39 + 364, 365, 366, 367, 368, 369, 371 // 46 }}; unsigned int CClientPickupManager::m_uiPickupCount = 0; @@ -70,7 +70,7 @@ void CClientPickupManager::DeleteAll() // Clear the list m_List.clear(); - + // Restore previous processing state if (!wasDisabled) { diff --git a/Client/mods/deathmatch/logic/CClientPlayer.cpp b/Client/mods/deathmatch/logic/CClientPlayer.cpp index 4669e2ef715..0ae10242311 100644 --- a/Client/mods/deathmatch/logic/CClientPlayer.cpp +++ b/Client/mods/deathmatch/logic/CClientPlayer.cpp @@ -66,7 +66,7 @@ CClientPlayer::CClientPlayer(CClientManager* pManager, ElementID ID, bool bIsLoc m_remoteDataStorage->SetProcessPlayerWeapon(true); // Enable voice playback for remote players - if (g_pClientGame->GetVoiceRecorder()->IsEnabled()) // If voice is enabled + if (g_pClientGame->GetVoiceRecorder()->IsEnabled()) // If voice is enabled m_voice = new CClientPlayerVoice(this, g_pClientGame->GetVoiceRecorder()); } diff --git a/Client/mods/deathmatch/logic/CClientPlayer.h b/Client/mods/deathmatch/logic/CClientPlayer.h index bef1f264976..57cd754dd0d 100644 --- a/Client/mods/deathmatch/logic/CClientPlayer.h +++ b/Client/mods/deathmatch/logic/CClientPlayer.h @@ -112,7 +112,7 @@ class CClientPlayer final : public CClientPed void SetIsInNetworkInterruption(bool bInNetworkInterruption); std::uint8_t GetPlayerScriptDebugLevel() const noexcept { return m_scriptDebugLevel; } - void SetPlayerScriptDebugLevel(std::uint8_t level) noexcept { m_scriptDebugLevel = level; } + void SetPlayerScriptDebugLevel(std::uint8_t level) noexcept { m_scriptDebugLevel = level; } CVector m_vecPrevBulletSyncStart; CVector m_vecPrevBulletSyncEnd; @@ -139,7 +139,7 @@ class CClientPlayer final : public CClientPed unsigned long m_ulTick; bool m_bDoExtrapolatingAim; - std::uint8_t m_scriptDebugLevel{}; + std::uint8_t m_scriptDebugLevel{}; bool m_bForce; CVector m_vecForcedMoveSpeed; diff --git a/Client/mods/deathmatch/logic/CClientPlayerClothes.cpp b/Client/mods/deathmatch/logic/CClientPlayerClothes.cpp index 789eab812d8..8ec23087ca2 100644 --- a/Client/mods/deathmatch/logic/CClientPlayerClothes.cpp +++ b/Client/mods/deathmatch/logic/CClientPlayerClothes.cpp @@ -15,171 +15,304 @@ static const SPlayerClothingType g_clothesNames[PLAYER_CLOTHING_SLOTS] = { {"Right Lower Arm"}, {"Back Top"}, {"Left Chest"}, {"Right Chest"}, {"Stomach"}, {"Lower Back"}, {"Extra1"}, {"Extra2"}, {"Extra3"}, {"Extra4"}, {"Suit"}}; -SFixedArray, PLAYER_CLOTHING_SLOTS> CClientPlayerClothes::m_DefaultClothes -{ - //Torso Clothing - std::vector { - {"player_torso", "torso"}, {"vestblack", "vest"}, {"vest", "vest"}, {"tshirt2horiz", "tshirt2"}, {"tshirtwhite", "tshirt"}, - {"tshirtilovels", "tshirt"}, {"tshirtblunts", "tshirt"}, {"shirtbplaid", "shirtb"}, {"shirtbcheck", "shirtb"}, - {"field", "field"}, {"tshirterisyell", "tshirt"}, {"tshirterisorn", "tshirt"}, {"trackytop2eris", "trackytop1"}, - {"bbjackrim", "bbjack"}, {"bballjackrstar", "bbjack"}, {"baskballdrib", "baskball"}, {"baskballrim", "baskball"}, - {"sixtyniners", "tshirt"}, {"bandits", "baseball"}, {"tshirtprored", "tshirt"}, {"tshirtproblk", "tshirt"}, - {"trackytop1pro", "trackytop1"}, {"hockeytop", "sweat"}, {"bbjersey", "sleevt"}, {"shellsuit", "trackytop1"}, - {"tshirtheatwht", "tshirt"}, {"tshirtbobomonk", "tshirt"}, {"tshirtbobored", "tshirt"}, {"tshirtbase5", "tshirt"}, - {"tshirtsuburb", "tshirt"}, {"hoodyamerc", "hoodya"}, {"hoodyabase5", "hoodya"}, {"hoodyarockstar", "hoodya"}, - {"wcoatblue", "wcoat"}, {"coach", "coach"}, {"coachsemi", "coach"}, {"sweatrstar", "sweat"}, {"hoodyAblue", "hoodyA"}, - {"hoodyAblack", "hoodyA"}, {"hoodyAgreen", "hoodyA"}, {"sleevtbrown", "sleevt"}, {"shirtablue", "shirta"}, {"shirtayellow", "shirta"}, - {"shirtagrey", "shirta"}, {"shirtbgang", "shirtb"}, {"tshirtzipcrm", "tshirt"}, {"tshirtzipgry", "tshirt"}, {"denimfade", "denim"}, - {"bowling", "hawaii"}, {"hoodjackbeige", "hoodjack"}, {"baskballloc", "baskball"}, {"tshirtlocgrey", "tshirt"}, - {"tshirtmaddgrey", "tshirt"}, {"tshirtmaddgrn", "tshirt"}, {"suit1grey", "suit1"}, {"suit1blk", "suit1"}, {"leather", "leather"}, - {"painter", "painter"}, {"hawaiiwht", "hawaii"}, {"hawaiired", "hawaii"}, {"sportjack", "trackytop1"}, {"suit1red", "suit1"}, - {"suit1blue", "suit1"}, {"suit1yellow", "suit1"}, {"suit2grn", "suit2"}, {"tuxedo", "suit2"}, {"suit1gang", "suit1"}, {"letter", "sleevt"} - }, - - //Hair Clothing - std::vector { - {"player_face", "head"}, {"hairblond", "head"}, {"hairred", "head"}, {"hairblue", "head"}, {"hairgreen", "head"}, {"hairpink", "head"}, - {"bald", "head"}, {"baldbeard", "head"}, {"baldtash", "head"}, {"baldgoatee", "head"}, {"highfade", "head"}, {"highafro", "highafro"}, - {"wedge", "wedge"}, {"slope", "slope"}, {"jhericurl", "jheri"}, {"cornrows", "cornrows"}, {"cornrowsb", "cornrows"}, {"tramline", "tramline"}, - {"groovecut", "groovecut"}, {"mohawk", "mohawk"}, {"mohawkblond", "mohawk"}, {"mohawkpink", "mohawk"}, - {"mohawkbeard", "mohawk"}, {"afro", "afro"}, {"afrotash", "afro"}, {"afrobeard", "afro"}, {"afroblond", "afro"}, {"flattop", "flattop"}, - {"elvishair", "elvishair"}, {"beard", "head"}, {"tash", "head"}, {"goatee", "head"}, {"afrogoatee", "afro"} - }, - - //Legs Clothing - std::vector { - {"player_legs", "legs"}, {"worktrcamogrn", "worktr"}, {"worktrcamogry", "worktr"}, {"worktrgrey", "worktr"}, - {"worktrkhaki", "worktr"}, {"tracktr", "tracktr"}, {"tracktreris", "tracktr"}, {"jeansdenim", "jeans"}, - {"legsblack", "legs"}, {"legsheart", "legs"}, {"biegetr", "chinosb"}, {"tracktrpro", "tracktr"}, - {"tracktrwhstr", "tracktr"}, {"tracktrblue", "tracktr"}, {"tracktrgang", "tracktr"}, {"bbshortwht", "boxingshort"}, - {"boxshort", "boxingshort"}, {"bbshortred", "boxingshort"}, {"shellsuittr", "tracktr"}, {"shortsgrey", "shorts"}, - {"shortskhaki", "shorts"}, {"chongergrey", "chonger"}, {"chongergang", "chonger"}, {"chongerred", "chonger"}, - {"chongerblue", "chonger"}, {"shortsgang", "shorts"}, {"denimsgang", "jeans"}, {"denimsred", "jeans"}, - {"chinosbiege", "chinosb"}, {"chinoskhaki", "chinosb"}, {"cutoffchinos", "shorts"}, {"cutoffchinosblue", "shorts"}, - {"chinosblack", "chinosb"}, {"chinosblue", "chinosb"}, {"leathertr", "leathertr"}, {"leathertrchaps", "leathertr"}, - {"suit1trgrey", "suit1tr"}, {"suit1trblk", "suit1tr"}, {"cutoffdenims", "shorts"}, {"suit1trred", "suit1tr"}, - {"suit1trblue", "suit1tr"}, {"suit1tryellow", "suit1tr"}, {"suit1trgreen", "suit1tr"}, {"suit1trblk2", "suit1tr"}, - {"suit1trgang", "suit1tr"} - }, - - //Shoes Clothing - std::vector { - {"foot", "feet"}, {"cowboyboot2", "biker"}, {"bask2semi", "bask1"}, {"bask1eris", "bask1"}, {"sneakerbincgang", "sneaker"}, {"sneakerbincblu", "sneaker"}, - {"sneakerbincblk", "sneaker"}, {"sandal", "flipflop"}, {"sandalsock", "flipflop"}, {"flipflop", "flipflop"}, {"hitop", "bask1"}, {"convproblk", "conv"}, - {"convproblu", "conv"}, {"convprogrn", "conv"}, {"sneakerprored", "sneaker"}, {"sneakerproblu", "sneaker"}, {"sneakerprowht", "sneaker"}, - {"bask1prowht", "bask1"}, {"bask1problk", "bask1"}, {"boxingshoe", "biker"}, {"convheatblk", "conv"}, {"convheatred", "conv"}, {"convheatorn", "conv"}, - {"sneakerheatwht", "sneaker"}, {"sneakerheatgry", "sneaker"}, {"sneakerheatblk", "sneaker"}, {"bask2heatwht", "bask1"}, {"bask2heatband", "bask1"}, - {"timbergrey", "bask1"}, {"timberred", "bask1"}, {"timberfawn", "bask1"}, {"timberhike", "bask1"}, {"cowboyboot", "biker"}, {"biker", "biker"}, - {"snakeskin", "biker"}, {"shoedressblk", "shoe"}, {"shoedressbrn", "shoe"}, {"shoespatz", "shoe"} - }, - - //Left Upper Arm Clothing - std::vector { - {"4weed", "4WEED"}, {"4rip", "4RIP"}, {"4spider", "4SPIDER"} - }, - - //Left Lower Arm Clothing - std::vector { - {"5gun", "5GUN"}, {"5cross", "5CROSS"}, {"5cross2", "5CROSS2"}, - {"5cross3", "5CROSS3"} - }, - - //Right Upper Arm Clothing - std::vector { - {"6aztec", "6AZTEC"}, {"6crown", "6CROWN"}, {"6clown", "6CLOWN"}, - {"6africa", "6AFRICA"} - }, - - //Right LowerA rm Clothing - std::vector { - {"7cross", "7CROSS"}, {"7cross2", "7CROSS2"}, {"7cross3", "7CROSS3"}, - {"7mary", "7MARY"} - }, - - //Back Top Clothing - std::vector { - {"8sa", "8SA"}, {"8sa2", "8SA2"}, {"8sa3", "8SA3"}, - {"8westside", "8WESTSD"}, {"8santos", "8SANTOS"}, - {"8poker", "8POKER"}, {"8gun", "8GUN"} - }, - - //Left Chest Clothing - std::vector { - {"9crown", "9CROWN"}, {"9gun", "9GUN"}, {"9gun2", "9GUN2"}, - {"9homeboy", "9HOMBY"}, {"9bullet", "9BULLT"}, - {"9rasta", "9RASTA"} - }, - - //Right Chest Clothing - std::vector { - {"10ls", "10LS"}, {"10ls2", "10LS2"}, {"10ls3", "10LS3"}, - {"10ls4", "10LS4"}, {"10ls5", "10LS5"}, {"10og", "10OG"}, - {"10weed", "10WEED"} - }, - - //Stomach Clothing - std::vector { - {"11grove", "11GROVE"}, {"11grove2", "11GROV2"}, {"11grove3", "11GROV3"}, {"11dice", "11DICE"}, - {"11dice2", "11DICE2"}, {"11jail", "11JAIL"}, {"11godsgift", "11GGIFT"} - }, - - //Lower Back Clothing - std::vector { - {"12angels", "12ANGEL"}, {"12mayabird", "12MAYBR"}, {"12dagger", "12DAGER"}, - {"12bandit", "12BNDIT"}, {"12cross7", "12CROSS"}, {"12mayaface", "12MYFAC"}, - }, - - //Extra1 Clothing - std::vector { - {"dogtag", "neck"}, {"neckafrica", "neck"}, {"stopwatch", "neck"}, {"necksaints", "neck"}, {"neckhash", "neck"}, {"necksilver", "neck2"}, - {"neckgold", "neck2"}, {"neckropes", "neck2"}, {"neckropeg", "neck2"}, {"neckls", "neck"}, {"neckdollar", "neck"}, {"neckcross", "neck"} - }, - - //Extra2 Clothing - std::vector { - {"watchpink", "watch"}, {"watchyellow", "watch"}, {"watchpro", "watch"}, {"watchpro2", "watch"}, {"watchsub1", "watch"}, - {"watchsub2", "watch"}, {"watchzip1", "watch"}, {"watchzip2", "watch"}, {"watchgno", "watch"}, {"watchgno2", "watch"}, - {"watchcro", "watch"}, {"watchcro2", "watch"} +SFixedArray, PLAYER_CLOTHING_SLOTS> CClientPlayerClothes::m_DefaultClothes{ + // Torso Clothing + std::vector{{"player_torso", "torso"}, + {"vestblack", "vest"}, + {"vest", "vest"}, + {"tshirt2horiz", "tshirt2"}, + {"tshirtwhite", "tshirt"}, + {"tshirtilovels", "tshirt"}, + {"tshirtblunts", "tshirt"}, + {"shirtbplaid", "shirtb"}, + {"shirtbcheck", "shirtb"}, + {"field", "field"}, + {"tshirterisyell", "tshirt"}, + {"tshirterisorn", "tshirt"}, + {"trackytop2eris", "trackytop1"}, + {"bbjackrim", "bbjack"}, + {"bballjackrstar", "bbjack"}, + {"baskballdrib", "baskball"}, + {"baskballrim", "baskball"}, + {"sixtyniners", "tshirt"}, + {"bandits", "baseball"}, + {"tshirtprored", "tshirt"}, + {"tshirtproblk", "tshirt"}, + {"trackytop1pro", "trackytop1"}, + {"hockeytop", "sweat"}, + {"bbjersey", "sleevt"}, + {"shellsuit", "trackytop1"}, + {"tshirtheatwht", "tshirt"}, + {"tshirtbobomonk", "tshirt"}, + {"tshirtbobored", "tshirt"}, + {"tshirtbase5", "tshirt"}, + {"tshirtsuburb", "tshirt"}, + {"hoodyamerc", "hoodya"}, + {"hoodyabase5", "hoodya"}, + {"hoodyarockstar", "hoodya"}, + {"wcoatblue", "wcoat"}, + {"coach", "coach"}, + {"coachsemi", "coach"}, + {"sweatrstar", "sweat"}, + {"hoodyAblue", "hoodyA"}, + {"hoodyAblack", "hoodyA"}, + {"hoodyAgreen", "hoodyA"}, + {"sleevtbrown", "sleevt"}, + {"shirtablue", "shirta"}, + {"shirtayellow", "shirta"}, + {"shirtagrey", "shirta"}, + {"shirtbgang", "shirtb"}, + {"tshirtzipcrm", "tshirt"}, + {"tshirtzipgry", "tshirt"}, + {"denimfade", "denim"}, + {"bowling", "hawaii"}, + {"hoodjackbeige", "hoodjack"}, + {"baskballloc", "baskball"}, + {"tshirtlocgrey", "tshirt"}, + {"tshirtmaddgrey", "tshirt"}, + {"tshirtmaddgrn", "tshirt"}, + {"suit1grey", "suit1"}, + {"suit1blk", "suit1"}, + {"leather", "leather"}, + {"painter", "painter"}, + {"hawaiiwht", "hawaii"}, + {"hawaiired", "hawaii"}, + {"sportjack", "trackytop1"}, + {"suit1red", "suit1"}, + {"suit1blue", "suit1"}, + {"suit1yellow", "suit1"}, + {"suit2grn", "suit2"}, + {"tuxedo", "suit2"}, + {"suit1gang", "suit1"}, + {"letter", "sleevt"}}, + + // Hair Clothing + std::vector{ + {"player_face", "head"}, {"hairblond", "head"}, {"hairred", "head"}, {"hairblue", "head"}, {"hairgreen", "head"}, + {"hairpink", "head"}, {"bald", "head"}, {"baldbeard", "head"}, {"baldtash", "head"}, {"baldgoatee", "head"}, + {"highfade", "head"}, {"highafro", "highafro"}, {"wedge", "wedge"}, {"slope", "slope"}, {"jhericurl", "jheri"}, + {"cornrows", "cornrows"}, {"cornrowsb", "cornrows"}, {"tramline", "tramline"}, {"groovecut", "groovecut"}, {"mohawk", "mohawk"}, + {"mohawkblond", "mohawk"}, {"mohawkpink", "mohawk"}, {"mohawkbeard", "mohawk"}, {"afro", "afro"}, {"afrotash", "afro"}, + {"afrobeard", "afro"}, {"afroblond", "afro"}, {"flattop", "flattop"}, {"elvishair", "elvishair"}, {"beard", "head"}, + {"tash", "head"}, {"goatee", "head"}, {"afrogoatee", "afro"}}, + + // Legs Clothing + std::vector{ + {"player_legs", "legs"}, {"worktrcamogrn", "worktr"}, {"worktrcamogry", "worktr"}, {"worktrgrey", "worktr"}, {"worktrkhaki", "worktr"}, + {"tracktr", "tracktr"}, {"tracktreris", "tracktr"}, {"jeansdenim", "jeans"}, {"legsblack", "legs"}, {"legsheart", "legs"}, + {"biegetr", "chinosb"}, {"tracktrpro", "tracktr"}, {"tracktrwhstr", "tracktr"}, {"tracktrblue", "tracktr"}, {"tracktrgang", "tracktr"}, + {"bbshortwht", "boxingshort"}, {"boxshort", "boxingshort"}, {"bbshortred", "boxingshort"}, {"shellsuittr", "tracktr"}, {"shortsgrey", "shorts"}, + {"shortskhaki", "shorts"}, {"chongergrey", "chonger"}, {"chongergang", "chonger"}, {"chongerred", "chonger"}, {"chongerblue", "chonger"}, + {"shortsgang", "shorts"}, {"denimsgang", "jeans"}, {"denimsred", "jeans"}, {"chinosbiege", "chinosb"}, {"chinoskhaki", "chinosb"}, + {"cutoffchinos", "shorts"}, {"cutoffchinosblue", "shorts"}, {"chinosblack", "chinosb"}, {"chinosblue", "chinosb"}, {"leathertr", "leathertr"}, + {"leathertrchaps", "leathertr"}, {"suit1trgrey", "suit1tr"}, {"suit1trblk", "suit1tr"}, {"cutoffdenims", "shorts"}, {"suit1trred", "suit1tr"}, + {"suit1trblue", "suit1tr"}, {"suit1tryellow", "suit1tr"}, {"suit1trgreen", "suit1tr"}, {"suit1trblk2", "suit1tr"}, {"suit1trgang", "suit1tr"}}, + + // Shoes Clothing + std::vector{{"foot", "feet"}, + {"cowboyboot2", "biker"}, + {"bask2semi", "bask1"}, + {"bask1eris", "bask1"}, + {"sneakerbincgang", "sneaker"}, + {"sneakerbincblu", "sneaker"}, + {"sneakerbincblk", "sneaker"}, + {"sandal", "flipflop"}, + {"sandalsock", "flipflop"}, + {"flipflop", "flipflop"}, + {"hitop", "bask1"}, + {"convproblk", "conv"}, + {"convproblu", "conv"}, + {"convprogrn", "conv"}, + {"sneakerprored", "sneaker"}, + {"sneakerproblu", "sneaker"}, + {"sneakerprowht", "sneaker"}, + {"bask1prowht", "bask1"}, + {"bask1problk", "bask1"}, + {"boxingshoe", "biker"}, + {"convheatblk", "conv"}, + {"convheatred", "conv"}, + {"convheatorn", "conv"}, + {"sneakerheatwht", "sneaker"}, + {"sneakerheatgry", "sneaker"}, + {"sneakerheatblk", "sneaker"}, + {"bask2heatwht", "bask1"}, + {"bask2heatband", "bask1"}, + {"timbergrey", "bask1"}, + {"timberred", "bask1"}, + {"timberfawn", "bask1"}, + {"timberhike", "bask1"}, + {"cowboyboot", "biker"}, + {"biker", "biker"}, + {"snakeskin", "biker"}, + {"shoedressblk", "shoe"}, + {"shoedressbrn", "shoe"}, + {"shoespatz", "shoe"}}, + + // Left Upper Arm Clothing + std::vector{{"4weed", "4WEED"}, {"4rip", "4RIP"}, {"4spider", "4SPIDER"}}, + + // Left Lower Arm Clothing + std::vector{{"5gun", "5GUN"}, {"5cross", "5CROSS"}, {"5cross2", "5CROSS2"}, {"5cross3", "5CROSS3"}}, + + // Right Upper Arm Clothing + std::vector{{"6aztec", "6AZTEC"}, {"6crown", "6CROWN"}, {"6clown", "6CLOWN"}, {"6africa", "6AFRICA"}}, + + // Right LowerA rm Clothing + std::vector{{"7cross", "7CROSS"}, {"7cross2", "7CROSS2"}, {"7cross3", "7CROSS3"}, {"7mary", "7MARY"}}, + + // Back Top Clothing + std::vector{ + {"8sa", "8SA"}, {"8sa2", "8SA2"}, {"8sa3", "8SA3"}, {"8westside", "8WESTSD"}, {"8santos", "8SANTOS"}, {"8poker", "8POKER"}, {"8gun", "8GUN"}}, + + // Left Chest Clothing + std::vector{ + {"9crown", "9CROWN"}, {"9gun", "9GUN"}, {"9gun2", "9GUN2"}, {"9homeboy", "9HOMBY"}, {"9bullet", "9BULLT"}, {"9rasta", "9RASTA"}}, + + // Right Chest Clothing + std::vector{ + {"10ls", "10LS"}, {"10ls2", "10LS2"}, {"10ls3", "10LS3"}, {"10ls4", "10LS4"}, {"10ls5", "10LS5"}, {"10og", "10OG"}, {"10weed", "10WEED"}}, + + // Stomach Clothing + std::vector{{"11grove", "11GROVE"}, + {"11grove2", "11GROV2"}, + {"11grove3", "11GROV3"}, + {"11dice", "11DICE"}, + {"11dice2", "11DICE2"}, + {"11jail", "11JAIL"}, + {"11godsgift", "11GGIFT"}}, + + // Lower Back Clothing + std::vector{ + {"12angels", "12ANGEL"}, + {"12mayabird", "12MAYBR"}, + {"12dagger", "12DAGER"}, + {"12bandit", "12BNDIT"}, + {"12cross7", "12CROSS"}, + {"12mayaface", "12MYFAC"}, }, - //Extra3 Clothing - std::vector { - {"groucho", "grouchos"}, {"zorro", "zorromask"}, {"eyepatch", "eyepatch"}, - {"glasses01", "glasses01"}, {"glasses04", "glasses04"}, {"bandred3", "bandmask"}, - {"bandblue3", "bandmask"}, {"bandgang3", "bandmask"}, {"bandblack3", "bandmask"}, - {"glasses01dark", "glasses01"}, {"glasses04dark", "glasses04"}, {"glasses03", "glasses03"}, - {"glasses03red", "glasses03"}, {"glasses03blue", "glasses03"}, {"glasses03dark", "glasses03"}, - {"glasses05dark", "glasses03"}, {"glasses05", "glasses03"} - }, - - //Extra4 Clothing - std::vector { - {"bandred", "bandana"}, {"bandblue", "bandana"}, {"bandgang", "bandana"}, {"bandblack", "bandana"}, {"bandred2", "bandknots"}, - {"bandblue2", "bandknots"}, {"bandblack2", "bandknots"}, {"bandgang2", "bandknots"}, {"capknitgrn", "capknit"}, {"captruck", "captruck"}, - {"cowboy", "cowboy"}, {"hattiger", "cowboy"}, {"helmet", "helmet"}, {"moto", "moto"}, {"boxingcap", "boxingcap"}, {"hockey", "hockeymask"}, {"capgang", "cap"}, - {"capgangback", "capback"}, {"capgangside", "capside"}, {"capgangover", "capovereye"}, {"capgangup", "caprimup"}, {"bikerhelmet", "bikerhelmet"}, - {"capred", "cap"}, {"capredback", "capback"}, {"capredside", "capside"}, {"capredover", "capovereye"}, {"capredup", "caprimup"}, {"capblue", "cap"}, - {"capblueback", "capback"}, {"capblueside", "capside"}, {"capblueover", "capovereye"}, {"capblueup", "caprimup"}, {"skullyblk", "skullycap"}, - {"skullygrn", "skullycap"}, {"hatmancblk", "hatmanc"}, {"hatmancplaid", "hatmanc"}, {"capzip", "cap"}, {"capzipback", "capback"}, {"capzipside", "capside"}, - {"capzipover", "capovereye"}, {"capzipup", "caprimup"}, {"beretred", "beret"}, {"beretblk", "beret"}, {"capblk", "cap"}, {"capblkback", "capback"}, - {"capblkside", "capside"}, {"capblkover", "capovereye"}, {"capblkup", "caprimup"}, {"trilbydrk", "trilby"}, {"trilbylght", "trilby"}, - {"bowler", "bowler"}, {"bowlerred", "bowler"}, {"bowlerblue", "bowler"}, {"bowleryellow", "bowler"}, {"boater", "boater"}, {"bowlergang", "bowler"}, - {"boaterblk", "boater"} - }, + // Extra1 Clothing + std::vector{{"dogtag", "neck"}, + {"neckafrica", "neck"}, + {"stopwatch", "neck"}, + {"necksaints", "neck"}, + {"neckhash", "neck"}, + {"necksilver", "neck2"}, + {"neckgold", "neck2"}, + {"neckropes", "neck2"}, + {"neckropeg", "neck2"}, + {"neckls", "neck"}, + {"neckdollar", "neck"}, + {"neckcross", "neck"}}, + + // Extra2 Clothing + std::vector{{"watchpink", "watch"}, + {"watchyellow", "watch"}, + {"watchpro", "watch"}, + {"watchpro2", "watch"}, + {"watchsub1", "watch"}, + {"watchsub2", "watch"}, + {"watchzip1", "watch"}, + {"watchzip2", "watch"}, + {"watchgno", "watch"}, + {"watchgno2", "watch"}, + {"watchcro", "watch"}, + {"watchcro2", "watch"}}, + + // Extra3 Clothing + std::vector{{"groucho", "grouchos"}, + {"zorro", "zorromask"}, + {"eyepatch", "eyepatch"}, + {"glasses01", "glasses01"}, + {"glasses04", "glasses04"}, + {"bandred3", "bandmask"}, + {"bandblue3", "bandmask"}, + {"bandgang3", "bandmask"}, + {"bandblack3", "bandmask"}, + {"glasses01dark", "glasses01"}, + {"glasses04dark", "glasses04"}, + {"glasses03", "glasses03"}, + {"glasses03red", "glasses03"}, + {"glasses03blue", "glasses03"}, + {"glasses03dark", "glasses03"}, + {"glasses05dark", "glasses03"}, + {"glasses05", "glasses03"}}, + + // Extra4 Clothing + std::vector{{"bandred", "bandana"}, + {"bandblue", "bandana"}, + {"bandgang", "bandana"}, + {"bandblack", "bandana"}, + {"bandred2", "bandknots"}, + {"bandblue2", "bandknots"}, + {"bandblack2", "bandknots"}, + {"bandgang2", "bandknots"}, + {"capknitgrn", "capknit"}, + {"captruck", "captruck"}, + {"cowboy", "cowboy"}, + {"hattiger", "cowboy"}, + {"helmet", "helmet"}, + {"moto", "moto"}, + {"boxingcap", "boxingcap"}, + {"hockey", "hockeymask"}, + {"capgang", "cap"}, + {"capgangback", "capback"}, + {"capgangside", "capside"}, + {"capgangover", "capovereye"}, + {"capgangup", "caprimup"}, + {"bikerhelmet", "bikerhelmet"}, + {"capred", "cap"}, + {"capredback", "capback"}, + {"capredside", "capside"}, + {"capredover", "capovereye"}, + {"capredup", "caprimup"}, + {"capblue", "cap"}, + {"capblueback", "capback"}, + {"capblueside", "capside"}, + {"capblueover", "capovereye"}, + {"capblueup", "caprimup"}, + {"skullyblk", "skullycap"}, + {"skullygrn", "skullycap"}, + {"hatmancblk", "hatmanc"}, + {"hatmancplaid", "hatmanc"}, + {"capzip", "cap"}, + {"capzipback", "capback"}, + {"capzipside", "capside"}, + {"capzipover", "capovereye"}, + {"capzipup", "caprimup"}, + {"beretred", "beret"}, + {"beretblk", "beret"}, + {"capblk", "cap"}, + {"capblkback", "capback"}, + {"capblkside", "capside"}, + {"capblkover", "capovereye"}, + {"capblkup", "caprimup"}, + {"trilbydrk", "trilby"}, + {"trilbylght", "trilby"}, + {"bowler", "bowler"}, + {"bowlerred", "bowler"}, + {"bowlerblue", "bowler"}, + {"bowleryellow", "bowler"}, + {"boater", "boater"}, + {"bowlergang", "bowler"}, + {"boaterblk", "boater"}}, // Suit Clothing - std::vector { - {"gimpleg", "gimpleg"}, {"valet", "valet"}, {"countrytr", "countrytr"}, {"croupier", "valet"}, - {"policetr", "policetr"}, {"balaclava", "balaclava"}, {"pimptr", "pimptr"}, - {"garageleg", "garagetr"}, {"medictr", "medictr"} - } -}; + std::vector{{"gimpleg", "gimpleg"}, + {"valet", "valet"}, + {"countrytr", "countrytr"}, + {"croupier", "valet"}, + {"policetr", "policetr"}, + {"balaclava", "balaclava"}, + {"pimptr", "pimptr"}, + {"garageleg", "garagetr"}, + {"medictr", "medictr"}}}; // This represents GTA's 1 clothing block -SFixedArray CClientPlayerClothes::m_GlobalClothes; -SFixedArray, PLAYER_CLOTHING_SLOTS> CClientPlayerClothes::m_NewClothes; -bool CClientPlayerClothes::m_bStaticInit = true; -bool CClientPlayerClothes::m_bHasClothesChanged = false; +SFixedArray CClientPlayerClothes::m_GlobalClothes; +SFixedArray, PLAYER_CLOTHING_SLOTS> CClientPlayerClothes::m_NewClothes; +bool CClientPlayerClothes::m_bStaticInit = true; +bool CClientPlayerClothes::m_bHasClothesChanged = false; CClientPlayerClothes::CClientPlayerClothes(CClientPed* pPlayerModel) { @@ -329,7 +462,7 @@ bool CClientPlayerClothes::HasEmptyClothing(unsigned char ucType) bool CClientPlayerClothes::IsEmptyClothing(const SPlayerClothing* pClothing, unsigned char ucType) { - if (!pClothing || ucType > 3) + if (!pClothing || ucType > 3) return false; const std::vector pGroup = GetClothingGroup(ucType); @@ -414,9 +547,8 @@ bool CClientPlayerClothes::AddClothingModel(const char* texture, const char* mod auto& clothes = m_NewClothes[clothingType]; - if (std::any_of(clothes.begin(), clothes.end(), [&](const SPlayerClothing& clothing) { - return !stricmp(texture, clothing.texture.c_str()) && !stricmp(model, clothing.model.c_str()); - })) + if (std::any_of(clothes.begin(), clothes.end(), [&](const SPlayerClothing& clothing) + { return !stricmp(texture, clothing.texture.c_str()) && !stricmp(model, clothing.model.c_str()); })) { return false; } @@ -437,9 +569,8 @@ bool CClientPlayerClothes::RemoveClothingModel(const char* texture, const char* auto& clothes = m_NewClothes[clothingType]; - auto it = std::find_if(clothes.begin(), clothes.end(),[&](const SPlayerClothing& clothing) { - return !stricmp(texture, clothing.texture.c_str()) && !stricmp(model, clothing.model.c_str()); - }); + auto it = std::find_if(clothes.begin(), clothes.end(), [&](const SPlayerClothing& clothing) + { return !stricmp(texture, clothing.texture.c_str()) && !stricmp(model, clothing.model.c_str()); }); if (it == clothes.end()) return false; @@ -462,49 +593,49 @@ void CClientPlayerClothes::RefreshClothes() { for (std::uint8_t clothingType = 0; clothingType < PLAYER_CLOTHING_SLOTS; clothingType++) { - auto& clothes = m_NewClothes[clothingType]; + auto& clothes = m_NewClothes[clothingType]; - if (clothes.empty() && !m_bHasClothesChanged) - continue; + if (clothes.empty() && !m_bHasClothesChanged) + continue; - bool hasInvalidClothing = false; - const SPlayerClothing* pCurrent = m_Clothes[clothingType]; + bool hasInvalidClothing = false; + const SPlayerClothing* pCurrent = m_Clothes[clothingType]; - if (!m_bHasClothesChanged) - { - for (auto clothing = clothes.begin(); clothing != clothes.end();) - { - std::string fileTXD = clothing->texture + ".txd"; - std::string fileDFF = clothing->model + ".dff"; + if (!m_bHasClothesChanged) + { + for (auto clothing = clothes.begin(); clothing != clothes.end();) + { + std::string fileTXD = clothing->texture + ".txd"; + std::string fileDFF = clothing->model + ".dff"; - if (!g_pGame->GetRenderWare()->HasClothesFile(fileTXD.c_str()) || !g_pGame->GetRenderWare()->HasClothesFile(fileDFF.c_str())) - { - if (pCurrent && (pCurrent->texture == clothing->texture || pCurrent->model == clothing->model)) - { + if (!g_pGame->GetRenderWare()->HasClothesFile(fileTXD.c_str()) || !g_pGame->GetRenderWare()->HasClothesFile(fileDFF.c_str())) + { + if (pCurrent && (pCurrent->texture == clothing->texture || pCurrent->model == clothing->model)) + { hasInvalidClothing = true; - } - - clothing = clothes.erase(clothing); - } - else - ++clothing; - } - } - - if (pCurrent && !hasInvalidClothing && m_bHasClothesChanged) - { - const SPlayerClothing* pClothing = GetClothing(pCurrent->texture.c_str(), pCurrent->model.c_str(), clothingType); - - if (!pClothing) - { - hasInvalidClothing = true; - } - } - - if (hasInvalidClothing) - { - RemoveClothes(clothingType, true); - } + } + + clothing = clothes.erase(clothing); + } + else + ++clothing; + } + } + + if (pCurrent && !hasInvalidClothing && m_bHasClothesChanged) + { + const SPlayerClothing* pClothing = GetClothing(pCurrent->texture.c_str(), pCurrent->model.c_str(), clothingType); + + if (!pClothing) + { + hasInvalidClothing = true; + } + } + + if (hasInvalidClothing) + { + RemoveClothes(clothingType, true); + } } m_bHasClothesChanged = false; diff --git a/Client/mods/deathmatch/logic/CClientPlayerClothes.h b/Client/mods/deathmatch/logic/CClientPlayerClothes.h index f01e3433fba..0f8e8e8ce6f 100644 --- a/Client/mods/deathmatch/logic/CClientPlayerClothes.h +++ b/Client/mods/deathmatch/logic/CClientPlayerClothes.h @@ -12,25 +12,25 @@ class CClientPlayerClothes; #pragma once -#define PLAYER_CLOTHING_SLOTS 18 -#define TORSO_CLOTHING_MAX 68 -#define HAIR_CLOTHING_MAX 33 -#define LEGS_CLOTHING_MAX 45 -#define SHOES_CLOTHING_MAX 38 -#define LEFT_UPPER_ARM_CLOTHING_MAX 3 -#define LEFT_LOWER_ARM_CLOTHING_MAX 4 +#define PLAYER_CLOTHING_SLOTS 18 +#define TORSO_CLOTHING_MAX 68 +#define HAIR_CLOTHING_MAX 33 +#define LEGS_CLOTHING_MAX 45 +#define SHOES_CLOTHING_MAX 38 +#define LEFT_UPPER_ARM_CLOTHING_MAX 3 +#define LEFT_LOWER_ARM_CLOTHING_MAX 4 #define RIGHT_UPPER_ARM_CLOTHING_MAX 4 #define RIGHT_LOWER_ARM_CLOTHING_MAX 4 -#define BACK_TOP_CLOTHING_MAX 7 -#define LEFT_CHEST_CLOTHING_MAX 6 -#define RIGHT_CHEST_CLOTHING_MAX 7 -#define STOMACH_CLOTHING_MAX 7 -#define LOWER_BACK_CLOTHING_MAX 6 -#define EXTRA1_CLOTHING_MAX 12 -#define EXTRA2_CLOTHING_MAX 12 -#define EXTRA3_CLOTHING_MAX 17 -#define EXTRA4_CLOTHING_MAX 57 -#define SUIT_CLOTHING_MAX 9 +#define BACK_TOP_CLOTHING_MAX 7 +#define LEFT_CHEST_CLOTHING_MAX 6 +#define RIGHT_CHEST_CLOTHING_MAX 7 +#define STOMACH_CLOTHING_MAX 7 +#define LOWER_BACK_CLOTHING_MAX 6 +#define EXTRA1_CLOTHING_MAX 12 +#define EXTRA2_CLOTHING_MAX 12 +#define EXTRA3_CLOTHING_MAX 17 +#define EXTRA4_CLOTHING_MAX 57 +#define SUIT_CLOTHING_MAX 9 class CClientPed; @@ -67,11 +67,11 @@ class CClientPlayerClothes static bool IsEmptyClothing(const SPlayerClothing* pClothing, unsigned char ucType); static const char* GetClothingName(unsigned char ucType); - static std::vector GetClothingGroup(unsigned char ucType); - static bool IsValidModel(unsigned short usModel); - static bool HasClothesChanged(); - static bool AddClothingModel(const char* texture, const char* model, unsigned char clothingType); - static bool RemoveClothingModel(const char* texture, const char* model, unsigned char clothingType); + static std::vector GetClothingGroup(unsigned char ucType); + static bool IsValidModel(unsigned short usModel); + static bool HasClothesChanged(); + static bool AddClothingModel(const char* texture, const char* model, unsigned char clothingType); + static bool RemoveClothingModel(const char* texture, const char* model, unsigned char clothingType); private: static const SPlayerClothing* GetClothing(const char* szTexture, const char* szModel, unsigned char ucType); diff --git a/Client/mods/deathmatch/logic/CClientPlayerVoice.cpp b/Client/mods/deathmatch/logic/CClientPlayerVoice.cpp index f7d5e4e17ab..f4241200c5b 100644 --- a/Client/mods/deathmatch/logic/CClientPlayerVoice.cpp +++ b/Client/mods/deathmatch/logic/CClientPlayerVoice.cpp @@ -446,14 +446,14 @@ void CClientPlayerVoice::SetPaused(bool bPaused) { // call onClientPlayerVoicePause CLuaArguments Arguments; - Arguments.PushString("paused"); // Reason + Arguments.PushString("paused"); // Reason m_pPlayer->CallEvent("onClientPlayerVoicePause", Arguments, false); } else { // call onClientPlayerVoiceResumed CLuaArguments Arguments; - Arguments.PushString("resumed"); // Reason + Arguments.PushString("resumed"); // Reason m_pPlayer->CallEvent("onClientPlayerVoiceResumed", Arguments, false); } } diff --git a/Client/mods/deathmatch/logic/CClientPlayerVoice.h b/Client/mods/deathmatch/logic/CClientPlayerVoice.h index bd5bf872d56..092958b27ad 100644 --- a/Client/mods/deathmatch/logic/CClientPlayerVoice.h +++ b/Client/mods/deathmatch/logic/CClientPlayerVoice.h @@ -34,7 +34,7 @@ class CClientPlayerVoice bool m_bVoiceActive; std::list m_EventQueue; - std::mutex m_Mutex; // Only for m_EventQueue and m_bVoiceActive + std::mutex m_Mutex; // Only for m_EventQueue and m_bVoiceActive void GetTempoValues(float& fSampleRate, float& fTempo, float& fPitch, bool& bReverse) { diff --git a/Client/mods/deathmatch/logic/CClientRadarArea.cpp b/Client/mods/deathmatch/logic/CClientRadarArea.cpp index 903ccc49927..0c958ab1947 100644 --- a/Client/mods/deathmatch/logic/CClientRadarArea.cpp +++ b/Client/mods/deathmatch/logic/CClientRadarArea.cpp @@ -48,7 +48,7 @@ void CClientRadarArea::DoPulse() void CClientRadarArea::DoPulse(bool bRender) { - #define RADAR_FLASH_CYCLETIME 1000 +#define RADAR_FLASH_CYCLETIME 1000 // Suppose to show? if (m_bStreamedIn) diff --git a/Client/mods/deathmatch/logic/CClientRadarMarkerManager.cpp b/Client/mods/deathmatch/logic/CClientRadarMarkerManager.cpp index d7273e96a01..e7f00c96cf0 100644 --- a/Client/mods/deathmatch/logic/CClientRadarMarkerManager.cpp +++ b/Client/mods/deathmatch/logic/CClientRadarMarkerManager.cpp @@ -120,4 +120,4 @@ void CClientRadarMarkerManager::OrderMarkers() bool CClientRadarMarkerManager::CompareOrderingIndex(CClientRadarMarker* p1, CClientRadarMarker* p2) { return p1->GetOrdering() < p2->GetOrdering(); -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CClientSearchLight.h b/Client/mods/deathmatch/logic/CClientSearchLight.h index 1550aacc750..2e2521ae04f 100644 --- a/Client/mods/deathmatch/logic/CClientSearchLight.h +++ b/Client/mods/deathmatch/logic/CClientSearchLight.h @@ -25,7 +25,7 @@ class CClientSearchLight final : public CClientStreamElement eClientEntityType GetType() const { return CCLIENTSEARCHLIGHT; } // CClientEntity methods - virtual void GetPosition(CVector& vecPosition) const override { vecPosition = m_StartPosition; } // required for streaming + virtual void GetPosition(CVector& vecPosition) const override { vecPosition = m_StartPosition; } // required for streaming virtual void SetPosition(const CVector& vecPosition) override {} // CClientStreamElement methods diff --git a/Client/mods/deathmatch/logic/CClientSound.cpp b/Client/mods/deathmatch/logic/CClientSound.cpp index 1f722769ce6..2e3c3174be0 100644 --- a/Client/mods/deathmatch/logic/CClientSound.cpp +++ b/Client/mods/deathmatch/logic/CClientSound.cpp @@ -388,7 +388,7 @@ double CClientSound::GetLength(bool bAvoidLoad) { // Not loaded by this entity yet -#if 0 // TODO +#if 0 // TODO if ( bAvoidLoad ) { // Caller wants to avoid loading the file to find out the length, @@ -508,14 +508,14 @@ void CClientSound::SetPaused(bool bPaused) { // call onClientSoundStopped CLuaArguments Arguments; - Arguments.PushString("paused"); // Reason + Arguments.PushString("paused"); // Reason this->CallEvent("onClientSoundStopped", Arguments, false); } else { // call onClientSoundStarted CLuaArguments Arguments; - Arguments.PushString("resumed"); // Reason + Arguments.PushString("resumed"); // Reason this->CallEvent("onClientSoundStarted", Arguments, false); } } @@ -756,7 +756,7 @@ void CClientSound::Process3D(const CVector& vecPlayerPosition, const CVector& ve if (Create()) { CLuaArguments Arguments; - Arguments.PushString("enabled"); // Reason + Arguments.PushString("enabled"); // Reason CallEvent("onClientSoundStarted", Arguments, false); } } @@ -766,7 +766,7 @@ void CClientSound::Process3D(const CVector& vecPlayerPosition, const CVector& ve { Destroy(); CLuaArguments Arguments; - Arguments.PushString("disabled"); // Reason + Arguments.PushString("disabled"); // Reason CallEvent("onClientSoundStopped", Arguments, false); } } diff --git a/Client/mods/deathmatch/logic/CClientSound.h b/Client/mods/deathmatch/logic/CClientSound.h index 7dfcd32ebec..db7843a850c 100644 --- a/Client/mods/deathmatch/logic/CClientSound.h +++ b/Client/mods/deathmatch/logic/CClientSound.h @@ -89,7 +89,7 @@ class CClientSound final : public CClientEntity bool SetFxEffectParameters(uint uiFxEffect, void* params); bool GetFxEffectParameters(uint uiFxEffect, void* params); - void Unlink(){}; + void Unlink() {}; bool IsSoundStopped() { return m_pAudio == NULL; } bool IsFinished(); diff --git a/Client/mods/deathmatch/logic/CClientSoundManager.cpp b/Client/mods/deathmatch/logic/CClientSoundManager.cpp index 043beadd580..3f8c42d8a0c 100644 --- a/Client/mods/deathmatch/logic/CClientSoundManager.cpp +++ b/Client/mods/deathmatch/logic/CClientSoundManager.cpp @@ -42,7 +42,7 @@ CClientSoundManager::CClientSoundManager(CClientManager* pClientManager) g_pCore->GetConsole()->Printf("BASS ERROR %d in PluginLoad WEBM", BASS_ErrorGetCode()); BASS_SetConfig(BASS_CONFIG_NET_PREBUF, 0); - BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST, 1); // Allow playlists + BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST, 1); // Allow playlists BASS_SetConfig(BASS_CONFIG_NET_TIMEOUT, 15000); m_strUserAgent = SString("MTA:SA Server %s - See http://mtasa.com/agent/", g_pNet->GetConnectedServer(true)); @@ -70,15 +70,15 @@ CClientSoundManager::CClientSoundManager(CClientManager* pClientManager) CClientSoundManager::~CClientSoundManager() { ProcessStopQueues(true); - + // Signal stream threads to exit as soon as their blocking call returns SignalStreamingThreadsToStop(); - + // Stopping and freeing BASS should lead any pending BASS_StreamCreateURL to abort/return. // This makes threads exit quickly BASS_Stop(); BASS_Free(); - + // Now wait for threads to finish - they should exit almost immediately since BASS was freed. // Use a short timeout since the blocking call should have been interrupted. WaitForAllStreamingThreads(3000); @@ -123,7 +123,7 @@ void CClientSoundManager::DoPulse() { // call onClientSoundStopped CLuaArguments Arguments; - Arguments.PushString("finished"); // Reason + Arguments.PushString("finished"); // Reason pSound->CallEvent("onClientSoundStopped", Arguments, false); g_pClientGame->GetElementDeleter()->Delete(pSound); } @@ -444,7 +444,7 @@ void CClientSoundManager::ProcessStopQueues(bool bFlush) { if (iter->second.Get() > 100 || bFlush) { - delete iter->first; // This will cause BASS_ChannelStop + delete iter->first; // This will cause BASS_ChannelStop m_AudioStopQueue.erase(iter++); } else diff --git a/Client/mods/deathmatch/logic/CClientSpatialDatabase.cpp b/Client/mods/deathmatch/logic/CClientSpatialDatabase.cpp index 1babdac2769..844725fdce3 100644 --- a/Client/mods/deathmatch/logic/CClientSpatialDatabase.cpp +++ b/Client/mods/deathmatch/logic/CClientSpatialDatabase.cpp @@ -209,7 +209,7 @@ bool CClientSpatialDatabaseImpl::IsValidSphere(const CSphere& sphere) return false; // Check radius within limits - if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) + if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) return false; // Check position within limits diff --git a/Client/mods/deathmatch/logic/CClientSpatialDatabase.h b/Client/mods/deathmatch/logic/CClientSpatialDatabase.h index 053e3af2c26..60171ba5b10 100644 --- a/Client/mods/deathmatch/logic/CClientSpatialDatabase.h +++ b/Client/mods/deathmatch/logic/CClientSpatialDatabase.h @@ -13,7 +13,7 @@ class CClientEntity; #pragma once // Bounding sphere z position for 2d objects -#define SPATIAL_2D_Z 0 +#define SPATIAL_2D_Z 0 // Result of a Query class CClientEntityResult : public std::vector diff --git a/Client/mods/deathmatch/logic/CClientStreamElement.h b/Client/mods/deathmatch/logic/CClientStreamElement.h index eb3ae101d17..90f96b1e900 100644 --- a/Client/mods/deathmatch/logic/CClientStreamElement.h +++ b/Client/mods/deathmatch/logic/CClientStreamElement.h @@ -53,7 +53,7 @@ class CClientStreamElement : public CClientEntity void SetStreamRow(CClientStreamSectorRow* pRow) { m_pStreamRow = pRow; } void SetStreamSector(CClientStreamSector* pSector) { m_pStreamSector = pSector; } void SetExpDistance(float fDistance) { m_fExpDistance = fDistance; } - + CClientStreamSectorRow* m_pStreamRow; CClientStreamSector* m_pStreamSector; CVector m_vecStreamPosition; @@ -61,9 +61,9 @@ class CClientStreamElement : public CClientEntity unsigned short m_usStreamReferences, m_usStreamReferencesScript; protected: - CClientStreamer* m_pStreamer; - bool m_bStreamedIn; - bool m_bAttemptingToStreamIn; + CClientStreamer* m_pStreamer; + bool m_bStreamedIn; + bool m_bAttemptingToStreamIn; public: float m_fCachedRadius; diff --git a/Client/mods/deathmatch/logic/CClientStreamSector.cpp b/Client/mods/deathmatch/logic/CClientStreamSector.cpp index 39a2f38c7b1..17ffed9964e 100644 --- a/Client/mods/deathmatch/logic/CClientStreamSector.cpp +++ b/Client/mods/deathmatch/logic/CClientStreamSector.cpp @@ -157,4 +157,4 @@ void CClientStreamSector::RemoveElements(list* pList) { pList->remove(*iter); } -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CClientStreamSectorRow.cpp b/Client/mods/deathmatch/logic/CClientStreamSectorRow.cpp index bf74f0debc8..31c92de1e46 100644 --- a/Client/mods/deathmatch/logic/CClientStreamSectorRow.cpp +++ b/Client/mods/deathmatch/logic/CClientStreamSectorRow.cpp @@ -133,4 +133,4 @@ void CClientStreamSectorRow::ConnectSector(CClientStreamSector* pSector) pSector->m_pTop->m_pBottom = pSector; if (pSector->m_pBottom) pSector->m_pBottom->m_pTop = pSector; -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CClientStreamSectorRow.h b/Client/mods/deathmatch/logic/CClientStreamSectorRow.h index 0fa26750fa4..024f44906a3 100644 --- a/Client/mods/deathmatch/logic/CClientStreamSectorRow.h +++ b/Client/mods/deathmatch/logic/CClientStreamSectorRow.h @@ -10,7 +10,7 @@ #pragma once -#define WORLD_SIZE 6000.0f // was 3000.0f +#define WORLD_SIZE 6000.0f // was 3000.0f #include "CClientCommon.h" #include diff --git a/Client/mods/deathmatch/logic/CClientStreamer.cpp b/Client/mods/deathmatch/logic/CClientStreamer.cpp index dacb77fa851..914c2661995 100644 --- a/Client/mods/deathmatch/logic/CClientStreamer.cpp +++ b/Client/mods/deathmatch/logic/CClientStreamer.cpp @@ -552,7 +552,7 @@ void CClientStreamer::Restream(bool bMovedFar) if (bReachedLimit) { // Add to the list that might be streamed in during the final phase - if ((int)ClosestStreamedOutList.size() < iMaxIn) // (only add if there is a chance it will be used) + if ((int)ClosestStreamedOutList.size() < iMaxIn) // (only add if there is a chance it will be used) ClosestStreamedOutList.push_back(pElement); } else @@ -606,7 +606,7 @@ void CClientStreamer::Restream(bool bMovedFar) iMaxOut--; } m_ToStreamOut.remove(pFurthestStreamedIn); - iFurthestStreamedInIndex--; // Always advance to the next candidate + iFurthestStreamedInIndex--; // Always advance to the next candidate // Stream in ClosestStreamedOut candidate if possible if (!ReachedLimit()) diff --git a/Client/mods/deathmatch/logic/CClientStreamer.h b/Client/mods/deathmatch/logic/CClientStreamer.h index 9e81fedbdfe..b233cf23cb4 100644 --- a/Client/mods/deathmatch/logic/CClientStreamer.h +++ b/Client/mods/deathmatch/logic/CClientStreamer.h @@ -35,7 +35,7 @@ class CClientStreamer std::list::iterator ActiveElementsBegin() { return m_ActiveElements.begin(); } std::list::iterator ActiveElementsEnd() { return m_ActiveElements.end(); } - std::uint16_t GetDimension() const noexcept { return m_usDimension; } + std::uint16_t GetDimension() const noexcept { return m_usDimension; } private: void CreateSectors(std::list* pList, CVector2D& vecSize, CVector2D& vecBottomLeft, CVector2D& vecTopRight); diff --git a/Client/mods/deathmatch/logic/CClientTXD.cpp b/Client/mods/deathmatch/logic/CClientTXD.cpp index a6de9d1ae42..e32c422b999 100644 --- a/Client/mods/deathmatch/logic/CClientTXD.cpp +++ b/Client/mods/deathmatch/logic/CClientTXD.cpp @@ -165,7 +165,8 @@ bool CClientTXD::Import(unsigned short usModelID) return false; } - if (!g_pGame->GetRenderWare()->ModelInfoTXDLoadTextures(&m_ReplacementTextures, strUseFilename, SString(), m_bFilteringEnabled, &m_strLastError)) + if (!g_pGame->GetRenderWare()->ModelInfoTXDLoadTextures(&m_ReplacementTextures, strUseFilename, SString(), m_bFilteringEnabled, + &m_strLastError)) { if (m_strLastError.empty()) m_strLastError = SString("Failed to load textures for model %d: %s", usModelID, ExtractFilename(strUseFilename).c_str()); @@ -283,11 +284,11 @@ bool CClientTXD::GetFilenameToUse(SString& strOutFilename) CDownloadableResource* pResFile = nullptr; bool bChecksumAlreadyValidated = false; - static const CChecksum zeroChecksum; + static const CChecksum zeroChecksum; - CChecksum serverChecksum; - bool bServerHasChecksum = false; - long long cachedFileSize = -1; + CChecksum serverChecksum; + bool bServerHasChecksum = false; + long long cachedFileSize = -1; if (g_pClientGame) { @@ -318,7 +319,8 @@ bool CClientTXD::GetFilenameToUse(SString& strOutFilename) } if (cachedFileSize != expectedSize) { - m_strLastError = SString("Download incomplete: %s (got %lld of %lld bytes)", ExtractFilename(m_strFilename).c_str(), cachedFileSize, expectedSize); + m_strLastError = + SString("Download incomplete: %s (got %lld of %lld bytes)", ExtractFilename(m_strFilename).c_str(), cachedFileSize, expectedSize); return false; } } @@ -357,7 +359,7 @@ bool CClientTXD::GetFilenameToUse(SString& strOutFilename) if (pResFile) { const long long expectedSize = static_cast(pResFile->GetDownloadSize()); - + // Cache file size for reuse (also used in RightSizeTxd logging) if (cachedFileSize < 0) cachedFileSize = static_cast(FileSize(m_strFilename)); @@ -448,8 +450,8 @@ bool CClientTXD::GetFilenameToUse(SString& strOutFilename) FileAppend(strShrunkFilename, GenerateSha256HexStringFromFile(strShrunkFilename)); // Use cached file size if available, otherwise compute it const long long originalSizeKB = (cachedFileSize >= 0 ? cachedFileSize : FileSize(m_strFilename)) / 1024; - AddReportLog(9400, SString("RightSized %s(%s) from %d KB => %d KB", *ExtractFilename(m_strFilename), *strLargeSha256.Left(8), - (uint)originalSizeKB, (uint)(FileSize(strShrunkFilename) / 1024))); + AddReportLog(9400, SString("RightSized %s(%s) from %d KB => %d KB", *ExtractFilename(m_strFilename), *strLargeSha256.Left(8), (uint)originalSizeKB, + (uint)(FileSize(strShrunkFilename) / 1024))); } else { diff --git a/Client/mods/deathmatch/logic/CClientTXD.h b/Client/mods/deathmatch/logic/CClientTXD.h index 6a0f3612b17..e9f5625b08c 100644 --- a/Client/mods/deathmatch/logic/CClientTXD.h +++ b/Client/mods/deathmatch/logic/CClientTXD.h @@ -21,9 +21,9 @@ class CClientTXD final : public CClientEntity CClientTXD(class CClientManager* pManager, ElementID ID); ~CClientTXD(); - void Unlink(){}; + void Unlink() {}; void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; eClientEntityType GetType() const { return CCLIENTTXD; } bool Load(bool isRaw, SString input, bool enableFiltering); diff --git a/Client/mods/deathmatch/logic/CClientTask.cpp b/Client/mods/deathmatch/logic/CClientTask.cpp index 4aadf7a76c1..3dec9c9ae07 100644 --- a/Client/mods/deathmatch/logic/CClientTask.cpp +++ b/Client/mods/deathmatch/logic/CClientTask.cpp @@ -21,8 +21,8 @@ using std::list; unsigned long CClientTask::m_ulLastUniqueIdentifier = 0; // Temporary until we start using ids -#define VERIFY_PLAYER(player) (m_pManager->GetPlayerManager ()->Exists(player)&&!player->IsBeingDeleted()) -#define VERIFY_VEHICLE(vehicle) (m_pManager->GetVehicleManager ()->Exists(vehicle)&&!vehicle->IsBeingDeleted()) +#define VERIFY_PLAYER(player) (m_pManager->GetPlayerManager()->Exists(player) && !player->IsBeingDeleted()) +#define VERIFY_VEHICLE(vehicle) (m_pManager->GetVehicleManager()->Exists(vehicle) && !vehicle->IsBeingDeleted()) CClientTask::CClientTask(CClientManager* pManager) { @@ -617,8 +617,8 @@ CTask* CClientTask::CreateTask(bool& bTaskPrimary, int& iTaskPriority) iTaskPriority = TASK_PRIORITY_PRIMARY; // Create the task - return g_pGame->GetTasks()->CreateTaskSimpleClimb(NULL, vecTarget, fHeading, static_cast(fSurfaceType), static_cast(fClimbStage), - bForceClimb); + return g_pGame->GetTasks()->CreateTaskSimpleClimb(NULL, vecTarget, fHeading, static_cast(fSurfaceType), + static_cast(fClimbStage), bForceClimb); } // Choking task? diff --git a/Client/mods/deathmatch/logic/CClientTeam.h b/Client/mods/deathmatch/logic/CClientTeam.h index 11e5dc71e15..6b1d51f4ed8 100644 --- a/Client/mods/deathmatch/logic/CClientTeam.h +++ b/Client/mods/deathmatch/logic/CClientTeam.h @@ -41,9 +41,9 @@ class CClientTeam final : public CClientEntity bool GetFriendlyFire() { return m_bFriendlyFire; } void SetFriendlyFire(bool bFriendlyFire) { m_bFriendlyFire = bFriendlyFire; } - void AddPlayer(CClientPlayer* pPlayer, bool bChangePlayer = false); - void RemovePlayer(CClientPlayer* pPlayer, bool bChangePlayer = false); - void RemoveAll(); + void AddPlayer(CClientPlayer* pPlayer, bool bChangePlayer = false); + void RemovePlayer(CClientPlayer* pPlayer, bool bChangePlayer = false); + void RemoveAll(); std::vector GetPlayers() const; bool Exists(CClientPlayer* pPlayer); diff --git a/Client/mods/deathmatch/logic/CClientVectorGraphic.cpp b/Client/mods/deathmatch/logic/CClientVectorGraphic.cpp index f5d09b086ed..bd3e35ce96e 100644 --- a/Client/mods/deathmatch/logic/CClientVectorGraphic.cpp +++ b/Client/mods/deathmatch/logic/CClientVectorGraphic.cpp @@ -59,8 +59,7 @@ namespace bool StyleContainsExternalReference(const std::string& styleValue) { SString styleLower = SString(styleValue).ToLower(); - return styleLower.find("url(") != std::string::npos || - styleLower.find("@import") != std::string::npos; + return styleLower.find("url(") != std::string::npos || styleLower.find("@import") != std::string::npos; } bool AttributeContainsExternalUrl(const std::string& value) @@ -73,8 +72,7 @@ namespace size_t start = urlPos + 4; - while (start < valueLower.length() && - (valueLower[start] == ' ' || valueLower[start] == '"' || valueLower[start] == '\'')) + while (start < valueLower.length() && (valueLower[start] == ' ' || valueLower[start] == '"' || valueLower[start] == '\'')) start++; if (start >= valueLower.length()) @@ -292,7 +290,7 @@ void CClientVectorGraphic::OnUpdate() if (std::holds_alternative(m_updateCallbackRef)) { auto& func = std::get(m_updateCallbackRef); - auto state = func.GetLuaVM(); + auto state = func.GetLuaVM(); if (VERIFY_FUNCTION(func) && state != NULL) { diff --git a/Client/mods/deathmatch/logic/CClientVectorGraphicDisplay.cpp b/Client/mods/deathmatch/logic/CClientVectorGraphicDisplay.cpp index 29c08ebe045..fc80c9ee83d 100644 --- a/Client/mods/deathmatch/logic/CClientVectorGraphicDisplay.cpp +++ b/Client/mods/deathmatch/logic/CClientVectorGraphicDisplay.cpp @@ -13,8 +13,7 @@ using namespace lunasvg; -CClientVectorGraphicDisplay::CClientVectorGraphicDisplay(CClientVectorGraphic* pVectorGraphic, int ID) - : CClientDisplay(ID) +CClientVectorGraphicDisplay::CClientVectorGraphicDisplay(CClientVectorGraphic* pVectorGraphic, int ID) : CClientDisplay(ID) { m_pVectorGraphic = pVectorGraphic; m_bVisible = true; diff --git a/Client/mods/deathmatch/logic/CClientVehicle.cpp b/Client/mods/deathmatch/logic/CClientVehicle.cpp index a892924d6e4..7fae5985acd 100644 --- a/Client/mods/deathmatch/logic/CClientVehicle.cpp +++ b/Client/mods/deathmatch/logic/CClientVehicle.cpp @@ -28,12 +28,12 @@ extern CClientGame* g_pClientGame; std::set ms_AttachedVehiclesToIgnore; // To hide the ugly "pointer truncation from DWORD* to unsigned long warning -#pragma warning(disable:4311) +#pragma warning(disable : 4311) // Maximum distance between current position and target position (for interpolation) // before we disable interpolation and warp to the position instead -#define VEHICLE_INTERPOLATION_WARP_THRESHOLD 15 -#define VEHICLE_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED 10 +#define VEHICLE_INTERPOLATION_WARP_THRESHOLD 15 +#define VEHICLE_INTERPOLATION_WARP_THRESHOLD_FOR_SPEED 10 CClientVehicle::CClientVehicle(CClientManager* pManager, ElementID ID, unsigned short usModel, unsigned char ucVariation, unsigned char ucVariation2) : ClassInit(this), CClientStreamElement(pManager->GetVehicleStreamer(), ID) @@ -1475,8 +1475,9 @@ void CClientVehicle::SetWheelStatus(unsigned char ucWheel, unsigned char ucStatu m_pVehicle->GetDamageManager()->SetWheelStatus((eWheelPosition)(ucWheel), ucGTAStatus); // Update the wheel's visibility - m_pVehicle->SetWheelVisibility((eWheelPosition)ucWheel, ucStatus != DT_WHEEL_MISSING && - (m_ComponentData.empty() || m_ComponentData[GetComponentNameForWheel(ucWheel)].m_bVisible)); + m_pVehicle->SetWheelVisibility( + (eWheelPosition)ucWheel, + ucStatus != DT_WHEEL_MISSING && (m_ComponentData.empty() || m_ComponentData[GetComponentNameForWheel(ucWheel)].m_bVisible)); } else if (m_eVehicleType == CLIENTVEHICLE_BIKE && ucWheel < 2) m_pVehicle->SetBikeWheelStatus(ucWheel, ucGTAStatus); @@ -2309,7 +2310,7 @@ void CClientVehicle::StreamedInPulse() // Check if we need to update the train position (because of streaming) CVector vecPosition; - float fCarriageDistance = 20.0f; // approximately || Todo: Find proper distance + float fCarriageDistance = 20.0f; // approximately || Todo: Find proper distance if (GetTrainDirection()) fCarriageDistance = -fCarriageDistance; @@ -2472,8 +2473,8 @@ bool CClientVehicle::DoCheckHasLandingGear() { auto model = static_cast(m_usModel); - return (model == VehicleType::VT_ANDROM || model == VehicleType::VT_AT400 || model == VehicleType::VT_NEVADA || model == VehicleType::VT_RUSTLER || model == VehicleType::VT_SHAMAL || model == VehicleType::VT_HYDRA || - model == VehicleType::VT_STUNT); + return (model == VehicleType::VT_ANDROM || model == VehicleType::VT_AT400 || model == VehicleType::VT_NEVADA || model == VehicleType::VT_RUSTLER || + model == VehicleType::VT_SHAMAL || model == VehicleType::VT_HYDRA || model == VehicleType::VT_STUNT); } void CClientVehicle::Create() @@ -2481,9 +2482,9 @@ void CClientVehicle::Create() // If the vehicle doesn't exist if (!m_pVehicle) { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG g_pCore->GetConsole()->Printf("CClientVehicle::Create %d", GetModel()); - #endif +#endif // Check again that the limit isn't reached. We are required to do so because // we load async. The streamer isn't always aware of our limits. @@ -2880,7 +2881,7 @@ void CClientVehicle::Create() } m_ComponentVisibilityBackup.clear(); } - + // Grab our component data std::map::iterator iter = m_ComponentData.begin(); // Loop through our component data @@ -2954,9 +2955,9 @@ void CClientVehicle::Destroy() // If the vehicle exists if (m_pVehicle) { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG g_pCore->GetConsole()->Printf("CClientVehicle::Destroy %d", GetModel()); - #endif +#endif // Invalidate m_pManager->InvalidateEntity(this); @@ -3325,7 +3326,7 @@ bool CClientVehicle::InternalSetTowLink(CClientVehicle* pTrailer) // SA can attach the trailer now pGameVehicle->SetTowLink(m_pVehicle); - pTrailer->PlaceProperlyOnGround(); // Probably not needed + pTrailer->PlaceProperlyOnGround(); // Probably not needed return true; } @@ -3337,7 +3338,7 @@ bool CClientVehicle::IsTowableBy(CClientVehicle* towingVehicle) bool CClientVehicle::SetWinchType(eWinchType winchType) { - if (static_cast(GetModel()) == VehicleType::VT_LEVIATHN) // Leviathan + if (static_cast(GetModel()) == VehicleType::VT_LEVIATHN) // Leviathan { if (m_pVehicle) { @@ -3929,18 +3930,17 @@ bool CClientVehicle::IsEnterable(bool localEntity) { if (!m_pVehicle) return false; - + // Server vehicle? if (IsLocalEntity() != localEntity) return false; - + if (GetHealth() <= 0.0f) return false; - - return !IsInWater() || (GetVehicleType() == CLIENTVEHICLE_BOAT - || m_usModel == 447 /* sea sparrow */ - || m_usModel == 417 /* levithan */ - || m_usModel == 460 /* skimmer */); + + return !IsInWater() || (GetVehicleType() == CLIENTVEHICLE_BOAT || m_usModel == 447 /* sea sparrow */ + || m_usModel == 417 /* levithan */ + || m_usModel == 460 /* skimmer */); } bool CClientVehicle::HasRadio() @@ -4017,11 +4017,15 @@ void CClientVehicle::SetHeadLightColor(const SColor color) // #if OCCUPY_DEBUG_INFO - #define INFO(x) g_pCore->GetConsole ()->Printf x - #define WARN(x) g_pCore->GetConsole ()->Printf x + #define INFO(x) g_pCore->GetConsole()->Printf x + #define WARN(x) g_pCore->GetConsole()->Printf x #else - #define INFO(x) {} - #define WARN(x) {} + #define INFO(x) \ + { \ + } + #define WARN(x) \ + { \ + } #endif std::string GetPlayerName(CClientPed* pClientPed) @@ -4391,9 +4395,9 @@ void CClientVehicle::HandleWaitingForGroundToLoad() { // If not near any MTA objects, then don't bother waiting SetFrozenWaitingForGroundToLoad(false, true); - #ifdef ASYNC_LOADING_DEBUG_OUTPUTA +#ifdef ASYNC_LOADING_DEBUG_OUTPUTA OutputDebugLine("[AsyncLoading] FreezeUntilCollisionLoaded - Early stop"); - #endif +#endif return; } @@ -4417,29 +4421,29 @@ void CClientVehicle::HandleWaitingForGroundToLoad() bool bASync = g_pGame->IsASyncLoadingEnabled(); bool bMTAObjLimit = pObjectManager->IsObjectLimitReached(); bool bHasModel = GetModelInfo() != NULL; - #ifndef ASYNC_LOADING_DEBUG_OUTPUTA +#ifndef ASYNC_LOADING_DEBUG_OUTPUTA bool bMTALoaded = pObjectManager->ObjectsAroundPointLoaded(vecPosition, fUseRadius, m_usDimension); - #else +#else SString strAround; bool bMTALoaded = pObjectManager->ObjectsAroundPointLoaded(vecPosition, fUseRadius, m_usDimension, &strAround); - #endif +#endif - #ifdef ASYNC_LOADING_DEBUG_OUTPUTA +#ifdef ASYNC_LOADING_DEBUG_OUTPUTA SString status = SString( "%2.2f,%2.2f,%2.2f bASync:%d bHasModel:%d bMTALoaded:%d bMTAObjLimit:%d m_fGroundCheckTolerance:%2.2f m_fObjectsAroundTolerance:%2.2f " "fUseRadius:%2.1f", vecPosition.fX, vecPosition.fY, vecPosition.fZ, bASync, bHasModel, bMTALoaded, bMTAObjLimit, m_fGroundCheckTolerance, m_fObjectsAroundTolerance, fUseRadius); - #endif +#endif // See if ground is ready if ((!bHasModel || !bMTALoaded) && m_fObjectsAroundTolerance < 1.f) { m_fGroundCheckTolerance = 0.f; m_fObjectsAroundTolerance = std::min(1.f, m_fObjectsAroundTolerance + 0.01f); - #ifdef ASYNC_LOADING_DEBUG_OUTPUTA +#ifdef ASYNC_LOADING_DEBUG_OUTPUTA status += (" FreezeUntilCollisionLoaded - wait"); - #endif +#endif } else { @@ -4452,16 +4456,16 @@ void CClientVehicle::HandleWaitingForGroundToLoad() if (fUseDist > -0.2f && fUseDist < 1.5f) SetFrozenWaitingForGroundToLoad(false, true); - #ifdef ASYNC_LOADING_DEBUG_OUTPUTA +#ifdef ASYNC_LOADING_DEBUG_OUTPUTA status += (SString(" GetDistanceFromGround: fDist:%2.2f fUseDist:%2.2f", fDist, fUseDist)); - #endif +#endif // Stop waiting after 3 frames, if the object limit has not been reached. (bASync should always be false here) if (m_fGroundCheckTolerance > 0.03f /*&& !bMTAObjLimit*/ && !bASync) SetFrozenWaitingForGroundToLoad(false, true); } - #ifdef ASYNC_LOADING_DEBUG_OUTPUTA +#ifdef ASYNC_LOADING_DEBUG_OUTPUTA OutputDebugLine(SStringX("[AsyncLoading] ") + status); g_pCore->GetGraphics()->DrawString(10, 220, -1, 1, status); @@ -4469,7 +4473,7 @@ void CClientVehicle::HandleWaitingForGroundToLoad() strAround.Split("\n", lineList); for (unsigned int i = 0; i < lineList.size(); i++) g_pCore->GetGraphics()->DrawString(10, 230 + i * 10, -1, 1, lineList[i]); - #endif +#endif } bool CClientVehicle::GiveVehicleSirens(unsigned char ucSirenType, unsigned char ucSirenCount) @@ -4969,7 +4973,6 @@ CVehicleAudioSettingsEntry& CClientVehicle::GetOrCreateAudioSettings() return *m_pSoundSettingsEntry.get(); } - bool CClientVehicle::GetDummyPosition(VehicleDummies dummy, CVector& position) const { if (dummy >= VehicleDummies::LIGHT_FRONT_MAIN && dummy < VehicleDummies::VEHICLE_DUMMY_COUNT) @@ -5124,15 +5127,15 @@ bool CClientVehicle::SpawnFlyingComponent(const eCarNodes& nodeID, const eCarCom return m_pVehicle->SpawnFlyingComponent(nodeID, collisionType, removalTime); } - + CVector CClientVehicle::GetEntryPoint(std::uint32_t entryPointIndex) { static const uint32_t lookup[4] = {10, 8, 11, 9}; assert(entryPointIndex < 4); const std::uint32_t saDoorIndex = lookup[entryPointIndex]; - CVector entryPoint; - CVehicle* gameVehicle = GetGameVehicle(); + CVector entryPoint; + CVehicle* gameVehicle = GetGameVehicle(); g_pGame->GetCarEnterExit()->GetPositionToOpenCarDoor(entryPoint, gameVehicle, saDoorIndex); @@ -5153,4 +5156,3 @@ void CClientVehicle::ResetAudioSettings() m_pSoundSettingsEntry = nullptr; ApplyAudioSettings(); } - diff --git a/Client/mods/deathmatch/logic/CClientVehicle.h b/Client/mods/deathmatch/logic/CClientVehicle.h index 99c00b46334..2c3c75e89c2 100644 --- a/Client/mods/deathmatch/logic/CClientVehicle.h +++ b/Client/mods/deathmatch/logic/CClientVehicle.h @@ -50,7 +50,7 @@ enum eClientVehicleType CLIENTVEHICLE_TRAILER }; -static constexpr int NUM_VEHICLE_TYPES = 11; +static constexpr int NUM_VEHICLE_TYPES = 11; enum eDelayedSyncVehicleData { @@ -136,12 +136,12 @@ struct SVehicleComponentData m_bVisible = true; } SString m_strParentName; - CVector m_vecComponentPosition; // Parent relative - CVector m_vecComponentRotation; // Parent relative radians - CVector m_vecComponentScale; // Parent relative - CVector m_vecOriginalComponentPosition; // Parent relative - CVector m_vecOriginalComponentRotation; // Parent relative radians - CVector m_vecOriginalComponentScale; // Parent relative + CVector m_vecComponentPosition; // Parent relative + CVector m_vecComponentRotation; // Parent relative radians + CVector m_vecComponentScale; // Parent relative + CVector m_vecOriginalComponentPosition; // Parent relative + CVector m_vecOriginalComponentRotation; // Parent relative radians + CVector m_vecOriginalComponentScale; // Parent relative bool m_bPositionChanged; bool m_bRotationChanged; bool m_bScaleChanged; @@ -156,10 +156,10 @@ class CClientVehicle : public CClientStreamElement friend class CClientCamera; friend class CClientPed; friend class CClientVehicleManager; - friend class CClientGame; // TEMP HACK + friend class CClientGame; // TEMP HACK -protected: // Use CDeathmatchVehicle constructor for now. Will get removed later when this class is - // cleaned up. +protected: // Use CDeathmatchVehicle constructor for now. Will get removed later when this class is + // cleaned up. CClientVehicle(CClientManager* pManager, ElementID ID, unsigned short usModel, unsigned char ucVariation, unsigned char ucVariation2); public: @@ -287,7 +287,7 @@ class CClientVehicle : public CClientStreamElement int GetWheelFrictionState(unsigned char ucWheel); unsigned char GetPanelStatus(unsigned char ucPanel); unsigned char GetLightStatus(unsigned char ucLight); - SString GetComponentNameForWheel(unsigned char ucWheel) const noexcept; + SString GetComponentNameForWheel(unsigned char ucWheel) const noexcept; bool AreLightsOn(); @@ -539,7 +539,7 @@ class CClientVehicle : public CClientStreamElement void SetWheelScale(float fWheelScale); void ResetWheelScale(); - bool OnVehicleFallThroughMap(); + bool OnVehicleFallThroughMap(); const CVehicleAudioSettingsEntry& GetAudioSettings() const noexcept; CVehicleAudioSettingsEntry& GetOrCreateAudioSettings(); @@ -619,60 +619,60 @@ class CClientVehicle : public CClientStreamElement SFixedArray ulStartTime; SFixedArray ulTargetTime; } m_doorInterp; - bool m_bSwingingDoorsAllowed; - bool m_bDoorsLocked; - bool m_bDoorsUndamageable; - bool m_bCanShootPetrolTank; - bool m_bCanBeTargettedByHeatSeekingMissiles; - bool m_bCanBeDamaged; - bool m_bScriptCanBeDamaged; - bool m_bSyncUnoccupiedDamage; - bool m_bTyresCanBurst; - SFixedArray m_ucDoorStates; - SFixedArray m_ucWheelStates; - SFixedArray m_ucPanelStates; - SFixedArray m_ucLightStates; - bool m_bJustBlewUp; - eEntityStatus m_NormalStatus; - bool m_bColorSaved; - CVehicleColor m_Color; - bool m_bIsFrozen; - bool m_bScriptFrozen; - bool m_bFrozenWaitingForGroundToLoad; - float m_fGroundCheckTolerance; - float m_fObjectsAroundTolerance; - CVector m_vecWaitingForGroundSavedMoveSpeed; - CVector m_vecWaitingForGroundSavedTurnSpeed; - CMatrix m_matFrozen; - CVehicleUpgrades* m_pUpgrades; - unsigned char m_ucOverrideLights; - CClientVehiclePtr m_pTowedVehicle; - CClientVehiclePtr m_pTowedByVehicle; - eWinchType m_eWinchType; - CClientEntityPtr m_pPickedUpWinchEntity; - SString m_strRegPlate; - unsigned char m_ucPaintjob; - float m_fDirtLevel; - bool m_bSmokeTrail; - unsigned char m_ucAlpha; - bool m_bAlphaChanged; - double m_dLastRotationTime; - bool m_blowAfterStreamIn; - bool m_bIsOnGround; - bool m_bHeliSearchLightVisible; - float m_fHeliRotorSpeed; - float m_fPlaneRotorSpeed; - const CHandlingEntry* m_pOriginalHandlingEntry = nullptr; - std::unique_ptr m_HandlingEntry = nullptr; - const CFlyingHandlingEntry* m_pOriginalFlyingHandlingEntry = nullptr; - std::unique_ptr m_FlyingHandlingEntry = nullptr; - const CBoatHandlingEntry* m_pOriginalBoatHandlingEntry = nullptr; - std::unique_ptr m_BoatHandlingEntry = nullptr; - const CBikeHandlingEntry* m_pOriginalBikeHandlingEntry = nullptr; - std::unique_ptr m_BikeHandlingEntry = nullptr; - float m_fNitroLevel; - char m_cNitroCount; - float m_fWheelScale; + bool m_bSwingingDoorsAllowed; + bool m_bDoorsLocked; + bool m_bDoorsUndamageable; + bool m_bCanShootPetrolTank; + bool m_bCanBeTargettedByHeatSeekingMissiles; + bool m_bCanBeDamaged; + bool m_bScriptCanBeDamaged; + bool m_bSyncUnoccupiedDamage; + bool m_bTyresCanBurst; + SFixedArray m_ucDoorStates; + SFixedArray m_ucWheelStates; + SFixedArray m_ucPanelStates; + SFixedArray m_ucLightStates; + bool m_bJustBlewUp; + eEntityStatus m_NormalStatus; + bool m_bColorSaved; + CVehicleColor m_Color; + bool m_bIsFrozen; + bool m_bScriptFrozen; + bool m_bFrozenWaitingForGroundToLoad; + float m_fGroundCheckTolerance; + float m_fObjectsAroundTolerance; + CVector m_vecWaitingForGroundSavedMoveSpeed; + CVector m_vecWaitingForGroundSavedTurnSpeed; + CMatrix m_matFrozen; + CVehicleUpgrades* m_pUpgrades; + unsigned char m_ucOverrideLights; + CClientVehiclePtr m_pTowedVehicle; + CClientVehiclePtr m_pTowedByVehicle; + eWinchType m_eWinchType; + CClientEntityPtr m_pPickedUpWinchEntity; + SString m_strRegPlate; + unsigned char m_ucPaintjob; + float m_fDirtLevel; + bool m_bSmokeTrail; + unsigned char m_ucAlpha; + bool m_bAlphaChanged; + double m_dLastRotationTime; + bool m_blowAfterStreamIn; + bool m_bIsOnGround; + bool m_bHeliSearchLightVisible; + float m_fHeliRotorSpeed; + float m_fPlaneRotorSpeed; + const CHandlingEntry* m_pOriginalHandlingEntry = nullptr; + std::unique_ptr m_HandlingEntry = nullptr; + const CFlyingHandlingEntry* m_pOriginalFlyingHandlingEntry = nullptr; + std::unique_ptr m_FlyingHandlingEntry = nullptr; + const CBoatHandlingEntry* m_pOriginalBoatHandlingEntry = nullptr; + std::unique_ptr m_BoatHandlingEntry = nullptr; + const CBikeHandlingEntry* m_pOriginalBikeHandlingEntry = nullptr; + std::unique_ptr m_BikeHandlingEntry = nullptr; + float m_fNitroLevel; + char m_cNitroCount; + float m_fWheelScale; std::unique_ptr m_pSoundSettingsEntry; bool m_bChainEngine; @@ -754,9 +754,9 @@ class CClientVehicle : public CClientStreamElement SSirenInfo m_tSirenBeaconInfo; std::map m_ComponentData; // Store visibility state when the component map is regenerated - std::map m_ComponentVisibilityBackup; - bool m_bAsyncLoadingDisabled; + std::map m_ComponentVisibilityBackup; + bool m_bAsyncLoadingDisabled; std::array(VehicleDummies::VEHICLE_DUMMY_COUNT)> m_dummyPositions; - bool m_copyDummyPositions = true; + bool m_copyDummyPositions = true; }; diff --git a/Client/mods/deathmatch/logic/CClientVehicleManager.cpp b/Client/mods/deathmatch/logic/CClientVehicleManager.cpp index 96416cf4485..287940fdd7e 100644 --- a/Client/mods/deathmatch/logic/CClientVehicleManager.cpp +++ b/Client/mods/deathmatch/logic/CClientVehicleManager.cpp @@ -16,40 +16,40 @@ using std::list; using std::vector; // List over all vehicles with their passenger max counts -const SFixedArray g_ucMaxPassengers = {3, 1, 1, 1, 3, 3, 0, 1, 1, 3, 1, 1, 1, 3, 1, 1, // 400->415 - 3, 1, 3, 1, 3, 3, 1, 1, 1, 0, 3, 3, 3, 1, 0, 8, // 416->431 - 0, 1, 1, 255, 1, 8, 3, 1, 3, 0, 1, 1, 1, 3, 0, 1, // 432->447 - 0, 1, 255, 1, 0, 0, 0, 1, 1, 1, 3, 3, 1, 1, 1, // 448->462 - 1, 1, 1, 3, 3, 1, 1, 3, 1, 0, 0, 1, 1, 0, 1, 1, // 463->478 - 3, 1, 0, 3, 3, 0, 0, 0, 3, 1, 1, 3, 1, 3, 0, 1, // 479->494 - 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, // 495->510 - 1, 0, 0, 1, 1, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, // 511->526 - 1, 1, 3, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 3, 1, // 527->541 - 1, 1, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 1, 1, 1, 1, // 542->557 - 1, 1, 3, 3, 1, 1, 0, 1, 3, 3, 0, 255, 1, 0, 0, // 558->572 - 1, 0, 1, 1, 1, 1, 3, 3, 1, 3, 0, 255, 3, 1, 1, 1, // 573->588 - 1, 255, 255, 1, 1, 1, 0, 3, 3, 3, 1, 1, 1, 1, 1, // 589->604 - 3, 1, 255, 255, 255, 3, 255, 255}; // 605->611 +const SFixedArray g_ucMaxPassengers = {3, 1, 1, 1, 3, 3, 0, 1, 1, 3, 1, 1, 1, 3, 1, 1, // 400->415 + 3, 1, 3, 1, 3, 3, 1, 1, 1, 0, 3, 3, 3, 1, 0, 8, // 416->431 + 0, 1, 1, 255, 1, 8, 3, 1, 3, 0, 1, 1, 1, 3, 0, 1, // 432->447 + 0, 1, 255, 1, 0, 0, 0, 1, 1, 1, 3, 3, 1, 1, 1, // 448->462 + 1, 1, 1, 3, 3, 1, 1, 3, 1, 0, 0, 1, 1, 0, 1, 1, // 463->478 + 3, 1, 0, 3, 3, 0, 0, 0, 3, 1, 1, 3, 1, 3, 0, 1, // 479->494 + 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, // 495->510 + 1, 0, 0, 1, 1, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, // 511->526 + 1, 1, 3, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 3, 1, // 527->541 + 1, 1, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 1, 1, 1, 1, // 542->557 + 1, 1, 3, 3, 1, 1, 0, 1, 3, 3, 0, 255, 1, 0, 0, // 558->572 + 1, 0, 1, 1, 1, 1, 3, 3, 1, 3, 0, 255, 3, 1, 1, 1, // 573->588 + 1, 255, 255, 1, 1, 1, 0, 3, 3, 3, 1, 1, 1, 1, 1, // 589->604 + 3, 1, 255, 255, 255, 3, 255, 255}; // 605->611 // List over all vehicles with their special attributes -#define VEHICLE_HAS_TURRENT 0x001UL //1 -#define VEHICLE_HAS_SIRENS 0x002UL //2 -#define VEHICLE_HAS_LANDING_GEARS 0x004UL //4 -#define VEHICLE_HAS_ADJUSTABLE_PROPERTY 0x008UL //8 -#define VEHICLE_HAS_SMOKE_TRAIL 0x010UL //16 -#define VEHICLE_HAS_TAXI_LIGHTS 0x020UL //32 -#define VEHICLE_HAS_SEARCH_LIGHT 0x040UL //64 +#define VEHICLE_HAS_TURRENT 0x001UL // 1 +#define VEHICLE_HAS_SIRENS 0x002UL // 2 +#define VEHICLE_HAS_LANDING_GEARS 0x004UL // 4 +#define VEHICLE_HAS_ADJUSTABLE_PROPERTY 0x008UL // 8 +#define VEHICLE_HAS_SMOKE_TRAIL 0x010UL // 16 +#define VEHICLE_HAS_TAXI_LIGHTS 0x020UL // 32 +#define VEHICLE_HAS_SEARCH_LIGHT 0x040UL // 64 // Generated by MTA10\utils\gentable\gentable_vehattr.cpp static const SFixedArray g_ulVehicleAttributes = { - 0, 0, 0, 0, 0, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 32, 0, 0, 2, 0, // 400-424 - 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 425-449 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 450-474 - 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 64, 0, 0, // 475-499 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 4, 12, 0, 0, 2, 8, // 500-524 - 8, 0, 0, 2, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, // 525-549 - 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 550-574 - 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 2, 2, 2, 2, // 575-599 + 0, 0, 0, 0, 0, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 32, 0, 0, 2, 0, // 400-424 + 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 425-449 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 450-474 + 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 64, 0, 0, // 475-499 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 4, 12, 0, 0, 2, 8, // 500-524 + 8, 0, 0, 2, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, // 525-549 + 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 550-574 + 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 2, 2, 2, 2, // 575-599 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static SFixedArray g_ucVariants; diff --git a/Client/mods/deathmatch/logic/CClientWater.h b/Client/mods/deathmatch/logic/CClientWater.h index 13277eef8ff..452613bf764 100644 --- a/Client/mods/deathmatch/logic/CClientWater.h +++ b/Client/mods/deathmatch/logic/CClientWater.h @@ -39,9 +39,9 @@ class CClientWater final : public CClientEntity private: CWaterPoly* m_pPoly; CClientWaterManager* m_pWaterManager; - bool m_bTriangle; // Is this water a triangle or a quad type? - bool m_bShallow; // Shallow water? - std::vector m_Vertices; // List of vertices for this water + bool m_bTriangle; // Is this water a triangle or a quad type? + bool m_bShallow; // Shallow water? + std::vector m_Vertices; // List of vertices for this water friend class CClientWaterManager; }; diff --git a/Client/mods/deathmatch/logic/CClientWeapon.cpp b/Client/mods/deathmatch/logic/CClientWeapon.cpp index 14f8e6338f3..37f47a842d7 100644 --- a/Client/mods/deathmatch/logic/CClientWeapon.cpp +++ b/Client/mods/deathmatch/logic/CClientWeapon.cpp @@ -309,10 +309,10 @@ void CClientWeapon::Fire(bool bServerFire) #ifdef SHOTGUN_TEST CVector vecFireOffset = *m_pWeaponInfo->GetFireOffset(); CMatrix matTemp = CMatrix(vecFireOffset) * matOrigin; -#ifdef MARKER_DEBUG + #ifdef MARKER_DEBUG // Process m_pMarker->SetPosition(matOrigin.GetPosition()); -#endif + #endif CVector vecTemp2; GetRotationDegrees(vecTemp2); vecTemp2.fZ -= 84.6f; @@ -419,18 +419,18 @@ void CClientWeapon::FireInstantHit(CVector vecOrigin, CVector vecTarget, bool bS CClientEntity* pClientEntity = pColEntity ? pPools->GetClientEntity((DWORD*)pColEntity->GetInterface()) : nullptr; CLuaArguments Arguments; if (pClientEntity) - Arguments.PushElement(pClientEntity); // entity that got hit + Arguments.PushElement(pClientEntity); // entity that got hit else - Arguments.PushNil(); // Probably a building. - Arguments.PushNumber(pColPoint->GetPosition().fX); // pos x - Arguments.PushNumber(pColPoint->GetPosition().fY); // pos y - Arguments.PushNumber(pColPoint->GetPosition().fZ); // pos z - Arguments.PushNumber(pColPoint->GetNormal().fX); // Normal x - Arguments.PushNumber(pColPoint->GetNormal().fY); // Normal y - Arguments.PushNumber(pColPoint->GetNormal().fZ); // Normal z - Arguments.PushNumber(pColPoint->GetSurfaceTypeB()); // Surface type "B" - Arguments.PushNumber(pColPoint->GetLightingForTimeOfDay()); // Lighting - Arguments.PushNumber(pColPoint->GetPieceTypeB()); // Piece + Arguments.PushNil(); // Probably a building. + Arguments.PushNumber(pColPoint->GetPosition().fX); // pos x + Arguments.PushNumber(pColPoint->GetPosition().fY); // pos y + Arguments.PushNumber(pColPoint->GetPosition().fZ); // pos z + Arguments.PushNumber(pColPoint->GetNormal().fX); // Normal x + Arguments.PushNumber(pColPoint->GetNormal().fY); // Normal y + Arguments.PushNumber(pColPoint->GetNormal().fZ); // Normal z + Arguments.PushNumber(pColPoint->GetSurfaceTypeB()); // Surface type "B" + Arguments.PushNumber(pColPoint->GetLightingForTimeOfDay()); // Lighting + Arguments.PushNumber(pColPoint->GetPieceTypeB()); // Piece if (!CallEvent("onClientWeaponFire", Arguments, true)) { if (pColPoint) diff --git a/Client/mods/deathmatch/logic/CClientWeapon.h b/Client/mods/deathmatch/logic/CClientWeapon.h index 00c400810d0..bc1dae9e4ce 100644 --- a/Client/mods/deathmatch/logic/CClientWeapon.h +++ b/Client/mods/deathmatch/logic/CClientWeapon.h @@ -124,7 +124,7 @@ class CClientWeapon final : public CClientObject eBone m_targetBone; int m_itargetWheel; SWeaponConfiguration m_weaponConfig; - CClientPlayerPtr m_pOwner; // For lag compensation + CClientPlayerPtr m_pOwner; // For lag compensation int m_nAmmoTotal; int m_nAmmoInClip; eWeaponState m_PreviousState; @@ -132,5 +132,5 @@ class CClientWeapon final : public CClientObject CElapsedTime m_reloadTimer; unsigned char m_ucCounter; int m_iWeaponFireRate; - CVector m_vecFireRotationNoTarget; // Rotation adjustment when firing directly forward + CVector m_vecFireRotationNoTarget; // Rotation adjustment when firing directly forward }; diff --git a/Client/mods/deathmatch/logic/CClientWebBrowser.cpp b/Client/mods/deathmatch/logic/CClientWebBrowser.cpp index 9cf39ee26cd..c56adf8df46 100644 --- a/Client/mods/deathmatch/logic/CClientWebBrowser.cpp +++ b/Client/mods/deathmatch/logic/CClientWebBrowser.cpp @@ -107,7 +107,7 @@ bool CClientWebBrowser::ExecuteJavascript(const SString& strJavascriptCode) { if (!m_pWebView) return false; - + // Don't allow javascript code execution on remote websites if (!m_pWebView->IsLocal()) return false; @@ -212,7 +212,7 @@ void CClientWebBrowser::Events_OnCreated() { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; CallEvent("onClientBrowserCreated", Arguments, false); } @@ -221,7 +221,7 @@ void CClientWebBrowser::Events_OnLoadingStart(const SString& strURL, bool bMainF { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strURL); Arguments.PushBoolean(bMainFrame); @@ -232,7 +232,7 @@ void CClientWebBrowser::Events_OnDocumentReady(const SString& strURL) { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strURL); CallEvent("onClientBrowserDocumentReady", Arguments, false); @@ -242,7 +242,7 @@ void CClientWebBrowser::Events_OnLoadingFailed(const SString& strURL, int errorC { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strURL); Arguments.PushNumber(errorCode); @@ -254,7 +254,7 @@ void CClientWebBrowser::Events_OnNavigate(const SString& strURL, bool bIsBlocked { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strURL); Arguments.PushBoolean(bIsBlocked); @@ -266,7 +266,7 @@ void CClientWebBrowser::Events_OnPopup(const SString& strTargetURL, const SStrin { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strTargetURL); Arguments.PushString(strOpenerURL); @@ -277,7 +277,7 @@ void CClientWebBrowser::Events_OnChangeCursor(unsigned char ucCursor) { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushNumber(ucCursor); CallEvent("onClientBrowserCursorChange", Arguments, false); @@ -299,7 +299,7 @@ void CClientWebBrowser::Events_OnTooltip(const SString& strTooltip) { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushString(strTooltip); CallEvent("onClientBrowserTooltip", Arguments, false); @@ -309,7 +309,7 @@ void CClientWebBrowser::Events_OnInputFocusChanged(bool bGainedFocus) { if (m_bBeingDestroyed) return; - + CLuaArguments Arguments; Arguments.PushBoolean(bGainedFocus); CallEvent("onClientBrowserInputFocusChanged", Arguments, false); @@ -324,7 +324,7 @@ bool CClientWebBrowser::Events_OnResourcePathCheck(SString& strURL) if (!m_pResource) return true; - CResource* pTempResource = m_pResource; // Make a copy to ignore a changed resource + CResource* pTempResource = m_pResource; // Make a copy to ignore a changed resource if (CResourceManager::ParseResourcePathInput(strURL, pTempResource, &strURL)) return true; @@ -401,7 +401,7 @@ bool CClientWebBrowser::AddAjaxHandler(const SString& strURL, ajax_callback_t& h { if (!m_pWebView) return false; - + if (!m_pWebView->RegisterAjaxHandler(strURL)) return false; @@ -413,7 +413,7 @@ bool CClientWebBrowser::RemoveAjaxHandler(const SString& strURL) { if (!m_pWebView) return false; - + if (!m_pWebView->UnregisterAjaxHandler(strURL)) return false; diff --git a/Client/mods/deathmatch/logic/CDeathmatchObject.cpp b/Client/mods/deathmatch/logic/CDeathmatchObject.cpp index 36f2dd81497..cd950285a85 100644 --- a/Client/mods/deathmatch/logic/CDeathmatchObject.cpp +++ b/Client/mods/deathmatch/logic/CDeathmatchObject.cpp @@ -102,8 +102,8 @@ void CDeathmatchObject::UpdateMovement() if (!bStillRunning) { - _StopMovement(false); // We don't unregister ourselves here since CDeathmatchObject::UpdateMovement is called from an iteration in - // CMovingObjectsManager::DoPulse + _StopMovement(false); // We don't unregister ourselves here since CDeathmatchObject::UpdateMovement is called from an iteration in + // CMovingObjectsManager::DoPulse // and we are automatically removed from the list after CDeathmatchObject::UpdateMovement if we are finished } } diff --git a/Client/mods/deathmatch/logic/CDownloadableResource.h b/Client/mods/deathmatch/logic/CDownloadableResource.h index f4fe9ee9633..3d115ca2f61 100644 --- a/Client/mods/deathmatch/logic/CDownloadableResource.h +++ b/Client/mods/deathmatch/logic/CDownloadableResource.h @@ -13,9 +13,9 @@ #ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms + #define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms -#include + #include #endif #include @@ -74,8 +74,8 @@ class CDownloadableResource CChecksum m_ServerChecksum; bool m_bAutoDownload; - bool m_bInDownloadQueue; // File in auto download queue - bool m_bDownloaded; // File has been downloaded and is ready to use + bool m_bInDownloadQueue; // File in auto download queue + bool m_bDownloaded; // File has been downloaded and is ready to use uint m_uiDownloadSize; uint m_uiHttpServerIndex; bool m_bModifedByScript; diff --git a/Client/mods/deathmatch/logic/CDynamicLibrary.cpp b/Client/mods/deathmatch/logic/CDynamicLibrary.cpp index b3d13162822..0f6d6b72c4f 100644 --- a/Client/mods/deathmatch/logic/CDynamicLibrary.cpp +++ b/Client/mods/deathmatch/logic/CDynamicLibrary.cpp @@ -29,10 +29,10 @@ bool CDynamicLibrary::Load(const char* szFilename) // Unload the previous library Unload(); - // Load the new library - #ifdef WIN32 +// Load the new library +#ifdef WIN32 m_hModule = LoadLibrary(szFilename); - #else +#else m_hModule = dlopen(szFilename, RTLD_NOW); // Output error if needed @@ -40,7 +40,7 @@ bool CDynamicLibrary::Load(const char* szFilename) { Print("%s\n", dlerror()); } - #endif +#endif // Return whether we succeeded or not return m_hModule != 0; @@ -51,11 +51,11 @@ void CDynamicLibrary::Unload() // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 FreeLibrary(m_hModule); - #else +#else dlclose(m_hModule); - #endif +#endif // Zero out our library as it's no longer valid m_hModule = 0; @@ -72,9 +72,9 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 return GetProcAddress(m_hModule, szProcName); - #else +#else char* szError = NULL; dlerror(); @@ -85,7 +85,7 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) } return pFunc; - #endif +#endif } return NULL; diff --git a/Client/mods/deathmatch/logic/CDynamicLibrary.h b/Client/mods/deathmatch/logic/CDynamicLibrary.h index 55daf8e2d14..f070cac8201 100644 --- a/Client/mods/deathmatch/logic/CDynamicLibrary.h +++ b/Client/mods/deathmatch/logic/CDynamicLibrary.h @@ -12,7 +12,7 @@ #pragma once #ifdef WIN32 -#include + #include #endif class CDynamicLibrary @@ -28,9 +28,9 @@ class CDynamicLibrary void* GetProcedureAddress(const char* szProcName); private: - #ifdef WIN32 +#ifdef WIN32 HMODULE m_hModule; - #else +#else void* m_hModule; - #endif +#endif }; diff --git a/Client/mods/deathmatch/logic/CElementGroup.cpp b/Client/mods/deathmatch/logic/CElementGroup.cpp index 2cf2aaeb2d3..50b86523e4e 100644 --- a/Client/mods/deathmatch/logic/CElementGroup.cpp +++ b/Client/mods/deathmatch/logic/CElementGroup.cpp @@ -49,4 +49,4 @@ void CElementGroup::Remove(class CClientEntity* element) unsigned int CElementGroup::GetCount() { return m_elements.size(); -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CLogger.cpp b/Client/mods/deathmatch/logic/CLogger.cpp index 930fde4e1a0..bfdbe42a6a9 100644 --- a/Client/mods/deathmatch/logic/CLogger.cpp +++ b/Client/mods/deathmatch/logic/CLogger.cpp @@ -47,7 +47,7 @@ void CLogger::LogPrintfNoStamp(const char* szFormat, ...) HandleLogPrint(false, "", szBuffer, true, true); } -#if 0 // Currently unused +#if 0 // Currently unused void CLogger::LogPrintNoStamp ( const char* szText ) { // Send to the console and logfile @@ -68,7 +68,7 @@ void CLogger::ErrorPrintf(const char* szFormat, ...) HandleLogPrint(true, "ERROR: ", szBuffer, true, true); } -#if 0 // Currently unused +#if 0 // Currently unused void CLogger::DebugPrintf ( const char* szFormat, ... ) { #ifdef MTA_DEBUG diff --git a/Client/mods/deathmatch/logic/CMapEventManager.cpp b/Client/mods/deathmatch/logic/CMapEventManager.cpp index 30f123be425..6b1f7c26334 100644 --- a/Client/mods/deathmatch/logic/CMapEventManager.cpp +++ b/Client/mods/deathmatch/logic/CMapEventManager.cpp @@ -164,11 +164,11 @@ bool CMapEventManager::Call(const char* szName, const CLuaArguments& Arguments, // Grab the current VM lua_State* pState = pMapEvent->GetVM()->GetVM(); - LUA_CHECKSTACK(pState, 1); // Ensure some room + LUA_CHECKSTACK(pState, 1); // Ensure some room - #if MTA_DEBUG +#if MTA_DEBUG int luaStackPointer = lua_gettop(pState); - #endif +#endif TIMEUS startTime = GetTimeUs(); @@ -260,9 +260,9 @@ bool CMapEventManager::Call(const char* szName, const CLuaArguments& Arguments, OldEventName.Push(pState); lua_setglobal(pState, "eventName"); - #if MTA_DEBUG +#if MTA_DEBUG assert(lua_gettop(pState) == luaStackPointer); - #endif +#endif // Aspect ratio adjustment bodges if (pMapEvent->ShouldAllowAspectRatioAdjustment()) diff --git a/Client/mods/deathmatch/logic/CModelNames.cpp b/Client/mods/deathmatch/logic/CModelNames.cpp index 0477fc66722..d090f3c981f 100644 --- a/Client/mods/deathmatch/logic/CModelNames.cpp +++ b/Client/mods/deathmatch/logic/CModelNames.cpp @@ -4808,7 +4808,7 @@ struct 333, "Golf_Club", 334, - "Night_Strick", // typo here retained for BC + "Night_Strick", // typo here retained for BC 334, "Night_Stick", 335, @@ -29324,7 +29324,7 @@ uint32 CModelNames::ResolveModelID(const SString& strModelName) { uint32 usModelID = atoi(strModelName.SubStr(3)); if (usModelID) - return g_pGame->GetBaseIDforTXD() + usModelID; // Encode global txd as model id 20000+ + return g_pGame->GetBaseIDforTXD() + usModelID; // Encode global txd as model id 20000+ } // Now search for the name diff --git a/Client/mods/deathmatch/logic/CModelNames.h b/Client/mods/deathmatch/logic/CModelNames.h index ffc21e18d55..75a28b668ef 100644 --- a/Client/mods/deathmatch/logic/CModelNames.h +++ b/Client/mods/deathmatch/logic/CModelNames.h @@ -8,11 +8,11 @@ * *****************************************************************************/ -#define CLOTHES_MODEL_ID_FIRST 30000 -#define CLOTHES_MODEL_ID_LAST 30151 -#define CLOTHES_TEX_ID_FIRST 30152 -#define CLOTHES_TEX_ID_LAST 30541 -#define INVALID_MODEL_ID 32000 +#define CLOTHES_MODEL_ID_FIRST 30000 +#define CLOTHES_MODEL_ID_LAST 30151 +#define CLOTHES_TEX_ID_FIRST 30152 +#define CLOTHES_TEX_ID_LAST 30541 +#define INVALID_MODEL_ID 32000 class CModelNames { diff --git a/Client/mods/deathmatch/logic/CModelRenderer.cpp b/Client/mods/deathmatch/logic/CModelRenderer.cpp index 8983197e75e..dd2090064f9 100644 --- a/Client/mods/deathmatch/logic/CModelRenderer.cpp +++ b/Client/mods/deathmatch/logic/CModelRenderer.cpp @@ -37,8 +37,8 @@ void CModelRenderer::Update() // Insert transparent entities into a sorted list if (modelDesc.pModelInfo->GetIdeFlag(eModelIdeFlag::DRAW_LAST)) { - const CVector& vecCameraPosition = *(CVector*)0xB76870; // CRenderer::ms_vecCameraPosition - const float fDistance = (modelDesc.matrix.GetPosition() - vecCameraPosition).Length(); + const CVector& vecCameraPosition = *(CVector*)0xB76870; // CRenderer::ms_vecCameraPosition + const float fDistance = (modelDesc.matrix.GetPosition() - vecCameraPosition).Length(); pVisibilityPlugins->InsertEntityIntoEntityList(&modelDesc, fDistance, RenderEntity); } @@ -48,7 +48,7 @@ void CModelRenderer::Update() void CModelRenderer::Render() { CRenderer* pRenderer = g_pGame->GetRenderer(); - assert(pRenderer); + assert(pRenderer); // Draw opaque entities for (auto& modelDesc : m_Queue) diff --git a/Client/mods/deathmatch/logic/CModelRenderer.h b/Client/mods/deathmatch/logic/CModelRenderer.h index 8272fcf34ce..43b8822fa6d 100644 --- a/Client/mods/deathmatch/logic/CModelRenderer.h +++ b/Client/mods/deathmatch/logic/CModelRenderer.h @@ -17,15 +17,10 @@ class CModelRenderer final struct SModelToRender final { CModelInfo* pModelInfo; - CMatrix matrix; - float lighting; - - SModelToRender(CModelInfo* pModelInfo, const CMatrix& matrix, float lighting = 0.0f) : - pModelInfo(pModelInfo), - matrix(matrix), - lighting(lighting) - { - } + CMatrix matrix; + float lighting; + + SModelToRender(CModelInfo* pModelInfo, const CMatrix& matrix, float lighting = 0.0f) : pModelInfo(pModelInfo), matrix(matrix), lighting(lighting) {} }; bool EnqueueModel(CModelInfo* pModelInfo, const CMatrix& matrix, float lighting); @@ -36,7 +31,6 @@ class CModelRenderer final static void RenderEntity(SModelToRender* entity, float distance); -private: - +private: std::vector m_Queue; }; diff --git a/Client/mods/deathmatch/logic/CNametags.cpp b/Client/mods/deathmatch/logic/CNametags.cpp index d3c68300aaf..9927b6253a1 100644 --- a/Client/mods/deathmatch/logic/CNametags.cpp +++ b/Client/mods/deathmatch/logic/CNametags.cpp @@ -14,17 +14,17 @@ using std::list; -#define MELEE_VISIBLE_RANGE 60.0f -#define AIM_VISIBLE_RANGE 300.0f -#define SNIPER_AIM_VISIBLE_RANGE 300.0f -#define WEAPON_RANGE_FACTOR 3.0f -#define NAMETAG_BEGIN_FADE_TIME 0 -#define NAMETAG_END_FADE_TIME 700 -#define NAMETAG_FONT_SIZE 0.8f -#define MAX_ALPHA 180.0f // max value is 255 - -#define DEFAULT_VIEW_RANGE 45.0f -#define DEFAULT_VIEW_RANGE_EXP ((DEFAULT_VIEW_RANGE)*(DEFAULT_VIEW_RANGE)) +#define MELEE_VISIBLE_RANGE 60.0f +#define AIM_VISIBLE_RANGE 300.0f +#define SNIPER_AIM_VISIBLE_RANGE 300.0f +#define WEAPON_RANGE_FACTOR 3.0f +#define NAMETAG_BEGIN_FADE_TIME 0 +#define NAMETAG_END_FADE_TIME 700 +#define NAMETAG_FONT_SIZE 0.8f +#define MAX_ALPHA 180.0f // max value is 255 + +#define DEFAULT_VIEW_RANGE 45.0f +#define DEFAULT_VIEW_RANGE_EXP ((DEFAULT_VIEW_RANGE) * (DEFAULT_VIEW_RANGE)) const bool bRenderOwn = false; @@ -310,11 +310,11 @@ void CNametags::DrawTagForPlayer(CClientPlayer* pPlayer, unsigned char ucAlpha) float fRemovedWidth = fWidth - (fHealth / 512.0f * fWidth); float fTopArmorOffset = fTopOffset + fHeight - 0.01f * fResWidth; float fMaxArmor = 100.0f; - float fArmorAlpha = (fArmor / fMaxArmor) * (ucAlpha / 255.0f); // 0->1 + float fArmorAlpha = (fArmor / fMaxArmor) * (ucAlpha / 255.0f); // 0->1 unsigned char ucArmorAlpha = (unsigned char)(255.0f * fArmorAlpha); - #define ARMOR_BORDER_COLOR COLOR_ABGR(ucArmorAlpha,167,177,179) +#define ARMOR_BORDER_COLOR COLOR_ABGR(ucArmorAlpha, 167, 177, 179) // Base rectangle CVector vecTopLeftBase(vecScreenPosition.fX - fWidth * 0.5f, vecScreenPosition.fY + fTopOffset, 0); diff --git a/Client/mods/deathmatch/logic/CNetAPI.cpp b/Client/mods/deathmatch/logic/CNetAPI.cpp index cdd0204f03e..74320154034 100644 --- a/Client/mods/deathmatch/logic/CNetAPI.cpp +++ b/Client/mods/deathmatch/logic/CNetAPI.cpp @@ -665,7 +665,7 @@ void CNetAPI::ReadKeysync(CClientPlayer* pPlayer, NetBitStreamInterface& BitStre // Eventually read vehicle specific keysync data ReadSmallVehicleSpecific(pVehicle, BitStream, pVehicle->GetModel()); - if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? + if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? { short sRightStickX, sRightStickY; BitStream.Read(sRightStickX); @@ -790,7 +790,7 @@ void CNetAPI::WriteKeysync(CClientPed* pPlayerModel, NetBitStreamInterface& BitS CVehicleUpgrades* pUpgrades = pVehicle->GetUpgrades(); if (pUpgrades) { - if (pUpgrades->HasUpgrade(1087)) // Hydraulics? + if (pUpgrades->HasUpgrade(1087)) // Hydraulics? { BitStream.Write(ControllerState.RightStickX); BitStream.Write(ControllerState.RightStickY); @@ -981,12 +981,13 @@ void CNetAPI::ReadPlayerPuresync(CClientPlayer* pPlayer, NetBitStreamInterface& pPlayer->SetOnFire(flags.data.bIsOnFire); pPlayer->SetStealthAiming(flags.data.bStealthAiming); - if (flags.data.hangingDuringClimb && pPlayer->GetMovementState() != eMovementState::MOVEMENTSTATE_HANGING && pPlayer->GetMovementState() != eMovementState::MOVEMENTSTATE_CLIMB) + if (flags.data.hangingDuringClimb && pPlayer->GetMovementState() != eMovementState::MOVEMENTSTATE_HANGING && + pPlayer->GetMovementState() != eMovementState::MOVEMENTSTATE_CLIMB) pPlayer->RunClimbingTask(); if (flags.data.bIsInWater && !pPlayer->IsInWater()) pPlayer->RunSwimTask(); - + // Remember now as the last puresync time pPlayer->SetLastPuresyncTime(CClientTime::GetTime()); pPlayer->SetLastPuresyncPosition(position.data.vecPosition); @@ -1052,16 +1053,16 @@ void WriteCameraOrientation(const CVector& vecPositionBase, NetBitStreamInterfac uint uiNumBits; float fRange; } bitCountTable[4] = { - {3, 4.0f}, // 3 bits is +-4 12 bits total - {5, 16.0f}, // 5 bits is +-16 18 bits total - {9, 256.0f}, // 9 bits is +-256 30 bits total - {14, 8192.0f}, // 14 bits is +-8192 45 bits total + {3, 4.0f}, // 3 bits is +-4 12 bits total + {5, 16.0f}, // 5 bits is +-16 18 bits total + {9, 256.0f}, // 9 bits is +-256 30 bits total + {14, 8192.0f}, // 14 bits is +-8192 45 bits total }; char idx; for (idx = 0; idx < 3; idx++) { if (bitCountTable[idx].fRange > fUseMaxValue) - break; // We have enough bits now + break; // We have enough bits now } const uint uiNumBits = bitCountTable[idx].uiNumBits; const float fRange = bitCountTable[idx].fRange; @@ -1758,10 +1759,10 @@ bool CNetAPI::ReadSmallKeysync(CControllerState& ControllerState, NetBitStreamIn short sButtonCross = 255 * keys.data.bButtonCross; { if (keys.data.ucButtonSquare != 0) - sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present + sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present if (keys.data.ucButtonCross != 0) - sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present + sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present } // Put the result into the controllerstate @@ -1781,16 +1782,16 @@ bool CNetAPI::ReadSmallKeysync(CControllerState& ControllerState, NetBitStreamIn void CNetAPI::WriteSmallKeysync(const CControllerState& ControllerState, NetBitStreamInterface& BitStream) { SSmallKeysyncSync keys; - keys.data.bLeftShoulder1 = (ControllerState.LeftShoulder1 != 0); // Action / Secondary-Fire - keys.data.bRightShoulder1 = (ControllerState.RightShoulder1 != 0); // Aim-Weapon / Handbrake - keys.data.bButtonSquare = (ControllerState.ButtonSquare != 0); // Jump / Reverse - keys.data.bButtonCross = (ControllerState.ButtonCross != 0); // Sprint / Accelerate - keys.data.bButtonCircle = (ControllerState.ButtonCircle != 0); // Fire // Fire - keys.data.bButtonTriangle = (ControllerState.ButtonTriangle != 0); // Enter/Exit/Special-Attack / Enter/exit - keys.data.bShockButtonL = (ControllerState.ShockButtonL != 0); // Crouch / Horn - keys.data.bPedWalk = (ControllerState.m_bPedWalk != 0); // Walk / - - keys.data.ucButtonSquare = (unsigned char)ControllerState.ButtonSquare; // Jump / Reverse - keys.data.ucButtonCross = (unsigned char)ControllerState.ButtonCross; // Sprint / Accelerate + keys.data.bLeftShoulder1 = (ControllerState.LeftShoulder1 != 0); // Action / Secondary-Fire + keys.data.bRightShoulder1 = (ControllerState.RightShoulder1 != 0); // Aim-Weapon / Handbrake + keys.data.bButtonSquare = (ControllerState.ButtonSquare != 0); // Jump / Reverse + keys.data.bButtonCross = (ControllerState.ButtonCross != 0); // Sprint / Accelerate + keys.data.bButtonCircle = (ControllerState.ButtonCircle != 0); // Fire // Fire + keys.data.bButtonTriangle = (ControllerState.ButtonTriangle != 0); // Enter/Exit/Special-Attack / Enter/exit + keys.data.bShockButtonL = (ControllerState.ShockButtonL != 0); // Crouch / Horn + keys.data.bPedWalk = (ControllerState.m_bPedWalk != 0); // Walk / - + keys.data.ucButtonSquare = (unsigned char)ControllerState.ButtonSquare; // Jump / Reverse + keys.data.ucButtonCross = (unsigned char)ControllerState.ButtonCross; // Sprint / Accelerate keys.data.sLeftStickX = ControllerState.LeftStickX; keys.data.sLeftStickY = ControllerState.LeftStickY; @@ -1809,10 +1810,10 @@ bool CNetAPI::ReadFullKeysync(CControllerState& ControllerState, NetBitStreamInt short sButtonCross = 255 * keys.data.bButtonCross; { if (keys.data.ucButtonSquare != 0) - sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present + sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present if (keys.data.ucButtonCross != 0) - sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present + sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present } // Put the result into the controllerstate @@ -2239,9 +2240,8 @@ void CNetAPI::ReadBulletsync(CClientPlayer* player, NetBitStreamInterface& strea CVector start; CVector end; - if (!stream.Read(reinterpret_cast(&start), sizeof(CVector)) || - !stream.Read(reinterpret_cast(&end), sizeof(CVector)) || - !start.IsValid() || !end.IsValid()) + if (!stream.Read(reinterpret_cast(&start), sizeof(CVector)) || !stream.Read(reinterpret_cast(&end), sizeof(CVector)) || !start.IsValid() || + !end.IsValid()) return; std::uint8_t order = 0; diff --git a/Client/mods/deathmatch/logic/CNetAPI.h b/Client/mods/deathmatch/logic/CNetAPI.h index 260c9a34a45..d3ed4cec57c 100644 --- a/Client/mods/deathmatch/logic/CNetAPI.h +++ b/Client/mods/deathmatch/logic/CNetAPI.h @@ -21,9 +21,9 @@ class CNetAPI; #include "CTickRateSettings.h" // SYNC SETTINGS -#define TICK_RATE ( g_TickRateSettings.iPureSync ) -#define CAM_SYNC_RATE ( g_TickRateSettings.iCamSync ) -#define TICK_RATE_AIM ( std::min ( TICK_RATE, g_TickRateSettings.iKeySyncRotation ) ) // Keysync or puresync update the aim, so use the shortest interval +#define TICK_RATE (g_TickRateSettings.iPureSync) +#define CAM_SYNC_RATE (g_TickRateSettings.iCamSync) +#define TICK_RATE_AIM (std::min(TICK_RATE, g_TickRateSettings.iKeySyncRotation)) // Keysync or puresync update the aim, so use the shortest interval enum eServerRPCFunctions { diff --git a/Client/mods/deathmatch/logic/CObjectSync.cpp b/Client/mods/deathmatch/logic/CObjectSync.cpp index 4cd196f7e14..f580376cddb 100644 --- a/Client/mods/deathmatch/logic/CObjectSync.cpp +++ b/Client/mods/deathmatch/logic/CObjectSync.cpp @@ -16,7 +16,7 @@ using std::list; -#define OBJECT_SYNC_RATE ( g_TickRateSettings.iObjectSync ) + #define OBJECT_SYNC_RATE (g_TickRateSettings.iObjectSync) CObjectSync::CObjectSync(CClientObjectManager* pObjectManager) { @@ -97,10 +97,10 @@ void CObjectSync::Packet_ObjectStartSync(NetBitStreamInterface& BitStream) SRotationRadiansSync rotation; if (BitStream.Read(&position) && BitStream.Read(&rotation)) { - // Disabled due to problem when attached in the editor - issue #5886 - #if 0 + // Disabled due to problem when attached in the editor - issue #5886 + #if 0 pObject->SetOrientation ( position.data.vecPosition, rotation.data.vecRotation ); - #endif + #endif } // No velocity due to issue #3522 @@ -267,4 +267,4 @@ void CObjectSync::WriteObjectInformation(NetBitStreamInterface* pBitStream, CDea } } -#endif \ No newline at end of file +#endif diff --git a/Client/mods/deathmatch/logic/CPacketHandler.cpp b/Client/mods/deathmatch/logic/CPacketHandler.cpp index 7cf90498616..fc10ed05cd8 100644 --- a/Client/mods/deathmatch/logic/CPacketHandler.cpp +++ b/Client/mods/deathmatch/logic/CPacketHandler.cpp @@ -595,7 +595,7 @@ void CPacketHandler::Packet_ServerDisconnected(NetBitStreamInterface& bitStream) break; case ePlayerDisconnectType::CUSTOM: strReason = "%s"; - strErrorCode = _E("CD48"); // Custom disconnect reason + strErrorCode = _E("CD48"); // Custom disconnect reason bExpectExtraString = true; break; case ePlayerDisconnectType::SHUTDOWN: @@ -822,7 +822,7 @@ void CPacketHandler::Packet_PlayerList(NetBitStreamInterface& bitStream) // Player flags bool bIsDead = bitStream.ReadBit(); - bool bIsSpawned = bitStream.ReadBit(); // Indicates extra info in packet. Always true for newer server builds. + bool bIsSpawned = bitStream.ReadBit(); // Indicates extra info in packet. Always true for newer server builds. bool bInVehicle = bitStream.ReadBit(); bool bHasJetPack = bitStream.ReadBit(); bool bNametagShowing = bitStream.ReadBit(); @@ -860,7 +860,7 @@ void CPacketHandler::Packet_PlayerList(NetBitStreamInterface& bitStream) unsigned char ucFightingStyle = 0; SEntityAlphaSync alpha; unsigned char ucInterior = 0; - if (bIsSpawned) // Always true for newer server builds. + if (bIsSpawned) // Always true for newer server builds. { // Read out the player model id bitStream.ReadCompressed(usPlayerModelID); @@ -901,7 +901,7 @@ void CPacketHandler::Packet_PlayerList(NetBitStreamInterface& bitStream) return; } } - else // On foot? + else // On foot? { // Set the vehicle id to 0 to indicate we're on foot ID = INVALID_ELEMENT_ID; @@ -964,7 +964,7 @@ void CPacketHandler::Packet_PlayerList(NetBitStreamInterface& bitStream) pPlayer->SetTeam(pTeam, true); // If the player has spawned - if (bIsSpawned) // Always true for newer server builds. + if (bIsSpawned) // Always true for newer server builds. { // Give him the correct skin pPlayer->SetModel(usPlayerModelID); @@ -978,7 +978,7 @@ void CPacketHandler::Packet_PlayerList(NetBitStreamInterface& bitStream) pPlayer->ResetInterpolation(); pPlayer->SetHasJetPack(bHasJetPack); } - else // In a vehicle + else // In a vehicle { // Grab the vehicle and warp him into it CClientVehicle* pVehicle = g_pClientGame->m_pVehicleManager->Get(ID); @@ -1090,7 +1090,7 @@ void CPacketHandler::Packet_PlayerSpawn(NetBitStreamInterface& bitStream) // Flags unsigned char ucFlags; - bitStream.Read(ucFlags); // Unused + bitStream.Read(ucFlags); // Unused // Position vector CVector vecPosition; @@ -1143,7 +1143,8 @@ void CPacketHandler::Packet_PlayerSpawn(NetBitStreamInterface& bitStream) pPlayer->SetDeadOnNetwork(false); // Reset death processing flag for new life - if (pPlayer->IsLocalPlayer()) { + if (pPlayer->IsLocalPlayer()) + { g_pClientGame->ResetDeathProcessingFlag(); } @@ -1228,7 +1229,8 @@ void CPacketHandler::Packet_PlayerWasted(NetBitStreamInterface& bitStream) // Clear stale damage data if this is the local player // This prevents DoWastedCheck from firing with stale data when server processes death - if (pPed->IsLocalPlayer()) { + if (pPed->IsLocalPlayer()) + { g_pClientGame->ClearDamageData(); } @@ -1429,7 +1431,7 @@ void CPacketHandler::Packet_ChatEcho(NetBitStreamInterface& bitStream) // actual limits enforced on the remote client, this is the maximum a string can be to be printed. SString textToProcess = bColorCoded ? RemoveColorCodes(szMessage) : szMessage; if (MbUTF8ToUTF16(textToProcess).size() <= - MAX_CHATECHO_LENGTH + 6) // Extra 6 characters to fix #7125 (Teamsay + long name + long message = too long message) + MAX_CHATECHO_LENGTH + 6) // Extra 6 characters to fix #7125 (Teamsay + long name + long message = too long message) { // Strip it for bad characters StripControlCodes(szMessage, ' '); @@ -1754,9 +1756,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) { // Call the onClientVehicleStartEnter event for remote players and peds we dont sync CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(ucSeat); // seat - Arguments.PushNumber(ucDoor); // Door + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(ucSeat); // seat + Arguments.PushNumber(ucDoor); // Door pVehicle->CallEvent("onClientVehicleStartEnter", Arguments, true); } @@ -1791,8 +1793,8 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientPlayerEnterVehicle/onClientPedEnterVehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(ucSeat); // seat + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(ucSeat); // seat if (IS_PLAYER(pPed)) pPed->CallEvent("onClientPlayerVehicleEnter", Arguments, true); else @@ -1800,8 +1802,8 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientVehicleEnter event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(ucSeat); // seat + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(ucSeat); // seat pVehicle->CallEvent("onClientVehicleEnter", Arguments2, true); break; } @@ -1827,25 +1829,27 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) CClientPed* pJacked = pVehicle->GetOccupant(ucSeat); // If it's the local player or syncing ped getting jacked, reset some stuff - if (pJacked) { - if (pJacked->IsLocalPlayer() || pJacked->IsSyncing()) { + if (pJacked) + { + if (pJacked->IsLocalPlayer() || pJacked->IsSyncing()) + { pJacked->ResetVehicleInOut(); } - else { + else + { // Desynced? Outside but supposed to be in // For local player or synced peds this is taken care of in CClientPed::UpdateVehicleInOut() - if (pJacked->GetOccupiedVehicle() && !pJacked->GetRealOccupiedVehicle()) { + if (pJacked->GetOccupiedVehicle() && !pJacked->GetRealOccupiedVehicle()) + { // Warp him back in pJacked->WarpIntoVehicle(pJacked->GetOccupiedVehicle(), pJacked->GetOccupiedVehicleSeat()); // For bikes and cars where jacked through passenger door, warp the passenger back in if desynced - if (ucSeat == 0) { + if (ucSeat == 0) + { CClientPed* pPassenger = pJacked->GetOccupiedVehicle()->GetOccupant(1); // Is the passenger a remote player or ped and is he physically outside but supposed to be in - if (pPassenger && - !pPassenger->IsLocalPlayer() && - !pPassenger->IsSyncing() && - pPassenger->GetOccupiedVehicle() && + if (pPassenger && !pPassenger->IsLocalPlayer() && !pPassenger->IsSyncing() && pPassenger->GetOccupiedVehicle() && !pPassenger->GetRealOccupiedVehicle()) { pPassenger->WarpIntoVehicle(pPassenger->GetOccupiedVehicle(), pPassenger->GetOccupiedVehicleSeat()); @@ -1889,9 +1893,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) pPed->SetVehicleInOutState(VEHICLE_INOUT_GETTING_OUT); CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(ucSeat); // seat - Arguments.PushNumber(ucDoor); // door being used + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(ucSeat); // seat + Arguments.PushNumber(ucDoor); // door being used pVehicle->CallEvent("onClientVehicleStartExit", Arguments, true); break; } @@ -1914,9 +1918,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientPlayerExitVehicle/onClientPedExitVehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(ucSeat); // seat - Arguments.PushBoolean(false); // jacker + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(ucSeat); // seat + Arguments.PushBoolean(false); // jacker if (IS_PLAYER(pPed)) pPed->CallEvent("onClientPlayerVehicleExit", Arguments, true); else @@ -1924,9 +1928,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientVehicleExit event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(ucSeat); // seat - Arguments2.PushBoolean(false); // jacker + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(ucSeat); // seat + Arguments2.PushBoolean(false); // jacker pVehicle->CallEvent("onClientVehicleExit", Arguments2, true); break; } @@ -1961,9 +1965,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) pVehicle->RemoveTargetPosition(); CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(ucSeat); // seat - Arguments.PushBoolean(false); // jacker + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(ucSeat); // seat + Arguments.PushBoolean(false); // jacker if (IS_PLAYER(pPed)) pPed->CallEvent("onClientPlayerVehicleExit", Arguments, true); else @@ -1971,9 +1975,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientVehicleExit event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(ucSeat); // seat - Arguments2.PushBoolean(false); // jacker + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(ucSeat); // seat + Arguments2.PushBoolean(false); // jacker pVehicle->CallEvent("onClientVehicleExit", Arguments2, true); break; } @@ -1998,9 +2002,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientVehicleStartEnter event for remote players and peds we don't sync // Local player / Syncing player triggers it himself before sending packet in CClientPed CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(ucSeat); // seat - Arguments.PushNumber(ucDoor); // Door + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(ucSeat); // seat + Arguments.PushNumber(ucDoor); // Door pVehicle->CallEvent("onClientVehicleStartEnter", Arguments, true); } @@ -2024,9 +2028,9 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) pPed->SetVehicleInOutState(VEHICLE_INOUT_JACKING); CLuaArguments Arguments2; - Arguments2.PushElement(pJacked); // player / ped - Arguments2.PushNumber(ucSeat); // seat - Arguments2.PushNumber(ucDoor); // door + Arguments2.PushElement(pJacked); // player / ped + Arguments2.PushNumber(ucSeat); // seat + Arguments2.PushNumber(ucDoor); // door pVehicle->CallEvent("onClientVehicleStartExit", Arguments2, true); break; } @@ -2091,27 +2095,27 @@ void CPacketHandler::Packet_Vehicle_InOut(NetBitStreamInterface& bitStream) // Call the onClientVehicleStartEnter event CLuaArguments Arguments; - Arguments.PushElement(pInsidePed); // player / ped - Arguments.PushNumber(ucSeat); // seat + Arguments.PushElement(pInsidePed); // player / ped + Arguments.PushNumber(ucSeat); // seat pVehicle->CallEvent("onClientVehicleEnter", Arguments, true); CLuaArguments Arguments2; - Arguments2.PushElement(pOutsidePed); // player / ped - Arguments2.PushNumber(ucSeat); // seat + Arguments2.PushElement(pOutsidePed); // player / ped + Arguments2.PushNumber(ucSeat); // seat pVehicle->CallEvent("onClientVehicleExit", Arguments2, true); CLuaArguments Arguments3; - Arguments3.PushElement(pVehicle); // vehicle - Arguments3.PushNumber(ucSeat); // seat - Arguments3.PushElement(pInsidePed); // jacker + Arguments3.PushElement(pVehicle); // vehicle + Arguments3.PushNumber(ucSeat); // seat + Arguments3.PushElement(pInsidePed); // jacker if (IS_PLAYER(pOutsidePed)) pOutsidePed->CallEvent("onClientPlayerVehicleExit", Arguments3, true); else pOutsidePed->CallEvent("onClientPedVehicleExit", Arguments3, true); CLuaArguments Arguments4; - Arguments4.PushElement(pVehicle); // vehicle - Arguments4.PushNumber(ucSeat); // seat + Arguments4.PushElement(pVehicle); // vehicle + Arguments4.PushNumber(ucSeat); // seat if (IS_PLAYER(pInsidePed)) pInsidePed->CallEvent("onClientPlayerVehicleEnter", Arguments4, true); else @@ -2193,9 +2197,9 @@ void CPacketHandler::Packet_VehicleTrailer(NetBitStreamInterface& bitStream) pTrailer->SetRotationDegrees(rotation.data.vecRotation); pTrailer->SetTurnSpeed(turn.data.vecVelocity); - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG g_pCore->GetConsole()->Printf("Packet_VehicleTrailer: attaching trailer %d to vehicle %d", TrailerID, ID); - #endif +#endif pVehicle->SetTowedVehicle(pTrailer); // Call the onClientTrailerAttach @@ -2205,9 +2209,9 @@ void CPacketHandler::Packet_VehicleTrailer(NetBitStreamInterface& bitStream) } else { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG g_pCore->GetConsole()->Printf("Packet_VehicleTrailer: detaching trailer %d from vehicle %d", TrailerID, ID); - #endif +#endif pVehicle->SetTowedVehicle(NULL); // Call the onClientTrailerDetach @@ -2218,12 +2222,12 @@ void CPacketHandler::Packet_VehicleTrailer(NetBitStreamInterface& bitStream) } else { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG if (!pVehicle) g_pCore->GetConsole()->Printf("Packet_VehicleTrailer: vehicle (id %d) not found", ID); if (!pTrailer) g_pCore->GetConsole()->Printf("Packet_VehicleTrailer: trailer (id %d) not found", TrailerID); - #endif +#endif } } } @@ -2366,7 +2370,7 @@ void CPacketHandler::Packet_MapInfo(NetBitStreamInterface& bitStream) // Apply world sea level (to world sea level water only) g_pClientGame->GetManager()->GetWaterManager()->SetWorldWaterLevel(fSeaLevel, nullptr, false, true, false); - std::uint16_t fps = 36; // Default to 36 + std::uint16_t fps = 36; // Default to 36 bitStream.ReadCompressed(fps); CStaticFunctionDefinitions::SetServerFPSLimit(fps); @@ -2699,8 +2703,8 @@ void CPacketHandler::Packet_PlayerNetworkStatus(NetBitStreamInterface& bitStream if (bitStream.Read(ucType) && bitStream.Read(uiTicks)) { CLuaArguments Arguments; - Arguments.PushNumber(ucType); // 0-interruption began 1-interruption end - Arguments.PushNumber(uiTicks); // Ticks since interruption start + Arguments.PushNumber(ucType); // 0-interruption began 1-interruption end + Arguments.PushNumber(uiTicks); // Ticks since interruption start CClientPlayer* pLocalPlayer = g_pClientGame->m_pPlayerManager->GetLocalPlayer(); if (pLocalPlayer) { @@ -2716,104 +2720,104 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) if (g_pClientGame) g_pClientGame->NotifyBigPacketProgress(0, 0); - // This packet contains a list over entities to add to the world. - // There's a byte seperating the entities saying what type it is (vehicle spawn,object,weapon pickup) - - // Common: - // ElementID (2) - entity id - // unsigned char (1) - entity type id - // ElementID (2) - parent entity id - // unsigned char (1) - entity interior - // unsigned short (2) - entity dimension - // ElementID (2) - attached to entity id - // bool (1) - collisions enabled - // ??? (?) - custom data - - // Objects: - // CVector (12) - position - // CVector (12) - rotation - // unsigned short (2) - object model id - // unsigned char (1) - alpha - // CVector (12) - scale - // bool (1) - static - // SObjectHealthSync (?) - health - // bool (1) - is break - // bool (1) - respawnable - - // Pickups: - // CVector (12) - position - // unsigned char (1) - type - // bool - visible? - // unsigned char (1) - weapon type (if type is weapon) - - // Vehicles: - // CMatrix (48) - matrix - // unsigned char (1) - vehicle id - // float (4) - health - // unsigned char (1) - blow state (if supported) - // unsigned char (1) - color 1 - // unsigned char (1) - color 2 - // unsigned char (1) - color 3 - // unsigned char (1) - color 4 - // unsigned char (1) - paintjob - // float (4) - turret position x (if applies) - // float (4) - turret position y (if applies) - // unsigned short (2) - adjustable property (if applies) - // SDoorAngleSync (?) - Door #0 angle ratio. - // SDoorAngleSync (?) - Door #1 angle ratio. - // SDoorAngleSync (?) - Door #2 angle ratio. - // SDoorAngleSync (?) - Door #3 angle ratio. - // SDoorAngleSync (?) - Door #4 angle ratio. - // SDoorAngleSync (?) - Door #5 angle ratio. - // bool - landing gear down? (if applies) - // bool - sirenes on? (if applies) - // unsigned char (1) - no. of upgrades - // unsigned char (1++) - list of upgrades - // unsigned char (1) - reg-plate length - // char[] (?) - reg-plate - // unsigned char (1) - light override - // bool - can shoot petrol tank - // bool - engine on - // bool - locked - // bool - doors damageable - - // Blips: - // bool - attached to an entity? - // -- following if attached: - // unsigned char (1) - attached entity type - // unsigned char/short (1/2) - attached entity id (char if player, otherwize short) - // -- following if not attached: - // CVector (12) - position - // -- end - // unsigned char (1) - icon - // -- if icon is 0 - // unsigned char (1) - size - // unsigned long (4) - color - - // Radar areas: - // CVector2D (8) - position - // CVector2D (8) - size - // unsigned long (4) - color - // bool - flashing? - - // Path Nodes: - // CVector (12) - position - // CVector (12) - rotation - // int (4) - time - // unsigned char (1) - style - // ElementID (2) - next-node id - - // World meshes - // unsigned short (2) - name length - // char[] (?) - name - // CVector (12) - position - // CVector (12) - rotation - - // Teams - // unsigned short (2) - name length - // char[] (?) - name - // unsigned char[3] (3) - cols - // unsigned char (1) - friendly-fire + // This packet contains a list over entities to add to the world. + // There's a byte seperating the entities saying what type it is (vehicle spawn,object,weapon pickup) + + // Common: + // ElementID (2) - entity id + // unsigned char (1) - entity type id + // ElementID (2) - parent entity id + // unsigned char (1) - entity interior + // unsigned short (2) - entity dimension + // ElementID (2) - attached to entity id + // bool (1) - collisions enabled + // ??? (?) - custom data + + // Objects: + // CVector (12) - position + // CVector (12) - rotation + // unsigned short (2) - object model id + // unsigned char (1) - alpha + // CVector (12) - scale + // bool (1) - static + // SObjectHealthSync (?) - health + // bool (1) - is break + // bool (1) - respawnable + + // Pickups: + // CVector (12) - position + // unsigned char (1) - type + // bool - visible? + // unsigned char (1) - weapon type (if type is weapon) + + // Vehicles: + // CMatrix (48) - matrix + // unsigned char (1) - vehicle id + // float (4) - health + // unsigned char (1) - blow state (if supported) + // unsigned char (1) - color 1 + // unsigned char (1) - color 2 + // unsigned char (1) - color 3 + // unsigned char (1) - color 4 + // unsigned char (1) - paintjob + // float (4) - turret position x (if applies) + // float (4) - turret position y (if applies) + // unsigned short (2) - adjustable property (if applies) + // SDoorAngleSync (?) - Door #0 angle ratio. + // SDoorAngleSync (?) - Door #1 angle ratio. + // SDoorAngleSync (?) - Door #2 angle ratio. + // SDoorAngleSync (?) - Door #3 angle ratio. + // SDoorAngleSync (?) - Door #4 angle ratio. + // SDoorAngleSync (?) - Door #5 angle ratio. + // bool - landing gear down? (if applies) + // bool - sirenes on? (if applies) + // unsigned char (1) - no. of upgrades + // unsigned char (1++) - list of upgrades + // unsigned char (1) - reg-plate length + // char[] (?) - reg-plate + // unsigned char (1) - light override + // bool - can shoot petrol tank + // bool - engine on + // bool - locked + // bool - doors damageable + + // Blips: + // bool - attached to an entity? + // -- following if attached: + // unsigned char (1) - attached entity type + // unsigned char/short (1/2) - attached entity id (char if player, otherwize short) + // -- following if not attached: + // CVector (12) - position + // -- end + // unsigned char (1) - icon + // -- if icon is 0 + // unsigned char (1) - size + // unsigned long (4) - color + + // Radar areas: + // CVector2D (8) - position + // CVector2D (8) - size + // unsigned long (4) - color + // bool - flashing? + + // Path Nodes: + // CVector (12) - position + // CVector (12) - rotation + // int (4) - time + // unsigned char (1) - style + // ElementID (2) - next-node id + + // World meshes + // unsigned short (2) - name length + // char[] (?) - name + // CVector (12) - position + // CVector (12) - rotation + + // Teams + // unsigned short (2) - name length + // char[] (?) - name + // unsigned char[3] (3) - cols + // unsigned char (1) - friendly-fire #if MTA_DEBUG retry: @@ -2893,7 +2897,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) } else { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG char buf[256] = {0}; bitStream.Read(buf, ucNameLength); // Raise a special assert, as we have to try and figure out this error. @@ -2901,7 +2905,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) // Replay the problem for debugging bitStream.ResetReadPointer(); goto retry; - #endif +#endif delete pCustomData; pCustomData = NULL; @@ -2912,11 +2916,11 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) } else { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG // Jax: had this with a colshape (ucNameLength=109,us=0,usNumData=4) // Raise a special assert, as we have to try and figure out this error. assert(0); - #endif +#endif delete pCustomData; pCustomData = NULL; @@ -3054,7 +3058,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) } CVector vecScale; - bool bIsUniform; + bool bIsUniform; bitStream.ReadBit(bIsUniform); if (bIsUniform) { @@ -3093,7 +3097,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) { CClientWeapon* pWeapon = (CClientWeapon*)pObject; unsigned char ucTargetType = eTargetType::TARGET_TYPE_FIXED; - bitStream.ReadBits(&ucTargetType, 3); // 3 bits = 4 possible values. + bitStream.ReadBits(&ucTargetType, 3); // 3 bits = 4 possible values. switch (ucTargetType) { case TARGET_TYPE_FIXED: @@ -3112,13 +3116,13 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) { if (IS_PED(pTarget)) { - bitStream.Read(ucSubTarget); // Send the entire unsigned char as there are a lot of bones. + bitStream.Read(ucSubTarget); // Send the entire unsigned char as there are a lot of bones. } else if (IS_VEHICLE(pTarget)) { bitStream.ReadBits(&ucSubTarget, 4); } - pWeapon->SetWeaponTarget(pTarget, ucSubTarget); // 4 bits = 8 possible values. + pWeapon->SetWeaponTarget(pTarget, ucSubTarget); // 4 bits = 8 possible values. } break; } @@ -3136,7 +3140,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) { float fAccuracy, fTargetRange, fWeaponRange; unsigned short usDamagePerHit; - bitStream.ReadBits(&usDamagePerHit, 12); // 12 bits = 2048 values... plenty. + bitStream.ReadBits(&usDamagePerHit, 12); // 12 bits = 2048 values... plenty. bitStream.Read(fAccuracy); bitStream.Read(fTargetRange); bitStream.Read(fWeaponRange); @@ -3163,7 +3167,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) unsigned short usAmmo, usClipAmmo; unsigned char ucWeaponState; - bitStream.ReadBits(&ucWeaponState, 4); // 4 bits = 8 possible values for weapon state + bitStream.ReadBits(&ucWeaponState, 4); // 4 bits = 8 possible values for weapon state bitStream.Read(usAmmo); bitStream.Read(usClipAmmo); pWeapon->SetClipAmmo(usClipAmmo); @@ -3961,10 +3965,10 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) if (bitStream.ReadBit()) { std::string blockName, animName; - int time, blendTime; - bool looped, updatePosition, interruptable, freezeLastFrame, taskRestore; - float speed; - double startTime; + int time, blendTime; + bool looped, updatePosition, interruptable, freezeLastFrame, taskRestore; + float speed; + double startTime; // Read data bitStream.ReadString(blockName); @@ -3980,7 +3984,8 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) bitStream.Read(speed); // Run anim - CStaticFunctionDefinitions::SetPedAnimation(*pPed, blockName, animName.c_str(), time, blendTime, looped, updatePosition, interruptable, freezeLastFrame); + CStaticFunctionDefinitions::SetPedAnimation(*pPed, blockName, animName.c_str(), time, blendTime, looped, updatePosition, interruptable, + freezeLastFrame); pPed->m_AnimationCache.startTime = static_cast(startTime); pPed->m_AnimationCache.speed = speed; pPed->m_AnimationCache.progress = 0.0f; @@ -4016,7 +4021,7 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) { CResource* pResource = g_pClientGame->m_pResourceManager->GetResource(szName); if (pResource) - pResource->SetResourceEntity(pDummy); // problem with resource starting without this entity + pResource->SetResourceEntity(pDummy); // problem with resource starting without this entity } } @@ -4184,7 +4189,8 @@ void CPacketHandler::Packet_EntityAdd(NetBitStreamInterface& bitStream) modelId = 1700; bitStream.Read(LowLodObjectID); - CClientBuilding* pBuilding = new CClientBuilding(g_pClientGame->m_pManager, EntityID, modelId, position.data.vecPosition, rotationRadians.data.vecRotation, ucInterior); + CClientBuilding* pBuilding = new CClientBuilding(g_pClientGame->m_pManager, EntityID, modelId, position.data.vecPosition, + rotationRadians.data.vecRotation, ucInterior); pBuilding->SetUsesCollision(bCollisonsEnabled); break; @@ -4521,7 +4527,7 @@ void CPacketHandler::Packet_TextItem(NetBitStreamInterface& bitStream) // Does the text not already exist? Create it std::shared_ptr textDisplay = nullptr; - std::shared_ptr display = g_pClientGame->m_pDisplayManager->Get(ulID); + std::shared_ptr display = g_pClientGame->m_pDisplayManager->Get(ulID); if (display && display->GetType() == DISPLAY_TEXT) { @@ -4708,7 +4714,7 @@ void CPacketHandler::Packet_ExplosionSync(NetBitStreamInterface& bitStream) // Call onClientVehicleExplode CLuaArguments arguments; - arguments.PushBoolean(!bCancelExplosion); // withExplosion + arguments.PushBoolean(!bCancelExplosion); // withExplosion vehicle->CallEvent("onClientVehicleExplode", arguments, true); if (!bCancelExplosion) @@ -5159,7 +5165,7 @@ void CPacketHandler::Packet_ResourceStart(NetBitStreamInterface& bitStream) { switch (ucChunkType) { - case 'E': // Exported Function + case 'E': // Exported Function if (bitStream.Read(ucChunkSize)) { szChunkData = new char[ucChunkSize + 1]; @@ -5173,7 +5179,7 @@ void CPacketHandler::Packet_ResourceStart(NetBitStreamInterface& bitStream) } break; - case 'F': // Resource File + case 'F': // Resource File if (bitStream.Read(ucChunkSize)) { szChunkData = new char[ucChunkSize + 1]; diff --git a/Client/mods/deathmatch/logic/CPedSync.cpp b/Client/mods/deathmatch/logic/CPedSync.cpp index dce4f5f55b4..8e8bc8dd84f 100644 --- a/Client/mods/deathmatch/logic/CPedSync.cpp +++ b/Client/mods/deathmatch/logic/CPedSync.cpp @@ -15,7 +15,7 @@ using std::list; extern CClientGame* g_pClientGame; -#define PED_SYNC_RATE ( g_TickRateSettings.iPedSync ) +#define PED_SYNC_RATE (g_TickRateSettings.iPedSync) CPedSync::CPedSync(CClientPedManager* pPedManager) { @@ -124,7 +124,7 @@ void CPedSync::Packet_PedStartSync(NetBitStreamInterface& BitStream) float fHealth, fArmor; BitStream.Read(fHealth); BitStream.Read(fArmor); - + float cameraRotation{}; BitStream.Read(cameraRotation); pPed->SetCameraRotation(cameraRotation); @@ -186,7 +186,7 @@ void CPedSync::Packet_PedSync(NetBitStreamInterface& BitStream) std::uint8_t flags2{}; BitStream.Read(flags2); - CVector vecPosition{ CVector::NoInit{} }, vecMoveSpeed{ CVector::NoInit{} }; + CVector vecPosition{CVector::NoInit{}}, vecMoveSpeed{CVector::NoInit{}}; float fRotation, fHealth, fArmor; bool bOnFire; bool bIsInWater; diff --git a/Client/mods/deathmatch/logic/CPlayerMap.cpp b/Client/mods/deathmatch/logic/CPlayerMap.cpp index fe089cd23b0..4d495e6a131 100644 --- a/Client/mods/deathmatch/logic/CPlayerMap.cpp +++ b/Client/mods/deathmatch/logic/CPlayerMap.cpp @@ -77,12 +77,11 @@ CPlayerMap::CPlayerMap(CClientManager* pManager) {colorWhiteTransparent, 0.92f, 1.5f, ""}, {colorWhite, 0.95f, 1.0f, SString(_("Change mode: %s"), *GetBoundKeyName("radar_attach"))}, - {colorWhite, 0.05f, 1.0f, SString(_("Zoom: %s/%s Movement: %s, %s, %s, %s Opacity: %s/%s"), - *GetBoundKeyName("radar_zoom_in"), *GetBoundKeyName("radar_zoom_out"), *GetBoundKeyName("radar_move_north"), - *GetBoundKeyName("radar_move_east"), *GetBoundKeyName("radar_move_south"), *GetBoundKeyName("radar_move_west"), - *GetBoundKeyName("radar_opacity_down"), *GetBoundKeyName("radar_opacity_up"))}, - {colorWhite, 0.07f, 1.0f, SString(_("Toggle map: %s Toggle help text: %s"), - *GetBoundKeyName("radar"), *GetBoundKeyName("radar_help"))}, + {colorWhite, 0.05f, 1.0f, + SString(_("Zoom: %s/%s Movement: %s, %s, %s, %s Opacity: %s/%s"), *GetBoundKeyName("radar_zoom_in"), *GetBoundKeyName("radar_zoom_out"), + *GetBoundKeyName("radar_move_north"), *GetBoundKeyName("radar_move_east"), *GetBoundKeyName("radar_move_south"), + *GetBoundKeyName("radar_move_west"), *GetBoundKeyName("radar_opacity_down"), *GetBoundKeyName("radar_opacity_up"))}, + {colorWhite, 0.07f, 1.0f, SString(_("Toggle map: %s Toggle help text: %s"), *GetBoundKeyName("radar"), *GetBoundKeyName("radar_help"))}, }; for (uint i = 0; i < NUMELMS(messageList); i++) @@ -267,11 +266,11 @@ CTextureItem* CPlayerMap::GetMarkerTexture(CClientRadarMarker* pMarker, float fL pMarker->GetPosition(vecMarker); if (fLocalZ > vecMarker.fZ + 4.0f) - uiListIndex = MARKER_DOWN_TRIANGLE_INDEX; // We're higher than this marker, so draw the arrow pointing down + uiListIndex = MARKER_DOWN_TRIANGLE_INDEX; // We're higher than this marker, so draw the arrow pointing down else if (fLocalZ < vecMarker.fZ - 4.0f) - uiListIndex = MARKER_UP_TRIANGLE_INDEX; // We're lower than this entity, so draw the arrow pointing up + uiListIndex = MARKER_UP_TRIANGLE_INDEX; // We're lower than this entity, so draw the arrow pointing up else - uiListIndex = MARKER_SQUARE_INDEX; // We're at the same level so draw a square + uiListIndex = MARKER_SQUARE_INDEX; // We're at the same level so draw a square fScale /= 4; } @@ -718,7 +717,8 @@ void CPlayerMap::SetAttachedToLocalPlayer(bool bIsAttachedToLocal) bool CPlayerMap::IsPlayerMapShowing() { - return ((m_bIsPlayerMapEnabled || m_bForcedState) && m_mapImageTexture && m_playerMarkerTexture && (!g_pCore->GetConsole()->IsVisible() && !g_pCore->IsMenuVisible())); + return ((m_bIsPlayerMapEnabled || m_bForcedState) && m_mapImageTexture && m_playerMarkerTexture && + (!g_pCore->GetConsole()->IsVisible() && !g_pCore->IsMenuVisible())); } bool CPlayerMap::GetBoundingBox(CVector& vecMin, CVector& vecMax) diff --git a/Client/mods/deathmatch/logic/CPlayerMap.h b/Client/mods/deathmatch/logic/CPlayerMap.h index d03f40892e0..eefd8cc99ed 100644 --- a/Client/mods/deathmatch/logic/CPlayerMap.h +++ b/Client/mods/deathmatch/logic/CPlayerMap.h @@ -117,7 +117,7 @@ class CPlayerMap unsigned long m_ulUpdateTime; std::vector> m_HelpTextList; - bool m_bHideHelpText; + bool m_bHideHelpText; bool m_bHudVisible; bool m_bChatVisible; diff --git a/Client/mods/deathmatch/logic/CRegisteredCommands.cpp b/Client/mods/deathmatch/logic/CRegisteredCommands.cpp index 370176b8797..5119e5e2245 100644 --- a/Client/mods/deathmatch/logic/CRegisteredCommands.cpp +++ b/Client/mods/deathmatch/logic/CRegisteredCommands.cpp @@ -31,17 +31,18 @@ bool CRegisteredCommands::AddCommand(CLuaMain* pLuaMain, const char* szKey, cons if (CommandExists(szKey, nullptr)) { const MultiCommandHandlerPolicy allowMultiHandlers = g_pClientGame->GetAllowMultiCommandHandlers(); - + switch (allowMultiHandlers) { case MultiCommandHandlerPolicy::BLOCK: - g_pClientGame->GetScriptDebugging()->LogError(pLuaMain->GetVM(), "addCommandHandler: Duplicate command registration blocked for '%s' (multiple handlers disabled)", szKey); + g_pClientGame->GetScriptDebugging()->LogError( + pLuaMain->GetVM(), "addCommandHandler: Duplicate command registration blocked for '%s' (multiple handlers disabled)", szKey); return false; - + case MultiCommandHandlerPolicy::WARN: g_pClientGame->GetScriptDebugging()->LogWarning(pLuaMain->GetVM(), "addCommandHandler: Attempt to register duplicate command '%s'", szKey); break; - + case MultiCommandHandlerPolicy::ALLOW: default: break; diff --git a/Client/mods/deathmatch/logic/CRegisteredCommands.h b/Client/mods/deathmatch/logic/CRegisteredCommands.h index 1fe63e25cfb..612f1d75da9 100644 --- a/Client/mods/deathmatch/logic/CRegisteredCommands.h +++ b/Client/mods/deathmatch/logic/CRegisteredCommands.h @@ -14,7 +14,7 @@ #include #include -#define MAX_REGISTERED_COMMAND_LENGTH 64 +#define MAX_REGISTERED_COMMAND_LENGTH 64 #define MAX_REGISTERED_COMMANDHANDLER_LENGTH 64 enum class MultiCommandHandlerPolicy : std::uint8_t diff --git a/Client/mods/deathmatch/logic/CRemoteCalls.cpp b/Client/mods/deathmatch/logic/CRemoteCalls.cpp index 4c6154bd724..e105a91910a 100644 --- a/Client/mods/deathmatch/logic/CRemoteCalls.cpp +++ b/Client/mods/deathmatch/logic/CRemoteCalls.cpp @@ -147,12 +147,13 @@ void CRemoteCall::MakeCall() m_iStartTime = GetTickCount64_(); const auto pWebCore = g_pCore->GetWebCore(); - bool bAnyHost = false; - + bool bAnyHost = false; + if (pWebCore) { // GetDomainFromURL requires protocol:// - const SString strDomain = [&]() { + const SString strDomain = [&]() + { SString domain = pWebCore->GetDomainFromURL(m_strURL); if (domain.empty()) domain = pWebCore->GetDomainFromURL("https://" + m_strURL); @@ -161,7 +162,7 @@ void CRemoteCall::MakeCall() // Bypass net module IP check if allowed to access the URL bAnyHost = (pWebCore->GetDomainState(strDomain) == eURLState::WEBPAGE_ALLOWED); } - + m_downloadMode = g_pClientGame->GetRemoteCalls()->GetDownloadModeForQueueName(m_strQueueName, bAnyHost); CNetHTTPDownloadManagerInterface* pDownloadManager = g_pNet->GetHTTPDownloadManager(m_downloadMode); pDownloadManager->QueueFile(m_strURL, NULL, this, DownloadFinishedCallback, m_options); diff --git a/Client/mods/deathmatch/logic/CResource.cpp b/Client/mods/deathmatch/logic/CResource.cpp index d1d9be1f8ea..e92473d3485 100644 --- a/Client/mods/deathmatch/logic/CResource.cpp +++ b/Client/mods/deathmatch/logic/CResource.cpp @@ -39,7 +39,7 @@ CResource::CResource(unsigned short usNetID, const char* szResourceName, CClient m_pLuaManager = g_pClientGame->GetLuaManager(); m_pRootEntity = g_pClientGame->GetRootEntity(); - m_pDefaultElementGroup = new CElementGroup(); // for use by scripts + m_pDefaultElementGroup = new CElementGroup(); // for use by scripts m_pResourceEntity = pResourceEntity; m_pResourceDynamicEntity = pResourceDynamicEntity; @@ -114,11 +114,11 @@ CResource::~CResource() // Remove all keybinds on this VM g_pClientGame->GetScriptKeyBinds()->RemoveAllKeys(m_pLuaVM); - + // Remove all resource-specific command bindings while preserving user bindings CKeyBindsInterface* pKeyBinds = g_pCore->GetKeyBinds(); pKeyBinds->SetAllCommandsActive(m_strResourceName, false); - + // Additional cleanup: remove any remaining resource bindings that weren't caught by SetAllCommandsActive for (auto& bind : *pKeyBinds) { diff --git a/Client/mods/deathmatch/logic/CResource.h b/Client/mods/deathmatch/logic/CResource.h index 1791a82c993..7e0688d6d6f 100644 --- a/Client/mods/deathmatch/logic/CResource.h +++ b/Client/mods/deathmatch/logic/CResource.h @@ -19,8 +19,8 @@ #include "CElementGroup.h" #include -#define MAX_RESOURCE_NAME_LENGTH 255 -#define MAX_FUNCTION_NAME_LENGTH 50 +#define MAX_RESOURCE_NAME_LENGTH 255 +#define MAX_FUNCTION_NAME_LENGTH 50 struct SNoClientCacheScript { @@ -124,8 +124,8 @@ class CResource bool m_bActive; bool m_bStarting; bool m_bStopping; - class CClientEntity* m_pResourceEntity; // no idea what this is used for anymore - class CClientEntity* m_pResourceDynamicEntity; // parent of elements created by the resource + class CClientEntity* m_pResourceEntity; // no idea what this is used for anymore + class CClientEntity* m_pResourceDynamicEntity; // parent of elements created by the resource class CClientEntity* m_pResourceCOLRoot; class CClientEntity* m_pResourceDFFEntity; class CClientEntity* m_pResourceGUIEntity; @@ -143,14 +143,14 @@ class CResource static int m_iShowingCursor; bool m_bShowingCursor; - SString m_strResourceDirectoryPath; // stores the path to /mods/deathmatch/resources/resource_name - SString m_strResourcePrivateDirectoryPath; // stores the path to /mods/deathmatch/priv/server-id/resource_name - SString m_strResourcePrivateDirectoryPathOld; // stores the path to /mods/deathmatch/priv/old-server-id/resource_name + SString m_strResourceDirectoryPath; // stores the path to /mods/deathmatch/resources/resource_name + SString m_strResourcePrivateDirectoryPath; // stores the path to /mods/deathmatch/priv/server-id/resource_name + SString m_strResourcePrivateDirectoryPathOld; // stores the path to /mods/deathmatch/priv/old-server-id/resource_name std::list m_ResourceFiles; std::list m_ConfigFiles; CFastHashSet m_exportedFunctions; - CElementGroup* m_pDefaultElementGroup; // stores elements created by scripts in this resource + CElementGroup* m_pDefaultElementGroup; // stores elements created by scripts in this resource std::list m_NoClientCacheScriptList; CResourceModelStreamer m_modelStreamer{}; diff --git a/Client/mods/deathmatch/logic/CResourceConfigItem.cpp b/Client/mods/deathmatch/logic/CResourceConfigItem.cpp index d68bd1a53b0..22de1f3fd6f 100644 --- a/Client/mods/deathmatch/logic/CResourceConfigItem.cpp +++ b/Client/mods/deathmatch/logic/CResourceConfigItem.cpp @@ -91,4 +91,4 @@ bool CResourceConfigItem::Stop() } return true; -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CResourceConfigItem.h b/Client/mods/deathmatch/logic/CResourceConfigItem.h index 1d9dcbc22d5..c53ea708163 100644 --- a/Client/mods/deathmatch/logic/CResourceConfigItem.h +++ b/Client/mods/deathmatch/logic/CResourceConfigItem.h @@ -16,7 +16,7 @@ #include #ifndef MAX_PATH -#define MAX_PATH 260 + #define MAX_PATH 260 #endif class CResourceConfigItem : public CDownloadableResource diff --git a/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp b/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp index f10ef66ed2f..7aff76f288e 100644 --- a/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp +++ b/Client/mods/deathmatch/logic/CResourceFileDownloadManager.cpp @@ -142,7 +142,7 @@ void CResourceFileDownloadManager::DoPulse() AddReportLog(7106, SString("Game - HTTPError (%s)", *m_strLastHTTPError)); g_pCore->GetModManager()->RequestUnload(); - g_pCore->ShowMessageBox(_("Error") + _E("CD20"), *m_strLastHTTPError, MB_BUTTON_OK | MB_ICON_ERROR); // HTTP Error + g_pCore->ShowMessageBox(_("Error") + _E("CD20"), *m_strLastHTTPError, MB_BUTTON_OK | MB_ICON_ERROR); // HTTP Error m_bIsTransferingFiles = false; return; } diff --git a/Client/mods/deathmatch/logic/CResourceManager.cpp b/Client/mods/deathmatch/logic/CResourceManager.cpp index affe51f7475..895b7223b5f 100644 --- a/Client/mods/deathmatch/logic/CResourceManager.cpp +++ b/Client/mods/deathmatch/logic/CResourceManager.cpp @@ -60,7 +60,7 @@ CResource* CResourceManager::GetResourceFromNetID(unsigned short usNetID) { if ((*iter)->GetNetID() == usNetID) { - assert(0); // Should be in map + assert(0); // Should be in map return (*iter); } } diff --git a/Client/mods/deathmatch/logic/CResourceManager.h b/Client/mods/deathmatch/logic/CResourceManager.h index d79bff256d7..b3578eab94d 100644 --- a/Client/mods/deathmatch/logic/CResourceManager.h +++ b/Client/mods/deathmatch/logic/CResourceManager.h @@ -54,7 +54,8 @@ class CResourceManager void ValidateResourceFile(const SString& strFilename, const char* buffer, size_t bufferSize); CDownloadableResource* GetDownloadableResourceFile(const SString& strFilename) { return MapFindRef(m_ResourceFileMap, strFilename); } - static bool ParseResourcePathInput(std::string strInput, CResource*& pResource, std::string* pStrPath, std::string* pStrMetaPath = nullptr, bool bPassSize = false); + static bool ParseResourcePathInput(std::string strInput, CResource*& pResource, std::string* pStrPath, std::string* pStrMetaPath = nullptr, + bool bPassSize = false); private: CMappedList m_resources; diff --git a/Client/mods/deathmatch/logic/CResourceModelStreamer.cpp b/Client/mods/deathmatch/logic/CResourceModelStreamer.cpp index a2209bf30e2..d724270c6ea 100644 --- a/Client/mods/deathmatch/logic/CResourceModelStreamer.cpp +++ b/Client/mods/deathmatch/logic/CResourceModelStreamer.cpp @@ -87,7 +87,7 @@ bool CResourceModelStreamer::ReleaseModel(std::uint16_t modelId, bool removeRef) void CResourceModelStreamer::ReleaseAll() { - for (const auto &modelRefs : m_requestedModels) + for (const auto& modelRefs : m_requestedModels) { if (modelRefs.second > 0) { diff --git a/Client/mods/deathmatch/logic/CScriptDebugging.cpp b/Client/mods/deathmatch/logic/CScriptDebugging.cpp index e961076d9e2..827ab9387d0 100644 --- a/Client/mods/deathmatch/logic/CScriptDebugging.cpp +++ b/Client/mods/deathmatch/logic/CScriptDebugging.cpp @@ -36,7 +36,7 @@ CScriptDebugging::~CScriptDebugging() if (m_flushTimerHandle) { // delete our flush timer - DeleteTimerQueueTimer(nullptr, m_flushTimerHandle, INVALID_HANDLE_VALUE); // INVALID_HANDLE_VALUE = wait for running callbacks to finish + DeleteTimerQueueTimer(nullptr, m_flushTimerHandle, INVALID_HANDLE_VALUE); // INVALID_HANDLE_VALUE = wait for running callbacks to finish } fclose(m_pLogFile); m_pLogFile = nullptr; @@ -71,7 +71,7 @@ bool CScriptDebugging::SetLogfile(const char* szFilename, unsigned int uiLevel) if (m_flushTimerHandle) { // delete our flush timer - DeleteTimerQueueTimer(nullptr, m_flushTimerHandle, INVALID_HANDLE_VALUE); // INVALID_HANDLE_VALUE = wait for running callbacks to finish + DeleteTimerQueueTimer(nullptr, m_flushTimerHandle, INVALID_HANDLE_VALUE); // INVALID_HANDLE_VALUE = wait for running callbacks to finish } fclose(m_pLogFile); m_pLogFile = nullptr; @@ -116,30 +116,29 @@ bool CScriptDebugging::SetLogfile(const char* szFilename, unsigned int uiLevel) return false; } - void CScriptDebugging::UpdateLogOutput() { SLogLine line; while (m_DuplicateLineFilter.PopOutputLine(line)) { - bool sufficientDebugLevel = CheckForSufficientDebugLevel(static_cast(m_uiLogFileLevel), - static_cast(line.uiMinimumDebugLevel)); + bool sufficientDebugLevel = + CheckForSufficientDebugLevel(static_cast(m_uiLogFileLevel), static_cast(line.uiMinimumDebugLevel)); if (sufficientDebugLevel) { PrintLog(line.strText); } - - #ifdef MTA_DEBUG + +#ifdef MTA_DEBUG if (!g_pCore->IsDebugVisible()) return; - #endif - +#endif + std::uint8_t clientDebugLevel = 0; - auto* localPlayer = g_pClientGame->GetPlayerManager()->GetLocalPlayer(); + auto* localPlayer = g_pClientGame->GetPlayerManager()->GetLocalPlayer(); if (localPlayer) clientDebugLevel = localPlayer->GetPlayerScriptDebugLevel(); - + bool shouldDisplayInConsole = CheckForSufficientDebugLevel(clientDebugLevel, static_cast(line.uiMinimumDebugLevel)); if (shouldDisplayInConsole) g_pCore->DebugEchoColor(line.strText, line.ucRed, line.ucGreen, line.ucBlue); diff --git a/Client/mods/deathmatch/logic/CScriptFile.h b/Client/mods/deathmatch/logic/CScriptFile.h index b3bea766985..b962816394e 100644 --- a/Client/mods/deathmatch/logic/CScriptFile.h +++ b/Client/mods/deathmatch/logic/CScriptFile.h @@ -32,11 +32,11 @@ class CScriptFile final : public CClientEntity // Functions required for linking void GetPosition(CVector& vecPosition) const {}; - void SetPosition(const CVector& vecPosition){}; + void SetPosition(const CVector& vecPosition) {}; // Functions required by CClientEntity eClientEntityType GetType() const { return SCRIPTFILE; }; - void Unlink(){}; + void Unlink() {}; // Load and unload routines bool Load(CResource* pResourceForFilePath, eMode Mode); @@ -53,7 +53,7 @@ class CScriptFile final : public CClientEntity /** * @brief Returns a pointer to CResourceFile if the script file points to one. * @return A pointer to CResourceFile on success, null otherwise - */ + */ CResourceFile* GetResourceFile() const; // Only call functions below this if you're sure that the file is loaded. @@ -79,8 +79,8 @@ class CScriptFile final : public CClientEntity void DoResourceFileCheck(); CBinaryFileInterface* m_pFile; - SString m_strFilename; // Resource relative - SString m_strAbsPath; // Absolute + SString m_strFilename; // Resource relative + SString m_strAbsPath; // Absolute unsigned long m_ulMaxSize; bool m_bDoneResourceFileCheck; unsigned int m_uiScriptId; diff --git a/Client/mods/deathmatch/logic/CServerIdManager.cpp b/Client/mods/deathmatch/logic/CServerIdManager.cpp index 983eaf8f151..49b6df0ddbf 100644 --- a/Client/mods/deathmatch/logic/CServerIdManager.cpp +++ b/Client/mods/deathmatch/logic/CServerIdManager.cpp @@ -13,20 +13,20 @@ #include "StdInc.h" #include "CServerIdManager.h" -#define MTA_SERVERID_LOOKUP_DIR "priv" -#define MTA_SERVERID_LOOKUP_XML "priv/server-ids.xml" +#define MTA_SERVERID_LOOKUP_DIR "priv" +#define MTA_SERVERID_LOOKUP_XML "priv/server-ids.xml" namespace { struct CServerIdKey { - SString strId; // Server id + SString strId; // Server id bool operator<(const CServerIdKey& other) const { return strId < other.strId; } }; struct CServerIdInfo { - SString strDir; // Server private directory + SString strDir; // Server private directory }; // Variables used for saving the file on a separate thread @@ -40,7 +40,7 @@ namespace strText.Split("_", &strMain, &strCount); return SString("%s_%d", *strMain, atoi(strCount) + 1); } -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -188,8 +188,7 @@ void CServerIdManagerImpl::SaveServerIdMap(bool bWait) ms_ServerIdMap = m_ServerIdMap; // Start save thread - HANDLE hThread = CreateThread(NULL, 0, reinterpret_cast(CServerIdManagerImpl::StaticThreadProc), - NULL, CREATE_SUSPENDED, NULL); + HANDLE hThread = CreateThread(NULL, 0, reinterpret_cast(CServerIdManagerImpl::StaticThreadProc), NULL, CREATE_SUSPENDED, NULL); if (!hThread) { g_pCore->GetConsole()->Printf("Could not create server-ids save thread."); diff --git a/Client/mods/deathmatch/logic/CServerInfo.h b/Client/mods/deathmatch/logic/CServerInfo.h index 80813d8bb18..81310fffba2 100644 --- a/Client/mods/deathmatch/logic/CServerInfo.h +++ b/Client/mods/deathmatch/logic/CServerInfo.h @@ -12,9 +12,9 @@ enum EServerInfoSyncFlag : uint8 { - SERVER_INFO_FLAG_ALL = 0xFF, // 0b11111111 - SERVER_INFO_FLAG_MAX_PLAYERS = 1, // 0b00000001 - SERVER_INFO_FLAG_RESERVED = 1 << 1 // 0b00000010 and so on + SERVER_INFO_FLAG_ALL = 0xFF, // 0b11111111 + SERVER_INFO_FLAG_MAX_PLAYERS = 1, // 0b00000001 + SERVER_INFO_FLAG_RESERVED = 1 << 1 // 0b00000010 and so on }; class CServerInfo diff --git a/Client/mods/deathmatch/logic/CSingularFileDownload.cpp b/Client/mods/deathmatch/logic/CSingularFileDownload.cpp index bb606d0be52..31c3f0fa12b 100644 --- a/Client/mods/deathmatch/logic/CSingularFileDownload.cpp +++ b/Client/mods/deathmatch/logic/CSingularFileDownload.cpp @@ -65,15 +65,15 @@ void CSingularFileDownload::CallFinished(bool bSuccess) { // Call the onClientbFileDownloadComplete event CLuaArguments Arguments; - Arguments.PushString(GetShortName()); // file name - Arguments.PushBoolean(bSuccess); // Completed successfully? + Arguments.PushString(GetShortName()); // file name + Arguments.PushBoolean(bSuccess); // Completed successfully? if (m_pRequestResource) { - Arguments.PushResource(m_pRequestResource); // Resource that called downloadFile + Arguments.PushResource(m_pRequestResource); // Resource that called downloadFile } else { - Arguments.PushBoolean(false); // or false + Arguments.PushBoolean(false); // or false } m_pResource->GetResourceEntity()->CallEvent("onClientFileDownloadComplete", Arguments, false); diff --git a/Client/mods/deathmatch/logic/CSingularFileDownload.h b/Client/mods/deathmatch/logic/CSingularFileDownload.h index b3686c14d85..1bfd4d5dd18 100644 --- a/Client/mods/deathmatch/logic/CSingularFileDownload.h +++ b/Client/mods/deathmatch/logic/CSingularFileDownload.h @@ -13,9 +13,9 @@ #ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms + #define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms -#include + #include #endif #include diff --git a/Client/mods/deathmatch/logic/CSingularFileDownloadManager.cpp b/Client/mods/deathmatch/logic/CSingularFileDownloadManager.cpp index 97be6ba0dd2..2f88040d36c 100644 --- a/Client/mods/deathmatch/logic/CSingularFileDownloadManager.cpp +++ b/Client/mods/deathmatch/logic/CSingularFileDownloadManager.cpp @@ -59,4 +59,4 @@ bool CSingularFileDownloadManager::AllComplete() return false; } return true; -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/CSingularFileDownloadManager.h b/Client/mods/deathmatch/logic/CSingularFileDownloadManager.h index 9b861b5dce8..a49ff55281c 100644 --- a/Client/mods/deathmatch/logic/CSingularFileDownloadManager.h +++ b/Client/mods/deathmatch/logic/CSingularFileDownloadManager.h @@ -13,9 +13,9 @@ #ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms + #define WIN32_LEAN_AND_MEAN // Exclude all uncommon functions from windows.h to reduce build time by 100ms -#include + #include #endif #include diff --git a/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp b/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp index d404c44c92b..7ac2e1785e1 100644 --- a/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp +++ b/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp @@ -274,10 +274,10 @@ bool CStaticFunctionDefinitions::OutputChatBox(const char* szText, unsigned char // Early null-safety checks to prevent crashes when called before initialization if (!m_pCore || !g_pClientGame || !szText || szText[0] == '\0') return false; - + // Calculate length without color codes when bColorCoded is true for accurate visible text length SString textToProcess = bColorCoded ? RemoveColorCodes(szText) : SStringX(szText); - + // Reject messages that exceed the maximum length if (textToProcess.length() > MAX_OUTPUTCHATBOX_LENGTH) return false; @@ -295,7 +295,7 @@ bool CStaticFunctionDefinitions::OutputChatBox(const char* szText, unsigned char m_pCore->ChatPrintfColor("%s", bColorCoded, ucRed, ucGreen, ucBlue, szText); return true; } - + return false; } @@ -576,7 +576,6 @@ bool CStaticFunctionDefinitions::GetElementBoundingBox(CClientEntity& Entity, CV pModelInfo = g_pGame->GetModelInfo(building.GetModel()); break; } - } if (pModelInfo) @@ -1284,7 +1283,7 @@ bool CStaticFunctionDefinitions::SetElementParent(CClientEntity& Entity, CClient const char* szTypeName = pTemp->GetTypeName(); if (szTypeName && strcmp(szTypeName, "map") == 0) { - bValidParent = true; // parents must be a map + bValidParent = true; // parents must be a map break; } @@ -1505,7 +1504,8 @@ bool CStaticFunctionDefinitions::SetElementHealth(CClientEntity& Entity, float f // If setting health to 0 for local player, clear stale damage data // and set proper scripted death parameters for DoWastedCheck - if (fHealth == 0.0f && Ped.IsLocalPlayer() && Ped.GetHealth() > 0.0f) { + if (fHealth == 0.0f && Ped.IsLocalPlayer() && Ped.GetHealth() > 0.0f) + { g_pClientGame->SetScriptedDeathData(); } @@ -1537,7 +1537,8 @@ bool CStaticFunctionDefinitions::SetElementModel(CClientEntity& Entity, unsigned { RUN_CHILDREN(SetElementModel(**iter, usModel)) - auto callOnChangeEvent = [](auto &element, uint16_t usCurrentModel, uint16_t usModel) { + auto callOnChangeEvent = [](auto& element, uint16_t usCurrentModel, uint16_t usModel) + { CLuaArguments Arguments; Arguments.PushNumber(usCurrentModel); Arguments.PushNumber(usModel); @@ -1803,7 +1804,7 @@ bool CStaticFunctionDefinitions::GetPedAnalogControlState(CClientPed& Ped, const unsigned int uiIndex; if (bRawInput) - cs = Ped.m_rawControllerState; // use the raw controller values without MTA glitch fixes modifying our raw inputs + cs = Ped.m_rawControllerState; // use the raw controller values without MTA glitch fixes modifying our raw inputs else Ped.GetControllerState(cs); @@ -2548,7 +2549,7 @@ bool CStaticFunctionDefinitions::SetPedAimTarget(CClientEntity& Entity, CVector& // Ped rotation CVector vecRot; Ped.GetRotationRadians(vecRot); - float fRotZ = -vecRot.fZ; // Counter-clockwise + float fRotZ = -vecRot.fZ; // Counter-clockwise fRotZ = (fRotZ > PI) ? fRotZ - PI * 2 : fRotZ; // Rotation difference @@ -2689,7 +2690,8 @@ bool CStaticFunctionDefinitions::GetTypeIndexFromClothes(const char* szTexture, { std::vector pPlayerClothing = CClientPlayerClothes::GetClothingGroup(ucType); - if (!pPlayerClothing.empty()) { + if (!pPlayerClothing.empty()) + { for (unsigned char ucIter = 0; ucIter < pPlayerClothing.size(); ucIter++) { if ((szTexture == NULL || strcmp(szTexture, pPlayerClothing[ucIter]->texture.c_str()) == 0) && @@ -2915,7 +2917,7 @@ bool CStaticFunctionDefinitions::BlowVehicle(CClientEntity& Entity, std::optiona if (!IS_VEHICLE(&Entity)) return false; - CClientVehicle& vehicle = static_cast(Entity); + CClientVehicle& vehicle = static_cast(Entity); VehicleBlowFlags blow; blow.withExplosion = withExplosion.value_or(true); @@ -2929,8 +2931,8 @@ bool CStaticFunctionDefinitions::BlowVehicle(CClientEntity& Entity, std::optiona CVector position; vehicle.GetPosition(position); - const auto type = vehicle.GetType(); - const auto state = (blow.withExplosion ? VehicleBlowState::AWAITING_EXPLOSION_SYNC : VehicleBlowState::BLOWN); + const auto type = vehicle.GetType(); + const auto state = (blow.withExplosion ? VehicleBlowState::AWAITING_EXPLOSION_SYNC : VehicleBlowState::BLOWN); eExplosionType explosion; switch (type) @@ -3265,7 +3267,8 @@ bool CStaticFunctionDefinitions::SetVehicleLightState(CClientEntity& Entity, uns return false; } -bool CStaticFunctionDefinitions::SetVehiclePanelState(CClientEntity& Entity, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent, bool breakGlass) +bool CStaticFunctionDefinitions::SetVehiclePanelState(CClientEntity& Entity, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent, + bool breakGlass) { RUN_CHILDREN(SetVehiclePanelState(**iter, ucPanel, ucState, spawnFlyingComponent, breakGlass)) @@ -4837,7 +4840,8 @@ bool CStaticFunctionDefinitions::SetBlipVisibleDistance(CClientEntity& Entity, u return false; } -CClientMarker* CStaticFunctionDefinitions::CreateMarker(CResource& Resource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, bool ignoreAlphaLimits) +CClientMarker* CStaticFunctionDefinitions::CreateMarker(CResource& Resource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, + bool ignoreAlphaLimits) { assert(szType); @@ -5001,7 +5005,7 @@ bool CStaticFunctionDefinitions::SetMarkerTargetArrowProperties(CClientEntity& E if (!IS_MARKER(&Entity)) return false; - CClientMarker& marker = static_cast(Entity); + CClientMarker& marker = static_cast(Entity); CClientCheckpoint* checkpoint = marker.GetCheckpoint(); if (!checkpoint) return false; @@ -5020,32 +5024,32 @@ bool CStaticFunctionDefinitions::GetCameraMatrix(CVector& vecPosition, CVector& m_pCamera->GetPosition(vecPosition); m_pCamera->GetFixedTarget(vecLookAt, &fRoll); - + fFOV = m_pCamera->GetAccurateFOV(); - + if (fRoll == 0.0f) { // Calculate roll from camera matrix when not directly available CMatrix matrix; m_pCamera->GetMatrix(matrix); - + CVector worldUp(0.0f, 0.0f, 1.0f); CVector cameraUp = matrix.vUp; CVector cameraRight = matrix.vRight; - + // Project camera up vector onto plane perpendicular to camera front CVector projectedUp = cameraUp - matrix.vFront * cameraUp.DotProduct(&matrix.vFront); if (projectedUp.Length() <= FLOAT_EPSILON) return true; projectedUp.Normalize(); - + float cosRoll = worldUp.DotProduct(&projectedUp); float sinRoll = cameraRight.DotProduct(&worldUp); - + fRoll = std::atan2(sinRoll, cosRoll) * (180.0f / std::numbers::pi_v); } - + return true; } @@ -5261,7 +5265,7 @@ bool CStaticFunctionDefinitions::SetCursorAlpha(float fAlpha) } bool CStaticFunctionDefinitions::GUIGetInputEnabled() -{ // can't inline because statics are defined in .cpp not .h +{ // can't inline because statics are defined in .cpp not .h return m_pGUI->GetGUIInputEnabled(); } @@ -6479,8 +6483,8 @@ void CStaticFunctionDefinitions::GUILabelSetColor(CClientEntity& Entity, int iR, if (IS_CGUIELEMENT_LABEL(&GUIElement)) { // Set the label color - static_cast(GUIElement.GetCGUIElement())->SetTextColor(static_cast(iR), static_cast(iG), - static_cast(iB)); + static_cast(GUIElement.GetCGUIElement()) + ->SetTextColor(static_cast(iR), static_cast(iG), static_cast(iB)); } } } @@ -6759,11 +6763,11 @@ bool CStaticFunctionDefinitions::GetGarageSize(unsigned char ucGarageID, float& if (pGarage) { pGarage->GetSize(fHeight, fWidth, fDepth); - + CVector vecPosition; pGarage->GetPosition(vecPosition); fHeight -= vecPosition.fZ; - + return true; } @@ -7321,7 +7325,7 @@ bool CStaticFunctionDefinitions::GetAnalogControlState(const char* szControl, fl bool bOnFoot = (!pLocalPlayer->GetRealOccupiedVehicle()); if (bRawInput) - cs = pLocalPlayer->m_rawControllerState; // use the raw controller values without MTA glitch fixes modifying our raw inputs + cs = pLocalPlayer->m_rawControllerState; // use the raw controller values without MTA glitch fixes modifying our raw inputs else pLocalPlayer->GetControllerState(cs); @@ -8082,7 +8086,9 @@ bool CStaticFunctionDefinitions::FxAddFootSplash(CVector& vecPosition) return true; } -bool CStaticFunctionDefinitions::FxCreateParticle(FxParticleSystems eFxParticle, CVector& vecPosition, CVector& vecDirection, float fR, float fG, float fB, float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife) +bool CStaticFunctionDefinitions::FxCreateParticle(FxParticleSystems eFxParticle, CVector& vecPosition, CVector& vecDirection, float fR, float fG, float fB, + float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, + float fLife) { g_pGame->GetFx()->AddParticle(eFxParticle, vecPosition, vecDirection, fR, fG, fB, fA, bRandomizeColors, iCount, fBrightness, fSize, bRandomizeSizes, fLife); return true; @@ -8117,7 +8123,7 @@ bool CStaticFunctionDefinitions::StopSound(CClientSound& Sound) { // call onClientSoundStopped CLuaArguments Arguments; - Arguments.PushString("destroyed"); // Reason + Arguments.PushString("destroyed"); // Reason Sound.CallEvent("onClientSoundStopped", Arguments, false); g_pClientGame->GetElementDeleter()->Delete(&Sound); return true; @@ -8653,7 +8659,7 @@ bool CStaticFunctionDefinitions::SetEntryHandling(CHandlingEntry* pEntry, Handli if (ucValue >= 0 && ucValue <= 29) { if (ucValue != 3 && ucValue != 8 && ucValue != 17 && ucValue != 23) - return true; // Pretend it worked to avoid script warnings + return true; // Pretend it worked to avoid script warnings pEntry->SetAnimGroup(ucValue); return true; @@ -9352,7 +9358,7 @@ bool CStaticFunctionDefinitions::GetEntryHandling(CHandlingEntry* pEntry, Handli case HandlingProperty::HANDLING_SEATOFFSETDISTANCE: fValue = pEntry->GetSeatOffsetDistance(); break; - case HandlingProperty::HANDLING_ABS: // bool + case HandlingProperty::HANDLING_ABS: // bool fValue = (float)(pEntry->GetABS() ? 1 : 0); break; default: @@ -9368,7 +9374,7 @@ bool CStaticFunctionDefinitions::GetEntryHandling(CHandlingEntry* pEntry, Handli { switch (eProperty) { - case HandlingProperty::HANDLING_PERCENTSUBMERGED: // unsigned int + case HandlingProperty::HANDLING_PERCENTSUBMERGED: // unsigned int uiValue = pEntry->GetPercentSubmerged(); break; case HandlingProperty::HANDLING_MONETARY: @@ -10009,8 +10015,8 @@ bool CStaticFunctionDefinitions::WarpPedIntoVehicle(CClientPed* pPed, CClientVeh // Call the onClientPlayerEnterVehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(uiSeat); // seat + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(uiSeat); // seat if (IS_PLAYER(pPed)) pPed->CallEvent("onClientPlayerVehicleEnter", Arguments, true); else @@ -10018,8 +10024,8 @@ bool CStaticFunctionDefinitions::WarpPedIntoVehicle(CClientPed* pPed, CClientVeh // Call the onClientVehicleEnter event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(uiSeat); // seat + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(uiSeat); // seat pVehicle->CallEvent("onClientVehicleEnter", Arguments2, true); return true; @@ -10030,7 +10036,7 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CClientPed* pPed) // Get the ped / player's occupied vehicle data before pulling it out CClientVehicle* pVehicle = pPed->GetOccupiedVehicle(); unsigned int uiSeat = pPed->GetOccupiedVehicleSeat(); - bool bCancellingWhileEntering = pPed->IsEnteringVehicle(); // Special case here that could cause network trouble. + bool bCancellingWhileEntering = pPed->IsEnteringVehicle(); // Special case here that could cause network trouble. // Occupied vehicle can be NULL here while entering (Walking up to a vehicle in preparation to getting in/opening the doors) if (pVehicle || bCancellingWhileEntering) @@ -10043,8 +10049,8 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CClientPed* pPed) if (pVehicle == NULL) pVehicle = pPed->GetOccupyingVehicle(); - if (pVehicle == NULL) // Every time I've tested this the occupying Vehicle has been correct, but if it doesn't exist let's not try and - // call an event on it! + if (pVehicle == NULL) // Every time I've tested this the occupying Vehicle has been correct, but if it doesn't exist let's not try and + // call an event on it! return false; } @@ -10062,9 +10068,9 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CClientPed* pPed) // Call onClientPlayerVehicleExit CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(uiSeat); // seat - Arguments.PushBoolean(false); // jacker + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(uiSeat); // seat + Arguments.PushBoolean(false); // jacker if (IS_PLAYER(pPed)) pPed->CallEvent("onClientPlayerVehicleExit", Arguments, true); else @@ -10072,8 +10078,8 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CClientPed* pPed) // Call onClientVehicleExit CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(uiSeat); // seat + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(uiSeat); // seat pVehicle->CallEvent("onClientVehicleExit", Arguments2, true); return true; } diff --git a/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.h b/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.h index 766a09a9ffc..3c98e5eee18 100644 --- a/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.h +++ b/Client/mods/deathmatch/logic/CStaticFunctionDefinitions.h @@ -174,8 +174,8 @@ class CStaticFunctionDefinitions static bool SetPedAnimation(CClientEntity& Entity, const SString& strBlockName, const char* szAnimName, int iTime, int iBlend, bool bLoop, bool bUpdatePosition, bool bInterruptable, bool bFreezeLastFrame); - static bool SetPedAnimationProgress(CClientEntity& Entity, const SString& strAnimName, float fProgress); - static bool SetPedAnimationSpeed(CClientEntity& Entity, const SString& strAnimName, float fSpeed); + static bool SetPedAnimationProgress(CClientEntity& Entity, const SString& strAnimName, float fProgress); + static bool SetPedAnimationSpeed(CClientEntity& Entity, const SString& strAnimName, float fSpeed); static bool SetPedMoveAnim(CClientEntity& Entity, unsigned int iMoveAnim); static bool AddPedClothes(CClientEntity& Entity, const char* szTexture, const char* szModel, unsigned char ucType); @@ -249,7 +249,8 @@ class CStaticFunctionDefinitions static bool SetVehicleDoorState(CClientEntity& Entity, unsigned char ucDoor, unsigned char ucState, bool spawnFlyingComponent); static bool SetVehicleWheelStates(CClientEntity& Entity, int iFrontLeft, int iRearLeft = -1, int iFrontRight = -1, int iRearRight = -1); static bool SetVehicleLightState(CClientEntity& Entity, unsigned char ucLight, unsigned char ucState); - static bool SetVehiclePanelState(CClientEntity& Entity, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent = true, bool breakGlass = false); + static bool SetVehiclePanelState(CClientEntity& Entity, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent = true, + bool breakGlass = false); static bool SetVehicleOverrideLights(CClientEntity& Entity, unsigned char ucLights); static bool AttachTrailerToVehicle(CClientVehicle& Vehicle, CClientVehicle& Trailer, const CVector& vecRotationOffsetDegrees); static bool DetachTrailerFromVehicle(CClientVehicle& Vehicle, CClientVehicle* pTrailer = NULL); @@ -374,7 +375,8 @@ class CStaticFunctionDefinitions static bool SetBlipVisibleDistance(CClientEntity& Entity, unsigned short usVisibleDistance); // Marker create/destroy funcs - static CClientMarker* CreateMarker(CResource& Resource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, bool ignoreAlphaLimits); + static CClientMarker* CreateMarker(CResource& Resource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, + bool ignoreAlphaLimits); // Marker get funcs static bool GetMarkerTarget(CClientMarker& Marker, CVector& vecTarget); @@ -542,7 +544,9 @@ class CStaticFunctionDefinitions }; static inline void GUIGridListSetItemColor(CClientGUIElement& GUIElement, int iRow, int iColumn, int iRed, int iGreen, int iBlue, int iAlpha) { - static_cast(GUIElement.GetCGUIElement())->SetItemColor(iRow, iColumn, static_cast(iRed), static_cast(iGreen), static_cast(iBlue), static_cast(iAlpha)); + static_cast(GUIElement.GetCGUIElement()) + ->SetItemColor(iRow, iColumn, static_cast(iRed), static_cast(iGreen), static_cast(iBlue), + static_cast(iAlpha)); } static void GUIGridListSetHorizontalScrollPosition(CClientEntity& Element, float fPosition); static void GUIGridListSetVerticalScrollPosition(CClientEntity& Element, float fPosition); @@ -741,7 +745,8 @@ class CStaticFunctionDefinitions static bool FxAddWaterSplash(CVector& vecPosition); static bool FxAddBulletSplash(CVector& vecPosition); static bool FxAddFootSplash(CVector& vecPosition); - static bool FxCreateParticle(FxParticleSystems eFxParticle, CVector& vecPosition, CVector& vecDirection, float fR, float fG, float fB, float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife); + static bool FxCreateParticle(FxParticleSystems eFxParticle, CVector& vecPosition, CVector& vecDirection, float fR, float fG, float fB, float fA, + bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife); static CClientEffect* CreateEffect(CResource& Resource, const SString& strFxName, const CVector& vecPosition, bool bSoundEnable); // Sound funcs @@ -796,28 +801,28 @@ class CStaticFunctionDefinitions // Handling funcs static HandlingProperty GetVehicleHandlingEnum(std::string strProperty); - static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, float& fValue); - static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, CVector& vecValue); - static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, std::string& strValue); - static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned int& uiValue); - static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned char& ucValue); - static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, float& fValue); - static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, CVector& vecValue); - static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, std::string& strValue); - static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned int& uiValue); - static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned char& ucValue); - static bool ResetVehicleHandling(CClientVehicle* pVehicle); - static bool ResetVehicleHandlingProperty(CClientVehicle* pVehicle, HandlingProperty eProperty); - static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, float fValue); - static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, CVector vecValue); - static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, std::string strValue); - static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned int uiValue); - static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned char ucValue); - static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, float fValue); - static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, CVector vecValue); - static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, std::string strValue); - static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned int uiValue); - static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned char ucValue); + static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, float& fValue); + static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, CVector& vecValue); + static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, std::string& strValue); + static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned int& uiValue); + static bool GetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned char& ucValue); + static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, float& fValue); + static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, CVector& vecValue); + static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, std::string& strValue); + static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned int& uiValue); + static bool GetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned char& ucValue); + static bool ResetVehicleHandling(CClientVehicle* pVehicle); + static bool ResetVehicleHandlingProperty(CClientVehicle* pVehicle, HandlingProperty eProperty); + static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, float fValue); + static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, CVector vecValue); + static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, std::string strValue); + static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned int uiValue); + static bool SetVehicleHandling(CClientVehicle* pVehicle, HandlingProperty eProperty, unsigned char ucValue); + static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, float fValue); + static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, CVector vecValue); + static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, std::string strValue); + static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned int uiValue); + static bool SetEntryHandling(CHandlingEntry* pEntry, HandlingProperty eProperty, unsigned char ucValue); // Version funcs static unsigned long GetVersion(); diff --git a/Client/mods/deathmatch/logic/CSyncDebug.cpp b/Client/mods/deathmatch/logic/CSyncDebug.cpp index f3d63fb2091..c4ff77a0280 100644 --- a/Client/mods/deathmatch/logic/CSyncDebug.cpp +++ b/Client/mods/deathmatch/logic/CSyncDebug.cpp @@ -27,8 +27,8 @@ CSyncDebug::CSyncDebug(CClientManager* pManager) m_ulLastUpdateTime = CClientTime::GetTime(); m_uiLastPacketsSent = m_uiPacketsSent = stats.packetsSent; m_uiLastPacketsReceived = m_uiPacketsReceived = stats.packetsReceived; - m_uiLastBitsReceived = m_uiBitsReceived = (uint)stats.bytesReceived * 8; // stats.runningTotal [ NS_ACTUAL_BYTES_RECEIVED ] * 8; - m_uiLastBitsSent = m_uiBitsSent = (uint)stats.bytesSent * 8; // stats.runningTotal [ NS_ACTUAL_BYTES_SENT ] * 8; + m_uiLastBitsReceived = m_uiBitsReceived = (uint)stats.bytesReceived * 8; // stats.runningTotal [ NS_ACTUAL_BYTES_RECEIVED ] * 8; + m_uiLastBitsSent = m_uiBitsSent = (uint)stats.bytesSent * 8; // stats.runningTotal [ NS_ACTUAL_BYTES_SENT ] * 8; m_usFakeLagVariance = 0; m_usFakeLagPing = 0; diff --git a/Client/mods/deathmatch/logic/CSyncDebug.h b/Client/mods/deathmatch/logic/CSyncDebug.h index 5d7a6921e40..41a823ccf22 100644 --- a/Client/mods/deathmatch/logic/CSyncDebug.h +++ b/Client/mods/deathmatch/logic/CSyncDebug.h @@ -30,14 +30,14 @@ class CSyncDebug void OnPulse(); #else - CSyncDebug(CClientManager* pManager){}; + CSyncDebug(CClientManager* pManager) {}; - void Unreference(CClientPlayer& Player){}; + void Unreference(CClientPlayer& Player) {}; - void Attach(CClientPlayer& Player){}; - void Detach(){}; + void Attach(CClientPlayer& Player) {}; + void Detach() {}; - void OnPulse(){}; + void OnPulse() {}; #endif diff --git a/Client/mods/deathmatch/logic/CTransferBox.cpp b/Client/mods/deathmatch/logic/CTransferBox.cpp index 340832bdeee..546fbbcb3bf 100644 --- a/Client/mods/deathmatch/logic/CTransferBox.cpp +++ b/Client/mods/deathmatch/logic/CTransferBox.cpp @@ -56,7 +56,7 @@ void CTransferBox::CreateTransferWindow() m_window->SetCloseButtonEnabled(false); m_window->SetSizingEnabled(false); m_window->SetPosition(CVector2D(screenSize.fX * 0.5f - fTransferBoxWidth * 0.5f, screenSize.fY * 0.85f - TRANSFERBOX_HEIGHT * 0.5f)); - m_window->SetSize(CVector2D(fTransferBoxWidth, TRANSFERBOX_HEIGHT)); // relative 0.35, 0.225 + m_window->SetSize(CVector2D(fTransferBoxWidth, TRANSFERBOX_HEIGHT)); // relative 0.35, 0.225 m_progressBar.reset(m_GUI->CreateProgressBar(m_window.get())); m_progressBar->SetPosition(CVector2D(0, TRANSFERBOX_YSTART)); diff --git a/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp b/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp index 7e4d647c7f7..b4dbe67ea88 100644 --- a/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp +++ b/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp @@ -16,7 +16,7 @@ using std::list; extern CClientGame* g_pClientGame; -#define UNOCCUPIED_VEHICLE_SYNC_RATE ( g_TickRateSettings.iUnoccupiedVehicle ) +#define UNOCCUPIED_VEHICLE_SYNC_RATE (g_TickRateSettings.iUnoccupiedVehicle) CUnoccupiedVehicleSync::CUnoccupiedVehicleSync(CClientVehicleManager* pVehicleManager) { diff --git a/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.h b/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.h index 749ff5c9ea4..cf4d338bf3d 100644 --- a/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.h +++ b/Client/mods/deathmatch/logic/CUnoccupiedVehicleSync.h @@ -13,7 +13,7 @@ #include #include "CDeathmatchVehicle.h" -#define MIN_ROTATION_DIFF 0.1 +#define MIN_ROTATION_DIFF 0.1 class CUnoccupiedVehicleSync { public: diff --git a/Client/mods/deathmatch/logic/CVehicleNames.cpp b/Client/mods/deathmatch/logic/CVehicleNames.cpp index 9d9e6b584f7..5de6553d859 100644 --- a/Client/mods/deathmatch/logic/CVehicleNames.cpp +++ b/Client/mods/deathmatch/logic/CVehicleNames.cpp @@ -17,7 +17,7 @@ const char* const szVehicleNameEmpty = ""; struct SVehicleName { const char* szName; - const char* szName_replaced; // Compatability + const char* szName_replaced; // Compatability }; static const SFixedArray VehicleNames = {{{"Landstalker"}, diff --git a/Client/mods/deathmatch/logic/CVehicleUpgrades.cpp b/Client/mods/deathmatch/logic/CVehicleUpgrades.cpp index 72872162f48..441347611b4 100644 --- a/Client/mods/deathmatch/logic/CVehicleUpgrades.cpp +++ b/Client/mods/deathmatch/logic/CVehicleUpgrades.cpp @@ -373,7 +373,6 @@ bool CVehicleUpgrades::IsUpgradeCompatible(unsigned short usUpgrade) // Allow slot 2 to be upgraded regardless of ID and then check it has the required part if (GetSlotFromUpgrade(us, ucSlot) && (bReturn || ucSlot == 2)) { - // Get our model supported upgrades auto* info = g_pGame->GetModelInfo(usModel); modelInfo = info ? info : m_pVehicle->GetModelInfo(); @@ -479,17 +478,17 @@ bool CVehicleUpgrades::GetSlotFromUpgrade(unsigned short us, unsigned char& ucSl ucSlot = 3; return true; } - if (us == 1115 || us == 1116) // front bullbars + if (us == 1115 || us == 1116) // front bullbars { ucSlot = 4; return true; } - if (us == 1109 || us == 1110) // rear bullbars + if (us == 1109 || us == 1110) // rear bullbars { ucSlot = 5; return true; } - if (us == 1013 || us == 1024) // lamps + if (us == 1013 || us == 1024) // lamps { ucSlot = 6; return true; @@ -501,17 +500,17 @@ bool CVehicleUpgrades::GetSlotFromUpgrade(unsigned short us, unsigned char& ucSl ucSlot = 7; return true; } - if (us == 1008 || us == 1009 || us == 1010) // nitro + if (us == 1008 || us == 1009 || us == 1010) // nitro { ucSlot = 8; return true; } - if (us == 1087) // hydraulics + if (us == 1087) // hydraulics { ucSlot = 9; return true; } - if (us == 1086) // stereo + if (us == 1086) // stereo { ucSlot = 10; return true; diff --git a/Client/mods/deathmatch/logic/Config.h b/Client/mods/deathmatch/logic/Config.h index a5348e0c40b..83cdb7c77df 100644 --- a/Client/mods/deathmatch/logic/Config.h +++ b/Client/mods/deathmatch/logic/Config.h @@ -41,7 +41,7 @@ class CVaPassNext CVaPassNext(va_list& args) { try - { // to avoid access violation + { // to avoid access violation memcpy(&svapassnext, args, sizeof(svapassnext)); } catch (...) @@ -62,7 +62,7 @@ class CVaPassNext // Min and max number of characters in chat echos #define MIN_CHATECHO_LENGTH 1 -#define MAX_CHATECHO_LENGTH (MAX_CHAT_LENGTH + MAX_PLAYER_NICK_LENGTH + 2) // +2 is for ": " between player nick and the message +#define MAX_CHATECHO_LENGTH (MAX_CHAT_LENGTH + MAX_PLAYER_NICK_LENGTH + 2) // +2 is for ": " between player nick and the message // Min and max number of characters in outputChatBox from the server #define MIN_OUTPUTCHATBOX_LENGTH 1 @@ -102,7 +102,7 @@ class CVaPassNext #define MAX_MAPNAME_LENGTH 255 // Timeouts -#define NET_CONNECT_TIMEOUT 30000 +#define NET_CONNECT_TIMEOUT 30000 #define CLIENT_VERIFICATION_TIMEOUT 10000 // Vehicle in-out delay (to prevent messed up like 1765/1956/1880 diff --git a/Client/mods/deathmatch/logic/lua/CLuaArgument.cpp b/Client/mods/deathmatch/logic/lua/CLuaArgument.cpp index e4a577bcea1..97c61cd60d4 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaArgument.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaArgument.cpp @@ -11,15 +11,15 @@ #include "StdInc.h" #include "net/SyncStructures.h" -#define ARGUMENT_TYPE_INT 9 -#define ARGUMENT_TYPE_FLOAT 10 +#define ARGUMENT_TYPE_INT 9 +#define ARGUMENT_TYPE_FLOAT 10 #ifndef VERIFY_ENTITY -#define VERIFY_ENTITY(entity) (CStaticFunctionDefinitions::GetRootElement()->IsMyChild(entity,true)&&!entity->IsBeingDeleted()) + #define VERIFY_ENTITY(entity) (CStaticFunctionDefinitions::GetRootElement()->IsMyChild(entity, true) && !entity->IsBeingDeleted()) #endif #ifndef VERIFY_RESOURCE -#define VERIFY_RESOURCE(resource) (g_pClientGame->GetResourceManager()->Exists(resource)) + #define VERIFY_RESOURCE(resource) (g_pClientGame->GetResourceManager()->Exists(resource)) #endif extern CClientGame* g_pClientGame; @@ -27,7 +27,7 @@ extern CClientGame* g_pClientGame; using namespace std; // Prevent the warning issued when doing unsigned short -> void* -#pragma warning(disable:4312) +#pragma warning(disable : 4312) CLuaArgument::CLuaArgument() { @@ -887,9 +887,9 @@ json_object* CLuaArgument::WriteToJSONObject(bool bSerialize, CFastHashMapGetScriptDebugging()->LogError(NULL, "Couldn't convert userdata argument to JSON, elements not allowed for this function."); - else if (!bSerialize) // eg toJSON() with invalid element + else if (!bSerialize) // eg toJSON() with invalid element g_pClientGame->GetScriptDebugging()->LogError( NULL, "Couldn't convert userdata argument to JSON, only valid resources can be included for this function."); else @@ -1038,7 +1038,7 @@ bool CLuaArgument::ReadFromJSONObject(json_object* object, std::vectorGetResourceManager()->GetResource(strString.c_str() + 3); if (resource) @@ -1070,7 +1070,7 @@ bool CLuaArgument::ReadFromJSONObject(json_object* object, std::vector(atol(strString.c_str() + 3)); if (pKnownTables && ulTableID < pKnownTables->size()) diff --git a/Client/mods/deathmatch/logic/lua/CLuaArgument.h b/Client/mods/deathmatch/logic/lua/CLuaArgument.h index b47aba8bde0..c861cb57a80 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaArgument.h +++ b/Client/mods/deathmatch/logic/lua/CLuaArgument.h @@ -12,7 +12,7 @@ extern "C" { - #include "lua.h" +#include "lua.h" } #include #include @@ -22,7 +22,7 @@ extern "C" class CClientEntity; class CLuaArguments; -#define LUA_TTABLEREF 9 +#define LUA_TTABLEREF 9 #define LUA_TSTRING_LONG 10 class CLuaArgument diff --git a/Client/mods/deathmatch/logic/lua/CLuaArguments.cpp b/Client/mods/deathmatch/logic/lua/CLuaArguments.cpp index 740e9f5f707..a639622e1a5 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaArguments.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaArguments.cpp @@ -15,7 +15,7 @@ using namespace std; #ifndef VERIFY_ENTITY -#define VERIFY_ENTITY(entity) (CStaticFunctionDefinitions::GetRootElement()->IsMyChild(entity,true)&&!entity->IsBeingDeleted()) + #define VERIFY_ENTITY(entity) (CStaticFunctionDefinitions::GetRootElement()->IsMyChild(entity, true) && !entity->IsBeingDeleted()) #endif extern CClientGame* g_pClientGame; @@ -114,10 +114,10 @@ void CLuaArguments::ReadTable(lua_State* luaVM, int iIndexBegin, CFastHashMap::const_iterator iter = m_Arguments.begin(); for (; iter != m_Arguments.end() && (iter + 1) != m_Arguments.end(); iter++) { - (*iter)->Push(luaVM, pKnownTables); // index + (*iter)->Push(luaVM, pKnownTables); // index iter++; - (*iter)->Push(luaVM, pKnownTables); // value + (*iter)->Push(luaVM, pKnownTables); // value lua_settable(luaVM, -3); } @@ -225,7 +225,7 @@ bool CLuaArguments::Call(CLuaMain* pLuaMain, const CLuaFunctionRef& iLuaFunction while (lua_gettop(luaVM) - luaStackPointer > 0) lua_pop(luaVM, 1); - return false; // the function call failed + return false; // the function call failed } else { @@ -289,7 +289,7 @@ bool CLuaArguments::CallGlobal(CLuaMain* pLuaMain, const char* szFunction, CLuaA while (lua_gettop(luaVM) - luaStackPointer > 0) lua_pop(luaVM, 1); - return false; // the function call failed + return false; // the function call failed } else { @@ -520,7 +520,7 @@ bool CLuaArguments::WriteToJSONString(std::string& strJSON, bool bSerialize, int if (my_array) { strJSON = json_object_to_json_string_ext(my_array, flags); - json_object_put(my_array); // dereference - causes a crash, is actually commented out in the example too + json_object_put(my_array); // dereference - causes a crash, is actually commented out in the example too return true; } return false; @@ -558,7 +558,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap pKnownTables->insert({this, pKnownTables->size()}); bool bIsArray = true; - std::vector> vecSortedArguments; // lua arrays are not necessarily sorted + std::vector> vecSortedArguments; // lua arrays are not necessarily sorted std::vector::const_iterator iter = m_Arguments.begin(); for (; iter != m_Arguments.end(); iter += 2) { @@ -577,7 +577,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap } } - if (bIsArray && !vecSortedArguments.empty()) // the table could possibly be an array + if (bIsArray && !vecSortedArguments.empty()) // the table could possibly be an array { // sort the table based on the keys (already handled correctly by std::pair) std::sort(vecSortedArguments.begin(), vecSortedArguments.end()); @@ -587,7 +587,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap auto const iFirstKey = vecSortedArguments.front().first; auto const iLastKey = vecSortedArguments.back().first; - auto const iFirstArrayPos = 1U; // lua arrays are 1 based + auto const iFirstArrayPos = 1U; // lua arrays are 1 based auto const iLastArrayPos = static_cast(vecSortedArguments.size()); if (iFirstKey != iFirstArrayPos || iLastKey != iLastArrayPos) @@ -596,7 +596,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap } } - if (bIsArray) // the table is definitely an array + if (bIsArray) // the table is definitely an array { json_object* my_array = json_object_new_array(); for (auto const& [iKey, pArgument] : vecSortedArguments) @@ -624,11 +624,11 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap char szKey[255]; szKey[0] = '\0'; CLuaArgument* pArgument = *iter; - if (!pArgument->WriteToString(szKey, 255)) // index + if (!pArgument->WriteToString(szKey, 255)) // index break; iter++; pArgument = *iter; - json_object* object = pArgument->WriteToJSONObject(bSerialize, pKnownTables); // value + json_object* object = pArgument->WriteToJSONObject(bSerialize, pKnownTables); // value if (object) { @@ -672,11 +672,11 @@ bool CLuaArguments::ReadFromJSONString(const char* szJSON) json_object* arrayObject = json_object_array_get_idx(object, i); CLuaArgument* pArgument = new CLuaArgument(); bSuccess = pArgument->ReadFromJSONObject(arrayObject, &knownTables); - m_Arguments.push_back(pArgument); // then the value + m_Arguments.push_back(pArgument); // then the value if (!bSuccess) break; } - json_object_put(object); // dereference + json_object_put(object); // dereference return bSuccess; } else if (json_object_get_type(object) == json_type_object) @@ -684,12 +684,12 @@ bool CLuaArguments::ReadFromJSONString(const char* szJSON) std::vector knownTables; CLuaArgument* pArgument = new CLuaArgument(); bool bSuccess = pArgument->ReadFromJSONObject(object, &knownTables); - m_Arguments.push_back(pArgument); // value + m_Arguments.push_back(pArgument); // value json_object_put(object); return bSuccess; } - json_object_put(object); // dereference + json_object_put(object); // dereference } // else // g_pClientGame->GetScriptDebugging()->LogError ( "Could not parse invalid JSON object."); @@ -718,9 +718,9 @@ bool CLuaArguments::ReadFromJSONObject(json_object* object, std::vectorReadString(key); - m_Arguments.push_back(pArgument); // push the key first + m_Arguments.push_back(pArgument); // push the key first pArgument = new CLuaArgument(); - bSuccess = pArgument->ReadFromJSONObject(val, pKnownTables); // then the value + bSuccess = pArgument->ReadFromJSONObject(val, pKnownTables); // then the value m_Arguments.push_back(pArgument); if (!bSuccess) break; @@ -756,12 +756,12 @@ bool CLuaArguments::ReadFromJSONArray(json_object* object, std::vectorReadNumber(i + 1); // push the key + pArgument->ReadNumber(i + 1); // push the key m_Arguments.push_back(pArgument); pArgument = new CLuaArgument(); bSuccess = pArgument->ReadFromJSONObject(arrayObject, pKnownTables); - m_Arguments.push_back(pArgument); // then the valoue + m_Arguments.push_back(pArgument); // then the valoue if (!bSuccess) break; } diff --git a/Client/mods/deathmatch/logic/lua/CLuaArguments.h b/Client/mods/deathmatch/logic/lua/CLuaArguments.h index 508fc426564..c6a7df10b9f 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaArguments.h +++ b/Client/mods/deathmatch/logic/lua/CLuaArguments.h @@ -12,7 +12,7 @@ extern "C" { - #include "lua.h" +#include "lua.h" } #include diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Event.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Event.cpp index 183abe241d2..7bdbc0e2aad 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Event.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Event.cpp @@ -71,7 +71,7 @@ int CLuaFunctionDefs::AddEventHandler(lua_State* luaVM) } if (!StringToEnum(strPriority, eventPriority)) - argStream.SetTypeError(GetEnumTypeName(eventPriority), 5); // priority is argument #5 + argStream.SetTypeError(GetEnumTypeName(eventPriority), 5); // priority is argument #5 } if (!argStream.HasErrors()) diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Input.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Input.cpp index 00256a1f72a..2dc8e42bcb7 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Input.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Input.cpp @@ -210,7 +210,7 @@ int CLuaFunctionDefs::UnbindKey(lua_State* luaVM) CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); if (pLuaMain) { - if (argStream.NextIsString(1)) // Check if has command + if (argStream.NextIsString(1)) // Check if has command { // bool unbindKey ( string key, string keyState, string command ) SString strResource = pLuaMain->GetResource()->GetName(); @@ -304,7 +304,7 @@ int CLuaFunctionDefs::SetAnalogControlState(lua_State* luaVM) // bool setAnalogControlState ( string controlName [, float state][, bFrameForced] ) SString strControlState = ""; float fState = 0.0f; - bool bForceOverrideNextFrame = false; // if user input effect should be forcefully overriden for the next frame + bool bForceOverrideNextFrame = false; // if user input effect should be forcefully overriden for the next frame CScriptArgReader argStream(luaVM); argStream.ReadString(strControlState); diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Util.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Util.cpp index 2df7db7cea2..1bdcfeb7c40 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Util.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Util.cpp @@ -12,7 +12,7 @@ int CLuaFunctionDefs::GetValidPedModels(lua_State* luaVM) { - bool includeCustom; + bool includeCustom; CScriptArgReader argStream(luaVM); argStream.ReadBool(includeCustom, true); @@ -235,16 +235,16 @@ int CLuaFunctionDefs::GetKeyboardLayout(lua_State* luaVM) { switch (readingLayoutValue) { - case 0: // Left to right (English) + case 0: // Left to right (English) readingLayout = "ltr"; break; - case 1: // Right to left (Arabic, Hebrew, and Persian) + case 1: // Right to left (Arabic, Hebrew, and Persian) readingLayout = "rtl"; break; - case 2: // Vertical top to bottom with columns to the left and also left to right (Japanese) + case 2: // Vertical top to bottom with columns to the left and also left to right (Japanese) readingLayout = "ttb-rtl-ltr"; break; - case 3: // Vertical top to bottom with columns proceeding to the right (Mongolian) + case 3: // Vertical top to bottom with columns proceeding to the right (Mongolian) readingLayout = "ttb-ltr"; break; default: @@ -293,7 +293,7 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) for (int c = 0; c < Result.ColumnCount(); c++) { const SString& name = Result.ColumnName(c); - lua_pushnumber(luaVM, c + 1); // row index number (starting at 1, not 0) + lua_pushnumber(luaVM, c + 1); // row index number (starting at 1, not 0) lua_pushlstring(luaVM, name.c_str(), name.length()); lua_settable(luaVM, -3); } @@ -301,10 +301,10 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) lua_newtable(luaVM); for (int r = 0; r < Result.RowCount(); r++) { - lua_newtable(luaVM); // new table - lua_pushnumber(luaVM, r + 1); // row index number (starting at 1, not 0) - lua_pushvalue(luaVM, -2); // value - lua_settable(luaVM, -4); // refer to the top level table + lua_newtable(luaVM); // new table + lua_pushnumber(luaVM, r + 1); // row index number (starting at 1, not 0) + lua_pushvalue(luaVM, -2); // value + lua_settable(luaVM, -4); // refer to the top level table for (int c = 0; c < Result.ColumnCount(); c++) { @@ -313,7 +313,7 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) lua_pushlstring(luaVM, cell.c_str(), cell.length()); lua_settable(luaVM, -3); } - lua_pop(luaVM, 1); // pop the inner table + lua_pop(luaVM, 1); // pop the inner table } return 2; } diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Voice.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Voice.cpp index 04a84ee5897..0ab5003465a 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Voice.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.Voice.cpp @@ -15,4 +15,4 @@ int CLuaFunctionDefs::IsVoiceEnabled(lua_State* luaVM) { lua_pushboolean(luaVM, g_pClientGame->GetVoiceRecorder()->IsEnabled()); return 1; -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.h b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.h index a6592f9df04..d2476b716e4 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.h +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionDefs.h @@ -18,7 +18,7 @@ class CLuaFunctionDefinitions; class CRegisteredCommands; -#define LUA_DECLARE(x) static int x ( lua_State * luaVM ); +#define LUA_DECLARE(x) static int x(lua_State* luaVM); class CLuaFunctionDefs { diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp index f056360de43..7ae83f8bfbb 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp @@ -250,13 +250,13 @@ ADD_ENUM(WeaponProperty::WEAPON_WEAPON_RANGE, "weapon_range") ADD_ENUM(WeaponProperty::WEAPON_TARGET_RANGE, "target_range") ADD_ENUM(WeaponProperty::WEAPON_ACCURACY, "accuracy") ADD_ENUM(WeaponProperty::WEAPON_DAMAGE, "damage") -ADD_ENUM(WeaponProperty::WEAPON_LIFE_SPAN, "life_span") // Disabled for release -ADD_ENUM(WeaponProperty::WEAPON_FIRING_SPEED, "firing_speed") // Disabled for release -ADD_ENUM(WeaponProperty::WEAPON_SPREAD, "spread") // Disabled for release +ADD_ENUM(WeaponProperty::WEAPON_LIFE_SPAN, "life_span") // Disabled for release +ADD_ENUM(WeaponProperty::WEAPON_FIRING_SPEED, "firing_speed") // Disabled for release +ADD_ENUM(WeaponProperty::WEAPON_SPREAD, "spread") // Disabled for release ADD_ENUM(WeaponProperty::WEAPON_MAX_CLIP_AMMO, "maximum_clip_ammo") ADD_ENUM(WeaponProperty::WEAPON_MOVE_SPEED, "move_speed") ADD_ENUM(WeaponProperty::WEAPON_FLAGS, "flags") -ADD_ENUM(WeaponProperty::WEAPON_ANIM_GROUP, "anim_group") // Disabled for release +ADD_ENUM(WeaponProperty::WEAPON_ANIM_GROUP, "anim_group") // Disabled for release ADD_ENUM(WeaponProperty::WEAPON_ANIM_LOOP_START, "anim_loop_start") ADD_ENUM(WeaponProperty::WEAPON_ANIM_LOOP_STOP, "anim_loop_stop") @@ -320,7 +320,7 @@ IMPLEMENT_ENUM_BEGIN(ERenderFormat) ADD_ENUM(RFORMAT_UNKNOWN, "unknown") ADD_ENUM(RFORMAT_ARGB, "argb") ADD_ENUM(RFORMAT_XRGB, "xrgb") -ADD_ENUM(RFORMAT_RGB, "rgb") +ADD_ENUM(RFORMAT_RGB, "rgb") ADD_ENUM(RFORMAT_DXT1, "dxt1") ADD_ENUM(RFORMAT_DXT2, "dxt2") ADD_ENUM(RFORMAT_DXT3, "dxt3") @@ -491,11 +491,11 @@ IMPLEMENT_ENUM_BEGIN(eFontQuality) ADD_ENUM(FONT_QUALITY_DEFAULT, "default") ADD_ENUM(FONT_QUALITY_DRAFT, "draft") ADD_ENUM(FONT_QUALITY_PROOF, "proof") -#if( WINVER >= 0x0400 ) +#if (WINVER >= 0x0400) ADD_ENUM(FONT_QUALITY_NONANTIALIASED, "nonantialiased") ADD_ENUM(FONT_QUALITY_ANTIALIASED, "antialiased") #endif -#if( _WIN32_WINNT >= _WIN32_WINNT_WINXP ) +#if (_WIN32_WINNT >= _WIN32_WINNT_WINXP) ADD_ENUM(FONT_QUALITY_CLEARTYPE, "cleartype") ADD_ENUM(FONT_QUALITY_CLEARTYPE_NATURAL, "cleartype_natural") #endif @@ -573,17 +573,17 @@ ADD_ENUM(JSONPRETTY_TABS, "tabs") IMPLEMENT_ENUM_END("json-pretty-type") IMPLEMENT_ENUM_BEGIN(eCursorType) -ADD_ENUM(CURSORTYPE_NONE, "none") // cursor has no image -ADD_ENUM(CURSORTYPE_DEFAULT, "arrow") // default cursor -ADD_ENUM(CURSORTYPE_SIZING_NS, "sizing_ns") // N-S (up-down) sizing cursor -ADD_ENUM(CURSORTYPE_SIZING_EW, "sizing_ew") // E-W (left-right) sizing cursor -ADD_ENUM(CURSORTYPE_SIZING_NWSE, "sizing_nwse") // NW-SE diagonal sizing cursor -ADD_ENUM(CURSORTYPE_SIZING_NESW, "sizing_nesw") // NE-SW diagonal sizing cursor -ADD_ENUM(CURSORTYPE_SIZING_ESWE, "sizing_eswe") // ES-WE horizontal sizing cursor -ADD_ENUM(CURSORTYPE_MOVE, "move") // move cursor -ADD_ENUM(CURSORTYPE_DRAG, "container_drag") // drag container cursor (note: not in use) -ADD_ENUM(CURSORTYPE_SEG_MOVING, "segment_moving") // segment moving cursor (note: not in use) -ADD_ENUM(CURSORTYPE_SEG_SIZING, "segment_sizing") // segment sizing cursor (note: not in use) +ADD_ENUM(CURSORTYPE_NONE, "none") // cursor has no image +ADD_ENUM(CURSORTYPE_DEFAULT, "arrow") // default cursor +ADD_ENUM(CURSORTYPE_SIZING_NS, "sizing_ns") // N-S (up-down) sizing cursor +ADD_ENUM(CURSORTYPE_SIZING_EW, "sizing_ew") // E-W (left-right) sizing cursor +ADD_ENUM(CURSORTYPE_SIZING_NWSE, "sizing_nwse") // NW-SE diagonal sizing cursor +ADD_ENUM(CURSORTYPE_SIZING_NESW, "sizing_nesw") // NE-SW diagonal sizing cursor +ADD_ENUM(CURSORTYPE_SIZING_ESWE, "sizing_eswe") // ES-WE horizontal sizing cursor +ADD_ENUM(CURSORTYPE_MOVE, "move") // move cursor +ADD_ENUM(CURSORTYPE_DRAG, "container_drag") // drag container cursor (note: not in use) +ADD_ENUM(CURSORTYPE_SEG_MOVING, "segment_moving") // segment moving cursor (note: not in use) +ADD_ENUM(CURSORTYPE_SEG_SIZING, "segment_sizing") // segment sizing cursor (note: not in use) IMPLEMENT_ENUM_END("cursor-type") IMPLEMENT_ENUM_BEGIN(eWheelPosition) @@ -953,7 +953,6 @@ ADD_ENUM(RestreamOption::PEDS, "peds") ADD_ENUM(RestreamOption::OBJECTS, "objects") IMPLEMENT_ENUM_CLASS_END("restream-option") - IMPLEMENT_ENUM_CLASS_BEGIN(taskType) ADD_ENUM(taskType::PRIMARY_TASK, "primary") ADD_ENUM(taskType::SECONDARY_TASK, "secondary") @@ -969,7 +968,6 @@ ADD_ENUM(ENTITY_TYPE_DUMMY, "dummy") ADD_ENUM(ENTITY_TYPE_NOTINPOOLS, "unknown") IMPLEMENT_ENUM_END("entity-type") - IMPLEMENT_ENUM_CLASS_BEGIN(VehicleAudioSettingProperty) ADD_ENUM(VehicleAudioSettingProperty::DOOR_SOUND, "door-sound") ADD_ENUM(VehicleAudioSettingProperty::ENGINE_OFF_SOUND_BANK_ID, "engine-off-soundbank-id") @@ -987,7 +985,6 @@ ADD_ENUM(VehicleAudioSettingProperty::ENGINE_UPGRADE, "engine-upgrade") ADD_ENUM(VehicleAudioSettingProperty::VEHICLE_TYPE_FOR_AUDIO, "vehicle-type-for-audio") IMPLEMENT_ENUM_CLASS_END("vehicle-audio-setting") - IMPLEMENT_ENUM_CLASS_BEGIN(PostFXType) ADD_ENUM(PostFXType::GAMMA, "gamma") ADD_ENUM(PostFXType::BRIGHTNESS, "brightness") @@ -1098,15 +1095,15 @@ SString GetUserDataClassName(void* ptr, lua_State* luaVM, bool bFindElementType) return GetClassTypeName(pClientElement); } - if (auto* pVar = UserDataCast((CResource*)ptr, luaVM)) // Try resource + if (auto* pVar = UserDataCast((CResource*)ptr, luaVM)) // Try resource return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CXMLNode*)ptr, luaVM)) // Try xml node + if (auto* pVar = UserDataCast((CXMLNode*)ptr, luaVM)) // Try xml node return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CLuaTimer*)ptr, luaVM)) // Try timer + if (auto* pVar = UserDataCast((CLuaTimer*)ptr, luaVM)) // Try timer return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CLuaVector2D*)ptr, luaVM)) // Try 2D Vector + if (auto* pVar = UserDataCast((CLuaVector2D*)ptr, luaVM)) // Try 2D Vector return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CLuaVector3D*)ptr, luaVM)) // Try 3D Vector + if (auto* pVar = UserDataCast((CLuaVector3D*)ptr, luaVM)) // Try 3D Vector return GetClassTypeName(pVar); if (auto* pVar = UserDataCast((CLuaVector4D*)ptr, luaVM)) return GetClassTypeName(pVar); @@ -1313,16 +1310,14 @@ void MinClientReqCheck(lua_State* luaVM, const char* szVersionReq, const char* s CResource* pResource = pLuaMain->GetResource(); if (!pResource) return; - + if (pResource->GetMinClientReq() < szVersionReq) { #if MTASA_VERSION_TYPE >= VERSION_TYPE_UNTESTED - SString err(" section in the meta.xml is incorrect or missing (expected at least client %s because %s)", - szVersionReq, szReason); + SString err(" section in the meta.xml is incorrect or missing (expected at least client %s because %s)", szVersionReq, szReason); throw std::invalid_argument(err); #endif } - } // @@ -1388,7 +1383,7 @@ uint GetWeaponPropertyFlagBit(WeaponProperty weaponProperty) return 0; // Check 20 bits from first to last - //dassert(WEAPON_FLAG_LAST + 1 - WEAPON_FLAG_FIRST == 20); + // dassert(WEAPON_FLAG_LAST + 1 - WEAPON_FLAG_FIRST == 20); uint uiFlagIndex = ((std::size_t)weaponProperty - (std::size_t)WeaponProperty::WEAPON_FLAG_FIRST); uint uiFlagBit = 1 << uiFlagIndex; diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp b/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp index 52b4fc3678d..65fa553727e 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp @@ -10,7 +10,7 @@ *****************************************************************************/ #include "StdInc.h" -#pragma warning( disable : 4355 ) // warning C4355: 'this' : used in base member initializer list +#pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list CIntrusiveList CLuaFunctionRef::ms_AllRefList(&CLuaFunctionRef::m_ListNode); diff --git a/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.h b/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.h index 9ab5e862d8d..1fe0fc39f03 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.h +++ b/Client/mods/deathmatch/logic/lua/CLuaFunctionRef.h @@ -11,9 +11,9 @@ #pragma once -#define LUA_REFNIL (-1) -#define VERIFY_FUNCTION(func) ( (func).ToInt () != LUA_REFNIL ) -#define IS_REFNIL(func) ( (func).ToInt () == LUA_REFNIL ) +#define LUA_REFNIL (-1) +#define VERIFY_FUNCTION(func) ((func).ToInt() != LUA_REFNIL) +#define IS_REFNIL(func) ((func).ToInt() == LUA_REFNIL) class CLuaFunctionRef { diff --git a/Client/mods/deathmatch/logic/lua/CLuaMain.cpp b/Client/mods/deathmatch/logic/lua/CLuaMain.cpp index 4db16040937..91f26561267 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaMain.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaMain.cpp @@ -21,7 +21,7 @@ static CLuaManager* m_pLuaManager; SString CLuaMain::ms_strExpectedUndumpHash; #define HOOK_INSTRUCTION_COUNT 1000000 -#define HOOK_MAXIMUM_TIME 5000 +#define HOOK_MAXIMUM_TIME 5000 #include "luascripts/coroutine_debug.lua.h" #include "luascripts/exports.lua.h" @@ -111,7 +111,7 @@ void CLuaMain::InitClasses(lua_State* luaVM) CLuaEngineDefs::AddClass(luaVM); CLuaEffectDefs::AddClass(luaVM); CLuaGUIDefs::AddClass(luaVM); - CLuaBrowserDefs::AddClass(luaVM); // browser must be after drawing/gui, since it extends DxTexture/GUIElement + CLuaBrowserDefs::AddClass(luaVM); // browser must be after drawing/gui, since it extends DxTexture/GUIElement CLuaMarkerDefs::AddClass(luaVM); CLuaObjectDefs::AddClass(luaVM); CLuaPedDefs::AddClass(luaVM); @@ -495,14 +495,14 @@ const SString& CLuaMain::GetFunctionTag(int iLuaFunction) strText = SString("@func_%d NULL", iLuaFunction); } - #ifdef CHECK_FUNCTION_TAG +#ifdef CHECK_FUNCTION_TAG if (pTag) { // Check tag remains unchanged assert(strText == *pTag); return *pTag; } - #endif +#endif MapSet(m_FunctionTagMap, iLuaFunction, strText); pTag = MapFind(m_FunctionTagMap, iLuaFunction); diff --git a/Client/mods/deathmatch/logic/lua/CLuaMain.h b/Client/mods/deathmatch/logic/lua/CLuaMain.h index 259fce07bab..f5400c93c2f 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaMain.h +++ b/Client/mods/deathmatch/logic/lua/CLuaMain.h @@ -33,7 +33,7 @@ struct CRefInfo int iFunction; }; -class CLuaMain //: public CClient +class CLuaMain //: public CClient { public: ZERO_ON_NEW @@ -90,7 +90,7 @@ class CLuaMain //: public CClient lua_State* m_luaVM; CLuaTimerManager* m_pLuaTimerManager; - bool m_bBeingDeleted; // prevent it being deleted twice + bool m_bBeingDeleted; // prevent it being deleted twice CElapsedTime m_FunctionEnterTimer; diff --git a/Client/mods/deathmatch/logic/lua/CLuaManager.cpp b/Client/mods/deathmatch/logic/lua/CLuaManager.cpp index 80c9ce03813..e97f802e612 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaManager.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaManager.cpp @@ -29,10 +29,10 @@ CLuaManager::CLuaManager(CClientGame* pClientGame) m_pGUIManager = pClientGame->GetGUIManager(); m_pRegisteredCommands = pClientGame->GetRegisteredCommands(); - // Ensure lua was compiled with apichecks - #ifdef NDEBUG - #error "NDEBUG should not be defined" - #endif +// Ensure lua was compiled with apichecks +#ifdef NDEBUG + #error "NDEBUG should not be defined" +#endif assert(luaX_is_apicheck_enabled()); // Load the C functions @@ -143,7 +143,7 @@ CLuaMain* CLuaManager::GetVirtualMachine(lua_State* luaVM) { if (luaVM == (*iter)->GetVirtualMachine()) { - dassert(0); // Why not in map? + dassert(0); // Why not in map? return *iter; } } diff --git a/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp b/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp index 5d34a1ba277..5006fbae246 100644 --- a/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp +++ b/Client/mods/deathmatch/logic/lua/CLuaTimerManager.cpp @@ -120,7 +120,6 @@ void CLuaTimerManager::SetTimerPaused(CLuaTimer* timer, bool paused) ListRemove(m_ProcessQueue, timer); } - void CLuaTimerManager::ResetTimer(CLuaTimer* pLuaTimer) { assert(pLuaTimer); diff --git a/Client/mods/deathmatch/logic/lua/LuaCommon.cpp b/Client/mods/deathmatch/logic/lua/LuaCommon.cpp index 5fc9d75eed8..45392327811 100644 --- a/Client/mods/deathmatch/logic/lua/LuaCommon.cpp +++ b/Client/mods/deathmatch/logic/lua/LuaCommon.cpp @@ -16,7 +16,7 @@ // End of temporary // Prevent the warning issued when doing unsigned short -> void* -#pragma warning(disable:4312) +#pragma warning(disable : 4312) CClientEntity* lua_toelement(lua_State* luaVM, int iArgument) { @@ -161,7 +161,7 @@ void lua_pushobject(lua_State* luaVM, const char* szClass, void* pObject, bool b // Assign the class metatable lua_getclass(luaVM, szClass); - lua_setmetatable(luaVM, -2); // element + lua_setmetatable(luaVM, -2); // element } void lua_pushvector(lua_State* luaVM, const CVector4D& vector) @@ -253,31 +253,31 @@ void lua_newclass(lua_State* luaVM) void lua_getclass(lua_State* luaVM, const char* szName) { - lua_pushstring(luaVM, "mt"); // "mt" - lua_rawget(luaVM, LUA_REGISTRYINDEX); // mt + lua_pushstring(luaVM, "mt"); // "mt" + lua_rawget(luaVM, LUA_REGISTRYINDEX); // mt assert(lua_istable(luaVM, -1)); - lua_pushstring(luaVM, szName); // mt, class name - lua_rawget(luaVM, -2); // mt, class + lua_pushstring(luaVM, szName); // mt, class name + lua_rawget(luaVM, -2); // mt, class - lua_remove(luaVM, -2); // class + lua_remove(luaVM, -2); // class } void lua_registerclass(lua_State* luaVM, const char* szName, const char* szParent) { if (szParent != NULL) { - lua_pushstring(luaVM, "mt"); // class table, "mt" - lua_rawget(luaVM, LUA_REGISTRYINDEX); // class table, mt table - lua_getfield(luaVM, -1, szParent); // class table, mt table, parent table + lua_pushstring(luaVM, "mt"); // class table, "mt" + lua_rawget(luaVM, LUA_REGISTRYINDEX); // class table, mt table + lua_getfield(luaVM, -1, szParent); // class table, mt table, parent table // Error if we can't find the parent class to extend from assert(lua_istable(luaVM, -1)); - lua_setfield(luaVM, -3, "__parent"); // class table, mt table + lua_setfield(luaVM, -3, "__parent"); // class table, mt table - lua_pop(luaVM, 1); // class table + lua_pop(luaVM, 1); // class table } lua_pushstring(luaVM, "mt"); diff --git a/Client/mods/deathmatch/logic/lua/LuaCommon.h b/Client/mods/deathmatch/logic/lua/LuaCommon.h index 0dfd8194053..71a90a6157d 100644 --- a/Client/mods/deathmatch/logic/lua/LuaCommon.h +++ b/Client/mods/deathmatch/logic/lua/LuaCommon.h @@ -13,14 +13,14 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } CLuaFunctionRef luaM_toref(lua_State* luaVM, int iArgument); -#define TO_ELEMENTID(x) ((ElementID) reinterpret_cast < unsigned long > (x) ) +#define TO_ELEMENTID(x) ((ElementID) reinterpret_cast(x)) // Predeclarations of our classes class CClientColModel; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaAudioDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaAudioDefs.cpp index 6684e6e697d..97986aac0ca 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaAudioDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaAudioDefs.cpp @@ -186,7 +186,7 @@ int CLuaAudioDefs::PlaySound(lua_State* luaVM) { // call onClientSoundStarted CLuaArguments Arguments; - Arguments.PushString("play"); // Reason + Arguments.PushString("play"); // Reason pSound->CallEvent("onClientSoundStarted", Arguments, false); lua_pushelement(luaVM, pSound); @@ -246,7 +246,7 @@ int CLuaAudioDefs::PlaySound3D(lua_State* luaVM) { // call onClientSoundStarted CLuaArguments Arguments; - Arguments.PushString("play"); // Reason + Arguments.PushString("play"); // Reason pSound->CallEvent("onClientSoundStarted", Arguments, false); lua_pushelement(luaVM, pSound); @@ -1407,12 +1407,12 @@ struct SPlayerVoiceWrapper bool SetFxEffectParameters(std::uint32_t uiFxEffect, void* params) { - CClientPlayerVoice* pVoice = pPlayer->GetVoice(); + CClientPlayerVoice* pVoice = pPlayer->GetVoice(); return pVoice ? pVoice->SetFxEffectParameters(uiFxEffect, params) : false; } bool GetFxEffectParameters(std::uint32_t uiFxEffect, void* params) { - CClientPlayerVoice* pVoice = pPlayer->GetVoice(); + CClientPlayerVoice* pVoice = pPlayer->GetVoice(); return pVoice ? pVoice->GetFxEffectParameters(uiFxEffect, params) : false; } }; @@ -1420,14 +1420,15 @@ struct SPlayerVoiceWrapper int CLuaAudioDefs::SetSoundEffectParameter(lua_State* luaVM) { // bool setSoundEffectParameter ( sound/player sound, string effectName, string effectParameter, var effectParameterValue ) - CClientSound* pSound{}; + CClientSound* pSound{}; SPlayerVoiceWrapper playerVoice; - SoundEffectType eEffectType; + SoundEffectType eEffectType; - CScriptArgReader argStream(luaVM); + CScriptArgReader argStream(luaVM); // Call `SetFxEffectParameters` and log errors if any - const auto SetParamWithErrorLog = [luaVM, &eEffectType](auto* pSound, auto effectParam, auto& params) { + const auto SetParamWithErrorLog = [luaVM, &eEffectType](auto* pSound, auto effectParam, auto& params) + { // Try setting parameter if (pSound->SetFxEffectParameters((uint)eEffectType, ¶ms)) { @@ -1451,7 +1452,8 @@ int CLuaAudioDefs::SetSoundEffectParameter(lua_State* luaVM) return 1; }; - const auto ProcessSoundParams = [&eEffectType, luaVM, &argStream, &SetParamWithErrorLog](auto* pSound) { + const auto ProcessSoundParams = [&eEffectType, luaVM, &argStream, &SetParamWithErrorLog](auto* pSound) + { if (!pSound->IsFxEffectEnabled((std::uint32_t)eEffectType)) return luaL_error(luaVM, "Effect's parameters can't be set unless it's enabled"); @@ -1864,7 +1866,7 @@ int CLuaAudioDefs::SetSoundEffectParameter(lua_State* luaVM) lua_pushboolean(luaVM, false); return 1; }; - + if (argStream.NextIsUserDataOfType()) argStream.ReadUserData(pSound); else if (argStream.NextIsUserDataOfType()) @@ -1896,13 +1898,14 @@ int CLuaAudioDefs::SetSoundEffectParameter(lua_State* luaVM) int CLuaAudioDefs::GetSoundEffectParameters(lua_State* luaVM) { // table getSoundEffectParameters ( sound/player sound, string effectName ) - CClientSound* pSound{}; + CClientSound* pSound{}; SPlayerVoiceWrapper playerVoice; - SoundEffectType eEffectType; + SoundEffectType eEffectType; CScriptArgReader argStream(luaVM); - const auto ProcessSoundParams = [luaVM, &eEffectType](auto* pSound) { + const auto ProcessSoundParams = [luaVM, &eEffectType](auto* pSound) + { if (!pSound->IsFxEffectEnabled((std::uint32_t)eEffectType)) return luaL_error(luaVM, "Effect's parameters can't be set unless it's enabled"); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp index 68d21cfb32c..f30c489b129 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp @@ -14,14 +14,18 @@ static constexpr std::uint8_t MAX_BLIP_SIZE = 25; -std::variant CLuaBlipDefs::CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance) +std::variant CLuaBlipDefs::CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, + std::optional ordering, std::optional visibleDistance) { if (icon.has_value() && !CClientRadarMarkerManager::IsValidIcon(icon.value())) throw std::invalid_argument("Invalid icon"); if (size.has_value() && size.value() > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", + MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } @@ -39,14 +43,19 @@ std::variant CLuaBlipDefs::CreateBlip(lua_State* luaV return radarMarker; } -std::variant CLuaBlipDefs::CreateBlipAttachedTo(lua_State* luaVM, CClientEntity* entity, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance) +std::variant CLuaBlipDefs::CreateBlipAttachedTo(lua_State* luaVM, CClientEntity* entity, std::optional icon, + std::optional size, std::optional r, + std::optional g, std::optional b, + std::optional a, std::optional ordering, + std::optional visibleDistance) { if (icon.has_value() && !CClientRadarMarkerManager::IsValidIcon(icon.value())) throw std::invalid_argument("Invalid icon"); if (size.has_value() && size.value() > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", + MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } @@ -57,7 +66,7 @@ std::variant CLuaBlipDefs::CreateBlipAttachedTo(lua_S if (!radarMarker) return false; - + if (CElementGroup* elementGroup = resource.GetElementGroup()) elementGroup->Add(radarMarker); @@ -102,7 +111,8 @@ bool CLuaBlipDefs::SetBlipSize(lua_State* luaVM, CClientRadarMarker* radarMarker { if (size > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size, MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning( + luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size, MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h index b6e4bea7873..fffd02abdb6 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h @@ -20,8 +20,15 @@ class CLuaBlipDefs : public CLuaDefs private: // Create functions - static std::variant CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance); - static std::variant CreateBlipAttachedTo(lua_State* luaVM, CClientEntity* entity, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance); + static std::variant CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, + std::optional ordering, std::optional visibleDistance); + static std::variant CreateBlipAttachedTo(lua_State* luaVM, CClientEntity* entity, std::optional icon, + std::optional size, std::optional r, + std::optional g, std::optional b, + std::optional a, std::optional ordering, + std::optional visibleDistance); // Get functions static auto GetBlipIcon(CClientRadarMarker* radarMarker) noexcept; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaBrowserDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaBrowserDefs.cpp index be45ecc9712..50f7a796111 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaBrowserDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaBrowserDefs.cpp @@ -211,7 +211,8 @@ int CLuaBrowserDefs::RequestBrowserDomains(lua_State* luaVM) std::transform(pages.begin(), pages.end(), pages.begin(), [pWebCore](const auto& url) { return pWebCore->GetDomainFromURL(url); }); } - WebRequestCallback callback = [=](bool bAllow, const std::unordered_set& domains) { + WebRequestCallback callback = [=](bool bAllow, const std::unordered_set& domains) + { // Test if luaVM is still available if (m_pLuaManager->IsLuaVMValid(luaVM) && VERIFY_FUNCTION(callbackFunction)) { @@ -574,7 +575,7 @@ int CLuaBrowserDefs::IsBrowserDomainBlocked(lua_State* luaVM) lua_pushnil(luaVM); return 1; } - + if (bIsURL) strURL = pWebCore->GetDomainFromURL(strURL); @@ -631,7 +632,7 @@ int CLuaBrowserDefs::IsBrowserFocused(lua_State* luaVM) if (!argStream.HasErrors()) { - auto pWebCore = g_pCore->GetWebCore(); + auto pWebCore = g_pCore->GetWebCore(); CWebViewInterface* pWebView = pWebCore ? pWebCore->GetFocusedWebView() : nullptr; lua_pushboolean(luaVM, pWebBrowser->GetWebView() == pWebView); return 1; @@ -700,7 +701,7 @@ int CLuaBrowserDefs::GetBrowserSettings(lua_State* luaVM) { // table getBrowserSettings () auto pWebCore = g_pCore->GetWebCore(); - + lua_createtable(luaVM, 0, 3); lua_pushstring(luaVM, "RemoteEnabled"); @@ -734,21 +735,23 @@ int CLuaBrowserDefs::GetBrowserSource(lua_State* luaVM) CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); if (pLuaMain && VERIFY_FUNCTION(callbackFunction)) { - pWebBrowser->GetSourceCode([callbackFunction, pLuaMain, pWebBrowser](const std::string& code) { - /* - This function should not be called when the resource is about to stop as - stopping the resource destroys the browser element and thus cancels the - CefStringVisitor callback class (see CWebView::GetSourceCode::MyStringVisitor) - */ - if (VERIFY_FUNCTION(callbackFunction)) + pWebBrowser->GetSourceCode( + [callbackFunction, pLuaMain, pWebBrowser](const std::string& code) { - CLuaArguments arguments; - // TODO: Use SCharStringRef/direct string access instead of copying strings around - arguments.PushString(code); - arguments.PushElement(pWebBrowser); - arguments.Call(pLuaMain, callbackFunction); - } - }); + /* + This function should not be called when the resource is about to stop as + stopping the resource destroys the browser element and thus cancels the + CefStringVisitor callback class (see CWebView::GetSourceCode::MyStringVisitor) + */ + if (VERIFY_FUNCTION(callbackFunction)) + { + CLuaArguments arguments; + // TODO: Use SCharStringRef/direct string access instead of copying strings around + arguments.PushString(code); + arguments.PushElement(pWebBrowser); + arguments.Call(pLuaMain, callbackFunction); + } + }); lua_pushboolean(luaVM, true); return 1; @@ -983,7 +986,7 @@ int CLuaBrowserDefs::GUICreateBrowser(lua_State* luaVM) return 1; } -int CLuaBrowserDefs::GUIGetBrowser(lua_State* luaVM) // Or rather guiGetBrowserBrowser? +int CLuaBrowserDefs::GUIGetBrowser(lua_State* luaVM) // Or rather guiGetBrowserBrowser? { // webbrowser guiGetBrowser ( gui-webbrowser browser ) CClientGUIElement* pGUIElement; @@ -1041,45 +1044,47 @@ int CLuaBrowserDefs::SetBrowserAjaxHandler(lua_State* luaVM) CResourceManager* pResourceManager = m_pResourceManager; auto netId = pResource->GetNetID(); - bool bResult = pWebBrowser->AddAjaxHandler(strURL, [=](std::vector& vecGet, std::vector& vecPost) -> const std::string { - // Make sure the resource is still running - if (!pResourceManager->Exists(pResource) || pResource->GetNetID() != netId) - { - return ""; - } - - // Make sure the function is valid - if (VERIFY_FUNCTION(callbackFunction)) - { - CLuaArguments arguments; - CLuaArguments getArguments; - CLuaArguments postArguments; - - for (auto&& param : vecGet) - getArguments.PushString(param); - - for (auto&& param : vecPost) - postArguments.PushString(param); - - arguments.PushTable(&getArguments); - arguments.PushTable(&postArguments); - - CLuaArguments result; - - arguments.Call(pLuaMain, callbackFunction, &result); - - if (result.IsEmpty()) - return ""; - - CLuaArgument* returnedValue = *result.begin(); - if (returnedValue->GetType() == LUA_TSTRING) - return std::string(returnedValue->GetString()); - else - return ""; - } - else - return ""; - }); + bool bResult = pWebBrowser->AddAjaxHandler(strURL, + [=](std::vector& vecGet, std::vector& vecPost) -> const std::string + { + // Make sure the resource is still running + if (!pResourceManager->Exists(pResource) || pResource->GetNetID() != netId) + { + return ""; + } + + // Make sure the function is valid + if (VERIFY_FUNCTION(callbackFunction)) + { + CLuaArguments arguments; + CLuaArguments getArguments; + CLuaArguments postArguments; + + for (auto&& param : vecGet) + getArguments.PushString(param); + + for (auto&& param : vecPost) + postArguments.PushString(param); + + arguments.PushTable(&getArguments); + arguments.PushTable(&postArguments); + + CLuaArguments result; + + arguments.Call(pLuaMain, callbackFunction, &result); + + if (result.IsEmpty()) + return ""; + + CLuaArgument* returnedValue = *result.begin(); + if (returnedValue->GetType() == LUA_TSTRING) + return std::string(returnedValue->GetString()); + else + return ""; + } + else + return ""; + }); lua_pushboolean(luaVM, bResult); return 1; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp index 778d14ab293..732b821cbea 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp @@ -33,7 +33,8 @@ void CLuaBuildingDefs::AddClass(lua_State* luaVM) lua_registerclass(luaVM, "Building", "Element"); } -CClientBuilding* CLuaBuildingDefs::CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, std::optional interior) +CClientBuilding* CLuaBuildingDefs::CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, + std::optional interior) { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); @@ -53,7 +54,7 @@ CClientBuilding* CLuaBuildingDefs::CreateBuilding(lua_State* const luaVM, std::u else rot.emplace(CVector(0, 0, 0)); - CClientBuilding* pBuilding = new CClientBuilding(m_pManager, INVALID_ELEMENT_ID, modelId, pos, rot.value() , interior.value_or(0)); + CClientBuilding* pBuilding = new CClientBuilding(m_pManager, INVALID_ELEMENT_ID, modelId, pos, rot.value(), interior.value_or(0)); CClientEntity* pRoot = pResource->GetResourceDynamicEntity(); pBuilding->SetParent(pRoot); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h index 1a723488024..28b950ac761 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h @@ -19,7 +19,8 @@ class CLuaBuildingDefs : public CLuaDefs static void AddClass(lua_State* luaVM); // Buiding create funcs - static CClientBuilding* CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, std::optional interior); + static CClientBuilding* CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, + std::optional interior); static void RemoveAllGameBuildings(); static void RestoreGameBuildings(); }; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaCameraDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaCameraDefs.cpp index eb8c3519c77..7b7faaf8ea6 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaCameraDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaCameraDefs.cpp @@ -560,7 +560,7 @@ bool CLuaCameraDefs::ShakeCamera(float radius, std::optional x, std::opti if (!x || !y || !z) { const auto* player = CStaticFunctionDefinitions::GetLocalPlayer(); - CVector out; + CVector out; player->GetPosition(out); x = out.fX; y = out.fY; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp index 9efb8a88523..3b74e2474ed 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp @@ -14,75 +14,75 @@ // Don't whine bout my gotos, lua api is a bitch, i had to! int CLuaClassDefs::Index(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, mt // First we look for a function - lua_pushstring(luaVM, "__class"); // ud, k, mt, "__class" - lua_rawget(luaVM, -2); // ud, k, mt, __class table + lua_pushstring(luaVM, "__class"); // ud, k, mt, "__class" + lua_rawget(luaVM, -2); // ud, k, mt, __class table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, mt, __class table, k - lua_rawget(luaVM, -2); // ud, k, mt, __class table, function - lua_remove(luaVM, -2); // ud, k, mt, function + lua_pushvalue(luaVM, 2); // ud, k, mt, __class table, k + lua_rawget(luaVM, -2); // ud, k, mt, __class table, function + lua_remove(luaVM, -2); // ud, k, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the function, clean up and return - lua_remove(luaVM, -2); // ud, k, function + { // Found the function, clean up and return + lua_remove(luaVM, -2); // ud, k, function return 1; } - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt // Function not found, look for property - lua_pushstring(luaVM, "__get"); // ud, k, mt, "__get" - lua_rawget(luaVM, -2); // ud, k, mt, __get table + lua_pushstring(luaVM, "__get"); // ud, k, mt, "__get" + lua_rawget(luaVM, -2); // ud, k, mt, __get table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, mt, __get table, k - lua_rawget(luaVM, -2); // ud, k, mt, __get table, function - lua_remove(luaVM, -2); // ud, k, mt, function + lua_pushvalue(luaVM, 2); // ud, k, mt, __get table, k + lua_rawget(luaVM, -2); // ud, k, mt, __get table, function + lua_remove(luaVM, -2); // ud, k, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property, - lua_remove(luaVM, -2); // ud, k, function + { // Found the property, + lua_remove(luaVM, -2); // ud, k, function - lua_pushvalue(luaVM, 1); // ud, k, function, ud - lua_call(luaVM, 1, 1); // ud, k, result + lua_pushvalue(luaVM, 1); // ud, k, function, ud + lua_call(luaVM, 1, 1); // ud, k, result return 1; } - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__index"); // ud, k, mt, __parent table, "__index" - lua_rawget(luaVM, -2); // ud, k, mt, __parent table, function + lua_pushstring(luaVM, "__index"); // ud, k, mt, __parent table, "__index" + lua_rawget(luaVM, -2); // ud, k, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 1); // ud, k, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, mt, __parent table, function, ud, k - lua_call(luaVM, 2, 1); // ud, k, mt, __parent table, result + lua_call(luaVM, 2, 1); // ud, k, mt, __parent table, result - lua_replace(luaVM, -3); // ud, k, result, __parent table - lua_pop(luaVM, 1); // ud, k, result + lua_replace(luaVM, -3); // ud, k, result, __parent table + lua_pop(luaVM, 1); // ud, k, result return 1; } - lua_pop(luaVM, 1); // ud, k, mt, __parent table + lua_pop(luaVM, 1); // ud, k, mt, __parent table } - lua_pop(luaVM, 2); // ud, k + lua_pop(luaVM, 2); // ud, k lua_pushnil(luaVM); return 1; @@ -90,113 +90,113 @@ int CLuaClassDefs::Index(lua_State* luaVM) int CLuaClassDefs::NewIndex(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt - lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table + lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function - lua_remove(luaVM, -2); // ud, k, v, mt, function + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function + lua_remove(luaVM, -2); // ud, k, v, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property - lua_pushvalue(luaVM, 1); // ud, k, v, mt, function, ud - lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, ud, v + { // Found the property + lua_pushvalue(luaVM, 1); // ud, k, v, mt, function, ud + lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, ud, v - lua_call(luaVM, 2, 0); // ud, k, v, mt + lua_call(luaVM, 2, 0); // ud, k, v, mt - lua_pop(luaVM, 1); // ud, k, v + lua_pop(luaVM, 1); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function + lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k - lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v + lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v - lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table + lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt, __parent table + lua_pop(luaVM, 1); // ud, k, v, mt, __parent table } - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } int CLuaClassDefs::StaticNewIndex(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt - lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table + lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function - lua_remove(luaVM, -2); // ud, k, v, mt, function + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function + lua_remove(luaVM, -2); // ud, k, v, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property - lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, v + { // Found the property + lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, v - lua_call(luaVM, 1, 0); // ud, k, v, mt + lua_call(luaVM, 1, 0); // ud, k, v, mt - lua_pop(luaVM, 1); // ud, k, v + lua_pop(luaVM, 1); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function + lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k - lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v + lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v - lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table + lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt, __parent table + lua_pop(luaVM, 1); // ud, k, v, mt, __parent table } - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.h index 2f20191aab8..78f09d3ccb9 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaClassDefs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } class CLuaClassDefs : public CLuaDefs diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaDefs.h index 9318f9a8062..bc2c6c2f275 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaDefs.h @@ -10,7 +10,7 @@ #pragma once -#define LUA_DECLARE(x) static int x ( lua_State * luaVM ); +#define LUA_DECLARE(x) static int x(lua_State* luaVM); #define LUA_DECLARE_OOP(x) LUA_DECLARE(x) LUA_DECLARE(OOP_##x) #include "lua/CLuaFunctionParser.h" diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.cpp index 0c4ba316273..262920c7b6a 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.cpp @@ -24,7 +24,7 @@ void CLuaDiscordDefs::LoadFunctions() {"setDiscordRichPresenceEndTime", ArgumentParser}, {"setDiscordRichPresencePartySize", ArgumentParser}, {"resetDiscordRichPresenceData", ArgumentParser}, - {"isDiscordRichPresenceConnected", ArgumentParser }, + {"isDiscordRichPresenceConnected", ArgumentParser}, {"getDiscordRichPresenceUserID", ArgumentParser}, }; @@ -48,8 +48,8 @@ void CLuaDiscordDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "setPartySize", "setDiscordRichPresencePartySize"); lua_classfunction(luaVM, "isConnected", "isDiscordRichPresenceConnected"); - //lua_classfunction(luaVM, "setAppID", "setDiscordRichPresenceAppID"); - //lua_classfunction(luaVM, "setAppID", "setDiscordRichPresenceAppID"); + // lua_classfunction(luaVM, "setAppID", "setDiscordRichPresenceAppID"); + // lua_classfunction(luaVM, "setAppID", "setDiscordRichPresenceAppID"); lua_registerclass(luaVM, "DiscordRPC"); } @@ -100,7 +100,7 @@ bool CLuaDiscordDefs::SetAppID(lua_State* luaVM, std::string strAppID) auto discord = g_pCore->GetDiscord(); - CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); + CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); const char* resourceName = ""; if (pLuaMain) { diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.h index 6fa724f2417..efd1fce687f 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaDiscordDefs.h @@ -17,18 +17,17 @@ class CLuaDiscordDefs : public CLuaDefs static void AddClass(lua_State* luaVM); private: - static bool ResetData(); - static bool SetState(std::string strState); - static bool SetAppID(lua_State* luaVM, std::string strAppID); - static bool SetDetails(std::string strDetails); - static bool SetAsset(std::string szAsset, std::string szAssetText, bool bIsLarge = false); - static bool SetButtons(unsigned short int iIndex, std::string szName, std::string szUrl); - static bool SetLargeAsset(std::string szAsset, std::string szAssetText); - static bool SetSmallAsset(std::string szAsset, std::string szAssetText); - static bool SetStartTime(unsigned long ulTime); - static bool SetEndTime(unsigned long ulTime); - static bool SetPartySize(int iMin, int iMax); - static bool IsDiscordRPCConnected(); + static bool ResetData(); + static bool SetState(std::string strState); + static bool SetAppID(lua_State* luaVM, std::string strAppID); + static bool SetDetails(std::string strDetails); + static bool SetAsset(std::string szAsset, std::string szAssetText, bool bIsLarge = false); + static bool SetButtons(unsigned short int iIndex, std::string szName, std::string szUrl); + static bool SetLargeAsset(std::string szAsset, std::string szAssetText); + static bool SetSmallAsset(std::string szAsset, std::string szAssetText); + static bool SetStartTime(unsigned long ulTime); + static bool SetEndTime(unsigned long ulTime); + static bool SetPartySize(int iMin, int iMax); + static bool IsDiscordRPCConnected(); static std::string GetDiscordUserID(); }; - diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.cpp index f1304623967..fa652401e78 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.cpp @@ -189,10 +189,10 @@ int CLuaDrawingDefs::DxDrawLine(lua_State* luaVM) int CLuaDrawingDefs::DxDrawLine3D(lua_State* luaVM) { // bool dxDrawLine3D ( float startX, float startY, float startZ, float endX, float endY, float endZ, int color[, int width, bool postGUI ] ) - CVector vecBegin; - CVector vecEnd; - SColor color; - float fWidth; + CVector vecBegin; + CVector vecEnd; + SColor color; + float fWidth; eRenderStage renderStage{eRenderStage::POST_FX}; CScriptArgReader argStream(luaVM); @@ -232,7 +232,7 @@ int CLuaDrawingDefs::DxDrawMaterialLine3D(lua_State* luaVM) SColor color; CVector vecFaceToward; bool bUseFaceToward = false; - eRenderStage renderStage{eRenderStage::POST_FX}; + eRenderStage renderStage{eRenderStage::POST_FX}; CScriptArgReader argStream(luaVM); argStream.ReadVector3D(vecBegin); @@ -282,7 +282,7 @@ int CLuaDrawingDefs::DxDrawMaterialSectionLine3D(lua_State* luaVM) SColor color; CVector vecFaceToward; bool bUseFaceToward = false; - eRenderStage renderStage{eRenderStage::POST_FX}; + eRenderStage renderStage{eRenderStage::POST_FX}; CScriptArgReader argStream(luaVM); argStream.ReadVector3D(vecBegin); @@ -598,7 +598,7 @@ int CLuaDrawingDefs::DxDrawPrimitive3D(lua_State* luaVM) // bool DxDrawPrimitive3D (string primitiveType, bool postGUI, table vertice1, ...) D3DPRIMITIVETYPE ePrimitiveType; auto pVecVertices = new std::vector(); - eRenderStage renderStage{eRenderStage::POST_FX}; + eRenderStage renderStage{eRenderStage::POST_FX}; CScriptArgReader argStream(luaVM); argStream.ReadEnumString(ePrimitiveType); if (argStream.NextIsBool()) @@ -651,7 +651,7 @@ int CLuaDrawingDefs::DxDrawMaterialPrimitive3D(lua_State* luaVM) D3DPRIMITIVETYPE ePrimitiveType; auto pVecVertices = new std::vector(); CClientMaterial* pMaterialElement; - eRenderStage renderStage{eRenderStage::POST_FX}; + eRenderStage renderStage{eRenderStage::POST_FX}; CScriptArgReader argStream(luaVM); argStream.ReadEnumString(ePrimitiveType); @@ -1055,7 +1055,10 @@ int CLuaDrawingDefs::DxCreateTexture(lua_State* luaVM) } else { - m_pScriptDebugging->LogCustom(luaVM, SString("[DxCreateTexture] Failed to create texture from file '%s' (may be corrupt, unsupported format, or out of memory)", strFilePath.c_str())); + m_pScriptDebugging->LogCustom( + luaVM, + SString("[DxCreateTexture] Failed to create texture from file '%s' (may be corrupt, unsupported format, or out of memory)", + strFilePath.c_str())); lua_pushnil(luaVM); return 1; } @@ -1097,7 +1100,8 @@ int CLuaDrawingDefs::DxCreateTexture(lua_State* luaVM) } else { - m_pScriptDebugging->LogCustom(luaVM, SString("[DxCreateTexture:Blank] Failed to create blank texture %dx%d (invalid dimensions or out of memory)", width, height)); + m_pScriptDebugging->LogCustom( + luaVM, SString("[DxCreateTexture:Blank] Failed to create blank texture %dx%d (invalid dimensions or out of memory)", width, height)); lua_pushnil(luaVM); return 1; } @@ -1224,9 +1228,9 @@ int CLuaDrawingDefs::DxCreateRenderTarget(lua_State* luaVM) { // element dxCreateRenderTarget( int sizeX, int sizeY [, int withAlphaChannel = false ] ) // element dxCreateRenderTarget( int sizeX, int sizeY, SurfaceFormat surfaceFormat ) - CVector2D vecSize; - bool bWithAlphaChannel = false; - bool bHasSurfaceFormat = false; + CVector2D vecSize; + bool bWithAlphaChannel = false; + bool bHasSurfaceFormat = false; _D3DFORMAT surfaceFormat; CScriptArgReader argStream(luaVM); @@ -1421,11 +1425,11 @@ int CLuaDrawingDefs::DxSetShaderValue(lua_State* luaVM) float fBuffer[16]{}; uint i = 0; - lua_pushnil(luaVM); // Loop through our table, beginning at the first key + lua_pushnil(luaVM); // Loop through our table, beginning at the first key while (lua_next(luaVM, argStream.m_iIndex) != 0 && i < NUMELMS(fBuffer)) { - fBuffer[i++] = static_cast(lua_tonumber(luaVM, -1)); // Ignore the index at -2, and just read the value - lua_pop(luaVM, 1); // Remove the item and keep the key for the next iteration + fBuffer[i++] = static_cast(lua_tonumber(luaVM, -1)); // Ignore the index at -2, and just read the value + lua_pop(luaVM, 1); // Remove the item and keep the key for the next iteration } bool bResult = pShader->GetShaderItem()->SetValue(strName, fBuffer, i); lua_pushboolean(luaVM, bResult); @@ -1774,27 +1778,29 @@ int CLuaDrawingDefs::DxGetStatus(lua_State* luaVM) lua_settable(luaVM, -3); lua::Push(luaVM, "SettingDebugMode"); - lua::Push(luaVM, [] { - switch (g_pCore->GetDiagnosticDebug()) - { - case EDiagnosticDebug::GRAPHICS_6734: - return "#6734 Graphics"; - case EDiagnosticDebug::D3D_6732: - return "#6732 D3D"; - case EDiagnosticDebug::LOG_TIMING_0000: - return "#0000 Log timing"; - case EDiagnosticDebug::JOYSTICK_0000: - return "#0000 Joystick"; - case EDiagnosticDebug::LUA_TRACE_0000: - return "#0000 Lua trace"; - case EDiagnosticDebug::RESIZE_ALWAYS_0000: - return "#0000 Resize always"; - case EDiagnosticDebug::RESIZE_NEVER_0000: - return "#0000 Resize never"; - default: - return "Default"; - } - }()); + lua::Push(luaVM, + [] + { + switch (g_pCore->GetDiagnosticDebug()) + { + case EDiagnosticDebug::GRAPHICS_6734: + return "#6734 Graphics"; + case EDiagnosticDebug::D3D_6732: + return "#6732 D3D"; + case EDiagnosticDebug::LOG_TIMING_0000: + return "#0000 Log timing"; + case EDiagnosticDebug::JOYSTICK_0000: + return "#0000 Joystick"; + case EDiagnosticDebug::LUA_TRACE_0000: + return "#0000 Lua trace"; + case EDiagnosticDebug::RESIZE_ALWAYS_0000: + return "#0000 Resize always"; + case EDiagnosticDebug::RESIZE_NEVER_0000: + return "#0000 Resize never"; + default: + return "Default"; + } + }()); lua_settable(luaVM, -3); return 1; @@ -1809,7 +1815,8 @@ int CLuaDrawingDefs::DxGetStatus(lua_State* luaVM) int CLuaDrawingDefs::DxGetTexturePixels(lua_State* luaVM) { - // string dxGetTexturePixels( [ int surfaceIndex, ] element texture [, string pixelsFormat = "plain" [, string textureFormat = "argb"] [, bool mipmaps = true]] + // string dxGetTexturePixels( [ int surfaceIndex, ] element texture [, string pixelsFormat = "plain" [, string textureFormat = "argb"] [, bool mipmaps = + // true]] // [, int x, int y, int width, int height ] ) CClientTexture* pTexture; CVector2D vecPosition; @@ -2141,7 +2148,8 @@ bool CLuaDrawingDefs::DxDrawWiredSphere(lua_State* const luaVM, const CVector po return true; } -bool CLuaDrawingDefs::DxDrawModel3D(std::uint32_t modelID, CVector position, CVector rotation, const std::optional scale, const std::optional lighting) +bool CLuaDrawingDefs::DxDrawModel3D(std::uint32_t modelID, CVector position, CVector rotation, const std::optional scale, + const std::optional lighting) { CModelInfo* pModelInfo = g_pGame->GetModelInfo(modelID); if (!pModelInfo) @@ -2155,6 +2163,6 @@ bool CLuaDrawingDefs::DxDrawModel3D(std::uint32_t modelID, CVector position, CVe ConvertDegreesToRadians(rotation); - return g_pClientGame->GetModelRenderer()->EnqueueModel(pModelInfo, - CMatrix{position, rotation, scale.value_or(CVector{1.0f, 1.0f, 1.0f})}, lighting.value_or(0.0f)); + return g_pClientGame->GetModelRenderer()->EnqueueModel(pModelInfo, CMatrix{position, rotation, scale.value_or(CVector{1.0f, 1.0f, 1.0f})}, + lighting.value_or(0.0f)); } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.h index 89278accd11..0a0a7917d48 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaDrawingDefs.h @@ -82,7 +82,8 @@ class CLuaDrawingDefs : public CLuaDefs static bool DxDrawWiredSphere(lua_State* const luaVM, const CVector position, const float radius, const std::optional color, const std::optional lineWidth, const std::optional iterations); - static bool DxDrawModel3D(std::uint32_t modelID, CVector position, CVector rotation, const std::optional scale, const std::optional lighting); + static bool DxDrawModel3D(std::uint32_t modelID, CVector position, CVector rotation, const std::optional scale, + const std::optional lighting); private: static void AddDxMaterialClass(lua_State* luaVM); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.cpp index 2112aaf4394..5aa04aca2e2 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.cpp @@ -643,7 +643,11 @@ int CLuaEffectDefs::SetEffectDensity(lua_State* luaVM) return 1; } -bool CLuaEffectDefs::FxCreateParticle(FxParticleSystems eParticleSystem, CVector vecPosition, CVector vecDirection, float fR, float fG, float fB, float fA, std::optional bRandomizeColors, std::optional iCount, std::optional fBrightness, std::optional fSize, std::optional bRandomizeSizes, std::optional fLife) +bool CLuaEffectDefs::FxCreateParticle(FxParticleSystems eParticleSystem, CVector vecPosition, CVector vecDirection, float fR, float fG, float fB, float fA, + std::optional bRandomizeColors, std::optional iCount, std::optional fBrightness, + std::optional fSize, std::optional bRandomizeSizes, std::optional fLife) { - return CStaticFunctionDefinitions::FxCreateParticle(eParticleSystem, vecPosition, vecDirection, fR/255, fG/255, fB/255, fA/255, bRandomizeColors.value_or(false), iCount.value_or(1), fBrightness.value_or(1.0f), fSize.value_or(0.3f), bRandomizeSizes.value_or(false), fLife.value_or(1.0f)); + return CStaticFunctionDefinitions::FxCreateParticle(eParticleSystem, vecPosition, vecDirection, fR / 255, fG / 255, fB / 255, fA / 255, + bRandomizeColors.value_or(false), iCount.value_or(1), fBrightness.value_or(1.0f), fSize.value_or(0.3f), + bRandomizeSizes.value_or(false), fLife.value_or(1.0f)); } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.h index d45107069cb..fa33a6c434d 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaEffectDefs.h @@ -38,5 +38,7 @@ class CLuaEffectDefs : public CLuaDefs LUA_DECLARE(SetEffectDensity); LUA_DECLARE(GetEffectDensity); - static bool FxCreateParticle(FxParticleSystems eParticleSystem, CVector vecPosition, CVector vecDirection, float fR, float fG, float fB, float fA, std::optional bRandomizeColors, std::optional iCount, std::optional fBrightness, std::optional fSize, std::optional bRandomizeSizes, std::optional fLife); + static bool FxCreateParticle(FxParticleSystems eParticleSystem, CVector vecPosition, CVector vecDirection, float fR, float fG, float fB, float fA, + std::optional bRandomizeColors, std::optional iCount, std::optional fBrightness, + std::optional fSize, std::optional bRandomizeSizes, std::optional fLife); }; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp index c763e1d3f4a..47325652346 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp @@ -978,7 +978,8 @@ CClientEntityResult CLuaElementDefs::GetElementsWithinRange(CVector pos, float r if (interior || dimension || typeHash) { result.erase(std::remove_if(result.begin(), result.end(), - [&, radiusSq = radius * radius](CElement* pElement) { + [&, radiusSq = radius * radius](CElement* pElement) + { if (typeHash && typeHash != pElement->GetTypeHash()) return true; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.cpp index e1f6330908d..8d9bc6ece59 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.cpp @@ -20,9 +20,10 @@ //! Set the CModelCacheManager limits //! By passing `nil`/no value the original values are restored -void EngineStreamingSetModelCacheLimits(std::optional numVehicles, std::optional numPeds) { - size_t vehicleValue = numVehicles.value_or(0); - size_t pedValue = numPeds.value_or(0); +void EngineStreamingSetModelCacheLimits(std::optional numVehicles, std::optional numPeds) +{ + size_t vehicleValue = numVehicles.value_or(0); + size_t pedValue = numPeds.value_or(0); const size_t* pVehicles = numVehicles.has_value() ? &vehicleValue : nullptr; const size_t* pPeds = numPeds.has_value() ? &pedValue : nullptr; g_pClientGame->GetModelCacheManager()->SetCustomLimits(pVehicles, pPeds); @@ -40,39 +41,49 @@ std::uint32_t EngineStreamingGetUsedMemory() } // Set the streaming memory size to a custom value -void EngineStreamingSetMemorySize(size_t sizeBytes) { - if (sizeBytes == 0) { +void EngineStreamingSetMemorySize(size_t sizeBytes) +{ + if (sizeBytes == 0) + { throw std::invalid_argument{"Memory size must be > 0"}; } g_pCore->SetCustomStreamingMemory(sizeBytes); } // Restore memory size to cvar -void EngineStreamingRestoreMemorySize() { +void EngineStreamingRestoreMemorySize() +{ g_pCore->SetCustomStreamingMemory(0); } // Get the streaming memory size [In bytes] - This is the limit, not the amount currently used! [See `EngineStreamingGetUsedMemory`] -size_t EngineStreamingGetMemorySize() { +size_t EngineStreamingGetMemorySize() +{ return g_pCore->GetStreamingMemory(); } // Set streaming buffer size -bool EngineStreamingSetBufferSize(size_t sizeBytes) { +bool EngineStreamingSetBufferSize(size_t sizeBytes) +{ const auto sizeBlocks = sizeBytes / 2048; - if (sizeBlocks > g_pClientGame->GetManager()->GetIMGManager()->GetLargestFileSizeBlocks()) { // Can't allow it to be less than the largest file + if (sizeBlocks > g_pClientGame->GetManager()->GetIMGManager()->GetLargestFileSizeBlocks()) + { // Can't allow it to be less than the largest file return g_pGame->GetStreaming()->SetStreamingBufferSize(sizeBlocks); - } else { + } + else + { return false; } } -void EngineStreamingRestoreBufferSize() { +void EngineStreamingRestoreBufferSize() +{ g_pGame->GetStreaming()->SetStreamingBufferSize(g_pClientGame->GetManager()->GetIMGManager()->GetLargestFileSizeBlocks()); } // Get current streaming buffer size -size_t EngineStreamingGetBufferSize() { +size_t EngineStreamingGetBufferSize() +{ return g_pGame->GetStreaming()->GetStreamingBufferSize(); } @@ -157,7 +168,6 @@ void CLuaEngineDefs::LoadFunctions() {"engineRestreamModel", ArgumentParser}, {"engineRestream", ArgumentParser}, - // CLuaCFunctions::AddFunction ( "engineReplaceMatchingAtomics", EngineReplaceMatchingAtomics ); // CLuaCFunctions::AddFunction ( "engineReplaceWheelAtomics", EngineReplaceWheelAtomics ); // CLuaCFunctions::AddFunction ( "enginePositionAtomic", EnginePositionAtomic ); @@ -434,7 +444,7 @@ int CLuaEngineDefs::EngineLoadTXD(lua_State* luaVM) bool bFilteringEnabled = true; CScriptArgReader argStream(luaVM); argStream.ReadString(input); - if (argStream.NextIsBool()) // Some scripts have a number here (in error) + if (argStream.NextIsBool()) // Some scripts have a number here (in error) argStream.ReadBool(bFilteringEnabled, true); if (!argStream.HasErrors()) @@ -491,7 +501,7 @@ int CLuaEngineDefs::EngineLoadTXD(lua_State* luaVM) SString strError = pTXD->GetLastError(); if (strError.empty()) strError = "Error loading TXD"; - + // Delete it again delete pTXD; argStream.SetCustomError(bIsRawData ? SStringX("raw data") : input, strError); @@ -780,7 +790,7 @@ std::string CLuaEngineDefs::EngineImageGetFile(CClientIMG* pIMG, std::variantGetFile(ResolveIMGFileID(pIMG, file), buffer)) // Get file might throw + if (!pIMG->GetFile(ResolveIMGFileID(pIMG, file), buffer)) // Get file might throw throw std::invalid_argument("Failed to read file. Probably EOF reached, make sure the archieve isn't corrupted."); return buffer; @@ -1596,7 +1606,7 @@ std::variant> CLuaEngineDefs::EngineGetModelVi { return std::tuple(cHourOn, cHourOff); } - else // Model is incompatible, don't let confuse user. + else // Model is incompatible, don't let confuse user. { return std::tuple(0, 24); } @@ -2158,9 +2168,12 @@ std::unordered_mapSetElasticity(fValue); }}, {ObjectGroupPhysicalProperties::Modifiable::BUOYANCY, [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetBuoyancy(fValue); }}, {ObjectGroupPhysicalProperties::Modifiable::UPROOTLIMIT, [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetUprootLimit(fValue); }}, - {ObjectGroupPhysicalProperties::Modifiable::COLDAMAGEMULTIPLIER, [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetCollisionDamageMultiplier(fValue); }}, - {ObjectGroupPhysicalProperties::Modifiable::SMASHMULTIPLIER, [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetSmashMultiplier(fValue); }}, - {ObjectGroupPhysicalProperties::Modifiable::BREAKVELOCITYRAND, [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetBreakVelocityRandomness(fValue); }}, + {ObjectGroupPhysicalProperties::Modifiable::COLDAMAGEMULTIPLIER, + [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetCollisionDamageMultiplier(fValue); }}, + {ObjectGroupPhysicalProperties::Modifiable::SMASHMULTIPLIER, + [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetSmashMultiplier(fValue); }}, + {ObjectGroupPhysicalProperties::Modifiable::BREAKVELOCITYRAND, + [](CObjectGroupPhysicalProperties* pGroup, float fValue) { pGroup->SetBreakVelocityRandomness(fValue); }}, }; std::unordered_map> g_GroupPropertiesSettersBool{ {ObjectGroupPhysicalProperties::Modifiable::CAMERAAVOID, [](CObjectGroupPhysicalProperties* pGroup, bool bValue) { pGroup->SetCameraAvoidObject(bValue); }}, @@ -2169,13 +2182,14 @@ std::unordered_map> g_GroupPropertiesSettersVector{ {ObjectGroupPhysicalProperties::Modifiable::FXOFFSET, [](CObjectGroupPhysicalProperties* pGroup, CVector vecValue) { pGroup->SetFxOffset(vecValue); }}, - {ObjectGroupPhysicalProperties::Modifiable::BREAKVELOCITY, [](CObjectGroupPhysicalProperties* pGroup, CVector vecValue) { pGroup->SetBreakVelocity(vecValue); }}, + {ObjectGroupPhysicalProperties::Modifiable::BREAKVELOCITY, + [](CObjectGroupPhysicalProperties* pGroup, CVector vecValue) { pGroup->SetBreakVelocity(vecValue); }}, }; int CLuaEngineDefs::EngineSetObjectGroupPhysicalProperty(lua_State* luaVM) { // bool engineSetObjectGroupPhysicalProperty ( int groupID, string property, ...) - int iGivenGroup; + int iGivenGroup; ObjectGroupPhysicalProperties::Modifiable eProperty; CScriptArgReader argStream(luaVM); @@ -2342,7 +2356,8 @@ std::unordered_mapGetElasticity(); }}, {ObjectGroupPhysicalProperties::Modifiable::BUOYANCY, [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetBuoyancy(); }}, {ObjectGroupPhysicalProperties::Modifiable::UPROOTLIMIT, [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetUprootLimit(); }}, - {ObjectGroupPhysicalProperties::Modifiable::COLDAMAGEMULTIPLIER, [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetCollisionDamageMultiplier(); }}, + {ObjectGroupPhysicalProperties::Modifiable::COLDAMAGEMULTIPLIER, + [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetCollisionDamageMultiplier(); }}, {ObjectGroupPhysicalProperties::Modifiable::SMASHMULTIPLIER, [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetSmashMultiplier(); }}, {ObjectGroupPhysicalProperties::Modifiable::BREAKVELOCITYRAND, [](CObjectGroupPhysicalProperties* pGroup) { return pGroup->GetBreakVelocityRandomness(); }}, }; @@ -2358,7 +2373,7 @@ std::unordered_map CLuaEngineDefs::EngineRequestTXD(lua_State* const luaVM if (iModelID == INVALID_MODEL_ID) return false; - auto modelManager = m_pManager->GetModelManager(); + auto modelManager = m_pManager->GetModelManager(); std::shared_ptr pModel = modelManager->Request(m_pManager, iModelID, eClientModelType::TXD); if (!pModel) @@ -2593,7 +2608,7 @@ std::variant CLuaEngineDefs::EngineRequestTXD(lua_State* const luaVM bool CLuaEngineDefs::EngineFreeTXD(uint txdID) { - auto modelManager = m_pManager->GetModelManager(); + auto modelManager = m_pManager->GetModelManager(); std::shared_ptr pModel = modelManager->FindModelByID(MAX_MODEL_DFF_ID + txdID); // Use the manager removal path so RestoreTXD runs and the TXD slot is actually freed. diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.h index 3b7512a5949..7f0f1d23ca2 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaEngineDefs.h @@ -89,7 +89,7 @@ class CLuaEngineDefs : public CLuaDefs static bool EngineSetPoolCapacity(lua_State* luaVM, ePools pool, size_t newSize); static std::variant EngineRequestTXD(lua_State* const luaVM, std::string strTxdName); - static bool EngineFreeTXD(uint txdID); + static bool EngineFreeTXD(uint txdID); static bool EngineStreamingRequestModel(lua_State* const luaVM, std::uint16_t modelId, std::optional addReference, std::optional blocking); static bool EngineStreamingReleaseModel(lua_State* const luaVM, std::uint16_t modelId, std::optional removeReference); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaGUIDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaGUIDefs.cpp index 6a564c5a778..5471c8e6089 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaGUIDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaGUIDefs.cpp @@ -2424,7 +2424,7 @@ int CLuaGUIDefs::GUIGridListInsertRowAfter(lua_State* luaVM) else { // Vector containing our string arguments. We add a bool to store whether it was originally a number. - std::vector > m_items; + std::vector> m_items; for (CLuaArgument* pArgument : Arguments) { SString strItemText; @@ -2569,7 +2569,7 @@ int CLuaGUIDefs::GUIGridListGetSelectedItem(lua_State* luaVM) int iRow = static_cast(guiGridlist->GetCGUIElement())->GetSelectedItemRow(); int iColumn = static_cast(guiGridlist->GetCGUIElement())->GetSelectedItemColumn(); lua_pushnumber(luaVM, iRow); - lua_pushnumber(luaVM, iColumn + 1); // columns start at 1 + lua_pushnumber(luaVM, iColumn + 1); // columns start at 1 return 2; } else diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp index 811ea6f12c0..70ece841563 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp @@ -182,8 +182,9 @@ int CLuaMarkerDefs::GetMarkerColor(lua_State* luaVM) lua_pushnumber(luaVM, static_cast(color.G)); lua_pushnumber(luaVM, static_cast(color.B)); - if (!pMarker->AreAlphaLimitsIgnored() && (pMarker->GetMarkerType() == CClientMarker::MARKER_CHECKPOINT || pMarker->GetMarkerType() == CClientMarker::MARKER_ARROW)) - lua_pushnumber(luaVM, 255); // fake alpha + if (!pMarker->AreAlphaLimitsIgnored() && + (pMarker->GetMarkerType() == CClientMarker::MARKER_CHECKPOINT || pMarker->GetMarkerType() == CClientMarker::MARKER_ARROW)) + lua_pushnumber(luaVM, 255); // fake alpha else lua_pushnumber(luaVM, static_cast(color.A)); @@ -427,7 +428,8 @@ bool CLuaMarkerDefs::IsCoronaReflectionEnabled(CClientMarker* pMarker) return pCorona->IsReflectionEnabled(); } -bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CClientMarker* marker, std::optional r, std::optional g, std::optional b, std::optional a, std::optional size) +bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CClientMarker* marker, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional size) { SColor color; color.R = r.value_or(255); @@ -438,7 +440,8 @@ bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CClientMarker* marker, std:: return CStaticFunctionDefinitions::SetMarkerTargetArrowProperties(*marker, color, size.value_or(marker->GetSize() * 0.625f)); } -std::variant, bool> CLuaMarkerDefs::GetMarkerTargetArrowProperties(CClientMarker* marker) noexcept +std::variant, bool> CLuaMarkerDefs::GetMarkerTargetArrowProperties( + CClientMarker* marker) noexcept { CClientCheckpoint* checkpoint = marker->GetCheckpoint(); if (!checkpoint) diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h index d32aadfb03d..b48dedeea7a 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h @@ -37,6 +37,8 @@ class CLuaMarkerDefs : public CLuaDefs static bool SetCoronaReflectionEnabled(CClientMarker* pMarker, bool bEnabled); static bool IsCoronaReflectionEnabled(CClientMarker* pMarker); - static bool SetMarkerTargetArrowProperties(CClientMarker* marker, std::optional r, std::optional g, std::optional b, std::optional a, std::optional size); - static std::variant, bool> GetMarkerTargetArrowProperties(CClientMarker* marker) noexcept; + static bool SetMarkerTargetArrowProperties(CClientMarker* marker, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional size); + static std::variant, bool> GetMarkerTargetArrowProperties( + CClientMarker* marker) noexcept; }; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaObjectDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaObjectDefs.cpp index 35e05386335..714d2a9eec2 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaObjectDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaObjectDefs.cpp @@ -252,7 +252,7 @@ int CLuaObjectDefs::GetObjectProperties(lua_State* luaVM) int CLuaObjectDefs::GetObjectProperty(lua_State* luaVM) { // float, float, float getObjectProperty ( object theObject, string property ) - CClientObject* pObject; + CClientObject* pObject; ObjectProperty eProp; CScriptArgReader argStream(luaVM); @@ -610,7 +610,7 @@ int CLuaObjectDefs::SetObjectMass(lua_State* luaVM) int CLuaObjectDefs::SetObjectProperty(lua_State* luaVM) { // bool setObjectProperty ( object theObject, string property, ... ) - CClientEntity* pEntity; + CClientEntity* pEntity; ObjectProperty eProp; CScriptArgReader argStream(luaVM); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp index c7f52ff0e4f..450214d624f 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp @@ -18,7 +18,7 @@ #include "CLuaPedDefs.h" #define MIN_CLIENT_REQ_REMOVEPEDFROMVEHICLE_CLIENTSIDE "1.3.0-9.04482" -#define MIN_CLIENT_REQ_WARPPEDINTOVEHICLE_CLIENTSIDE "1.3.0-9.04482" +#define MIN_CLIENT_REQ_WARPPEDINTOVEHICLE_CLIENTSIDE "1.3.0-9.04482" void CLuaPedDefs::LoadFunctions() { @@ -75,7 +75,7 @@ void CLuaPedDefs::LoadFunctions() {"getPedAnimation", GetPedAnimation}, {"getPedAnimationProgress", ArgumentParser}, {"getPedAnimationSpeed", ArgumentParser}, - {"getPedAnimationLength", ArgumentParser}, + {"getPedAnimationLength", ArgumentParser}, {"getPedWalkingStyle", GetPedMoveAnim}, {"getPedControlState", ArgumentParserWarn}, {"getPedAnalogControlState", GetPedAnalogControlState}, @@ -141,7 +141,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "canBeKnockedOffBike", "canPedBeKnockedOffBike"); lua_classfunction(luaVM, "doesHaveJetPack", "doesPedHaveJetPack"); - lua_classfunction(luaVM, "isWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 + lua_classfunction(luaVM, "isWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 lua_classfunction(luaVM, "getAmmoInClip", "getPedAmmoInClip"); lua_classfunction(luaVM, "getAnalogControlState", "getPedAnalogControlState"); lua_classfunction(luaVM, "getAnimation", "getPedAnimation"); @@ -218,7 +218,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classvariable(luaVM, "vehicleSeat", NULL, "getPedOccupiedVehicleSeat"); lua_classvariable(luaVM, "canBeKnockedOffBike", "setPedCanBeKnockedOffBike", "canPedBeKnockedOffBike"); lua_classvariable(luaVM, "hasJetPack", NULL, "doesPedHaveJetPack"); - lua_classvariable(luaVM, "jetpack", NULL, "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 + lua_classvariable(luaVM, "jetpack", NULL, "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 lua_classvariable(luaVM, "armor", "setPedArmor", "getPedArmor"); lua_classvariable(luaVM, "fightingStyle", "setPedFightingStyle", "getPedFightingStyle"); lua_classvariable(luaVM, "cameraRotation", "setPedCameraRotation", "getPedCameraRotation"); @@ -1003,7 +1003,7 @@ std::variant> CLuaPedDefs::GetElement throw std::invalid_argument("Invalid bone: " + std::to_string(bone)); CEntity* entity = ped->GetGameEntity(); - CVector position; + CVector position; if (!entity || !entity->GetBonePosition(static_cast(bone), position)) return false; @@ -1020,7 +1020,7 @@ std::variant> CLuaPedDefs::GetElement float yaw = 0.0f; float pitch = 0.0f; float roll = 0.0f; - + if (!entity || !entity->GetBoneRotation(static_cast(bone), yaw, pitch, roll)) return false; @@ -1134,7 +1134,7 @@ bool CLuaPedDefs::UpdateElementRpHAnim(CClientPed* ped) if (clump) { - ((void(__cdecl*)(RpClump*))0x5DF560)(clump); // CPed::ShoulderBoneRotation + ((void(__cdecl*)(RpClump*))0x5DF560)(clump); // CPed::ShoulderBoneRotation } return true; @@ -1262,7 +1262,7 @@ bool CLuaPedDefs::IsPedReloadingWeapon(CClientPed* const ped) noexcept { return ped->IsReloadingWeapon(); } - + int CLuaPedDefs::GetPedClothes(lua_State* luaVM) { // Verify the argument @@ -1313,7 +1313,7 @@ bool CLuaPedDefs::GetPedControlState(std::variant firs } bool state; - + if (!CStaticFunctionDefinitions::GetPedControlState(*ped, control, state)) return false; @@ -2242,9 +2242,9 @@ int CLuaPedDefs::SetPedAnimation(lua_State* luaVM) CScriptArgReader argStream(luaVM); argStream.ReadUserData(pEntity); if (argStream.NextIsBool()) - argStream.ReadBool(bDummy); // Wiki used setPedAnimation(source,false) as an example + argStream.ReadBool(bDummy); // Wiki used setPedAnimation(source,false) as an example else if (argStream.NextIsNil()) - argStream.m_iIndex++; // Wiki docs said blockName could be nil + argStream.m_iIndex++; // Wiki docs said blockName could be nil else argStream.ReadString(strBlockName, ""); argStream.ReadString(strAnimName, ""); @@ -2518,10 +2518,11 @@ int CLuaPedDefs::DetonateSatchels(lua_State* luaVM) return 1; } -bool CLuaPedDefs::SetPedEnterVehicle(CClientPed* pPed, std::optional pOptVehicle, std::optional> seatOrPassenger) +bool CLuaPedDefs::SetPedEnterVehicle(CClientPed* pPed, std::optional pOptVehicle, + std::optional> seatOrPassenger) { - CClientVehicle* pVehicle = pOptVehicle.value_or(nullptr); - bool bPassenger = false; + CClientVehicle* pVehicle = pOptVehicle.value_or(nullptr); + bool bPassenger = false; std::optional optSeat; // Parse third argument: either a bool (passenger flag) or int (seat number) @@ -2547,7 +2548,7 @@ bool CLuaPedDefs::SetPedExitVehicle(CClientPed* pPed) return pPed->ExitVehicle(); } -bool CLuaPedDefs::killPedTask(CClientPed* ped, taskType taskType, std::uint8_t taskNumber, std::optional gracefully) +bool CLuaPedDefs::killPedTask(CClientPed* ped, taskType taskType, std::uint8_t taskNumber, std::optional gracefully) { switch (taskType) { @@ -2559,7 +2560,7 @@ bool CLuaPedDefs::killPedTask(CClientPed* ped, taskType taskType, std::uint8_t t if (taskNumber >= TASK_PRIORITY_MAX) throw LuaFunctionError("Invalid task slot number"); - return ped->KillTask(taskNumber, gracefully.value_or(true)); + return ped->KillTask(taskNumber, gracefully.value_or(true)); } case taskType::SECONDARY_TASK: { @@ -2569,7 +2570,7 @@ bool CLuaPedDefs::killPedTask(CClientPed* ped, taskType taskType, std::uint8_t t return ped->KillTaskSecondary(taskNumber, gracefully.value_or(true)); } default: - return false; + return false; } } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.h index f418fbe512b..8f9e386bf8d 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPedDefs.h @@ -51,8 +51,8 @@ class CLuaPedDefs : public CLuaDefs LUA_DECLARE(GetPedRotation); LUA_DECLARE(CanPedBeKnockedOffBike); - static std::variant> GetElementBonePosition(CClientPed* ped, const std::uint16_t bone); - static std::variant> GetElementBoneRotation(CClientPed* ped, const std::uint16_t bone); + static std::variant> GetElementBonePosition(CClientPed* ped, const std::uint16_t bone); + static std::variant> GetElementBoneRotation(CClientPed* ped, const std::uint16_t bone); static std::variant> GetElementBoneQuaternion(CClientPed* ped, const std::uint16_t bone); static std::variant, 4>> GetElementBoneMatrix(CClientPed* ped, const std::uint16_t bone); @@ -96,8 +96,7 @@ class CLuaPedDefs : public CLuaDefs static bool IsPedReloadingWeapon(CClientPed* const ped) noexcept; LUA_DECLARE(AddPedClothes); LUA_DECLARE(RemovePedClothes); - static bool SetPedControlState(std::variant first, std::variant second, - std::optional maybeState); + static bool SetPedControlState(std::variant first, std::variant second, std::optional maybeState); LUA_DECLARE(SetPedAnalogControlState); LUA_DECLARE(SetPedDoingGangDriveby); static bool SetPedFightingStyle(CClientEntity* const entity, const unsigned int style); @@ -112,11 +111,12 @@ class CLuaPedDefs : public CLuaDefs LUA_DECLARE(RemovePedFromVehicle); LUA_DECLARE(SetPedOxygenLevel); LUA_DECLARE(SetPedStat); - static bool SetPedEnterVehicle(CClientPed* pPed, std::optional pOptVehicle, std::optional> seatOrPassenger); + static bool SetPedEnterVehicle(CClientPed* pPed, std::optional pOptVehicle, + std::optional> seatOrPassenger); static bool SetPedExitVehicle(CClientPed* pPed); static bool IsPedBleeding(CClientPed* ped); static bool SetPedBleeding(CClientPed* ped, bool bleeding); - + static bool killPedTask(CClientPed* ped, taskType taskType, std::uint8_t taskNumber, std::optional gracefully); static void PlayPedVoiceLine(CClientPed* ped, int speechId, std::optional probability); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp index b4813e21a70..e6f8a8d9e57 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp @@ -492,8 +492,8 @@ int CLuaPlayerDefs::SetPlayerNametagColor(lua_State* luaVM) if (!argStream.HasErrors()) { - if (CStaticFunctionDefinitions::SetPlayerNametagColor(*pPlayer, false, static_cast(iR), - static_cast(iG), static_cast(iB))) + if (CStaticFunctionDefinitions::SetPlayerNametagColor(*pPlayer, false, static_cast(iR), static_cast(iG), + static_cast(iB))) { lua_pushboolean(luaVM, true); return 1; @@ -652,10 +652,11 @@ bool CLuaPlayerDefs::IsPlayerCrosshairVisible() return g_pGame->GetHud()->IsCrosshairVisible(); } -bool CLuaPlayerDefs::SetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property, std::variant value) +bool CLuaPlayerDefs::SetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property, + std::variant value) { - if (component == HUD_ALL || component == HUD_CROSSHAIR || component == HUD_VITAL_STATS || component == HUD_HELP_TEXT || component == HUD_RADAR - || component == HUD_RADAR_MAP || component == HUD_RADAR_BLIPS || component == HUD_RADAR_ALTIMETER) + if (component == HUD_ALL || component == HUD_CROSSHAIR || component == HUD_VITAL_STATS || component == HUD_HELP_TEXT || component == HUD_RADAR || + component == HUD_RADAR_MAP || component == HUD_RADAR_BLIPS || component == HUD_RADAR_ALTIMETER) return false; CHud* hud = g_pGame->GetHud(); @@ -939,9 +940,10 @@ bool CLuaPlayerDefs::ResetPlayerHudComponentProperty(eHudComponent component, eH } return false; -} +} -std::variant, CLuaMultiReturn> CLuaPlayerDefs::GetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property) +std::variant, CLuaMultiReturn> +CLuaPlayerDefs::GetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property) { if (component == HUD_ALL || component == HUD_CROSSHAIR || component == HUD_VITAL_STATS || component == HUD_HELP_TEXT || component == HUD_RADAR) return false; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h index 1bc08998a47..a051291bf28 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h @@ -31,7 +31,8 @@ class CLuaPlayerDefs : public CLuaDefs LUA_DECLARE(GetPlayerWantedLevel); static std::uint8_t GetPlayerScriptDebugLevel() noexcept; static bool IsPlayerCrosshairVisible(); - static std::variant, CLuaMultiReturn> GetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property); + static std::variant, CLuaMultiReturn> + GetPlayerHudComponentProperty(eHudComponent component, eHudComponentProperty property); // Player set LUA_DECLARE(ShowPlayerHudComponent); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPointLightDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaPointLightDefs.h index 6d0811d0d68..066d0f58a8a 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPointLightDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPointLightDefs.h @@ -26,4 +26,4 @@ class CLuaPointLightDefs : public CLuaDefs LUA_DECLARE(SetLightRadius); LUA_DECLARE(SetLightColor); LUA_DECLARE(SetLightDirection); -}; \ No newline at end of file +}; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.cpp index 98499d9a78e..3dc6728b9c0 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.cpp @@ -47,8 +47,8 @@ float CLuaPostfxDefs::GetPostFXValue(PostFXType type) int CLuaPostfxDefs::GetPostFXMode() { return g_pCore->GetCVars()->GetValue("borderless_apply_fullscreen", false) ? 1 - : g_pCore->GetCVars()->GetValue("borderless_apply_windowed", false) ? 2 - : 0; + : g_pCore->GetCVars()->GetValue("borderless_apply_windowed", false) ? 2 + : 0; } bool CLuaPostfxDefs::IsPostFXEnabled(PostFXType type) diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.h index 3a206c785a5..832e0f60401 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaPostfxDefs.h @@ -18,6 +18,6 @@ class CLuaPostfxDefs : public CLuaDefs private: static float GetPostFXValue(PostFXType type); - static int GetPostFXMode(); - static bool IsPostFXEnabled(PostFXType type); + static int GetPostFXMode(); + static bool IsPostFXEnabled(PostFXType type); }; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp index 265c6383b1f..cfea233f591 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp @@ -89,7 +89,7 @@ int CLuaResourceDefs::Call(lua_State* luaVM) args.ReadArguments(luaVM, 3); CLuaArguments returns; - LUA_CHECKSTACK(targetLuaVM, 1); // Ensure some room + LUA_CHECKSTACK(targetLuaVM, 1); // Ensure some room // Lets grab the original hidden variables so we can restore them later lua_getglobal(targetLuaVM, "sourceResource"); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp index 28944179b9d..7e8450a681f 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp @@ -13,13 +13,9 @@ void CLuaTeamDefs::LoadFunctions() { constexpr static const std::pair functions[]{ - {"getTeamFromName", ArgumentParserWarn}, - {"getTeamName", ArgumentParserWarn}, - {"getTeamColor", ArgumentParserWarn}, - {"getTeamFriendlyFire", ArgumentParserWarn}, - {"getPlayersInTeam", ArgumentParserWarn}, - {"countPlayersInTeam", ArgumentParserWarn} - }; + {"getTeamFromName", ArgumentParserWarn}, {"getTeamName", ArgumentParserWarn}, + {"getTeamColor", ArgumentParserWarn}, {"getTeamFriendlyFire", ArgumentParserWarn}, + {"getPlayersInTeam", ArgumentParserWarn}, {"countPlayersInTeam", ArgumentParserWarn}}; // Add functions for (const auto& [name, func] : functions) diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h index e3de95df131..46cdc9969ce 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h @@ -18,10 +18,10 @@ class CLuaTeamDefs : public CLuaDefs static void AddClass(lua_State* luaVM); private: - static std::variant GetTeamFromName(const std::string name) noexcept; - static std::string GetTeamName(CClientTeam* team); + static std::variant GetTeamFromName(const std::string name) noexcept; + static std::string GetTeamName(CClientTeam* team); static CLuaMultiReturn GetTeamColor(CClientTeam* team) noexcept; - static bool GetTeamFriendlyFire(CClientTeam* team) noexcept; - static std::vector GetPlayersInTeam(CClientTeam* team); - static std::uint32_t CountPlayersInTeam(CClientTeam* team) noexcept; + static bool GetTeamFriendlyFire(CClientTeam* team) noexcept; + static std::vector GetPlayersInTeam(CClientTeam* team); + static std::uint32_t CountPlayersInTeam(CClientTeam* team) noexcept; }; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp index 0d022164fa5..4de67d4c1a5 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp @@ -15,9 +15,14 @@ void CLuaTimerDefs::LoadFunctions() { constexpr static const std::pair functions[]{ - {"setTimer", SetTimer}, {"killTimer", KillTimer}, {"resetTimer", ResetTimer}, - {"setTimerPaused", ArgumentParser},{"isTimerPaused", ArgumentParser}, - {"getTimers", GetTimers}, {"isTimer", IsTimer}, {"getTimerDetails", GetTimerDetails}, + {"setTimer", SetTimer}, + {"killTimer", KillTimer}, + {"resetTimer", ResetTimer}, + {"setTimerPaused", ArgumentParser}, + {"isTimerPaused", ArgumentParser}, + {"getTimers", GetTimers}, + {"isTimer", IsTimer}, + {"getTimerDetails", GetTimerDetails}, }; // Add functions diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp index 83fd33065ad..6d20f56bc59 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp @@ -407,7 +407,7 @@ int CLuaVehicleDefs::GetVehicleType(lua_State* luaVM) if (!argStream.HasErrors()) { - lua_pushstring(luaVM, CVehicleNames::GetVehicleTypeName(ucModel)); // Range check will be done by GetVehicleTypeName + lua_pushstring(luaVM, CVehicleNames::GetVehicleTypeName(ucModel)); // Range check will be done by GetVehicleTypeName return 1; } else @@ -2577,8 +2577,8 @@ int CLuaVehicleDefs::SetVehicleHandling(lua_State* luaVM) } break; } - case HandlingProperty::HANDLING_PERCENTSUBMERGED: // unsigned int - // case HANDLING_MONETARY: + case HandlingProperty::HANDLING_PERCENTSUBMERGED: // unsigned int + // case HANDLING_MONETARY: case HandlingProperty::HANDLING_HANDLINGFLAGS: case HandlingProperty::HANDLING_MODELFLAGS: { @@ -2699,7 +2699,7 @@ int CLuaVehicleDefs::GetVehicleHandling(lua_State* luaVM) SString strProperty; argStream.ReadString(strProperty); - bool bResult = true; + bool bResult = true; HandlingProperty eProperty = g_pGame->GetHandlingManager()->GetPropertyEnumFromName(strProperty); if (eProperty != HandlingProperty::HANDLING_MAX) { @@ -2795,7 +2795,7 @@ int CLuaVehicleDefs::GetVehicleHandling(lua_State* luaVM) lua_pushstring(luaVM, "rwd"); else if (eDriveType == CHandlingEntry::FOURWHEEL) lua_pushstring(luaVM, "awd"); - else // What the ... (yeah, security) + else // What the ... (yeah, security) lua_pushnil(luaVM); lua_setfield(luaVM, -2, "driveType"); CHandlingEntry::eEngineType eEngineType = entry->GetCarEngineType(); @@ -2951,7 +2951,7 @@ int CLuaVehicleDefs::GetOriginalHandling(lua_State* luaVM) lua_pushstring(luaVM, "rwd"); else if (eDriveType == CHandlingEntry::FOURWHEEL) lua_pushstring(luaVM, "awd"); - else // What the ... (yeah, security) + else // What the ... (yeah, security) lua_pushnil(luaVM); lua_setfield(luaVM, -2, "driveType"); CHandlingEntry::eEngineType eEngineType = entry->GetCarEngineType(); @@ -3083,37 +3083,37 @@ int CLuaVehicleDefs::GetVehicleSirenParams(lua_State* luaVM) argStream.ReadUserData(pVehicle); if (!argStream.HasErrors()) { - tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Grab the siren structure data + tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Grab the siren structure data lua_newtable(luaVM); lua_pushstring(luaVM, "SirenCount"); lua_pushnumber(luaVM, tSirenInfo.m_ucSirenCount); - lua_settable(luaVM, -3); // End of SirenCount Property + lua_settable(luaVM, -3); // End of SirenCount Property lua_pushstring(luaVM, "SirenType"); lua_pushnumber(luaVM, tSirenInfo.m_ucSirenType); - lua_settable(luaVM, -3); // End of SirenType Property + lua_settable(luaVM, -3); // End of SirenType Property lua_pushstring(luaVM, "Flags"); lua_newtable(luaVM); lua_pushstring(luaVM, "360"); lua_pushboolean(luaVM, tSirenInfo.m_b360Flag); - lua_settable(luaVM, -3); // End of 360 Property + lua_settable(luaVM, -3); // End of 360 Property lua_pushstring(luaVM, "DoLOSCheck"); lua_pushboolean(luaVM, tSirenInfo.m_bDoLOSCheck); - lua_settable(luaVM, -3); // End of DoLOSCheck Property + lua_settable(luaVM, -3); // End of DoLOSCheck Property lua_pushstring(luaVM, "UseRandomiser"); lua_pushboolean(luaVM, tSirenInfo.m_bUseRandomiser); - lua_settable(luaVM, -3); // End of UseRandomiser Property + lua_settable(luaVM, -3); // End of UseRandomiser Property lua_pushstring(luaVM, "Silent"); lua_pushboolean(luaVM, tSirenInfo.m_bSirenSilent); - lua_settable(luaVM, -3); // End of Silent Property + lua_settable(luaVM, -3); // End of Silent Property - lua_settable(luaVM, -3); // End of table + lua_settable(luaVM, -3); // End of table return 1; } @@ -3134,7 +3134,7 @@ int CLuaVehicleDefs::GetVehicleSirens(lua_State* luaVM) argStream.ReadUserData(pVehicle); if (!argStream.HasErrors()) { - tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Grab the siren structure data + tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Grab the siren structure data lua_newtable(luaVM); for (int i = 0; i < tSirenInfo.m_ucSirenCount; i++) @@ -3144,37 +3144,37 @@ int CLuaVehicleDefs::GetVehicleSirens(lua_State* luaVM) lua_pushstring(luaVM, "Min_Alpha"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_dwMinSirenAlpha); - lua_settable(luaVM, -3); // End of Min_Alpha property + lua_settable(luaVM, -3); // End of Min_Alpha property lua_pushstring(luaVM, "Red"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_RGBBeaconColour.R); - lua_settable(luaVM, -3); // End of Red property + lua_settable(luaVM, -3); // End of Red property lua_pushstring(luaVM, "Green"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_RGBBeaconColour.G); - lua_settable(luaVM, -3); // End of Green property + lua_settable(luaVM, -3); // End of Green property lua_pushstring(luaVM, "Blue"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_RGBBeaconColour.B); - lua_settable(luaVM, -3); // End of Blue property + lua_settable(luaVM, -3); // End of Blue property lua_pushstring(luaVM, "Alpha"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_RGBBeaconColour.A); - lua_settable(luaVM, -3); // End of Alpha property + lua_settable(luaVM, -3); // End of Alpha property lua_pushstring(luaVM, "x"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_vecSirenPositions.fX); - lua_settable(luaVM, -3); // End of X property + lua_settable(luaVM, -3); // End of X property lua_pushstring(luaVM, "y"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_vecSirenPositions.fY); - lua_settable(luaVM, -3); // End of Y property + lua_settable(luaVM, -3); // End of Y property lua_pushstring(luaVM, "z"); lua_pushnumber(luaVM, tSirenInfo.m_tSirenInfo[i].m_vecSirenPositions.fZ); - lua_settable(luaVM, -3); // End of Z property + lua_settable(luaVM, -3); // End of Z property - lua_settable(luaVM, -3); // End of Table + lua_settable(luaVM, -3); // End of Table } return 1; @@ -3671,7 +3671,7 @@ int CLuaVehicleDefs::GetVehicleComponents(lua_State* luaVM) { lua_pushstring(luaVM, (*iter).first); lua_pushboolean(luaVM, (*iter).second.m_bVisible); - lua_settable(luaVM, -3); // End of Table + lua_settable(luaVM, -3); // End of Table } return 1; } @@ -3985,9 +3985,9 @@ int CLuaVehicleDefs::IsVehicleWindowOpen(lua_State* luaVM) int CLuaVehicleDefs::SetVehicleModelDummyPosition(lua_State* luaVM) { // bool setVehicleModelDummyPosition ( int modelID, vehicle-dummy dummy, float x, float y, float z ) - unsigned short usModel; + unsigned short usModel; VehicleDummies eDummy; - CVector vecPosition; + CVector vecPosition; CScriptArgReader argStream(luaVM); argStream.ReadNumber(usModel); @@ -4012,7 +4012,7 @@ int CLuaVehicleDefs::SetVehicleModelDummyPosition(lua_State* luaVM) int CLuaVehicleDefs::GetVehicleModelDummyPosition(lua_State* luaVM) { // float, float, float getVehicleModelDummyPosition ( int modelID, vehicle-dummy dummy ) - unsigned short usModel; + unsigned short usModel; VehicleDummies eDummy; CScriptArgReader argStream(luaVM); @@ -4041,7 +4041,7 @@ int CLuaVehicleDefs::GetVehicleModelDummyPosition(lua_State* luaVM) int CLuaVehicleDefs::OOP_GetVehicleModelDummyPosition(lua_State* luaVM) { // float, float, float getVehicleModelDummyPosition ( int modelID, vehicle-dummy dummy ) - unsigned short usModel; + unsigned short usModel; VehicleDummies eDummy; CScriptArgReader argStream(luaVM); @@ -4222,8 +4222,7 @@ int CLuaVehicleDefs::GetVehicleWheelFrictionState(CClientVehicle* pVehicle, unsi return pVehicle->GetWheelFrictionState(wheel); } -std::variant> CLuaVehicleDefs::GetVehicleModelDummyDefaultPosition(unsigned short vehicleModel, - VehicleDummies dummy) +std::variant> CLuaVehicleDefs::GetVehicleModelDummyDefaultPosition(unsigned short vehicleModel, VehicleDummies dummy) { CVector position; @@ -4440,7 +4439,7 @@ bool CLuaVehicleDefs::SetVehicleModelAudioSetting(const uint32_t uiModel, const { if (!CClientVehicleManager::IsStandardModel(uiModel)) throw std::invalid_argument("Cannot change audio setting for allocated vechiles"); - + CVehicleAudioSettingsEntry& pModelSettings = g_pGame->GetVehicleAudioSettingsManager()->GetVehicleModelAudioSettingsData(uiModel); switch (eProperty) @@ -4546,8 +4545,8 @@ bool CLuaVehicleDefs::ResetVehicleModelAudioSettings(const uint32_t uiModel) if (!CClientVehicleManager::IsStandardModel(uiModel)) throw std::invalid_argument("Cannot change audio setting for allocated vechiles"); - g_pGame->GetVehicleAudioSettingsManager()->ResetModelSettings(uiModel); - return true; + g_pGame->GetVehicleAudioSettingsManager()->ResetModelSettings(uiModel); + return true; } bool CLuaVehicleDefs::SetVehicleAudioSetting(CClientVehicle* pVehicle, const VehicleAudioSettingProperty eProperty, float varValue) @@ -4709,4 +4708,3 @@ std::unordered_map CLuaVehicleDefs::GetVehicleAudioSettings( return output; } - diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h index d2139619184..945efed4c47 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h @@ -154,8 +154,8 @@ class CLuaVehicleDefs : public CLuaDefs static std::variant OOP_GetVehicleDummyPosition(CClientVehicle* vehicle, VehicleDummies dummy); static bool ResetVehicleDummyPositions(CClientVehicle* vehicle); - static std::variant, 4>> GetVehicleEntryPoints(CClientVehicle* vehicle); - static std::variant> OOP_GetVehicleEntryPoints(CClientVehicle* vehicle); + static std::variant, 4>> GetVehicleEntryPoints(CClientVehicle* vehicle); + static std::variant> OOP_GetVehicleEntryPoints(CClientVehicle* vehicle); LUA_DECLARE(SetVehicleModelExhaustFumesPosition); LUA_DECLARE_OOP(GetVehicleModelExhaustFumesPosition); @@ -163,7 +163,7 @@ class CLuaVehicleDefs : public CLuaDefs static bool SetVehicleVariant(CClientVehicle* pVehicle, std::optional optVariant1, std::optional optVariant2); static float GetVehicleWheelScale(CClientVehicle* const pVehicle); static bool SetVehicleWheelScale(CClientVehicle* const pVehicle, const float fWheelScale); - static std::variant> GetVehicleModelWheelSize(const unsigned short usModel, + static std::variant> GetVehicleModelWheelSize(const unsigned short usModel, const std::optional eWheelGroup); static bool SetVehicleModelWheelSize(const unsigned short usModel, const ResizableVehicleWheelGroup eWheelGroup, const float fWheelSize); static int GetVehicleWheelFrictionState(CClientVehicle* pVehicle, unsigned char wheel); @@ -171,9 +171,10 @@ class CLuaVehicleDefs : public CLuaDefs static bool SetVehicleRotorState(CClientVehicle* const vehicle, bool state, std::optional stopRotor) noexcept; static bool GetVehicleRotorState(CClientVehicle* const vehicle) noexcept; - static bool AddVehicleSirens(CClientVehicle* vehicle, std::uint8_t sirenType, std::uint8_t sirenCount, std::optional enable360, std::optional enableLOSCheck, std::optional enableRandomiser, std::optional enableSilent) noexcept; + static bool AddVehicleSirens(CClientVehicle* vehicle, std::uint8_t sirenType, std::uint8_t sirenCount, std::optional enable360, + std::optional enableLOSCheck, std::optional enableRandomiser, std::optional enableSilent) noexcept; static bool RemoveVehicleSirens(CClientVehicle* vehicle) noexcept; - + static bool SetVehicleModelAudioSetting(const uint32_t uiModel, const VehicleAudioSettingProperty eProperty, float varValue); static bool ResetVehicleModelAudioSettings(const uint32_t uiModel); static bool SetVehicleAudioSetting(CClientVehicle* pVehicle, const VehicleAudioSettingProperty eProperty, float varValue); @@ -195,7 +196,8 @@ class CLuaVehicleDefs : public CLuaDefs LUA_DECLARE(GetVehicleComponentVisible); LUA_DECLARE(GetVehicleComponents); - static bool SpawnVehicleFlyingComponent(CClientVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, std::optional removalTime); + static bool SpawnVehicleFlyingComponent(CClientVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, + std::optional removalTime); static bool SetSmokeTrailEnabled(CClientVehicle* vehicle, bool state); static bool IsSmokeTrailEnabled(CClientVehicle* vehicle) noexcept; diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWaterDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaWaterDefs.cpp index f8a6890497d..e048f060b49 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWaterDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWaterDefs.cpp @@ -41,7 +41,7 @@ void CLuaWaterDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "create", "createWater"); lua_classfunction(luaVM, "testLineAgainst", "testLineAgainstWater"); - lua_classfunction(luaVM, "isDrawnLast", "isWaterDrawnLast"); // Drawn last property affects all water instances + lua_classfunction(luaVM, "isDrawnLast", "isWaterDrawnLast"); // Drawn last property affects all water instances lua_classfunction(luaVM, "setDrawnLast", "setWaterDrawnLast"); // Static variables (not implemented yet!) @@ -80,7 +80,7 @@ int CLuaWaterDefs::CreateWater(lua_State* luaVM) argStream.ReadVector3D(v1); argStream.ReadVector3D(v2); argStream.ReadVector3D(v3); - bool bIsQuad = argStream.NextCouldBeNumber(2); // Check for existence of v4.fZ + bool bIsQuad = argStream.NextCouldBeNumber(2); // Check for existence of v4.fZ if (bIsQuad) { argStream.ReadVector3D(v4); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.cpp index 39cb8eff19c..3384e50b4ad 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.cpp @@ -12,7 +12,7 @@ #include "StdInc.h" #include "game/CWeaponStatManager.h" -#define MIN_CLIENT_REQ_WEAPON_PROPERTY_FLAG "1.3.5-9.06139" +#define MIN_CLIENT_REQ_WEAPON_PROPERTY_FLAG "1.3.5-9.06139" void CLuaWeaponDefs::LoadFunctions() { @@ -41,8 +41,7 @@ void CLuaWeaponDefs::LoadFunctions() {"setWeaponAmmo", SetWeaponAmmo}, {"setWeaponClipAmmo", SetWeaponClipAmmo}, {"setWeaponRenderEnabled", ArgumentParser}, - {"isWeaponRenderEnabled", ArgumentParser} - }; + {"isWeaponRenderEnabled", ArgumentParser}}; // Add functions for (const auto& [name, func] : functions) @@ -209,7 +208,7 @@ int CLuaWeaponDefs::FireWeapon(lua_State* luaVM) int CLuaWeaponDefs::SetWeaponProperty(lua_State* luaVM) { CClientWeapon* pWeapon; - WeaponProperty weaponProperty; + WeaponProperty weaponProperty; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pWeapon); argStream.ReadEnumString(weaponProperty); @@ -694,7 +693,10 @@ int CLuaWeaponDefs::SetWeaponClipAmmo(lua_State* luaVM) return 1; } -std::variant> CLuaWeaponDefs::GetWeaponProperty(lua_State* luaVM, std::variant weapon, std::variant weaponSkill, WeaponProperty property) +std::variant> CLuaWeaponDefs::GetWeaponProperty(lua_State* luaVM, + std::variant weapon, + std::variant weaponSkill, + WeaponProperty property) { eWeaponSkill skill = WEAPONSKILL_POOR; if (std::holds_alternative(weaponSkill)) @@ -708,7 +710,7 @@ std::variant> CLuaWeaponDef // custom weapon if (std::holds_alternative(weapon)) { - auto* weaponPtr = std::get(weapon); + auto* weaponPtr = std::get(weapon); CWeaponStat* weaponStats = weaponPtr->GetWeaponStat(); if (!weaponPtr || !weaponStats) return false; @@ -840,7 +842,10 @@ std::variant> CLuaWeaponDef return false; } -std::variant> CLuaWeaponDefs::GetOriginalWeaponProperty(lua_State* luaVM, std::variant weapon, std::variant weaponSkill, WeaponProperty property) +std::variant> CLuaWeaponDefs::GetOriginalWeaponProperty(lua_State* luaVM, + std::variant weapon, + std::variant weaponSkill, + WeaponProperty property) { eWeaponType weaponType = eWeaponType::WEAPONTYPE_INVALID; if (std::holds_alternative(weapon)) diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.h index d61b1a88bbf..93338c895a2 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWeaponDefs.h @@ -25,8 +25,14 @@ class CLuaWeaponDefs : public CLuaDefs LUA_DECLARE(CreateWeapon); LUA_DECLARE(FireWeapon); LUA_DECLARE(SetWeaponProperty); - static std::variant> GetWeaponProperty(lua_State* luaVM, std::variant weapon, std::variant weaponSkill, WeaponProperty property); - static std::variant> GetOriginalWeaponProperty(lua_State* luaVM, std::variant weapon, std::variant weaponSkill, WeaponProperty property); + static std::variant> GetWeaponProperty(lua_State* luaVM, + std::variant weapon, + std::variant weaponSkill, + WeaponProperty property); + static std::variant> GetOriginalWeaponProperty(lua_State* luaVM, + std::variant weapon, + std::variant weaponSkill, + WeaponProperty property); LUA_DECLARE(SetWeaponState); LUA_DECLARE(GetWeaponState); LUA_DECLARE(SetWeaponTarget); diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp index a13aca8be32..f9c1e69bdcc 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp @@ -17,139 +17,139 @@ void CLuaWorldDefs::LoadFunctions() { - constexpr static const std::pair functions[]{// World get functions - {"getTime", GetTime}, - {"getColorFilter", ArgumentParser}, - {"getRoofPosition", GetRoofPosition}, - {"getGroundPosition", GetGroundPosition}, - {"processLineAgainstMesh", ArgumentParser}, - {"processLineOfSight", ProcessLineOfSight}, - {"getWorldFromScreenPosition", GetWorldFromScreenPosition}, - {"getScreenFromWorldPosition", GetScreenFromWorldPosition}, - {"getWeather", GetWeather}, - {"getZoneName", GetZoneName}, - {"getGravity", GetGravity}, - {"getGameSpeed", GetGameSpeed}, - {"getMinuteDuration", GetMinuteDuration}, - {"getWaveHeight", GetWaveHeight}, - {"getGaragePosition", GetGaragePosition}, - {"getGarageSize", GetGarageSize}, - {"getGarageBoundingBox", GetGarageBoundingBox}, - {"getBlurLevel", GetBlurLevel}, - {"getTrafficLightState", GetTrafficLightState}, - {"getSkyGradient", GetSkyGradient}, - {"getHeatHaze", GetHeatHaze}, - {"getJetpackMaxHeight", GetJetpackMaxHeight}, - {"getWindVelocity", GetWindVelocity}, - {"getInteriorSoundsEnabled", GetInteriorSoundsEnabled}, - {"getInteriorFurnitureEnabled", GetInteriorFurnitureEnabled}, - {"getFarClipDistance", GetFarClipDistance}, - {"getNearClipDistance", GetNearClipDistance}, - {"getVehiclesLODDistance", GetVehiclesLODDistance}, - {"getPedsLODDistance", GetPedsLODDistance}, - {"getFogDistance", GetFogDistance}, - {"getSunColor", GetSunColor}, - {"getSunSize", GetSunSize}, - {"getAircraftMaxHeight", GetAircraftMaxHeight}, - {"getAircraftMaxVelocity", GetAircraftMaxVelocity}, - {"getOcclusionsEnabled", GetOcclusionsEnabled}, - {"getCloudsEnabled", GetCloudsEnabled}, - {"getRainLevel", GetRainLevel}, - {"getMoonSize", GetMoonSize}, - {"getFPSLimit", GetFPSLimit}, - {"getBirdsEnabled", GetBirdsEnabled}, - {"getCoronaReflectionsEnabled", ArgumentParser}, - {"getWorldProperty", ArgumentParser}, - - // World set funcs - {"setTime", SetTime}, - {"setColorFilter", ArgumentParser}, - {"setGrainMultiplier", ArgumentParser}, - {"setGrainLevel", ArgumentParser}, - {"setSkyGradient", SetSkyGradient}, - {"setHeatHaze", SetHeatHaze}, - {"setWeather", SetWeather}, - {"setWeatherBlended", SetWeatherBlended}, - {"setGravity", SetGravity}, - {"setGameSpeed", SetGameSpeed}, - {"setWaveHeight", SetWaveHeight}, - {"setMinuteDuration", SetMinuteDuration}, - {"setGarageOpen", SetGarageOpen}, - {"setWorldSpecialPropertyEnabled", ArgumentParser}, - {"setBlurLevel", SetBlurLevel}, - {"setJetpackMaxHeight", SetJetpackMaxHeight}, - {"setCloudsEnabled", SetCloudsEnabled}, - {"setTrafficLightState", SetTrafficLightState}, - {"setTrafficLightsLocked", SetTrafficLightsLocked}, - {"setWindVelocity", SetWindVelocity}, - {"setInteriorSoundsEnabled", SetInteriorSoundsEnabled}, - {"setInteriorFurnitureEnabled", SetInteriorFurnitureEnabled}, - {"setRainLevel", SetRainLevel}, - {"setFarClipDistance", SetFarClipDistance}, - {"setNearClipDistance", SetNearClipDistance}, - {"setVehiclesLODDistance", SetVehiclesLODDistance}, - {"setPedsLODDistance", SetPedsLODDistance}, - {"setFogDistance", SetFogDistance}, - {"setSunColor", SetSunColor}, - {"setSunSize", SetSunSize}, - {"setAircraftMaxHeight", SetAircraftMaxHeight}, - {"setAircraftMaxVelocity", SetAircraftMaxVelocity}, - {"setOcclusionsEnabled", SetOcclusionsEnabled}, - {"setBirdsEnabled", SetBirdsEnabled}, - {"setPedTargetingMarkerEnabled", SetPedTargetingMarkerEnabled}, - {"setMoonSize", SetMoonSize}, - {"setFPSLimit", SetFPSLimit}, - {"setCoronaReflectionsEnabled", ArgumentParser}, - {"setWorldProperty", ArgumentParser}, - - // World remove/restore functions - {"removeWorldModel", RemoveWorldBuilding}, - {"restoreAllWorldModels", RestoreWorldBuildings}, - {"restoreWorldModel", RestoreWorldBuilding}, - {"removeGameWorld", ArgumentParser}, - {"restoreGameWorld", ArgumentParser}, - - {"setTimeFrozen", ArgumentParser}, - {"setVolumetricShadowsEnabled", ArgumentParser}, - {"setDynamicPedShadowsEnabled", ArgumentParser}, - - - // World create funcs - {"createSWATRope", CreateSWATRope}, - {"createExplosion", CreateExplosion}, - - // World reset funcs - {"resetColorFilter", ArgumentParser}, - {"resetCoronaReflectionsEnabled", ArgumentParser}, - {"resetSkyGradient", ResetSkyGradient}, - {"resetHeatHaze", ResetHeatHaze}, - {"resetWindVelocity", ResetWindVelocity}, - {"resetRainLevel", ResetRainLevel}, - {"resetFarClipDistance", ResetFarClipDistance}, - {"resetNearClipDistance", ResetNearClipDistance}, - {"resetVehiclesLODDistance", ResetVehiclesLODDistance}, - {"resetPedsLODDistance", ResetPedsLODDistance}, - {"resetFogDistance", ResetFogDistance}, - {"resetSunColor", ResetSunColor}, - {"resetSunSize", ResetSunSize}, - {"resetMoonSize", ResetMoonSize}, - {"resetBlurLevel", ResetBlurLevel}, - {"resetWorldProperty", ArgumentParserWarn}, - {"resetTimeFrozen", ArgumentParser}, - {"resetVolumetricShadows", ArgumentParser}, - {"resetWorldProperties", ArgumentParser}, - {"resetDynamicPedShadows", ArgumentParser}, - - // World check funcs - {"areTrafficLightsLocked", AreTrafficLightsLocked}, - {"isPedTargetingMarkerEnabled", IsPedTargetingMarkerEnabled}, - {"isLineOfSightClear", IsLineOfSightClear}, - {"isWorldSpecialPropertyEnabled", ArgumentParserWarn}, - {"isGarageOpen", IsGarageOpen}, - {"isTimeFrozen", ArgumentParser}, - {"isVolumetricShadowsEnabled", ArgumentParser}, - {"isDynamicPedShadowsEnabled", ArgumentParser}, - {"testSphereAgainstWorld", ArgumentParser}}; + constexpr static const std::pair functions[]{ + // World get functions + {"getTime", GetTime}, + {"getColorFilter", ArgumentParser}, + {"getRoofPosition", GetRoofPosition}, + {"getGroundPosition", GetGroundPosition}, + {"processLineAgainstMesh", ArgumentParser}, + {"processLineOfSight", ProcessLineOfSight}, + {"getWorldFromScreenPosition", GetWorldFromScreenPosition}, + {"getScreenFromWorldPosition", GetScreenFromWorldPosition}, + {"getWeather", GetWeather}, + {"getZoneName", GetZoneName}, + {"getGravity", GetGravity}, + {"getGameSpeed", GetGameSpeed}, + {"getMinuteDuration", GetMinuteDuration}, + {"getWaveHeight", GetWaveHeight}, + {"getGaragePosition", GetGaragePosition}, + {"getGarageSize", GetGarageSize}, + {"getGarageBoundingBox", GetGarageBoundingBox}, + {"getBlurLevel", GetBlurLevel}, + {"getTrafficLightState", GetTrafficLightState}, + {"getSkyGradient", GetSkyGradient}, + {"getHeatHaze", GetHeatHaze}, + {"getJetpackMaxHeight", GetJetpackMaxHeight}, + {"getWindVelocity", GetWindVelocity}, + {"getInteriorSoundsEnabled", GetInteriorSoundsEnabled}, + {"getInteriorFurnitureEnabled", GetInteriorFurnitureEnabled}, + {"getFarClipDistance", GetFarClipDistance}, + {"getNearClipDistance", GetNearClipDistance}, + {"getVehiclesLODDistance", GetVehiclesLODDistance}, + {"getPedsLODDistance", GetPedsLODDistance}, + {"getFogDistance", GetFogDistance}, + {"getSunColor", GetSunColor}, + {"getSunSize", GetSunSize}, + {"getAircraftMaxHeight", GetAircraftMaxHeight}, + {"getAircraftMaxVelocity", GetAircraftMaxVelocity}, + {"getOcclusionsEnabled", GetOcclusionsEnabled}, + {"getCloudsEnabled", GetCloudsEnabled}, + {"getRainLevel", GetRainLevel}, + {"getMoonSize", GetMoonSize}, + {"getFPSLimit", GetFPSLimit}, + {"getBirdsEnabled", GetBirdsEnabled}, + {"getCoronaReflectionsEnabled", ArgumentParser}, + {"getWorldProperty", ArgumentParser}, + + // World set funcs + {"setTime", SetTime}, + {"setColorFilter", ArgumentParser}, + {"setGrainMultiplier", ArgumentParser}, + {"setGrainLevel", ArgumentParser}, + {"setSkyGradient", SetSkyGradient}, + {"setHeatHaze", SetHeatHaze}, + {"setWeather", SetWeather}, + {"setWeatherBlended", SetWeatherBlended}, + {"setGravity", SetGravity}, + {"setGameSpeed", SetGameSpeed}, + {"setWaveHeight", SetWaveHeight}, + {"setMinuteDuration", SetMinuteDuration}, + {"setGarageOpen", SetGarageOpen}, + {"setWorldSpecialPropertyEnabled", ArgumentParser}, + {"setBlurLevel", SetBlurLevel}, + {"setJetpackMaxHeight", SetJetpackMaxHeight}, + {"setCloudsEnabled", SetCloudsEnabled}, + {"setTrafficLightState", SetTrafficLightState}, + {"setTrafficLightsLocked", SetTrafficLightsLocked}, + {"setWindVelocity", SetWindVelocity}, + {"setInteriorSoundsEnabled", SetInteriorSoundsEnabled}, + {"setInteriorFurnitureEnabled", SetInteriorFurnitureEnabled}, + {"setRainLevel", SetRainLevel}, + {"setFarClipDistance", SetFarClipDistance}, + {"setNearClipDistance", SetNearClipDistance}, + {"setVehiclesLODDistance", SetVehiclesLODDistance}, + {"setPedsLODDistance", SetPedsLODDistance}, + {"setFogDistance", SetFogDistance}, + {"setSunColor", SetSunColor}, + {"setSunSize", SetSunSize}, + {"setAircraftMaxHeight", SetAircraftMaxHeight}, + {"setAircraftMaxVelocity", SetAircraftMaxVelocity}, + {"setOcclusionsEnabled", SetOcclusionsEnabled}, + {"setBirdsEnabled", SetBirdsEnabled}, + {"setPedTargetingMarkerEnabled", SetPedTargetingMarkerEnabled}, + {"setMoonSize", SetMoonSize}, + {"setFPSLimit", SetFPSLimit}, + {"setCoronaReflectionsEnabled", ArgumentParser}, + {"setWorldProperty", ArgumentParser}, + + // World remove/restore functions + {"removeWorldModel", RemoveWorldBuilding}, + {"restoreAllWorldModels", RestoreWorldBuildings}, + {"restoreWorldModel", RestoreWorldBuilding}, + {"removeGameWorld", ArgumentParser}, + {"restoreGameWorld", ArgumentParser}, + + {"setTimeFrozen", ArgumentParser}, + {"setVolumetricShadowsEnabled", ArgumentParser}, + {"setDynamicPedShadowsEnabled", ArgumentParser}, + + // World create funcs + {"createSWATRope", CreateSWATRope}, + {"createExplosion", CreateExplosion}, + + // World reset funcs + {"resetColorFilter", ArgumentParser}, + {"resetCoronaReflectionsEnabled", ArgumentParser}, + {"resetSkyGradient", ResetSkyGradient}, + {"resetHeatHaze", ResetHeatHaze}, + {"resetWindVelocity", ResetWindVelocity}, + {"resetRainLevel", ResetRainLevel}, + {"resetFarClipDistance", ResetFarClipDistance}, + {"resetNearClipDistance", ResetNearClipDistance}, + {"resetVehiclesLODDistance", ResetVehiclesLODDistance}, + {"resetPedsLODDistance", ResetPedsLODDistance}, + {"resetFogDistance", ResetFogDistance}, + {"resetSunColor", ResetSunColor}, + {"resetSunSize", ResetSunSize}, + {"resetMoonSize", ResetMoonSize}, + {"resetBlurLevel", ResetBlurLevel}, + {"resetWorldProperty", ArgumentParserWarn}, + {"resetTimeFrozen", ArgumentParser}, + {"resetVolumetricShadows", ArgumentParser}, + {"resetWorldProperties", ArgumentParser}, + {"resetDynamicPedShadows", ArgumentParser}, + + // World check funcs + {"areTrafficLightsLocked", AreTrafficLightsLocked}, + {"isPedTargetingMarkerEnabled", IsPedTargetingMarkerEnabled}, + {"isLineOfSightClear", IsLineOfSightClear}, + {"isWorldSpecialPropertyEnabled", ArgumentParserWarn}, + {"isGarageOpen", IsGarageOpen}, + {"isTimeFrozen", ArgumentParser}, + {"isVolumetricShadowsEnabled", ArgumentParser}, + {"isDynamicPedShadowsEnabled", ArgumentParser}, + {"testSphereAgainstWorld", ArgumentParser}}; // Add functions for (const auto& [name, func] : functions) @@ -252,16 +252,21 @@ int CLuaWorldDefs::GetRoofPosition(lua_State* luaVM) return 1; } -std::variant> CLuaWorldDefs::ProcessLineAgainstMesh(CClientEntity* e, CVector start, CVector end) { +std::variant> CLuaWorldDefs::ProcessLineAgainstMesh(CClientEntity* e, + CVector start, + CVector end) +{ const auto ge = e->GetGameEntity(); - if (!ge) { + if (!ge) + { // Element likely not streamed in, and such // Can't process it. This isn't an error per-se, thus we won't raise anything and treat this as a no-hit scenario - return { false }; + return {false}; } const SProcessLineOfSightMaterialInfoResult matInfo{g_pGame->GetWorld()->ProcessLineAgainstMesh(ge->GetInterface(), start, end)}; - if (!matInfo.valid) { - return { false }; // No hit + if (!matInfo.valid) + { + return {false}; // No hit } return CLuaMultiReturn{ true, @@ -332,7 +337,7 @@ int CLuaWorldDefs::ProcessLineOfSight(lua_State* L) // Get the collision position vecColPosition = pColPoint->GetPosition(); vecColNormal = pColPoint->GetNormal(); - iMaterial = pColPoint->GetSurfaceTypeB(); // From test, only B function return relevant data + iMaterial = pColPoint->GetSurfaceTypeB(); // From test, only B function return relevant data fLighting = pColPoint->GetLightingForTimeOfDay(); iPiece = pColPoint->GetPieceTypeB(); @@ -360,7 +365,7 @@ int CLuaWorldDefs::ProcessLineOfSight(lua_State* L) lua_pushnumber(L, fLighting); lua_pushinteger(L, iPiece); - if (bIncludeBuildingInfo && buildingResult.bValid) // 8 args + if (bIncludeBuildingInfo && buildingResult.bValid) // 8 args { lua_pushnumber(L, buildingResult.usModelID); @@ -373,13 +378,17 @@ int CLuaWorldDefs::ProcessLineOfSight(lua_State* L) lua_pushnumber(L, ConvertRadiansToDegrees(buildingResult.vecRotation.fZ)); lua_pushnumber(L, buildingResult.usLODModelID); - } else { - for (auto i = 1 + 3 + 3 + 1; i-- > 0;) { + } + else + { + for (auto i = 1 + 3 + 3 + 1; i-- > 0;) + { lua_pushnil(L); } } - if (bIncludeExtraMateriaInfo && matInfo.valid) { // 7 args + if (bIncludeExtraMateriaInfo && matInfo.valid) + { // 7 args lua::Push(L, matInfo.uv.fX); lua::Push(L, matInfo.uv.fY); @@ -389,8 +398,11 @@ int CLuaWorldDefs::ProcessLineOfSight(lua_State* L) lua::Push(L, matInfo.hitPos.fX); lua::Push(L, matInfo.hitPos.fY); lua::Push(L, matInfo.hitPos.fZ); - } else { - for (auto i = 2 + 1 + 1 + 3; i-- > 0;) { + } + else + { + for (auto i = 2 + 1 + 1 + 3; i-- > 0;) + { lua_pushnil(L); } } @@ -1126,8 +1138,8 @@ int CLuaWorldDefs::RemoveWorldBuilding(lua_State* luaVM) if (pResource) { uint uiAmount; - CStaticFunctionDefinitions::RemoveWorldBuilding(static_cast(iModelToRemove), fRadius, vecPosition.fX, - vecPosition.fY, vecPosition.fZ, cInterior, uiAmount); + CStaticFunctionDefinitions::RemoveWorldBuilding(static_cast(iModelToRemove), fRadius, vecPosition.fX, vecPosition.fY, + vecPosition.fZ, cInterior, uiAmount); lua_pushboolean(luaVM, true); lua_pushnumber(luaVM, uiAmount); @@ -1183,8 +1195,8 @@ int CLuaWorldDefs::RestoreWorldBuilding(lua_State* luaVM) if (pResource) { uint uiAmount; - CStaticFunctionDefinitions::RestoreWorldBuilding(static_cast(iModelToRestore), fRadius, vecPosition.fX, - vecPosition.fY, vecPosition.fZ, cInterior, uiAmount); + CStaticFunctionDefinitions::RestoreWorldBuilding(static_cast(iModelToRestore), fRadius, vecPosition.fX, vecPosition.fY, + vecPosition.fZ, cInterior, uiAmount); lua_pushboolean(luaVM, true); lua_pushnumber(luaVM, uiAmount); @@ -2053,8 +2065,7 @@ CLuaMultiReturn CLuaWorl SColor uColor1 = 0; g_pMultiplayer->GetColorFilter(uColor0.ulARGB, uColor1.ulARGB, isOriginal); return { - uColor0.R, uColor0.G, uColor0.B, uColor0.A, - uColor1.R, uColor1.G, uColor1.B, uColor1.A, + uColor0.R, uColor0.G, uColor0.B, uColor0.A, uColor1.R, uColor1.G, uColor1.B, uColor1.A, }; } @@ -2319,9 +2330,11 @@ bool CLuaWorldDefs::ResetVolumetricShadows() noexcept return g_pGame->GetSettings()->ResetVolumetricShadows(); } -void CLuaWorldDefs::ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds) noexcept +void CLuaWorldDefs::ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, + std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds) noexcept { - g_pClientGame->ResetWorldProperties(ResetWorldPropsInfo{resetSpecialWorldProperties.value_or(true), resetWorldProperties.value_or(true), resetWeatherProperties.value_or(true), resetLODs.value_or(true), resetSounds.value_or(true)}); + g_pClientGame->ResetWorldProperties(ResetWorldPropsInfo{resetSpecialWorldProperties.value_or(true), resetWorldProperties.value_or(true), + resetWeatherProperties.value_or(true), resetLODs.value_or(true), resetSounds.value_or(true)}); } bool CLuaWorldDefs::SetDynamicPedShadowsEnabled(bool enable) @@ -2340,14 +2353,28 @@ bool CLuaWorldDefs::ResetDynamicPedShadows() noexcept return g_pGame->GetSettings()->ResetDynamicPedShadows(); } -CLuaMultiReturn CLuaWorldDefs::TestSphereAgainstWorld(CVector sphereCenter, float radius, std::optional ignoredEntity, std::optional checkBuildings, std::optional checkVehicles, std::optional checkPeds, std::optional checkObjects, std::optional checkDummies, std::optional cameraIgnore) +CLuaMultiReturn CLuaWorldDefs::TestSphereAgainstWorld( + CVector sphereCenter, float radius, std::optional ignoredEntity, std::optional checkBuildings, std::optional checkVehicles, + std::optional checkPeds, std::optional checkObjects, std::optional checkDummies, std::optional cameraIgnore) { STestSphereAgainstWorldResult result; - CClientEntity* collidedEntity = nullptr; + CClientEntity* collidedEntity = nullptr; - CEntity* entity = g_pGame->GetWorld()->TestSphereAgainstWorld(sphereCenter, radius, ignoredEntity.has_value() ? ignoredEntity.value()->GetGameEntity() : nullptr, checkBuildings.value_or(true), checkVehicles.value_or(true), checkPeds.value_or(true), checkObjects.value_or(true), checkDummies.value_or(true), cameraIgnore.value_or(false), result); + CEntity* entity = g_pGame->GetWorld()->TestSphereAgainstWorld( + sphereCenter, radius, ignoredEntity.has_value() ? ignoredEntity.value()->GetGameEntity() : nullptr, checkBuildings.value_or(true), + checkVehicles.value_or(true), checkPeds.value_or(true), checkObjects.value_or(true), checkDummies.value_or(true), cameraIgnore.value_or(false), result); if (entity) collidedEntity = reinterpret_cast(entity->GetStoredPointer()); - return {result.collisionDetected, collidedEntity, result.modelID, result.entityPosition.fX, result.entityPosition.fY, result.entityPosition.fZ, ConvertRadiansToDegrees(result.entityRotation.fX), ConvertRadiansToDegrees(result.entityRotation.fY), ConvertRadiansToDegrees(result.entityRotation.fZ), result.lodID, result.type}; + return {result.collisionDetected, + collidedEntity, + result.modelID, + result.entityPosition.fX, + result.entityPosition.fY, + result.entityPosition.fZ, + ConvertRadiansToDegrees(result.entityRotation.fX), + ConvertRadiansToDegrees(result.entityRotation.fY), + ConvertRadiansToDegrees(result.entityRotation.fZ), + result.lodID, + result.type}; } diff --git a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h index 5668ca6dd48..5ad83bdeae0 100644 --- a/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h +++ b/Client/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h @@ -15,11 +15,12 @@ class CLuaWorldDefs : public CLuaDefs public: static void LoadFunctions(); - LUA_DECLARE(GetTime); LUA_DECLARE(GetGroundPosition); LUA_DECLARE(GetRoofPosition); - static std::variant> ProcessLineAgainstMesh(CClientEntity* e, CVector start, CVector end); + static std::variant> ProcessLineAgainstMesh(CClientEntity* e, + CVector start, + CVector end); LUA_DECLARE(ProcessLineOfSight); LUA_DECLARE(IsLineOfSightClear); LUA_DECLARE(GetWorldFromScreenPosition); @@ -115,9 +116,9 @@ class CLuaWorldDefs : public CLuaDefs LUA_DECLARE(CreateExplosion); - static bool ResetColorFilter(); - static bool SetColorFilter(uchar ucPass0Red, uchar ucPass0Green, uchar ucPass0Blue, uchar ucPass0Alpha, - uchar ucPass1Red, uchar ucPass1Green, uchar ucPass1Blue, uchar ucPass1Alpha); + static bool ResetColorFilter(); + static bool SetColorFilter(uchar ucPass0Red, uchar ucPass0Green, uchar ucPass0Blue, uchar ucPass0Alpha, uchar ucPass1Red, uchar ucPass1Green, + uchar ucPass1Blue, uchar ucPass1Alpha); static CLuaMultiReturn GetColorFilter(bool isOriginal = false); static bool SetGrainMultiplier(eGrainMultiplierType type, float fMultiplier); @@ -134,18 +135,21 @@ class CLuaWorldDefs : public CLuaDefs static bool SetTimeFrozen(bool value) noexcept; static bool IsTimeFrozen() noexcept; static bool ResetTimeFrozen() noexcept; - + static bool SetVolumetricShadowsEnabled(bool enable) noexcept; static bool IsVolumetricShadowsEnabled() noexcept; static bool ResetVolumetricShadows() noexcept; - - static void ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds) noexcept; + + static void ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, + std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds) noexcept; static bool SetDynamicPedShadowsEnabled(bool enable); static bool IsDynamicPedShadowsEnabled() noexcept; static bool ResetDynamicPedShadows() noexcept; - static CLuaMultiReturn TestSphereAgainstWorld(CVector sphereCenter, float radius, std::optional ignoredEntity, std::optional checkBuildings, std::optional checkVehicles, std::optional checkPeds, std::optional checkObjects, std::optional checkDummies, std::optional cameraIgnore); + static CLuaMultiReturn TestSphereAgainstWorld( + CVector sphereCenter, float radius, std::optional ignoredEntity, std::optional checkBuildings, std::optional checkVehicles, + std::optional checkPeds, std::optional checkObjects, std::optional checkDummies, std::optional cameraIgnore); static void RemoveGameWorld(); static void RestoreGameWorld(); diff --git a/Client/mods/deathmatch/logic/rpc/CBlipRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CBlipRPCs.cpp index c684724e4fa..a59111ebe90 100644 --- a/Client/mods/deathmatch/logic/rpc/CBlipRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CBlipRPCs.cpp @@ -110,4 +110,4 @@ void CBlipRPCs::SetBlipVisibleDistance(CClientEntity* pSource, NetBitStreamInter pMarker->SetVisibleDistance(visibleDistance); } } -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/rpc/CCameraRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CCameraRPCs.cpp index 07307108173..488e9921899 100644 --- a/Client/mods/deathmatch/logic/rpc/CCameraRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CCameraRPCs.cpp @@ -26,18 +26,18 @@ void CCameraRPCs::SetCameraMatrix(NetBitStreamInterface& bitStream) uchar ucTimeContext; if (!bitStream.Read(ucTimeContext)) return; - + if (m_pCamera) m_pCamera->SetSyncTimeContext(ucTimeContext); CVector vecPosition, vecLookAt; float fRoll = 0.0f; float fFOV = 70.0f; - - if (!bitStream.Read(vecPosition.fX) || !bitStream.Read(vecPosition.fY) || !bitStream.Read(vecPosition.fZ) || - !bitStream.Read(vecLookAt.fX) || !bitStream.Read(vecLookAt.fY) || !bitStream.Read(vecLookAt.fZ)) + + if (!bitStream.Read(vecPosition.fX) || !bitStream.Read(vecPosition.fY) || !bitStream.Read(vecPosition.fZ) || !bitStream.Read(vecLookAt.fX) || + !bitStream.Read(vecLookAt.fY) || !bitStream.Read(vecLookAt.fZ)) { - return; // Invalid data + return; // Invalid data } const unsigned int unreadBits = bitStream.GetNumberOfUnreadBits(); @@ -53,11 +53,10 @@ void CCameraRPCs::SetCameraMatrix(NetBitStreamInterface& bitStream) } // Validate float values to prevent potential issues - if (!std::isfinite(fRoll) || !std::isfinite(fFOV) || - !std::isfinite(vecPosition.fX) || !std::isfinite(vecPosition.fY) || !std::isfinite(vecPosition.fZ) || + if (!std::isfinite(fRoll) || !std::isfinite(fFOV) || !std::isfinite(vecPosition.fX) || !std::isfinite(vecPosition.fY) || !std::isfinite(vecPosition.fZ) || !std::isfinite(vecLookAt.fX) || !std::isfinite(vecLookAt.fY) || !std::isfinite(vecLookAt.fZ)) { - return; // Invalid float values (NaN, infinity, etc.) + return; // Invalid float values (NaN, infinity, etc.) } if (fFOV <= 0.0f) @@ -93,7 +92,7 @@ void CCameraRPCs::SetCameraTarget(NetBitStreamInterface& bitStream) uchar ucTimeContext; if (!bitStream.Read(ucTimeContext)) return; - + if (m_pCamera) m_pCamera->SetSyncTimeContext(ucTimeContext); @@ -160,7 +159,7 @@ void CCameraRPCs::FadeCamera(NetBitStreamInterface& bitStream) { unsigned char ucFadeIn; float fFadeTime = 1.0f; - + if (!bitStream.Read(ucFadeIn) || !bitStream.Read(fFadeTime)) return; @@ -173,7 +172,7 @@ void CCameraRPCs::FadeCamera(NetBitStreamInterface& bitStream) if (ucFadeIn) { m_pCamera->FadeIn(fFadeTime); - + // Validate game and HUD pointers if (g_pGame && g_pGame->GetHud()) { @@ -190,7 +189,7 @@ void CCameraRPCs::FadeCamera(NetBitStreamInterface& bitStream) return; m_pCamera->FadeOut(fFadeTime, ucRed, ucGreen, ucBlue); - + // Validate game and HUD pointers if (g_pGame && g_pGame->GetHud()) { diff --git a/Client/mods/deathmatch/logic/rpc/CElementRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CElementRPCs.cpp index 756c0e10adc..224c0c01b5b 100644 --- a/Client/mods/deathmatch/logic/rpc/CElementRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CElementRPCs.cpp @@ -105,7 +105,7 @@ void CElementRPCs::RemoveElementData(CClientEntity* pSource, NetBitStreamInterfa { // Read out the name length unsigned short usNameLength; - bool bRecursive; // Unused + bool bRecursive; // Unused if (bitStream.ReadCompressed(usNameLength)) { SString strName; @@ -359,7 +359,7 @@ void CElementRPCs::DetachElements(CClientEntity* pSource, NetBitStreamInterface& return; } - ElementID usAttachedToID; + ElementID usAttachedToID; CClientEntity* pAttachedToEntity = CElementIDs::GetElement(usAttachedToID); CVector vecPosition; @@ -470,7 +470,8 @@ void CElementRPCs::SetElementHealth(CClientEntity* pSource, NetBitStreamInterfac pPed->SetHealth(fHealth); // If server sets health to 0 for local player, mark as server-processed death // to prevent DoWastedCheck from firing with stale local damage data - if (fHealth == 0.0f && pPed->IsLocalPlayer()) { + if (fHealth == 0.0f && pPed->IsLocalPlayer()) + { g_pClientGame->ClearDamageData(); } } diff --git a/Client/mods/deathmatch/logic/rpc/CObjectRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CObjectRPCs.cpp index 907b955357d..15ff752b6a3 100644 --- a/Client/mods/deathmatch/logic/rpc/CObjectRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CObjectRPCs.cpp @@ -129,7 +129,7 @@ void CObjectRPCs::SetObjectBreakable(CClientEntity* pSource, NetBitStreamInterfa void CObjectRPCs::BreakObject(CClientEntity* pSource, NetBitStreamInterface& bitStream) { - auto* pObject = static_cast(m_pObjectManager->Get(pSource->GetID())); + auto* pObject = static_cast(m_pObjectManager->Get(pSource->GetID())); if (pObject) pObject->Break(); diff --git a/Client/mods/deathmatch/logic/rpc/CPickupRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CPickupRPCs.cpp index a565794acaa..c303c6043c9 100644 --- a/Client/mods/deathmatch/logic/rpc/CPickupRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CPickupRPCs.cpp @@ -89,4 +89,4 @@ void CPickupRPCs::SetPickupVisible(CClientEntity* pSource, NetBitStreamInterface pPickup->SetVisible(ucVisible != 0); } } -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/rpc/CRPCFunctions.h b/Client/mods/deathmatch/logic/rpc/CRPCFunctions.h index 81fd123b0a6..4b3f44c3384 100644 --- a/Client/mods/deathmatch/logic/rpc/CRPCFunctions.h +++ b/Client/mods/deathmatch/logic/rpc/CRPCFunctions.h @@ -13,8 +13,8 @@ class CRPCFunctions; -#define DECLARE_RPC(a) static void a ( class NetBitStreamInterface& bitStream ); -#define DECLARE_ELEMENT_RPC(a) static void a ( CClientEntity* pSourceEntity, NetBitStreamInterface& bitStream ); +#define DECLARE_RPC(a) static void a(class NetBitStreamInterface& bitStream); +#define DECLARE_ELEMENT_RPC(a) static void a(CClientEntity* pSourceEntity, NetBitStreamInterface& bitStream); class CRPCFunctions { @@ -65,8 +65,8 @@ class CRPCFunctions static class CClientGame* m_pClientGame; protected: - // Include the RPC functions enum - #include "net/rpc_enums.h" +// Include the RPC functions enum +#include "net/rpc_enums.h" static SFixedArray m_RPCHandlers; static SFixedArray m_ElementRPCHandlers; diff --git a/Client/mods/deathmatch/logic/rpc/CRadarRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CRadarRPCs.cpp index 288ac1977ed..ce6a8f3903c 100644 --- a/Client/mods/deathmatch/logic/rpc/CRadarRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CRadarRPCs.cpp @@ -72,4 +72,4 @@ void CRadarRPCs::SetRadarAreaFlashing(CClientEntity* pSource, NetBitStreamInterf pArea->SetFlashing(bFlashing); } } -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/rpc/CTeamRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CTeamRPCs.cpp index 60d27ce0744..5eb1d7b4253 100644 --- a/Client/mods/deathmatch/logic/rpc/CTeamRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CTeamRPCs.cpp @@ -56,4 +56,4 @@ void CTeamRPCs::SetTeamFriendlyFire(CClientEntity* pSource, NetBitStreamInterfac pTeam->SetFriendlyFire(bFriendlyFire); } } -} \ No newline at end of file +} diff --git a/Client/mods/deathmatch/logic/rpc/CVehicleRPCs.cpp b/Client/mods/deathmatch/logic/rpc/CVehicleRPCs.cpp index 0d318c75467..d78b978b928 100644 --- a/Client/mods/deathmatch/logic/rpc/CVehicleRPCs.cpp +++ b/Client/mods/deathmatch/logic/rpc/CVehicleRPCs.cpp @@ -312,7 +312,7 @@ void CVehicleRPCs::SetVehicleDamageState(CClientEntity* pSource, NetBitStreamInt { switch (ucObject) { - case 0: // Door + case 0: // Door { unsigned char ucDoor, ucState; if (bitStream.Read(ucDoor) && bitStream.Read(ucState)) @@ -326,7 +326,7 @@ void CVehicleRPCs::SetVehicleDamageState(CClientEntity* pSource, NetBitStreamInt } break; } - case 1: // Wheel + case 1: // Wheel { unsigned char ucWheel, ucState; if (bitStream.Read(ucWheel) && bitStream.Read(ucState)) @@ -335,7 +335,7 @@ void CVehicleRPCs::SetVehicleDamageState(CClientEntity* pSource, NetBitStreamInt } break; } - case 2: // Light + case 2: // Light { unsigned char ucLight, ucState; if (bitStream.Read(ucLight) && bitStream.Read(ucState)) @@ -344,7 +344,7 @@ void CVehicleRPCs::SetVehicleDamageState(CClientEntity* pSource, NetBitStreamInt } break; } - case 3: // Panel + case 3: // Panel { unsigned char ucPanel, ucState; if (bitStream.Read(ucPanel) && bitStream.Read(ucState)) @@ -677,12 +677,12 @@ void CVehicleRPCs::SetVehicleNitroActivated(CClientEntity* pSourceEntity, NetBit CClientVehicle* vehicle = m_pVehicleManager->Get(pSourceEntity->GetID()); if (!vehicle) - return; + return; if (!vehicle->IsNitroInstalled()) return; - // If nitro level < 0, nitro is activated. (until nitro level reaches -1, at that point it will become 0 and increase instead of decrease) + // If nitro level < 0, nitro is activated. (until nitro level reaches -1, at that point it will become 0 and increase instead of decrease) if ((vehicle->GetNitroLevel() < 0.0f) == state) return; @@ -692,4 +692,3 @@ void CVehicleRPCs::SetVehicleNitroActivated(CClientEntity* pSourceEntity, NetBit else vehicle->SetNitroLevel(vehicle->GetNitroLevel() + 1.0001f); } - diff --git a/Client/multiplayer_sa/CLimitsSA.cpp b/Client/multiplayer_sa/CLimitsSA.cpp index bc4cb0d9a22..d95a79be868 100644 --- a/Client/multiplayer_sa/CLimitsSA.cpp +++ b/Client/multiplayer_sa/CLimitsSA.cpp @@ -19,8 +19,8 @@ #include "StdInc.h" -#define INTEGER_AT(addr) *(int *)(addr) -#define FLOAT_AT(addr) *(float *)(addr) +#define INTEGER_AT(addr) *(int*)(addr) +#define FLOAT_AT(addr) *(float*)(addr) int CLimitsSA::GetIPLFiles() const { diff --git a/Client/multiplayer_sa/CMultiplayerSA.cpp b/Client/multiplayer_sa/CMultiplayerSA.cpp index d6e82139cde..f4b9573d05d 100644 --- a/Client/multiplayer_sa/CMultiplayerSA.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA.cpp @@ -50,16 +50,16 @@ extern CGame* pGameInterface; #define HOOKPOS_ComputeDamageResponse_StartChoking 0x4C05B9 #define HOOKPOS_CAutomobile__ProcessSwingingDoor 0x6A9DAF -#define FUNC_CStreaming_Update 0x40E670 -#define FUNC_CAudioEngine__DisplayRadioStationName 0x507030 -#define FUNC_CHud_Draw 0x58FAE0 -#define FUNC_CPlayerInfoBase 0xB7CD98 +#define FUNC_CStreaming_Update 0x40E670 +#define FUNC_CAudioEngine__DisplayRadioStationName 0x507030 +#define FUNC_CHud_Draw 0x58FAE0 +#define FUNC_CPlayerInfoBase 0xB7CD98 -#define ADDR_CursorHiding 0x7481CD -#define ADDR_GotFocus 0x748054 +#define ADDR_CursorHiding 0x7481CD +#define ADDR_GotFocus 0x748054 -#define HOOKPOS_FxManager_CreateFxSystem 0x4A9BE0 -#define HOOKPOS_FxManager_DestroyFxSystem 0x4A9810 +#define HOOKPOS_FxManager_CreateFxSystem 0x4A9BE0 +#define HOOKPOS_FxManager_DestroyFxSystem 0x4A9810 DWORD RETURN_FxManager_CreateFxSystem = 0x4A9BE8; DWORD RETURN_FxManager_DestroyFxSystem = 0x4A9817; @@ -72,227 +72,227 @@ DWORD RETURN_CCam_ProcessFixed = 0x51D475; DWORD RETURN_CTaskSimplePlayerOnFoot_ProcessPlayerWeapon = 0x6859A7; DWORD RETURN_CPed_IsPlayer = 0x5DF8F6; -#define VAR_CollisionStreamRead_ModelInfo 0x9689E0 -#define HOOKPOS_CollisionStreamRead 0x41B1D0 +#define VAR_CollisionStreamRead_ModelInfo 0x9689E0 +#define HOOKPOS_CollisionStreamRead 0x41B1D0 DWORD RETURN_CollisionStreamRead = 0x41B1D6; -#define CALL_Render3DStuff 0x53EABF -#define FUNC_Render3DStuff 0x53DF40 +#define CALL_Render3DStuff 0x53EABF +#define FUNC_Render3DStuff 0x53DF40 -#define CALL_CRenderer_Render 0x53EA12 -#define FUNC_CRenderer_Render 0x727140 +#define CALL_CRenderer_Render 0x53EA12 +#define FUNC_CRenderer_Render 0x727140 -#define CALL_CTrafficLights_GetPrimaryLightState 0x49DB5F -#define CALL_CTrafficLights_GetSecondaryLightState 0x49DB6D -#define HOOKPOS_CTrafficLights_DisplayActualLight 0x49E1D9 +#define CALL_CTrafficLights_GetPrimaryLightState 0x49DB5F +#define CALL_CTrafficLights_GetSecondaryLightState 0x49DB6D +#define HOOKPOS_CTrafficLights_DisplayActualLight 0x49E1D9 DWORD RETURN_CTrafficLights_DisplayActualLight = 0x49E1FF; -#define HOOKPOS_CGame_Process 0x53C095 +#define HOOKPOS_CGame_Process 0x53C095 DWORD RETURN_CGame_Process = 0x53C09F; -#define HOOKPOS_Idle 0x53E981 +#define HOOKPOS_Idle 0x53E981 DWORD RETURN_Idle = 0x53E98B; DWORD FUNC_CEntity_Render = 0x534310; -#define HOOKPOS_VehicleCamStart 0x5245ED +#define HOOKPOS_VehicleCamStart 0x5245ED DWORD RETURN_VehicleCamStart_success = 0x5245F3; DWORD RETURN_VehicleCamStart_failure = 0x525E43; -#define HOOKPOS_VehicleCamTargetZTweak 0x524A68 +#define HOOKPOS_VehicleCamTargetZTweak 0x524A68 DWORD RETURN_VehicleCamTargetZTweak = 0x524AA4; -#define HOOKPOS_VehicleCamLookDir1 0x524DF1 +#define HOOKPOS_VehicleCamLookDir1 0x524DF1 DWORD RETURN_VehicleCamLookDir1 = 0x524DF6; -#define HOOKPOS_VehicleCamLookDir2 0x525B0E +#define HOOKPOS_VehicleCamLookDir2 0x525B0E DWORD RETURN_VehicleCamLookDir2 = 0x525B73; -#define HOOKPOS_VehicleCamHistory 0x525C56 +#define HOOKPOS_VehicleCamHistory 0x525C56 DWORD RETURN_VehicleCamHistory = 0x525D4A; -#define HOOKPOS_VehicleCamColDetect 0x525D8D +#define HOOKPOS_VehicleCamColDetect 0x525D8D DWORD RETURN_VehicleCamColDetect = 0x525D92; -#define CALL_VehicleCamUp 0x525E1F -#define HOOKPOS_VehicleCamEnd 0x525E3C +#define CALL_VehicleCamUp 0x525E1F +#define HOOKPOS_VehicleCamEnd 0x525E3C DWORD RETURN_VehicleCamEnd = 0x525E42; -#define HOOKPOS_VehicleLookBehind 0x5207E3 +#define HOOKPOS_VehicleLookBehind 0x5207E3 DWORD RETURN_VehicleLookBehind = 0x520891; -#define CALL_VehicleLookBehindUp 0x520E2A -#define HOOKPOS_VehicleLookAside 0x520F70 +#define CALL_VehicleLookBehindUp 0x520E2A +#define HOOKPOS_VehicleLookAside 0x520F70 DWORD RETURN_VehicleLookAside = 0x520FDC; -#define CALL_VehicleLookAsideUp 0x5211E0 +#define CALL_VehicleLookAsideUp 0x5211E0 -#define HOOKPOS_OccupiedVehicleBurnCheck 0x570C84 +#define HOOKPOS_OccupiedVehicleBurnCheck 0x570C84 DWORD RETURN_OccupiedVehicleBurnCheck = 0x570C8A; -#define HOOKPOS_UnoccupiedVehicleBurnCheck 0x6A76DC +#define HOOKPOS_UnoccupiedVehicleBurnCheck 0x6A76DC DWORD RETURN_UnoccupiedVehicleBurnCheck = 0x6A76E4; -#define HOOKPOS_ApplyCarBlowHop 0x6B3816 +#define HOOKPOS_ApplyCarBlowHop 0x6B3816 DWORD RETURN_ApplyCarBlowHop = 0x6B3831; -#define HOOKPOS_CVehicle_ApplyBoatWaterResistance 0x6D2771 +#define HOOKPOS_CVehicle_ApplyBoatWaterResistance 0x6D2771 DWORD RETURN_CVehicle_ApplyBoatWaterResistance = 0x6D2777; -#define HOOKPOS_CPhysical_ApplyGravity 0x543081 +#define HOOKPOS_CPhysical_ApplyGravity 0x543081 DWORD RETURN_CPhysical_ApplyGravity = 0x543093; -#define HOOKPOS_CWorld_SetWorldOnFire 0x56B983 +#define HOOKPOS_CWorld_SetWorldOnFire 0x56B983 DWORD RETURN_CWorld_SetWorldOnFire = 0x56B989; -#define HOOKPOS_CTaskSimplePlayerOnFire_ProcessPed 0x6336DA +#define HOOKPOS_CTaskSimplePlayerOnFire_ProcessPed 0x6336DA DWORD RETURN_CTaskSimplePlayerOnFire_ProcessPed = 0x6336E0; -#define HOOKPOS_CFire_ProcessFire 0x53AC1A +#define HOOKPOS_CFire_ProcessFire 0x53AC1A DWORD RETURN_CFire_ProcessFire = 0x53AC1F; -#define HOOKPOS_CExplosion_Update 0x7377D3 +#define HOOKPOS_CExplosion_Update 0x7377D3 DWORD RETURN_CExplosion_Update = 0x7377D8; -#define HOOKPOS_CWeapon_FireAreaEffect 0x73EBFE +#define HOOKPOS_CWeapon_FireAreaEffect 0x73EBFE DWORD RETURN_CWeapon_FireAreaEffect = 0x73EC03; -#define CALL_RenderScene_Plants 0x53E103 -#define HOOKPOS_RenderScene_end 0x53E159 -#define HOOKPOS_CPlantMgr_Render 0x5DBC4C +#define CALL_RenderScene_Plants 0x53E103 +#define HOOKPOS_RenderScene_end 0x53E159 +#define HOOKPOS_CPlantMgr_Render 0x5DBC4C DWORD RETURN_CPlantMgr_Render_success = 0x5DBC52; -#define HOOKPOS_CEventHandler_ComputeKnockOffBikeResponse 0x4BA06F +#define HOOKPOS_CEventHandler_ComputeKnockOffBikeResponse 0x4BA06F DWORD RETURN_CEventHandler_ComputeKnockOffBikeResponse = 0x4BA076; -#define HOOKPOS_CAnimBlendAssocGroupCopyAnimation 0x4CE130 +#define HOOKPOS_CAnimBlendAssocGroupCopyAnimation 0x4CE130 -#define HOOKPOS_CPed_GetWeaponSkill 0x5e3b60 +#define HOOKPOS_CPed_GetWeaponSkill 0x5e3b60 DWORD RETURN_CPed_GetWeaponSkill = 0x5E3B68; -#define HOOKPOS_CPed_AddGogglesModel 0x5E3ACB +#define HOOKPOS_CPed_AddGogglesModel 0x5E3ACB DWORD RETURN_CPed_AddGogglesModel = 0x5E3AD4; -#define FUNC_CWorld_Remove 0x563280 -#define FUNC_CTagManager_ShutdownForRestart 0x49CC60 +#define FUNC_CWorld_Remove 0x563280 +#define FUNC_CTagManager_ShutdownForRestart 0x49CC60 unsigned int* VAR_NumTags = (unsigned int*)0xA9AD70; DWORD** VAR_TagInfoArray = (DWORD**)0xA9A8C0; -#define HOOKPOS_CPhysical_ProcessCollisionSectorList 0x54BB93 +#define HOOKPOS_CPhysical_ProcessCollisionSectorList 0x54BB93 DWORD RETURN_CPhysical_ProcessCollisionSectorList = 0x54BB9A; -#define HOOKPOS_CheckAnimMatrix 0x7C5A5C +#define HOOKPOS_CheckAnimMatrix 0x7C5A5C DWORD RETURN_CheckAnimMatrix = 0x7C5A61; -#define HOOKPOS_VehColCB 0x04C838D +#define HOOKPOS_VehColCB 0x04C838D DWORD RETURN_VehColCB = 0x04C83AA; -#define HOOKPOS_VehCol 0x06D6603 +#define HOOKPOS_VehCol 0x06D6603 DWORD RETURN_VehCol = 0x06D660C; #define HOOKPOS_Transmission_CalculateDriveAcceleration 0x6D05E0 DWORD RETURN_Transmission_CalculateDriveAcceleration = 0x6D05E6; // Handling fix - driveType is per model -#define HOOKPOS_CHandlingData_isNotRWD 0x6A048C +#define HOOKPOS_CHandlingData_isNotRWD 0x6A048C DWORD RETURN_CHandlingData_isNotRWD = 0x6A0493; -#define HOOKPOS_CHandlingData_isNotFWD 0x6A04BC +#define HOOKPOS_CHandlingData_isNotFWD 0x6A04BC DWORD RETURN_CHandlingData_isNotFWD = 0x6A04C3; // end of handling fix -#define CALL_CAutomobile_ProcessEntityCollision 0x6AD053 -#define CALL_CMonsterTruck_ProcessEntityCollision 0x6C8B9E +#define CALL_CAutomobile_ProcessEntityCollision 0x6AD053 +#define CALL_CMonsterTruck_ProcessEntityCollision 0x6C8B9E DWORD RETURN_ProcessEntityCollision = 0x4185C0; -#define HOOKPOS_PreFxRender 0x049E650 +#define HOOKPOS_PreFxRender 0x049E650 DWORD RETURN_PreFxRender = 0x0404D1E; -#define HOOKPOS_PostColorFilterRender 0x705099 +#define HOOKPOS_PostColorFilterRender 0x705099 DWORD RETURN_PostColorFilterRender = 0x70509E; -#define HOOKPOS_PreHUDRender 0x053EAD8 +#define HOOKPOS_PreHUDRender 0x053EAD8 DWORD RETURN_PreHUDRender = 0x053EADD; -#define HOOKPOS_LoadIPLInstance 0x4061E8 +#define HOOKPOS_LoadIPLInstance 0x4061E8 DWORD CALL_LoadIPLInstance = 0x538090; DWORD RETURN_LoadIPLInstance = 0x04061ED; -#define HOOKPOS_CWorld_LOD_SETUP 0x406224 -#define HOOKPOS_CWorld_LOD_SETUP2 0x406326 +#define HOOKPOS_CWorld_LOD_SETUP 0x406224 +#define HOOKPOS_CWorld_LOD_SETUP2 0x406326 DWORD CALL_CWorld_LODSETUP = 0x404C90; -#define HOOKPOS_CBuilding_DTR 0x404180 +#define HOOKPOS_CBuilding_DTR 0x404180 DWORD JMP_CBuilding_DTR = 0x535E90; -#define HOOKPOS_CDummy_DTR 0x532566 +#define HOOKPOS_CDummy_DTR 0x532566 DWORD JMP_CDummy_DTR = 0x535E90; -#define HOOKPOS_CObject_DTR 0x59F680 +#define HOOKPOS_CObject_DTR 0x59F680 DWORD JMP_CObject_DTR = 0x59F686; -#define HOOKPOS_AddBuildingInstancesToWorld_CWorldAdd 0x5B5348 +#define HOOKPOS_AddBuildingInstancesToWorld_CWorldAdd 0x5B5348 DWORD JMP_CWorld_Add_AddBuildingInstancesToWorld_CALL_CWorldAdd = 0x563220; DWORD RETURN_AddBuildingInstancesToWorld_CWorldAdd = 0x5B534D; -#define HOOKPOS_CWorld_Remove_CPopulation_ConvertToDummyObject 0x6146F8 +#define HOOKPOS_CWorld_Remove_CPopulation_ConvertToDummyObject 0x6146F8 -#define HOOKPOS_CWorld_ADD_CPopulation_ConvertToRealObject 0x6145C7 +#define HOOKPOS_CWorld_ADD_CPopulation_ConvertToRealObject 0x6145C7 DWORD JMP_CWorld_Add_CPopulation_ConvertToRealObject_Retn = 0x6145CC; DWORD JMP_CWorld_Add_CPopulation_ConvertToRealObject_CallCWorldAdd = 0x563220; -#define HOOKPOS_ConvertToObject_CPopulationManageDummy 0x616091 +#define HOOKPOS_ConvertToObject_CPopulationManageDummy 0x616091 DWORD CALL_Convert_To_Real_Object_CPopulation_ManageDummy = 0x614580; DWORD JMP_RETN_Called_CPopulation_ManageDummy = 0x616097; DWORD JMP_RETN_Cancel_CPopulation_ManageDummy = 0x616098; -#define HOOKPOS_CWorld_ADD_CPopulation_ConvertToDummyObject 0x61470C +#define HOOKPOS_CWorld_ADD_CPopulation_ConvertToDummyObject 0x61470C DWORD CALL_CWorld_Add_CPopulation_ConvertToDummyObject = 0x563220; DWORD JMP_RETN_Called_CPopulation_ConvertToDummyObject = 0x614712; DWORD JMP_RETN_Cancelled_CPopulation_ConvertToDummyObject = 0x614715; -#define HOOKPOS_CEntity_IsOnScreen_FixObjectsScale 0x534575 +#define HOOKPOS_CEntity_IsOnScreen_FixObjectsScale 0x534575 DWORD JMP_CEntity_IsOnScreen_FixObjectsScale = 0x53457C; -#define HOOKPOS_CClothes_RebuildPlayer 0x5A82C0 +#define HOOKPOS_CClothes_RebuildPlayer 0x5A82C0 DWORD RETURN_CClothes_RebuildPlayera = 0x5A82C8; DWORD RETURN_CClothes_RebuildPlayerb = 0x5A837F; -#define HOOKPOS_CProjectileInfo_FindPlayerPed 0x739321 -#define HOOKPOS_CProjectileInfo_FindPlayerVehicle 0x739570 +#define HOOKPOS_CProjectileInfo_FindPlayerPed 0x739321 +#define HOOKPOS_CProjectileInfo_FindPlayerVehicle 0x739570 -#define HOOKPOS_CHeli_ProcessHeliKill 0x6DB201 +#define HOOKPOS_CHeli_ProcessHeliKill 0x6DB201 DWORD RETURN_CHeli_ProcessHeliKill_RETN_Cancel = 0x6DB9E0; DWORD RETURN_CHeli_ProcessHeliKill_RETN_Cont_Zero = 0x6DB207; DWORD RETURN_CHeli_ProcessHeliKill_6DB437h = 0x6DB437; -#define HOOKPOS_CObject_ProcessBreak 0x5A0F0F +#define HOOKPOS_CObject_ProcessBreak 0x5A0F0F DWORD RETURN_CObject_ProcessBreak = 0x5A0F14; -#define HOOKPOS_CObject_ProcessDamage 0x5A0E0D +#define HOOKPOS_CObject_ProcessDamage 0x5A0E0D DWORD RETURN_CObject_ProcessDamage = 0x5A0E13; DWORD RETURN_CObject_ProcessDamage_Cancel = 0x5A1241; -#define HOOKPOS_CObject_ProcessCollision 0x548DC7 +#define HOOKPOS_CObject_ProcessCollision 0x548DC7 DWORD RETURN_CObject_ProcessCollision = 0x548DD1; DWORD JMP_DynamicObject_Cond_Zero = 0x548E98; -#define HOOKPOS_CGlass_WindowRespondsToCollision 0x71BC40 +#define HOOKPOS_CGlass_WindowRespondsToCollision 0x71BC40 DWORD RETURN_CGlass_WindowRespondsToCollision = 0x71BC48; -#define HOOKPOS_CGlass__BreakGlassPhysically 0x71D14B +#define HOOKPOS_CGlass__BreakGlassPhysically 0x71D14B DWORD RETURN_CGlass__BreakGlassPhysically = 0x71D150; -#define HOOKPOS_CGlass_WindowRespondsToExplosion 0x71C255 -DWORD RETURN_CGlass_WindowRespondsToExplosion = 0x71C25A; +#define HOOKPOS_CGlass_WindowRespondsToExplosion 0x71C255 +DWORD RETURN_CGlass_WindowRespondsToExplosion = 0x71C25A; constexpr const DWORD CALL_FROM_CGlass_WindowRespondsToExplosion = 0x71C28E; constexpr const DWORD CALL_FROM_CGlass_WasGlassHitByBullet = 0x71C192; constexpr const DWORD CALL_FROM_CPhysical_ApplyCollision = 0x548F39; constexpr const DWORD CALL_FROM_CPhysical_ApplyCollision_2 = 0x5490AE; constexpr const DWORD CALL_FROM_CPhysical_ApplySoftCollision = 0x54A816; -#define HOOKPOS_FxManager_c__DestroyFxSystem 0x4A989A +#define HOOKPOS_FxManager_c__DestroyFxSystem 0x4A989A -#define HOOKPOS_CTaskSimplyGangDriveBy__ProcessPed 0x62D5A7 +#define HOOKPOS_CTaskSimplyGangDriveBy__ProcessPed 0x62D5A7 DWORD RETURN_CTaskSimplyGangDriveBy__ProcessPed = 0x62D5AC; #define HOOKPOS_CAERadioTrackManager__ChooseMusicTrackIndex 0x4EA296 DWORD RETURN_CAERadioTrackManager__ChooseMusicTrackIndex = 0x4EA2A0; DWORD RETURN_CAERadioTrackManager__ChooseMusicTrackIndex_Regenerate = 0x04EA286; -#define HOOKPOS_CAEVEhicleAudioEntity__ProcessDummyHeli 0x4FE9B9 +#define HOOKPOS_CAEVEhicleAudioEntity__ProcessDummyHeli 0x4FE9B9 DWORD RETURN_CAEVEhicleAudioEntity__ProcessDummyHeli = 0x4FEDFB; DWORD dwFUNC_CAEVehicleAudioEntity__ProcessAIHeli = FUNC_CAEVehicleAudioEntity__ProcessAIHeli; -#define HOOKPOS_CAEVEhicleAudioEntity__ProcessDummyProp 0x4FD96D +#define HOOKPOS_CAEVEhicleAudioEntity__ProcessDummyProp 0x4FD96D DWORD RETURN_CAEVEhicleAudioEntity__ProcessDummyProp = 0x4FDFAB; DWORD dwFUNC_CAEVehicleAudioEntity__ProcessAIProp = FUNC_CAEVehicleAudioEntity__ProcessAIProp; -#define HOOKPOS_CTaskSimpleSwim_ProcessSwimmingResistance 0x68A4EF +#define HOOKPOS_CTaskSimpleSwim_ProcessSwimmingResistance 0x68A4EF DWORD RETURN_CTaskSimpleSwim_ProcessSwimmingResistance = 0x68A50E; const DWORD HOOKPOS_Idle_CWorld_ProcessPedsAfterPreRender = 0x53EA03; const DWORD RETURN_Idle_CWorld_ProcessPedsAfterPreRender = 0x53EA08; -#define HOOKPOS_CAEAmbienceTrackManager__UpdateAmbienceTrackAndVolume_StartRadio 0x4D7198 -#define HOOKPOS_CAEAmbienceTrackManager__UpdateAmbienceTrackAndVolume_StopRadio 0x4D71E7 +#define HOOKPOS_CAEAmbienceTrackManager__UpdateAmbienceTrackAndVolume_StartRadio 0x4D7198 +#define HOOKPOS_CAEAmbienceTrackManager__UpdateAmbienceTrackAndVolume_StopRadio 0x4D71E7 #define HOOKPOS_CAutomobile__dmgDrawCarCollidingParticles 0x6A6FF0 @@ -320,13 +320,13 @@ bool bTrafficLightsBlocked = false; bool bInteriorSoundsEnabled = true; bool bInteriorFurnitureStates[5] = {true, true, true, true, true}; -bool bUsingCustomSkyGradient = false; -BYTE ucSkyGradientTopR = 0; -BYTE ucSkyGradientTopG = 0; -BYTE ucSkyGradientTopB = 0; -BYTE ucSkyGradientBottomR = 0; -BYTE ucSkyGradientBottomG = 0; -BYTE ucSkyGradientBottomB = 0; +bool bUsingCustomSkyGradient = false; +BYTE ucSkyGradientTopR = 0; +BYTE ucSkyGradientTopG = 0; +BYTE ucSkyGradientTopB = 0; +BYTE ucSkyGradientBottomR = 0; +BYTE ucSkyGradientBottomG = 0; +BYTE ucSkyGradientBottomB = 0; bool bUsingCustomAmbientColor = false; float fAmbientColorR = 0.0F; @@ -365,22 +365,22 @@ extern bool bWeaponFire; float fDuckingHealthThreshold; static const std::array shadowAddr{ - 0x6FAD5D, // CRegisteredCorona::Update - 0x7041DB, // CPostEffects::Fog - 0x7085A9, // CShadows::RenderStaticShadows - 0x709B2F, // CShadows::CastShadowEntityXY - 0x709B8E, // CShadows::CastShadowEntityXY - 0x709BC7, // CShadows::CastShadowEntityXY - 0x709BF6, // CShadows::CastShadowEntityXY - 0x709C93, // CShadows::CastShadowEntityXY - 0x709E9E, // IntersectEntityRenderTriangleCB - 0x709EBC, // IntersectEntityRenderTriangleCB - 0x709ED7, // IntersectEntityRenderTriangleCB - 0x70B221, // CShadows::RenderStoredShadows - 0x70B373, // CShadows::RenderStoredShadows - 0x70B4D1, // CShadows::RenderStoredShadows - 0x70B635, // CShadows::RenderStoredShadows - 0x73A48F // CWeapon::AddGunshell + 0x6FAD5D, // CRegisteredCorona::Update + 0x7041DB, // CPostEffects::Fog + 0x7085A9, // CShadows::RenderStaticShadows + 0x709B2F, // CShadows::CastShadowEntityXY + 0x709B8E, // CShadows::CastShadowEntityXY + 0x709BC7, // CShadows::CastShadowEntityXY + 0x709BF6, // CShadows::CastShadowEntityXY + 0x709C93, // CShadows::CastShadowEntityXY + 0x709E9E, // IntersectEntityRenderTriangleCB + 0x709EBC, // IntersectEntityRenderTriangleCB + 0x709ED7, // IntersectEntityRenderTriangleCB + 0x70B221, // CShadows::RenderStoredShadows + 0x70B373, // CShadows::RenderStoredShadows + 0x70B4D1, // CShadows::RenderStoredShadows + 0x70B635, // CShadows::RenderStoredShadows + 0x73A48F // CWeapon::AddGunshell }; PreContextSwitchHandler* m_pPreContextSwitchHandler = NULL; @@ -416,7 +416,7 @@ DrivebyAnimationHandler* m_pDrivebyAnimationHandler = NULL; AudioZoneRadioSwitchHandler* m_pAudioZoneRadioSwitchHandler = NULL; CEntitySAInterface* dwSavedPlayerPointer = 0; -CEntitySAInterface* activeEntityForStreaming = 0; // the entity that the streaming system considers active +CEntitySAInterface* activeEntityForStreaming = 0; // the entity that the streaming system considers active void HOOK_FindPlayerCoors(); void HOOK_FindPlayerCentreOfWorld(); @@ -584,7 +584,7 @@ CMultiplayerSA::CMultiplayerSA() m_pProjectileStopHandler = NULL; MemSetFast(&localStatsData, 0, sizeof(CStatsData)); - localStatsData.StatTypesFloat[24] = 569.0f; // Max Health + localStatsData.StatTypesFloat[24] = 569.0f; // Max Health m_fAircraftMaxHeight = 800.0f; @@ -741,7 +741,7 @@ void CMultiplayerSA::InitHooks() HookInstall(HOOKPOS_CObject_ProcessCollision, (DWORD)HOOK_CObject_ProcessCollision, 10); HookInstall(HOOKPOS_CGlass_WindowRespondsToCollision, (DWORD)HOOK_CGlass_WindowRespondsToCollision, 8); HookInstall(HOOKPOS_CGlass__BreakGlassPhysically, (DWORD)HOOK_CGlass__BreakGlassPhysically, 5); - + // Post-destruction hook for FxSystems HookInstall(HOOKPOS_FxManager_c__DestroyFxSystem, (DWORD)HOOK_FxManager_c__DestroyFxSystem, 5); @@ -966,11 +966,11 @@ void CMultiplayerSA::InitHooks() MemSet((LPVOID)0x6B5B17, 0x90, 6); // Increase VehicleStruct pool size - MemPut(0x5B8342 + 0, 0x33); // xor eax, eax + MemPut(0x5B8342 + 0, 0x33); // xor eax, eax MemPut(0x5B8342 + 1, 0xC0); - MemPut(0x5B8342 + 2, 0xB0); // mov al, 0xFF + MemPut(0x5B8342 + 2, 0xB0); // mov al, 0xFF MemPut(0x5B8342 + 3, 0xFF); - MemPut(0x5B8342 + 4, 0x8B); // mov edi, eax + MemPut(0x5B8342 + 4, 0x8B); // mov edi, eax MemPut(0x5B8342 + 5, 0xF8); /* @@ -1092,7 +1092,7 @@ void CMultiplayerSA::InitHooks() // Prevent TRAINS spawning with PEDs MemPut(0x6F7865, 0xEB); MemPut(0x6F8E7B, 0xE9); - MemPut(0x6F8E7C, 0x109); // jmp to 0x6F8F89 + MemPut(0x6F8E7C, 0x109); // jmp to 0x6F8F89 MemPut(0x6F8E80, 0x90); // DISABLE PLANES @@ -1299,8 +1299,8 @@ void CMultiplayerSA::InitHooks() MemPut(0x748B0E, 5); // Skip copyright screen - MemSet((void*)0x748C2B, 0x90, 5); // call CLoadingScreen::DoPCTitleFadeIn - MemSet((void*)0x748C9A, 0x90, 5); // call CLoadingScreen::DoPCTitleFadeOut + MemSet((void*)0x748C2B, 0x90, 5); // call CLoadingScreen::DoPCTitleFadeIn + MemSet((void*)0x748C9A, 0x90, 5); // call CLoadingScreen::DoPCTitleFadeOut // Force triggering of the damage event for players on fire MemSet((void*)0x633695, 0x90, 6); @@ -1377,7 +1377,7 @@ void CMultiplayerSA::InitHooks() // Disable the loading screen tune. MemSet((void*)0x748CF6, 0x90, 5); - + // Do not render the loading screen. MemSet((void*)0x590D7C, 0x90, 5); MemSet((void*)0x590DB3, 0x90, 5); @@ -1501,8 +1501,8 @@ void CMultiplayerSA::InitHooks() MemSetFast((void*)0x60D861, 0x90, 14); // Allow water cannon to hit objects and players visually - MemSet((void*)0x72925D, 0x1, 1); // objects - MemSet((void*)0x729263, 0x1, 1); // players + MemSet((void*)0x72925D, 0x1, 1); // objects + MemSet((void*)0x729263, 0x1, 1); // players // Allow crouching with 1HP MemPut((void*)0x6943AD, &fDuckingHealthThreshold); @@ -1718,8 +1718,8 @@ void CMultiplayerSA::ResetColorFilter() { if (*(BYTE*)0x7036EC == 0xB8) { - static BYTE DefaultBytes[5] = {0xC1, 0xE0, 0x08, 0x0B, 0xC1}; // shl eax, 8 - // or eax, ecx + static BYTE DefaultBytes[5] = {0xC1, 0xE0, 0x08, 0x0B, 0xC1}; // shl eax, 8 + // or eax, ecx MemCpy((void*)0x7036EC, DefaultBytes, sizeof(DefaultBytes)); MemCpy((void*)0x70373D, DefaultBytes, sizeof(DefaultBytes)); } @@ -1732,14 +1732,14 @@ void CMultiplayerSA::SetColorFilter(DWORD dwPass0Color, DWORD dwPass1Color) // Update a pass0 color if needed if (!bEnabled || *(DWORD*)0x7036ED != dwPass0Color) { - MemPut(0x7036EC, 0xB8); // mov eax + MemPut(0x7036EC, 0xB8); // mov eax MemPut(0x7036ED, dwPass0Color); } // Update a pass1 color if needed if (!bEnabled || *(DWORD*)0x70373E != dwPass1Color) { - MemPut(0x70373D, 0xB8); // mov eax + MemPut(0x70373D, 0xB8); // mov eax MemPut(0x70373E, dwPass1Color); } } @@ -1748,7 +1748,8 @@ void CMultiplayerSA::GetColorFilter(DWORD& dwPass0Color, DWORD& dwPass1Color, bo { // GTASA PC has 2 color filters, one of them is static color filter, and another one is blended by time cycle bool bUseTimeCycle = *(BYTE*)0x7036EC == 0xC1; - if (bUseTimeCycle || isOriginal){ //If we are using color filter from time cycle or we specified color filter from time cycle + if (bUseTimeCycle || isOriginal) + { // If we are using color filter from time cycle or we specified color filter from time cycle SColorRGBA pass0SColor(*(float*)0xB7C518, *(float*)0xB7C51C, *(float*)0xB7C520, *(float*)0xB7C524); SColorRGBA pass1SColor(*(float*)0xB7C528, *(float*)0xB7C52C, *(float*)0xB7C530, *(float*)0xB7C534); dwPass0Color = pass0SColor.ulARGB; @@ -1781,17 +1782,17 @@ void DoSetHeatHazePokes(const SHeatHazeSettings& settings, int iHourStart, int i MemPutFast(0xC402BA, settings.bInsideBuilding); if (bAllowAutoTypeChange) - MemPut(0x701455, 0x83); // sub + MemPut(0x701455, 0x83); // sub else - MemPut(0x701455, 0xC3); // retn + MemPut(0x701455, 0xC3); // retn } void CMultiplayerSA::SetHeatHaze(const SHeatHazeSettings& settings) { if (settings.ucIntensity != 0) - DoSetHeatHazePokes(settings, 0, 24, 1.0f, 1.0f, false); // 24 hrs + DoSetHeatHazePokes(settings, 0, 24, 1.0f, 1.0f, false); // 24 hrs else - DoSetHeatHazePokes(settings, 38, 39, 1.0f, 1.0f, false); // 0 hrs + DoSetHeatHazePokes(settings, 38, 39, 1.0f, 1.0f, false); // 0 hrs m_bHeatHazeCustomized = true; ApplyHeatHazeEnabled(); @@ -1810,7 +1811,7 @@ void CMultiplayerSA::ResetHeatHaze() settings.usRenderSizeY = 0x55; settings.bInsideBuilding = false; - DoSetHeatHazePokes(settings, 10, 19, 0.05f, 1.0f, true); // defaults + DoSetHeatHazePokes(settings, 10, 19, 0.05f, 1.0f, true); // defaults m_bHeatHazeCustomized = false; ApplyHeatHazeEnabled(); @@ -3647,7 +3648,7 @@ void CRunningScript_Process() pCamera->SetFadeColor(0, 0, 0); pCamera->Fade(0.0f, FADE_OUT); - DWORD dwFunc = 0x409D10; // RequestSpecialModel + DWORD dwFunc = 0x409D10; // RequestSpecialModel char szModelName[64]; strcpy(szModelName, "player"); @@ -3663,7 +3664,7 @@ void CRunningScript_Process() } // clang-format on - dwFunc = 0x40EA10; // load all requested models + dwFunc = 0x40EA10; // load all requested models // clang-format off __asm { @@ -3673,7 +3674,7 @@ void CRunningScript_Process() } // clang-format on - dwFunc = 0x60D790; // setup player ped + dwFunc = 0x60D790; // setup player ped // clang-format off __asm { @@ -3704,7 +3705,7 @@ void CRunningScript_Process() } // clang-format on */ - dwFunc = 0x420B80; // set position + dwFunc = 0x420B80; // set position fX = 2488.562f; fY = -1666.864f; fZ = 12.8757f; @@ -3791,7 +3792,7 @@ static void __declspec(naked) HOOK_CRunningScript_Process() // clang-format on } -static CVehicleSAInterface* pDerailingTrain = NULL; +static CVehicleSAInterface* pDerailingTrain = NULL; static void __declspec(naked) HOOK_CTrain_ProcessControl_Derail() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -3928,7 +3929,7 @@ static void SetVehicleAlpha() bEntityHasAlpha = false; } -static DWORD dwCVehicle_SetupRender_ret = 0x6D6517; +static DWORD dwCVehicle_SetupRender_ret = 0x6D6517; static void __declspec(naked) HOOK_CVehicle_SetupRender() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -3954,7 +3955,7 @@ static void __declspec(naked) HOOK_CVehicle_SetupRender() // clang-format on } -static DWORD dwCVehicle_ResetAfterRender_ret = 0x6D0E43; +static DWORD dwCVehicle_ResetAfterRender_ret = 0x6D0E43; static void __declspec(naked) HOOK_CVehicle_ResetAfterRender() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -4101,23 +4102,23 @@ static void __declspec(naked) HOOK_EndWorldColors() { MTA_VERIFY_HOOK_LOCAL_SIZE; - // clang-format off + // clang-format off __asm { call DoEndWorldColorsPokes ret } - // clang-format on + // clang-format on } // This hook modifies the code in CWorld::ProcessVerticalLineSectorList to // force it to also check the world objects, so we can get a reliable ground // position on custom object maps. This will make getGroundPosition, jetpacks // and molotovs to work. -static DWORD dwObjectsChecked = 0; -static DWORD dwProcessVerticalKeepLooping = 0x5632D1; -static DWORD dwProcessVerticalEndLooping = 0x56335F; -static DWORD dwGlobalListOfObjects = 0xB9ACCC; +static DWORD dwObjectsChecked = 0; +static DWORD dwProcessVerticalKeepLooping = 0x5632D1; +static DWORD dwProcessVerticalEndLooping = 0x56335F; +static DWORD dwGlobalListOfObjects = 0xB9ACCC; static void __declspec(naked) HOOK_CWorld_ProcessVerticalLineSectorList() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -4148,9 +4149,9 @@ static void __declspec(naked) HOOK_CWorld_ProcessVerticalLineSectorList() } // Hook to detect when a player is choking -static DWORD dwChokingChoke = 0x4C05C1; -static DWORD dwChokingDontchoke = 0x4C0620; -static unsigned char ucChokingWeaponType = 0; +static DWORD dwChokingChoke = 0x4C05C1; +static DWORD dwChokingDontchoke = 0x4C0620; +static unsigned char ucChokingWeaponType = 0; static void __declspec(naked) HOOK_ComputeDamageResponse_StartChoking() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -4529,7 +4530,7 @@ static void __declspec(naked) HOOK_CollisionStreamRead() } } -unsigned char ucDesignatedLightState = 0; +unsigned char ucDesignatedLightState = 0; static void __declspec(naked) HOOK_CTrafficLights_GetPrimaryLightState() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -4543,17 +4544,17 @@ static void __declspec(naked) HOOK_CTrafficLights_GetPrimaryLightState() if (ucTrafficLightState == 0 || ucTrafficLightState == 5 || ucTrafficLightState == 8) { - ucDesignatedLightState = 0; // Green + ucDesignatedLightState = 0; // Green } else if (ucTrafficLightState == 1 || ucTrafficLightState == 6 || ucTrafficLightState == 7) { - ucDesignatedLightState = 1; // Amber + ucDesignatedLightState = 1; // Amber } else if (ucTrafficLightState == 9) { - ucDesignatedLightState = 4; // Off + ucDesignatedLightState = 4; // Off } - else ucDesignatedLightState = 2; // Red + else ucDesignatedLightState = 2; // Red // clang-format off __asm @@ -4578,17 +4579,17 @@ static void __declspec(naked) HOOK_CTrafficLights_GetSecondaryLightState() if (ucTrafficLightState == 3 || ucTrafficLightState == 5 || ucTrafficLightState == 7) { - ucDesignatedLightState = 0; // Green + ucDesignatedLightState = 0; // Green } else if (ucTrafficLightState == 4 || ucTrafficLightState == 6 || ucTrafficLightState == 8) { - ucDesignatedLightState = 1; // Amber + ucDesignatedLightState = 1; // Amber } else if (ucTrafficLightState == 9) { - ucDesignatedLightState = 4; // Off + ucDesignatedLightState = 4; // Off } - else ucDesignatedLightState = 2; // Red + else ucDesignatedLightState = 2; // Red // clang-format off __asm @@ -4615,8 +4616,14 @@ static void __declspec(naked) HOOK_CTrafficLights_DisplayActualLight() { ucDesignatedLightState = 0; } - else if (ucTrafficLightState == 9) { ucDesignatedLightState = 1; } - else { ucDesignatedLightState = 2; } + else if (ucTrafficLightState == 9) + { + ucDesignatedLightState = 1; + } + else + { + ucDesignatedLightState = 2; + } // clang-format off __asm @@ -4810,7 +4817,7 @@ void _cdecl CPhysical_ApplyGravity(DWORD dwThis) } } -const float kfTimeStepOrg = 5.0f / 3.0f; +const float kfTimeStepOrg = 5.0f / 3.0f; static void __declspec(naked) HOOK_CVehicle_ApplyBoatWaterResistance() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5326,7 +5333,7 @@ static void Post_CGame_Process() TIMING_CHECKPOINT("-CWorld_Process"); } -DWORD CALL_CWorld_Process = 0x5684a0; +DWORD CALL_CWorld_Process = 0x5684a0; static void __declspec(naked) HOOK_CGame_Process() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5383,7 +5390,7 @@ static void IdleWithTiming() TIMING_CHECKPOINT("-Idle"); } -DWORD CALL_CGame_Process = 0x53BEE0; +DWORD CALL_CGame_Process = 0x53BEE0; static void __declspec(naked) HOOK_Idle() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5490,25 +5497,25 @@ void vehicle_lights_init() #else -#define HOOKPOS_CVehicle_DoVehicleLights 0x6e1a60 + #define HOOKPOS_CVehicle_DoVehicleLights 0x6e1a60 DWORD RETURN_CVehicle_DoVehicleLights = 0x6e1a68; -#define HOOKPOS_CVehicle_DoHeadLightBeam_1 0x6E0E20 + #define HOOKPOS_CVehicle_DoHeadLightBeam_1 0x6E0E20 DWORD RETURN_CVehicle_DoHeadLightBeam_1 = 0x6E0E26; -#define HOOKPOS_CVehicle_DoHeadLightBeam_2 0x6E13A4 + #define HOOKPOS_CVehicle_DoHeadLightBeam_2 0x6E13A4 DWORD RETURN_CVehicle_DoHeadLightBeam_2 = 0x6E13AE; -#define HOOKPOS_CVehicle_DoHeadLightEffect_1 0x6E0D01 + #define HOOKPOS_CVehicle_DoHeadLightEffect_1 0x6E0D01 DWORD RETURN_CVehicle_DoHeadLightEffect_1 = 0x6E0D09; -#define HOOKPOS_CVehicle_DoHeadLightEffect_2 0x6E0DF7 + #define HOOKPOS_CVehicle_DoHeadLightEffect_2 0x6E0DF7 DWORD RETURN_CVehicle_DoHeadLightEffect_2 = 0x6E0DFF; -#define HOOKPOS_CVehicle_DoHeadLightReflectionTwin 0x6E170F + #define HOOKPOS_CVehicle_DoHeadLightReflectionTwin 0x6E170F DWORD RETURN_CVehicle_DoHeadLightReflectionTwin = 0x6E1717; -#define HOOKPOS_CVehicle_DoHeadLightReflectionSingle 0x6E15E2 + #define HOOKPOS_CVehicle_DoHeadLightReflectionSingle 0x6E15E2 DWORD RETURN_CVehicle_DoHeadLightReflectionSingle = 0x6E15EA; void HOOK_CVehicle_DoVehicleLights(); @@ -5536,7 +5543,7 @@ void vehicle_lights_init() MemPut(0x6E1D4F, 2); } -CVehicleSAInterface* pLightsVehicleInterface = NULL; +CVehicleSAInterface* pLightsVehicleInterface = NULL; static void __declspec(naked) HOOK_CVehicle_DoVehicleLights() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5569,7 +5576,7 @@ void CVehicle_GetHeadLightColor(CVehicleSAInterface* pInterface, float ulHeadLightB = (unsigned char)std::min(255.f, color.B * (1 / 255.0f) * fB); } -CVehicleSAInterface* pHeadLightBeamVehicleInterface = NULL; +CVehicleSAInterface* pHeadLightBeamVehicleInterface = NULL; static void __declspec(naked) HOOK_CVehicle_DoHeadLightBeam_1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5625,7 +5632,7 @@ static void __declspec(naked) HOOK_CVehicle_DoHeadLightBeam_2() // clang-format on } -DWORD dwCCoronas_RegisterCorona = 0x6FC580; +DWORD dwCCoronas_RegisterCorona = 0x6FC580; static void __declspec(naked) HOOK_CVehicle_DoHeadLightEffect_1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -5692,7 +5699,7 @@ static void __declspec(naked) HOOK_CVehicle_DoHeadLightEffect_2() // clang-format on } -DWORD dwCShadows_StoreCarLightShadow = 0x70C500; +DWORD dwCShadows_StoreCarLightShadow = 0x70C500; static void __declspec(naked) HOOK_CVehicle_DoHeadLightReflectionTwin() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -6072,7 +6079,7 @@ void CEventHandler_ComputeKnockOffBikeResponse() pEvent->Destroy(); } -DWORD dw_CEventDamage_AffectsPed = 0x4b35a0; +DWORD dw_CEventDamage_AffectsPed = 0x4b35a0; static void __declspec(naked) HOOK_CEventHandler_ComputeKnockOffBikeResponse() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -6404,7 +6411,7 @@ void _cdecl CheckMatrix(float* pMatrix) pMatrix[6] = 0.0f; pMatrix[8] = 0.0f; pMatrix[9] = 0.0f; - pMatrix[10] = scale; // This one was missing for a long time (pre-Sept 2025) + pMatrix[10] = scale; // This one was missing for a long time (pre-Sept 2025) pMatrix[12] = 0.0f; pMatrix[13] = 0.0f; pMatrix[14] = 1.0f; @@ -6556,7 +6563,7 @@ void* SetModelSuspensionLinesToVehiclePrivate(CVehicleSAInterface* pVehicleIntf) { // Set the per-model suspension line data of the vehicle's model to the per-vehicle // suspension line data so that collision processing will use that instead. - CVehicle* pVehicle = pVehicleIntf->m_pVehicle; + CVehicle* pVehicle = pVehicleIntf->m_pVehicle; if (!pVehicle) return nullptr; @@ -6930,8 +6937,7 @@ static void __declspec(naked) HOOK_ConvertToObject_CPopulationManageDummy() pop ecx mov pLODInterface, ecx pushad - } - // clang-format on + } // clang-format on RemoveObjectIfNeeded(); // clang-format off __asm @@ -7079,7 +7085,7 @@ static void __declspec(naked) Hook_CDummy_DTR() // clang-format on } -DWORD dwObjectVtbl = 0x866F60; +DWORD dwObjectVtbl = 0x866F60; static void __declspec(naked) Hook_CObject_DTR() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7102,8 +7108,8 @@ static void __declspec(naked) Hook_CObject_DTR() // clang-format on } -static DWORD dwEntityVtbl; -static DWORD dwMultResult; +static DWORD dwEntityVtbl; +static DWORD dwMultResult; static void __declspec(naked) HOOK_CEntity_IsOnScreen_FixObjectScale() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7130,8 +7136,8 @@ static void __declspec(naked) HOOK_CEntity_IsOnScreen_FixObjectScale() } // clang-format on -IsOnScreen_IsObject: - // clang-format off + IsOnScreen_IsObject : + // clang-format off __asm { popad @@ -7214,8 +7220,8 @@ void CMultiplayerSA::SetVehicleEngineAutoStartEnabled(bool enabled) } else { - MemSet((void*)0x64BC03, 0x90, 5); // prevent vehicle engine from turning on (driver enter) - MemCpy((void*)0x6C4EA9, "\xE9\x15\x03\x00", 4); // prevent aircraft engine from turning off (driver exit) + MemSet((void*)0x64BC03, 0x90, 5); // prevent vehicle engine from turning on (driver enter) + MemCpy((void*)0x6C4EA9, "\xE9\x15\x03\x00", 4); // prevent aircraft engine from turning off (driver exit) } } @@ -7427,7 +7433,7 @@ static void __declspec(naked) HOOK_CObject_ProcessCollision() } } -DWORD WindowRespondsToCollision_CalledFrom = 0; +DWORD WindowRespondsToCollision_CalledFrom = 0; static void __declspec(naked) HOOK_CGlass_WindowRespondsToCollision() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7476,7 +7482,7 @@ static void __declspec(naked) HOOK_CGlass_WindowRespondsToCollision() } // clang-format on - if (!pObjectAttacker || (pObjectAttacker && !pObjectAttacker->m_pRwObject)) // WasGlassHitByBullet called from CBulletInfo::Update + if (!pObjectAttacker || (pObjectAttacker && !pObjectAttacker->m_pRwObject)) // WasGlassHitByBullet called from CBulletInfo::Update { // clang-format off __asm @@ -7501,7 +7507,7 @@ static void __declspec(naked) HOOK_CGlass_WindowRespondsToCollision() // clang-format on } - if (pObjectAttacker && !pObjectAttacker->m_pRwObject) // Still wrong? + if (pObjectAttacker && !pObjectAttacker->m_pRwObject) // Still wrong? pObjectAttacker = nullptr; if (TriggerObjectBreakEvent()) @@ -7528,7 +7534,7 @@ static void __declspec(naked) HOOK_CGlass_WindowRespondsToCollision() } // Called when glass object is being broken by ped melee attack -DWORD dummy_404350 = 0x404350; +DWORD dummy_404350 = 0x404350; static void __declspec(naked) HOOK_CGlass__BreakGlassPhysically() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7620,7 +7626,7 @@ void CTaskSimpleGangDriveBy__ProcessPed() *pRequiredAnim = m_pDrivebyAnimationHandler(*pRequiredAnim, requiredAnimGroup); } -DWORD RETURN_CTaskSimpleGangDriveBy_ProcessPed_Cancel = 0x62D5C1; +DWORD RETURN_CTaskSimpleGangDriveBy_ProcessPed_Cancel = 0x62D5C1; static void __declspec(naked) HOOK_CTaskSimpleGangDriveBy__ProcessPed() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7655,17 +7661,17 @@ BYTE bTrackID = 0; DWORD dwNumberOfTracks = 0; const DWORD pTrackNumbers[] = { - 0x2, // radio off, somewhere 2 is subtracted from this so that's why it's 2 - 0xB, // playback fm - 0xF, // k-rose - 0xF, // k-dst - 0xE, // bounce fm - 0x10, // sf-ur - 0xE, // rls - 0xD, // radio x - 0xD, // csr - 0xE, // k-jah - 0xC, // master sounds + 0x2, // radio off, somewhere 2 is subtracted from this so that's why it's 2 + 0xB, // playback fm + 0xF, // k-rose + 0xF, // k-dst + 0xE, // bounce fm + 0x10, // sf-ur + 0xE, // rls + 0xD, // radio x + 0xD, // csr + 0xE, // k-jah + 0xC, // master sounds 0x1F, }; @@ -7903,7 +7909,7 @@ static void __declspec(naked) HOOK_CAEVehicleAudioEntity__ProcessDummyProp() // clang-format on } -const float kfTimeStepOriginal = 1.66f; +const float kfTimeStepOriginal = 1.66f; static void __declspec(naked) HOOK_CTaskSimpleSwim_ProcessSwimmingResistance() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -7968,7 +7974,7 @@ void PostCWorld_ProcessPedsAfterPreRender() } } -const DWORD CWorld_ProcessPedsAfterPreRender = 0x563430; +const DWORD CWorld_ProcessPedsAfterPreRender = 0x563430; static void __declspec(naked) HOOK_Idle_CWorld_ProcessPedsAfterPreRender() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -8047,19 +8053,16 @@ static void AddVehicleColoredDebris(CAutomobileSAInterface* pVehicleInterface, C SColor colors[4]; pVehicle->GetColor(&colors[0], &colors[1], &colors[2], &colors[3], false); - RwColor color = { - static_cast(colors[0].R * pVehicleInterface->m_fLighting), - static_cast(colors[0].G * pVehicleInterface->m_fLighting), - static_cast(colors[0].B * pVehicleInterface->m_fLighting), - 0xFF - }; + RwColor color = {static_cast(colors[0].R * pVehicleInterface->m_fLighting), + static_cast(colors[0].G * pVehicleInterface->m_fLighting), + static_cast(colors[0].B * pVehicleInterface->m_fLighting), 0xFF}; // Fx_c::AddDebris ((void(__thiscall*)(int, CVector&, RwColor&, float, int))0x49F750)(CLASS_CFx, vecPosition, color, 0.06f, count / 100 + 1); } } -const DWORD RETURN_CAutomobile__dmgDrawCarCollidingParticles = 0x6A7081; +const DWORD RETURN_CAutomobile__dmgDrawCarCollidingParticles = 0x6A7081; static void __declspec(naked) HOOK_CAutomobile__dmgDrawCarCollidingParticles() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -8086,7 +8089,7 @@ static void TakePhotograph() g_pCore->InitiateScreenShot(true); } -const DWORD RETURN_CWeapon__TakePhotograph = 0x73C273; +const DWORD RETURN_CWeapon__TakePhotograph = 0x73C273; static void __declspec(naked) HOOK_CWeapon__TakePhotograph() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -8115,18 +8118,18 @@ bool CanEntityCollideWithCamera(CEntitySAInterface* pEntity) switch (pEntity->m_nModelIndex) { // projectiles - case 342: // grenade - case 343: // teargas - case 344: // molotov - case 363: // satchel + case 342: // grenade + case 343: // teargas + case 344: // molotov + case 363: // satchel // vehicle parts - case 374: // car_door - case 375: // car_bumper - case 376: // car_panel - case 377: // car_bonnet - case 378: // car_boot - case 379: // car_wheel + case 374: // car_door + case 375: // car_bumper + case 376: // car_panel + case 377: // car_bonnet + case 378: // car_boot + case 379: // car_wheel return false; } diff --git a/Client/multiplayer_sa/CMultiplayerSA.h b/Client/multiplayer_sa/CMultiplayerSA.h index 2d209976b3c..77e95b4191a 100644 --- a/Client/multiplayer_sa/CMultiplayerSA.h +++ b/Client/multiplayer_sa/CMultiplayerSA.h @@ -19,8 +19,8 @@ #include "CRemoteDataSA.h" class CRemoteDataSA; -#define DEFAULT_NEAR_CLIP_DISTANCE ( 0.3f ) -#define DEFAULT_SHADOWS_OFFSET ( 0.013f ) // GTA default = 0.06f +#define DEFAULT_NEAR_CLIP_DISTANCE (0.3f) +#define DEFAULT_SHADOWS_OFFSET (0.013f) // GTA default = 0.06f enum eRadioStationID { @@ -48,11 +48,11 @@ class CMultiplayerSA : public CMultiplayer CRemoteDataSA* RemoteData; public: -ZERO_ON_NEW + ZERO_ON_NEW -CMultiplayerSA(); -~CMultiplayerSA(); -void InitHooks(); + CMultiplayerSA(); + ~CMultiplayerSA(); + void InitHooks(); void InitHooks_CrashFixHacks(); void Init_13(); void InitHooks_13(); @@ -204,17 +204,17 @@ void InitHooks(); int GetMoonSize(); void ResetMoonSize(); - void GetAmbientColor(float& red, float& green, float& blue) const; - bool SetAmbientColor(float red, float green, float blue); - bool ResetAmbientColor(); + void GetAmbientColor(float& red, float& green, float& blue) const; + bool SetAmbientColor(float red, float green, float blue); + bool ResetAmbientColor(); - void GetAmbientObjectColor(float& red, float& green, float& blue) const; - bool SetAmbientObjectColor(float red, float green, float blue); - bool ResetAmbientObjectColor(); + void GetAmbientObjectColor(float& red, float& green, float& blue) const; + bool SetAmbientObjectColor(float red, float green, float blue); + bool ResetAmbientObjectColor(); - void GetDirectionalColor(float& red, float& green, float& blue) const; - bool SetDirectionalColor(float red, float green, float blue); - bool ResetDirectionalColor(); + void GetDirectionalColor(float& red, float& green, float& blue) const; + bool SetDirectionalColor(float red, float green, float blue); + bool ResetDirectionalColor(); float GetSpriteSize() const; bool SetSpriteSize(float size); @@ -240,13 +240,13 @@ void InitHooks(); bool SetLightsOnGroundBrightness(float brightness); bool ResetLightsOnGroundBrightness(); - void GetLowCloudsColor(int16& red, int16& green, int16& blue) const; - bool SetLowCloudsColor(int16 red, int16 green, int16 blue); - bool ResetLowCloudsColor(); + void GetLowCloudsColor(int16& red, int16& green, int16& blue) const; + bool SetLowCloudsColor(int16 red, int16 green, int16 blue); + bool ResetLowCloudsColor(); - void GetBottomCloudsColor(int16& red, int16& green, int16& blue) const; - bool SetBottomCloudsColor(int16 red, int16 green, int16 blue); - bool ResetBottomCloudsColor(); + void GetBottomCloudsColor(int16& red, int16& green, int16& blue) const; + bool SetBottomCloudsColor(int16 red, int16 green, int16 blue); + bool ResetBottomCloudsColor(); float GetCloudsAlpha1() const; bool SetCloudsAlpha1(float alpha); diff --git a/Client/multiplayer_sa/CMultiplayerSA_1.3.cpp b/Client/multiplayer_sa/CMultiplayerSA_1.3.cpp index 8526cd85e26..ec474ec7ecc 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_1.3.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_1.3.cpp @@ -14,135 +14,135 @@ extern CCoreInterface* g_pCore; -#define FUNC_CPed__RenderTargetMarker 0x60BA80 +#define FUNC_CPed__RenderTargetMarker 0x60BA80 WaterCannonHitHandler* m_pWaterCannonHitHandler = NULL; VehicleFellThroughMapHandler* m_pVehicleFellThroughMapHandler = NULL; -#define HOOKPOS_CEventHitByWaterCannon 0x729899 +#define HOOKPOS_CEventHitByWaterCannon 0x729899 DWORD RETURN_CWaterCannon_PushPeds_RETN = 0x7298A7; DWORD CALL_CEventHitByWaterCannon = 0x4B1290; DWORD RETURN_CWaterCannon_PushPeds_RETN_Cancel = 0x729AEB; void HOOK_CEventHitByWaterCannon(); -#define HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeSingle 0x6AB366 +#define HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeSingle 0x6AB366 DWORD RETN_CVehicle_ProcessStuff_TestSirenTypeSingle = 0x6AB36D; -#define HOOKPOS_CVehicle_ProcessStuff_SetSirenPositionSingle 0x6ABC51 +#define HOOKPOS_CVehicle_ProcessStuff_SetSirenPositionSingle 0x6ABC51 DWORD RETN_CVehicle_ProcessStuff_PostPushSirenPositionSingle = 0x6ABC64; -#define HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeDual 0x6AB382 +#define HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeDual 0x6AB382 DWORD RETN_CVehicle_ProcessStuff_TestSirenTypeDual = 0x6AB389; -#define HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition1 0x6ABA47 +#define HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition1 0x6ABA47 DWORD RETN_CVehicle_ProcessStuff_PostPushSirenPositionDual1 = 0x6ABA5E; -#define HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition2 0x6AB9F7 +#define HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition2 0x6AB9F7 DWORD RETN_CVehicle_ProcessStuff_PostPushSirenPositionDual2 = 0x6ABA07; -#define HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionBlue 0x6BD4C3 +#define HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionBlue 0x6BD4C3 DWORD RETN_CMotorBike_ProcessStuff_PushSirenPositionDualBlue = 0x6BD4DB; -#define HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionRed 0x6BD516 +#define HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionRed 0x6BD516 DWORD RETN_CMotorBike_ProcessStuff_PushSirenPositionDualRed = 0x6BD52C; -#define HOOKPOS_CMotorbike_ProcessStuff_TestVehicleModel 0x6BD40F +#define HOOKPOS_CMotorbike_ProcessStuff_TestVehicleModel 0x6BD40F DWORD RETN_CMotorbike_ProcessStuff_TestVehicleModel = 0x6BD415; -#define HOOKPOS_CVehicle_DoesVehicleUseSiren 0x6D8470 +#define HOOKPOS_CVehicle_DoesVehicleUseSiren 0x6D8470 DWORD RETN_CVehicleDoesVehicleUseSirenRetn = 0x6D8497; -#define HOOKPOS_CVehicle_ProcessStuff_TestCameraPosition 0x6ABC17 +#define HOOKPOS_CVehicle_ProcessStuff_TestCameraPosition 0x6ABC17 DWORD RETN_CVehicle_ProcessStuff_TestCameraPosition = 0x6ABC1C; DWORD RETN_CVehicle_ProcessStuff_TestCameraPosition2 = 0x6ABC1E; -#define HOOKPOS_CVehicleAudio_ProcessSirenSound1 0x501FC2 +#define HOOKPOS_CVehicleAudio_ProcessSirenSound1 0x501FC2 DWORD RETN_CVehicleAudio_ProcessSirenSound1 = 0x501FC7; -#define HOOKPOS_CVehicleAudio_ProcessSirenSound2 0x502067 +#define HOOKPOS_CVehicleAudio_ProcessSirenSound2 0x502067 DWORD RETN_CVehicleAudio_ProcessSirenSound2 = 0x50206C; -#define HOOKPOS_CVehicleAudio_ProcessSirenSound3 0x5021AE +#define HOOKPOS_CVehicleAudio_ProcessSirenSound3 0x5021AE DWORD RETN_CVehicleAudio_ProcessSirenSound3 = 0x5021B3; -#define HOOKPOS_CVehicleAudio_ProcessSirenSound 0x4F62BB +#define HOOKPOS_CVehicleAudio_ProcessSirenSound 0x4F62BB DWORD RETN_CVehicleAudio_GetVehicleSirenType = 0x4F62C1; -#define HOOKPOS_CVehicle_ProcessStuff_PushRGBPointLights 0x6AB7A5 +#define HOOKPOS_CVehicle_ProcessStuff_PushRGBPointLights 0x6AB7A5 DWORD RETN_CVehicle_ProcessStuff_PushRGBPointLights = 0x6AB7D5; -#define HOOKPOS_CVehicle_ProcessStuff_StartPointLightCode 0x6AB722 +#define HOOKPOS_CVehicle_ProcessStuff_StartPointLightCode 0x6AB722 DWORD RETN_CVehicle_ProcessStuff_StartPointLightCode = 0x6AB729; DWORD RETN_CVehicle_ProcessStuff_IgnorePointLightCode = 0x6AB823; -#define HOOKPOS_CTaskSimpleJetpack_ProcessInput 0x67E7F1 +#define HOOKPOS_CTaskSimpleJetpack_ProcessInput 0x67E7F1 DWORD RETN_CTaskSimpleJetpack_ProcessInputEnable = 0x67E812; DWORD RETN_CTaskSimpleJetpack_ProcessInputDisabled = 0x67E821; -#define HOOKPOS_CTaskSimplePlayerOnFoot_ProcessWeaponFire 0x685ABA +#define HOOKPOS_CTaskSimplePlayerOnFoot_ProcessWeaponFire 0x685ABA DWORD RETN_CTaskSimplePlayerOnFoot_ProcessWeaponFire = 0x685ABF; DWORD RETN_CTaskSimplePlayerOnFoot_ProcessWeaponFire_Call = 0x540670; -#define HOOKPOS_CWorld_RemoveFallenPeds 0x565D0D +#define HOOKPOS_CWorld_RemoveFallenPeds 0x565D0D DWORD RETURN_CWorld_RemoveFallenPeds_Cont = 0x565D13; DWORD RETURN_CWorld_RemoveFallenPeds_Cancel = 0x565E6F; -#define HOOKPOS_CWorld_RemoveFallenCars 0x565F52 +#define HOOKPOS_CWorld_RemoveFallenCars 0x565F52 DWORD RETURN_CWorld_RemoveFallenCars_Cont = 0x565F59; DWORD RETURN_CWorld_RemoveFallenCars_Cancel = 0x56609B; -#define HOOKPOS_CVehicleModelInterface_SetClump 0x4C9606 +#define HOOKPOS_CVehicleModelInterface_SetClump 0x4C9606 DWORD RETURN_CVehicleModelInterface_SetClump = 0x4C9611; -#define HOOKPOS_CBoat_ApplyDamage 0x6F1C32 +#define HOOKPOS_CBoat_ApplyDamage 0x6F1C32 DWORD RETURN_CBoat_ApplyDamage = 0x6F1C3E; -#define HOOKPOS_CProjectile_FixTearGasCrash 0x4C0403 +#define HOOKPOS_CProjectile_FixTearGasCrash 0x4C0403 DWORD RETURN_CProjectile_FixTearGasCrash_Fix = 0x4C05B9; DWORD RETURN_CProjectile_FixTearGasCrash_Cont = 0x4C0409; -#define HOOKPOS_CVehicle_ProcessTyreSmoke_Initial 0x6DE8A2 -#define HOOKPOS_CVehicle_ProcessTyreSmoke_Burnouts 0x6DF197 -#define HOOKPOS_CVehicle_ProcessTyreSmoke_Braking 0x6DECED -#define HOOKPOS_CVehicle_ProcessTyreSmoke_HookAddress 0x6DF308 +#define HOOKPOS_CVehicle_ProcessTyreSmoke_Initial 0x6DE8A2 +#define HOOKPOS_CVehicle_ProcessTyreSmoke_Burnouts 0x6DF197 +#define HOOKPOS_CVehicle_ProcessTyreSmoke_Braking 0x6DECED +#define HOOKPOS_CVehicle_ProcessTyreSmoke_HookAddress 0x6DF308 -#define HOOKPOS_CProjectile_FixExplosionLocation 0x738A77 +#define HOOKPOS_CProjectile_FixExplosionLocation 0x738A77 DWORD RETURN_CProjectile_FixExplosionLocation = 0x738A86; #define HOOKPOS_CPed_RemoveWeaponWhenEnteringVehicle 0x5E6370 DWORD RETURN_CPed_RemoveWeaponWhenEnteringVehicle = 0x5E6379; -void HOOK_CVehicle_ProcessStuff_TestSirenTypeSingle(); -void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionSingle(); -void HOOK_CVehicle_ProcessStuff_TestSirenTypeDual(); -void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualRed(); -void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualBlue(); -void HOOK_CVehicle_DoesVehicleUseSiren(); -void HOOK_CVehicle_ProcessStuff_TestCameraPosition(); -void HOOK_CVehicleAudio_ProcessSirenSound(); -void HOOK_CVehicleAudio_ProcessSirenSound1(); -void HOOK_CVehicleAudio_ProcessSirenSound2(); -void HOOK_CVehicleAudio_ProcessSirenSound3(); -void HOOK_CMotorBike_ProcessStuff_PushSirenPositionBlue(); -void HOOK_CMotorBike_ProcessStuff_PushSirenPositionRed(); -void HOOK_CMotorBike_ProcessStuff_PushSirenPosition2(); -void HOOK_CMotorbike_ProcessStuff_TestVehicleModel(); -void HOOK_CVehicle_ProcessStuff_PushRGBPointLights(); -void HOOK_CVehicle_ProcessStuff_StartPointLightCode(); -void HOOK_CTaskSimpleJetpack_ProcessInput(); -void HOOK_CTaskSimplePlayerOnFoot_ProcessWeaponFire(); -void HOOK_CTaskSimpleJetpack_ProcessInputFixFPS2(); -void HOOK_CWorld_RemoveFallenPeds(); -void HOOK_CWorld_RemoveFallenCars(); -void HOOK_CVehicleModelInterface_SetClump(); -void HOOK_CBoat_ApplyDamage(); -void HOOK_CProjectile_FixTearGasCrash(); -void HOOK_CProjectile_FixExplosionLocation(); -void HOOK_CPed_RemoveWeaponWhenEnteringVehicle(); +void HOOK_CVehicle_ProcessStuff_TestSirenTypeSingle(); +void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionSingle(); +void HOOK_CVehicle_ProcessStuff_TestSirenTypeDual(); +void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualRed(); +void HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualBlue(); +void HOOK_CVehicle_DoesVehicleUseSiren(); +void HOOK_CVehicle_ProcessStuff_TestCameraPosition(); +void HOOK_CVehicleAudio_ProcessSirenSound(); +void HOOK_CVehicleAudio_ProcessSirenSound1(); +void HOOK_CVehicleAudio_ProcessSirenSound2(); +void HOOK_CVehicleAudio_ProcessSirenSound3(); +void HOOK_CMotorBike_ProcessStuff_PushSirenPositionBlue(); +void HOOK_CMotorBike_ProcessStuff_PushSirenPositionRed(); +void HOOK_CMotorBike_ProcessStuff_PushSirenPosition2(); +void HOOK_CMotorbike_ProcessStuff_TestVehicleModel(); +void HOOK_CVehicle_ProcessStuff_PushRGBPointLights(); +void HOOK_CVehicle_ProcessStuff_StartPointLightCode(); +void HOOK_CTaskSimpleJetpack_ProcessInput(); +void HOOK_CTaskSimplePlayerOnFoot_ProcessWeaponFire(); +void HOOK_CTaskSimpleJetpack_ProcessInputFixFPS2(); +void HOOK_CWorld_RemoveFallenPeds(); +void HOOK_CWorld_RemoveFallenCars(); +void HOOK_CVehicleModelInterface_SetClump(); +void HOOK_CBoat_ApplyDamage(); +void HOOK_CProjectile_FixTearGasCrash(); +void HOOK_CProjectile_FixExplosionLocation(); +void HOOK_CPed_RemoveWeaponWhenEnteringVehicle(); void* __cdecl HOOK_CMemoryMgr_MallocAlign(int size, int alignment, int nHint); -void __cdecl HOOK_CMemoryMgr_FreeAlign(void* ptr); +void __cdecl HOOK_CMemoryMgr_FreeAlign(void* ptr); void CMultiplayerSA::Init_13() { @@ -157,18 +157,18 @@ void CMultiplayerSA::InitHooks_13() // Siren hooks HookInstall(HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeSingle, (DWORD)HOOK_CVehicle_ProcessStuff_TestSirenTypeSingle, - 7); // Test siren type is single for a jump + 7); // Test siren type is single for a jump HookInstall(HOOKPOS_CVehicle_ProcessStuff_SetSirenPositionSingle, (DWORD)HOOK_CVehicle_ProcessStuff_PostPushSirenPositionSingle, - 19); // mov before Push for the siren position (overhook so we can get RGBA) + 19); // mov before Push for the siren position (overhook so we can get RGBA) HookInstall(HOOKPOS_CVehicle_ProcessStuff_TestSirenTypeDual, (DWORD)HOOK_CVehicle_ProcessStuff_TestSirenTypeDual, - 7); // test siren type is dual for a jump + 7); // test siren type is dual for a jump HookInstall(HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition1, (DWORD)HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualRed, - 15); // mov before push for the siren position (overhook so we can get RGBA) + 15); // mov before push for the siren position (overhook so we can get RGBA) HookInstall(HOOKPOS_CVehicle_ProcessStuff_PostPushSirenPosition2, (DWORD)HOOK_CVehicle_ProcessStuff_PostPushSirenPositionDualBlue, - 15); // mov before push for the siren position (overhook so we can get RGBA) - HookInstall(HOOKPOS_CVehicle_DoesVehicleUseSiren, (DWORD)HOOK_CVehicle_DoesVehicleUseSiren, 5); // Does vehicle have a siren + 15); // mov before push for the siren position (overhook so we can get RGBA) + HookInstall(HOOKPOS_CVehicle_DoesVehicleUseSiren, (DWORD)HOOK_CVehicle_DoesVehicleUseSiren, 5); // Does vehicle have a siren HookInstall(HOOKPOS_CVehicle_ProcessStuff_TestCameraPosition, (DWORD)HOOK_CVehicle_ProcessStuff_TestCameraPosition, - 5); // Fix for single sirens being 360 degrees + 5); // Fix for single sirens being 360 degrees // Breaks Rear wheel rendering leave for now // HookInstall ( HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionBlue, (DWORD)HOOK_CMotorBike_ProcessStuff_PushSirenPositionBlue, 15 ); // mov before the // push for the sien position (overhook so we can get RGBA) HookInstall ( HOOKPOS_CMotorBike_ProcessStuff_PushSirenPositionRed, @@ -228,7 +228,7 @@ void CMultiplayerSA::InitMemoryCopies_13() MemPut(0x040892A, 0x53); MemPut(0x040892B, 0x90); - MemPut(0x04341C0, 0xC3); // Skip CCarCtrl::GenerateRandomCars + MemPut(0x04341C0, 0xC3); // Skip CCarCtrl::GenerateRandomCars // Prevent garages deleting vehicles MemPut(0x0449C50, 0xC3); @@ -979,7 +979,7 @@ static void __declspec(naked) HOOK_CVehicleAudio_ProcessSirenSound() // clang-format on } } -DWORD CALL_CVehicleAudio_ProcessCarHorn = 0x5002C0; +DWORD CALL_CVehicleAudio_ProcessCarHorn = 0x5002C0; static void __declspec(naked) HOOK_CVehicleAudio_ProcessSirenSound1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1172,7 +1172,7 @@ static void __declspec(naked) HOOK_CMotorBike_ProcessStuff_PushSirenPositionRed( // clang-format on } } -DWORD RETN_CMotorbike_ProcessStuff_TestVehicleModel2 = 0x6BD41B; +DWORD RETN_CMotorbike_ProcessStuff_TestVehicleModel2 = 0x6BD41B; static void __declspec(naked) HOOK_CMotorbike_ProcessStuff_TestVehicleModel() { // clang-format off @@ -1205,7 +1205,7 @@ static void __declspec(naked) HOOK_CMotorbike_ProcessStuff_TestVehicleModel() // clang-format on } } -DWORD dwValue = 0x858B4C; +DWORD dwValue = 0x858B4C; static void __declspec(naked) HOOK_CVehicle_ProcessStuff_PushRGBPointLights() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1665,8 +1665,8 @@ static void __declspec(naked) HOOK_CBoat_ApplyDamage() } // clang-format on -boatCanBeDamaged: - // clang-format off + boatCanBeDamaged : + // clang-format off __asm { pop eax @@ -1873,7 +1873,7 @@ static void __declspec(naked) HOOK_CProjectile_FixExplosionLocation() // clang-format on } -DWORD CPed_RemoveWeaponWhenEnteringVehicle_CalledFrom = 0; +DWORD CPed_RemoveWeaponWhenEnteringVehicle_CalledFrom = 0; static void __declspec(naked) HOOK_CPed_RemoveWeaponWhenEnteringVehicle() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_ClothesCache.cpp b/Client/multiplayer_sa/CMultiplayerSA_ClothesCache.cpp index 0e6b17cfc56..47b966d3455 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ClothesCache.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ClothesCache.cpp @@ -14,7 +14,7 @@ #include "..\game_sa\gamesa_renderware.h" #include "..\game_sa\gamesa_renderware.hpp" -#define CLOTHES_REF_TEST 1 // Debug clothes geometry refs +#define CLOTHES_REF_TEST 1 // Debug clothes geometry refs //////////////////////////////////////////////// // @@ -28,7 +28,7 @@ class CPedClothesDesc public: union { - DWORD things1[10]; // models + DWORD things1[10]; // models struct { DWORD torso; @@ -45,7 +45,7 @@ class CPedClothesDesc union { - DWORD things2[18]; // +0x28 textures? + DWORD things2[18]; // +0x28 textures? struct { DWORD Torso; @@ -69,8 +69,8 @@ class CPedClothesDesc }; }; - float fFatAmount; // +0x70 - float fMuscleAmount; // +0x74 + float fFatAmount; // +0x70 + float fMuscleAmount; // +0x74 bool operator==(const CPedClothesDesc& other) const { @@ -142,17 +142,17 @@ class CClumpStore { if (!info.pClump || !info.pClump->atomics.root.next) [[unlikely]] continue; - + if (info.pClump->atomics.root.next == &info.pClump->atomics.root) [[unlikely]] continue; - + // Container_of pattern: RwLLLink at offset 0x8 in RpAtomic - char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); + char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); RpAtomic* pAtomic = reinterpret_cast(pListNode - 0x8); - + if (!SharedUtil::IsReadablePointer(pAtomic, sizeof(RpAtomic))) [[unlikely]] continue; - + RpGeometry* pGeometry = pAtomic->geometry; if (!pGeometry) [[unlikely]] continue; @@ -203,10 +203,9 @@ class CClumpStore SSavedClumpInfo info; info.pClump = pClumpCopy; #ifdef CLOTHES_REF_TEST - if (info.pClump && info.pClump->atomics.root.next && - info.pClump->atomics.root.next != &info.pClump->atomics.root) + if (info.pClump && info.pClump->atomics.root.next && info.pClump->atomics.root.next != &info.pClump->atomics.root) { - char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); + char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); RpAtomic* pAtomic = reinterpret_cast(pListNode - 0x8); if (SharedUtil::IsReadablePointer(pAtomic, sizeof(RpAtomic))) { @@ -281,10 +280,9 @@ class CClumpStore return false; #ifdef CLOTHES_REF_TEST - if (info.pClump && info.pClump->atomics.root.next && - info.pClump->atomics.root.next != &info.pClump->atomics.root) + if (info.pClump && info.pClump->atomics.root.next && info.pClump->atomics.root.next != &info.pClump->atomics.root) { - char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); + char* pListNode = reinterpret_cast(info.pClump->atomics.root.next); RpAtomic* pAtomic = reinterpret_cast(pListNode - 0x8); if (SharedUtil::IsReadablePointer(pAtomic, sizeof(RpAtomic))) { @@ -313,7 +311,7 @@ class CClumpStore for (SSavedClumpInfo& info : savedClumpList) { if (info.iCacheRevision != m_iCacheRevision) - continue; // Don't match if it was generated with different custom clothes textures + continue; // Don't match if it was generated with different custom clothes textures if (info.clothedDesc == *pClothesDesc) { @@ -376,9 +374,9 @@ void _cdecl OnCClothesBuilderCreateSkinnedClumpPost(RpClump* pRpClumpResult, RpC } // Hook info -#define HOOKPOS_CClothesBuilderCreateSkinnedClump 0x5A69D0 -#define HOOKSIZE_CClothesBuilderCreateSkinnedClump 6 -DWORD RETURN_CClothesBuilderCreateSkinnedClump = 0x5A69D6; +#define HOOKPOS_CClothesBuilderCreateSkinnedClump 0x5A69D0 +#define HOOKSIZE_CClothesBuilderCreateSkinnedClump 6 +DWORD RETURN_CClothesBuilderCreateSkinnedClump = 0x5A69D6; static void __declspec(naked) HOOK_CClothesBuilderCreateSkinnedClump() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_ClothesMemFix.cpp b/Client/multiplayer_sa/CMultiplayerSA_ClothesMemFix.cpp index 23c579d41f0..0b087525ad9 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ClothesMemFix.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ClothesMemFix.cpp @@ -11,10 +11,10 @@ #include "StdInc.h" -#define FUNC_CPedModelInfo_DeleteRwObject 0x04C6C50 -#define FUNC_CPedModelInfo_SetClump 0x04C7340 -#define FUNC_CClumpModelInfo_SetClump 0x04C4F70 -DWORD ADDR_CPedModelInfo_SetClump_AfterHook = 0x04C7349; +#define FUNC_CPedModelInfo_DeleteRwObject 0x04C6C50 +#define FUNC_CPedModelInfo_SetClump 0x04C7340 +#define FUNC_CClumpModelInfo_SetClump 0x04C4F70 +DWORD ADDR_CPedModelInfo_SetClump_AfterHook = 0x04C7349; ////////////////////////////////////////////////////////////////////////////////////////// // @@ -65,9 +65,9 @@ void OnMy_CClothesDeleteRwObject() } // Hook info -#define HOOKPOS_CClothesDeleteRwObject 0x5A8243 -#define HOOKSIZE_CClothesDeleteRwObject 5 -DWORD RETURN_CClothesDeleteRwObject = 0x5A8248; +#define HOOKPOS_CClothesDeleteRwObject 0x5A8243 +#define HOOKSIZE_CClothesDeleteRwObject 5 +DWORD RETURN_CClothesDeleteRwObject = 0x5A8248; static void __declspec(naked) HOOK_CClothesDeleteRwObject() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -120,9 +120,9 @@ void OnMy_PostCPedDress() } // Hook info -#define HOOKPOS_PostCPedDress 0x5A835C -#define HOOKSIZE_PostCPedDress 5 -DWORD RETURN_PostCPedDress = 0x5A8361; +#define HOOKPOS_PostCPedDress 0x5A835C +#define HOOKSIZE_PostCPedDress 5 +DWORD RETURN_PostCPedDress = 0x5A8361; static void __declspec(naked) HOOK_PostCPedDress() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_ClothesSpeedUp.cpp b/Client/multiplayer_sa/CMultiplayerSA_ClothesSpeedUp.cpp index d7541d82329..4cede94c85f 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ClothesSpeedUp.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ClothesSpeedUp.cpp @@ -69,18 +69,18 @@ namespace ushort usNext; ushort usPrev; - ushort uiUnknown1; // Parent ? - uchar uiUnknown2; // 0x12 when loading, 0x02 when finished loading + ushort uiUnknown1; // Parent ? + uchar uiUnknown2; // 0x12 when loading, 0x02 when finished loading uchar ucImgId; int iBlockOffset; int iBlockCount; - uint uiLoadflag; // 0-not loaded 2-requested 3-loaded 1-processed + uint uiLoadflag; // 0-not loaded 2-requested 3-loaded 1-processed }; int iReturnFileId; char* pReturnBuffer; -} // namespace +} // namespace //////////////////////////////////////////////////////////////////////////////////////////////// // @@ -94,8 +94,8 @@ bool _cdecl OnCallCStreamingInfoAddToList(int flags, SImgGTAItemInfo* pImgGTAInf if (pImgGTAInfo->ucImgId == 5) { - // If bLoadingBigModel is set, try to get it unset - #define VAR_CStreaming_bLoadingBigModel 0x08E4A58 +// If bLoadingBigModel is set, try to get it unset +#define VAR_CStreaming_bLoadingBigModel 0x08E4A58 BYTE& bLoadingBigModel = *(BYTE*)VAR_CStreaming_bLoadingBigModel; if (bLoadingBigModel) { @@ -124,10 +124,10 @@ bool _cdecl OnCallCStreamingInfoAddToList(int flags, SImgGTAItemInfo* pImgGTAInf } // Hook info -#define HOOKPOS_CallCStreamingInfoAddToList 0x408962 -#define HOOKSIZE_CallCStreamingInfoAddToList 5 -DWORD RETURN_CallCStreamingInfoAddToListA = 0x408967; -DWORD RETURN_CallCStreamingInfoAddToListB = 0x408990; +#define HOOKPOS_CallCStreamingInfoAddToList 0x408962 +#define HOOKSIZE_CallCStreamingInfoAddToList 5 +DWORD RETURN_CallCStreamingInfoAddToListA = 0x408967; +DWORD RETURN_CallCStreamingInfoAddToListB = 0x408990; static void __declspec(naked) HOOK_CallCStreamingInfoAddToList() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -188,10 +188,10 @@ bool _cdecl ShouldSkipLoadRequestedModels(DWORD calledFrom) } // Hook info -#define HOOKPOS_CStreamingLoadRequestedModels 0x15670A0 -#define HOOKSIZE_CStreamingLoadRequestedModels 5 -DWORD RETURN_CStreamingLoadRequestedModels = 0x15670A5; -DWORD RETURN_CStreamingLoadRequestedModelsB = 0x156711B; +#define HOOKPOS_CStreamingLoadRequestedModels 0x15670A0 +#define HOOKSIZE_CStreamingLoadRequestedModels 5 +DWORD RETURN_CStreamingLoadRequestedModels = 0x15670A5; +DWORD RETURN_CStreamingLoadRequestedModelsB = 0x156711B; static void __declspec(naked) HOOK_CStreamingLoadRequestedModels() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -238,9 +238,9 @@ bool IsPlayerImgDirLoaded() // Hook info #define HOOKSIZE_LoadingPlayerImgDir 5 -#define HOOKPOS_LoadingPlayerImgDir 0x5A69E3 // 005A69D6 -> CClothesBuilder::CreateSkinnedClump -> playerImgEntries -static constexpr std::uintptr_t RETURN_LoadingPlayerImgDirA = 0x5A69E8; // push 00000226 { 550 } -static constexpr std::uintptr_t RETURN_LoadingPlayerImgDirB = 0x5A6A06; // return of CreateSkinnedClump function +#define HOOKPOS_LoadingPlayerImgDir 0x5A69E3 // 005A69D6 -> CClothesBuilder::CreateSkinnedClump -> playerImgEntries +static constexpr std::uintptr_t RETURN_LoadingPlayerImgDirA = 0x5A69E8; // push 00000226 { 550 } +static constexpr std::uintptr_t RETURN_LoadingPlayerImgDirB = 0x5A6A06; // return of CreateSkinnedClump function static void __declspec(naked) HOOK_LoadingPlayerImgDir() { @@ -282,9 +282,9 @@ bool SetClothingDirectorySize(int directorySize) return false; // CClothesBuilder::LoadCdDirectory(void) - MemPut(0x5A4190 + 1, reinterpret_cast(clothesDirectory)); // push offset _playerImgEntries; headers - MemPut(0x5A4195 + 1, static_cast(directorySize)); // push 550 ; count - MemPut(0x5A69E8 + 1, static_cast(directorySize)); // push 550 ; count + MemPut(0x5A4190 + 1, reinterpret_cast(clothesDirectory)); // push offset _playerImgEntries; headers + MemPut(0x5A4195 + 1, static_cast(directorySize)); // push 550 ; count + MemPut(0x5A69E8 + 1, static_cast(directorySize)); // push 550 ; count g_playerImgEntries = reinterpret_cast(clothesDirectory); g_playerImgSize = static_cast(directorySize); diff --git a/Client/multiplayer_sa/CMultiplayerSA_CrashFixHacks.cpp b/Client/multiplayer_sa/CMultiplayerSA_CrashFixHacks.cpp index 791d16e2c01..972d6787705 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_CrashFixHacks.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_CrashFixHacks.cpp @@ -71,7 +71,7 @@ static bool HasWriteAccess(DWORD dwProtect) noexcept return dwProtect == PAGE_READWRITE || dwProtect == PAGE_WRITECOPY || dwProtect == PAGE_EXECUTE_READWRITE || dwProtect == PAGE_EXECUTE_WRITECOPY; } -static constexpr std::size_t REGION_CACHE_SIZE = 8; +static constexpr std::size_t REGION_CACHE_SIZE = 8; static constexpr std::uintptr_t NUM_LOWMEM_THRESHOLD = 0x10000; #define NUM_LOWMEM_THRESHOLD_ASM 0x10000 @@ -312,7 +312,7 @@ static void __declspec(naked) HOOK_CrashFix_Misc5() mov edi, dword ptr [ecx*4+edi] mov edi, dword ptr [edi+5Ch] test edi, edi - je cont // Skip much code if edi is zero + je cont // Skip much code if edi is zero mov edi, dword ptr[ARRAY_ModelInfo] mov edi, dword ptr [ecx*4+edi] @@ -1265,15 +1265,15 @@ static void __declspec(naked) HOOK_CrashFix_Misc32() // Solution: CallOriginalRwTexDictionaryFindNamedTexture replicates Misc33's overwritten // bytes (mov eax,[esp+4]; push ebx) and jumps to 0x7F39F5 to work around the hook. //////////////////////////////////////////////////////////////////////// -typedef RwTexture* (__cdecl *RwTexDictionaryFindNamedTexture_t)(RwTexDictionary* dict, const char* name); -typedef RwTexDictionary* (__cdecl *RwTexDictionaryGetCurrent_t)(); +typedef RwTexture*(__cdecl* RwTexDictionaryFindNamedTexture_t)(RwTexDictionary* dict, const char* name); +typedef RwTexDictionary*(__cdecl* RwTexDictionaryGetCurrent_t)(); static RwTexDictionaryGetCurrent_t pfnRwTexDictionaryGetCurrentForMisc39 = (RwTexDictionaryGetCurrent_t)0x7F3A90; // Trampoline to call the ORIGINAL RwTexDictionaryFindNamedTexture at 0x7F39F0, // thereby working around HOOK_CrashFix_Misc33. // Replicates the 5 overwritten bytes (mov eax,[esp+4]; push ebx) then jumps to 0x7F39F5. -static constexpr DWORD AddrFindNamedTexture_Continue = 0x7F39F5; +static constexpr DWORD AddrFindNamedTexture_Continue = 0x7F39F5; static void __declspec(naked) TrampolineRwTexDictionaryFindNamedTexture() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1288,17 +1288,16 @@ static void __declspec(naked) TrampolineRwTexDictionaryFindNamedTexture() } static constexpr std::size_t TextureNameSize = 32; -static constexpr char RemapPrefix[] = "remap"; +static constexpr char RemapPrefix[] = "remap"; static RwTexture* __cdecl OnMY_FindTextureCB(const char* name) { - if (name == nullptr) return nullptr; const auto RwTexDictionaryFindNamedTexture = reinterpret_cast(TrampolineRwTexDictionaryFindNamedTexture); const auto RwTexDictionaryGetCurrent = pfnRwTexDictionaryGetCurrentForMisc39; - + RwTexDictionary* vehicleTxd = *reinterpret_cast(0x00B4E688); if (vehicleTxd != nullptr) { @@ -1342,8 +1341,8 @@ static RwTexture* __cdecl OnMY_FindTextureCB(const char* name) return tex; } -#define HOOKPOS_CrashFix_Misc39 0x4C7510 -#define HOOKSIZE_CrashFix_Misc39 5 +#define HOOKPOS_CrashFix_Misc39 0x4C7510 +#define HOOKSIZE_CrashFix_Misc39 5 static void __declspec(naked) HOOK_CrashFix_Misc39() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1476,7 +1475,7 @@ static void __declspec(naked) HOOK_CrashFix_Misc33() #define HOOKPOS_CrashFix_Misc34 0x5D9CB2 #define HOOKSIZE_CrashFix_Misc34 6 DWORD RETURN_CrashFix_Misc34 = 0x5D9CB8; -DWORD RETURN_CrashFix_Misc34_Skip = 0x5D9E0D; // Skip to end of EnvWave block +DWORD RETURN_CrashFix_Misc34_Skip = 0x5D9E0D; // Skip to end of EnvWave block static void __declspec(naked) HOOK_CrashFix_Misc34() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1521,8 +1520,8 @@ static void __declspec(naked) HOOK_CrashFix_Misc34() #define HOOKPOS_CrashFix_Misc35 0x7F374A #define HOOKSIZE_CrashFix_Misc35 5 #define HOOKCHECK_CrashFix_Misc35 0x8B -DWORD RETURN_CrashFix_Misc35 = 0x7F374F; -DWORD RETURN_CrashFix_Misc35_Abort = 0x7F3760; +DWORD RETURN_CrashFix_Misc35 = 0x7F374F; +DWORD RETURN_CrashFix_Misc35_Abort = 0x7F3760; static void __declspec(naked) HOOK_CrashFix_Misc35() { @@ -1566,9 +1565,9 @@ static void __declspec(naked) HOOK_CrashFix_Misc35() // WARNING: No pushad/popad with C++ calls (corrupts /GS cookie > 0xC0000409) // Use push eax/ecx/edx + pushfd instead (16 bytes vs 32) /////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CrashFix_Misc36 0x7F3A09 -#define HOOKSIZE_CrashFix_Misc36 6 -#define HOOKCHECK_CrashFix_Misc36 0x8D +#define HOOKPOS_CrashFix_Misc36 0x7F3A09 +#define HOOKSIZE_CrashFix_Misc36 6 +#define HOOKCHECK_CrashFix_Misc36 0x8D DWORD RETURN_CrashFix_Misc36 = 0x7F3A0F; DWORD RETURN_CrashFix_Misc36_Abort = 0x7F3A5C; @@ -1620,9 +1619,9 @@ static void __declspec(naked) HOOK_CrashFix_Misc36() // (https://pastebin.com/pkWwsSih) // WARNING: No pushad/popad with C++ calls (corrupts /GS cookie > 0xC0000409) //////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CrashFix_Misc37 0x7F39B3 -#define HOOKSIZE_CrashFix_Misc37 5 -#define HOOKCHECK_CrashFix_Misc37 0x89 +#define HOOKPOS_CrashFix_Misc37 0x7F39B3 +#define HOOKSIZE_CrashFix_Misc37 5 +#define HOOKCHECK_CrashFix_Misc37 0x89 DWORD RETURN_CrashFix_Misc37 = 0x7F39B8; static void __declspec(naked) HOOK_CrashFix_Misc37() @@ -1674,18 +1673,18 @@ static void __declspec(naked) HOOK_CrashFix_Misc37() // Hook at loc_7C91C0 validates [eax] // On NULL, skip to loc_7C91DA (after the call block) to continue the loop. //////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CrashFix_Misc38 0x7C91C0 -#define HOOKSIZE_CrashFix_Misc38 6 -#define HOOKCHECK_CrashFix_Misc38 0x8B +#define HOOKPOS_CrashFix_Misc38 0x7C91C0 +#define HOOKSIZE_CrashFix_Misc38 6 +#define HOOKCHECK_CrashFix_Misc38 0x8B DWORD RETURN_CrashFix_Misc38 = 0x7C91C6; -DWORD RETURN_CrashFix_Misc38_Skip = 0x7C91DA; // loc_7C91DA: after call block, safe loop continuation +DWORD RETURN_CrashFix_Misc38_Skip = 0x7C91DA; // loc_7C91DA: after call block, safe loop continuation constexpr std::uint32_t NUM_VRAM_RELIEF_THROTTLE_MS = 500; static void OnVideoMemoryExhausted() { static DWORD s_dwLastReliefTick = 0; - const DWORD dwNow = GetTickCount32(); + const DWORD dwNow = GetTickCount32(); if (dwNow - s_dwLastReliefTick < NUM_VRAM_RELIEF_THROTTLE_MS) return; @@ -1737,10 +1736,10 @@ RwFrame* OnMY_CClumpModelInfo_GetFrameFromId_Post(RwFrame* pFrameResult, DWORD _ return pFrameResult; // Don't check frame if call can legitimately return NULL - if (calledFrom == 0x6D308F // CVehicle::SetWindowOpenFlag - || calledFrom == 0x6D30BF // CVehicle::ClearWindowOpenFlag - || calledFrom == 0x4C7DDE // CVehicleModelInfo::GetOriginalCompPosition - || calledFrom == 0x4C96BD) // CVehicleModelInfo::CreateInstance + if (calledFrom == 0x6D308F // CVehicle::SetWindowOpenFlag + || calledFrom == 0x6D30BF // CVehicle::ClearWindowOpenFlag + || calledFrom == 0x4C7DDE // CVehicleModelInfo::GetOriginalCompPosition + || calledFrom == 0x4C96BD) // CVehicleModelInfo::CreateInstance return NULL; // Ignore external calls @@ -1754,14 +1753,14 @@ RwFrame* OnMY_CClumpModelInfo_GetFrameFromId_Post(RwFrame* pFrameResult, DWORD _ int iModelId = 0; DWORD pVehicle = NULL; - if (calledFrom == 0x6D3847) // CVehicle::AddReplacementUpgrade + if (calledFrom == 0x6D3847) // CVehicle::AddReplacementUpgrade pVehicle = _ebx; - else if (calledFrom == 0x6DFA61 // CVehicle::AddUpgrade - || calledFrom == 0x6D3A62) // CVehicle::GetReplacementUpgrade + else if (calledFrom == 0x6DFA61 // CVehicle::AddUpgrade + || calledFrom == 0x6D3A62) // CVehicle::GetReplacementUpgrade pVehicle = _edi; - else if (calledFrom == 0x06AC740 // CAutomobile::PreRender (Forklift) - || calledFrom == 0x6D39F3 // CVehicle::RemoveReplacementUpgrade - || calledFrom == 0x6D3A32) // CVehicle::RemoveReplacementUpgrade2 + else if (calledFrom == 0x06AC740 // CAutomobile::PreRender (Forklift) + || calledFrom == 0x6D39F3 // CVehicle::RemoveReplacementUpgrade + || calledFrom == 0x6D3A32) // CVehicle::RemoveReplacementUpgrade2 pVehicle = _esi; if (pVehicle > 0x1000) @@ -1772,7 +1771,7 @@ RwFrame* OnMY_CClumpModelInfo_GetFrameFromId_Post(RwFrame* pFrameResult, DWORD _ { RwFrame* pNewFrameResult = NULL; uint uiNewId = id + (i / 2) * ((i & 1) ? -1 : 1); - DWORD dwFunc = 0x4C53C0; // CClumpModelInfo::GetFrameFromId + DWORD dwFunc = 0x4C53C0; // CClumpModelInfo::GetFrameFromId // clang-format off __asm { @@ -2024,7 +2023,7 @@ static void __declspec(naked) HOOK_ResetFurnitureObjectCounter() { MTA_VERIFY_HOOK_LOCAL_SIZE; - *(int*)0xBB3A18 = 0; // InteriorManager_c::ms_objectCounter + *(int*)0xBB3A18 = 0; // InteriorManager_c::ms_objectCounter // clang-format off __asm @@ -2140,7 +2139,7 @@ static void __declspec(naked) HOOK_CVolumetricShadowMgr_Update() //////////////////////////////////////////////////////////////////////// void OnMY_CAnimManager_CreateAnimAssocGroups(uint uiModelId) { - CModelInfo* pModelInfo = pGameInterface->GetModelInfo(uiModelId); + CModelInfo* pModelInfo = pGameInterface->GetModelInfo(uiModelId); CBaseModelInfoSAInterface* pInterface = pModelInfo ? pModelInfo->GetInterface() : nullptr; if (!pInterface || pInterface->pRwObject == nullptr) { @@ -2383,7 +2382,7 @@ static void __declspec(naked) HOOK_CAnimBlendNode_GetCurrentTranslation() altcode: // Save registers before logging pushad - push ebp // Pass 'this' pointer + push ebp // Pass 'this' pointer call OnMY_CAnimBlendNode_GetCurrentTranslation add esp, 4 popad diff --git a/Client/multiplayer_sa/CMultiplayerSA_CustomAnimations.cpp b/Client/multiplayer_sa/CMultiplayerSA_CustomAnimations.cpp index b7716974dff..55f3c52a017 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_CustomAnimations.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_CustomAnimations.cpp @@ -107,7 +107,7 @@ static void __declspec(naked) HOOK_CAnimBlendAssociation_SetCurrentTime() // clang-format on } -#define HOOKPOS_RpAnimBlendClumpUpdateAnimations 0x4D34F0 +#define HOOKPOS_RpAnimBlendClumpUpdateAnimations 0x4D34F0 static void __declspec(naked) HOOK_RpAnimBlendClumpUpdateAnimations() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -160,7 +160,7 @@ CAnimBlendAssociationSAInterface* __cdecl CAnimBlendAssocGroup_CopyAnimation(RpC return pAnimAssociationInterface; } -#define HOOKPOS_CAnimManager_AddAnimation 0x4d3aa0 +#define HOOKPOS_CAnimManager_AddAnimation 0x4d3aa0 static void __declspec(naked) HOOK_CAnimManager_AddAnimation() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -211,12 +211,12 @@ static void __declspec(naked) HOOK_CAnimManager_AddAnimation() // clang-format on } -#define HOOKPOS_CAnimManager_AddAnimationAndSync 0x4D3B30 +#define HOOKPOS_CAnimManager_AddAnimationAndSync 0x4D3B30 static void __declspec(naked) HOOK_CAnimManager_AddAnimationAndSync() { MTA_VERIFY_HOOK_LOCAL_SIZE; - // clang-format off + // clang-format off __asm { lea edx, [esp + 12] // animationGroup address @@ -227,11 +227,11 @@ static void __declspec(naked) HOOK_CAnimManager_AddAnimationAndSync() add esp, 8 pushad } - // clang-format on + // clang-format on if (m_pAddAnimationAndSyncHandler) { - // clang-format off + // clang-format off __asm { popad @@ -247,10 +247,10 @@ static void __declspec(naked) HOOK_CAnimManager_AddAnimationAndSync() push edi jmp RETURN_CAnimManager_AddAnimationAndSync } - // clang-format on + // clang-format on } - // clang-format off + // clang-format off __asm { @@ -259,10 +259,10 @@ static void __declspec(naked) HOOK_CAnimManager_AddAnimationAndSync() mov edx, dword ptr ds : [0B4EA34h] jmp RETURN_CAnimManager_AddAnimationAndSync_NORMAL_FLOW } - // clang-format on + // clang-format on } -#define HOOKPOS_CAnimManager_BlendAnimation_Hierarchy 0x4D453E +#define HOOKPOS_CAnimManager_BlendAnimation_Hierarchy 0x4D453E static void __declspec(naked) HOOK_CAnimManager_BlendAnimation_Hierarchy() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_DeviceSelection.cpp b/Client/multiplayer_sa/CMultiplayerSA_DeviceSelection.cpp index 5cc031475ff..8769fd77db8 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_DeviceSelection.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_DeviceSelection.cpp @@ -94,7 +94,7 @@ struct RwSubSystemInfo char name[80]; }; -using rwDeviceSystemRequest = RwSubSystemInfo*(__cdecl*)(RwDevice* device, std::int32_t requestId, RwSubSystemInfo* pOut, void* pInOut, std::int32_t numIn); +using rwDeviceSystemRequest = RwSubSystemInfo*(__cdecl*)(RwDevice * device, std::int32_t requestId, RwSubSystemInfo* pOut, void* pInOut, std::int32_t numIn); static RwSubSystemInfo* RwEngineGetSubSystemInfo_Hooked(RwSubSystemInfo* subSystemInfo, std::int32_t subSystemIndex) { auto* rwGlobals = *(RwGlobals**)CLASS_RwGlobals; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Direct3D.cpp b/Client/multiplayer_sa/CMultiplayerSA_Direct3D.cpp index 982483e0395..32d7fe35f94 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Direct3D.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Direct3D.cpp @@ -21,7 +21,7 @@ namespace D3DPRESENT_PARAMETERS* ms_pPresentationParameters = NULL; IDirect3DDevice9** ms_ppReturnedDeviceInterface = NULL; bool ms_hasDeviceArgs = false; -} // namespace +} // namespace DWORD RESTORE_Addr_PreCreateDevice; DWORD RESTORE_Size_PreCreateDevice; @@ -38,9 +38,7 @@ void _cdecl OnPreCreateDevice(IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE De D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) { // Safely unpatch with validation - if (RESTORE_Addr_PreCreateDevice && - RESTORE_Size_PreCreateDevice > 0 && - RESTORE_Size_PreCreateDevice <= sizeof(RESTORE_Bytes_PreCreateDevice)) + if (RESTORE_Addr_PreCreateDevice && RESTORE_Size_PreCreateDevice > 0 && RESTORE_Size_PreCreateDevice <= sizeof(RESTORE_Bytes_PreCreateDevice)) { MemCpy((PVOID)RESTORE_Addr_PreCreateDevice, RESTORE_Bytes_PreCreateDevice, RESTORE_Size_PreCreateDevice); } @@ -67,9 +65,9 @@ void _cdecl OnPreCreateDevice(IDirect3D9* pDirect3D, UINT Adapter, D3DDEVTYPE De } // Hook info -#define HOOKPOS_PreCreateDevice 0x007F675B -#define HOOKSIZE_PreCreateDevice 6 -DWORD RETURN_PreCreateDevice = 0x07F6781; +#define HOOKPOS_PreCreateDevice 0x007F675B +#define HOOKSIZE_PreCreateDevice 6 +DWORD RETURN_PreCreateDevice = 0x07F6781; static void __declspec(naked) HOOK_PreCreateDevice() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -161,17 +159,17 @@ HRESULT _cdecl OnPostCreateDevice(HRESULT hResult) return hResult; } - HRESULT result = g_pCore->OnPostCreateDevice(hResult, ms_pDirect3D, ms_Adapter, ms_DeviceType, ms_hFocusWindow, ms_BehaviorFlags, ms_pPresentationParameters, - ms_ppReturnedDeviceInterface); + HRESULT result = g_pCore->OnPostCreateDevice(hResult, ms_pDirect3D, ms_Adapter, ms_DeviceType, ms_hFocusWindow, ms_BehaviorFlags, + ms_pPresentationParameters, ms_ppReturnedDeviceInterface); ms_hasDeviceArgs = false; return result; } // Hook info -#define HOOKPOS_PostCreateDevice 0x07F6784 -#define HOOKSIZE_PostCreateDevice 6 -DWORD RETURN_PostCreateDevice = 0x07F678A; -DWORD RETURN_PostCreateDeviceB = 0x07F6799; +#define HOOKPOS_PostCreateDevice 0x07F6784 +#define HOOKSIZE_PostCreateDevice 6 +DWORD RETURN_PostCreateDevice = 0x07F678A; +DWORD RETURN_PostCreateDeviceB = 0x07F6799; static void __declspec(naked) HOOK_PostCreateDevice() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Explosions.cpp b/Client/multiplayer_sa/CMultiplayerSA_Explosions.cpp index 3b8ed5b0472..9ec1fe801cd 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Explosions.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Explosions.cpp @@ -19,7 +19,7 @@ #define HOOKPOS_CWorld_TriggerExplosion 0x56B82E #define HOOKSIZE_CWorld_TriggerExplosion 8 static constexpr std::uintptr_t RETURN_CWorld_TriggerExplosion = 0x56B836; -static void __declspec(naked) HOOK_CWorld_TriggerExplosion() +static void __declspec(naked) HOOK_CWorld_TriggerExplosion() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -46,7 +46,7 @@ static void __declspec(naked) HOOK_CWorld_TriggerExplosion() #define HOOKSIZE_CWorld_TriggerExplosionSectorList 7 static constexpr std::uintptr_t RETURN_CWorld_TriggerExplosionSectorList = 0x5677FB; static constexpr std::uintptr_t SKIP_CWorld_TriggerExplosionSectorList = 0x568473; -static void __declspec(naked) HOOK_CWorld_TriggerExplosionSectorList() +static void __declspec(naked) HOOK_CWorld_TriggerExplosionSectorList() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Files.cpp b/Client/multiplayer_sa/CMultiplayerSA_Files.cpp index f16cce9c4ed..9ecb6476d5e 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Files.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Files.cpp @@ -44,9 +44,9 @@ void OnMY_Rtl_fopen_Post(FILE* fh, DWORD calledFrom, const char* szFilename, con } // Hook info -#define HOOKPOS_Rtl_fopen 0x8232D8 -#define HOOKSIZE_Rtl_fopen 6 -DWORD RETURN_Rtl_fopen = 0x8232DE; +#define HOOKPOS_Rtl_fopen 0x8232D8 +#define HOOKSIZE_Rtl_fopen 6 +DWORD RETURN_Rtl_fopen = 0x8232DE; static void __declspec(naked) HOOK_Rtl_fopen() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -92,9 +92,9 @@ void OnMY_Rtl_fclose(DWORD calledFrom, FILE* fh) } // Hook info -#define HOOKPOS_Rtl_fclose 0x82318B -#define HOOKSIZE_Rtl_fclose 6 -DWORD RETURN_Rtl_fclose = 0x823192; +#define HOOKPOS_Rtl_fclose 0x82318B +#define HOOKSIZE_Rtl_fclose 6 +DWORD RETURN_Rtl_fclose = 0x823192; static void __declspec(naked) HOOK_Rtl_fclose() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_FixBadAnimId.cpp b/Client/multiplayer_sa/CMultiplayerSA_FixBadAnimId.cpp index 23c2eb119c0..2659691761c 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_FixBadAnimId.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_FixBadAnimId.cpp @@ -92,9 +92,9 @@ void _cdecl OnGetAnimHierarchyFromSkinClump(RpClump* pRpClump, void* pRpHAnimHie } } -#define HOOKPOS_GetAnimHierarchyFromSkinClump 0x734A5D -#define HOOKSIZE_GetAnimHierarchyFromSkinClump 7 -DWORD RETURN_GetAnimHierarchyFromSkinClump = 0x734A64; +#define HOOKPOS_GetAnimHierarchyFromSkinClump 0x734A5D +#define HOOKSIZE_GetAnimHierarchyFromSkinClump 7 +DWORD RETURN_GetAnimHierarchyFromSkinClump = 0x734A64; static void __declspec(naked) HOOK_GetAnimHierarchyFromSkinClump() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_FixLineOfSightArgs.cpp b/Client/multiplayer_sa/CMultiplayerSA_FixLineOfSightArgs.cpp index 9e1f070bd5b..cbb1a98b20c 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_FixLineOfSightArgs.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_FixLineOfSightArgs.cpp @@ -33,7 +33,7 @@ namespace vecEnd = vecStart + CVector(0, 0, 0.01f); } } -} // namespace +} // namespace //////////////////////////////////////////////////////////////// // @@ -48,9 +48,9 @@ void _cdecl OnCWorld_ProcessLineOfSight(CVector* pvecStart, CVector* pvecEnd) } // Hook info -#define HOOKPOS_CWorld_ProcessLineOfSight 0x56BA00 -#define HOOKSIZE_CWorld_ProcessLineOfSight 12 -DWORD RETURN_CWorld_ProcessLineOfSight = 0x56BA0C; +#define HOOKPOS_CWorld_ProcessLineOfSight 0x56BA00 +#define HOOKSIZE_CWorld_ProcessLineOfSight 12 +DWORD RETURN_CWorld_ProcessLineOfSight = 0x56BA0C; static void __declspec(naked) HOOK_CWorld_ProcessLineOfSight() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -85,9 +85,9 @@ void _cdecl OnCWorld_GetIsLineOfSightClear(CVector* pvecStart, CVector* pvecEnd) } // Hook info -#define HOOKPOS_CWorld_GetIsLineOfSightClear 0x56A490 -#define HOOKSIZE_CWorld_GetIsLineOfSightClear 12 -DWORD RETURN_CWorld_GetIsLineOfSightClear = 0x56A49C; +#define HOOKPOS_CWorld_GetIsLineOfSightClear 0x56A490 +#define HOOKSIZE_CWorld_GetIsLineOfSightClear 12 +DWORD RETURN_CWorld_GetIsLineOfSightClear = 0x56A49C; static void __declspec(naked) HOOK_CWorld_GetIsLineOfSightClear() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_FixMallocAlign.cpp b/Client/multiplayer_sa/CMultiplayerSA_FixMallocAlign.cpp index 596e2716ecf..69a3cdd3bfe 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_FixMallocAlign.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_FixMallocAlign.cpp @@ -21,7 +21,7 @@ namespace mta::memory constexpr std::uint32_t MAX_ADDRESS_SPACE = 0xFFFFFFFF; constexpr std::uint32_t POINTER_SIZE = 4; constexpr std::uint32_t POINTER_METADATA_OVERHEAD = POINTER_SIZE * 2; - constexpr std::uint32_t METADATA_MAGIC = 0x4D544100; // 'MTA\0' + constexpr std::uint32_t METADATA_MAGIC = 0x4D544100; // 'MTA\0' constexpr std::uint32_t METADATA_MAGIC_MASK = 0xFFFFFFFE; constexpr std::uint32_t METADATA_FLAG_VIRTUALALLOC = 0x1; @@ -92,7 +92,8 @@ namespace mta::memory const std::uint32_t aligned_addr = (raw_addr + POINTER_METADATA_OVERHEAD + align_u32 - 1) & ~(align_u32 - 1); - if (aligned_addr < raw_addr + POINTER_METADATA_OVERHEAD || aligned_addr + size_u32 > raw_addr + total_size || aligned_addr + size_u32 < aligned_addr) + if (aligned_addr < raw_addr + POINTER_METADATA_OVERHEAD || aligned_addr + size_u32 > raw_addr + total_size || + aligned_addr + size_u32 < aligned_addr) { free(raw_memory); errno = EINVAL; @@ -102,13 +103,13 @@ namespace mta::memory void* result = reinterpret_cast(aligned_addr); // Validate store location - void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); - std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); + void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); + std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); const std::uint32_t store_addr = reinterpret_cast(store_location); const std::uint32_t metadata_addr = reinterpret_cast(metadata_location); - if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || - metadata_addr < raw_addr || metadata_addr > raw_addr + total_size - POINTER_SIZE) + if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || metadata_addr < raw_addr || + metadata_addr > raw_addr + total_size - POINTER_SIZE) { free(raw_memory); errno = EFAULT; @@ -178,13 +179,13 @@ namespace mta::memory void* result = reinterpret_cast(aligned_addr); - void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); - std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); + void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); + std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); const std::uint32_t store_addr = reinterpret_cast(store_location); const std::uint32_t metadata_addr = reinterpret_cast(metadata_location); - if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || - metadata_addr < raw_addr || metadata_addr > raw_addr + total_size - POINTER_SIZE) + if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || metadata_addr < raw_addr || + metadata_addr > raw_addr + total_size - POINTER_SIZE) { free(raw_memory); errno = EFAULT; @@ -272,13 +273,13 @@ namespace mta::memory void* result = reinterpret_cast(aligned_addr); // Validate store location - void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); - std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); + void** store_location = reinterpret_cast(aligned_addr - POINTER_SIZE); + std::uint32_t* metadata_location = reinterpret_cast(aligned_addr - POINTER_METADATA_OVERHEAD); const std::uint32_t store_addr = reinterpret_cast(store_location); const std::uint32_t metadata_addr = reinterpret_cast(metadata_location); - if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || - metadata_addr < raw_addr || metadata_addr > raw_addr + total_size - POINTER_SIZE) + if (store_addr < raw_addr || store_addr > raw_addr + total_size - POINTER_SIZE || metadata_addr < raw_addr || + metadata_addr > raw_addr + total_size - POINTER_SIZE) { BOOL vfree_result = VirtualFree(raw_ptr, 0, MEM_RELEASE); (void)vfree_result; @@ -310,7 +311,7 @@ namespace mta::memory return; } - void** read_location = reinterpret_cast(ptr_addr - POINTER_SIZE); + void** read_location = reinterpret_cast(ptr_addr - POINTER_SIZE); std::uint32_t* metadata_location = reinterpret_cast(ptr_addr - POINTER_METADATA_OVERHEAD); // Validate memory readable @@ -344,7 +345,7 @@ namespace mta::memory return; } - void* original_ptr = *read_location; + void* original_ptr = *read_location; const std::uint32_t metadata = *metadata_location; if ((metadata & METADATA_MAGIC_MASK) != METADATA_MAGIC) @@ -361,18 +362,18 @@ namespace mta::memory if (original_addr >= ptr_addr) { - return; // Impossible for our allocator + return; // Impossible for our allocator } const std::uint32_t distance = ptr_addr - original_addr; if (distance > MAX_ALIGNMENT + POINTER_METADATA_OVERHEAD) { - return; // Beyond maximum possible alignment + return; // Beyond maximum possible alignment } if (original_addr > ptr_addr - POINTER_SIZE) { - return; // Violates our storage pattern + return; // Violates our storage pattern } if (original_addr >= 0xFFFF0000 || original_addr < NULL_PAGE_BOUNDARY) @@ -389,7 +390,7 @@ namespace mta::memory free(original_ptr); } -} // namespace mta::memory +} // namespace mta::memory // Hook constants #define HOOKPOS_CMemoryMgr_MallocAlign 0x72F4C0 diff --git a/Client/multiplayer_sa/CMultiplayerSA_FrameRateFixes.cpp b/Client/multiplayer_sa/CMultiplayerSA_FrameRateFixes.cpp index c93e223611c..f71793cb26b 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_FrameRateFixes.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_FrameRateFixes.cpp @@ -16,9 +16,9 @@ static unsigned int nLastFrameTime = 0; constexpr float kOriginalTimeStep = 50.0f / 30.0f; // Fixes player movement issue while aiming and walking on high FPS. -#define HOOKPOS_CTaskSimpleUseGun__SetMoveAnim 0x61E4F2 +#define HOOKPOS_CTaskSimpleUseGun__SetMoveAnim 0x61E4F2 #define HOOKSIZE_CTaskSimpleUseGun__SetMoveAnim 0x6 -const unsigned int RETURN_CTaskSimpleUseGun__SetMoveAnim = 0x61E4F8; +const unsigned int RETURN_CTaskSimpleUseGun__SetMoveAnim = 0x61E4F8; static void __declspec(naked) HOOK_CTaskSimpleUseGun__SetMoveAnim() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -39,9 +39,9 @@ static void __declspec(naked) HOOK_CTaskSimpleUseGun__SetMoveAnim() } // Fixes excessively fast camera shaking with setCameraShakeLevel on high FPS. -#define HOOKPOS_CCamera__Process 0x52C723 +#define HOOKPOS_CCamera__Process 0x52C723 #define HOOKSIZE_CCamera__Process 0x12 -static const unsigned int RETURN_CCamera__Process = 0x52C735; +static const unsigned int RETURN_CCamera__Process = 0x52C735; static void __declspec(naked) HOOK_CCamera__Process() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -60,9 +60,9 @@ static void __declspec(naked) HOOK_CCamera__Process() } // Fixes helicopters accelerating excessively during takeoff at high FPS. -#define HOOKPOS_CHeli__ProcessFlyingCarStuff 0x6C4F13 +#define HOOKPOS_CHeli__ProcessFlyingCarStuff 0x6C4F13 #define HOOKSIZE_CHeli__ProcessFlyingCarStuff 0x2A -static const unsigned int RETURN_CHeli__ProcessFlyingCarStuff = 0x6C4F3D; +static const unsigned int RETURN_CHeli__ProcessFlyingCarStuff = 0x6C4F3D; static void __declspec(naked) HOOK_CHeli__ProcessFlyingCarStuff() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -92,9 +92,9 @@ static void __declspec(naked) HOOK_CHeli__ProcessFlyingCarStuff() } // Fixes excessively fast movement of fog on high FPS. -#define HOOKPOS_CClouds__MovingFog_Update 0x716BA6 +#define HOOKPOS_CClouds__MovingFog_Update 0x716BA6 #define HOOKSIZE_CClouds__MovingFog_Update 0x16 -static const unsigned int RETURN_CClouds__MovingFog_Update = 0x716BBC; +static const unsigned int RETURN_CClouds__MovingFog_Update = 0x716BBC; static void __declspec(naked) HOOK_CClouds__MovingFog_Update() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -117,9 +117,9 @@ static void __declspec(naked) HOOK_CClouds__MovingFog_Update() } // Fixes glass shards spinning and moving at excessive speeds on high FPS. -#define HOOKPOS_CFallingGlassPane__Update_A 0x71AABF +#define HOOKPOS_CFallingGlassPane__Update_A 0x71AABF #define HOOKSIZE_CFallingGlassPane__Update_A 0x6 -static const unsigned int RETURN_CFallingGlassPane__Update_A = 0x71AAC5; +static const unsigned int RETURN_CFallingGlassPane__Update_A = 0x71AAC5; static void __declspec(naked) HOOK_CFallingGlassPane__Update_A() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -145,9 +145,9 @@ static void __declspec(naked) HOOK_CFallingGlassPane__Update_A() } // Fixes glass shards spinning and moving at excessive speeds on high FPS. -#define HOOKPOS_CFallingGlassPane__Update_B 0x71AAEA +#define HOOKPOS_CFallingGlassPane__Update_B 0x71AAEA #define HOOKSIZE_CFallingGlassPane__Update_B 0x6 -static const unsigned int RETURN_CFallingGlassPane__Update_B = 0x71AAF0; +static const unsigned int RETURN_CFallingGlassPane__Update_B = 0x71AAF0; static void __declspec(naked) HOOK_CFallingGlassPane__Update_B() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -175,9 +175,9 @@ static void __declspec(naked) HOOK_CFallingGlassPane__Update_B() } // Fixes glass shards spinning and moving at excessive speeds on high FPS. -#define HOOKPOS_CFallingGlassPane__Update_C 0x71AB29 +#define HOOKPOS_CFallingGlassPane__Update_C 0x71AB29 #define HOOKSIZE_CFallingGlassPane__Update_C 0x6 -static const unsigned int RETURN_CFallingGlassPane__Update_C = 0x71AB2F; +static const unsigned int RETURN_CFallingGlassPane__Update_C = 0x71AB2F; static void __declspec(naked) HOOK_CFallingGlassPane__Update_C() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -205,7 +205,7 @@ static void __declspec(naked) HOOK_CFallingGlassPane__Update_C() } // Ensure that CTimer::CurrentFrame is updated only every 33+ milliseconds. -#define HOOKPOS_CTimer__Update 0x561C5D +#define HOOKPOS_CTimer__Update 0x561C5D #define HOOKSIZE_CTimer__Update 0xE static void __declspec(naked) HOOK_CTimer__Update() { @@ -237,9 +237,9 @@ static void __declspec(naked) HOOK_CTimer__Update() } // Fixes premature despawning of broken breakable objects on high FPS. -#define HOOKPOS_BreakObject_c__Update 0x59E420 +#define HOOKPOS_BreakObject_c__Update 0x59E420 #define HOOKSIZE_BreakObject_c__Update 0xB -static const unsigned int RETURN_BreakObject_c__Update = 0x59E42B; +static const unsigned int RETURN_BreakObject_c__Update = 0x59E42B; static void __declspec(naked) HOOK_BreakObject_c__Update() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -265,11 +265,10 @@ static void __declspec(naked) HOOK_BreakObject_c__Update() // Fixes limited reach of the water cannon on high FPS. #define HOOKPOS_CWaterCannon__Update_OncePerFrame 0x72A29B #define HOOKSIZE_CWaterCannon__Update_OncePerFrame 0x5 -static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame = 0x72A2A0; -static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_SKIP = 0x72A2BB; +static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame = 0x72A2A0; +static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_SKIP = 0x72A2BB; static void __declspec(naked) HOOK_CWaterCannon__Update_OncePerFrame() { - MTA_VERIFY_HOOK_LOCAL_SIZE; // clang-format off @@ -290,10 +289,10 @@ static void __declspec(naked) HOOK_CWaterCannon__Update_OncePerFrame() } // Fixes money animation issues on high FPS. -#define HOOKPOS_CPlayerInfo__Process 0x5700F5 +#define HOOKPOS_CPlayerInfo__Process 0x5700F5 #define HOOKSIZE_CPlayerInfo__Process 0x6 -static const unsigned int RETURN_CPlayerInfo__Process = 0x5700FB; -static const unsigned int RETURN_CPlayerInfo__Process_SKIP = 0x57015B; +static const unsigned int RETURN_CPlayerInfo__Process = 0x5700FB; +static const unsigned int RETURN_CPlayerInfo__Process_SKIP = 0x57015B; static void __declspec(naked) HOOK_CPlayerInfo__Process() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -315,10 +314,10 @@ static void __declspec(naked) HOOK_CPlayerInfo__Process() } // Fixes excessive effects spawning from rocket launchers on high FPS. -#define HOOKPOS_CProjectileInfo__Update 0x738C63 +#define HOOKPOS_CProjectileInfo__Update 0x738C63 #define HOOKSIZE_CProjectileInfo__Update 0x5 -static const unsigned int RETURN_CProjectileInfo__Update = 0x738C68; -static const unsigned int RETURN_CProjectileInfo__Update_SKIP = 0x738F22; +static const unsigned int RETURN_CProjectileInfo__Update = 0x738C68; +static const unsigned int RETURN_CProjectileInfo__Update_SKIP = 0x738F22; static void __declspec(naked) HOOK_CProjectileInfo__Update() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -341,9 +340,9 @@ static void __declspec(naked) HOOK_CProjectileInfo__Update() } // Fixes excessive surface effects spawning from wheels on high FPS. -#define HOOKPOS_CVehicle__AddWheelDirtAndWater 0x6D2D50 +#define HOOKPOS_CVehicle__AddWheelDirtAndWater 0x6D2D50 #define HOOKSIZE_CVehicle__AddWheelDirtAndWater 0x6 -static const unsigned int RETURN_CVehicle__AddWheelDirtAndWater = 0x6D2D56; +static const unsigned int RETURN_CVehicle__AddWheelDirtAndWater = 0x6D2D56; static void __declspec(naked) HOOK_CVehicle__AddWheelDirtAndWater() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -367,10 +366,10 @@ static void __declspec(naked) HOOK_CVehicle__AddWheelDirtAndWater() } // Fixes excessive smoke trail particle spawning from stuntplanes and cropdusters on high FPS. -#define HOOKPOS_CPlane__PreRender 0x6CA937 +#define HOOKPOS_CPlane__PreRender 0x6CA937 #define HOOKSIZE_CPlane__PreRender 0x6 -static const unsigned int RETURN_CPlane__PreRender = 0x6CA93D; -static const unsigned int RETURN_CPlane__PreRender_SKIP = 0x6CAA93; +static const unsigned int RETURN_CPlane__PreRender = 0x6CA93D; +static const unsigned int RETURN_CPlane__PreRender_SKIP = 0x6CAA93; static void __declspec(naked) HOOK_CPlane__PreRender() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -392,10 +391,10 @@ static void __declspec(naked) HOOK_CPlane__PreRender() } // Fixes increased frequency of water cannon pushing peds on high FPS. -#define HOOKPOS_CWaterCannon__Update_OncePerFrame_PushPedFix 0x72A37B +#define HOOKPOS_CWaterCannon__Update_OncePerFrame_PushPedFix 0x72A37B #define HOOKSIZE_CWaterCannon__Update_OncePerFrame_PushPedFix 0x6 -static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_PushPedFix = 0x72A381; -static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_PushPedFix_SKIP = 0x72A38E; +static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_PushPedFix = 0x72A381; +static const unsigned int RETURN_CWaterCannon__Update_OncePerFrame_PushPedFix_SKIP = 0x72A38E; static void __declspec(naked) HOOK_CWaterCannon__Update_OncePerFrame_PushPedFix() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -417,10 +416,10 @@ static void __declspec(naked) HOOK_CWaterCannon__Update_OncePerFrame_PushPedFix( } // Fixes excessive particle spawning from water cannons on high FPS. -#define HOOKPOS_CWaterCannon__Render_FxFix 0x729437 +#define HOOKPOS_CWaterCannon__Render_FxFix 0x729437 #define HOOKSIZE_CWaterCannon__Render_FxFix 0x5 -static const unsigned int RETURN_CWaterCannon__Render_FxFix = 0x729440; -static const unsigned int RETURN_CWaterCannon__Render_FxFix_SKIP = 0x7294EE; +static const unsigned int RETURN_CWaterCannon__Render_FxFix = 0x729440; +static const unsigned int RETURN_CWaterCannon__Render_FxFix_SKIP = 0x7294EE; static void __declspec(naked) HOOK_CWaterCannon__Render_FxFix() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -440,10 +439,10 @@ static void __declspec(naked) HOOK_CWaterCannon__Render_FxFix() } // Fixes excessive particle spawning with setPedHeadless on high FPS. -#define HOOKPOS_CPed__PreRenderAfterTest 0x5E7181 +#define HOOKPOS_CPed__PreRenderAfterTest 0x5E7181 #define HOOKSIZE_CPed__PreRenderAfterTest 0x6 -static const unsigned int RETURN_CPed__PreRenderAfterTest = 0x5E7187; -static const unsigned int RETURN_CPed__PreRenderAfterTest_SKIP = 0x5E722D; +static const unsigned int RETURN_CPed__PreRenderAfterTest = 0x5E7187; +static const unsigned int RETURN_CPed__PreRenderAfterTest_SKIP = 0x5E722D; static void __declspec(naked) HOOK_CPed__PreRenderAfterTest() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -465,9 +464,9 @@ static void __declspec(naked) HOOK_CPed__PreRenderAfterTest() } // Fixes excessive particle spawning from boats on high FPS. -#define HOOKPOS_cBuoyancy__AddSplashParticles 0x6C34E0 +#define HOOKPOS_cBuoyancy__AddSplashParticles 0x6C34E0 #define HOOKSIZE_cBuoyancy__AddSplashParticles 0x6 -static const unsigned int RETURN_cBuoyancy__AddSplashParticles = 0x6C34E6; +static const unsigned int RETURN_cBuoyancy__AddSplashParticles = 0x6C34E6; static void __declspec(naked) HOOK_cBuoyancy__AddSplashParticles() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -489,9 +488,9 @@ static void __declspec(naked) HOOK_cBuoyancy__AddSplashParticles() } // Fixes excessive weather particle spawning on high FPS. -#define HOOKPOS_CWeather__AddRain 0x72AAA8 +#define HOOKPOS_CWeather__AddRain 0x72AAA8 #define HOOKSIZE_CWeather__AddRain 0x6 -static const unsigned int RETURN_CWeather__AddRain = 0x72AAAE; +static const unsigned int RETURN_CWeather__AddRain = 0x72AAAE; static void __declspec(naked) HOOK_CWeather__AddRain() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -515,10 +514,10 @@ static void __declspec(naked) HOOK_CWeather__AddRain() } // Fixes excessive damage particle spawning from airplanes on high FPS. -#define HOOKPOS_CPlane__ProcessFlyingCarStuff 0x6CBE4B +#define HOOKPOS_CPlane__ProcessFlyingCarStuff 0x6CBE4B #define HOOKSIZE_CPlane__ProcessFlyingCarStuff 0x6 -static const unsigned int RETURN_CPlane__ProcessFlyingCarStuff = 0x6CBE51; -static const unsigned int RETURN_CPlane__ProcessFlyingCarStuff_SKIP = 0x6CC0D9; +static const unsigned int RETURN_CPlane__ProcessFlyingCarStuff = 0x6CBE51; +static const unsigned int RETURN_CPlane__ProcessFlyingCarStuff_SKIP = 0x6CC0D9; static void __declspec(naked) HOOK_CPlane__ProcessFlyingCarStuff() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -540,10 +539,10 @@ static void __declspec(naked) HOOK_CPlane__ProcessFlyingCarStuff() } // Fixes excessive spawning of sand and water particles from vehicles on high FPS. -#define HOOKPOS_CAutomobile__UpdateWheelMatrix 0x6AA78A +#define HOOKPOS_CAutomobile__UpdateWheelMatrix 0x6AA78A #define HOOKSIZE_CAutomobile__UpdateWheelMatrix 0x5 -static const unsigned int RETURN_CAutomobile__UpdateWheelMatrix = 0x6AA78F; -static const unsigned int RETURN_CAutomobile__UpdateWheelMatrix_SKIP = 0x6AAAD0; +static const unsigned int RETURN_CAutomobile__UpdateWheelMatrix = 0x6AA78F; +static const unsigned int RETURN_CAutomobile__UpdateWheelMatrix_SKIP = 0x6AAAD0; static void __declspec(naked) HOOK_CAutomobile__UpdateWheelMatrix() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -565,9 +564,9 @@ static void __declspec(naked) HOOK_CAutomobile__UpdateWheelMatrix() } // Fixes excessive particle spawning from boats on high FPS. -#define HOOKPOS_CVehicle__DoBoatSplashes 0x6DD130 +#define HOOKPOS_CVehicle__DoBoatSplashes 0x6DD130 #define HOOKSIZE_CVehicle__DoBoatSplashes 0x6 -static const unsigned int RETURN_CVehicle__DoBoatSplashes = 0x6DD136; +static const unsigned int RETURN_CVehicle__DoBoatSplashes = 0x6DD136; static void __declspec(naked) HOOK_CVehicle__DoBoatSplashes() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -589,9 +588,9 @@ static void __declspec(naked) HOOK_CVehicle__DoBoatSplashes() } // Fixes excessive rain particle spawning on vehicles on high FPS. -#define HOOKPOS_CVehicle__AddWaterSplashParticles 0x6DDF60 +#define HOOKPOS_CVehicle__AddWaterSplashParticles 0x6DDF60 #define HOOKSIZE_CVehicle__AddWaterSplashParticles 0x6 -static const unsigned int RETURN_CVehicle__AddWaterSplashParticles = 0x6DDF66; +static const unsigned int RETURN_CVehicle__AddWaterSplashParticles = 0x6DDF66; static void __declspec(naked) HOOK_CVehicle__AddWaterSplashParticles() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -613,10 +612,10 @@ static void __declspec(naked) HOOK_CVehicle__AddWaterSplashParticles() } // Fixes excessive particle spawning from airplanes when damaged on high FPS. -#define HOOKPOS_CPlane__ProcessControl 0x6C939A +#define HOOKPOS_CPlane__ProcessControl 0x6C939A #define HOOKSIZE_CPlane__ProcessControl 0x5 -static const unsigned int RETURN_CPlane__ProcessControl = 0x6C939F; -static const unsigned int RETURN_CPlane__ProcessControl_SKIP = 0x6C9463; +static const unsigned int RETURN_CPlane__ProcessControl = 0x6C939F; +static const unsigned int RETURN_CPlane__ProcessControl_SKIP = 0x6C9463; static void __declspec(naked) HOOK_CPlane__ProcessControl() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -639,9 +638,9 @@ static void __declspec(naked) HOOK_CPlane__ProcessControl() } // Fixes excessive exhaust particle spawning from vehicles on high FPS. -#define HOOKPOS_CVehicle__AddExhaustParticles 0x6DE240 +#define HOOKPOS_CVehicle__AddExhaustParticles 0x6DE240 #define HOOKSIZE_CVehicle__AddExhaustParticles 0x6 -static const unsigned int RETURN_CVehicle__AddExhaustParticles = 0x6DE246; +static const unsigned int RETURN_CVehicle__AddExhaustParticles = 0x6DE246; static void __declspec(naked) HOOK_CVehicle__AddExhaustParticles() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -663,10 +662,10 @@ static void __declspec(naked) HOOK_CVehicle__AddExhaustParticles() } // Fixes excessive particle spawning while swimming on high FPS. -#define HOOKPOS_CTaskSimpleSwim__ProcessEffects 0x68AD3B +#define HOOKPOS_CTaskSimpleSwim__ProcessEffects 0x68AD3B #define HOOKSIZE_CTaskSimpleSwim__ProcessEffects 0x6 -static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffects = 0x68AD41; -static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffects_SKIP = 0x68AFDB; +static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffects = 0x68AD41; +static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffects_SKIP = 0x68AFDB; static void __declspec(naked) HOOK_CTaskSimpleSwim__ProcessEffects() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -689,10 +688,10 @@ static void __declspec(naked) HOOK_CTaskSimpleSwim__ProcessEffects() } // Fixes excessive particle spawning while swimming on high FPS. -#define HOOKPOS_CTaskSimpleSwim__ProcessEffectsBubbleFix 0x68AC31 +#define HOOKPOS_CTaskSimpleSwim__ProcessEffectsBubbleFix 0x68AC31 #define HOOKSIZE_CTaskSimpleSwim__ProcessEffectsBubbleFix 0x7 -static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffectsBubbleFix = 0x68AC38; -static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffectsBubbleFix_SKIP = 0x68AD36; +static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffectsBubbleFix = 0x68AC38; +static const unsigned int RETURN_CTaskSimpleSwim__ProcessEffectsBubbleFix_SKIP = 0x68AD36; static void __declspec(naked) HOOK_CTaskSimpleSwim__ProcessEffectsBubbleFix() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -715,10 +714,10 @@ static void __declspec(naked) HOOK_CTaskSimpleSwim__ProcessEffectsBubbleFix() } // Fixes invisible weapon particles (extinguisher, spraycan, flamethrower) at high FPS -#define HOOKPOS_CWeapon_Update 0x73DC3D +#define HOOKPOS_CWeapon_Update 0x73DC3D #define HOOKSIZE_CWeapon_Update 5 static constexpr std::uintptr_t RETURN_CWeapon_Update = 0x073DC42; -static void __declspec(naked) HOOK_CWeapon_Update() +static void __declspec(naked) HOOK_CWeapon_Update() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -761,7 +760,7 @@ static void __declspec(naked) HOOK_CWeapon_Update() #define HOOKPOS_CPhysical__ApplyAirResistance 0x544D29 #define HOOKSIZE_CPhysical__ApplyAirResistance 5 -static const unsigned int RETURN_CPhysical__ApplyAirResistance = 0x544D4D; +static const unsigned int RETURN_CPhysical__ApplyAirResistance = 0x544D4D; static void __declspec(naked) HOOK_CPhysical__ApplyAirResistance() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_HookDestructors.cpp b/Client/multiplayer_sa/CMultiplayerSA_HookDestructors.cpp index 718d7fdfee4..c8741606e21 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_HookDestructors.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_HookDestructors.cpp @@ -1,13 +1,13 @@ /***************************************************************************** -* -* PROJECT: Multi Theft Auto v1.0 -* LICENSE: See LICENSE in the top level directory -* FILE: multiplayer_sa/CMultiplayerSA_HookDestructors.cpp -* PURPOSE: Game destructor hooks and entity lifecycle tracking -* -* Multi Theft Auto is available from https://www.multitheftauto.com/ -* -*****************************************************************************/ + * + * PROJECT: Multi Theft Auto v1.0 + * LICENSE: See LICENSE in the top level directory + * FILE: multiplayer_sa/CMultiplayerSA_HookDestructors.cpp + * PURPOSE: Game destructor hooks and entity lifecycle tracking + * + * Multi Theft Auto is available from https://www.multitheftauto.com/ + * + *****************************************************************************/ #include "StdInc.h" #include @@ -16,21 +16,21 @@ namespace { // Handler pointers for game destructors - CAnimBlendAssocDestructorHandler* m_pCAnimBlendAssocDestructorHandler = nullptr; - GameObjectDestructHandler* pGameObjectDestructHandler = nullptr; - GameVehicleDestructHandler* pGameVehicleDestructHandler = nullptr; - GamePlayerDestructHandler* pGamePlayerDestructHandler = nullptr; - GameProjectileDestructHandler* pGameProjectileDestructHandler = nullptr; + CAnimBlendAssocDestructorHandler* m_pCAnimBlendAssocDestructorHandler = nullptr; + GameObjectDestructHandler* pGameObjectDestructHandler = nullptr; + GameVehicleDestructHandler* pGameVehicleDestructHandler = nullptr; + GamePlayerDestructHandler* pGamePlayerDestructHandler = nullptr; + GameProjectileDestructHandler* pGameProjectileDestructHandler = nullptr; std::atomic pGameModelRemoveHandler{nullptr}; - GameRunNamedAnimDestructorHandler* pRunNamedAnimDestructorHandler = nullptr; + GameRunNamedAnimDestructorHandler* pRunNamedAnimDestructorHandler = nullptr; // Reentrancy protection for CStreamingRemoveModel static std::atomic g_bStreamingRemoveModelInProgress{false}; static std::atomic_flag g_streamingRemoveModelLock{}; - #define FUNC_CPtrListSingleLink_Remove 0x0533610 - #define FUNC_CPtrListDoubleLink_Remove 0x05336B0 - #define FUNC_CPhysical_RemoveFromMovingList 0x542860 +#define FUNC_CPtrListSingleLink_Remove 0x0533610 +#define FUNC_CPtrListDoubleLink_Remove 0x05336B0 +#define FUNC_CPhysical_RemoveFromMovingList 0x542860 struct SStreamSectorEntrySingle { @@ -53,13 +53,13 @@ namespace }; CFastHashMap ms_EntitySAInterfaceExtraInfoMap; - std::mutex ms_EntityMapMutex; // Protects ms_EntitySAInterfaceExtraInfoMap + std::mutex ms_EntityMapMutex; // Protects ms_EntitySAInterfaceExtraInfoMap void RemoveEntitySAInterfaceExtraInfo(CEntitySAInterface* pEntitySAInterface) { const std::lock_guard lock(ms_EntityMapMutex); MapRemove(ms_EntitySAInterfaceExtraInfoMap, pEntitySAInterface); - } // + } // // CPtrListSingleLink contains item // [[nodiscard]] bool CPtrListSingleLink_Contains(SStreamSectorEntrySingle* pStreamEntry, CEntitySAInterface* pCheckEntity) noexcept @@ -128,19 +128,19 @@ namespace // Copy sector lists while holding lock to prevent dangling pointers std::vector sectorSingleList; std::vector sectorDoubleList; - + { const std::lock_guard lock(ms_EntityMapMutex); // Can throw std::system_error - auto* const pInfo = MapFind(ms_EntitySAInterfaceExtraInfoMap, pEntity); - + auto* const pInfo = MapFind(ms_EntitySAInterfaceExtraInfoMap, pEntity); + if (!pInfo) [[unlikely]] return; - + // Remove map entry FIRST, before moving vectors, to prevent leak if move throws. // Use std::move for exception safety (move hardly throws). sectorSingleList = std::move(pInfo->AddedSectorSingleList); // Usually noexcept sectorDoubleList = std::move(pInfo->AddedSectorDoubleList); // Usually noexcept - + // Now safe to remove - entry has been emptied MapRemove(ms_EntitySAInterfaceExtraInfoMap, pEntity); } @@ -166,7 +166,7 @@ namespace // This is acceptable as entity destructor will eventually clean up } } -} // namespace +} // namespace //////////////////////////////////////////////////////////////////////////////////////////////// // @@ -178,8 +178,8 @@ void __cdecl CAnimBlendAssoc_destructor(CAnimBlendAssociationSAInterface* pThis) } } -#define HOOKPOS_CAnimBlendAssoc_destructor 0x4CECF0 -static DWORD RETURN_CAnimBlendAssoc_destructor = 0x4CECF6; +#define HOOKPOS_CAnimBlendAssoc_destructor 0x4CECF0 +static DWORD RETURN_CAnimBlendAssoc_destructor = 0x4CECF6; static void __declspec(naked) HOOK_CAnimBlendAssoc_destructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -222,9 +222,9 @@ void _cdecl OnCObjectDestructor(DWORD calledFrom, CObjectSAInterface* pObject) } // Hook info -#define HOOKPOS_CObjectDestructor 0x59F660 -#define HOOKSIZE_CObjectDestructor 7 -DWORD RETURN_CObjectDestructor = 0x59F667; +#define HOOKPOS_CObjectDestructor 0x59F660 +#define HOOKSIZE_CObjectDestructor 7 +DWORD RETURN_CObjectDestructor = 0x59F667; static void __declspec(naked) HOOK_CObjectDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -269,9 +269,10 @@ void _cdecl OnVehicleDestructor(DWORD calledFrom, CVehicleSAInterface* pVehicle) } // Hook info -#define HOOKPOS_CVehicleDestructor 0x6E2B40 -#define HOOKSIZE_CVehicleDestructor 7 -DWORD RETURN_CVehicleDestructor = 0x6E2B47; // Avoid SA's anti-disasm obfuscation at 0x401355 (which had been the return address for years), jump directly to real destructor body +#define HOOKPOS_CVehicleDestructor 0x6E2B40 +#define HOOKSIZE_CVehicleDestructor 7 +DWORD RETURN_CVehicleDestructor = + 0x6E2B47; // Avoid SA's anti-disasm obfuscation at 0x401355 (which had been the return address for years), jump directly to real destructor body static void __declspec(naked) HOOK_CVehicleDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -315,9 +316,9 @@ void _cdecl OnCPlayerPedDestructor(DWORD calledFrom, CPedSAInterface* pPlayerPed } // Hook info -#define HOOKPOS_CPlayerPedDestructor 0x6093B0 -#define HOOKSIZE_CPlayerPedDestructor 7 -DWORD RETURN_CPlayerPedDestructor = 0x6093B7; +#define HOOKPOS_CPlayerPedDestructor 0x6093B0 +#define HOOKSIZE_CPlayerPedDestructor 7 +DWORD RETURN_CPlayerPedDestructor = 0x6093B7; static void __declspec(naked) HOOK_CPlayerPedDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -358,9 +359,9 @@ void _cdecl OnCProjectileDestructor(DWORD calledFrom, CEntitySAInterface* pProje } // Hook info -#define HOOKPOS_CProjectileDestructor 0x5A40E0 -#define HOOKSIZE_CProjectileDestructor 6 -DWORD RETURN_CProjectileDestructor = 0x5A40E6; +#define HOOKPOS_CProjectileDestructor 0x5A40E0 +#define HOOKSIZE_CProjectileDestructor 6 +DWORD RETURN_CProjectileDestructor = 0x5A40E6; static void __declspec(naked) HOOK_CProjectileDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -407,7 +408,7 @@ void _cdecl OnCPhysicalDestructor(DWORD calledFrom, CPhysicalSAInterface* pEntit // Called from naked asm hook - MUST NOT throw or stack is corrupted // If SString alloc fails, skip logging but continue cleanup } - + // Always perform the actual removal, even if logging failed DWORD dwFunc = FUNC_CPhysical_RemoveFromMovingList; // clang-format off @@ -421,9 +422,9 @@ void _cdecl OnCPhysicalDestructor(DWORD calledFrom, CPhysicalSAInterface* pEntit } // Hook info -#define HOOKPOS_CPhysicalDestructor 0x542450 -#define HOOKSIZE_CPhysicalDestructor 7 -DWORD RETURN_CPhysicalDestructor = 0x542457; +#define HOOKPOS_CPhysicalDestructor 0x542450 +#define HOOKSIZE_CPhysicalDestructor 7 +DWORD RETURN_CPhysicalDestructor = 0x542457; static void __declspec(naked) HOOK_CPhysicalDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -463,9 +464,9 @@ void _cdecl OnCEntityDestructor(DWORD calledFrom, CEntitySAInterface* pEntity) } // Hook info -#define HOOKPOS_CEntityDestructor 0x535E97 -#define HOOKSIZE_CEntityDestructor 6 -DWORD RETURN_CEntityDestructor = 0x535E9D; +#define HOOKPOS_CEntityDestructor 0x535E97 +#define HOOKSIZE_CEntityDestructor 6 +DWORD RETURN_CEntityDestructor = 0x535E9D; static void __declspec(naked) HOOK_CEntityDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -501,7 +502,7 @@ void cdecl OnCEntityAddMid1(SStreamSectorEntrySingle** ppStreamEntryList, CEntit try { const std::lock_guard lock(ms_EntityMapMutex); - + // Find or create entry - use find() first to prevent empty entry leak if push_back throws auto it = ms_EntitySAInterfaceExtraInfoMap.find(pEntitySAInterface); if (it != ms_EntitySAInterfaceExtraInfoMap.end()) @@ -513,7 +514,7 @@ void cdecl OnCEntityAddMid1(SStreamSectorEntrySingle** ppStreamEntryList, CEntit { // Entry doesn't exist - create with initial value to avoid empty entry leak SEntitySAInterfaceExtraInfo info; - info.AddedSectorSingleList.push_back(ppStreamEntryList); // May throw - info is local, no leak + info.AddedSectorSingleList.push_back(ppStreamEntryList); // May throw - info is local, no leak ms_EntitySAInterfaceExtraInfoMap[pEntitySAInterface] = std::move(info); // Move assignment (noexcept) } } @@ -525,10 +526,10 @@ void cdecl OnCEntityAddMid1(SStreamSectorEntrySingle** ppStreamEntryList, CEntit } // Hook info -#define HOOKPOS_CEntityAddMid1 0x5348FB -#define HOOKSIZE_CEntityAddMid1 5 -#define HOOKCHECK_CEntityAddMid1 0xE8 -DWORD RETURN_CEntityAddMid1 = 0x534900; +#define HOOKPOS_CEntityAddMid1 0x5348FB +#define HOOKSIZE_CEntityAddMid1 5 +#define HOOKCHECK_CEntityAddMid1 0xE8 +DWORD RETURN_CEntityAddMid1 = 0x534900; static void __declspec(naked) HOOK_CEntityAddMid1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -570,7 +571,7 @@ void cdecl OnCEntityAddMid2(SStreamSectorEntrySingle** ppStreamEntryList, CEntit try { const std::lock_guard lock(ms_EntityMapMutex); - + // Find or create entry - use find() first to prevent empty entry leak if push_back throws auto it = ms_EntitySAInterfaceExtraInfoMap.find(pEntitySAInterface); if (it != ms_EntitySAInterfaceExtraInfoMap.end()) @@ -582,7 +583,7 @@ void cdecl OnCEntityAddMid2(SStreamSectorEntrySingle** ppStreamEntryList, CEntit { // Entry doesn't exist - create with initial value to avoid empty entry leak SEntitySAInterfaceExtraInfo info; - info.AddedSectorSingleList.push_back(ppStreamEntryList); // May throw - info is local, no leak + info.AddedSectorSingleList.push_back(ppStreamEntryList); // May throw - info is local, no leak ms_EntitySAInterfaceExtraInfoMap[pEntitySAInterface] = std::move(info); // Move assignment (noexcept) } } @@ -594,10 +595,10 @@ void cdecl OnCEntityAddMid2(SStreamSectorEntrySingle** ppStreamEntryList, CEntit } // Hook info -#define HOOKPOS_CEntityAddMid2 0x534A10 -#define HOOKSIZE_CEntityAddMid2 5 -#define HOOKCHECK_CEntityAddMid2 0xE8 -DWORD RETURN_CEntityAddMid2 = 0x534A15; +#define HOOKPOS_CEntityAddMid2 0x534A10 +#define HOOKSIZE_CEntityAddMid2 5 +#define HOOKCHECK_CEntityAddMid2 0xE8 +DWORD RETURN_CEntityAddMid2 = 0x534A15; static void __declspec(naked) HOOK_CEntityAddMid2() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -633,13 +634,13 @@ static void __declspec(naked) HOOK_CEntityAddMid2() // void cdecl OnCEntityAddMid3(SStreamSectorEntryDouble** ppStreamEntryList, CEntitySAInterface* pEntitySAInterface) noexcept { - if (!ppStreamEntryList || !pEntitySAInterface) [[unlikely]] + if (!ppStreamEntryList || !pEntitySAInterface) [[unlikely]] return; try { const std::lock_guard lock(ms_EntityMapMutex); - + // Find or create entry - use find() first to prevent empty entry leak if push_back throws auto it = ms_EntitySAInterfaceExtraInfoMap.find(pEntitySAInterface); if (it != ms_EntitySAInterfaceExtraInfoMap.end()) @@ -651,7 +652,7 @@ void cdecl OnCEntityAddMid3(SStreamSectorEntryDouble** ppStreamEntryList, CEntit { // Entry doesn't exist - create with initial value to avoid empty entry leak SEntitySAInterfaceExtraInfo info; - info.AddedSectorDoubleList.push_back(ppStreamEntryList); // May throw - info is local, no leak + info.AddedSectorDoubleList.push_back(ppStreamEntryList); // May throw - info is local, no leak ms_EntitySAInterfaceExtraInfoMap[pEntitySAInterface] = std::move(info); // Move assignment (noexcept) } } @@ -663,10 +664,10 @@ void cdecl OnCEntityAddMid3(SStreamSectorEntryDouble** ppStreamEntryList, CEntit } // Hook info -#define HOOKPOS_CEntityAddMid3 0x534AA2 -#define HOOKSIZE_CEntityAddMid3 5 -#define HOOKCHECK_CEntityAddMid3 0xE8 -DWORD RETURN_CEntityAddMid3 = 0x534AA7; +#define HOOKPOS_CEntityAddMid3 0x534AA2 +#define HOOKSIZE_CEntityAddMid3 5 +#define HOOKCHECK_CEntityAddMid3 0xE8 +DWORD RETURN_CEntityAddMid3 = 0x534AA7; static void __declspec(naked) HOOK_CEntityAddMid3() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -709,10 +710,10 @@ void cdecl OnCEntityRemovePost(CEntitySAInterface* pEntity) } // Hook info -#define HOOKPOS_CEntityRemove 0x534AE0 -#define HOOKSIZE_CEntityRemove 5 -#define HOOKCHECK_CEntityRemove 0x83 -DWORD RETURN_CEntityRemove = 0x534AE5; +#define HOOKPOS_CEntityRemove 0x534AE0 +#define HOOKSIZE_CEntityRemove 5 +#define HOOKCHECK_CEntityRemove 0x83 +DWORD RETURN_CEntityRemove = 0x534AE5; static void __declspec(naked) HOOK_CEntityRemove() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -753,7 +754,6 @@ static void __declspec(naked) HOOK_CEntityRemove() // clang-format on } - static void CallGameModelRemoveHandlerSafe(GameModelRemoveHandler* handler, ushort modelId) { __try @@ -772,12 +772,12 @@ void _cdecl OnCStreamingRemoveModel(DWORD calledFrom, int modelId) noexcept bool bLockAcquired = false; bool bTimeout = false; - int attemptCount = 0; - + int attemptCount = 0; + // Acquire spinlock with timeout constexpr int MAX_SPIN_ATTEMPTS = 50000; // ~50ms on most CPU's - int spinCount = 0; - + int spinCount = 0; + while (g_streamingRemoveModelLock.test_and_set(std::memory_order_acquire)) { if (++spinCount > MAX_SPIN_ATTEMPTS) @@ -788,32 +788,31 @@ void _cdecl OnCStreamingRemoveModel(DWORD calledFrom, int modelId) noexcept } SwitchToThread(); } - + if (!bTimeout) { bLockAcquired = true; - + // Call handler with exception protection auto* const handler = pGameModelRemoveHandler.load(std::memory_order_acquire); if (handler) [[likely]] { CallGameModelRemoveHandlerSafe(handler, static_cast(modelId)); } - + // Release spinlock g_streamingRemoveModelLock.clear(std::memory_order_release); } - + // Always release reentrancy flag g_bStreamingRemoveModelInProgress.store(false, std::memory_order_release); - + // Log timeout (SString can throw, so wrap in try/catch) if (bTimeout) { try { - AddReportLog(8641, SString("Failed to acquire CStreamingRemoveModel lock after %d attempts (modelId=%d)", - attemptCount, modelId)); + AddReportLog(8641, SString("Failed to acquire CStreamingRemoveModel lock after %d attempts (modelId=%d)", attemptCount, modelId)); } catch (...) { @@ -824,9 +823,9 @@ void _cdecl OnCStreamingRemoveModel(DWORD calledFrom, int modelId) noexcept } // Hook info -#define HOOKPOS_CStreamingRemoveModel 0x4089A0 -#define HOOKSIZE_CStreamingRemoveModel 6 -DWORD RETURN_CStreamingRemoveModel = 0x4089A6; +#define HOOKPOS_CStreamingRemoveModel 0x4089A0 +#define HOOKSIZE_CStreamingRemoveModel 6 +DWORD RETURN_CStreamingRemoveModel = 0x4089A6; static void __declspec(naked) HOOK_CStreamingRemoveModel() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -868,9 +867,9 @@ void _cdecl OnCTaskSimpleRunNamedAnimDestructor(class CTaskSimpleRunNamedAnimSAI } // Hook info -#define HOOKPOS_CTaskSimpleRunNamedAnimDestructor 0x61BEF0 -#define HOOKSIZE_CTaskSimpleRunNamedAnimDestructor 8 -DWORD RETURN_CTaskSimpleRunNamedAnim = 0x61BEF8; +#define HOOKPOS_CTaskSimpleRunNamedAnimDestructor 0x61BEF0 +#define HOOKSIZE_CTaskSimpleRunNamedAnimDestructor 8 +DWORD RETURN_CTaskSimpleRunNamedAnim = 0x61BEF8; static void __declspec(naked) HOOK_CTaskSimpleRunNamedAnimDestructor() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_LicensePlate.cpp b/Client/multiplayer_sa/CMultiplayerSA_LicensePlate.cpp index 030686090d2..4c62bde3215 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_LicensePlate.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_LicensePlate.cpp @@ -22,7 +22,7 @@ namespace std::vector ms_SavedTextureList; CVehicleModelInfoSAInterface* ms_pProcessingVehicleModelInfo = NULL; RwTexture* ms_pLastGeneratedPlateText = NULL; -} // namespace +} // namespace ////////////////////////////////////////////////////////////////////////////////////////// // @@ -58,9 +58,9 @@ void OnMY_CAutomobile_CustomCarPlate_BeforeRenderingStart(CVehicleSAInterface* p } // Hook info -#define HOOKPOS_CAutomobile_CustomCarPlate_BeforeRenderingStart 0x006A2F00 -#define HOOKSIZE_CAutomobile_CustomCarPlate_BeforeRenderingStart 7 -DWORD RETURN_CAutomobile_CustomCarPlate_BeforeRenderingStart = 0x006A2F07; +#define HOOKPOS_CAutomobile_CustomCarPlate_BeforeRenderingStart 0x006A2F00 +#define HOOKSIZE_CAutomobile_CustomCarPlate_BeforeRenderingStart 7 +DWORD RETURN_CAutomobile_CustomCarPlate_BeforeRenderingStart = 0x006A2F07; static void __declspec(naked) HOOK_CAutomobile_CustomCarPlate_BeforeRenderingStart() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -117,9 +117,9 @@ void OnMY_CAutomobile_CustomCarPlate_AfterRenderingStop(CVehicleModelInfoSAInter } // Hook info -#define HOOKPOS_CAutomobile_CustomCarPlate_AfterRenderingStop 0x006A2F30 -#define HOOKSIZE_CAutomobile_CustomCarPlate_AfterRenderingStop 7 -DWORD RETURN_CAutomobile_CustomCarPlate_AfterRenderingStop = 0x006A2F37; +#define HOOKPOS_CAutomobile_CustomCarPlate_AfterRenderingStop 0x006A2F30 +#define HOOKSIZE_CAutomobile_CustomCarPlate_AfterRenderingStop 7 +DWORD RETURN_CAutomobile_CustomCarPlate_AfterRenderingStop = 0x006A2F37; static void __declspec(naked) HOOK_CAutomobile_CustomCarPlate_AfterRenderingStop() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -157,9 +157,9 @@ void OnMY_CCustomCarPlateMgr_SetupMaterialPlateTexture(struct RpMaterial* a, cha } // Hook info -#define HOOKPOS_CCustomCarPlateMgr_SetupMaterialPlateTexture 0x006FE020 -#define HOOKSIZE_CCustomCarPlateMgr_SetupMaterialPlateTexture 5 -DWORD RETURN_CCustomCarPlateMgr_SetupMaterialPlateTexture = 0x006FE025; +#define HOOKPOS_CCustomCarPlateMgr_SetupMaterialPlateTexture 0x006FE020 +#define HOOKSIZE_CCustomCarPlateMgr_SetupMaterialPlateTexture 5 +DWORD RETURN_CCustomCarPlateMgr_SetupMaterialPlateTexture = 0x006FE025; static void __declspec(naked) HOOK_CCustomCarPlateMgr_SetupMaterialPlateTexture() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -205,9 +205,9 @@ void OnMY_CVehicleModelInfo_SetCarCustomPlate_Post() } // Hook info -#define HOOKPOS_CVehicleModelInfo_SetCarCustomPlate 0x004C9450 -#define HOOKSIZE_CVehicleModelInfo_SetCarCustomPlate 6 -DWORD RETURN_CVehicleModelInfo_SetCarCustomPlate = 0x004C9456; +#define HOOKPOS_CVehicleModelInfo_SetCarCustomPlate 0x004C9450 +#define HOOKSIZE_CVehicleModelInfo_SetCarCustomPlate 6 +DWORD RETURN_CVehicleModelInfo_SetCarCustomPlate = 0x004C9456; static void __declspec(naked) HOOK_CVehicleModelInfo_SetCarCustomPlate() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -245,9 +245,9 @@ static void __declspec(naked) HOOK_CVehicleModelInfo_SetCarCustomPlate() // Prevent GTA from generating a new texture for each occurrence of 'carplate' in a model // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CCustomCarPlateMgr_CreatePlateTexture 0x006FDEA0 -#define HOOKSIZE_CCustomCarPlateMgr_CreatePlateTexture 5 -DWORD RETURN_CCustomCarPlateMgr_CreatePlateTexture = 0x006FDEA5; +#define HOOKPOS_CCustomCarPlateMgr_CreatePlateTexture 0x006FDEA0 +#define HOOKSIZE_CCustomCarPlateMgr_CreatePlateTexture 5 +DWORD RETURN_CCustomCarPlateMgr_CreatePlateTexture = 0x006FDEA5; static void __declspec(naked) HOOK_CCustomCarPlateMgr_CreatePlateTexture() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_ObjectCollision.cpp b/Client/multiplayer_sa/CMultiplayerSA_ObjectCollision.cpp index d737428af1e..232305d3905 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ObjectCollision.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ObjectCollision.cpp @@ -42,8 +42,8 @@ static void ColStoreRemoveRef(CObjectSAInterface* gameObject) // >>> 0x59F8D1 | 0D 00 00 01 00 | or eax, 10000h // >>> 0x59F8D6 | 89 86 40 01 00 00 | mov [esi+140h], eax // 0x59F8DC | 0F BF 4E 22 | movsx ecx, word ptr [esi+22h] -#define HOOKPOS_CObject_Init 0x59F8BE -#define HOOKSIZE_CObject_Init 30 +#define HOOKPOS_CObject_Init 0x59F8BE +#define HOOKSIZE_CObject_Init 30 static const DWORD CONTINUE_CObject_Init = 0x59F8DC; static void __declspec(naked) HOOK_CObject_Init() @@ -85,8 +85,8 @@ static void __declspec(naked) HOOK_CObject_Init() // >>> 0x59F701 | E8 CA 10 E7 FF | call CColStore::RemoveRef(int) // >>> 0x59F706 | 83 C4 04 | add esp, 4 // 0x59F709 | 8B 3D 9C 44 B7 00 | mov edi, ds:CPools::ms_pObjectPool -#define HOOKPOS_CObject_Destructor 0x59F6EE -#define HOOKSIZE_CObject_Destructor 27 +#define HOOKPOS_CObject_Destructor 0x59F6EE +#define HOOKSIZE_CObject_Destructor 27 static const DWORD CONTINUE_CObject_Destructor = 0x59F709; static void __declspec(naked) HOOK_CObject_Destructor() diff --git a/Client/multiplayer_sa/CMultiplayerSA_ObjectLODSystem.cpp b/Client/multiplayer_sa/CMultiplayerSA_ObjectLODSystem.cpp index e390d7de4e9..1b3e3823eea 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ObjectLODSystem.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ObjectLODSystem.cpp @@ -18,12 +18,18 @@ //////////////////////////////////////////////// namespace { - // #define ARRAY_ModelInfo 0xA9B0C8 - #define LOW_LOD_DRAW_DISTANCE_SCALE 5 +// #define ARRAY_ModelInfo 0xA9B0C8 +#define LOW_LOD_DRAW_DISTANCE_SCALE 5 - void SetGlobalDrawDistanceScale(float fValue) { MemPut(0x858FD8, 300.f * fValue); } + void SetGlobalDrawDistanceScale(float fValue) + { + MemPut(0x858FD8, 300.f * fValue); + } - float GetDrawDistanceSetting() { return *(float*)0xB6F118; } + float GetDrawDistanceSetting() + { + return *(float*)0xB6F118; + } float CalculateLowLodFadeAlpha(CBaseModelInfoSAInterface* pModelInfo, float fDist) { @@ -40,7 +46,7 @@ namespace float fLodDistanceUnscaled; CBaseModelInfoSAInterface* pModelInfo; } saved = {false, 0.f, NULL}; -} // namespace +} // namespace //////////////////////////////////////////////// // @@ -84,9 +90,9 @@ void OnMY_CRenderer_SetupEntityVisibility_Post(int result, CEntitySAInterface* p } // Hook info -#define HOOKPOS_CRenderer_SetupEntityVisibility 0x554230 -#define HOOKSIZE_CRenderer_SetupEntityVisibility 8 -DWORD RETURN_CRenderer_SetupEntityVisibility = 0x554238; +#define HOOKPOS_CRenderer_SetupEntityVisibility 0x554230 +#define HOOKSIZE_CRenderer_SetupEntityVisibility 8 +DWORD RETURN_CRenderer_SetupEntityVisibility = 0x554238; static void __declspec(naked) HOOK_CRenderer_SetupEntityVisibility() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -147,10 +153,10 @@ void OnMY_CWorldScan_ScanWorld_Pre(CVector2D* pVec, int iValue, void(__cdecl* fu } // Hook info -#define HOOKPOS_CWorldScan_ScanWorld 0x55555E -#define HOOKSIZE_CWorldScan_ScanWorld 5 -DWORD RETURN_CWorldScan_ScanWorlda = 0x555563; -DWORD RETURN_CWorldScan_ScanWorldb = 0x72CAE0; +#define HOOKPOS_CWorldScan_ScanWorld 0x55555E +#define HOOKSIZE_CWorldScan_ScanWorld 5 +DWORD RETURN_CWorldScan_ScanWorlda = 0x555563; +DWORD RETURN_CWorldScan_ScanWorldb = 0x72CAE0; static void __declspec(naked) HOOK_CWorldScan_ScanWorld() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -193,9 +199,9 @@ int OnMY_CVisibilityPlugins_CalculateFadingAtomicAlpha_Pre(CBaseModelInfoSAInter } // Hook info -#define HOOKPOS_CVisibilityPlugins_CalculateFadingAtomicAlpha 0x732500 -#define HOOKSIZE_CVisibilityPlugins_CalculateFadingAtomicAlpha 5 -DWORD RETURN_CVisibilityPlugins_CalculateFadingAtomicAlpha = 0x732505; +#define HOOKPOS_CVisibilityPlugins_CalculateFadingAtomicAlpha 0x732500 +#define HOOKSIZE_CVisibilityPlugins_CalculateFadingAtomicAlpha 5 +DWORD RETURN_CVisibilityPlugins_CalculateFadingAtomicAlpha = 0x732505; static void __declspec(naked) HOOK_CVisibilityPlugins_CalculateFadingAtomicAlpha() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -251,7 +257,7 @@ void CMultiplayerSA::SetLODSystemEnabled(bool bEnable) // Memory saved here static CBuffer savedMem; SHookInfo hookInfoList[] = {MAKE_HOOK_INFO(CRenderer_SetupEntityVisibility), MAKE_HOOK_INFO(CWorldScan_ScanWorld), - MAKE_HOOK_INFO(CVisibilityPlugins_CalculateFadingAtomicAlpha)}; + MAKE_HOOK_INFO(CVisibilityPlugins_CalculateFadingAtomicAlpha)}; // Enable or not? if (bEnable) diff --git a/Client/multiplayer_sa/CMultiplayerSA_ObjectStreamerOptimization.cpp b/Client/multiplayer_sa/CMultiplayerSA_ObjectStreamerOptimization.cpp index 895eb9d7b57..cde18d68ab2 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ObjectStreamerOptimization.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ObjectStreamerOptimization.cpp @@ -13,7 +13,7 @@ static unsigned int CEntryInfoNodePool_UsedSpaces = 0; static unsigned int CPtrNodeDoubleLinkPool_UsedSpaces = 0; -#define HOOKPOS_CEntryInfoNodePool__New 0x536D6E +#define HOOKPOS_CEntryInfoNodePool__New 0x536D6E #define HOOKSIZE_CEntryInfoNodePool__New 0x5 static void __declspec(naked) HOOK_CEntryInfoNodePool__New() { @@ -31,9 +31,9 @@ static void __declspec(naked) HOOK_CEntryInfoNodePool__New() // clang-format on } -#define HOOKPOS_CEntryInfoNode__operator_delete 0x536DF1 +#define HOOKPOS_CEntryInfoNode__operator_delete 0x536DF1 #define HOOKSIZE_CEntryInfoNode__operator_delete 0x6 -static const unsigned int RETURN_CEntryInfoNode__operator_delete = 0x536DF7; +static const unsigned int RETURN_CEntryInfoNode__operator_delete = 0x536DF7; static void __declspec(naked) HOOK_CEntryInfoNode__operator_delete() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -50,9 +50,9 @@ static void __declspec(naked) HOOK_CEntryInfoNode__operator_delete() // clang-format on } -#define HOOKPOS_CEntryInfoList__Flush 0x536E6C +#define HOOKPOS_CEntryInfoList__Flush 0x536E6C #define HOOKSIZE_CEntryInfoList__Flush 0x5 -static const unsigned int RETURN_CEntryInfoList__Flush = 0x536E71; +static const unsigned int RETURN_CEntryInfoList__Flush = 0x536E71; static void __declspec(naked) HOOK_CEntryInfoList__Flush() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -69,7 +69,7 @@ static void __declspec(naked) HOOK_CEntryInfoList__Flush() // clang-format on } -#define HOOKPOS_CPtrNodeDoubleLinkPool__New 0x55233E +#define HOOKPOS_CPtrNodeDoubleLinkPool__New 0x55233E #define HOOKSIZE_CPtrNodeDoubleLinkPool__New 0x6 static void __declspec(naked) HOOK_CPtrNodeDoubleLinkPool__New() { @@ -87,9 +87,9 @@ static void __declspec(naked) HOOK_CPtrNodeDoubleLinkPool__New() // clang-format on } -#define HOOKPOS_CPtrNodeDoubleLink__operator_delete 0x5523F0 +#define HOOKPOS_CPtrNodeDoubleLink__operator_delete 0x5523F0 #define HOOKSIZE_CPtrNodeDoubleLink__operator_delete 0x6 -static const unsigned int RETURN_CPtrNodeDoubleLink__operator_delete = 0x5523F6; +static const unsigned int RETURN_CPtrNodeDoubleLink__operator_delete = 0x5523F6; static void __declspec(naked) HOOK_CPtrNodeDoubleLink__operator_delete() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -106,9 +106,9 @@ static void __declspec(naked) HOOK_CPtrNodeDoubleLink__operator_delete() // clang-format on } -#define HOOKPOS_CPtrListDoubleLink__Flush 0x5524CB +#define HOOKPOS_CPtrListDoubleLink__Flush 0x5524CB #define HOOKSIZE_CPtrListDoubleLink__Flush 0x5 -static const unsigned int RETURN_CPtrListDoubleLink__Flush = 0x5524D0; +static const unsigned int RETURN_CPtrListDoubleLink__Flush = 0x5524D0; static void __declspec(naked) HOOK_CPtrListDoubleLink__Flush() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Peds.cpp b/Client/multiplayer_sa/CMultiplayerSA_Peds.cpp index 18d815a83d4..8e022e6eda7 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Peds.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Peds.cpp @@ -29,8 +29,8 @@ static void __cdecl DoFootLanded(CPedSAInterface* pPedSAInterface, short footId, pPedStepHandler(pPedSAInterface, footId == LANDED_PED_LEFT_FOOT ? true : false); } -#define HOOKPOS_CPed_DoFootLanded 0x5E5380 -#define HOOKSIZE_CPed_DoFootLanded 6 +#define HOOKPOS_CPed_DoFootLanded 0x5E5380 +#define HOOKSIZE_CPed_DoFootLanded 6 static const DWORD CONTINUE_CPed_DoFootLanded = 0x5E5386; static void __declspec(naked) HOOK_CPed_DoFootLanded() diff --git a/Client/multiplayer_sa/CMultiplayerSA_Postprocess.cpp b/Client/multiplayer_sa/CMultiplayerSA_Postprocess.cpp index 4155328fca1..d7a4313c30f 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Postprocess.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Postprocess.cpp @@ -35,40 +35,28 @@ namespace GrainEffect { static float fMultiplier; - static void ApplyEffect(int grainStrength, bool updateGrainRaster) - { - MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); - } + static void ApplyEffect(int grainStrength, bool updateGrainRaster) { MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); } }; struct NightModifier { static float fMultiplier; - static void ApplyEffect(int grainStrength, bool updateGrainRaster) - { - MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); - } + static void ApplyEffect(int grainStrength, bool updateGrainRaster) { MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); } }; struct RainModifier { static float fMultiplier; - static void ApplyEffect(int grainStrength, bool updateGrainRaster) - { - MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); - } + static void ApplyEffect(int grainStrength, bool updateGrainRaster) { MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); } }; struct OverlayModifier { static float fMultiplier; - static void ApplyEffect(int grainStrength, bool updateGrainRaster) - { - MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); - } + static void ApplyEffect(int grainStrength, bool updateGrainRaster) { MasterModifier::ApplyEffect(grainStrength * fMultiplier, updateGrainRaster); } }; float MasterModifier::fMultiplier = 1.0f; @@ -76,7 +64,7 @@ namespace GrainEffect float NightModifier::fMultiplier = 1.0f; float RainModifier::fMultiplier = 1.0f; float OverlayModifier::fMultiplier = 1.0f; -} // namespace GrainEffect +} void CMultiplayerSA::SetGrainMultiplier(eGrainMultiplierType type, float fMultiplier) { @@ -136,7 +124,7 @@ void CMultiplayerSA::SetGrainLevel(BYTE ucLevel) void CMultiplayerSA::SetNightVisionEnabled(bool bEnabled, bool bNoiseEnabled) { - MemPutFast(0xC402B8, bEnabled ? 1 : 0); // bool CPostEffects::m_bNightVision + MemPutFast(0xC402B8, bEnabled ? 1 : 0); // bool CPostEffects::m_bNightVision if (bNoiseEnabled) { @@ -150,7 +138,7 @@ void CMultiplayerSA::SetNightVisionEnabled(bool bEnabled, bool bNoiseEnabled) void CMultiplayerSA::SetThermalVisionEnabled(bool bEnabled, bool bNoiseEnabled) { - MemPutFast(0xC402B9, bEnabled ? 1 : 0); // bool CPostEffects::m_bInfraredVision + MemPutFast(0xC402B9, bEnabled ? 1 : 0); // bool CPostEffects::m_bInfraredVision if (bNoiseEnabled) { @@ -164,12 +152,12 @@ void CMultiplayerSA::SetThermalVisionEnabled(bool bEnabled, bool bNoiseEnabled) bool CMultiplayerSA::IsNightVisionEnabled() { - return (*(BYTE*)0xC402B8 == 1); // bool CPostEffects::m_bNightVision + return (*(BYTE*)0xC402B8 == 1); // bool CPostEffects::m_bNightVision } bool CMultiplayerSA::IsThermalVisionEnabled() { - return (*(BYTE*)0xC402B9 == 1); // bool CPostEffects::m_bInfraredVision + return (*(BYTE*)0xC402B9 == 1); // bool CPostEffects::m_bInfraredVision } void CMultiplayerSA::InitHooks_Postprocess() diff --git a/Client/multiplayer_sa/CMultiplayerSA_ProjectileCollisionFix.cpp b/Client/multiplayer_sa/CMultiplayerSA_ProjectileCollisionFix.cpp index 268f2dbd3b2..187269d5302 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_ProjectileCollisionFix.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_ProjectileCollisionFix.cpp @@ -32,9 +32,9 @@ static void InitializeGrenadeColModel() &colModelGrenade.m_data->m_spheres[0], colModelGrenade.m_sphere.m_radius * 0.75f, colModelGrenade.m_sphere.m_center, 56, 0, 255); } -#define HOOKPOS_CTempColModels__Initialise 0x5BB87D +#define HOOKPOS_CTempColModels__Initialise 0x5BB87D #define HOOKSIZE_CTempColModels__Initialise 0x6 -static const unsigned int RETURN_CTempColModels__Initialise = 0x5BB883; +static const unsigned int RETURN_CTempColModels__Initialise = 0x5BB883; static void __declspec(naked) HOOK_CTempColModels__Initialise() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -51,9 +51,9 @@ static void __declspec(naked) HOOK_CTempColModels__Initialise() // clang-format on } -#define HOOKPOS_CFileLoader__LoadWeaponObject 0x5B401E +#define HOOKPOS_CFileLoader__LoadWeaponObject 0x5B401E #define HOOKSIZE_CFileLoader__LoadWeaponObject 0x5 -static const unsigned int RETURN_CFileLoader__LoadWeaponObject = 0x5B4023; +static const unsigned int RETURN_CFileLoader__LoadWeaponObject = 0x5B4023; static void __declspec(naked) HOOK_CFileLoader__LoadWeaponObject() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Rendering.cpp b/Client/multiplayer_sa/CMultiplayerSA_Rendering.cpp index ae99be23804..e539576c726 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Rendering.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Rendering.cpp @@ -9,14 +9,14 @@ *****************************************************************************/ #include "StdInc.h" -extern CCoreInterface* g_pCore; -GameEntityRenderHandler* pGameEntityRenderHandler = nullptr; -PreRenderSkyHandler* pPreRenderSkyHandlerHandler = nullptr; -RenderHeliLightHandler* pRenderHeliLightHandler = nullptr; -RenderEverythingBarRoadsHandler* pRenderEverythingBarRoadsHandler = nullptr; +extern CCoreInterface* g_pCore; +GameEntityRenderHandler* pGameEntityRenderHandler = nullptr; +PreRenderSkyHandler* pPreRenderSkyHandlerHandler = nullptr; +RenderHeliLightHandler* pRenderHeliLightHandler = nullptr; +RenderEverythingBarRoadsHandler* pRenderEverythingBarRoadsHandler = nullptr; -#define VAR_CCullZones_NumMirrorAttributeZones 0x0C87AC4 // int -#define VAR_CMirrors_d3dRestored 0x0C7C729 // uchar +#define VAR_CCullZones_NumMirrorAttributeZones 0x0C87AC4 // int +#define VAR_CMirrors_d3dRestored 0x0C7C729 // uchar namespace { @@ -24,7 +24,7 @@ namespace CEntitySAInterface* ms_RenderingOneNonRoad = NULL; bool ms_bIsMinimizedAndNotConnected = false; int ms_iSavedNumMirrorZones = 0; -} // namespace +} // namespace ////////////////////////////////////////////////////////////////////////////////////////// // @@ -44,10 +44,10 @@ void OnMY_CallIdle_Post(RwGeometry* pGeometry, DWORD calledFrom) } // Hook info -#define HOOKPOS_CallIdle 0x53ECBD -#define HOOKSIZE_CallIdle 5 -DWORD RETURN_CallIdle = 0x53ECC2; -DWORD DO_CallIdle = 0x53E920; +#define HOOKPOS_CallIdle 0x53ECBD +#define HOOKSIZE_CallIdle 5 +DWORD RETURN_CallIdle = 0x53ECC2; +DWORD DO_CallIdle = 0x53E920; static void __declspec(naked) HOOK_CallIdle() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -110,14 +110,14 @@ void OnMY_CEntity_Render_Post() if (ms_Rendering) { ms_Rendering = NULL; - CallGameEntityRenderHandler(ms_RenderingOneNonRoad); // restore value set in RenderOneNonRoad + CallGameEntityRenderHandler(ms_RenderingOneNonRoad); // restore value set in RenderOneNonRoad } } // Hook info -#define HOOKPOS_CEntity_Render 0x534310 -#define HOOKSIZE_CEntity_Render 6 -DWORD RETURN_CEntity_Render = 0x534317; +#define HOOKPOS_CEntity_Render 0x534310 +#define HOOKSIZE_CEntity_Render 6 +DWORD RETURN_CEntity_Render = 0x534317; static void __declspec(naked) HOOK_CEntity_Render() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -172,9 +172,9 @@ void OnMY_CEntity_RenderOneNonRoad_Post(CEntitySAInterface* pEntity) } // Hook info -#define HOOKPOS_CEntity_RenderOneNonRoad 0x553260 -#define HOOKSIZE_CEntity_RenderOneNonRoad 5 -DWORD RETURN_CEntity_RenderOneNonRoad = 0x553265; +#define HOOKPOS_CEntity_RenderOneNonRoad 0x553260 +#define HOOKSIZE_CEntity_RenderOneNonRoad 5 +DWORD RETURN_CEntity_RenderOneNonRoad = 0x553265; static void __declspec(naked) HOOK_CEntity_RenderOneNonRoad() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -223,9 +223,9 @@ void OnMY_CVisibilityPlugins_RenderWeaponPedsForPC_Mid(CPedSAInterface* pEntity) } // Hook info -#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC_Mid 0x733080 -#define HOOKSIZE_CVisibilityPlugins_RenderWeaponPedsForPC_Mid 6 -DWORD RETURN_CVisibilityPlugins_RenderWeaponPedsForPC_Mid = 0x733086; +#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC_Mid 0x733080 +#define HOOKSIZE_CVisibilityPlugins_RenderWeaponPedsForPC_Mid 6 +DWORD RETURN_CVisibilityPlugins_RenderWeaponPedsForPC_Mid = 0x733086; static void __declspec(naked) HOOK_CVisibilityPlugins_RenderWeaponPedsForPC_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -259,8 +259,8 @@ void OnMY_CVisibilityPlugins_RenderWeaponPedsForPC_End() } // Hook info -#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC_End 0x73314D -#define HOOKSIZE_CVisibilityPlugins_RenderWeaponPedsForPC_End 5 +#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC_End 0x73314D +#define HOOKSIZE_CVisibilityPlugins_RenderWeaponPedsForPC_End 5 static void __declspec(naked) HOOK_CVisibilityPlugins_RenderWeaponPedsForPC_End() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -288,9 +288,9 @@ static void __declspec(naked) HOOK_CVisibilityPlugins_RenderWeaponPedsForPC_End( // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_Check_NoOfVisibleLods 0x5534F9 -#define HOOKSIZE_Check_NoOfVisibleLods 6 -DWORD RETURN_Check_NoOfVisibleLods = 0x5534FF; +#define HOOKPOS_Check_NoOfVisibleLods 0x5534F9 +#define HOOKSIZE_Check_NoOfVisibleLods 6 +DWORD RETURN_Check_NoOfVisibleLods = 0x5534FF; static void __declspec(naked) HOOK_Check_NoOfVisibleLods() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -316,9 +316,9 @@ static void __declspec(naked) HOOK_Check_NoOfVisibleLods() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_Check_NoOfVisibleEntities 0x55352D -#define HOOKSIZE_Check_NoOfVisibleEntities 6 -DWORD RETURN_Check_NoOfVisibleEntities = 0x553533; +#define HOOKPOS_Check_NoOfVisibleEntities 0x55352D +#define HOOKSIZE_Check_NoOfVisibleEntities 6 +DWORD RETURN_Check_NoOfVisibleEntities = 0x553533; static void __declspec(naked) HOOK_Check_NoOfVisibleEntities() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -348,9 +348,9 @@ void OnMY_WinLoop() } // Hook info -#define HOOKPOS_WinLoop 0x748A93 -#define HOOKSIZE_WinLoop 5 -DWORD RETURN_WinLoop = 0x748A98; +#define HOOKPOS_WinLoop 0x748A93 +#define HOOKSIZE_WinLoop 5 +DWORD RETURN_WinLoop = 0x748A98; static void __declspec(naked) HOOK_WinLoop() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -375,9 +375,9 @@ static void __declspec(naked) HOOK_WinLoop() // Just before GTA calculates frame time deltas // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CTimer_Update 0x561B10 -#define HOOKSIZE_CTimer_Update 6 -static const DWORD CONTINUE_CTimer_Update = 0x561B16; +#define HOOKPOS_CTimer_Update 0x561B10 +#define HOOKSIZE_CTimer_Update 6 +static const DWORD CONTINUE_CTimer_Update = 0x561B16; static void __declspec(naked) HOOK_CTimer_Update() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -410,9 +410,9 @@ static void __declspec(naked) HOOK_CTimer_Update() // Prevent crashes if _timerFunction is NULL during init // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CTimer_Suspend 0x5619E9 -#define HOOKSIZE_CTimer_Suspend 6 -static const DWORD CONTINUE_CTimer_Suspend = 0x5619EF; +#define HOOKPOS_CTimer_Suspend 0x5619E9 +#define HOOKSIZE_CTimer_Suspend 6 +static const DWORD CONTINUE_CTimer_Suspend = 0x5619EF; static void _declspec(naked) HOOK_CTimer_Suspend() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -423,8 +423,8 @@ static void _declspec(naked) HOOK_CTimer_Suspend() mov eax, dword ptr ds:[0B7CB28h] test eax, eax jz skip_suspend - - // Original code: call [_timerFunction] + + // Original code: call [_timerFunction] call eax jmp CONTINUE_CTimer_Suspend @@ -436,9 +436,9 @@ static void _declspec(naked) HOOK_CTimer_Suspend() } } -#define HOOKPOS_CTimer_Resume 0x561A11 -#define HOOKSIZE_CTimer_Resume 6 -static const DWORD CONTINUE_CTimer_Resume = 0x561A17; +#define HOOKPOS_CTimer_Resume 0x561A11 +#define HOOKSIZE_CTimer_Resume 6 +static const DWORD CONTINUE_CTimer_Resume = 0x561A17; static void _declspec(naked) HOOK_CTimer_Resume() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -449,8 +449,8 @@ static void _declspec(naked) HOOK_CTimer_Resume() mov eax, dword ptr ds:[0B7CB28h] test eax, eax jz skip_resume - - // Original code: call [_timerFunction] + + // Original code: call [_timerFunction] call eax jmp CONTINUE_CTimer_Resume @@ -496,10 +496,10 @@ bool OnMY_psGrabScreen_ShouldUseRect() } // Hook info -#define HOOKPOS_psGrabScreen 0x7452FC -#define HOOKSIZE_psGrabScreen 5 -DWORD RETURN_psGrabScreen_YesChange = 0x745311; -DWORD RETURN_psGrabScreen_NoChange = 0x745336; +#define HOOKPOS_psGrabScreen 0x7452FC +#define HOOKSIZE_psGrabScreen 5 +DWORD RETURN_psGrabScreen_YesChange = 0x745311; +DWORD RETURN_psGrabScreen_NoChange = 0x745336; static void __declspec(naked) HOOK_psGrabScreen() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -544,10 +544,10 @@ void OnMY_CClouds_RenderSkyPolys() } // Hook info -#define HOOKCHECK_CClouds_RenderSkyPolys 0xA1 -#define HOOKPOS_CClouds_RenderSkyPolys 0x714650 -#define HOOKSIZE_CClouds_RenderSkyPolys 5 -DWORD RETURN_CClouds_RenderSkyPolys = 0x714655; +#define HOOKCHECK_CClouds_RenderSkyPolys 0xA1 +#define HOOKPOS_CClouds_RenderSkyPolys 0x714650 +#define HOOKSIZE_CClouds_RenderSkyPolys 5 +DWORD RETURN_CClouds_RenderSkyPolys = 0x714655; static void __declspec(naked) HOOK_CClouds_RenderSkyPolys() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -603,10 +603,10 @@ float OnMY_RwCameraSetNearClipPlane(DWORD dwCalledFrom, void* pUnknown, float fD } // Hook info -#define HOOKCHECK_RwCameraSetNearClipPlane 0xD9 -#define HOOKPOS_RwCameraSetNearClipPlane 0x7EE1D0 -#define HOOKSIZE_RwCameraSetNearClipPlane 5 -DWORD RETURN_RwCameraSetNearClipPlane = 0x7EE1D5; +#define HOOKCHECK_RwCameraSetNearClipPlane 0xD9 +#define HOOKPOS_RwCameraSetNearClipPlane 0x7EE1D0 +#define HOOKSIZE_RwCameraSetNearClipPlane 5 +DWORD RETURN_RwCameraSetNearClipPlane = 0x7EE1D5; static void __declspec(naked) HOOK_RwCameraSetNearClipPlane() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -639,9 +639,9 @@ static void __declspec(naked) HOOK_RwCameraSetNearClipPlane() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_RenderEffects_HeliLight 0x53E1B9 -#define HOOKSIZE_RenderEffects_HeliLight 5 -DWORD RETURN_RenderEffects_HeliLight = 0x53E1BE; +#define HOOKPOS_RenderEffects_HeliLight 0x53E1B9 +#define HOOKSIZE_RenderEffects_HeliLight 5 +DWORD RETURN_RenderEffects_HeliLight = 0x53E1BE; static void __declspec(naked) HOOK_RenderEffects_HeliLight() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -767,34 +767,29 @@ bool IsMatrixValid(RwMatrix* pMatrix) constexpr float maxValue = 100000.0; constexpr float minValue = -100000.0; - return - pMatrix->at.x >= minValue && pMatrix->at.x <= maxValue - && pMatrix->at.y >= minValue && pMatrix->at.y <= maxValue - && pMatrix->at.z >= minValue && pMatrix->at.y <= maxValue + return pMatrix->at.x >= minValue && pMatrix->at.x <= maxValue && pMatrix->at.y >= minValue && pMatrix->at.y <= maxValue && pMatrix->at.z >= minValue && + pMatrix->at.y <= maxValue - && pMatrix->right.x >= minValue && pMatrix->right.x <= maxValue - && pMatrix->right.y >= minValue && pMatrix->right.y <= maxValue - && pMatrix->right.z >= minValue && pMatrix->right.y <= maxValue + && pMatrix->right.x >= minValue && pMatrix->right.x <= maxValue && pMatrix->right.y >= minValue && pMatrix->right.y <= maxValue && + pMatrix->right.z >= minValue && pMatrix->right.y <= maxValue - && pMatrix->up.x >= minValue && pMatrix->up.x <= maxValue - && pMatrix->up.y >= minValue && pMatrix->up.y <= maxValue - && pMatrix->up.z >= minValue && pMatrix->up.y <= maxValue + && pMatrix->up.x >= minValue && pMatrix->up.x <= maxValue && pMatrix->up.y >= minValue && pMatrix->up.y <= maxValue && pMatrix->up.z >= minValue && + pMatrix->up.y <= maxValue - && pMatrix->pos.x >= minValue && pMatrix->pos.x <= maxValue - && pMatrix->pos.y >= minValue && pMatrix->pos.y <= maxValue - && pMatrix->pos.z >= minValue && pMatrix->pos.y <= maxValue; + && pMatrix->pos.x >= minValue && pMatrix->pos.x <= maxValue && pMatrix->pos.y >= minValue && pMatrix->pos.y <= maxValue && + pMatrix->pos.z >= minValue && pMatrix->pos.y <= maxValue; } bool AreMatricesOfRpAtomicValid(RpAtomic* pAtomic) { - uint32 atomicSkinOffset = *(uint32*)0xC978A4; + uint32 atomicSkinOffset = *(uint32*)0xC978A4; RpHAnimHierarchy* pSkinPluginData = *(RpHAnimHierarchy**)((char*)pAtomic + atomicSkinOffset); if (!pSkinPluginData) return true; unsigned __int32 count = pSkinPluginData->numNodes; - RwMatrix* pMatrixArray = pSkinPluginData->pMatrixArray; + RwMatrix* pMatrixArray = pSkinPluginData->pMatrixArray; for (unsigned int i = 0; i < count; i++) { @@ -805,8 +800,8 @@ bool AreMatricesOfRpAtomicValid(RpAtomic* pAtomic) return true; } -#define HOOKPOS_CVisibilityPlugins_RenderPedCB 0x7335B0 -#define HOOKSIZE_CVisibilityPlugins_RenderPedCB 5 +#define HOOKPOS_CVisibilityPlugins_RenderPedCB 0x7335B0 +#define HOOKSIZE_CVisibilityPlugins_RenderPedCB 5 static void __declspec(naked) HOOK_CVisibilityPlugins_RenderPedCB() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -837,10 +832,10 @@ static void __declspec(naked) HOOK_CVisibilityPlugins_RenderPedCB() } // Hook info -#define HOOKPOS_CRenderer_EverythingBarRoads 0x553C78 -#define HOOKSIZE_CRenderer_EverythingBarRoads 5 -DWORD RETURN_CRenderer_EverythingBarRoads = 0x553C7D; -DWORD DO_CRenderer_EverythingBarRoads = 0x7EE180; +#define HOOKPOS_CRenderer_EverythingBarRoads 0x553C78 +#define HOOKSIZE_CRenderer_EverythingBarRoads 5 +DWORD RETURN_CRenderer_EverythingBarRoads = 0x553C7D; +DWORD DO_CRenderer_EverythingBarRoads = 0x7EE180; static void __declspec(naked) HOOK_CRenderer_EverythingBarRoads() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -852,8 +847,7 @@ static void __declspec(naked) HOOK_CRenderer_EverythingBarRoads() } // clang-format on - if (pRenderEverythingBarRoadsHandler) - pRenderEverythingBarRoadsHandler(); + if (pRenderEverythingBarRoadsHandler) pRenderEverythingBarRoadsHandler(); // clang-format off __asm diff --git a/Client/multiplayer_sa/CMultiplayerSA_RwResources.cpp b/Client/multiplayer_sa/CMultiplayerSA_RwResources.cpp index 0140d7425cc..d29e894fb91 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_RwResources.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_RwResources.cpp @@ -39,9 +39,9 @@ void OnMY_RwTextureCreate_Post(RwTexture* pTexture, DWORD calledFrom) } // Hook info -#define HOOKPOS_RwTextureCreate 0x7F37C0 -#define HOOKSIZE_RwTextureCreate 5 -DWORD RETURN_RwTextureCreate = 0x7F37C5; +#define HOOKPOS_RwTextureCreate 0x7F37C0 +#define HOOKSIZE_RwTextureCreate 5 +DWORD RETURN_RwTextureCreate = 0x7F37C5; static void __declspec(naked) HOOK_RwTextureCreate() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -97,9 +97,9 @@ void OnMY_RwTextureDestroy(RwTexture* pTexture, DWORD calledFrom) } // Hook info -#define HOOKPOS_RwTextureDestroy 0x7F3820 -#define HOOKSIZE_RwTextureDestroy 5 -DWORD RETURN_RwTextureDestroy = 0x7F3825; +#define HOOKPOS_RwTextureDestroy 0x7F3820 +#define HOOKSIZE_RwTextureDestroy 5 +DWORD RETURN_RwTextureDestroy = 0x7F3825; static void __declspec(naked) HOOK_RwTextureDestroy() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -132,9 +132,9 @@ void OnMY_RwRasterCreate(DWORD calledFrom) } // Hook info -#define HOOKPOS_RwRasterCreate 0x7FB230 -#define HOOKSIZE_RwRasterCreate 5 -DWORD RETURN_RwRasterCreate = 0x7FB235; +#define HOOKPOS_RwRasterCreate 0x7FB230 +#define HOOKSIZE_RwRasterCreate 5 +DWORD RETURN_RwRasterCreate = 0x7FB235; static void __declspec(naked) HOOK_RwRasterCreate() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -166,9 +166,9 @@ void OnMY_RwRasterDestroy(DWORD calledFrom) } // Hook info -#define HOOKPOS_RwRasterDestroy 0x7FB020 -#define HOOKSIZE_RwRasterDestroy 5 -DWORD RETURN_RwRasterDestroy = 0x7FB025; +#define HOOKPOS_RwRasterDestroy 0x7FB020 +#define HOOKSIZE_RwRasterDestroy 5 +DWORD RETURN_RwRasterDestroy = 0x7FB025; static void __declspec(naked) HOOK_RwRasterDestroy() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -207,9 +207,9 @@ void OnMY_RwGeometryCreate_Post(RwGeometry* pGeometry, DWORD calledFrom) } // Hook info -#define HOOKPOS_RwGeometryCreate 0x74CA90 -#define HOOKSIZE_RwGeometryCreate 7 -DWORD RETURN_RwGeometryCreate = 0x74CA97; +#define HOOKPOS_RwGeometryCreate 0x74CA90 +#define HOOKSIZE_RwGeometryCreate 7 +DWORD RETURN_RwGeometryCreate = 0x74CA97; static void __declspec(naked) HOOK_RwGeometryCreate() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -268,9 +268,9 @@ void OnMY_RwGeometryDestroy(DWORD calledFrom, RwGeometry* pGeometry) } // Hook info -#define HOOKPOS_RwGeometryDestroy 0x74CCC0 -#define HOOKSIZE_RwGeometryDestroy 5 -DWORD RETURN_RwGeometryDestroy = 0x74CCC5; +#define HOOKPOS_RwGeometryDestroy 0x74CCC0 +#define HOOKSIZE_RwGeometryDestroy 5 +DWORD RETURN_RwGeometryDestroy = 0x74CCC5; static void __declspec(naked) HOOK_RwGeometryDestroy() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_Tasks.cpp b/Client/multiplayer_sa/CMultiplayerSA_Tasks.cpp index 58e94878265..1af1cc09cf4 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Tasks.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Tasks.cpp @@ -26,7 +26,7 @@ static bool __IsIgnoreFireStateEnabled() #define HOOKSIZE_CTaskSimplePlayerOnFoot__MakeAbortable 6 static constexpr std::uintptr_t RETURN_CTaskSimplePlayerOnFoot__MakeAbortable = 0x68585F; static constexpr std::uintptr_t SKIP_CTaskSimplePlayerOnFoot__MakeAbortable = 0x685855; -static void __declspec(naked) HOOK_CTaskSimplePlayerOnFoot__MakeAbortable() +static void __declspec(naked) HOOK_CTaskSimplePlayerOnFoot__MakeAbortable() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_VehicleCollision.cpp b/Client/multiplayer_sa/CMultiplayerSA_VehicleCollision.cpp index 28475950385..0a5b2fbf08b 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_VehicleCollision.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_VehicleCollision.cpp @@ -56,8 +56,8 @@ void TriggerVehicleCollisionEvent() // CAutomobile, CPlane, CHeli, CMonsterTruck, CQuadBike, CTrailer // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CAutomobile_ProcessControl_VehicleDamage 0x6B1F3B -#define HOOKSIZE_CAutomobile_ProcessControl_VehicleDamage 6 +#define HOOKPOS_CAutomobile_ProcessControl_VehicleDamage 0x6B1F3B +#define HOOKSIZE_CAutomobile_ProcessControl_VehicleDamage 6 static const DWORD CONTINUE_CAutomobile_ProcessControl_VehicleDamage = 0x6B1F41; static void __declspec(naked) HOOK_CAutomobile_ProcessControl_VehicleDamage() @@ -95,8 +95,8 @@ static void __declspec(naked) HOOK_CAutomobile_ProcessControl_VehicleDamage() // CBike, CBmx // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CBike_ProcessControl_VehicleDamage 0x6B9AA5 -#define HOOKSIZE_CBike_ProcessControl_VehicleDamage 6 +#define HOOKPOS_CBike_ProcessControl_VehicleDamage 0x6B9AA5 +#define HOOKSIZE_CBike_ProcessControl_VehicleDamage 6 static const DWORD CONTINUE_CBike_ProcessControl_VehicleDamage = 0x6B9AAB; static void __declspec(naked) HOOK_CBike_ProcessControl_VehicleDamage() @@ -134,8 +134,8 @@ static void __declspec(naked) HOOK_CBike_ProcessControl_VehicleDamage() // CBoat // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CBoat_ProcessControl_VehicleDamage 0x6F1864 -#define HOOKSIZE_CBoat_ProcessControl_VehicleDamage 5 +#define HOOKPOS_CBoat_ProcessControl_VehicleDamage 0x6F1864 +#define HOOKSIZE_CBoat_ProcessControl_VehicleDamage 5 static const DWORD CONTINUE_CBoat_ProcessControl_VehicleDamage = 0x6F1869; static const DWORD FUNC_CVehicle_ProcessCarAlarm = 0x6D21F0; @@ -173,8 +173,8 @@ static void __declspec(naked) HOOK_CBoat_ProcessControl_VehicleDamage() // CTrain // ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CTrain_ProcessControl_VehicleDamage 0x6F86BB -#define HOOKSIZE_CTrain_ProcessControl_VehicleDamage 5 +#define HOOKPOS_CTrain_ProcessControl_VehicleDamage 0x6F86BB +#define HOOKSIZE_CTrain_ProcessControl_VehicleDamage 5 static const DWORD CONTINUE_CTrain_ProcessControl_VehicleDamage = 0x6F86C0; static void __declspec(naked) HOOK_CTrain_ProcessControl_VehicleDamage() diff --git a/Client/multiplayer_sa/CMultiplayerSA_VehicleDamage.cpp b/Client/multiplayer_sa/CMultiplayerSA_VehicleDamage.cpp index 8f613c81de8..8c801c7de1d 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_VehicleDamage.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_VehicleDamage.cpp @@ -24,7 +24,7 @@ namespace CVector ms_SavedDamagedPos; VehicleDamageHandler* m_pVehicleDamageHandler = NULL; -} // namespace +} // namespace ////////////////////////////////////////////////////////////////////////////////////////// // @@ -58,11 +58,11 @@ bool OnMY_CVehicle_BurstTyre(CVehicleSAInterface* pVehicle, uchar ucTyre) } // Hook info -#define HOOKPOS_CAutomobile_BurstTyre 0x06A331C -#define HOOKSIZE_CAutomobile_BurstTyre 5 -#define HOOKCHECK_CAutomobile_BurstTyre 0x6A -DWORD RETURN_CAutomobile_BurstTyre_A = 0x06A3321; -DWORD RETURN_CAutomobile_BurstTyre_B = 0x06A3425; +#define HOOKPOS_CAutomobile_BurstTyre 0x06A331C +#define HOOKSIZE_CAutomobile_BurstTyre 5 +#define HOOKCHECK_CAutomobile_BurstTyre 0x6A +DWORD RETURN_CAutomobile_BurstTyre_A = 0x06A3321; +DWORD RETURN_CAutomobile_BurstTyre_B = 0x06A3425; static void __declspec(naked) HOOK_CAutomobile_BurstTyre() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -99,11 +99,11 @@ static void __declspec(naked) HOOK_CAutomobile_BurstTyre() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CBike_BurstTyre 0x06BEB94 -#define HOOKSIZE_CBike_BurstTyre 10 -#define HOOKCHECK_CBike_BurstTyre 0x6A -DWORD RETURN_CBike_BurstTyre_A = 0x06BEB9E; -DWORD RETURN_CBike_BurstTyre_B = 0x06BECA5; +#define HOOKPOS_CBike_BurstTyre 0x06BEB94 +#define HOOKSIZE_CBike_BurstTyre 10 +#define HOOKCHECK_CBike_BurstTyre 0x6A +DWORD RETURN_CBike_BurstTyre_A = 0x06BEB9E; +DWORD RETURN_CBike_BurstTyre_B = 0x06BECA5; static void __declspec(naked) HOOK_CBike_BurstTyre() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -153,10 +153,10 @@ bool OnMY_CVehicle_InflictDamage(CVehicleSAInterface* pVehicle, CEntitySAInterfa } // Hook info -#define HOOKPOS_CVehicle_InflictDamage 0x06D7C90 -#define HOOKSIZE_CVehicle_InflictDamage 5 -#define HOOKCHECK_CVehicle_InflictDamage 0x6A -DWORD RETURN_CVehicle_InflictDamage = 0x0404CDC; +#define HOOKPOS_CVehicle_InflictDamage 0x06D7C90 +#define HOOKSIZE_CVehicle_InflictDamage 5 +#define HOOKCHECK_CVehicle_InflictDamage 0x6A +DWORD RETURN_CVehicle_InflictDamage = 0x0404CDC; static void __declspec(naked) HOOK_CVehicle_InflictDamage() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -211,10 +211,10 @@ void OnMY_CVehicle_VehicleDamage1(CVehicleSAInterface* pVehicle, float f, ushort } // Hook info -#define HOOKPOS_CAutomobile_VehicleDamage1 0x06A7650 -#define HOOKSIZE_CAutomobile_VehicleDamage1 7 -#define HOOKCHECK_CAutomobile_VehicleDamage1 0x6A -DWORD RETURN_CAutomobile_VehicleDamage1 = 0x06A7657; +#define HOOKPOS_CAutomobile_VehicleDamage1 0x06A7650 +#define HOOKSIZE_CAutomobile_VehicleDamage1 7 +#define HOOKCHECK_CAutomobile_VehicleDamage1 0x6A +DWORD RETURN_CAutomobile_VehicleDamage1 = 0x06A7657; static void __declspec(naked) HOOK_CAutomobile_VehicleDamage1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -274,10 +274,10 @@ float OnMY_CVehicle_VehicleDamage2(CVehicleSAInterface* pVehicle, float fDamage) } // Hook info -#define HOOKPOS_CAutomobile_VehicleDamage2 0x06A8325 -#define HOOKSIZE_CAutomobile_VehicleDamage2 6 -#define HOOKCHECK_CAutomobile_VehicleDamage2 0xD8 -DWORD RETURN_CAutomobile_VehicleDamage2 = 0x06A832B; +#define HOOKPOS_CAutomobile_VehicleDamage2 0x06A8325 +#define HOOKSIZE_CAutomobile_VehicleDamage2 6 +#define HOOKCHECK_CAutomobile_VehicleDamage2 0xD8 +DWORD RETURN_CAutomobile_VehicleDamage2 = 0x06A832B; static void __declspec(naked) HOOK_CAutomobile_VehicleDamage2() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -309,10 +309,10 @@ static void __declspec(naked) HOOK_CAutomobile_VehicleDamage2() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CPlane_VehicleDamage1 0x06CC4B0 -#define HOOKSIZE_CPlane_VehicleDamage1 8 -#define HOOKCHECK_CPlane_VehicleDamage1 0x83 -DWORD RETURN_CPlane_VehicleDamage1 = 0x06CC4B8; +#define HOOKPOS_CPlane_VehicleDamage1 0x06CC4B0 +#define HOOKSIZE_CPlane_VehicleDamage1 8 +#define HOOKCHECK_CPlane_VehicleDamage1 0x83 +DWORD RETURN_CPlane_VehicleDamage1 = 0x06CC4B8; static void __declspec(naked) HOOK_CPlane_VehicleDamage1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -348,10 +348,10 @@ static void __declspec(naked) HOOK_CPlane_VehicleDamage1() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CPlane_VehicleDamage2 0x06CC6C8 -#define HOOKSIZE_CPlane_VehicleDamage2 6 -#define HOOKCHECK_CPlane_VehicleDamage2 0xD8 -DWORD RETURN_CPlane_VehicleDamage2 = 0x06CC6CE; +#define HOOKPOS_CPlane_VehicleDamage2 0x06CC6C8 +#define HOOKSIZE_CPlane_VehicleDamage2 6 +#define HOOKCHECK_CPlane_VehicleDamage2 0xD8 +DWORD RETURN_CPlane_VehicleDamage2 = 0x06CC6CE; static void __declspec(naked) HOOK_CPlane_VehicleDamage2() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -383,10 +383,10 @@ static void __declspec(naked) HOOK_CPlane_VehicleDamage2() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CBike_VehicleDamage1 0x06B8EC0 -#define HOOKSIZE_CBike_VehicleDamage1 5 -#define HOOKCHECK_CBike_VehicleDamage1 0x51 -DWORD RETURN_CBike_VehicleDamage1 = 0x06B8EC5; +#define HOOKPOS_CBike_VehicleDamage1 0x06B8EC0 +#define HOOKSIZE_CBike_VehicleDamage1 5 +#define HOOKCHECK_CBike_VehicleDamage1 0x51 +DWORD RETURN_CBike_VehicleDamage1 = 0x06B8EC5; static void __declspec(naked) HOOK_CBike_VehicleDamage1() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -422,10 +422,10 @@ static void __declspec(naked) HOOK_CBike_VehicleDamage1() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CBike_VehicleDamage2 0x06B91C2 -#define HOOKSIZE_CBike_VehicleDamage2 6 -#define HOOKCHECK_CBike_VehicleDamage2 0xD8 -DWORD RETURN_CBike_VehicleDamage2 = 0x06B91C8; +#define HOOKPOS_CBike_VehicleDamage2 0x06B91C2 +#define HOOKSIZE_CBike_VehicleDamage2 6 +#define HOOKCHECK_CBike_VehicleDamage2 0xD8 +DWORD RETURN_CBike_VehicleDamage2 = 0x06B91C8; static void __declspec(naked) HOOK_CBike_VehicleDamage2() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_VehicleDummies.cpp b/Client/multiplayer_sa/CMultiplayerSA_VehicleDummies.cpp index f24064c4a7e..835bb832c4b 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_VehicleDummies.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_VehicleDummies.cpp @@ -45,8 +45,8 @@ static void __cdecl UpdateVehicleDummiesPositionArray(CVehicleSAInterface* vehic // >>> 0x6DE325 | 89 54 24 70 | mov [esp+0D4h+var_64.x], edx // >>> 0x6DE329 | 89 54 24 48 | mov [esp+0D4h+var_8C], edx // 0x6DE32D | E8 BE D9 EB FF | call CMatrix::CMatrix(CMatrix const &) -#define HOOKPOS_CVehicle_AddExhaustParticles_1 0x6DE2F1 -#define HOOKSIZE_CVehicle_AddExhaustParticles_1 59 +#define HOOKPOS_CVehicle_AddExhaustParticles_1 0x6DE2F1 +#define HOOKSIZE_CVehicle_AddExhaustParticles_1 59 static const DWORD CONTINUE_CVehicle_AddExhaustParticles_1 = 0x6DE32D; static void __cdecl ApplyExhaustParticlesPosition(CVehicleSAInterface* vehicleInterface, CVector* mainPosition, CVector* secondaryPosition) @@ -134,8 +134,8 @@ static void __declspec(naked) HOOK_CVehicle_AddExhaustParticles_1() // >>> 0x6DE39E | 8B 57 5C | mov edx, [edi+5Ch] // >>> 0x6DE3A1 | 81 C2 84 00 00 00 | add edx, 84h // 0x6DE3A7 | 8B 02 | mov eax, [edx] -#define HOOKPOS_CVehicle_AddExhaustParticles_2 0x6DE39E -#define HOOKSIZE_CVehicle_AddExhaustParticles_2 9 +#define HOOKPOS_CVehicle_AddExhaustParticles_2 0x6DE39E +#define HOOKSIZE_CVehicle_AddExhaustParticles_2 9 static const DWORD CONTINUE_CVehicle_AddExhaustParticles_2 = 0x6DE3A7; static void __declspec(naked) HOOK_CVehicle_AddExhaustParticles_2() @@ -175,8 +175,8 @@ static void __declspec(naked) HOOK_CVehicle_AddExhaustParticles_2() // >>> 0x6D2B09 | 8B 49 5C | mov ecx, [ecx+5Ch] // >>> 0x6D2B0C | 83 C1 54 | add ecx, 54h // 0x6D2B0F | 84 D2 | test dl, dl -#define HOOKPOS_CVehicle_AddDamagedVehicleParticles 0x6D2B09 -#define HOOKSIZE_CVehicle_AddDamagedVehicleParticles 6 +#define HOOKPOS_CVehicle_AddDamagedVehicleParticles 0x6D2B09 +#define HOOKSIZE_CVehicle_AddDamagedVehicleParticles 6 static const DWORD CONTINUE_CVehicle_AddDamagedVehicleParticles = 0x6D2B0F; static void __declspec(naked) HOOK_CVehicle_AddDamagedVehicleParticles() @@ -220,8 +220,8 @@ static void __declspec(naked) HOOK_CVehicle_AddDamagedVehicleParticles() // >>> 0x53A714 | 8B 40 5C | mov eax, [eax+5Ch] // >>> 0x53A717 | 8B 10 | mov edx, [eax] // 0x53A719 | 89 54 24 18 | mov [esp+3Ch+var_24.x], edx -#define HOOKPOS_CFire_ProcessFire 0x53A714 -#define HOOKSIZE_CFire_ProcessFire 5 +#define HOOKPOS_CFire_ProcessFire 0x53A714 +#define HOOKSIZE_CFire_ProcessFire 5 static const DWORD CONTINUE_CFire_ProcessFire = 0x53A719; static void __declspec(naked) HOOK_CFire_ProcessFire() @@ -265,8 +265,8 @@ static void __declspec(naked) HOOK_CFire_ProcessFire() // >>> 0x6A3BE2 | 8B 48 5C | mov ecx, [eax+5Ch] // >>> 0x6A3BE5 | 83 C1 48 | add ecx, 48h // 0x6A3BE8 | 8B 11 | mov edx, [ecx] -#define HOOKPOS_CAutomobile_DoNitroEffect_1 0x6A3BE2 -#define HOOKSIZE_CAutomobile_DoNitroEffect_1 6 +#define HOOKPOS_CAutomobile_DoNitroEffect_1 0x6A3BE2 +#define HOOKSIZE_CAutomobile_DoNitroEffect_1 6 static const DWORD CONTINUE_CAutomobile_DoNitroEffect_1 = 0x6A3BE8; static void __declspec(naked) HOOK_CAutomobile_DoNitroEffect_1() @@ -318,8 +318,8 @@ static void __declspec(naked) HOOK_CAutomobile_DoNitroEffect_1() // >>> 0x6A3C89 | D9 5C 24 20 | fstp [esp+38h+secondaryNitroPos.x] // >>> 0x6A3C8D | 89 54 24 24 | mov [esp+38h+secondaryNitroPos.y], edx // 0x6A3C91 | 74 4B | jz short loc_6A3CDE -#define HOOKPOS_CAutomobile_DoNitroEffect_2 0x6A3C68 -#define HOOKSIZE_CAutomobile_DoNitroEffect_2 41 +#define HOOKPOS_CAutomobile_DoNitroEffect_2 0x6A3C68 +#define HOOKSIZE_CAutomobile_DoNitroEffect_2 41 static const DWORD CONTINUE_CAutomobile_DoNitroEffect_2 = 0x6A3C91; static void __cdecl ApplySecondaryExhaustNitroPosition(CVehicleSAInterface* vehicleInterface, CVector* secondaryExhaustPosition) @@ -379,8 +379,8 @@ static void __declspec(naked) HOOK_CAutomobile_DoNitroEffect_2() // >>> 0x6E1F3C | 8B 40 5C | mov eax, [eax+5Ch] // >>> 0x6E1F3F | 83 C0 18 | add eax, 18h // 0x6E1F42 | 8B 08 | mov ecx, [eax] -#define HOOKPOS_CVehicle_DoVehicleLights_1 0x6E1F3C -#define HOOKSIZE_CVehicle_DoVehicleLights_1 6 +#define HOOKPOS_CVehicle_DoVehicleLights_1 0x6E1F3C +#define HOOKSIZE_CVehicle_DoVehicleLights_1 6 static const DWORD CONTINUE_CVehicle_DoVehicleLights_1 = 0x6E1F42; static void __declspec(naked) HOOK_CVehicle_DoVehicleLights_1() @@ -417,8 +417,8 @@ static void __declspec(naked) HOOK_CVehicle_DoVehicleLights_1() // >>> 0x6E22CD | 8B 48 5C | mov ecx, [eax+5Ch] // >>> 0x6E22D0 | 83 C1 18 | add ecx, 18h // 0x6E22D3 | 8B 11 | mov edx, [ecx] -#define HOOKPOS_CVehicle_DoVehicleLights_2 0x6E22CD -#define HOOKSIZE_CVehicle_DoVehicleLights_2 6 +#define HOOKPOS_CVehicle_DoVehicleLights_2 0x6E22CD +#define HOOKSIZE_CVehicle_DoVehicleLights_2 6 static const DWORD CONTINUE_CVehicle_DoVehicleLights_2 = 0x6E22D3; static void __declspec(naked) HOOK_CVehicle_DoVehicleLights_2() @@ -462,8 +462,8 @@ static void __declspec(naked) HOOK_CVehicle_DoVehicleLights_2() // >>> 0x6A717F | 8B 40 5C | mov eax, [eax+5Ch] // >>> 0x6A7182 | 83 C0 54 | add eax, 54h // 0x6A7185 | 8B 08 | mov ecx, [eax] -#define HOOKPOS_CAutomobile_ProcessCarOnFireAndExplode 0x6A717F -#define HOOKSIZE_CAutomobile_ProcessCarOnFireAndExplode 6 +#define HOOKPOS_CAutomobile_ProcessCarOnFireAndExplode 0x6A717F +#define HOOKSIZE_CAutomobile_ProcessCarOnFireAndExplode 6 static const DWORD CONTINUE_CAutomobile_ProcessCarOnFireAndExplode = 0x6A7185; static void __declspec(naked) HOOK_CAutomobile_ProcessCarOnFireAndExplode() @@ -507,8 +507,8 @@ static void __declspec(naked) HOOK_CAutomobile_ProcessCarOnFireAndExplode() // >>> 0x6B8053 | 8B 40 5C | mov eax, [eax+92] // >>> 0x6B8056 | 83 C0 78 | add eax, 78h // 0x6B8059 | 8B 10 | mov edx, [eax] -#define HOOKPOS_CBike_FixHandsToBars 0x6B8053 -#define HOOKSIZE_CBike_FixHandsToBars 6 +#define HOOKPOS_CBike_FixHandsToBars 0x6B8053 +#define HOOKSIZE_CBike_FixHandsToBars 6 static const DWORD CONTINUE_CBike_FixHandsToBars = 0x6B8059; static void __declspec(naked) HOOK_CBike_FixHandsToBars() @@ -552,8 +552,8 @@ static void __declspec(naked) HOOK_CBike_FixHandsToBars() // >>> 0x5DF98B | 83 7F 3C 05 | cmp dword ptr [edi+3Ch], 5 // >>> 0x5DF98F | 8B 7F 5C | mov edi, [edi+5Ch] // 0x5DF992 | 74 03 | jz short loc_5DF997 -#define HOOKPOS_CPed_SetPedPositionInCar_1 0x5DF98B -#define HOOKSIZE_CPed_SetPedPositionInCar_1 7 +#define HOOKPOS_CPed_SetPedPositionInCar_1 0x5DF98B +#define HOOKSIZE_CPed_SetPedPositionInCar_1 7 static const DWORD CONTINUE_CPed_SetPedPositionInCar_1 = 0x5DF992; static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_1() @@ -598,8 +598,8 @@ static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_1() // >>> 0x5DFA56 | 8B 47 5C | mov eax, [edi+5Ch] // >>> 0x5DFA59 | 83 C0 3C | add eax, 3Ch // 0x5DFA5C | 8B 10 | mov edx, [eax] -#define HOOKPOS_CPed_SetPedPositionInCar_2 0x5DFA56 -#define HOOKSIZE_CPed_SetPedPositionInCar_2 6 +#define HOOKPOS_CPed_SetPedPositionInCar_2 0x5DFA56 +#define HOOKSIZE_CPed_SetPedPositionInCar_2 6 static const DWORD CONTINUE_CPed_SetPedPositionInCar_2 = 0x5DFA5C; static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_2() @@ -644,8 +644,8 @@ static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_2() // >>> 0x5DFA04 | 83 7F 3C 05 | cmp dword ptr [edi+3Ch], 5 // >>> 0x5DFA08 | 8B 7F 5C | mov edi, [edi+5Ch] // 0x5DFA0B | 74 03 | jz short loc_5DFA10 -#define HOOKPOS_CPed_SetPedPositionInCar_3 0x5DFA04 -#define HOOKSIZE_CPed_SetPedPositionInCar_3 7 +#define HOOKPOS_CPed_SetPedPositionInCar_3 0x5DFA04 +#define HOOKSIZE_CPed_SetPedPositionInCar_3 7 static const DWORD CONTINUE_CPed_SetPedPositionInCar_3 = 0x5DFA0B; static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_3() @@ -690,8 +690,8 @@ static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_3() // >>> 0x5DFA80 | 8B 57 5C | mov edx, [edi+5Ch] // >>> 0x5DFA83 | 83 C2 3C | add edx, 3Ch // 0x5DFA86 | 8B 02 | mov eax, [edx] -#define HOOKPOS_CPed_SetPedPositionInCar_4 0x5DFA80 -#define HOOKSIZE_CPed_SetPedPositionInCar_4 6 +#define HOOKPOS_CPed_SetPedPositionInCar_4 0x5DFA80 +#define HOOKSIZE_CPed_SetPedPositionInCar_4 6 static const DWORD CONTINUE_CPed_SetPedPositionInCar_4 = 0x5DFA86; static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_4() @@ -736,8 +736,8 @@ static void __declspec(naked) HOOK_CPed_SetPedPositionInCar_4() // >>> 0x6E0A69 | 8B 50 5C | mov edx, [eax+5Ch] // >>> 0x6E0A6C | 8D 0C 5B | lea ecx, [ebx+ebx*2] // 0x6E0A6F | 8D 04 CA | lea eax, [edx+ecx*8] -#define HOOKPOS_CVehicle_DoHeadLightEffect 0x6E0A69 -#define HOOKSIZE_CVehicle_DoHeadLightEffect 6 +#define HOOKPOS_CVehicle_DoHeadLightEffect 0x6E0A69 +#define HOOKSIZE_CVehicle_DoHeadLightEffect 6 static const DWORD CONTINUE_CVehicle_DoHeadLightEffect = 0x6E0A6F; static void __declspec(naked) HOOK_CVehicle_DoHeadLightEffect() @@ -782,8 +782,8 @@ static void __declspec(naked) HOOK_CVehicle_DoHeadLightEffect() // >>> 0x6E17C3 | 53 | push ebx // >>> 0x6E17C4 | 8B 5C 24 34 | mov ebx, [esp+4+30h] // 0x6E17C8 | 83 FB 01 | cmp ebx, 1 -#define HOOKPOS_CVehicle_DoTailLightEffect 0x6E17C0 -#define HOOKSIZE_CVehicle_DoTailLightEffect 8 +#define HOOKPOS_CVehicle_DoTailLightEffect 0x6E17C0 +#define HOOKSIZE_CVehicle_DoTailLightEffect 8 static const DWORD CONTINUE_CVehicle_DoTailLightEffect = 0x6E17C8; static void __declspec(naked) HOOK_CVehicle_DoTailLightEffect() @@ -829,8 +829,8 @@ static void __declspec(naked) HOOK_CVehicle_DoTailLightEffect() // >>> 0x6E1452 | 8B 50 5C | mov edx, [eax+5Ch] // >>> 0x6E1455 | 8B 02 | mov eax, [edx] // 0x6E1457 | 89 44 24 18 | mov [esp+24h+var_C], eax -#define HOOKPOS_CVehicle_DoHeadLightReflectionSingle 0x6E1452 -#define HOOKSIZE_CVehicle_DoHeadLightReflectionSingle 5 +#define HOOKPOS_CVehicle_DoHeadLightReflectionSingle 0x6E1452 +#define HOOKSIZE_CVehicle_DoHeadLightReflectionSingle 5 static const DWORD CONTINUE_CVehicle_DoHeadLightReflectionSingle = 0x6E1457; static void __declspec(naked) HOOK_CVehicle_DoHeadLightReflectionSingle() @@ -874,8 +874,8 @@ static void __declspec(naked) HOOK_CVehicle_DoHeadLightReflectionSingle() // >>> 0x6E160E | 8B 50 5C | mov edx, [eax+5Ch] // >>> 0x6E1611 | 8B 02 | mov eax, [edx] // 0x6E1613 | 89 44 24 10 | mov [esp+1Ch+var_C], eax -#define HOOKPOS_CVehicle_DoHeadLightReflectionTwin 0x6E160E -#define HOOKSIZE_CVehicle_DoHeadLightReflectionTwin 5 +#define HOOKPOS_CVehicle_DoHeadLightReflectionTwin 0x6E160E +#define HOOKSIZE_CVehicle_DoHeadLightReflectionTwin 5 static const DWORD CONTINUE_CVehicle_DoHeadLightReflectionTwin = 0x6E1613; static void __declspec(naked) HOOK_CVehicle_DoHeadLightReflectionTwin() @@ -920,8 +920,8 @@ static void __declspec(naked) HOOK_CVehicle_DoHeadLightReflectionTwin() // >>> 0x6D429A | 8B 04 8D C8 B0 A9 00 | mov eax, CModelInfo::ms_modelInfoPtrs // >>> 0x6D42A1 | 8B 40 5C | mov eax, [eax+5Ch] // 0x6D42A4 | 05 9C 00 00 00 | add eax, 9Ch -#define HOOKPOS_CVehicle_GetPlaneGunsPosition 0x6D4297 -#define HOOKSIZE_CVehicle_GetPlaneGunsPosition 13 +#define HOOKPOS_CVehicle_GetPlaneGunsPosition 0x6D4297 +#define HOOKSIZE_CVehicle_GetPlaneGunsPosition 13 static const DWORD CONTINUE_CVehicle_GetPlaneGunsPosition = 0x6D42A4; static void __declspec(naked) HOOK_CVehicle_GetPlaneGunsPosition() @@ -967,8 +967,8 @@ static void __declspec(naked) HOOK_CVehicle_GetPlaneGunsPosition() // >>> 0x6D46F0 | 8B 40 5C | mov eax, [eax+5Ch] // >>> 0x6D46F3 | 05 9C 00 00 00 | add eax, 9Ch // 0x6D46F8 | 8B 08 | mov ecx, [eax] -#define HOOKPOS_CVehicle_GetPlaneOrdnancePosition 0x6D46F0 -#define HOOKSIZE_CVehicle_GetPlaneOrdnancePosition 8 +#define HOOKPOS_CVehicle_GetPlaneOrdnancePosition 0x6D46F0 +#define HOOKSIZE_CVehicle_GetPlaneOrdnancePosition 8 static const DWORD CONTINUE_CVehicle_GetPlaneOrdnancePosition = 0x6D46F8; static void __declspec(naked) HOOK_CVehicle_GetPlaneOrdnancePosition() @@ -1012,8 +1012,8 @@ static void __declspec(naked) HOOK_CVehicle_GetPlaneOrdnancePosition() // >>> 0x6D5438 | 83 78 3C 05 | cmp dword ptr [eax+3Ch], 5 // >>> 0x6D543C | 8B 40 5C | mov eax, [eax+5Ch] // 0x6D543F | 74 03 | jz short loc_6D5444 -#define HOOKPOS_CVehicle_CanBeDriven 0x6D5438 -#define HOOKSIZE_CVehicle_CanBeDriven 7 +#define HOOKPOS_CVehicle_CanBeDriven 0x6D5438 +#define HOOKSIZE_CVehicle_CanBeDriven 7 static const DWORD CONTINUE_CVehicle_CanBeDriven = 0x6D543F; static void __declspec(naked) HOOK_CVehicle_CanBeDriven() @@ -1057,8 +1057,8 @@ static void __declspec(naked) HOOK_CVehicle_CanBeDriven() // >>> 0x6C971B | 8B 4D 5C | mov ecx, [ebp+5Ch] // >>> 0x6C971E | 81 C1 84 00 00 00 | add ecx, 84h // 0x6C9724 | 8B 11 | mov edx, [ecx] -#define HOOKPOS_CPlane_PreRender_1 0x6C971B -#define HOOKSIZE_CPlane_PreRender_1 9 +#define HOOKPOS_CPlane_PreRender_1 0x6C971B +#define HOOKSIZE_CPlane_PreRender_1 9 static const DWORD CONTINUE_CPlane_PreRender_1 = 0x6C9724; static void __declspec(naked) HOOK_CPlane_PreRender_1() @@ -1102,8 +1102,8 @@ static void __declspec(naked) HOOK_CPlane_PreRender_1() // >>> 0x6C98C9 | 8B 45 5C | mov eax, [ebp+5Ch] // >>> 0x6C98CC | 83 C0 6C | add eax, 6Ch // 0x6C98CF | 8B 08 | mov ecx, [eax] -#define HOOKPOS_CPlane_PreRender_2 0x6C98C9 -#define HOOKSIZE_CPlane_PreRender_2 6 +#define HOOKPOS_CPlane_PreRender_2 0x6C98C9 +#define HOOKSIZE_CPlane_PreRender_2 6 static const DWORD CONTINUE_CPlane_PreRender_2 = 0x6C98CF; static void __declspec(naked) HOOK_CPlane_PreRender_2() @@ -1147,8 +1147,8 @@ static void __declspec(naked) HOOK_CPlane_PreRender_2() // >>> 0x6C9B56 | 8B 45 5C | mov eax, [ebp+5Ch] // >>> 0x6C9B59 | 83 C0 78 | add eax, 78h // 0x6C9B5C | 8B 08 | mov ecx, [eax] -#define HOOKPOS_CPlane_PreRender_3 0x6C9B56 -#define HOOKSIZE_CPlane_PreRender_3 6 +#define HOOKPOS_CPlane_PreRender_3 0x6C9B56 +#define HOOKSIZE_CPlane_PreRender_3 6 static const DWORD CONTINUE_CPlane_PreRender_3 = 0x6C9B5C; static void __declspec(naked) HOOK_CPlane_PreRender_3() @@ -1192,8 +1192,8 @@ static void __declspec(naked) HOOK_CPlane_PreRender_3() // >>> 0x6E0E34 | 8B 49 5C | mov ecx, [ecx+5Ch] // >>> 0x6E0E37 | 8B 84 24 9C 00 00 00 | mov eax, [esp+98h+arg_0] // 0x6E0E3E | 83 F8 01 | cmp eax, 1 -#define HOOKPOS_CVehicle_DoHeadLightBeam 0x6E0E34 -#define HOOKSIZE_CVehicle_DoHeadLightBeam 10 +#define HOOKPOS_CVehicle_DoHeadLightBeam 0x6E0E34 +#define HOOKSIZE_CVehicle_DoHeadLightBeam 10 static const DWORD CONTINUE_CVehicle_DoHeadLightBeam = 0x6E0E3E; static void __declspec(naked) HOOK_CVehicle_DoHeadLightBeam() diff --git a/Client/multiplayer_sa/CMultiplayerSA_VehicleLights.cpp b/Client/multiplayer_sa/CMultiplayerSA_VehicleLights.cpp index 442b4633892..4a371de5160 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_VehicleLights.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_VehicleLights.cpp @@ -14,7 +14,7 @@ namespace { // Used to save state between CVehicle_DoTailLightEffect_Mid and CVehicle_DoTailLightEffect_Mid2 uint bCameraFacingCorona = false; -} // namespace +} // namespace ////////////////////////////////////////////////////////////////////////////////////////// // @@ -25,10 +25,10 @@ namespace // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CVehicle_DoTailLightEffect_Mid 0x006E18E5 -#define HOOKSIZE_CVehicle_DoTailLightEffect_Mid 6 -#define HOOKCHECK_CVehicle_DoTailLightEffect_Mid 0x0F -DWORD RETURN_CVehicle_DoTailLightEffect_Mid = 0x006E18EB; +#define HOOKPOS_CVehicle_DoTailLightEffect_Mid 0x006E18E5 +#define HOOKSIZE_CVehicle_DoTailLightEffect_Mid 6 +#define HOOKCHECK_CVehicle_DoTailLightEffect_Mid 0x0F +DWORD RETURN_CVehicle_DoTailLightEffect_Mid = 0x006E18EB; static void __declspec(naked) HOOK_CVehicle_DoTailLightEffect_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -56,11 +56,11 @@ static void __declspec(naked) HOOK_CVehicle_DoTailLightEffect_Mid() // ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CVehicle_DoTailLightEffect_Mid2 0x006E19E6 -#define HOOKSIZE_CVehicle_DoTailLightEffect_Mid2 10 -#define HOOKCHECK_CVehicle_DoTailLightEffect_Mid2 0x8B -DWORD RETURN_CVehicle_DoTailLightEffect_Mid2 = 0x006E19F0; -DWORD RETURN_CVehicle_DoTailLightEffect_Mid2_NoCorona = 0x006E1A32; +#define HOOKPOS_CVehicle_DoTailLightEffect_Mid2 0x006E19E6 +#define HOOKSIZE_CVehicle_DoTailLightEffect_Mid2 10 +#define HOOKCHECK_CVehicle_DoTailLightEffect_Mid2 0x8B +DWORD RETURN_CVehicle_DoTailLightEffect_Mid2 = 0x006E19F0; +DWORD RETURN_CVehicle_DoTailLightEffect_Mid2_NoCorona = 0x006E1A32; static void __declspec(naked) HOOK_CVehicle_DoTailLightEffect_Mid2() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/CMultiplayerSA_VehicleWeapons.cpp b/Client/multiplayer_sa/CMultiplayerSA_VehicleWeapons.cpp index 3c091a14cab..543b2e12034 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_VehicleWeapons.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_VehicleWeapons.cpp @@ -40,8 +40,8 @@ static void TriggerVehicleWeaponHitEvent(EVehicleWeaponType weaponType, CVehicle // 0x729324 | 0F 84 1C 02 00 00 | jz 0x729546 // >>> 0x72932A | 68 CD CC 4C 3E | push 3E4CCCCDh // 0x72932F | 68 00 00 80 3F | push 3F800000h -#define HOOKPOS_CWaterCannon__Render 0x72932A -#define HOOKSIZE_CWaterCannon__Render 5 +#define HOOKPOS_CWaterCannon__Render 0x72932A +#define HOOKSIZE_CWaterCannon__Render 5 static DWORD CONTINUE_CWaterCannon__Render = 0x72932F; static void HandleWaterCannonHit(CVehicleSAInterface* pGameVehicle, CColPointSAInterface* pColPoint, CEntitySAInterface** ppHitGameEntity) diff --git a/Client/multiplayer_sa/CMultiplayerSA_Vehicles.cpp b/Client/multiplayer_sa/CMultiplayerSA_Vehicles.cpp index 199b02d707a..610f9a55f9d 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Vehicles.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Vehicles.cpp @@ -31,8 +31,8 @@ static bool __fastcall AreVehicleDoorsUndamageable(CVehicleSAInterface* vehicle) // 0x6C2321 | 56 | push esi // 0x6C2322 | 0F B6 74 24 0C | movzx esi, [esp + doorId] // 0x6C2327 | 85 F6 | test esi, esi -#define HOOKPOS_CDamageManager__ProgressDoorDamage 0x6C2320 -#define HOOKSIZE_CDamageManager__ProgressDoorDamage 7 +#define HOOKPOS_CDamageManager__ProgressDoorDamage 0x6C2320 +#define HOOKSIZE_CDamageManager__ProgressDoorDamage 7 static DWORD CONTINUE_CDamageManager__ProgressDoorDamage = 0x6C2327; static void __declspec(naked) HOOK_CDamageManager__ProgressDoorDamage() diff --git a/Client/multiplayer_sa/CMultiplayerSA_Weapons.cpp b/Client/multiplayer_sa/CMultiplayerSA_Weapons.cpp index 48ef17ef988..4fb0d36b872 100644 --- a/Client/multiplayer_sa/CMultiplayerSA_Weapons.cpp +++ b/Client/multiplayer_sa/CMultiplayerSA_Weapons.cpp @@ -51,9 +51,9 @@ void OnMY_CWeapon_GenerateDamageEvent(DWORD calledFrom, CPedSAInterface* pPed, C } // Hook info -#define HOOKPOS_CWeapon_GenerateDamageEvent 0x73A530 -#define HOOKSIZE_CWeapon_GenerateDamageEvent 7 -DWORD RETURN_CWeapon_GenerateDamageEvent = 0x73A537; +#define HOOKPOS_CWeapon_GenerateDamageEvent 0x73A530 +#define HOOKSIZE_CWeapon_GenerateDamageEvent 7 +DWORD RETURN_CWeapon_GenerateDamageEvent = 0x73A537; static void __declspec(naked) HOOK_CWeapon_GenerateDamageEvent() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -89,8 +89,8 @@ static void __declspec(naked) HOOK_CWeapon_GenerateDamageEvent() ////////////////////////////////////////////////////////////////////////////////////////// // Hook info -#define HOOKPOS_CShotInfo_Update 0x739E60 -#define HOOKSIZE_CShotInfo_Update 6 +#define HOOKPOS_CShotInfo_Update 0x739E60 +#define HOOKSIZE_CShotInfo_Update 6 DWORD RETURN_CShotInfo_Update = 0x739E66; // Clear all shotinfos @@ -104,8 +104,8 @@ void ResetShotInfoArray() memcpy(pInfo + i, pInfo, sizeof(CFlameShotInfo)); } -#pragma warning( push ) -#pragma warning( disable : 4731 ) // warning C4731: 'Call_CShotInfo_Update' : frame pointer register 'ebp' modified by inline assembly code +#pragma warning(push) +#pragma warning(disable : 4731) // warning C4731: 'Call_CShotInfo_Update' : frame pointer register 'ebp' modified by inline assembly code void Call_CShotInfo_Update() { @@ -124,7 +124,7 @@ void Call_CShotInfo_Update() // clang-format on } -#pragma warning( pop ) +#pragma warning(pop) // Our code for when CShotInfo_Update is called void OnMY_CShotInfo_Update() @@ -181,16 +181,16 @@ int OnMY_Fx_AddBulletImpact(int iType) if (iType == 2 || iType == 4) { if (ms_LastFxTimer.Get() > 500) - ms_LastFxTimer.Reset(); // Allow once every 500ms + ms_LastFxTimer.Reset(); // Allow once every 500ms else - iType = 1; // Otherwise replace with spark + iType = 1; // Otherwise replace with spark } return iType; } // Hook info -#define HOOKPOS_Fx_AddBulletImpact 0x049F3E8 -#define HOOKSIZE_Fx_AddBulletImpact 5 +#define HOOKPOS_Fx_AddBulletImpact 0x049F3E8 +#define HOOKSIZE_Fx_AddBulletImpact 5 DWORD RETURN_Fx_AddBulletImpact = 0x049F3ED; static void __declspec(naked) HOOK_Fx_AddBulletImpact() @@ -217,13 +217,13 @@ static void __declspec(naked) HOOK_Fx_AddBulletImpact() ////////////////////////////////////////////////////////////////////////////////////////// // // CVisibilityPlugins::RenderWeaponPedsForPC -// +// // Fix for the bright objects after weapon change sometimes -// +// ////////////////////////////////////////////////////////////////////////////////////////// -#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC 0x733123 +#define HOOKPOS_CVisibilityPlugins_RenderWeaponPedsForPC 0x733123 #define HOOKSIZE_CVisibilityPlugins_RenderWeaponPedsForPC 5 -static constexpr DWORD CONTINUE_CVisibilityPlugins_RenderWeaponPedsForPC = 0x733128; +static constexpr DWORD CONTINUE_CVisibilityPlugins_RenderWeaponPedsForPC = 0x733128; static void __declspec(naked) HOOK_CVisibilityPlugins_RenderWeaponPedsForPC() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/StdInc.h b/Client/multiplayer_sa/StdInc.h index 9396212e417..5647a9be0cd 100644 --- a/Client/multiplayer_sa/StdInc.h +++ b/Client/multiplayer_sa/StdInc.h @@ -1,6 +1,6 @@ // Pragmas -#pragma warning (disable:4250) +#pragma warning(disable : 4250) #include #define MTA_CLIENT diff --git a/Client/multiplayer_sa/multiplayer_hooksystem.h b/Client/multiplayer_sa/multiplayer_hooksystem.h index 1e0bb419c40..16e4106d93d 100644 --- a/Client/multiplayer_sa/multiplayer_hooksystem.h +++ b/Client/multiplayer_sa/multiplayer_hooksystem.h @@ -13,19 +13,22 @@ #pragma once -#pragma warning(disable : 4102) // unreferenced label +#pragma warning(disable : 4102) // unreferenced label // This macro adds an unreferenced label to your '__declspec(naked)' hook functions, to // point to the value of __LOCAL_SIZE, which will be examined by an external tool after // compilation, and it must be zero. -// +// // NOTE: This was copied from game_sa. Check the comment there for more details. -#define MTA_VERIFY_HOOK_LOCAL_SIZE \ -{ \ - __asm { push eax }; \ - __asm { _localSize: mov eax, __LOCAL_SIZE }; \ - __asm { pop eax }; \ -} +#define MTA_VERIFY_HOOK_LOCAL_SIZE \ + { \ + __asm { push eax } \ + ; \ + __asm { _localSize: mov eax, __LOCAL_SIZE } \ + ; \ + __asm { pop eax } \ + ; \ + } VOID HookInstallMethod(DWORD dwInstallAddress, DWORD dwHookFunction); VOID HookInstallCall(DWORD dwInstallAddress, DWORD dwHookFunction); @@ -33,13 +36,12 @@ BOOL HookInstall(DWORD dwInstallAddress, DWORD dwHookHandler, int iJmpCodeSize) BYTE* CreateJump(DWORD dwFrom, DWORD dwTo, BYTE* ByteArray); VOID HookCheckOriginalByte(DWORD dwInstallAddress, uchar ucExpectedValue); -#define EZHookInstall(type) \ - HookInstall( HOOKPOS_##type, (DWORD)HOOK_##type, HOOKSIZE_##type ); +#define EZHookInstall(type) HookInstall(HOOKPOS_##type, (DWORD)HOOK_##type, HOOKSIZE_##type); // Check original byte before hooking #define EZHookInstallChecked(type) \ - HookCheckOriginalByte( HOOKPOS_##type, HOOKCHECK_##type ); \ - EZHookInstall( type ); + HookCheckOriginalByte(HOOKPOS_##type, HOOKCHECK_##type); \ + EZHookInstall(type); #define EZHookInstallRestore(type) \ __if_exists(RESTORE_Bytes_##type) \ @@ -49,7 +51,7 @@ VOID HookCheckOriginalByte(DWORD dwInstallAddress, uchar ucExpectedValue); assert(sizeof(RESTORE_Bytes_##type) >= RESTORE_Size_##type); \ MemCpyFast(RESTORE_Bytes_##type, (PVOID)RESTORE_Addr_##type, RESTORE_Size_##type); \ } \ - EZHookInstall( type ); + EZHookInstall(type); // Structure for holding hook info struct SHookInfo @@ -63,7 +65,7 @@ struct SHookInfo uint uiSize; }; -#define MAKE_HOOK_INFO(type) SHookInfo ( HOOKPOS_##type, HOOK_##type, HOOKSIZE_##type ) +#define MAKE_HOOK_INFO(type) SHookInfo(HOOKPOS_##type, HOOK_##type, HOOKSIZE_##type) // Structure for holding poke info struct SPokeInfo diff --git a/Client/multiplayer_sa/multiplayer_keysync.cpp b/Client/multiplayer_sa/multiplayer_keysync.cpp index 68bdb72826f..02eca200fb5 100644 --- a/Client/multiplayer_sa/multiplayer_keysync.cpp +++ b/Client/multiplayer_sa/multiplayer_keysync.cpp @@ -15,8 +15,8 @@ extern CMultiplayerSA* pMultiplayer; -DWORD dwCurrentPlayerPed = 0; // stores the player ped temporarily during hooks -DWORD dwCurrentVehicle = 0; // stores the current vehicle during the hooks +DWORD dwCurrentPlayerPed = 0; // stores the player ped temporarily during hooks +DWORD dwCurrentVehicle = 0; // stores the current vehicle during the hooks DWORD dwParameter = 0; @@ -201,7 +201,7 @@ VOID ReturnContextToLocalPlayer() bNotInLocalContext = false; - CPed* pLocalPlayerPed = pGameInterface->GetPools()->GetPedFromRef((DWORD)1); // the player + CPed* pLocalPlayerPed = pGameInterface->GetPools()->GetPedFromRef((DWORD)1); // the player CPedSA* pLocalPlayerPedSA = dynamic_cast(pLocalPlayerPed); if (pLocalPlayerPedSA) { @@ -222,7 +222,7 @@ VOID ReturnContextToLocalPlayer() // Store any changes to the local-players stats? if (!bLocalStatsStatic) { - assert(0); // bLocalStatsStatic is always true + assert(0); // bLocalStatsStatic is always true MemCpyFast(&localStatsData.StatTypesFloat, (void*)0xb79380, sizeof(float) * MAX_FLOAT_STATS); MemCpyFast(&localStatsData.StatTypesInt, (void*)0xb79000, sizeof(int) * MAX_INT_STATS); MemCpyFast(&localStatsData.StatReactionValue, (void*)0xb78f10, sizeof(float) * MAX_REACTION_STATS); @@ -245,7 +245,7 @@ void SwitchContext(CPed* thePed) if (thePed && !bNotInLocalContext) { // Grab the local ped and the local pad - CPed* pLocalPlayerPed = pGameInterface->GetPools()->GetPedFromRef((DWORD)1); // the player + CPed* pLocalPlayerPed = pGameInterface->GetPools()->GetPedFromRef((DWORD)1); // the player CPad* pLocalPad = pGameInterface->GetPad(); CPadSAInterface* pLocalPadInterface = ((CPadSA*)pLocalPad)->GetInterface(); @@ -253,7 +253,7 @@ void SwitchContext(CPed* thePed) if (thePed != pLocalPlayerPed) { // Store the local pad - pLocalPad->Store(); // store a copy of the local pad internally + pLocalPad->Store(); // store a copy of the local pad internally // Grab the remote data storage for the player we're context switching to CPlayerPed* thePlayerPed = dynamic_cast(thePed); @@ -314,7 +314,8 @@ void SwitchContext(CPed* thePed) // Disable mouse look if they're not in a fight task and not aiming (strafing) // Fix GitHub Issue #395 - if (thePed->GetCurrentWeaponSlot() == eWeaponSlot::WEAPONSLOT_TYPE_UNARMED && data->m_pad.NewState.RightShoulder1 != 0 && thePed->GetPedIntelligence()->GetFightTask()) + if (thePed->GetCurrentWeaponSlot() == eWeaponSlot::WEAPONSLOT_TYPE_UNARMED && data->m_pad.NewState.RightShoulder1 != 0 && + thePed->GetPedIntelligence()->GetFightTask()) bDisableMouseLook = false; // Disable mouse look if they're not underwater (Ped vertical rotation when diving) diff --git a/Client/multiplayer_sa/multiplayer_keysync.h b/Client/multiplayer_sa/multiplayer_keysync.h index ec0e13e7194..d95f0e2c092 100644 --- a/Client/multiplayer_sa/multiplayer_keysync.h +++ b/Client/multiplayer_sa/multiplayer_keysync.h @@ -37,44 +37,44 @@ VOID HOOK_CBike__ProcessControl(); VOID HOOK_CHeli__ProcessControl(); // gta's stuff -#define VAR_Keystates 0x7DBCB0 +#define VAR_Keystates 0x7DBCB0 -#define FUNC_CPlayerPed__ProcessControl 0x60EA90 -#define VTBL_CPlayerPed__ProcessControl 0x86D190 +#define FUNC_CPlayerPed__ProcessControl 0x60EA90 +#define VTBL_CPlayerPed__ProcessControl 0x86D190 -#define FUNC_CAutomobile__ProcessControl 0x6B1880 -#define VTBL_CAutomobile__ProcessControl 0x871148 +#define FUNC_CAutomobile__ProcessControl 0x6B1880 +#define VTBL_CAutomobile__ProcessControl 0x871148 -#define FUNC_CMonsterTruck__ProcessControl 0x6C8250 -#define VTBL_CMonsterTruck__ProcessControl 0x871800 +#define FUNC_CMonsterTruck__ProcessControl 0x6C8250 +#define VTBL_CMonsterTruck__ProcessControl 0x871800 -#define FUNC_CTrailer__ProcessControl 0x6CED20 -#define VTBL_CTrailer__ProcessControl 0x871C50 +#define FUNC_CTrailer__ProcessControl 0x6CED20 +#define VTBL_CTrailer__ProcessControl 0x871C50 -#define FUNC_CQuadBike__ProcessControl 0x6CDCC0 -#define VTBL_CQuadBike__ProcessControl 0x871B10 +#define FUNC_CQuadBike__ProcessControl 0x6CDCC0 +#define VTBL_CQuadBike__ProcessControl 0x871B10 -#define FUNC_CPlane__ProcessControl 0x6C9260 -#define VTBL_CPlane__ProcessControl 0x871970 +#define FUNC_CPlane__ProcessControl 0x6C9260 +#define VTBL_CPlane__ProcessControl 0x871970 -#define FUNC_CBmx__ProcessControl 0x6BFA30 -#define VTBL_CBmx__ProcessControl 0x871550 +#define FUNC_CBmx__ProcessControl 0x6BFA30 +#define VTBL_CBmx__ProcessControl 0x871550 -#define FUNC_CTrain__ProcessControl 0x6F86A0 -#define VTBL_CTrain__ProcessControl 0x872398 +#define FUNC_CTrain__ProcessControl 0x6F86A0 +#define VTBL_CTrain__ProcessControl 0x872398 -#define FUNC_CBoat__ProcessControl 0x6F1770 -#define VTBL_CBoat__ProcessControl 0x8721C8 +#define FUNC_CBoat__ProcessControl 0x6F1770 +#define VTBL_CBoat__ProcessControl 0x8721C8 -#define FUNC_CBike__ProcessControl 0x6B9250 -#define VTBL_CBike__ProcessControl 0x871388 +#define FUNC_CBike__ProcessControl 0x6B9250 +#define VTBL_CBike__ProcessControl 0x871388 -#define FUNC_CHeli__ProcessControl 0x6C7050 -#define VTBL_CHeli__ProcessControl 0x8716A8 +#define FUNC_CHeli__ProcessControl 0x6C7050 +#define VTBL_CHeli__ProcessControl 0x8716A8 // #define FUNC_CVehicle__ProcessUnknown 0x593030 // #define VTBL_CVehicle__ProcessUnknown 0x69ADB0 -#define CODE_SetTargetRotation 0x535851 +#define CODE_SetTargetRotation 0x535851 -#define VAR_CameraRotation 0xB6F178 +#define VAR_CameraRotation 0xB6F178 diff --git a/Client/multiplayer_sa/multiplayer_shotsync.cpp b/Client/multiplayer_sa/multiplayer_shotsync.cpp index 1ad2b9634b1..531c6051755 100644 --- a/Client/multiplayer_sa/multiplayer_shotsync.cpp +++ b/Client/multiplayer_sa/multiplayer_shotsync.cpp @@ -21,7 +21,7 @@ extern CMultiplayerSA* pMultiplayer; std::list ShotSyncData; -CShotSyncData LocalShotSyncData; +CShotSyncData LocalShotSyncData; float* fDirectionX; float* fDirectionY; @@ -79,7 +79,7 @@ DWORD RETURN_CProjectile__CProjectile = 0x4037B3; CPools* m_pools = 0; -#define VAR_CWorld_IncludeCarTyres 0xb7cd70 // Used for CWorld_ProcessLineOfSight +#define VAR_CWorld_IncludeCarTyres 0xb7cd70 // Used for CWorld_ProcessLineOfSight void InitFireInstantHit_MidHooks(); void InitFireSniper_MidHooks(); @@ -307,7 +307,7 @@ static void Event_BulletImpact() m_pBulletImpactHandler(pInitiator, pVictim, pBulletImpactStartPosition, pBulletImpactEndPosition); } } - vecSavedBulletImpactEndPosition = *pBulletImpactEndPosition; // Saved for vehicle damage event parameters + vecSavedBulletImpactEndPosition = *pBulletImpactEndPosition; // Saved for vehicle damage event parameters } } @@ -381,7 +381,7 @@ static void __declspec(naked) HOOK_SkipAim() { // Grab his remote storage pTempRemote = CRemoteDataSA::GetRemoteDataStorage( - pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed + pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed if (pTempRemote) { if (pTempRemote->ProcessPlayerWeapon()) @@ -462,7 +462,7 @@ static void __declspec(naked) HOOK_IKChainManager_PointArm() { // Grab his remote storage pTempRemote = CRemoteDataSA::GetRemoteDataStorage( - pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed + pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed if (pTempRemote) { if (pTempRemote->ProcessPlayerWeapon()) @@ -531,7 +531,7 @@ static void __declspec(naked) HOOK_IKChainManager_LookAt() { // Grab his remote storage pTempRemote = CRemoteDataSA::GetRemoteDataStorage( - pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed + pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed if (pTempRemote) { if (pTempRemote->ProcessPlayerWeapon()) @@ -593,17 +593,17 @@ static void __declspec(naked) HOOK_CWeapon__Fire() if (!WriteTargetDataForPed(pShootingPed, vecTargetPosition, vecOrigin)) { // Don't fire shot - // clang-format off + // clang-format off __asm { popad mov al, 1 retn 18h } - // clang-format on + // clang-format on } - // clang-format off + // clang-format off __asm { popad @@ -613,7 +613,7 @@ static void __declspec(naked) HOOK_CWeapon__Fire() push esi push edi } - // clang-format on + // clang-format on // clang-format off __asm @@ -652,7 +652,7 @@ static void __declspec(naked) HOOK_CWeapon__PostFire() // clang-format on } -static void __declspec(naked) HOOK_CWeapon__PostFire2() // handles the FALSE exit point at 0x074241E +static void __declspec(naked) HOOK_CWeapon__PostFire2() // handles the FALSE exit point at 0x074241E { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -676,7 +676,7 @@ static void __declspec(naked) HOOK_CWeapon__PostFire2() // handles th // clang-format on } -static const DWORD CWeapon_DoBulletImpact_RET = 0x73B557; +static const DWORD CWeapon_DoBulletImpact_RET = 0x73B557; static void __declspec(naked) HOOK_CWeapon_DoBulletImpact() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -856,8 +856,8 @@ bool ProcessDamageEvent(CEventDamageSAInterface* event, CPedSAInterface* affects return true; } -CPedSAInterface* affectsPed = 0; -CEventDamageSAInterface* event = 0; +CPedSAInterface* affectsPed = 0; +CEventDamageSAInterface* event = 0; static void __declspec(naked) HOOK_CEventDamage__AffectsPed() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1082,7 +1082,7 @@ static void __declspec(naked) HOOK_CProjectileInfo__AddProjectile() } // clang-format on if (ProcessProjectileAdd()) - { // projectile should be created + { // projectile should be created // clang-format off __asm { @@ -1207,9 +1207,9 @@ void OnMy_CWeapon_FireInstantHit_Mid(CEntitySAInterface* pEntity, CVector* pvecN } // Hook info -#define HOOKPOS_CWeapon_FireInstantHit_Mid 0x740B89 -#define HOOKSIZE_CWeapon_FireInstantHit_Mid 5 -DWORD RETURN_CWeapon_FireInstantHit_Mid = 0x740B8E; +#define HOOKPOS_CWeapon_FireInstantHit_Mid 0x740B89 +#define HOOKSIZE_CWeapon_FireInstantHit_Mid 5 +DWORD RETURN_CWeapon_FireInstantHit_Mid = 0x740B8E; static void __declspec(naked) HOOK_CWeapon_FireInstantHit_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1292,9 +1292,9 @@ void OnMy_CWeapon_FireSniper_Mid(CEntitySAInterface* pEntity, CVector* pvecEndHi } // Hook info -#define HOOKPOS_CWeapon_FireSniper_Mid 0x73AE31 -#define HOOKSIZE_CWeapon_FireSniper_Mid 5 -DWORD RETURN_CWeapon_FireSniper_Mid = 0x73AE39; +#define HOOKPOS_CWeapon_FireSniper_Mid 0x73AE31 +#define HOOKSIZE_CWeapon_FireSniper_Mid 5 +DWORD RETURN_CWeapon_FireSniper_Mid = 0x73AE39; static void __declspec(naked) HOOK_CWeapon_FireSniper_Mid() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1382,8 +1382,8 @@ void _cdecl DoFireInstantHitPokes() MemPutFast(VAR_CWorld_IncludeCarTyres, 1); } -DWORD dwFunc_CWeapon_FireInstantHit_ret = 0x740B6E; -DWORD dwFunc_CWorld_ProcessLineOfSight = 0x56BA00; +DWORD dwFunc_CWeapon_FireInstantHit_ret = 0x740B6E; +DWORD dwFunc_CWorld_ProcessLineOfSight = 0x56BA00; static void __declspec(naked) HOOK_CWeapon_FireInstantHit() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1439,8 +1439,7 @@ static void __declspec(naked) HOOK_CWeapon_FireInstantHit() __asm { call DoFireInstantHitPokes - } - // clang-format on + } // clang-format on HandleRemoteInstantHit(); @@ -1479,10 +1478,10 @@ bool FireInstantHit_CameraMode() return false; } -DWORD dwFunc_CWeapon_FireInstantHit_CameraMode_ret = 0x7403C7; -DWORD dwAddr_FireInstantHit_CameraMode = 0x740389; -DWORD dwAddr_FireInstantHit_CameraMode_2 = 0x740373; -short sFireInstantHit_CameraMode_camMode = 0; +DWORD dwFunc_CWeapon_FireInstantHit_CameraMode_ret = 0x7403C7; +DWORD dwAddr_FireInstantHit_CameraMode = 0x740389; +DWORD dwAddr_FireInstantHit_CameraMode_2 = 0x740373; +short sFireInstantHit_CameraMode_camMode = 0; static void __declspec(naked) HOOK_CWeapon_FireInstantHit_CameraMode() { MTA_VERIFY_HOOK_LOCAL_SIZE; @@ -1561,8 +1560,8 @@ bool FireInstantHit_IsPlayer() return false; } -DWORD RETURN_CWeapon_FireInstantHit_IsPlayer = 0x740353; -DWORD FUNC_CPlayer_IsPed = 0x5DF8F0; +DWORD RETURN_CWeapon_FireInstantHit_IsPlayer = 0x740353; +DWORD FUNC_CPlayer_IsPed = 0x5DF8F0; static void __declspec(naked) HOOK_CWeapon_FireInstantHit_IsPlayer() { MTA_VERIFY_HOOK_LOCAL_SIZE; diff --git a/Client/multiplayer_sa/multiplayer_shotsync.h b/Client/multiplayer_sa/multiplayer_shotsync.h index 1c06574f36c..7ea90b17609 100644 --- a/Client/multiplayer_sa/multiplayer_shotsync.h +++ b/Client/multiplayer_sa/multiplayer_shotsync.h @@ -18,26 +18,26 @@ // #include "../game_sa/CPedIKSA.h" -#define HOOKPOS_CWeapon__Fire 0x742300 -#define HOOKPOS_CWeapon__PostFire 0x742A02 // if the function returns true -#define HOOKPOS_CWeapon__PostFire2 0x742423 // if the function returns false -#define HOOKPOS_CPedIK__PointGunInDirection 0x5FDC00 -#define HOOKPOS_CTaskSimpleGangDriveBy__PlayerTarget 0x621A57 -#define HOOKPOS_CWeapon__Fire_Sniper 0x7424A6 -#define HOOKRET_CWeapon__Fire_Sniper 0x7424D7 -#define HOOKPOS_CEventDamage__AffectsPed 0x4B35A0 -#define HOOKPOS_CEventVehicleExplosion__AffectsPed 0x4B0E58 -#define HOOKPOS_CFireManager__StartFire 0x53A050 -#define HOOKPOS_CProjectileInfo__AddProjectile 0x737C80 -#define HOOKPOS_CProjectile__CProjectile 0x5A4030 -#define HOOKPOS_IKChainManager_PointArm 0x618B66 -#define HOOKPOS_IKChainManager_LookAt 0x618970 -#define HOOKPOS_IKChainManager_SkipAim 0x62AEE7 -#define HOOKPOS_CTaskSimpleUsegun_ProcessPed 0x62A380 -#define HOOKPOS_CWeapon_FireInstantHit 0x740B42 -#define HOOKPOS_CWeapon_FireInstantHit_CameraMode 0x74036D -#define HOOKPOS_CWeapon_FireInstantHit_IsPlayer 0x74034C -#define HOOKPOS_CWeapon_DoBulletImpact 0x73B550 +#define HOOKPOS_CWeapon__Fire 0x742300 +#define HOOKPOS_CWeapon__PostFire 0x742A02 // if the function returns true +#define HOOKPOS_CWeapon__PostFire2 0x742423 // if the function returns false +#define HOOKPOS_CPedIK__PointGunInDirection 0x5FDC00 +#define HOOKPOS_CTaskSimpleGangDriveBy__PlayerTarget 0x621A57 +#define HOOKPOS_CWeapon__Fire_Sniper 0x7424A6 +#define HOOKRET_CWeapon__Fire_Sniper 0x7424D7 +#define HOOKPOS_CEventDamage__AffectsPed 0x4B35A0 +#define HOOKPOS_CEventVehicleExplosion__AffectsPed 0x4B0E58 +#define HOOKPOS_CFireManager__StartFire 0x53A050 +#define HOOKPOS_CProjectileInfo__AddProjectile 0x737C80 +#define HOOKPOS_CProjectile__CProjectile 0x5A4030 +#define HOOKPOS_IKChainManager_PointArm 0x618B66 +#define HOOKPOS_IKChainManager_LookAt 0x618970 +#define HOOKPOS_IKChainManager_SkipAim 0x62AEE7 +#define HOOKPOS_CTaskSimpleUsegun_ProcessPed 0x62A380 +#define HOOKPOS_CWeapon_FireInstantHit 0x740B42 +#define HOOKPOS_CWeapon_FireInstantHit_CameraMode 0x74036D +#define HOOKPOS_CWeapon_FireInstantHit_IsPlayer 0x74034C +#define HOOKPOS_CWeapon_DoBulletImpact 0x73B550 // our stuff VOID InitShotsyncHooks(); diff --git a/Client/sdk/core/CChatInterface.h b/Client/sdk/core/CChatInterface.h index dd929a3d1d1..3ef94dd5aa4 100644 --- a/Client/sdk/core/CChatInterface.h +++ b/Client/sdk/core/CChatInterface.h @@ -57,7 +57,7 @@ namespace Chat BOTTOM = 2 }; } - } // namespace Position + } namespace Text { @@ -69,8 +69,8 @@ namespace Chat RIGHT = 1 }; } - } // namespace Text -} // namespace Chat + } +} typedef Chat::Font::eFont eChatFont; typedef Chat::ColorType::eType eChatColorType; diff --git a/Client/sdk/core/CClientCommands.h b/Client/sdk/core/CClientCommands.h index bc9f1689b18..ecb58869689 100644 --- a/Client/sdk/core/CClientCommands.h +++ b/Client/sdk/core/CClientCommands.h @@ -18,4 +18,4 @@ namespace mtasa using namespace std::string_view_literals; static inline auto CMD_ALWAYS_SHOW_TRANSFERBOX = "cvar_always_show_transferbox"sv; -} // namespace mtasa +} diff --git a/Client/sdk/core/CCommandsInterface.h b/Client/sdk/core/CCommandsInterface.h index 950a1bc1dc8..c90d15a2595 100644 --- a/Client/sdk/core/CCommandsInterface.h +++ b/Client/sdk/core/CCommandsInterface.h @@ -18,8 +18,8 @@ typedef bool (*pfnExecuteCommandHandler)(const char*, const char*, bool, bool, b typedef void (*PFNCOMMAND)(const char*); -#define MAX_COMMAND_NAME_LENGTH 128 -#define MAX_COMMAND_DESCRIPTION_LENGTH 128 +#define MAX_COMMAND_NAME_LENGTH 128 +#define MAX_COMMAND_DESCRIPTION_LENGTH 128 typedef struct tagCOMMANDENTRY { diff --git a/Client/sdk/core/CCoreInterface.h b/Client/sdk/core/CCoreInterface.h index c80cb331884..07f3848e61c 100644 --- a/Client/sdk/core/CCoreInterface.h +++ b/Client/sdk/core/CCoreInterface.h @@ -42,7 +42,7 @@ enum eCoreVersion }; #ifndef WITH_TIMING_CHECKPOINTS - #define WITH_TIMING_CHECKPOINTS 1 // Comment this line to remove timing checkpoint code + #define WITH_TIMING_CHECKPOINTS 1 // Comment this line to remove timing checkpoint code #endif #if WITH_TIMING_CHECKPOINTS @@ -80,7 +80,7 @@ class CCoreInterface virtual CCVarsInterface* GetCVars() = 0; virtual CLocalizationInterface* GetLocalization() = 0; virtual CWebCoreInterface* GetWebCore() = 0; - virtual CWebCoreInterface* GetWebCoreUnchecked() = 0; // For cleanup in destructors only - bypasses initialization check + virtual CWebCoreInterface* GetWebCoreUnchecked() = 0; // For cleanup in destructors only - bypasses initialization check virtual CTrayIconInterface* GetTrayIcon() = 0; virtual std::shared_ptr GetDiscord() = 0; virtual FPSLimiter::FPSLimiterInterface* GetFPSLimiter() const noexcept = 0; diff --git a/Client/sdk/core/CGraphicsInterface.h b/Client/sdk/core/CGraphicsInterface.h index 50c4cdf5b1f..e12a8814249 100644 --- a/Client/sdk/core/CGraphicsInterface.h +++ b/Client/sdk/core/CGraphicsInterface.h @@ -70,12 +70,12 @@ enum eFontQuality FONT_QUALITY_DRAFT = DRAFT_QUALITY, FONT_QUALITY_PROOF = PROOF_QUALITY, -#if( WINVER >= 0x0400 ) +#if (WINVER >= 0x0400) FONT_QUALITY_NONANTIALIASED = NONANTIALIASED_QUALITY, FONT_QUALITY_ANTIALIASED = ANTIALIASED_QUALITY, #endif -#if( _WIN32_WINNT >= _WIN32_WINNT_WINXP ) +#if (_WIN32_WINNT >= _WIN32_WINNT_WINXP) FONT_QUALITY_CLEARTYPE = CLEARTYPE_QUALITY, FONT_QUALITY_CLEARTYPE_NATURAL = CLEARTYPE_NATURAL_QUALITY, #endif @@ -88,10 +88,10 @@ namespace EBlendMode enum EBlendModeType { NONE, - BLEND, // Alpha blend - ADD, // Color add (used for making composite textures with a premultiplied source) - MODULATE_ADD, // Modulate color with alpha then add (used for making composite textures with a non-premultiplied source) - OVERWRITE, // Blat everything + BLEND, // Alpha blend + ADD, // Color add (used for making composite textures with a premultiplied source) + MODULATE_ADD, // Modulate color with alpha then add (used for making composite textures with a non-premultiplied source) + OVERWRITE, // Blat everything }; } using EBlendMode::EBlendModeType; @@ -152,11 +152,13 @@ class CGraphicsInterface // Queued up drawing virtual void DrawLineQueued(float fX1, float fY1, float fX2, float fY2, float fWidth, unsigned long ulColor, bool bPostGUI) = 0; - virtual void DrawLine3DQueued(const CVector& vecBegin, const CVector& vecEnd, float fWidth, unsigned long ulColor, eRenderStage stage = eRenderStage::PRE_FX) = 0; + virtual void DrawLine3DQueued(const CVector& vecBegin, const CVector& vecEnd, float fWidth, unsigned long ulColor, + eRenderStage stage = eRenderStage::PRE_FX) = 0; virtual void DrawMaterialLine3DQueued(const CVector& vecBegin, const CVector& vecEnd, float fWidth, unsigned long ulColor, CMaterialItem* pMaterial, float fU = 0, float fV = 0, float fSizeU = 1, float fSizeV = 1, bool bRelativeUV = true, bool bFlipUV = false, - bool bUseFaceToward = false, const CVector& vecFaceToward = CVector(), eRenderStage renderStage = eRenderStage::POST_FX) = 0; + bool bUseFaceToward = false, const CVector& vecFaceToward = CVector(), + eRenderStage renderStage = eRenderStage::POST_FX) = 0; virtual void DrawRectQueued(float fX, float fY, float fWidth, float fHeight, unsigned long ulColor, bool bPostGUI, bool bSubPixelPositioning = false) = 0; diff --git a/Client/sdk/core/CKeyBindsInterface.h b/Client/sdk/core/CKeyBindsInterface.h index 210efd0a126..b6cb07671cf 100644 --- a/Client/sdk/core/CKeyBindsInterface.h +++ b/Client/sdk/core/CKeyBindsInterface.h @@ -64,10 +64,10 @@ struct SBindableGTAControl enum class KeyBindType { UNDEFINED, - COMMAND, // bind key function args - GTA_CONTROL, // bind key gta_control - FUNCTION, // script bind key to function - CONTROL_FUNCTION, // script bind gta_control to function (pressing control, calls function) + COMMAND, // bind key function args + GTA_CONTROL, // bind key gta_control + FUNCTION, // script bind key to function + CONTROL_FUNCTION, // script bind gta_control to function (pressing control, calls function) }; class CKeyBind @@ -91,14 +91,14 @@ class CKeyBindWithState : public CKeyBind public: bool state{false}; - bool triggerState{false}; // true == "down", false == "up" + bool triggerState{false}; // true == "down", false == "up" }; enum class BindingContext { - USER, // Created by user via /bind command - RESOURCE, // Created by resource via bindKey - SYSTEM // Created by system/default + USER, // Created by user via /bind command + RESOURCE, // Created by resource via bindKey + SYSTEM // Created by system/default }; class CCommandBind : public CKeyBindWithState @@ -107,13 +107,13 @@ class CCommandBind : public CKeyBindWithState CCommandBind() : CKeyBindWithState(KeyBindType::COMMAND) {} public: - std::string command; - std::string arguments; - std::string resource; - std::string originalScriptKey; // Original key set by script - std::string sourceResource; // Resource that created this binding - bool wasCreatedByScript{false}; - bool isReplacingScriptKey{false}; // true if script set key is not being used + std::string command; + std::string arguments; + std::string resource; + std::string originalScriptKey; // Original key set by script + std::string sourceResource; // Resource that created this binding + bool wasCreatedByScript{false}; + bool isReplacingScriptKey{false}; // true if script set key is not being used BindingContext context{BindingContext::USER}; // Context of this binding }; @@ -184,8 +184,10 @@ class CKeyBindsInterface virtual CCommandBind* FindMatchingUpBind(CCommandBind* pBind) = 0; // Context-aware binding methods - virtual bool CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, const char* arguments = NULL, const char* resource = NULL) = 0; - virtual bool RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, const char* arguments = NULL, const char* resource = NULL) = 0; + virtual bool CommandExistsInContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, + const char* arguments = NULL, const char* resource = NULL) = 0; + virtual bool RemoveCommandFromContext(const char* key, const char* command, BindingContext context, bool checkState = false, bool state = true, + const char* arguments = NULL, const char* resource = NULL) = 0; virtual bool HasAnyBindingForKey(const char* key, bool checkState = false, bool state = true) = 0; virtual bool HasBindingInContext(const char* key, BindingContext context, bool checkState = false, bool state = true) = 0; diff --git a/Client/sdk/core/CLocalizationInterface.h b/Client/sdk/core/CLocalizationInterface.h index e5d877f999c..4c4eeee4701 100644 --- a/Client/sdk/core/CLocalizationInterface.h +++ b/Client/sdk/core/CLocalizationInterface.h @@ -12,14 +12,14 @@ #pragma once #ifdef _ -#undef _ + #undef _ #endif -#define _ g_pLocalization->Translate -#define _tc g_pLocalization->TranslateWithContext -#define _tn g_pLocalization->TranslatePlural -#define _tcn g_pLocalization->TranslatePluralWithContext -#define _td // Dummy translation tag for compile-time use only. Translation templates are generated by this, but no source code interaction +#define _ g_pLocalization->Translate +#define _tc g_pLocalization->TranslateWithContext +#define _tn g_pLocalization->TranslatePlural +#define _tcn g_pLocalization->TranslatePluralWithContext +#define _td // Dummy translation tag for compile-time use only. Translation templates are generated by this, but no source code interaction class CLanguage; diff --git a/Client/sdk/core/CRenderItemManagerInterface.h b/Client/sdk/core/CRenderItemManagerInterface.h index c6faf45a0c5..2f3cf1bb84d 100644 --- a/Client/sdk/core/CRenderItemManagerInterface.h +++ b/Client/sdk/core/CRenderItemManagerInterface.h @@ -43,14 +43,14 @@ class CWebViewInterface; class CEffectTemplate; class CVectorGraphicItem; -#define RDEFAULT ((uint)-1) +#define RDEFAULT ((uint) - 1) enum ERenderFormat { RFORMAT_UNKNOWN, - RFORMAT_ARGB = 21, // D3DFMT_A8R8G8B8 - RFORMAT_XRGB = 22, // D3DFMT_X8R8G8B8 - RFORMAT_RGB = 23, // D3DFMT_R5G6B5 + RFORMAT_ARGB = 21, // D3DFMT_A8R8G8B8 + RFORMAT_XRGB = 22, // D3DFMT_X8R8G8B8 + RFORMAT_RGB = 23, // D3DFMT_R5G6B5 RFORMAT_DXT1 = '1TXD', RFORMAT_DXT2 = '2TXD', RFORMAT_DXT3 = '3TXD', @@ -161,8 +161,8 @@ class CRenderItemManagerInterface ETextureType textureType = TTYPE_TEXTURE, uint uiVolumeDepth = 1) = 0; virtual CShaderItem* CreateShader(const SString& strFile, const SString& strRootPath, bool bIsRawData, SString& strOutStatus, float fPriority, float fMaxDistance, bool bLayered, bool bDebug, int iTypeMask, const EffectMacroList& macros) = 0; - virtual CRenderTargetItem* CreateRenderTarget(uint uiSizeX, uint uiSizeY, bool bHasSurfaceFormat, bool bWithAlphaChannel, - int surfaceFormat, bool bForce = false) = 0; + virtual CRenderTargetItem* CreateRenderTarget(uint uiSizeX, uint uiSizeY, bool bHasSurfaceFormat, bool bWithAlphaChannel, int surfaceFormat, + bool bForce = false) = 0; virtual CScreenSourceItem* CreateScreenSource(uint uiSizeX, uint uiSizeY) = 0; virtual CWebBrowserItem* CreateWebBrowser(uint uiSizeX, uint uiSizeY) = 0; virtual CVectorGraphicItem* CreateVectorGraphic(uint uiSizeX, uint uiSizeY) = 0; @@ -185,10 +185,10 @@ class CRenderItemManagerInterface virtual void PreDrawWorld() = 0; virtual void SetDepthBufferFormat(ERenderFormat depthBufferFormat) = 0; virtual ERenderFormat GetDepthBufferFormat() = 0; - virtual void SaveReadableDepthBuffer() = 0; - virtual void FlushNonAARenderTarget() = 0; - virtual HRESULT HandleStretchRect(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, - CONST RECT* pDestRect, int Filter) = 0; + virtual void SaveReadableDepthBuffer() = 0; + virtual void FlushNonAARenderTarget() = 0; + virtual HRESULT HandleStretchRect(IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, CONST RECT* pDestRect, + int Filter) = 0; }; //////////////////////////////////////////////////////////////// @@ -505,8 +505,8 @@ class CRenderTargetItem : public CTextureItem { DECLARE_CLASS(CRenderTargetItem, CTextureItem) CRenderTargetItem() : ClassInit(this) {} - virtual void PostConstruct(CRenderItemManager* pManager, uint uiSizeX, uint uiSizeY, bool bHasSurfaceFormat, bool bWithAlphaChannel, - int surfaceFormat, bool bIncludeInMemoryStats); + virtual void PostConstruct(CRenderItemManager* pManager, uint uiSizeX, uint uiSizeY, bool bHasSurfaceFormat, bool bWithAlphaChannel, int surfaceFormat, + bool bIncludeInMemoryStats); virtual void PreDestruct(); virtual bool IsValid(); virtual void OnLostDevice(); diff --git a/Client/sdk/core/CrashHandlerExports.h b/Client/sdk/core/CrashHandlerExports.h index 6c1f148ad4e..72e6366a433 100644 --- a/Client/sdk/core/CrashHandlerExports.h +++ b/Client/sdk/core/CrashHandlerExports.h @@ -18,28 +18,28 @@ #endif #ifdef __cplusplus - #define MTA_CH_NOEXCEPT noexcept + #define MTA_CH_NOEXCEPT noexcept #define MTA_CH_NODISCARD [[nodiscard]] - extern "C" - { +extern "C" +{ #else #define MTA_CH_NOEXCEPT #define MTA_CH_NODISCARD #endif -MTA_CH_NODISCARD BOOL BUGSUTIL_DLLINTERFACE __stdcall EnableAllHandlersAfterInitialization(void) MTA_CH_NOEXCEPT; + MTA_CH_NODISCARD BOOL BUGSUTIL_DLLINTERFACE __stdcall EnableAllHandlersAfterInitialization(void) MTA_CH_NOEXCEPT; #ifdef __cplusplus -MTA_CH_NODISCARD BOOL BUGSUTIL_DLLINTERFACE __stdcall StartWatchdogThread(DWORD mainThreadId, DWORD timeoutSeconds = 20) MTA_CH_NOEXCEPT; + MTA_CH_NODISCARD BOOL BUGSUTIL_DLLINTERFACE __stdcall StartWatchdogThread(DWORD mainThreadId, DWORD timeoutSeconds = 20) MTA_CH_NOEXCEPT; #else MTA_CH_NODISCARD BOOL BUGSUTIL_DLLINTERFACE __stdcall StartWatchdogThread(DWORD mainThreadId, DWORD timeoutSeconds) MTA_CH_NOEXCEPT; #endif -void BUGSUTIL_DLLINTERFACE __stdcall StopWatchdogThread(void) MTA_CH_NOEXCEPT; -void BUGSUTIL_DLLINTERFACE __stdcall UpdateWatchdogHeartbeat(void) MTA_CH_NOEXCEPT; + void BUGSUTIL_DLLINTERFACE __stdcall StopWatchdogThread(void) MTA_CH_NOEXCEPT; + void BUGSUTIL_DLLINTERFACE __stdcall UpdateWatchdogHeartbeat(void) MTA_CH_NOEXCEPT; #ifdef __cplusplus - } +} #endif #undef MTA_CH_NOEXCEPT diff --git a/Client/sdk/core/FPSLimiterInterface.h b/Client/sdk/core/FPSLimiterInterface.h index 79315af887a..c428d7f3be0 100644 --- a/Client/sdk/core/FPSLimiterInterface.h +++ b/Client/sdk/core/FPSLimiterInterface.h @@ -19,11 +19,11 @@ namespace FPSLimiter // Enum for enforcement types (replaces constexpr constants for better type safety) enum class EnforcerType : std::uint8_t { - None = 0, // No frame rate limit enforced (unlimited FPS) - VSync = 1, // Frame rate limited by display refresh rate - UserDefined = 2, // Frame rate limited by the user via settings menu or console variable - Client = 3, // Frame rate limited by the client script - Server = 4 // Frame rate limited by the server script + None = 0, // No frame rate limit enforced (unlimited FPS) + VSync = 1, // Frame rate limited by display refresh rate + UserDefined = 2, // Frame rate limited by the user via settings menu or console variable + Client = 3, // Frame rate limited by the client script + Server = 4 // Frame rate limited by the server script }; DECLARE_ENUM(EnforcerType); @@ -33,18 +33,18 @@ namespace FPSLimiter virtual ~FPSLimiterInterface() {} public: - virtual void Reset() = 0; // Reset all frame rate limits to default (unlimited) + virtual void Reset() = 0; // Reset all frame rate limits to default (unlimited) - virtual std::uint16_t GetFPSTarget() const noexcept = 0; // Get the current active frame rate limit (0 = no limit) - virtual EnforcerType GetEnforcer() const noexcept = 0; // Get who is enforcing the current frame rate limit (as uint8_t from EnforcerType) + virtual std::uint16_t GetFPSTarget() const noexcept = 0; // Get the current active frame rate limit (0 = no limit) + virtual EnforcerType GetEnforcer() const noexcept = 0; // Get who is enforcing the current frame rate limit (as uint8_t from EnforcerType) - virtual void SetServerEnforcedFPS(std::uint16_t fps) = 0; // Set the server-enforced frame rate limit (0 = no limit) - virtual void SetClientEnforcedFPS(std::uint16_t fps) = 0; // Set the client-enforced frame rate limit (0 = no limit) - virtual void SetUserDefinedFPS(std::uint16_t fps) = 0; // Set the user-defined frame rate limit (0 = no limit) - virtual void SetDisplayVSync(bool enabled) = 0; // Set the display refresh rate to cap FPS (0 = no cap) + virtual void SetServerEnforcedFPS(std::uint16_t fps) = 0; // Set the server-enforced frame rate limit (0 = no limit) + virtual void SetClientEnforcedFPS(std::uint16_t fps) = 0; // Set the client-enforced frame rate limit (0 = no limit) + virtual void SetUserDefinedFPS(std::uint16_t fps) = 0; // Set the user-defined frame rate limit (0 = no limit) + virtual void SetDisplayVSync(bool enabled) = 0; // Set the display refresh rate to cap FPS (0 = no cap) - virtual void OnFPSLimitChange() = 0; // Event handler called when the active frame rate limit changes - virtual void OnFrameStart() = 0; // Event handler called at the start of each frame - virtual void OnFrameEnd() = 0; // Event handler called at the end of each frame + virtual void OnFPSLimitChange() = 0; // Event handler called when the active frame rate limit changes + virtual void OnFrameStart() = 0; // Event handler called at the start of each frame + virtual void OnFrameEnd() = 0; // Event handler called at the end of each frame }; -} // namespace FPSLimiter +} diff --git a/Client/sdk/game/C3DMarker.h b/Client/sdk/game/C3DMarker.h index 151184eaf0d..43ffdd2c32d 100644 --- a/Client/sdk/game/C3DMarker.h +++ b/Client/sdk/game/C3DMarker.h @@ -23,13 +23,13 @@ struct RpClump; class C3DMarker { public: - virtual ~C3DMarker(){}; + virtual ~C3DMarker() {}; virtual void GetMatrix(CMatrix* pMatrix) = 0; virtual void SetMatrix(CMatrix* pMatrix) = 0; virtual void SetPosition(CVector* vecPosition) = 0; virtual CVector* GetPosition() = 0; - virtual DWORD GetType() = 0; // need enum? + virtual DWORD GetType() = 0; // need enum? virtual bool IsActive() = 0; virtual DWORD GetIdentifier() = 0; virtual SharedUtil::SColor GetColor() = 0; diff --git a/Client/sdk/game/CAEVehicleAudioEntity.h b/Client/sdk/game/CAEVehicleAudioEntity.h index 14549e4763e..1904b0d7166 100644 --- a/Client/sdk/game/CAEVehicleAudioEntity.h +++ b/Client/sdk/game/CAEVehicleAudioEntity.h @@ -19,10 +19,10 @@ enum eVehicleAudioType VEHICLE_AUDIO_BOAT, VEHICLE_AUDIO_HELI, VEHICLE_AUDIO_PLANE, - VEHICLE_AUDIO_SEAPLANE, // unused? + VEHICLE_AUDIO_SEAPLANE, // unused? VEHICLE_AUDIO_TRAIN = 8, - VEHICLE_AUDIO_SPECIAL, // RC vehicles, vortex, caddy, few trailers + VEHICLE_AUDIO_SPECIAL, // RC vehicles, vortex, caddy, few trailers VEHICLE_AUDIO_SILENT }; diff --git a/Client/sdk/game/CAnimBlendAssocGroup.h b/Client/sdk/game/CAnimBlendAssocGroup.h index ab679af5773..dc9873751d6 100644 --- a/Client/sdk/game/CAnimBlendAssocGroup.h +++ b/Client/sdk/game/CAnimBlendAssocGroup.h @@ -387,9 +387,9 @@ enum class eAnimID : int ANIM_ID_BIKE_DRIVEBYRHS = 203, ANIM_ID_BIKE_DRIVEBYFT = 204, ANIM_ID_BIKE_PASSENGER = 205, - ANIM_ID_BIKE_BUNNYHOP = 206, // bicycle anim - ANIM_ID_BIKE_PEDAL = 207, // bicycle anim - ANIM_ID_BIKE_SPRINT = 208, // bicycle anim + ANIM_ID_BIKE_BUNNYHOP = 206, // bicycle anim + ANIM_ID_BIKE_PEDAL = 207, // bicycle anim + ANIM_ID_BIKE_SPRINT = 208, // bicycle anim ANIM_ID_FIGHT_1 = 214, ANIM_ID_FIGHT_2 = 215, ANIM_ID_FIGHT_3 = 216, diff --git a/Client/sdk/game/CAnimManager.h b/Client/sdk/game/CAnimManager.h index 31e4c88e00e..2b1a9c1a944 100644 --- a/Client/sdk/game/CAnimManager.h +++ b/Client/sdk/game/CAnimManager.h @@ -15,7 +15,7 @@ // Get correct values #define MAX_ANIM_GROUPS 200 -#define MAX_ANIMATIONS 500 +#define MAX_ANIMATIONS 500 #define MAX_ANIM_BLOCKS 200 typedef unsigned long AssocGroupId; @@ -128,7 +128,7 @@ class CAnimManager virtual void DeleteCustomAnimHierarchyInterface(CAnimBlendHierarchySAInterface* pInterface) = 0; virtual void DeleteCustomAnimSequenceInterface(CAnimBlendSequenceSAInterface* pInterface) = 0; - virtual bool isGateWayAnimationHierarchy(CAnimBlendHierarchySAInterface* pInterface) = 0; + virtual bool isGateWayAnimationHierarchy(CAnimBlendHierarchySAInterface* pInterface) = 0; virtual const char* GetGateWayBlockName() const = 0; virtual const char* GetGateWayAnimationName() const = 0; diff --git a/Client/sdk/game/CAudioEngine.h b/Client/sdk/game/CAudioEngine.h index 7e34c646fc8..e91bea204b1 100644 --- a/Client/sdk/game/CAudioEngine.h +++ b/Client/sdk/game/CAudioEngine.h @@ -54,7 +54,7 @@ class CAudioEngine public: virtual void PlayFrontEndSound(DWORD dwSound) = 0; virtual void PlayBeatTrack(short iTrack) = 0; - virtual void SetEffectsMasterVolume(BYTE bVolume) = 0; // 64 = max volume + virtual void SetEffectsMasterVolume(BYTE bVolume) = 0; // 64 = max volume virtual void SetMusicMasterVolume(BYTE bVolume) = 0; virtual void ClearMissionAudio(int slot = 1) = 0; virtual void PreloadMissionAudio(unsigned short usAudioEvent, int slot = 1) = 0; diff --git a/Client/sdk/game/CAutomobile.h b/Client/sdk/game/CAutomobile.h index eeef7a92911..365c98ee51e 100644 --- a/Client/sdk/game/CAutomobile.h +++ b/Client/sdk/game/CAutomobile.h @@ -20,5 +20,5 @@ class CDoor; class CAutomobile : public virtual CVehicle { public: - virtual ~CAutomobile(){}; + virtual ~CAutomobile() {}; }; diff --git a/Client/sdk/game/CBike.h b/Client/sdk/game/CBike.h index 5750fa55031..122f14f02d4 100644 --- a/Client/sdk/game/CBike.h +++ b/Client/sdk/game/CBike.h @@ -18,7 +18,7 @@ class CBikeHandlingEntry; class CBike : public virtual CVehicle { public: - virtual ~CBike(){}; + virtual ~CBike() {}; virtual CBikeHandlingEntry* GetBikeHandlingData() = 0; virtual void SetBikeHandlingData(CBikeHandlingEntry* pHandling) = 0; diff --git a/Client/sdk/game/CBikeHandlingEntry.h b/Client/sdk/game/CBikeHandlingEntry.h index 543e718ef22..4d1ff2dfa9f 100644 --- a/Client/sdk/game/CBikeHandlingEntry.h +++ b/Client/sdk/game/CBikeHandlingEntry.h @@ -15,7 +15,7 @@ class CBikeHandlingEntry { public: // Destructor - virtual ~CBikeHandlingEntry(){}; + virtual ~CBikeHandlingEntry() {}; // Use this to copy data from an another handling class to this virtual void Assign(const CBikeHandlingEntry* pData) = 0; diff --git a/Client/sdk/game/CBmx.h b/Client/sdk/game/CBmx.h index 5f649c3dc21..04d6ed892c0 100644 --- a/Client/sdk/game/CBmx.h +++ b/Client/sdk/game/CBmx.h @@ -16,5 +16,5 @@ class CBmx : public virtual CBike { public: - virtual ~CBmx(){}; + virtual ~CBmx() {}; }; diff --git a/Client/sdk/game/CBoat.h b/Client/sdk/game/CBoat.h index 2275be6404a..826658dcde9 100644 --- a/Client/sdk/game/CBoat.h +++ b/Client/sdk/game/CBoat.h @@ -18,7 +18,7 @@ class CBoatHandlingEntry; class CBoat : public virtual CVehicle { public: - virtual ~CBoat(){}; + virtual ~CBoat() {}; virtual CBoatHandlingEntry* GetBoatHandlingData() = 0; virtual void SetBoatHandlingData(CBoatHandlingEntry* pHandling) = 0; diff --git a/Client/sdk/game/CBoatHandlingEntry.h b/Client/sdk/game/CBoatHandlingEntry.h index b7583d595ff..8f0fce87aec 100644 --- a/Client/sdk/game/CBoatHandlingEntry.h +++ b/Client/sdk/game/CBoatHandlingEntry.h @@ -15,7 +15,7 @@ class CBoatHandlingEntry { public: // Destructor - virtual ~CBoatHandlingEntry(){}; + virtual ~CBoatHandlingEntry() {}; // Use this to copy data from an another handling class to this virtual void Assign(const CBoatHandlingEntry* pData) = 0; diff --git a/Client/sdk/game/CBuilding.h b/Client/sdk/game/CBuilding.h index 8969df3daab..a7e2627eb3e 100644 --- a/Client/sdk/game/CBuilding.h +++ b/Client/sdk/game/CBuilding.h @@ -18,7 +18,7 @@ class CBuildingSAInterface; class CBuilding : public virtual CEntity { public: - virtual ~CBuilding(){}; + virtual ~CBuilding() {}; virtual CBuildingSAInterface* GetBuildingInterface() = 0; virtual void SetLod(CBuilding* pLod) = 0; diff --git a/Client/sdk/game/CBuildingRemoval.h b/Client/sdk/game/CBuildingRemoval.h index 655996f99b3..35577132c7f 100644 --- a/Client/sdk/game/CBuildingRemoval.h +++ b/Client/sdk/game/CBuildingRemoval.h @@ -120,5 +120,4 @@ class CBuildingRemoval virtual bool IsObjectRemoved(CEntitySAInterface* pInterface) = 0; virtual bool IsDataModelRemoved(uint16_t usModelID) = 0; virtual bool IsEntityRemoved(CEntitySAInterface* pInterface) = 0; - }; diff --git a/Client/sdk/game/CBuildingsPool.h b/Client/sdk/game/CBuildingsPool.h index 85ad4b87391..ea5a99f2690 100644 --- a/Client/sdk/game/CBuildingsPool.h +++ b/Client/sdk/game/CBuildingsPool.h @@ -20,7 +20,6 @@ class CBuildingSA; class CBuildingsPool { public: - // Buildings pool virtual CBuilding* AddBuilding(class CClientBuilding*, std::uint16_t modelId, CVector* vPos, CVector* vRot, std::uint8_t interior) = 0; virtual void RemoveBuilding(CBuilding* pObject) = 0; diff --git a/Client/sdk/game/CCamera.h b/Client/sdk/game/CCamera.h index 7ef8d39a169..b0f6eef1863 100644 --- a/Client/sdk/game/CCamera.h +++ b/Client/sdk/game/CCamera.h @@ -23,72 +23,72 @@ constexpr const float DEFAULT_FOV = 70.0f; enum eCamMode { MODE_NONE = 0, - MODE_TOPDOWN, //=1, - MODE_GTACLASSIC, // =2, - MODE_BEHINDCAR, //=3, - MODE_FOLLOWPED, //=4, - MODE_AIMING, //=5, - MODE_DEBUG, //=6, - MODE_SNIPER, //=7, - MODE_ROCKETLAUNCHER, //=8, - MODE_MODELVIEW, //=9, - MODE_BILL, //=10, - MODE_SYPHON, //=11, - MODE_CIRCLE, //=12, - MODE_CHEESYZOOM, //=13, - MODE_WHEELCAM, //=14, - MODE_FIXED, //=15, - MODE_1STPERSON, //=16, - MODE_FLYBY, //=17, - MODE_CAM_ON_A_STRING, //=18, - MODE_REACTION, //=19, - MODE_FOLLOW_PED_WITH_BIND, //=20, - MODE_CHRIS, // 21 - MODE_BEHINDBOAT, //=22, - MODE_PLAYER_FALLEN_WATER, //=23, - MODE_CAM_ON_TRAIN_ROOF, //=24, - MODE_CAM_RUNNING_SIDE_TRAIN, //=25, - MODE_BLOOD_ON_THE_TRACKS, //=26, - MODE_IM_THE_PASSENGER_WOOWOO, //=27, - MODE_SYPHON_CRIM_IN_FRONT, // =28, - MODE_PED_DEAD_BABY, //=29, - MODE_PILLOWS_PAPS, //=30, - MODE_LOOK_AT_CARS, //=31, - MODE_ARRESTCAM_ONE, //=32, - MODE_ARRESTCAM_TWO, //=33, - MODE_M16_1STPERSON, //=34, - MODE_SPECIAL_FIXED_FOR_SYPHON, //=35, - MODE_FIGHT_CAM, //=36, - MODE_TOP_DOWN_PED, //=37, - MODE_LIGHTHOUSE, //=38 + MODE_TOPDOWN, //=1, + MODE_GTACLASSIC, // =2, + MODE_BEHINDCAR, //=3, + MODE_FOLLOWPED, //=4, + MODE_AIMING, //=5, + MODE_DEBUG, //=6, + MODE_SNIPER, //=7, + MODE_ROCKETLAUNCHER, //=8, + MODE_MODELVIEW, //=9, + MODE_BILL, //=10, + MODE_SYPHON, //=11, + MODE_CIRCLE, //=12, + MODE_CHEESYZOOM, //=13, + MODE_WHEELCAM, //=14, + MODE_FIXED, //=15, + MODE_1STPERSON, //=16, + MODE_FLYBY, //=17, + MODE_CAM_ON_A_STRING, //=18, + MODE_REACTION, //=19, + MODE_FOLLOW_PED_WITH_BIND, //=20, + MODE_CHRIS, // 21 + MODE_BEHINDBOAT, //=22, + MODE_PLAYER_FALLEN_WATER, //=23, + MODE_CAM_ON_TRAIN_ROOF, //=24, + MODE_CAM_RUNNING_SIDE_TRAIN, //=25, + MODE_BLOOD_ON_THE_TRACKS, //=26, + MODE_IM_THE_PASSENGER_WOOWOO, //=27, + MODE_SYPHON_CRIM_IN_FRONT, // =28, + MODE_PED_DEAD_BABY, //=29, + MODE_PILLOWS_PAPS, //=30, + MODE_LOOK_AT_CARS, //=31, + MODE_ARRESTCAM_ONE, //=32, + MODE_ARRESTCAM_TWO, //=33, + MODE_M16_1STPERSON, //=34, + MODE_SPECIAL_FIXED_FOR_SYPHON, //=35, + MODE_FIGHT_CAM, //=36, + MODE_TOP_DOWN_PED, //=37, + MODE_LIGHTHOUSE, //=38 /// all 1rst person run ablout run about modes now - MODE_SNIPER_RUNABOUT, //=39, - MODE_ROCKETLAUNCHER_RUNABOUT, //=40, - MODE_1STPERSON_RUNABOUT, //=41, - MODE_M16_1STPERSON_RUNABOUT, //=42, - MODE_FIGHT_CAM_RUNABOUT, //=43, - MODE_EDITOR, //=44, - MODE_HELICANNON_1STPERSON, //= 45 - MODE_CAMERA, // 46 - MODE_ATTACHCAM, // 47 + MODE_SNIPER_RUNABOUT, //=39, + MODE_ROCKETLAUNCHER_RUNABOUT, //=40, + MODE_1STPERSON_RUNABOUT, //=41, + MODE_M16_1STPERSON_RUNABOUT, //=42, + MODE_FIGHT_CAM_RUNABOUT, //=43, + MODE_EDITOR, //=44, + MODE_HELICANNON_1STPERSON, //= 45 + MODE_CAMERA, // 46 + MODE_ATTACHCAM, // 47 MODE_TWOPLAYER, MODE_TWOPLAYER_IN_CAR_AND_SHOOTING, - MODE_TWOPLAYER_SEPARATE_CARS, // 50 + MODE_TWOPLAYER_SEPARATE_CARS, // 50 MODE_ROCKETLAUNCHER_HS, MODE_ROCKETLAUNCHER_RUNABOUT_HS, MODE_AIMWEAPON, MODE_TWOPLAYER_SEPARATE_CARS_TOPDOWN, - MODE_AIMWEAPON_FROMCAR, // 55 + MODE_AIMWEAPON_FROMCAR, // 55 MODE_DW_HELI_CHASE, MODE_DW_CAM_MAN, MODE_DW_BIRDY, MODE_DW_PLANE_SPOTTER, - MODE_DW_DOG_FIGHT, // 60 + MODE_DW_DOG_FIGHT, // 60 MODE_DW_FISH, MODE_DW_PLANECAM1, MODE_DW_PLANECAM2, MODE_DW_PLANECAM3, - MODE_AIMWEAPON_ATTACHED // 65 + MODE_AIMWEAPON_ATTACHED // 65 }; enum class eVehicleCamMode diff --git a/Client/sdk/game/CCheckpoint.h b/Client/sdk/game/CCheckpoint.h index b5a7f8de777..c298c30f181 100644 --- a/Client/sdk/game/CCheckpoint.h +++ b/Client/sdk/game/CCheckpoint.h @@ -21,9 +21,9 @@ class CVector; enum { - CHECKPOINT_TUBE, // a long tube with arrow as direction - CHECKPOINT_ENDTUBE, // finish flag long tube checkpoint - CHECKPOINT_EMPTYTUBE, // just a long tube checkpoint + CHECKPOINT_TUBE, // a long tube with arrow as direction + CHECKPOINT_ENDTUBE, // finish flag long tube checkpoint + CHECKPOINT_EMPTYTUBE, // just a long tube checkpoint CHECKPOINT_TORUS, CHECKPOINT_TORUS_NOFADE, CHECKPOINT_TORUSROT, @@ -40,7 +40,7 @@ class CCheckpoint virtual CVector* GetPosition() = 0; virtual void SetPointDirection(CVector* vecPointDirection) = 0; virtual CVector* GetPointDirection() = 0; - virtual DWORD GetType() = 0; // need enum? + virtual DWORD GetType() = 0; // need enum? virtual bool IsActive() = 0; virtual DWORD GetIdentifier() = 0; virtual SharedUtil::SColor GetColor() = 0; diff --git a/Client/sdk/game/CColPoint.h b/Client/sdk/game/CColPoint.h index 26cac7c4da4..c4e1337e7bf 100644 --- a/Client/sdk/game/CColPoint.h +++ b/Client/sdk/game/CColPoint.h @@ -214,15 +214,15 @@ C_ASSERT(sizeof(EColSurface) == 1); // Collision stored lighting struct CColLighting { - uchar day : 4; // 0-15 - uchar night : 4; // 0-15 + uchar day : 4; // 0-15 + uchar night : 4; // 0-15 }; C_ASSERT(sizeof(CColLighting) == 1); class CColPoint { public: - virtual ~CColPoint(){}; + virtual ~CColPoint() {}; virtual CColPointSAInterface* GetInterface() = 0; virtual const CVector& GetPosition() = 0; diff --git a/Client/sdk/game/CCollision.h b/Client/sdk/game/CCollision.h index e286c4c82f1..544392566a3 100644 --- a/Client/sdk/game/CCollision.h +++ b/Client/sdk/game/CCollision.h @@ -14,7 +14,8 @@ struct CColLineSA; struct CColSphereSA; -class CCollision { +class CCollision +{ public: virtual bool TestLineSphere(const CColLineSA& line, const CColSphereSA& sphere) const = 0; }; diff --git a/Client/sdk/game/CControllerConfigManager.h b/Client/sdk/game/CControllerConfigManager.h index e0a48fb5d19..91b280f3b23 100644 --- a/Client/sdk/game/CControllerConfigManager.h +++ b/Client/sdk/game/CControllerConfigManager.h @@ -22,9 +22,9 @@ #define GTA_KEY_MXB2 7 #define GTA_KEY_SPACE 32 #define GTA_KEY_COMMA 44 -#define GTA_KEY_MINUS 45 /* - on main keyboard */ -#define GTA_KEY_PERIOD 46 /* . on main keyboard */ -#define GTA_KEY_SLASH 47 /* / on main keyboard */ +#define GTA_KEY_MINUS 45 /* - on main keyboard */ +#define GTA_KEY_PERIOD 46 /* . on main keyboard */ +#define GTA_KEY_SLASH 47 /* / on main keyboard */ #define GTA_KEY_0 48 #define GTA_KEY_1 49 #define GTA_KEY_2 50 @@ -68,7 +68,7 @@ #define GTA_KEY_LBRACKET 91 #define GTA_KEY_BACKSLASH 92 #define GTA_KEY_RBRACKET 93 -#define GTA_KEY_GRAVE 96 /* accent grave */ +#define GTA_KEY_GRAVE 96 /* accent grave */ #define GTA_KEY_F1 1001 #define GTA_KEY_F2 1002 #define GTA_KEY_F3 1003 @@ -81,21 +81,21 @@ #define GTA_KEY_F10 1010 #define GTA_KEY_F11 1011 #define GTA_KEY_F12 1012 -#define GTA_KEY_INSERT 1013 /* Insert on arrow keypad */ -#define GTA_KEY_DELETE 1014 /* Delete on arrow keypad */ -#define GTA_KEY_HOME 1015 /* Home on arrow keypad */ -#define GTA_KEY_END 1016 /* End on arrow keypad */ -#define GTA_KEY_PGUP 1017 /* PgUp on arrow keypad */ -#define GTA_KEY_PGDN 1018 /* PgDn on arrow keypad */ -#define GTA_KEY_UP 1019 /* UpArrow on arrow keypad */ -#define GTA_KEY_DOWN 1020 /* DownArrow on arrow keypad */ -#define GTA_KEY_LEFT 1021 /* LeftArrow on arrow keypad */ -#define GTA_KEY_RIGHT 1022 /* RightArrow on arrow keypad */ -#define GTA_KEY_DIVIDE 1023 /* / on numeric keypad */ -#define GTA_KEY_MULTIPLY 1024 /* * on numeric keypad */ -#define GTA_KEY_ADD 1025 /* + on numeric keypad */ -#define GTA_KEY_SUBTRACT 1026 /* - on numeric keypad */ -#define GTA_KEY_DECIMAL 1027 /* . on numeric keypad */ +#define GTA_KEY_INSERT 1013 /* Insert on arrow keypad */ +#define GTA_KEY_DELETE 1014 /* Delete on arrow keypad */ +#define GTA_KEY_HOME 1015 /* Home on arrow keypad */ +#define GTA_KEY_END 1016 /* End on arrow keypad */ +#define GTA_KEY_PGUP 1017 /* PgUp on arrow keypad */ +#define GTA_KEY_PGDN 1018 /* PgDn on arrow keypad */ +#define GTA_KEY_UP 1019 /* UpArrow on arrow keypad */ +#define GTA_KEY_DOWN 1020 /* DownArrow on arrow keypad */ +#define GTA_KEY_LEFT 1021 /* LeftArrow on arrow keypad */ +#define GTA_KEY_RIGHT 1022 /* RightArrow on arrow keypad */ +#define GTA_KEY_DIVIDE 1023 /* / on numeric keypad */ +#define GTA_KEY_MULTIPLY 1024 /* * on numeric keypad */ +#define GTA_KEY_ADD 1025 /* + on numeric keypad */ +#define GTA_KEY_SUBTRACT 1026 /* - on numeric keypad */ +#define GTA_KEY_DECIMAL 1027 /* . on numeric keypad */ #define GTA_KEY_NUMPAD1 1028 #define GTA_KEY_NUMPAD2 1029 #define GTA_KEY_NUMPAD3 1030 @@ -107,21 +107,21 @@ #define GTA_KEY_NUMPAD8 1036 #define GTA_KEY_NUMPAD9 1037 #define GTA_KEY_NUMPAD0 1038 -#define GTA_KEY_NUMPADENTER 1039 /* Enter on numeric keypad */ -#define GTA_KEY_SCROLL 1040 /* Scroll Lock */ -#define GTA_KEY_PAUSE 1041 /* Pause */ -#define GTA_KEY_BACK 1042 /* backspace */ +#define GTA_KEY_NUMPADENTER 1039 /* Enter on numeric keypad */ +#define GTA_KEY_SCROLL 1040 /* Scroll Lock */ +#define GTA_KEY_PAUSE 1041 /* Pause */ +#define GTA_KEY_BACK 1042 /* backspace */ #define GTA_KEY_TAB 1043 -#define GTA_KEY_CAPSLOCK 1044 /* Caps Lock */ -#define GTA_KEY_RETURN 1045 /* Enter on main keyboard */ +#define GTA_KEY_CAPSLOCK 1044 /* Caps Lock */ +#define GTA_KEY_RETURN 1045 /* Enter on main keyboard */ #define GTA_KEY_LSHIFT 1046 #define GTA_KEY_RSHIFT 1047 #define GTA_KEY_LCONTROL 1049 #define GTA_KEY_RCONTROL 1050 -#define GTA_KEY_LMENU 1051 /* left Alt */ -#define GTA_KEY_RMENU 1052 /* right Alt */ -#define GTA_KEY_LWIN 1053 /* Left Windows key */ -#define GTA_KEY_RWIN 1054 /* Right Windows key */ +#define GTA_KEY_LMENU 1051 /* left Alt */ +#define GTA_KEY_RMENU 1052 /* right Alt */ +#define GTA_KEY_LWIN 1053 /* Left Windows key */ +#define GTA_KEY_RWIN 1054 /* Right Windows key */ #define NO_KEY_DEFINED 1056 /* diff --git a/Client/sdk/game/CCoronas.h b/Client/sdk/game/CCoronas.h index f87ef55bf6f..6a184176bcd 100644 --- a/Client/sdk/game/CCoronas.h +++ b/Client/sdk/game/CCoronas.h @@ -16,8 +16,8 @@ class CRegisteredCorona; class CVector; // these are the IDs that are used internally for coronas -#define CORONA_SUN 1 -#define CORONA_MOON 2 +#define CORONA_SUN 1 +#define CORONA_MOON 2 class CCoronas { diff --git a/Client/sdk/game/CDamageManager.h b/Client/sdk/game/CDamageManager.h index 326ebaeba6e..46442eda878 100644 --- a/Client/sdk/game/CDamageManager.h +++ b/Client/sdk/game/CDamageManager.h @@ -12,12 +12,12 @@ #pragma once // Not sure if R* used these -#define DT_ENGINE_OK (0) -#define DT_ENGINE_RADIATOR_BURST (100) -#define DT_ENGINE_ENGINE_OVERHEAT (150) -#define DT_ENGINE_ENGINE_PIPES_BURST (200) -#define DT_ENGINE_ON_FIRE (225) -#define DT_ENGINE_FUCKED (250) +#define DT_ENGINE_OK (0) +#define DT_ENGINE_RADIATOR_BURST (100) +#define DT_ENGINE_ENGINE_OVERHEAT (150) +#define DT_ENGINE_ENGINE_PIPES_BURST (200) +#define DT_ENGINE_ON_FIRE (225) +#define DT_ENGINE_FUCKED (250) /* const unsigned char DT_ENG_INOPERABLE = 0x01; @@ -97,11 +97,11 @@ enum ePanels FRONT_RIGHT_PANEL, REAR_LEFT_PANEL, REAR_RIGHT_PANEL, - WINDSCREEN_PANEL, // needs to be in same order as in component.h + WINDSCREEN_PANEL, // needs to be in same order as in component.h FRONT_BUMPER, REAR_BUMPER, - MAX_PANELS // MUST BE 8 OR LESS + MAX_PANELS // MUST BE 8 OR LESS }; enum eLights @@ -118,7 +118,7 @@ enum eLights REAR_LEFT_INDICATOR, REAR_RIGHT_INDICATOR,*/ - MAX_LIGHTS // MUST BE 16 OR LESS + MAX_LIGHTS // MUST BE 16 OR LESS }; enum class eCarNodes @@ -182,7 +182,7 @@ class CDamageManager virtual void SetLightStatus(BYTE bLight, BYTE bLightStatus) = 0; virtual void SetLightStatus(unsigned char ucStatus) = 0; virtual BYTE GetAeroplaneCompStatus(BYTE CompID) = 0; - virtual void SetAeroplaneCompStatus(BYTE CompID, BYTE Status) = 0; // component ids begin at 12 - probably + virtual void SetAeroplaneCompStatus(BYTE CompID, BYTE Status) = 0; // component ids begin at 12 - probably virtual void FuckCarCompletely(bool bKeepWheels) = 0; }; diff --git a/Client/sdk/game/CDoor.h b/Client/sdk/game/CDoor.h index 56e7b29dbcf..2da58f89a31 100644 --- a/Client/sdk/game/CDoor.h +++ b/Client/sdk/game/CDoor.h @@ -15,9 +15,9 @@ class CDoor { public: - virtual float GetAngleOpenRatio() = 0; - virtual bool IsClosed() = 0; - virtual bool IsFullyOpen() = 0; - virtual void Open(float fRatio) = 0; + virtual float GetAngleOpenRatio() = 0; + virtual bool IsClosed() = 0; + virtual bool IsFullyOpen() = 0; + virtual void Open(float fRatio) = 0; virtual DoorState GetDoorState() = 0; }; diff --git a/Client/sdk/game/CEntity.h b/Client/sdk/game/CEntity.h index 264c5bb14d5..8f370fc6a76 100644 --- a/Client/sdk/game/CEntity.h +++ b/Client/sdk/game/CEntity.h @@ -46,14 +46,14 @@ enum eEntityStatus STATUS_PLANE, STATUS_REMOTE_CONTROLLED, STATUS_PLAYER_DISABLED, - STATUS_TRAILER, // ToDo: Check this. I can't reproduce that this is set for trailers - STATUS_SIMPLE_TRAILER // Same here + STATUS_TRAILER, // ToDo: Check this. I can't reproduce that this is set for trailers + STATUS_SIMPLE_TRAILER // Same here }; class CEntity { public: - virtual ~CEntity(){}; + virtual ~CEntity() {}; // virtual VOID SetModelAlpha ( int iAlpha )=0; virtual class CEntitySAInterface* GetInterface() = 0; diff --git a/Client/sdk/game/CFlyingHandlingEntry.h b/Client/sdk/game/CFlyingHandlingEntry.h index e329e19a747..dbd73fbc3e8 100644 --- a/Client/sdk/game/CFlyingHandlingEntry.h +++ b/Client/sdk/game/CFlyingHandlingEntry.h @@ -15,7 +15,7 @@ class CFlyingHandlingEntry { public: // Destructor - virtual ~CFlyingHandlingEntry(){}; + virtual ~CFlyingHandlingEntry() {}; // Use this to copy data from an another handling class to this virtual void Assign(const CFlyingHandlingEntry* pData) = 0; diff --git a/Client/sdk/game/CFx.h b/Client/sdk/game/CFx.h index d575f28b835..f71bfdf1ae1 100644 --- a/Client/sdk/game/CFx.h +++ b/Client/sdk/game/CFx.h @@ -35,5 +35,6 @@ class CFx virtual void TriggerWaterSplash(CVector& vecPosition) = 0; virtual void TriggerBulletSplash(CVector& vecPosition) = 0; virtual void TriggerFootSplash(CVector& vecPosition) = 0; - virtual void AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife) = 0; + virtual void AddParticle(FxParticleSystems eFxParticle, const CVector& vecPosition, const CVector& vecDirection, float fR, float fG, float fB, float fA, + bool bRandomizeColors, std::uint32_t iCount, float fBrightness, float fSize, bool bRandomizeSizes, float fLife) = 0; }; diff --git a/Client/sdk/game/CGame.h b/Client/sdk/game/CGame.h index fbaba31d4b8..974ff8e94eb 100644 --- a/Client/sdk/game/CGame.h +++ b/Client/sdk/game/CGame.h @@ -161,18 +161,18 @@ class __declspec(novtable) CGame virtual CWeaponInfo* GetWeaponInfo(eWeaponType weapon, eWeaponSkill skill = WEAPONSKILL_STD) = 0; virtual CModelInfo* GetModelInfo(DWORD dwModelID, bool bCanBeInvalid = false) = 0; - virtual DWORD GetSystemTime() = 0; - virtual int GetSystemFrameCounter() const = 0; - virtual bool IsAtMenu() = 0; - virtual void StartGame() = 0; - virtual void SetSystemState(SystemState State) = 0; - virtual SystemState GetSystemState() = 0; - virtual void Pause(bool bPaused) = 0; - virtual void SetTimeScale(float fTimeScale) = 0; - virtual float GetFPS() = 0; - virtual float GetTimeStep() = 0; - virtual float GetOldTimeStep() = 0; - virtual float GetTimeScale() = 0; + virtual DWORD GetSystemTime() = 0; + virtual int GetSystemFrameCounter() const = 0; + virtual bool IsAtMenu() = 0; + virtual void StartGame() = 0; + virtual void SetSystemState(SystemState State) = 0; + virtual SystemState GetSystemState() = 0; + virtual void Pause(bool bPaused) = 0; + virtual void SetTimeScale(float fTimeScale) = 0; + virtual float GetFPS() = 0; + virtual float GetTimeStep() = 0; + virtual float GetOldTimeStep() = 0; + virtual float GetTimeScale() = 0; virtual void Initialize() = 0; virtual void Reset() = 0; @@ -291,5 +291,4 @@ class __declspec(novtable) CGame virtual void RestoreGameWorld() = 0; virtual bool SetBuildingPoolSize(size_t size) = 0; - }; diff --git a/Client/sdk/game/CHandlingEntry.h b/Client/sdk/game/CHandlingEntry.h index f40eeb433aa..4e3667642a1 100644 --- a/Client/sdk/game/CHandlingEntry.h +++ b/Client/sdk/game/CHandlingEntry.h @@ -16,52 +16,52 @@ class CVector; // ### MODELFLAGS ### // 1st digit -#define MODELFLAGS_IS_VAN 0x00000001 -#define MODELFLAGS_IS_BUS 0x00000002 -#define MODELFLAGS_IS_LOW 0x00000004 -#define MODELFLAGS_IS_BIG 0x00000008 +#define MODELFLAGS_IS_VAN 0x00000001 +#define MODELFLAGS_IS_BUS 0x00000002 +#define MODELFLAGS_IS_LOW 0x00000004 +#define MODELFLAGS_IS_BIG 0x00000008 // 2nd digit -#define MODELFLAGS_REVERSE_BONNET 0x00000010 -#define MODELFLAGS_HANGING_BOOT 0x00000020 -#define MODELFLAGS_TAILGATE_BOOT 0x00000040 -#define MODELFLAGS_NOSWING_BOOT 0x00000080 +#define MODELFLAGS_REVERSE_BONNET 0x00000010 +#define MODELFLAGS_HANGING_BOOT 0x00000020 +#define MODELFLAGS_TAILGATE_BOOT 0x00000040 +#define MODELFLAGS_NOSWING_BOOT 0x00000080 // 3rd digit -#define MODELFLAGS_NO_DOORS 0x00000100 -#define MODELFLAGS_TANDEM_SEATS 0x00000200 -#define MODELFLAGS_SIT_IN_BOAT 0x00000400 -#define MODELFLAGS_CONVERTIBLE 0x00000800 +#define MODELFLAGS_NO_DOORS 0x00000100 +#define MODELFLAGS_TANDEM_SEATS 0x00000200 +#define MODELFLAGS_SIT_IN_BOAT 0x00000400 +#define MODELFLAGS_CONVERTIBLE 0x00000800 // 4th digit -#define MODELFLAGS_NO_EXHAUST 0x00001000 -#define MODELFLAGS_DOUBLE_EXHAUST 0x00002000 -#define MODELFLAGS_NO1FPS_LOOK_BEHIND 0x00004000 -#define MODELFLAGS_FORCE_DOOR_CHECK 0x00008000 +#define MODELFLAGS_NO_EXHAUST 0x00001000 +#define MODELFLAGS_DOUBLE_EXHAUST 0x00002000 +#define MODELFLAGS_NO1FPS_LOOK_BEHIND 0x00004000 +#define MODELFLAGS_FORCE_DOOR_CHECK 0x00008000 // 5th digit -#define MODELFLAGS_AXLE_F_NOTILT 0x00010000 -#define MODELFLAGS_AXLE_F_SOLID 0x00020000 -#define MODELFLAGS_AXLE_F_MCPHERSON 0x00040000 -#define MODELFLAGS_AXLE_F_REVERSE 0x00080000 +#define MODELFLAGS_AXLE_F_NOTILT 0x00010000 +#define MODELFLAGS_AXLE_F_SOLID 0x00020000 +#define MODELFLAGS_AXLE_F_MCPHERSON 0x00040000 +#define MODELFLAGS_AXLE_F_REVERSE 0x00080000 // 6th digit -#define MODELFLAGS_AXLE_R_NOTILT 0x00100000 -#define MODELFLAGS_AXLE_R_SOLID 0x00200000 -#define MODELFLAGS_AXLE_R_MCPHERSON 0x00400000 -#define MODELFLAGS_AXLE_R_REVERSE 0x00800000 +#define MODELFLAGS_AXLE_R_NOTILT 0x00100000 +#define MODELFLAGS_AXLE_R_SOLID 0x00200000 +#define MODELFLAGS_AXLE_R_MCPHERSON 0x00400000 +#define MODELFLAGS_AXLE_R_REVERSE 0x00800000 // 7th digit -#define MODELFLAGS_IS_BIKE 0x01000000 -#define MODELFLAGS_IS_HELI 0x02000000 -#define MODELFLAGS_IS_PLANE 0x04000000 -#define MODELFLAGS_IS_BOAT 0x08000000 +#define MODELFLAGS_IS_BIKE 0x01000000 +#define MODELFLAGS_IS_HELI 0x02000000 +#define MODELFLAGS_IS_PLANE 0x04000000 +#define MODELFLAGS_IS_BOAT 0x08000000 // 8th digit -#define MODELFLAGS_BOUNCE_PANELS 0x10000000 -#define MODELFLAGS_DOUBLE_RWHEELS 0x20000000 -#define MODELFLAGS_FORCE_GROUND_CLEARANCE 0x40000000 -#define MODELFLAGS_IS_HATCHBACK 0x80000000 +#define MODELFLAGS_BOUNCE_PANELS 0x10000000 +#define MODELFLAGS_DOUBLE_RWHEELS 0x20000000 +#define MODELFLAGS_FORCE_GROUND_CLEARANCE 0x40000000 +#define MODELFLAGS_IS_HATCHBACK 0x80000000 class CHandlingEntry { @@ -89,7 +89,7 @@ class CHandlingEntry }; // Destructor - virtual ~CHandlingEntry(){}; + virtual ~CHandlingEntry() {}; // Use this to copy data from an another handling class to this virtual void Assign(const CHandlingEntry* pEntry) noexcept = 0; diff --git a/Client/sdk/game/CHeli.h b/Client/sdk/game/CHeli.h index 89f8b5c73b8..cac8e2dca33 100644 --- a/Client/sdk/game/CHeli.h +++ b/Client/sdk/game/CHeli.h @@ -15,5 +15,5 @@ class CHeli : public virtual CAutomobile { public: - virtual ~CHeli(){}; + virtual ~CHeli() {}; }; diff --git a/Client/sdk/game/CHud.h b/Client/sdk/game/CHud.h index a4dca3f1f4e..da95656daf9 100644 --- a/Client/sdk/game/CHud.h +++ b/Client/sdk/game/CHud.h @@ -113,16 +113,16 @@ class CHud virtual void ResetComponentFontAlignment(const eHudComponent& component) noexcept = 0; virtual void ResetComponentFontProportional(const eHudComponent& component) noexcept = 0; - virtual CVector2D GetComponentPosition(const eHudComponent& component) const noexcept = 0; - virtual CVector2D GetComponentSize(const eHudComponent& component) const noexcept = 0; + virtual CVector2D GetComponentPosition(const eHudComponent& component) const noexcept = 0; + virtual CVector2D GetComponentSize(const eHudComponent& component) const noexcept = 0; - virtual SColor GetComponentColor(const eHudComponent& component) const noexcept = 0; - virtual SColor GetComponentSecondaryColor(const eHudComponent& component) const noexcept = 0; - virtual SColor GetComponentFontDropColor(const eHudComponent& component) const = 0; + virtual SColor GetComponentColor(const eHudComponent& component) const noexcept = 0; + virtual SColor GetComponentSecondaryColor(const eHudComponent& component) const noexcept = 0; + virtual SColor GetComponentFontDropColor(const eHudComponent& component) const = 0; - virtual bool GetComponentDrawBlackBorder(const eHudComponent& component) const noexcept = 0; - virtual bool GetComponentDrawPercentage(const eHudComponent& component) const noexcept = 0; - virtual float GetHealthBarBlinkingValue(const eHudComponent& component) const noexcept = 0; + virtual bool GetComponentDrawBlackBorder(const eHudComponent& component) const noexcept = 0; + virtual bool GetComponentDrawPercentage(const eHudComponent& component) const noexcept = 0; + virtual float GetHealthBarBlinkingValue(const eHudComponent& component) const noexcept = 0; virtual float GetComponentFontOutline(const eHudComponent& component) const = 0; virtual float GetComponentFontShadow(const eHudComponent& component) const = 0; @@ -130,7 +130,7 @@ class CHud virtual eFontAlignment GetComponentFontAlignment(const eHudComponent& component) const = 0; virtual bool GetComponentFontProportional(const eHudComponent& component) const = 0; - virtual bool GetComponentUseCustomAlpha(const eHudComponent& component) const noexcept = 0; + virtual bool GetComponentUseCustomAlpha(const eHudComponent& component) const noexcept = 0; - virtual CVector2D GetComponentTextSize(const eHudComponent& component) const = 0; + virtual CVector2D GetComponentTextSize(const eHudComponent& component) const = 0; }; diff --git a/Client/sdk/game/CMarker.h b/Client/sdk/game/CMarker.h index 7ab48725655..f968d3a9a8d 100644 --- a/Client/sdk/game/CMarker.h +++ b/Client/sdk/game/CMarker.h @@ -22,8 +22,8 @@ class CPed; class CVector; class CVehicle; -#define MARKER_SCALE_SMALL 1 -#define MARKER_SCALE_NORMAL 2 +#define MARKER_SCALE_SMALL 1 +#define MARKER_SCALE_NORMAL 2 class CMarker { diff --git a/Client/sdk/game/CModelInfo.h b/Client/sdk/game/CModelInfo.h index 7e5cc8ec65e..592776ea51f 100644 --- a/Client/sdk/game/CModelInfo.h +++ b/Client/sdk/game/CModelInfo.h @@ -40,7 +40,7 @@ enum class eModelIdeFlag IS_ROAD, DRAW_LAST, ADDITIVE, - IGNORE_LIGHTING, // Used with animated objects + IGNORE_LIGHTING, // Used with animated objects NO_ZBUFFER_WRITE, DONT_RECEIVE_SHADOWS, IS_GLASS_TYPE_1, diff --git a/Client/sdk/game/CMonsterTruck.h b/Client/sdk/game/CMonsterTruck.h index f1d6f740af3..3107615ae8d 100644 --- a/Client/sdk/game/CMonsterTruck.h +++ b/Client/sdk/game/CMonsterTruck.h @@ -16,5 +16,5 @@ class CMonsterTruck : public virtual CAutomobile { public: - virtual ~CMonsterTruck(){}; + virtual ~CMonsterTruck() {}; }; diff --git a/Client/sdk/game/CObject.h b/Client/sdk/game/CObject.h index 1d65e4fc77f..0f8c75c2830 100644 --- a/Client/sdk/game/CObject.h +++ b/Client/sdk/game/CObject.h @@ -20,7 +20,7 @@ class CVehicle; class CObject : public virtual CPhysical { public: - virtual ~CObject(){}; + virtual ~CObject() {}; virtual CObjectSAInterface* GetObjectInterface() = 0; @@ -41,5 +41,4 @@ class CObject : public virtual CPhysical virtual void SetScale(float fX, float fY, float fZ) = 0; virtual CVector* GetScale() = 0; virtual void ResetScale() = 0; - }; diff --git a/Client/sdk/game/CObjectGroupPhysicalProperties.h b/Client/sdk/game/CObjectGroupPhysicalProperties.h index f350f531a07..9cbb6b934f2 100644 --- a/Client/sdk/game/CObjectGroupPhysicalProperties.h +++ b/Client/sdk/game/CObjectGroupPhysicalProperties.h @@ -22,42 +22,42 @@ class CObjectGroupPhysicalProperties virtual unsigned char GetGroup() const = 0; virtual void RestoreDefault() = 0; - virtual void SetMass(float fMass) = 0; - virtual float GetMass() const = 0; - virtual void SetTurnMass(float fTurnMass) = 0; - virtual float GetTurnMass() const = 0; - virtual void SetAirResistance(float fAirResistance) = 0; - virtual float GetAirResistance() const = 0; - virtual void SetElasticity(float fElasticity) = 0; - virtual float GetElasticity() const = 0; - virtual void SetBuoyancy(float fBuoyancy) = 0; - virtual float GetBuoyancy() const = 0; - virtual void SetUprootLimit(float fUprootLimit) = 0; - virtual float GetUprootLimit() const = 0; - virtual void SetCollisionDamageMultiplier(float fColMult) = 0; - virtual float GetCollisionDamageMultiplier() const = 0; - virtual void SetCollisionDamageEffect(ObjectGroupPhysicalProperties::DamageEffect eDamageEffect) = 0; - virtual ObjectGroupPhysicalProperties::DamageEffect GetCollisionDamageEffect() const = 0; - virtual void SetCollisionSpecialResponseCase(ObjectGroupPhysicalProperties::CollisionResponse eResponseCase) = 0; + virtual void SetMass(float fMass) = 0; + virtual float GetMass() const = 0; + virtual void SetTurnMass(float fTurnMass) = 0; + virtual float GetTurnMass() const = 0; + virtual void SetAirResistance(float fAirResistance) = 0; + virtual float GetAirResistance() const = 0; + virtual void SetElasticity(float fElasticity) = 0; + virtual float GetElasticity() const = 0; + virtual void SetBuoyancy(float fBuoyancy) = 0; + virtual float GetBuoyancy() const = 0; + virtual void SetUprootLimit(float fUprootLimit) = 0; + virtual float GetUprootLimit() const = 0; + virtual void SetCollisionDamageMultiplier(float fColMult) = 0; + virtual float GetCollisionDamageMultiplier() const = 0; + virtual void SetCollisionDamageEffect(ObjectGroupPhysicalProperties::DamageEffect eDamageEffect) = 0; + virtual ObjectGroupPhysicalProperties::DamageEffect GetCollisionDamageEffect() const = 0; + virtual void SetCollisionSpecialResponseCase(ObjectGroupPhysicalProperties::CollisionResponse eResponseCase) = 0; virtual ObjectGroupPhysicalProperties::CollisionResponse GetCollisionSpecialResponseCase() const = 0; - virtual void SetCameraAvoidObject(bool bAvoid) = 0; - virtual bool GetCameraAvoidObject() const = 0; - virtual void SetCausesExplosion(bool bExplodes) = 0; - virtual bool GetCausesExplosion() const = 0; - virtual void SetFxType(ObjectGroupPhysicalProperties::FxType eFxType) = 0; + virtual void SetCameraAvoidObject(bool bAvoid) = 0; + virtual bool GetCameraAvoidObject() const = 0; + virtual void SetCausesExplosion(bool bExplodes) = 0; + virtual bool GetCausesExplosion() const = 0; + virtual void SetFxType(ObjectGroupPhysicalProperties::FxType eFxType) = 0; virtual ObjectGroupPhysicalProperties::FxType GetFxType() const = 0; - virtual void SetFxOffset(CVector vecOffset) = 0; - virtual CVector GetFxOffset() const = 0; - virtual bool SetFxParticleSystem(CFxSystemBPSAInterface* pBlueprint) = 0; - virtual void RemoveFxParticleSystem() = 0; - virtual void SetSmashMultiplier(float fMult) = 0; - virtual float GetSmashMultiplier() const = 0; - virtual void SetBreakVelocity(CVector vecVelocity) = 0; - virtual CVector GetBreakVelocity() const = 0; - virtual void SetBreakVelocityRandomness(float fRand) = 0; - virtual float GetBreakVelocityRandomness() const = 0; - virtual void SetBreakMode(ObjectGroupPhysicalProperties::BreakMode eBreakMode) = 0; + virtual void SetFxOffset(CVector vecOffset) = 0; + virtual CVector GetFxOffset() const = 0; + virtual bool SetFxParticleSystem(CFxSystemBPSAInterface* pBlueprint) = 0; + virtual void RemoveFxParticleSystem() = 0; + virtual void SetSmashMultiplier(float fMult) = 0; + virtual float GetSmashMultiplier() const = 0; + virtual void SetBreakVelocity(CVector vecVelocity) = 0; + virtual CVector GetBreakVelocity() const = 0; + virtual void SetBreakVelocityRandomness(float fRand) = 0; + virtual float GetBreakVelocityRandomness() const = 0; + virtual void SetBreakMode(ObjectGroupPhysicalProperties::BreakMode eBreakMode) = 0; virtual ObjectGroupPhysicalProperties::BreakMode GetBreakMode() const = 0; - virtual void SetSparksOnImpact(bool bSparks) = 0; - virtual bool GetSparksOnImpact() const = 0; + virtual void SetSparksOnImpact(bool bSparks) = 0; + virtual bool GetSparksOnImpact() const = 0; }; diff --git a/Client/sdk/game/CPad.h b/Client/sdk/game/CPad.h index 448311252f1..d1727dfbf1d 100644 --- a/Client/sdk/game/CPad.h +++ b/Client/sdk/game/CPad.h @@ -15,31 +15,31 @@ class CControllerState { public: - signed short LeftStickX; // move/steer left (-128?)/right (+128) - signed short LeftStickY; // move back(+128)/forwards(-128?) - signed short RightStickX; // numpad 6(+128)/numpad 4(-128?) + signed short LeftStickX; // move/steer left (-128?)/right (+128) + signed short LeftStickY; // move back(+128)/forwards(-128?) + signed short RightStickX; // numpad 6(+128)/numpad 4(-128?) signed short RightStickY; signed short LeftShoulder1; signed short LeftShoulder2; - signed short RightShoulder1; // target / hand brake + signed short RightShoulder1; // target / hand brake signed short RightShoulder2; - signed short DPadUp; // radio change up - signed short DPadDown; // radio change down + signed short DPadUp; // radio change up + signed short DPadDown; // radio change down signed short DPadLeft; signed short DPadRight; signed short Start; signed short Select; - signed short ButtonSquare; // jump / reverse - signed short ButtonTriangle; // get in/out - signed short ButtonCross; // sprint / accelerate - signed short ButtonCircle; // fire + signed short ButtonSquare; // jump / reverse + signed short ButtonTriangle; // get in/out + signed short ButtonCross; // sprint / accelerate + signed short ButtonCircle; // fire signed short ShockButtonL; - signed short ShockButtonR; // look behind + signed short ShockButtonR; // look behind signed short m_bChatIndicated; signed short m_bPedWalk; diff --git a/Client/sdk/game/CPed.h b/Client/sdk/game/CPed.h index 7f032596b0b..1d90ba466c8 100644 --- a/Client/sdk/game/CPed.h +++ b/Client/sdk/game/CPed.h @@ -179,7 +179,10 @@ struct SSatchelsData CVector* vecAttachedOffsets; CVector* vecAttachedRotation; - SSatchelsData(CProjectileSAInterface* proj, CVector* offset, CVector* rotation) : pProjectileInterface(proj), vecAttachedOffsets(offset), vecAttachedRotation(rotation) {} + SSatchelsData(CProjectileSAInterface* proj, CVector* offset, CVector* rotation) + : pProjectileInterface(proj), vecAttachedOffsets(offset), vecAttachedRotation(rotation) + { + } }; inline bool IsValidMoveAnim(std::uint32_t iMoveAnim) noexcept @@ -190,7 +193,7 @@ inline bool IsValidMoveAnim(std::uint32_t iMoveAnim) noexcept class CPed : public virtual CPhysical { public: - virtual ~CPed(){}; + virtual ~CPed() {}; virtual class CPedSAInterface* GetPedInterface() noexcept = 0; @@ -265,7 +268,7 @@ class CPed : public virtual CPhysical virtual void SetTestForShotInVehicle(bool test) = 0; virtual std::uint8_t GetOccupiedSeat() const noexcept = 0; - virtual void SetOccupiedSeat(std::uint8_t seat) noexcept = 0; + virtual void SetOccupiedSeat(std::uint8_t seat) noexcept = 0; virtual void RemoveBodyPart(std::uint8_t boneID, std::uint8_t direction) = 0; @@ -302,9 +305,9 @@ class CPed : public virtual CPhysical virtual std::unique_ptr GetPedIK() = 0; virtual CEntitySAInterface* GetTargetedObject() const = 0; - virtual PedState GetPedState() const = 0; + virtual PedState GetPedState() const = 0; - virtual void GetAttachedSatchels(std::vector &satchelsList) const = 0; + virtual void GetAttachedSatchels(std::vector& satchelsList) const = 0; virtual void Say(const ePedSpeechContext& speechId, float probability) = 0; diff --git a/Client/sdk/game/CPedIntelligence.h b/Client/sdk/game/CPedIntelligence.h index ef54c42a53f..a1ff8d71f54 100644 --- a/Client/sdk/game/CPedIntelligence.h +++ b/Client/sdk/game/CPedIntelligence.h @@ -20,9 +20,9 @@ class CTaskSimpleFight; class CPedIntelligence { public: - virtual CTaskManager* GetTaskManager() = 0; - virtual bool TestForStealthKill(CPed* pPed, bool bUnk) = 0; - virtual CTaskSAInterface* SetTaskDuckSecondary(unsigned short nLengthOfDuck) = 0; + virtual CTaskManager* GetTaskManager() = 0; + virtual bool TestForStealthKill(CPed* pPed, bool bUnk) = 0; + virtual CTaskSAInterface* SetTaskDuckSecondary(unsigned short nLengthOfDuck) = 0; virtual CTaskSimpleUseGun* GetTaskUseGun() = 0; virtual CTaskSimpleFight* GetFightTask() = 0; }; diff --git a/Client/sdk/game/CPhysical.h b/Client/sdk/game/CPhysical.h index 3f04fa257b9..d395d5aebe1 100644 --- a/Client/sdk/game/CPhysical.h +++ b/Client/sdk/game/CPhysical.h @@ -16,7 +16,7 @@ class CPhysical : public virtual CEntity { public: - virtual ~CPhysical(){}; + virtual ~CPhysical() {}; virtual CVector* GetMoveSpeed(CVector* vecMoveSpeed) = 0; virtual CVector* GetTurnSpeed(CVector* vecTurnSpeed) = 0; diff --git a/Client/sdk/game/CPickup.h b/Client/sdk/game/CPickup.h index 7fe9ba03e66..3f7b31b199c 100644 --- a/Client/sdk/game/CPickup.h +++ b/Client/sdk/game/CPickup.h @@ -25,22 +25,22 @@ class CPickup virtual CVector* GetPosition(CVector* vecPosition) = 0; virtual PickupType GetType() = 0; - virtual void SetType(PickupType type) = 0; - virtual float GetCurrentValue() = 0; - virtual void SetCurrentValue(float fCurrentValue) = 0; - virtual void SetRegenerationTime(DWORD dwTime) = 0; - virtual void SetMoneyPerDay(WORD wMoneyPerDay) = 0; - virtual WORD GetMoneyPerDay() = 0; - virtual WORD GetModel() = 0; - virtual void SetModel(WORD wModelIndex) = 0; // do not export + virtual void SetType(PickupType type) = 0; + virtual float GetCurrentValue() = 0; + virtual void SetCurrentValue(float fCurrentValue) = 0; + virtual void SetRegenerationTime(DWORD dwTime) = 0; + virtual void SetMoneyPerDay(WORD wMoneyPerDay) = 0; + virtual WORD GetMoneyPerDay() = 0; + virtual WORD GetModel() = 0; + virtual void SetModel(WORD wModelIndex) = 0; // do not export virtual PickupState GetState() = 0; - virtual void SetState(PickupState bState) = 0; - virtual BYTE GetAmmo() = 0; - virtual void SetAmmo(BYTE bAmmo) = 0; - virtual long GetMonetaryValue() = 0; - virtual void SetMonetaryValue(long lMonetaryValue) = 0; - virtual BYTE IsNearby() = 0; - virtual void Remove() = 0; - virtual bool GiveUsAPickUpObject(int ForcedObjectIndex = -1) = 0; - virtual void GetRidOfObjects() = 0; + virtual void SetState(PickupState bState) = 0; + virtual BYTE GetAmmo() = 0; + virtual void SetAmmo(BYTE bAmmo) = 0; + virtual long GetMonetaryValue() = 0; + virtual void SetMonetaryValue(long lMonetaryValue) = 0; + virtual BYTE IsNearby() = 0; + virtual void Remove() = 0; + virtual bool GiveUsAPickUpObject(int ForcedObjectIndex = -1) = 0; + virtual void GetRidOfObjects() = 0; }; diff --git a/Client/sdk/game/CPickups.h b/Client/sdk/game/CPickups.h index 6a15f97b914..631b2511997 100644 --- a/Client/sdk/game/CPickups.h +++ b/Client/sdk/game/CPickups.h @@ -19,7 +19,7 @@ class CVector; class CPickups { public: - virtual CPickup* CreatePickup(CVector* position, DWORD ModelIndex, PickupType Type = PickupType::PICKUP_ONCE, DWORD dwMonetaryValue = 0, DWORD dwMoneyPerDay = 0, - BYTE bPingOutOfPlayer = 0) = 0; + virtual CPickup* CreatePickup(CVector* position, DWORD ModelIndex, PickupType Type = PickupType::PICKUP_ONCE, DWORD dwMonetaryValue = 0, + DWORD dwMoneyPerDay = 0, BYTE bPingOutOfPlayer = 0) = 0; virtual void DisablePickupProcessing(bool bDisabled) = 0; }; diff --git a/Client/sdk/game/CPlane.h b/Client/sdk/game/CPlane.h index 22b0e56fc39..461cdd0cf0d 100644 --- a/Client/sdk/game/CPlane.h +++ b/Client/sdk/game/CPlane.h @@ -16,5 +16,5 @@ class CPlane : public virtual CAutomobile { public: - virtual ~CPlane(){}; + virtual ~CPlane() {}; }; diff --git a/Client/sdk/game/CPlayerInfo.h b/Client/sdk/game/CPlayerInfo.h index 328f0a27d38..8314d0e30ea 100644 --- a/Client/sdk/game/CPlayerInfo.h +++ b/Client/sdk/game/CPlayerInfo.h @@ -31,13 +31,13 @@ class CPlayerInfo virtual byte GetCamDrunkLevel() = 0; virtual void SetCamDrunkLevel(byte level) = 0; - virtual DWORD GetCarTwoWheelCounter() = 0; - virtual float GetCarTwoWheelDist() = 0; - virtual DWORD GetCarLess3WheelCounter() = 0; - virtual DWORD GetBikeRearWheelCounter() = 0; - virtual float GetBikeRearWheelDist() = 0; - virtual DWORD GetBikeFrontWheelCounter() = 0; - virtual float GetBikeFrontWheelDist() = 0; + virtual DWORD GetCarTwoWheelCounter() = 0; + virtual float GetCarTwoWheelDist() = 0; + virtual DWORD GetCarLess3WheelCounter() = 0; + virtual DWORD GetBikeRearWheelCounter() = 0; + virtual float GetBikeRearWheelDist() = 0; + virtual DWORD GetBikeFrontWheelCounter() = 0; + virtual float GetBikeFrontWheelDist() = 0; virtual std::uint8_t GetMaxHealth() const = 0; virtual std::uint8_t GetMaxArmor() const = 0; }; diff --git a/Client/sdk/game/CPlayerPed.h b/Client/sdk/game/CPlayerPed.h index 9eba8102dc7..bfa4873e562 100644 --- a/Client/sdk/game/CPlayerPed.h +++ b/Client/sdk/game/CPlayerPed.h @@ -18,7 +18,7 @@ class CWanted; class CPlayerPed : public virtual CPed { public: - virtual ~CPlayerPed(){}; + virtual ~CPlayerPed() {}; virtual CWanted* GetWanted() = 0; diff --git a/Client/sdk/game/CPools.h b/Client/sdk/game/CPools.h index 7c209ed6c4b..55d6bacb242 100644 --- a/Client/sdk/game/CPools.h +++ b/Client/sdk/game/CPools.h @@ -87,7 +87,7 @@ class CPools virtual CPed* AddPed(class CClientPed* pClientPed, DWORD* pGameInterface) = 0; virtual void RemovePed(CPed* pPed, bool bDelete = true) = 0; - virtual SClientEntity* GetPed(DWORD* pGameInterface) = 0; // not sure we really want this here + virtual SClientEntity* GetPed(DWORD* pGameInterface) = 0; // not sure we really want this here virtual SClientEntity* GetPed(size_t pos) = 0; virtual CPed* GetPedFromRef(DWORD dwGameRef) = 0; virtual unsigned long GetPedCount() = 0; @@ -109,8 +109,8 @@ class CPools virtual void ResetPedPoolCount() = 0; virtual void InvalidateLocalPlayerClientEntity() = 0; - virtual CBuildingsPool& GetBuildingsPool() noexcept = 0; - virtual CDummyPool& GetDummyPool() noexcept = 0; - virtual CTxdPool& GetTxdPool() noexcept = 0; + virtual CBuildingsPool& GetBuildingsPool() noexcept = 0; + virtual CDummyPool& GetDummyPool() noexcept = 0; + virtual CTxdPool& GetTxdPool() noexcept = 0; virtual CPtrNodeSingleLinkPool& GetPtrNodeSingleLinkPool() noexcept = 0; }; diff --git a/Client/sdk/game/CProjectile.h b/Client/sdk/game/CProjectile.h index d6f9faa7c9f..799ea6a5284 100644 --- a/Client/sdk/game/CProjectile.h +++ b/Client/sdk/game/CProjectile.h @@ -18,7 +18,7 @@ class CProjectileInfo; class CProjectile : public virtual CObject { public: - virtual ~CProjectile(){}; + virtual ~CProjectile() {}; virtual void Destroy(bool bBlow) = 0; virtual void SetProjectileInfo(CProjectileInfo* pProjectileInfo) = 0; diff --git a/Client/sdk/game/CProjectileInfo.h b/Client/sdk/game/CProjectileInfo.h index 70cdc7fb2b8..aeb3d564bfc 100644 --- a/Client/sdk/game/CProjectileInfo.h +++ b/Client/sdk/game/CProjectileInfo.h @@ -20,8 +20,8 @@ class CProjectileInfo { public: virtual bool AddProjectile(CEntity* creator, eWeaponType eWeapon, CVector vecOrigin, float fForce, CVector* target, CEntity* targetEntity) = 0; - virtual CProjectile* GetProjectile(void* projectilePointer) = 0; // hack, don't use please - virtual CProjectileInfo* GetProjectileInfo(void* projectileInfoInterface) = 0; // don't use + virtual CProjectile* GetProjectile(void* projectilePointer) = 0; // hack, don't use please + virtual CProjectileInfo* GetProjectileInfo(void* projectileInfoInterface) = 0; // don't use virtual void RemoveProjectile(CProjectileInfo* pProjectileInfo, CProjectile* pProjectile, bool bBlow = true) = 0; virtual CProjectileInfo* GetProjectileInfo(DWORD Index) = 0; virtual void RemoveEntityReferences(CEntity* entity) = 0; diff --git a/Client/sdk/game/CQuadBike.h b/Client/sdk/game/CQuadBike.h index 50af912b879..4ed8836e663 100644 --- a/Client/sdk/game/CQuadBike.h +++ b/Client/sdk/game/CQuadBike.h @@ -16,5 +16,5 @@ class CQuadBike : public virtual CAutomobile { public: - virtual ~CQuadBike(){}; + virtual ~CQuadBike() {}; }; diff --git a/Client/sdk/game/CRenderWare.h b/Client/sdk/game/CRenderWare.h index 47d51bf34ae..e05c44abc71 100644 --- a/Client/sdk/game/CRenderWare.h +++ b/Client/sdk/game/CRenderWare.h @@ -44,19 +44,19 @@ struct SReplacementTextures std::vector replacedOriginals; unsigned short usTxdId; bool bTexturesAreCopies; - SString strDebugSource; // filename/resource for diagnostics - SString strDebugHash; // Short hash of source data for deduping logs + SString strDebugSource; // filename/resource for diagnostics + SString strDebugHash; // Short hash of source data for deduping logs }; - std::vector textures; // List of textures we want to inject into TXD's - std::vector perTxdList; // TXD's which have been modified - std::unordered_set usedInTxdIds; // contains/erase for streaming hot path - std::unordered_set usedInModelIds; // contains/erase for streaming hot path - uint32_t uiSessionId = 0; // Texture-replacing session generation (used to ignore stale cross-session cleanup) - SString strDebugName; // Source path or description for logging - SString strDebugHash; // Short hash of the loaded TXD bytes - SString strDebugResource; // Resource name, if known - bool bHasRequestedSpace = false; + std::vector textures; // List of textures we want to inject into TXD's + std::vector perTxdList; // TXD's which have been modified + std::unordered_set usedInTxdIds; // contains/erase for streaming hot path + std::unordered_set usedInModelIds; // contains/erase for streaming hot path + uint32_t uiSessionId = 0; // Texture-replacing session generation (used to ignore stale cross-session cleanup) + SString strDebugName; // Source path or description for logging + SString strDebugHash; // Short hash of the loaded TXD bytes + SString strDebugResource; // Resource name, if known + bool bHasRequestedSpace = false; }; // Shader layers to render @@ -81,23 +81,23 @@ enum EEntityTypeMask typedef void (*PFN_WATCH_CALLBACK)(CSHADERDUMMY* pContext, CD3DDUMMY* pD3DDataNew, CD3DDUMMY* pD3DDataOld); -#define MAX_ATOMICS_PER_CLUMP 128 +#define MAX_ATOMICS_PER_CLUMP 128 class CRenderWare { public: - virtual bool ModelInfoTXDLoadTextures(SReplacementTextures* pReplacementTextures, const SString& strFilename, const SString& buffer, - bool bFilteringEnabled, SString* pOutError = nullptr) = 0; - virtual bool ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTextures, unsigned short usModelId) = 0; - virtual void ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacementTextures) = 0; - virtual void StaticResetModelTextureReplacing() = 0; - virtual void StaticResetShaderSupport() = 0; - virtual void ClothesAddReplacement(char* pFileData, size_t fileSize, unsigned short usFileId) = 0; - virtual void ClothesRemoveReplacement(char* pFileData) = 0; - virtual bool HasClothesReplacementChanged() = 0; - virtual bool ClothesAddFile(const char* fileData, std::size_t fileSize, const char* fileName) = 0; - virtual bool ClothesRemoveFile(char* fileData) = 0; - virtual bool HasClothesFile(const char* fileName) const noexcept = 0; + virtual bool ModelInfoTXDLoadTextures(SReplacementTextures* pReplacementTextures, const SString& strFilename, const SString& buffer, bool bFilteringEnabled, + SString* pOutError = nullptr) = 0; + virtual bool ModelInfoTXDAddTextures(SReplacementTextures* pReplacementTextures, unsigned short usModelId) = 0; + virtual void ModelInfoTXDRemoveTextures(SReplacementTextures* pReplacementTextures) = 0; + virtual void StaticResetModelTextureReplacing() = 0; + virtual void StaticResetShaderSupport() = 0; + virtual void ClothesAddReplacement(char* pFileData, size_t fileSize, unsigned short usFileId) = 0; + virtual void ClothesRemoveReplacement(char* pFileData) = 0; + virtual bool HasClothesReplacementChanged() = 0; + virtual bool ClothesAddFile(const char* fileData, std::size_t fileSize, const char* fileName) = 0; + virtual bool ClothesRemoveFile(char* fileData) = 0; + virtual bool HasClothesFile(const char* fileName) const noexcept = 0; virtual RwTexDictionary* ReadTXD(const SString& strFilename, const SString& buffer) = 0; virtual RpClump* ReadDFF(const SString& strFilename, const SString& buffer, unsigned short usModelID, bool bLoadEmbeddedCollisions) = 0; virtual CColModel* ReadCOL(const SString& buffer) = 0; @@ -117,9 +117,10 @@ class CRenderWare virtual bool ReplacePartModels(RpClump* pClump, RpAtomicContainer* pAtomics, unsigned int uiAtomics, const char* szName) = 0; virtual void PulseWorldTextureWatch() = 0; virtual void GetModelTextureNames(std::vector& outNameList, unsigned short usModelID) = 0; - virtual bool GetModelTextures(std::vector>& outTextureList, unsigned short usModelID, std::vector vTextureNames) = 0; - virtual const char* GetTextureName(CD3DDUMMY* pD3DData) = 0; - virtual unsigned short GetTXDIDForModelID(unsigned short usModelID) = 0; + virtual bool GetModelTextures(std::vector>& outTextureList, unsigned short usModelID, + std::vector vTextureNames) = 0; + virtual const char* GetTextureName(CD3DDUMMY* pD3DData) = 0; + virtual unsigned short GetTXDIDForModelID(unsigned short usModelID) = 0; virtual void SetRenderingClientEntity(CClientEntityBase* pClientEntity, unsigned short usModelId, int iTypeMask) = 0; virtual SShaderItemLayers* GetAppliedShaderForD3DData(CD3DDUMMY* pD3DData) = 0; diff --git a/Client/sdk/game/CSettings.h b/Client/sdk/game/CSettings.h index 624b166fb56..1d4ee3a99a1 100644 --- a/Client/sdk/game/CSettings.h +++ b/Client/sdk/game/CSettings.h @@ -12,10 +12,10 @@ #pragma once #if (!defined(RWFORCEENUMSIZEINT)) -#define RWFORCEENUMSIZEINT ((int)((~((unsigned int)0))>>1)) + #define RWFORCEENUMSIZEINT ((int)((~((unsigned int)0)) >> 1)) #endif /* (!defined(RWFORCEENUMSIZEINT)) */ -enum VideoModeFlag // RwVideoModeFlag +enum VideoModeFlag // RwVideoModeFlag { rwVIDEOMODEEXCLUSIVE = 0x0001, /** #define INVALID_ARCHIVE_ID 0xFF -#define INVALID_STREAM_ID 0xFF +#define INVALID_STREAM_ID 0xFF enum class eModelLoadState : std::uint32_t { @@ -54,13 +54,13 @@ enum class RestreamOption struct CStreamingInfo { - uint16_t prevId = (uint16_t)-1; - uint16_t nextId = (uint16_t)-1; - uint16_t nextInImg = (uint16_t)-1; - uint8_t flg = 0u; - uint8_t archiveId = 0u; - uint32_t offsetInBlocks = 0u; - uint32_t sizeInBlocks = 0u; + uint16_t prevId = (uint16_t)-1; + uint16_t nextId = (uint16_t)-1; + uint16_t nextInImg = (uint16_t)-1; + uint8_t flg = 0u; + uint8_t archiveId = 0u; + uint32_t offsetInBlocks = 0u; + uint32_t sizeInBlocks = 0u; eModelLoadState loadState = eModelLoadState::LOADSTATE_NOT_LOADED; }; static_assert(sizeof(CStreamingInfo) == 0x14, "Invalid size for CStreamingInfo"); @@ -75,7 +75,7 @@ class CStreaming virtual void RequestSpecialModel(DWORD model, const char* szTexture, DWORD channel) = 0; virtual CStreamingInfo* GetStreamingInfo(uint32 id) = 0; virtual void ReinitStreaming() = 0; - virtual unsigned char AddArchive(const wchar_t *szFilePath) = 0; + virtual unsigned char AddArchive(const wchar_t* szFilePath) = 0; virtual void RemoveArchive(unsigned char ucArchiveID) = 0; virtual void SetStreamingInfo(unsigned int id, unsigned char usStreamID, unsigned int uiOffset, unsigned short usSize, unsigned int uiNextInImg = -1) = 0; virtual bool SetStreamingBufferSize(uint32 uiSize) = 0; diff --git a/Client/sdk/game/CTaskManager.h b/Client/sdk/game/CTaskManager.h index 69fba5b8d2d..d2b25a0232c 100644 --- a/Client/sdk/game/CTaskManager.h +++ b/Client/sdk/game/CTaskManager.h @@ -25,8 +25,8 @@ enum enum eSecondaryTaskType { - TASK_SECONDARY_ATTACK = 0, // want duck to be after attack - TASK_SECONDARY_DUCK, // because attack controls ducking movement + TASK_SECONDARY_ATTACK = 0, // want duck to be after attack + TASK_SECONDARY_DUCK, // because attack controls ducking movement TASK_SECONDARY_SAY, TASK_SECONDARY_FACIAL_COMPLEX, TASK_SECONDARY_PARTIAL_ANIM, @@ -47,7 +47,6 @@ enum taskType SECONDARY_TASK }; - class CTaskManager { public: diff --git a/Client/sdk/game/CTrailer.h b/Client/sdk/game/CTrailer.h index e3ebb499b0d..905e76ec13f 100644 --- a/Client/sdk/game/CTrailer.h +++ b/Client/sdk/game/CTrailer.h @@ -16,5 +16,5 @@ class CTrailer : public virtual CVehicle { public: - virtual ~CTrailer(){}; + virtual ~CTrailer() {}; }; diff --git a/Client/sdk/game/CTrain.h b/Client/sdk/game/CTrain.h index 4dd13aeb73b..91c604d4438 100644 --- a/Client/sdk/game/CTrain.h +++ b/Client/sdk/game/CTrain.h @@ -15,5 +15,5 @@ class CTrain : public virtual CVehicle { public: - virtual ~CTrain(){}; + virtual ~CTrain() {}; }; diff --git a/Client/sdk/game/CVehicle.h b/Client/sdk/game/CVehicle.h index ce4b337d541..d302b4313b9 100644 --- a/Client/sdk/game/CVehicle.h +++ b/Client/sdk/game/CVehicle.h @@ -54,9 +54,9 @@ enum eDoorLock : int32_t }; #define SIREN_TYPE_FIRST 1 -#define SIREN_TYPE_LAST 6 -#define SIREN_ID_MAX 7 -#define SIREN_COUNT_MAX 8 +#define SIREN_TYPE_LAST 6 +#define SIREN_ID_MAX 7 +#define SIREN_COUNT_MAX 8 struct SSirenBeaconInfo { @@ -88,13 +88,13 @@ struct SVehicleFrame RwFrame* pFrame; bool bReadOnly; - std::vector frameList; // Frames from root to parent + std::vector frameList; // Frames from root to parent }; class CVehicle : public virtual CPhysical { public: - virtual ~CVehicle(){}; + virtual ~CVehicle() {}; virtual bool AddProjectile(eWeaponType eWeapon, CVector vecOrigin, float fForce, CVector* target, CEntity* targetEntity) = 0; @@ -269,9 +269,9 @@ class CVehicle : public virtual CPhysical virtual SColor GetHeadLightColor() = 0; virtual void SetHeadLightColor(const SColor color) = 0; - virtual bool SpawnFlyingComponent(const eCarNodes& nodeIndex, const eCarComponentCollisionTypes& collisionType, std::int32_t removalTime = -1) = 0; - virtual void SetWheelVisibility(eWheelPosition wheel, bool bVisible) = 0; - virtual CVector GetWheelPosition(eWheelPosition wheel) = 0; + virtual bool SpawnFlyingComponent(const eCarNodes& nodeIndex, const eCarComponentCollisionTypes& collisionType, std::int32_t removalTime = -1) = 0; + virtual void SetWheelVisibility(eWheelPosition wheel, bool bVisible) = 0; + virtual CVector GetWheelPosition(eWheelPosition wheel) = 0; virtual bool IsHeliSearchLightVisible() = 0; virtual void SetHeliSearchLightVisible(bool bVisible) = 0; diff --git a/Client/sdk/game/CVehicleAudioSettingsEntry.h b/Client/sdk/game/CVehicleAudioSettingsEntry.h index f16a3c37217..fc980cf5761 100644 --- a/Client/sdk/game/CVehicleAudioSettingsEntry.h +++ b/Client/sdk/game/CVehicleAudioSettingsEntry.h @@ -17,23 +17,23 @@ class CVehicleAudioSettingsEntry { public: // Destructor - virtual ~CVehicleAudioSettingsEntry(){} + virtual ~CVehicleAudioSettingsEntry() {} // Get - virtual VehicleSoundType GetSoundType() const noexcept = 0; - virtual short GetEngineOnSoundBankID() const noexcept = 0; - virtual short GetEngineOffSoundBankID() const noexcept = 0; - virtual char GetBassSetting() const noexcept = 0; - virtual float GetBassEq() const noexcept = 0; - virtual float GetFieldC() const noexcept = 0; - virtual char GetHornTon() const noexcept = 0; - virtual float GetHornHign() const noexcept = 0; - virtual char GetEngineUpgrade() const noexcept = 0; - virtual char GetDoorSound() const noexcept = 0; - virtual char GetRadioNum() const noexcept = 0; - virtual char GetRadioType() const noexcept = 0; - virtual char GetVehicleTypeForAudio() const noexcept = 0; - virtual float GetHornVolumeDelta() const noexcept = 0; + virtual VehicleSoundType GetSoundType() const noexcept = 0; + virtual short GetEngineOnSoundBankID() const noexcept = 0; + virtual short GetEngineOffSoundBankID() const noexcept = 0; + virtual char GetBassSetting() const noexcept = 0; + virtual float GetBassEq() const noexcept = 0; + virtual float GetFieldC() const noexcept = 0; + virtual char GetHornTon() const noexcept = 0; + virtual float GetHornHign() const noexcept = 0; + virtual char GetEngineUpgrade() const noexcept = 0; + virtual char GetDoorSound() const noexcept = 0; + virtual char GetRadioNum() const noexcept = 0; + virtual char GetRadioType() const noexcept = 0; + virtual char GetVehicleTypeForAudio() const noexcept = 0; + virtual float GetHornVolumeDelta() const noexcept = 0; // Set virtual void SetSoundType(VehicleSoundType value) noexcept = 0; diff --git a/Client/sdk/game/CVehicleAudioSettingsManager.h b/Client/sdk/game/CVehicleAudioSettingsManager.h index a34864cb99e..7a77ef2591b 100644 --- a/Client/sdk/game/CVehicleAudioSettingsManager.h +++ b/Client/sdk/game/CVehicleAudioSettingsManager.h @@ -18,7 +18,7 @@ class CVehicleAudioSettingsManager public: virtual std::unique_ptr CreateVehicleAudioSettingsData(uint32_t modelId) = 0; virtual CVehicleAudioSettingsEntry& GetVehicleModelAudioSettingsData(uint32_t modelId) noexcept = 0; - + virtual void ResetModelSettings(uint32_t modelId) noexcept = 0; virtual void ResetAudioSettingsData() noexcept = 0; virtual void SetNextSettings(CVehicleAudioSettingsEntry const* pSettings) noexcept = 0; diff --git a/Client/sdk/game/CVisibilityPlugins.h b/Client/sdk/game/CVisibilityPlugins.h index 3d857dd5f75..55765d64548 100644 --- a/Client/sdk/game/CVisibilityPlugins.h +++ b/Client/sdk/game/CVisibilityPlugins.h @@ -11,8 +11,8 @@ #pragma once -#define ATOMIC_ID_FLAG_TWO_VERSIONS_UNDAMAGED 1 -#define ATOMIC_ID_FLAG_TWO_VERSIONS_DAMAGED 2 +#define ATOMIC_ID_FLAG_TWO_VERSIONS_UNDAMAGED 1 +#define ATOMIC_ID_FLAG_TWO_VERSIONS_DAMAGED 2 struct RpClump; struct RwObject; diff --git a/Client/sdk/game/CWaterManager.h b/Client/sdk/game/CWaterManager.h index 05eee46507b..e399743d0fa 100644 --- a/Client/sdk/game/CWaterManager.h +++ b/Client/sdk/game/CWaterManager.h @@ -35,6 +35,6 @@ class CWaterManager virtual bool TestLineAgainstWater(const CVector& vecStart, const CVector& vecEnd, CVector* vecCollision) = 0; virtual void UndoChanges(void* pChangeSource = NULL) = 0; - virtual void RebuildIndex() = 0; // Call this after moving a polygon's vertices - virtual void Reset() = 0; // Reset all water to SA default + virtual void RebuildIndex() = 0; // Call this after moving a polygon's vertices + virtual void Reset() = 0; // Reset all water to SA default }; diff --git a/Client/sdk/game/CWeaponInfo.h b/Client/sdk/game/CWeaponInfo.h index 6f804158ee0..ac03689eff3 100644 --- a/Client/sdk/game/CWeaponInfo.h +++ b/Client/sdk/game/CWeaponInfo.h @@ -20,7 +20,7 @@ enum eWeaponSkill : std::uint8_t WEAPONSKILL_POOR = 0, WEAPONSKILL_STD, WEAPONSKILL_PRO, - WEAPONSKILL_SPECIAL, // for cops using pistols differently for example + WEAPONSKILL_SPECIAL, // for cops using pistols differently for example WEAPONSKILL_MAX_NUMBER }; @@ -42,15 +42,15 @@ enum eWeaponSlot WEAPONSLOT_TYPE_MELEE, WEAPONSLOT_TYPE_HANDGUN, WEAPONSLOT_TYPE_SHOTGUN, - WEAPONSLOT_TYPE_SMG, // 4 + WEAPONSLOT_TYPE_SMG, // 4 WEAPONSLOT_TYPE_MG, WEAPONSLOT_TYPE_RIFLE, WEAPONSLOT_TYPE_HEAVY, WEAPONSLOT_TYPE_THROWN, - WEAPONSLOT_TYPE_SPECIAL, // 9 - WEAPONSLOT_TYPE_GIFT, // 10 - WEAPONSLOT_TYPE_PARACHUTE, // 11 - WEAPONSLOT_TYPE_DETONATOR, // 12 + WEAPONSLOT_TYPE_SPECIAL, // 9 + WEAPONSLOT_TYPE_GIFT, // 10 + WEAPONSLOT_TYPE_PARACHUTE, // 11 + WEAPONSLOT_TYPE_DETONATOR, // 12 WEAPONSLOT_MAX }; @@ -81,7 +81,7 @@ enum eWeaponType WEAPONTYPE_CHAINSAW, // gifts - WEAPONTYPE_DILDO1, // 10 + WEAPONTYPE_DILDO1, // 10 WEAPONTYPE_DILDO2, WEAPONTYPE_VIBE1, WEAPONTYPE_VIBE2, @@ -92,31 +92,31 @@ enum eWeaponType WEAPONTYPE_TEARGAS, WEAPONTYPE_MOLOTOV, WEAPONTYPE_ROCKET, - WEAPONTYPE_ROCKET_HS, // 20 + WEAPONTYPE_ROCKET_HS, // 20 WEAPONTYPE_FREEFALL_BOMB, // FIRST SKILL WEAPON - WEAPONTYPE_PISTOL, // handguns + WEAPONTYPE_PISTOL, // handguns WEAPONTYPE_PISTOL_SILENCED, WEAPONTYPE_DESERT_EAGLE, - WEAPONTYPE_SHOTGUN, // shotguns - WEAPONTYPE_SAWNOFF_SHOTGUN, // one handed + WEAPONTYPE_SHOTGUN, // shotguns + WEAPONTYPE_SAWNOFF_SHOTGUN, // one handed WEAPONTYPE_SPAS12_SHOTGUN, - WEAPONTYPE_MICRO_UZI, // submachine guns + WEAPONTYPE_MICRO_UZI, // submachine guns WEAPONTYPE_MP5, - WEAPONTYPE_AK47, // 30 // machine guns + WEAPONTYPE_AK47, // 30 // machine guns WEAPONTYPE_M4, - WEAPONTYPE_TEC9, // this uses stat from the micro_uzi + WEAPONTYPE_TEC9, // this uses stat from the micro_uzi // END SKILL WEAPONS - WEAPONTYPE_COUNTRYRIFLE, // rifles + WEAPONTYPE_COUNTRYRIFLE, // rifles WEAPONTYPE_SNIPERRIFLE, - WEAPONTYPE_ROCKETLAUNCHER, // specials + WEAPONTYPE_ROCKETLAUNCHER, // specials WEAPONTYPE_ROCKETLAUNCHER_HS, WEAPONTYPE_FLAMETHROWER, WEAPONTYPE_MINIGUN, WEAPONTYPE_REMOTE_SATCHEL_CHARGE, - WEAPONTYPE_DETONATOR, // 40 // plastic explosive + WEAPONTYPE_DETONATOR, // 40 // plastic explosive WEAPONTYPE_SPRAYCAN, WEAPONTYPE_EXTINGUISHER, WEAPONTYPE_CAMERA, @@ -128,12 +128,12 @@ enum eWeaponType WEAPONTYPE_ARMOUR, // these are possible ways to die WEAPONTYPE_RAMMEDBYCAR, - WEAPONTYPE_RUNOVERBYCAR, // 50 + WEAPONTYPE_RUNOVERBYCAR, // 50 WEAPONTYPE_EXPLOSION, WEAPONTYPE_UZI_DRIVEBY, WEAPONTYPE_DROWNING, WEAPONTYPE_FALL, - WEAPONTYPE_UNIDENTIFIED, // Used for damage being done + WEAPONTYPE_UNIDENTIFIED, // Used for damage being done WEAPONTYPE_ANYMELEE, WEAPONTYPE_ANYWEAPON, WEAPONTYPE_FLARE, diff --git a/Client/sdk/game/CWorld.h b/Client/sdk/game/CWorld.h index cb86712ade8..7fb82345ce0 100644 --- a/Client/sdk/game/CWorld.h +++ b/Client/sdk/game/CWorld.h @@ -39,7 +39,7 @@ struct SLineOfSightFlags bool bCheckDummies; bool bSeeThroughStuff; bool bIgnoreSomeObjectsForCamera; - bool bShootThroughStuff; // not used for IsLineOfSightClear + bool bShootThroughStuff; // not used for IsLineOfSightClear bool bCheckCarTires; }; @@ -54,22 +54,23 @@ struct SLineOfSightBuildingResult CEntitySAInterface* pInterface; }; -struct SProcessLineOfSightMaterialInfoResult { - CVector2D uv; //< On-texture UV coordinates of the intersection point - const char* textureName; //< GTA texture name - const char* frameName; //< The name of the frame the hit geometry belongs to - CVector hitPos; //< Precise hit position on the clump [World space] - bool valid{}; //< Data found in this struct is only valid if this is `true`! +struct SProcessLineOfSightMaterialInfoResult +{ + CVector2D uv; //< On-texture UV coordinates of the intersection point + const char* textureName; //< GTA texture name + const char* frameName; //< The name of the frame the hit geometry belongs to + CVector hitPos; //< Precise hit position on the clump [World space] + bool valid{}; //< Data found in this struct is only valid if this is `true`! }; struct STestSphereAgainstWorldResult { - bool collisionDetected{false}; - std::uint32_t modelID{0}; - CVector entityPosition{}; - CVector entityRotation{}; - std::uint32_t lodID{0}; - eEntityType type{ENTITY_TYPE_NOTHING}; + bool collisionDetected{false}; + std::uint32_t modelID{0}; + CVector entityPosition{}; + CVector entityRotation{}; + std::uint32_t lodID{0}; + eEntityType type{ENTITY_TYPE_NOTHING}; }; enum eDebugCaller @@ -181,58 +182,58 @@ class SurfaceInfo_c { public: uint8_t m_tyreGrip; - uint8_t m_wetGrip; // 2 - uint16_t pad; // 4 + uint8_t m_wetGrip; // 2 + uint16_t pad; // 4 union { - struct // size 8 + struct // size 8 { uint32_t flags[2]; }; - struct // size = 51 + struct // size = 51 { - uint32_t m_adhesionGroup : 3; // 1 - 3 - uint32_t m_skidmarkType : 2; // 4 - 5 - uint32_t m_frictionEffect : 3; // 6 - 8 - uint32_t m_bulletFx : 3; // 9 - 11 - uint32_t m_softLanding : 1; // 12 - uint32_t m_seeThrough : 1; // 13 - uint32_t m_shootThrough : 1; // 14 - uint32_t m_sand : 1; // 15 + uint32_t m_adhesionGroup : 3; // 1 - 3 + uint32_t m_skidmarkType : 2; // 4 - 5 + uint32_t m_frictionEffect : 3; // 6 - 8 + uint32_t m_bulletFx : 3; // 9 - 11 + uint32_t m_softLanding : 1; // 12 + uint32_t m_seeThrough : 1; // 13 + uint32_t m_shootThrough : 1; // 14 + uint32_t m_sand : 1; // 15 uint32_t m_water : 1; - uint32_t m_shallowWater : 1; // unknown effect + uint32_t m_shallowWater : 1; // unknown effect uint32_t m_beach : 1; uint32_t m_steepSlope : 1; - uint32_t m_glass : 1; // 20 + uint32_t m_glass : 1; // 20 uint32_t m_stairs : 1; uint32_t m_skateable : 1; uint32_t m_pavement : 1; - uint32_t m_roughness : 2; // 24 - 25 - uint32_t m_flammability : 2; // 26 - 27 - uint32_t m_createsSparks : 1; // 28 - uint32_t m_cantSprintOn : 1; // 29 + uint32_t m_roughness : 2; // 24 - 25 + uint32_t m_flammability : 2; // 26 - 27 + uint32_t m_createsSparks : 1; // 28 + uint32_t m_cantSprintOn : 1; // 29 uint32_t m_leavesFootsteps : 1; uint32_t m_producesFootDust : 1; - uint32_t m_makesCarDirty : 1; // 32 + uint32_t m_makesCarDirty : 1; // 32 - uint32_t m_makesCarClean : 1; // 1 + uint32_t m_makesCarClean : 1; // 1 uint32_t m_createsWheelGrass : 1; uint32_t m_createsWheelGravel : 1; uint32_t m_createsWheelMud : 1; - uint32_t m_createsWheelDust : 1; // 5 - uint32_t m_createsWheelSand : 1; // no effect - uint32_t m_createsWheelSpray : 1; // crash - uint32_t m_createsPlants : 1; // 8 + uint32_t m_createsWheelDust : 1; // 5 + uint32_t m_createsWheelSand : 1; // no effect + uint32_t m_createsWheelSpray : 1; // crash + uint32_t m_createsPlants : 1; // 8 uint32_t m_createsObjects : 1; - uint32_t m_canClimb : 1; // 10 - uint32_t m_audioConcrete : 1; // 11 + uint32_t m_canClimb : 1; // 10 + uint32_t m_audioConcrete : 1; // 11 uint32_t m_audioGrass : 1; - uint32_t m_audioSand : 1; // 13 + uint32_t m_audioSand : 1; // 13 uint32_t m_audioGravel : 1; uint32_t m_audioWood : 1; uint32_t m_audioWater : 1; uint32_t m_audioMetal : 1; - uint32_t m_audioLongGrass : 1; // 18 + uint32_t m_audioLongGrass : 1; // 18 uint32_t m_audioTile : 1; }; }; @@ -264,7 +265,8 @@ class CWorld virtual void Remove(CEntitySAInterface* entityInterface, eDebugCaller CallerId) = 0; virtual auto ProcessLineAgainstMesh(CEntitySAInterface* e, CVector start, CVector end) -> SProcessLineOfSightMaterialInfoResult = 0; virtual bool ProcessLineOfSight(const CVector* vecStart, const CVector* vecEnd, CColPoint** colCollision, CEntity** CollisionEntity, - const SLineOfSightFlags flags = SLineOfSightFlags(), SLineOfSightBuildingResult* pBuildingResult = NULL, SProcessLineOfSightMaterialInfoResult* outMatInfo = {}) = 0; + const SLineOfSightFlags flags = SLineOfSightFlags(), SLineOfSightBuildingResult* pBuildingResult = NULL, + SProcessLineOfSightMaterialInfoResult* outMatInfo = {}) = 0; virtual void IgnoreEntity(CEntity* entity) = 0; virtual float FindGroundZFor3DPosition(CVector* vecPosition) = 0; virtual float FindRoofZFor3DCoord(CVector* pvecPosition, bool* pbOutResult) = 0; @@ -288,5 +290,6 @@ class CWorld virtual void ResetAllSurfaceInfo() = 0; virtual bool ResetSurfaceInfo(short sSurfaceID) = 0; - virtual CEntity* TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, bool checkPeds, bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) = 0; + virtual CEntity* TestSphereAgainstWorld(const CVector& sphereCenter, float radius, CEntity* ignoredEntity, bool checkBuildings, bool checkVehicles, + bool checkPeds, bool checkObjects, bool checkDummies, bool cameraIgnore, STestSphereAgainstWorldResult& result) = 0; }; diff --git a/Client/sdk/game/Common.h b/Client/sdk/game/Common.h index 80810a7d24d..fa3597f9b88 100644 --- a/Client/sdk/game/Common.h +++ b/Client/sdk/game/Common.h @@ -13,42 +13,42 @@ #include // Limits for MTA -#define MAX_VEHICLES_MTA 64 // Real limit is 110 -#define MAX_PEDS_MTA 110 // Real limit is 140 -#define MAX_OBJECTS_MTA 1000 // Real limit is 1200 -#define MAX_ENTRY_INFO_NODES_MTA 72000 // Real limit is 72600 ( MAX_OBJECTS_MTA * 72 ) [Large col models are the cause of high usage] -#define MAX_POINTER_SINGLE_LINKS_MTA 85000 // Real limit is 90000 [Large col models are the cause of high usage] -#define MAX_POINTER_DOUBLE_LINKS_MTA 74000 // Real limit is 74800 ( MAX_OBJECTS_MTA * 72 + 2000 ) +#define MAX_VEHICLES_MTA 64 // Real limit is 110 +#define MAX_PEDS_MTA 110 // Real limit is 140 +#define MAX_OBJECTS_MTA 1000 // Real limit is 1200 +#define MAX_ENTRY_INFO_NODES_MTA 72000 // Real limit is 72600 ( MAX_OBJECTS_MTA * 72 ) [Large col models are the cause of high usage] +#define MAX_POINTER_SINGLE_LINKS_MTA 85000 // Real limit is 90000 [Large col models are the cause of high usage] +#define MAX_POINTER_DOUBLE_LINKS_MTA 74000 // Real limit is 74800 ( MAX_OBJECTS_MTA * 72 + 2000 ) // Real limits for GTA -#define MAX_VEHICLES ( MAX_VEHICLES_MTA + 46 ) // 110 -#define MAX_PEDS ( MAX_PEDS_MTA + 30 ) // 140 -#define MAX_OBJECTS ( MAX_OBJECTS_MTA + 200 ) // 1200 -#define MAX_BUILDINGS 13000 -#define MAX_DUMMIES 2500 -#define MAX_ENTRY_INFO_NODES ( MAX_ENTRY_INFO_NODES_MTA + 600 ) // 72600 -#define MAX_POINTER_SINGLE_LINKS ( MAX_POINTER_SINGLE_LINKS_MTA + 5000 ) // 90000 May be changed in runtime -#define MAX_POINTER_DOUBLE_LINKS ( MAX_POINTER_DOUBLE_LINKS_MTA + 800 ) // 74800 -#define MAX_RWOBJECT_INSTANCES 2500 +#define MAX_VEHICLES (MAX_VEHICLES_MTA + 46) // 110 +#define MAX_PEDS (MAX_PEDS_MTA + 30) // 140 +#define MAX_OBJECTS (MAX_OBJECTS_MTA + 200) // 1200 +#define MAX_BUILDINGS 13000 +#define MAX_DUMMIES 2500 +#define MAX_ENTRY_INFO_NODES (MAX_ENTRY_INFO_NODES_MTA + 600) // 72600 +#define MAX_POINTER_SINGLE_LINKS (MAX_POINTER_SINGLE_LINKS_MTA + 5000) // 90000 May be changed in runtime +#define MAX_POINTER_DOUBLE_LINKS (MAX_POINTER_DOUBLE_LINKS_MTA + 800) // 74800 +#define MAX_RWOBJECT_INSTANCES 2500 /** * Flags used to define weapon characteristics */ // aiming options -#define WEAPONTYPE_CANAIM (0x000001) // can auto target to aim -#define WEAPONTYPE_CANAIMWITHARM (0x000002) // only needs arm to aim -#define WEAPONTYPE_FIRSTPERSON (0x000004) // uses 1st person aim -#define WEAPONTYPE_CANFREEAIM (0x000008) // can only use free aiming +#define WEAPONTYPE_CANAIM (0x000001) // can auto target to aim +#define WEAPONTYPE_CANAIMWITHARM (0x000002) // only needs arm to aim +#define WEAPONTYPE_FIRSTPERSON (0x000004) // uses 1st person aim +#define WEAPONTYPE_CANFREEAIM (0x000008) // can only use free aiming // movement options -#define WEAPONTYPE_MOVEAIM (0x000010) // can move and aim at same time -#define WEAPONTYPE_MOVEFIRE (0x000020) // can move and fire at same time +#define WEAPONTYPE_MOVEAIM (0x000010) // can move and aim at same time +#define WEAPONTYPE_MOVEFIRE (0x000020) // can move and fire at same time // basic characteristics -#define WEAPONTYPE_THROW (0x000100) // is a throwing weapon -#define WEAPONTYPE_HEAVY (0x000200) // heavy weapon - can't jump -#define WEAPONTYPE_CONTINUOUS_FIRE (0x000400) // fires every frame within loop (ie paint spray) -#define WEAPONTYPE_TWIN_PISTOLS (0x000800) // can use 2x guns at same time +#define WEAPONTYPE_THROW (0x000100) // is a throwing weapon +#define WEAPONTYPE_HEAVY (0x000200) // heavy weapon - can't jump +#define WEAPONTYPE_CONTINUOUS_FIRE (0x000400) // fires every frame within loop (ie paint spray) +#define WEAPONTYPE_TWIN_PISTOLS (0x000800) // can use 2x guns at same time // these are gun anim options #define WEAPONTYPE_ANIM_RELOAD (0x001000) // weapon has reload anims @@ -57,8 +57,8 @@ #define WEAPONTYPE_LONG_RELOAD_TIME (0x008000) // force a longer reload time! // these are area effect/shot options -#define WEAPONTYPE_SLOWS_DOWN (0x010000) // -#define WEAPONTYPE_RANDOM_SPEED (0x020000) // +#define WEAPONTYPE_SLOWS_DOWN (0x010000) // +#define WEAPONTYPE_RANDOM_SPEED (0x020000) // #define WEAPONTYPE_FORCE_FINISH_ANIM (0x040000) // force the anim to finish player after aim/fire rather than blending out -#define WEAPONTYPE_EXPANDS (0x080000) // -#define WEAPONTYPE_CHAINGUN WEAPONTYPE_MINIGUN +#define WEAPONTYPE_EXPANDS (0x080000) // +#define WEAPONTYPE_CHAINGUN WEAPONTYPE_MINIGUN diff --git a/Client/sdk/game/RenderWare.h b/Client/sdk/game/RenderWare.h index d43099d0cc2..c0a4257b059 100644 --- a/Client/sdk/game/RenderWare.h +++ b/Client/sdk/game/RenderWare.h @@ -22,10 +22,10 @@ #define RWFORCEENUMSIZEINT ((std::int32_t)((~((std::uint32_t)0)) >> 1)) #endif #define RWPLUGINOFFSET(_type, _base, _offset) ((_type*)((std::uint8_t*)(_base) + (_offset))) -#define RW_STRUCT_ALIGN ((int)((~((unsigned int)0))>>1)) -#define RW_TEXTURE_NAME_LENGTH 32 -#define RW_FRAME_NAME_LENGTH 23 -#define RW_MAX_TEXTURE_COORDS 8 +#define RW_STRUCT_ALIGN ((int)((~((unsigned int)0)) >> 1)) +#define RW_TEXTURE_NAME_LENGTH 32 +#define RW_FRAME_NAME_LENGTH 23 +#define RW_MAX_TEXTURE_COORDS 8 /* Type IDs */ @@ -59,11 +59,11 @@ typedef RpClump* (*RpClumpCallback)(RpClump* clump, void* data); // RenderWare primitive types struct RwV2d -{ // 8-byte +{ // 8-byte float x, y; }; struct RwV3d -{ // 12-byte +{ // 12-byte float x, y, z; }; struct RwPlane @@ -207,7 +207,7 @@ struct RwObject unsigned char subtype; unsigned char flags; unsigned char privateFlags; - void* parent; // should be RwFrame with RpClump + void* parent; // should be RwFrame with RpClump }; struct RwVertex { @@ -226,18 +226,18 @@ struct RwList }; struct RwFrame { - RwObject object; // 0 - void * pad1, *pad2; // 8 - RwMatrix modelling; // 16 - RwMatrix ltm; // 32 - RwList objects; // 48 - struct RwFrame* child; // 56 - struct RwFrame* next; // 60 - struct RwFrame* root; // 64 + RwObject object; // 0 + void * pad1, *pad2; // 8 + RwMatrix modelling; // 16 + RwMatrix ltm; // 32 + RwList objects; // 48 + struct RwFrame* child; // 56 + struct RwFrame* next; // 60 + struct RwFrame* root; // 64 // Rockstar Frame extension (0x253F2FE) (24 bytes) - unsigned char pluginData[8]; // padding - char szName[RW_FRAME_NAME_LENGTH + 1]; // name (as stored in the frame extension) + unsigned char pluginData[8]; // padding + char szName[RW_FRAME_NAME_LENGTH + 1]; // name (as stored in the frame extension) }; struct RwTexDictionary { @@ -261,11 +261,11 @@ struct RwTextureCoordinates }; struct RwRaster { - RwRaster* parent; // 0 - unsigned char* pixels; // 4 - unsigned char* palette; // 8 - int width, height, depth; // 12, 16 / 0x10, 20 - int numLevels; // 24 / 0x18 + RwRaster* parent; // 0 + unsigned char* pixels; // 4 + unsigned char* palette; // 8 + int width, height, depth; // 12, 16 / 0x10, 20 + int numLevels; // 24 / 0x18 short u, v; unsigned char type; unsigned char flags; @@ -273,7 +273,7 @@ struct RwRaster unsigned char format; unsigned char* origPixels; int origWidth, origHeight, origDepth; - void* renderResource; // RwD3D9Raster continues from here + void* renderResource; // RwD3D9Raster continues from here }; struct RwColorFloat { @@ -372,7 +372,7 @@ struct RpLight unsigned short unknown2; }; struct RpClump -{ // RenderWare (plugin) Clump (used by GTA) +{ // RenderWare (plugin) Clump (used by GTA) RwObject object; RwList atomics; RwList lights; @@ -407,9 +407,9 @@ struct RpTriangle struct RpMorphTarget { RpGeometry* parentGeom; - RwSphere boundingSphere; - RwV3d* verts; - RwV3d* normals; + RwSphere boundingSphere; + RwV3d* verts; + RwV3d* normals; }; struct RpGeometry { @@ -432,31 +432,34 @@ struct RpGeometry RpMorphTarget* morph_target; }; -inline auto rwObjectGetParent(RwObject* o) { +inline auto rwObjectGetParent(RwObject* o) +{ return (RwObject*)o->parent; } -inline auto RpAtomicGetFrame(RpAtomic* atomic) { +inline auto RpAtomicGetFrame(RpAtomic* atomic) +{ return (RwFrame*)atomic->object.object.parent; } -inline auto RwFrameGetParent(RwFrame* f) { +inline auto RwFrameGetParent(RwFrame* f) +{ return (RwFrame*)rwObjectGetParent((RwObject*)f); } -inline RwMatrix* RwFrameGetMatrix(RwFrame* f) { +inline RwMatrix* RwFrameGetMatrix(RwFrame* f) +{ return &f->modelling; } -inline void _rpAtomicResyncInterpolatedSphere(RpAtomic* atomic) { +inline void _rpAtomicResyncInterpolatedSphere(RpAtomic* atomic) +{ reinterpret_cast(0x7491F0)(atomic); } /* NB "RpAtomicGetBoundingSphere(atomic++)" will break it */ -#define RpAtomicGetBoundingSphere(_atomic) \ - ((((_atomic)->interpolator.flags & rpINTERPOLATORDIRTYSPHERE)? \ - _rpAtomicResyncInterpolatedSphere(_atomic), 0: 0), \ - &((_atomic)->boundingSphere)) +#define RpAtomicGetBoundingSphere(_atomic) \ + ((((_atomic)->interpolator.flags & rpINTERPOLATORDIRTYSPHERE) ? _rpAtomicResyncInterpolatedSphere(_atomic), 0 : 0), &((_atomic)->boundingSphere)) /*****************************************************************************/ /** RenderWare I/O **/ @@ -554,13 +557,13 @@ struct RwDevice typedef bool (*RwStandardFunc)(void*, void*, std::int32_t); struct RwGlobals { - void* curCamera; - void* curWorld; - std::uint16_t renderFrame; - std::uint16_t lightFrame; - std::uint16_t pad[2]; - RwDevice dOpenDevice; - RwStandardFunc stdFunc[29]; + void* curCamera; + void* curWorld; + std::uint16_t renderFrame; + std::uint16_t lightFrame; + std::uint16_t pad[2]; + RwDevice dOpenDevice; + RwStandardFunc stdFunc[29]; // RwLinkList dirtyFrameList; // RwFileFunctions fileFuncs; // RwStringFunctions stringFuncs; @@ -571,4 +574,4 @@ struct RwGlobals // RwEngineStatus engineStatus; // RwUInt32 resArenaInitSize; }; -//static_assert(sizeof(RwGlobals) == 0x158, "Incorrect class size: RwGlobals"); +// static_assert(sizeof(RwGlobals) == 0x158, "Incorrect class size: RwGlobals"); diff --git a/Client/sdk/game/Task.h b/Client/sdk/game/Task.h index f233a7e68ef..ae5dd16b24a 100644 --- a/Client/sdk/game/Task.h +++ b/Client/sdk/game/Task.h @@ -17,27 +17,27 @@ class CEvent; class CPed; class CTaskSAInterface; -#define NO_TASK_TYPE 9999 +#define NO_TASK_TYPE 9999 class CTask { public: - virtual ~CTask(){}; + virtual ~CTask() {}; - virtual CTask* Clone() = 0; - virtual void SetParent(CTask* pParent) = 0; - virtual CTask* GetParent() = 0; - virtual CTask* GetSubTask() = 0; - virtual bool IsSimpleTask() = 0; - virtual int GetTaskType() = 0; // returns NO_TASK_TYPE if no task type exists - virtual void StopTimer(const CEvent* pEvent) = 0; - virtual bool MakeAbortable(CPed* pPed, const int iPriority, const CEvent* pEvent) = 0; - virtual const char* GetTaskName() = 0; - virtual class CTaskSAInterface* GetInterface() noexcept = 0; + virtual CTask* Clone() = 0; + virtual void SetParent(CTask* pParent) = 0; + virtual CTask* GetParent() = 0; + virtual CTask* GetSubTask() = 0; + virtual bool IsSimpleTask() = 0; + virtual int GetTaskType() = 0; // returns NO_TASK_TYPE if no task type exists + virtual void StopTimer(const CEvent* pEvent) = 0; + virtual bool MakeAbortable(CPed* pPed, const int iPriority, const CEvent* pEvent) = 0; + virtual const char* GetTaskName() = 0; + virtual class CTaskSAInterface* GetInterface() noexcept = 0; virtual const class CTaskSAInterface* GetInterface() const noexcept = 0; - virtual bool IsValid() = 0; - virtual void SetAsPedTask(CPed* pPed, const int iTaskPriority, const bool bForceNewTask = false) = 0; - virtual void SetAsSecondaryPedTask(CPed* pPed, const int iType) = 0; + virtual bool IsValid() = 0; + virtual void SetAsPedTask(CPed* pPed, const int iTaskPriority, const bool bForceNewTask = false) = 0; + virtual void SetAsSecondaryPedTask(CPed* pPed, const int iType) = 0; virtual void Destroy() = 0; virtual void DestroyJustThis() = 0; @@ -46,7 +46,7 @@ class CTask class CTaskSimple : public virtual CTask { public: - virtual ~CTaskSimple(){}; + virtual ~CTaskSimple() {}; virtual bool ProcessPed(CPed* pPed) = 0; virtual bool SetPedPosition(CPed* pPed) = 0; @@ -55,7 +55,7 @@ class CTaskSimple : public virtual CTask class CTaskComplex : public virtual CTask { public: - virtual ~CTaskComplex(){}; + virtual ~CTaskComplex() {}; virtual void SetSubTask(CTask* pSubTask) = 0; virtual CTask* CreateNextSubTask(CPed* pPed) = 0; diff --git a/Client/sdk/game/TaskAttack.h b/Client/sdk/game/TaskAttack.h index 5f1741e60fa..59d7a13a785 100644 --- a/Client/sdk/game/TaskAttack.h +++ b/Client/sdk/game/TaskAttack.h @@ -19,7 +19,7 @@ class CVector; class CTaskSimpleGangDriveBy : public virtual CTaskSimple { public: - virtual ~CTaskSimpleGangDriveBy(){}; + virtual ~CTaskSimpleGangDriveBy() {}; }; enum eGunCommand @@ -39,7 +39,7 @@ class CVector2D; class CTaskSimpleUseGun : public virtual CTaskSimple { public: - virtual ~CTaskSimpleUseGun(){}; + virtual ~CTaskSimpleUseGun() {}; virtual bool ControlGun(CPed* pPed, CEntity* pTargetEntity, char nCommand) = 0; virtual bool ControlGunMove(CVector2D* pMoveVec) = 0; @@ -51,5 +51,5 @@ class CTaskSimpleUseGun : public virtual CTaskSimple class CTaskSimpleFight : public virtual CTaskSimple { public: - virtual ~CTaskSimpleFight(){}; + virtual ~CTaskSimpleFight() {}; }; diff --git a/Client/sdk/game/TaskBasic.h b/Client/sdk/game/TaskBasic.h index 8ec831dc55d..e3f0df8ddfb 100644 --- a/Client/sdk/game/TaskBasic.h +++ b/Client/sdk/game/TaskBasic.h @@ -16,19 +16,19 @@ class CTaskComplexUseMobilePhone : public virtual CTaskComplex { public: - virtual ~CTaskComplexUseMobilePhone(){}; + virtual ~CTaskComplexUseMobilePhone() {}; }; class CTaskSimpleAnim : public virtual CTaskSimple { public: - virtual ~CTaskSimpleAnim(){}; + virtual ~CTaskSimpleAnim() {}; }; class CTaskSimpleRunAnim : public virtual CTaskSimpleAnim { public: - virtual ~CTaskSimpleRunAnim(){}; + virtual ~CTaskSimpleRunAnim() {}; }; class CTaskSimpleRunNamedAnim : public virtual CTaskSimpleAnim @@ -41,25 +41,25 @@ class CTaskSimpleRunNamedAnim : public virtual CTaskSimpleAnim class CTaskComplexDie : public virtual CTaskComplex { public: - virtual ~CTaskComplexDie(){}; + virtual ~CTaskComplexDie() {}; }; class CTaskSimpleStealthKill : public virtual CTaskSimple { public: - virtual ~CTaskSimpleStealthKill(){}; + virtual ~CTaskSimpleStealthKill() {}; }; class CTaskSimpleDead : public virtual CTaskSimple { public: - virtual ~CTaskSimpleDead(){}; + virtual ~CTaskSimpleDead() {}; }; class CTaskSimpleBeHit : public virtual CTaskSimple { public: - virtual ~CTaskSimpleBeHit(){}; + virtual ~CTaskSimpleBeHit() {}; }; enum eSunbatherType @@ -74,7 +74,7 @@ enum eSunbatherType class CTaskComplexSunbathe : public virtual CTaskComplex { public: - virtual ~CTaskComplexSunbathe(){}; + virtual ~CTaskComplexSunbathe() {}; virtual void SetEndTime(DWORD dwTime) = 0; }; @@ -84,7 +84,7 @@ class CTaskComplexSunbathe : public virtual CTaskComplex class CTaskSimplePlayerOnFoot : public virtual CTaskSimple { public: - virtual ~CTaskSimplePlayerOnFoot(){}; + virtual ~CTaskSimplePlayerOnFoot() {}; }; //////////////////// @@ -93,11 +93,11 @@ class CTaskSimplePlayerOnFoot : public virtual CTaskSimple class CTaskComplexFacial : public virtual CTaskComplex { public: - virtual ~CTaskComplexFacial(){}; + virtual ~CTaskComplexFacial() {}; }; class CTaskComplexInWater : public virtual CTaskComplex { public: - virtual ~CTaskComplexInWater(){}; + virtual ~CTaskComplexInWater() {}; }; diff --git a/Client/sdk/game/TaskCar.h b/Client/sdk/game/TaskCar.h index 171ddda1588..e1a607c30aa 100644 --- a/Client/sdk/game/TaskCar.h +++ b/Client/sdk/game/TaskCar.h @@ -24,7 +24,7 @@ enum class CTaskComplexEnterCar : public virtual CTaskComplex { public: - virtual ~CTaskComplexEnterCar(){}; + virtual ~CTaskComplexEnterCar() {}; virtual int GetTargetDoor() = 0; virtual void SetTargetDoor(int iDoor) = 0; @@ -34,25 +34,25 @@ class CTaskComplexEnterCar : public virtual CTaskComplex class CTaskComplexEnterCarAsDriver : public virtual CTaskComplexEnterCar { public: - virtual ~CTaskComplexEnterCarAsDriver(){}; + virtual ~CTaskComplexEnterCarAsDriver() {}; }; class CTaskComplexEnterCarAsPassenger : public virtual CTaskComplexEnterCar { public: - virtual ~CTaskComplexEnterCarAsPassenger(){}; + virtual ~CTaskComplexEnterCarAsPassenger() {}; }; class CTaskComplexEnterBoatAsDriver : public virtual CTaskComplex { public: - virtual ~CTaskComplexEnterBoatAsDriver(){}; + virtual ~CTaskComplexEnterBoatAsDriver() {}; }; class CTaskComplexLeaveCar : public virtual CTaskComplex { public: - virtual ~CTaskComplexLeaveCar(){}; + virtual ~CTaskComplexLeaveCar() {}; virtual int GetTargetDoor() = 0; }; diff --git a/Client/sdk/game/TaskCarAccessories.h b/Client/sdk/game/TaskCarAccessories.h index 4e849947677..6a6d422391d 100644 --- a/Client/sdk/game/TaskCarAccessories.h +++ b/Client/sdk/game/TaskCarAccessories.h @@ -18,7 +18,7 @@ class CVehicle; class CTaskSimpleCarSetPedInAsDriver : public virtual CTaskSimple { public: - virtual ~CTaskSimpleCarSetPedInAsDriver(){}; + virtual ~CTaskSimpleCarSetPedInAsDriver() {}; virtual void SetIsWarpingPedIntoCar() = 0; virtual void SetDoorFlagsToClear(const unsigned char nDoorFlagsToClear) = 0; @@ -28,7 +28,7 @@ class CTaskSimpleCarSetPedInAsDriver : public virtual CTaskSimple class CTaskSimpleCarSetPedOut : public virtual CTaskSimple { public: - virtual ~CTaskSimpleCarSetPedOut(){}; + virtual ~CTaskSimpleCarSetPedOut() {}; virtual void SetIsWarpingPedOutOfCar() = 0; virtual void SetKnockedOffBike() = 0; @@ -40,7 +40,7 @@ class CTaskSimpleCarSetPedOut : public virtual CTaskSimple class CTaskSimpleCarSetPedInAsPassenger : public virtual CTaskSimple { public: - virtual ~CTaskSimpleCarSetPedInAsPassenger(){}; + virtual ~CTaskSimpleCarSetPedInAsPassenger() {}; virtual void SetIsWarpingPedIntoCar() = 0; virtual void SetDoorFlagsToClear(const unsigned char nDoorFlagsToClear) = 0; diff --git a/Client/sdk/game/TaskGoTo.h b/Client/sdk/game/TaskGoTo.h index dbf283a2086..0f96fe9eff3 100644 --- a/Client/sdk/game/TaskGoTo.h +++ b/Client/sdk/game/TaskGoTo.h @@ -34,12 +34,12 @@ enum WANDER_TYPE_PROSTITUTE }; -#define NO_WANDER_TYPE 9999 +#define NO_WANDER_TYPE 9999 class CTaskComplexWander : public virtual CTaskComplex { public: - virtual ~CTaskComplexWander(){}; + virtual ~CTaskComplexWander() {}; virtual CNodeAddress* GetNextNode() = 0; virtual CNodeAddress* GetLastNode() = 0; @@ -50,5 +50,5 @@ class CTaskComplexWander : public virtual CTaskComplex class CTaskComplexWanderStandard : public virtual CTaskComplexWander { public: - virtual ~CTaskComplexWanderStandard(){}; + virtual ~CTaskComplexWanderStandard() {}; }; diff --git a/Client/sdk/game/TaskIK.h b/Client/sdk/game/TaskIK.h index c1530200025..51a4cc0fb71 100644 --- a/Client/sdk/game/TaskIK.h +++ b/Client/sdk/game/TaskIK.h @@ -13,24 +13,24 @@ #include "Task.h" -#define NUM_IK_CHAIN_SLOTS 5 //(28 - sizeof(CTaskSimple)) / 4 +#define NUM_IK_CHAIN_SLOTS 5 //(28 - sizeof(CTaskSimple)) / 4 class CTaskSimpleIKChain : public virtual CTaskSimple { public: - virtual ~CTaskSimpleIKChain(){}; + virtual ~CTaskSimpleIKChain() {}; }; class CTaskSimpleIKLookAt : public virtual CTaskSimpleIKChain { public: - virtual ~CTaskSimpleIKLookAt(){}; + virtual ~CTaskSimpleIKLookAt() {}; }; class CTaskSimpleIKManager : public virtual CTaskSimple { public: - virtual ~CTaskSimpleIKManager(){}; + virtual ~CTaskSimpleIKManager() {}; virtual int AddIKChainTask(CTaskSimpleIKChain* pIKChainTask, int slotID = -1) = 0; virtual void RemoveIKChainTask(int slotID) = 0; @@ -42,5 +42,5 @@ class CTaskSimpleIKManager : public virtual CTaskSimple class CTaskSimpleTriggerLookAt : public virtual CTaskSimple { public: - virtual ~CTaskSimpleTriggerLookAt(){}; + virtual ~CTaskSimpleTriggerLookAt() {}; }; diff --git a/Client/sdk/game/TaskJumpFall.h b/Client/sdk/game/TaskJumpFall.h index b5399e4f79c..596739c9453 100644 --- a/Client/sdk/game/TaskJumpFall.h +++ b/Client/sdk/game/TaskJumpFall.h @@ -19,7 +19,7 @@ enum eClimbHeights : std::int8_t; class CTaskSimpleClimb : public virtual CTaskSimple { public: - virtual ~CTaskSimpleClimb(){}; + virtual ~CTaskSimpleClimb() {}; virtual eClimbHeights GetHeightForPos() const = 0; @@ -29,14 +29,15 @@ class CTaskSimpleClimb : public virtual CTaskSimple return nullptr; // CTaskSimpleClimb::TestForClimb - return ((class CEntitySAInterface*(__cdecl*)(class CPedSAInterface*, CVector*, float*, int*, bool))0x6803A0)(ped->GetPedInterface(), &climbPos, &climbAngle, &surfaceType, launch); + return ((class CEntitySAInterface * (__cdecl*)(class CPedSAInterface*, CVector*, float*, int*, bool))0x6803A0)(ped->GetPedInterface(), &climbPos, + &climbAngle, &surfaceType, launch); } }; class CTaskSimpleJetPack : public virtual CTaskSimple { public: - virtual ~CTaskSimpleJetPack(){}; + virtual ~CTaskSimpleJetPack() {}; virtual bool IsFinished() const = 0; }; diff --git a/Client/sdk/game/TaskPhysicalResponse.h b/Client/sdk/game/TaskPhysicalResponse.h index 552d8e14502..d6b4af2ab57 100644 --- a/Client/sdk/game/TaskPhysicalResponse.h +++ b/Client/sdk/game/TaskPhysicalResponse.h @@ -16,7 +16,7 @@ class CTaskSimpleChoking : public virtual CTaskSimple { public: - virtual ~CTaskSimpleChoking(){}; + virtual ~CTaskSimpleChoking() {}; virtual CPed* GetAttacker() = 0; virtual unsigned int GetTimeRemaining() = 0; diff --git a/Client/sdk/game/TaskSecondary.h b/Client/sdk/game/TaskSecondary.h index 14f5c993748..b40d22d827a 100644 --- a/Client/sdk/game/TaskSecondary.h +++ b/Client/sdk/game/TaskSecondary.h @@ -15,15 +15,15 @@ enum eDuckControlTypes { - DUCK_STANDALONE = 0, // duck anim removed when task removed - DUCK_STANDALONE_WEAPON_CROUCH, // duck anim removed when task removed - DUCK_TASK_CONTROLLED, // duck directly linked to a controlling task - DUCK_ANIM_CONTROLLED, // duck linked to duck anim (make duck partial?) + DUCK_STANDALONE = 0, // duck anim removed when task removed + DUCK_STANDALONE_WEAPON_CROUCH, // duck anim removed when task removed + DUCK_TASK_CONTROLLED, // duck directly linked to a controlling task + DUCK_ANIM_CONTROLLED, // duck linked to duck anim (make duck partial?) DUCK_SCRIPT_CONTROLLED, }; class CTaskSimpleDuck : public virtual CTaskSimple { public: - virtual ~CTaskSimpleDuck(){}; + virtual ~CTaskSimpleDuck() {}; }; diff --git a/Client/sdk/game/TaskTypes.h b/Client/sdk/game/TaskTypes.h index 289d368bf7f..5a511b8e535 100644 --- a/Client/sdk/game/TaskTypes.h +++ b/Client/sdk/game/TaskTypes.h @@ -144,9 +144,9 @@ enum eTaskType TASK_COMPLEX_FACIAL, TASK_SIMPLE_AFFECT_SECONDARY_BEHAVIOUR, TASK_SIMPLE_HOLD_ENTITY, - TASK_SIMPLE_PICKUP_ENTITY, // these three aren't really secondary tasks - TASK_SIMPLE_PUTDOWN_ENTITY, // but they exist around the secondary hold entity - TASK_COMPLEX_GO_PICKUP_ENTITY, // task at the start and finish + TASK_SIMPLE_PICKUP_ENTITY, // these three aren't really secondary tasks + TASK_SIMPLE_PUTDOWN_ENTITY, // but they exist around the secondary hold entity + TASK_COMPLEX_GO_PICKUP_ENTITY, // task at the start and finish TASK_SIMPLE_DUCK_WHILE_SHOTS_WHIZZING, // SCRIPT_DECISION @@ -415,8 +415,8 @@ enum eTaskType TASK_SIMPLE_GANG_DRIVEBY, // SCRIPT_DECISION - TASK_COMPLEX_KILL_PED_ON_FOOT_TIMED, // SCRIPT_DECISION - TASK_COMPLEX_KILL_PED_ON_FOOT_STAND_STILL, // SCRIPT_DECISION + TASK_COMPLEX_KILL_PED_ON_FOOT_TIMED, // SCRIPT_DECISION + TASK_COMPLEX_KILL_PED_ON_FOOT_STAND_STILL, // SCRIPT_DECISION TASK_UNUSED2, TASK_KILL_PED_ON_FOOT_WHILE_DUCKING, // SCRIPT_DECISION diff --git a/Client/sdk/gui/CGUI.h b/Client/sdk/gui/CGUI.h index 1b7f641226c..184a22511b2 100644 --- a/Client/sdk/gui/CGUI.h +++ b/Client/sdk/gui/CGUI.h @@ -38,14 +38,14 @@ class CGUI; #include "CGUITypes.h" // Path defines for CGUI -#define CGUI_ICON_MESSAGEBOX_INFO "cgui\\images\\info.png" -#define CGUI_ICON_MESSAGEBOX_QUESTION "cgui\\images\\question.png" -#define CGUI_ICON_MESSAGEBOX_WARNING "cgui\\images\\warning.png" -#define CGUI_ICON_MESSAGEBOX_ERROR "cgui\\images\\error.png" -#define CGUI_ICON_SERVER_PASSWORD "cgui\\images\\locked.png" -#define CGUI_GetMaxTextExtent(...) GetMaxTextExtent(__VA_ARGS__, SString()) - -#define CHECK_CHANNEL(channel) assert ( (channel) >= 0 && (channel) < INPUT_CHANNEL_COUNT ) +#define CGUI_ICON_MESSAGEBOX_INFO "cgui\\images\\info.png" +#define CGUI_ICON_MESSAGEBOX_QUESTION "cgui\\images\\question.png" +#define CGUI_ICON_MESSAGEBOX_WARNING "cgui\\images\\warning.png" +#define CGUI_ICON_MESSAGEBOX_ERROR "cgui\\images\\error.png" +#define CGUI_ICON_SERVER_PASSWORD "cgui\\images\\locked.png" +#define CGUI_GetMaxTextExtent(...) GetMaxTextExtent(__VA_ARGS__, SString()) + +#define CHECK_CHANNEL(channel) assert((channel) >= 0 && (channel) < INPUT_CHANNEL_COUNT) class CGUI { diff --git a/Client/sdk/gui/CGUIButton.h b/Client/sdk/gui/CGUIButton.h index 620619741d8..f3b80b93293 100644 --- a/Client/sdk/gui/CGUIButton.h +++ b/Client/sdk/gui/CGUIButton.h @@ -17,5 +17,5 @@ class CGUIButton : public CGUIElement { public: - virtual ~CGUIButton(){}; + virtual ~CGUIButton() {}; }; diff --git a/Client/sdk/gui/CGUICallback.h b/Client/sdk/gui/CGUICallback.h index e7342dcd77b..45f44cca348 100644 --- a/Client/sdk/gui/CGUICallback.h +++ b/Client/sdk/gui/CGUICallback.h @@ -14,10 +14,10 @@ class CGUIElement; // Define callbacks -#define GUI_CALLBACK CGUICallback < bool, CGUIElement * > -#define GUI_CALLBACK_KEY CGUICallback < bool, CGUIKeyEventArgs > -#define GUI_CALLBACK_MOUSE CGUICallback < bool, CGUIMouseEventArgs > -#define GUI_CALLBACK_FOCUS CGUICallback < bool, CGUIFocusEventArgs > +#define GUI_CALLBACK CGUICallback +#define GUI_CALLBACK_KEY CGUICallback +#define GUI_CALLBACK_MOUSE CGUICallback +#define GUI_CALLBACK_FOCUS CGUICallback // Represents any callback template @@ -98,5 +98,5 @@ class CGUICallback operator bool() const { return *(DWORD*)m_Callback != NULL; } protected: - char m_Callback[4 + 4 + 20]; // vtable + pObj + pMemFn + char m_Callback[4 + 4 + 20]; // vtable + pObj + pMemFn }; diff --git a/Client/sdk/gui/CGUICheckBox.h b/Client/sdk/gui/CGUICheckBox.h index b800e712b87..5f4950f9ae6 100644 --- a/Client/sdk/gui/CGUICheckBox.h +++ b/Client/sdk/gui/CGUICheckBox.h @@ -17,7 +17,7 @@ class CGUICheckBox : public CGUIElement { public: - virtual ~CGUICheckBox(){}; + virtual ~CGUICheckBox() {}; virtual void SetSelected(bool bSelected) = 0; virtual bool GetSelected() = 0; diff --git a/Client/sdk/gui/CGUIComboBox.h b/Client/sdk/gui/CGUIComboBox.h index ae8c54f2b34..253d4803892 100644 --- a/Client/sdk/gui/CGUIComboBox.h +++ b/Client/sdk/gui/CGUIComboBox.h @@ -17,7 +17,7 @@ class CGUIComboBox : public CGUIElement { public: - virtual ~CGUIComboBox(){}; + virtual ~CGUIComboBox() {}; virtual void SetReadOnly(bool bRead) = 0; virtual CGUIListItem* AddItem(const char* szText) = 0; diff --git a/Client/sdk/gui/CGUIEdit.h b/Client/sdk/gui/CGUIEdit.h index 3126be3acc6..836cbcf4bd5 100644 --- a/Client/sdk/gui/CGUIEdit.h +++ b/Client/sdk/gui/CGUIEdit.h @@ -17,7 +17,7 @@ class CGUIEdit : public CGUIElement { public: - virtual ~CGUIEdit(){}; + virtual ~CGUIEdit() {}; virtual void SetReadOnly(bool bReadOnly) = 0; virtual bool IsReadOnly() = 0; diff --git a/Client/sdk/gui/CGUIElement.h b/Client/sdk/gui/CGUIElement.h index f6e93103be8..309a2f47360 100644 --- a/Client/sdk/gui/CGUIElement.h +++ b/Client/sdk/gui/CGUIElement.h @@ -47,7 +47,7 @@ enum eCGUIType class CGUIElement { public: - virtual ~CGUIElement(){}; + virtual ~CGUIElement() {}; virtual void SetVisible(bool bVisible) = 0; virtual bool IsVisible() = 0; diff --git a/Client/sdk/gui/CGUIFont.h b/Client/sdk/gui/CGUIFont.h index 27b52fc2155..76b946a6d74 100644 --- a/Client/sdk/gui/CGUIFont.h +++ b/Client/sdk/gui/CGUIFont.h @@ -16,7 +16,7 @@ class CGUIFont { public: - virtual ~CGUIFont(){}; + virtual ~CGUIFont() {}; virtual void SetAntiAliasingEnabled(bool bAntialiased) = 0; virtual bool IsAntiAliasingEnabled() = 0; diff --git a/Client/sdk/gui/CGUIGridList.h b/Client/sdk/gui/CGUIGridList.h index 49a3371c52e..8d3ad38f088 100644 --- a/Client/sdk/gui/CGUIGridList.h +++ b/Client/sdk/gui/CGUIGridList.h @@ -50,7 +50,7 @@ using SortDirections::SortDirection; class CGUIGridList : public CGUIElement { public: - virtual ~CGUIGridList(){}; + virtual ~CGUIGridList() {}; virtual unsigned int AddColumn(const char* szTitle, float fWidth) = 0; virtual void RemoveColumn(unsigned int uiColumn) = 0; diff --git a/Client/sdk/gui/CGUILabel.h b/Client/sdk/gui/CGUILabel.h index 0bbefd93a24..cebc2d4eec8 100644 --- a/Client/sdk/gui/CGUILabel.h +++ b/Client/sdk/gui/CGUILabel.h @@ -16,7 +16,7 @@ class CGUILabel : public CGUIElement { public: - virtual ~CGUILabel(){}; + virtual ~CGUILabel() {}; virtual void SetText(const char* Text) = 0; diff --git a/Client/sdk/gui/CGUIListItem.h b/Client/sdk/gui/CGUIListItem.h index 5c0d34af163..74abe4c167b 100644 --- a/Client/sdk/gui/CGUIListItem.h +++ b/Client/sdk/gui/CGUIListItem.h @@ -17,7 +17,7 @@ class CGUIListItem { public: - virtual ~CGUIListItem(){}; + virtual ~CGUIListItem() {}; virtual std::string GetText() const = 0; virtual void SetText(const char* pszText, const char* pszSortText = NULL) = 0; diff --git a/Client/sdk/gui/CGUIMemo.h b/Client/sdk/gui/CGUIMemo.h index 8a42249d73a..a8160b33f1c 100644 --- a/Client/sdk/gui/CGUIMemo.h +++ b/Client/sdk/gui/CGUIMemo.h @@ -17,7 +17,7 @@ class CGUIMemo : public CGUIElement { public: - virtual ~CGUIMemo(){}; + virtual ~CGUIMemo() {}; virtual void SetReadOnly(bool bReadOnly) = 0; virtual bool IsReadOnly() = 0; diff --git a/Client/sdk/gui/CGUIMessageBox.h b/Client/sdk/gui/CGUIMessageBox.h index 31639266c06..8178303afa5 100644 --- a/Client/sdk/gui/CGUIMessageBox.h +++ b/Client/sdk/gui/CGUIMessageBox.h @@ -18,7 +18,7 @@ class CGUIMessageBox { public: - virtual ~CGUIMessageBox(){}; + virtual ~CGUIMessageBox() {}; virtual void SetAutoDestroy(bool bAutoDestroy) = 0; virtual bool GetAutoDestroy() = 0; diff --git a/Client/sdk/gui/CGUIProgressBar.h b/Client/sdk/gui/CGUIProgressBar.h index b100a58a309..abea94bf50f 100644 --- a/Client/sdk/gui/CGUIProgressBar.h +++ b/Client/sdk/gui/CGUIProgressBar.h @@ -17,7 +17,7 @@ class CGUIProgressBar : public CGUIElement { public: - virtual ~CGUIProgressBar(){}; + virtual ~CGUIProgressBar() {}; virtual void SetProgress(float fProgress) = 0; virtual float GetProgress() = 0; diff --git a/Client/sdk/gui/CGUIRadioButton.h b/Client/sdk/gui/CGUIRadioButton.h index 3d29bfe555e..b0a34c813ad 100644 --- a/Client/sdk/gui/CGUIRadioButton.h +++ b/Client/sdk/gui/CGUIRadioButton.h @@ -17,7 +17,7 @@ class CGUIRadioButton : public CGUIElement { public: - virtual ~CGUIRadioButton(){}; + virtual ~CGUIRadioButton() {}; virtual void SetSelected(bool bSelected) = 0; virtual bool GetSelected() = 0; diff --git a/Client/sdk/gui/CGUIScrollBar.h b/Client/sdk/gui/CGUIScrollBar.h index 67dcc752334..92740157344 100644 --- a/Client/sdk/gui/CGUIScrollBar.h +++ b/Client/sdk/gui/CGUIScrollBar.h @@ -17,7 +17,7 @@ class CGUIScrollBar : public CGUIElement { public: - virtual ~CGUIScrollBar(){}; + virtual ~CGUIScrollBar() {}; virtual void SetOnScrollHandler(const GUI_CALLBACK& Callback) = 0; diff --git a/Client/sdk/gui/CGUIScrollPane.h b/Client/sdk/gui/CGUIScrollPane.h index 1947d826b92..3a898d9fdc9 100644 --- a/Client/sdk/gui/CGUIScrollPane.h +++ b/Client/sdk/gui/CGUIScrollPane.h @@ -16,7 +16,7 @@ class CGUIScrollPane : public CGUIElement { public: - virtual ~CGUIScrollPane(){}; + virtual ~CGUIScrollPane() {}; virtual void SetHorizontalScrollBar(bool bEnabled) = 0; virtual void SetVerticalScrollBar(bool bEnabled) = 0; diff --git a/Client/sdk/gui/CGUIStaticImage.h b/Client/sdk/gui/CGUIStaticImage.h index 0ec5734d146..8f9c8052c90 100644 --- a/Client/sdk/gui/CGUIStaticImage.h +++ b/Client/sdk/gui/CGUIStaticImage.h @@ -17,7 +17,7 @@ class CGUIStaticImage : public CGUIElement { public: - virtual ~CGUIStaticImage(){}; + virtual ~CGUIStaticImage() {}; virtual bool LoadFromFile(const char* szFilename) = 0; virtual bool LoadFromTexture(CGUITexture* pTexture) = 0; diff --git a/Client/sdk/gui/CGUITab.h b/Client/sdk/gui/CGUITab.h index 2ec0b6f616c..2b5e4685fad 100644 --- a/Client/sdk/gui/CGUITab.h +++ b/Client/sdk/gui/CGUITab.h @@ -16,7 +16,7 @@ class CGUITab : public CGUIElement { public: - virtual ~CGUITab(){}; + virtual ~CGUITab() {}; virtual void SetCaption(const char* szCaption) = 0; }; diff --git a/Client/sdk/gui/CGUITabPanel.h b/Client/sdk/gui/CGUITabPanel.h index a178e19c49a..4b875027ab6 100644 --- a/Client/sdk/gui/CGUITabPanel.h +++ b/Client/sdk/gui/CGUITabPanel.h @@ -17,7 +17,7 @@ class CGUITabPanel : public CGUIElement { public: - virtual ~CGUITabPanel(){}; + virtual ~CGUITabPanel() {}; virtual CGUITab* CreateTab(const char* szCaption) = 0; virtual void DeleteTab(CGUITab* pTab) = 0; diff --git a/Client/sdk/gui/CGUITexture.h b/Client/sdk/gui/CGUITexture.h index e613da25d03..adb9ef2665f 100644 --- a/Client/sdk/gui/CGUITexture.h +++ b/Client/sdk/gui/CGUITexture.h @@ -18,7 +18,7 @@ struct IDirect3DTexture9; class CGUITexture { public: - virtual ~CGUITexture(){}; + virtual ~CGUITexture() {}; virtual bool LoadFromFile(const char* szFilename) = 0; virtual void LoadFromMemory(const void* pBuffer, unsigned int uiWidth, unsigned int uiHeight) = 0; diff --git a/Client/sdk/gui/CGUITypes.h b/Client/sdk/gui/CGUITypes.h index 3a43cfc9dd5..2bb2f46c1a8 100644 --- a/Client/sdk/gui/CGUITypes.h +++ b/Client/sdk/gui/CGUITypes.h @@ -17,7 +17,7 @@ #include #ifndef NULL -#define NULL 0 + #define NULL 0 #endif typedef int CGUIHandle; @@ -40,7 +40,7 @@ enum CGUIMouseInput CGUI_MI_MOUSEWHEEL }; -enum CGUIMouseButton // Synchronized with CEGUI::MouseButton in ceguiinputevent.h +enum CGUIMouseButton // Synchronized with CEGUI::MouseButton in ceguiinputevent.h { LeftButton, RightButton, @@ -100,8 +100,8 @@ struct CGUIMouse MiddleButton, X1Button, X2Button, - MouseButtonCount, // #include - // DOESNT WORK FOR 64-BIT APPS ! +// DOESNT WORK FOR 64-BIT APPS ! - #pragma warning ( disable:4311 ) - #pragma warning ( disable:4312 ) + #pragma warning(disable : 4311) + #pragma warning(disable : 4312) extern bool g_bBoundsChecker; extern DWORD* g_Table; diff --git a/Client/sdk/multiplayer/CMultiplayer.h b/Client/sdk/multiplayer/CMultiplayer.h index e5e591ad5d3..5926e578a89 100644 --- a/Client/sdk/multiplayer/CMultiplayer.h +++ b/Client/sdk/multiplayer/CMultiplayer.h @@ -105,8 +105,8 @@ typedef void(PreFxRenderHandler)(); typedef void(PostColorFilterRenderHandler)(); typedef void(PreHudRenderHandler)(); typedef void(RenderEverythingBarRoadsHandler)(); -typedef CAnimBlendAssociationSAInterface*(AddAnimationHandler)(RpClump* pClump, AssocGroupId animGroup, AnimationId animID); -typedef CAnimBlendAssociationSAInterface*(AddAnimationAndSyncHandler)(RpClump* pClump, CAnimBlendAssociationSAInterface* pAnimAssocToSyncWith, +typedef CAnimBlendAssociationSAInterface*(AddAnimationHandler)(RpClump * pClump, AssocGroupId animGroup, AnimationId animID); +typedef CAnimBlendAssociationSAInterface*(AddAnimationAndSyncHandler)(RpClump * pClump, CAnimBlendAssociationSAInterface* pAnimAssocToSyncWith, AssocGroupId animGroup, AnimationId animID); typedef void(CAnimBlendAssocDestructorHandler)(CAnimBlendAssociationSAInterface* pThis); typedef bool(AssocGroupCopyAnimationHandler)(CAnimBlendAssociationSAInterface* pAnimAssoc, RpClump* pClump, CAnimBlendAssocGroupSAInterface* pAnimAssocGroup, @@ -311,17 +311,17 @@ class CMultiplayer virtual int GetMoonSize() = 0; virtual void ResetMoonSize() = 0; - virtual void GetAmbientColor(float& red, float& green, float& blue) const = 0; - virtual bool SetAmbientColor(float red, float green, float blue) = 0; - virtual bool ResetAmbientColor() = 0; + virtual void GetAmbientColor(float& red, float& green, float& blue) const = 0; + virtual bool SetAmbientColor(float red, float green, float blue) = 0; + virtual bool ResetAmbientColor() = 0; - virtual void GetAmbientObjectColor(float& red, float& green, float& blue) const = 0; - virtual bool SetAmbientObjectColor(float red, float green, float blue) = 0; - virtual bool ResetAmbientObjectColor() = 0; + virtual void GetAmbientObjectColor(float& red, float& green, float& blue) const = 0; + virtual bool SetAmbientObjectColor(float red, float green, float blue) = 0; + virtual bool ResetAmbientObjectColor() = 0; - virtual void GetDirectionalColor(float& red, float& green, float& blue) const = 0; - virtual bool SetDirectionalColor(float red, float green, float blue) = 0; - virtual bool ResetDirectionalColor() = 0; + virtual void GetDirectionalColor(float& red, float& green, float& blue) const = 0; + virtual bool SetDirectionalColor(float red, float green, float blue) = 0; + virtual bool ResetDirectionalColor() = 0; virtual float GetSpriteSize() const = 0; virtual bool SetSpriteSize(float size) = 0; @@ -347,13 +347,13 @@ class CMultiplayer virtual bool SetLightsOnGroundBrightness(float brightness) = 0; virtual bool ResetLightsOnGroundBrightness() = 0; - virtual void GetLowCloudsColor(int16& red, int16& green, int16& blue) const = 0; - virtual bool SetLowCloudsColor(int16 red, int16 green, int16 blue) = 0; - virtual bool ResetLowCloudsColor() = 0; + virtual void GetLowCloudsColor(int16& red, int16& green, int16& blue) const = 0; + virtual bool SetLowCloudsColor(int16 red, int16 green, int16 blue) = 0; + virtual bool ResetLowCloudsColor() = 0; - virtual void GetBottomCloudsColor(int16& red, int16& green, int16& blue) const = 0; - virtual bool SetBottomCloudsColor(int16 red, int16 green, int16 blue) = 0; - virtual bool ResetBottomCloudsColor() = 0; + virtual void GetBottomCloudsColor(int16& red, int16& green, int16& blue) const = 0; + virtual bool SetBottomCloudsColor(int16 red, int16 green, int16 blue) = 0; + virtual bool ResetBottomCloudsColor() = 0; virtual float GetCloudsAlpha1() const = 0; virtual bool SetCloudsAlpha1(float alpha) = 0; diff --git a/Client/sdk/net/CNet.h b/Client/sdk/net/CNet.h index f64ec279032..2ff09c3a062 100644 --- a/Client/sdk/net/CNet.h +++ b/Client/sdk/net/CNet.h @@ -16,7 +16,7 @@ #include "net/bitstream.h" #include "net/CNetHTTPDownloadManagerInterface.h" -#define MAX_CALL_REMOTE_QUEUES 100 +#define MAX_CALL_REMOTE_QUEUES 100 namespace EDownloadMode { @@ -26,7 +26,7 @@ namespace EDownloadMode CORE_ASE_LIST, CORE_UPDATER, WEBBROWSER_LISTS, - CORE_LAST, // Download modes after this one will be reset on server disconnect + CORE_LAST, // Download modes after this one will be reset on server disconnect RESOURCE_INITIAL_FILES_INTERNAL, RESOURCE_INITIAL_FILES_EXTERNAL, RESOURCE_SINGULAR_FILES, diff --git a/Client/sdk/net/net_common.h b/Client/sdk/net/net_common.h index adfe6cd3347..20540740cf8 100644 --- a/Client/sdk/net/net_common.h +++ b/Client/sdk/net/net_common.h @@ -12,18 +12,18 @@ #pragma once #ifdef WIN32 -#include + #include #endif #include "net/bitstream.h" #include "net/packetenums.h" -#define CNET_DOWNLOAD_INVALID 65535 +#define CNET_DOWNLOAD_INVALID 65535 -#define NET_CLIENT_PORT 0 // 0 will allow it to automatically choose a port, otherwise, use the value specific -#define NET_DISCONNECT_DELAY 30 +#define NET_CLIENT_PORT 0 // 0 will allow it to automatically choose a port, otherwise, use the value specific +#define NET_DISCONNECT_DELAY 30 -#define NET_INVALID_PACKET_ID 255 +#define NET_INVALID_PACKET_ID 255 typedef bool (*PPACKETHANDLER)(unsigned char, NetBitStreamInterface&); @@ -37,11 +37,11 @@ enum NetPacketPriority enum NetPacketReliability { - PACKET_RELIABILITY_UNRELIABLE = 0, // Can arrive out of order + PACKET_RELIABILITY_UNRELIABLE = 0, // Can arrive out of order PACKET_RELIABILITY_UNRELIABLE_SEQUENCED, - PACKET_RELIABILITY_RELIABLE, // Can arrive out of order + PACKET_RELIABILITY_RELIABLE, // Can arrive out of order PACKET_RELIABILITY_RELIABLE_ORDERED, - PACKET_RELIABILITY_RELIABLE_SEQUENCED // Can drop packets + PACKET_RELIABILITY_RELIABLE_SEQUENCED // Can drop packets }; // Copy of raknet statistics diff --git a/Client/sdk/utils/XFont.h b/Client/sdk/utils/XFont.h index 7c5f62cad1e..8ed4438330f 100644 --- a/Client/sdk/utils/XFont.h +++ b/Client/sdk/utils/XFont.h @@ -32,7 +32,7 @@ #include #ifndef XFONT_H -#define XFONT_H + #define XFONT_H typedef struct _tagFONT_PROPERTIES { @@ -73,17 +73,17 @@ typedef struct _tagTT_OFFSET_TABLE typedef struct _tagTT_TABLE_DIRECTORY { - char szTag[4]; // table name - ULONG uCheckSum; // Check sum - ULONG uOffset; // Offset from beginning of file - ULONG uLength; // length of the table in bytes + char szTag[4]; // table name + ULONG uCheckSum; // Check sum + ULONG uOffset; // Offset from beginning of file + ULONG uLength; // length of the table in bytes } TT_TABLE_DIRECTORY; typedef struct _tagTT_NAME_TABLE_HEADER { - USHORT uFSelector; // format selector. Always 0 - USHORT uNRCount; // Name Records count - USHORT uStorageOffset; // Offset for strings storage, from start of the table + USHORT uFSelector; // format selector. Always 0 + USHORT uNRCount; // Name Records count + USHORT uStorageOffset; // Offset for strings storage, from start of the table } TT_NAME_TABLE_HEADER; typedef struct _tagTT_NAME_RECORD @@ -93,11 +93,11 @@ typedef struct _tagTT_NAME_RECORD USHORT uLanguageID; USHORT uNameID; USHORT uStringLength; - USHORT uStringOffset; // from start of storage area + USHORT uStringOffset; // from start of storage area } TT_NAME_RECORD; -#define SWAPWORD(x) MAKEWORD(HIBYTE(x), LOBYTE(x)) -#define SWAPLONG(x) MAKELONG(SWAPWORD(HIWORD(x)), SWAPWORD(LOWORD(x))) + #define SWAPWORD(x) MAKEWORD(HIBYTE(x), LOBYTE(x)) + #define SWAPLONG(x) MAKELONG(SWAPWORD(HIWORD(x)), SWAPWORD(LOWORD(x))) BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) { @@ -108,14 +108,14 @@ BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) HANDLE hFile = INVALID_HANDLE_VALUE; hFile = ::CreateFile(lpszFilePath, - GENERIC_READ, // | GENERIC_WRITE, + GENERIC_READ, // | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) { // Windows 8 fix hFile = ::CreateFile(lpszFilePath, - GENERIC_READ, // | GENERIC_WRITE, + GENERIC_READ, // | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); } @@ -141,7 +141,7 @@ BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) // Create a file mapping object that is the current size of the file HANDLE hMappedFile = NULL; hMappedFile = ::CreateFileMapping(hFile, NULL, - PAGE_READONLY, // PAGE_READWRITE, + PAGE_READONLY, // PAGE_READWRITE, 0, dwFileSize, NULL); if (hMappedFile == NULL) @@ -151,11 +151,11 @@ BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) return FALSE; } - LPBYTE lpMapAddress = (LPBYTE)::MapViewOfFile(hMappedFile, // handle to file-mapping object - FILE_MAP_READ, // FILE_MAP_WRITE, // access mode - 0, // high-order DWORD of offset - 0, // low-order DWORD of offset - 0); // number of bytes to map + LPBYTE lpMapAddress = (LPBYTE)::MapViewOfFile(hMappedFile, // handle to file-mapping object + FILE_MAP_READ, // FILE_MAP_WRITE, // access mode + 0, // high-order DWORD of offset + 0, // low-order DWORD of offset + 0); // number of bytes to map if (lpMapAddress == NULL) { @@ -239,7 +239,7 @@ BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) if (ttRecord.uNameID == 1 || ttRecord.uNameID == 0 || ttRecord.uNameID == 4 || ttRecord.uNameID == 7) { - int nPos = index; // f.GetPosition(); + int nPos = index; // f.GetPosition(); index = tblDir.uOffset + ttRecord.uStringOffset + ttNTHeader.uStorageOffset; @@ -321,4 +321,4 @@ BOOL GetFontProperties(LPCTSTR lpszFilePath, FONT_PROPERTIES* lpFontPropsX) return bRetVal; } -#endif //XFONT_H +#endif // XFONT_H diff --git a/Server/core/CCrashHandler.cpp b/Server/core/CCrashHandler.cpp index a1f9014de66..b808152fd10 100644 --- a/Server/core/CCrashHandler.cpp +++ b/Server/core/CCrashHandler.cpp @@ -46,9 +46,9 @@ static SString ms_strDumpPathFilename; static SString ms_strDumpPath; #ifdef WIN32 -#include -#include -#include + #include + #include + #include typedef BOOL(WINAPI* MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, @@ -63,10 +63,10 @@ void CCrashHandler::Init(const SString& strInServerPath) strServerPath = GetSystemCurrentDirectory(); ms_strDumpPath = PathJoin(strServerPath, SERVER_DUMP_PATH); - // Set a global filter - #ifdef WIN32 +// Set a global filter +#ifdef WIN32 SetCrashHandlerFilter(HandleExceptionGlobal); - #else +#else // Prepare initial dumpfile name time_t pTime = time(NULL); @@ -75,17 +75,17 @@ void CCrashHandler::Init(const SString& strInServerPath) ms_strDumpPathFilename = PathJoin(ms_strDumpPath, strFilename); MakeSureDirExists(ms_strDumpPathFilename); - #ifdef WITH_BACKTRACE_ONLY + #ifdef WITH_BACKTRACE_ONLY signal(SIGSEGV, HandleExceptionGlobal); - #else - #ifdef __APPLE__ + #else + #ifdef __APPLE__ static google_breakpad::ExceptionHandler eh(ms_strDumpPath, NULL, DumpCallback, NULL, true, NULL); - #else - google_breakpad::MinidumpDescriptor descriptor(ms_strDumpPath); + #else + google_breakpad::MinidumpDescriptor descriptor(ms_strDumpPath); static google_breakpad::ExceptionHandler eh(descriptor, NULL, DumpCallback, NULL, true, -1); - #endif #endif #endif +#endif } #ifndef WIN32 @@ -142,16 +142,16 @@ inline __attribute__((always_inline)) static void SaveBacktraceSummary() } } -// Linux/Mac crash callback when using google-breakpad -#ifdef __APPLE__ + // Linux/Mac crash callback when using google-breakpad + #ifdef __APPLE__ bool DumpCallback(const char* dump_dir, const char* minidump_id, void* context, bool succeeded) { auto path = PathJoin(dump_dir, SString("%s.dmp", minidump_id)); -#else + #else bool DumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded) { auto path = descriptor.path(); -#endif + #endif // Set inital dump file name (Safeish) File::Rename(path, ms_strDumpPathFilename); @@ -232,9 +232,9 @@ void CCrashHandler::DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionInfo if (strModuleName.length() == 0) strModuleName = "unknown"; - #ifdef _WIN64 + #ifdef _WIN64 strModuleName += "64"; - #endif + #endif SString strFilename("server_%s_%s_%08x_%x_%04d%02d%02d_%02d%02d.dmp", MTA_DM_BUILDTAG_LONG, strModuleName.c_str(), pExceptionInformation->GetAddressModuleOffset(), pExceptionInformation->GetCode() & 0xffff, SystemTime.wYear, SystemTime.wMonth, diff --git a/Server/core/CCrashHandler.h b/Server/core/CCrashHandler.h index 0c3878b6e02..7fdd3c31f6d 100644 --- a/Server/core/CCrashHandler.h +++ b/Server/core/CCrashHandler.h @@ -27,16 +27,16 @@ class CCrashHandler static void Init(const SString& strServerPath); private: - #ifdef WIN32 +#ifdef WIN32 static long WINAPI HandleExceptionGlobal(_EXCEPTION_POINTERS* pException); static void DumpMiniDump(_EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation); static void RunErrorTool(); - #else +#else static void HandleExceptionGlobal(int iSig); - #endif +#endif }; diff --git a/Server/core/CCrashHandlerAPI.cpp b/Server/core/CCrashHandlerAPI.cpp index e7edfdb52cf..ffa74272a95 100644 --- a/Server/core/CCrashHandlerAPI.cpp +++ b/Server/core/CCrashHandlerAPI.cpp @@ -27,9 +27,9 @@ CONDITIONAL COMPILATION : #include "CCrashHandlerAPI.h" #ifdef WIN32 -#ifdef _M_IX86 - #include -#endif + #ifdef _M_IX86 + #include + #endif /*////////////////////////////////////////////////////////////////////// File Scope Global Variables @@ -46,13 +46,13 @@ static LPTOP_LEVEL_EXCEPTION_FILTER g_pfnOrigFilt = NULL; // The exception handler LONG __stdcall CrashHandlerExceptionFilter(EXCEPTION_POINTERS* pExPtrs); -/*////////////////////////////////////////////////////////////////////// - Destructor Class -//////////////////////////////////////////////////////////////////////*/ -// See the note in MEMDUMPVALIDATOR.CPP about automatic classes. -// Turn off warning : initializers put in library initialization area -#pragma warning (disable : 4073) -#pragma init_seg(lib) + /*////////////////////////////////////////////////////////////////////// + Destructor Class + //////////////////////////////////////////////////////////////////////*/ + // See the note in MEMDUMPVALIDATOR.CPP about automatic classes. + // Turn off warning : initializers put in library initialization area + #pragma warning(disable : 4073) + #pragma init_seg(lib) class CleanUpCrashHandler { public: @@ -102,11 +102,12 @@ BOOL __stdcall SetCrashHandlerFilter(PFNCHFILTFN pFn) { g_pfnOrigFilt = SetUnhandledExceptionFilter(CrashHandlerExceptionFilter); -#ifdef _M_IX86 + #ifdef _M_IX86 // Stop the OS from turning off our handler // Ref: https://www.codeproject.com/Articles/154686/SetUnhandledExceptionFilter-and-the-C-C-Runtime-Li LPTOP_LEVEL_EXCEPTION_FILTER(WINAPI * RedirectedSetUnhandledExceptionFilter) - (LPTOP_LEVEL_EXCEPTION_FILTER) = [](LPTOP_LEVEL_EXCEPTION_FILTER /*ExceptionInfo*/) -> LPTOP_LEVEL_EXCEPTION_FILTER { + (LPTOP_LEVEL_EXCEPTION_FILTER) = [](LPTOP_LEVEL_EXCEPTION_FILTER /*ExceptionInfo*/) -> LPTOP_LEVEL_EXCEPTION_FILTER + { // When the CRT calls SetUnhandledExceptionFilter with NULL parameter // our handler will not get removed. return 0; @@ -115,7 +116,7 @@ BOOL __stdcall SetCrashHandlerFilter(PFNCHFILTFN pFn) "invalid type of RedirectedSetUnhandledExceptionFilter"); DetourLibraryFunction("kernel32.dll", "SetUnhandledExceptionFilter", RedirectedSetUnhandledExceptionFilter); -#endif + #endif } } return (TRUE); diff --git a/Server/core/CCrashHandlerAPI.h b/Server/core/CCrashHandlerAPI.h index c3f06e859aa..0013b541d40 100644 --- a/Server/core/CCrashHandlerAPI.h +++ b/Server/core/CCrashHandlerAPI.h @@ -21,16 +21,16 @@ Copyright (c) 1997-2000 John Robbins -- All rights reserved. #ifdef WIN32 -#ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN -#endif -#include -#define BUGSUTIL_DLLINTERFACE + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #define BUGSUTIL_DLLINTERFACE -#ifdef __cplusplus + #ifdef __cplusplus extern "C" { -#endif //__cplusplus + #endif //__cplusplus /*////////////////////////////////////////////////////////////////////// Type Definitions @@ -59,8 +59,8 @@ extern "C" ----------------------------------------------------------------------*/ BOOL BUGSUTIL_DLLINTERFACE __stdcall SetCrashHandlerFilter(PFNCHFILTFN pFn); -#ifdef __cplusplus + #ifdef __cplusplus } -#endif //__cplusplus + #endif //__cplusplus #endif diff --git a/Server/core/CDynamicLibrary.cpp b/Server/core/CDynamicLibrary.cpp index 7da19be2f8c..711f938bbcf 100644 --- a/Server/core/CDynamicLibrary.cpp +++ b/Server/core/CDynamicLibrary.cpp @@ -56,8 +56,8 @@ bool CDynamicLibrary::Load(const char* szFilename) #endif - // Load the new library - #ifdef WIN32 +// Load the new library +#ifdef WIN32 m_hModule = LoadLibraryEx(szFilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); // Failed? @@ -76,7 +76,7 @@ bool CDynamicLibrary::Load(const char* szFilename) // Free the error message buffer LocalFree(lpMsgBuf); } - #else +#else m_hModule = dlopen(szFilename, RTLD_NOW); // Output error if needed @@ -88,7 +88,7 @@ bool CDynamicLibrary::Load(const char* szFilename) else Print("Loading %s failed\n", szFilename); } - #endif +#endif // Check for version mismatch if (!CheckMtaVersion(ExtractFilename(szFilename))) @@ -105,11 +105,11 @@ void CDynamicLibrary::Unload() // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 FreeLibrary(m_hModule); - #else +#else dlclose(m_hModule); - #endif +#endif // Zero out our library as it's no longer valid m_hModule = 0; @@ -126,9 +126,9 @@ FuncPtr_t CDynamicLibrary::GetProcedureAddress(const char* szProcName) // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 return reinterpret_cast(static_cast(GetProcAddress(m_hModule, szProcName))); - #else +#else char* szError = NULL; dlerror(); @@ -139,7 +139,7 @@ FuncPtr_t CDynamicLibrary::GetProcedureAddress(const char* szProcName) } return pFunc; - #endif +#endif } return NULL; @@ -149,7 +149,7 @@ bool CDynamicLibrary::CheckMtaVersion(const char* szLibName) { #if MTASA_VERSION_TYPE >= VERSION_TYPE_UNSTABLE // define MTASA_SKIP_VERSION_CHECKS in "Shared/build_overrides.h" to skip version checks -#ifndef MTASA_SKIP_VERSION_CHECKS + #ifndef MTASA_SKIP_VERSION_CHECKS if (m_hModule == 0) return false; @@ -179,7 +179,7 @@ bool CDynamicLibrary::CheckMtaVersion(const char* szLibName) return false; } -#endif + #endif #endif return true; } diff --git a/Server/core/CDynamicLibrary.h b/Server/core/CDynamicLibrary.h index ab65575adb7..8323bb1035b 100644 --- a/Server/core/CDynamicLibrary.h +++ b/Server/core/CDynamicLibrary.h @@ -12,7 +12,7 @@ #pragma once #ifdef WIN32 -#include + #include #endif typedef void (*FuncPtr_t)(); @@ -31,9 +31,9 @@ class CDynamicLibrary bool CheckMtaVersion(const char* szLibName); private: - #ifdef WIN32 +#ifdef WIN32 HMODULE m_hModule; - #else +#else void* m_hModule; - #endif +#endif }; diff --git a/Server/core/CExceptionInformation_Impl.h b/Server/core/CExceptionInformation_Impl.h index f4ff0863318..189797f612a 100644 --- a/Server/core/CExceptionInformation_Impl.h +++ b/Server/core/CExceptionInformation_Impl.h @@ -18,7 +18,7 @@ class CExceptionInformation_Impl : public CExceptionInformation { public: CExceptionInformation_Impl(); - ~CExceptionInformation_Impl(); // {}; + ~CExceptionInformation_Impl(); // {}; unsigned int GetCode() { return m_uiCode; }; void* GetAddress() { return m_pAddress; }; diff --git a/Server/core/CModManagerImpl.cpp b/Server/core/CModManagerImpl.cpp index a4742016eee..9a79f9ac0f1 100644 --- a/Server/core/CModManagerImpl.cpp +++ b/Server/core/CModManagerImpl.cpp @@ -73,8 +73,8 @@ bool CModManagerImpl::Load(const char* szModName, int iArgumentCount, char* szAr return false; } - // Grab the initialization procedure - #pragma warning(suppress: 4191) +// Grab the initialization procedure +#pragma warning(suppress : 4191) auto pfnInitServer = reinterpret_cast(m_Library.GetProcedureAddress("InitServer")); if (!pfnInitServer) { diff --git a/Server/core/CModManagerImpl.h b/Server/core/CModManagerImpl.h index 272cef87a3d..1dfaedcb9ab 100644 --- a/Server/core/CModManagerImpl.h +++ b/Server/core/CModManagerImpl.h @@ -62,6 +62,6 @@ class CModManagerImpl : public CModManager CServerBase* m_pBase; CDynamicLibrary m_Library; - SString m_strServerPath; // Root path - SString m_strModPath; // root/mods/deathmatch + SString m_strServerPath; // Root path + SString m_strModPath; // root/mods/deathmatch }; diff --git a/Server/core/CServerImpl.cpp b/Server/core/CServerImpl.cpp index ed5c3349ac4..9ccf23b2e2a 100644 --- a/Server/core/CServerImpl.cpp +++ b/Server/core/CServerImpl.cpp @@ -48,7 +48,7 @@ bool IsCursesActive() return m_wndInput != NULL; } #else -bool g_isChildProcess = false; +bool g_isChildProcess = false; HANDLE g_readyEvent = nullptr; #endif @@ -58,13 +58,13 @@ CServerImpl::CServerImpl(CThreadCommandQueue* pThreadCommandQueue) CServerImpl::CServerImpl() #endif { - #ifdef WIN32 +#ifdef WIN32 m_pThreadCommandQueue = pThreadCommandQueue; m_hConsole = NULL; - #else +#else m_wndMenu = NULL; m_wndInput = NULL; - #endif +#endif // Init m_pNetwork = NULL; @@ -331,7 +331,7 @@ int CServerImpl::Run(int iArgumentCount, char* szArguments[]) { // Network module compatibility check typedef unsigned long (*PFNCHECKCOMPATIBILITY)(unsigned long, unsigned long*); - #pragma warning(suppress: 4191) +#pragma warning(suppress : 4191) auto pfnCheckCompatibility = reinterpret_cast(m_NetworkLibrary.GetProcedureAddress("CheckCompatibility")); if (!pfnCheckCompatibility || !pfnCheckCompatibility(MTA_DM_SERVER_NET_MODULE_VERSION, (unsigned long*)MTASA_VERSION_TYPE)) { @@ -352,12 +352,12 @@ int CServerImpl::Run(int iArgumentCount, char* szArguments[]) if (m_XMLLibrary.Load(PathJoin(m_strServerPath, SERVER_BIN_PATH, szXMLLibName))) { - #pragma warning(push) - #pragma warning(disable: 4191) +#pragma warning(push) +#pragma warning(disable : 4191) auto pfnInitNetServerInterface = (InitNetServerInterface)(m_NetworkLibrary.GetProcedureAddress("InitNetServerInterface")); auto pfnReleaseNetServerInterface = (ReleaseNetServerInterface)(m_NetworkLibrary.GetProcedureAddress("ReleaseNetServerInterface")); auto pfnInitXMLInterface = (InitXMLInterface)(m_XMLLibrary.GetProcedureAddress("InitXMLInterface")); - #pragma warning(pop) +#pragma warning(pop) if (pfnInitNetServerInterface && pfnInitXMLInterface) { @@ -368,7 +368,7 @@ int CServerImpl::Run(int iArgumentCount, char* szArguments[]) if (m_pNetwork && m_pXML) { // Make the modmanager load our mod - if (m_pModManager->Load("deathmatch", iArgumentCount, szArguments)) // Hardcoded for now + if (m_pModManager->Load("deathmatch", iArgumentCount, szArguments)) // Hardcoded for now { // Enter our mainloop MainLoop(); @@ -450,7 +450,7 @@ int CServerImpl::Run(int iArgumentCount, char* szArguments[]) void CServerImpl::MainLoop() { #ifdef WIN32 - timeBeginPeriod(1); // Change sleep resolution to 1ms + timeBeginPeriod(1); // Change sleep resolution to 1ms #endif // Loop until a termination is requested @@ -478,10 +478,10 @@ void CServerImpl::MainLoop() // Handle the interpreter input HandleInput(); - // Handle input from the secondary thread - #ifdef WIN32 +// Handle input from the secondary thread +#ifdef WIN32 m_pThreadCommandQueue->Process(m_bRequestedQuit, m_pModManager); - #endif +#endif // Pulse the modmanager m_pModManager->DoPulse(); @@ -502,7 +502,7 @@ void CServerImpl::MainLoop() } #ifdef WIN32 - timeEndPeriod(1); // Restore previous sleep resolution + timeEndPeriod(1); // Restore previous sleep resolution #endif // Unload the current mod @@ -557,7 +557,7 @@ void CServerImpl::ApplyFrameRateLimit(uint uiUseRate) const double dTargetTimeToUse = 1000.0 / uiUseRate; // Time now - double dTimeMs = CTickCount::Now().ToDouble(); // GetTickCount32 (); + double dTimeMs = CTickCount::Now().ToDouble(); // GetTickCount32 (); // Get delta time in ms since last frame double dTimeUsed = dTimeMs - m_dLastTimeMs; @@ -771,7 +771,7 @@ void CServerImpl::HandleInput() switch (iStdIn) { - case '\n': // Newlines and carriage returns + case '\n': // Newlines and carriage returns case '\r': #ifdef WIN32 // Echo a newline @@ -832,12 +832,12 @@ void CServerImpl::HandleInput() m_uiSelectedCommandHistoryEntry = 0; break; - case KEY_BACKSPACE: // Backspace + case KEY_BACKSPACE: // Backspace case 0x7F: if (m_uiInputCount == 0) break; - // Insert a blank space + backspace + // Insert a blank space + backspace #ifdef WIN32 Printf("%c %c", 0x08, 0x08); #else @@ -848,7 +848,7 @@ void CServerImpl::HandleInput() m_szInputBuffer[m_uiInputCount] = 0; break; -#ifdef WIN32 // WIN32: we have to use a prefix code, this routine opens an extra switch +#ifdef WIN32 // WIN32: we have to use a prefix code, this routine opens an extra switch case KEY_EXTENDED: // Color the text if (!g_bSilent && HasConsole()) @@ -901,7 +901,7 @@ void CServerImpl::HandleInput() break; } - case KEY_UP: // Up-arrow cursor + case KEY_UP: // Up-arrow cursor { // If there's nothing to select, break here if (m_vecCommandHistory.size() <= 1 || m_uiSelectedCommandHistoryEntry == 1) @@ -919,7 +919,7 @@ void CServerImpl::HandleInput() break; } - case KEY_DOWN: // Down-arrow cursor + case KEY_DOWN: // Down-arrow cursor { // If there's nothing to select, break here if (m_vecCommandHistory.size() <= 1 || m_uiSelectedCommandHistoryEntry == 0) @@ -930,13 +930,13 @@ void CServerImpl::HandleInput() break; } -#ifdef WIN32 // WIN32: Close the switch again +#ifdef WIN32 // WIN32: Close the switch again } // Restore the color if (!g_bSilent && HasConsole()) SetConsoleTextAttribute(m_hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); - break; // KEY_EXTENDED + break; // KEY_EXTENDED #endif default: diff --git a/Server/core/CServerImpl.h b/Server/core/CServerImpl.h index f5fd12d25ac..f7917b5fd5e 100644 --- a/Server/core/CServerImpl.h +++ b/Server/core/CServerImpl.h @@ -37,11 +37,11 @@ constexpr SHORT SCREEN_BUFFER_SIZE = 256; class CServerImpl : public CServerInterface { public: - #ifdef WIN32 +#ifdef WIN32 CServerImpl(CThreadCommandQueue* pThreadCommandQueue); - #else +#else CServerImpl(); - #endif +#endif ~CServerImpl(); diff --git a/Server/core/CThreadCommandQueue.cpp b/Server/core/CThreadCommandQueue.cpp index 873a1c5c574..4a20e7e4499 100644 --- a/Server/core/CThreadCommandQueue.cpp +++ b/Server/core/CThreadCommandQueue.cpp @@ -11,8 +11,8 @@ #include "StdInc.h" #ifdef WIN32 -#include "CThreadCommandQueue.h" -#include "CModManagerImpl.h" + #include "CThreadCommandQueue.h" + #include "CModManagerImpl.h" using std::string; diff --git a/Server/core/CThreadCommandQueue.h b/Server/core/CThreadCommandQueue.h index 8b43c931aea..c33078dd93d 100644 --- a/Server/core/CThreadCommandQueue.h +++ b/Server/core/CThreadCommandQueue.h @@ -13,8 +13,8 @@ #ifdef WIN32 -#include -#include + #include + #include class CThreadCommandQueue { diff --git a/Server/core/ErrorCodes.h b/Server/core/ErrorCodes.h index 4b30901b89a..1d1731fd8f3 100644 --- a/Server/core/ErrorCodes.h +++ b/Server/core/ErrorCodes.h @@ -11,8 +11,8 @@ #pragma once -#define ERROR_NO_ERROR 0 -#define ERROR_NO_NETWORK_LIBRARY 1 +#define ERROR_NO_ERROR 0 +#define ERROR_NO_NETWORK_LIBRARY 1 #define ERROR_NETWORK_LIBRARY_FAILED 2 -#define ERROR_LOADING_MOD 3 -#define ERROR_OTHER 4 +#define ERROR_LOADING_MOD 3 +#define ERROR_OTHER 4 diff --git a/Server/core/Server.cpp b/Server/core/Server.cpp index 952e432c30c..93cc2ae59ab 100644 --- a/Server/core/Server.cpp +++ b/Server/core/Server.cpp @@ -35,26 +35,26 @@ MTAEXPORT int Run(int iArgumentCount, char* szArguments[]) } } - #ifdef WIN32 +#ifdef WIN32 // Disable critical error message boxes SetErrorMode(SEM_FAILCRITICALERRORS); - #endif +#endif - #ifdef WIN_x86 +#ifdef WIN_x86 // Apply file hooks if not already done by the client bool bSkipFileHooks = false; for (int i = 1; i < iArgumentCount; i++) bSkipFileHooks |= SStringX(szArguments[i]).Contains("--clientfeedback"); if (!bSkipFileHooks) AddUtf8FileHooks(); - #endif +#endif - // Create the server - #ifdef WIN32 + // Create the server +#ifdef WIN32 CServerImpl Server(&g_CommandQueue); - #else +#else CServerImpl Server; - #endif +#endif // Run the main func int iReturn; @@ -63,10 +63,10 @@ MTAEXPORT int Run(int iArgumentCount, char* szArguments[]) iReturn = Server.Run(iArgumentCount, szArguments); } while (iReturn == SERVER_RESET_RETURN); - // Done - #ifdef WIN_x86 +// Done +#ifdef WIN_x86 RemoveUtf8FileHooks(); - #endif +#endif // Overwrite the exit code, if we are stopping gracefully without errors if (iReturn == ERROR_NO_ERROR) diff --git a/Server/core/StdInc.h b/Server/core/StdInc.h index 070a739d35a..cd370fa42ea 100644 --- a/Server/core/StdInc.h +++ b/Server/core/StdInc.h @@ -55,6 +55,6 @@ #endif #ifndef Sleep - #define Sleep(duration) usleep((duration)*1000) + #define Sleep(duration) usleep((duration) * 1000) #endif #endif diff --git a/Server/dbconmy/CDatabaseConnectionMySql.cpp b/Server/dbconmy/CDatabaseConnectionMySql.cpp index be29caf8179..de9e6b998ea 100644 --- a/Server/dbconmy/CDatabaseConnectionMySql.cpp +++ b/Server/dbconmy/CDatabaseConnectionMySql.cpp @@ -110,7 +110,7 @@ CDatabaseConnectionMySql::CDatabaseConnectionMySql(CDatabaseType* pManager, cons m_handle = mysql_init(NULL); if (m_handle) { - bool reconnect = m_bAutomaticReconnect; + bool reconnect = m_bAutomaticReconnect; uint const ssl_mode = m_bUseSSL ? SSL_MODE_REQUIRED : SSL_MODE_DISABLED; mysql_options(m_handle, MYSQL_OPT_RECONNECT, &reconnect); mysql_options(m_handle, MYSQL_OPT_SSL_MODE, &ssl_mode); diff --git a/Server/launcher/CDynamicLibrary.cpp b/Server/launcher/CDynamicLibrary.cpp index a75d0919206..9e45a3b8ee3 100644 --- a/Server/launcher/CDynamicLibrary.cpp +++ b/Server/launcher/CDynamicLibrary.cpp @@ -32,10 +32,10 @@ bool CDynamicLibrary::Load(const char* szFilename) // Unload the previous library Unload(); - // Load the new library - #ifdef WIN32 +// Load the new library +#ifdef WIN32 m_hModule = LoadLibrary(szFilename); - #else +#else m_hModule = dlopen(szFilename, RTLD_NOW); // Output error if needed @@ -43,7 +43,7 @@ bool CDynamicLibrary::Load(const char* szFilename) { printf("%s\n", dlerror()); } - #endif +#endif // Return whether we succeeded or not return m_hModule != 0; @@ -54,11 +54,11 @@ void CDynamicLibrary::Unload() // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 FreeLibrary(m_hModule); - #else +#else dlclose(m_hModule); - #endif +#endif // Zero out our library as it's no longer valid m_hModule = 0; @@ -75,9 +75,9 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 return GetProcAddress(m_hModule, szProcName); - #else +#else char* szError = NULL; dlerror(); @@ -88,7 +88,7 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) } return pFunc; - #endif +#endif } return NULL; diff --git a/Server/launcher/CDynamicLibrary.h b/Server/launcher/CDynamicLibrary.h index 32530629712..7549ec0e89a 100644 --- a/Server/launcher/CDynamicLibrary.h +++ b/Server/launcher/CDynamicLibrary.h @@ -12,9 +12,9 @@ #pragma once #ifdef WIN32 -#include + #include #else -#include + #include #endif class CDynamicLibrary @@ -30,9 +30,9 @@ class CDynamicLibrary void* GetProcedureAddress(const char* szProcName); private: - #ifdef WIN32 +#ifdef WIN32 HMODULE m_hModule; - #else +#else void* m_hModule; - #endif +#endif }; diff --git a/Server/launcher/Main.cpp b/Server/launcher/Main.cpp index 82806513499..e0733c1c813 100644 --- a/Server/launcher/Main.cpp +++ b/Server/launcher/Main.cpp @@ -113,14 +113,14 @@ int main(int argc, char* argv[]) FILE* fh = File::Fopen(LIB_CORE, "r"); if (!fh) { - #ifdef WIN32 +#ifdef WIN32 wchar_t szBuffer[64000]; GetModuleFileNameW(NULL, szBuffer, 64000); PathRemoveFileSpecW(szBuffer); SetCurrentDirectoryW(szBuffer); - #else +#else chdir(strLaunchDirectory); - #endif +#endif } else fclose(fh); diff --git a/Server/launcher/resource.h b/Server/launcher/resource.h index a2ed40b8252..f3df8e2c143 100644 --- a/Server/launcher/resource.h +++ b/Server/launcher/resource.h @@ -2,15 +2,15 @@ // Microsoft Visual C++ generated include file. // Used by Server - Launcher.rc // -#define IDI_ICON1 110 +#define IDI_ICON1 110 // Next default values for new objects // #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif + #ifndef APSTUDIO_READONLY_SYMBOLS + #define _APS_NEXT_RESOURCE_VALUE 101 + #define _APS_NEXT_COMMAND_VALUE 40001 + #define _APS_NEXT_CONTROL_VALUE 1001 + #define _APS_NEXT_SYMED_VALUE 101 + #endif #endif diff --git a/Server/mods/deathmatch/CServer.cpp b/Server/mods/deathmatch/CServer.cpp index 3db2a2d7f86..9f88916f45e 100644 --- a/Server/mods/deathmatch/CServer.cpp +++ b/Server/mods/deathmatch/CServer.cpp @@ -43,9 +43,9 @@ void CServer::ServerInitialize(CServerInterface* pServerInterface) g_pServerInterface = pServerInterface; g_pNetServer = pServerInterface->GetNetwork(); g_pRealNetServer = g_pNetServer; - #if defined(MTA_DEBUG) +#if defined(MTA_DEBUG) SharedUtil_Tests(); - #endif +#endif } bool CServer::ServerStartup(int iArgumentCount, char* szArguments[]) diff --git a/Server/mods/deathmatch/Config.h b/Server/mods/deathmatch/Config.h index 5a368934fc3..d857a680489 100644 --- a/Server/mods/deathmatch/Config.h +++ b/Server/mods/deathmatch/Config.h @@ -39,7 +39,7 @@ // Min and max number of characters in chat echos #define MIN_CHATECHO_LENGTH 1 -#define MAX_CHATECHO_LENGTH (MAX_CHAT_LENGTH + MAX_PLAYER_NICK_LENGTH + 2) // +2 is for ": " between player nick and the message +#define MAX_CHATECHO_LENGTH (MAX_CHAT_LENGTH + MAX_PLAYER_NICK_LENGTH + 2) // +2 is for ": " between player nick and the message // Min and max number of characters in outputChatBox from the server #define MIN_OUTPUTCHATBOX_LENGTH 1 @@ -89,41 +89,41 @@ #define GAME_TYPE_STRING "MTA:SA" // Banlist filename -#define FILENAME_BANLIST "banlist.xml" +#define FILENAME_BANLIST "banlist.xml" // Settings filename -#define FILENAME_SETTINGS "settings.xml" +#define FILENAME_SETTINGS "settings.xml" // Settings root-node -#define ROOTNODE_SETTINGS "settings" +#define ROOTNODE_SETTINGS "settings" // Settings prefixes and delimiters -#define SETTINGS_PREFIX_PRIVATE '@' // Private prefix -#define SETTINGS_PREFIX_PROTECTED '#' // Protected prefix -#define SETTINGS_PREFIX_PUBLIC '*' // Public prefix -#define SETTINGS_NO_PREFIX CSettings::Private // Access type when no prefix is used -#define SETTINGS_DELIMITER '.' // Delimiter +#define SETTINGS_PREFIX_PRIVATE '@' // Private prefix +#define SETTINGS_PREFIX_PROTECTED '#' // Protected prefix +#define SETTINGS_PREFIX_PUBLIC '*' // Public prefix +#define SETTINGS_NO_PREFIX CSettings::Private // Access type when no prefix is used +#define SETTINGS_DELIMITER '.' // Delimiter // Maximum length for names and values in settings registry -#define MAX_SETTINGS_LENGTH 256 +#define MAX_SETTINGS_LENGTH 256 // Maximum resource length -#define MAX_RESOURCE_LENGTH 64 +#define MAX_RESOURCE_LENGTH 64 // SQL variable placeholder (replaces with actual variable content) -#define SQL_VARIABLE_PLACEHOLDER '?' +#define SQL_VARIABLE_PLACEHOLDER '?' // Server FPS limit (in milliseconds) -#define FPS_LIMIT 16 +#define FPS_LIMIT 16 // Max garages -#define MAX_GARAGES 50 +#define MAX_GARAGES 50 // MTA master server query URL (Inputs: game port, ase port, http port, version, extra, serverip) #define QUERY_URL_MTA_MASTER_SERVER "https://master.multitheftauto.com/ase/add.php?g=%GAME%&a=%ASE%&h=%HTTP%&v=%VER%&x=%EXTRA%&ip=%IP%" // MTA port tester URL -#define PORT_TESTER_URL "https://nightly.multitheftauto.com/ports/" +#define PORT_TESTER_URL "https://nightly.multitheftauto.com/ports/" // MTA minclientversion auto update and others -#define HQCOMMS_URL "https://updatesa.multitheftauto.com/sa/server/hqcomms/" +#define HQCOMMS_URL "https://updatesa.multitheftauto.com/sa/server/hqcomms/" diff --git a/Server/mods/deathmatch/Server.cpp b/Server/mods/deathmatch/Server.cpp index 771c8e43671..246136bebce 100644 --- a/Server/mods/deathmatch/Server.cpp +++ b/Server/mods/deathmatch/Server.cpp @@ -42,7 +42,7 @@ MTAEXPORT void ReleaseServer(void) } } -#ifdef WIN32 /* Win32 DllMain entry */ +#ifdef WIN32 /* Win32 DllMain entry */ int WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, PVOID pvNothing) { diff --git a/Server/mods/deathmatch/StdInc.h b/Server/mods/deathmatch/StdInc.h index 8a845b8b2a4..3f06363f4c5 100644 --- a/Server/mods/deathmatch/StdInc.h +++ b/Server/mods/deathmatch/StdInc.h @@ -27,7 +27,7 @@ #include "MTAPlatform.h" #ifdef WIN32 -#define _WINSOCK_DEPRECATED_NO_WARNINGS + #define _WINSOCK_DEPRECATED_NO_WARNINGS // // Windows // diff --git a/Server/mods/deathmatch/logic/ASE.cpp b/Server/mods/deathmatch/logic/ASE.cpp index 204e51a86d8..8d5e1c6238d 100644 --- a/Server/mods/deathmatch/logic/ASE.cpp +++ b/Server/mods/deathmatch/logic/ASE.cpp @@ -18,13 +18,13 @@ extern "C" { - #include "ASEQuerySDK.h" +#include "ASEQuerySDK.h" } ASE* ASE::_instance = NULL; ASE::ASE(CMainConfig* pMainConfig, CPlayerManager* pPlayerManager, unsigned short usPort, const SString& strServerIPList /*, bool bLan*/) - : m_QueryDosProtect(5, 6000, 7000) // Max of 5 queries per 6 seconds, then 7 second ignore + : m_QueryDosProtect(5, 6000, 7000) // Max of 5 queries per 6 seconds, then 7 second ignore { _instance = this; m_tStartTime = time(NULL); @@ -36,15 +36,15 @@ ASE::ASE(CMainConfig* pMainConfig, CPlayerManager* pPlayerManager, unsigned shor m_uiFullLastPlayerCount = 0; m_llFullLastTime = 0; - m_lFullMinInterval = 10 * 1000; // Update full query cache after 10 seconds + m_lFullMinInterval = 10 * 1000; // Update full query cache after 10 seconds m_uiLightLastPlayerCount = 0; m_llLightLastTime = 0; - m_lLightMinInterval = 10 * 1000; // Update light query cache after 10 seconds + m_lLightMinInterval = 10 * 1000; // Update light query cache after 10 seconds m_uiXfireLightLastPlayerCount = 0; m_llXfireLightLastTime = 0; - m_lXfireLightMinInterval = 10 * 1000; // Update XFire light query cache after 10 seconds + m_lXfireLightMinInterval = 10 * 1000; // Update XFire light query cache after 10 seconds m_ulMasterServerQueryCount = 0; m_uiNumQueriesTotal = 0; @@ -123,13 +123,13 @@ bool ASE::SetPortEnabled(bool bInternetEnabled, bool bLanEnabled) return false; } - // Set it to non blocking, so we dont have to wait for a packet - #ifdef WIN32 +// Set it to non blocking, so we dont have to wait for a packet +#ifdef WIN32 unsigned long ulNonBlock = 1; ioctlsocket(newSocket, FIONBIO, &ulNonBlock); - #else +#else fcntl(newSocket, F_SETFL, fcntl(newSocket, F_GETFL) | O_NONBLOCK); - #endif +#endif m_SocketList.push_back(newSocket); } @@ -152,7 +152,7 @@ void ASE::DoPulse() m_llCurrentTime = GetTickCount64_(); m_uiCurrentPlayerCount = m_pPlayerManager->Count(); - char szBuffer[100]; // Extra bytes for future use + char szBuffer[100]; // Extra bytes for future use for (uint s = 0; s < m_SocketList.size(); s++) { @@ -176,28 +176,28 @@ void ASE::DoPulse() switch (szBuffer[0]) { case 's': - { // ASE protocol query + { // ASE protocol query m_ulMasterServerQueryCount++; strReply = QueryFullCached(); break; } case 'b': - { // Our own lighter query for ingame browser + { // Our own lighter query for ingame browser strReply = QueryLightCached(); break; } case 'r': - { // Our own lighter query for ingame browser - Release version only + { // Our own lighter query for ingame browser - Release version only strReply = QueryLightCached(); break; } case 'x': - { // Our own lighter query for xfire updates + { // Our own lighter query for xfire updates strReply = QueryXfireLightCached(); break; } case 'v': - { // MTA Version (For further possibilities to quick ping, in case we do multiply master servers) + { // MTA Version (For further possibilities to quick ping, in case we do multiply master servers) strReply = &m_strMtaAseVersion; break; } @@ -288,12 +288,12 @@ std::string ASE::QueryFull() // the flags that tell what data we carry per player ( apparently we need all set cause of GM atm ) unsigned char ucFlags = 0; - ucFlags |= 0x01; // nick - ucFlags |= 0x02; // team - ucFlags |= 0x04; // skin - ucFlags |= 0x08; // score - ucFlags |= 0x10; // ping - ucFlags |= 0x20; // time + ucFlags |= 0x01; // nick + ucFlags |= 0x02; // team + ucFlags |= 0x04; // skin + ucFlags |= 0x08; // score + ucFlags |= 0x10; // ping + ucFlags |= 0x20; // time char szTemp[256] = {'\0'}; CPlayer* pPlayer = NULL; diff --git a/Server/mods/deathmatch/logic/ASE.h b/Server/mods/deathmatch/logic/ASE.h index e6e0f041f81..556632ecec7 100644 --- a/Server/mods/deathmatch/logic/ASE.h +++ b/Server/mods/deathmatch/logic/ASE.h @@ -33,11 +33,11 @@ typedef int SOCKET; #include #include -#define MAX_ASE_GAME_TYPE_LENGTH 200 -#define MAX_ASE_MAP_NAME_LENGTH 200 -#define MAX_RULE_KEY_LENGTH 200 -#define MAX_RULE_VALUE_LENGTH 200 -#define MAX_ANNOUNCE_VALUE_LENGTH 200 +#define MAX_ASE_GAME_TYPE_LENGTH 200 +#define MAX_ASE_MAP_NAME_LENGTH 200 +#define MAX_RULE_KEY_LENGTH 200 +#define MAX_RULE_VALUE_LENGTH 200 +#define MAX_ANNOUNCE_VALUE_LENGTH 200 class CASERule; class CMainConfig; diff --git a/Server/mods/deathmatch/logic/CAccessControlListGroup.h b/Server/mods/deathmatch/logic/CAccessControlListGroup.h index 93997196726..e97776c3465 100644 --- a/Server/mods/deathmatch/logic/CAccessControlListGroup.h +++ b/Server/mods/deathmatch/logic/CAccessControlListGroup.h @@ -34,7 +34,7 @@ class CAccessControlListGroupObject m_eObjectType = eObjectType; } - virtual ~CAccessControlListGroupObject(){}; + virtual ~CAccessControlListGroupObject() {}; static SString GenerateKey(const char* szName, EObjectType eObjectType) { return SString("%s_%d", szName, (unsigned int)eObjectType); } diff --git a/Server/mods/deathmatch/logic/CAccount.cpp b/Server/mods/deathmatch/logic/CAccount.cpp index e2e82f6ce8a..40b32ebf6ac 100644 --- a/Server/mods/deathmatch/logic/CAccount.cpp +++ b/Server/mods/deathmatch/logic/CAccount.cpp @@ -34,7 +34,7 @@ CAccount::CAccount(CAccountManager* pManager, EAccountType accountType, const st m_pManager->AddToList(this); if (m_Password.SetPassword(strPassword)) - m_pManager->MarkAsChanged(this); // Save if password upgraded + m_pManager->MarkAsChanged(this); // Save if password upgraded } CAccount::~CAccount() @@ -143,7 +143,7 @@ std::shared_ptr CAccount::GetData(const std::string& strKey) break; default: - dassert(0); // It never should hit this, if so, something corrupted + dassert(0); // It never should hit this, if so, something corrupted break; } } @@ -263,9 +263,12 @@ bool CAccount::IsValidSerial(const std::string& serial) const noexcept { const std::regex serialPattern("^[A-Fa-f0-9]{32}$"); - try{ + try + { return std::regex_match(serial, serialPattern); - } catch (...) { + } + catch (...) + { return false; } } diff --git a/Server/mods/deathmatch/logic/CAccount.h b/Server/mods/deathmatch/logic/CAccount.h index 24490e6b548..49892d11659 100644 --- a/Server/mods/deathmatch/logic/CAccount.h +++ b/Server/mods/deathmatch/logic/CAccount.h @@ -27,10 +27,10 @@ class CAccountPassword enum EAccountPasswordType { - NONE, // "" (empty string) possibly means 'not a password' + NONE, // "" (empty string) possibly means 'not a password' PLAINTEXT, - MD5, // pass stored as sha256(md5)+salt+type, stored as "1" - SHA256 // pass stored as sha256(plaintext)+salt+type, stored as "0" + MD5, // pass stored as sha256(md5)+salt+type, stored as "1" + SHA256 // pass stored as sha256(plaintext)+salt+type, stored as "0" }; protected: @@ -39,7 +39,7 @@ class CAccountPassword SString m_strSha256; SString m_strSalt; - SString m_strType; // can be "1", "0" or "" as shown in EAccountPasswordType + SString m_strType; // can be "1", "0" or "" as shown in EAccountPasswordType }; enum class EAccountType diff --git a/Server/mods/deathmatch/logic/CAccountManager.cpp b/Server/mods/deathmatch/logic/CAccountManager.cpp index cb64bce6962..3f3d39a3f0e 100644 --- a/Server/mods/deathmatch/logic/CAccountManager.cpp +++ b/Server/mods/deathmatch/logic/CAccountManager.cpp @@ -21,7 +21,7 @@ #include "CMapManager.h" CAccountManager::CAccountManager(const SString& strDbPathFilename) - : m_AccountProtect(6, 30000, 60000 * 1) // Max of 6 attempts per 30 seconds, then 1 minute ignore + : m_AccountProtect(6, 30000, 60000 * 1) // Max of 6 attempts per 30 seconds, then 1 minute ignore { m_llLastTimeSaved = GetTickCount64_(); m_bChangedSinceSaved = false; @@ -591,7 +591,7 @@ bool CAccountManager::LogIn(CClient* pClient, CClient* pEchoClient, const std::s CLuaArguments Arguments; Arguments.PushAccount(pCurrentAccount); Arguments.PushAccount(pAccount); - Arguments.PushBoolean(false); // was bAutoLogin + Arguments.PushBoolean(false); // was bAutoLogin if (!pPlayer->CallEvent("onPlayerLogin", Arguments)) { // DENIED! @@ -723,7 +723,7 @@ std::shared_ptr CAccountManager::GetAccountData(CAccount* pAccount break; default: - dassert(0); // It never should hit this, if so, something corrupted + dassert(0); // It never should hit this, if so, something corrupted break; } } @@ -777,14 +777,14 @@ bool CAccountManager::CopyAccountData(CAccount* pFromAccount, CAccount* pToAccou // list to store pFromAccount data to std::map copiedData; - if (!pFromAccount->IsRegistered()) // is not registered account, retrieve data from memory + if (!pFromAccount->IsRegistered()) // is not registered account, retrieve data from memory { for (const auto& iter : *pFromAccount) { MapSet(copiedData, iter.second.GetKey(), CAccountData(iter.second.GetKey(), iter.second.GetStrValue(), iter.second.GetType())); } } - else // is registered account, retrieve from database + else // is registered account, retrieve from database { SString strKey; SString strValue; @@ -813,17 +813,17 @@ bool CAccountManager::CopyAccountData(CAccount* pFromAccount, CAccount* pToAccou } } - if (copiedData.size() > 0) // got anything to copy? + if (copiedData.size() > 0) // got anything to copy? { std::map::iterator iter = copiedData.begin(); for (; iter != copiedData.end(); iter++) { - if (!pToAccount->IsRegistered()) // store to memory + if (!pToAccount->IsRegistered()) // store to memory { pToAccount->SetData(iter->second.GetKey(), iter->second.GetStrValue(), iter->second.GetType()); } - else // store to database + else // store to database { CRegistryResult subResult; @@ -1011,7 +1011,7 @@ CAccount* CAccountManager::AddConsoleAccount(const SString& strName) CAccount* CAccountManager::AddPlayerAccount(const SString& strName, const SString& strPassword, int iUserID, const SString& strIP, const SString& strSerial, const SString& strHttpPassAppend) { - CAccount* pAccount = new CAccount(this, EAccountType::Player, strName, strPassword, iUserID, strIP, strSerial, strHttpPassAppend); + CAccount* pAccount = new CAccount(this, EAccountType::Player, strName, strPassword, iUserID, strIP, strSerial, strHttpPassAppend); CLuaArguments Arguments; Arguments.PushAccount(pAccount); g_pGame->GetMapManager()->GetRootElement()->CallEvent("onAccountCreate", Arguments); @@ -1146,7 +1146,7 @@ bool CAccountManager::IsAuthorizedSerialRequired(CAccount* pAccount) bool CAccountManager::IsHttpLoginAllowed(CAccount* pAccount, const SString& strIp) { return !g_pGame->GetConfig()->GetAuthSerialHttpEnabled() || g_pGame->GetConfig()->IsAuthSerialHttpIpException(strIp) || - !IsAuthorizedSerialRequired(pAccount) || pAccount->IsIpAuthorized(strIp); + !IsAuthorizedSerialRequired(pAccount) || pAccount->IsIpAuthorized(strIp); } // diff --git a/Server/mods/deathmatch/logic/CAccountManager.h b/Server/mods/deathmatch/logic/CAccountManager.h index c3a0b72f281..bb9e7a89d01 100644 --- a/Server/mods/deathmatch/logic/CAccountManager.h +++ b/Server/mods/deathmatch/logic/CAccountManager.h @@ -21,10 +21,10 @@ class CDatabaseManager; typedef uint SDbConnectionId; -#define GUEST_ACCOUNT_NAME "guest" -#define HTTP_GUEST_ACCOUNT_NAME "http_guest" -#define CONSOLE_ACCOUNT_NAME "Console" -#define CONSOLE_NICK_NAME "Console" +#define GUEST_ACCOUNT_NAME "guest" +#define HTTP_GUEST_ACCOUNT_NAME "http_guest" +#define CONSOLE_ACCOUNT_NAME "Console" +#define CONSOLE_NICK_NAME "Console" // // CFastList with additional name->account mapping diff --git a/Server/mods/deathmatch/logic/CBanManager.cpp b/Server/mods/deathmatch/logic/CBanManager.cpp index f4308b8ae27..6a6a760285e 100644 --- a/Server/mods/deathmatch/logic/CBanManager.cpp +++ b/Server/mods/deathmatch/logic/CBanManager.cpp @@ -224,7 +224,7 @@ CBan* CBanManager::GetBanFromIP(const char* szIP) if (a == b) { if (a == 0) - return *iter; // Full match + return *iter; // Full match } else { @@ -238,7 +238,7 @@ CBan* CBanManager::GetBanFromIP(const char* szIP) } else if (strIP == szIP) { - return *iter; // Full match + return *iter; // Full match } } return pBanWildcardMatch; diff --git a/Server/mods/deathmatch/logic/CBandwidthSettings.h b/Server/mods/deathmatch/logic/CBandwidthSettings.h index abfe7371a6d..1479402bc14 100644 --- a/Server/mods/deathmatch/logic/CBandwidthSettings.h +++ b/Server/mods/deathmatch/logic/CBandwidthSettings.h @@ -12,10 +12,10 @@ enum { - ZONE0, // Near sync - ZONE1, // Mid sync + out of fov - ZONE2, // Mid sync + way out of fov - ZONE3, // Far sync + ZONE0, // Near sync + ZONE1, // Mid sync + out of fov + ZONE2, // Mid sync + way out of fov + ZONE3, // Far sync ZONE_MAX }; @@ -95,17 +95,17 @@ struct CBandwidthSettings float fZone1Dot; float fZone2Dot; float fZone0RadiusSq; - SFixedArray ZoneUpdateIntervals; // First is always 0, next is Zone1 interval then Zone2 and Zone3 + SFixedArray ZoneUpdateIntervals; // First is always 0, next is Zone1 interval then Zone2 and Zone3 int iMaxZoneIfOtherCanSee; bool bLightSyncEnabled; protected: - float fZone0Radius; // 10 - 200 Use zone1&2 only if other player is at least this distance away - float fZone1Angle; // 90 - 350 Use zone1 if angle to other player is greater than this - float fZone2Angle; // 100 - 360 Use zone2 if angle to other player is greater than this - int iMaxZoneIfOtherCanSeeNormal; // Zone limit if other player can see us - int iMaxZoneIfOtherCanSeeBulletSync; // Zone limit if other player can see us when bullet sync is enabled - bool bBulletSyncEnabled; // Cache flag set by game + float fZone0Radius; // 10 - 200 Use zone1&2 only if other player is at least this distance away + float fZone1Angle; // 90 - 350 Use zone1 if angle to other player is greater than this + float fZone2Angle; // 100 - 360 Use zone2 if angle to other player is greater than this + int iMaxZoneIfOtherCanSeeNormal; // Zone limit if other player can see us + int iMaxZoneIfOtherCanSeeBulletSync; // Zone limit if other player can see us when bullet sync is enabled + bool bBulletSyncEnabled; // Cache flag set by game }; extern CBandwidthSettings* g_pBandwidthSettings; diff --git a/Server/mods/deathmatch/logic/CBuilding.cpp b/Server/mods/deathmatch/logic/CBuilding.cpp index 763d129c6fe..d9001e79bdb 100644 --- a/Server/mods/deathmatch/logic/CBuilding.cpp +++ b/Server/mods/deathmatch/logic/CBuilding.cpp @@ -209,4 +209,3 @@ bool CBuilding::SetLowLodBuilding(CBuilding* pNewLowLodBuilding) noexcept return true; } } - diff --git a/Server/mods/deathmatch/logic/CCameraSpatialDatabase.cpp b/Server/mods/deathmatch/logic/CCameraSpatialDatabase.cpp index f28e8dd6ba6..33c951467d8 100644 --- a/Server/mods/deathmatch/logic/CCameraSpatialDatabase.cpp +++ b/Server/mods/deathmatch/logic/CCameraSpatialDatabase.cpp @@ -25,7 +25,7 @@ namespace { CBox box; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -214,7 +214,7 @@ bool CCameraSpatialDatabaseImpl::IsValidSphere(const CSphere& sphere) return false; // Check radius within limits - if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) + if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) return false; // Check position within limits diff --git a/Server/mods/deathmatch/logic/CCameraSpatialDatabase.h b/Server/mods/deathmatch/logic/CCameraSpatialDatabase.h index bdbf2e0a5e3..687898e3f48 100644 --- a/Server/mods/deathmatch/logic/CCameraSpatialDatabase.h +++ b/Server/mods/deathmatch/logic/CCameraSpatialDatabase.h @@ -11,7 +11,7 @@ class CPlayerCamera; // Bounding sphere z position for 2d objects -#define SPATIAL_2D_Z 0 +#define SPATIAL_2D_Z 0 // Result of a Query class CCameraQueryResult : public std::vector diff --git a/Server/mods/deathmatch/logic/CColCuboid.cpp b/Server/mods/deathmatch/logic/CColCuboid.cpp index aaf043ed01c..74113e11e98 100644 --- a/Server/mods/deathmatch/logic/CColCuboid.cpp +++ b/Server/mods/deathmatch/logic/CColCuboid.cpp @@ -30,11 +30,10 @@ bool CColCuboid::DoHitDetection(const CVector& vecNowPosition) { // FIXME: What about radius? - // See if the now position is within our cube + // See if the now position is within our cube const CVector& vecPosition = GetPosition(); return (vecNowPosition.fX >= vecPosition.fX && vecNowPosition.fX <= vecPosition.fX + m_vecSize.fX && vecNowPosition.fY >= vecPosition.fY && - vecNowPosition.fY <= vecPosition.fY + m_vecSize.fY && vecNowPosition.fZ >= vecPosition.fZ && - vecNowPosition.fZ <= vecPosition.fZ + m_vecSize.fZ); + vecNowPosition.fY <= vecPosition.fY + m_vecSize.fY && vecNowPosition.fZ >= vecPosition.fZ && vecNowPosition.fZ <= vecPosition.fZ + m_vecSize.fZ); } bool CColCuboid::ReadSpecialData(const int iLine) diff --git a/Server/mods/deathmatch/logic/CColPolygon.cpp b/Server/mods/deathmatch/logic/CColPolygon.cpp index 3ba7efdeca9..fbe949fac74 100644 --- a/Server/mods/deathmatch/logic/CColPolygon.cpp +++ b/Server/mods/deathmatch/logic/CColPolygon.cpp @@ -161,8 +161,8 @@ void CColPolygon::CalculateRadius(const CVector2D& vecPoint) bool CColPolygon::IsInBounds(CVector vecPoint) { const CVector& vecPosition = GetPosition(); - float fDistanceX = vecPoint.fX - vecPosition.fX; - float fDistanceY = vecPoint.fY - vecPosition.fY; + float fDistanceX = vecPoint.fX - vecPosition.fX; + float fDistanceY = vecPoint.fY - vecPosition.fY; float fDist = sqrt(fDistanceX * fDistanceX + fDistanceY * fDistanceY); diff --git a/Server/mods/deathmatch/logic/CCommon.h b/Server/mods/deathmatch/logic/CCommon.h index 3e884862eec..41e379d6018 100644 --- a/Server/mods/deathmatch/logic/CCommon.h +++ b/Server/mods/deathmatch/logic/CCommon.h @@ -25,7 +25,7 @@ extern CServerInterface* g_pServerInterface; extern CNetServer* g_pNetServer; #define REMOTE_ADMIN_ID 254 -#define CONSOLE_ID 255 +#define CONSOLE_ID 255 #define MAX_HTTP_DOWNLOAD_URL 512 @@ -558,27 +558,27 @@ enum eWeaponProperty WEAPON_DEFAULT_COMBO, WEAPON_COMBOS_AVAILABLE, - WEAPON_FLAG_AIM_NO_AUTO, // 0x000001 - cant auto target to aim (disable automatic up/down adjustment when firing without aiming) + WEAPON_FLAG_AIM_NO_AUTO, // 0x000001 - cant auto target to aim (disable automatic up/down adjustment when firing without aiming) WEAPON_FLAG_FIRST = WEAPON_FLAG_AIM_NO_AUTO, - WEAPON_FLAG_AIM_ARM, // 0x000002 - only needs arm to aim (ie pistol/shotgun/tec9/uzi) - WEAPON_FLAG_AIM_1ST_PERSON, // 0x000004 - uses 1st person aim (ie sniper/rpg-hs - WEAPON_FLAG_AIM_FREE, // 0x000008 - can only use free aiming (ie country sniper/flame thrower/minigun/fire extinguisher) - WEAPON_FLAG_MOVE_AND_AIM, // 0x000010 - can move and aim at same time - WEAPON_FLAG_MOVE_AND_SHOOT, // 0x000020 - can move and fire at same time + WEAPON_FLAG_AIM_ARM, // 0x000002 - only needs arm to aim (ie pistol/shotgun/tec9/uzi) + WEAPON_FLAG_AIM_1ST_PERSON, // 0x000004 - uses 1st person aim (ie sniper/rpg-hs + WEAPON_FLAG_AIM_FREE, // 0x000008 - can only use free aiming (ie country sniper/flame thrower/minigun/fire extinguisher) + WEAPON_FLAG_MOVE_AND_AIM, // 0x000010 - can move and aim at same time + WEAPON_FLAG_MOVE_AND_SHOOT, // 0x000020 - can move and fire at same time WEAPON_FLAG_UNKNOWN_0040, WEAPON_FLAG_UNKNOWN_0080, - WEAPON_FLAG_TYPE_THROW, // 0x000100 - is a throwing weapon (ie satchel) - WEAPON_FLAG_TYPE_HEAVY, // 0x000200 - heavy weapon - can't jump (ie flame thrower/rpgs/minigun) - WEAPON_FLAG_TYPE_CONSTANT, // 0x000400 - fires every frame within loop (ie paint spray) - WEAPON_FLAG_TYPE_DUAL, // 0x000800 - can use 2x guns at same time (ie pistol/shotgun/tec9/uzi) - WEAPON_FLAG_ANIM_RELOAD, // 0x001000 - weapon has reload anims (ie everything except shotgun/snipers/flame thrower/rpgs/minigun/satchel) - WEAPON_FLAG_ANIM_CROUCH, // 0x002000 - weapon has crouching anims (ie everything except flame thrower/rpgs/minigun/satchel) - WEAPON_FLAG_ANIM_RELOAD_LOOP, // 0x004000 - loop from end of reload to fire loop start - WEAPON_FLAG_ANIM_RELOAD_LONG, // 0x008000 - force a longer reload time! (ie rpgs/snipers) - WEAPON_FLAG_SHOT_SLOWS, // 0x010000 - slows down (ie flame thrower) - WEAPON_FLAG_SHOT_RAND_SPEED, // 0x020000 - random speed (ie flame thrower) - WEAPON_FLAG_SHOT_ANIM_ABRUPT, // 0x040000 - force the anim to finish player after aim/fire rather than blending out (ie rpgs) - WEAPON_FLAG_SHOT_EXPANDS, // 0x080000 - expands + WEAPON_FLAG_TYPE_THROW, // 0x000100 - is a throwing weapon (ie satchel) + WEAPON_FLAG_TYPE_HEAVY, // 0x000200 - heavy weapon - can't jump (ie flame thrower/rpgs/minigun) + WEAPON_FLAG_TYPE_CONSTANT, // 0x000400 - fires every frame within loop (ie paint spray) + WEAPON_FLAG_TYPE_DUAL, // 0x000800 - can use 2x guns at same time (ie pistol/shotgun/tec9/uzi) + WEAPON_FLAG_ANIM_RELOAD, // 0x001000 - weapon has reload anims (ie everything except shotgun/snipers/flame thrower/rpgs/minigun/satchel) + WEAPON_FLAG_ANIM_CROUCH, // 0x002000 - weapon has crouching anims (ie everything except flame thrower/rpgs/minigun/satchel) + WEAPON_FLAG_ANIM_RELOAD_LOOP, // 0x004000 - loop from end of reload to fire loop start + WEAPON_FLAG_ANIM_RELOAD_LONG, // 0x008000 - force a longer reload time! (ie rpgs/snipers) + WEAPON_FLAG_SHOT_SLOWS, // 0x010000 - slows down (ie flame thrower) + WEAPON_FLAG_SHOT_RAND_SPEED, // 0x020000 - random speed (ie flame thrower) + WEAPON_FLAG_SHOT_ANIM_ABRUPT, // 0x040000 - force the anim to finish player after aim/fire rather than blending out (ie rpgs) + WEAPON_FLAG_SHOT_EXPANDS, // 0x080000 - expands WEAPON_FLAG_LAST = WEAPON_FLAG_SHOT_EXPANDS, }; @@ -587,7 +587,7 @@ enum eWeaponSkill WEAPONSKILL_POOR = 0, WEAPONSKILL_STD, WEAPONSKILL_PRO, - WEAPONSKILL_SPECIAL, // for cops using pistols differently for example + WEAPONSKILL_SPECIAL, // for cops using pistols differently for example WEAPONSKILL_MAX_NUMBER }; @@ -625,7 +625,7 @@ enum eWeaponType WEAPONTYPE_CHAINSAW, // gifts - WEAPONTYPE_DILDO1, // 10 + WEAPONTYPE_DILDO1, // 10 WEAPONTYPE_DILDO2, WEAPONTYPE_VIBE1, WEAPONTYPE_VIBE2, @@ -636,31 +636,31 @@ enum eWeaponType WEAPONTYPE_TEARGAS, WEAPONTYPE_MOLOTOV, WEAPONTYPE_ROCKET, - WEAPONTYPE_ROCKET_HS, // 20 + WEAPONTYPE_ROCKET_HS, // 20 WEAPONTYPE_FREEFALL_BOMB, // FIRST SKILL WEAPON - WEAPONTYPE_PISTOL, // handguns + WEAPONTYPE_PISTOL, // handguns WEAPONTYPE_PISTOL_SILENCED, WEAPONTYPE_DESERT_EAGLE, - WEAPONTYPE_SHOTGUN, // shotguns - WEAPONTYPE_SAWNOFF_SHOTGUN, // one handed + WEAPONTYPE_SHOTGUN, // shotguns + WEAPONTYPE_SAWNOFF_SHOTGUN, // one handed WEAPONTYPE_SPAS12_SHOTGUN, - WEAPONTYPE_MICRO_UZI, // submachine guns + WEAPONTYPE_MICRO_UZI, // submachine guns WEAPONTYPE_MP5, - WEAPONTYPE_AK47, // 30 // machine guns + WEAPONTYPE_AK47, // 30 // machine guns WEAPONTYPE_M4, - WEAPONTYPE_TEC9, // this uses stat from the micro_uzi + WEAPONTYPE_TEC9, // this uses stat from the micro_uzi // END SKILL WEAPONS - WEAPONTYPE_COUNTRYRIFLE, // rifles + WEAPONTYPE_COUNTRYRIFLE, // rifles WEAPONTYPE_SNIPERRIFLE, - WEAPONTYPE_ROCKETLAUNCHER, // specials + WEAPONTYPE_ROCKETLAUNCHER, // specials WEAPONTYPE_ROCKETLAUNCHER_HS, WEAPONTYPE_FLAMETHROWER, WEAPONTYPE_MINIGUN, WEAPONTYPE_REMOTE_SATCHEL_CHARGE, - WEAPONTYPE_DETONATOR, // 40 // plastic explosive + WEAPONTYPE_DETONATOR, // 40 // plastic explosive WEAPONTYPE_SPRAYCAN, WEAPONTYPE_EXTINGUISHER, WEAPONTYPE_CAMERA, @@ -672,12 +672,12 @@ enum eWeaponType WEAPONTYPE_ARMOUR, // these are possible ways to die WEAPONTYPE_RAMMEDBYCAR, - WEAPONTYPE_RUNOVERBYCAR, // 50 + WEAPONTYPE_RUNOVERBYCAR, // 50 WEAPONTYPE_EXPLOSION, WEAPONTYPE_UZI_DRIVEBY, WEAPONTYPE_DROWNING, WEAPONTYPE_FALL, - WEAPONTYPE_UNIDENTIFIED, // Used for damage being done + WEAPONTYPE_UNIDENTIFIED, // Used for damage being done WEAPONTYPE_ANYMELEE, WEAPONTYPE_ANYWEAPON, WEAPONTYPE_FLARE, @@ -691,15 +691,15 @@ enum eWeaponSlot WEAPONSLOT_TYPE_MELEE, WEAPONSLOT_TYPE_HANDGUN, WEAPONSLOT_TYPE_SHOTGUN, - WEAPONSLOT_TYPE_SMG, // 4 + WEAPONSLOT_TYPE_SMG, // 4 WEAPONSLOT_TYPE_MG, WEAPONSLOT_TYPE_RIFLE, WEAPONSLOT_TYPE_HEAVY, WEAPONSLOT_TYPE_THROWN, - WEAPONSLOT_TYPE_SPECIAL, // 9 - WEAPONSLOT_TYPE_GIFT, // 10 - WEAPONSLOT_TYPE_PARACHUTE, // 11 - WEAPONSLOT_TYPE_DETONATOR, // 12 + WEAPONSLOT_TYPE_SPECIAL, // 9 + WEAPONSLOT_TYPE_GIFT, // 10 + WEAPONSLOT_TYPE_PARACHUTE, // 11 + WEAPONSLOT_TYPE_DETONATOR, // 12 WEAPONSLOT_MAX }; @@ -1082,20 +1082,20 @@ DECLARE_ENUM(eJSONPrettyType); // flags used to define weapon characteristics // aiming options -#define WEAPONTYPE_CANAIM (0x000001) // can auto target to aim -#define WEAPONTYPE_CANAIMWITHARM (0x000002) // only needs arm to aim -#define WEAPONTYPE_FIRSTPERSON (0x000004) // uses 1st person aim -#define WEAPONTYPE_CANFREEAIM (0x000008) // can only use free aiming +#define WEAPONTYPE_CANAIM (0x000001) // can auto target to aim +#define WEAPONTYPE_CANAIMWITHARM (0x000002) // only needs arm to aim +#define WEAPONTYPE_FIRSTPERSON (0x000004) // uses 1st person aim +#define WEAPONTYPE_CANFREEAIM (0x000008) // can only use free aiming // movement options -#define WEAPONTYPE_MOVEAIM (0x000010) // can move and aim at same time -#define WEAPONTYPE_MOVEFIRE (0x000020) // can move and fire at same time +#define WEAPONTYPE_MOVEAIM (0x000010) // can move and aim at same time +#define WEAPONTYPE_MOVEFIRE (0x000020) // can move and fire at same time // basic characteristics -#define WEAPONTYPE_THROW (0x000100) // is a throwing weapon -#define WEAPONTYPE_HEAVY (0x000200) // heavy weapon - can't jump -#define WEAPONTYPE_CONTINUOUS_FIRE (0x000400) // fires every frame within loop (ie paint spray) -#define WEAPONTYPE_TWIN_PISTOLS (0x000800) // can use 2x guns at same time +#define WEAPONTYPE_THROW (0x000100) // is a throwing weapon +#define WEAPONTYPE_HEAVY (0x000200) // heavy weapon - can't jump +#define WEAPONTYPE_CONTINUOUS_FIRE (0x000400) // fires every frame within loop (ie paint spray) +#define WEAPONTYPE_TWIN_PISTOLS (0x000800) // can use 2x guns at same time // these are gun anim options #define WEAPONTYPE_ANIM_RELOAD (0x001000) // weapon has reload anims @@ -1104,7 +1104,7 @@ DECLARE_ENUM(eJSONPrettyType); #define WEAPONTYPE_LONG_RELOAD_TIME (0x008000) // force a longer reload time! // these are area effect/shot options -#define WEAPONTYPE_SLOWS_DOWN (0x010000) // -#define WEAPONTYPE_RANDOM_SPEED (0x020000) // +#define WEAPONTYPE_SLOWS_DOWN (0x010000) // +#define WEAPONTYPE_RANDOM_SPEED (0x020000) // #define WEAPONTYPE_FORCE_FINISH_ANIM (0x040000) // force the anim to finish player after aim/fire rather than blending out -#define WEAPONTYPE_EXPANDS (0x080000) // +#define WEAPONTYPE_EXPANDS (0x080000) // diff --git a/Server/mods/deathmatch/logic/CConnectHistory.cpp b/Server/mods/deathmatch/logic/CConnectHistory.cpp index dabd32be8b1..cd120d0fe74 100644 --- a/Server/mods/deathmatch/logic/CConnectHistory.cpp +++ b/Server/mods/deathmatch/logic/CConnectHistory.cpp @@ -73,7 +73,7 @@ CConnectHistoryItem& CConnectHistory::GetHistoryItem(const std::string& strIP) } #if MTA_DEBUG -#if 0 + #if 0 // Dump info const CConnectHistoryItem& historyItem = iter->second; if ( !historyItem.joinTimes.empty () ) @@ -86,7 +86,7 @@ CConnectHistoryItem& CConnectHistory::GetHistoryItem(const std::string& strIP) strInfo += "\n"; OutputDebugString ( strInfo ); } -#endif + #endif #endif return iter->second; diff --git a/Server/mods/deathmatch/logic/CConsoleClient.h b/Server/mods/deathmatch/logic/CConsoleClient.h index f28658b5a45..d3ff263a497 100644 --- a/Server/mods/deathmatch/logic/CConsoleClient.h +++ b/Server/mods/deathmatch/logic/CConsoleClient.h @@ -20,7 +20,7 @@ class CConsoleClient final : public CElement, public CClient { public: CConsoleClient(CConsole* pConsole); - virtual ~CConsoleClient(){}; + virtual ~CConsoleClient() {}; int GetClientType() { return CClient::CLIENT_CONSOLE; }; const char* GetNick() { return m_strNick; }; @@ -28,7 +28,7 @@ class CConsoleClient final : public CElement, public CClient void SendEcho(const char* szEcho) { CLogger::LogPrintf("%s\n", szEcho); }; void SendConsole(const char* szEcho) { CLogger::LogPrintf("%s\n", szEcho); }; - void Unlink(){}; + void Unlink() {}; protected: bool ReadSpecialData(const int iLine) override { return false; } diff --git a/Server/mods/deathmatch/logic/CConsoleCommands.cpp b/Server/mods/deathmatch/logic/CConsoleCommands.cpp index 4b678e2977b..b5801f12fa2 100644 --- a/Server/mods/deathmatch/logic/CConsoleCommands.cpp +++ b/Server/mods/deathmatch/logic/CConsoleCommands.cpp @@ -86,7 +86,8 @@ bool CConsoleCommands::StartResource(CConsole* pConsole, const char* szArguments if (!resource->IsLoaded()) { - pEchoClient->SendConsole(SString("start: Resource '%s' is loaded, but has errors (%s)", resourceName.c_str(), resource->GetFailureReason().c_str())); + pEchoClient->SendConsole( + SString("start: Resource '%s' is loaded, but has errors (%s)", resourceName.c_str(), resource->GetFailureReason().c_str())); continue; } @@ -135,7 +136,8 @@ bool CConsoleCommands::RestartResource(CConsole* pConsole, const char* szArgumen if (!resource->IsLoaded()) { - pEchoClient->SendConsole(SString("restart: Resource '%s' is loaded, but has errors (%s)", resourceName.c_str(), resource->GetFailureReason().c_str())); + pEchoClient->SendConsole( + SString("restart: Resource '%s' is loaded, but has errors (%s)", resourceName.c_str(), resource->GetFailureReason().c_str())); continue; } @@ -384,7 +386,7 @@ bool CConsoleCommands::Say(CConsole* pConsole, const char* szInArguments, CClien // Send the chat message and player pointer to the script CLuaArguments Arguments; Arguments.PushString(szArguments); - Arguments.PushNumber(MESSAGE_TYPE_PLAYER); // Normal chat + Arguments.PushNumber(MESSAGE_TYPE_PLAYER); // Normal chat bool bContinue = static_cast(pClient)->CallEvent("onPlayerChat", Arguments); if (bContinue) { @@ -519,7 +521,7 @@ bool CConsoleCommands::TeamSay(CConsole* pConsole, const char* szInArguments, CC // Send the chat message and player pointer to the script CLuaArguments Arguments; Arguments.PushString(szArguments); - Arguments.PushNumber(MESSAGE_TYPE_TEAM); // Team chat + Arguments.PushNumber(MESSAGE_TYPE_TEAM); // Team chat bool bContinue = static_cast(pClient)->CallEvent("onPlayerChat", Arguments); if (bContinue) { @@ -626,9 +628,9 @@ bool CConsoleCommands::Msg(CConsole* pConsole, const char* szInArguments, CClien // Send the message and player pointer to the script CLuaArguments Arguments; - Arguments.PushString(szArguments); // We don't want to remove this for backwards compatibility reasons + Arguments.PushString(szArguments); // We don't want to remove this for backwards compatibility reasons Arguments.PushElement(pPlayer); - Arguments.PushString(szMessage); // Fix #2135 + Arguments.PushString(szMessage); // Fix #2135 bool bContinue = pSender->CallEvent("onPlayerPrivateMessage", Arguments); if (bContinue) @@ -726,8 +728,8 @@ bool CConsoleCommands::Me(CConsole* pConsole, const char* szArguments, CClient* if (pClient->GetClientType() == CClient::CLIENT_PLAYER) { CLuaArguments Arguments; - Arguments.PushString(szArguments); // text - Arguments.PushNumber(MESSAGE_TYPE_ACTION); // Me chat + Arguments.PushString(szArguments); // text + Arguments.PushNumber(MESSAGE_TYPE_ACTION); // Me chat bool bContinue = static_cast(pClient)->CallEvent("onPlayerChat", Arguments); if (bContinue) { @@ -796,7 +798,7 @@ bool CConsoleCommands::Nick(CConsole* pConsole, const char* szArguments, CClient CLuaArguments Arguments; Arguments.PushString(pClient->GetNick()); Arguments.PushString(szNewNick); - Arguments.PushBoolean(true); // manually changed + Arguments.PushBoolean(true); // manually changed if (pPlayer->CallEvent("onPlayerChangeNick", Arguments)) { // Tell the console @@ -1295,8 +1297,8 @@ bool CConsoleCommands::DebugScript(CConsole* console, const char* arguments, CCl } CPlayer* player = static_cast(client); - int debugLevel = arguments[0] - '0'; // Convert the character to an integer (e.g., '2' -> 2) - int debugLevelCurrent = player->GetScriptDebugLevel(); + int debugLevel = arguments[0] - '0'; // Convert the character to an integer (e.g., '2' -> 2) + int debugLevelCurrent = player->GetScriptDebugLevel(); // Check if the level is the same if (debugLevel == debugLevelCurrent) diff --git a/Server/mods/deathmatch/logic/CCustomWeapon.h b/Server/mods/deathmatch/logic/CCustomWeapon.h index ef0248170a5..01cc15a0630 100644 --- a/Server/mods/deathmatch/logic/CCustomWeapon.h +++ b/Server/mods/deathmatch/logic/CCustomWeapon.h @@ -39,7 +39,7 @@ struct SLineOfSightFlags bool bCheckDummies; bool bSeeThroughStuff; bool bIgnoreSomeObjectsForCamera; - bool bShootThroughStuff; // not used for IsLineOfSightClear + bool bShootThroughStuff; // not used for IsLineOfSightClear bool bCheckCarTires; }; @@ -120,7 +120,7 @@ class CCustomWeapon final : public CObject eBone m_targetBone; int m_itargetWheel; SWeaponConfiguration m_weaponConfig; - CPlayer* m_pOwner; // For lag compensation + CPlayer* m_pOwner; // For lag compensation int m_nAmmoTotal; int m_nAmmoInClip; eWeaponState m_PreviousState; diff --git a/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp b/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp index cc9ad55a37a..00dd1387e08 100644 --- a/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp +++ b/Server/mods/deathmatch/logic/CDatabaseJobQueue.cpp @@ -66,7 +66,7 @@ class CDatabaseJobQueueImpl : public CDatabaseJobQueue // Main thread variables CThreadHandle* m_pServiceThreadHandle; std::map m_ActiveJobHandles; - std::set m_FinishedList; // Result has been used, will be deleted next pulse + std::set m_FinishedList; // Result has been used, will be deleted next pulse uint m_uiJobCountWarnThresh; uint m_uiJobCount10sMin; CElapsedTime m_JobCountElpasedTime; @@ -435,7 +435,7 @@ bool CDatabaseJobQueueImpl::FreeCommand(CDbJobData* pJobData) } if (pJobData->result.bIgnoreResult) - return false; // Already ignoring query handle + return false; // Already ignoring query handle // if in command or result queue, then put in ignore result list bool bFound; diff --git a/Server/mods/deathmatch/logic/CDatabaseManager.cpp b/Server/mods/deathmatch/logic/CDatabaseManager.cpp index b99e9681f4c..cc459bc27c6 100644 --- a/Server/mods/deathmatch/logic/CDatabaseManager.cpp +++ b/Server/mods/deathmatch/logic/CDatabaseManager.cpp @@ -680,10 +680,10 @@ CDbJobData::~CDbJobData() bool CDbJobData::SetCallback(PFN_DBRESULT pfnDbResult, void* pContext) { if (callback.bSet) - return false; // One has already been set + return false; // One has already been set if (this->stage > EJobStage::RESULT) - return false; // Too late to set a callback now + return false; // Too late to set a callback now // Set new callback.pfnDbResult = pfnDbResult; diff --git a/Server/mods/deathmatch/logic/CDatabaseManager.h b/Server/mods/deathmatch/logic/CDatabaseManager.h index b238faa70af..86963aefc68 100644 --- a/Server/mods/deathmatch/logic/CDatabaseManager.h +++ b/Server/mods/deathmatch/logic/CDatabaseManager.h @@ -17,7 +17,7 @@ #define INVALID_DB_HANDLE (0) #define DB_SQLITE_QUEUE_NAME_INTERNAL "sqlite internal" -#define DB_SQLITE_QUEUE_NAME_DEFAULT "sqlite" // Note: MySql default queue name is the host string +#define DB_SQLITE_QUEUE_NAME_DEFAULT "sqlite" // Note: MySql default queue name is the host string class CDatabaseJobQueue; typedef uint SDbConnectionId; diff --git a/Server/mods/deathmatch/logic/CDatabaseType.h b/Server/mods/deathmatch/logic/CDatabaseType.h index 45f5a16ea26..ee300c17955 100644 --- a/Server/mods/deathmatch/logic/CDatabaseType.h +++ b/Server/mods/deathmatch/logic/CDatabaseType.h @@ -74,5 +74,5 @@ CDatabaseConnection* NewDatabaseConnectionSqlite(CDatabaseType* pManager, const // Create interfaces for mysql // CDatabaseType* NewDatabaseTypeMySql(); -typedef CDatabaseConnection*(NewDatabaseConnectionMySql_t)(CDatabaseType* pManager, const SString& strHost, const SString& strUsername, +typedef CDatabaseConnection*(NewDatabaseConnectionMySql_t)(CDatabaseType * pManager, const SString& strHost, const SString& strUsername, const SString& strPassword, const SString& strOptions); diff --git a/Server/mods/deathmatch/logic/CDatabaseTypeMySql.cpp b/Server/mods/deathmatch/logic/CDatabaseTypeMySql.cpp index 2d599739465..9450670a741 100644 --- a/Server/mods/deathmatch/logic/CDatabaseTypeMySql.cpp +++ b/Server/mods/deathmatch/logic/CDatabaseTypeMySql.cpp @@ -198,8 +198,7 @@ CDatabaseConnection* CDatabaseTypeMySql::CallNewDatabaseConnectionMySql(CDatabas { SString strServerPath = g_pServerInterface->GetModManager()->GetServerPath(); m_DbconmyLib.Load(PathJoin(strServerPath, SERVER_BIN_PATH_MOD, LIB_DBCONMY)); - m_pfnNewDatabaseConnection = - reinterpret_cast(m_DbconmyLib.GetProcedureAddress("NewDatabaseConnectionMySql")); + m_pfnNewDatabaseConnection = reinterpret_cast(m_DbconmyLib.GetProcedureAddress("NewDatabaseConnectionMySql")); } if (!m_pfnNewDatabaseConnection) diff --git a/Server/mods/deathmatch/logic/CDynamicLibrary.cpp b/Server/mods/deathmatch/logic/CDynamicLibrary.cpp index c555fedb9f8..331ca2f7164 100644 --- a/Server/mods/deathmatch/logic/CDynamicLibrary.cpp +++ b/Server/mods/deathmatch/logic/CDynamicLibrary.cpp @@ -30,8 +30,8 @@ bool CDynamicLibrary::Load(const char* szFilename) // Unload the previous library Unload(); - // Load the new library - #ifdef WIN32 +// Load the new library +#ifdef WIN32 // Search at the same path for dependencies (path must be abslolute) m_hModule = LoadLibraryEx(szFilename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); @@ -43,7 +43,7 @@ bool CDynamicLibrary::Load(const char* szFilename) CLogger::ErrorPrintf("Could not load %s - %s", szFilename, szError); } - #else +#else m_hModule = dlopen(szFilename, RTLD_NOW); // Output error if needed @@ -51,7 +51,7 @@ bool CDynamicLibrary::Load(const char* szFilename) { CLogger::ErrorPrintf("Could not load %s - %s", szFilename, dlerror()); } - #endif +#endif // Return whether we succeeded or not return m_hModule != 0; @@ -62,11 +62,11 @@ void CDynamicLibrary::Unload() // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 FreeLibrary(m_hModule); - #else +#else dlclose(m_hModule); - #endif +#endif // Zero out our library as it's no longer valid m_hModule = 0; @@ -83,9 +83,9 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) // Got a module? if (m_hModule != 0) { - #ifdef WIN32 +#ifdef WIN32 return GetProcAddress(m_hModule, szProcName); - #else +#else char* szError = NULL; dlerror(); @@ -96,7 +96,7 @@ void* CDynamicLibrary::GetProcedureAddress(const char* szProcName) } return pFunc; - #endif +#endif } return NULL; diff --git a/Server/mods/deathmatch/logic/CDynamicLibrary.h b/Server/mods/deathmatch/logic/CDynamicLibrary.h index f948a7458ef..972fd47d9c6 100644 --- a/Server/mods/deathmatch/logic/CDynamicLibrary.h +++ b/Server/mods/deathmatch/logic/CDynamicLibrary.h @@ -12,9 +12,9 @@ #pragma once #ifdef WIN32 -#include + #include #else -#include + #include #endif class CDynamicLibrary @@ -30,9 +30,9 @@ class CDynamicLibrary void* GetProcedureAddress(const char* szProcName); private: - #ifdef WIN32 +#ifdef WIN32 HMODULE m_hModule; - #else +#else void* m_hModule; - #endif +#endif }; diff --git a/Server/mods/deathmatch/logic/CElement.cpp b/Server/mods/deathmatch/logic/CElement.cpp index e1d20f5f3f5..335f31491f1 100644 --- a/Server/mods/deathmatch/logic/CElement.cpp +++ b/Server/mods/deathmatch/logic/CElement.cpp @@ -30,7 +30,7 @@ extern CGame* g_pGame; #if defined(_MSC_VER) -#pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list + #pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list #endif CElement::CElement(CElement* pParent) @@ -356,7 +356,7 @@ void CElement::ClearChildren() assert(m_pParent != this); // Process our children - Move up to our parent - if (!m_Children.empty()) // This check reduces cpu usage when unloading large maps (due to recursion) + if (!m_Children.empty()) // This check reduces cpu usage when unloading large maps (due to recursion) { while (!m_Children.empty()) (*m_Children.begin())->SetParentObject(m_pParent, false); @@ -544,8 +544,8 @@ CLuaArguments* CElement::GetAllCustomData(CLuaArguments* table) auto iter = m_CustomData.IterBegin(); for (; iter != m_CustomData.IterEnd(); iter++) { - table->PushString(iter->first); // key - table->PushArgument(iter->second.Variable); // value + table->PushString(iter->first); // key + table->PushArgument(iter->second.Variable); // value } return table; @@ -769,7 +769,7 @@ bool CElement::DeleteCustomData(const CStringName& name) CLuaArguments Arguments; Arguments.PushString(name); Arguments.PushArgument(oldVariable); - Arguments.PushArgument(CLuaArgument()); // Use nil as the new value to indicate the data has been removed + Arguments.PushArgument(CLuaArgument()); // Use nil as the new value to indicate the data has been removed if (!CallEvent("onElementDataChange", Arguments)) { // Event was cancelled, restore previous value @@ -866,7 +866,7 @@ bool CElement::LoadFromCustomData(CEvents* pEvents, CXMLNode& Node) void CElement::OnSubtreeAdd(CElement* pElement) { // Call the event on the elements that references us - if (!m_ElementReferenced.empty()) // This check reduces cpu usage when loading large maps (due to recursion) + if (!m_ElementReferenced.empty()) // This check reduces cpu usage when loading large maps (due to recursion) { std::list::const_iterator iter = m_ElementReferenced.begin(); for (; iter != m_ElementReferenced.end(); iter++) @@ -885,7 +885,7 @@ void CElement::OnSubtreeAdd(CElement* pElement) void CElement::OnSubtreeRemove(CElement* pElement) { // Call the event on the elements that references us - if (!m_ElementReferenced.empty()) // This check reduces cpu usage when unloading large maps (due to recursion) + if (!m_ElementReferenced.empty()) // This check reduces cpu usage when unloading large maps (due to recursion) { std::list::const_iterator iter = m_ElementReferenced.begin(); for (; iter != m_ElementReferenced.end(); iter++) @@ -1039,7 +1039,7 @@ void CElement::CallEventNoParent(const char* szName, const CLuaArguments& Argume // Call it on all our children CElementListSnapshotRef childrenList = GetChildrenListSnapshot(); - for (CElement* pElement : *childrenList) + for (CElement* pElement : *childrenList) { if (!pElement->IsBeingDeleted()) { @@ -1199,7 +1199,7 @@ bool CElement::IsAttachedToElement(CElement* pElement, bool bRecursive) return true; if (!std::get(history.insert(pCurrent))) - break; // This should not be possible, but you never know + break; // This should not be possible, but you never know } return false; diff --git a/Server/mods/deathmatch/logic/CElement.h b/Server/mods/deathmatch/logic/CElement.h index 17e3a37ea05..f607861b0fe 100644 --- a/Server/mods/deathmatch/logic/CElement.h +++ b/Server/mods/deathmatch/logic/CElement.h @@ -25,22 +25,22 @@ // Used to check fast version of getElementsByType // #define CHECK_ENTITIES_FROM_ROOT MTA_DEBUG -#define IS_BLIP(element) ((element)->GetType()==CElement::BLIP) -#define IS_COLSHAPE(element) ((element)->GetType()==CElement::COLSHAPE) -#define IS_DUMMY(element) ((element)->GetType()==CElement::DUMMY) -#define IS_FILE(element) ((element)->GetType()==CElement::SCRIPTFILE) -#define IS_MARKER(element) ((element)->GetType()==CElement::MARKER) -#define IS_OBJECT(element) ((element)->GetType()==CElement::OBJECT) +#define IS_BLIP(element) ((element)->GetType() == CElement::BLIP) +#define IS_COLSHAPE(element) ((element)->GetType() == CElement::COLSHAPE) +#define IS_DUMMY(element) ((element)->GetType() == CElement::DUMMY) +#define IS_FILE(element) ((element)->GetType() == CElement::SCRIPTFILE) +#define IS_MARKER(element) ((element)->GetType() == CElement::MARKER) +#define IS_OBJECT(element) ((element)->GetType() == CElement::OBJECT) #define IS_PERPLAYER_ENTITY(element) ((element)->IsPerPlayerEntity()) -#define IS_PICKUP(element) ((element)->GetType()==CElement::PICKUP) -#define IS_PED(element) ((element)->GetType()==CElement::PLAYER||(element)->GetType()==CElement::PED) -#define IS_PLAYER(element) ((element)->GetType()==CElement::PLAYER) -#define IS_RADAR_AREA(element) ((element)->GetType()==CElement::RADAR_AREA) -#define IS_VEHICLE(element) ((element)->GetType()==CElement::VEHICLE) -#define IS_CONSOLE(element) ((element)->GetType()==CElement::CONSOLE) -#define IS_TEAM(element) ((element)->GetType()==CElement::TEAM) -#define IS_WATER(element) ((element)->GetType()==CElement::WATER) -#define IS_WEAPON(element) ((element)->GetType()==CElement::WEAPON) +#define IS_PICKUP(element) ((element)->GetType() == CElement::PICKUP) +#define IS_PED(element) ((element)->GetType() == CElement::PLAYER || (element)->GetType() == CElement::PED) +#define IS_PLAYER(element) ((element)->GetType() == CElement::PLAYER) +#define IS_RADAR_AREA(element) ((element)->GetType() == CElement::RADAR_AREA) +#define IS_VEHICLE(element) ((element)->GetType() == CElement::VEHICLE) +#define IS_CONSOLE(element) ((element)->GetType() == CElement::CONSOLE) +#define IS_TEAM(element) ((element)->GetType() == CElement::TEAM) +#define IS_WATER(element) ((element)->GetType() == CElement::WATER) +#define IS_WEAPON(element) ((element)->GetType() == CElement::WEAPON) class CLuaMain; @@ -84,7 +84,7 @@ class CElement ROOT, UNKNOWN, BUILDING, - _POINTLIGHTS, // client only + _POINTLIGHTS, // client only }; public: @@ -139,7 +139,8 @@ class CElement void ReadCustomData(CEvents* pEvents, CXMLNode& Node); CCustomData& GetCustomDataManager() { return m_CustomData; } - CLuaArgument* GetCustomData(const CStringName& name, bool bInheritData, ESyncType* pSyncType = nullptr, eCustomDataClientTrust* clientChangesMode = nullptr); + CLuaArgument* GetCustomData(const CStringName& name, bool bInheritData, ESyncType* pSyncType = nullptr, + eCustomDataClientTrust* clientChangesMode = nullptr); CLuaArguments* GetAllCustomData(CLuaArguments* table); bool GetCustomDataString(const CStringName& name, char* pOut, size_t sizeBuffer, bool bInheritData); bool GetCustomDataInt(const CStringName& name, int& iOut, bool bInheritData); @@ -176,7 +177,7 @@ class CElement void OnSubtreeAdd(CElement* pElement); void OnSubtreeRemove(CElement* pElement); - virtual void UpdatePerPlayer(){}; + virtual void UpdatePerPlayer() {}; void UpdatePerPlayerEntities(); void AddCollision(class CColShape* pShape) { m_Collisions.push_back(pShape); } @@ -290,8 +291,8 @@ class CElement bool m_bDoubleSided; bool m_bUpdatingSpatialData; bool m_bCallPropagationEnabled; - bool m_canBeDestroyedByScript = true; // If true, destroyElement function will - // have no effect on this element + bool m_canBeDestroyedByScript = true; // If true, destroyElement function will + // have no effect on this element // Optimization for getElementsByType starting at root public: static void StartupEntitiesFromRoot(); diff --git a/Server/mods/deathmatch/logic/CElementRefManager.cpp b/Server/mods/deathmatch/logic/CElementRefManager.cpp index 54a6a9ca9df..7388f49aad2 100644 --- a/Server/mods/deathmatch/logic/CElementRefManager.cpp +++ b/Server/mods/deathmatch/logic/CElementRefManager.cpp @@ -139,11 +139,11 @@ void CElementRefManager::OnElementDelete(CElement* pElement) { // NULL invalid pointer pOther = NULL; - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG SString* pstrDebugInfo = MapFind(ms_ElementRefListDebugInfo, &pOther); assert(pstrDebugInfo); OutputDebugLine(SString("[ElementRef] Did null %s (%08x @ %08x)", **pstrDebugInfo, pElement, &pOther)); - #endif +#endif } } } @@ -164,11 +164,11 @@ void CElementRefManager::OnElementDelete(CElement* pElement) { // Remove invalid pointer from list - TODO - Think man, think itList = rList.erase(itList); - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG SString* pstrDebugInfo = MapFind(ms_ElementRefListListDebugInfo, &rList); assert(pstrDebugInfo); OutputDebugLine(SString("[ElementRef] Did list item %s (%08x @ %08x)", **pstrDebugInfo, pElement, &rList)); - #endif +#endif } else ++itList; diff --git a/Server/mods/deathmatch/logic/CElementRefManager.h b/Server/mods/deathmatch/logic/CElementRefManager.h index 9dbbca58fdf..23cb4503706 100644 --- a/Server/mods/deathmatch/logic/CElementRefManager.h +++ b/Server/mods/deathmatch/logic/CElementRefManager.h @@ -11,11 +11,9 @@ #pragma once #ifdef MTA_DEBUG - #define ELEMENT_REF_DEBUG( ptr, desc ) \ - SString ( "%p %s", ptr, desc ) + #define ELEMENT_REF_DEBUG(ptr, desc) SString("%p %s", ptr, desc) #else - #define ELEMENT_REF_DEBUG( ptr, desc ) \ - NULL + #define ELEMENT_REF_DEBUG(ptr, desc) NULL #endif class CElement; diff --git a/Server/mods/deathmatch/logic/CEvents.cpp b/Server/mods/deathmatch/logic/CEvents.cpp index ed627d78c5b..411822ccadc 100644 --- a/Server/mods/deathmatch/logic/CEvents.cpp +++ b/Server/mods/deathmatch/logic/CEvents.cpp @@ -158,7 +158,7 @@ void CEvents::CancelEvent(bool bCancelled, const char* szReason) { // ALWAYS set the old global variable for backward compatibility m_bEventCancelled = bCancelled; - + // Also update context if it exists if (!m_ContextStack.empty()) { @@ -168,7 +168,7 @@ void CEvents::CancelEvent(bool bCancelled, const char* szReason) else pCurrentContext->Reset(); } - + if (szReason) m_strLastError = szReason; } @@ -177,7 +177,7 @@ bool CEvents::WasEventCancelled() { if (!m_ContextStack.empty()) return m_ContextStack.back()->IsCancelled(); - + return m_bEventCancelled || m_bWasEventCancelled; } diff --git a/Server/mods/deathmatch/logic/CEvents.h b/Server/mods/deathmatch/logic/CEvents.h index 3572c6f5575..adb3b57e179 100644 --- a/Server/mods/deathmatch/logic/CEvents.h +++ b/Server/mods/deathmatch/logic/CEvents.h @@ -54,10 +54,10 @@ class CEvents CFastHashMap m_EventHashMap; - std::vector m_CancelledList; - bool m_bEventCancelled; - bool m_bWasEventCancelled; - SString m_strLastError; + std::vector m_CancelledList; + bool m_bEventCancelled; + bool m_bWasEventCancelled; + SString m_strLastError; - std::vector m_ContextStack; + std::vector m_ContextStack; }; diff --git a/Server/mods/deathmatch/logic/CGame.cpp b/Server/mods/deathmatch/logic/CGame.cpp index 5807a7f3edf..0ed84294df7 100644 --- a/Server/mods/deathmatch/logic/CGame.cpp +++ b/Server/mods/deathmatch/logic/CGame.cpp @@ -154,7 +154,7 @@ void sighandler(int sig) } #endif -CGame::CGame() : m_FloodProtect(4, 30000, 30000) // Max of 4 connections per 30 seconds, then 30 second ignore +CGame::CGame() : m_FloodProtect(4, 30000, 30000) // Max of 4 connections per 30 seconds, then 30 second ignore { // Set our global pointer g_pGame = this; @@ -903,7 +903,7 @@ bool CGame::Start(int iArgumentCount, char* szArguments[]) m_pResourceManager = new CResourceManager; m_pSettings = new CSettings(m_pResourceManager); if (!m_pResourceManager->Refresh()) - return false; // Load cancelled + return false; // Load cancelled m_pUnoccupiedVehicleSync = new CUnoccupiedVehicleSync(m_pPlayerManager, m_pVehicleManager); m_pPedSync = new CPedSync(m_pPlayerManager, m_pPedManager); #ifdef WITH_OBJECT_SYNC @@ -1004,7 +1004,7 @@ bool CGame::Start(int iArgumentCount, char* szArguments[]) // Now load the rest of the config if (!m_pMainConfig->LoadExtended()) - return false; // Fail or cancelled + return false; // Fail or cancelled // Is the script debug log enabled? if (m_pMainConfig->GetScriptDebugLogEnabled()) @@ -1359,12 +1359,11 @@ void CGame::JoinPlayer(CPlayer& Player) marker.Set("Start"); // Let him join - Player.Send(CPlayerJoinCompletePacket(Player.GetID(), m_pMapManager->GetRootElement()->GetID(), m_pMainConfig->GetHTTPDownloadType(), - m_pMainConfig->GetHTTPPort(), m_pMainConfig->GetHTTPDownloadURL().c_str(), - m_pMainConfig->GetHTTPMaxConnectionsPerClient(), m_pMainConfig->GetEnableClientChecks(), - m_pMainConfig->IsVoiceEnabled(), static_cast(m_pMainConfig->GetVoiceSampleRate()), - static_cast(m_pMainConfig->GetVoiceQuality()), m_pMainConfig->GetVoiceBitrate(), - m_pMainConfig->GetServerName().c_str())); + Player.Send(CPlayerJoinCompletePacket( + Player.GetID(), m_pMapManager->GetRootElement()->GetID(), m_pMainConfig->GetHTTPDownloadType(), m_pMainConfig->GetHTTPPort(), + m_pMainConfig->GetHTTPDownloadURL().c_str(), m_pMainConfig->GetHTTPMaxConnectionsPerClient(), m_pMainConfig->GetEnableClientChecks(), + m_pMainConfig->IsVoiceEnabled(), static_cast(m_pMainConfig->GetVoiceSampleRate()), + static_cast(m_pMainConfig->GetVoiceQuality()), m_pMainConfig->GetVoiceBitrate(), m_pMainConfig->GetServerName().c_str())); marker.Set("CPlayerJoinCompletePacket"); @@ -1414,7 +1413,7 @@ void CGame::InitialDataStream(CPlayer& Player) marker.Set("PlayerNotice"); // Tell the map manager - m_pMapManager->OnPlayerJoin(Player); // This sends the elements that are needed before the resources start + m_pMapManager->OnPlayerJoin(Player); // This sends the elements that are needed before the resources start marker.Set("SendMapElements"); @@ -1675,7 +1674,8 @@ void CGame::AddBuiltInEvents() m_Events.AddEvent("onElementModelChange", "oldModel, newModel", NULL, false); m_Events.AddEvent("onElementDimensionChange", "oldDimension, newDimension", nullptr, false); m_Events.AddEvent("onElementInteriorChange", "oldInterior, newInterior", nullptr, false); - m_Events.AddEvent("onElementAttach", "attachSource, attachOffsetX, attachOffsetY, attachOffsetZ, attachOffsetRX, attachOffsetRY, attachOffsetRZ", nullptr, false); + m_Events.AddEvent("onElementAttach", "attachSource, attachOffsetX, attachOffsetY, attachOffsetZ, attachOffsetRX, attachOffsetRY, attachOffsetRZ", nullptr, + false); m_Events.AddEvent("onElementDetach", "detachSource, detachWorldX, detachWorldY, detachWorldZ, detachWorldRX, detachWorldRY, detachWorldRZ", nullptr, false); // Radar area events @@ -1728,15 +1728,15 @@ void CGame::ProcessTrafficLights(long long llCurrentTime) if (ulDiff >= 1000) { - if ((m_ucTrafficLightState == 0 || m_ucTrafficLightState == 3) && ulDiff >= 8000) // green + if ((m_ucTrafficLightState == 0 || m_ucTrafficLightState == 3) && ulDiff >= 8000) // green { ucNewState = m_ucTrafficLightState + 1; } - else if ((m_ucTrafficLightState == 1 || m_ucTrafficLightState == 4) && ulDiff >= 3000) // orange + else if ((m_ucTrafficLightState == 1 || m_ucTrafficLightState == 4) && ulDiff >= 3000) // orange { ucNewState = (m_ucTrafficLightState == 4) ? 0 : 2; } - else if (m_ucTrafficLightState == 2 && ulDiff >= 2000) // red + else if (m_ucTrafficLightState == 2 && ulDiff >= 2000) // red { ucNewState = 3; } @@ -1958,7 +1958,7 @@ void CGame::Packet_PlayerJoinData(CPlayerJoinDataPacket& Packet) if (CBan* pBan = m_pBanManager->GetBanFromIP(strIP)) { time_t Duration = pBan->GetBanTimeRemaining(); - SString strBanMessage; // = "Serial is banned"; + SString strBanMessage; // = "Serial is banned"; SString strDurationDesc = pBan->GetDurationDesc(); if (strDurationDesc.length()) strBanMessage += " (" + strDurationDesc + ")"; @@ -2255,7 +2255,7 @@ void CGame::RelayPlayerPuresync(CPacket& Packet) SViewerMapType& nearList = pPlayer->GetNearPlayerList(); // Array for holding players that need moving to the puresync far list - static std::vector moveToFarListList; // static to help reduce memory allocations + static std::vector moveToFarListList; // static to help reduce memory allocations moveToFarListList.clear(); // For each puresync near player @@ -2269,7 +2269,7 @@ void CGame::RelayPlayerPuresync(CPacket& Packet) { // Remove player from puresync near list (Has to be not near for 5 calls to get removed (The delay ensures timely updates of players moving far // away)) - if (!pPlayer->ShouldPlayerBeInNearList(pSendPlayer)) // Double check remove is required. + if (!pPlayer->ShouldPlayerBeInNearList(pSendPlayer)) // Double check remove is required. { moveToFarListList.push_back(pSendPlayer); continue; @@ -2536,8 +2536,7 @@ void CGame::Packet_Bulletsync(CBulletsyncPacket& packet) const float range = stats->GetWeaponRange(); const float rangeSq = range * range; - - const float maxRangeSq = rangeSq * 1.1f; // 10% tolerance for floating point + const float maxRangeSq = rangeSq * 1.1f; // 10% tolerance for floating point if (distanceSq > maxRangeSq) return; @@ -2672,13 +2671,12 @@ void CGame::Packet_LuaEvent(CLuaEventPacket& Packet) m_pScriptDebugging->LogError(NULL, "Client (%s) triggered serverside event %s, but event is not marked as remotely triggerable", pCaller->GetNick(), szName); } - } else { // Limit this error to prevent debug / log files being flooded. static std::uint64_t s_lastClientEventErrorLog = 0; - auto now = GetTickCount64_(); + auto now = GetTickCount64_(); if (now - s_lastClientEventErrorLog > NUM_CLIENT_EVENT_ERROR_GAP) { CLuaArguments arguments; @@ -2718,7 +2716,7 @@ void CGame::Packet_CustomData(CCustomDataPacket& Packet) return; } - ESyncType lastSyncType = ESyncType::BROADCAST; + ESyncType lastSyncType = ESyncType::BROADCAST; eCustomDataClientTrust clientChangesMode{}; pElement->GetCustomData(szName, false, &lastSyncType, &clientChangesMode); @@ -2727,8 +2725,7 @@ void CGame::Packet_CustomData(CCustomDataPacket& Packet) : clientChangesMode == eCustomDataClientTrust::ALLOW; if (!changesAllowed) { - CLogger::ErrorPrintf("Client trying to change protected element data %s (%s)\n", Packet.GetSourcePlayer()->GetNick(), - szName); + CLogger::ErrorPrintf("Client trying to change protected element data %s (%s)\n", Packet.GetSourcePlayer()->GetNick(), szName); CLuaArguments arguments; arguments.PushElement(pElement); @@ -2949,23 +2946,23 @@ void CGame::Packet_ProjectileSync(CProjectileSyncPacket& Packet) } CLuaArguments arguments; - arguments.PushNumber(Packet.m_ucWeaponType); // "weaponType" - arguments.PushNumber(vecPosition.fX); // "posX" - arguments.PushNumber(vecPosition.fY); // "posY" - arguments.PushNumber(vecPosition.fZ); // "posZ" - arguments.PushNumber(Packet.m_fForce); // "force" + arguments.PushNumber(Packet.m_ucWeaponType); // "weaponType" + arguments.PushNumber(vecPosition.fX); // "posX" + arguments.PushNumber(vecPosition.fY); // "posY" + arguments.PushNumber(vecPosition.fZ); // "posZ" + arguments.PushNumber(Packet.m_fForce); // "force" CElement* pTarget = nullptr; if (Packet.m_bHasTarget && Packet.m_TargetID != INVALID_ELEMENT_ID) pTarget = CElementIDs::GetElement(Packet.m_TargetID); - arguments.PushElement(pTarget); // "target" - arguments.PushNumber(Packet.m_vecRotation.fX); // "rotX" - arguments.PushNumber(Packet.m_vecRotation.fY); // "rotY" - arguments.PushNumber(Packet.m_vecRotation.fZ); // "rotZ" - arguments.PushNumber(Packet.m_vecMoveSpeed.fX); // "velX" - arguments.PushNumber(Packet.m_vecMoveSpeed.fY); // "velY" - arguments.PushNumber(Packet.m_vecMoveSpeed.fZ); // "velZ" + arguments.PushElement(pTarget); // "target" + arguments.PushNumber(Packet.m_vecRotation.fX); // "rotX" + arguments.PushNumber(Packet.m_vecRotation.fY); // "rotY" + arguments.PushNumber(Packet.m_vecRotation.fZ); // "rotZ" + arguments.PushNumber(Packet.m_vecMoveSpeed.fX); // "velX" + arguments.PushNumber(Packet.m_vecMoveSpeed.fY); // "velY" + arguments.PushNumber(Packet.m_vecMoveSpeed.fZ); // "velZ" // Trigger Lua event and see if we are allowed to continue if (!pPlayer->CallEvent("onPlayerProjectileCreation", arguments)) @@ -3105,7 +3102,7 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) bWarpIn = true; } if (usVehicleModel == VT_RCBARON) - { // warp in for rc baron. + { // warp in for rc baron. fCutoffDistance = 10.0f; bWarpIn = true; } @@ -3139,10 +3136,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the entering vehicle event CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(0); // seat - Arguments.PushBoolean(false); // jacked - Arguments.PushNumber(ucDoor); // Door + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(0); // seat + Arguments.PushBoolean(false); // jacked + Arguments.PushNumber(ucDoor); // Door if (pVehicle->CallEvent("onVehicleStartEnter", Arguments)) { // HACK?: check the ped's vehicle-action is still the same (not warped in?) @@ -3209,10 +3206,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the entering vehicle event CLuaArguments EnterArguments; - EnterArguments.PushElement(pPed); // player / ped - EnterArguments.PushNumber(0); // seat - EnterArguments.PushElement(pOccupant); // jacked - EnterArguments.PushNumber(ucDoor); // Door + EnterArguments.PushElement(pPed); // player / ped + EnterArguments.PushNumber(0); // seat + EnterArguments.PushElement(pOccupant); // jacked + EnterArguments.PushNumber(ucDoor); // Door if (pVehicle->CallEvent("onVehicleStartEnter", EnterArguments)) { // HACK?: check the peds vehicle-action is still the same (not warped in?) @@ -3220,9 +3217,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) { // Call the exiting vehicle event CLuaArguments ExitArguments; - ExitArguments.PushElement(pOccupant); // player / ped - ExitArguments.PushNumber(ucSeat); // seat - ExitArguments.PushElement(pPed); // jacker + ExitArguments.PushElement(pOccupant); // player / ped + ExitArguments.PushNumber(ucSeat); // seat + ExitArguments.PushElement(pPed); // jacker if (pVehicle->CallEvent("onVehicleStartExit", ExitArguments)) { // HACK?: check the player's vehicle-action is still the same (not warped out?) @@ -3271,10 +3268,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the entering vehicle event CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(ucSeat); // seat - Arguments.PushBoolean(false); // jacked - Arguments.PushNumber(ucDoor); // Door + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(ucSeat); // seat + Arguments.PushBoolean(false); // jacked + Arguments.PushNumber(ucDoor); // Door if (pVehicle->CallEvent("onVehicleStartEnter", Arguments)) { // HACK?: check the player's vehicle-action is still the same (not warped in?) @@ -3376,9 +3373,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the player->vehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(occupiedSeat); // seat - Arguments.PushBoolean(false); // jacked + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(occupiedSeat); // seat + Arguments.PushBoolean(false); // jacked if (pPed->IsPlayer()) pPed->CallEvent("onPlayerVehicleEnter", Arguments); else @@ -3386,9 +3383,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the vehicle->player event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(occupiedSeat); // seat - Arguments2.PushBoolean(false); // jacked + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(occupiedSeat); // seat + Arguments2.PushBoolean(false); // jacked pVehicle->CallEvent("onVehicleEnter", Arguments2); } } @@ -3418,7 +3415,8 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) pVehicle->SetDoorOpenRatio(ucDoor + 2, fDoorAngle); // Tell everyone he's out (they should warp him out) - CVehicleInOutPacket Reply(PedID, VehicleID, static_cast(occupiedSeat), VEHICLE_NOTIFY_IN_ABORT_RETURN, ucDoor); + CVehicleInOutPacket Reply(PedID, VehicleID, static_cast(occupiedSeat), VEHICLE_NOTIFY_IN_ABORT_RETURN, + ucDoor); Reply.SetDoorAngle(fDoorAngle); m_pPlayerManager->BroadcastOnlyJoined(Reply); } @@ -3439,13 +3437,13 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) { // Reset the occupant changed flag before calling the event pVehicle->m_bOccupantChanged = false; - + // Call the exiting vehicle event CLuaArguments Arguments; - Arguments.PushElement(pPed); // player / ped - Arguments.PushNumber(occupiedSeat); // seat - Arguments.PushBoolean(false); // jacked - Arguments.PushNumber(Packet.GetDoor()); // door being used + Arguments.PushElement(pPed); // player / ped + Arguments.PushNumber(occupiedSeat); // seat + Arguments.PushBoolean(false); // jacked + Arguments.PushNumber(Packet.GetDoor()); // door being used if (pVehicle->CallEvent("onVehicleStartExit", Arguments) && pPed->GetOccupiedVehicle() == pVehicle) { // Check if the occupant was changed during the event (e.g., by warpPedIntoVehicle) @@ -3455,7 +3453,8 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) pPed->SetVehicleAction(CPed::VEHICLEACTION_EXITING); // Tell everyone he can start exiting the vehicle - CVehicleInOutPacket Reply(PedID, VehicleID, static_cast(occupiedSeat), VEHICLE_REQUEST_OUT_CONFIRMED, Packet.GetDoor()); + CVehicleInOutPacket Reply(PedID, VehicleID, static_cast(occupiedSeat), VEHICLE_REQUEST_OUT_CONFIRMED, + Packet.GetDoor()); m_pPlayerManager->BroadcastOnlyJoined(Reply); } else @@ -3518,10 +3517,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the ped->vehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(occupiedSeat); // seat - Arguments.PushBoolean(false); // jacker - Arguments.PushBoolean(false); // forcedByScript + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(occupiedSeat); // seat + Arguments.PushBoolean(false); // jacker + Arguments.PushBoolean(false); // forcedByScript if (pPed->IsPlayer()) pPed->CallEvent("onPlayerVehicleExit", Arguments); else @@ -3529,10 +3528,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the vehicle->player event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(occupiedSeat); // seat - Arguments2.PushBoolean(false); // jacker - Arguments2.PushBoolean(false); // forcedByScript + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(occupiedSeat); // seat + Arguments2.PushBoolean(false); // jacker + Arguments2.PushBoolean(false); // forcedByScript pVehicle->CallEvent("onVehicleExit", Arguments2); } } @@ -3585,10 +3584,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the ped->vehicle event CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(occupiedSeat); // seat - Arguments.PushBoolean(false); // jacker - Arguments.PushBoolean(false); // forcedByScript + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(occupiedSeat); // seat + Arguments.PushBoolean(false); // jacker + Arguments.PushBoolean(false); // forcedByScript if (pPed->IsPlayer()) { pPed->CallEvent("onPlayerVehicleExit", Arguments); @@ -3600,17 +3599,17 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Call the vehicle->player event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(occupiedSeat); // seat - Arguments2.PushBoolean(false); // jacker - Arguments2.PushBoolean(false); // forcedByScript + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(occupiedSeat); // seat + Arguments2.PushBoolean(false); // jacker + Arguments2.PushBoolean(false); // forcedByScript pVehicle->CallEvent("onVehicleExit", Arguments2); } break; } - case VEHICLE_NOTIFY_JACK: // Finished jacking him + case VEHICLE_NOTIFY_JACK: // Finished jacking him { // Is the ped jacking? if (pPed->GetVehicleAction() == CPed::VEHICLEACTION_JACKING) @@ -3637,10 +3636,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Execute the ped->vehicle script function for the jacked ped CLuaArguments ArgumentsExit; - ArgumentsExit.PushElement(pVehicle); // vehicle - ArgumentsExit.PushNumber(0); // seat - ArgumentsExit.PushElement(pPed); // jacker - ArgumentsExit.PushBoolean(false); // forcedByScript + ArgumentsExit.PushElement(pVehicle); // vehicle + ArgumentsExit.PushNumber(0); // seat + ArgumentsExit.PushElement(pPed); // jacker + ArgumentsExit.PushBoolean(false); // forcedByScript if (pJacked->IsPlayer()) pJacked->CallEvent("onPlayerVehicleExit", ArgumentsExit); else @@ -3648,17 +3647,17 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Execute the vehicle->ped script function for the jacked ped CLuaArguments ArgumentsExit2; - ArgumentsExit2.PushElement(pJacked); // player / ped - ArgumentsExit2.PushNumber(0); // seat - ArgumentsExit2.PushElement(pPed); // jacker - ArgumentsExit2.PushBoolean(false); // forcedByScript + ArgumentsExit2.PushElement(pJacked); // player / ped + ArgumentsExit2.PushNumber(0); // seat + ArgumentsExit2.PushElement(pPed); // jacker + ArgumentsExit2.PushBoolean(false); // forcedByScript pVehicle->CallEvent("onVehicleExit", ArgumentsExit2); // Execute the ped->vehicle script function CLuaArguments ArgumentsEnter; - ArgumentsEnter.PushElement(pVehicle); // vehicle - ArgumentsEnter.PushNumber(0); // seat - ArgumentsEnter.PushElement(pJacked); // jacked + ArgumentsEnter.PushElement(pVehicle); // vehicle + ArgumentsEnter.PushNumber(0); // seat + ArgumentsEnter.PushElement(pJacked); // jacked if (pPed->IsPlayer()) pPed->CallEvent("onPlayerVehicleEnter", ArgumentsEnter); else @@ -3666,9 +3665,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Execute the vehicle->ped script function CLuaArguments ArgumentsEnter2; - ArgumentsEnter2.PushElement(pPed); // player / ped - ArgumentsEnter2.PushNumber(0); // seat - ArgumentsEnter2.PushElement(pJacked); // jacked + ArgumentsEnter2.PushElement(pPed); // player / ped + ArgumentsEnter2.PushNumber(0); // seat + ArgumentsEnter2.PushElement(pJacked); // jacked pVehicle->CallEvent("onVehicleEnter", ArgumentsEnter2); } else @@ -3685,9 +3684,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Execute the player->vehicle script function CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(0); // seat - Arguments.PushBoolean(false); // jacked + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(0); // seat + Arguments.PushBoolean(false); // jacked if (pPed->IsPlayer()) pPed->CallEvent("onPlayerVehicleEnter", Arguments); else @@ -3695,9 +3694,9 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) // Execute the vehicle->player script function CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(0); // seat - Arguments2.PushBoolean(false); // jacked + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(0); // seat + Arguments2.PushBoolean(false); // jacked pVehicle->CallEvent("onVehicleEnter", Arguments2); } } @@ -3746,10 +3745,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) m_pPlayerManager->BroadcastOnlyJoined(JackedReply); CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(occupiedSeat); // seat - Arguments.PushElement(pPed); // jacker - Arguments.PushBoolean(false); // forcedByScript + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(occupiedSeat); // seat + Arguments.PushElement(pPed); // jacker + Arguments.PushBoolean(false); // forcedByScript if (pJacked->IsPlayer()) { @@ -3761,10 +3760,10 @@ void CGame::Packet_Vehicle_InOut(CVehicleInOutPacket& Packet) } CLuaArguments Arguments2; - Arguments2.PushElement(pJacked); // jacked - Arguments2.PushNumber(occupiedSeat); // seat - Arguments2.PushElement(pPed); // jacker - Arguments2.PushBoolean(false); // forcedByScript + Arguments2.PushElement(pJacked); // jacked + Arguments2.PushNumber(occupiedSeat); // seat + Arguments2.PushElement(pPed); // jacker + Arguments2.PushBoolean(false); // forcedByScript pVehicle->CallEvent("onVehicleExit", Arguments2); } pJacked->SetVehicleAction(CPed::VEHICLEACTION_NONE); @@ -3874,7 +3873,7 @@ void CGame::Packet_VehicleTrailer(CVehicleTrailerPacket& Packet) m_pPlayerManager->BroadcastOnlyJoined(DetachPacket); } } - else // If we're detaching + else // If we're detaching { // Make sure they're attached if (pVehicle->GetTowedVehicle() == pTrailer && pTrailer->GetTowedByVehicle() == pVehicle) @@ -3902,7 +3901,7 @@ void CGame::Packet_Voice_Data(CVoiceDataPacket& Packet) { unsigned short usDataLength = 0; - if (m_pMainConfig->IsVoiceEnabled()) // Shouldn't really be receiving voice packets at all if voice is disabled + if (m_pMainConfig->IsVoiceEnabled()) // Shouldn't really be receiving voice packets at all if voice is disabled { if (!Packet.IsEmpty()) { @@ -3910,7 +3909,7 @@ void CGame::Packet_Voice_Data(CVoiceDataPacket& Packet) if (pPlayer) { - if (pPlayer->IsVoiceMuted()) // Shouldn't be receiving voice packets, player should be muted client side + if (pPlayer->IsVoiceMuted()) // Shouldn't be receiving voice packets, player should be muted client side return; // Is it the start of the voice stream? @@ -3920,7 +3919,7 @@ void CGame::Packet_Voice_Data(CVoiceDataPacket& Packet) CLuaArguments Arguments; bool bEventTriggered = pPlayer->CallEvent("onPlayerVoiceStart", Arguments, pPlayer); - if (!bEventTriggered) // Was the event cancelled? + if (!bEventTriggered) // Was the event cancelled? { pPlayer->SetVoiceState(VOICESTATE_TRANSMITTING_IGNORED); return; @@ -3930,8 +3929,7 @@ void CGame::Packet_Voice_Data(CVoiceDataPacket& Packet) pPlayer->SetVoiceState(VOICESTATE_TRANSMITTING); } - if (pPlayer->GetVoiceState() == - VOICESTATE_TRANSMITTING) // If we reach here, and we're still in idle state, then the event was cancelled + if (pPlayer->GetVoiceState() == VOICESTATE_TRANSMITTING) // If we reach here, and we're still in idle state, then the event was cancelled { // Make list of players to send the voice packet to std::set playerSendMap; @@ -3984,7 +3982,7 @@ void CGame::Packet_Voice_Data(CVoiceDataPacket& Packet) void CGame::Packet_Voice_End(CVoiceEndPacket& Packet) { - if (m_pMainConfig->IsVoiceEnabled()) // Shouldn't really be receiving voice packets at all if voice is disabled + if (m_pMainConfig->IsVoiceEnabled()) // Shouldn't really be receiving voice packets at all if voice is disabled { CPlayer* pPlayer = Packet.GetSourcePlayer(); @@ -4209,8 +4207,8 @@ void CGame::Packet_PlayerNetworkStatus(CPlayerNetworkStatusPacket& Packet) if (pPlayer) { CLuaArguments Arguments; - Arguments.PushNumber(Packet.m_ucType); // 0-interruption began 1-interruption end - Arguments.PushNumber(Packet.m_uiTicks); // Ticks since interruption start + Arguments.PushNumber(Packet.m_ucType); // 0-interruption began 1-interruption end + Arguments.PushNumber(Packet.m_uiTicks); // Ticks since interruption start pPlayer->CallEvent("onPlayerNetworkStatus", Arguments, NULL); } } @@ -4599,7 +4597,7 @@ void CGame::HandleBackup() time_t timeSinceBackup = secondsNow - mktime(&timeinfo); if (timeSinceBackup < iBackupInterval * 86400L) - return; // No backup required + return; // No backup required } m_pMainConfig->NotifyDidBackup(); @@ -4613,7 +4611,7 @@ void CGame::HandleBackup() SString strTempZip = PathJoin(strBackupPath, strDateNow + "_temp.zip"); if (FileExists(strBackupZip)) - return; // Can't do backup as target file already exists + return; // Can't do backup as target file already exists MkDir(strBackupPath); @@ -4622,7 +4620,7 @@ void CGame::HandleBackup() CZipMaker zipMaker(strTempZip); if (!zipMaker.IsValid()) - return; // Can't do backup as can't create target zip + return; // Can't do backup as can't create target zip CLogger::LogPrintfNoStamp("Please wait...\n"); @@ -4720,7 +4718,7 @@ void CGame::SendPacketBatchEnd() bool CGame::IsBulletSyncActive() { bool bConfigSaysEnable = m_pMainConfig->GetBulletSyncEnabled(); -#if 0 // No auto bullet sync as there are some problems with it +#if 0 // No auto bullet sync as there are some problems with it bool bGlitchesSayEnable = ( m_Glitches [ GLITCH_FASTFIRE ] || m_Glitches [ GLITCH_CROUCHBUG ] ); #else bool bGlitchesSayEnable = false; @@ -4752,14 +4750,14 @@ void CGame::SendSyncSettings(CPlayer* pPlayer) MapInsert(weaponTypesUsingBulletSync, weaponList[i]); } - short sVehExtrapolateBaseMs = 5; - auto sVehExtrapolatePercent = static_cast(m_pMainConfig->GetVehExtrapolatePercent()); - auto sVehExtrapolateMaxMs = static_cast(m_pMainConfig->GetVehExtrapolatePingLimit()); - uchar ucVehExtrapolateEnabled = sVehExtrapolatePercent != 0; - uchar ucUseAltPulseOrder = m_pMainConfig->GetUseAltPulseOrder() != 0; - uchar ucAllowFastSprintFix = true; - uchar ucAllowDrivebyAnimFix = true; - uchar ucAllowShotgunDamageFix = true; + short sVehExtrapolateBaseMs = 5; + auto sVehExtrapolatePercent = static_cast(m_pMainConfig->GetVehExtrapolatePercent()); + auto sVehExtrapolateMaxMs = static_cast(m_pMainConfig->GetVehExtrapolatePingLimit()); + uchar ucVehExtrapolateEnabled = sVehExtrapolatePercent != 0; + uchar ucUseAltPulseOrder = m_pMainConfig->GetUseAltPulseOrder() != 0; + uchar ucAllowFastSprintFix = true; + uchar ucAllowDrivebyAnimFix = true; + uchar ucAllowShotgunDamageFix = true; std::uint8_t multiCommandHandlerPolicy = static_cast(m_pMainConfig->GetAllowMultiCommandHandlers()); CSyncSettingsPacket packet(weaponTypesUsingBulletSync, ucVehExtrapolateEnabled, sVehExtrapolateBaseMs, sVehExtrapolatePercent, sVehExtrapolateMaxMs, diff --git a/Server/mods/deathmatch/logic/CGame.h b/Server/mods/deathmatch/logic/CGame.h index 07c4f227e65..9d0ace7b1aa 100644 --- a/Server/mods/deathmatch/logic/CGame.h +++ b/Server/mods/deathmatch/logic/CGame.h @@ -158,7 +158,7 @@ class CSendList : public std::multimap class CGame { public: - ZERO_ON_NEW // To be sure everything is cleared + ZERO_ON_NEW // To be sure everything is cleared enum { VEHICLE_REQUEST_IN, VEHICLE_NOTIFY_IN, @@ -218,19 +218,19 @@ class CGame void SetIsFinished(bool bFinished) { m_bIsFinished = bFinished; }; bool IsFinished() { return m_bIsFinished; }; - CMainConfig* GetConfig() { return m_pMainConfig; } - CHandlingManager* GetHandlingManager() const noexcept { return m_HandlingManager.get(); } - CMapManager* GetMapManager() { return m_pMapManager; } - CPlayerManager* GetPlayerManager() { return m_pPlayerManager; } - CObjectManager* GetObjectManager() { return m_pObjectManager; } - CBuildingManager* GetBuildingManager() const noexcept { return m_pBuildingManager; } - CVehicleManager* GetVehicleManager() { return m_pVehicleManager; } - CTeamManager* GetTeamManager() { return m_pTeamManager; } - CUnoccupiedVehicleSync* GetUnoccupiedVehicleSync() { return m_pUnoccupiedVehicleSync; } - CPedSync* GetPedSync() { return m_pPedSync; } - CRegisteredCommands* GetRegisteredCommands() { return m_pRegisteredCommands; } + CMainConfig* GetConfig() { return m_pMainConfig; } + CHandlingManager* GetHandlingManager() const noexcept { return m_HandlingManager.get(); } + CMapManager* GetMapManager() { return m_pMapManager; } + CPlayerManager* GetPlayerManager() { return m_pPlayerManager; } + CObjectManager* GetObjectManager() { return m_pObjectManager; } + CBuildingManager* GetBuildingManager() const noexcept { return m_pBuildingManager; } + CVehicleManager* GetVehicleManager() { return m_pVehicleManager; } + CTeamManager* GetTeamManager() { return m_pTeamManager; } + CUnoccupiedVehicleSync* GetUnoccupiedVehicleSync() { return m_pUnoccupiedVehicleSync; } + CPedSync* GetPedSync() { return m_pPedSync; } + CRegisteredCommands* GetRegisteredCommands() { return m_pRegisteredCommands; } #ifdef WITH_OBJECT_SYNC - CObjectSync* GetObjectSync() { return m_pObjectSync; } + CObjectSync* GetObjectSync() { return m_pObjectSync; } #endif CConsole* GetConsole() { return m_pConsole; } CDatabaseManager* GetDatabaseManager() { return m_pDatabaseManager; } @@ -532,30 +532,30 @@ class CGame // Technically, this could be put somewhere else. It's a callback function // which the voice server library will call to send out data. - CEvents m_Events; - CRemoteCalls* m_pRemoteCalls; - CHTTPD* m_pHTTPD; - CMainConfig* m_pMainConfig; - CBlipManager* m_pBlipManager; - CGroups* m_pGroups; - CColManager* m_pColManager; - CObjectManager* m_pObjectManager; - CBuildingManager* m_pBuildingManager; - CPickupManager* m_pPickupManager; - CPlayerManager* m_pPlayerManager; - CRadarAreaManager* m_pRadarAreaManager; - CVehicleManager* m_pVehicleManager; - CPacketTranslator* m_pPacketTranslator; - CMapManager* m_pMapManager; - CElementDeleter m_ElementDeleter; - CConnectHistory m_FloodProtect; - CLuaManager* m_pLuaManager; - CScriptDebugging* m_pScriptDebugging; - CConsole* m_pConsole; - CUnoccupiedVehicleSync* m_pUnoccupiedVehicleSync; - CPedSync* m_pPedSync; + CEvents m_Events; + CRemoteCalls* m_pRemoteCalls; + CHTTPD* m_pHTTPD; + CMainConfig* m_pMainConfig; + CBlipManager* m_pBlipManager; + CGroups* m_pGroups; + CColManager* m_pColManager; + CObjectManager* m_pObjectManager; + CBuildingManager* m_pBuildingManager; + CPickupManager* m_pPickupManager; + CPlayerManager* m_pPlayerManager; + CRadarAreaManager* m_pRadarAreaManager; + CVehicleManager* m_pVehicleManager; + CPacketTranslator* m_pPacketTranslator; + CMapManager* m_pMapManager; + CElementDeleter m_ElementDeleter; + CConnectHistory m_FloodProtect; + CLuaManager* m_pLuaManager; + CScriptDebugging* m_pScriptDebugging; + CConsole* m_pConsole; + CUnoccupiedVehicleSync* m_pUnoccupiedVehicleSync; + CPedSync* m_pPedSync; #ifdef WITH_OBJECT_SYNC - CObjectSync* m_pObjectSync; + CObjectSync* m_pObjectSync; #endif CMarkerManager* m_pMarkerManager; CClock* m_pClock; @@ -665,7 +665,7 @@ class CGame CLightsyncManager m_lightsyncManager; - bool m_bServerFullyUp; // No http operations should be allowed unless this is true + bool m_bServerFullyUp; // No http operations should be allowed unless this is true bool m_bLatentSendsEnabled; int m_iLatentSendsBandwidth; @@ -686,8 +686,8 @@ class CGame struct ClientTriggeredEventsInfo { - long long m_llTicks = 0; - uint32_t m_uiCounter = 0; + long long m_llTicks = 0; + uint32_t m_uiCounter = 0; std::string m_strLastEventName; }; diff --git a/Server/mods/deathmatch/logic/CHTTPD.cpp b/Server/mods/deathmatch/logic/CHTTPD.cpp index f50c24bb199..785ffcc8735 100644 --- a/Server/mods/deathmatch/logic/CHTTPD.cpp +++ b/Server/mods/deathmatch/logic/CHTTPD.cpp @@ -27,13 +27,14 @@ extern CGame* g_pGame; CHTTPD::CHTTPD() - : m_BruteForceProtect(4, 30000, 60000 * 5) // Max of 4 attempts per 30 seconds, then 5 minute ignore - , m_HttpDosProtect(0, 0, 0) + : m_BruteForceProtect(4, 30000, 60000 * 5) // Max of 4 attempts per 30 seconds, then 5 minute ignore + , + m_HttpDosProtect(0, 0, 0) { m_pGuestAccount = g_pGame->GetAccountManager()->AddGuestAccount(HTTP_GUEST_ACCOUNT_NAME); m_HttpDosProtect = CConnectHistory(g_pGame->GetConfig()->GetHTTPDosThreshold(), 10000, - 60000 * 1); // Max of 'n' connections per 10 seconds, then 1 minute ignore + 60000 * 1); // Max of 'n' connections per 10 seconds, then 1 minute ignore std::vector excludeList; g_pGame->GetConfig()->GetHTTPDosExclude().Split(",", excludeList); @@ -81,7 +82,7 @@ bool CHTTPD::StartHTTPD(const char* szIP, unsigned int port) parameters["bindip"] = (long)INADDR_ANY; } - parameters["mode"] = "threadpool"; // or "singlethreaded"/"threadpool" + parameters["mode"] = "threadpool"; // or "singlethreaded"/"threadpool" parameters["threadcount"] = g_pGame->GetConfig()->GetHTTPThreadCount(); bResult = (StartServer(parameters) == STARTSERVER_SUCCESS); @@ -302,7 +303,7 @@ void CHTTPD::HttpPulse() { std::lock_guard guard(m_mutexLoggedInMap); - long long llExpireTime = GetTickCount64_() - 1000 * 60 * 5; // 5 minute timeout + long long llExpireTime = GetTickCount64_() - 1000 * 60 * 5; // 5 minute timeout map::iterator iter = m_LoggedInMap.begin(); while (iter != m_LoggedInMap.end()) diff --git a/Server/mods/deathmatch/logic/CHTTPD.h b/Server/mods/deathmatch/logic/CHTTPD.h index a27970b06c1..6235114b3b4 100644 --- a/Server/mods/deathmatch/logic/CHTTPD.h +++ b/Server/mods/deathmatch/logic/CHTTPD.h @@ -23,7 +23,7 @@ class CResource; class CHTTPD : public EHS { public: - CHTTPD(); // start the initial server + CHTTPD(); // start the initial server ~CHTTPD(); // EHS interface HttpResponse* RouteRequest(HttpRequest* ipoHttpRequest); @@ -43,7 +43,7 @@ class CHTTPD : public EHS private: CResource* m_resource{}; CHTTPD* m_server{}; - std::string m_strDefaultResourceName; // default resource name + std::string m_strDefaultResourceName; // default resource name EHSServerParameters m_Parameters; diff --git a/Server/mods/deathmatch/logic/CHandlingEntry.h b/Server/mods/deathmatch/logic/CHandlingEntry.h index 7f2afeca2aa..91e7bfa8d9c 100644 --- a/Server/mods/deathmatch/logic/CHandlingEntry.h +++ b/Server/mods/deathmatch/logic/CHandlingEntry.h @@ -16,58 +16,58 @@ class CHandlingEntry; class CTransmissionSAInterface { public: - unsigned char ucDriveType : 8; // +112 - unsigned char ucEngineType : 8; // +113 - unsigned char ucNumberOfGears : 8; // +114 - unsigned char ucUnknown : 8; // +115 + unsigned char ucDriveType : 8; // +112 + unsigned char ucEngineType : 8; // +113 + unsigned char ucNumberOfGears : 8; // +114 + unsigned char ucUnknown : 8; // +115 - unsigned int uiHandlingFlags; // +116 + unsigned int uiHandlingFlags; // +116 - float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) - float fEngineInertia; // +124 - float fMaxVelocity; // +128 + float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) + float fEngineInertia; // +124 + float fMaxVelocity; // +128 }; struct tHandlingData { - int iVehicleID; // +0 + int iVehicleID; // +0 - float fMass; // +4 + float fMass; // +4 - float fTurnMass; // +12 - float fDragCoeff; // +16 - CVector vecCenterOfMass; // +20 - unsigned int uiPercentSubmerged; // +32 + float fTurnMass; // +12 + float fDragCoeff; // +16 + CVector vecCenterOfMass; // +20 + unsigned int uiPercentSubmerged; // +32 - float fTractionMultiplier; // +40 + float fTractionMultiplier; // +40 - CTransmissionSAInterface Transmission; // +44 - float fBrakeDeceleration; // +148 - float fBrakeBias; // +152 - bool bABS; // +156 + CTransmissionSAInterface Transmission; // +44 + float fBrakeDeceleration; // +148 + float fBrakeBias; // +152 + bool bABS; // +156 - float fSteeringLock; // +160 - float fTractionLoss; // +164 - float fTractionBias; // +168 + float fSteeringLock; // +160 + float fTractionLoss; // +164 + float fTractionBias; // +168 - float fSuspensionForceLevel; // +172 - float fSuspensionDamping; // +176 - float fSuspensionHighSpdDamping; // +180 - float fSuspensionUpperLimit; // +184 - float fSuspensionLowerLimit; // +188 - float fSuspensionFrontRearBias; // +192 - float fSuspensionAntiDiveMultiplier; // +196 + float fSuspensionForceLevel; // +172 + float fSuspensionDamping; // +176 + float fSuspensionHighSpdDamping; // +180 + float fSuspensionUpperLimit; // +184 + float fSuspensionLowerLimit; // +188 + float fSuspensionFrontRearBias; // +192 + float fSuspensionAntiDiveMultiplier; // +196 - float fCollisionDamageMultiplier; // +200 + float fCollisionDamageMultiplier; // +200 - unsigned int uiModelFlags; // +204 - unsigned int uiHandlingFlags; // +208 - float fSeatOffsetDistance; // +212 - unsigned int uiMonetary; // +216 + unsigned int uiModelFlags; // +204 + unsigned int uiHandlingFlags; // +208 + float fSeatOffsetDistance; // +212 + unsigned int uiMonetary; // +216 - unsigned char ucHeadLight : 8; // +220 - unsigned char ucTailLight : 8; // +221 - unsigned char ucAnimGroup : 8; // +222 + unsigned char ucHeadLight : 8; // +220 + unsigned char ucTailLight : 8; // +221 + unsigned char ucAnimGroup : 8; // +222 }; class CHandlingEntry @@ -96,12 +96,12 @@ class CHandlingEntry }; // Constructor for creatable dummy entries - CHandlingEntry(){}; + CHandlingEntry() {}; // Constructor for original entries CHandlingEntry(tHandlingData* pOriginal); - ~CHandlingEntry(){}; + ~CHandlingEntry() {}; // Use this to copy data from an another handling class to this void ApplyHandlingData(const CHandlingEntry* const pData) noexcept; diff --git a/Server/mods/deathmatch/logic/CHandlingManager.cpp b/Server/mods/deathmatch/logic/CHandlingManager.cpp index 7776c55af05..72c5e10b184 100644 --- a/Server/mods/deathmatch/logic/CHandlingManager.cpp +++ b/Server/mods/deathmatch/logic/CHandlingManager.cpp @@ -39,39 +39,39 @@ CHandlingManager::CHandlingManager() // https://www.gtamodding.com/index.php?title=Handling.cfg#GTA_San_Andreas // https://projectcerbera.com/gta/sa/tutorials/handling - m_HandlingNames["mass"] = HANDLING_MASS; // works (mass > 0) - m_HandlingNames["turnMass"] = HANDLING_TURNMASS; // works - m_HandlingNames["dragCoeff"] = HANDLING_DRAGCOEFF; // works - m_HandlingNames["centerOfMass"] = HANDLING_CENTEROFMASS; // works - m_HandlingNames["percentSubmerged"] = HANDLING_PERCENTSUBMERGED; // works - m_HandlingNames["tractionMultiplier"] = HANDLING_TRACTIONMULTIPLIER; // works - m_HandlingNames["driveType"] = HANDLING_DRIVETYPE; // works - m_HandlingNames["engineType"] = HANDLING_ENGINETYPE; // works - m_HandlingNames["numberOfGears"] = HANDLING_NUMOFGEARS; // works - m_HandlingNames["engineAcceleration"] = HANDLING_ENGINEACCELERATION; // works - m_HandlingNames["engineInertia"] = HANDLING_ENGINEINERTIA; // works - m_HandlingNames["maxVelocity"] = HANDLING_MAXVELOCITY; // works - m_HandlingNames["brakeDeceleration"] = HANDLING_BRAKEDECELERATION; // works - m_HandlingNames["brakeBias"] = HANDLING_BRAKEBIAS; // works - m_HandlingNames["ABS"] = HANDLING_ABS; // has no effect in vanilla gta either - m_HandlingNames["steeringLock"] = HANDLING_STEERINGLOCK; // works - m_HandlingNames["tractionLoss"] = HANDLING_TRACTIONLOSS; // works - m_HandlingNames["tractionBias"] = HANDLING_TRACTIONBIAS; // works - m_HandlingNames["suspensionForceLevel"] = HANDLING_SUSPENSION_FORCELEVEL; // works - m_HandlingNames["suspensionDamping"] = HANDLING_SUSPENSION_DAMPING; // works - m_HandlingNames["suspensionHighSpeedDamping"] = HANDLING_SUSPENSION_HIGHSPEEDDAMPING; // works - m_HandlingNames["suspensionUpperLimit"] = HANDLING_SUSPENSION_UPPER_LIMIT; // works - m_HandlingNames["suspensionLowerLimit"] = HANDLING_SUSPENSION_LOWER_LIMIT; // works - m_HandlingNames["suspensionFrontRearBias"] = HANDLING_SUSPENSION_FRONTREARBIAS; // works - m_HandlingNames["suspensionAntiDiveMultiplier"] = HANDLING_SUSPENSION_ANTIDIVEMULTIPLIER; // works - m_HandlingNames["collisionDamageMultiplier"] = HANDLING_COLLISIONDAMAGEMULTIPLIER; // works - m_HandlingNames["seatOffsetDistance"] = HANDLING_SEATOFFSETDISTANCE; // works - m_HandlingNames["monetary"] = HANDLING_MONETARY; // useless as it only influences SP stats (value of damaged property) - m_HandlingNames["handlingFlags"] = HANDLING_HANDLINGFLAGS; // works - m_HandlingNames["modelFlags"] = HANDLING_MODELFLAGS; // works - m_HandlingNames["headLight"] = HANDLING_HEADLIGHT; // doesn't work - m_HandlingNames["tailLight"] = HANDLING_TAILLIGHT; // doesn't seem to work* - m_HandlingNames["animGroup"] = HANDLING_ANIMGROUP; // works model based + m_HandlingNames["mass"] = HANDLING_MASS; // works (mass > 0) + m_HandlingNames["turnMass"] = HANDLING_TURNMASS; // works + m_HandlingNames["dragCoeff"] = HANDLING_DRAGCOEFF; // works + m_HandlingNames["centerOfMass"] = HANDLING_CENTEROFMASS; // works + m_HandlingNames["percentSubmerged"] = HANDLING_PERCENTSUBMERGED; // works + m_HandlingNames["tractionMultiplier"] = HANDLING_TRACTIONMULTIPLIER; // works + m_HandlingNames["driveType"] = HANDLING_DRIVETYPE; // works + m_HandlingNames["engineType"] = HANDLING_ENGINETYPE; // works + m_HandlingNames["numberOfGears"] = HANDLING_NUMOFGEARS; // works + m_HandlingNames["engineAcceleration"] = HANDLING_ENGINEACCELERATION; // works + m_HandlingNames["engineInertia"] = HANDLING_ENGINEINERTIA; // works + m_HandlingNames["maxVelocity"] = HANDLING_MAXVELOCITY; // works + m_HandlingNames["brakeDeceleration"] = HANDLING_BRAKEDECELERATION; // works + m_HandlingNames["brakeBias"] = HANDLING_BRAKEBIAS; // works + m_HandlingNames["ABS"] = HANDLING_ABS; // has no effect in vanilla gta either + m_HandlingNames["steeringLock"] = HANDLING_STEERINGLOCK; // works + m_HandlingNames["tractionLoss"] = HANDLING_TRACTIONLOSS; // works + m_HandlingNames["tractionBias"] = HANDLING_TRACTIONBIAS; // works + m_HandlingNames["suspensionForceLevel"] = HANDLING_SUSPENSION_FORCELEVEL; // works + m_HandlingNames["suspensionDamping"] = HANDLING_SUSPENSION_DAMPING; // works + m_HandlingNames["suspensionHighSpeedDamping"] = HANDLING_SUSPENSION_HIGHSPEEDDAMPING; // works + m_HandlingNames["suspensionUpperLimit"] = HANDLING_SUSPENSION_UPPER_LIMIT; // works + m_HandlingNames["suspensionLowerLimit"] = HANDLING_SUSPENSION_LOWER_LIMIT; // works + m_HandlingNames["suspensionFrontRearBias"] = HANDLING_SUSPENSION_FRONTREARBIAS; // works + m_HandlingNames["suspensionAntiDiveMultiplier"] = HANDLING_SUSPENSION_ANTIDIVEMULTIPLIER; // works + m_HandlingNames["collisionDamageMultiplier"] = HANDLING_COLLISIONDAMAGEMULTIPLIER; // works + m_HandlingNames["seatOffsetDistance"] = HANDLING_SEATOFFSETDISTANCE; // works + m_HandlingNames["monetary"] = HANDLING_MONETARY; // useless as it only influences SP stats (value of damaged property) + m_HandlingNames["handlingFlags"] = HANDLING_HANDLINGFLAGS; // works + m_HandlingNames["modelFlags"] = HANDLING_MODELFLAGS; // works + m_HandlingNames["headLight"] = HANDLING_HEADLIGHT; // doesn't work + m_HandlingNames["tailLight"] = HANDLING_TAILLIGHT; // doesn't seem to work* + m_HandlingNames["animGroup"] = HANDLING_ANIMGROUP; // works model based } //* needs testing by someone who knows more about handling @@ -8157,27 +8157,27 @@ void CHandlingManager::InitializeDefaultHandlings() noexcept m_OriginalHandlingData[209].ucTailLight = 1; m_OriginalHandlingData[209].ucAnimGroup = 0; - m_OriginalHandlingData[210] = m_OriginalHandlingData[69]; // HT_HOTRINA = HT_HOTRING + m_OriginalHandlingData[210] = m_OriginalHandlingData[69]; // HT_HOTRINA = HT_HOTRING m_OriginalHandlingData[210].iVehicleID = 210; - m_OriginalHandlingData[211] = m_OriginalHandlingData[69]; // HT_HOTRINB = HT_HOTRING + m_OriginalHandlingData[211] = m_OriginalHandlingData[69]; // HT_HOTRINB = HT_HOTRING m_OriginalHandlingData[211].iVehicleID = 211; - m_OriginalHandlingData[212] = m_OriginalHandlingData[103]; // HT_SADLSHIT = HT_SADLER + m_OriginalHandlingData[212] = m_OriginalHandlingData[103]; // HT_SADLSHIT = HT_SADLER m_OriginalHandlingData[212].iVehicleID = 212; - m_OriginalHandlingData[213] = m_OriginalHandlingData[52]; // HT_GLENSHIT = HT_GLENDALE + m_OriginalHandlingData[213] = m_OriginalHandlingData[52]; // HT_GLENSHIT = HT_GLENDALE m_OriginalHandlingData[213].iVehicleID = 213; - m_OriginalHandlingData[214] = m_OriginalHandlingData[163]; // HT_FAGGIO = HT_PIZZABOY + m_OriginalHandlingData[214] = m_OriginalHandlingData[163]; // HT_FAGGIO = HT_PIZZABOY m_OriginalHandlingData[214].iVehicleID = 214; - m_OriginalHandlingData[215] = m_OriginalHandlingData[7]; // HT_FIRELA = HT_FIRETRUK + m_OriginalHandlingData[215] = m_OriginalHandlingData[7]; // HT_FIRELA = HT_FIRETRUK m_OriginalHandlingData[215].iVehicleID = 215; - m_OriginalHandlingData[216] = m_OriginalHandlingData[65]; // HT_RNCHLURE = HT_RANCHER + m_OriginalHandlingData[216] = m_OriginalHandlingData[65]; // HT_RNCHLURE = HT_RANCHER m_OriginalHandlingData[216].iVehicleID = 216; - m_OriginalHandlingData[217] = m_OriginalHandlingData[126]; // HT_FREIBOX = HT_FREIFLAT + m_OriginalHandlingData[217] = m_OriginalHandlingData[126]; // HT_FREIBOX = HT_FREIFLAT m_OriginalHandlingData[217].iVehicleID = 217; } diff --git a/Server/mods/deathmatch/logic/CLanBroadcast.cpp b/Server/mods/deathmatch/logic/CLanBroadcast.cpp index 5a62d228604..22cee03f76f 100644 --- a/Server/mods/deathmatch/logic/CLanBroadcast.cpp +++ b/Server/mods/deathmatch/logic/CLanBroadcast.cpp @@ -33,13 +33,13 @@ CLanBroadcast::CLanBroadcast(unsigned short usServerPort) return; } - // Set it to non blocking, so we dont have to wait for a packet - #ifdef WIN32 +// Set it to non blocking, so we dont have to wait for a packet +#ifdef WIN32 unsigned long ulNonBlock = 1; ioctlsocket(m_Socket, FIONBIO, &ulNonBlock); - #else +#else fcntl(m_Socket, F_SETFL, fcntl(m_Socket, F_GETFL) | O_NONBLOCK); - #endif +#endif // Set up the query messages std::stringstream ss; diff --git a/Server/mods/deathmatch/logic/CLightsyncManager.cpp b/Server/mods/deathmatch/logic/CLightsyncManager.cpp index 94e4ce8a708..700abd6bf65 100644 --- a/Server/mods/deathmatch/logic/CLightsyncManager.cpp +++ b/Server/mods/deathmatch/logic/CLightsyncManager.cpp @@ -33,7 +33,7 @@ void CLightsyncManager::RegisterPlayer(CPlayer* pPlayer) entry.ullTime = GetTickCount64_(); entry.pPlayer = pPlayer; entry.eType = SYNC_PLAYER; - entry.uiContext = 0; // Unused + entry.uiContext = 0; // Unused m_Queue.push_back(entry); } diff --git a/Server/mods/deathmatch/logic/CLightsyncManager.h b/Server/mods/deathmatch/logic/CLightsyncManager.h index 332555fc218..3250363eb3c 100644 --- a/Server/mods/deathmatch/logic/CLightsyncManager.h +++ b/Server/mods/deathmatch/logic/CLightsyncManager.h @@ -14,12 +14,12 @@ #include #ifndef _MSC_VER -#include + #include typedef int64_t __int64; #endif -#define LIGHTSYNC_HEALTH_THRESHOLD 2.0f -#define LIGHTSYNC_VEHICLE_HEALTH_THRESHOLD 50.0f +#define LIGHTSYNC_HEALTH_THRESHOLD 2.0f +#define LIGHTSYNC_VEHICLE_HEALTH_THRESHOLD 50.0f class CLightsyncManager { diff --git a/Server/mods/deathmatch/logic/CLogger.cpp b/Server/mods/deathmatch/logic/CLogger.cpp index a52d2c99c3b..e8f710fa22e 100644 --- a/Server/mods/deathmatch/logic/CLogger.cpp +++ b/Server/mods/deathmatch/logic/CLogger.cpp @@ -106,7 +106,7 @@ void CLogger::ErrorPrintvf(const char* format, va_list vlist) void CLogger::DebugPrintf(const char* szFormat, ...) { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG // Compose the formatted message char szBuffer[MAX_STRING_LENGTH]; va_list marker; @@ -116,7 +116,7 @@ void CLogger::DebugPrintf(const char* szFormat, ...) // Timestamp and send to the console and logfile HandleLogPrint(true, "DEBUG: ", szBuffer, true, true, false); - #endif +#endif } void CLogger::AuthPrintf(const char* szFormat, ...) diff --git a/Server/mods/deathmatch/logic/CMainConfig.cpp b/Server/mods/deathmatch/logic/CMainConfig.cpp index e40d2adb96c..413d9d0e9b2 100644 --- a/Server/mods/deathmatch/logic/CMainConfig.cpp +++ b/Server/mods/deathmatch/logic/CMainConfig.cpp @@ -138,12 +138,12 @@ bool CMainConfig::Load() } // Grab rules - CXMLNode* currentNode = nullptr; + CXMLNode* currentNode = nullptr; std::size_t currentIndex = 0; while (currentNode = m_pRootNode->FindSubNode("rule", currentIndex++)) { CXMLAttribute* attribute = currentNode->GetAttributes().Find("name"); - SString ruleName = attribute ? attribute->GetValue() : SString{}; + SString ruleName = attribute ? attribute->GetValue() : SString{}; attribute = currentNode->GetAttributes().Find("value"); SString ruleValue = attribute ? attribute->GetValue() : SString{}; @@ -151,7 +151,7 @@ bool CMainConfig::Load() if (!ruleName.empty() && !ruleValue.empty()) m_RulesForASEMap[std::move(ruleName)] = std::move(ruleValue); } - + // Strip spaces from beginning and end of server name m_strServerName = SString(m_strServerName).TrimStart(" ").TrimEnd(" "); @@ -260,13 +260,13 @@ bool CMainConfig::Load() { // Grab its "name" attribute CXMLAttribute* attribute = currentNode->GetAttributes().Find("name"); - SString name = attribute ? attribute->GetValue() : SString{}; + SString name = attribute ? attribute->GetValue() : SString{}; name = name.Replace("\\", "/").ToLower(); // Grab its "verify" attribute attribute = currentNode->GetAttributes().Find("verify"); SString verify = attribute ? attribute->GetValue() : SString{}; - bool shouldVerify = verify == "true" || verify == "yes" || verify == "1"; + bool shouldVerify = verify == "true" || verify == "yes" || verify == "1"; // Find bitnumber bool found = false; @@ -771,7 +771,8 @@ bool CMainConfig::LoadExtended() RegisterCommand("start", CConsoleCommands::StartResource, false, "Usage: start ...\nStart a loaded resource eg: start admin"); RegisterCommand("stop", CConsoleCommands::StopResource, false, "Usage: stop ...\nStop a resource eg: stop admin"); RegisterCommand("stopall", CConsoleCommands::StopAllResources, false, "Stop all running resources"); - RegisterCommand("restart", CConsoleCommands::RestartResource, false, "Usage: restart ...\nRestarts a running resource eg: restart admin"); + RegisterCommand("restart", CConsoleCommands::RestartResource, false, + "Usage: restart ...\nRestarts a running resource eg: restart admin"); RegisterCommand("refresh", CConsoleCommands::RefreshResources, false, "Refresh resource list to find new resources"); RegisterCommand("refreshall", CConsoleCommands::RefreshAllResources, false, "Refresh resources and restart any changed resources"); RegisterCommand("list", CConsoleCommands::ListResources, false, "Shows a list of resources"); @@ -883,18 +884,18 @@ bool CMainConfig::AddMissingSettings() } // Check that each item in the template also exists in the server config - bool configChanged = false; + bool configChanged = false; CXMLNode* previousNode = nullptr; for (auto it = templateRootNode->ChildrenBegin(); it != templateRootNode->ChildrenEnd(); ++it) { - CXMLNode* templateNode = *it; + CXMLNode* templateNode = *it; const std::string& templateNodeName = templateNode->GetTagName(); // Skip certain optional nodes if (templateNodeName == "resource" || templateNodeName == "module") continue; - + // Find node with exact same attributes CXMLAttributes& templateAttributes = templateNode->GetAttributes(); CXMLNode* foundNode = nullptr; @@ -903,10 +904,10 @@ bool CMainConfig::AddMissingSettings() CXMLNode* tempNode = *it2; if (tempNode->GetTagName() != templateNodeName) continue; - + CXMLAttributes& attributes = tempNode->GetAttributes(); - bool attributesMatch = true; - + bool attributesMatch = true; + for (auto it3 = templateAttributes.ListBegin(); it3 != templateAttributes.ListEnd(); ++it3) { CXMLAttribute* templateAttribute = *it3; @@ -915,9 +916,9 @@ bool CMainConfig::AddMissingSettings() // Don't check value attribute which is intended to be customized by the server if (attrName == "value") continue; - + const SString& attrValue = templateAttribute->GetValue(); - + CXMLAttribute* foundAttribute = attributes.Find(attrName); if (!foundAttribute || foundAttribute->GetValue() != attrValue) { @@ -925,18 +926,18 @@ bool CMainConfig::AddMissingSettings() break; } } - + if (attributesMatch) { foundNode = tempNode; break; } } - + if (!foundNode) { const std::string templateNodeValue = templateNode->GetTagContent(); - const SString templateNodeComment = templateNode->GetCommentText(); + const SString templateNodeComment = templateNode->GetCommentText(); foundNode = m_pRootNode->CreateSubNode(templateNodeName.c_str(), previousNode); foundNode->SetTagContent(templateNodeValue.c_str()); @@ -1533,7 +1534,8 @@ const std::vector& CMainConfig::GetIntSettingList() {false, false, 0, 1, 1, "database_credentials_protection", &m_bDatabaseCredentialsProtectionEnabled, NULL}, {false, false, 0, 0, 1, "fakelag", &m_bFakeLagCommandEnabled, NULL}, {true, true, 50, 1000, 5000, "player_triggered_event_interval", &m_iPlayerTriggeredEventIntervalMs, &CMainConfig::OnPlayerTriggeredEventIntervalChange}, - {true, true, 1, 100, 1000, "max_player_triggered_events_per_interval", &m_iMaxPlayerTriggeredEventsPerInterval, &CMainConfig::OnPlayerTriggeredEventIntervalChange}, + {true, true, 1, 100, 1000, "max_player_triggered_events_per_interval", &m_iMaxPlayerTriggeredEventsPerInterval, + &CMainConfig::OnPlayerTriggeredEventIntervalChange}, {true, true, 0, 1, 1, "resource_client_file_checks", &m_checkResourceClientFiles, nullptr}, {true, true, 0, 1, 2, "allow_multi_command_handlers", &m_allowMultiCommandHandlers, &CMainConfig::OnAllowMultiCommandHandlersChange}, }; diff --git a/Server/mods/deathmatch/logic/CMainConfig.h b/Server/mods/deathmatch/logic/CMainConfig.h index 0d76fa2bf6a..5eb6e6e4bde 100644 --- a/Server/mods/deathmatch/logic/CMainConfig.h +++ b/Server/mods/deathmatch/logic/CMainConfig.h @@ -68,68 +68,68 @@ class CMainConfig : public CXMLConfig unsigned int GetVoiceQuality() { return m_ucVoiceQuality; }; unsigned int GetVoiceBitrate() { return m_uiVoiceBitrate; }; - bool GetAseInternetPushEnabled() { return m_iAseMode == 2 && !IsFakeLagCommandEnabled(); } - bool GetAseInternetListenEnabled() { return m_iAseMode == 1 && !IsFakeLagCommandEnabled(); } - bool GetAseLanListenEnabled() { return m_bDontBroadcastLan ? false : true; } - unsigned short GetHTTPPort(); - eHTTPDownloadType GetHTTPDownloadType() { return m_ucHTTPDownloadType; }; - const std::string& GetHTTPDownloadURL() { return m_strHTTPDownloadURL; }; - int GetHTTPMaxConnectionsPerClient() { return m_iHTTPMaxConnectionsPerClient; }; - int GetHTTPThreadCount() { return m_iHTTPThreadCount; }; - int GetHTTPDosThreshold() { return m_iHTTPDosThreshold; }; - const SString& GetHTTPDosExclude() { return m_strHTTPDosExclude; }; - int GetEnableClientChecks() { return m_iEnableClientChecks; }; - const std::string& GetLogFile() { return m_strLogFile; }; - const std::string& GetAuthFile() { return m_strAuthFile; }; - bool GetJoinFloodProtectionEnabled() { return m_bJoinFloodProtectionEnabled; }; - bool GetScriptDebugLogEnabled() { return m_bScriptDebugLogEnabled && !m_strScriptDebugLogFile.empty(); }; - const std::string& GetScriptDebugLogFile() { return m_strScriptDebugLogFile; }; - unsigned int GetScriptDebugLogLevel() { return m_uiScriptDebugLogLevel; }; - const std::string& GetAccessControlListFile() { return m_strAccessControlListFile; }; - bool GetSerialVerificationEnabled() { return m_bVerifySerials; }; + bool GetAseInternetPushEnabled() { return m_iAseMode == 2 && !IsFakeLagCommandEnabled(); } + bool GetAseInternetListenEnabled() { return m_iAseMode == 1 && !IsFakeLagCommandEnabled(); } + bool GetAseLanListenEnabled() { return m_bDontBroadcastLan ? false : true; } + unsigned short GetHTTPPort(); + eHTTPDownloadType GetHTTPDownloadType() { return m_ucHTTPDownloadType; }; + const std::string& GetHTTPDownloadURL() { return m_strHTTPDownloadURL; }; + int GetHTTPMaxConnectionsPerClient() { return m_iHTTPMaxConnectionsPerClient; }; + int GetHTTPThreadCount() { return m_iHTTPThreadCount; }; + int GetHTTPDosThreshold() { return m_iHTTPDosThreshold; }; + const SString& GetHTTPDosExclude() { return m_strHTTPDosExclude; }; + int GetEnableClientChecks() { return m_iEnableClientChecks; }; + const std::string& GetLogFile() { return m_strLogFile; }; + const std::string& GetAuthFile() { return m_strAuthFile; }; + bool GetJoinFloodProtectionEnabled() { return m_bJoinFloodProtectionEnabled; }; + bool GetScriptDebugLogEnabled() { return m_bScriptDebugLogEnabled && !m_strScriptDebugLogFile.empty(); }; + const std::string& GetScriptDebugLogFile() { return m_strScriptDebugLogFile; }; + unsigned int GetScriptDebugLogLevel() { return m_uiScriptDebugLogLevel; }; + const std::string& GetAccessControlListFile() { return m_strAccessControlListFile; }; + bool GetSerialVerificationEnabled() { return m_bVerifySerials; }; const std::map& GetRulesForASE() const noexcept { return m_RulesForASEMap; }; - bool IsDisableAC(const char* szTagAC) { return MapContains(m_DisableComboACMap, szTagAC); }; - bool IsEnableDiagnostic(const char* szTag) { return MapContains(m_EnableDiagnosticMap, szTag); }; - CMtaVersion GetMinClientVersion() { return m_strMinClientVersion; } - const CMtaVersion& GetRecommendedClientVersion() { return m_strRecommendedClientVersion; } - int GetMinClientVersionAutoUpdate() { return m_iMinClientVersionAutoUpdate; } - const SString& GetIdFile() { return m_strIdFile; } - bool GetThreadNetEnabled() { return m_bThreadNetEnabled; } - const SString& GetGlobalDatabasesPath() { return m_strGlobalDatabasesPath; } - const SString& GetSystemDatabasesPath() { return m_strSystemDatabasesPath; } - const SString& GetBackupPath() { return m_strBackupPath; } - int GetBackupInterval() { return m_iBackupInterval; } - int GetBackupAmount() { return m_iBackupAmount; } - void NotifyDidBackup(); - bool ShouldCompactInternalDatabases(); - std::uint16_t GetFPSLimit() const noexcept { return m_fpsLimit; }; - bool SetFPSLimit(std::uint16_t fps, bool save); - int GetPendingWorkToDoSleepTime(); - int GetNoWorkToDoSleepTime(); - int GetServerLogicFpsLimit() { return m_iServerLogicFpsLimit; }; - const SString& GetDbLogFilename() { return m_strDbLogFilename; } - bool GetSyncMapElementData() const { return m_bSyncMapElementData; } - void SetSyncMapElementData(bool bOn) { m_bSyncMapElementData = bOn; } - bool GetBulletSyncEnabled() const { return m_bBulletSyncEnabled != 0; } - int GetVehExtrapolatePercent() const { return m_iVehExtrapolatePercent; } - int GetVehExtrapolatePingLimit() const { return m_iVehExtrapolatePingLimit; } - bool GetUseAltPulseOrder() const { return m_bUseAltPulseOrder != 0; } - const SString& GetLoadstringLogFilename() const { return m_strLoadstringLogFilename; } - bool GetLoadstringLogEnabled() const { return !m_strLoadstringLogFilename.empty(); } - bool GetCrashDumpUploadEnabled() const { return m_bCrashDumpUploadEnabled != 0; } - bool GetFilterDuplicateLogLinesEnabled() const { return m_bFilterDuplicateLogLinesEnabled != 0; } - bool IsAuthSerialGroup(const SString& strGroup) const { return ListContains(m_AuthSerialGroupList, strGroup); }; - bool IsAuthSerialHttpIpException(const SString& strIp) const { return ListContains(m_AuthSerialHttpIpExceptionList, strIp); } - bool GetAuthSerialEnabled() const { return !m_AuthSerialGroupList.empty(); }; - bool GetAuthSerialHttpEnabled() const { return m_bAuthSerialHttpEnabled && GetAuthSerialEnabled(); }; - const std::vector& GetAuthSerialGroupList() const { return m_AuthSerialGroupList; } - const std::vector& GetAuthSerialHttpIpExceptionList() const { return m_AuthSerialHttpIpExceptionList; } - const std::vector& GetOwnerEmailAddressList() const { return m_OwnerEmailAddressList; } - bool IsDatabaseCredentialsProtectionEnabled() const { return m_bDatabaseCredentialsProtectionEnabled != 0; } - bool IsFakeLagCommandEnabled() const { return m_bFakeLagCommandEnabled != 0; } - bool IsElementDataWhitelisted() const { return m_elementDataWhitelisted; } - bool IsCheckDuplicateSerialsEnabled() const noexcept { return m_checkDuplicateSerials; } - bool IsCheckResourceClientFilesEnabled() const noexcept { return m_checkResourceClientFiles != 0; } + bool IsDisableAC(const char* szTagAC) { return MapContains(m_DisableComboACMap, szTagAC); }; + bool IsEnableDiagnostic(const char* szTag) { return MapContains(m_EnableDiagnosticMap, szTag); }; + CMtaVersion GetMinClientVersion() { return m_strMinClientVersion; } + const CMtaVersion& GetRecommendedClientVersion() { return m_strRecommendedClientVersion; } + int GetMinClientVersionAutoUpdate() { return m_iMinClientVersionAutoUpdate; } + const SString& GetIdFile() { return m_strIdFile; } + bool GetThreadNetEnabled() { return m_bThreadNetEnabled; } + const SString& GetGlobalDatabasesPath() { return m_strGlobalDatabasesPath; } + const SString& GetSystemDatabasesPath() { return m_strSystemDatabasesPath; } + const SString& GetBackupPath() { return m_strBackupPath; } + int GetBackupInterval() { return m_iBackupInterval; } + int GetBackupAmount() { return m_iBackupAmount; } + void NotifyDidBackup(); + bool ShouldCompactInternalDatabases(); + std::uint16_t GetFPSLimit() const noexcept { return m_fpsLimit; }; + bool SetFPSLimit(std::uint16_t fps, bool save); + int GetPendingWorkToDoSleepTime(); + int GetNoWorkToDoSleepTime(); + int GetServerLogicFpsLimit() { return m_iServerLogicFpsLimit; }; + const SString& GetDbLogFilename() { return m_strDbLogFilename; } + bool GetSyncMapElementData() const { return m_bSyncMapElementData; } + void SetSyncMapElementData(bool bOn) { m_bSyncMapElementData = bOn; } + bool GetBulletSyncEnabled() const { return m_bBulletSyncEnabled != 0; } + int GetVehExtrapolatePercent() const { return m_iVehExtrapolatePercent; } + int GetVehExtrapolatePingLimit() const { return m_iVehExtrapolatePingLimit; } + bool GetUseAltPulseOrder() const { return m_bUseAltPulseOrder != 0; } + const SString& GetLoadstringLogFilename() const { return m_strLoadstringLogFilename; } + bool GetLoadstringLogEnabled() const { return !m_strLoadstringLogFilename.empty(); } + bool GetCrashDumpUploadEnabled() const { return m_bCrashDumpUploadEnabled != 0; } + bool GetFilterDuplicateLogLinesEnabled() const { return m_bFilterDuplicateLogLinesEnabled != 0; } + bool IsAuthSerialGroup(const SString& strGroup) const { return ListContains(m_AuthSerialGroupList, strGroup); }; + bool IsAuthSerialHttpIpException(const SString& strIp) const { return ListContains(m_AuthSerialHttpIpExceptionList, strIp); } + bool GetAuthSerialEnabled() const { return !m_AuthSerialGroupList.empty(); }; + bool GetAuthSerialHttpEnabled() const { return m_bAuthSerialHttpEnabled && GetAuthSerialEnabled(); }; + const std::vector& GetAuthSerialGroupList() const { return m_AuthSerialGroupList; } + const std::vector& GetAuthSerialHttpIpExceptionList() const { return m_AuthSerialHttpIpExceptionList; } + const std::vector& GetOwnerEmailAddressList() const { return m_OwnerEmailAddressList; } + bool IsDatabaseCredentialsProtectionEnabled() const { return m_bDatabaseCredentialsProtectionEnabled != 0; } + bool IsFakeLagCommandEnabled() const { return m_bFakeLagCommandEnabled != 0; } + bool IsElementDataWhitelisted() const { return m_elementDataWhitelisted; } + bool IsCheckDuplicateSerialsEnabled() const noexcept { return m_checkDuplicateSerials; } + bool IsCheckResourceClientFilesEnabled() const noexcept { return m_checkResourceClientFiles != 0; } SString GetSetting(const SString& configSetting); bool GetSetting(const SString& configSetting, SString& strValue); diff --git a/Server/mods/deathmatch/logic/CMapEventManager.cpp b/Server/mods/deathmatch/logic/CMapEventManager.cpp index 7006fa1d359..0ebc786c190 100644 --- a/Server/mods/deathmatch/logic/CMapEventManager.cpp +++ b/Server/mods/deathmatch/logic/CMapEventManager.cpp @@ -166,11 +166,11 @@ bool CMapEventManager::Call(const char* szName, const CLuaArguments& Arguments, // Grab the current VM lua_State* pState = pMapEvent->GetVM()->GetVM(); - LUA_CHECKSTACK(pState, 1); // Ensure some room + LUA_CHECKSTACK(pState, 1); // Ensure some room - #if MTA_DEBUG +#if MTA_DEBUG int luaStackPointer = lua_gettop(pState); - #endif +#endif TIMEUS startTime = GetTimeUs(); @@ -267,9 +267,9 @@ bool CMapEventManager::Call(const char* szName, const CLuaArguments& Arguments, OldClient.Push(pState); lua_setglobal(pState, "client"); - #if MTA_DEBUG +#if MTA_DEBUG assert(lua_gettop(pState) == luaStackPointer); - #endif +#endif CPerfStatLuaTiming::GetSingleton()->UpdateLuaTiming(pMapEvent->GetVM(), szName, GetTimeUs() - startTime); } diff --git a/Server/mods/deathmatch/logic/CMapManager.cpp b/Server/mods/deathmatch/logic/CMapManager.cpp index d62ad044f42..29b9c7eb2e4 100644 --- a/Server/mods/deathmatch/logic/CMapManager.cpp +++ b/Server/mods/deathmatch/logic/CMapManager.cpp @@ -372,8 +372,8 @@ void CMapManager::BroadcastResourceElements(CElement* pResourceElement, CElement CEntityAddPacket Packet; Packet.Add(pResourceElement); - std::set doneElements; // Lookup map of elements already processed - std::vector pPerPlayerList; // A list of per player elements we will process the last + std::set doneElements; // Lookup map of elements already processed + std::vector pPerPlayerList; // A list of per player elements we will process the last if (pResourceElement->CountChildren() > 0) BroadcastElementChildren(pResourceElement, Packet, pPerPlayerList, doneElements); @@ -524,11 +524,11 @@ void CMapManager::OnPlayerJoin(CPlayer& Player) // Send the packet to the given player Player.Send(CMapInfoPacket(ucCurrentWeather, ucWeatherBlendingTo, ucBlendedWeatherHour, ucClockHour, ucClockMin, ulMinuteDuration, bNametagsEnabled, bRadarEnabled, fGravity, fGameSpeed, fWaveHeight, worldWaterLevelInfo, bHasSkyGradient, garageStates, ucTopRed, ucTopGreen, - ucTopBlue, ucBottomRed, ucBottomGreen, ucBottomBlue, bHasHeatHaze, heatHazeSettings, fps, bCloudsEnabled, - fJetpackMaxHeight, bOverrideWaterColor, ucWaterRed, ucWaterGreen, ucWaterBlue, ucWaterAlpha, bInteriorSoundsEnabled, - bOverrideRainLevel, fRainLevel, bOverrideSunSize, fSunSize, bOverrideSunColor, ucCoreR, ucCoreG, ucCoreB, ucCoronaR, ucCoronaG, - ucCoronaB, bOverrideWindVelocity, fWindVelX, fWindVelY, fWindVelZ, bOverrideFarClipDistance, fFarClip, bOverrideFogDistance, - fFogDistance, fAircraftMaxHeight, fAircraftMaxVelocity, bOverrideMoonSize, iMoonSize)); + ucTopBlue, ucBottomRed, ucBottomGreen, ucBottomBlue, bHasHeatHaze, heatHazeSettings, fps, bCloudsEnabled, fJetpackMaxHeight, + bOverrideWaterColor, ucWaterRed, ucWaterGreen, ucWaterBlue, ucWaterAlpha, bInteriorSoundsEnabled, bOverrideRainLevel, fRainLevel, + bOverrideSunSize, fSunSize, bOverrideSunColor, ucCoreR, ucCoreG, ucCoreB, ucCoronaR, ucCoronaG, ucCoronaB, bOverrideWindVelocity, + fWindVelX, fWindVelY, fWindVelZ, bOverrideFarClipDistance, fFarClip, bOverrideFogDistance, fFogDistance, fAircraftMaxHeight, + fAircraftMaxVelocity, bOverrideMoonSize, iMoonSize)); marker.Set("SendMapInfoPacket"); diff --git a/Server/mods/deathmatch/logic/CMarker.cpp b/Server/mods/deathmatch/logic/CMarker.cpp index 5596de0848f..5eabd474891 100644 --- a/Server/mods/deathmatch/logic/CMarker.cpp +++ b/Server/mods/deathmatch/logic/CMarker.cpp @@ -343,15 +343,15 @@ void CMarker::Callback_OnCollision(CColShape& Shape, CElement& Element) { // Call the marker hit event CLuaArguments Arguments; - Arguments.PushElement(&Element); // Hit element - Arguments.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? + Arguments.PushElement(&Element); // Hit element + Arguments.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? CallEvent("onMarkerHit", Arguments); if (IS_PLAYER(&Element)) { CLuaArguments Arguments2; - Arguments2.PushElement(this); // marker - Arguments2.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? + Arguments2.PushElement(this); // marker + Arguments2.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? Element.CallEvent("onPlayerMarkerHit", Arguments2); } } @@ -364,15 +364,15 @@ void CMarker::Callback_OnLeave(CColShape& Shape, CElement& Element) { // Call the marker hit event CLuaArguments Arguments; - Arguments.PushElement(&Element); // Hit element - Arguments.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? + Arguments.PushElement(&Element); // Hit element + Arguments.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? CallEvent("onMarkerLeave", Arguments); if (IS_PLAYER(&Element)) { CLuaArguments Arguments2; - Arguments2.PushElement(this); // marker - Arguments2.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? + Arguments2.PushElement(this); // marker + Arguments2.PushBoolean(GetDimension() == Element.GetDimension()); // Matching dimension? Element.CallEvent("onPlayerMarkerLeave", Arguments2); } } @@ -410,7 +410,7 @@ void CMarker::UpdateCollisionObject(unsigned char ucOldType) { if (m_pCollision) g_pGame->GetElementDeleter()->Delete(m_pCollision); - + m_pCollision = new CColSphere(m_pColManager, nullptr, m_vecPosition, m_fSize, true); } diff --git a/Server/mods/deathmatch/logic/CMarker.h b/Server/mods/deathmatch/logic/CMarker.h index ddc9c4831ac..d48c08d2d67 100644 --- a/Server/mods/deathmatch/logic/CMarker.h +++ b/Server/mods/deathmatch/logic/CMarker.h @@ -72,7 +72,7 @@ class CMarker : public CPerPlayerEntity, private CColCallback SColor GetTargetArrowColor() const noexcept { return m_TargetArrowColor; }; float GetTargetArrowSize() const noexcept { return m_TargetArrowSize; }; - void SetTargetArrowProperties(const SColor color, float size) noexcept; + void SetTargetArrowProperties(const SColor color, float size) noexcept; protected: bool ReadSpecialData(const int iLine) override; diff --git a/Server/mods/deathmatch/logic/CObject.cpp b/Server/mods/deathmatch/logic/CObject.cpp index bde33eb009e..4c5e7d30ec2 100644 --- a/Server/mods/deathmatch/logic/CObject.cpp +++ b/Server/mods/deathmatch/logic/CObject.cpp @@ -248,7 +248,7 @@ const CVector& CObject::GetPosition() } if (vecOldPosition != m_vecPosition) - UpdateSpatialData(); // This is necessary because 'GetAttachedPosition ( m_vecPosition )' can change alter this objects position + UpdateSpatialData(); // This is necessary because 'GetAttachedPosition ( m_vecPosition )' can change alter this objects position // Finally, return it return m_vecPosition; } @@ -377,7 +377,7 @@ void CObject::StopMoving() const CPositionRotationAnimation* CObject::GetMoveAnimation() { - if (IsMoving()) // Call IsMoving since it will make sure the anim is stopped if it's finished + if (IsMoving()) // Call IsMoving since it will make sure the anim is stopped if it's finished { return m_pMoveAnimation; } diff --git a/Server/mods/deathmatch/logic/CObject.h b/Server/mods/deathmatch/logic/CObject.h index 5fc8c02a179..23a0cf91907 100644 --- a/Server/mods/deathmatch/logic/CObject.h +++ b/Server/mods/deathmatch/logic/CObject.h @@ -106,9 +106,9 @@ class CObject : public CElement protected: bool m_bCollisionsEnabled; - const bool m_bIsLowLod; // true if this object is low LOD - CObject* m_pLowLodObject; // Pointer to low LOD version of this object - std::vector m_HighLodObjectList; // List of objects that use this object as a low LOD version + const bool m_bIsLowLod; // true if this object is low LOD + CObject* m_pLowLodObject; // Pointer to low LOD version of this object + std::vector m_HighLodObjectList; // List of objects that use this object as a low LOD version public: CPositionRotationAnimation* m_pMoveAnimation; diff --git a/Server/mods/deathmatch/logic/CObjectSync.cpp b/Server/mods/deathmatch/logic/CObjectSync.cpp index e6a98078b79..745d4f89da5 100644 --- a/Server/mods/deathmatch/logic/CObjectSync.cpp +++ b/Server/mods/deathmatch/logic/CObjectSync.cpp @@ -14,8 +14,8 @@ #ifdef WITH_OBJECT_SYNC -#define SYNC_RATE 500 -#define MAX_PLAYER_SYNC_DISTANCE 100.0f + #define SYNC_RATE 500 + #define MAX_PLAYER_SYNC_DISTANCE 100.0f CObjectSync::CObjectSync(CPlayerManager* pPlayerManager, CObjectManager* pObjectManager) { @@ -141,7 +141,7 @@ void CObjectSync::StartSync(CPlayer* pPlayer, CObject* pObject) // Call the onElementStartSync event CLuaArguments Arguments; - Arguments.PushElement(pPlayer); // New syncer + Arguments.PushElement(pPlayer); // New syncer pObject->CallEvent("onElementStartSync", Arguments); } @@ -158,7 +158,7 @@ void CObjectSync::StopSync(CObject* pObject) // Call the onElementStopSync event CLuaArguments Arguments; - Arguments.PushElement(pSyncer); // Old syncer + Arguments.PushElement(pSyncer); // Old syncer pObject->CallEvent("onElementStopSync", Arguments); } diff --git a/Server/mods/deathmatch/logic/CObjectSync.h b/Server/mods/deathmatch/logic/CObjectSync.h index e24eb1d928f..9aa8fee125b 100644 --- a/Server/mods/deathmatch/logic/CObjectSync.h +++ b/Server/mods/deathmatch/logic/CObjectSync.h @@ -13,9 +13,9 @@ #ifdef WITH_OBJECT_SYNC -#include "CPlayerManager.h" -#include "CObjectManager.h" -#include "packets/CObjectSyncPacket.h" + #include "CPlayerManager.h" + #include "CObjectManager.h" + #include "packets/CObjectSyncPacket.h" class CObjectSync { diff --git a/Server/mods/deathmatch/logic/CPacketTranslator.cpp b/Server/mods/deathmatch/logic/CPacketTranslator.cpp index 2d12509c502..20ced1ab808 100644 --- a/Server/mods/deathmatch/logic/CPacketTranslator.cpp +++ b/Server/mods/deathmatch/logic/CPacketTranslator.cpp @@ -250,10 +250,10 @@ CPacket* CPacketTranslator::Translate(const NetServerPlayerID& Socket, ePacketID else // Attempt to read the content, if we fail, delete the packet again if (!pTemp->Read(BitStream)) - { - delete pTemp; - pTemp = NULL; - } + { + delete pTemp; + pTemp = NULL; + } } // Return the class diff --git a/Server/mods/deathmatch/logic/CPad.cpp b/Server/mods/deathmatch/logic/CPad.cpp index b8676bde1ac..a7a3f2713f0 100644 --- a/Server/mods/deathmatch/logic/CPad.cpp +++ b/Server/mods/deathmatch/logic/CPad.cpp @@ -78,7 +78,7 @@ static const SString g_mtaControls[] = { "vehicle_next_weapon", "vehicle_previous_weapon", "sinfo", - "textscale" // Anything missing here? + "textscale" // Anything missing here? }; CPad::CPad(CPlayer* pPlayer) @@ -121,10 +121,10 @@ void CPad::UpdateKeys() m_ControlStates[0].bState = (m_csCurrentState.ButtonCircle) ? true : false; m_ControlStates[1].bState = (m_csCurrentState.RightShoulder2) ? true : false; m_ControlStates[2].bState = (m_csCurrentState.LeftShoulder2) ? true : false; - m_ControlStates[3].bState = (m_csCurrentState.LeftStickY < 0); // forwards - m_ControlStates[4].bState = (m_csCurrentState.LeftStickY > 0); // backwards - m_ControlStates[5].bState = (m_csCurrentState.LeftStickX < 0); // left - m_ControlStates[6].bState = (m_csCurrentState.LeftStickX > 0); // right + m_ControlStates[3].bState = (m_csCurrentState.LeftStickY < 0); // forwards + m_ControlStates[4].bState = (m_csCurrentState.LeftStickY > 0); // backwards + m_ControlStates[5].bState = (m_csCurrentState.LeftStickX < 0); // left + m_ControlStates[6].bState = (m_csCurrentState.LeftStickX > 0); // right m_ControlStates[7].bState = (m_csCurrentState.RightShoulder2) ? true : false; m_ControlStates[8].bState = (m_csCurrentState.LeftShoulder2) ? true : false; m_ControlStates[9].bState = (m_csCurrentState.LeftShoulder2) ? true : false; @@ -167,8 +167,8 @@ void CPad::UpdateKeys() m_ControlStates[37].bState = (m_csCurrentState.RightStickY > 0); m_ControlStates[38].bState = (m_csCurrentState.RightStickY < 0); } - m_ControlStates[9].bState = (m_csCurrentState.ButtonTriangle); // Enter Exit - m_ControlStates[10].bState = (m_csCurrentState.Select) ? true : false; // Change View + m_ControlStates[9].bState = (m_csCurrentState.ButtonTriangle); // Enter Exit + m_ControlStates[10].bState = (m_csCurrentState.Select) ? true : false; // Change View } } diff --git a/Server/mods/deathmatch/logic/CPad.h b/Server/mods/deathmatch/logic/CPad.h index 203e3d9ac99..18ea6cc5fe7 100644 --- a/Server/mods/deathmatch/logic/CPad.h +++ b/Server/mods/deathmatch/logic/CPad.h @@ -20,9 +20,9 @@ class CPad; class CControllerState { public: - signed short LeftStickX; // move/steer left (-128?)/right (+128) - signed short LeftStickY; // move back(+128)/forwards(-128?) - signed short RightStickX; // numpad 6(+128)/numpad 4(-128?) + signed short LeftStickX; // move/steer left (-128?)/right (+128) + signed short LeftStickY; // move back(+128)/forwards(-128?) + signed short RightStickX; // numpad 6(+128)/numpad 4(-128?) signed short RightStickY; // signed short LeftShoulder1; @@ -30,8 +30,8 @@ class CControllerState // signed short RightShoulder1; // target / hand brake signed short RightShoulder2; - signed short DPadUp; // radio change up - signed short DPadDown; // radio change down + signed short DPadUp; // radio change up + signed short DPadDown; // radio change down signed short DPadLeft; signed short DPadRight; @@ -44,7 +44,7 @@ class CControllerState // signed short ButtonCircle; // fire // signed short ShockButtonL; - signed short ShockButtonR; // look behind + signed short ShockButtonR; // look behind signed short m_bChatIndicated; // signed short m_bPedWalk; @@ -137,7 +137,7 @@ struct SGTAControlState bool bEnabled; }; -#define NUM_CONTROL_STATES 45 +#define NUM_CONTROL_STATES 45 #define NUM_MTA_CONTROL_STATES 19 class CPad diff --git a/Server/mods/deathmatch/logic/CPed.cpp b/Server/mods/deathmatch/logic/CPed.cpp index c7493fb7833..e782a2b139c 100644 --- a/Server/mods/deathmatch/logic/CPed.cpp +++ b/Server/mods/deathmatch/logic/CPed.cpp @@ -41,7 +41,7 @@ CPed::CPed(CPedManager* pPedManager, CElement* pParent, unsigned short usModel) m_armor = 0.0f; memset(&m_fStats[0], 0, sizeof(m_fStats)); - m_fStats[24] = 569.0f; // default max_health + m_fStats[24] = 569.0f; // default max_health m_pClothes = new CPlayerClothes; m_pClothes->DefaultClothes(); @@ -63,7 +63,7 @@ CPed::CPed(CPedManager* pPedManager, CElement* pParent, unsigned short usModel) m_bSpawned = false; m_fRotation = 0.0f; m_pTargetedEntity = NULL; - m_ucFightingStyle = 15; // STYLE_GRAB_KICK + m_ucFightingStyle = 15; // STYLE_GRAB_KICK m_iMoveAnim = MOVE_DEFAULT; m_fGravity = 0.008f; m_bDoingGangDriveby = false; diff --git a/Server/mods/deathmatch/logic/CPed.h b/Server/mods/deathmatch/logic/CPed.h index 22adb2a5c33..e3c44201909 100644 --- a/Server/mods/deathmatch/logic/CPed.h +++ b/Server/mods/deathmatch/logic/CPed.h @@ -19,9 +19,9 @@ #include #define INVALID_VEHICLE_SEAT 0xFF -#define NUM_PLAYER_STATS 343 -#define WEAPON_SLOTS 13 -#define STEALTH_KILL_RANGE 2.5f +#define NUM_PLAYER_STATS 343 +#define WEAPON_SLOTS 13 +#define STEALTH_KILL_RANGE 2.5f enum ePedMoveAnim { @@ -353,7 +353,7 @@ class CPed : public CElement CVehicle* m_pJackingVehicle; SPlayerAnimData m_animData{}; float m_cameraRotation{}; - bool m_hanging{false}; // Is the player hanging during a climb task? + bool m_hanging{false}; // Is the player hanging during a climb task? CVehicle* m_pVehicle; unsigned int m_uiVehicleSeat; diff --git a/Server/mods/deathmatch/logic/CPedSync.cpp b/Server/mods/deathmatch/logic/CPedSync.cpp index 42952266cf1..fa09b51661e 100644 --- a/Server/mods/deathmatch/logic/CPedSync.cpp +++ b/Server/mods/deathmatch/logic/CPedSync.cpp @@ -163,7 +163,7 @@ void CPedSync::StartSync(CPlayer* pPlayer, CPed* pPed) // Call the onElementStartSync event CLuaArguments Arguments; - Arguments.PushElement(pPlayer); // New syncer + Arguments.PushElement(pPlayer); // New syncer pPed->CallEvent("onElementStartSync", Arguments); } @@ -180,7 +180,7 @@ void CPedSync::StopSync(CPed* pPed) // Call the onElementStopSync event CLuaArguments Arguments; - Arguments.PushElement(pSyncer); // Old syncer + Arguments.PushElement(pSyncer); // Old syncer pPed->CallEvent("onElementStopSync", Arguments); } diff --git a/Server/mods/deathmatch/logic/CPerPlayerEntity.cpp b/Server/mods/deathmatch/logic/CPerPlayerEntity.cpp index 9c4ec6969e3..050f6747df5 100644 --- a/Server/mods/deathmatch/logic/CPerPlayerEntity.cpp +++ b/Server/mods/deathmatch/logic/CPerPlayerEntity.cpp @@ -77,7 +77,7 @@ void CPerPlayerEntity::OnReferencedSubtreeRemove(CElement* pElement) void CPerPlayerEntity::UpdatePerPlayer() { - if (m_PlayersAdded.empty() && m_PlayersRemoved.empty()) // This check reduces cpu usage when loading large maps (due to recursion) + if (m_PlayersAdded.empty() && m_PlayersRemoved.empty()) // This check reduces cpu usage when loading large maps (due to recursion) return; // Remove entries that match in both added and removed lists @@ -310,7 +310,7 @@ void CPerPlayerEntity::AddPlayersBelow(CElement* pElement, std::set& A for (; iterChildren != pElement->IterEnd(); iterChildren++) { CElement* pElement = *iterChildren; - if (pElement->CountChildren() || IS_PLAYER(pElement)) // This check reduces cpu usage when loading large maps (due to recursion) + if (pElement->CountChildren() || IS_PLAYER(pElement)) // This check reduces cpu usage when loading large maps (due to recursion) AddPlayersBelow(pElement, Added); } } @@ -338,7 +338,7 @@ void CPerPlayerEntity::RemovePlayersBelow(CElement* pElement, std::set for (; iterChildren != pElement->IterEnd(); iterChildren++) { CElement* pElement = *iterChildren; - if (pElement->CountChildren() || IS_PLAYER(pElement)) // This check reduces cpu usage when unloading large maps (due to recursion) + if (pElement->CountChildren() || IS_PLAYER(pElement)) // This check reduces cpu usage when unloading large maps (due to recursion) RemovePlayersBelow(pElement, Removed); } } diff --git a/Server/mods/deathmatch/logic/CPerfStat.BandwidthUsage.cpp b/Server/mods/deathmatch/logic/CPerfStat.BandwidthUsage.cpp index e4602ba035a..457abb7e291 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.BandwidthUsage.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.BandwidthUsage.cpp @@ -52,7 +52,7 @@ namespace BWSTAT_INDEX_COUNT, }; - #define BW_STATS_TABLE_NAME "`perfstats_bandwidth_usage`" +#define BW_STATS_TABLE_NAME "`perfstats_bandwidth_usage`" SFixedArray BWStatIndexNameList = {{ "Special", @@ -83,11 +83,17 @@ namespace } // Unix time in, stats hours out - uint UnixTimeToStatsHours(time_t tTime) { return static_cast((tTime - 1293861600UL) / 3600UL); } + uint UnixTimeToStatsHours(time_t tTime) + { + return static_cast((tTime - 1293861600UL) / 3600UL); + } // Stats hours in, unix time out - time_t StatsHoursToUnixTime(uint uiStatsHours) { return uiStatsHours * 3600UL + 1293861600UL; } -} // namespace + time_t StatsHoursToUnixTime(uint uiStatsHours) + { + return uiStatsHours * 3600UL + 1293861600UL; + } +} // namespace /////////////////////////////////////////////////////////////// // @@ -302,8 +308,8 @@ void CPerfStatBandwidthUsageImpl::LoadStats() // Special item const SNetStatHistoryType& type = m_History[BWSTAT_INDEX_SPECIAL]; - uint uiStatsHoursThen = (uint)type.itemList[0].llGameSent; // Hours since 1/1/2011 - uint uiStatsHoursNow = UnixTimeToStatsHours(tTime); // Hours since 1/1/2011 + uint uiStatsHoursThen = (uint)type.itemList[0].llGameSent; // Hours since 1/1/2011 + uint uiStatsHoursNow = UnixTimeToStatsHours(tTime); // Hours since 1/1/2011 int iHoursElpased = uiStatsHoursNow - uiStatsHoursThen; // Max elapsed time of 13 months @@ -482,7 +488,7 @@ void CPerfStatBandwidthUsageImpl::AddSampleAtTime(time_t tTime, long long llGame else if (i == BWSTAT_INDEX_SPECIAL) { // Calculate special value - uint uiStatsHours = UnixTimeToStatsHours(tTime); // Hours since 1/1/2011 + uint uiStatsHours = UnixTimeToStatsHours(tTime); // Hours since 1/1/2011 if (uiStatsHours != (uint)type.itemList[0].llGameSent) { type.itemList[0].bDirty = true; diff --git a/Server/mods/deathmatch/logic/CPerfStat.DebugInfo.cpp b/Server/mods/deathmatch/logic/CPerfStat.DebugInfo.cpp index d2d83362caa..a9251fa7350 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.DebugInfo.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.DebugInfo.cpp @@ -20,7 +20,7 @@ namespace SString strHead; SString strData; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // diff --git a/Server/mods/deathmatch/logic/CPerfStat.DebugTable.cpp b/Server/mods/deathmatch/logic/CPerfStat.DebugTable.cpp index b27d27f7322..32e6d54d502 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.DebugTable.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.DebugTable.cpp @@ -20,7 +20,7 @@ namespace CTickCount endTickCount; bool bHasEndTime; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -49,7 +49,7 @@ class CPerfStatDebugTableImpl : public CPerfStatDebugTable SString m_strCategoryName; CElapsedTime m_TimeSinceRemoveOld; std::map m_LineMap; - CCriticalSection m_CS; // Required as some methods are called from the database thread + CCriticalSection m_CS; // Required as some methods are called from the database thread }; /////////////////////////////////////////////////////////////// diff --git a/Server/mods/deathmatch/logic/CPerfStat.FunctionTiming.cpp b/Server/mods/deathmatch/logic/CPerfStat.FunctionTiming.cpp index ccea827200e..58bca2c51da 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.FunctionTiming.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.FunctionTiming.cpp @@ -76,7 +76,7 @@ namespace } }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // diff --git a/Server/mods/deathmatch/logic/CPerfStat.LibMemory.cpp b/Server/mods/deathmatch/logic/CPerfStat.LibMemory.cpp index 2b4c4a15b37..0aa6150095b 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.LibMemory.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.LibMemory.cpp @@ -46,7 +46,7 @@ namespace CDynamicLibrary* pLibrary; PFNGETALLOCSTATS pfnGetAllocStats; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -217,16 +217,16 @@ void CPerfStatLibMemoryImpl::GetLibMemoryStats(CPerfStatResult* pResult, const s { CLibraryInfo info; info.strName = libs[i]; - #if MTA_DEBUG +#if MTA_DEBUG info.strName += "_d"; - #endif - #ifdef WIN32 +#endif +#ifdef WIN32 info.strName += ".dll"; - #elif defined(__APPLE__) +#elif defined(__APPLE__) info.strName += ".dylib"; - #else +#else info.strName += ".so"; - #endif +#endif info.pLibrary = new CDynamicLibrary(); SString strPathFilename = g_pServerInterface->GetAbsolutePath(info.strName); diff --git a/Server/mods/deathmatch/logic/CPerfStat.LuaMemory.cpp b/Server/mods/deathmatch/logic/CPerfStat.LuaMemory.cpp index c8ff647532f..f930d51528c 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.LuaMemory.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.LuaMemory.cpp @@ -41,7 +41,7 @@ namespace public: CLuaMainMemoryMap LuaMainMemoryMap; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // diff --git a/Server/mods/deathmatch/logic/CPerfStat.LuaTiming.cpp b/Server/mods/deathmatch/logic/CPerfStat.LuaTiming.cpp index 0fd55bf5703..45af36c8b09 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.LuaTiming.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.LuaTiming.cpp @@ -33,8 +33,8 @@ namespace struct CTimingPair { - CTiming acc; // Accumulator for current period - CTiming prev; // Result for previous period + CTiming acc; // Accumulator for current period + CTiming prev; // Result for previous period void Pulse(CTimingPair* above) { @@ -48,10 +48,10 @@ namespace class CTimingBlock { public: - CTimingPair s5; // 5 second period - CTimingPair s60; // 60 - CTimingPair m5; // 300 - CTimingPair m60; // 3600 + CTimingPair s5; // 5 second period + CTimingPair s60; // 60 + CTimingPair m5; // 300 + CTimingPair m60; // 3600 void Pulse1s(int flags) { @@ -102,7 +102,7 @@ namespace } } }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -270,13 +270,13 @@ void CPerfStatLuaTimingImpl::DoPulse() int flags = 0; m_SecondCounter++; - if (m_SecondCounter % 5 == 0) // 1 second + if (m_SecondCounter % 5 == 0) // 1 second flags |= 1; - if (m_SecondCounter % 60 == 0) // 60 seconds + if (m_SecondCounter % 60 == 0) // 60 seconds flags |= 2; - if (m_SecondCounter % (60 * 5) == 0) // 5 mins + if (m_SecondCounter % (60 * 5) == 0) // 5 mins flags |= 4; - if (m_SecondCounter % (60 * 60) == 0) // 60 mins + if (m_SecondCounter % (60 * 60) == 0) // 60 mins flags |= 8; AllLuaTiming.Pulse1s(flags); diff --git a/Server/mods/deathmatch/logic/CPerfStat.PacketUsage.cpp b/Server/mods/deathmatch/logic/CPerfStat.PacketUsage.cpp index 19cc44d5e9d..3b4c8ebe4e6 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.PacketUsage.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.PacketUsage.cpp @@ -252,7 +252,7 @@ void CPerfStatPacketUsageImpl::GetStats(CPerfStatResult* pResult, const std::map row[c++] = SString("%d", (statInDelta.iCount + 4) / 5); row[c++] = CPerfStatManager::GetScaledByteString((statInDelta.iTotalBytes + 4) / 5); row[c++] = SString("%2.2f%%", - statInDelta.totalTime / 50000.f); // Number of microseconds in sample period ( 5sec * 1000000 ) into percent ( * 100 ) + statInDelta.totalTime / 50000.f); // Number of microseconds in sample period ( 5sec * 1000000 ) into percent ( * 100 ) } else { diff --git a/Server/mods/deathmatch/logic/CPerfStat.PlayerPacketUsage.cpp b/Server/mods/deathmatch/logic/CPerfStat.PlayerPacketUsage.cpp index b621aab8e5f..81b3bd24253 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.PlayerPacketUsage.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.PlayerPacketUsage.cpp @@ -19,7 +19,7 @@ extern CNetServer* g_pRealNetServer; namespace { - #define TOP_COUNT (3) +#define TOP_COUNT (3) struct CTopValue { @@ -47,8 +47,8 @@ namespace struct CTimeSpan { - CTopSet acc; // Accumulator for current period - CTopSet prev; // Result for previous period + CTopSet acc; // Accumulator for current period + CTopSet prev; // Result for previous period void Pulse(CTimeSpan* above) { @@ -62,10 +62,10 @@ namespace class CTimeSpanBlock { public: - CTimeSpan s5; // 5 second period - CTimeSpan s60; // 60 - CTimeSpan m5; // 300 - CTimeSpan m60; // 3600 + CTimeSpan s5; // 5 second period + CTimeSpan s60; // 60 + CTimeSpan m5; // 300 + CTimeSpan m60; // 3600 void Pulse1s(int flags) { @@ -95,7 +95,7 @@ namespace } } }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -200,13 +200,13 @@ void CPerfStatPlayerPacketUsageImpl::DoPulse() int flags = 0; m_SecondCounter++; - if (m_SecondCounter % 5 == 0) // 5 second + if (m_SecondCounter % 5 == 0) // 5 second flags |= 1; - if (m_SecondCounter % 60 == 0) // 60 seconds + if (m_SecondCounter % 60 == 0) // 60 seconds flags |= 2; - if (m_SecondCounter % (5 * 60) == 0) // 5 mins + if (m_SecondCounter % (5 * 60) == 0) // 5 mins flags |= 4; - if (m_SecondCounter % (60 * 60) == 0) // 60 mins + if (m_SecondCounter % (60 * 60) == 0) // 60 mins flags |= 8; m_AllPlayerPacketUsage.Pulse1s(flags); diff --git a/Server/mods/deathmatch/logic/CPerfStat.ServerInfo.cpp b/Server/mods/deathmatch/logic/CPerfStat.ServerInfo.cpp index f997bb201d6..c9e170d044e 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.ServerInfo.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.ServerInfo.cpp @@ -51,8 +51,8 @@ namespace return strResult; } - #define UDP_PACKET_OVERHEAD (28LL) -} // namespace +#define UDP_PACKET_OVERHEAD (28LL) +} // namespace /////////////////////////////////////////////////////////////// // @@ -237,11 +237,11 @@ SString CPerfStatServerInfoImpl::GetProcessMemoryUsage() long rss; statStream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> - cutime >> cstime >> priority >> nice >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest + cutime >> cstime >> priority >> nice >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest statStream.close(); - long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages + long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages uint vm_usage = vsize / (1024 * 1024); uint resident_set = rss * page_size_kb / 1024; diff --git a/Server/mods/deathmatch/logic/CPerfStat.SqliteTiming.cpp b/Server/mods/deathmatch/logic/CPerfStat.SqliteTiming.cpp index f66cd919a7e..226375ac238 100644 --- a/Server/mods/deathmatch/logic/CPerfStat.SqliteTiming.cpp +++ b/Server/mods/deathmatch/logic/CPerfStat.SqliteTiming.cpp @@ -28,7 +28,7 @@ namespace SString databaseName; SString resourceName; }; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // @@ -219,7 +219,7 @@ void CPerfStatSqliteTimingImpl::GetStats(CPerfStatResult* pResult, const std::ma { GetSqliteTimingStats(pResult, optionMap, strFilter); - uint uiTicks = 1000 * 10; // 10 seconds + uint uiTicks = 1000 * 10; // 10 seconds long long llTime = GetTickCount64_(); m_llRecordStatsEndTime = llTime + uiTicks; @@ -228,9 +228,9 @@ void CPerfStatSqliteTimingImpl::GetStats(CPerfStatResult* pResult, const std::ma for (std::map::iterator iter = m_RegistryMap.begin(); iter != m_RegistryMap.end(); ++iter) { if (m_bDisableBatching) - iter->first->SuspendBatching(uiTicks); // Suspend batching + iter->first->SuspendBatching(uiTicks); // Suspend batching else - iter->first->SuspendBatching(0); // Unsuspend batching + iter->first->SuspendBatching(0); // Unsuspend batching } } diff --git a/Server/mods/deathmatch/logic/CPerfStatManager.cpp b/Server/mods/deathmatch/logic/CPerfStatManager.cpp index 342984da0a1..b83a7d916cd 100644 --- a/Server/mods/deathmatch/logic/CPerfStatManager.cpp +++ b/Server/mods/deathmatch/logic/CPerfStatManager.cpp @@ -312,12 +312,12 @@ SString CPerfStatManager::GetScaledBitString(long long Amount) SString CPerfStatManager::GetScaledFloatString(float fValue) { if (fValue < 1) - return SString("%.2f", fValue); // 0.00 to 0.99 + return SString("%.2f", fValue); // 0.00 to 0.99 if (fValue < 5) - return SString("%.1f", fValue); // 1.0 to 4.9 + return SString("%.1f", fValue); // 1.0 to 4.9 - return SString("%.0f", fValue); // 5 to inf. and beyond + return SString("%.0f", fValue); // 5 to inf. and beyond } /////////////////////////////////////////////////////////////// diff --git a/Server/mods/deathmatch/logic/CPerfStatModule.h b/Server/mods/deathmatch/logic/CPerfStatModule.h index 9efa16bf246..fab0c4acd75 100644 --- a/Server/mods/deathmatch/logic/CPerfStatModule.h +++ b/Server/mods/deathmatch/logic/CPerfStatModule.h @@ -121,7 +121,7 @@ class CPerfStatModule virtual const SString& GetCategoryName() = 0; virtual void DoPulse() = 0; virtual void GetStats(CPerfStatResult* pOutResult, const std::map& optionMap, const SString& strFilter) = 0; - virtual void Stop(){}; + virtual void Stop() {}; }; // diff --git a/Server/mods/deathmatch/logic/CPickup.cpp b/Server/mods/deathmatch/logic/CPickup.cpp index a9589a6ac0a..45496ffa9f7 100644 --- a/Server/mods/deathmatch/logic/CPickup.cpp +++ b/Server/mods/deathmatch/logic/CPickup.cpp @@ -129,10 +129,10 @@ bool CPickup::ReadSpecialData(const int iLine) m_usModel = CPickupManager::GetArmorModel(); } else if (IsNumericString(szBuffer)) - { // could be a weapon + { // could be a weapon usBuffer = static_cast(atoi(szBuffer)); if (CPickupManager::IsValidWeaponID(usBuffer)) - { // its a weapon + { // its a weapon m_ucType = WEAPON; m_usModel = CPickupManager::GetWeaponModel(m_ucWeaponType); } @@ -243,7 +243,7 @@ bool CPickup::ReadSpecialData(const int iLine) if (GetCustomDataInt("model", iTemp, true)) { // Valid id? - if (CObjectManager::IsValidModel(iTemp) || iTemp == 370) // 370 = jetpack - sort of a hack + if (CObjectManager::IsValidModel(iTemp) || iTemp == 370) // 370 = jetpack - sort of a hack { // Set the object id m_usModel = static_cast(iTemp); @@ -406,13 +406,13 @@ void CPickup::Use(CPlayer& Player) if (!CallEvent("onPickupUse", Arguments)) { CLuaArguments Arguments2; - Arguments2.PushElement(this); // pickup + Arguments2.PushElement(this); // pickup Player.CallEvent("onPlayerPickupUse", Arguments2); } else { CLuaArguments Arguments2; - Arguments2.PushElement(this); // pickup + Arguments2.PushElement(this); // pickup if (Player.CallEvent("onPlayerPickupUse", Arguments2)) { // Tell all the other players to hide it if the respawn intervals are bigger than 0 @@ -497,7 +497,7 @@ void CPickup::Callback_OnCollision(CColShape& Shape, CElement& Element) bool bContinue1 = CallEvent("onPickupHit", Arguments); CLuaArguments Arguments2; - Arguments2.PushElement(this); // pickup + Arguments2.PushElement(this); // pickup bool bContinue2 = Element.CallEvent("onPlayerPickupHit", Arguments2); if (bContinue1 && bContinue2) @@ -540,7 +540,7 @@ void CPickup::Callback_OnLeave(CColShape& Shape, CElement& Element) CallEvent("onPickupLeave", Arguments); CLuaArguments Arguments2; - Arguments2.PushElement(this); // pickup + Arguments2.PushElement(this); // pickup Element.CallEvent("onPlayerPickupLeave", Arguments2); } } diff --git a/Server/mods/deathmatch/logic/CPickupManager.cpp b/Server/mods/deathmatch/logic/CPickupManager.cpp index 3641a530c04..2c5ea86daea 100644 --- a/Server/mods/deathmatch/logic/CPickupManager.cpp +++ b/Server/mods/deathmatch/logic/CPickupManager.cpp @@ -14,11 +14,11 @@ #include "Utils.h" static SFixedArray g_usWeaponModels = {{ - 0, 331, 333, 334, 335, 336, 337, 338, 339, 341, // 9 - 321, 322, 323, 324, 325, 326, 342, 343, 344, 0, // 19 - 0, 0, 346, 347, 348, 349, 350, 351, 352, 353, // 29 - 355, 356, 372, 357, 358, 359, 360, 361, 362, 363, // 39 - 364, 365, 366, 367, 368, 369, 371 // 46 + 0, 331, 333, 334, 335, 336, 337, 338, 339, 341, // 9 + 321, 322, 323, 324, 325, 326, 342, 343, 344, 0, // 19 + 0, 0, 346, 347, 348, 349, 350, 351, 352, 353, // 29 + 355, 356, 372, 357, 358, 359, 360, 361, 362, 363, // 39 + 364, 365, 366, 367, 368, 369, 371 // 46 }}; CPickupManager::CPickupManager(CColManager* pColManager) diff --git a/Server/mods/deathmatch/logic/CPlayer.cpp b/Server/mods/deathmatch/logic/CPlayer.cpp index c57ebc3aaac..7362ac4a936 100644 --- a/Server/mods/deathmatch/logic/CPlayer.cpp +++ b/Server/mods/deathmatch/logic/CPlayer.cpp @@ -97,7 +97,7 @@ CPlayer::CPlayer(CPlayerManager* pPlayerManager, class CScriptDebugging* pScript m_ucNametagB = 0xFF; m_bNametagShowing = true; - m_ucBlurLevel = 36; // Default + m_ucBlurLevel = 36; // Default // Sync stuff m_bSyncingVelocity = false; @@ -542,7 +542,7 @@ void CPlayer::Reset() // functions clientside and serverside possibly returning different results. memset(&m_fStats[0], 0, sizeof(m_fStats)); m_pPlayerStatsPacket->Clear(); - SetPlayerStat(24, 569.0f); // default max_health + SetPlayerStat(24, 569.0f); // default max_health m_pClothes->DefaultClothes(); m_bHasJetPack = false; @@ -556,7 +556,7 @@ void CPlayer::Reset() m_bCursorShowing = false; // Added - m_ucFightingStyle = 15; // STYLE_GRAB_KICK + m_ucFightingStyle = 15; // STYLE_GRAB_KICK SetNametagText(NULL); m_ucAlpha = 255; @@ -633,7 +633,7 @@ bool CPlayer::IsTimeForPuresyncFar() { int iSlowSyncRate = g_pBandwidthSettings->ZoneUpdateIntervals[ZONE3]; m_llNextFarPuresyncTime = llTime + iSlowSyncRate; - m_llNextFarPuresyncTime += rand() % (1 + iSlowSyncRate / 10); // Extra bit to help distribute the load + m_llNextFarPuresyncTime += rand() % (1 + iSlowSyncRate / 10); // Extra bit to help distribute the load // No far sync if light sync is enabled if (g_pBandwidthSettings->bLightSyncEnabled) @@ -646,7 +646,7 @@ bool CPlayer::IsTimeForPuresyncFar() g_pStats->lightsync.llSyncBytesSkipped += iNumPackets * GetApproxPuresyncPacketSize(); g_pStats->lightsync.llSyncPacketsSkipped += iNumSkipped; g_pStats->lightsync.llSyncBytesSkipped += iNumSkipped * GetApproxPuresyncPacketSize(); - return false; // No far sync if light sync is enabled + return false; // No far sync if light sync is enabled } // Add stats @@ -740,11 +740,11 @@ void CPlayer::MaybeUpdateOthersNearList() else // or player has moved too far if ((m_vecUpdateNearLastPosition - GetPosition()).LengthSquared() > MOVEMENT_UPDATE_THRESH * MOVEMENT_UPDATE_THRESH) - { - CLOCK("RelayPlayerPuresync", "UpdateNearList_Movement"); - UpdateOthersNearList(); - UNCLOCK("RelayPlayerPuresync", "UpdateNearList_Movement"); - } + { + CLOCK("RelayPlayerPuresync", "UpdateNearList_Movement"); + UpdateOthersNearList(); + UNCLOCK("RelayPlayerPuresync", "UpdateNearList_Movement"); + } } // Put this player in other players nearlist if this player can observe them in some way @@ -1091,7 +1091,7 @@ int CPlayer::GetPuresyncZone(CPlayer* pOther) vecDirToHere.Normalize(); float fDot = vecOtherCamFwd.DotProduct(&vecDirToHere); // 1=0 deg 0=90 deg -1=180 deg - if (fDot > 0.643) // 100 deg fov [cos ( DEG2RAD( 100 ) * 0.5f )] + if (fDot > 0.643) // 100 deg fov [cos ( DEG2RAD( 100 ) * 0.5f )] iZone = g_pBandwidthSettings->iMaxZoneIfOtherCanSee; } diff --git a/Server/mods/deathmatch/logic/CPlayer.h b/Server/mods/deathmatch/logic/CPlayer.h index 2db065e1247..b332f40eb12 100644 --- a/Server/mods/deathmatch/logic/CPlayer.h +++ b/Server/mods/deathmatch/logic/CPlayer.h @@ -35,7 +35,7 @@ enum eVoiceState VOICESTATE_TRANSMITTING_IGNORED, }; -#define MOVEMENT_UPDATE_THRESH (5) +#define MOVEMENT_UPDATE_THRESH (5) #define DISTANCE_FOR_NEAR_VIEWER (310) struct SViewerInfo diff --git a/Server/mods/deathmatch/logic/CPlayerCamera.h b/Server/mods/deathmatch/logic/CPlayerCamera.h index 0e7b60543e6..f6345d76f5c 100644 --- a/Server/mods/deathmatch/logic/CPlayerCamera.h +++ b/Server/mods/deathmatch/logic/CPlayerCamera.h @@ -47,15 +47,9 @@ class CPlayerCamera void SetTarget(CElement* pElement); float GetRoll() const { return m_fRoll; } - void SetRoll(float fRoll) - { - m_fRoll = CameraScriptShared::NormalizeRoll(fRoll); - } + void SetRoll(float fRoll) { m_fRoll = CameraScriptShared::NormalizeRoll(fRoll); } float GetFOV() const { return m_fFOV; } - void SetFOV(float fFOV) - { - m_fFOV = CameraScriptShared::SanitizeFOV(fFOV); - } + void SetFOV(float fFOV) { m_fFOV = CameraScriptShared::SanitizeFOV(fFOV); } void SetRotation(CVector& vecRotation); diff --git a/Server/mods/deathmatch/logic/CPlayerClothes.h b/Server/mods/deathmatch/logic/CPlayerClothes.h index d3efa24c659..063dfdf9c95 100644 --- a/Server/mods/deathmatch/logic/CPlayerClothes.h +++ b/Server/mods/deathmatch/logic/CPlayerClothes.h @@ -15,25 +15,25 @@ class CPlayerClothes; #include "CCommon.h" -#define PLAYER_CLOTHING_SLOTS 18 -#define TORSO_CLOTHING_MAX 68 -#define HAIR_CLOTHING_MAX 33 -#define LEGS_CLOTHING_MAX 45 -#define SHOES_CLOTHING_MAX 38 -#define LEFT_UPPER_ARM_CLOTHING_MAX 3 -#define LEFT_LOWER_ARM_CLOTHING_MAX 4 +#define PLAYER_CLOTHING_SLOTS 18 +#define TORSO_CLOTHING_MAX 68 +#define HAIR_CLOTHING_MAX 33 +#define LEGS_CLOTHING_MAX 45 +#define SHOES_CLOTHING_MAX 38 +#define LEFT_UPPER_ARM_CLOTHING_MAX 3 +#define LEFT_LOWER_ARM_CLOTHING_MAX 4 #define RIGHT_UPPER_ARM_CLOTHING_MAX 4 #define RIGHT_LOWER_ARM_CLOTHING_MAX 4 -#define BACK_TOP_CLOTHING_MAX 7 -#define LEFT_CHEST_CLOTHING_MAX 6 -#define RIGHT_CHEST_CLOTHING_MAX 7 -#define STOMACH_CLOTHING_MAX 7 -#define LOWER_BACK_CLOTHING_MAX 6 -#define EXTRA1_CLOTHING_MAX 12 -#define EXTRA2_CLOTHING_MAX 12 -#define EXTRA3_CLOTHING_MAX 17 -#define EXTRA4_CLOTHING_MAX 57 -#define SUIT_CLOTHING_MAX 9 +#define BACK_TOP_CLOTHING_MAX 7 +#define LEFT_CHEST_CLOTHING_MAX 6 +#define RIGHT_CHEST_CLOTHING_MAX 7 +#define STOMACH_CLOTHING_MAX 7 +#define LOWER_BACK_CLOTHING_MAX 6 +#define EXTRA1_CLOTHING_MAX 12 +#define EXTRA2_CLOTHING_MAX 12 +#define EXTRA3_CLOTHING_MAX 17 +#define EXTRA4_CLOTHING_MAX 57 +#define SUIT_CLOTHING_MAX 9 class CPed; diff --git a/Server/mods/deathmatch/logic/CPlayerManager.cpp b/Server/mods/deathmatch/logic/CPlayerManager.cpp index ab71d7964b9..4d3d9be10fe 100644 --- a/Server/mods/deathmatch/logic/CPlayerManager.cpp +++ b/Server/mods/deathmatch/logic/CPlayerManager.cpp @@ -338,11 +338,11 @@ void CPlayerManager::Broadcast(const CPacket& Packet, const std::multimap 312) - return false; // TODO: On client side maybe check if a model was allocated with engineRequestModel and it is a ped + return false; // TODO: On client side maybe check if a model was allocated with engineRequestModel and it is a ped switch (model) { - case 74: // Missing skin + case 74: // Missing skin case 149: case 208: return false; diff --git a/Server/mods/deathmatch/logic/CPlayerTextManager.cpp b/Server/mods/deathmatch/logic/CPlayerTextManager.cpp index 2a50f14c044..1853dffed52 100644 --- a/Server/mods/deathmatch/logic/CPlayerTextManager.cpp +++ b/Server/mods/deathmatch/logic/CPlayerTextManager.cpp @@ -67,8 +67,8 @@ void CPlayerTextManager::Update(CTextItem* pTextItem, bool bRemovedFromDisplay) eTextPriority updatePriority = pTextItem->GetPriority(); CTextItem* pClonedItem = new CTextItem(*pTextItem); if (bRemovedFromDisplay) - pClonedItem->m_bDeletable = true; // we pretend that the text item has actually been deleted - // as far as the player is concerned, it has been + pClonedItem->m_bDeletable = true; // we pretend that the text item has actually been deleted + // as far as the player is concerned, it has been // Push it on the correct queue switch (updatePriority) diff --git a/Server/mods/deathmatch/logic/CRPCFunctions.cpp b/Server/mods/deathmatch/logic/CRPCFunctions.cpp index 7f0f7499472..c69308b31cd 100644 --- a/Server/mods/deathmatch/logic/CRPCFunctions.cpp +++ b/Server/mods/deathmatch/logic/CRPCFunctions.cpp @@ -351,10 +351,10 @@ void CRPCFunctions::RequestStealthKill(NetBitStreamInterface& bitStream) // You shouldn't be able to get here without cheating to get a knife. if (!g_pGame->GetConfig()->IsDisableAC("2")) { - // Kick disabled as sometimes causing false positives due weapon slot sync problems - #if 0 +// Kick disabled as sometimes causing false positives due weapon slot sync problems +#if 0 CStaticFunctionDefinitions::KickPlayer ( m_pSourcePlayer, NULL, "AC #2: You were kicked from the game" ); - #endif +#endif } } } diff --git a/Server/mods/deathmatch/logic/CRPCFunctions.h b/Server/mods/deathmatch/logic/CRPCFunctions.h index bf616d1f726..20736c5adb6 100644 --- a/Server/mods/deathmatch/logic/CRPCFunctions.h +++ b/Server/mods/deathmatch/logic/CRPCFunctions.h @@ -19,7 +19,7 @@ class CPlayer; class CGame; -#define DECLARE_RPC(a) static void a ( NetBitStreamInterface& bitStream ); +#define DECLARE_RPC(a) static void a(NetBitStreamInterface& bitStream); class CRPCFunctions { diff --git a/Server/mods/deathmatch/logic/CRegisteredCommands.cpp b/Server/mods/deathmatch/logic/CRegisteredCommands.cpp index 7a6e9f26f9f..cf9c0ad6942 100644 --- a/Server/mods/deathmatch/logic/CRegisteredCommands.cpp +++ b/Server/mods/deathmatch/logic/CRegisteredCommands.cpp @@ -45,7 +45,8 @@ bool CRegisteredCommands::AddCommand(CLuaMain* pLuaMain, const char* szKey, cons switch (policy) { case MultiCommandHandlerPolicy::BLOCK: - g_pGame->GetScriptDebugging()->LogError(pLuaMain->GetVM(), "addCommandHandler: Duplicate command registration blocked for '%s' (multiple handlers disabled)", szKey); + g_pGame->GetScriptDebugging()->LogError( + pLuaMain->GetVM(), "addCommandHandler: Duplicate command registration blocked for '%s' (multiple handlers disabled)", szKey); return false; case MultiCommandHandlerPolicy::WARN: @@ -189,7 +190,7 @@ bool CRegisteredCommands::ProcessCommand(const char* szKey, const char* szArgume if (m_pACLManager->CanObjectUseRight( pClient->GetAccount()->GetName().c_str(), CAccessControlListGroupObject::OBJECT_TYPE_USER, (*iter)->strKey, CAccessControlListRight::RIGHT_TYPE_COMMAND, - !(*iter)->bRestricted)) // If this command is restricted, the default access should be false unless granted specially + !(*iter)->bRestricted)) // If this command is restricted, the default access should be false unless granted specially { // Call it CallCommandHandler((*iter)->pLuaMain, (*iter)->iLuaFunction, (*iter)->strKey, szArguments, pClient); diff --git a/Server/mods/deathmatch/logic/CRegisteredCommands.h b/Server/mods/deathmatch/logic/CRegisteredCommands.h index c786b74b4de..5bc7e963dc2 100644 --- a/Server/mods/deathmatch/logic/CRegisteredCommands.h +++ b/Server/mods/deathmatch/logic/CRegisteredCommands.h @@ -16,7 +16,7 @@ #include #include -#define MAX_REGISTERED_COMMAND_LENGTH 64 +#define MAX_REGISTERED_COMMAND_LENGTH 64 #define MAX_REGISTERED_COMMANDHANDLER_LENGTH 64 enum class MultiCommandHandlerPolicy : std::uint8_t diff --git a/Server/mods/deathmatch/logic/CRegistry.h b/Server/mods/deathmatch/logic/CRegistry.h index dcde1f528a5..4ccf50bb162 100644 --- a/Server/mods/deathmatch/logic/CRegistry.h +++ b/Server/mods/deathmatch/logic/CRegistry.h @@ -62,7 +62,7 @@ class CRegistry SString m_strFileName; private: - bool Query(const char* szQuery, CRegistryResult* pResult); // Not defined to catch incorrect usage + bool Query(const char* szQuery, CRegistryResult* pResult); // Not defined to catch incorrect usage }; struct CRegistryResultCell @@ -126,9 +126,9 @@ struct CRegistryResultCell return 0; } - int nType; // Type identifier, SQLITE_* - int nLength; // Length in bytes if nType == SQLITE_BLOB or SQLITE_TEXT - // (includes zero terminator if TEXT) + int nType; // Type identifier, SQLITE_* + int nLength; // Length in bytes if nType == SQLITE_BLOB or SQLITE_TEXT + // (includes zero terminator if TEXT) long long int nVal; float fVal; unsigned char* pVal; diff --git a/Server/mods/deathmatch/logic/CResource.AclRequest.cpp b/Server/mods/deathmatch/logic/CResource.AclRequest.cpp index 9e6dbbc5f67..4bafafa7543 100644 --- a/Server/mods/deathmatch/logic/CResource.AclRequest.cpp +++ b/Server/mods/deathmatch/logic/CResource.AclRequest.cpp @@ -123,7 +123,6 @@ bool CResource::HasAutoPermissions(CXMLNode* pNodeAclRequest) /////////////////////////////////////////////////////////////// void CResource::RefreshAutoPermissions(CXMLNode* pNodeAclRequest) { - // Ensure group and acl exist CAccessControlListGroup* pAutoGroup = g_pGame->GetACLManager()->AddGroup(GetAutoGroupName()); pAutoGroup->AddACL(GetAutoAcl()); diff --git a/Server/mods/deathmatch/logic/CResource.cpp b/Server/mods/deathmatch/logic/CResource.cpp index 63a1bc584be..57187a55a81 100644 --- a/Server/mods/deathmatch/logic/CResource.cpp +++ b/Server/mods/deathmatch/logic/CResource.cpp @@ -107,7 +107,7 @@ bool CResource::Load() m_uiVersionMajor = 0; m_uiVersionMinor = 0; m_uiVersionRevision = 0; - m_uiVersionState = 2; // release + m_uiVersionState = 2; // release m_bClientConfigs = true; m_bClientScripts = true; @@ -521,68 +521,70 @@ void CResource::SetInfoValue(const char* szKey, const char* szValue, bool bSave) std::future CResource::GenerateChecksumForFile(CResourceFile* pResourceFile) { - return SharedUtil::async([pResourceFile, this] { - SString strPath; - - if (!GetFilePath(pResourceFile->GetName(), strPath)) - return SString(); - - auto checksumOrError = CChecksum::GenerateChecksumFromFile(strPath); - if (std::holds_alternative(checksumOrError)) + return SharedUtil::async( + [pResourceFile, this] { - return SString(std::get(checksumOrError)); - } + SString strPath; - pResourceFile->SetLastChecksum(std::get(checksumOrError)); - pResourceFile->SetLastFileSizeHint(static_cast(FileSize(strPath))); + if (!GetFilePath(pResourceFile->GetName(), strPath)) + return SString(); - // Check if file is blocked - char szHashResult[33]; - CMD5Hasher::ConvertToHex(pResourceFile->GetLastChecksum().md5, szHashResult); - SString strBlockReason = m_pResourceManager->GetBlockedFileReason(szHashResult); + auto checksumOrError = CChecksum::GenerateChecksumFromFile(strPath); + if (std::holds_alternative(checksumOrError)) + { + return SString(std::get(checksumOrError)); + } - if (!strBlockReason.empty()) - { - return SString("file '%s' is blocked (%s)", pResourceFile->GetName(), *strBlockReason); - } + pResourceFile->SetLastChecksum(std::get(checksumOrError)); + pResourceFile->SetLastFileSizeHint(static_cast(FileSize(strPath))); - // Copy file to http holding directory - switch (pResourceFile->GetType()) - { - case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_SCRIPT: - case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_CONFIG: - case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_FILE: + // Check if file is blocked + char szHashResult[33]; + CMD5Hasher::ConvertToHex(pResourceFile->GetLastChecksum().md5, szHashResult); + SString strBlockReason = m_pResourceManager->GetBlockedFileReason(szHashResult); + + if (!strBlockReason.empty()) { - SString strCachedFilePath = pResourceFile->GetCachedPathFilename(); + return SString("file '%s' is blocked (%s)", pResourceFile->GetName(), *strBlockReason); + } - if (!g_pRealNetServer->ValidateHttpCacheFileName(strCachedFilePath)) + // Copy file to http holding directory + switch (pResourceFile->GetType()) + { + case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_SCRIPT: + case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_CONFIG: + case CResourceFile::RESOURCE_FILE_TYPE_CLIENT_FILE: { - FileDelete(strCachedFilePath); - return SString("ERROR: Resource '%s' client filename '%s' not allowed\n", GetName().c_str(), *ExtractFilename(strCachedFilePath)); - } + SString strCachedFilePath = pResourceFile->GetCachedPathFilename(); - CChecksum cachedChecksum = CChecksum::GenerateChecksumFromFileUnsafe(strCachedFilePath); + if (!g_pRealNetServer->ValidateHttpCacheFileName(strCachedFilePath)) + { + FileDelete(strCachedFilePath); + return SString("ERROR: Resource '%s' client filename '%s' not allowed\n", GetName().c_str(), *ExtractFilename(strCachedFilePath)); + } - if (pResourceFile->GetLastChecksum() != cachedChecksum) - { - if (!FileCopy(strPath, strCachedFilePath)) + CChecksum cachedChecksum = CChecksum::GenerateChecksumFromFileUnsafe(strCachedFilePath); + + if (pResourceFile->GetLastChecksum() != cachedChecksum) { - return SString("Could not copy '%s' to '%s'\n", *strPath, *strCachedFilePath); + if (!FileCopy(strPath, strCachedFilePath)) + { + return SString("Could not copy '%s' to '%s'\n", *strPath, *strCachedFilePath); + } + + // If script is 'no client cache', make sure there is no trace of it in the output dir + if (pResourceFile->IsNoClientCache()) + FileDelete(pResourceFile->GetCachedPathFilename(true)); } - // If script is 'no client cache', make sure there is no trace of it in the output dir - if (pResourceFile->IsNoClientCache()) - FileDelete(pResourceFile->GetCachedPathFilename(true)); + break; } - - break; + default: + break; } - default: - break; - } - return SString(); - }); + return SString(); + }); } bool CResource::GenerateChecksums() @@ -637,7 +639,7 @@ bool CResource::GenerateChecksums() bool CResource::HasResourceChanged() { - std::string strPath; + std::string strPath; std::string_view strDirPath = m_strResourceDirectoryPath; if (IsResourceZip()) @@ -763,7 +765,7 @@ bool CResource::GetCompatibilityStatus(SString& strOutStatus) { strOutStatus = " section in the meta.xml is incorrect or missing (expected at least "; strOutStatus += SString("client %s because of '%s')", *m_strMinClientReqFromSource, *m_strMinClientReason); - m_strMinClientRequirement = m_strMinClientReqFromSource; // Apply higher version requirement + m_strMinClientRequirement = m_strMinClientReqFromSource; // Apply higher version requirement } else if (m_strMinServerReqFromSource > m_strMinServerFromMetaXml) { @@ -1051,7 +1053,7 @@ bool CResource::Start(std::list* pDependents, bool bManualStart, con return false; } - m_startCounter = std::max(m_startCounter + 1, 1); // We consider zero to be an invalid start counter. + m_startCounter = std::max(m_startCounter + 1, 1); // We consider zero to be an invalid start counter. m_bStartedManually = bManualStart; // Remember the client files state @@ -1088,19 +1090,19 @@ void CResource::OnResourceStateChange(const char* state) noexcept stateArgs.PushResource(this); switch (m_eState) { - case EResourceState::Loaded: // When resource is stopped + case EResourceState::Loaded: // When resource is stopped stateArgs.PushString("loaded"); break; - case EResourceState::Running: // When resource is running + case EResourceState::Running: // When resource is running stateArgs.PushString("running"); break; - case EResourceState::Starting: // When resource is starting + case EResourceState::Starting: // When resource is starting stateArgs.PushString("starting"); break; - case EResourceState::Stopping: // When resource is stopping + case EResourceState::Stopping: // When resource is stopping stateArgs.PushString("stopping"); break; - case EResourceState::None: // When resource is not loaded + case EResourceState::None: // When resource is not loaded default: stateArgs.PushString("unloaded"); break; @@ -1258,7 +1260,7 @@ bool CResource::DestroyVM() return true; } -void CResource::DisplayInfo() // duplicated for HTML +void CResource::DisplayInfo() // duplicated for HTML { CLogger::LogPrintf("== Details for resource '%s' ==\n", m_strResourceName.c_str()); @@ -1402,9 +1404,9 @@ bool CResource::GetFilePath(const char* szFilename, string& strPath) std::vector CResource::GetFilePaths(const char* szFilename) { - std::vector vecFiles; - const std::string& strDirectory = IsResourceZip() ? m_strResourceCachePath : m_strResourceDirectoryPath; - const std::string strFilePath = strDirectory + szFilename; + std::vector vecFiles; + const std::string& strDirectory = IsResourceZip() ? m_strResourceCachePath : m_strResourceDirectoryPath; + const std::string strFilePath = strDirectory + szFilename; for (const std::filesystem::path& path : glob::rglob(strFilePath)) { @@ -1537,7 +1539,8 @@ bool CResource::ReadIncludedHTML(CXMLNode* pRoot) // This one is supposed to be default, but there's already a default page if (bFoundDefault && bIsDefault) { - CLogger::LogPrintf("Only one html item can be default per resource, ignoring %s in %s\n", strFilename.c_str(), m_strResourceName.c_str()); + CLogger::LogPrintf("Only one html item can be default per resource, ignoring %s in %s\n", strFilename.c_str(), + m_strResourceName.c_str()); bIsDefault = false; } @@ -1546,7 +1549,8 @@ bool CResource::ReadIncludedHTML(CXMLNode* pRoot) bFoundDefault = true; // Create a new resource HTML file and add it to the list - auto pResourceFile = new CResourceHTMLItem(this, strFilename.c_str(), strFullFilename.c_str(), &Attributes, bIsDefault, bIsRaw, bIsRestricted, m_bOOPEnabledInMetaXml); + auto pResourceFile = new CResourceHTMLItem(this, strFilename.c_str(), strFullFilename.c_str(), &Attributes, bIsDefault, bIsRaw, + bIsRestricted, m_bOOPEnabledInMetaXml); m_ResourceFiles.push_back(pResourceFile); // This is the first HTML file? Remember it @@ -1770,8 +1774,7 @@ bool CResource::ReadIncludedExports(CXMLNode* pRoot) if (functionName[0] == '\0') { - CLogger::ErrorPrintf("WARNING: Empty 'function' attribute of 'export' node of 'meta.xml' for resource '%s', ignoring\n", - m_strResourceName.c_str()); + CLogger::ErrorPrintf("WARNING: Empty 'function' attribute of 'export' node of 'meta.xml' for resource '%s', ignoring\n", m_strResourceName.c_str()); continue; } @@ -1796,15 +1799,14 @@ bool CResource::ReadIncludedExports(CXMLNode* pRoot) if (!isHttpFunction && isHttpRouter) { isHttpRouter = false; - CLogger::ErrorPrintf("WARNING: Regular function '%s' in resource '%s' uses HTTP router attribute\n", - functionName, m_strResourceName.c_str()); + CLogger::ErrorPrintf("WARNING: Regular function '%s' in resource '%s' uses HTTP router attribute\n", functionName, m_strResourceName.c_str()); } if (isHttpRouter && !m_httpRouterFunction.empty()) { isHttpRouter = false; - CLogger::ErrorPrintf("WARNING: HTTP router function '%s' in resource '%s' ignored, using '%s'\n", - functionName, m_strResourceName.c_str(), m_httpRouterFunction.c_str()); + CLogger::ErrorPrintf("WARNING: HTTP router function '%s' in resource '%s' ignored, using '%s'\n", functionName, m_strResourceName.c_str(), + m_httpRouterFunction.c_str()); } // See if the restricted attribute is true or false @@ -1835,8 +1837,8 @@ bool CResource::ReadIncludedExports(CXMLNode* pRoot) } else if (stricmp(value, "server") != 0) { - CLogger::LogPrintf("WARNING: Function '%s' in resource '%s' uses unknown function type, assuming 'server'\n", - functionName, m_strResourceName.c_str()); + CLogger::LogPrintf("WARNING: Function '%s' in resource '%s' uses unknown function type, assuming 'server'\n", functionName, + m_strResourceName.c_str()); } } @@ -1849,8 +1851,8 @@ bool CResource::ReadIncludedExports(CXMLNode* pRoot) continue; } - CLogger::LogPrintf("WARNING: HTTP router function '%s' in resource '%s' is not a server-sided function, ignoring\n", - functionName, m_strResourceName.c_str()); + CLogger::LogPrintf("WARNING: HTTP router function '%s' in resource '%s' is not a server-sided function, ignoring\n", functionName, + m_strResourceName.c_str()); continue; } @@ -2579,7 +2581,8 @@ HttpStatusCode CResource::HandleRequest(HttpRequest* ipoHttpRequest, HttpRespons std::string Unescape(std::string_view sv) { // Converts a character to a hexadecimal value - auto toHex = [](char c) -> unsigned char { + auto toHex = [](char c) -> unsigned char + { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') @@ -2725,7 +2728,7 @@ HttpStatusCode CResource::HandleRequestCall(HttpRequest* ipoHttpRequest, HttpRes { switch (szArg[1]) { - case 'E': // element + case 'E': // element { int id = atoi(szArg + 3); CElement* pElement = nullptr; @@ -2745,7 +2748,7 @@ HttpStatusCode CResource::HandleRequestCall(HttpRequest* ipoHttpRequest, HttpRes break; } - case 'R': // resource + case 'R': // resource { CResource* pResource = g_pGame->GetResourceManager()->GetResource(szArg + 3); @@ -2796,7 +2799,7 @@ HttpStatusCode CResource::HandleRequestCall(HttpRequest* ipoHttpRequest, HttpRes Headers.PushString(pair.second.c_str()); } - LUA_CHECKSTACK(m_pVM->GetVM(), 1); // Ensure some room + LUA_CHECKSTACK(m_pVM->GetVM(), 1); // Ensure some room // cache old data lua_getglobal(m_pVM->GetVM(), "form"); @@ -2941,7 +2944,7 @@ static HttpStatusCode ParseLuaHttpRouterResponse(CLuaArguments& luaResponse, Htt argValue = (*cookies)[j + 1]; std::string_view n, v; - + if (argName->TryGetString(n) && argValue->TryGetString(v)) { CookieParameters cookie; @@ -3061,7 +3064,7 @@ HttpStatusCode CResource::HandleRequestRouter(HttpRequest* request, HttpResponse luaRequest.PushString("*"); break; } - + luaRequest.PushString("path"); luaRequest.PushString(path); @@ -3094,7 +3097,7 @@ HttpStatusCode CResource::HandleRequestRouter(HttpRequest* request, HttpResponse } luaRequest.PushString("formData"); luaRequest.PushTable(&formData); - + CLuaArguments cookies; for (const auto& pair : request->oCookieMap) { @@ -3214,10 +3217,10 @@ HttpStatusCode CResource::HandleRequestActive(HttpRequest* ipoHttpRequest, HttpR pResourceFile->GetType() == CResourceFile::RESOURCE_FILE_TYPE_CLIENT_SCRIPT || pResourceFile->GetType() == CResourceFile::RESOURCE_FILE_TYPE_CLIENT_FILE) { - return pResourceFile->Request(ipoHttpRequest, ipoHttpResponse); // sends back any file in the resource + return pResourceFile->Request(ipoHttpRequest, ipoHttpResponse); // sends back any file in the resource } } - else // handle the default page + else // handle the default page { if (!IsHttpAccessAllowed(pAccount)) { @@ -3420,7 +3423,7 @@ bool CResource::UnzipResource() { // If we're using a zip file, we need a temp directory for extracting // 17 = already exists (on windows) - if (File::Mkdir(m_strResourceCachePath.c_str()) == -1 && errno != EEXIST) // check this is the correct return for *NIX too + if (File::Mkdir(m_strResourceCachePath.c_str()) == -1 && errno != EEXIST) // check this is the correct return for *NIX too { // Show error m_strFailureReason = SString("Couldn't create directory '%s' for resource '%s', check that the server has write access to the resources folder.\n", @@ -3460,7 +3463,7 @@ bool CResource::UnzipResource() unsigned long ulFileOnDiskCRC = CRCGenerator::GetCRCFromFile(strPath.c_str()); if (ulFileInZipCRC == ulFileOnDiskCRC) - continue; // we've already extracted EXACTLY this file before + continue; // we've already extracted EXACTLY this file before RemoveFile(strPath.c_str()); } @@ -3560,7 +3563,7 @@ void change_file_date(const char* filename, uLong dosdate, tm_unz tmu_date) SetFileTime(hFile, &ftm, &ftLastAcc, &ftm); CloseHandle(hFile); #else -#ifdef unix + #ifdef unix struct utimbuf ut; struct tm newdate; newdate.tm_sec = tmu_date.tm_sec; @@ -3576,7 +3579,7 @@ void change_file_date(const char* filename, uLong dosdate, tm_unz tmu_date) ut.actime = ut.modtime = mktime(&newdate); utime(filename, &ut); -#endif + #endif #endif } @@ -3730,7 +3733,7 @@ int do_extract_currentfile(unzFile uf, const int* popt_extract_without_path, int return err; } -bool CIncludedResources::CreateLink() // just a pointer to it +bool CIncludedResources::CreateLink() // just a pointer to it { // Grab the resource that we are m_pResource = m_pResourceManager->GetResource(m_strResourceName.c_str()); diff --git a/Server/mods/deathmatch/logic/CResource.h b/Server/mods/deathmatch/logic/CResource.h index 6aa393b5fb9..aff0364111e 100644 --- a/Server/mods/deathmatch/logic/CResource.h +++ b/Server/mods/deathmatch/logic/CResource.h @@ -23,9 +23,9 @@ #include #include -#define MAX_AUTHOR_LENGTH 255 -#define MAX_RESOURCE_NAME_LENGTH 255 -#define MAX_FUNCTION_NAME_LENGTH 50 +#define MAX_AUTHOR_LENGTH 255 +#define MAX_RESOURCE_NAME_LENGTH 255 +#define MAX_FUNCTION_NAME_LENGTH 50 class CDummy; class CElement; @@ -84,8 +84,8 @@ class CIncludedResources SVersion m_MaxVersion; bool m_bExists; bool m_bBadVersion; - CResource* m_pResource; // the resource this links to - CResource* m_pOwner; // the resource this is inside + CResource* m_pResource; // the resource this links to + CResource* m_pOwner; // the resource this is inside CResourceManager* m_pResourceManager; public: @@ -125,10 +125,10 @@ class CIncludedResources enum class EResourceState : unsigned char { None, - Loaded, // its been loaded successfully (i.e. meta parsed ok), included resources loaded ok - Starting, // the resource is starting - Running, // resource items are running - Stopping, // the resource is stopping + Loaded, // its been loaded successfully (i.e. meta parsed ok), included resources loaded ok + Starting, // the resource is starting + Running, // resource items are running + Stopping, // the resource is stopping }; // A resource is either a directory with files or a ZIP file which contains the content of such directory. @@ -253,11 +253,11 @@ class CResource : public EHS bool CheckIfStartable(); void DisplayInfo(); - bool GetFilePath(const char* szFilename, std::string& strPath); - std::vector GetFilePaths(const char* szFilename); + bool GetFilePath(const char* szFilename, std::string& strPath); + std::vector GetFilePaths(const char* szFilename); - const std::string& GetResourceDirectoryPath() const { return m_strResourceDirectoryPath; } - const std::string& GetResourceCacheDirectoryPath() const { return m_strResourceCachePath; } + const std::string& GetResourceDirectoryPath() const { return m_strResourceDirectoryPath; } + const std::string& GetResourceCacheDirectoryPath() const { return m_strResourceCachePath; } std::list& GetFiles() { return m_ResourceFiles; } size_t GetFileCount() const noexcept { return m_ResourceFiles.size(); } @@ -351,7 +351,7 @@ class CResource : public EHS bool FindAclRequest(SAclRequest& result); private: - bool CheckState(); // if the resource has no Dependents, stop it, if it has, start it. returns true if the resource is started. + bool CheckState(); // if the resource has no Dependents, stop it, if it has, start it. returns true if the resource is started. bool ReadIncludedResources(CXMLNode* pRoot); bool ReadIncludedMaps(CXMLNode* pRoot); bool ReadIncludedScripts(CXMLNode* pRoot); @@ -378,15 +378,15 @@ class CResource : public EHS CResourceManager* m_pResourceManager; SString m_strResourceName; - SString m_strAbsPath; // Absolute path to containing directory i.e. /server/mods/deathmatch/resources - std::string m_strResourceZip; // Absolute path to zip file (if a zip) i.e. m_strAbsPath/resource_name.zip - std::string m_strResourceDirectoryPath; // Absolute path to resource files (if a dir) i.e. m_strAbsPath/resource_name - std::string m_strResourceCachePath; // Absolute path to unzipped cache (if a zip) i.e. /server/mods/deathmatch/resources/cache/resource_name + SString m_strAbsPath; // Absolute path to containing directory i.e. /server/mods/deathmatch/resources + std::string m_strResourceZip; // Absolute path to zip file (if a zip) i.e. m_strAbsPath/resource_name.zip + std::string m_strResourceDirectoryPath; // Absolute path to resource files (if a dir) i.e. m_strAbsPath/resource_name + std::string m_strResourceCachePath; // Absolute path to unzipped cache (if a zip) i.e. /server/mods/deathmatch/resources/cache/resource_name unsigned int m_uiVersionMajor = 0; unsigned int m_uiVersionMinor = 0; unsigned int m_uiVersionRevision = 0; - unsigned int m_uiVersionState = 2; // 2 = release + unsigned int m_uiVersionState = 2; // 2 = release int m_iDownloadPriorityGroup = 0; @@ -396,19 +396,19 @@ class CResource : public EHS CElement* m_pRootElement = nullptr; CDummy* m_pResourceElement = nullptr; CDummy* m_pResourceDynamicElementRoot = nullptr; - CElementGroup* m_pDefaultElementGroup = nullptr; // stores elements created by scripts in this resource + CElementGroup* m_pDefaultElementGroup = nullptr; // stores elements created by scripts in this resource CLuaMain* m_pVM = nullptr; unsigned int m_startCounter{}; std::unordered_set m_isRunningForPlayer; KeyValueMap m_Info; - std::list m_IncludedResources; // we store them here temporarily, then read them once all the resources are loaded + std::list m_IncludedResources; // we store them here temporarily, then read them once all the resources are loaded std::list m_ResourceFiles; std::map m_ResourceFilesCountPerDir; - std::list m_Dependents; // resources that have "included" or loaded this one + std::list m_Dependents; // resources that have "included" or loaded this one std::list m_ExportedFunctions; - std::list m_TemporaryIncludes; // started by startResource script command + std::list m_TemporaryIncludes; // started by startResource script command int m_httpRouterCheck{}; std::string m_httpRouterFunction; @@ -434,23 +434,23 @@ class CResource : public EHS bool m_bUsingDbConnectMysql = false; bool m_bOOPEnabledInMetaXml = false; - bool m_bLinked = false; // if true, the included resources are already linked to this resource - bool m_bIsPersistent = false; // if true, the resource will remain even if it has no Dependents, mainly if started by the user or the startup + bool m_bLinked = false; // if true, the included resources are already linked to this resource + bool m_bIsPersistent = false; // if true, the resource will remain even if it has no Dependents, mainly if started by the user or the startup bool m_bDestroyed = false; - CXMLNode* m_pNodeSettings = nullptr; // Settings XML node, read from meta.xml and copied into it's own instance - CXMLNode* m_pNodeStorage = nullptr; // Dummy XML node used for temporary storage of stuff returned by CSettings::Get + CXMLNode* m_pNodeSettings = nullptr; // Settings XML node, read from meta.xml and copied into it's own instance + CXMLNode* m_pNodeStorage = nullptr; // Dummy XML node used for temporary storage of stuff returned by CSettings::Get - CMtaVersion m_strMinClientRequirement; // Min MTA client version - CMtaVersion m_strMinServerRequirement; // Min MTA server version - CMtaVersion m_strMinClientFromMetaXml; // Min MTA client version as declared in meta.xml - CMtaVersion m_strMinServerFromMetaXml; // Min MTA server version as declared in meta.xml - CMtaVersion m_strMinClientReqFromSource; // Min MTA client version as calculated by scanning the script source - CMtaVersion m_strMinServerReqFromSource; // Min MTA server version as calculated by scanning the script source + CMtaVersion m_strMinClientRequirement; // Min MTA client version + CMtaVersion m_strMinServerRequirement; // Min MTA server version + CMtaVersion m_strMinClientFromMetaXml; // Min MTA client version as declared in meta.xml + CMtaVersion m_strMinServerFromMetaXml; // Min MTA server version as declared in meta.xml + CMtaVersion m_strMinClientReqFromSource; // Min MTA client version as calculated by scanning the script source + CMtaVersion m_strMinServerReqFromSource; // Min MTA server version as calculated by scanning the script source SString m_strMinClientReason; SString m_strMinServerReason; - CChecksum m_metaChecksum; // Checksum of meta.xml last time this was loaded, generated in GenerateChecksums() + CChecksum m_metaChecksum; // Checksum of meta.xml last time this was loaded, generated in GenerateChecksums() uint m_uiFunctionRightCacheRevision = 0; CFastHashMap m_FunctionRightCacheMap; diff --git a/Server/mods/deathmatch/logic/CResourceChecker.Data.h b/Server/mods/deathmatch/logic/CResourceChecker.Data.h index 51d8c22258c..a91d96f501a 100644 --- a/Server/mods/deathmatch/logic/CResourceChecker.Data.h +++ b/Server/mods/deathmatch/logic/CResourceChecker.Data.h @@ -15,7 +15,7 @@ namespace // Minimum version requirements for functions/events // -#if 0 // Activate the counterpart in CResourceChecker::CheckVersionRequirements when you add items to these lists +#if 0 // Activate the counterpart in CResourceChecker::CheckVersionRequirements when you add items to these lists struct SVersionItem { SString functionName; @@ -213,7 +213,7 @@ namespace {false, "getPlayerOccupiedVehicleSeat", "getPedOccupiedVehicleSeat"}, {false, "isPlayerInVehicle", "isPedInVehicle"}, {false, "getPlayerFromNick", "getPlayerFromName"}, - + // Client {false, "getClientName", "getPlayerName"}, {false, "getClientIP", "getPlayerIP"}, @@ -241,9 +241,8 @@ namespace // Base Encoding & Decoding {true, "base64Encode", "Please manually change this to encodeString (different syntax). Refer to the wiki for details"}, {true, "base64Decode", "Please manually change this to decodeString (different syntax). Refer to the wiki for details"}, - + // Ped {false, "setPedOnFire", "setElementOnFire"}, - {false, "isPedOnFire", "isElementOnFire"} - }; -} // namespace + {false, "isPedOnFire", "isElementOnFire"}}; +} // namespace diff --git a/Server/mods/deathmatch/logic/CResourceChecker.cpp b/Server/mods/deathmatch/logic/CResourceChecker.cpp index 017446f47e1..efde93c1f50 100644 --- a/Server/mods/deathmatch/logic/CResourceChecker.cpp +++ b/Server/mods/deathmatch/logic/CResourceChecker.cpp @@ -309,24 +309,24 @@ void CResourceChecker::CheckMetaFileForIssues(const string& strPath, const strin else // ..or do an upgrade if (m_bUpgradeScripts == true) - { - bool bHasChanged = false; - CheckMetaSourceForIssues(pRootNode, strFileName, strResourceName, ECheckerMode::UPGRADE, &bHasChanged); - - // Has contents changed? - if (bHasChanged) { - // Rename original to xml.old - if (!RenameBackupFile(strPath, ".old")) - return; + bool bHasChanged = false; + CheckMetaSourceForIssues(pRootNode, strFileName, strResourceName, ECheckerMode::UPGRADE, &bHasChanged); - // Save new content - metaFile->Write(); - CLogger::LogPrintf("Upgrading %s:%s ...........done\n", strResourceName.c_str(), strFileName.c_str()); + // Has contents changed? + if (bHasChanged) + { + // Rename original to xml.old + if (!RenameBackupFile(strPath, ".old")) + return; - m_upgradedFullPathList.push_back(strPath); + // Save new content + metaFile->Write(); + CLogger::LogPrintf("Upgrading %s:%s ...........done\n", strResourceName.c_str(), strFileName.c_str()); + + m_upgradedFullPathList.push_back(strPath); + } } - } delete metaFile; } @@ -422,11 +422,11 @@ void CResourceChecker::CheckLuaFileForIssues(const string& strPath, const string if (strFileContents.length() > 1000000) CLogger::LogPrintf("Please wait...\n"); - if (m_bUpgradeScripts == false) // Output warnings... + if (m_bUpgradeScripts == false) // Output warnings... { CheckLuaSourceForIssues(strFileContents, strFileName, strResourceName, bClientScript, bCompiledScript, ECheckerMode::WARNINGS); } - else if (!bCompiledScript) // ..or do an upgrade (if not compiled) + else if (!bCompiledScript) // ..or do an upgrade (if not compiled) { string strNewFileContents; CheckLuaSourceForIssues(strFileContents, strFileName, strResourceName, bClientScript, bCompiledScript, ECheckerMode::UPGRADE, &strNewFileContents); @@ -519,7 +519,7 @@ void CResourceChecker::CheckLuaSourceForIssues(string strLuaSource, const string { std::wstring strUTF16Script = ANSIToUTF16(strLuaSource); #ifdef WIN32 - std::setlocale(LC_CTYPE, ""); // Temporarilly use locales to read the script + std::setlocale(LC_CTYPE, ""); // Temporarilly use locales to read the script std::string strUTFScript = UTF16ToMbUTF8(strUTF16Script); std::setlocale(LC_CTYPE, "C"); #else @@ -540,8 +540,8 @@ void CResourceChecker::CheckLuaSourceForIssues(string strLuaSource, const string if (checkerMode == ECheckerMode::WARNINGS) { m_ulDeprecatedWarningCount++; - CLogger::LogPrintf("WARNING: %s/%s [%s] is encoded in ANSI instead of UTF-8. Please convert your file to UTF-8.\n", - strResourceName.c_str(), strFileName.c_str(), bClientScript ? "Client" : "Server"); + CLogger::LogPrintf("WARNING: %s/%s [%s] is encoded in ANSI instead of UTF-8. Please convert your file to UTF-8.\n", strResourceName.c_str(), + strFileName.c_str(), bClientScript ? "Client" : "Server"); } } } @@ -750,7 +750,7 @@ void CResourceChecker::CheckLuaSourceForIssues(string strLuaSource, const string continue; } - if (first == ']' && second == '=' && tokenLevel > 0) // Maybe close a long comment of level 1 and above: "]=]" or "]==]" or ... + if (first == ']' && second == '=' && tokenLevel > 0) // Maybe close a long comment of level 1 and above: "]=]" or "]==]" or ... { const unsigned char* start = current + 1; const unsigned char* equals = start + 1; @@ -907,7 +907,7 @@ void CResourceChecker::CheckLuaSourceForIssues(string strLuaSource, const string if (const size_t length = pos - current; length > 2) { - std::string_view literal(reinterpret_cast(current + 1), length - 2); // Do not include surrounding quotes. + std::string_view literal(reinterpret_cast(current + 1), length - 2); // Do not include surrounding quotes. tokenContent = literal; tokenLine = line; processStringLiteral(); @@ -957,7 +957,7 @@ void CResourceChecker::CheckLuaSourceForIssues(string strLuaSource, const string current += 1; continue; } - + // We are calling a function with several arguments or with a table: foo (...) or foo {...} if ((first == '(' && lastKeyword != "function") || first == '{') { @@ -1057,7 +1057,7 @@ ECheckerWhatType CResourceChecker::GetLuaFunctionNameUpgradeInfo(const string& s // Query the correct map with the cleaned function name SDeprecatedItem* pItem = MapFindRef(bClientScript ? clientUpgradeInfoMap : serverUpgradeInfoMap, strFunctionName); if (!pItem) - return ECheckerWhat::NONE; // Nothing found + return ECheckerWhat::NONE; // Nothing found strOutHow = pItem->strNewName; strOutVersion = pItem->strVersion; @@ -1156,11 +1156,11 @@ int CResourceChecker::ReplaceFilesInZIP(const string& strOrigZip, const string& { // open source and destination file zlib_filefunc_def ffunc; - #ifdef WIN32 +#ifdef WIN32 fill_win32_filefunc(&ffunc); - #else +#else fill_fopen_filefunc(&ffunc); - #endif +#endif zipFile szip = unzOpen2(strOrigZip.c_str(), &ffunc); if (szip == NULL) @@ -1215,9 +1215,9 @@ int CResourceChecker::ReplaceFilesInZIP(const string& strOrigZip, const string& if (unzGetCurrentFileInfo(szip, &unzfi, dos_fn, MAX_PATH, NULL, 0, NULL, 0) != UNZ_OK) break; char fn[MAX_PATH]; - #ifdef WIN32 +#ifdef WIN32 OemToChar(dos_fn, fn); - #endif +#endif // See if file should be replaced string fullPathReplacement; diff --git a/Server/mods/deathmatch/logic/CResourceClientConfigItem.h b/Server/mods/deathmatch/logic/CResourceClientConfigItem.h index 6c89159a51b..23e14f33c92 100644 --- a/Server/mods/deathmatch/logic/CResourceClientConfigItem.h +++ b/Server/mods/deathmatch/logic/CResourceClientConfigItem.h @@ -29,5 +29,5 @@ class CResourceClientConfigItem : public CResourceFile class CXMLFile* m_pXMLFile; CXMLNode* m_pXMLRootNode; - bool m_bInvalid; // it failed to load + bool m_bInvalid; // it failed to load }; diff --git a/Server/mods/deathmatch/logic/CResourceClientScriptItem.cpp b/Server/mods/deathmatch/logic/CResourceClientScriptItem.cpp index 138661f1871..ba8f4bacb7f 100644 --- a/Server/mods/deathmatch/logic/CResourceClientScriptItem.cpp +++ b/Server/mods/deathmatch/logic/CResourceClientScriptItem.cpp @@ -62,7 +62,7 @@ bool CResourceClientScriptItem::Start() // Compress the source unsigned int originalLength = m_sourceCode.length(); unsigned long bufferLength = - m_sourceCode.length() + 12 + (unsigned int)(m_sourceCode.length() * 0.001f); // Refer to the compress2() function documentation. + m_sourceCode.length() + 12 + (unsigned int)(m_sourceCode.length() * 0.001f); // Refer to the compress2() function documentation. char* compressedBuffer = new char[bufferLength]; if (compress2((Bytef*)compressedBuffer, (uLongf*)&bufferLength, (const Bytef*)m_sourceCode.c_str(), m_sourceCode.length(), Z_BEST_COMPRESSION) != Z_OK) { diff --git a/Server/mods/deathmatch/logic/CResourceConfigItem.h b/Server/mods/deathmatch/logic/CResourceConfigItem.h index 154a86abde9..d047e0a8417 100644 --- a/Server/mods/deathmatch/logic/CResourceConfigItem.h +++ b/Server/mods/deathmatch/logic/CResourceConfigItem.h @@ -15,7 +15,7 @@ #include #ifndef MAX_PATH -#define MAX_PATH 260 + #define MAX_PATH 260 #endif class CResourceConfigItem : public CResourceFile diff --git a/Server/mods/deathmatch/logic/CResourceFile.h b/Server/mods/deathmatch/logic/CResourceFile.h index 4cfc3b36d06..7e1337c36bf 100644 --- a/Server/mods/deathmatch/logic/CResourceFile.h +++ b/Server/mods/deathmatch/logic/CResourceFile.h @@ -35,18 +35,18 @@ class CResourceFile RESOURCE_FILE_TYPE_HTML, RESOURCE_FILE_TYPE_CLIENT_FILE, RESOURCE_FILE_TYPE_NONE, - }; // TODO: sort all client-side enums and use >= (instead of each individual type) on comparisons that use this enum? + }; // TODO: sort all client-side enums and use >= (instead of each individual type) on comparisons that use this enum? protected: class CResource* m_resource; - std::string m_strResourceFileName; // full path - std::string m_strShortName; // just the filename - std::string m_strWindowsName; // the name with backwards slashes + std::string m_strResourceFileName; // full path + std::string m_strShortName; // just the filename + std::string m_strWindowsName; // the name with backwards slashes eResourceType m_type; class CLuaMain* m_pVM; - CChecksum m_checksum; // Checksum last time this was loaded, generated by GenerateChecksum() + CChecksum m_checksum; // Checksum last time this was loaded, generated by GenerateChecksum() uint m_uiFileSizeHint; - map m_attributeMap; // Map of attributes from the meta.xml file + map m_attributeMap; // Map of attributes from the meta.xml file public: CResourceFile(class CResource* resource, const char* szShortName, const char* szResourceFileName, CXMLAttributes* xmlAttributes); @@ -67,7 +67,7 @@ class CResourceFile void SetLastChecksum(CChecksum checksum) { m_checksum = checksum; } void SetLastFileSizeHint(uint uiFileSizeHint) { m_uiFileSizeHint = uiFileSizeHint; } - uint GetSizeHint() { return m_uiFileSizeHint; } // Only used by download counters + uint GetSizeHint() { return m_uiFileSizeHint; } // Only used by download counters string GetMetaFileAttribute(const string& key) { return m_attributeMap[key]; } SString GetCachedPathFilename(bool bForceClientCachePath = false); }; diff --git a/Server/mods/deathmatch/logic/CResourceHTMLItem.cpp b/Server/mods/deathmatch/logic/CResourceHTMLItem.cpp index 980708152ea..cc3220ae286 100644 --- a/Server/mods/deathmatch/logic/CResourceHTMLItem.cpp +++ b/Server/mods/deathmatch/logic/CResourceHTMLItem.cpp @@ -122,15 +122,15 @@ HttpStatusCode CResourceHTMLItem::Request(HttpRequest* ipoHttpRequest, HttpRespo m_currentResponse = ipoHttpResponse; CLuaArguments querystring(formData); CLuaArguments args; - args.PushTable(&headers); // requestHeaders - args.PushTable(&formData); // form - args.PushTable(&cookies); // cookies - args.PushString(ipoHttpRequest->GetAddress().c_str()); // hostname - args.PushString(ipoHttpRequest->sOriginalUri.c_str()); // url - args.PushTable(&querystring); // querystring + args.PushTable(&headers); // requestHeaders + args.PushTable(&formData); // form + args.PushTable(&cookies); // cookies + args.PushString(ipoHttpRequest->GetAddress().c_str()); // hostname + args.PushString(ipoHttpRequest->sOriginalUri.c_str()); // url + args.PushTable(&querystring); // querystring args.PushAccount(account); - args.PushString(ipoHttpRequest->sBody); // requestBody - args.PushString(sMethod); // method + args.PushString(ipoHttpRequest->sBody); // requestBody + args.PushString(sMethod); // method // g_pGame->Lock(); // get the mutex (blocking) args.CallGlobal(m_pVM, "renderPage"); @@ -244,7 +244,7 @@ bool CResourceHTMLItem::Start() bool bIsShorthandCodeBlock = false; std::string strScript; strScript += "function renderPage ( requestHeaders, form, cookies, hostname, url, querystring, user, requestBody, method )\n"; - strScript += "\nhttpWrite ( \""; // bit hacky, possibly can be terminated straight away + strScript += "\nhttpWrite ( \""; // bit hacky, possibly can be terminated straight away unsigned char c; int i = 0; while (!feof(pFile)) @@ -253,19 +253,19 @@ bool CResourceHTMLItem::Start() if (feof(pFile)) break; - if (bInCode == false) // we're in a plain HTML section + if (bInCode == false) // we're in a plain HTML section { if (c == '<' && !feof(pFile)) { c = ReadChar(pFile); - if (c == '*') // we've found <* + if (c == '*') // we've found <* { bInCode = true; bJustStartedCodeBlock = true; - strScript.append("\" )\n"); // add ") to the end to terminate our last non-code section + strScript.append("\" )\n"); // add ") to the end to terminate our last non-code section } else - { // we found < but not a *, so just output both characters we read + { // we found < but not a *, so just output both characters we read strScript += '<'; strScript += c; } @@ -293,22 +293,22 @@ bool CResourceHTMLItem::Start() } } else - { // we're in a code block + { // we're in a code block if (c == '*' && !feof(pFile)) { c = ReadChar(pFile); - if (c == '>') // we've found *> + if (c == '>') // we've found *> { bInCode = false; if (bIsShorthandCodeBlock) { bIsShorthandCodeBlock = false; - strScript += ')'; // terminate the 'httpWrite' function + strScript += ')'; // terminate the 'httpWrite' function } - strScript.append("\nhttpWrite ( \""); // add httpWrite ( " to start a new non-code section + strScript.append("\nhttpWrite ( \""); // add httpWrite ( " to start a new non-code section } else - { // we found * but not a >, so just output both characters we read + { // we found * but not a >, so just output both characters we read strScript += '*'; strScript += c; } @@ -320,7 +320,7 @@ bool CResourceHTMLItem::Start() } else { - if (c != '\t' && c != ' ') // we allow whitespace before the shorthand '=' sign + if (c != '\t' && c != ' ') // we allow whitespace before the shorthand '=' sign bJustStartedCodeBlock = false; strScript += c; } diff --git a/Server/mods/deathmatch/logic/CResourceHTMLItem.h b/Server/mods/deathmatch/logic/CResourceHTMLItem.h index 506e0728611..f88505f8d45 100644 --- a/Server/mods/deathmatch/logic/CResourceHTMLItem.h +++ b/Server/mods/deathmatch/logic/CResourceHTMLItem.h @@ -15,7 +15,7 @@ #include "ehs/ehs.h" #ifndef MAX_PATH -#define MAX_PATH 260 + #define MAX_PATH 260 #endif class CResourceHTMLItem : public CResourceFile @@ -43,11 +43,11 @@ class CResourceHTMLItem : public CResourceFile char ReadChar(FILE* pFile) { return (unsigned char)fgetc(pFile); } void GetMimeType(const char* szFilename); - bool m_bIsBeingRequested; // crude mutex + bool m_bIsBeingRequested; // crude mutex bool m_bIsRaw; CLuaMain* m_pVM; - std::string m_strPageBuffer; // contains what we're sending - bool m_bDefault; // is this the default page for this resource? + std::string m_strPageBuffer; // contains what we're sending + bool m_bDefault; // is this the default page for this resource? std::string m_strMime; bool m_bRestricted; diff --git a/Server/mods/deathmatch/logic/CResourceManager.cpp b/Server/mods/deathmatch/logic/CResourceManager.cpp index 24102eb63f2..67dd48fd6d2 100644 --- a/Server/mods/deathmatch/logic/CResourceManager.cpp +++ b/Server/mods/deathmatch/logic/CResourceManager.cpp @@ -23,8 +23,8 @@ #include "CDatabaseManager.h" #include "CRegistry.h" -#define BLOCKED_DB_FILE_NAME "fileblock.db" -#define BLOCKED_DB_TABLE_NAME "`block_reasons`" +#define BLOCKED_DB_FILE_NAME "fileblock.db" +#define BLOCKED_DB_TABLE_NAME "`block_reasons`" // SResInfo - Item in list of potential resources - Used in Refresh() struct SResInfo @@ -549,7 +549,7 @@ CResource* CResourceManager::GetResourceFromNetID(unsigned short usNetID) { if ((*iter)->GetNetID() == usNetID) { - assert(0); // Should be in map + assert(0); // Should be in map return (*iter); } } @@ -1359,11 +1359,11 @@ void CResourceManager::ReevaluateSyncMapElementDataOption() { if (iter->second) { - bSyncMapElementData = true; // Any 'true' will stop the set + bSyncMapElementData = true; // Any 'true' will stop the set break; } else - bSyncMapElementData = false; // Need at least one 'false' to set + bSyncMapElementData = false; // Need at least one 'false' to set } // Apply diff --git a/Server/mods/deathmatch/logic/CResourceManager.h b/Server/mods/deathmatch/logic/CResourceManager.h index 66a8052bf8d..59f2f94766d 100644 --- a/Server/mods/deathmatch/logic/CResourceManager.h +++ b/Server/mods/deathmatch/logic/CResourceManager.h @@ -19,7 +19,7 @@ #include "ehs/ehs.h" #include -#define INVALID_RESOURCE_NET_ID 0xFFFF +#define INVALID_RESOURCE_NET_ID 0xFFFF class CResource; diff --git a/Server/mods/deathmatch/logic/CScriptDebugging.cpp b/Server/mods/deathmatch/logic/CScriptDebugging.cpp index 6e185fe7da5..de670b65741 100644 --- a/Server/mods/deathmatch/logic/CScriptDebugging.cpp +++ b/Server/mods/deathmatch/logic/CScriptDebugging.cpp @@ -148,7 +148,8 @@ void CScriptDebugging::Broadcast(const CPacket& Packet, unsigned int uiMinimumDe // Tell everyone we log to about it for (const auto& pPlayer : m_Players) { - bool sufficientDebugLevel = CheckForSufficientDebugLevel(static_cast(pPlayer->m_uiScriptDebugLevel), static_cast(uiMinimumDebugLevel)); + bool sufficientDebugLevel = + CheckForSufficientDebugLevel(static_cast(pPlayer->m_uiScriptDebugLevel), static_cast(uiMinimumDebugLevel)); if (sufficientDebugLevel) { diff --git a/Server/mods/deathmatch/logic/CScriptFile.h b/Server/mods/deathmatch/logic/CScriptFile.h index fbe1a6ff9fa..c9b03ebe6c3 100644 --- a/Server/mods/deathmatch/logic/CScriptFile.h +++ b/Server/mods/deathmatch/logic/CScriptFile.h @@ -32,7 +32,7 @@ class CScriptFile final : public CElement ~CScriptFile(); // Functions required by CElement - void Unlink(){}; + void Unlink() {}; // Load and unload routines bool Load(CResource* pResourceForFilePath, eMode Mode); diff --git a/Server/mods/deathmatch/logic/CSettings.cpp b/Server/mods/deathmatch/logic/CSettings.cpp index 00e1fe11e41..9f6f049c10c 100644 --- a/Server/mods/deathmatch/logic/CSettings.cpp +++ b/Server/mods/deathmatch/logic/CSettings.cpp @@ -16,7 +16,7 @@ #include "CGame.h" #include "CMapManager.h" -#define ERROR_BUFFER 32 +#define ERROR_BUFFER 32 CSettings::CSettings(CResourceManager* pResourceManager) { @@ -85,7 +85,7 @@ CXMLNode* CSettings::Get(CXMLNode* pSource, CXMLNode* pStorage, const char* szSo // Get the resource name from the specified setting if (!GetResourceName(szSetting, szQueryResource, MAX_RESOURCE_LENGTH - 1)) - { // (something): No resource specified, so use the local resource name + { // (something): No resource specified, so use the local resource name strncpy(szQueryResource, szLocalResource, MAX_RESOURCE_LENGTH - 1); } else @@ -169,7 +169,7 @@ CXMLNode* CSettings::Get(CXMLNode* pSource, CXMLNode* pStorage, const char* szSo } } else if (stricmp(szName, szQueryName) == 0 && stricmp(szResource, szQueryResource) == 0) - { // If the query name/resource and found node name/resource combinations are equal + { // If the query name/resource and found node name/resource combinations are equal eStatus = (stricmp(szResource, szLocalResource) == 0 || eAccess != CSettings::Private) ? Found : NoAccess; return pNode; } @@ -239,9 +239,9 @@ CXMLNode* CSettings::Get(const char* szLocalResource, const char* szSetting, boo // See if we found a matching setting if (eStatus == Found) - return pNode; // Found + return pNode; // Found else if (eStatus == NotFound) - { // Not found, continue searching + { // Not found, continue searching // Try to get the value for the appropriate setting from the resource's meta XML file if (pSource) pNode = Get(pSource, pStorage, pResource->GetName().c_str(), szLocalResource, szSetting, bDeleteNode, eStatus); @@ -257,7 +257,7 @@ CXMLNode* CSettings::Get(const char* szLocalResource, const char* szSetting, boo return pNode; } - return NULL; // No access or no settings found + return NULL; // No access or no settings found } // Creates a new setting and adds it to the destination node @@ -306,13 +306,13 @@ bool CSettings::Set(const char* szLocalResource, const char* szSetting, const ch // Check whether the setting exists in the settings registry pNode = Get(m_pNodeGlobalSettings, NULL, "", szLocalResource, szSetting, bDeleteNode, eStatus); - bExists = true; // Default value + bExists = true; // Default value // Try to get the value for the appropriate setting from the resource's meta XML file if (eStatus == NotFound && pSource) { pNode = Get(pSource, NULL, pResource->GetName().c_str(), szLocalResource, szSetting, bDeleteNode, eStatus); - bExists = false; // There's no node in the settings registry, so we create one + bExists = false; // There's no node in the settings registry, so we create one } // See if we have access @@ -340,11 +340,11 @@ bool CSettings::Set(const char* szLocalResource, const char* szSetting, const ch } if (!bExists || !pNode) - { // No existing settings registry entry, so create a new setting + { // No existing settings registry entry, so create a new setting CreateSetting(m_pNodeGlobalSettings, szBuffer, szContent); } else - { // Existing settings registry entry + { // Existing settings registry entry // Get the attributes pAttributes = &(pNode->GetAttributes()); @@ -392,13 +392,13 @@ bool CSettings::HasPrefix(char cCharacter) { switch (cCharacter) { - case SETTINGS_PREFIX_PRIVATE: // Private variable + case SETTINGS_PREFIX_PRIVATE: // Private variable return true; - case SETTINGS_PREFIX_PUBLIC: // Public variable + case SETTINGS_PREFIX_PUBLIC: // Public variable return true; - case SETTINGS_PREFIX_PROTECTED: // Protected variable + case SETTINGS_PREFIX_PROTECTED: // Protected variable return true; - default: // No variable + default: // No variable return false; } } @@ -408,13 +408,13 @@ CSettings::AccessType CSettings::GetAccessType(char cCharacter) { switch (cCharacter) { - case SETTINGS_PREFIX_PRIVATE: // Private variable + case SETTINGS_PREFIX_PRIVATE: // Private variable return CSettings::Private; - case SETTINGS_PREFIX_PUBLIC: // Public variable + case SETTINGS_PREFIX_PUBLIC: // Public variable return CSettings::Public; - case SETTINGS_PREFIX_PROTECTED: // Protected variable + case SETTINGS_PREFIX_PROTECTED: // Protected variable return CSettings::Protected; - default: // Default variable (as declared in SETTINGS_NO_PREFIX) + default: // Default variable (as declared in SETTINGS_NO_PREFIX) return SETTINGS_NO_PREFIX; } } @@ -424,7 +424,7 @@ inline const char* CSettings::GetResourceName(const char* szSetting, char* szBuf { const char* szChr = strchr(szSetting, SETTINGS_DELIMITER); if (szChr == NULL) - return NULL; // Not found? Return NULL, because there's no resource name. + return NULL; // Not found? Return NULL, because there's no resource name. // Strip off the prefix, if any if (HasPrefix(szSetting[0])) diff --git a/Server/mods/deathmatch/logic/CSpatialDatabase.cpp b/Server/mods/deathmatch/logic/CSpatialDatabase.cpp index fcf920d0ebe..affe883bd87 100644 --- a/Server/mods/deathmatch/logic/CSpatialDatabase.cpp +++ b/Server/mods/deathmatch/logic/CSpatialDatabase.cpp @@ -211,7 +211,7 @@ bool CSpatialDatabaseImpl::IsValidSphere(const CSphere& sphere) return false; // Check radius within limits - if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) + if (sphere.fRadius < -12000 || sphere.fRadius > 12000) // radius = sqrt(worldlimits*worldlimits + worldlimits*worldlimits) return false; // Check position within limits diff --git a/Server/mods/deathmatch/logic/CSpatialDatabase.h b/Server/mods/deathmatch/logic/CSpatialDatabase.h index a268b17828a..6e64738f341 100644 --- a/Server/mods/deathmatch/logic/CSpatialDatabase.h +++ b/Server/mods/deathmatch/logic/CSpatialDatabase.h @@ -13,7 +13,7 @@ class CElement; #pragma once // Bounding sphere z position for 2d objects -#define SPATIAL_2D_Z 0 +#define SPATIAL_2D_Z 0 // Result of a Query class CElementResult : public std::vector diff --git a/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp b/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp index 810820a820e..2e1065bd897 100644 --- a/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp +++ b/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp @@ -83,28 +83,28 @@ extern CGame* g_pGame; extern CTimeUsMarker<20> markerLatentEvent; -static CLuaManager* m_pLuaManager; -static CColManager* m_pColManager; -static CPickupManager* m_pPickupManager; -static CPlayerManager* m_pPlayerManager; -static CVehicleManager* m_pVehicleManager; -static CObjectManager* m_pObjectManager; -static CMarkerManager* m_pMarkerManager; -static CMapManager* m_pMapManager; -static CBlipManager* m_pBlipManager; -static CRadarAreaManager* m_pRadarAreaManager; -static CTeamManager* m_pTeamManager; -static CClock* m_pClock; -static CEvents* m_pEvents; -static CElementDeleter* m_pElementDeleter; -static CMainConfig* m_pMainConfig; -static CRegistry* m_pRegistry; -static CAccountManager* m_pAccountManager; -static CBanManager* m_pBanManager; -static CPedManager* m_pPedManager; -static CWaterManager* m_pWaterManager; -static CCustomWeaponManager* m_pCustomWeaponManager; -static CHandlingManager* m_pHandlingManager; +static CLuaManager* m_pLuaManager; +static CColManager* m_pColManager; +static CPickupManager* m_pPickupManager; +static CPlayerManager* m_pPlayerManager; +static CVehicleManager* m_pVehicleManager; +static CObjectManager* m_pObjectManager; +static CMarkerManager* m_pMarkerManager; +static CMapManager* m_pMapManager; +static CBlipManager* m_pBlipManager; +static CRadarAreaManager* m_pRadarAreaManager; +static CTeamManager* m_pTeamManager; +static CClock* m_pClock; +static CEvents* m_pEvents; +static CElementDeleter* m_pElementDeleter; +static CMainConfig* m_pMainConfig; +static CRegistry* m_pRegistry; +static CAccountManager* m_pAccountManager; +static CBanManager* m_pBanManager; +static CPedManager* m_pPedManager; +static CWaterManager* m_pWaterManager; +static CCustomWeaponManager* m_pCustomWeaponManager; +static CHandlingManager* m_pHandlingManager; // Used to run a function on all the children of the elements too #define RUN_CHILDREN(func) \ @@ -334,24 +334,25 @@ bool CStaticFunctionDefinitions::DestroyElement(CElement* pElement) // We can't destroy the root or a player/remote client/console int iType = pElement->GetType(); - if (pElement == m_pMapManager->GetRootElement() || iType == CElement::PLAYER || iType == CElement::CONSOLE || + if (pElement == m_pMapManager->GetRootElement() || iType == CElement::PLAYER || iType == CElement::CONSOLE || g_pGame->GetResourceManager()->IsAResourceElement(pElement)) { return false; } - if (iType == CElement::TEAM) { // Its team trigger onPlayerTeamChange for each player in the team + if (iType == CElement::TEAM) + { // Its team trigger onPlayerTeamChange for each player in the team CTeam* pTeam = static_cast(pElement); - auto iterBegin = pTeam->PlayersBegin(); - auto iterEnd = pTeam->PlayersEnd(); + auto iterBegin = pTeam->PlayersBegin(); + auto iterEnd = pTeam->PlayersEnd(); CLuaArguments arguments; for (auto iter = iterBegin; iter != iterEnd; ++iter) { CPlayer* player = *iter; - arguments.PushElement(pTeam); // Return team element as oldteam - arguments.PushNil(); // No new team return nil + arguments.PushElement(pTeam); // Return team element as oldteam + arguments.PushNil(); // No new team return nil player->CallEvent("onPlayerTeamChange", arguments); arguments.DeleteArguments(); } @@ -363,7 +364,7 @@ bool CStaticFunctionDefinitions::DestroyElement(CElement* pElement) // Unsync it (will destroy it for those that know about it) CPerPlayerEntity* pEntity = static_cast(pElement); pEntity->Sync(false); - } + } // Tell everyone to destroy it CEntityRemovePacket Packet; @@ -1018,7 +1019,7 @@ bool CStaticFunctionDefinitions::SetElementData(CElement* pElement, CStringName if (!pCurrentVariable || *pCurrentVariable != Variable || lastSyncType != syncType) { if (!pElement->SetCustomData(name, Variable, syncType)) - return false; // The server cancelled the change in onElementDataChange + return false; // The server cancelled the change in onElementDataChange if (syncType != ESyncType::LOCAL) { @@ -1055,14 +1056,14 @@ bool CStaticFunctionDefinitions::RemoveElementData(CElement* pElement, CStringNa if (pElement->GetCustomData(name, false)) { if (!pElement->DeleteCustomData(name)) - return false; // The server cancelled the change in onElementDataChange + return false; // The server cancelled the change in onElementDataChange // Tell our clients to update their data unsigned short usNameLength = static_cast(name->length()); CBitStream BitStream; BitStream.pBitStream->WriteCompressed(usNameLength); BitStream.pBitStream->Write(name.ToCString(), usNameLength); - BitStream.pBitStream->WriteBit(false); // Unused (was recursive flag) + BitStream.pBitStream->WriteBit(false); // Unused (was recursive flag) m_pPlayerManager->BroadcastOnlyJoined(CElementRPCPacket(pElement, REMOVE_ELEMENT_DATA, *BitStream.pBitStream)); // Clean up after the data removal @@ -1137,7 +1138,7 @@ bool CStaticFunctionDefinitions::SetElementParent(CElement* pElement, CElement* const char* szTypeName = pTemp->GetTypeName().c_str(); if (szTypeName && strcmp(szTypeName, "map") == 0) { - bValidParent = true; // parents must be a map + bValidParent = true; // parents must be a map break; } @@ -1191,7 +1192,7 @@ bool CStaticFunctionDefinitions::GetElementRotation(CElement* pElement, CVector& case CElement::PLAYER: { CPed* pPed = static_cast(pElement); - vecRotation.fZ = ConvertRadiansToDegrees(pPed->GetRotation()); // No conversion since only Z is used + vecRotation.fZ = ConvertRadiansToDegrees(pPed->GetRotation()); // No conversion since only Z is used break; } @@ -1304,7 +1305,7 @@ bool CStaticFunctionDefinitions::SetElementPosition(CElement* pElement, const CV assert(pElement); RUN_CHILDREN(SetElementPosition(*iter, vecPosition, bWarp)) - if (IS_PLAYER(pElement)) + if (IS_PLAYER(pElement)) { CPlayer* player = static_cast(pElement); player->SetTeleported(true); @@ -1359,7 +1360,7 @@ bool CStaticFunctionDefinitions::SetElementRotation(CElement* pElement, const CV case CElement::PLAYER: { CPed* pPed = static_cast(pElement); - SetPedRotation(pPed, vecRotation.fZ, bNewWay); // No rotation order conversion required since only Z is used + SetPedRotation(pPed, vecRotation.fZ, bNewWay); // No rotation order conversion required since only Z is used break; } @@ -1631,7 +1632,7 @@ bool CStaticFunctionDefinitions::AttachElements(CElement* pElement, CElement* pA if (IS_MARKER(pElement)) { CMarker* pMarker = static_cast(pElement); - CVector attachedPosition; + CVector attachedPosition; pMarker->GetAttachedPosition(attachedPosition); pMarker->SetPosition(attachedPosition); @@ -1690,7 +1691,7 @@ bool CStaticFunctionDefinitions::DetachElements(CElement* pElement, CElement* pA if (IS_MARKER(pElement)) { - CMarker* pMarker = static_cast(pElement); + CMarker* pMarker = static_cast(pElement); CColShape* pColShape = pMarker->GetColShape(); if (pColShape) RefreshColShapeColliders(pColShape); @@ -1831,11 +1832,11 @@ bool CStaticFunctionDefinitions::SetElementModel(CElement* pElement, unsigned sh return false; if (!CPlayerManager::IsValidPlayerModel(usModel)) return false; - unsigned short usOldModel = pPed->GetModel(); // Get the old model + unsigned short usOldModel = pPed->GetModel(); // Get the old model CLuaArguments Arguments; Arguments.PushNumber(usOldModel); - pPed->SetModel(usModel); // Set the new model - Arguments.PushNumber(usModel); // Get the new model + pPed->SetModel(usModel); // Set the new model + Arguments.PushNumber(usModel); // Get the new model bool bContinue = pPed->CallEvent("onElementModelChange", Arguments); // Check for another call to setElementModel if (usModel != pPed->GetModel()) @@ -1856,11 +1857,11 @@ bool CStaticFunctionDefinitions::SetElementModel(CElement* pElement, unsigned sh return false; if (!CVehicleManager::IsValidModel(usModel)) return false; - unsigned short usOldModel = pVehicle->GetModel(); // Get the old model + unsigned short usOldModel = pVehicle->GetModel(); // Get the old model CLuaArguments Arguments; Arguments.PushNumber(usOldModel); - pVehicle->SetModel(usModel); // Set the new model - Arguments.PushNumber(usModel); // Get the new model + pVehicle->SetModel(usModel); // Set the new model + Arguments.PushNumber(usModel); // Get the new model bool bContinue = pVehicle->CallEvent("onElementModelChange", Arguments); // Check for another call to setElementModel if (usModel != pVehicle->GetModel()) @@ -1899,11 +1900,11 @@ bool CStaticFunctionDefinitions::SetElementModel(CElement* pElement, unsigned sh return false; if (!CObjectManager::IsValidModel(usModel)) return false; - unsigned short usOldModel = pObject->GetModel(); // Get the old model + unsigned short usOldModel = pObject->GetModel(); // Get the old model CLuaArguments Arguments; Arguments.PushNumber(usOldModel); - pObject->SetModel(usModel); // Set the new model - Arguments.PushNumber(usModel); // Get the new model + pObject->SetModel(usModel); // Set the new model + Arguments.PushNumber(usModel); // Get the new model bool bContinue = pObject->CallEvent("onElementModelChange", Arguments); // Check for another call to setElementModel if (usModel != pObject->GetModel()) @@ -2184,7 +2185,7 @@ bool CStaticFunctionDefinitions::SetPlayerName(CElement* pElement, const char* s CLuaArguments Arguments; Arguments.PushString(szNick); Arguments.PushString(szName); - Arguments.PushBoolean(false); // manually changed + Arguments.PushBoolean(false); // manually changed pPlayer->CallEvent("onPlayerChangeNick", Arguments); // Tell the console @@ -2511,7 +2512,7 @@ bool CStaticFunctionDefinitions::SetWeaponProperty(eWeaponProperty eProperty, eW BitStream.pBitStream->Write(static_cast(eProperty)); BitStream.pBitStream->Write(static_cast(eSkillLevel)); if (eProperty == WEAPON_FLAGS) - BitStream.pBitStream->Write(sData); // Backward compat because sent little end first + BitStream.pBitStream->Write(sData); // Backward compat because sent little end first else BitStream.pBitStream->Write((short)sData); m_pPlayerManager->BroadcastOnlyJoined(CLuaPacket(SET_WEAPON_PROPERTY, *BitStream.pBitStream)); @@ -4332,9 +4333,9 @@ bool CStaticFunctionDefinitions::WarpPedIntoVehicle(CPed* pPed, CVehicle* pVehic // Call the player->vehicle event CLuaArguments PlayerVehicleArguments; - PlayerVehicleArguments.PushElement(pVehicle); // vehicle - PlayerVehicleArguments.PushNumber(uiSeat); // seat - if (pPreviousOccupant) // jacked + PlayerVehicleArguments.PushElement(pVehicle); // vehicle + PlayerVehicleArguments.PushNumber(uiSeat); // seat + if (pPreviousOccupant) // jacked PlayerVehicleArguments.PushElement(pPreviousOccupant); else PlayerVehicleArguments.PushBoolean(false); @@ -4346,9 +4347,9 @@ bool CStaticFunctionDefinitions::WarpPedIntoVehicle(CPed* pPed, CVehicle* pVehic // Call the vehicle->player event CLuaArguments VehiclePlayerArguments; - VehiclePlayerArguments.PushElement(pPed); // player - VehiclePlayerArguments.PushNumber(uiSeat); // seat - if (pPreviousOccupant) // jacked + VehiclePlayerArguments.PushElement(pPed); // player + VehiclePlayerArguments.PushNumber(uiSeat); // seat + if (pPreviousOccupant) // jacked VehiclePlayerArguments.PushElement(pPreviousOccupant); else VehiclePlayerArguments.PushBoolean(false); @@ -4382,14 +4383,14 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CElement* pElement) if (pVehicle) { unsigned int uiVehicleAction = pPed->GetVehicleAction(); - + // Handle mid-enter/exit states if (uiVehicleAction == CPed::VEHICLEACTION_ENTERING || uiVehicleAction == CPed::VEHICLEACTION_JACKING) { pVehicle->SetOccupant(nullptr, ucOccupiedSeat); pPed->SetOccupiedVehicle(nullptr, 0); pPed->SetVehicleAction(CPed::VEHICLEACTION_NONE); - + if (uiVehicleAction == CPed::VEHICLEACTION_JACKING) pPed->SetJackingVehicle(nullptr); @@ -4399,15 +4400,15 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CElement* pElement) CVehicleInOutPacket Reply(pPed->GetID(), pVehicle->GetID(), ucOccupiedSeat, CGame::VEHICLE_NOTIFY_IN_ABORT_RETURN); m_pPlayerManager->BroadcastOnlyJoined(Reply); } - + return true; } - + CLuaArguments Arguments; - Arguments.PushElement(pVehicle); // vehicle - Arguments.PushNumber(ucOccupiedSeat); // seat - Arguments.PushBoolean(false); // jacker - Arguments.PushBoolean(true); // forcedByScript + Arguments.PushElement(pVehicle); // vehicle + Arguments.PushNumber(ucOccupiedSeat); // seat + Arguments.PushBoolean(false); // jacker + Arguments.PushBoolean(true); // forcedByScript if (IS_PLAYER(pPed)) pPed->CallEvent("onPlayerVehicleExit", Arguments); else @@ -4415,10 +4416,10 @@ bool CStaticFunctionDefinitions::RemovePedFromVehicle(CElement* pElement) // Call the vehicle->ped event CLuaArguments Arguments2; - Arguments2.PushElement(pPed); // player / ped - Arguments2.PushNumber(ucOccupiedSeat); // seat - Arguments2.PushBoolean(false); // jacker - Arguments2.PushBoolean(true); // forcedByScript + Arguments2.PushElement(pPed); // player / ped + Arguments2.PushNumber(ucOccupiedSeat); // seat + Arguments2.PushBoolean(false); // jacker + Arguments2.PushBoolean(true); // forcedByScript pVehicle->CallEvent("onVehicleExit", Arguments2); // Remove him from the vehicle @@ -4490,7 +4491,8 @@ bool CStaticFunctionDefinitions::SetPedAnimation(CElement* pElement, const SStri pPed->SetChoking(false); // Store anim data - pPed->SetAnimationData(SPlayerAnimData{blockName, animName, iTime, bLoop, bUpdatePosition, bInterruptable, bFreezeLastFrame, iBlend, bTaskToBeRestoredOnAnimEnd, GetTickCount64_()}); + pPed->SetAnimationData(SPlayerAnimData{blockName, animName, iTime, bLoop, bUpdatePosition, bInterruptable, bFreezeLastFrame, iBlend, + bTaskToBeRestoredOnAnimEnd, GetTickCount64_()}); BitStream.pBitStream->WriteString(blockName); BitStream.pBitStream->WriteString(animName); @@ -4633,7 +4635,8 @@ bool CStaticFunctionDefinitions::SetPedFrozen(CElement* pElement, bool bIsFrozen return false; } -bool CStaticFunctionDefinitions::ReloadPedWeapon(CElement* pElement) noexcept { +bool CStaticFunctionDefinitions::ReloadPedWeapon(CElement* pElement) noexcept +{ assert(pElement); RUN_CHILDREN(ReloadPedWeapon(*iter)) @@ -4645,7 +4648,7 @@ bool CStaticFunctionDefinitions::ReloadPedWeapon(CElement* pElement) noexcept { bool result; CLuaArguments arguments; - std::uint8_t weapon = ped->GetWeaponType(); + std::uint8_t weapon = ped->GetWeaponType(); std::uint16_t clip = ped->GetWeaponAmmoInClip(); std::uint16_t ammo = ped->GetWeaponTotalAmmo(); @@ -4676,12 +4679,12 @@ bool CStaticFunctionDefinitions::GetCameraMatrix(CPlayer* pPlayer, CVector& vecP CPlayerCamera* pCamera = pPlayer->GetCamera(); if (!pCamera) return false; - + pCamera->GetPosition(vecPosition); pCamera->GetLookAt(vecLookAt); fRoll = pCamera->GetRoll(); fFOV = pCamera->GetFOV(); - + return true; } @@ -4718,7 +4721,7 @@ bool CStaticFunctionDefinitions::SetCameraMatrix(CElement* pElement, const CVect if (!CameraScriptShared::IsFiniteVector(sanitizedPosition)) return false; - CVector sanitizedLookAt; + CVector sanitizedLookAt; CVector* pSanitizedLookAt = nullptr; if (pvecLookAt) { @@ -4918,11 +4921,11 @@ bool CStaticFunctionDefinitions::GiveWeapon(CElement* pElement, unsigned char uc // Client ammo emulation mode - Try to ensure that the ammo we set on the server will be the same as the client) if (ucWeaponSlot <= 1 || ucWeaponSlot >= 10) - uiTotalAmmo = std::min(1U, uiTotalAmmo + usAmmo); // If slot 0,1,10,11,12 - Ammo is max 1 + uiTotalAmmo = std::min(1U, uiTotalAmmo + usAmmo); // If slot 0,1,10,11,12 - Ammo is max 1 else if ((ucWeaponSlot >= 3 && ucWeaponSlot <= 5) || ucPreviousWeaponID == ucWeaponID) - uiTotalAmmo += usAmmo; // If slot 3,4,5 or slot weapon the same, ammo is shared, so add + uiTotalAmmo += usAmmo; // If slot 3,4,5 or slot weapon the same, ammo is shared, so add else - uiTotalAmmo = usAmmo; // Otherwise ammo is not shared, so replace + uiTotalAmmo = usAmmo; // Otherwise ammo is not shared, so replace uiTotalAmmo = std::min(0xFFFFU, uiTotalAmmo); pPed->SetWeaponTotalAmmo(static_cast(uiTotalAmmo), ucWeaponSlot); @@ -5041,7 +5044,7 @@ bool CStaticFunctionDefinitions::SetWeaponAmmo(CElement* pElement, unsigned char { CPed* pPed = static_cast(pElement); CWeapon* pWeapon = pPed->GetWeapon(CWeaponNames::GetSlotFromWeapon(ucWeaponID)); - if (pPed->IsSpawned() && pWeapon) // Check We have that weapon + if (pPed->IsSpawned() && pWeapon) // Check We have that weapon { unsigned char ucWeaponID = pWeapon->ucType; if (ucWeaponID) @@ -5138,7 +5141,7 @@ bool CStaticFunctionDefinitions::GiveVehicleSirens(CVehicle* pVehicle, unsigned eVehicleType vehicleType = CVehicleManager::GetVehicleType(pVehicle->GetModel()); // Won't work with below. if (vehicleType != VEHICLE_CAR && vehicleType != VEHICLE_MONSTERTRUCK && vehicleType != VEHICLE_QUADBIKE) - return false; + return false; if (ucSirenType < 1 || ucSirenType > 6) return false; @@ -5591,7 +5594,7 @@ bool CStaticFunctionDefinitions::BlowVehicle(CElement* pElement, std::optionalSetBlowState(createExplosion ? VehicleBlowState::AWAITING_EXPLOSION_SYNC : VehicleBlowState::BLOWN); CLuaArguments arguments; - arguments.PushBoolean(createExplosion); // withExplosion + arguments.PushBoolean(createExplosion); // withExplosion if (!vehicle->CallEvent("onVehicleExplode", arguments)) return false; @@ -5915,7 +5918,7 @@ bool CStaticFunctionDefinitions::GetEntryHandling(const CHandlingEntry* pEntry, case HANDLING_SEATOFFSETDISTANCE: fValue = pEntry->GetSeatOffsetDistance(); break; - case HANDLING_ABS: // bool + case HANDLING_ABS: // bool fValue = (float)(pEntry->GetABS() ? 1 : 0); break; default: @@ -5934,7 +5937,7 @@ bool CStaticFunctionDefinitions::GetEntryHandling(const CHandlingEntry* pEntry, { switch (eProperty) { - case HANDLING_PERCENTSUBMERGED: // unsigned int + case HANDLING_PERCENTSUBMERGED: // unsigned int uiValue = pEntry->GetPercentSubmerged(); break; case HANDLING_MONETARY: @@ -6119,7 +6122,7 @@ bool CStaticFunctionDefinitions::SetEntryHandling(CHandlingEntry* pEntry, eHandl if (ucValue >= 0 && ucValue <= 29) { if (ucValue != 3 && ucValue != 8 && ucValue != 17 && ucValue != 23) - return true; // Pretend it worked to avoid script warnings + return true; // Pretend it worked to avoid script warnings pEntry->SetAnimGroup(ucValue); return true; @@ -6902,7 +6905,8 @@ bool CStaticFunctionDefinitions::SetVehicleLightState(CElement* pElement, unsign return false; } -bool CStaticFunctionDefinitions::SetVehiclePanelState(CElement* pElement, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent, bool breakGlass) +bool CStaticFunctionDefinitions::SetVehiclePanelState(CElement* pElement, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent, + bool breakGlass) { assert(pElement); RUN_CHILDREN(SetVehiclePanelState(*iter, ucPanel, ucState, spawnFlyingComponent, breakGlass)) @@ -8370,8 +8374,8 @@ bool CStaticFunctionDefinitions::SetObjectScale(CElement* pElement, const CVecto CBitStream BitStream; BitStream.pBitStream->Write(vecScale.fX); - BitStream.pBitStream->Write(vecScale.fY); // Ignored by clients with bitstream version < 0x41 - BitStream.pBitStream->Write(vecScale.fZ); // Ignored by clients with bitstream version < 0x41 + BitStream.pBitStream->Write(vecScale.fY); // Ignored by clients with bitstream version < 0x41 + BitStream.pBitStream->Write(vecScale.fZ); // Ignored by clients with bitstream version < 0x41 m_pPlayerManager->BroadcastOnlyJoined(CElementRPCPacket(pObject, SET_OBJECT_SCALE, *BitStream.pBitStream)); return true; } @@ -8476,7 +8480,7 @@ bool CStaticFunctionDefinitions::BreakObject(CElement* pElement) CBitStream BitStream; m_pPlayerManager->BroadcastOnlyJoined(CElementRPCPacket(pObject, BREAK_OBJECT, *BitStream.pBitStream)); - + return true; } @@ -8950,7 +8954,7 @@ bool CStaticFunctionDefinitions::CreateExplosion(const CVector& vecPosition, uns if (pElement) { RUN_CHILDREN(CreateExplosion(vecPosition, ucType, *iter)) - + if (IS_PLAYER(pElement)) { CPlayer* player = static_cast(pElement); @@ -9498,14 +9502,14 @@ bool CStaticFunctionDefinitions::SetPlayerTeam(CPlayer* pPlayer, CTeam* pTeam) if (currentTeam) { Arguments.PushElement(currentTeam); - } + } else { - Arguments.PushNil(); // No oldTeam return nil + Arguments.PushNil(); // No oldTeam return nil } Arguments.PushElement(pTeam); if (!pPlayer->CallEvent("onPlayerTeamChange", Arguments)) - return false; // Event cancelled, return false + return false; // Event cancelled, return false // Change his team pPlayer->SetTeam(pTeam, true); @@ -10996,7 +11000,7 @@ bool CStaticFunctionDefinitions::RemoveWorldModel(unsigned short usModel, float BitStream.pBitStream->Write(vecPosition.fX); BitStream.pBitStream->Write(vecPosition.fY); BitStream.pBitStream->Write(vecPosition.fZ); - BitStream.pBitStream->Write(cInterior); // Only used by clients with bitstream version >= 0x039 + BitStream.pBitStream->Write(cInterior); // Only used by clients with bitstream version >= 0x039 m_pPlayerManager->BroadcastOnlyJoined(CLuaPacket(REMOVE_WORLD_MODEL, *BitStream.pBitStream)); return true; @@ -11012,7 +11016,7 @@ bool CStaticFunctionDefinitions::RestoreWorldModel(unsigned short usModel, float BitStream.pBitStream->Write(vecPosition.fX); BitStream.pBitStream->Write(vecPosition.fY); BitStream.pBitStream->Write(vecPosition.fZ); - BitStream.pBitStream->Write(cInterior); // Only used by clients with bitstream version >= 0x039 + BitStream.pBitStream->Write(cInterior); // Only used by clients with bitstream version >= 0x039 m_pPlayerManager->BroadcastOnlyJoined(CLuaPacket(RESTORE_WORLD_MODEL, *BitStream.pBitStream)); @@ -11056,7 +11060,6 @@ bool CStaticFunctionDefinitions::SendSyncIntervals(CPlayer* pPlayer) pPlayer->Send(CLuaPacket(SET_SYNC_INTERVALS, *BitStream.pBitStream)); }; - if (pPlayer) sendSyncIntervalPatket(pPlayer); else @@ -11192,7 +11195,7 @@ bool CStaticFunctionDefinitions::SetWaveHeight(float fHeight) bool CStaticFunctionDefinitions::SetFPSLimit(std::uint16_t fps, bool save) { - if(!g_pGame->GetConfig()->SetFPSLimit(fps, save)) + if (!g_pGame->GetConfig()->SetFPSLimit(fps, save)) return false; CBitStream BitStream; @@ -11627,7 +11630,6 @@ bool CStaticFunctionDefinitions::GetAccountSerial(CAccount* pAccount, SString& s return bRegistered; } - bool CStaticFunctionDefinitions::SetAccountSerial(CAccount* account, const std::string& serial) noexcept { if (account && account->IsRegistered()) @@ -12682,7 +12684,8 @@ bool CStaticFunctionDefinitions::SetColPolygonHeight(CColPolygon* pColPolygon, f return false; } -bool CStaticFunctionDefinitions::SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::uint8_t collisionType, std::int32_t removalTime) +bool CStaticFunctionDefinitions::SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::uint8_t collisionType, + std::int32_t removalTime) { CBitStream bitStream; bitStream.pBitStream->Write(nodeIndex); diff --git a/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.h b/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.h index 388f38b4439..0b642a1714d 100644 --- a/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.h +++ b/Server/mods/deathmatch/logic/CStaticFunctionDefinitions.h @@ -243,7 +243,7 @@ class CStaticFunctionDefinitions // Vehicle create/destroy functions static CVehicle* CreateVehicle(CResource* pResource, unsigned short usModel, const CVector& vecPosition, const CVector& vecRotation, const char* szRegPlate, unsigned char ucVariant, unsigned char ucVariant2, bool bSynced); - static bool SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::uint8_t collisionType, std::int32_t removalTime = -1); + static bool SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::uint8_t collisionType, std::int32_t removalTime = -1); // Vehicle get functions static bool GetVehicleVariant(CVehicle* pVehicle, unsigned char& ucVariant, unsigned char& ucVariant2); @@ -314,7 +314,8 @@ class CStaticFunctionDefinitions static bool SetVehicleDoorState(CElement* pElement, unsigned char ucDoor, unsigned char ucState, bool spawnFlyingComponent); static bool SetVehicleWheelStates(CElement* pElement, int iFrontLeft, int iRearLeft = -1, int iFrontRight = -1, int iRearRight = -1); static bool SetVehicleLightState(CElement* pElement, unsigned char ucLight, unsigned char ucState); - static bool SetVehiclePanelState(CElement* pElement, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent = true, bool breakGlass = false); + static bool SetVehiclePanelState(CElement* pElement, unsigned char ucPanel, unsigned char ucState, bool spawnFlyingComponent = true, + bool breakGlass = false); static bool SetVehicleIdleRespawnDelay(CElement* pElement, unsigned long ulTime); static bool SetVehicleRespawnDelay(CElement* pElement, unsigned long ulTime); static bool GetVehicleRespawnPosition(CElement* pElement, CVector& vecPosition); @@ -371,7 +372,8 @@ class CStaticFunctionDefinitions static bool RemoveVehicleSirens(CVehicle* pVehicle); // Marker create/destroy functions - static CMarker* CreateMarker(CResource* pResource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, CElement* pVisibleTo, bool ignoreAlphaLimits); + static CMarker* CreateMarker(CResource* pResource, const CVector& vecPosition, const char* szType, float fSize, const SColor color, CElement* pVisibleTo, + bool ignoreAlphaLimits); // Marker get functions static bool GetMarkerCount(unsigned int& uiCount); diff --git a/Server/mods/deathmatch/logic/CTeam.h b/Server/mods/deathmatch/logic/CTeam.h index 69866b0acb9..6558472ff76 100644 --- a/Server/mods/deathmatch/logic/CTeam.h +++ b/Server/mods/deathmatch/logic/CTeam.h @@ -33,9 +33,9 @@ class CTeam final : public CElement const char* GetTeamName() { return m_strTeamName; } void SetTeamName(const char* szName); - void AddPlayer(CPlayer* pPlayer, bool bChangePlayer = false); - void RemovePlayer(CPlayer* pPlayer, bool bChangePlayer = false); - void RemoveAllPlayers(); + void AddPlayer(CPlayer* pPlayer, bool bChangePlayer = false); + void RemovePlayer(CPlayer* pPlayer, bool bChangePlayer = false); + void RemoveAllPlayers(); std::vector GetPlayers() const; void GetColor(unsigned char& ucRed, unsigned char& ucGreen, unsigned char& ucBlue); diff --git a/Server/mods/deathmatch/logic/CTrainTrack.h b/Server/mods/deathmatch/logic/CTrainTrack.h index 84d576c4dde..87a9f1b3c2c 100644 --- a/Server/mods/deathmatch/logic/CTrainTrack.h +++ b/Server/mods/deathmatch/logic/CTrainTrack.h @@ -23,7 +23,7 @@ struct STrackNode position.fX = 8.0f * x; position.fY = 8.0f * y; position.fZ = 8.0f * z; - railDistance = 3.0f * distance; // TODO(Jusonex, feature/custom-train-tracks/9063a3dc080): Remove distance + railDistance = 3.0f * distance; // TODO(Jusonex, feature/custom-train-tracks/9063a3dc080): Remove distance } STrackNode(const CVector& pos) : position(pos) {} diff --git a/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp b/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp index a8687552a03..6f9a0678b9d 100644 --- a/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp +++ b/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.cpp @@ -204,7 +204,7 @@ void CUnoccupiedVehicleSync::StartSync(CPlayer* pPlayer, CVehicle* pVehicle) // Call the onElementStartSync event CLuaArguments Arguments; - Arguments.PushElement(pPlayer); // New syncer + Arguments.PushElement(pPlayer); // New syncer pVehicle->CallEvent("onElementStartSync", Arguments); } @@ -221,7 +221,7 @@ void CUnoccupiedVehicleSync::StopSync(CVehicle* pVehicle) // Call the onElementStopSync event CLuaArguments Arguments; - Arguments.PushElement(pSyncer); // Old syncer + Arguments.PushElement(pSyncer); // Old syncer pVehicle->CallEvent("onElementStopSync", Arguments); } @@ -488,8 +488,8 @@ void CUnoccupiedVehicleSync::Packet_UnoccupiedVehiclePushSync(CUnoccupiedVehicle // Is the player syncing this vehicle and there is no driver? Also only process // this packet if the time context matches. if (pVehicle->GetSyncer() != pPlayer && pVehicle->GetTimeSinceLastPush() >= MIN_PUSH_ANTISPAM_RATE && - IsPointNearPoint3D(pVehicle->GetPosition(), pPlayer->GetPosition(), static_cast(g_TickRateSettings.iVehicleContactSyncRadius)) - && pVehicle->GetDimension() == pPlayer->GetDimension()) + IsPointNearPoint3D(pVehicle->GetPosition(), pPlayer->GetPosition(), static_cast(g_TickRateSettings.iVehicleContactSyncRadius)) && + pVehicle->GetDimension() == pPlayer->GetDimension()) { // Is there no player driver? CPed* pOccupant = pVehicle->GetOccupant(0); diff --git a/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.h b/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.h index 787329fc863..a6aa8feb94a 100644 --- a/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.h +++ b/Server/mods/deathmatch/logic/CUnoccupiedVehicleSync.h @@ -11,8 +11,8 @@ #pragma once -#define MIN_ROTATION_DIFF 0.1 -#define MIN_PUSH_ANTISPAM_RATE 1500 +#define MIN_ROTATION_DIFF 0.1 +#define MIN_PUSH_ANTISPAM_RATE 1500 class CVehicle; class CPlayer; diff --git a/Server/mods/deathmatch/logic/CVehicle.h b/Server/mods/deathmatch/logic/CVehicle.h index 8c24363d65a..4430a5a41bf 100644 --- a/Server/mods/deathmatch/logic/CVehicle.h +++ b/Server/mods/deathmatch/logic/CVehicle.h @@ -20,9 +20,9 @@ class CVehicle; #include "CVehicleUpgrades.h" #include "CHandlingEntry.h" -#define MAX_VEHICLE_SEATS 9 +#define MAX_VEHICLE_SEATS 9 #define DEFAULT_VEHICLE_HEALTH 1000 -#define MAX_VEHICLE_HEALTH 10000 +#define MAX_VEHICLE_HEALTH 10000 enum eWheelStatus { @@ -155,9 +155,9 @@ enum class eCarComponentCollisionTypes }; #define SIREN_TYPE_FIRST 1 -#define SIREN_TYPE_LAST 6 -#define SIREN_ID_MAX 7 -#define SIREN_COUNT_MAX 8 +#define SIREN_TYPE_LAST 6 +#define SIREN_ID_MAX 7 +#define SIREN_COUNT_MAX 8 struct SSirenBeaconInfo { @@ -501,7 +501,7 @@ class CVehicle final : public CElement bool m_bNeedsDimensionResync; ushort m_usLastUnoccupiedSyncDimension; -public: // 'Safe' variables (that have no need for accessors) +public: // 'Safe' variables (that have no need for accessors) bool m_bDamageProof; uint m_uiDamageInfoSendPhase; SFixedArray m_ucDoorStates; diff --git a/Server/mods/deathmatch/logic/CVehicleManager.cpp b/Server/mods/deathmatch/logic/CVehicleManager.cpp index 76621cecb8a..bab0e77a87e 100644 --- a/Server/mods/deathmatch/logic/CVehicleManager.cpp +++ b/Server/mods/deathmatch/logic/CVehicleManager.cpp @@ -14,40 +14,40 @@ #include "Utils.h" #include "lua/LuaCommon.h" -static const SFixedArray g_ucMaxPassengers = {{3, 1, 1, 1, 3, 3, 0, 1, 1, 3, 1, 1, 1, 3, 1, 1, // 400->415 - 3, 1, 3, 1, 3, 3, 1, 1, 1, 0, 3, 3, 3, 1, 0, 8, // 416->431 - 0, 1, 1, 255, 1, 8, 3, 1, 3, 0, 1, 1, 1, 3, 0, 1, // 432->447 - 0, 1, 255, 1, 0, 0, 0, 1, 1, 1, 3, 3, 1, 1, 1, // 448->462 - 1, 1, 1, 3, 3, 1, 1, 3, 1, 0, 0, 1, 1, 0, 1, 1, // 463->478 - 3, 1, 0, 3, 3, 0, 0, 0, 3, 1, 1, 3, 1, 3, 0, 1, // 479->494 - 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, // 495->510 - 1, 0, 0, 1, 1, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, // 511->526 - 1, 1, 3, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 3, 1, // 527->541 - 1, 1, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 1, 1, 1, 1, // 542->557 - 1, 1, 3, 3, 1, 1, 0, 1, 3, 3, 0, 255, 1, 0, 0, // 558->572 - 1, 0, 1, 1, 1, 1, 3, 3, 1, 3, 0, 255, 3, 1, 1, 1, // 573->588 - 1, 255, 255, 1, 1, 1, 0, 3, 3, 3, 1, 1, 1, 1, 1, // 589->604 - 3, 1, 255, 255, 255, 3, 255, 255}}; // 605->611 +static const SFixedArray g_ucMaxPassengers = {{3, 1, 1, 1, 3, 3, 0, 1, 1, 3, 1, 1, 1, 3, 1, 1, // 400->415 + 3, 1, 3, 1, 3, 3, 1, 1, 1, 0, 3, 3, 3, 1, 0, 8, // 416->431 + 0, 1, 1, 255, 1, 8, 3, 1, 3, 0, 1, 1, 1, 3, 0, 1, // 432->447 + 0, 1, 255, 1, 0, 0, 0, 1, 1, 1, 3, 3, 1, 1, 1, // 448->462 + 1, 1, 1, 3, 3, 1, 1, 3, 1, 0, 0, 1, 1, 0, 1, 1, // 463->478 + 3, 1, 0, 3, 3, 0, 0, 0, 3, 1, 1, 3, 1, 3, 0, 1, // 479->494 + 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, // 495->510 + 1, 0, 0, 1, 1, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, // 511->526 + 1, 1, 3, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 3, 1, // 527->541 + 1, 1, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 1, 1, 1, 1, // 542->557 + 1, 1, 3, 3, 1, 1, 0, 1, 3, 3, 0, 255, 1, 0, 0, // 558->572 + 1, 0, 1, 1, 1, 1, 3, 3, 1, 3, 0, 255, 3, 1, 1, 1, // 573->588 + 1, 255, 255, 1, 1, 1, 0, 3, 3, 3, 1, 1, 1, 1, 1, // 589->604 + 3, 1, 255, 255, 255, 3, 255, 255}}; // 605->611 // List over all vehicles with their special attributes -#define VEHICLE_HAS_TURRENT 0x001UL //1 -#define VEHICLE_HAS_SIRENS 0x002UL //2 -#define VEHICLE_HAS_LANDING_GEARS 0x004UL //4 -#define VEHICLE_HAS_ADJUSTABLE_PROPERTY 0x008UL //8 -#define VEHICLE_HAS_SMOKE_TRAIL 0x010UL //16 -#define VEHICLE_HAS_TAXI_LIGHTS 0x020UL //32 -#define VEHICLE_HAS_SEARCH_LIGHT 0x040UL //64 +#define VEHICLE_HAS_TURRENT 0x001UL // 1 +#define VEHICLE_HAS_SIRENS 0x002UL // 2 +#define VEHICLE_HAS_LANDING_GEARS 0x004UL // 4 +#define VEHICLE_HAS_ADJUSTABLE_PROPERTY 0x008UL // 8 +#define VEHICLE_HAS_SMOKE_TRAIL 0x010UL // 16 +#define VEHICLE_HAS_TAXI_LIGHTS 0x020UL // 32 +#define VEHICLE_HAS_SEARCH_LIGHT 0x040UL // 64 // Generated by MTA10\utils\gentable\gentable_vehattr.cpp static const SFixedArray g_ulVehicleAttributes = { - {0, 0, 0, 0, 0, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 32, 0, 0, 2, 0, // 400-424 - 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 425-449 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 450-474 - 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 64, 0, 0, // 475-499 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 4, 12, 0, 0, 2, 8, // 500-524 - 8, 0, 0, 2, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, // 525-549 - 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 550-574 - 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 2, 2, 2, 2, // 575-599 + {0, 0, 0, 0, 0, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 32, 0, 0, 2, 0, // 400-424 + 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 425-449 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 450-474 + 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 64, 0, 0, // 475-499 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 4, 12, 0, 0, 2, 8, // 500-524 + 8, 0, 0, 2, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, // 525-549 + 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 550-574 + 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 2, 2, 2, 2, // 575-599 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; static const SFixedArray gs_vehicleTypes = { diff --git a/Server/mods/deathmatch/logic/CVehicleManager.h b/Server/mods/deathmatch/logic/CVehicleManager.h index f8ecfdb5aeb..fe674982347 100644 --- a/Server/mods/deathmatch/logic/CVehicleManager.h +++ b/Server/mods/deathmatch/logic/CVehicleManager.h @@ -18,7 +18,7 @@ class CVehicleManager; #include // Undefined number of passengers (to disable custom passenger seats overriding in CVehicle) -#define VEHICLE_PASSENGERS_UNDEFINED 255 +#define VEHICLE_PASSENGERS_UNDEFINED 255 class CVehicleManager { diff --git a/Server/mods/deathmatch/logic/CVehicleNames.cpp b/Server/mods/deathmatch/logic/CVehicleNames.cpp index 84bac0b1c76..ae8d51085fc 100644 --- a/Server/mods/deathmatch/logic/CVehicleNames.cpp +++ b/Server/mods/deathmatch/logic/CVehicleNames.cpp @@ -18,7 +18,7 @@ const char* szVehicleNameEmpty = ""; struct SVehicleName { const char* szName; - const char* szName_replaced; // Compatability + const char* szName_replaced; // Compatability }; static const SFixedArray VehicleNames = {{{"Landstalker"}, diff --git a/Server/mods/deathmatch/logic/CVehicleUpgrades.cpp b/Server/mods/deathmatch/logic/CVehicleUpgrades.cpp index d46f31e8417..f06d97855fb 100644 --- a/Server/mods/deathmatch/logic/CVehicleUpgrades.cpp +++ b/Server/mods/deathmatch/logic/CVehicleUpgrades.cpp @@ -320,17 +320,17 @@ bool CVehicleUpgrades::GetSlotFromUpgrade(unsigned short us, unsigned char& ucSl ucSlot = 3; return true; } - if (us == 1115 || us == 1116) // front bullbars + if (us == 1115 || us == 1116) // front bullbars { ucSlot = 4; return true; } - if (us == 1109 || us == 1110) // rear bullbars + if (us == 1109 || us == 1110) // rear bullbars { ucSlot = 5; return true; } - if (us == 1013 || us == 1024) // lamps + if (us == 1013 || us == 1024) // lamps { ucSlot = 6; return true; @@ -342,17 +342,17 @@ bool CVehicleUpgrades::GetSlotFromUpgrade(unsigned short us, unsigned char& ucSl ucSlot = 7; return true; } - if (us == 1008 || us == 1009 || us == 1010) // nitro + if (us == 1008 || us == 1009 || us == 1010) // nitro { ucSlot = 8; return true; } - if (us == 1087) // hydraulics + if (us == 1087) // hydraulics { ucSlot = 9; return true; } - if (us == 1086) // stereo + if (us == 1086) // stereo { ucSlot = 10; return true; diff --git a/Server/mods/deathmatch/logic/CWeaponStat.h b/Server/mods/deathmatch/logic/CWeaponStat.h index 281e19e4df0..d5e9e6b90c3 100644 --- a/Server/mods/deathmatch/logic/CWeaponStat.h +++ b/Server/mods/deathmatch/logic/CWeaponStat.h @@ -12,15 +12,15 @@ #include "CCommon.h" struct sWeaponStats { - eFireType m_eFireType; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) + eFireType m_eFireType; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) - FLOAT m_fTargetRange; // max targeting range - FLOAT m_fWeaponRange; // absolute gun range / default melee attack range - int m_modelId; // modelinfo id - int m_modelId2; // second modelinfo id + FLOAT m_fTargetRange; // max targeting range + FLOAT m_fWeaponRange; // absolute gun range / default melee attack range + int m_modelId; // modelinfo id + int m_modelId2; // second modelinfo id eWeaponSlot m_nWeaponSlot; - int m_nFlags; // flags defining characteristics + int m_nFlags; // flags defining characteristics // instead of storing pointers directly to anims, use anim association groups // NOTE: this is used for stealth kill anims for melee weapons @@ -29,39 +29,39 @@ struct sWeaponStats ////////////////////////////////// // Gun Data ///////////////////////////////// - short m_nAmmo; // ammo in one clip - short m_nDamage; // damage inflicted per hit - CVector m_vecFireOffset; // offset from weapon origin to projectile starting point + short m_nAmmo; // ammo in one clip + short m_nDamage; // damage inflicted per hit + CVector m_vecFireOffset; // offset from weapon origin to projectile starting point // skill settings - eWeaponSkill m_SkillLevel; // what's the skill level of this weapontype - int m_nReqStatLevel; // what stat level is required for this skill level - FLOAT m_fAccuracy; // modify accuracy of weapon - FLOAT m_fMoveSpeed; // how fast can move with weapon + eWeaponSkill m_SkillLevel; // what's the skill level of this weapontype + int m_nReqStatLevel; // what stat level is required for this skill level + FLOAT m_fAccuracy; // modify accuracy of weapon + FLOAT m_fMoveSpeed; // how fast can move with weapon // anim timings - FLOAT m_animLoopStart; // start of animation loop - FLOAT m_animLoopEnd; // end of animation loop - FLOAT m_animFireTime; // time in animation when weapon should be fired + FLOAT m_animLoopStart; // start of animation loop + FLOAT m_animLoopEnd; // end of animation loop + FLOAT m_animFireTime; // time in animation when weapon should be fired - FLOAT m_anim2LoopStart; // start of animation2 loop - FLOAT m_anim2LoopEnd; // end of animation2 loop - FLOAT m_anim2FireTime; // time in animation2 when weapon should be fired + FLOAT m_anim2LoopStart; // start of animation2 loop + FLOAT m_anim2LoopEnd; // end of animation2 loop + FLOAT m_anim2FireTime; // time in animation2 when weapon should be fired - FLOAT m_animBreakoutTime; // time after which player can break out of attack and run off + FLOAT m_animBreakoutTime; // time after which player can break out of attack and run off // projectile/area effect specific info - FLOAT m_fSpeed; // speed of projectile - FLOAT m_fRadius; // radius affected - FLOAT m_fLifeSpan; // time taken for shot to dissipate - FLOAT m_fSpread; // angle inside which shots are created + FLOAT m_fSpeed; // speed of projectile + FLOAT m_fRadius; // radius affected + FLOAT m_fLifeSpan; // time taken for shot to dissipate + FLOAT m_fSpread; // angle inside which shots are created - short m_nAimOffsetIndex; // index into array of aiming offsets + short m_nAimOffsetIndex; // index into array of aiming offsets ////////////////////////////////// // Melee Data ///////////////////////////////// - BYTE m_defaultCombo; // base combo for this melee weapon - BYTE m_nCombosAvailable; // how many further combos are available + BYTE m_defaultCombo; // base combo for this melee weapon + BYTE m_nCombosAvailable; // how many further combos are available }; class CWeaponStat { diff --git a/Server/mods/deathmatch/logic/CWeaponStatManager.cpp b/Server/mods/deathmatch/logic/CWeaponStatManager.cpp index dd42aae5828..0aa0aef874b 100644 --- a/Server/mods/deathmatch/logic/CWeaponStatManager.cpp +++ b/Server/mods/deathmatch/logic/CWeaponStatManager.cpp @@ -483,8 +483,8 @@ void CWeaponStatManager::Init() OriginalNormalWeaponData[33].default_combo = 4; OriginalNormalWeaponData[33].combos_available = 1; // 34 - Sniper - OriginalNormalWeaponData[34].weapon_range = 300.0f; // Default is actually 100; - OriginalNormalWeaponData[34].target_range = 250.0f; // Default is actually 50; + OriginalNormalWeaponData[34].weapon_range = 300.0f; // Default is actually 100; + OriginalNormalWeaponData[34].target_range = 250.0f; // Default is actually 50; OriginalNormalWeaponData[34].accuracy = 1.0f; OriginalNormalWeaponData[34].damage = 125; OriginalNormalWeaponData[34].life_span = 0.0f; @@ -1601,20 +1601,34 @@ eStats CWeaponStatManager::GetSkillStatIndex(eWeaponType weapon) { switch (weapon) { - case WEAPONTYPE_PISTOL: return STAT_PISTOL_SKILL; - case WEAPONTYPE_PISTOL_SILENCED: return STAT_SILENCED_PISTOL_SKILL; - case WEAPONTYPE_DESERT_EAGLE: return STAT_DESERT_EAGLE_SKILL; - case WEAPONTYPE_SHOTGUN: return STAT_SHOTGUN_SKILL; - case WEAPONTYPE_SAWNOFF_SHOTGUN: return STAT_SAWN_OFF_SHOTGUN_SKILL; - case WEAPONTYPE_SPAS12_SHOTGUN: return STAT_COMBAT_SHOTGUN_SKILL; - case WEAPONTYPE_MICRO_UZI: return STAT_MACHINE_PISTOL_SKILL; - case WEAPONTYPE_MP5: return STAT_SMG_SKILL; - case WEAPONTYPE_AK47: return STAT_AK_47_SKILL; - case WEAPONTYPE_M4: return STAT_M4_SKILL; - case WEAPONTYPE_TEC9: return STAT_MACHINE_PISTOL_SKILL; - case WEAPONTYPE_COUNTRYRIFLE: return STAT_RIFLE_SKILL; - case WEAPONTYPE_SNIPERRIFLE: return STAT_RIFLE_SKILL; - default: return static_cast(0); + case WEAPONTYPE_PISTOL: + return STAT_PISTOL_SKILL; + case WEAPONTYPE_PISTOL_SILENCED: + return STAT_SILENCED_PISTOL_SKILL; + case WEAPONTYPE_DESERT_EAGLE: + return STAT_DESERT_EAGLE_SKILL; + case WEAPONTYPE_SHOTGUN: + return STAT_SHOTGUN_SKILL; + case WEAPONTYPE_SAWNOFF_SHOTGUN: + return STAT_SAWN_OFF_SHOTGUN_SKILL; + case WEAPONTYPE_SPAS12_SHOTGUN: + return STAT_COMBAT_SHOTGUN_SKILL; + case WEAPONTYPE_MICRO_UZI: + return STAT_MACHINE_PISTOL_SKILL; + case WEAPONTYPE_MP5: + return STAT_SMG_SKILL; + case WEAPONTYPE_AK47: + return STAT_AK_47_SKILL; + case WEAPONTYPE_M4: + return STAT_M4_SKILL; + case WEAPONTYPE_TEC9: + return STAT_MACHINE_PISTOL_SKILL; + case WEAPONTYPE_COUNTRYRIFLE: + return STAT_RIFLE_SKILL; + case WEAPONTYPE_SNIPERRIFLE: + return STAT_RIFLE_SKILL; + default: + return static_cast(0); } } diff --git a/Server/mods/deathmatch/logic/CWeaponStatManager.h b/Server/mods/deathmatch/logic/CWeaponStatManager.h index 9aa23e696c7..61ef6db791b 100644 --- a/Server/mods/deathmatch/logic/CWeaponStatManager.h +++ b/Server/mods/deathmatch/logic/CWeaponStatManager.h @@ -14,24 +14,24 @@ #include // Straight out of CGameSA.h -#define CLASSSIZE_WeaponInfo 112 // ##SA## -#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE -#define NUM_WeaponInfosOtherSkill 11 -#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3*NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) +#define CLASSSIZE_WeaponInfo 112 // ##SA## +#define NUM_WeaponInfosStdSkill WEAPONTYPE_LAST_WEAPONTYPE +#define NUM_WeaponInfosOtherSkill 11 +#define NUM_WeaponInfosTotal (NUM_WeaponInfosStdSkill + (3 * NUM_WeaponInfosOtherSkill)) // std, (poor, pro, special) class CWeaponStat; struct sWeaponInfo { - eFireType fire_type; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) + eFireType fire_type; // type - instant hit (e.g. pistol), projectile (e.g. rocket launcher), area effect (e.g. flame thrower) - FLOAT target_range; // max targeting range - FLOAT weapon_range; // absolute gun range / default melee attack range - int model; // modelinfo id - int model2; // second modelinfo id + FLOAT target_range; // max targeting range + FLOAT weapon_range; // absolute gun range / default melee attack range + int model; // modelinfo id + int model2; // second modelinfo id eWeaponSlot weapon_slot; - int flags; // flags defining characteristics + int flags; // flags defining characteristics // instead of storing pointers directly to anims, use anim association groups // NOTE: this is used for stealth kill anims for melee weapons @@ -40,39 +40,39 @@ struct sWeaponInfo ////////////////////////////////// // Gun Data ///////////////////////////////// - short maximum_clip_ammo; // ammo in one clip - short damage; // damage inflicted per hit - CVector fire_offset; // offset from weapon origin to projectile starting point + short maximum_clip_ammo; // ammo in one clip + short damage; // damage inflicted per hit + CVector fire_offset; // offset from weapon origin to projectile starting point // skill settings - eWeaponSkill skill_level; // what's the skill level of this weapontype - int required_skill_level; // what stat level is required for this skill level - FLOAT accuracy; // modify accuracy of weapon - FLOAT move_speed; // how fast can move with weapon + eWeaponSkill skill_level; // what's the skill level of this weapontype + int required_skill_level; // what stat level is required for this skill level + FLOAT accuracy; // modify accuracy of weapon + FLOAT move_speed; // how fast can move with weapon // anim timings - FLOAT anim_loop_start; // start of animation loop - FLOAT anim_loop_stop; // end of animation loop - FLOAT anim_loop_bullet_fire; // time in animation when weapon should be fired + FLOAT anim_loop_start; // start of animation loop + FLOAT anim_loop_stop; // end of animation loop + FLOAT anim_loop_bullet_fire; // time in animation when weapon should be fired - FLOAT anim2_loop_start; // start of animation2 loop - FLOAT anim2_loop_stop; // end of animation2 loop - FLOAT anim2_loop_bullet_fire; // time in animation2 when weapon should be fired + FLOAT anim2_loop_start; // start of animation2 loop + FLOAT anim2_loop_stop; // end of animation2 loop + FLOAT anim2_loop_bullet_fire; // time in animation2 when weapon should be fired - FLOAT anim_breakout_time; // time after which player can break out of attack and run off + FLOAT anim_breakout_time; // time after which player can break out of attack and run off // projectile/area effect specific info - FLOAT firing_speed; // speed of projectile - FLOAT radius; // radius affected - FLOAT life_span; // time taken for shot to dissipate - FLOAT spread; // angle inside which shots are created + FLOAT firing_speed; // speed of projectile + FLOAT radius; // radius affected + FLOAT life_span; // time taken for shot to dissipate + FLOAT spread; // angle inside which shots are created - short aim_offset; // index into array of aiming offsets + short aim_offset; // index into array of aiming offsets ////////////////////////////////// // Melee Data ///////////////////////////////// - BYTE default_combo; // base combo for this melee weapon - BYTE combos_available; // how many further combos are available + BYTE default_combo; // base combo for this melee weapon + BYTE combos_available; // how many further combos are available }; #define WEAPON_STAT_MAX 112 @@ -91,7 +91,7 @@ class CWeaponStatManager // Static Methods static eStats GetSkillStatIndex(eWeaponType weapon); - static bool HasWeaponBulletSync(uint32_t weaponID) noexcept; + static bool HasWeaponBulletSync(uint32_t weaponID) noexcept; private: std::list m_OriginalWeaponData; diff --git a/Server/mods/deathmatch/logic/lua/CLuaArgument.cpp b/Server/mods/deathmatch/logic/lua/CLuaArgument.cpp index c245247d5d9..29bf2144b6e 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaArgument.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaArgument.cpp @@ -21,7 +21,7 @@ extern CGame* g_pGame; #ifndef VERIFY_ELEMENT -#define VERIFY_ELEMENT(element) (g_pGame->GetMapManager()->GetRootElement ()->IsMyChild(element,true)&&!element->IsBeingDeleted()) + #define VERIFY_ELEMENT(element) (g_pGame->GetMapManager()->GetRootElement()->IsMyChild(element, true) && !element->IsBeingDeleted()) #endif using namespace std; @@ -853,9 +853,9 @@ json_object* CLuaArgument::WriteToJSONObject(bool bSerialize, CFastHashMapGetScriptDebugging()->LogError(NULL, "Couldn't convert userdata argument to JSON, elements not allowed for this function."); - else if (!bSerialize) // eg toJSON() with invalid element + else if (!bSerialize) // eg toJSON() with invalid element g_pGame->GetScriptDebugging()->LogError( NULL, "Couldn't convert userdata argument to JSON, only valid resources can be included for this function."); else @@ -1038,7 +1038,7 @@ bool CLuaArgument::ReadFromJSONObject(json_object* object, std::vectorGetResourceManager()->GetResource(strString.c_str() + 3); if (resource) @@ -1070,7 +1070,7 @@ bool CLuaArgument::ReadFromJSONObject(json_object* object, std::vector(atol(strString.c_str() + 3)); if (pKnownTables && ulTableID < pKnownTables->size()) diff --git a/Server/mods/deathmatch/logic/lua/CLuaArgument.h b/Server/mods/deathmatch/logic/lua/CLuaArgument.h index 0414975ee51..2ecf4114d48 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaArgument.h +++ b/Server/mods/deathmatch/logic/lua/CLuaArgument.h @@ -15,7 +15,7 @@ extern "C" { - #include "lua.h" +#include "lua.h" } #include "../common/CBitStream.h" #include "json.h" @@ -23,7 +23,7 @@ extern "C" class CElement; class CLuaArguments; -#define LUA_TTABLEREF 9 +#define LUA_TTABLEREF 9 #define LUA_TSTRING_LONG 10 class CLuaArgument diff --git a/Server/mods/deathmatch/logic/lua/CLuaArguments.cpp b/Server/mods/deathmatch/logic/lua/CLuaArguments.cpp index 245838165ce..f737a00fa48 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaArguments.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaArguments.cpp @@ -22,13 +22,13 @@ #include "CAccessControlListGroup.h" #ifndef WIN32 -#include + #include #endif extern CGame* g_pGame; #ifndef VERIFY_ELEMENT -#define VERIFY_ELEMENT(element) (g_pGame->GetMapManager()->GetRootElement()->IsMyChild(element, true) && !element->IsBeingDeleted()) + #define VERIFY_ELEMENT(element) (g_pGame->GetMapManager()->GetRootElement()->IsMyChild(element, true) && !element->IsBeingDeleted()) #endif CLuaArguments::CLuaArguments(const CLuaArguments& Arguments, CFastHashMap* pKnownTables) @@ -120,10 +120,10 @@ void CLuaArguments::ReadTable(lua_State* luaVM, int iIndexBegin, CFastHashMap::const_iterator iter = m_Arguments.begin(); for (; iter != m_Arguments.end() && (iter + 1) != m_Arguments.end(); ++iter) { - (*iter)->Push(luaVM, pKnownTables); // index + (*iter)->Push(luaVM, pKnownTables); // index ++iter; - (*iter)->Push(luaVM, pKnownTables); // value + (*iter)->Push(luaVM, pKnownTables); // value lua_settable(luaVM, -3); } @@ -231,7 +231,7 @@ bool CLuaArguments::Call(CLuaMain* pLuaMain, const CLuaFunctionRef& iLuaFunction while (lua_gettop(luaVM) - luaStackPointer > 0) lua_pop(luaVM, 1); - return false; // the function call failed + return false; // the function call failed } else { @@ -295,7 +295,7 @@ bool CLuaArguments::CallGlobal(CLuaMain* pLuaMain, const char* szFunction, CLuaA while (lua_gettop(luaVM) - luaStackPointer > 0) lua_pop(luaVM, 1); - return false; // the function call failed + return false; // the function call failed } else { @@ -351,7 +351,7 @@ CLuaArgument* CLuaArguments::PushNumber(double dNumber) CLuaArgument* CLuaArguments::PushArgument(const CLuaArgument& argument) { - CLuaArgument* pArgument = new CLuaArgument(argument); // create a copy + CLuaArgument* pArgument = new CLuaArgument(argument); // create a copy m_Arguments.push_back(pArgument); return pArgument; } @@ -596,7 +596,7 @@ bool CLuaArguments::WriteToJSONString(std::string& strJSON, bool bSerialize, int if (my_array) { strJSON = json_object_to_json_string_ext(my_array, flags); - json_object_put(my_array); // dereference - causes a crash, is actually commented out in the example too + json_object_put(my_array); // dereference - causes a crash, is actually commented out in the example too return true; } return false; @@ -634,7 +634,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap pKnownTables->insert({this, pKnownTables->size()}); bool bIsArray = true; - std::vector> vecSortedArguments; // lua arrays are not necessarily sorted + std::vector> vecSortedArguments; // lua arrays are not necessarily sorted std::vector::const_iterator iter = m_Arguments.begin(); for (; iter != m_Arguments.end(); iter += 2) { @@ -653,7 +653,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap } } - if (bIsArray && !vecSortedArguments.empty()) // the table could possibly be an array + if (bIsArray && !vecSortedArguments.empty()) // the table could possibly be an array { // sort the table based on the keys (already handled correctly by std::pair) std::sort(vecSortedArguments.begin(), vecSortedArguments.end()); @@ -663,7 +663,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap auto const iFirstKey = vecSortedArguments.front().first; auto const iLastKey = vecSortedArguments.back().first; - auto const iFirstArrayPos = 1U; // lua arrays are 1 based + auto const iFirstArrayPos = 1U; // lua arrays are 1 based auto const iLastArrayPos = static_cast(vecSortedArguments.size()); if (iFirstKey != iFirstArrayPos || iLastKey != iLastArrayPos) @@ -672,7 +672,7 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap } } - if (bIsArray) // the table is definitely an array + if (bIsArray) // the table is definitely an array { json_object* my_array = json_object_new_array(); for (auto const& [iKey, pArgument] : vecSortedArguments) @@ -700,11 +700,11 @@ json_object* CLuaArguments::WriteTableToJSONObject(bool bSerialize, CFastHashMap char szKey[255]; szKey[0] = '\0'; CLuaArgument* pArgument = *iter; - if (!pArgument->WriteToString(szKey, 255)) // index + if (!pArgument->WriteToString(szKey, 255)) // index break; ++iter; pArgument = *iter; - json_object* object = pArgument->WriteToJSONObject(bSerialize, pKnownTables); // value + json_object* object = pArgument->WriteToJSONObject(bSerialize, pKnownTables); // value if (object) { @@ -748,11 +748,11 @@ bool CLuaArguments::ReadFromJSONString(const char* szJSON) json_object* arrayObject = json_object_array_get_idx(object, i); CLuaArgument* pArgument = new CLuaArgument(); bSuccess = pArgument->ReadFromJSONObject(arrayObject, &knownTables); - m_Arguments.push_back(pArgument); // then the value + m_Arguments.push_back(pArgument); // then the value if (!bSuccess) break; } - json_object_put(object); // dereference + json_object_put(object); // dereference return bSuccess; } else if (json_object_get_type(object) == json_type_object) @@ -760,12 +760,12 @@ bool CLuaArguments::ReadFromJSONString(const char* szJSON) std::vector knownTables; CLuaArgument* pArgument = new CLuaArgument(); bool bSuccess = pArgument->ReadFromJSONObject(object, &knownTables); - m_Arguments.push_back(pArgument); // value + m_Arguments.push_back(pArgument); // value json_object_put(object); return bSuccess; } - json_object_put(object); // dereference + json_object_put(object); // dereference } // else // g_pGame->GetScriptDebugging()->LogError ( "Could not parse invalid JSON object."); @@ -794,9 +794,9 @@ bool CLuaArguments::ReadFromJSONObject(json_object* object, std::vectorReadString(key); - m_Arguments.push_back(pArgument); // push the key first + m_Arguments.push_back(pArgument); // push the key first pArgument = new CLuaArgument(); - bSuccess = pArgument->ReadFromJSONObject(val, pKnownTables); // then the value + bSuccess = pArgument->ReadFromJSONObject(val, pKnownTables); // then the value m_Arguments.push_back(pArgument); if (!bSuccess) break; @@ -832,12 +832,12 @@ bool CLuaArguments::ReadFromJSONArray(json_object* object, std::vectorReadNumber(i + 1); // push the key + pArgument->ReadNumber(i + 1); // push the key m_Arguments.push_back(pArgument); pArgument = new CLuaArgument(); bSuccess = pArgument->ReadFromJSONObject(arrayObject, pKnownTables); - m_Arguments.push_back(pArgument); // then the valoue + m_Arguments.push_back(pArgument); // then the valoue if (!bSuccess) break; } diff --git a/Server/mods/deathmatch/logic/lua/CLuaArguments.h b/Server/mods/deathmatch/logic/lua/CLuaArguments.h index 9550235fcd7..3c550799d26 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaArguments.h +++ b/Server/mods/deathmatch/logic/lua/CLuaArguments.h @@ -13,7 +13,7 @@ extern "C" { - #include "lua.h" +#include "lua.h" } #include "CLuaArgument.h" diff --git a/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp b/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp index a46958aa479..ffe4133f790 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.cpp @@ -319,7 +319,7 @@ CLuaTimer* UserDataCast(CLuaTimer* ptr, lua_State* luaState) CLuaManager* luaManager = g_pGame->GetLuaManager(); if (!luaManager) return nullptr; - + return luaManager->FindTimerGlobally(reinterpret_cast(ptr)); } @@ -496,13 +496,13 @@ CClient* UserDataCast(CClient* ptr, lua_State* luaState) // SString GetUserDataClassName(void* ptr, lua_State* luaVM, bool bFindElementType) { - if (CElement* pVar = UserDataCast((CElement*)ptr, luaVM)) // Try element + if (CElement* pVar = UserDataCast((CElement*)ptr, luaVM)) // Try element return bFindElementType ? pVar->GetTypeName() : GetClassTypeName(pVar); - if (auto* pVar = UserDataCast(static_cast(ptr), luaVM)) // Try resource + if (auto* pVar = UserDataCast(static_cast(ptr), luaVM)) // Try resource return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CXMLNode*)ptr, luaVM)) // Try xml node + if (auto* pVar = UserDataCast((CXMLNode*)ptr, luaVM)) // Try xml node return GetClassTypeName(pVar); - if (auto* pVar = UserDataCast((CLuaTimer*)ptr, luaVM)) // Try timer + if (auto* pVar = UserDataCast((CLuaTimer*)ptr, luaVM)) // Try timer return GetClassTypeName(pVar); if (auto* pVar = UserDataCast((CAccount*)ptr, luaVM)) return GetClassTypeName(pVar); diff --git a/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.h b/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.h index d9dcb23ee5c..1d5bc7feee7 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.h +++ b/Server/mods/deathmatch/logic/lua/CLuaFunctionParseHelpers.h @@ -56,8 +56,8 @@ enum eHudComponent HUD_WANTED, HUD_CROSSHAIR, HUD_ALL, - HUD_VITAL_STATS, // Unused on server, but used on client side - HUD_HELP_TEXT, // Unused on server, but used on client side + HUD_VITAL_STATS, // Unused on server, but used on client side + HUD_HELP_TEXT, // Unused on server, but used on client side HUD_RADAR_MAP, HUD_RADAR_BLIPS, HUD_RADAR_ALTIMETER, diff --git a/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp b/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp index 935d0275854..39902037b31 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.cpp @@ -15,7 +15,7 @@ #include "CGame.h" #ifdef WIN32 - #pragma warning( disable : 4355 ) // warning C4355: 'this' : used in base member initializer list + #pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list #endif struct lua_State; diff --git a/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.h b/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.h index 79e9d2a41f4..b7da904de41 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.h +++ b/Server/mods/deathmatch/logic/lua/CLuaFunctionRef.h @@ -11,9 +11,9 @@ #pragma once -#define LUA_REFNIL (-1) -#define VERIFY_FUNCTION(func) ( (func).ToInt () != LUA_REFNIL ) -#define IS_REFNIL(func) ( (func).ToInt () == LUA_REFNIL ) +#define LUA_REFNIL (-1) +#define VERIFY_FUNCTION(func) ((func).ToInt() != LUA_REFNIL) +#define IS_REFNIL(func) ((func).ToInt() == LUA_REFNIL) struct lua_State; diff --git a/Server/mods/deathmatch/logic/lua/CLuaMain.cpp b/Server/mods/deathmatch/logic/lua/CLuaMain.cpp index 9d3dd0ac5c8..b3c093f27e0 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaMain.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaMain.cpp @@ -53,7 +53,7 @@ static CLuaManager* m_pLuaManager; SString CLuaMain::ms_strExpectedUndumpHash; #define HOOK_INSTRUCTION_COUNT 1000000 -#define HOOK_MAXIMUM_TIME 5000 +#define HOOK_MAXIMUM_TIME 5000 extern CGame* g_pGame; extern CNetServer* g_pRealNetServer; @@ -172,7 +172,7 @@ void CLuaMain::InitClasses(lua_State* luaVM) if (!m_bEnableOOP) return; - CLuaElementDefs ::AddClass(luaVM); // keep this at the top because inheritance + CLuaElementDefs ::AddClass(luaVM); // keep this at the top because inheritance CLuaAccountDefs ::AddClass(luaVM); CLuaACLDefs ::AddClass(luaVM); CLuaBanDefs ::AddClass(luaVM); @@ -307,7 +307,7 @@ bool CLuaMain::LoadScriptFromBuffer(const char* cpInBuffer, unsigned int uiInSiz { std::string strBuffer = std::string(cpBuffer, uiSize); #ifdef WIN32 - std::setlocale(LC_CTYPE, ""); // Temporarilly use locales to read the script + std::setlocale(LC_CTYPE, ""); // Temporarilly use locales to read the script strUTFScript = UTF16ToMbUTF8(ANSIToUTF16(strBuffer)); std::setlocale(LC_CTYPE, "C"); #else @@ -604,14 +604,14 @@ const SString& CLuaMain::GetFunctionTag(int iLuaFunction) strText = SString("@func_%d NULL", iLuaFunction); } - #ifdef CHECK_FUNCTION_TAG +#ifdef CHECK_FUNCTION_TAG if (pTag) { // Check tag remains unchanged assert(strText == *pTag); return *pTag; } - #endif +#endif MapSet(m_FunctionTagMap, iLuaFunction, strText); pTag = MapFind(m_FunctionTagMap, iLuaFunction); @@ -629,7 +629,7 @@ const SString& CLuaMain::GetFunctionTag(int iLuaFunction) int CLuaMain::PCall(lua_State* L, int nargs, int nresults, int errfunc) { if (m_uiPCallDepth++ == 0) - m_WarningTimer.Reset(); // Only restart timer if initial call + m_WarningTimer.Reset(); // Only restart timer if initial call g_pGame->GetScriptDebugging()->PushLuaMain(this); int iret = lua_pcall(L, nargs, nresults, errfunc); diff --git a/Server/mods/deathmatch/logic/lua/CLuaMain.h b/Server/mods/deathmatch/logic/lua/CLuaMain.h index c78c2324956..6e64c4088d9 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaMain.h +++ b/Server/mods/deathmatch/logic/lua/CLuaMain.h @@ -35,7 +35,7 @@ struct CRefInfo int iFunction; }; -class CLuaMain //: public CClient +class CLuaMain //: public CClient { public: ZERO_ON_NEW @@ -140,7 +140,7 @@ class CLuaMain //: public CClient bool m_bEnableOOP; - bool m_bBeingDeleted; // prevent it being deleted twice + bool m_bBeingDeleted; // prevent it being deleted twice CElapsedTime m_FunctionEnterTimer; CElapsedTimeApprox m_WarningTimer; diff --git a/Server/mods/deathmatch/logic/lua/CLuaManager.cpp b/Server/mods/deathmatch/logic/lua/CLuaManager.cpp index a9c2941bfe5..abae51389ff 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaManager.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaManager.cpp @@ -167,7 +167,7 @@ CLuaMain* CLuaManager::GetVirtualMachine(lua_State* luaVM) { if (luaVM == (*iter)->GetVirtualMachine()) { - dassert(0); // Why not in map? + dassert(0); // Why not in map? return *iter; } } @@ -191,24 +191,24 @@ CLuaTimer* CLuaManager::FindTimerGlobally(unsigned long scriptID) const CLuaTimer* luaTimer = static_cast(CIdArray::FindEntry(scriptID, EIdClass::TIMER)); if (!luaTimer) return nullptr; - + // Verify timer exists in any resource manager (ensures it's still valid) for (std::list::const_iterator iter = m_virtualMachines.begin(); iter != m_virtualMachines.end(); ++iter) { CLuaMain* luaMain = *iter; if (!luaMain) continue; - + CLuaTimerManager* timerManager = luaMain->GetTimerManager(); if (!timerManager) continue; - + if (timerManager->GetTimerFromScriptID(scriptID) == luaTimer) { return luaTimer; } } - + // Timer exists in global ID array but not in any resource manager // This indicates the timer has been cleaned up return nullptr; diff --git a/Server/mods/deathmatch/logic/lua/CLuaModule.cpp b/Server/mods/deathmatch/logic/lua/CLuaModule.cpp index c52f8512160..6d7158c78ba 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaModule.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaModule.cpp @@ -95,20 +95,20 @@ int CLuaModule::_LoadModule() CLogger::LogPrintf("MODULE: File not found - %s\n", *strExpectedPathFilename); } else - #ifdef WIN_x64 +#ifdef WIN_x64 if (IsModule32Bit(strExpectedPathFilename)) { CLogger::LogPrintf("MODULE: File not 64 bit - %s\n", *strExpectedPathFilename); } else - #endif - #ifdef WIN_x86 +#endif +#ifdef WIN_x86 if (!IsModule32Bit(strExpectedPathFilename)) { CLogger::LogPrintf("MODULE: File not 32 bit - %s\n", *strExpectedPathFilename); } else - #endif +#endif { CLogger::LogPrintf("MODULE: Unable to load %s (%s)\n", *strExpectedPathFilename, *strError); } @@ -285,7 +285,7 @@ bool CLuaModule::RegisterFunction(lua_State* luaVM, const char* szFunctionName, CLuaCFunctions::AddFunction(szFunctionName, Func); lua_register(luaVM, szFunctionName, Func); if (!_DoesFunctionExist(szFunctionName)) - { // Check or it adds for each resource + { // Check or it adds for each resource m_Functions.push_back(szFunctionName); } } diff --git a/Server/mods/deathmatch/logic/lua/CLuaModule.h b/Server/mods/deathmatch/logic/lua/CLuaModule.h index 38558c370ec..fcac556c594 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaModule.h +++ b/Server/mods/deathmatch/logic/lua/CLuaModule.h @@ -59,7 +59,7 @@ class CLuaModule : public ILuaModuleManager10 void DebugPrintf(lua_State* luaVM, const char* szFormat, ...); bool RegisterFunction(lua_State* luaVM, const char* szFunctionName, lua_CFunction Func); bool GetResourceName(lua_State* luaVM, - std::string& strName); // This function might not work if module and MTA were compiled with different compiler versions + std::string& strName); // This function might not work if module and MTA were compiled with different compiler versions CChecksum GetResourceMetaChecksum(lua_State* luaVM); CChecksum GetResourceFileChecksum(lua_State* luaVM, const char* szFile); diff --git a/Server/mods/deathmatch/logic/lua/CLuaModuleManager.cpp b/Server/mods/deathmatch/logic/lua/CLuaModuleManager.cpp index 9b5f52bd45b..766747fc8e8 100644 --- a/Server/mods/deathmatch/logic/lua/CLuaModuleManager.cpp +++ b/Server/mods/deathmatch/logic/lua/CLuaModuleManager.cpp @@ -55,7 +55,7 @@ void CLuaModuleManager::DoPulse() } int CLuaModuleManager::LoadModule(const char* szShortFileName, const char* szFileName, bool bLateLoad) -{ // 0 = Success, 1 = Can't find file, 2 = Can't find initialise function, 3 = can't find dopulse function, +{ // 0 = Success, 1 = Can't find file, 2 = Can't find initialise function, 3 = can't find dopulse function, // 4 = can't find shutdownmodule function, 5 = can't find register function, 6 = can't find resourcestopping function // 7 = can't find resourcestopped function, 8 = resource already loaded @@ -112,7 +112,7 @@ int CLuaModuleManager::ReloadModule(const char* szShortFileName, const char* szF } int CLuaModuleManager::UnloadModule(const char* szShortFileName) -{ // 0 = Success, 9 = Can't find module by name +{ // 0 = Success, 9 = Can't find module by name list::iterator iter = m_Modules.begin(); for (; iter != m_Modules.end(); ++iter) { diff --git a/Server/mods/deathmatch/logic/lua/LuaCommon.cpp b/Server/mods/deathmatch/logic/lua/LuaCommon.cpp index bcbe670fe22..ba4a131e885 100644 --- a/Server/mods/deathmatch/logic/lua/LuaCommon.cpp +++ b/Server/mods/deathmatch/logic/lua/LuaCommon.cpp @@ -250,7 +250,7 @@ void lua_pushobject(lua_State* luaVM, const char* szClass, void* pObject, bool b // Assign the class metatable lua_getclass(luaVM, szClass); - lua_setmetatable(luaVM, -2); // element + lua_setmetatable(luaVM, -2); // element } void lua_pushvector(lua_State* luaVM, const CVector4D& vector) @@ -342,30 +342,30 @@ void lua_newclass(lua_State* luaVM) void lua_getclass(lua_State* luaVM, const char* szName) { - lua_pushstring(luaVM, "mt"); // "mt" - lua_rawget(luaVM, LUA_REGISTRYINDEX); // mt + lua_pushstring(luaVM, "mt"); // "mt" + lua_rawget(luaVM, LUA_REGISTRYINDEX); // mt assert(lua_istable(luaVM, -1)); - lua_pushstring(luaVM, szName); // mt, class name - lua_rawget(luaVM, -2); // mt, class + lua_pushstring(luaVM, szName); // mt, class name + lua_rawget(luaVM, -2); // mt, class - lua_remove(luaVM, -2); // class + lua_remove(luaVM, -2); // class } void lua_registerclass(lua_State* luaVM, const char* szName, const char* szParent, bool bRegisterWithEnvironment) { if (szParent != NULL) { - lua_pushstring(luaVM, "mt"); // class table, "mt" - lua_rawget(luaVM, LUA_REGISTRYINDEX); // class table, mt table - lua_getfield(luaVM, -1, szParent); // class table, mt table, parent table + lua_pushstring(luaVM, "mt"); // class table, "mt" + lua_rawget(luaVM, LUA_REGISTRYINDEX); // class table, mt table + lua_getfield(luaVM, -1, szParent); // class table, mt table, parent table assert(lua_istable(luaVM, -1)); - lua_setfield(luaVM, -3, "__parent"); // class table, mt table + lua_setfield(luaVM, -3, "__parent"); // class table, mt table - lua_pop(luaVM, 1); // class table + lua_pop(luaVM, 1); // class table } lua_pushstring(luaVM, "mt"); diff --git a/Server/mods/deathmatch/logic/lua/LuaCommon.h b/Server/mods/deathmatch/logic/lua/LuaCommon.h index a62a0205161..1b7389519d8 100644 --- a/Server/mods/deathmatch/logic/lua/LuaCommon.h +++ b/Server/mods/deathmatch/logic/lua/LuaCommon.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "CLuaFunctionRef.h" diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaACLDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaACLDefs.cpp index 35a578173b2..0307318c578 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaACLDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaACLDefs.cpp @@ -1055,7 +1055,7 @@ int CLuaACLDefs::OOP_isObjectInACLGroup(lua_State* luaVM) std::vector CLuaACLDefs::aclObjectGetGroups(std::string strObject) { CAccessControlListGroupObject::EObjectType objectType; - const char* szObjectAfterDot = strObject.c_str(); + const char* szObjectAfterDot = strObject.c_str(); if (StringBeginsWith(szObjectAfterDot, "resource.")) { szObjectAfterDot += 9; @@ -1071,8 +1071,7 @@ std::vector CLuaACLDefs::aclObjectGetGroups(std::strin std::vector groups; - for (auto iter = m_pACLManager->Groups_Begin(); - iter != m_pACLManager->Groups_End(); ++iter) + for (auto iter = m_pACLManager->Groups_Begin(); iter != m_pACLManager->Groups_End(); ++iter) { if (!(*iter)->FindObjectMatch(szObjectAfterDot, objectType)) continue; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaAccountDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaAccountDefs.cpp index 00af2884165..cdeb86ae181 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaAccountDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaAccountDefs.cpp @@ -520,7 +520,6 @@ bool CLuaAccountDefs::SetAccountSerial(CAccount* account, std::string serial) no return CStaticFunctionDefinitions::SetAccountSerial(account, serial); } - int CLuaAccountDefs::SetAccountName(lua_State* luaVM) { // bool setAccountPassword ( account theAccount, string name[, bool allowCaseVariations = false ] ) diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp index 6b3bd66de02..2dbdd777eda 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.cpp @@ -17,14 +17,18 @@ static constexpr std::uint8_t MAX_BLIP_SIZE = 25; -std::variant CLuaBlipDefs::CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance, std::optional visibleTo) +std::variant CLuaBlipDefs::CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional ordering, + std::optional visibleDistance, std::optional visibleTo) { if (icon.has_value() && !CBlipManager::IsValidIcon(icon.value())) throw std::invalid_argument("Invalid icon"); if (size.has_value() && size.value() > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", + MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } @@ -41,14 +45,19 @@ std::variant CLuaBlipDefs::CreateBlip(lua_State* luaVM, const CVec return radarMarker; } -std::variant CLuaBlipDefs::CreateBlipAttachedTo(lua_State* luaVM, CElement* entity, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance, std::optional visibleTo) +std::variant CLuaBlipDefs::CreateBlipAttachedTo(lua_State* luaVM, CElement* entity, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, + std::optional ordering, std::optional visibleDistance, + std::optional visibleTo) { if (icon.has_value() && !CBlipManager::IsValidIcon(icon.value())) throw std::invalid_argument("Invalid icon"); if (size.has_value() && size.value() > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", + MAX_BLIP_SIZE, size.value(), MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } @@ -104,7 +113,8 @@ bool CLuaBlipDefs::SetBlipSize(lua_State* luaVM, CElement* radarMarker, std::uin { if (size > MAX_BLIP_SIZE) { - m_pScriptDebugging->LogWarning(luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size, MAX_BLIP_SIZE)); + m_pScriptDebugging->LogWarning( + luaVM, SString("Blip size beyond %i is no longer supported (got %i). It will be clamped between 0 and %i.", MAX_BLIP_SIZE, size, MAX_BLIP_SIZE)); size = MAX_BLIP_SIZE; } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h index 298486ef814..3d06f40f785 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaBlipDefs.h @@ -20,15 +20,21 @@ class CLuaBlipDefs : public CLuaDefs private: // Create functions - static std::variant CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance, std::optional visibleTo); - static std::variant CreateBlipAttachedTo(lua_State* luaVM, CElement* entity, std::optional icon, std::optional size, std::optional r, std::optional g, std::optional b, std::optional a, std::optional ordering, std::optional visibleDistance, std::optional visibleTo); + static std::variant CreateBlip(lua_State* luaVM, const CVector vecPosition, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional ordering, + std::optional visibleDistance, std::optional visibleTo); + static std::variant CreateBlipAttachedTo(lua_State* luaVM, CElement* entity, std::optional icon, + std::optional size, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional ordering, + std::optional visibleDistance, std::optional visibleTo); // Get functions - static auto GetBlipIcon(CBlip* radarMarker) noexcept; - static auto GetBlipSize(CBlip* radarMarker) noexcept; - static auto GetBlipColor(CBlip* radarMarker) noexcept; - static auto GetBlipOrdering(CBlip* radarMarker) noexcept; - static auto GetBlipVisibleDistance(CBlip* radarMarker) noexcept; + static auto GetBlipIcon(CBlip* radarMarker) noexcept; + static auto GetBlipSize(CBlip* radarMarker) noexcept; + static auto GetBlipColor(CBlip* radarMarker) noexcept; + static auto GetBlipOrdering(CBlip* radarMarker) noexcept; + static auto GetBlipVisibleDistance(CBlip* radarMarker) noexcept; // Set functions static bool SetBlipIcon(CElement* radarMarker, std::uint8_t icon); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp index 779d31b08c6..192c9421720 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.cpp @@ -36,7 +36,7 @@ void CLuaBuildingDefs::AddClass(lua_State* luaVM) } CBuilding* CLuaBuildingDefs::CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, - std::optional interior) + std::optional interior) { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h index e85353dec27..31520835aca 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaBuildingDefs.h @@ -19,5 +19,5 @@ class CLuaBuildingDefs : public CLuaDefs static void AddClass(lua_State* luaVM); static CBuilding* CreateBuilding(lua_State* const luaVM, std::uint16_t modelId, CVector pos, std::optional rot, - std::optional interior); + std::optional interior); }; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaCameraDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaCameraDefs.h index 0a61c97f583..e120884d4ed 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaCameraDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaCameraDefs.h @@ -27,4 +27,4 @@ class CLuaCameraDefs : public CLuaDefs LUA_DECLARE(setCameraTarget); LUA_DECLARE(setCameraInterior); LUA_DECLARE(fadeCamera); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp index 4b10ee3baa1..321907c87c0 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.cpp @@ -14,75 +14,75 @@ int CLuaClassDefs::Index(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, mt // First we look for a function - lua_pushstring(luaVM, "__class"); // ud, k, mt, "__class" - lua_rawget(luaVM, -2); // ud, k, mt, __class table + lua_pushstring(luaVM, "__class"); // ud, k, mt, "__class" + lua_rawget(luaVM, -2); // ud, k, mt, __class table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, mt, __class table, k - lua_rawget(luaVM, -2); // ud, k, mt, __class table, function - lua_remove(luaVM, -2); // ud, k, mt, function + lua_pushvalue(luaVM, 2); // ud, k, mt, __class table, k + lua_rawget(luaVM, -2); // ud, k, mt, __class table, function + lua_remove(luaVM, -2); // ud, k, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the function, clean up and return - lua_remove(luaVM, -2); // ud, k, function + { // Found the function, clean up and return + lua_remove(luaVM, -2); // ud, k, function return 1; } - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt // Function not found, look for property - lua_pushstring(luaVM, "__get"); // ud, k, mt, "__get" - lua_rawget(luaVM, -2); // ud, k, mt, __get table + lua_pushstring(luaVM, "__get"); // ud, k, mt, "__get" + lua_rawget(luaVM, -2); // ud, k, mt, __get table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, mt, __get table, k - lua_rawget(luaVM, -2); // ud, k, mt, __get table, function - lua_remove(luaVM, -2); // ud, k, mt, function + lua_pushvalue(luaVM, 2); // ud, k, mt, __get table, k + lua_rawget(luaVM, -2); // ud, k, mt, __get table, function + lua_remove(luaVM, -2); // ud, k, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property, - lua_remove(luaVM, -2); // ud, k, function + { // Found the property, + lua_remove(luaVM, -2); // ud, k, function - lua_pushvalue(luaVM, 1); // ud, k, function, ud - lua_call(luaVM, 1, 1); // ud, k, result + lua_pushvalue(luaVM, 1); // ud, k, function, ud + lua_call(luaVM, 1, 1); // ud, k, result return 1; } - lua_pop(luaVM, 1); // ud, k, mt + lua_pop(luaVM, 1); // ud, k, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__index"); // ud, k, mt, __parent table, "__index" - lua_rawget(luaVM, -2); // ud, k, mt, __parent table, function + lua_pushstring(luaVM, "__index"); // ud, k, mt, __parent table, "__index" + lua_rawget(luaVM, -2); // ud, k, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 1); // ud, k, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, mt, __parent table, function, ud, k - lua_call(luaVM, 2, 1); // ud, k, mt, __parent table, result + lua_call(luaVM, 2, 1); // ud, k, mt, __parent table, result - lua_replace(luaVM, -3); // ud, k, result, __parent table - lua_pop(luaVM, 1); // ud, k, result + lua_replace(luaVM, -3); // ud, k, result, __parent table + lua_pop(luaVM, 1); // ud, k, result return 1; } - lua_pop(luaVM, 1); // ud, k, mt, __parent table + lua_pop(luaVM, 1); // ud, k, mt, __parent table } - lua_pop(luaVM, 2); // ud, k + lua_pop(luaVM, 2); // ud, k lua_pushnil(luaVM); return 1; @@ -90,113 +90,113 @@ int CLuaClassDefs::Index(lua_State* luaVM) int CLuaClassDefs::NewIndex(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt - lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table + lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function - lua_remove(luaVM, -2); // ud, k, v, mt, function + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function + lua_remove(luaVM, -2); // ud, k, v, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property - lua_pushvalue(luaVM, 1); // ud, k, v, mt, function, ud - lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, ud, v + { // Found the property + lua_pushvalue(luaVM, 1); // ud, k, v, mt, function, ud + lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, ud, v - lua_call(luaVM, 2, 0); // ud, k, v, mt + lua_call(luaVM, 2, 0); // ud, k, v, mt - lua_pop(luaVM, 1); // ud, k, v + lua_pop(luaVM, 1); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function + lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k - lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v + lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v - lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table + lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt, __parent table + lua_pop(luaVM, 1); // ud, k, v, mt, __parent table } - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } int CLuaClassDefs::StaticNewIndex(lua_State* luaVM) { - lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt + lua_pushvalue(luaVM, lua_upvalueindex(1)); // ud, k, v, mt - lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table + lua_pushstring(luaVM, "__set"); // ud, k, v, mt, "__set" + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table if (!lua_istable(luaVM, -1)) { - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt goto searchparent; } - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k - lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function - lua_remove(luaVM, -2); // ud, k, v, mt, function + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __set table, k + lua_rawget(luaVM, -2); // ud, k, v, mt, __set table, function + lua_remove(luaVM, -2); // ud, k, v, mt, function if (lua_isfunction(luaVM, -1)) - { // Found the property - lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, v + { // Found the property + lua_pushvalue(luaVM, 3); // ud, k, v, mt, function, v - lua_call(luaVM, 1, 0); // ud, k, v, mt + lua_call(luaVM, 1, 0); // ud, k, v, mt - lua_pop(luaVM, 1); // ud, k, v + lua_pop(luaVM, 1); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt + lua_pop(luaVM, 1); // ud, k, v, mt searchparent: - lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table + lua_pushstring(luaVM, "__parent"); // ud, k, v, mt, "__parent" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table if (lua_istable(luaVM, -1)) { - lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" - lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function + lua_pushstring(luaVM, "__newindex"); // ud, k, v, mt, __parent table, "__newindex" + lua_rawget(luaVM, -2); // ud, k, v, mt, __parent table, function if (lua_isfunction(luaVM, -1)) { - lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud - lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k - lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v + lua_pushvalue(luaVM, 1); // ud, k, v, mt, __parent table, function, ud + lua_pushvalue(luaVM, 2); // ud, k, v, mt, __parent table, function, ud, k + lua_pushvalue(luaVM, 3); // ud, k, v, mt, __parent table, function, ud, k, v - lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table + lua_call(luaVM, 3, 0); // ud, k, v, mt, __parent table - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } - lua_pop(luaVM, 1); // ud, k, v, mt, __parent table + lua_pop(luaVM, 1); // ud, k, v, mt, __parent table } - lua_pop(luaVM, 2); // ud, k, v + lua_pop(luaVM, 2); // ud, k, v return 0; } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.h index 248958b11fd..798ae7675e8 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaClassDefs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "CLuaDefs.h" diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaColShapeDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaColShapeDefs.h index cf57a783345..4fe67df1938 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaColShapeDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaColShapeDefs.h @@ -42,5 +42,5 @@ class CLuaColShapeDefs : public CLuaDefs LUA_DECLARE(GetColShapeType); static CLuaMultiReturn GetColPolygonHeight(CColShape* shape); - static bool SetColPolygonHeight(CColShape* shape, std::variant floor, std::variant ceil); + static bool SetColPolygonHeight(CColShape* shape, std::variant floor, std::variant ceil); }; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaCompatibilityDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaCompatibilityDefs.cpp index 9737d64068d..11a5e3525fe 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaCompatibilityDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaCompatibilityDefs.cpp @@ -85,7 +85,8 @@ void CLuaCompatibilityDefs::LoadFunctions() // Old Discord implementation (see #2499) {"setPlayerDiscordJoinParams", - [](lua_State* luaVM) -> int { + [](lua_State* luaVM) -> int + { lua_pushboolean(luaVM, false); return 1; }}, diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.cpp index ce4a90f50b8..9c021326c2a 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.cpp @@ -526,7 +526,7 @@ void PushRegistryResultTable(lua_State* luaVM, const CRegistryResultData* Result // Push the column name lua_pushlstring(luaVM, Result->ColNames[j].c_str(), Result->ColNames[j].size()); - switch (cell.nType) // push the value with the right type + switch (cell.nType) // push the value with the right type { case SQLITE_INTEGER: lua_pushnumber(luaVM, static_cast(cell.nVal)); @@ -609,15 +609,15 @@ int CLuaDatabaseDefs::DbPoll(lua_State* luaVM) lua_pushnumber(luaVM, i + 1); lua_newtable(luaVM); { - lua_pushnumber(luaVM, 1); // [1] - table of result rows + lua_pushnumber(luaVM, 1); // [1] - table of result rows PushRegistryResultTable(luaVM, Result); lua_settable(luaVM, -3); - lua_pushnumber(luaVM, 2); // [2] - NumAffectedRows + lua_pushnumber(luaVM, 2); // [2] - NumAffectedRows lua_pushnumber(luaVM, Result->uiNumAffectedRows); lua_settable(luaVM, -3); - lua_pushnumber(luaVM, 3); // [3] - LastInsertId + lua_pushnumber(luaVM, 3); // [3] - LastInsertId lua_pushnumber(luaVM, static_cast(Result->ullLastInsertId)); lua_settable(luaVM, -3); } @@ -687,10 +687,10 @@ int CLuaDatabaseDefs::ExecuteSQLQuery(lua_State* luaVM) { const CRegistryResultRow& row = *iter; // for ( int i = 0; i < Result.nRows; i++ ) { - lua_newtable(luaVM); // new table - lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) - lua_pushvalue(luaVM, -2); // value - lua_settable(luaVM, -4); // refer to the top level table + lua_newtable(luaVM); // new table + lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) + lua_pushvalue(luaVM, -2); // value + lua_settable(luaVM, -4); // refer to the top level table for (int j = 0; j < Result->nColumns; j++) { const CRegistryResultCell& cell = row[j]; @@ -699,7 +699,7 @@ int CLuaDatabaseDefs::ExecuteSQLQuery(lua_State* luaVM) // Push the column name lua_pushlstring(luaVM, Result->ColNames[j].c_str(), Result->ColNames[j].size()); - switch (cell.nType) // push the value with the right type + switch (cell.nType) // push the value with the right type { case SQLITE_INTEGER: lua_pushnumber(luaVM, static_cast(cell.nVal)); @@ -718,7 +718,7 @@ int CLuaDatabaseDefs::ExecuteSQLQuery(lua_State* luaVM) } lua_settable(luaVM, -3); } - lua_pop(luaVM, 1); // pop the inner table + lua_pop(luaVM, 1); // pop the inner table } return 1; } @@ -765,10 +765,10 @@ int CLuaDatabaseDefs::ExecuteSQLSelect(lua_State* luaVM) { const CRegistryResultRow& row = *iter; // for ( int i = 0; i < Result.nRows; i++ ) { - lua_newtable(luaVM); // new table - lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) - lua_pushvalue(luaVM, -2); // value - lua_settable(luaVM, -4); // refer to the top level table + lua_newtable(luaVM); // new table + lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) + lua_pushvalue(luaVM, -2); // value + lua_settable(luaVM, -4); // refer to the top level table for (int j = 0; j < Result->nColumns; j++) { const CRegistryResultCell& cell = row[j]; @@ -777,7 +777,7 @@ int CLuaDatabaseDefs::ExecuteSQLSelect(lua_State* luaVM) // Push the column name lua_pushlstring(luaVM, Result->ColNames[j].c_str(), Result->ColNames[j].size()); - switch (cell.nType) // push the value with the right type + switch (cell.nType) // push the value with the right type { case SQLITE_INTEGER: lua_pushnumber(luaVM, static_cast(cell.nVal)); @@ -796,7 +796,7 @@ int CLuaDatabaseDefs::ExecuteSQLSelect(lua_State* luaVM) } lua_settable(luaVM, -3); } - lua_pop(luaVM, 1); // pop the inner table + lua_pop(luaVM, 1); // pop the inner table } return 1; } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.h index 42a369d6cab..af7b787e9cd 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaDatabaseDefs.h @@ -36,4 +36,4 @@ class CLuaDatabaseDefs : public CLuaDefs LUA_DECLARE(ExecuteSQLSelect); LUA_DECLARE(ExecuteSQLUpdate); LUA_DECLARE(ExecuteSQLQuery); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaDefs.cpp index 7d054a0dcb3..dfbe215e4e0 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaDefs.cpp @@ -36,7 +36,7 @@ namespace }; std::list ms_TimingFunctionStack; bool ms_bRegisterdPostCallHook = false; -} // namespace +} // namespace CElementDeleter* CLuaDefs::m_pElementDeleter = NULL; CBlipManager* CLuaDefs::m_pBlipManager = NULL; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaDefs.h index f8e3e90e9d1..291f51da15e 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaDefs.h @@ -34,7 +34,7 @@ #include "../CDatabaseManager.h" #include -#define LUA_DECLARE(x) static int x ( lua_State * luaVM ); +#define LUA_DECLARE(x) static int x(lua_State* luaVM); #define LUA_DECLARE_OOP(x) LUA_DECLARE(x) LUA_DECLARE(OOP_##x) class CLuaDefs diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp index 7d339104fb3..078383c4b28 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaElementDefs.cpp @@ -1011,7 +1011,8 @@ CElementResult CLuaElementDefs::getElementsWithinRange(CVector pos, float radius if (interior || dimension || typeHash) { result.erase(std::remove_if(result.begin(), result.end(), - [&, radiusSq = radius * radius](CElement* pElement) { + [&, radiusSq = radius * radius](CElement* pElement) + { if (typeHash && typeHash != pElement->GetTypeHash()) return true; @@ -1539,10 +1540,10 @@ int CLuaElementDefs::setElementID(lua_State* luaVM) int CLuaElementDefs::setElementData(lua_State* luaVM) { // bool setElementData ( element theElement, string key, var value, [var syncMode = true] ) - CElement* pElement; - CStringName key; - CLuaArgument value; - ESyncType syncType = ESyncType::BROADCAST; + CElement* pElement; + CStringName key; + CLuaArgument value; + ESyncType syncType = ESyncType::BROADCAST; std::optional clientTrust{}; CScriptArgReader argStream(luaVM); @@ -1595,7 +1596,7 @@ int CLuaElementDefs::setElementData(lua_State* luaVM) int CLuaElementDefs::removeElementData(lua_State* luaVM) { // bool removeElementData ( element theElement, string key ) - CElement* pElement; + CElement* pElement; CStringName key; CScriptArgReader argStream(luaVM); @@ -1630,9 +1631,9 @@ int CLuaElementDefs::removeElementData(lua_State* luaVM) int CLuaElementDefs::addElementDataSubscriber(lua_State* luaVM) { // bool addElementDataSubscriber ( element theElement, string key, player thePlayer ) - CElement* pElement; + CElement* pElement; CStringName key; - CPlayer* pPlayer; + CPlayer* pPlayer; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -1659,9 +1660,9 @@ int CLuaElementDefs::addElementDataSubscriber(lua_State* luaVM) int CLuaElementDefs::removeElementDataSubscriber(lua_State* luaVM) { // bool removeElementDataSubscriber ( element theElement, string key, player thePlayer ) - CElement* pElement; + CElement* pElement; CStringName key; - CPlayer* pPlayer; + CPlayer* pPlayer; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -1688,9 +1689,9 @@ int CLuaElementDefs::removeElementDataSubscriber(lua_State* luaVM) int CLuaElementDefs::hasElementDataSubscriber(lua_State* luaVM) { // bool hasElementDataSubscriber ( element theElement, string key, player thePlayer ) - CElement* pElement; + CElement* pElement; CStringName key; - CPlayer* pPlayer; + CPlayer* pPlayer; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Event.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Event.cpp index cef47c2e4cd..6d9d55d634d 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Event.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Event.cpp @@ -17,7 +17,7 @@ #include "CLatentTransferManager.h" #include "CDebugHookManager.h" -#define MIN_SERVER_REQ_TRIGGERCLIENTEVENT_SENDLIST "1.3.0-9.04570" +#define MIN_SERVER_REQ_TRIGGERCLIENTEVENT_SENDLIST "1.3.0-9.04570" extern CTimeUsMarker<20> markerLatentEvent; @@ -81,7 +81,7 @@ int CLuaFunctionDefs::AddEventHandler(lua_State* luaVM) } if (!StringToEnum(strPriority, eventPriority)) - argStream.SetTypeError(GetEnumTypeName(eventPriority), 5); // priority is argument #5 + argStream.SetTypeError(GetEnumTypeName(eventPriority), 5); // priority is argument #5 } if (!argStream.HasErrors()) diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Server.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Server.cpp index 845b9fc519f..af2fa3c1a21 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Server.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Server.cpp @@ -18,11 +18,11 @@ #include "CPerfStatManager.h" #include "CMapManager.h" -#define MIN_SERVER_REQ_CALLREMOTE_QUEUE_NAME "1.5.3-9.11270" -#define MIN_SERVER_REQ_CALLREMOTE_CONNECTION_ATTEMPTS "1.3.0-9.04563" -#define MIN_SERVER_REQ_CALLREMOTE_CONNECT_TIMEOUT "1.3.5" -#define MIN_SERVER_REQ_CALLREMOTE_OPTIONS_TABLE "1.5.4-9.11342" -#define MIN_SERVER_REQ_CALLREMOTE_OPTIONS_FORMFIELDS "1.5.4-9.11413" +#define MIN_SERVER_REQ_CALLREMOTE_QUEUE_NAME "1.5.3-9.11270" +#define MIN_SERVER_REQ_CALLREMOTE_CONNECTION_ATTEMPTS "1.3.0-9.04563" +#define MIN_SERVER_REQ_CALLREMOTE_CONNECT_TIMEOUT "1.3.5" +#define MIN_SERVER_REQ_CALLREMOTE_OPTIONS_TABLE "1.5.4-9.11342" +#define MIN_SERVER_REQ_CALLREMOTE_OPTIONS_FORMFIELDS "1.5.4-9.11413" int CLuaFunctionDefs::AddCommandHandler(lua_State* luaVM) { @@ -409,7 +409,7 @@ int CLuaFunctionDefs::SetGameType(lua_State* luaVM) SString strGameType; CScriptArgReader argStream(luaVM); - argStream.ReadIfNextIsString(strGameType, ""); // Default to empty for backward compat with previous implementation + argStream.ReadIfNextIsString(strGameType, ""); // Default to empty for backward compat with previous implementation if (!argStream.HasErrors()) { @@ -433,7 +433,7 @@ int CLuaFunctionDefs::SetMapName(lua_State* luaVM) SString strMapName; CScriptArgReader argStream(luaVM); - argStream.ReadIfNextIsString(strMapName, ""); // Default to empty for backward compat with previous implementation + argStream.ReadIfNextIsString(strMapName, ""); // Default to empty for backward compat with previous implementation if (!argStream.HasErrors()) { @@ -764,7 +764,7 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) for (int c = 0; c < Result.ColumnCount(); c++) { const SString& name = Result.ColumnName(c); - lua_pushnumber(luaVM, c + 1); // row index number (starting at 1, not 0) + lua_pushnumber(luaVM, c + 1); // row index number (starting at 1, not 0) lua_pushlstring(luaVM, name.c_str(), name.length()); lua_settable(luaVM, -3); } @@ -772,10 +772,10 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) lua_newtable(luaVM); for (int r = 0; r < Result.RowCount(); r++) { - lua_newtable(luaVM); // new table - lua_pushnumber(luaVM, r + 1); // row index number (starting at 1, not 0) - lua_pushvalue(luaVM, -2); // value - lua_settable(luaVM, -4); // refer to the top level table + lua_newtable(luaVM); // new table + lua_pushnumber(luaVM, r + 1); // row index number (starting at 1, not 0) + lua_pushvalue(luaVM, -2); // value + lua_settable(luaVM, -4); // refer to the top level table for (int c = 0; c < Result.ColumnCount(); c++) { @@ -784,7 +784,7 @@ int CLuaFunctionDefs::GetPerformanceStats(lua_State* luaVM) lua_pushlstring(luaVM, cell.c_str(), cell.length()); lua_settable(luaVM, -3); } - lua_pop(luaVM, 1); // pop the inner table + lua_pop(luaVM, 1); // pop the inner table } return 2; } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Weapon.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Weapon.cpp index 19897098aa4..de986285805 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Weapon.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.Weapon.cpp @@ -15,7 +15,7 @@ #include "CStaticFunctionDefinitions.h" #include "CWeaponNames.h" -#define MIN_SERVER_REQ_WEAPON_PROPERTY_FLAG "1.3.5-9.06139" +#define MIN_SERVER_REQ_WEAPON_PROPERTY_FLAG "1.3.5-9.06139" int CLuaFunctionDefs::SetWeaponAmmo(lua_State* luaVM) { diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.cpp index 3e891761f25..dbf615c5875 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaFunctionDefs.cpp @@ -12,73 +12,104 @@ #include "StdInc.h" #include "CLuaFunctionDefs.h" -CTimeUsMarker<20> markerLatentEvent; // For timing triggerLatentClientEvent +CTimeUsMarker<20> markerLatentEvent; // For timing triggerLatentClientEvent void CLuaFunctionDefs::LoadFunctions() { - constexpr static const std::pair functions[] - { - {"addEvent", CLuaFunctionDefs::AddEvent}, {"addEventHandler", CLuaFunctionDefs::AddEventHandler}, - {"removeEventHandler", CLuaFunctionDefs::RemoveEventHandler}, {"getEventHandlers", CLuaFunctionDefs::GetEventHandlers}, - {"triggerEvent", CLuaFunctionDefs::TriggerEvent}, {"triggerClientEvent", CLuaFunctionDefs::TriggerClientEvent}, - {"cancelEvent", CLuaFunctionDefs::CancelEvent}, {"wasEventCancelled", CLuaFunctionDefs::WasEventCancelled}, - {"getCancelReason", CLuaFunctionDefs::GetCancelReason}, {"triggerLatentClientEvent", CLuaFunctionDefs::TriggerLatentClientEvent}, - {"getLatentEventHandles", CLuaFunctionDefs::GetLatentEventHandles}, {"getLatentEventStatus", CLuaFunctionDefs::GetLatentEventStatus}, - {"cancelLatentEvent", CLuaFunctionDefs::CancelLatentEvent}, {"addDebugHook", CLuaFunctionDefs::AddDebugHook}, - {"removeDebugHook", CLuaFunctionDefs::RemoveDebugHook}, - - // Explosion create funcs - {"createExplosion", CLuaFunctionDefs::CreateExplosion}, - - // Ped body funcs? - {"getBodyPartName", CLuaFunctionDefs::GetBodyPartName}, {"getClothesByTypeIndex", CLuaFunctionDefs::GetClothesByTypeIndex}, - {"getTypeIndexFromClothes", CLuaFunctionDefs::GetTypeIndexFromClothes}, {"getClothesTypeName", CLuaFunctionDefs::GetClothesTypeName}, - - // Weapon funcs - {"getWeaponNameFromID", CLuaFunctionDefs::GetWeaponNameFromID}, {"getWeaponIDFromName", CLuaFunctionDefs::GetWeaponIDFromName}, - {"getWeaponProperty", CLuaFunctionDefs::GetWeaponProperty}, {"getOriginalWeaponProperty", CLuaFunctionDefs::GetOriginalWeaponProperty}, - {"setWeaponProperty", CLuaFunctionDefs::SetWeaponProperty}, {"setWeaponAmmo", CLuaFunctionDefs::SetWeaponAmmo}, - {"getSlotFromWeapon", CLuaFunctionDefs::GetSlotFromWeapon}, - - #if MTASA_VERSION_TYPE < VERSION_TYPE_UNTESTED - {"createWeapon", CLuaFunctionDefs::CreateWeapon}, {"fireWeapon", CLuaFunctionDefs::FireWeapon}, - {"setWeaponState", CLuaFunctionDefs::SetWeaponState}, {"getWeaponState", CLuaFunctionDefs::GetWeaponState}, - {"setWeaponTarget", CLuaFunctionDefs::SetWeaponTarget}, {"getWeaponTarget", CLuaFunctionDefs::GetWeaponTarget}, - {"setWeaponOwner", CLuaFunctionDefs::SetWeaponOwner}, {"getWeaponOwner", CLuaFunctionDefs::GetWeaponOwner}, - {"setWeaponFlags", CLuaFunctionDefs::SetWeaponFlags}, {"getWeaponFlags", CLuaFunctionDefs::GetWeaponFlags}, - {"setWeaponFiringRate", CLuaFunctionDefs::SetWeaponFiringRate}, {"getWeaponFiringRate", CLuaFunctionDefs::GetWeaponFiringRate}, - {"resetWeaponFiringRate", CLuaFunctionDefs::ResetWeaponFiringRate}, {"getWeaponAmmo", CLuaFunctionDefs::GetWeaponAmmo}, - {"getWeaponClipAmmo", CLuaFunctionDefs::GetWeaponClipAmmo}, {"setWeaponClipAmmo", CLuaFunctionDefs::SetWeaponClipAmmo}, - #endif - - // Console funcs - {"addCommandHandler", CLuaFunctionDefs::AddCommandHandler}, {"removeCommandHandler", CLuaFunctionDefs::RemoveCommandHandler}, - {"executeCommandHandler", CLuaFunctionDefs::ExecuteCommandHandler}, {"getCommandHandlers", CLuaFunctionDefs::GetCommandHandlers}, - - // Loaded map funcs - {"getRootElement", CLuaFunctionDefs::GetRootElement}, {"loadMapData", CLuaFunctionDefs::LoadMapData}, - {"saveMapData", CLuaFunctionDefs::SaveMapData}, - - // All-Seeing Eye Functions - {"getGameType", CLuaFunctionDefs::GetGameType}, {"getMapName", CLuaFunctionDefs::GetMapName}, {"setGameType", CLuaFunctionDefs::SetGameType}, - {"setMapName", CLuaFunctionDefs::SetMapName}, {"getRuleValue", CLuaFunctionDefs::GetRuleValue}, {"setRuleValue", CLuaFunctionDefs::SetRuleValue}, - {"removeRuleValue", CLuaFunctionDefs::RemoveRuleValue}, - - // Registry functions - {"getPerformanceStats", CLuaFunctionDefs::GetPerformanceStats}, - - // Misc funcs - {"resetMapInfo", CLuaFunctionDefs::ResetMapInfo}, {"getServerPort", CLuaFunctionDefs::GetServerPort}, - - // Settings registry funcs - {"get", CLuaFunctionDefs::Get}, {"set", CLuaFunctionDefs::Set}, - - // Utility - {"getVersion", CLuaFunctionDefs::GetVersion}, {"getNetworkUsageData", CLuaFunctionDefs::GetNetworkUsageData}, - {"getNetworkStats", CLuaFunctionDefs::GetNetworkStats}, {"getLoadedModules", CLuaFunctionDefs::GetModules}, - {"getModuleInfo", CLuaFunctionDefs::GetModuleInfo}, - - {"setDevelopmentMode", CLuaFunctionDefs::SetDevelopmentMode}, {"getDevelopmentMode", CLuaFunctionDefs::GetDevelopmentMode}, + constexpr static const std::pair functions[]{ + {"addEvent", CLuaFunctionDefs::AddEvent}, + {"addEventHandler", CLuaFunctionDefs::AddEventHandler}, + {"removeEventHandler", CLuaFunctionDefs::RemoveEventHandler}, + {"getEventHandlers", CLuaFunctionDefs::GetEventHandlers}, + {"triggerEvent", CLuaFunctionDefs::TriggerEvent}, + {"triggerClientEvent", CLuaFunctionDefs::TriggerClientEvent}, + {"cancelEvent", CLuaFunctionDefs::CancelEvent}, + {"wasEventCancelled", CLuaFunctionDefs::WasEventCancelled}, + {"getCancelReason", CLuaFunctionDefs::GetCancelReason}, + {"triggerLatentClientEvent", CLuaFunctionDefs::TriggerLatentClientEvent}, + {"getLatentEventHandles", CLuaFunctionDefs::GetLatentEventHandles}, + {"getLatentEventStatus", CLuaFunctionDefs::GetLatentEventStatus}, + {"cancelLatentEvent", CLuaFunctionDefs::CancelLatentEvent}, + {"addDebugHook", CLuaFunctionDefs::AddDebugHook}, + {"removeDebugHook", CLuaFunctionDefs::RemoveDebugHook}, + + // Explosion create funcs + {"createExplosion", CLuaFunctionDefs::CreateExplosion}, + + // Ped body funcs? + {"getBodyPartName", CLuaFunctionDefs::GetBodyPartName}, + {"getClothesByTypeIndex", CLuaFunctionDefs::GetClothesByTypeIndex}, + {"getTypeIndexFromClothes", CLuaFunctionDefs::GetTypeIndexFromClothes}, + {"getClothesTypeName", CLuaFunctionDefs::GetClothesTypeName}, + + // Weapon funcs + {"getWeaponNameFromID", CLuaFunctionDefs::GetWeaponNameFromID}, + {"getWeaponIDFromName", CLuaFunctionDefs::GetWeaponIDFromName}, + {"getWeaponProperty", CLuaFunctionDefs::GetWeaponProperty}, + {"getOriginalWeaponProperty", CLuaFunctionDefs::GetOriginalWeaponProperty}, + {"setWeaponProperty", CLuaFunctionDefs::SetWeaponProperty}, + {"setWeaponAmmo", CLuaFunctionDefs::SetWeaponAmmo}, + {"getSlotFromWeapon", CLuaFunctionDefs::GetSlotFromWeapon}, + +#if MTASA_VERSION_TYPE < VERSION_TYPE_UNTESTED + {"createWeapon", CLuaFunctionDefs::CreateWeapon}, + {"fireWeapon", CLuaFunctionDefs::FireWeapon}, + {"setWeaponState", CLuaFunctionDefs::SetWeaponState}, + {"getWeaponState", CLuaFunctionDefs::GetWeaponState}, + {"setWeaponTarget", CLuaFunctionDefs::SetWeaponTarget}, + {"getWeaponTarget", CLuaFunctionDefs::GetWeaponTarget}, + {"setWeaponOwner", CLuaFunctionDefs::SetWeaponOwner}, + {"getWeaponOwner", CLuaFunctionDefs::GetWeaponOwner}, + {"setWeaponFlags", CLuaFunctionDefs::SetWeaponFlags}, + {"getWeaponFlags", CLuaFunctionDefs::GetWeaponFlags}, + {"setWeaponFiringRate", CLuaFunctionDefs::SetWeaponFiringRate}, + {"getWeaponFiringRate", CLuaFunctionDefs::GetWeaponFiringRate}, + {"resetWeaponFiringRate", CLuaFunctionDefs::ResetWeaponFiringRate}, + {"getWeaponAmmo", CLuaFunctionDefs::GetWeaponAmmo}, + {"getWeaponClipAmmo", CLuaFunctionDefs::GetWeaponClipAmmo}, + {"setWeaponClipAmmo", CLuaFunctionDefs::SetWeaponClipAmmo}, +#endif + + // Console funcs + {"addCommandHandler", CLuaFunctionDefs::AddCommandHandler}, + {"removeCommandHandler", CLuaFunctionDefs::RemoveCommandHandler}, + {"executeCommandHandler", CLuaFunctionDefs::ExecuteCommandHandler}, + {"getCommandHandlers", CLuaFunctionDefs::GetCommandHandlers}, + + // Loaded map funcs + {"getRootElement", CLuaFunctionDefs::GetRootElement}, + {"loadMapData", CLuaFunctionDefs::LoadMapData}, + {"saveMapData", CLuaFunctionDefs::SaveMapData}, + + // All-Seeing Eye Functions + {"getGameType", CLuaFunctionDefs::GetGameType}, + {"getMapName", CLuaFunctionDefs::GetMapName}, + {"setGameType", CLuaFunctionDefs::SetGameType}, + {"setMapName", CLuaFunctionDefs::SetMapName}, + {"getRuleValue", CLuaFunctionDefs::GetRuleValue}, + {"setRuleValue", CLuaFunctionDefs::SetRuleValue}, + {"removeRuleValue", CLuaFunctionDefs::RemoveRuleValue}, + + // Registry functions + {"getPerformanceStats", CLuaFunctionDefs::GetPerformanceStats}, + + // Misc funcs + {"resetMapInfo", CLuaFunctionDefs::ResetMapInfo}, + {"getServerPort", CLuaFunctionDefs::GetServerPort}, + + // Settings registry funcs + {"get", CLuaFunctionDefs::Get}, + {"set", CLuaFunctionDefs::Set}, + + // Utility + {"getVersion", CLuaFunctionDefs::GetVersion}, + {"getNetworkUsageData", CLuaFunctionDefs::GetNetworkUsageData}, + {"getNetworkStats", CLuaFunctionDefs::GetNetworkStats}, + {"getLoadedModules", CLuaFunctionDefs::GetModules}, + {"getModuleInfo", CLuaFunctionDefs::GetModuleInfo}, + + {"setDevelopmentMode", CLuaFunctionDefs::SetDevelopmentMode}, + {"getDevelopmentMode", CLuaFunctionDefs::GetDevelopmentMode}, }; // Add all functions diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaHTTPDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaHTTPDefs.h index 595bd68f17f..cdecbfbe10f 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaHTTPDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaHTTPDefs.h @@ -25,4 +25,4 @@ class CLuaHTTPDefs : public CLuaDefs LUA_DECLARE(httpSetResponseCode); LUA_DECLARE(httpClear); LUA_DECLARE(httpRequestLogin); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.cpp index 552cde4a63e..a62170d8ef3 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.cpp @@ -98,7 +98,7 @@ int CLuaHandlingDefs::SetVehicleHandling(lua_State* luaVM) } break; } - case HANDLING_PERCENTSUBMERGED: // unsigned int + case HANDLING_PERCENTSUBMERGED: // unsigned int // case HANDLING_MONETARY: case HANDLING_HANDLINGFLAGS: case HANDLING_MODELFLAGS: @@ -275,7 +275,7 @@ int CLuaHandlingDefs::SetModelHandling(lua_State* luaVM) } break; } - case HANDLING_PERCENTSUBMERGED: // unsigned int + case HANDLING_PERCENTSUBMERGED: // unsigned int // case HANDLING_MONETARY: case HANDLING_HANDLINGFLAGS: case HANDLING_MODELFLAGS: @@ -498,7 +498,7 @@ int CLuaHandlingDefs::GetVehicleHandling(lua_State* luaVM) lua_pushstring(luaVM, "rwd"); else if (eDriveType == CHandlingEntry::FOURWHEEL) lua_pushstring(luaVM, "awd"); - else // What the ... (yeah, security) + else // What the ... (yeah, security) lua_pushnil(luaVM); lua_setfield(luaVM, -2, "driveType"); @@ -664,7 +664,7 @@ int CLuaHandlingDefs::GetModelHandling(lua_State* luaVM) lua_pushstring(luaVM, "rwd"); else if (eDriveType == CHandlingEntry::FOURWHEEL) lua_pushstring(luaVM, "awd"); - else // What the ... (yeah, security) + else // What the ... (yeah, security) lua_pushnil(luaVM); lua_setfield(luaVM, -2, "driveType"); @@ -828,7 +828,7 @@ int CLuaHandlingDefs::GetOriginalHandling(lua_State* luaVM) lua_pushstring(luaVM, "rwd"); else if (eDriveType == CHandlingEntry::FOURWHEEL) lua_pushstring(luaVM, "awd"); - else // What the ... (yeah, security) + else // What the ... (yeah, security) lua_pushnil(luaVM); lua_setfield(luaVM, -2, "driveType"); CHandlingEntry::eEngineType eEngineType = entry->GetCarEngineType(); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.h index cd515c55804..a43acb308b0 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaHandlingDefs.h @@ -116,4 +116,4 @@ class CLuaHandlingDefs : public CLuaDefs LUA_DECLARE ( handlingSetHeadLightType ); LUA_DECLARE ( handlingSetTailLightType ); LUA_DECLARE ( handlingSetAnimGroup );*/ -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp index fe2e5e11155..dc927344cd3 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.cpp @@ -54,13 +54,13 @@ void CLuaMarkerDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "getIcon", "getMarkerIcon"); lua_classfunction(luaVM, "getSize", "getMarkerSize"); lua_classfunction(luaVM, "getTarget", "getMarkerTarget", OOP_GetMarkerTarget); - lua_classfunction(luaVM, "getColor", "getMarkerColor"); // color + lua_classfunction(luaVM, "getColor", "getMarkerColor"); // color lua_classfunction(luaVM, "setType", "setMarkerType"); lua_classfunction(luaVM, "setIcon", "setMarkerIcon"); lua_classfunction(luaVM, "setSize", "setMarkerSize"); lua_classfunction(luaVM, "setTarget", "setMarkerTarget"); - lua_classfunction(luaVM, "setColor", "setMarkerColor"); // color + lua_classfunction(luaVM, "setColor", "setMarkerColor"); // color lua_classvariable(luaVM, "markerType", "setMarkerType", "getMarkerType"); lua_classvariable(luaVM, "icon", "setMarkerIcon", "getMarkerIcon"); @@ -206,7 +206,7 @@ int CLuaMarkerDefs::GetMarkerColor(lua_State* luaVM) lua_pushnumber(luaVM, static_cast(color.B)); if (!pMarker->AreAlphaLimitsIgnored() && (pMarker->GetMarkerType() == CMarker::TYPE_CHECKPOINT || pMarker->GetMarkerType() == CMarker::TYPE_ARROW)) - lua_pushnumber(luaVM, 255); // fake alpha + lua_pushnumber(luaVM, 255); // fake alpha else lua_pushnumber(luaVM, static_cast(color.A)); @@ -423,7 +423,8 @@ int CLuaMarkerDefs::SetMarkerIcon(lua_State* luaVM) return 1; } -bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CMarker* marker, std::optional r, std::optional g, std::optional b, std::optional a, std::optional size) +bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CMarker* marker, std::optional r, std::optional g, + std::optional b, std::optional a, std::optional size) { SColor color; color.R = r.value_or(255); @@ -434,7 +435,8 @@ bool CLuaMarkerDefs::SetMarkerTargetArrowProperties(CMarker* marker, std::option return CStaticFunctionDefinitions::SetMarkerTargetArrowProperties(marker, color, size.value_or(marker->GetSize() * 0.625f)); } -std::variant, bool> CLuaMarkerDefs::GetMarkerTargetArrowProperties(CMarker* marker) noexcept +std::variant, bool> CLuaMarkerDefs::GetMarkerTargetArrowProperties( + CMarker* marker) noexcept { if (!marker->HasTarget() || marker->GetMarkerType() != CMarker::TYPE_CHECKPOINT) return false; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h index 519cf725cc8..ad1f1990c42 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaMarkerDefs.h @@ -36,6 +36,8 @@ class CLuaMarkerDefs : public CLuaDefs LUA_DECLARE(SetMarkerColor); LUA_DECLARE(SetMarkerTarget); LUA_DECLARE(SetMarkerIcon); - static bool SetMarkerTargetArrowProperties(CMarker* marker, std::optional r, std::optional g, std::optional b, std::optional a, std::optional size); - static std::variant, bool> GetMarkerTargetArrowProperties(CMarker* marker) noexcept; + static bool SetMarkerTargetArrowProperties(CMarker* marker, std::optional r, std::optional g, std::optional b, + std::optional a, std::optional size); + static std::variant, bool> GetMarkerTargetArrowProperties( + CMarker* marker) noexcept; }; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp index 1d10a059162..135e5a4e9a8 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaPedDefs.cpp @@ -35,7 +35,7 @@ void CLuaPedDefs::LoadFunctions() {"getPedTotalAmmo", GetPedTotalAmmo}, {"getPedWeapon", GetPedWeapon}, {"getPedClothes", GetPedClothes}, - {"isPedWearingJetpack", DoesPedHaveJetPack}, // introduced in 1.5.5-9.13846 + {"isPedWearingJetpack", DoesPedHaveJetPack}, // introduced in 1.5.5-9.13846 {"isPedOnGround", IsPedOnGround}, {"getPedFightingStyle", GetPedFightingStyle}, {"getPedWalkingStyle", GetPedMoveAnim}, @@ -58,7 +58,7 @@ void CLuaPedDefs::LoadFunctions() {"setPedStat", SetPedStat}, {"addPedClothes", AddPedClothes}, {"removePedClothes", RemovePedClothes}, - {"setPedWearingJetpack", SetPedWearingJetpack}, // introduced in 1.5.5-9.13846 + {"setPedWearingJetpack", SetPedWearingJetpack}, // introduced in 1.5.5-9.13846 {"setPedFightingStyle", SetPedFightingStyle}, {"setPedWalkingStyle", SetPedMoveAnim}, {"setPedGravity", SetPedGravity}, @@ -106,7 +106,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "removeClothes", "removePedClothes"); lua_classfunction(luaVM, "removeFromVehicle", "removePedFromVehicle"); lua_classfunction(luaVM, "removeJetPack", "removePedJetPack"); - lua_classfunction(luaVM, "doesHaveJetpack", "doesPedHaveJetPack"); // deprecated in 1.5.5-9.13846 + lua_classfunction(luaVM, "doesHaveJetpack", "doesPedHaveJetPack"); // deprecated in 1.5.5-9.13846 lua_classfunction(luaVM, "isDead", "isPedDead"); lua_classfunction(luaVM, "isDucked", "isPedDucked"); @@ -118,7 +118,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "isDoingGangDriveby", "isPedDoingGangDriveby"); lua_classfunction(luaVM, "isFrozen", "isPedFrozen"); lua_classfunction(luaVM, "isHeadless", "isPedHeadless"); - lua_classfunction(luaVM, "isWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 + lua_classfunction(luaVM, "isWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 lua_classfunction(luaVM, "isReloadingWeapon", "isPedReloadingWeapon"); lua_classfunction(luaVM, "getArmor", "getPedArmor"); @@ -150,7 +150,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "setAnimation", "setPedAnimation"); lua_classfunction(luaVM, "setAnimationProgress", "setPedAnimationProgress"); lua_classfunction(luaVM, "setAnimationSpeed", "setPedAnimationSpeed"); - lua_classfunction(luaVM, "setWearingJetpack", "setPedWearingJetpack"); // introduced in 1.5.5-9.13846 + lua_classfunction(luaVM, "setWearingJetpack", "setPedWearingJetpack"); // introduced in 1.5.5-9.13846 lua_classvariable(luaVM, "inVehicle", NULL, "isPedInVehicle"); lua_classvariable(luaVM, "ducked", NULL, "isPedDucked"); @@ -170,7 +170,7 @@ void CLuaPedDefs::AddClass(lua_State* luaVM) lua_classvariable(luaVM, "contactElement", NULL, "getPedContactElement"); lua_classvariable(luaVM, "vehicle", "warpPedIntoVehicle", "getPedOccupiedVehicle", OOP_WarpPedIntoVehicle, GetPedOccupiedVehicle); lua_classvariable(luaVM, "walkingStyle", "setPedWalkingStyle", "getPedWalkingStyle"); - lua_classvariable(luaVM, "jetpack", "setPedWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 + lua_classvariable(luaVM, "jetpack", "setPedWearingJetpack", "isPedWearingJetpack"); // introduced in 1.5.5-9.13846 lua_classvariable(luaVM, "reloadingWeapon", nullptr, "isPedReloadingWeapon"); // TODO(qaisjp): setting this to any value will kill the ped. add OOP_KillPed that only allows `true`. @@ -421,7 +421,9 @@ bool CLuaPedDefs::SetPedAnimation(CElement* pPed, std::optional> blockName, std::optional> animName, std::optional time, std::optional loop, std::optional updatePosition, std::optional interruptable, std::optional freezeLastFrame, std::optional blendTime, std::optional restoreTask); + static bool SetPedAnimation(CElement* pPed, std::optional> blockName, + std::optional> animName, std::optional time, std::optional loop, + std::optional updatePosition, std::optional interruptable, std::optional freezeLastFrame, + std::optional blendTime, std::optional restoreTask); LUA_DECLARE(SetPedAnimationProgress); LUA_DECLARE(SetPedAnimationSpeed); LUA_DECLARE(SetPedWeaponSlot); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp index 41ea5464808..20572e7d5e0 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.cpp @@ -235,7 +235,7 @@ int CLuaPlayerDefs::CanPlayerUseFunction(lua_State* luaVM) int CLuaPlayerDefs::GetPlayerName(lua_State* luaVM) { // string getPlayerName ( player thePlayer ) - CElement* pElement; // player or console + CElement* pElement; // player or console CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -264,7 +264,7 @@ int CLuaPlayerDefs::GetPlayerName(lua_State* luaVM) int CLuaPlayerDefs::GetPlayerIP(lua_State* luaVM) { // string getPlayerIP ( player thePlayer ) - CElement* pElement; // player or console + CElement* pElement; // player or console CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -314,7 +314,7 @@ int CLuaPlayerDefs::GetPlayerVersion(lua_State* luaVM) int CLuaPlayerDefs::GetPlayerAccount(lua_State* luaVM) { // account getPlayerAccount ( player thePlayer ) - CElement* pElement; // player or console + CElement* pElement; // player or console CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -1536,7 +1536,7 @@ int CLuaPlayerDefs::UnbindKey(lua_State* luaVM) argStream.ReadUserData(pPlayer); argStream.ReadString(strKey); - if (argStream.NextIsString(1)) // Check if has command + if (argStream.NextIsString(1)) // Check if has command { // bool unbindKey ( player thePlayer, string key, string keyState, string command ) argStream.ReadString(strHitState); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h index 73c499d8f4a..21768454c8e 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaPlayerDefs.h @@ -38,8 +38,8 @@ class CLuaPlayerDefs : public CLuaDefs LUA_DECLARE(GetPlayerNametagColor); LUA_DECLARE(IsPlayerNametagShowing); LUA_DECLARE(GetPlayerSerial); - LUA_DECLARE(GetPlayerCommunityID); // deprecate me - LUA_DECLARE(GetPlayerUserName); // deprecate me + LUA_DECLARE(GetPlayerCommunityID); // deprecate me + LUA_DECLARE(GetPlayerUserName); // deprecate me LUA_DECLARE(GetPlayerBlurLevel); LUA_DECLARE(GetPlayerName); LUA_DECLARE(GetPlayerIP); @@ -53,7 +53,7 @@ class CLuaPlayerDefs : public CLuaDefs LUA_DECLARE(GivePlayerMoney); LUA_DECLARE(TakePlayerMoney); LUA_DECLARE(SpawnPlayer); - LUA_DECLARE(ShowPlayerHudComponent); // deprecate me + LUA_DECLARE(ShowPlayerHudComponent); // deprecate me LUA_DECLARE(SetPlayerWantedLevel); LUA_DECLARE(ForcePlayerMap); LUA_DECLARE(SetPlayerNametagText); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaRadarAreaDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaRadarAreaDefs.h index 2f846f17749..f31d1449128 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaRadarAreaDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaRadarAreaDefs.h @@ -31,4 +31,4 @@ class CLuaRadarAreaDefs : public CLuaDefs LUA_DECLARE(SetRadarAreaSize); LUA_DECLARE(SetRadarAreaColor); LUA_DECLARE(SetRadarAreaFlashing); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp index 58660c21ba0..1fffce55261 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.cpp @@ -97,7 +97,7 @@ void CLuaResourceDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "getFromName", "getResourceFromName"); lua_classfunction(luaVM, "getAll", "getResources"); lua_classfunction(luaVM, "getThis", "getThisResource"); - lua_classfunction(luaVM, "refresh", "refreshResources"); // Can't use "all" here because that's an argument + lua_classfunction(luaVM, "refresh", "refreshResources"); // Can't use "all" here because that's an argument lua_classfunction(luaVM, "create", "createResource"); lua_classfunction(luaVM, "start", "startResource"); @@ -595,7 +595,7 @@ int CLuaResourceDefs::stopResource(lua_State* luaVM) int CLuaResourceDefs::restartResource(lua_State* luaVM) { CResource* pResource = nullptr; - bool bPersistent = false; // unused + bool bPersistent = false; // unused SResourceStartOptions StartOptions; CScriptArgReader argStream(luaVM); @@ -1140,7 +1140,7 @@ int CLuaResourceDefs::call(lua_State* luaVM) args.ReadArguments(luaVM, 3); CLuaArguments returns; - LUA_CHECKSTACK(targetLuaVM, 1); // Ensure some room + LUA_CHECKSTACK(targetLuaVM, 1); // Ensure some room // Lets grab the original hidden variables so we can restore them later lua_getglobal(targetLuaVM, "sourceResource"); @@ -1237,10 +1237,10 @@ int CLuaResourceDefs::getResourceACLRequests(lua_State* luaVM) lua_newtable(luaVM); for (uint i = 0; i < Result.size(); i++) { - lua_newtable(luaVM); // new table - lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) - lua_pushvalue(luaVM, -2); // value - lua_settable(luaVM, -4); // refer to the top level table + lua_newtable(luaVM); // new table + lua_pushnumber(luaVM, i + 1); // row index number (starting at 1, not 0) + lua_pushvalue(luaVM, -2); // value + lua_settable(luaVM, -4); // refer to the top level table const SAclRequest& request = Result[i]; lua_pushstring(luaVM, "name"); @@ -1263,7 +1263,7 @@ int CLuaResourceDefs::getResourceACLRequests(lua_State* luaVM) lua_pushstring(luaVM, request.strDate); lua_settable(luaVM, -3); - lua_pop(luaVM, 1); // pop the inner table + lua_pop(luaVM, 1); // pop the inner table } return 1; } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.h index 69524ece50e..8739dd658a3 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaResourceDefs.h @@ -55,7 +55,7 @@ class CLuaResourceDefs : public CLuaDefs LUA_DECLARE(isResourceArchived); static std::string GetResourceName(lua_State* luaVM, std::optional resourceElement); - static bool isResourceProtected(CResource* const resource); + static bool isResourceProtected(CResource* const resource); // Set stuff LUA_DECLARE(setResourceInfo); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp index f81c0c06844..e4d7f7ea24e 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.cpp @@ -15,24 +15,22 @@ void CLuaTeamDefs::LoadFunctions() { - constexpr static const std::pair functions[]{ - // Team create/destroy functions - {"createTeam", ArgumentParserWarn}, - - // Team get funcs - {"getTeamName", ArgumentParserWarn}, - {"getTeamFromName", ArgumentParserWarn}, - {"getTeamColor", ArgumentParserWarn}, - {"getTeamFriendlyFire", ArgumentParserWarn}, - {"getPlayersInTeam", ArgumentParserWarn}, - {"countPlayersInTeam", ArgumentParserWarn}, - - // Team set funcs - {"setPlayerTeam", ArgumentParserWarn}, - {"setTeamName", ArgumentParserWarn}, - {"setTeamColor", ArgumentParserWarn}, - {"setTeamFriendlyFire", ArgumentParserWarn} - }; + constexpr static const std::pair functions[]{// Team create/destroy functions + {"createTeam", ArgumentParserWarn}, + + // Team get funcs + {"getTeamName", ArgumentParserWarn}, + {"getTeamFromName", ArgumentParserWarn}, + {"getTeamColor", ArgumentParserWarn}, + {"getTeamFriendlyFire", ArgumentParserWarn}, + {"getPlayersInTeam", ArgumentParserWarn}, + {"countPlayersInTeam", ArgumentParserWarn}, + + // Team set funcs + {"setPlayerTeam", ArgumentParserWarn}, + {"setTeamName", ArgumentParserWarn}, + {"setTeamColor", ArgumentParserWarn}, + {"setTeamFriendlyFire", ArgumentParserWarn}}; // Add functions for (const auto& [name, func] : functions) @@ -48,7 +46,7 @@ void CLuaTeamDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "countPlayers", "countPlayersInTeam"); lua_classfunction(luaVM, "getPlayers", "getPlayersInTeam"); lua_classfunction(luaVM, "outputChat", "outputChatBox", ArgumentParserWarn); - + lua_classfunction(luaVM, "getFriendlyFire", "getTeamFriendlyFire"); lua_classfunction(luaVM, "getName", "getTeamName"); lua_classfunction(luaVM, "getColor", "getTeamColor"); @@ -65,9 +63,10 @@ void CLuaTeamDefs::AddClass(lua_State* luaVM) lua_registerclass(luaVM, "Team", "Element"); } -std::variant CLuaTeamDefs::CreateTeam(lua_State* lua, const std::string name, const std::optional red, const std::optional green, const std::optional blue) +std::variant CLuaTeamDefs::CreateTeam(lua_State* lua, const std::string name, const std::optional red, + const std::optional green, const std::optional blue) { - CLuaMain& vm = lua_getownercluamain(lua); + CLuaMain& vm = lua_getownercluamain(lua); CResource* resource = vm.GetResource(); if (!resource) diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h index 5e309460aab..4caf9c6a8d1 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaTeamDefs.h @@ -19,15 +19,16 @@ class CLuaTeamDefs : public CLuaDefs private: // Team create/destroy functions - static std::variant CreateTeam(lua_State* lua, const std::string name, const std::optional red, const std::optional green, const std::optional blue); + static std::variant CreateTeam(lua_State* lua, const std::string name, const std::optional red, + const std::optional green, const std::optional blue); // Team get funcs - static std::variant GetTeamFromName(const std::string name); - static std::string GetTeamName(CTeam* team); + static std::variant GetTeamFromName(const std::string name); + static std::string GetTeamName(CTeam* team); static CLuaMultiReturn GetTeamColor(CTeam* team) noexcept; - static bool GetTeamFriendlyFire(CTeam* team) noexcept; - static std::vector GetPlayersInTeam(CTeam* team); - static std::uint32_t CountPlayersInTeam(CTeam* team) noexcept; + static bool GetTeamFriendlyFire(CTeam* team) noexcept; + static std::vector GetPlayersInTeam(CTeam* team); + static std::uint32_t CountPlayersInTeam(CTeam* team) noexcept; // Team set funcs static bool SetPlayerTeam(CPlayer* player, std::optional team) noexcept; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.cpp index a328869d87f..b2453e97459 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.cpp @@ -174,14 +174,14 @@ int CLuaTextDefs::textCreateTextItem(lua_State* luaVM) { unsigned char ucFormat = 0; if (strHorzAlign == "center") - ucFormat |= 0x00000001; // DT_CENTER + ucFormat |= 0x00000001; // DT_CENTER else if (strHorzAlign == "right") - ucFormat |= 0x00000002; // DT_RIGHT + ucFormat |= 0x00000002; // DT_RIGHT if (strVertAlign == "center") - ucFormat |= 0x00000004; // DT_VCENTER + ucFormat |= 0x00000004; // DT_VCENTER else if (strVertAlign == "bottom") - ucFormat |= 0x00000008; // DT_BOTTOM + ucFormat |= 0x00000008; // DT_BOTTOM // Grab our virtual machine CLuaMain* luaMain = m_pLuaManager->GetVirtualMachine(luaVM); diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.h index 04cba64314c..1865755ae73 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaTextDefs.h @@ -40,4 +40,4 @@ class CLuaTextDefs : public CLuaDefs LUA_DECLARE(textItemGetColor); LUA_DECLARE(textItemSetPriority); LUA_DECLARE(textItemGetPriority); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp index 857f70b443c..fb234bccbdc 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaTimerDefs.cpp @@ -16,9 +16,14 @@ void CLuaTimerDefs::LoadFunctions() { constexpr static const std::pair functions[]{ - {"setTimer", SetTimer}, {"killTimer", KillTimer}, {"resetTimer", ResetTimer}, - {"setTimerPaused", ArgumentParser},{"isTimerPaused", ArgumentParser}, - {"getTimers", GetTimers}, {"isTimer", IsTimer},{"getTimerDetails", GetTimerDetails}, + {"setTimer", SetTimer}, + {"killTimer", KillTimer}, + {"resetTimer", ResetTimer}, + {"setTimerPaused", ArgumentParser}, + {"isTimerPaused", ArgumentParser}, + {"getTimers", GetTimers}, + {"isTimer", IsTimer}, + {"getTimerDetails", GetTimerDetails}, }; // Add functions diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp index e3c2b21ec0c..63f0565b73c 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.cpp @@ -17,7 +17,7 @@ #include "CScriptArgReader.h" #include "packets/CElementRPCPacket.h" -#include "lua/CLuaShared.h" // for CLuaShared::CustomTrainTracks +#include "lua/CLuaShared.h" // for CLuaShared::CustomTrainTracks void CLuaVehicleDefs::LoadFunctions() { @@ -206,7 +206,7 @@ void CLuaVehicleDefs::AddClass(lua_State* luaVM) lua_classfunction(luaVM, "getTowingVehicle", "getVehicleTowingVehicle"); lua_classfunction(luaVM, "getTurnVelocity", "getVehicleTurnVelocity", CLuaVehicleDefs::OOP_GetVehicleTurnVelocity); lua_classfunction(luaVM, "getTurretPosition", "getVehicleTurretPosition"); - lua_classfunction(luaVM, "getVehicleType", "getVehicleType"); // This isn't "getType" because it would overwrite Element.getType + lua_classfunction(luaVM, "getVehicleType", "getVehicleType"); // This isn't "getType" because it would overwrite Element.getType lua_classfunction(luaVM, "getUpgradeOnSlot", "getVehicleUpgradeOnSlot"); lua_classfunction(luaVM, "getUpgrades", "getVehicleUpgrades"); lua_classfunction(luaVM, "getWheelStates", "getVehicleWheelStates"); @@ -251,7 +251,7 @@ void CLuaVehicleDefs::AddClass(lua_State* luaVM) if (CLuaShared::CustomTrainTracks) lua_classfunction(luaVM, "setTrainTrack", "setTrainTrack"); lua_classfunction(luaVM, "setTrainPosition", "setTrainPosition"); - lua_classfunction(luaVM, "setTrainSpeed", "setTrainSpeed"); // Reduce confusion + lua_classfunction(luaVM, "setTrainSpeed", "setTrainSpeed"); // Reduce confusion lua_classfunction(luaVM, "spawnFlyingComponent", "spawnVehicleFlyingComponent"); lua_classvariable(luaVM, "damageProof", "setVehicleDamageProof", "isVehicleDamageProof"); @@ -648,37 +648,37 @@ int CLuaVehicleDefs::GetVehicleSirenParams(lua_State* luaVM) argStream.ReadUserData(pVehicle); if (argStream.HasErrors() == false) { - tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Create a new table + tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Create a new table lua_newtable(luaVM); lua_pushstring(luaVM, "SirenCount"); lua_pushnumber(luaVM, tSirenInfo.m_ucSirenCount); - lua_settable(luaVM, -3); // End of SirenCount Property + lua_settable(luaVM, -3); // End of SirenCount Property lua_pushstring(luaVM, "SirenType"); lua_pushnumber(luaVM, tSirenInfo.m_ucSirenType); - lua_settable(luaVM, -3); // End of SirenType Property + lua_settable(luaVM, -3); // End of SirenType Property lua_pushstring(luaVM, "Flags"); lua_newtable(luaVM); lua_pushstring(luaVM, "360"); lua_pushboolean(luaVM, tSirenInfo.m_b360Flag); - lua_settable(luaVM, -3); // End of 360 Property + lua_settable(luaVM, -3); // End of 360 Property lua_pushstring(luaVM, "DoLOSCheck"); lua_pushboolean(luaVM, tSirenInfo.m_bDoLOSCheck); - lua_settable(luaVM, -3); // End of DoLOSCheck Property + lua_settable(luaVM, -3); // End of DoLOSCheck Property lua_pushstring(luaVM, "UseRandomiser"); lua_pushboolean(luaVM, tSirenInfo.m_bUseRandomiser); - lua_settable(luaVM, -3); // End of UseRandomiser Property + lua_settable(luaVM, -3); // End of UseRandomiser Property lua_pushstring(luaVM, "Silent"); lua_pushboolean(luaVM, tSirenInfo.m_bSirenSilent); - lua_settable(luaVM, -3); // End of Silent Property + lua_settable(luaVM, -3); // End of Silent Property - lua_settable(luaVM, -3); // End of Flags table + lua_settable(luaVM, -3); // End of Flags table return 1; } @@ -698,7 +698,7 @@ int CLuaVehicleDefs::GetVehicleSirens(lua_State* luaVM) argStream.ReadUserData(pVehicle); if (argStream.HasErrors() == false) { - tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Create a new table + tSirenInfo = pVehicle->m_tSirenBeaconInfo; // Create a new table lua_newtable(luaVM); for (int i = 0; i < tSirenInfo.m_ucSirenCount; i++) @@ -710,37 +710,37 @@ int CLuaVehicleDefs::GetVehicleSirens(lua_State* luaVM) lua_pushstring(luaVM, "Min_Alpha"); lua_pushnumber(luaVM, info.m_dwMinSirenAlpha); - lua_settable(luaVM, -3); // End of Min_Alpha property + lua_settable(luaVM, -3); // End of Min_Alpha property lua_pushstring(luaVM, "Red"); lua_pushnumber(luaVM, info.m_RGBBeaconColour.R); - lua_settable(luaVM, -3); // End of Red property + lua_settable(luaVM, -3); // End of Red property lua_pushstring(luaVM, "Green"); lua_pushnumber(luaVM, info.m_RGBBeaconColour.G); - lua_settable(luaVM, -3); // End of Green property + lua_settable(luaVM, -3); // End of Green property lua_pushstring(luaVM, "Blue"); lua_pushnumber(luaVM, info.m_RGBBeaconColour.B); - lua_settable(luaVM, -3); // End of Blue property + lua_settable(luaVM, -3); // End of Blue property lua_pushstring(luaVM, "Alpha"); lua_pushnumber(luaVM, info.m_RGBBeaconColour.A); - lua_settable(luaVM, -3); // End of Alpha property + lua_settable(luaVM, -3); // End of Alpha property lua_pushstring(luaVM, "x"); lua_pushnumber(luaVM, info.m_vecSirenPositions.fX); - lua_settable(luaVM, -3); // End of X property + lua_settable(luaVM, -3); // End of X property lua_pushstring(luaVM, "y"); lua_pushnumber(luaVM, info.m_vecSirenPositions.fY); - lua_settable(luaVM, -3); // End of Y property + lua_settable(luaVM, -3); // End of Y property lua_pushstring(luaVM, "z"); lua_pushnumber(luaVM, info.m_vecSirenPositions.fZ); - lua_settable(luaVM, -3); // End of Z property + lua_settable(luaVM, -3); // End of Z property - lua_settable(luaVM, -3); // End of Table + lua_settable(luaVM, -3); // End of Table } return 1; @@ -1481,7 +1481,7 @@ int CLuaVehicleDefs::GetVehiclePlateText(lua_State* luaVM) if (!argStream.HasErrors()) { - char szPlateText[9] = {0}; // 8 chars + \0 + char szPlateText[9] = {0}; // 8 chars + \0 if (CStaticFunctionDefinitions::GetVehiclePlateText(pVehicle, szPlateText)) { lua_pushstring(luaVM, szPlateText); @@ -2998,10 +2998,12 @@ int CLuaVehicleDefs::SetVehiclePlateText(lua_State* luaVM) return 1; } -bool CLuaVehicleDefs::SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, std::optional removalTime) +bool CLuaVehicleDefs::SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, + std::optional removalTime) { auto partNodeIndex = static_cast(nodeIndex); - auto collisionType = componentCollisionType.has_value() ? static_cast(componentCollisionType.value()) : eCarComponentCollisionTypes::COL_NODE_PANEL; + auto collisionType = componentCollisionType.has_value() ? static_cast(componentCollisionType.value()) + : eCarComponentCollisionTypes::COL_NODE_PANEL; if (nodeIndex < 1 || partNodeIndex >= eCarNodes::NUM_NODES) throw std::invalid_argument("Invalid component index"); @@ -3067,4 +3069,4 @@ bool CLuaVehicleDefs::SetVehicleNitroActivated(CVehicle* vehicle, bool state) no m_pPlayerManager->BroadcastOnlyJoined(CElementRPCPacket(vehicle, SET_VEHICLE_NITRO_ACTIVATED, *BitStream.pBitStream)); return true; -} \ No newline at end of file +} diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h index 38652371c00..8fb2530b6a6 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaVehicleDefs.h @@ -92,7 +92,7 @@ class CLuaVehicleDefs : public CLuaDefs LUA_DECLARE(SetVehicleRespawnRotation); LUA_DECLARE_OOP(GetVehicleRespawnPosition); LUA_DECLARE_OOP(GetVehicleRespawnRotation); - static bool IsVehicleRespawnable(CVehicle* vehicle) noexcept; + static bool IsVehicleRespawnable(CVehicle* vehicle) noexcept; static uint32_t GetVehicleRespawnDelay(CVehicle* vehicle) noexcept; static uint32_t GetVehicleIdleRespawnDelay(CVehicle* vehicle) noexcept; LUA_DECLARE(ToggleVehicleRespawn); @@ -125,7 +125,8 @@ class CLuaVehicleDefs : public CLuaDefs LUA_DECLARE(GetVehicleSirens); LUA_DECLARE(GetVehicleSirenParams); LUA_DECLARE(SetVehiclePlateText); - - static bool SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, std::optional removalTime); + + static bool SpawnVehicleFlyingComponent(CVehicle* const vehicle, std::uint8_t nodeIndex, std::optional componentCollisionType, + std::optional removalTime); static bool SetVehicleNitroActivated(CVehicle* vehicle, bool state) noexcept; }; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaVoiceDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaVoiceDefs.h index 22ec6567046..9a54ca38533 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaVoiceDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaVoiceDefs.h @@ -19,4 +19,4 @@ class CLuaVoiceDefs : public CLuaDefs LUA_DECLARE(IsVoiceEnabled); LUA_DECLARE(SetPlayerVoiceBroadcastTo); LUA_DECLARE(setPlayerVoiceIgnoreFrom); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaWaterDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaWaterDefs.h index 31a55fcb9bb..5b8e007c549 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaWaterDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaWaterDefs.h @@ -26,4 +26,4 @@ class CLuaWaterDefs : public CLuaDefs LUA_DECLARE(GetWaterColor); LUA_DECLARE(SetWaterColor); LUA_DECLARE(ResetWaterColor); -}; \ No newline at end of file +}; diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp b/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp index 181798114c7..0e7f7dc212c 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp +++ b/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.cpp @@ -16,84 +16,85 @@ void CLuaWorldDefs::LoadFunctions() { - constexpr static const std::pair functions[]{// Get - {"getTime", getTime}, - {"getWeather", getWeather}, - {"getZoneName", getZoneName}, - {"getGravity", getGravity}, - {"getGameSpeed", getGameSpeed}, - {"getWaveHeight", getWaveHeight}, - {"getFPSLimit", getFPSLimit}, - {"getMinuteDuration", getMinuteDuration}, - {"getTrafficLightState", getTrafficLightState}, - {"getJetpackMaxHeight", getJetpackMaxHeight}, - {"getSkyGradient", getSkyGradient}, - {"getHeatHaze", getHeatHaze}, - {"getJetpackWeaponEnabled", getJetpackWeaponEnabled}, - {"getCloudsEnabled", getCloudsEnabled}, - {"getInteriorSoundsEnabled", getInteriorSoundsEnabled}, - {"getRainLevel", getRainLevel}, - {"getSunSize", getSunSize}, - {"getSunColor", getSunColor}, - {"getWindVelocity", getWindVelocity}, - {"getFarClipDistance", getFarClipDistance}, - {"getFogDistance", getFogDistance}, - {"getAircraftMaxHeight", getAircraftMaxHeight}, - {"getAircraftMaxVelocity", getAircraftMaxVelocity}, - {"getOcclusionsEnabled", getOcclusionsEnabled}, - {"getMoonSize", getMoonSize}, - - // Set - {"setTime", setTime}, - {"setWeather", setWeather}, - {"setWeatherBlended", setWeatherBlended}, - {"setGravity", setGravity}, - {"setGameSpeed", setGameSpeed}, - {"setWaveHeight", setWaveHeight}, - {"setSkyGradient", setSkyGradient}, - {"setHeatHaze", setHeatHaze}, - {"setFPSLimit", setFPSLimit}, - {"setMinuteDuration", setMinuteDuration}, - {"setGarageOpen", setGarageOpen}, - {"setGlitchEnabled", setGlitchEnabled}, - {"setCloudsEnabled", setCloudsEnabled}, - {"setTrafficLightState", setTrafficLightState}, - {"setTrafficLightsLocked", setTrafficLightsLocked}, - {"setJetpackMaxHeight", setJetpackMaxHeight}, - {"setInteriorSoundsEnabled", setInteriorSoundsEnabled}, - {"setRainLevel", setRainLevel}, - {"setSunSize", setSunSize}, - {"setSunColor", setSunColor}, - {"setWindVelocity", setWindVelocity}, - {"setFarClipDistance", setFarClipDistance}, - {"setFogDistance", setFogDistance}, - {"setAircraftMaxHeight", setAircraftMaxHeight}, - {"setAircraftMaxVelocity", setAircraftMaxVelocity}, - {"setOcclusionsEnabled", setOcclusionsEnabled}, - {"setMoonSize", setMoonSize}, - {"setJetpackWeaponEnabled", setJetpackWeaponEnabled}, - {"setWorldSpecialPropertyEnabled", ArgumentParserWarn}, - - // Reset - {"resetSkyGradient", resetSkyGradient}, - {"resetHeatHaze", resetHeatHaze}, - {"resetRainLevel", resetRainLevel}, - {"resetSunSize", resetSunSize}, - {"resetSunColor", resetSunColor}, - {"resetWindVelocity", resetWindVelocity}, - {"resetFarClipDistance", resetFarClipDistance}, - {"resetFogDistance", resetFogDistance}, - {"removeWorldModel", RemoveWorldModel}, - {"restoreWorldModel", RestoreWorldModel}, - {"restoreAllWorldModels", RestoreAllWorldModels}, - {"resetMoonSize", resetMoonSize}, - {"resetWorldProperties", ArgumentParser}, - - // Check - {"isGarageOpen", isGarageOpen}, - {"isGlitchEnabled", isGlitchEnabled}, - {"isWorldSpecialPropertyEnabled", ArgumentParserWarn}, - {"areTrafficLightsLocked", areTrafficLightsLocked}}; + constexpr static const std::pair functions[]{ + // Get + {"getTime", getTime}, + {"getWeather", getWeather}, + {"getZoneName", getZoneName}, + {"getGravity", getGravity}, + {"getGameSpeed", getGameSpeed}, + {"getWaveHeight", getWaveHeight}, + {"getFPSLimit", getFPSLimit}, + {"getMinuteDuration", getMinuteDuration}, + {"getTrafficLightState", getTrafficLightState}, + {"getJetpackMaxHeight", getJetpackMaxHeight}, + {"getSkyGradient", getSkyGradient}, + {"getHeatHaze", getHeatHaze}, + {"getJetpackWeaponEnabled", getJetpackWeaponEnabled}, + {"getCloudsEnabled", getCloudsEnabled}, + {"getInteriorSoundsEnabled", getInteriorSoundsEnabled}, + {"getRainLevel", getRainLevel}, + {"getSunSize", getSunSize}, + {"getSunColor", getSunColor}, + {"getWindVelocity", getWindVelocity}, + {"getFarClipDistance", getFarClipDistance}, + {"getFogDistance", getFogDistance}, + {"getAircraftMaxHeight", getAircraftMaxHeight}, + {"getAircraftMaxVelocity", getAircraftMaxVelocity}, + {"getOcclusionsEnabled", getOcclusionsEnabled}, + {"getMoonSize", getMoonSize}, + + // Set + {"setTime", setTime}, + {"setWeather", setWeather}, + {"setWeatherBlended", setWeatherBlended}, + {"setGravity", setGravity}, + {"setGameSpeed", setGameSpeed}, + {"setWaveHeight", setWaveHeight}, + {"setSkyGradient", setSkyGradient}, + {"setHeatHaze", setHeatHaze}, + {"setFPSLimit", setFPSLimit}, + {"setMinuteDuration", setMinuteDuration}, + {"setGarageOpen", setGarageOpen}, + {"setGlitchEnabled", setGlitchEnabled}, + {"setCloudsEnabled", setCloudsEnabled}, + {"setTrafficLightState", setTrafficLightState}, + {"setTrafficLightsLocked", setTrafficLightsLocked}, + {"setJetpackMaxHeight", setJetpackMaxHeight}, + {"setInteriorSoundsEnabled", setInteriorSoundsEnabled}, + {"setRainLevel", setRainLevel}, + {"setSunSize", setSunSize}, + {"setSunColor", setSunColor}, + {"setWindVelocity", setWindVelocity}, + {"setFarClipDistance", setFarClipDistance}, + {"setFogDistance", setFogDistance}, + {"setAircraftMaxHeight", setAircraftMaxHeight}, + {"setAircraftMaxVelocity", setAircraftMaxVelocity}, + {"setOcclusionsEnabled", setOcclusionsEnabled}, + {"setMoonSize", setMoonSize}, + {"setJetpackWeaponEnabled", setJetpackWeaponEnabled}, + {"setWorldSpecialPropertyEnabled", ArgumentParserWarn}, + + // Reset + {"resetSkyGradient", resetSkyGradient}, + {"resetHeatHaze", resetHeatHaze}, + {"resetRainLevel", resetRainLevel}, + {"resetSunSize", resetSunSize}, + {"resetSunColor", resetSunColor}, + {"resetWindVelocity", resetWindVelocity}, + {"resetFarClipDistance", resetFarClipDistance}, + {"resetFogDistance", resetFogDistance}, + {"removeWorldModel", RemoveWorldModel}, + {"restoreWorldModel", RestoreWorldModel}, + {"restoreAllWorldModels", RestoreAllWorldModels}, + {"resetMoonSize", resetMoonSize}, + {"resetWorldProperties", ArgumentParser}, + + // Check + {"isGarageOpen", isGarageOpen}, + {"isGlitchEnabled", isGlitchEnabled}, + {"isWorldSpecialPropertyEnabled", ArgumentParserWarn}, + {"areTrafficLightsLocked", areTrafficLightsLocked}}; // Add functions for (const auto& [name, func] : functions) @@ -205,7 +206,7 @@ int CLuaWorldDefs::getFPSLimit(lua_State* luaVM) // int getFPSLimit () std::uint16_t fpsLimit; CStaticFunctionDefinitions::GetFPSLimit(fpsLimit); - + lua_pushnumber(luaVM, fpsLimit); return 1; } @@ -1447,7 +1448,11 @@ int CLuaWorldDefs::getOcclusionsEnabled(lua_State* luaVM) return 1; } -void CLuaWorldDefs::ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds, std::optional resetGlitches, std::optional resetJetpackWeapons) noexcept +void CLuaWorldDefs::ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, + std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds, + std::optional resetGlitches, std::optional resetJetpackWeapons) noexcept { - g_pGame->ResetWorldProperties(ResetWorldPropsInfo{resetSpecialWorldProperties.value_or(true), resetWorldProperties.value_or(true), resetWeatherProperties.value_or(true), resetLODs.value_or(true), resetSounds.value_or(true), resetGlitches.value_or(true), resetJetpackWeapons.value_or(true)}); + g_pGame->ResetWorldProperties(ResetWorldPropsInfo{resetSpecialWorldProperties.value_or(true), resetWorldProperties.value_or(true), + resetWeatherProperties.value_or(true), resetLODs.value_or(true), resetSounds.value_or(true), + resetGlitches.value_or(true), resetJetpackWeapons.value_or(true)}); } diff --git a/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h b/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h index 49032579b38..be9a0d9dce8 100644 --- a/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h +++ b/Server/mods/deathmatch/logic/luadefs/CLuaWorldDefs.h @@ -95,5 +95,7 @@ class CLuaWorldDefs : public CLuaDefs LUA_DECLARE(RestoreAllWorldModels); LUA_DECLARE(resetMoonSize); - static void ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds, std::optional resetGlitches, std::optional resetJetpackWeapons) noexcept; + static void ResetWorldProperties(std::optional resetSpecialWorldProperties, std::optional resetWorldProperties, + std::optional resetWeatherProperties, std::optional resetLODs, std::optional resetSounds, + std::optional resetGlitches, std::optional resetJetpackWeapons) noexcept; }; diff --git a/Server/mods/deathmatch/logic/net/CNetBuffer.cpp b/Server/mods/deathmatch/logic/net/CNetBuffer.cpp index d9b6401c7d1..c0e461f8ce0 100644 --- a/Server/mods/deathmatch/logic/net/CNetBuffer.cpp +++ b/Server/mods/deathmatch/logic/net/CNetBuffer.cpp @@ -102,7 +102,7 @@ namespace ms_StatsSendCmdsTotal += ms_StatsSendNumCommands; ms_StatsSendCmdsMax = std::max(ms_StatsSendCmdsMax, ms_StatsSendNumCommands); } -} // namespace +} // namespace /////////////////////////////////////////////////////////////////////////// // @@ -237,7 +237,7 @@ void CNetServerBuffer::DoPulse() shared.m_Mutex.Lock(); fSyncFPS = static_cast(shared.m_iThreadFrameCount); shared.m_iThreadFrameCount = 0; - shared.m_iuGamePlayerCount = g_pGame->GetPlayerManager()->Count(); // Also update player count here (for scaling buffer size checks) + shared.m_iuGamePlayerCount = g_pGame->GetPlayerManager()->Count(); // Also update player count here (for scaling buffer size checks) shared.m_Mutex.Unlock(); // Compress high counts @@ -1089,29 +1089,54 @@ void CNetServerBuffer::ProcessCommand(CNetJobData* pJobData) #define CALLPRE0(func) \ case TYPE_##func: \ { - #define CALLPRE(func) \ case TYPE_##func: \ { \ S##func##Args& a = *(S##func##Args*)pJobData->pArgs; -#define CALLREALNET0(func) CALLPRE0(func) m_pRealNetServer->func (); CALLPOST -#define CALLREALNET1(func,t1,n1) CALLPRE(func) m_pRealNetServer->func ( a.n1 ); CALLPOST -#define CALLREALNET2(func,t1,n1,t2,n2) CALLPRE(func) m_pRealNetServer->func ( a.n1, a.n2 ); CALLPOST -#define CALLREALNET3(func,t1,n1,t2,n2,t3,n3) CALLPRE(func) m_pRealNetServer->func ( a.n1, a.n2, a.n3 ); CALLPOST -#define CALLREALNET4(func,t1,n1,t2,n2,t3,n3,t4,n4) CALLPRE(func) m_pRealNetServer->func ( a.n1, a.n2, a.n3, a.n4 ); CALLPOST -#define CALLREALNET5(func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5) CALLPRE(func) m_pRealNetServer->func ( a.n1, a.n2, a.n3, a.n4, a.n5 ); CALLPOST -#define CALLREALNET6(func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5,t6,n6) CALLPRE(func) m_pRealNetServer->func ( a.n1, a.n2, a.n3, a.n4, a.n5, a.n6 ); CALLPOST - -#define CALLREALNET0R(ret,func) CALLPRE(func) a.result = m_pRealNetServer->func (); CALLPOST -#define CALLREALNET1R(ret,func,t1,n1) CALLPRE(func) a.result = m_pRealNetServer->func ( a.n1 ); CALLPOST -#define CALLREALNET2R(ret,func,t1,n1,t2,n2) CALLPRE(func) a.result = m_pRealNetServer->func ( a.n1, a.n2 ); CALLPOST -#define CALLREALNET3R(ret,func,t1,n1,t2,n2,t3,n3) CALLPRE(func) a.result = m_pRealNetServer->func ( a.n1, a.n2, a.n3 ); CALLPOST -#define CALLREALNET4R(ret,func,t1,n1,t2,n2,t3,n3,t4,n4) CALLPRE(func) a.result = m_pRealNetServer->func ( a.n1, a.n2, a.n3, a.n4 ); CALLPOST -#define CALLREALNET7R(ret,func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5,t6,n6,t7,n7) CALLPRE(func) a.result = m_pRealNetServer->func ( a.n1, a.n2, a.n3, a.n4, a.n5, a.n6, a.n7 ); CALLPOST +#define CALLREALNET0(func) \ + CALLPRE0(func) m_pRealNetServer->func(); \ + CALLPOST +#define CALLREALNET1(func, t1, n1) \ + CALLPRE(func) m_pRealNetServer->func(a.n1); \ + CALLPOST +#define CALLREALNET2(func, t1, n1, t2, n2) \ + CALLPRE(func) m_pRealNetServer->func(a.n1, a.n2); \ + CALLPOST +#define CALLREALNET3(func, t1, n1, t2, n2, t3, n3) \ + CALLPRE(func) m_pRealNetServer->func(a.n1, a.n2, a.n3); \ + CALLPOST +#define CALLREALNET4(func, t1, n1, t2, n2, t3, n3, t4, n4) \ + CALLPRE(func) m_pRealNetServer->func(a.n1, a.n2, a.n3, a.n4); \ + CALLPOST +#define CALLREALNET5(func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5) \ + CALLPRE(func) m_pRealNetServer->func(a.n1, a.n2, a.n3, a.n4, a.n5); \ + CALLPOST +#define CALLREALNET6(func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5, t6, n6) \ + CALLPRE(func) m_pRealNetServer->func(a.n1, a.n2, a.n3, a.n4, a.n5, a.n6); \ + CALLPOST + +#define CALLREALNET0R(ret, func) \ + CALLPRE(func) a.result = m_pRealNetServer->func(); \ + CALLPOST +#define CALLREALNET1R(ret, func, t1, n1) \ + CALLPRE(func) a.result = m_pRealNetServer->func(a.n1); \ + CALLPOST +#define CALLREALNET2R(ret, func, t1, n1, t2, n2) \ + CALLPRE(func) a.result = m_pRealNetServer->func(a.n1, a.n2); \ + CALLPOST +#define CALLREALNET3R(ret, func, t1, n1, t2, n2, t3, n3) \ + CALLPRE(func) a.result = m_pRealNetServer->func(a.n1, a.n2, a.n3); \ + CALLPOST +#define CALLREALNET4R(ret, func, t1, n1, t2, n2, t3, n3, t4, n4) \ + CALLPRE(func) a.result = m_pRealNetServer->func(a.n1, a.n2, a.n3, a.n4); \ + CALLPOST +#define CALLREALNET7R(ret, func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5, t6, n6, t7, n7) \ + CALLPRE(func) a.result = m_pRealNetServer->func(a.n1, a.n2, a.n3, a.n4, a.n5, a.n6, a.n7); \ + CALLPOST #define CALLPOST \ - break; \ + break; \ } switch (pJobData->pArgs->type) @@ -1288,10 +1313,10 @@ void CNetServerBuffer::GetQueueSizes(uint& uiFinishedList, uint& uiOutCommandQue bool CNetJobData::SetCallback(PFN_NETRESULT pfnNetResult, void* pContext) { if (callback.bSet) - return false; // One has already been set + return false; // One has already been set if (this->stage > EJobStage::RESULT) - return false; // Too late to set a callback now + return false; // Too late to set a callback now // Set new callback.pfnNetResult = pfnNetResult; diff --git a/Server/mods/deathmatch/logic/net/CNetBuffer.h b/Server/mods/deathmatch/logic/net/CNetBuffer.h index 6b62788c395..c2231860391 100644 --- a/Server/mods/deathmatch/logic/net/CNetBuffer.h +++ b/Server/mods/deathmatch/logic/net/CNetBuffer.h @@ -111,26 +111,110 @@ class CNetServerBuffer : public CNetServer virtual void SetNetOptions(const SNetOptions& options); virtual void GenerateRandomData(void* pOutData, uint uiLength); - // - // Macros of doom to declare function argument structures - // - #define DOTYPE(func) const static int TYPE_##func = __COUNTER__; - #define SETTYPE(func) type=TYPE_##func; - - #define DECLARE_FUNC_ARGS0(func) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( ) {SETTYPE(func)} }; - #define DECLARE_FUNC_ARGS1(func,t1,n1) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1 ) : n1(n1) {SETTYPE(func)} t1 n1; }; - #define DECLARE_FUNC_ARGS2(func,t1,n1,t2,n2) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2 ) : n1(n1), n2(n2) {SETTYPE(func)} t1 n1; t2 n2; }; - #define DECLARE_FUNC_ARGS3(func,t1,n1,t2,n2,t3,n3) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3 ) : n1(n1), n2(n2), n3(n3) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; }; - #define DECLARE_FUNC_ARGS4(func,t1,n1,t2,n2,t3,n3,t4,n4) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3,t4 n4 ) : n1(n1), n2(n2), n3(n3), n4(n4) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; t4 n4; }; - #define DECLARE_FUNC_ARGS5(func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3,t4 n4,t5 n5 ) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; t4 n4; t5 n5; }; - #define DECLARE_FUNC_ARGS6(func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5,t6,n6) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3,t4 n4,t5 n5,t6 n6 ) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5), n6(n6) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; t4 n4; t5 n5; t6 n6; }; - - #define DECLARE_FUNC_ARGS0R(ret,func) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( ) {SETTYPE(func)} ret result; }; - #define DECLARE_FUNC_ARGS1R(ret,func,t1,n1) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1 ) : n1(n1) {SETTYPE(func)} t1 n1; ret result; }; - #define DECLARE_FUNC_ARGS2R(ret,func,t1,n1,t2,n2) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2 ) : n1(n1), n2(n2) {SETTYPE(func)} t1 n1; t2 n2; ret result; }; - #define DECLARE_FUNC_ARGS3R(ret,func,t1,n1,t2,n2,t3,n3) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3 ) : n1(n1), n2(n2), n3(n3) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; ret result; }; - #define DECLARE_FUNC_ARGS4R(ret,func,t1,n1,t2,n2,t3,n3,t4,n4) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3,t4 n4 ) : n1(n1), n2(n2), n3(n3), n4(n4) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; t4 n4; ret result; }; - #define DECLARE_FUNC_ARGS7R(ret,func,t1,n1,t2,n2,t3,n3,t4,n4,t5,n5,t6,n6,t7,n7) DOTYPE(func) struct S##func##Args : SArgs { S##func##Args ( t1 n1,t2 n2,t3 n3,t4 n4,t5 n5,t6 n6,t7 n7 ) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5), n6(n6), n7(n7) {SETTYPE(func)} t1 n1; t2 n2; t3 n3; t4 n4; t5 n5; t6 n6; t7 n7; ret result; }; +// +// Macros of doom to declare function argument structures +// +#define DOTYPE(func) const static int TYPE_##func = __COUNTER__; +#define SETTYPE(func) type = TYPE_##func; + +#define DECLARE_FUNC_ARGS0(func) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args() { SETTYPE(func) } \ + }; +#define DECLARE_FUNC_ARGS1(func, t1, n1) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1) : n1(n1){SETTYPE(func)} t1 n1; \ + }; +#define DECLARE_FUNC_ARGS2(func, t1, n1, t2, n2) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2) : n1(n1), n2(n2){SETTYPE(func)} t1 n1; \ + t2 n2; \ + }; +#define DECLARE_FUNC_ARGS3(func, t1, n1, t2, n2, t3, n3) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3) : n1(n1), n2(n2), n3(n3){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + }; +#define DECLARE_FUNC_ARGS4(func, t1, n1, t2, n2, t3, n3, t4, n4) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3, t4 n4) : n1(n1), n2(n2), n3(n3), n4(n4){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + t4 n4; \ + }; +#define DECLARE_FUNC_ARGS5(func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3, t4 n4, t5 n5) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + t4 n4; \ + t5 n5; \ + }; +#define DECLARE_FUNC_ARGS6(func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5, t6, n6) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3, t4 n4, t5 n5, t6 n6) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5), n6(n6){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + t4 n4; \ + t5 n5; \ + t6 n6; \ + }; + +#define DECLARE_FUNC_ARGS0R(ret, func) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(){SETTYPE(func)} ret result; \ + }; +#define DECLARE_FUNC_ARGS1R(ret, func, t1, n1) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1) : n1(n1){SETTYPE(func)} t1 n1; \ + ret result; \ + }; +#define DECLARE_FUNC_ARGS2R(ret, func, t1, n1, t2, n2) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2) : n1(n1), n2(n2){SETTYPE(func)} t1 n1; \ + t2 n2; \ + ret result; \ + }; +#define DECLARE_FUNC_ARGS3R(ret, func, t1, n1, t2, n2, t3, n3) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3) : n1(n1), n2(n2), n3(n3){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + ret result; \ + }; +#define DECLARE_FUNC_ARGS4R(ret, func, t1, n1, t2, n2, t3, n3, t4, n4) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3, t4 n4) : n1(n1), n2(n2), n3(n3), n4(n4){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + t4 n4; \ + ret result; \ + }; +#define DECLARE_FUNC_ARGS7R(ret, func, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5, t6, n6, t7, n7) \ + DOTYPE(func) struct S##func##Args : SArgs \ + { \ + S##func##Args(t1 n1, t2 n2, t3 n3, t4 n4, t5 n5, t6 n6, t7 n7) : n1(n1), n2(n2), n3(n3), n4(n4), n5(n5), n6(n6), n7(n7){SETTYPE(func)} t1 n1; \ + t2 n2; \ + t3 n3; \ + t4 n4; \ + t5 n5; \ + t6 n6; \ + t7 n7; \ + ret result; \ + }; typedef NetServerPlayerID NetServerPlayerIDRef; @@ -209,7 +293,7 @@ class CNetServerBuffer : public CNetServer std::list m_OutCommandQueue; std::list m_OutResultQueue; std::list m_InResultQueue; - std::set m_FinishedList; // Result has been used, will be deleted next pulse (shared access with watchdog thread) + std::set m_FinishedList; // Result has been used, will be deleted next pulse (shared access with watchdog thread) CComboMutex m_Mutex; CNetBufferWatchDog* m_pWatchDog; int m_iThreadFrameCount; diff --git a/Server/mods/deathmatch/logic/net/CSimBulletsyncPacket.cpp b/Server/mods/deathmatch/logic/net/CSimBulletsyncPacket.cpp index 25c6c6f3542..1d5c4735e95 100644 --- a/Server/mods/deathmatch/logic/net/CSimBulletsyncPacket.cpp +++ b/Server/mods/deathmatch/logic/net/CSimBulletsyncPacket.cpp @@ -12,7 +12,9 @@ #include "CPickupManager.h" #include "CWeaponStatManager.h" -CSimBulletsyncPacket::CSimBulletsyncPacket(ElementID id) : m_id(id) {} +CSimBulletsyncPacket::CSimBulletsyncPacket(ElementID id) : m_id(id) +{ +} bool CSimBulletsyncPacket::Read(NetBitStreamInterface& stream) { diff --git a/Server/mods/deathmatch/logic/net/CSimControl.cpp b/Server/mods/deathmatch/logic/net/CSimControl.cpp index 36b4c67cf10..428f7fd6f2c 100644 --- a/Server/mods/deathmatch/logic/net/CSimControl.cpp +++ b/Server/mods/deathmatch/logic/net/CSimControl.cpp @@ -21,7 +21,7 @@ namespace bool ms_bEnableRequest = false; CNetServerBuffer* ms_pNetServerBuffer = NULL; CSimPlayerManager* ms_pSimPlayerManager = NULL; -} // namespace +} // namespace /////////////////////////////////////////////////////////////// // diff --git a/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.cpp b/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.cpp index d426bf54fe7..3a4ee1c4fec 100644 --- a/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.cpp +++ b/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.cpp @@ -64,11 +64,11 @@ bool CSimKeysyncPacket::Read(NetBitStreamInterface& BitStream) if (m_ucPlayerGotWeaponType != ucClientWeaponType) { - bWeaponCorrect = false; // Possibly old weapon data. - ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data + bWeaponCorrect = false; // Possibly old weapon data. + ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data } - m_Cache.bWeaponCorrect = bWeaponCorrect; // Copied from PlayerPuresyncPacket + m_Cache.bWeaponCorrect = bWeaponCorrect; // Copied from PlayerPuresyncPacket // Read out the current weapon slot and set it SWeaponSlotSync slot; @@ -168,7 +168,7 @@ bool CSimKeysyncPacket::Write(NetBitStreamInterface& BitStream) const if (m_sharedControllerState.ButtonCircle || (m_sharedControllerState.RightShoulder1)) { // Write his current weapon slot - unsigned int uiSlot = m_Cache.ucWeaponSlot; // check m_Cache.bWeaponCorrect ! + unsigned int uiSlot = m_Cache.ucWeaponSlot; // check m_Cache.bWeaponCorrect ! SWeaponSlotSync slot; slot.data.uiSlot = uiSlot; BitStream.Write(&slot); diff --git a/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.h b/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.h index ad22f144d04..3b3f6cf6518 100644 --- a/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.h +++ b/Server/mods/deathmatch/logic/net/CSimKeysyncPacket.h @@ -43,10 +43,10 @@ class CSimKeysyncPacket : public CSimPacket SKeysyncFlags flags; bool bWeaponCorrect; - uchar ucWeaponSlot; // Only valid if bWeaponCorrect - ushort usAmmoInClip; // Only valid if bWeaponCorrect + uchar ucWeaponSlot; // Only valid if bWeaponCorrect + ushort usAmmoInClip; // Only valid if bWeaponCorrect - float fAimDirection; // Only valid if bWeaponCorrect + float fAimDirection; // Only valid if bWeaponCorrect CVector vecSniperSource; CVector vecTargetting; diff --git a/Server/mods/deathmatch/logic/net/CSimPlayer.h b/Server/mods/deathmatch/logic/net/CSimPlayer.h index 7519c140706..16885e303a0 100644 --- a/Server/mods/deathmatch/logic/net/CSimPlayer.h +++ b/Server/mods/deathmatch/logic/net/CSimPlayer.h @@ -39,11 +39,11 @@ class CSimPlayer unsigned short m_usBitStreamVersion; NetServerPlayerID m_PlayerSocket; std::vector m_PuresyncSendListFlat; - std::multimap m_PuresyncSendListGrouped; // Send list grouped by bitstream version + std::multimap m_PuresyncSendListGrouped; // Send list grouped by bitstream version bool m_bSendListChanged; bool m_bHasOccupiedVehicle; bool m_bIsExitingVehicle; - CControllerState m_sharedControllerState; // Updated by CSim*Packet code + CControllerState m_sharedControllerState; // Updated by CSim*Packet code // Used in CSimPlayerPuresyncPacket and CSimVehiclePuresyncPacket ElementID m_PlayerID; diff --git a/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp b/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp index 24afdac00e6..e0f1e63113b 100644 --- a/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp +++ b/Server/mods/deathmatch/logic/net/CSimPlayerManager.cpp @@ -41,7 +41,7 @@ /////////////////////////////////////////////////////////////////////////// void CSimPlayerManager::AddSimPlayer(CPlayer* pPlayer) { - LockSimSystem(); // Prevent any sim activity on the sync thread + LockSimSystem(); // Prevent any sim activity on the sync thread // Create CSimPlayer* pSim = new CSimPlayer(); @@ -72,7 +72,7 @@ void CSimPlayerManager::AddSimPlayer(CPlayer* pPlayer) /////////////////////////////////////////////////////////////////////////// void CSimPlayerManager::RemoveSimPlayer(CPlayer* pPlayer) { - LockSimSystem(); // Prevent any sim activity on the sync thread + LockSimSystem(); // Prevent any sim activity on the sync thread // Check assert(pPlayer->m_pSimPlayer->m_pRealPlayer == pPlayer); @@ -110,7 +110,7 @@ void CSimPlayerManager::RemoveSimPlayer(CPlayer* pPlayer) /////////////////////////////////////////////////////////////////////////// void CSimPlayerManager::UpdateSimPlayer(CPlayer* pPlayer) { - LockSimSystem(); // TODO - only lock the CSimPlayer + LockSimSystem(); // TODO - only lock the CSimPlayer // Get matching sim player CSimPlayer* pSim = pPlayer->m_pSimPlayer; @@ -162,7 +162,7 @@ void CSimPlayerManager::UpdateSimPlayer(CPlayer* pPlayer) if (pSendSimPlayer && pSendSimPlayer->m_bDoneFirstUpdate) pSim->m_PuresyncSendListFlat.push_back(pSendSimPlayer); else - pPlayer->m_bPureSyncSimSendListDirty = true; // Retry next time + pPlayer->m_bPureSyncSimSendListDirty = true; // Retry next time } } @@ -228,7 +228,7 @@ bool CSimPlayerManager::HandlePlayerPureSync(const NetServerPlayerID& Socket, Ne if (!CNetBufferWatchDog::CanSendPacket(PACKET_ID_PLAYER_PURESYNC)) return true; - LockSimSystem(); // Prevent player additions and deletions + LockSimSystem(); // Prevent player additions and deletions // Grab the source player CSimPlayer* pSourceSimPlayer = Get(Socket); @@ -266,7 +266,7 @@ bool CSimPlayerManager::HandleVehiclePureSync(const NetServerPlayerID& Socket, N if (!CNetBufferWatchDog::CanSendPacket(PACKET_ID_PLAYER_VEHICLE_PURESYNC)) return true; - LockSimSystem(); // Prevent player additions and deletions + LockSimSystem(); // Prevent player additions and deletions // Grab the source player CSimPlayer* pSourceSimPlayer = Get(Socket); @@ -305,7 +305,7 @@ bool CSimPlayerManager::HandleKeySync(const NetServerPlayerID& Socket, NetBitStr if (!CNetBufferWatchDog::CanSendPacket(PACKET_ID_PLAYER_KEYSYNC)) return true; - LockSimSystem(); // Prevent player additions and deletions + LockSimSystem(); // Prevent player additions and deletions // Grab the source player CSimPlayer* pSourceSimPlayer = Get(Socket); @@ -378,7 +378,7 @@ bool CSimPlayerManager::HandlePedTaskPacket(const NetServerPlayerID& Socket, Net if (!CNetBufferWatchDog::CanSendPacket(PACKET_ID_PED_TASK)) return true; - LockSimSystem(); // Prevent player additions and deletions + LockSimSystem(); // Prevent player additions and deletions // Grab the source player CSimPlayer* pSourceSimPlayer = Get(Socket); diff --git a/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.cpp b/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.cpp index 8542cb4793a..69f2f5e3e69 100644 --- a/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.cpp +++ b/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.cpp @@ -115,8 +115,8 @@ bool CSimPlayerPuresyncPacket::Read(NetBitStreamInterface& BitStream) if (m_PlayerGotWeaponType != ucClientWeaponType) { - bWeaponCorrect = false; // Possibly old weapon data. - ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data + bWeaponCorrect = false; // Possibly old weapon data. + ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data } // Update check counts @@ -231,7 +231,7 @@ bool CSimPlayerPuresyncPacket::Write(NetBitStreamInterface& BitStream) const if (m_Cache.flags.data.bHasAWeapon) { - unsigned int uiSlot = m_Cache.ucWeaponSlot; // check m_Cache.bWeaponCorrect ! + unsigned int uiSlot = m_Cache.ucWeaponSlot; // check m_Cache.bWeaponCorrect ! SWeaponSlotSync slot; slot.data.uiSlot = uiSlot; BitStream.Write(&slot); diff --git a/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.h b/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.h index a3132568f71..aba98cb7572 100644 --- a/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.h +++ b/Server/mods/deathmatch/logic/net/CSimPlayerPuresyncPacket.h @@ -73,13 +73,13 @@ class CSimPlayerPuresyncPacket : public CSimPacket CVector vecCamFwd; bool bWeaponCorrect; - uchar ucWeaponSlot; // Only valid if bWeaponCorrect - ushort usAmmoInClip; // Only valid if bWeaponCorrect - ushort usTotalAmmo; // Only valid if bWeaponCorrect + uchar ucWeaponSlot; // Only valid if bWeaponCorrect + ushort usAmmoInClip; // Only valid if bWeaponCorrect + ushort usTotalAmmo; // Only valid if bWeaponCorrect bool bIsAimFull; - float fAimDirection; // Only valid if bWeaponCorrect - CVector vecSniperSource; // Only valid if bWeaponCorrect and bIsAimFull - CVector vecTargetting; // Only valid if bWeaponCorrect and bIsAimFull + float fAimDirection; // Only valid if bWeaponCorrect + CVector vecSniperSource; // Only valid if bWeaponCorrect and bIsAimFull + CVector vecTargetting; // Only valid if bWeaponCorrect and bIsAimFull } m_Cache; }; diff --git a/Server/mods/deathmatch/logic/net/CSimVehiclePuresyncPacket.h b/Server/mods/deathmatch/logic/net/CSimVehiclePuresyncPacket.h index a05385cb6d0..0446ca52b3e 100644 --- a/Server/mods/deathmatch/logic/net/CSimVehiclePuresyncPacket.h +++ b/Server/mods/deathmatch/logic/net/CSimVehiclePuresyncPacket.h @@ -69,7 +69,7 @@ class CSimVehiclePuresyncPacket : public CSimPacket CVector vecCamPosition; CVector vecCamFwd; - CVector VehPosition; // Same as PlrPosition ? + CVector VehPosition; // Same as PlrPosition ? CVector VehRotationDeg; CVector BothVelocity; CVector VehTurnSpeed; diff --git a/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.cpp index 53bf77831ee..a185a2d892b 100644 --- a/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.cpp @@ -18,13 +18,7 @@ #include "CWeaponNames.h" CBulletsyncPacket::CBulletsyncPacket(CPlayer* player) - : m_weapon(WEAPONTYPE_UNARMED) - , m_start() - , m_end() - , m_order(0) - , m_damage(0.0f) - , m_zone(0) - , m_damaged(INVALID_ELEMENT_ID) + : m_weapon(WEAPONTYPE_UNARMED), m_start(), m_end(), m_order(0), m_damage(0.0f), m_zone(0), m_damaged(INVALID_ELEMENT_ID) { m_pSourceElement = player; } @@ -33,16 +27,16 @@ bool CBulletsyncPacket::IsValidVector(const CVector& vec) noexcept { if (!vec.IsValid()) return false; - + if (IsNaN(vec.fX)) return false; - + if (IsNaN(vec.fY)) return false; - + if (IsNaN(vec.fZ)) return false; - + return true; } @@ -56,9 +50,9 @@ bool CBulletsyncPacket::ValidateTrajectory() const noexcept const float dx = m_end.fX - m_start.fX; const float dy = m_end.fY - m_start.fY; const float dz = m_end.fZ - m_start.fZ; - + const float movementSq = (dx * dx) + (dy * dy) + (dz * dz); - + if (IsNaN(movementSq)) return false; @@ -67,7 +61,7 @@ bool CBulletsyncPacket::ValidateTrajectory() const noexcept if (movementSq > MAX_DISTANCE_SQ) return false; - + return true; } @@ -91,19 +85,19 @@ bool CBulletsyncPacket::ReadWeaponAndPositions(NetBitStreamInterface& stream) if (!stream.Read(reinterpret_cast(&m_start), sizeof(CVector))) return false; - + if (!stream.Read(reinterpret_cast(&m_end), sizeof(CVector))) return false; - + if (!IsValidVector(m_start)) return false; if (!IsValidVector(m_end)) return false; - + if (!ValidateTrajectory()) return false; - + return true; } @@ -124,19 +118,19 @@ bool CBulletsyncPacket::ReadOptionalDamage(NetBitStreamInterface& stream) ResetDamageData(); return false; } - + if (m_damage < 0.0f || m_damage > MAX_DAMAGE) { ResetDamageData(); return false; } - + if (m_zone > MAX_BODY_ZONE) { ResetDamageData(); return false; } - + if (m_damaged == 0) { ResetDamageData(); @@ -155,7 +149,7 @@ bool CBulletsyncPacket::ReadOptionalDamage(NetBitStreamInterface& stream) } // Element exists } - + return true; } @@ -163,7 +157,7 @@ bool CBulletsyncPacket::Read(NetBitStreamInterface& stream) { if (!m_pSourceElement) return false; - + CPlayer* pPlayer = static_cast(m_pSourceElement); if (pPlayer) { @@ -173,11 +167,11 @@ bool CBulletsyncPacket::Read(NetBitStreamInterface& stream) // Check player position is reasonable relative to bullet start const CVector& playerPos = pPlayer->GetPosition(); - const float maxShootDistance = 50.0f; // Max distance from player to bullet start - + const float maxShootDistance = 50.0f; // Max distance from player to bullet start + // This check will be done after we read positions } - + if (!ReadWeaponAndPositions(stream)) return false; @@ -185,31 +179,31 @@ bool CBulletsyncPacket::Read(NetBitStreamInterface& stream) if (pPlayer) { const CVector& playerPos = pPlayer->GetPosition(); - float dx = m_start.fX - playerPos.fX; - float dy = m_start.fY - playerPos.fY; - float dz = m_start.fZ - playerPos.fZ; - float distSq = dx * dx + dy * dy + dz * dz; - + float dx = m_start.fX - playerPos.fX; + float dy = m_start.fY - playerPos.fY; + float dz = m_start.fZ - playerPos.fZ; + float distSq = dx * dx + dy * dy + dz * dz; + // Allow larger distance if player is in vehicle (vehicle guns like Hunter have offsets of ~5m, // plus vehicle size, plus network lag compensation) const float maxShootDistanceSq = pPlayer->GetOccupiedVehicle() ? (100.0f * 100.0f) : (50.0f * 50.0f); if (distSq > maxShootDistanceSq) return false; - + // Check if player has this weapon if (!pPlayer->HasWeaponType(static_cast(m_weapon))) return false; - + // Check if weapon has ammo const auto type = static_cast(m_weapon); const auto slot = CWeaponNames::GetSlotFromWeapon(type); if (pPlayer->GetWeaponTotalAmmo(slot) <= 0) return false; } - + if (!stream.Read(m_order)) return false; - + if (!ReadOptionalDamage(stream)) return false; @@ -226,7 +220,7 @@ bool CBulletsyncPacket::Write(NetBitStreamInterface& stream) const return false; const ElementID id = pPlayer->GetID(); - + if (id == INVALID_ELEMENT_ID) return false; @@ -238,7 +232,7 @@ bool CBulletsyncPacket::Write(NetBitStreamInterface& stream) const if (!IsValidVector(m_end)) return false; - + if (!ValidateTrajectory()) return false; @@ -254,7 +248,7 @@ bool CBulletsyncPacket::Write(NetBitStreamInterface& stream) const const bool hasDamage = (m_damage > EPSILON) && (m_damaged != INVALID_ELEMENT_ID); stream.WriteBit(hasDamage); - + if (hasDamage) { stream.Write(m_damage); diff --git a/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.h b/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.h index 7e189c290e4..0f46f8e9646 100644 --- a/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CBulletsyncPacket.h @@ -20,13 +20,13 @@ class CBulletsyncPacket final : public CPacket { public: - static constexpr float MIN_DISTANCE_SQ = 0.0001f; - static constexpr float MAX_DISTANCE_SQ = 160000.0f; - static constexpr float EPSILON = 0.0001f; - static constexpr float EPSILON_SQ = EPSILON * EPSILON; + static constexpr float MIN_DISTANCE_SQ = 0.0001f; + static constexpr float MAX_DISTANCE_SQ = 160000.0f; + static constexpr float EPSILON = 0.0001f; + static constexpr float EPSILON_SQ = EPSILON * EPSILON; static constexpr unsigned char MAX_BODY_ZONE = 9; - static constexpr float MAX_DAMAGE = 200.0f; - + static constexpr float MAX_DAMAGE = 200.0f; + CBulletsyncPacket() = default; explicit CBulletsyncPacket(class CPlayer* player); @@ -42,10 +42,10 @@ class CBulletsyncPacket final : public CPacket bool ReadOptionalDamage(NetBitStreamInterface& stream); bool ValidateTrajectory() const noexcept; void ResetDamageData() noexcept; - + static constexpr bool IsNaN(float value) noexcept { return value != value; } - static bool IsValidVector(const CVector& vec) noexcept; - static bool IsValidWeaponId(unsigned char weaponId) noexcept; + static bool IsValidVector(const CVector& vec) noexcept; + static bool IsValidWeaponId(unsigned char weaponId) noexcept; public: eWeaponType m_weapon{}; @@ -57,4 +57,4 @@ class CBulletsyncPacket final : public CPacket ElementID m_damaged{INVALID_ELEMENT_ID}; }; -#endif // __CBULLETSYNCPACKET_H \ No newline at end of file +#endif // __CBULLETSYNCPACKET_H diff --git a/Server/mods/deathmatch/logic/packets/CChatClearPacket.h b/Server/mods/deathmatch/logic/packets/CChatClearPacket.h index b85cf2012e4..de68b520313 100644 --- a/Server/mods/deathmatch/logic/packets/CChatClearPacket.h +++ b/Server/mods/deathmatch/logic/packets/CChatClearPacket.h @@ -16,7 +16,7 @@ class CChatClearPacket final : public CPacket { public: - CChatClearPacket(){}; + CChatClearPacket() {}; // Chat uses low priority channel to avoid getting queued behind large map downloads #6877 ePacketID GetPacketID() const { return PACKET_ID_CHAT_CLEAR; }; diff --git a/Server/mods/deathmatch/logic/packets/CChatEchoPacket.h b/Server/mods/deathmatch/logic/packets/CChatEchoPacket.h index 7abf8aa279a..0d65f611bb1 100644 --- a/Server/mods/deathmatch/logic/packets/CChatEchoPacket.h +++ b/Server/mods/deathmatch/logic/packets/CChatEchoPacket.h @@ -14,13 +14,13 @@ #include "CPacket.h" #include "../../Config.h" -#define CHATCOLOR_SAY 235, 221, 178 -#define CHATCOLOR_TEAMSAY 235, 221, 178 -#define CHATCOLOR_MESSAGE 255, 168, 0 -#define CHATCOLOR_INFO 255, 100, 100 -#define CHATCOLOR_ME 255, 0, 255 -#define CHATCOLOR_ADMINSAY 131, 205, 241 -#define CHATCOLOR_CONSOLESAY 223, 149, 232 +#define CHATCOLOR_SAY 235, 221, 178 +#define CHATCOLOR_TEAMSAY 235, 221, 178 +#define CHATCOLOR_MESSAGE 255, 168, 0 +#define CHATCOLOR_INFO 255, 100, 100 +#define CHATCOLOR_ME 255, 0, 255 +#define CHATCOLOR_ADMINSAY 131, 205, 241 +#define CHATCOLOR_CONSOLESAY 223, 149, 232 enum eMessageType { diff --git a/Server/mods/deathmatch/logic/packets/CDebugEchoPacket.h b/Server/mods/deathmatch/logic/packets/CDebugEchoPacket.h index 83cea1181dd..8cb7783a54a 100644 --- a/Server/mods/deathmatch/logic/packets/CDebugEchoPacket.h +++ b/Server/mods/deathmatch/logic/packets/CDebugEchoPacket.h @@ -14,9 +14,9 @@ #include "CPacket.h" #include "../../Config.h" -#define DEBUGCOLOR_WARNING 255, 128, 0 -#define DEBUGCOLOR_ERROR 255, 0, 0 -#define DEBUGCOLOR_INFO 0, 255, 0 +#define DEBUGCOLOR_WARNING 255, 128, 0 +#define DEBUGCOLOR_ERROR 255, 0, 0 +#define DEBUGCOLOR_INFO 0, 255, 0 class CDebugEchoPacket final : public CPacket { diff --git a/Server/mods/deathmatch/logic/packets/CElementRPCPacket.h b/Server/mods/deathmatch/logic/packets/CElementRPCPacket.h index c99ede97e65..d87d1facc50 100644 --- a/Server/mods/deathmatch/logic/packets/CElementRPCPacket.h +++ b/Server/mods/deathmatch/logic/packets/CElementRPCPacket.h @@ -17,7 +17,7 @@ class CElementRPCPacket final : public CPacket { public: CElementRPCPacket(CElement* pSourceElement, unsigned char ucActionID, NetBitStreamInterface& BitStream) - : m_ucActionID(ucActionID), m_BitStream(BitStream), m_pSourceElement(pSourceElement){}; + : m_ucActionID(ucActionID), m_BitStream(BitStream), m_pSourceElement(pSourceElement) {}; ePacketID GetPacketID() const { return PACKET_ID_LUA_ELEMENT_RPC; }; unsigned long GetFlags() const { return PACKET_HIGH_PRIORITY | PACKET_RELIABLE | PACKET_SEQUENCED; }; diff --git a/Server/mods/deathmatch/logic/packets/CEntityAddPacket.cpp b/Server/mods/deathmatch/logic/packets/CEntityAddPacket.cpp index f87a776f1ea..9d72afb0247 100644 --- a/Server/mods/deathmatch/logic/packets/CEntityAddPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CEntityAddPacket.cpp @@ -217,7 +217,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Position position.data.vecPosition = pObject->GetPosition(); - SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients + SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Rotation @@ -266,7 +266,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Scale const CVector& vecScale = pObject->GetScale(); - bool bIsUniform = (vecScale.fX == vecScale.fY && vecScale.fX == vecScale.fZ); + bool bIsUniform = (vecScale.fX == vecScale.fY && vecScale.fX == vecScale.fZ); BitStream.WriteBit(bIsUniform); if (bIsUniform) { @@ -301,7 +301,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const { CCustomWeapon* pWeapon = static_cast(pElement); unsigned char targetType = pWeapon->GetTargetType(); - BitStream.WriteBits(&targetType, 3); // 3 bits = 4 possible values. + BitStream.WriteBits(&targetType, 3); // 3 bits = 4 possible values. switch (targetType) { @@ -319,12 +319,12 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const { // Send full unsigned char... bone documentation looks scarce. unsigned char ucSubTarget = pWeapon->GetTargetBone(); - BitStream.Write(ucSubTarget); // Send the entire unsigned char as there are a lot of bones. + BitStream.Write(ucSubTarget); // Send the entire unsigned char as there are a lot of bones. } else if (IS_VEHICLE(pTarget)) { auto ucSubTarget = static_cast(pWeapon->GetTargetWheel()); - BitStream.WriteBits(&ucSubTarget, 4); // 4 bits = 8 possible values. + BitStream.WriteBits(&ucSubTarget, 4); // 4 bits = 8 possible values. } break; } @@ -344,7 +344,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const float fAccuracy = pWeaponStat->GetAccuracy(); float fTargetRange = pWeaponStat->GetTargetRange(); float fWeaponRange = pWeaponStat->GetWeaponRange(); - BitStream.WriteBits(&usDamage, 12); // 12 bits = 2048 values... plenty. + BitStream.WriteBits(&usDamage, 12); // 12 bits = 2048 values... plenty. BitStream.Write(fAccuracy); BitStream.Write(fTargetRange); BitStream.Write(fWeaponRange); @@ -365,11 +365,11 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const BitStream.WriteBit(weaponConfig.flags.bSeeThroughStuff); BitStream.WriteBit(weaponConfig.flags.bShootThroughStuff); - auto usAmmo = static_cast(pWeapon->GetAmmo()); - auto usClipAmmo = static_cast(pWeapon->GetAmmo()); - ElementID OwnerID = pWeapon->GetOwner() == NULL ? INVALID_ELEMENT_ID : pWeapon->GetOwner()->GetID(); - unsigned char ucWeaponState = pWeapon->GetWeaponState(); - BitStream.WriteBits(&ucWeaponState, 4); // 4 bits = 8 possible values for weapon state + auto usAmmo = static_cast(pWeapon->GetAmmo()); + auto usClipAmmo = static_cast(pWeapon->GetAmmo()); + ElementID OwnerID = pWeapon->GetOwner() == NULL ? INVALID_ELEMENT_ID : pWeapon->GetOwner()->GetID(); + unsigned char ucWeaponState = pWeapon->GetWeaponState(); + BitStream.WriteBits(&ucWeaponState, 4); // 4 bits = 8 possible values for weapon state BitStream.Write(usAmmo); BitStream.Write(usClipAmmo); BitStream.Write(OwnerID); @@ -384,7 +384,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Position position.data.vecPosition = pPickup->GetPosition(); - SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients + SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Grab the model and write it @@ -686,7 +686,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Position position.data.vecPosition = pMarker->GetPosition(); - SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients + SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Type @@ -772,13 +772,13 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Write the position SPosition2DSync position2D(false); position2D.data.vecPosition = pArea->GetPosition(); - SilentlyFixIndeterminate(position2D.data.vecPosition); // Crash fix for pre r6459 clients + SilentlyFixIndeterminate(position2D.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position2D); // Write the size SPosition2DSync size2D(false); size2D.data.vecPosition = pArea->GetSize(); - SilentlyFixIndeterminate(size2D.data.vecPosition); // Crash fix for pre r6459 clients + SilentlyFixIndeterminate(size2D.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&size2D); // And the color @@ -953,7 +953,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const // Animation const SPlayerAnimData& animData = pPed->GetAnimationData(); - bool animRunning = animData.IsAnimating(); + bool animRunning = animData.IsAnimating(); BitStream.WriteBit(animRunning); if (animRunning) @@ -1129,7 +1129,7 @@ bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const BitStream.WriteCompressed(pBuilding->GetInterior()); CBuilding* pLowLodBuilding = pBuilding->GetLowLodElement(); - ElementID lowLodBuildingID = pLowLodBuilding ? pLowLodBuilding->GetID() : INVALID_ELEMENT_ID; + ElementID lowLodBuildingID = pLowLodBuilding ? pLowLodBuilding->GetID() : INVALID_ELEMENT_ID; BitStream.Write(lowLodBuildingID); break; } diff --git a/Server/mods/deathmatch/logic/packets/CKeysyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CKeysyncPacket.cpp index ada913b451a..bc9ce7f116c 100644 --- a/Server/mods/deathmatch/logic/packets/CKeysyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CKeysyncPacket.cpp @@ -70,8 +70,8 @@ bool CKeysyncPacket::Read(NetBitStreamInterface& BitStream) if (pSourcePlayer->GetWeaponType() != ucClientWeaponType) { - bWeaponCorrect = false; // Possibly old weapon data. - ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data + bWeaponCorrect = false; // Possibly old weapon data. + ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data } // Read out the current weapon slot and set it @@ -131,7 +131,7 @@ bool CKeysyncPacket::Read(NetBitStreamInterface& BitStream) { ReadVehicleSpecific(pVehicle, BitStream); - if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? + if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? { short sRightStickX, sRightStickY; if (!BitStream.Read(sRightStickX) || !BitStream.Read(sRightStickY)) @@ -235,7 +235,7 @@ bool CKeysyncPacket::Write(NetBitStreamInterface& BitStream) const { WriteVehicleSpecific(pVehicle, BitStream); - if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? + if (pVehicle->GetUpgrades()->HasUpgrade(1087)) // Hydraulics? { BitStream.Write(ControllerState.RightStickX); BitStream.Write(ControllerState.RightStickY); diff --git a/Server/mods/deathmatch/logic/packets/CKeysyncPacket.h b/Server/mods/deathmatch/logic/packets/CKeysyncPacket.h index 7d555d6d210..f02ba6cc48b 100644 --- a/Server/mods/deathmatch/logic/packets/CKeysyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CKeysyncPacket.h @@ -17,7 +17,7 @@ class CKeysyncPacket final : public CPacket { public: - CKeysyncPacket(){}; + CKeysyncPacket() {}; CKeysyncPacket(class CPlayer* pPlayer); bool HasSimHandler() const { return true; } diff --git a/Server/mods/deathmatch/logic/packets/CLuaEventPacket.cpp b/Server/mods/deathmatch/logic/packets/CLuaEventPacket.cpp index e0e80c48b41..a3d3a9f11f6 100644 --- a/Server/mods/deathmatch/logic/packets/CLuaEventPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CLuaEventPacket.cpp @@ -22,7 +22,7 @@ CLuaEventPacket::CLuaEventPacket(const char* szName, ElementID ID, CLuaArguments { m_strName.AssignLeft(szName, MAX_EVENT_NAME_LENGTH); m_ElementID = ID; - m_pArguments = pArguments; // Use a pointer to save copying the arguments + m_pArguments = pArguments; // Use a pointer to save copying the arguments } bool CLuaEventPacket::Read(NetBitStreamInterface& BitStream) diff --git a/Server/mods/deathmatch/logic/packets/CLuaPacket.h b/Server/mods/deathmatch/logic/packets/CLuaPacket.h index 384c9973de5..ad319000c6b 100644 --- a/Server/mods/deathmatch/logic/packets/CLuaPacket.h +++ b/Server/mods/deathmatch/logic/packets/CLuaPacket.h @@ -16,7 +16,7 @@ class CLuaPacket final : public CPacket { public: - CLuaPacket(unsigned char ucActionID, NetBitStreamInterface& BitStream) : m_ucActionID(ucActionID), m_BitStream(BitStream){}; + CLuaPacket(unsigned char ucActionID, NetBitStreamInterface& BitStream) : m_ucActionID(ucActionID), m_BitStream(BitStream) {}; ePacketID GetPacketID() const { return PACKET_ID_LUA; }; unsigned long GetFlags() const { return PACKET_HIGH_PRIORITY | PACKET_RELIABLE | PACKET_SEQUENCED; }; diff --git a/Server/mods/deathmatch/logic/packets/CMapInfoPacket.h b/Server/mods/deathmatch/logic/packets/CMapInfoPacket.h index f4583cc3c20..9425a0687e6 100644 --- a/Server/mods/deathmatch/logic/packets/CMapInfoPacket.h +++ b/Server/mods/deathmatch/logic/packets/CMapInfoPacket.h @@ -32,12 +32,12 @@ class CMapInfoPacket final : public CPacket float fWaveHeight, const SWorldWaterLevelInfo& worldWaterLevelInfo, bool bHasSkyGradient, const SGarageStates& garageStates, unsigned char ucSkyGradientTR, unsigned char ucSkyGradientTG, unsigned char ucSkyGradientTB, unsigned char ucSkyGradientBR, unsigned char ucSkyGradientBG, unsigned char ucSkyGradientBB, bool bHasHeatHaze, const SHeatHazeSettings& heatHazeSettings, - unsigned short fps = FPSLimits::FPS_MIN, bool bCloudsEnabled = true, float fJetpackMaxHeight = 100, bool bOverrideWaterColor = false, - unsigned char ucWaterRed = 0, unsigned char ucWaterGreen = 0, unsigned char ucWaterBlue = 0, unsigned char ucWaterAlpha = 0, - bool bInteriorSoundsEnabled = true, bool bOverrideRainLevel = false, float fRainLevel = 0, bool bOverrideSunSize = false, - float fSunSize = 0, bool bOverrideSunColor = false, unsigned char ucSunCoreR = 0, unsigned char ucSunCoreG = 0, - unsigned char ucSunCoreB = 0, unsigned char ucSunCoronaR = 0, unsigned char ucSunCoronaG = 0, unsigned char ucSunCoronaB = 0, - bool bOverrideWindVelocity = false, float fWindVelX = 0, float fWindVelY = 0, float fWindVelZ = 0, + unsigned short fps = FPSLimits::FPS_MIN, bool bCloudsEnabled = true, float fJetpackMaxHeight = 100, + bool bOverrideWaterColor = false, unsigned char ucWaterRed = 0, unsigned char ucWaterGreen = 0, unsigned char ucWaterBlue = 0, + unsigned char ucWaterAlpha = 0, bool bInteriorSoundsEnabled = true, bool bOverrideRainLevel = false, float fRainLevel = 0, + bool bOverrideSunSize = false, float fSunSize = 0, bool bOverrideSunColor = false, unsigned char ucSunCoreR = 0, + unsigned char ucSunCoreG = 0, unsigned char ucSunCoreB = 0, unsigned char ucSunCoronaR = 0, unsigned char ucSunCoronaG = 0, + unsigned char ucSunCoronaB = 0, bool bOverrideWindVelocity = false, float fWindVelX = 0, float fWindVelY = 0, float fWindVelZ = 0, bool bOverrideFarClipDistance = false, float fFarClip = 0, bool bOverrideFogDistance = false, float fFogDistance = 0, float fAircraftMaxHeight = 800, float fAircraftMaxVelocity = 1.5f, bool bOverrideMoonSize = false, int iMoonSize = 3); diff --git a/Server/mods/deathmatch/logic/packets/CPacket.h b/Server/mods/deathmatch/logic/packets/CPacket.h index 93c466e74f4..455e9a1c418 100644 --- a/Server/mods/deathmatch/logic/packets/CPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPacket.h @@ -35,7 +35,7 @@ class CPacket { public: CPacket(); - virtual ~CPacket(){}; + virtual ~CPacket() {}; virtual bool RequiresSourcePlayer() const { return true; } virtual bool HasSimHandler() const { return false; } diff --git a/Server/mods/deathmatch/logic/packets/CPedSyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CPedSyncPacket.cpp index 453da054198..54679c1da42 100644 --- a/Server/mods/deathmatch/logic/packets/CPedSyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CPedSyncPacket.cpp @@ -43,7 +43,7 @@ bool CPedSyncPacket::Read(NetBitStreamInterface& BitStream) // Did we recieve position? if (ucFlags & 0x01) - { + { if (!Data.ReadSpatialData(BitStream)) return false; } @@ -150,21 +150,21 @@ bool CPedSyncPacket::SyncData::ReadSpatialData(NetBitStreamInterface& BitStream) { // Did we recieve position? if (ucFlags & 0x01) - { + { if (!BitStream.Read(&position)) return false; } // Rotation if (ucFlags & 0x02) - { + { if (!BitStream.Read(&rotation)) return false; } // Velocity if (ucFlags & 0x04) - { + { if (!BitStream.Read(&velocity)) return false; } diff --git a/Server/mods/deathmatch/logic/packets/CPedSyncPacket.h b/Server/mods/deathmatch/logic/packets/CPedSyncPacket.h index 00824233f94..9513619b663 100644 --- a/Server/mods/deathmatch/logic/packets/CPedSyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPedSyncPacket.h @@ -21,19 +21,19 @@ class CPedSyncPacket final : public CPacket public: struct SyncData { - ElementID ID; - unsigned char ucFlags; - std::uint8_t flags2; - unsigned char ucSyncTimeContext; - SPositionSync position; - SPedRotationSync rotation; - SVelocitySync velocity; - float fHealth; - float fArmor; - bool bOnFire; - bool bIsInWater; - bool isReloadingWeapon; - float cameraRotation; + ElementID ID; + unsigned char ucFlags; + std::uint8_t flags2; + unsigned char ucSyncTimeContext; + SPositionSync position; + SPedRotationSync rotation; + SVelocitySync velocity; + float fHealth; + float fArmor; + bool bOnFire; + bool bIsInWater; + bool isReloadingWeapon; + float cameraRotation; bool ReadSpatialData(NetBitStreamInterface& BitStream); // Backward compatibility @@ -42,7 +42,7 @@ class CPedSyncPacket final : public CPacket public: // Used when receiving ped sync from clients, can contain multiple SyncData - CPedSyncPacket(){}; + CPedSyncPacket() {}; // Used when sending ped sync to clients, only contains one SyncData CPedSyncPacket(SyncData& pReadData); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerACInfoPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerACInfoPacket.h index b485f8b5e4a..af5b0e8e26b 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerACInfoPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerACInfoPacket.h @@ -17,7 +17,7 @@ class CPlayerACInfoPacket final : public CPacket { public: ePacketID GetPacketID() const { return PACKET_ID_PLAYER_ACINFO; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerClothesPacket.cpp b/Server/mods/deathmatch/logic/packets/CPlayerClothesPacket.cpp index 3cf103baeff..5ea2d6260d6 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerClothesPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CPlayerClothesPacket.cpp @@ -18,8 +18,8 @@ CPlayerClothesPacket::~CPlayerClothesPacket() std::vector::iterator iter = m_List.begin(); for (; iter != m_List.end(); ++iter) { - delete[](*iter)->szTexture; - delete[](*iter)->szModel; + delete[] (*iter)->szTexture; + delete[] (*iter)->szModel; delete *iter; } m_List.clear(); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerDiagnosticPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerDiagnosticPacket.h index d985f73e0db..623b9ba0d78 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerDiagnosticPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerDiagnosticPacket.h @@ -17,7 +17,7 @@ class CPlayerDiagnosticPacket final : public CPacket { public: ePacketID GetPacketID() const { return PACKET_ID_PLAYER_DIAGNOSTIC; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerListPacket.cpp b/Server/mods/deathmatch/logic/packets/CPlayerListPacket.cpp index 170dd72e2e0..6f2eb499439 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerListPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CPlayerListPacket.cpp @@ -122,7 +122,7 @@ bool CPlayerListPacket::Write(NetBitStreamInterface& BitStream) const // Flags bool bInVehicle = (pPlayer->GetOccupiedVehicle() != NULL); BitStream.WriteBit(pPlayer->IsDead()); - BitStream.WriteBit(true); // (Was IsSpawned) Used by the client to determine if extra info was sent (in this packet) + BitStream.WriteBit(true); // (Was IsSpawned) Used by the client to determine if extra info was sent (in this packet) BitStream.WriteBit(bInVehicle); BitStream.WriteBit(pPlayer->HasJetPack()); BitStream.WriteBit(pPlayer->IsNametagShowing()); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerModInfoPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerModInfoPacket.h index bcc283d3964..ad1a7faaf44 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerModInfoPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerModInfoPacket.h @@ -34,7 +34,7 @@ class CPlayerModInfoPacket final : public CPacket { public: ePacketID GetPacketID() const { return PACKET_ID_PLAYER_MODINFO; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); diff --git a/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.cpp index 2297e985c16..cd4f96cf744 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.cpp @@ -94,9 +94,8 @@ bool CPlayerPuresyncPacket::Read(NetBitStreamInterface& BitStream) break; } - if (radius > -1 && - (!IsPointNearPoint3D(pSourcePlayer->GetPosition(), pContactElement->GetPosition(), static_cast(radius)) || - pSourcePlayer->GetDimension() != pContactElement->GetDimension())) + if (radius > -1 && (!IsPointNearPoint3D(pSourcePlayer->GetPosition(), pContactElement->GetPosition(), static_cast(radius)) || + pSourcePlayer->GetDimension() != pContactElement->GetDimension())) { pContactElement = nullptr; // Use current player position. They are not reporting their absolute position so we have to disregard it. @@ -110,7 +109,7 @@ bool CPlayerPuresyncPacket::Read(NetBitStreamInterface& BitStream) { position.data.vecPosition = pSourcePlayer->GetPosition(); } - + CElement* pPreviousContactElement = pSourcePlayer->GetContactElement(); pSourcePlayer->SetContactElement(pContactElement); @@ -145,7 +144,7 @@ bool CPlayerPuresyncPacket::Read(NetBitStreamInterface& BitStream) // if (position.data.vecPosition.fX != 0.0f || position.data.vecPosition.fY != 0.0f || position.data.vecPosition.fZ != 0.0f) { CVector playerPosition = pSourcePlayer->GetPosition(); - float playerDistancePosition = DistanceBetweenPoints3D(playerPosition, position.data.vecPosition); + float playerDistancePosition = DistanceBetweenPoints3D(playerPosition, position.data.vecPosition); if (playerDistancePosition >= g_TickRateSettings.playerTeleportAlert) { if (!pSourcePlayer->GetTeleported()) @@ -221,8 +220,8 @@ bool CPlayerPuresyncPacket::Read(NetBitStreamInterface& BitStream) if (pSourcePlayer->GetWeaponType() != ucClientWeaponType) { - bWeaponCorrect = false; // Possibly old weapon data. - ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data + bWeaponCorrect = false; // Possibly old weapon data. + ucUseWeaponType = ucClientWeaponType; // Use the packet supplied weapon type to skip over the correct amount of data } // Update check counts diff --git a/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.h index ac53d4d773e..04cff3a99c2 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerPuresyncPacket.h @@ -16,7 +16,7 @@ class CPlayerPuresyncPacket final : public CPacket { public: - CPlayerPuresyncPacket(){}; + CPlayerPuresyncPacket() {}; explicit CPlayerPuresyncPacket(CPlayer* pPlayer); bool HasSimHandler() const { return true; } diff --git a/Server/mods/deathmatch/logic/packets/CPlayerResourceStartPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerResourceStartPacket.h index ec08dc16397..830f1c93d43 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerResourceStartPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerResourceStartPacket.h @@ -25,7 +25,7 @@ class CPlayerResourceStartPacket final : public CPacket bool Read(NetBitStreamInterface& BitStream); - CResource* GetResource() const noexcept { return m_pResource; } + CResource* GetResource() const noexcept { return m_pResource; } unsigned int GetStartCounter() const noexcept { return m_startCounter; } private: diff --git a/Server/mods/deathmatch/logic/packets/CPlayerScreenShotPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerScreenShotPacket.h index e73321e7f95..a4715adb94b 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerScreenShotPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerScreenShotPacket.h @@ -19,11 +19,11 @@ class CPlayerScreenShotPacket final : public CPacket { public: ePacketID GetPacketID() const { return PACKET_ID_PLAYER_SCREENSHOT; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); - uchar m_ucStatus; // 1 = has image, 2 = minimized, 3 = disabled, 4 = error + uchar m_ucStatus; // 1 = has image, 2 = minimized, 3 = disabled, 4 = error // With every packet if status is 1 ushort m_usScreenShotId; diff --git a/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp b/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp index f7b19179725..ac0f8909ebe 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp @@ -21,7 +21,7 @@ bool CPlayerStatsPacket::Write(NetBitStreamInterface& BitStream) const // Write the source elements's ID BitStream.Write(m_pSourceElement->GetID()); - BitStream.WriteCompressed(static_cast(m_map.size())); // Write stat count + BitStream.WriteCompressed(static_cast(m_map.size())); // Write stat count for (auto&& [statID, value] : m_map) { BitStream.Write(statID); @@ -36,10 +36,10 @@ void CPlayerStatsPacket::Add(unsigned short usID, float fValue) if (auto iter = m_map.find(usID); iter != m_map.end()) { if (fValue == 0.0f) - m_map.erase(iter); // Erase stat + m_map.erase(iter); // Erase stat else - iter->second = fValue; // Update value + iter->second = fValue; // Update value } - else // Not in map + else // Not in map m_map.emplace(usID, fValue); } diff --git a/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.h index 9398f264541..d8429b06dd7 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.h @@ -31,5 +31,5 @@ class CPlayerStatsPacket final : public CPacket size_t GetSize() const noexcept { return m_map.size(); } private: - std::map m_map; // id - value pairs + std::map m_map; // id - value pairs }; diff --git a/Server/mods/deathmatch/logic/packets/CPlayerTransgressionPacket.h b/Server/mods/deathmatch/logic/packets/CPlayerTransgressionPacket.h index 7b48d60a8c5..8183c6e3b4e 100644 --- a/Server/mods/deathmatch/logic/packets/CPlayerTransgressionPacket.h +++ b/Server/mods/deathmatch/logic/packets/CPlayerTransgressionPacket.h @@ -17,7 +17,7 @@ class CPlayerTransgressionPacket final : public CPacket { public: ePacketID GetPacketID() const { return PACKET_ID_PLAYER_TRANSGRESSION; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); diff --git a/Server/mods/deathmatch/logic/packets/CProjectileSyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CProjectileSyncPacket.cpp index dc4c19b921b..45eb3c29968 100644 --- a/Server/mods/deathmatch/logic/packets/CProjectileSyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CProjectileSyncPacket.cpp @@ -44,10 +44,10 @@ bool CProjectileSyncPacket::Read(NetBitStreamInterface& BitStream) switch (m_ucWeaponType) { - case 16: // WEAPONTYPE_GRENADE - case 17: // WEAPONTYPE_TEARGAS - case 18: // WEAPONTYPE_MOLOTOV - case 39: // WEAPONTYPE_REMOTE_SATCHEL_CHARGE + case 16: // WEAPONTYPE_GRENADE + case 17: // WEAPONTYPE_TEARGAS + case 18: // WEAPONTYPE_MOLOTOV + case 39: // WEAPONTYPE_REMOTE_SATCHEL_CHARGE { SFloatSync<7, 17> projectileForce; if (!BitStream.Read(&projectileForce)) @@ -61,8 +61,8 @@ bool CProjectileSyncPacket::Read(NetBitStreamInterface& BitStream) break; } - case 19: // WEAPONTYPE_ROCKET - case 20: // WEAPONTYPE_ROCKET_HS + case 19: // WEAPONTYPE_ROCKET + case 20: // WEAPONTYPE_ROCKET_HS { if (!BitStream.ReadBit(m_bHasTarget)) return false; @@ -83,8 +83,8 @@ bool CProjectileSyncPacket::Read(NetBitStreamInterface& BitStream) break; } - case 58: // WEAPONTYPE_FLARE - case 21: // WEAPONTYPE_FREEFALL_BOMB + case 58: // WEAPONTYPE_FLARE + case 21: // WEAPONTYPE_FREEFALL_BOMB break; default: @@ -128,10 +128,10 @@ bool CProjectileSyncPacket::Write(NetBitStreamInterface& BitStream) const switch (m_ucWeaponType) { - case 16: // WEAPONTYPE_GRENADE - case 17: // WEAPONTYPE_TEARGAS - case 18: // WEAPONTYPE_MOLOTOV - case 39: // WEAPONTYPE_REMOTE_SATCHEL_CHARGE + case 16: // WEAPONTYPE_GRENADE + case 17: // WEAPONTYPE_TEARGAS + case 18: // WEAPONTYPE_MOLOTOV + case 39: // WEAPONTYPE_REMOTE_SATCHEL_CHARGE { SFloatSync<7, 17> projectileForce; projectileForce.data.fValue = m_fForce; @@ -143,8 +143,8 @@ bool CProjectileSyncPacket::Write(NetBitStreamInterface& BitStream) const break; } - case 19: // WEAPONTYPE_ROCKET - case 20: // WEAPONTYPE_ROCKET_HS + case 19: // WEAPONTYPE_ROCKET + case 20: // WEAPONTYPE_ROCKET_HS { if (m_TargetID != INVALID_ELEMENT_ID) { @@ -164,7 +164,7 @@ bool CProjectileSyncPacket::Write(NetBitStreamInterface& BitStream) const break; } - case 58: // WEAPONTYPE_FLARE + case 58: // WEAPONTYPE_FLARE break; } diff --git a/Server/mods/deathmatch/logic/packets/CResourceStartPacket.cpp b/Server/mods/deathmatch/logic/packets/CResourceStartPacket.cpp index 18f9856d74b..6f518ca4ebf 100644 --- a/Server/mods/deathmatch/logic/packets/CResourceStartPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CResourceStartPacket.cpp @@ -106,7 +106,7 @@ bool CResourceStartPacket::Write(NetBitStreamInterface& BitStream) const CChecksum checksum = resourceFile->GetLastChecksum(); BitStream.Write(checksum.ulCRC); BitStream.Write((const char*)checksum.md5.data, sizeof(checksum.md5.data)); - BitStream.Write((double)resourceFile->GetSizeHint()); // Has to be double for bitstream format compatibility + BitStream.Write((double)resourceFile->GetSizeHint()); // Has to be double for bitstream format compatibility if (resourceFile->GetType() == CResourceScriptItem::RESOURCE_FILE_TYPE_CLIENT_FILE) { CResourceClientFileItem* pRCFItem = reinterpret_cast(resourceFile); diff --git a/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.cpp b/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.cpp index 2e298371073..cfde9f6739d 100644 --- a/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.cpp +++ b/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.cpp @@ -14,14 +14,14 @@ bool CServerInfoSyncPacket::Write(NetBitStreamInterface& BitStream) const { - if (m_ActualInfo) // Flag is set + if (m_ActualInfo) // Flag is set { BitStream.Write(m_ActualInfo); // Check the flags one by one & write in order if (maxPlayers) - BitStream.Write(static_cast( - CStaticFunctionDefinitions::GetMaxPlayers())); // static_cast ensures the type is uint in case it's changed in future + BitStream.Write( + static_cast(CStaticFunctionDefinitions::GetMaxPlayers())); // static_cast ensures the type is uint in case it's changed in future // other info diff --git a/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.h b/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.h index bb6d9fcfb4a..2b16a121338 100644 --- a/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CServerInfoSyncPacket.h @@ -14,9 +14,9 @@ enum EServerInfoSyncFlag : uint8 { - SERVER_INFO_FLAG_ALL = 0xFF, // 0b11111111 - SERVER_INFO_FLAG_MAX_PLAYERS = 1, // 0b00000001 - SERVER_INFO_FLAG_RESERVED = 1 << 1 // 0b00000010 and so on + SERVER_INFO_FLAG_ALL = 0xFF, // 0b11111111 + SERVER_INFO_FLAG_MAX_PLAYERS = 1, // 0b00000001 + SERVER_INFO_FLAG_RESERVED = 1 << 1 // 0b00000010 and so on }; class CServerInfoSyncPacket final : public CPacket @@ -37,7 +37,7 @@ class CServerInfoSyncPacket final : public CPacket struct { bool maxPlayers : 1; - bool reserved : 7; // for future? + bool reserved : 7; // for future? }; }; }; diff --git a/Server/mods/deathmatch/logic/packets/CSyncSettingsPacket.h b/Server/mods/deathmatch/logic/packets/CSyncSettingsPacket.h index f20ef002c59..0c70154fa60 100644 --- a/Server/mods/deathmatch/logic/packets/CSyncSettingsPacket.h +++ b/Server/mods/deathmatch/logic/packets/CSyncSettingsPacket.h @@ -16,7 +16,7 @@ class CSyncSettingsPacket final : public CPacket { public: - CSyncSettingsPacket(){}; + CSyncSettingsPacket() {}; CSyncSettingsPacket(const std::set& weaponTypesUsingBulletSync, uchar ucVehExtrapolateEnabled, short sVehExtrapolateBaseMs, short sVehExtrapolatePercent, short sVehExtrapolateMaxMs, uchar ucUseAltPulseOrder, uchar ucAllowFastSprintFix, uchar ucAllowDrivebyAnimationFix, uchar ucAllowShotgunDamageFix, std::uint8_t multiCommandHandlerPolicy); diff --git a/Server/mods/deathmatch/logic/packets/CUnoccupiedVehiclePushPacket.h b/Server/mods/deathmatch/logic/packets/CUnoccupiedVehiclePushPacket.h index 5c6aa90d47b..1d7efad9f0d 100644 --- a/Server/mods/deathmatch/logic/packets/CUnoccupiedVehiclePushPacket.h +++ b/Server/mods/deathmatch/logic/packets/CUnoccupiedVehiclePushPacket.h @@ -19,10 +19,10 @@ class CVehicle; class CUnoccupiedVehiclePushPacket final : public CPacket { public: - CUnoccupiedVehiclePushPacket(){}; + CUnoccupiedVehiclePushPacket() {}; ePacketID GetPacketID() const { return PACKET_ID_VEHICLE_PUSH_SYNC; }; - unsigned long GetFlags() const { return 0; }; // Not used + unsigned long GetFlags() const { return 0; }; // Not used bool Read(NetBitStreamInterface& BitStream); diff --git a/Server/mods/deathmatch/logic/packets/CUnoccupiedVehicleSyncPacket.h b/Server/mods/deathmatch/logic/packets/CUnoccupiedVehicleSyncPacket.h index 380faae7ef7..e07e33c1da5 100644 --- a/Server/mods/deathmatch/logic/packets/CUnoccupiedVehicleSyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CUnoccupiedVehicleSyncPacket.h @@ -26,7 +26,7 @@ class CUnoccupiedVehicleSyncPacket final : public CPacket }; public: - CUnoccupiedVehicleSyncPacket(){}; + CUnoccupiedVehicleSyncPacket() {}; ~CUnoccupiedVehicleSyncPacket(); ePacketID GetPacketID() const { return PACKET_ID_UNOCCUPIED_VEHICLE_SYNC; }; diff --git a/Server/mods/deathmatch/logic/packets/CVehicleInOutPacket.h b/Server/mods/deathmatch/logic/packets/CVehicleInOutPacket.h index 2e034208efb..bdffb4bdb7a 100644 --- a/Server/mods/deathmatch/logic/packets/CVehicleInOutPacket.h +++ b/Server/mods/deathmatch/logic/packets/CVehicleInOutPacket.h @@ -52,16 +52,16 @@ class CVehicleInOutPacket final : public CPacket void SetCorrectVector(const CVector& vector) { m_pCorrectVector = new CVector(vector.fX, vector.fY, vector.fZ); } private: - ElementID m_PedID; // The ped - ElementID m_VehicleID; // The vehicle - unsigned char m_ucSeat; // The seat - unsigned char m_ucAction; // The action, see CGame.h - ElementID m_PedIn; // The ped jacking - ElementID m_PedOut; // The ped getting jacked - unsigned char m_ucStartedJacking; // 1 = client reports he started jacking - unsigned char m_ucFailReason; // eFailReasons - CVector* m_pCorrectVector; // Ped position reported by client - bool m_bOnWater; // Vehicle in water reported by client - unsigned char m_ucDoor; // Door ID - float m_fDoorAngle; // Door angle + ElementID m_PedID; // The ped + ElementID m_VehicleID; // The vehicle + unsigned char m_ucSeat; // The seat + unsigned char m_ucAction; // The action, see CGame.h + ElementID m_PedIn; // The ped jacking + ElementID m_PedOut; // The ped getting jacked + unsigned char m_ucStartedJacking; // 1 = client reports he started jacking + unsigned char m_ucFailReason; // eFailReasons + CVector* m_pCorrectVector; // Ped position reported by client + bool m_bOnWater; // Vehicle in water reported by client + unsigned char m_ucDoor; // Door ID + float m_fDoorAngle; // Door angle }; diff --git a/Server/mods/deathmatch/logic/packets/CVehiclePuresyncPacket.h b/Server/mods/deathmatch/logic/packets/CVehiclePuresyncPacket.h index 4a86ad957a2..f924bd170a6 100644 --- a/Server/mods/deathmatch/logic/packets/CVehiclePuresyncPacket.h +++ b/Server/mods/deathmatch/logic/packets/CVehiclePuresyncPacket.h @@ -19,7 +19,7 @@ class CVehicle; class CVehiclePuresyncPacket final : public CPacket { public: - CVehiclePuresyncPacket(){}; + CVehiclePuresyncPacket() {}; explicit CVehiclePuresyncPacket(class CPlayer* pPlayer); bool HasSimHandler() const { return true; } diff --git a/Server/mods/deathmatch/logic/packets/CVehicleTrailerPacket.h b/Server/mods/deathmatch/logic/packets/CVehicleTrailerPacket.h index b9eae09fa20..b6ed1affdff 100644 --- a/Server/mods/deathmatch/logic/packets/CVehicleTrailerPacket.h +++ b/Server/mods/deathmatch/logic/packets/CVehicleTrailerPacket.h @@ -19,7 +19,7 @@ class CVehicle; class CVehicleTrailerPacket final : public CPacket { public: - CVehicleTrailerPacket(){}; + CVehicleTrailerPacket() {}; CVehicleTrailerPacket(CVehicle* pVehicle, CVehicle* pTrailer, bool bAttached); ePacketID GetPacketID() const { return PACKET_ID_VEHICLE_TRAILER; }; diff --git a/Server/mods/deathmatch/utils/CHqComms.h b/Server/mods/deathmatch/utils/CHqComms.h index 8be9247f0fc..18ddeba4f35 100644 --- a/Server/mods/deathmatch/utils/CHqComms.h +++ b/Server/mods/deathmatch/utils/CHqComms.h @@ -49,7 +49,7 @@ class CHqComms : public CRefCountable m_Stage = HQCOMMS_STAGE_QUERY; CBitStream bitStream; - bitStream->Write((char)4); // Data version + bitStream->Write((char)4); // Data version bitStream->WriteStr(g_pGame->GetConfig()->GetServerIP()); bitStream->Write(g_pGame->GetConfig()->GetServerPort()); bitStream->WriteStr(CStaticFunctionDefinitions::GetVersionSortable()); @@ -91,7 +91,7 @@ class CHqComms : public CRefCountable bitStream->WriteStr(SString::Join(",", g_pGame->GetConfig()->GetOwnerEmailAddressList())); // Send request - this->AddRef(); // Keep object alive + this->AddRef(); // Keep object alive SHttpRequestOptions options; options.strPostData = SStringX((const char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); options.bPostBinary = true; @@ -107,7 +107,7 @@ class CHqComms : public CRefCountable { CHqComms* pHqComms = (CHqComms*)result.pObj; pHqComms->DownloadFinishedCallback(result); - pHqComms->Release(); // No need to keep object alive now + pHqComms->Release(); // No need to keep object alive now } // @@ -247,7 +247,7 @@ class CHqComms : public CRefCountable static CNetHTTPDownloadManagerInterface* GetDownloadManager() { return g_pNetServer->GetHTTPDownloadManager(EDownloadMode::ASE); } protected: - ~CHqComms() {} // Must use Release() + ~CHqComms() {} // Must use Release() int m_iPollInterval; int m_iPrevBadFileHashesRev; @@ -256,5 +256,5 @@ class CHqComms : public CRefCountable SString m_strURL; SString m_strPrevMessage; SString m_strCrashLogFilename; - SString m_strCrashDumpMeta; // Filename of file which contains the latest crash dump filename + SString m_strCrashDumpMeta; // Filename of file which contains the latest crash dump filename }; diff --git a/Server/mods/deathmatch/utils/CMasterServerAnnouncer.h b/Server/mods/deathmatch/utils/CMasterServerAnnouncer.h index 4278a819fdb..35be9577894 100644 --- a/Server/mods/deathmatch/utils/CMasterServerAnnouncer.h +++ b/Server/mods/deathmatch/utils/CMasterServerAnnouncer.h @@ -46,12 +46,12 @@ class CMasterServer : public CRefCountable { m_Stage = ANNOUNCE_STAGE_INITIAL; m_uiInitialAnnounceRetryAttempts = 5; - m_uiInitialAnnounceRetryInterval = 1000 * 60 * 5; // 5 mins initial announce retry interval - m_uiPushInterval = 1000 * 60 * 10; // 10 mins push interval + m_uiInitialAnnounceRetryInterval = 1000 * 60 * 5; // 5 mins initial announce retry interval + m_uiPushInterval = 1000 * 60 * 10; // 10 mins push interval } protected: - ~CMasterServer() {} // Must use Release() + ~CMasterServer() {} // Must use Release() public: // // Pulse this master server @@ -81,7 +81,7 @@ class CMasterServer : public CRefCountable m_llLastAnnounceTime = llTickCountNow; // Send request - this->AddRef(); // Keep object alive + this->AddRef(); // Keep object alive m_bStatusBusy = true; SHttpRequestOptions options; options.uiConnectionAttempts = 2; @@ -115,7 +115,7 @@ class CMasterServer : public CRefCountable { CMasterServer* pMasterServer = (CMasterServer*)result.pObj; pMasterServer->DownloadFinishedCallback(result); - pMasterServer->Release(); // No need to keep object alive now + pMasterServer->Release(); // No need to keep object alive now } // @@ -151,7 +151,7 @@ class CMasterServer : public CRefCountable } else { - bool bCanRetry = (result.iErrorCode == 28); // We can retry if 'Timeout was reached' + bool bCanRetry = (result.iErrorCode == 28); // We can retry if 'Timeout was reached' if (m_Stage == ANNOUNCE_STAGE_INITIAL) { diff --git a/Server/mods/deathmatch/utils/CZipMaker.cpp b/Server/mods/deathmatch/utils/CZipMaker.cpp index 7ac45238f6e..38f91d5b7db 100644 --- a/Server/mods/deathmatch/utils/CZipMaker.cpp +++ b/Server/mods/deathmatch/utils/CZipMaker.cpp @@ -31,7 +31,7 @@ CZipMaker::CZipMaker(const SString& strZipPathFilename) fill_win32_filefunc(&ffunc); m_uzFile = zipOpen2(strZipPathFilename, APPEND_STATUS_CREATE, nullptr, &ffunc); #else - m_uzFile = zipOpen(strZipPathFilename, APPEND_STATUS_CREATE); // Use APPEND_STATUS_ADDINZIP to open existing + m_uzFile = zipOpen(strZipPathFilename, APPEND_STATUS_CREATE); // Use APPEND_STATUS_ADDINZIP to open existing #endif } diff --git a/Server/sdk/MTAPlatform.h b/Server/sdk/MTAPlatform.h index a7ec32c7854..ee4e2274146 100644 --- a/Server/sdk/MTAPlatform.h +++ b/Server/sdk/MTAPlatform.h @@ -17,38 +17,38 @@ extern "C" bool g_bNoTopBar; /** Operating system identifiers **/ #if defined(WIN32) #ifdef _WIN64 - #define MTA_OS_STRING "Windows x64" + #define MTA_OS_STRING "Windows x64" #elif defined(_M_ARM64) - #define MTA_OS_STRING "Windows arm64" + #define MTA_OS_STRING "Windows arm64" #elif defined(_M_ARM) - #define MTA_OS_STRING "Windows arm" + #define MTA_OS_STRING "Windows arm" #else - #define MTA_OS_STRING "Windows" + #define MTA_OS_STRING "Windows" #endif - #define MTA_LIB_EXTENSION ".dll" + #define MTA_LIB_EXTENSION ".dll" #elif defined(__linux__) #ifdef __x86_64__ - #define MTA_OS_STRING "GNU/Linux x64" + #define MTA_OS_STRING "GNU/Linux x64" #elif defined(__aarch64__) - #define MTA_OS_STRING "GNU/Linux arm64" + #define MTA_OS_STRING "GNU/Linux arm64" #elif defined(__arm__) - #define MTA_OS_STRING "GNU/Linux arm" + #define MTA_OS_STRING "GNU/Linux arm" #else - #define MTA_OS_STRING "GNU/Linux" + #define MTA_OS_STRING "GNU/Linux" #endif - #define MTA_LIB_EXTENSION ".so" + #define MTA_LIB_EXTENSION ".so" #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) - #define MTA_OS_STRING "BSD" - #define MTA_LIB_EXTENSION ".so" + #define MTA_OS_STRING "BSD" + #define MTA_LIB_EXTENSION ".so" #elif defined(__APPLE__) - #define MTA_OS_STRING "macOS" - #define MTA_LIB_EXTENSION ".dylib" + #define MTA_OS_STRING "macOS" + #define MTA_LIB_EXTENSION ".dylib" #else #error "Unsupported operating system" #endif #if defined(MTA_DEBUG) - #define MTA_LIB_SUFFIX "_d" + #define MTA_LIB_SUFFIX "_d" #else #define MTA_LIB_SUFFIX #endif diff --git a/Server/sdk/net/CNetServer.h b/Server/sdk/net/CNetServer.h index eb8868c9ae1..e1171db035a 100644 --- a/Server/sdk/net/CNetServer.h +++ b/Server/sdk/net/CNetServer.h @@ -16,7 +16,7 @@ #include "ns_playerid.h" #include "net/CNetHTTPDownloadManagerInterface.h" -#define MAX_CALL_REMOTE_QUEUES 100 +#define MAX_CALL_REMOTE_QUEUES 100 namespace EDownloadMode { diff --git a/Server/sdk/net/ns_common.h b/Server/sdk/net/ns_common.h index 8467b706ad2..2902720698c 100644 --- a/Server/sdk/net/ns_common.h +++ b/Server/sdk/net/ns_common.h @@ -18,10 +18,10 @@ const NetServerPlayerID NET_INVALID_PLAYER_ID; #define NET_INVALID_PLAYER_INDEX 255; -#define NET_MAX_PLAYER_COUNT 64 -#define NET_MAX_VEHICLE_COUNT 250 +#define NET_MAX_PLAYER_COUNT 64 +#define NET_MAX_VEHICLE_COUNT 250 -#define NET_MAX_PLAYER_NAME_LENGTH 32 +#define NET_MAX_PLAYER_NAME_LENGTH 32 typedef struct __static_client_data_t { @@ -48,7 +48,7 @@ enum NetServerPacketReliability PACKET_RELIABILITY_UNRELIABLE_SEQUENCED, PACKET_RELIABILITY_RELIABLE, PACKET_RELIABILITY_RELIABLE_ORDERED, - PACKET_RELIABILITY_RELIABLE_SEQUENCED // Can drop packets + PACKET_RELIABILITY_RELIABLE_SEQUENCED // Can drop packets }; // Copy of raknet statistics diff --git a/Server/sdk/net/ns_playerid.h b/Server/sdk/net/ns_playerid.h index 5b8612b176c..bacfff6fbae 100644 --- a/Server/sdk/net/ns_playerid.h +++ b/Server/sdk/net/ns_playerid.h @@ -47,7 +47,7 @@ class NetServerPlayerID m_usPort = usPort; }; - ~NetServerPlayerID(){}; + ~NetServerPlayerID() {}; friend inline int operator==(const NetServerPlayerID& left, const NetServerPlayerID& right) { diff --git a/Shared/XML/CXMLArray.cpp b/Shared/XML/CXMLArray.cpp index 28df306d617..521b42c3f8f 100644 --- a/Shared/XML/CXMLArray.cpp +++ b/Shared/XML/CXMLArray.cpp @@ -13,7 +13,7 @@ using namespace std; -#define XML_ARRAY_BASE_ID 0x01000000 +#define XML_ARRAY_BASE_ID 0x01000000 CStack CXMLArray::m_IDStack; std::vector CXMLArray::m_Elements; diff --git a/Shared/XML/CXMLAttributeImpl.cpp b/Shared/XML/CXMLAttributeImpl.cpp index 13d3ce384ed..546a196bc98 100644 --- a/Shared/XML/CXMLAttributeImpl.cpp +++ b/Shared/XML/CXMLAttributeImpl.cpp @@ -11,7 +11,7 @@ #include "StdInc.h" -#define XML_ATTRIBUTE_VALUE_BUFFER 40 +#define XML_ATTRIBUTE_VALUE_BUFFER 40 CXMLAttributeImpl::CXMLAttributeImpl(CXMLAttributesImpl& Attributes, TiXmlElement& Node, const std::string& strName) : m_ulID(INVALID_XML_ID), diff --git a/Shared/XML/CXMLImpl.cpp b/Shared/XML/CXMLImpl.cpp index 9cbd481c726..e289f4f1f33 100644 --- a/Shared/XML/CXMLImpl.cpp +++ b/Shared/XML/CXMLImpl.cpp @@ -13,7 +13,7 @@ #define ALLOC_STATS_MODULE_NAME "xml" #include #ifndef MAX_PATH -#define MAX_PATH 260 + #define MAX_PATH 260 #endif #include "SharedUtil.hpp" diff --git a/Shared/XML/CXMLNodeImpl.cpp b/Shared/XML/CXMLNodeImpl.cpp index 6d443b37b09..f439b0b633f 100644 --- a/Shared/XML/CXMLNodeImpl.cpp +++ b/Shared/XML/CXMLNodeImpl.cpp @@ -231,7 +231,7 @@ bool CXMLNodeImpl::GetTagContent(bool& bContent) return true; } - return false; // Invalid + return false; // Invalid } bool CXMLNodeImpl::GetTagContent(int& iContent) diff --git a/Shared/XML/StdInc.h b/Shared/XML/StdInc.h index b55ac90d4ba..969629fe8a1 100644 --- a/Shared/XML/StdInc.h +++ b/Shared/XML/StdInc.h @@ -1,9 +1,9 @@ #ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include + #define WIN32_LEAN_AND_MEAN + #include #else -#include + #include #endif #include diff --git a/Shared/animation/CEasingCurve.cpp b/Shared/animation/CEasingCurve.cpp index e1ad2b2179f..ee46f1e40bf 100644 --- a/Shared/animation/CEasingCurve.cpp +++ b/Shared/animation/CEasingCurve.cpp @@ -10,12 +10,12 @@ #include "StdInc.h" #include "CEasingCurve.h" #include "lua/CLuaFunctionParseHelpers.h" -#include "EasingEquations.hpp" //Included from cpp to separate just visually maths equations from framework +#include "EasingEquations.hpp" //Included from cpp to separate just visually maths equations from framework // For easing functions that require more parameters than time (like amplitude, period, overshot) class CComplexEasingFunction { -public: // All public since it's only an internal class +public: // All public since it's only an internal class enum eType { In = 0, @@ -113,7 +113,7 @@ class CBounceEase : public CComplexEasingFunction class CEasingCurve_Impl { -public: // All public since it's only an internal class +public: // All public since it's only an internal class explicit CEasingCurve_Impl(CEasingCurve::eType a_eType); ~CEasingCurve_Impl(); @@ -124,7 +124,7 @@ class CEasingCurve_Impl CEasingCurve::eType m_eType; CEasingCurve::SimpleEasingFunction m_pSimpleFunction; CComplexEasingFunction* m_pComplexFunction; - bool m_bFinishesAtOne; // f(1) = 1? + bool m_bFinishesAtOne; // f(1) = 1? }; CEasingCurve_Impl::CEasingCurve_Impl(CEasingCurve::eType a_eType) : m_eType(CEasingCurve::EASING_INVALID), m_pSimpleFunction(NULL), m_pComplexFunction(NULL) diff --git a/Shared/animation/CEasingCurve.h b/Shared/animation/CEasingCurve.h index 791bc8b6bb2..43013a2d8e7 100644 --- a/Shared/animation/CEasingCurve.h +++ b/Shared/animation/CEasingCurve.h @@ -75,7 +75,7 @@ class CEasingCurve void GetParams(double& a_rfPeriod, double& a_rfAmplitude, double& a_rfOvershoot) const; float ValueForProgress(float progress) const; - bool IsTargetValueFinalValue() const; // at t=1 can we use target as the final value (false for sin & cos) + bool IsTargetValueFinalValue() const; // at t=1 can we use target as the final value (false for sin & cos) protected: CEasingCurve_Impl* m_pImplementation; }; diff --git a/Shared/animation/CPositionRotationAnimation.cpp b/Shared/animation/CPositionRotationAnimation.cpp index 35cd953cb98..aff05fd4af2 100644 --- a/Shared/animation/CPositionRotationAnimation.cpp +++ b/Shared/animation/CPositionRotationAnimation.cpp @@ -81,7 +81,7 @@ void CPositionRotationAnimation::ToBitStream(NetBitStreamInterface& a_rBitStream positionSync.data.vecPosition = m_SourceValue.m_vecPosition; a_rBitStream.Write(&positionSync); - SRotationRadiansSync rotationSync(true); // RPC function used floats when join time packet didn't, let's go for float + SRotationRadiansSync rotationSync(true); // RPC function used floats when join time packet didn't, let's go for float rotationSync.data.vecRotation = m_SourceValue.m_vecRotation; a_rBitStream.Write(&rotationSync); @@ -91,7 +91,7 @@ void CPositionRotationAnimation::ToBitStream(NetBitStreamInterface& a_rBitStream a_rBitStream.WriteBit(m_bDeltaRotationMode); if (m_bDeltaRotationMode) { - rotationSync.data.vecRotation = m_DeltaValue.m_vecRotation; // We serialize DELTA + rotationSync.data.vecRotation = m_DeltaValue.m_vecRotation; // We serialize DELTA } else { @@ -116,7 +116,7 @@ CPositionRotationAnimation* CPositionRotationAnimation::FromBitStream(NetBitStre return NULL; } - CPositionRotationAnimation* pAnimation = new CPositionRotationAnimation(); // It's up to the caller do delete it if we return it + CPositionRotationAnimation* pAnimation = new CPositionRotationAnimation(); // It's up to the caller do delete it if we return it if (bResumeMode) { diff --git a/Shared/animation/CPositionRotationAnimation.h b/Shared/animation/CPositionRotationAnimation.h index f5486ae6877..5af64c48e80 100644 --- a/Shared/animation/CPositionRotationAnimation.h +++ b/Shared/animation/CPositionRotationAnimation.h @@ -65,5 +65,5 @@ class CPositionRotationAnimation : public TInterpolation static CPositionRotationAnimation* FromBitStream(NetBitStreamInterface& a_rBitStream); protected: - bool m_bDeltaRotationMode; // defines if the rotation provided is a relative rotation + bool m_bDeltaRotationMode; // defines if the rotation provided is a relative rotation }; diff --git a/Shared/animation/EasingDeclarations.hpp b/Shared/animation/EasingDeclarations.hpp index 651a6785b65..3e933949d31 100644 --- a/Shared/animation/EasingDeclarations.hpp +++ b/Shared/animation/EasingDeclarations.hpp @@ -22,4 +22,4 @@ DECLARE_EASING(InOutBounce) DECLARE_EASING(OutInBounce) DECLARE_EASING(SineCurve) -DECLARE_EASING(CosineCurve) \ No newline at end of file +DECLARE_EASING(CosineCurve) diff --git a/Shared/animation/EasingEquations.hpp b/Shared/animation/EasingEquations.hpp index 92ed2f0a573..6d6e233745d 100644 --- a/Shared/animation/EasingEquations.hpp +++ b/Shared/animation/EasingEquations.hpp @@ -35,10 +35,10 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVE #include #ifndef M_PI -#define M_PI 3.14159265358979323846 + #define M_PI 3.14159265358979323846 #endif #ifndef M_PI_2 -#define M_PI_2 (M_PI / 2) + #define M_PI_2 (M_PI / 2) #endif static double easeNone(double progress) diff --git a/Shared/animation/TInterpolation.h b/Shared/animation/TInterpolation.h index 405c20d9bd6..09054ff3898 100644 --- a/Shared/animation/TInterpolation.h +++ b/Shared/animation/TInterpolation.h @@ -17,7 +17,7 @@ class TInterpolation public: TInterpolation() : m_easingCurve(CEasingCurve::Linear), m_ullStartTime(0), m_ullEndTime(0), m_ulDuration(0) {} - virtual ~TInterpolation(){}; + virtual ~TInterpolation() {}; virtual void SetSourceValue(const T& a_rValue) { @@ -67,8 +67,8 @@ class TInterpolation unsigned long long ullNow = _GetTime(); float fElapsedTime = static_cast(ullNow - m_ullStartTime); - float fAnimationTime = fElapsedTime / m_ulDuration; // Division by 0 is handled by IsRunning () - fAnimationTime = m_easingCurve.ValueForProgress(fAnimationTime); // Get the animation time to use (since it can be non linear) + float fAnimationTime = fElapsedTime / m_ulDuration; // Division by 0 is handled by IsRunning () + fAnimationTime = m_easingCurve.ValueForProgress(fAnimationTime); // Get the animation time to use (since it can be non linear) _GetValue(a_rResult, fAnimationTime); @@ -90,7 +90,7 @@ class TInterpolation } else { - float fAnimationTime = m_easingCurve.ValueForProgress(1.0); // Get the animation time to use (since it can be non linear) + float fAnimationTime = m_easingCurve.ValueForProgress(1.0); // Get the animation time to use (since it can be non linear) _GetValue(a_rResult, fAnimationTime); } } @@ -130,7 +130,7 @@ class TInterpolation T m_SourceValue; T m_TargetValue; - T m_DeltaValue; // Used for calculations, also allows some subtypes to use a different way to set delta + T m_DeltaValue; // Used for calculations, also allows some subtypes to use a different way to set delta CEasingCurve m_easingCurve; diff --git a/Shared/mods/deathmatch/logic/CDebugHookManager.cpp b/Shared/mods/deathmatch/logic/CDebugHookManager.cpp index fbb96de0be8..8e5798c35aa 100644 --- a/Shared/mods/deathmatch/logic/CDebugHookManager.cpp +++ b/Shared/mods/deathmatch/logic/CDebugHookManager.cpp @@ -33,10 +33,10 @@ CDebugHookManager::CDebugHookManager() { m_MaskArgumentsMap = { #ifndef MTA_CLIENT - {"logIn", {{EArgType::Password, 2}}}, // player, account, 2=PASSWORD - {"addAccount", {{EArgType::Password, 1}}}, // name, 1=PASSWORD - {"getAccount", {{EArgType::Password, 1}}}, // name, 1=PASSWORD - {"setAccountPassword", {{EArgType::Password, 1}}}, // account, 1=PASSWORD + {"logIn", {{EArgType::Password, 2}}}, // player, account, 2=PASSWORD + {"addAccount", {{EArgType::Password, 1}}}, // name, 1=PASSWORD + {"getAccount", {{EArgType::Password, 1}}}, // name, 1=PASSWORD + {"setAccountPassword", {{EArgType::Password, 1}}}, // account, 1=PASSWORD {"dbConnect", {{EArgType::MaxArgs, 0}}}, {"dbExec", {{EArgType::MaxArgs, 0}}}, {"dbFree", {{EArgType::MaxArgs, 0}}}, @@ -44,15 +44,15 @@ CDebugHookManager::CDebugHookManager() {"dbPrepareString", {{EArgType::MaxArgs, 0}}}, {"dbQuery", {{EArgType::MaxArgs, 0}}}, {"executeSQLQuery", {{EArgType::MaxArgs, 0}}}, - {"callRemote", {{EArgType::MaxArgs, 1}, {EArgType::Url, 0}}}, // 0=URL, ... + {"callRemote", {{EArgType::MaxArgs, 1}, {EArgType::Url, 0}}}, // 0=URL, ... #endif - {"fetchRemote", {{EArgType::MaxArgs, 1}, {EArgType::Url, 0}}}, // 0=URL, ... - {"passwordHash", {{EArgType::Password, 0}}}, // 0=PASSWORD, ... - {"passwordVerify", {{EArgType::Password, 0}}}, // 0=PASSWORD, ... - {"encodeString", {{EArgType::MaxArgs, 2}}}, // algorithm, input, 2=SECRETKEY, ... - {"decodeString", {{EArgType::MaxArgs, 2}}}, // algorithm, input, 2=SECRETKEY, ... - {"teaEncode", {{EArgType::Password, 1}}}, // input, 1=SECRETKEY - {"teaDecode", {{EArgType::Password, 1}}}, // input, 1=SECRETKEY + {"fetchRemote", {{EArgType::MaxArgs, 1}, {EArgType::Url, 0}}}, // 0=URL, ... + {"passwordHash", {{EArgType::Password, 0}}}, // 0=PASSWORD, ... + {"passwordVerify", {{EArgType::Password, 0}}}, // 0=PASSWORD, ... + {"encodeString", {{EArgType::MaxArgs, 2}}}, // algorithm, input, 2=SECRETKEY, ... + {"decodeString", {{EArgType::MaxArgs, 2}}}, // algorithm, input, 2=SECRETKEY, ... + {"teaEncode", {{EArgType::Password, 1}}}, // input, 1=SECRETKEY + {"teaDecode", {{EArgType::Password, 1}}}, // input, 1=SECRETKEY }; } @@ -534,10 +534,10 @@ bool CDebugHookManager::IsNameAllowed(const char* szName, const std::vector CIdArray::m_IDStack; std::vector CIdArray::m_Elements; @@ -35,7 +35,7 @@ void CIdArray::Initialize() m_uiCapacity = 0; m_bInitialized = true; m_uiPopIdCounter = 0; - m_uiMinTicksBetweenIdReuse = 1000 * 60 * 60; // 1 hour + m_uiMinTicksBetweenIdReuse = 1000 * 60 * 60; // 1 hour m_LastPeriodStart = CTickCount::Now(); ExpandBy(2000); } diff --git a/Shared/mods/deathmatch/logic/CIdArray.h b/Shared/mods/deathmatch/logic/CIdArray.h index ff8093d5b39..681199e5092 100644 --- a/Shared/mods/deathmatch/logic/CIdArray.h +++ b/Shared/mods/deathmatch/logic/CIdArray.h @@ -33,7 +33,7 @@ */ typedef unsigned long SArrayId; -#define INVALID_ARRAY_ID 0xFFFFFFFF +#define INVALID_ARRAY_ID 0xFFFFFFFF namespace EIdClass { diff --git a/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp b/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp index f72155dd17a..92050e087fa 100644 --- a/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp +++ b/Shared/mods/deathmatch/logic/CLatentTransferManager.cpp @@ -64,9 +64,9 @@ void CLatentTransferManager::DoPulse() // Smooth out time between calls, with more resistance when rising int iBetweenCallsChange = iDeltaTimeMs - m_iTimeMsBetweenCalls; if (iBetweenCallsChange > 0) - m_iTimeMsBetweenCalls += std::min(iBetweenCallsChange, std::max(1, m_iTimeMsBetweenCalls / 10)); // 10% max when rising + m_iTimeMsBetweenCalls += std::min(iBetweenCallsChange, std::max(1, m_iTimeMsBetweenCalls / 10)); // 10% max when rising else - m_iTimeMsBetweenCalls -= std::min(-iBetweenCallsChange, std::max(1, m_iTimeMsBetweenCalls / 5)); // 20% max when falling + m_iTimeMsBetweenCalls -= std::min(-iBetweenCallsChange, std::max(1, m_iTimeMsBetweenCalls / 5)); // 20% max when falling m_iTimeMsBetweenCalls = Clamp(1, m_iTimeMsBetweenCalls, 100); @@ -141,7 +141,7 @@ void CLatentTransferManager::AddSendBatchBegin(unsigned char ucPacketId, NetBitS // Copy data from bitstream into buffer buffer.SetSize(uiHeadSize + uiBitStreamBytesUsed); - *(buffer.GetData() + buffer.GetSize() - 1) = 0; // Zero last byte of destination buffer + *(buffer.GetData() + buffer.GetSize() - 1) = 0; // Zero last byte of destination buffer pBitStream->ResetReadPointer(); pBitStream->ReadBits(buffer.GetData() + uiHeadSize, uiBitStreamBitsUsed); @@ -375,7 +375,7 @@ bool DoStaticProcessPacket(unsigned char ucPacketID, NetPlayerID remoteId, NetBi void DoDisconnectRemote(NetPlayerID remoteId, const SString& strReason) { - g_pCore->ShowMessageBox(_("Error") + _E("CD61"), strReason, MB_BUTTON_OK | MB_ICON_ERROR); // DoDisconnectRemote + g_pCore->ShowMessageBox(_("Error") + _E("CD61"), strReason, MB_BUTTON_OK | MB_ICON_ERROR); // DoDisconnectRemote g_pCore->GetModManager()->RequestUnload(); } diff --git a/Shared/mods/deathmatch/logic/CLatentTransferManager.h b/Shared/mods/deathmatch/logic/CLatentTransferManager.h index 70510614dfe..7850b18d939 100644 --- a/Shared/mods/deathmatch/logic/CLatentTransferManager.h +++ b/Shared/mods/deathmatch/logic/CLatentTransferManager.h @@ -32,10 +32,10 @@ namespace LatentTransfer CATEGORY_PACKET, }; - const static int MIN_SEND_RATE = 500; // Bytes per second + const static int MIN_SEND_RATE = 500; // Bytes per second const static int MIN_PACKET_SIZE = 500; - const static int MAX_PACKET_SIZE = 1100; // Set to 1100 as MTU is hard coded at 1200 (as of 2012-01-28) -}; // namespace LatentTransfer + const static int MAX_PACKET_SIZE = 1100; // Set to 1100 as MTU is hard coded at 1200 (as of 2012-01-28) +}; // namespace LatentTransfer // // One complete item to send @@ -56,18 +56,18 @@ struct SSendItem { } - uint uiId; // Handle - CBufferRef bufferRef; // The data to transfer - uint uiRate; // Desired bytes per second - ushort usCategory; // Data category - uint uiReadPosition; // Current position in the buffer sent so far - bool bSendStarted; // true when the send actually starts - bool bSendFinishing; // true when the last part has been sent - void* pLuaMain; // For cancelling by VM - ushort usResourceNetId; // Only allow packet if this resource is running (ignored if 0xFFFF) - - int iEstSendDurationMsRemaining; // Used for status calculations - int iEstSendDurationMsUsed; // '' + uint uiId; // Handle + CBufferRef bufferRef; // The data to transfer + uint uiRate; // Desired bytes per second + ushort usCategory; // Data category + uint uiReadPosition; // Current position in the buffer sent so far + bool bSendStarted; // true when the send actually starts + bool bSendFinishing; // true when the last part has been sent + void* pLuaMain; // For cancelling by VM + ushort usResourceNetId; // Only allow packet if this resource is running (ignored if 0xFFFF) + + int iEstSendDurationMsRemaining; // Used for status calculations + int iEstSendDurationMsUsed; // '' }; // @@ -77,14 +77,14 @@ struct SReceiveItem { SReceiveItem() : usId(0), uiRate(0), usCategory(0), usResourceNetId(0xFFFF), uiWritePosition(0), bReceiveStarted(false) {} - ushort usId; // Part of handle - Used for verification - CBuffer buffer; // The receive buffer - uint uiRate; // Desired bytes per second (Info from the sender - not really used for anything here yet) - ushort usCategory; // Data category - ushort usResourceNetId; // Only allow packet if this resource is running (ignored if 0xFFFF) + ushort usId; // Part of handle - Used for verification + CBuffer buffer; // The receive buffer + uint uiRate; // Desired bytes per second (Info from the sender - not really used for anything here yet) + ushort usCategory; // Data category + ushort usResourceNetId; // Only allow packet if this resource is running (ignored if 0xFFFF) - uint uiWritePosition; // Current position in the buffer received so far - bool bReceiveStarted; // true when the receive actually starts + uint uiWritePosition; // Current position in the buffer received so far + bool bReceiveStarted; // true when the receive actually starts }; // @@ -92,10 +92,10 @@ struct SReceiveItem // struct SSendStatus { - int iStartTimeMsOffset; // Est. start time (Negative if already started) - int iEndTimeMsOffset; // Est. end time + int iStartTimeMsOffset; // Est. start time (Negative if already started) + int iEndTimeMsOffset; // Est. end time int iTotalSize; - double dPercentComplete; // How much done + double dPercentComplete; // How much done }; /////////////////////////////////////////////////////////////// diff --git a/Shared/mods/deathmatch/logic/CScriptDebugging.cpp b/Shared/mods/deathmatch/logic/CScriptDebugging.cpp index cdbc9b3728c..ff37d7d7481 100644 --- a/Shared/mods/deathmatch/logic/CScriptDebugging.cpp +++ b/Shared/mods/deathmatch/logic/CScriptDebugging.cpp @@ -72,16 +72,16 @@ bool CScriptDebugging::CheckForSufficientDebugLevel(std::uint8_t playerDebugLeve { switch (messageDebugLevel) { - case MESSAGE_TYPE_ERROR: - return playerDebugLevel >= ERRORS_ONLY; - case MESSAGE_TYPE_WARNING: - return playerDebugLevel >= ERRORS_AND_WARNINGS; - case MESSAGE_TYPE_INFO: - case MESSAGE_TYPE_CUSTOM: - case MESSAGE_TYPE_DEBUG: - return playerDebugLevel == ALL; - default: - break; + case MESSAGE_TYPE_ERROR: + return playerDebugLevel >= ERRORS_ONLY; + case MESSAGE_TYPE_WARNING: + return playerDebugLevel >= ERRORS_AND_WARNINGS; + case MESSAGE_TYPE_INFO: + case MESSAGE_TYPE_CUSTOM: + case MESSAGE_TYPE_DEBUG: + return playerDebugLevel == ALL; + default: + break; } return false; diff --git a/Shared/mods/deathmatch/logic/CStringName.cpp b/Shared/mods/deathmatch/logic/CStringName.cpp index f3d6d18df81..9bfc5778e73 100644 --- a/Shared/mods/deathmatch/logic/CStringName.cpp +++ b/Shared/mods/deathmatch/logic/CStringName.cpp @@ -15,7 +15,7 @@ extern "C" { - #include "lua/src/lstring.h" +#include "lua/src/lstring.h" } static StringNameHash MakeStringNameHash(const std::string_view& str) @@ -37,8 +37,8 @@ class CStringNameStorage return &ZERO_NAME_DATA; } - const StringNameHash hash = MakeStringNameHash(str); - const uint32_t idx = hash & CStringName::STRING_TABLE_MASK; + const StringNameHash hash = MakeStringNameHash(str); + const uint32_t idx = hash & CStringName::STRING_TABLE_MASK; CIntrusiveDoubleLinkedList& list = m_table[idx]; CStringNameData* data = list.First(); @@ -59,7 +59,7 @@ class CStringNameStorage data->AddRef(); return data; - } + } void Release(CStringNameData* data) { @@ -71,7 +71,7 @@ class CStringNameStorage CStringNameData* Find(const std::string_view& str, StringNameHash hash) { - const uint32_t idx = hash & CStringName::STRING_TABLE_MASK; + const uint32_t idx = hash & CStringName::STRING_TABLE_MASK; CIntrusiveDoubleLinkedList& list = m_table[idx]; for (CStringNameData& data : list) @@ -95,7 +95,7 @@ class CStringNameStorage std::array, CStringName::STRING_TABLE_LEN> m_table; }; -CStringNameData CStringNameStorage::ZERO_NAME_DATA{ {}, 0u, 1 }; +CStringNameData CStringNameStorage::ZERO_NAME_DATA{{}, 0u, 1}; /* CStringNameData @@ -119,35 +119,29 @@ void CStringNameData::RemoveRef() */ const CStringName CStringName::ZERO{}; -CStringName::CStringName() : - m_data(CStringNameStorage::Instance().Get({})) +CStringName::CStringName() : m_data(CStringNameStorage::Instance().Get({})) { } -CStringName::CStringName(const char* str) : - m_data(CStringNameStorage::Instance().Get(str)) +CStringName::CStringName(const char* str) : m_data(CStringNameStorage::Instance().Get(str)) { } -CStringName::CStringName(const std::string& str) : - m_data(CStringNameStorage::Instance().Get(str)) +CStringName::CStringName(const std::string& str) : m_data(CStringNameStorage::Instance().Get(str)) { } -CStringName::CStringName(const std::string_view& str) : - m_data(CStringNameStorage::Instance().Get(str)) +CStringName::CStringName(const std::string_view& str) : m_data(CStringNameStorage::Instance().Get(str)) { } -CStringName::CStringName(const CStringName& name) : - m_data(name.m_data) +CStringName::CStringName(const CStringName& name) : m_data(name.m_data) { if (m_data) m_data->AddRef(); } -CStringName::CStringName(CStringNameData* data) : - m_data(data) +CStringName::CStringName(CStringNameData* data) : m_data(data) { if (m_data) m_data->AddRef(); diff --git a/Shared/mods/deathmatch/logic/CStringName.h b/Shared/mods/deathmatch/logic/CStringName.h index cd3fa79f022..bece80c9ee0 100644 --- a/Shared/mods/deathmatch/logic/CStringName.h +++ b/Shared/mods/deathmatch/logic/CStringName.h @@ -22,12 +22,7 @@ class CStringNameData : public CIntrusiveDoubleLinkedListNode public: CStringNameData() = default; - CStringNameData(const std::string_view& name, StringNameHash hash, size_t refs = 0) : - m_name(name), - m_hash(hash), - m_refs(refs) - { - } + CStringNameData(const std::string_view& name, StringNameHash hash, size_t refs = 0) : m_name(name), m_hash(hash), m_refs(refs) {} void AddRef(); @@ -44,11 +39,12 @@ class CStringName { friend class CStringNameStorage; - enum { - STRING_TABLE_BITS = 16, - STRING_TABLE_LEN = 1 << STRING_TABLE_BITS, - STRING_TABLE_MASK = STRING_TABLE_LEN - 1 - }; + enum + { + STRING_TABLE_BITS = 16, + STRING_TABLE_LEN = 1 << STRING_TABLE_BITS, + STRING_TABLE_MASK = STRING_TABLE_LEN - 1 + }; public: // Default constructor @@ -67,32 +63,32 @@ class CStringName CStringName(const CStringName& name); // Copy-assignment from another string name. - CStringName& operator =(const CStringName& name); + CStringName& operator=(const CStringName& name); // Copy-assignment from string. - CStringName& operator =(const std::string& str); + CStringName& operator=(const std::string& str); // Copy-assignment from string view. - CStringName& operator =(const std::string_view& str); + CStringName& operator=(const std::string_view& str); // Destruct ~CStringName(); // Test for equality with another string name. - bool operator ==(const CStringName& rhs) const { return m_data == rhs.m_data; } + bool operator==(const CStringName& rhs) const { return m_data == rhs.m_data; } // Test for inequality with another string name. - bool operator !=(const CStringName& rhs) const { return m_data != rhs.m_data; } + bool operator!=(const CStringName& rhs) const { return m_data != rhs.m_data; } // Test if less than another string name. - bool operator <(const CStringName& rhs) const { return m_data->m_hash < rhs.m_data->m_hash; } + bool operator<(const CStringName& rhs) const { return m_data->m_hash < rhs.m_data->m_hash; } // Test if greater than another string name. - bool operator >(const CStringName& rhs) const { return m_data->m_hash > rhs.m_data->m_hash; } + bool operator>(const CStringName& rhs) const { return m_data->m_hash > rhs.m_data->m_hash; } - const std::string* operator ->() const { return &m_data->m_name; } + const std::string* operator->() const { return &m_data->m_name; } - const std::string& operator *() const { return m_data->m_name; } + const std::string& operator*() const { return m_data->m_name; } // Return true if nonzero string name value. explicit operator bool() const { return m_data != nullptr; } @@ -122,14 +118,11 @@ class CStringName private: // String name data - CStringNameData* m_data{}; + CStringNameData* m_data{}; }; template <> struct std::hash { - std::size_t operator()(const CStringName& k) const - { - return static_cast(k.Hash()); - } + std::size_t operator()(const CStringName& k) const { return static_cast(k.Hash()); } }; diff --git a/Shared/mods/deathmatch/logic/Utils.cpp b/Shared/mods/deathmatch/logic/Utils.cpp index e3107c77a68..05f6e1898aa 100644 --- a/Shared/mods/deathmatch/logic/Utils.cpp +++ b/Shared/mods/deathmatch/logic/Utils.cpp @@ -84,8 +84,8 @@ bool IsValidFilePath(const char* szDir) // iterate through the char array for (unsigned int i = 0; i < uiLen; i++) { - c = szDir[i]; // current character - c_d = (i < (uiLen - 1)) ? szDir[i + 1] : 0; // one character ahead, if any + c = szDir[i]; // current character + c_d = (i < (uiLen - 1)) ? szDir[i + 1] : 0; // one character ahead, if any if (!IsVisibleCharacter(c) || c == ':' || (c == '.' && c_d == '.') || (c == '\\' && c_d == '\\')) return false; } @@ -102,8 +102,8 @@ bool IsValidFilePath(const char* szDir, size_t length) // iterate through the char array for (size_t i = 0; i < length; i++) { - c = szDir[i]; // current character - c_d = (i < (length - 1)) ? szDir[i + 1] : 0; // one character ahead, if any + c = szDir[i]; // current character + c_d = (i < (length - 1)) ? szDir[i + 1] : 0; // one character ahead, if any if (!IsVisibleCharacter(c) || c == ':' || (c == '.' && c_d == '.') || (c == '\\' && c_d == '\\')) return false; } @@ -119,9 +119,9 @@ void ReplaceOccurrencesInString(std::string& s, const char* a, const char* b) void RaiseFatalError(unsigned int uiCode) { -#ifdef MTA_DEBUG + #ifdef MTA_DEBUG assert(0); -#endif + #endif // Populate the message and show the box SString strBuffer(_("Fatal error (%u). If this problem persists, please check out multitheftauto.com for support."), uiCode); @@ -142,7 +142,7 @@ void RaiseProtocolError(unsigned int uiCode) // Populate the message and show the box SString strBuffer(_("Protocol error (%u). If this problem persists, please check out multitheftauto.com for support."), uiCode); SString strTroubleLink(SString("protocol-error&code=%d", uiCode)); - g_pCore->ShowErrorMessageBox(_("Connection error") + _E("CD63"), strBuffer, strTroubleLink); // Protocol error + g_pCore->ShowErrorMessageBox(_("Connection error") + _E("CD63"), strBuffer, strTroubleLink); // Protocol error // Request the mod unload g_pCore->GetModManager()->RequestUnload(); @@ -202,16 +202,16 @@ void LongToDottedIP(unsigned long ulIP, char* szDottedIP) bool DoesDirectoryExist(const char* szPath) { -#ifdef WIN32 + #ifdef WIN32 DWORD dwAtr = GetFileAttributes(szPath); if (dwAtr == INVALID_FILE_ATTRIBUTES) return false; return ((dwAtr & FILE_ATTRIBUTE_DIRECTORY) != 0); -#else + #else struct stat Info; stat(szPath, &Info); return (S_ISDIR(Info.st_mode)); -#endif + #endif } bool CheckNickProvided(const char* szNick) @@ -376,22 +376,22 @@ void DisconnectConnectionDesync(CGame* pGame, CPlayer& Player, unsigned int uiCo bool InitializeSockets() { -#ifdef WIN32 + #ifdef WIN32 WSADATA wsaData; if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR) { WSACleanup(); return false; } -#endif + #endif return true; } bool CleanupSockets() { -#ifdef WIN32 + #ifdef WIN32 WSACleanup(); -#endif + #endif return true; } #endif @@ -461,7 +461,7 @@ bool IsValidFilePath(const char* szDir) unsigned int uiLen = strlen(szDir); - if (uiLen > 0 && szDir[uiLen - 1] == '/') // will return false if ending with an invalid character, mainly used for linux (#6871) + if (uiLen > 0 && szDir[uiLen - 1] == '/') // will return false if ending with an invalid character, mainly used for linux (#6871) return false; unsigned char c, c_d; @@ -469,8 +469,8 @@ bool IsValidFilePath(const char* szDir) // iterate through the char array for (unsigned int i = 0; i < uiLen; i++) { - c = szDir[i]; // current character - c_d = (i < (uiLen - 1)) ? szDir[i + 1] : 0; // one character ahead, if any + c = szDir[i]; // current character + c_d = (i < (uiLen - 1)) ? szDir[i + 1] : 0; // one character ahead, if any if (!IsVisibleCharacter(c) || c == ':' || (c == '.' && c_d == '.') || (c == '\\' && c_d == '\\')) return false; } @@ -487,8 +487,8 @@ bool IsValidFilePath(const char* szDir, size_t length) // iterate through the char array for (size_t i = 0; i < length; i++) { - c = szDir[i]; // current character - c_d = (i < (length - 1)) ? szDir[i + 1] : 0; // one character ahead, if any + c = szDir[i]; // current character + c_d = (i < (length - 1)) ? szDir[i + 1] : 0; // one character ahead, if any if (!IsVisibleCharacter(c) || c == ':' || (c == '.' && c_d == '.') || (c == '\\' && c_d == '\\')) return false; } @@ -502,7 +502,7 @@ bool IsValidOrganizationPath(const char* szDir) unsigned int uiLen = strlen(szDir); - if (uiLen > 0 && szDir[uiLen - 1] == '/') // will return false if ending with an invalid character, mainly used for linux (#6871) + if (uiLen > 0 && szDir[uiLen - 1] == '/') // will return false if ending with an invalid character, mainly used for linux (#6871) return false; unsigned char c; @@ -511,7 +511,7 @@ bool IsValidOrganizationPath(const char* szDir) // iterate through the char array for (unsigned int i = 0; i < uiLen; i++) { - c = szDir[i]; // current character + c = szDir[i]; // current character // Enforce braces around visible letters if (!bInsideBraces && IsVisibleCharacter(c) && c != '[' && c != ']' && c != '/' && c != '\\') @@ -520,21 +520,21 @@ bool IsValidOrganizationPath(const char* szDir) if (c == '[') { if (bInsideBraces) - return false; // Duplicate braces (e.g. "[hel[lo]world]") + return false; // Duplicate braces (e.g. "[hel[lo]world]") else bInsideBraces = true; } else if (c == ']') { if (!bInsideBraces) - return false; // Ending brace without opening brace (e.g. "hello]") + return false; // Ending brace without opening brace (e.g. "hello]") else bInsideBraces = false; } else if (c == '/' || c == '\\') { if (bInsideBraces) - return false; // Slash within braches (e.g. "[hell/o]") + return false; // Slash within braches (e.g. "[hell/o]") } } @@ -734,10 +734,10 @@ bool ReadSmallKeysync(CControllerState& ControllerState, NetBitStreamInterface& short sButtonCross = keys.data.bButtonCross ? 255 : 0; { if (keys.data.ucButtonSquare != 0) - sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present + sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present if (keys.data.ucButtonCross != 0) - sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present + sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present } // Put the result into the controllerstate @@ -757,16 +757,16 @@ bool ReadSmallKeysync(CControllerState& ControllerState, NetBitStreamInterface& void WriteSmallKeysync(const CControllerState& ControllerState, NetBitStreamInterface& BitStream) { SSmallKeysyncSync keys; - keys.data.bLeftShoulder1 = (ControllerState.LeftShoulder1 != 0); // Action / Secondary-Fire - keys.data.bRightShoulder1 = (ControllerState.RightShoulder1 != 0); // Aim-Weapon / Handbrake - keys.data.bButtonSquare = (ControllerState.ButtonSquare != 0); // Jump / Reverse - keys.data.bButtonCross = (ControllerState.ButtonCross != 0); // Sprint / Accelerate - keys.data.bButtonCircle = (ControllerState.ButtonCircle != 0); // Fire // Fire - keys.data.bButtonTriangle = (ControllerState.ButtonTriangle != 0); // Enter/Exit/Special-Attack / Enter/exit - keys.data.bShockButtonL = (ControllerState.ShockButtonL != 0); // Crouch / Horn - keys.data.bPedWalk = (ControllerState.m_bPedWalk != 0); // Walk / - - keys.data.ucButtonSquare = (unsigned char)ControllerState.ButtonSquare; // Reverse - keys.data.ucButtonCross = (unsigned char)ControllerState.ButtonCross; // Accelerate + keys.data.bLeftShoulder1 = (ControllerState.LeftShoulder1 != 0); // Action / Secondary-Fire + keys.data.bRightShoulder1 = (ControllerState.RightShoulder1 != 0); // Aim-Weapon / Handbrake + keys.data.bButtonSquare = (ControllerState.ButtonSquare != 0); // Jump / Reverse + keys.data.bButtonCross = (ControllerState.ButtonCross != 0); // Sprint / Accelerate + keys.data.bButtonCircle = (ControllerState.ButtonCircle != 0); // Fire // Fire + keys.data.bButtonTriangle = (ControllerState.ButtonTriangle != 0); // Enter/Exit/Special-Attack / Enter/exit + keys.data.bShockButtonL = (ControllerState.ShockButtonL != 0); // Crouch / Horn + keys.data.bPedWalk = (ControllerState.m_bPedWalk != 0); // Walk / - + keys.data.ucButtonSquare = (unsigned char)ControllerState.ButtonSquare; // Reverse + keys.data.ucButtonCross = (unsigned char)ControllerState.ButtonCross; // Accelerate keys.data.sLeftStickX = ControllerState.LeftStickX; keys.data.sLeftStickY = ControllerState.LeftStickY; @@ -785,10 +785,10 @@ bool ReadFullKeysync(CControllerState& ControllerState, NetBitStreamInterface& B short sButtonCross = keys.data.bButtonCross ? 255 : 0; { if (keys.data.ucButtonSquare != 0) - sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present + sButtonSquare = (short)keys.data.ucButtonSquare; // override controller state with analog data if present if (keys.data.ucButtonCross != 0) - sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present + sButtonCross = (short)keys.data.ucButtonCross; // override controller state with analog data if present } // Put the result into the controllerstate @@ -856,10 +856,10 @@ void ReadCameraOrientation(const CVector& vecBasePosition, NetBitStreamInterface uint uiNumBits; float fRange; } bitCountTable[4] = { - {3, 4.0f}, // 3 bits is +-4 12 bits total - {5, 16.0f}, // 5 bits is +-16 18 bits total - {9, 256.0f}, // 9 bits is +-256 30 bits total - {14, 8192.0f}, // 14 bits is +-8192 45 bits total + {3, 4.0f}, // 3 bits is +-4 12 bits total + {5, 16.0f}, // 5 bits is +-16 18 bits total + {9, 256.0f}, // 9 bits is +-256 30 bits total + {14, 8192.0f}, // 14 bits is +-8192 45 bits total }; // Read flag bool bUseAbsolutePosition = false; @@ -1006,7 +1006,7 @@ SString LongToDottedIP(unsigned long ulIP) CVector euler_ZXY_to_ZYX(const CVector& a_vZXY) { CVector vZXY(a_vZXY); - ConvertDegreesToRadiansNoWrap(vZXY); // NoWrap for this conversion since it's used for cos/sin only + ConvertDegreesToRadiansNoWrap(vZXY); // NoWrap for this conversion since it's used for cos/sin only float cx = cos(vZXY.fX); float sx = sin(vZXY.fX); @@ -1038,7 +1038,7 @@ CVector euler_ZXY_to_ZYX(const CVector& a_vZXY) CVector euler_ZYX_to_ZXY(const CVector& a_vZYX) { CVector vZYX(a_vZYX); - ConvertDegreesToRadiansNoWrap(vZYX); // NoWrap for this conversion since it's used for cos/sin only + ConvertDegreesToRadiansNoWrap(vZYX); // NoWrap for this conversion since it's used for cos/sin only float cx = cos(vZYX.fX); float sx = sin(vZYX.fX); diff --git a/Shared/mods/deathmatch/logic/lua/CLuaFunctionParser.h b/Shared/mods/deathmatch/logic/lua/CLuaFunctionParser.h index c4f74a3d9c5..9cf6f73f0e3 100644 --- a/Shared/mods/deathmatch/logic/lua/CLuaFunctionParser.h +++ b/Shared/mods/deathmatch/logic/lua/CLuaFunctionParser.h @@ -26,8 +26,7 @@ class LuaFunctionError bool m_bWarning; public: - constexpr LuaFunctionError(const char* what, bool throwWarning = true) noexcept - : m_message(what), m_bWarning(throwWarning) {} + constexpr LuaFunctionError(const char* what, bool throwWarning = true) noexcept : m_message(what), m_bWarning(throwWarning) {} constexpr const char* what() const noexcept { return m_message; } constexpr bool IsWarning() const noexcept { return m_bWarning; } @@ -95,7 +94,7 @@ struct CLuaFunctionParserBase else if constexpr (std::is_same_v) return "colour"; else if constexpr (std::is_same_v) - return ""; // not reachable + return ""; // not reachable else if constexpr (is_variant::value) { SString strTypes; @@ -325,10 +324,9 @@ struct CLuaFunctionParserBase return false; using class_t = std::remove_pointer_t; - int tempIndex{index}; - void* pValue = lua::PopPrimitive(L, tempIndex); - auto result = iArgument == LUA_TLIGHTUSERDATA ? UserDataCast((class_t*)pValue, L) : - UserDataCast(*reinterpret_cast(pValue), L); + int tempIndex{index}; + void* pValue = lua::PopPrimitive(L, tempIndex); + auto result = iArgument == LUA_TLIGHTUSERDATA ? UserDataCast((class_t*)pValue, L) : UserDataCast(*reinterpret_cast(pValue), L); return result != nullptr; } @@ -410,7 +408,7 @@ struct CLuaFunctionParserBase return lua::PopPrimitive(L, index); else if constexpr (std::is_same_v) return lua::PopPrimitive(L, index); - else if constexpr (std::is_integral_v || std::is_floating_point_v) // bool is an integral type, so must pop it before ^^ + else if constexpr (std::is_integral_v || std::is_floating_point_v) // bool is an integral type, so must pop it before ^^ { const auto number = lua::PopPrimitive(L, index); @@ -481,7 +479,7 @@ struct CLuaFunctionParserBase return std::nullopt; } - else if constexpr (is_2specialization::value) // 2 specialization due to allocator + else if constexpr (is_2specialization::value) // 2 specialization due to allocator { using param = typename is_2specialization::param1_t; T vecData; @@ -497,7 +495,7 @@ struct CLuaFunctionParserBase int i = -1; vecData.emplace_back(PopUnsafe(L, i)); - lua_pop(L, 1); // drop value, keep key for lua_next + lua_pop(L, 1); // drop value, keep key for lua_next } ++index; return vecData; @@ -527,7 +525,7 @@ struct CLuaFunctionParserBase auto v = PopUnsafe(L, i); auto k = PopUnsafe(L, i); map.emplace(std::move(k), std::move(v)); - lua_pop(L, 2); // drop values(key copy and value), keep original key for lua_next + lua_pop(L, 2); // drop values(key copy and value), keep original key for lua_next } ++index; return map; @@ -579,9 +577,10 @@ struct CLuaFunctionParserBase int iType = lua_type(L, index); bool isLightUserData = iType == LUA_TLIGHTUSERDATA; void* pValue = lua::PopPrimitive(L, index); - auto cast = [isLightUserData, pValue, L](auto null) { + auto cast = [isLightUserData, pValue, L](auto null) + { return isLightUserData ? UserDataCast(reinterpret_cast(pValue), L) - : UserDataCast(*reinterpret_cast(pValue), L); + : UserDataCast(*reinterpret_cast(pValue), L); }; // A vector2 may also be filled from a vector3/vector4 if (CLuaVector2D* pVec2D = cast((CLuaVector2D*)0); pVec2D != nullptr) @@ -609,9 +608,10 @@ struct CLuaFunctionParserBase int iType = lua_type(L, index); bool isLightUserData = iType == LUA_TLIGHTUSERDATA; void* pValue = lua::PopPrimitive(L, index); - auto cast = [isLightUserData, pValue, L](auto null) { + auto cast = [isLightUserData, pValue, L](auto null) + { return isLightUserData ? UserDataCast(reinterpret_cast(pValue), L) - : UserDataCast(*reinterpret_cast(pValue), L); + : UserDataCast(*reinterpret_cast(pValue), L); }; // A vector3 may also be filled from a vector4 if (CLuaVector3D* pVec3D = cast((CLuaVector3D*)0); pVec3D != nullptr) @@ -638,9 +638,10 @@ struct CLuaFunctionParserBase int iType = lua_type(L, index); bool isLightUserData = iType == LUA_TLIGHTUSERDATA; void* pValue = lua::PopPrimitive(L, index); - auto cast = [isLightUserData, pValue, L](auto null) { + auto cast = [isLightUserData, pValue, L](auto null) + { return isLightUserData ? UserDataCast(reinterpret_cast(pValue), L) - : UserDataCast(*reinterpret_cast(pValue), L); + : UserDataCast(*reinterpret_cast(pValue), L); }; // A vector3 may also be filled from a vector4 if (CLuaVector4D* pVec4D = cast((CLuaVector4D*)0); pVec4D != nullptr) @@ -689,9 +690,10 @@ struct CLuaFunctionParserBase int iType = lua_type(L, index); bool isLightUserData = iType == LUA_TLIGHTUSERDATA; void* pValue = lua::PopPrimitive(L, index); - auto cast = [isLightUserData, pValue, L](auto null) { + auto cast = [isLightUserData, pValue, L](auto null) + { return isLightUserData ? UserDataCast(reinterpret_cast(pValue), L) - : UserDataCast(*reinterpret_cast(pValue), L); + : UserDataCast(*reinterpret_cast(pValue), L); }; // A vector4 may also be filled from a CLuaMatrix if (CLuaMatrix* pMatrix = cast((CLuaMatrix*)0); pMatrix != nullptr) @@ -832,7 +834,7 @@ struct CLuaFunctionParser : CLuaFunctionP // Case where F is a class method pointer // Note: If you see weird compiler errors like: Undefined type, overload resolution failed, etc.. // Ask on Dev Discord(#new-argument-parser), because rn this implementation is pretty beta. - 03/2021 -template +template struct CLuaFunctionParser { // Remove constness here, because we must be able to std::move diff --git a/Shared/mods/deathmatch/logic/lua/CLuaOverloadParser.h b/Shared/mods/deathmatch/logic/lua/CLuaOverloadParser.h index 7e77df4ebd0..be5a61eaf01 100644 --- a/Shared/mods/deathmatch/logic/lua/CLuaOverloadParser.h +++ b/Shared/mods/deathmatch/logic/lua/CLuaOverloadParser.h @@ -59,13 +59,14 @@ struct CLuaOverloadParser static ChosenFunction MakeChoice(std::variant var) { return std::visit( - [](auto&& f) { + [](auto&& f) + { using ft = decltype(f); if constexpr (!std::is_convertible_v>) - return ChosenFunction::FUNCB; // if it cannot match A, B it is + return ChosenFunction::FUNCB; // if it cannot match A, B it is if constexpr (!std::is_convertible_v>) - return ChosenFunction::FUNCA; // if it cannot match B, A it is - return ChosenFunction::COMMON; // Both match + return ChosenFunction::FUNCA; // if it cannot match B, A it is + return ChosenFunction::COMMON; // Both match }, var); } diff --git a/Shared/mods/deathmatch/logic/lua/CLuaShared.h b/Shared/mods/deathmatch/logic/lua/CLuaShared.h index 5fe58f30812..046d9b6d00f 100644 --- a/Shared/mods/deathmatch/logic/lua/CLuaShared.h +++ b/Shared/mods/deathmatch/logic/lua/CLuaShared.h @@ -7,7 +7,7 @@ *****************************************************************************/ #pragma once -#define LUA_GC_EXTRA_BYTES 30 // Used in hack to make lua GC more aggressive when using OOP Matrix & Vector +#define LUA_GC_EXTRA_BYTES 30 // Used in hack to make lua GC more aggressive when using OOP Matrix & Vector // Lua function definitions (shared) #include "luadefs/CLuaBitDefs.h" diff --git a/Shared/mods/deathmatch/logic/lua/CLuaStackChecker.h b/Shared/mods/deathmatch/logic/lua/CLuaStackChecker.h index dceb65e7365..2663665b4b4 100644 --- a/Shared/mods/deathmatch/logic/lua/CLuaStackChecker.h +++ b/Shared/mods/deathmatch/logic/lua/CLuaStackChecker.h @@ -47,10 +47,10 @@ namespace lua } } }; -} // namespace lua +} // namespace lua #ifdef MTA_DEBUG -#define LUA_STACK_EXPECT(i) lua::CLuaStackChecker invalidHiddenName(L, i) + #define LUA_STACK_EXPECT(i) lua::CLuaStackChecker invalidHiddenName(L, i) #else -#define LUA_STACK_EXPECT(i) + #define LUA_STACK_EXPECT(i) #endif diff --git a/Shared/mods/deathmatch/logic/lua/CLuaTimer.cpp b/Shared/mods/deathmatch/logic/lua/CLuaTimer.cpp index 5de04e728b8..c3fd609ca99 100644 --- a/Shared/mods/deathmatch/logic/lua/CLuaTimer.cpp +++ b/Shared/mods/deathmatch/logic/lua/CLuaTimer.cpp @@ -46,7 +46,7 @@ void CLuaTimer::ExecuteTimer(CLuaMain* pLuaMain) { lua_State* pState = pLuaMain->GetVM(); - LUA_CHECKSTACK(pState, 1); // Ensure some room + LUA_CHECKSTACK(pState, 1); // Ensure some room // Store the current values of the globals lua_getglobal(pState, "sourceTimer"); diff --git a/Shared/mods/deathmatch/logic/lua/LuaBasic.cpp b/Shared/mods/deathmatch/logic/lua/LuaBasic.cpp index c7b369e4459..109867efcfc 100644 --- a/Shared/mods/deathmatch/logic/lua/LuaBasic.cpp +++ b/Shared/mods/deathmatch/logic/lua/LuaBasic.cpp @@ -42,11 +42,11 @@ namespace lua return lua_touserdata(L, index++); } - template<> + template <> lua_Number PopPrimitive(lua_State* L, int& index) { return lua_tonumber(L, index++); } // Int types aren't Poppable directly, because they need to be checked for under/overflow, NaN, inf -} // namespace lua +} // namespace lua diff --git a/Shared/mods/deathmatch/logic/lua/LuaBasic.h b/Shared/mods/deathmatch/logic/lua/LuaBasic.h index 77ada03315e..d2a8856fc73 100644 --- a/Shared/mods/deathmatch/logic/lua/LuaBasic.h +++ b/Shared/mods/deathmatch/logic/lua/LuaBasic.h @@ -35,20 +35,47 @@ namespace lua // Push should push a value of type T to the Lua Stack // This will always increase the stack size by 1 - inline void Push(lua_State* L, int value) { lua_pushnumber(L, value); } - inline void Push(lua_State* L, unsigned int value) { lua_pushnumber(L, value); } - inline void Push(lua_State* L, float value) { lua_pushnumber(L, value); } - inline void Push(lua_State* L, double value) { lua_pushnumber(L, value); } + inline void Push(lua_State* L, int value) + { + lua_pushnumber(L, value); + } + inline void Push(lua_State* L, unsigned int value) + { + lua_pushnumber(L, value); + } + inline void Push(lua_State* L, float value) + { + lua_pushnumber(L, value); + } + inline void Push(lua_State* L, double value) + { + lua_pushnumber(L, value); + } - inline void Push(lua_State* L, bool value) { lua_pushboolean(L, value); } + inline void Push(lua_State* L, bool value) + { + lua_pushboolean(L, value); + } - inline void Push(lua_State* L, std::nullptr_t) { lua_pushnil(L); } + inline void Push(lua_State* L, std::nullptr_t) + { + lua_pushnil(L); + } - inline void Push(lua_State* L, const char* value) { lua_pushstring(L, value); } + inline void Push(lua_State* L, const char* value) + { + lua_pushstring(L, value); + } - inline void Push(lua_State* L, const std::string& value) { lua_pushlstring(L, value.data(), value.length()); } + inline void Push(lua_State* L, const std::string& value) + { + lua_pushlstring(L, value.data(), value.length()); + } - inline void Push(lua_State* L, const std::string_view& value) { lua_pushlstring(L, value.data(), value.length()); } + inline void Push(lua_State* L, const std::string_view& value) + { + lua_pushlstring(L, value.data(), value.length()); + } inline void Push(lua_State* L, const CLuaArgument& arg) { @@ -61,36 +88,99 @@ namespace lua arg.Push(L); } - inline void Push(lua_State* L, const CLuaArguments& args) { args.PushAsTable(L); } + inline void Push(lua_State* L, const CLuaArguments& args) + { + args.PushAsTable(L); + } - inline void Push(lua_State* L, const CVector2D& value) { lua_pushvector(L, value); } + inline void Push(lua_State* L, const CVector2D& value) + { + lua_pushvector(L, value); + } - inline void Push(lua_State* L, const CVector& value) { lua_pushvector(L, value); } + inline void Push(lua_State* L, const CVector& value) + { + lua_pushvector(L, value); + } - inline void Push(lua_State* L, const CVector4D& value) { lua_pushvector(L, value); } + inline void Push(lua_State* L, const CVector4D& value) + { + lua_pushvector(L, value); + } - inline void Push(lua_State* L, const CMatrix& value) { lua_pushmatrix(L, value); } + inline void Push(lua_State* L, const CMatrix& value) + { + lua_pushmatrix(L, value); + } - // Script entities - #ifdef MTA_CLIENT - inline void Push(lua_State* L, const CClientEntity* value) { lua_pushelement(L, const_cast(value)); } - #else - inline void Push(lua_State* L, const CElement* value) { lua_pushelement(L, const_cast(value)); } - inline void Push(lua_State* L, const CAccount* value) { lua_pushaccount(L, const_cast(value)); } - inline void Push(lua_State* L, const CAccessControlList* value) { lua_pushacl(L, const_cast(value)); } - inline void Push(lua_State* L, const CAccessControlListGroup* value) { lua_pushaclgroup(L, const_cast(value)); } - inline void Push(lua_State* L, const CBan* value) { lua_pushban(L, const_cast(value)); } - inline void Push(lua_State* L, const CTextDisplay* value) { lua_pushtextdisplay(L, const_cast(value)); } - inline void Push(lua_State* L, const CTextItem* value) { lua_pushtextitem(L, const_cast(value)); } - inline void Push(lua_State* L, const CDbJobData* value) { lua_pushquery(L, const_cast(value)); } - #endif - inline void Push(lua_State* L, const CResource* value) { lua_pushresource(L, const_cast(value)); } - inline void Push(lua_State* L, const CXMLNode* value) { lua_pushxmlnode(L, const_cast(value)); } - inline void Push(lua_State* L, const CLuaTimer* value) { lua_pushtimer(L, const_cast(value)); } - inline void Push(lua_State* L, const CLuaVector2D* value) { lua_pushvector(L, *value); } - inline void Push(lua_State* L, const CLuaVector3D* value) { lua_pushvector(L, *value); } - inline void Push(lua_State* L, const CLuaVector4D* value) { lua_pushvector(L, *value); } - inline void Push(lua_State* L, const CLuaMatrix* value) { lua_pushmatrix(L, *value); } +// Script entities +#ifdef MTA_CLIENT + inline void Push(lua_State* L, const CClientEntity* value) + { + lua_pushelement(L, const_cast(value)); + } +#else + inline void Push(lua_State* L, const CElement* value) + { + lua_pushelement(L, const_cast(value)); + } + inline void Push(lua_State* L, const CAccount* value) + { + lua_pushaccount(L, const_cast(value)); + } + inline void Push(lua_State* L, const CAccessControlList* value) + { + lua_pushacl(L, const_cast(value)); + } + inline void Push(lua_State* L, const CAccessControlListGroup* value) + { + lua_pushaclgroup(L, const_cast(value)); + } + inline void Push(lua_State* L, const CBan* value) + { + lua_pushban(L, const_cast(value)); + } + inline void Push(lua_State* L, const CTextDisplay* value) + { + lua_pushtextdisplay(L, const_cast(value)); + } + inline void Push(lua_State* L, const CTextItem* value) + { + lua_pushtextitem(L, const_cast(value)); + } + inline void Push(lua_State* L, const CDbJobData* value) + { + lua_pushquery(L, const_cast(value)); + } +#endif + inline void Push(lua_State* L, const CResource* value) + { + lua_pushresource(L, const_cast(value)); + } + inline void Push(lua_State* L, const CXMLNode* value) + { + lua_pushxmlnode(L, const_cast(value)); + } + inline void Push(lua_State* L, const CLuaTimer* value) + { + lua_pushtimer(L, const_cast(value)); + } + inline void Push(lua_State* L, const CLuaVector2D* value) + { + lua_pushvector(L, *value); + } + inline void Push(lua_State* L, const CLuaVector3D* value) + { + lua_pushvector(L, *value); + } + inline void Push(lua_State* L, const CLuaVector4D* value) + { + lua_pushvector(L, *value); + } + inline void Push(lua_State* L, const CLuaMatrix* value) + { + lua_pushmatrix(L, *value); + } // Overload for enum types only template @@ -198,9 +288,11 @@ namespace lua // Call Push on each element of the tuple lua_createtable(L, sizeof...(Ts), 0); std::apply( - [L](const auto&... values) { + [L](const auto&... values) + { int key = 1; - auto PushTable = [](lua_State* L, int& key, const auto& value) { + auto PushTable = [](lua_State* L, int& key, const auto& value) + { Push(L, value); lua_rawseti(L, -2, key++); }; @@ -209,4 +301,4 @@ namespace lua }, tuple); } -} // namespace lua +} // namespace lua diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaBitDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaBitDefs.cpp index a1944039d27..7ef77afcd66 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaBitDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaBitDefs.cpp @@ -184,7 +184,7 @@ int CLuaBitDefs::bitLRotate(lua_State* luaVM) if (!argStream.HasErrors()) { - iDisp &= (32 - 1); // iDisp %= 32 + iDisp &= (32 - 1); // iDisp %= 32 uint uiResult = (uiVar << iDisp) | (uiVar >> (32 - iDisp)); lua_pushnumber(luaVM, uiResult); @@ -209,7 +209,7 @@ int CLuaBitDefs::bitRRotate(lua_State* luaVM) if (!argStream.HasErrors()) { - iDisp &= (32 - 1); // iDisp %= 32 + iDisp &= (32 - 1); // iDisp %= 32 uint uiResult = (uiVar >> iDisp) | (uiVar << (32 - iDisp)); lua_pushnumber(luaVM, uiResult); diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaCryptDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaCryptDefs.cpp index 42c343f5784..a559e982dfc 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaCryptDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaCryptDefs.cpp @@ -19,20 +19,18 @@ void CLuaCryptDefs::LoadFunctions() { - constexpr static const std::pair functions[]{ - {"md5", ArgumentParserWarn}, - {"sha256", ArgumentParserWarn}, - {"hash", ArgumentParserWarn}, - {"teaEncode", ArgumentParserWarn}, - {"teaDecode", ArgumentParserWarn}, - {"base64Encode", ArgumentParserWarn}, - {"base64Decode", ArgumentParserWarn}, - {"passwordHash", ArgumentParserWarn}, - {"generateKeyPair", ArgumentParser}, - {"passwordVerify", PasswordVerify}, - {"encodeString", EncodeString}, - {"decodeString", DecodeString} - }; + constexpr static const std::pair functions[]{{"md5", ArgumentParserWarn}, + {"sha256", ArgumentParserWarn}, + {"hash", ArgumentParserWarn}, + {"teaEncode", ArgumentParserWarn}, + {"teaDecode", ArgumentParserWarn}, + {"base64Encode", ArgumentParserWarn}, + {"base64Decode", ArgumentParserWarn}, + {"passwordHash", ArgumentParserWarn}, + {"generateKeyPair", ArgumentParser}, + {"passwordVerify", PasswordVerify}, + {"encodeString", EncodeString}, + {"decodeString", DecodeString}}; // Add functions for (const auto& [name, func] : functions) @@ -191,11 +189,13 @@ std::variant CLuaCryptDefs::PasswordHash(lua_State* luaVM, st if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [password, salt = options["salt"], cost] { + [password, salt = options["salt"], cost] + { // Execute time-consuming task return SharedUtil::BcryptHash(password, salt, cost); }, - [luaFunctionRef = callback.value()](const SString& hash) { + [luaFunctionRef = callback.value()](const SString& hash) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -276,17 +276,19 @@ int CLuaCryptDefs::PasswordVerify(lua_State* luaVM) { lua_pushboolean(luaVM, SharedUtil::BcryptVerify(password, hash)); } - else // Async + else // Async { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [password, hash] { + [password, hash] + { // Execute time-consuming task return SharedUtil::BcryptVerify(password, hash); }, - [luaFunctionRef](const bool& correct) { + [luaFunctionRef](const bool& correct) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -336,7 +338,8 @@ std::variant> CLuaCryptDefs::GenerateKey if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [size]() -> std::variant { + [size]() -> std::variant + { // Execute time-consuming task try { @@ -347,7 +350,8 @@ std::variant> CLuaCryptDefs::GenerateKey return {ex.GetWhat()}; } }, - [luaFunctionRef = callback.value()](const auto& result) { + [luaFunctionRef = callback.value()](const auto& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -434,13 +438,15 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key] { + [data, key] + { // Execute time-consuming task SString result; SharedUtil::TeaEncode(data, key, &result); return result; }, - [luaFunctionRef](const SString& result) { + [luaFunctionRef](const SString& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -453,7 +459,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { SString result; SharedUtil::TeaEncode(data, key, &result); @@ -479,7 +485,8 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key] { + [data, key] + { std::pair result; try { @@ -490,7 +497,8 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) } return result; }, - [luaFunctionRef](const std::pair result) { + [luaFunctionRef](const std::pair result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -512,7 +520,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { std::pair result; try @@ -547,7 +555,8 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key] { + [data, key] + { try { return std::make_pair(SharedUtil::RsaEncode(data, key), true); @@ -557,7 +566,8 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) return std::make_pair(SString(ex.GetWhat()), false); } }, - [luaFunctionRef](const std::pair& result) { + [luaFunctionRef](const std::pair& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -579,7 +589,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -646,7 +656,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -713,7 +723,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -730,8 +740,8 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) } case StringEncodeFunction::ZLIB: { - int compression = 9; - int format = (int)ZLibFormat::GZIP; + int compression = 9; + int format = (int)ZLibFormat::GZIP; ZLibStrategy strategy = ZLibStrategy::DEFAULT; if (!options["format"].empty() && !StringToEnum(options["format"], (ZLibFormat&)format) && !StringToZLibFormat(options["format"], format)) { @@ -796,7 +806,7 @@ int CLuaCryptDefs::EncodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { SString output; int result = SharedUtil::ZLibCompress(data, output, format, compression, strategy); @@ -867,13 +877,15 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key] { + [data, key] + { // Execute time-consuming task SString result; SharedUtil::TeaDecode(data, key, &result); return result; }, - [luaFunctionRef](const SString& result) { + [luaFunctionRef](const SString& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -886,7 +898,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { SString result; SharedUtil::TeaDecode(data, key, &result); @@ -920,7 +932,8 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key, iv] { + [data, key, iv] + { // Execute time-consuming task SString result; try @@ -932,7 +945,8 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) } return result; }, - [luaFunctionRef](const SString& result) { + [luaFunctionRef](const SString& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -953,7 +967,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { SString result; try @@ -987,7 +1001,8 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) if (pLuaMain) { CLuaShared::GetAsyncTaskScheduler()->PushTask( - [data, key] { + [data, key] + { try { return std::make_pair(SharedUtil::RsaDecode(data, key), true); @@ -997,7 +1012,8 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) return std::make_pair(SString(ex.GetWhat()), false); } }, - [luaFunctionRef](const std::pair& result) { + [luaFunctionRef](const std::pair& result) + { CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaFunctionRef.GetLuaVM()); if (pLuaMain) { @@ -1019,7 +1035,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -1086,7 +1102,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -1153,7 +1169,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua::Push(luaVM, true); } } - else // Sync + else // Sync { try { @@ -1218,7 +1234,7 @@ int CLuaCryptDefs::DecodeString(lua_State* luaVM) lua_pushboolean(luaVM, true); } } - else // Sync + else // Sync { SString output; int result = SharedUtil::ZLibUncompress(data, output, format); diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaElementDefsShared.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaElementDefsShared.cpp index b85b7dfc4ce..823845118a0 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaElementDefsShared.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaElementDefsShared.cpp @@ -18,9 +18,9 @@ int CLuaElementDefs::GetElementData(lua_State* luaVM) { // var getElementData ( element theElement, string key [, inherit = true] ) - CElement* pElement; + CElement* pElement; CStringName key; - bool bInherit; + bool bInherit; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); @@ -72,9 +72,9 @@ int CLuaElementDefs::HasElementData(lua_State* luaVM) { // bool hasElementData ( element theElement, string key [, bool inherit = true ] ) - CElement* pElement; + CElement* pElement; CStringName key; - bool bInherit; + bool bInherit; CScriptArgReader argStream(luaVM); argStream.ReadUserData(pElement); diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaFileDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaFileDefs.cpp index 5b2c16f6aba..3c268b557f9 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaFileDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaFileDefs.cpp @@ -227,7 +227,7 @@ int CLuaFileDefs::fileOpen(lua_State* luaVM) CheckCanAccessOtherResourceFile(argStream, pThisResource, pResource, strAbsPath, &bReadOnly); if (!argStream.HasErrors()) { -#ifndef MTA_CLIENT // IF SERVER +#ifndef MTA_CLIENT // IF SERVER // Create the file to create CScriptFile* pFile = new CScriptFile(pThisResource->GetScriptID(), strMetaPath, DEFAULT_MAX_FILESIZE); #else @@ -313,7 +313,7 @@ int CLuaFileDefs::fileCreate(lua_State* luaVM) lua_pushboolean(luaVM, false); return 1; } -#endif // MTA_CLIENT +#endif // MTA_CLIENT SString strAbsPath; SString strMetaPath; @@ -765,7 +765,7 @@ int CLuaFileDefs::fileWrite(lua_State* luaVM) if (!argStream.HasErrors()) { - long lBytesWritten = 0; // Total bytes written + long lBytesWritten = 0; // Total bytes written // While we're not out of string arguments // (we will always have at least one string because we validated it above) @@ -816,7 +816,7 @@ std::optional CLuaFileDefs::fileGetContents(lua_State* L, CScriptFi // string fileGetContents ( file target [, bool verifyContents = true ] ) std::string buffer; - const long bytesRead = scriptFile->GetContents(buffer); + const long bytesRead = scriptFile->GetContents(buffer); if (bytesRead == -2) { @@ -951,7 +951,7 @@ std::optional CLuaFileDefs::fileGetHash(lua_State* const luaVM, CSc if (algorithm.empty() || !StringToEnum(algorithm, hmacAlgorithm)) throw std::invalid_argument("Invalid value for field 'algorithm'"); - + switch (hmacAlgorithm) { case HmacAlgorithm::MD5: diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaMatrixDefs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaMatrixDefs.h index 4c987e719ce..8967885734c 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaMatrixDefs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaMatrixDefs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "luadefs/CLuaDefs.h" diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.cpp index a36ed162157..80a8368dfb9 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.cpp @@ -44,10 +44,8 @@ void CLuaPathDefs::AddClass(lua_State* luaVM) lua_registerclass(luaVM, "path"); } -std::optional> CLuaPathDefs::pathListDir( - lua_State* luaVM, - std::string path -) { +std::optional> CLuaPathDefs::pathListDir(lua_State* luaVM, std::string path) +{ CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); if (!pLuaMain) return std::nullopt; @@ -57,15 +55,13 @@ std::optional> CLuaPathDefs::pathListDir( CResource* pResource = pLuaMain->GetResource(); if (!CResourceManager::ParseResourcePathInput(path, pResource, &strAbsPath)) { - m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", - path.c_str()); + m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", path.c_str()); return std::nullopt; } if (!DirectoryExists(strAbsPath)) { - m_pScriptDebugging->LogWarning(luaVM, "Directory \"%s\" doesn't exist!", - path.c_str()); + m_pScriptDebugging->LogWarning(luaVM, "Directory \"%s\" doesn't exist!", path.c_str()); return std::nullopt; } @@ -83,8 +79,7 @@ bool CLuaPathDefs::pathIsFile(lua_State* luaVM, std::string path) CResource* pResource = pLuaMain->GetResource(); if (!CResourceManager::ParseResourcePathInput(path, pResource, &strAbsPath)) { - m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", - path.c_str()); + m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", path.c_str()); return false; } @@ -102,8 +97,7 @@ bool CLuaPathDefs::pathIsDirectory(lua_State* luaVM, std::string path) CResource* pResource = pLuaMain->GetResource(); if (!CResourceManager::ParseResourcePathInput(path, pResource, &strAbsPath)) { - m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", - path.c_str()); + m_pScriptDebugging->LogWarning(luaVM, "Cannot parse provided path: \"%s\"", path.c_str()); return false; } diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.h index 6a8e950f551..d3e1d6eb089 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaPathDefs.h @@ -19,7 +19,7 @@ class CLuaPathDefs : public CLuaDefs private: static std::optional> pathListDir(lua_State* luaVM, std::string path); - + static bool pathIsFile(lua_State* luaVM, std::string path); static bool pathIsDirectory(lua_State* luaVM, std::string path); }; diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.cpp index b2c39a0b6c4..ed9a364c1ac 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.cpp @@ -204,7 +204,7 @@ int CLuaUtilDefs::Split(lua_State* luaVM) wchar_t wUNICODE[2] = {static_cast(uiDelimiter), '\0'}; strDelimiter = UTF16ToMbUTF8(wUNICODE); } - else // It's already a string + else // It's already a string argStream.ReadString(strDelimiter); if (!argStream.HasErrors()) @@ -664,7 +664,7 @@ int CLuaUtilDefs::GetTok(lua_State* luaVM) wchar_t wUNICODE[2] = {static_cast(uiDelimiter), '\0'}; strDelimiter = UTF16ToMbUTF8(wUNICODE); } - else // It's already a string + else // It's already a string argStream.ReadString(strDelimiter); if (!argStream.HasErrors()) @@ -728,8 +728,8 @@ int CLuaUtilDefs::tocolor(lua_State* luaVM) if (!argStream.HasErrors()) { // Make it into an unsigned long - unsigned long ulColor = COLOR_RGBA(static_cast(iRed), static_cast(iGreen), - static_cast(iBlue), static_cast(iAlpha)); + unsigned long ulColor = COLOR_RGBA(static_cast(iRed), static_cast(iGreen), static_cast(iBlue), + static_cast(iAlpha)); lua_pushinteger(luaVM, static_cast(ulColor)); return 1; } diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.h index e690c7cf3ca..02993d72d81 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaUtilDefs.h @@ -23,7 +23,7 @@ class CLuaUtilDefs : public CLuaDefs // Some of these are based on standard mIRC script funcs as a lot of people will be used to them LUA_DECLARE(Dereference); LUA_DECLARE(Reference); - LUA_DECLARE(GetTickCount_); // Trailing underscore to prevent macro issues + LUA_DECLARE(GetTickCount_); // Trailing underscore to prevent macro issues LUA_DECLARE(GetCTime); LUA_DECLARE(Split); LUA_DECLARE(IsOOPEnabled); diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaVector2Defs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaVector2Defs.h index deb38f6b851..035827e9d3f 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaVector2Defs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaVector2Defs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "luadefs/CLuaDefs.h" diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaVector3Defs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaVector3Defs.h index 24b786ab7a8..da73aa7a247 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaVector3Defs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaVector3Defs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "luadefs/CLuaDefs.h" diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaVector4Defs.h b/Shared/mods/deathmatch/logic/luadefs/CLuaVector4Defs.h index ee6d76d0355..4edf07f44d9 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaVector4Defs.h +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaVector4Defs.h @@ -13,9 +13,9 @@ extern "C" { - #include "lua.h" - #include "lualib.h" - #include "lauxlib.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" } #include "luadefs/CLuaDefs.h" diff --git a/Shared/mods/deathmatch/logic/luadefs/CLuaXMLDefs.cpp b/Shared/mods/deathmatch/logic/luadefs/CLuaXMLDefs.cpp index 90c3773ee9c..17e617b5b56 100644 --- a/Shared/mods/deathmatch/logic/luadefs/CLuaXMLDefs.cpp +++ b/Shared/mods/deathmatch/logic/luadefs/CLuaXMLDefs.cpp @@ -55,7 +55,7 @@ void CLuaXMLDefs::AddClass(lua_State* luaVM) #ifndef MTA_CLIENT lua_classfunction(luaVM, "loadMapData", "loadMapData"); lua_classfunction(luaVM, "saveMapData", "saveMapData"); -#endif // !MTA_CLIENT +#endif // !MTA_CLIENT lua_classfunction(luaVM, "getValue", "xmlNodeGetValue"); lua_classfunction(luaVM, "setAttribute", "xmlNodeSetAttribute"); @@ -85,7 +85,7 @@ int CLuaXMLDefs::xmlCreateFile(lua_State* luaVM) #ifndef MTA_CLIENT if (lua_type(luaVM, 3) == LUA_TLIGHTUSERDATA) m_pScriptDebugging->LogCustom(luaVM, "xmlCreateFile may be using an outdated syntax. Please check and update."); -#endif // !MTA_CLIENT +#endif // !MTA_CLIENT // Grab our resource CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); @@ -101,7 +101,7 @@ int CLuaXMLDefs::xmlCreateFile(lua_State* luaVM) { SString strPath; CResource* pThisResource = pLuaMain->GetResource(); - CResource* pOtherResource = pThisResource; // clientside, this variable will always be pThisResource + CResource* pOtherResource = pThisResource; // clientside, this variable will always be pThisResource // Resolve other resource from name if (CResourceManager::ParseResourcePathInput(strInputPath, pOtherResource, &strPath, nullptr)) @@ -144,7 +144,7 @@ int CLuaXMLDefs::xmlLoadFile(lua_State* luaVM) #ifndef MTA_CLIENT if (lua_type(luaVM, 2) == LUA_TLIGHTUSERDATA) m_pScriptDebugging->LogCustom(luaVM, "xmlLoadFile may be using an outdated syntax. Please check and update."); -#endif // !MTA_CLIENT +#endif // !MTA_CLIENT // Grab our resource CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine(luaVM); @@ -250,7 +250,7 @@ int CLuaXMLDefs::xmlCopyFile(lua_State* luaVM) #ifndef MTA_CLIENT if (lua_type(luaVM, 3) == LUA_TLIGHTUSERDATA) m_pScriptDebugging->LogCustom(luaVM, "xmlCopyFile may be using an outdated syntax. Please check and update."); -#endif // !MTA_CLIENT +#endif // !MTA_CLIENT // Grab our resource CLuaMain* pLUA = m_pLuaManager->GetVirtualMachine(luaVM); diff --git a/Shared/mods/deathmatch/logic/luascripts/coroutine_debug.lua.h b/Shared/mods/deathmatch/logic/luascripts/coroutine_debug.lua.h index 1c361b07876..d0f26c5a9c2 100644 --- a/Shared/mods/deathmatch/logic/luascripts/coroutine_debug.lua.h +++ b/Shared/mods/deathmatch/logic/luascripts/coroutine_debug.lua.h @@ -23,4 +23,4 @@ function coroutine.resume(...) end )~LUA~"; -} \ No newline at end of file +} diff --git a/Shared/mods/deathmatch/logic/luascripts/inspect.lua.h b/Shared/mods/deathmatch/logic/luascripts/inspect.lua.h index 16eb1078b81..9a19021105f 100644 --- a/Shared/mods/deathmatch/logic/luascripts/inspect.lua.h +++ b/Shared/mods/deathmatch/logic/luascripts/inspect.lua.h @@ -443,4 +443,4 @@ setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) en )~LUA~"; -} \ No newline at end of file +} diff --git a/Shared/publicsdk/CThread.cpp b/Shared/publicsdk/CThread.cpp index 4bbeab012c4..29354858e54 100644 --- a/Shared/publicsdk/CThread.cpp +++ b/Shared/publicsdk/CThread.cpp @@ -22,7 +22,7 @@ CThread::CThread() { m_pThreadData = NULL; m_pArg = NULL; -#ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads m_hThread = NULL; #endif } @@ -34,22 +34,22 @@ CThread::~CThread() bool CThread::Start(CThreadData* pData) { - if (pData == NULL) // pData HAS to be valid + if (pData == NULL) // pData HAS to be valid return false; Stop(); Arg(pData); - #ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads m_hThread = CreateThread(NULL, 0, &CThread::EntryPoint, this, 0, NULL); return m_hThread != NULL; - #else // POSIX threads +#else // POSIX threads if (pthread_create(&m_hThread, NULL, CThread::EntryPoint, this)) { // something bad happened return false; } - #endif +#endif return true; } @@ -65,32 +65,32 @@ void CThread::Stop() bool CThread::TryLock(ThreadMutex* Mutex) { - #ifdef WIN32 +#ifdef WIN32 if (TryEnterCriticalSection(Mutex) != 0) return true; - #else +#else if (pthread_mutex_trylock(Mutex) == 0) return true; - #endif +#endif return false; } void CThread::Lock(ThreadMutex* Mutex) { - #ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads EnterCriticalSection(Mutex); - #else // POSIX threads +#else // POSIX threads pthread_mutex_lock(Mutex); - #endif +#endif } void CThread::Unlock(ThreadMutex* Mutex) { - #ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads LeaveCriticalSection(Mutex); - #else // POSIX threads +#else // POSIX threads pthread_mutex_unlock(Mutex); - #endif +#endif } int CThread::Run(CThreadData* arg) @@ -98,13 +98,13 @@ int CThread::Run(CThreadData* arg) return Execute(arg); } -#ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads DWORD CThread::EntryPoint(void* pThis) { CThread* pt = (CThread*)pThis; return pt->Run(pt->Arg()); } -#else // POSIX threads +#else // POSIX threads void* CThread::EntryPoint(void* pThis) { CThread* pt = (CThread*)pThis; diff --git a/Shared/publicsdk/CThread.h b/Shared/publicsdk/CThread.h index f4a23bd9d95..bf74e4d64dc 100644 --- a/Shared/publicsdk/CThread.h +++ b/Shared/publicsdk/CThread.h @@ -20,14 +20,14 @@ #pragma once -#ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads #define _WIN32_WINNT 0x400 #define WIN32_LEAN_AND_MEAN #include typedef HANDLE ThreadHandle; typedef CRITICAL_SECTION ThreadMutex; -#else // POSIX threads +#else // POSIX threads #include #include @@ -59,9 +59,9 @@ class CThread CThreadData* Arg() const; void Arg(CThreadData* pData); -#ifdef WIN32 // Win32 threads +#ifdef WIN32 // Win32 threads static DWORD WINAPI EntryPoint(void*); -#else // POSIX threads +#else // POSIX threads static void* EntryPoint(void*); #endif diff --git a/Shared/publicsdk/CThreadData.cpp b/Shared/publicsdk/CThreadData.cpp index 383410128e6..f773d7dbbdc 100644 --- a/Shared/publicsdk/CThreadData.cpp +++ b/Shared/publicsdk/CThreadData.cpp @@ -22,21 +22,21 @@ CThreadData::CThreadData() { bAbortThread = false; - // Initialize the mutexes - #ifdef WIN32 // Win32 threads +// Initialize the mutexes +#ifdef WIN32 // Win32 threads InitializeCriticalSection(&MutexPrimary); InitializeCriticalSection(&MutexLogical); - #else // POSIX threads +#else // POSIX threads pthread_mutex_init(&MutexPrimary, NULL); pthread_mutex_init(&MutexLogical, NULL); - #endif +#endif } CThreadData::~CThreadData() { - #ifdef WIN32 +#ifdef WIN32 DeleteCriticalSection(&MutexPrimary); DeleteCriticalSection(&MutexLogical); - #else - #endif +#else +#endif } diff --git a/Shared/publicsdk/CThreadData.h b/Shared/publicsdk/CThreadData.h index c5c7e04c708..75564e13a49 100644 --- a/Shared/publicsdk/CThreadData.h +++ b/Shared/publicsdk/CThreadData.h @@ -29,6 +29,6 @@ class CThreadData ~CThreadData(); bool bAbortThread; - ThreadMutex MutexPrimary; // primary mutex for suspend/resume operations - ThreadMutex MutexLogical; // logical mutex for proper CThreadData sync + ThreadMutex MutexPrimary; // primary mutex for suspend/resume operations + ThreadMutex MutexLogical; // logical mutex for proper CThreadData sync }; diff --git a/Shared/publicsdk/Common.h b/Shared/publicsdk/Common.h index 7a09f65850d..a0c5f93495e 100644 --- a/Shared/publicsdk/Common.h +++ b/Shared/publicsdk/Common.h @@ -18,15 +18,15 @@ extern "C" { - #include - #include - #include +#include +#include +#include } #ifdef WIN32 #define MTAEXPORT extern "C" __declspec(dllexport) #else - #define MTAEXPORT extern "C" __attribute__ ((visibility ("default"))) + #define MTAEXPORT extern "C" __attribute__((visibility("default"))) #endif #include @@ -37,10 +37,10 @@ using std::list; using std::vector; #ifndef __COMMON_H -#define __COMMON_H + #define __COMMON_H -// used in the function argument vector -#define MAX_ARGUMENTS 10 + // used in the function argument vector + #define MAX_ARGUMENTS 10 struct FunctionArguments { lua_State* luaVM; diff --git a/Shared/publicsdk/extra/CLuaArgument.h b/Shared/publicsdk/extra/CLuaArgument.h index faaef1ebfcf..e5c61438056 100644 --- a/Shared/publicsdk/extra/CLuaArgument.h +++ b/Shared/publicsdk/extra/CLuaArgument.h @@ -20,7 +20,7 @@ extern "C" { - #include +#include } class CLuaArgument diff --git a/Shared/publicsdk/extra/CLuaArguments.cpp b/Shared/publicsdk/extra/CLuaArguments.cpp index d56b8aa39d0..88afc0573cf 100644 --- a/Shared/publicsdk/extra/CLuaArguments.cpp +++ b/Shared/publicsdk/extra/CLuaArguments.cpp @@ -98,7 +98,7 @@ bool CLuaArguments::Call(lua_State* luaVM, const char* szFunction) const if (iret == LUA_ERRRUN || iret == LUA_ERRMEM) { const char* szRes = lua_tostring(luaVM, -1); - return false; // the function call failed + return false; // the function call failed } return true; diff --git a/Shared/publicsdk/extra/CLuaArguments.h b/Shared/publicsdk/extra/CLuaArguments.h index 7eb41301b93..8d0a3534466 100644 --- a/Shared/publicsdk/extra/CLuaArguments.h +++ b/Shared/publicsdk/extra/CLuaArguments.h @@ -20,7 +20,7 @@ extern "C" { - #include +#include } #include "CLuaArgument.h" @@ -31,7 +31,7 @@ using std::vector; class CLuaArguments { public: - CLuaArguments(){}; + CLuaArguments() {}; CLuaArguments(const CLuaArguments& Arguments); ~CLuaArguments() { DeleteArguments(); }; diff --git a/Shared/publicsdk/include/ILuaModuleManager.h b/Shared/publicsdk/include/ILuaModuleManager.h index 2c8a6e22039..03848c3e24c 100644 --- a/Shared/publicsdk/include/ILuaModuleManager.h +++ b/Shared/publicsdk/include/ILuaModuleManager.h @@ -17,14 +17,14 @@ extern "C" { - #include - #include - #include +#include +#include +#include } #include #ifndef __CChecksum_H -#define __CChecksum_H + #define __CChecksum_H class CChecksum { public: @@ -41,9 +41,9 @@ class ILuaModuleManager virtual void DebugPrintf(lua_State* luaVM, const char* szFormat, ...) = 0; virtual void Printf(const char* szFormat, ...) = 0; - virtual bool RegisterFunction(lua_State* luaVM, const char* szFunctionName, lua_CFunction Func) = 0; - virtual bool GetResourceName( - lua_State* luaVM, std::string& strName) = 0; // This function might not work if module and MTA were compiled with different compiler versions + virtual bool RegisterFunction(lua_State* luaVM, const char* szFunctionName, lua_CFunction Func) = 0; + virtual bool GetResourceName(lua_State* luaVM, + std::string& strName) = 0; // This function might not work if module and MTA were compiled with different compiler versions virtual CChecksum GetResourceMetaChecksum(lua_State* luaVM) = 0; virtual CChecksum GetResourceFileChecksum(lua_State* luaVM, const char* szFile) = 0; }; diff --git a/Shared/publicsdk/ml_base.h b/Shared/publicsdk/ml_base.h index ac09276c2de..c70f55760b8 100644 --- a/Shared/publicsdk/ml_base.h +++ b/Shared/publicsdk/ml_base.h @@ -17,9 +17,9 @@ *********************************************************/ /** MODULE SPECIFIC INFORMATION **/ -#define MODULE_NAME "Base Module" -#define MODULE_AUTHOR "anon" -#define MODULE_VERSION 1.0 +#define MODULE_NAME "Base Module" +#define MODULE_AUTHOR "anon" +#define MODULE_VERSION 1.0 #include #include "Common.h" diff --git a/Shared/sdk/CChecksum.h b/Shared/sdk/CChecksum.h index f3c90a9fa6c..7001dae20d2 100644 --- a/Shared/sdk/CChecksum.h +++ b/Shared/sdk/CChecksum.h @@ -21,8 +21,8 @@ #include #if defined(_WIN32) && defined(MTA_CLIENT) -#include -#include + #include + #include #endif // Depends on CMD5Hasher and CRCGenerator @@ -38,33 +38,63 @@ class CChecksum #if defined(_WIN32) && defined(MTA_CLIENT) private: - struct CacheEntry { std::uint64_t size, mtime; unsigned long crc; MD5 md5; }; - static std::unordered_map& Cache() { static std::unordered_map c; return c; } - static std::mutex& CacheMtx() { static std::mutex m; return m; } + struct CacheEntry + { + std::uint64_t size, mtime; + unsigned long crc; + MD5 md5; + }; + static std::unordered_map& Cache() + { + static std::unordered_map c; + return c; + } + static std::mutex& CacheMtx() + { + static std::mutex m; + return m; + } public: - static void ClearChecksumCache() { std::lock_guard l(CacheMtx()); Cache().clear(); } + static void ClearChecksumCache() + { + std::lock_guard l(CacheMtx()); + Cache().clear(); + } static std::variant GenerateChecksumFromFile(const SString& strFilename) { std::string key = strFilename; - for (char& c : key) { - if (c >= 'A' && c <= 'Z') c += 32; - if (c == '\\') c = '/'; + for (char& c : key) + { + if (c >= 'A' && c <= 'Z') + c += 32; + if (c == '\\') + c = '/'; } WIN32_FILE_ATTRIBUTE_DATA attr; - WString wide; - try { wide = SharedUtil::FromUTF8(strFilename); } catch (...) {} - bool hasMeta = !wide.empty() && GetFileAttributesExW(wide.c_str(), GetFileExInfoStandard, &attr); + WString wide; + try + { + wide = SharedUtil::FromUTF8(strFilename); + } + catch (...) + { + } + bool hasMeta = !wide.empty() && GetFileAttributesExW(wide.c_str(), GetFileExInfoStandard, &attr); std::uint64_t sz = 0, mt = 0; - if (hasMeta) { + if (hasMeta) + { sz = (std::uint64_t(attr.nFileSizeHigh) << 32) | attr.nFileSizeLow; mt = (std::uint64_t(attr.ftLastWriteTime.dwHighDateTime) << 32) | attr.ftLastWriteTime.dwLowDateTime; std::lock_guard l(CacheMtx()); - auto it = Cache().find(key); - if (it != Cache().end() && it->second.size == sz && it->second.mtime == mt) { - CChecksum cached; cached.ulCRC = it->second.crc; cached.md5 = it->second.md5; + auto it = Cache().find(key); + if (it != Cache().end() && it->second.size == sz && it->second.mtime == mt) + { + CChecksum cached; + cached.ulCRC = it->second.crc; + cached.md5 = it->second.md5; return cached; } } @@ -83,8 +113,10 @@ class CChecksum if (hasMeta && GetFileAttributesExW(wide.c_str(), GetFileExInfoStandard, &attr) && sz == ((std::uint64_t(attr.nFileSizeHigh) << 32) | attr.nFileSizeLow) && - mt == ((std::uint64_t(attr.ftLastWriteTime.dwHighDateTime) << 32) | attr.ftLastWriteTime.dwLowDateTime)) { - std::lock_guard l(CacheMtx()); Cache()[key] = {sz, mt, r.ulCRC, r.md5}; + mt == ((std::uint64_t(attr.ftLastWriteTime.dwHighDateTime) << 32) | attr.ftLastWriteTime.dwLowDateTime)) + { + std::lock_guard l(CacheMtx()); + Cache()[key] = {sz, mt, r.ulCRC, r.md5}; } return r; } @@ -95,8 +127,10 @@ class CChecksum if (hasMeta && GetFileAttributesExW(wide.c_str(), GetFileExInfoStandard, &attr) && sz == ((std::uint64_t(attr.nFileSizeHigh) << 32) | attr.nFileSizeLow) && - mt == ((std::uint64_t(attr.ftLastWriteTime.dwHighDateTime) << 32) | attr.ftLastWriteTime.dwLowDateTime)) { - std::lock_guard l(CacheMtx()); Cache()[key] = {sz, mt, r.ulCRC, r.md5}; + mt == ((std::uint64_t(attr.ftLastWriteTime.dwHighDateTime) << 32) | attr.ftLastWriteTime.dwLowDateTime)) + { + std::lock_guard l(CacheMtx()); + Cache()[key] = {sz, mt, r.ulCRC, r.md5}; } return r; } @@ -108,8 +142,8 @@ class CChecksum { constexpr int maxRetries = 3; constexpr int retryDelayMs = 50; - int lastErrno = 0; - int attemptsMade = 0; + int lastErrno = 0; + int attemptsMade = 0; for (int attempt = 0; attempt < maxRetries; ++attempt) { @@ -148,15 +182,11 @@ class CChecksum if (lastErrno == ENOENT) return SString("File not found: %s", strFilename.c_str()); - return SString("Could not checksum '%s' after %d attempt%s: %s", - strFilename.c_str(), - attemptsMade, - attemptsMade == 1 ? "" : "s", + return SString("Could not checksum '%s' after %d attempt%s: %s", strFilename.c_str(), attemptsMade, attemptsMade == 1 ? "" : "s", lastErrno ? std::strerror(lastErrno) : "Unknown error"); } #endif - // GenerateChecksumFromFileUnsafe should never ever be used unless you are a bad person. Or unless you really know what you're doing. // If it's the latter, please leave a code comment somewhere explaining why. Otherwise we'll think it's just code that hasn't been migrated yet. static CChecksum GenerateChecksumFromFileUnsafe(const SString& strFilename) diff --git a/Shared/sdk/CDuplicateLineFilter.h b/Shared/sdk/CDuplicateLineFilter.h index 67d67576246..f7312022eed 100644 --- a/Shared/sdk/CDuplicateLineFilter.h +++ b/Shared/sdk/CDuplicateLineFilter.h @@ -50,7 +50,7 @@ class CDuplicateLineFilter m_uiMatchCurLine = i; m_uiDupCount = 0; if (m_uiMatchCurLine == 0) - m_uiDupCount++; // Completed matching set (will only occur here for single line match) + m_uiDupCount++; // Completed matching set (will only occur here for single line match) return; } } @@ -65,7 +65,7 @@ class CDuplicateLineFilter // Still matching m_uiMatchCurLine = uiNextLine; if (m_uiMatchCurLine == 0) - m_uiDupCount++; // Completed matching set + m_uiDupCount++; // Completed matching set return; } else @@ -153,11 +153,11 @@ class CDuplicateLineFilter protected: std::deque m_History; std::list m_PendingOutput; - bool m_bIsMatching = false; // true if matching a duplicate set - uint m_uiMatchSize = 0; // Number of lines in active match - uint m_uiMatchCurLine = 0; // Current line in active match - uint m_uiDupCount = 0; // Number of duplicates found for active match + bool m_bIsMatching = false; // true if matching a duplicate set + uint m_uiMatchSize = 0; // Number of lines in active match + uint m_uiMatchCurLine = 0; // Current line in active match + uint m_uiDupCount = 0; // Number of duplicates found for active match time_t m_tLastOutputTime = 0; - uint m_uiMaxNumOfLinesInMatch; // Max number lines in a matching set - uint m_uiMaxDelaySeconds; // Max seconds to delay outputting duplicated lines + uint m_uiMaxNumOfLinesInMatch; // Max number lines in a matching set + uint m_uiMaxDelaySeconds; // Max seconds to delay outputting duplicated lines }; diff --git a/Shared/sdk/CFastList.h b/Shared/sdk/CFastList.h index a8020362ea9..773b0999fed 100644 --- a/Shared/sdk/CFastList.h +++ b/Shared/sdk/CFastList.h @@ -52,21 +52,21 @@ class CFastList T item; }; - uint uiRevision; // Incremented every time the ordered map changes - uint uiNextFrontIndex; // Next (decrementing) index to use as a map key for items added to the front - uint uiNextBackIndex; // Next (incrementing) index to use as a map key for items added to the back - MapType orderedMap; // Ordered map of items - InfoType infoMap; // info for each item + uint uiRevision; // Incremented every time the ordered map changes + uint uiNextFrontIndex; // Next (decrementing) index to use as a map key for items added to the front + uint uiNextBackIndex; // Next (incrementing) index to use as a map key for items added to the back + MapType orderedMap; // Ordered map of items + InfoType infoMap; // info for each item bool m_bSuspendingModifyOperations; std::vector m_SuspendedOperationList; CFastList() : uiRevision(1), uiNextFrontIndex(UINT_MAX / 2 - 1), uiNextBackIndex(UINT_MAX / 2), m_bSuspendingModifyOperations(false) { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG // T must be a pointer void* ptr = (T)NULL; ptr = NULL; - #endif +#endif } const T& front() const { return orderedMap.begin()->second; } diff --git a/Shared/sdk/CIntrusiveDoubleLinkedList.h b/Shared/sdk/CIntrusiveDoubleLinkedList.h index bfda4c9f88e..66e9f3b532e 100644 --- a/Shared/sdk/CIntrusiveDoubleLinkedList.h +++ b/Shared/sdk/CIntrusiveDoubleLinkedList.h @@ -23,21 +23,19 @@ struct CIntrusiveDoubleLinkedListNode }; // Double-linked list template class. Elements must inherit from CIntrusiveDoubleLinkedListNode. -template class CIntrusiveDoubleLinkedList +template +class CIntrusiveDoubleLinkedList { public: struct SIterator { using iterator_category = std::bidirectional_iterator_tag; - using difference_type = std::ptrdiff_t; - using value_type = T; - using pointer = T*; - using reference = T&; + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using reference = T&; - SIterator(T* ptr) : - m_ptr(ptr) - { - } + SIterator(T* ptr) : m_ptr(ptr) {} // Point to the node value. reference operator*() const { return *m_ptr; } @@ -78,10 +76,10 @@ template class CIntrusiveDoubleLinkedList } // Test for equality with another iterator. - friend bool operator== (const SIterator& a, const SIterator& b) { return a.m_ptr == b.m_ptr; }; + friend bool operator==(const SIterator& a, const SIterator& b) { return a.m_ptr == b.m_ptr; }; // Test for inequality with another iterator. - friend bool operator!= (const SIterator& a, const SIterator& b) { return a.m_ptr != b.m_ptr; }; + friend bool operator!=(const SIterator& a, const SIterator& b) { return a.m_ptr != b.m_ptr; }; private: T* m_ptr; @@ -90,15 +88,12 @@ template class CIntrusiveDoubleLinkedList struct SConstIterator { using iterator_category = std::bidirectional_iterator_tag; - using difference_type = std::ptrdiff_t; - using value_type = T; - using pointer = T*; - using reference = T&; + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using reference = T&; - SConstIterator(T* ptr) : - m_ptr(ptr) - { - } + SConstIterator(T* ptr) : m_ptr(ptr) {} // Point to the node value. const reference operator*() const { return *m_ptr; } @@ -139,20 +134,17 @@ template class CIntrusiveDoubleLinkedList } // Test for equality with another iterator. - friend bool operator== (const SConstIterator& a, const SConstIterator& b) { return a.m_ptr == b.m_ptr; }; + friend bool operator==(const SConstIterator& a, const SConstIterator& b) { return a.m_ptr == b.m_ptr; }; // Test for inequality with another iterator. - friend bool operator!= (const SConstIterator& a, const SConstIterator& b) { return a.m_ptr != b.m_ptr; }; + friend bool operator!=(const SConstIterator& a, const SConstIterator& b) { return a.m_ptr != b.m_ptr; }; private: T* m_ptr; }; // Construct empty. - CIntrusiveDoubleLinkedList() : - m_head(nullptr) - { - } + CIntrusiveDoubleLinkedList() : m_head(nullptr) {} // Non-copyable. CIntrusiveDoubleLinkedList(const CIntrusiveDoubleLinkedList& list) = delete; @@ -165,13 +157,10 @@ template class CIntrusiveDoubleLinkedList } // Non-assignable. - CIntrusiveDoubleLinkedList& operator =(const CIntrusiveDoubleLinkedList& list) = delete; + CIntrusiveDoubleLinkedList& operator=(const CIntrusiveDoubleLinkedList& list) = delete; // Destruct. - ~CIntrusiveDoubleLinkedList() - { - Clear(); - } + ~CIntrusiveDoubleLinkedList() { Clear(); } // Remove all elements. void Clear() @@ -223,7 +212,7 @@ template class CIntrusiveDoubleLinkedList void Detach(T* element) { assert(element); - + T* previous = Previous(element); T* next = Next(element); @@ -239,7 +228,7 @@ template class CIntrusiveDoubleLinkedList // Invalidate element's references element->m_previous = nullptr; element->m_next = nullptr; - } + } // Return first element, or null if empty. T* First() const { return m_head; } @@ -260,7 +249,7 @@ template class CIntrusiveDoubleLinkedList T* Previous(T* element) const { return element ? static_cast(element->m_previous) : nullptr; } // Return next element, or null if no more elements. - T* Next(T* element) const { return element ? static_cast(element->m_next) : nullptr; } + T* Next(T* element) const { return element ? static_cast(element->m_next) : nullptr; } // Return whether is empty. bool Empty() const { return m_head == nullptr; } diff --git a/Shared/sdk/CMatrix_Pad.h b/Shared/sdk/CMatrix_Pad.h index aded0d67f1b..61d565668d7 100644 --- a/Shared/sdk/CMatrix_Pad.h +++ b/Shared/sdk/CMatrix_Pad.h @@ -20,14 +20,14 @@ class CMatrix_Padded { public: - CVector vRight; // 0 RIGHT - DWORD dwPadRoll; // 12 - CVector vFront; // 16 FOREWARDS - DWORD dwPadDirection; // 28 - CVector vUp; // 32 UP - DWORD dwPadWas; // 44 - CVector vPos; // 48 TRANSLATE - DWORD dwPadPos; // 60 + CVector vRight; // 0 RIGHT + DWORD dwPadRoll; // 12 + CVector vFront; // 16 FOREWARDS + DWORD dwPadDirection; // 28 + CVector vUp; // 32 UP + DWORD dwPadWas; // 44 + CVector vPos; // 48 TRANSLATE + DWORD dwPadPos; // 60 CMatrix_Padded() { memset(this, 0, sizeof(CMatrix_Padded)); } diff --git a/Shared/sdk/CMtaVersion.h b/Shared/sdk/CMtaVersion.h index c5b1ac4ef2e..2cef9e3a5a8 100644 --- a/Shared/sdk/CMtaVersion.h +++ b/Shared/sdk/CMtaVersion.h @@ -26,7 +26,7 @@ namespace SharedUtil CMtaVersion(const std::string& strString) : std::string(strString) {} // Assignment like SString - operator const char*() const { return c_str(); } // Auto assign to const char* without using c_str() + operator const char*() const { return c_str(); } // Auto assign to const char* without using c_str() const char* operator*() const { return c_str(); } // Compare disregarding build type @@ -55,4 +55,4 @@ namespace SharedUtil SString GetGeneration() const { return SStringX(*this).SubStr(0, 3); } }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/CRect.h b/Shared/sdk/CRect.h index 39f49f04e3f..e6e13baf5ae 100644 --- a/Shared/sdk/CRect.h +++ b/Shared/sdk/CRect.h @@ -19,10 +19,10 @@ class CRect { public: - float left; // x1 - float bottom; // y1 - float right; // x2 - float top; // y2 + float left; // x1 + float bottom; // y1 + float right; // x2 + float top; // y2 CRect() { diff --git a/Shared/sdk/CScriptArgReader.h b/Shared/sdk/CScriptArgReader.h index 70af7f9872d..8fa46c71240 100644 --- a/Shared/sdk/CScriptArgReader.h +++ b/Shared/sdk/CScriptArgReader.h @@ -166,7 +166,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -179,7 +179,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -192,7 +192,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } @@ -227,7 +227,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -240,7 +240,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -253,7 +253,7 @@ class CScriptArgReader return; } outValue = CVector2D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } else if (iArgument == LUA_TNIL || iArgument == LUA_TNONE) @@ -292,7 +292,7 @@ class CScriptArgReader return; } outValue = CVector(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -305,7 +305,7 @@ class CScriptArgReader return; } outValue = CVector4D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } @@ -341,7 +341,7 @@ class CScriptArgReader return; } outValue = CVector(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } else if (NextIsUserDataOfType()) { @@ -354,7 +354,7 @@ class CScriptArgReader return; } outValue = CVector4D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } else if (iArgument == LUA_TNIL || iArgument == LUA_TNONE) @@ -394,7 +394,7 @@ class CScriptArgReader return; } outValue = CVector4D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } @@ -431,7 +431,7 @@ class CScriptArgReader return; } outValue = CVector4D(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } } else if (iArgument == LUA_TNIL || iArgument == LUA_TNONE) @@ -477,7 +477,7 @@ class CScriptArgReader return; } outValue = CMatrix(); - return; // Error set in ReadUserData + return; // Error set in ReadUserData } outValue = CMatrix(); @@ -537,7 +537,7 @@ class CScriptArgReader { return lua_toboolean(m_luaVM, m_iIndex++) ? true : false; } - + m_iIndex++; return false; } @@ -619,9 +619,9 @@ class CScriptArgReader const int iArgument = lua_type(m_luaVM, m_iIndex); if (iArgument == LUA_TSTRING) { - size_t length; + size_t length; const char* str = lua_tolstring(m_luaVM, m_iIndex, &length); - unsigned hash = lua_tostringhash(m_luaVM, m_iIndex++); + unsigned hash = lua_tostringhash(m_luaVM, m_iIndex++); try { @@ -633,7 +633,7 @@ class CScriptArgReader } return; - } + } outValue.Clear(); SetTypeError("string"); @@ -651,7 +651,7 @@ class CScriptArgReader m_iIndex = -1; ReadAnyAsString(outValue); - lua_pop(m_luaVM, 1); // Clean up stack + lua_pop(m_luaVM, 1); // Clean up stack m_iIndex = oldIndex + 1; return; } @@ -821,7 +821,7 @@ class CScriptArgReader // If will be coercing a string to an enum, make sure string contains only digits size_t uiPos = strValue.find_first_not_of("0123456789"); if (uiPos != SString::npos || strValue.empty()) - iArgument = LUA_TNONE; // Force error + iArgument = LUA_TNONE; // Force error } if (iArgument == LUA_TSTRING || iArgument == LUA_TNUMBER) @@ -1455,11 +1455,11 @@ class CScriptArgReader // Output warning here (there's no better way to integrate it without huge code changes if (!m_bError && !m_strCustomWarning.empty()) { - #ifdef MTA_CLIENT +#ifdef MTA_CLIENT CLuaFunctionDefs::m_pScriptDebugging->LogWarning(m_luaVM, m_strCustomWarning); - #else +#else g_pGame->GetScriptDebugging()->LogWarning(m_luaVM, m_strCustomWarning); - #endif +#endif m_strCustomWarning.clear(); } diff --git a/Shared/sdk/CVector.h b/Shared/sdk/CVector.h index ad9805077e7..fb55ede23b3 100644 --- a/Shared/sdk/CVector.h +++ b/Shared/sdk/CVector.h @@ -30,11 +30,13 @@ class CVector float fY; float fZ; - struct NoInit {}; + struct NoInit + { + }; CVector(NoInit) noexcept {} constexpr CVector() noexcept : fX(0.0f), fY(0.0f), fZ(0.0f) {} - + constexpr explicit CVector(float x, float y = 0.0f, float z = 0.0f) noexcept : fX(x), fY(y), fZ(z) {} constexpr CVector(const CVector4D& vec) noexcept : fX(vec.fX), fY(vec.fY), fZ(vec.fZ) {} @@ -142,8 +144,8 @@ class CVector } // https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm - bool IntersectsSegmentTriangle(const CVector& dir, const CVector& vecVert1, const CVector& vecVert2, const CVector& vecVert3, - CVector* outVec, CVector* outHitBary = nullptr) const noexcept + bool IntersectsSegmentTriangle(const CVector& dir, const CVector& vecVert1, const CVector& vecVert2, const CVector& vecVert3, CVector* outVec, + CVector* outHitBary = nullptr) const noexcept { constexpr float fEpsilon = 1e-6f; @@ -185,8 +187,9 @@ class CVector if (t > fEpsilon && t <= dir.Length()) { *outVec = *this + vecRay * t; - if (outHitBary) { // Calculate all barycentric coords if necessary - *outHitBary = CVector( 1.f - u - v, u, v ); // For vertices A, B, C [I assume?] + if (outHitBary) + { // Calculate all barycentric coords if necessary + *outHitBary = CVector(1.f - u - v, u, v); // For vertices A, B, C [I assume?] } return true; } diff --git a/Shared/sdk/Common.h b/Shared/sdk/Common.h index 6f921def786..13517bf29a1 100644 --- a/Shared/sdk/Common.h +++ b/Shared/sdk/Common.h @@ -19,14 +19,14 @@ #define MAX_SERIAL_LENGTH 32 // Network disconnection reason (message) size -#define NET_DISCONNECT_REASON_SIZE 256 +#define NET_DISCONNECT_REASON_SIZE 256 // Element IDs #define RESERVED_ELEMENT_ID 0xFFFFFFFE -#define INVALID_ELEMENT_ID 0xFFFFFFFF +#define INVALID_ELEMENT_ID 0xFFFFFFFF // Element name characteristics -#define MAX_TYPENAME_LENGTH 32 +#define MAX_TYPENAME_LENGTH 32 #define MAX_ELEMENT_NAME_LENGTH 64 // Allow 2^17 server elements and 2^17 client elements @@ -86,28 +86,28 @@ struct ElementID #define MAX_EVENT_NAME_LENGTH 512 // LAN packet broadcasting port -#define SERVER_LIST_BROADCAST_PORT 34219 +#define SERVER_LIST_BROADCAST_PORT 34219 // Server game to query port offset (gameport + offset = queryport) -#define SERVER_LIST_QUERY_PORT_OFFSET 123 +#define SERVER_LIST_QUERY_PORT_OFFSET 123 // LAN packet broadcasting string -#define SERVER_LIST_CLIENT_BROADCAST_STR "MTA-CLIENT" -#define SERVER_LIST_SERVER_BROADCAST_STR "MTA-SERVER" +#define SERVER_LIST_CLIENT_BROADCAST_STR "MTA-CLIENT" +#define SERVER_LIST_SERVER_BROADCAST_STR "MTA-SERVER" // Defines the min/max size for the player nick for use in the core module -#define MIN_PLAYER_NICK_LENGTH 1 -#define MAX_PLAYER_NICK_LENGTH 22 +#define MIN_PLAYER_NICK_LENGTH 1 +#define MAX_PLAYER_NICK_LENGTH 22 // Maximum number of players that can be packed in a single lightweight puresync packet -#define LIGHTSYNC_MAX_PLAYERS 32 +#define LIGHTSYNC_MAX_PLAYERS 32 // Frame rate limits namespace FPSLimits { - constexpr std::uint16_t FPS_MAX = std::numeric_limits::max(); // Maximum allowed frame rate limit - constexpr std::uint16_t FPS_MIN = 25; // Minimum allowed frame rate limit - constexpr std::uint16_t FPS_UNLIMITED = 0; // Unlimited frame rate (no limit) + constexpr std::uint16_t FPS_MAX = std::numeric_limits::max(); // Maximum allowed frame rate limit + constexpr std::uint16_t FPS_MIN = 25; // Minimum allowed frame rate limit + constexpr std::uint16_t FPS_UNLIMITED = 0; // Unlimited frame rate (no limit) // Takes a FPS value and // 1. Returns if `fpsToValidate` was valid @@ -132,4 +132,4 @@ namespace FPSLimits outValidFps = fpsToValidate; return true; } -} // namespace FPSLimits \ No newline at end of file +} // namespace FPSLimits diff --git a/Shared/sdk/CrashTelemetry.h b/Shared/sdk/CrashTelemetry.h index dffbe4118dc..b9cde5d3c73 100644 --- a/Shared/sdk/CrashTelemetry.h +++ b/Shared/sdk/CrashTelemetry.h @@ -24,132 +24,129 @@ namespace CrashTelemetry { struct Context { - std::size_t requestedSize{0}; - const void* resourcePointer{nullptr}; - std::array resourceTag{}; - std::array detail{}; + std::size_t requestedSize{0}; + const void* resourcePointer{nullptr}; + std::array resourceTag{}; + std::array detail{}; std::chrono::system_clock::time_point timestamp{}; - std::uint32_t threadId{0}; - bool hasData{false}; + std::uint32_t threadId{0}; + bool hasData{false}; }; -#if defined(MTA_CLIENT) -# include -# include -# include -# include -# include + #if defined(MTA_CLIENT) + #include + #include + #include + #include + #include -namespace detail -{ - constexpr std::size_t kHistoryCapacity = 6; - - template - inline void CopyInto(std::array& destination, const char* source) noexcept + namespace detail { - if (destination.empty()) - return; + constexpr std::size_t kHistoryCapacity = 6; - const std::size_t maxCopy = N - 1; - const std::size_t copyLength = (source != nullptr) ? std::min(std::strlen(source), maxCopy) : 0; - - if (copyLength != 0) - { - std::memcpy(destination.data(), source, copyLength); - destination[copyLength] = '\0'; - } - else + template + inline void CopyInto(std::array& destination, const char* source) noexcept { - destination[0] = '\0'; - } + if (destination.empty()) + return; - if (copyLength + 1 < N) - { - std::fill(destination.begin() + static_cast(copyLength + 1), destination.end(), '\0'); - } - } + const std::size_t maxCopy = N - 1; + const std::size_t copyLength = (source != nullptr) ? std::min(std::strlen(source), maxCopy) : 0; - inline std::uint32_t GetThreadIdentifier() noexcept - { -# if defined(_WIN32) - return static_cast(::GetCurrentThreadId()); -# else - const auto hashed = std::hash{}(std::this_thread::get_id()); - return static_cast(hashed & 0xFFFFFFFFu); -# endif - } + if (copyLength != 0) + { + std::memcpy(destination.data(), source, copyLength); + destination[copyLength] = '\0'; + } + else + { + destination[0] = '\0'; + } - struct ThreadState - { - Context current{}; - std::array history{}; - std::size_t nextSlot = 0; - std::size_t size = 0; - std::size_t lastFailureSize = 0; - Context lastManualScope{}; - bool lastManualScopeValid = false; - - void PushSnapshot() noexcept + if (copyLength + 1 < N) + { + std::fill(destination.begin() + static_cast(copyLength + 1), destination.end(), '\0'); + } + } + + inline std::uint32_t GetThreadIdentifier() noexcept { - history[nextSlot] = current; - history[nextSlot].hasData = true; - nextSlot = (nextSlot + 1) % kHistoryCapacity; - if (size < kHistoryCapacity) - ++size; + #if defined(_WIN32) + return static_cast(::GetCurrentThreadId()); + #else + const auto hashed = std::hash{}(std::this_thread::get_id()); + return static_cast(hashed & 0xFFFFFFFFu); + #endif } - template - void VisitNewestFirst(Callback&& callback) const noexcept + struct ThreadState { - for (std::size_t i = 0; i < size; ++i) + Context current{}; + std::array history{}; + std::size_t nextSlot = 0; + std::size_t size = 0; + std::size_t lastFailureSize = 0; + Context lastManualScope{}; + bool lastManualScopeValid = false; + + void PushSnapshot() noexcept { - const auto slotIndex = (nextSlot + kHistoryCapacity - 1 - i) % kHistoryCapacity; - const Context& entry = history[slotIndex]; - if (!entry.hasData) - continue; + history[nextSlot] = current; + history[nextSlot].hasData = true; + nextSlot = (nextSlot + 1) % kHistoryCapacity; + if (size < kHistoryCapacity) + ++size; + } - callback(entry); + template + void VisitNewestFirst(Callback&& callback) const noexcept + { + for (std::size_t i = 0; i < size; ++i) + { + const auto slotIndex = (nextSlot + kHistoryCapacity - 1 - i) % kHistoryCapacity; + const Context& entry = history[slotIndex]; + if (!entry.hasData) + continue; + + callback(entry); + } } - } - }; + }; - inline ThreadState& GetThreadState() noexcept - { - thread_local ThreadState state{}; - return state; - } + inline ThreadState& GetThreadState() noexcept + { + thread_local ThreadState state{}; + return state; + } - inline bool ContextEquals(const Context& lhs, const Context& rhs) noexcept - { - if (!lhs.hasData || !rhs.hasData) - return false; + inline bool ContextEquals(const Context& lhs, const Context& rhs) noexcept + { + if (!lhs.hasData || !rhs.hasData) + return false; - if (lhs.requestedSize != rhs.requestedSize || lhs.resourcePointer != rhs.resourcePointer || lhs.threadId != rhs.threadId - || lhs.timestamp != rhs.timestamp) - return false; + if (lhs.requestedSize != rhs.requestedSize || lhs.resourcePointer != rhs.resourcePointer || lhs.threadId != rhs.threadId || + lhs.timestamp != rhs.timestamp) + return false; - if (std::memcmp(lhs.resourceTag.data(), rhs.resourceTag.data(), lhs.resourceTag.size()) != 0) - return false; + if (std::memcmp(lhs.resourceTag.data(), rhs.resourceTag.data(), lhs.resourceTag.size()) != 0) + return false; - if (std::memcmp(lhs.detail.data(), rhs.detail.data(), lhs.detail.size()) != 0) - return false; + if (std::memcmp(lhs.detail.data(), rhs.detail.data(), lhs.detail.size()) != 0) + return false; - return true; - } + return true; + } - inline void RecordManualScopeSnapshot() noexcept - { - ThreadState& state = GetThreadState(); - state.lastManualScope = state.current; - state.lastManualScope.hasData = true; - state.lastManualScopeValid = true; - } -} // namespace detail + inline void RecordManualScopeSnapshot() noexcept + { + ThreadState& state = GetThreadState(); + state.lastManualScope = state.current; + state.lastManualScope.hasData = true; + state.lastManualScopeValid = true; + } + } // namespace detail - inline void SetAllocationContext(std::size_t sizeBytes, - const void* resourcePtr, - const char* resourceTag, - const char* detail) noexcept + inline void SetAllocationContext(std::size_t sizeBytes, const void* resourcePtr, const char* resourceTag, const char* detail) noexcept { Context& current = detail::GetThreadState().current; current.requestedSize = sizeBytes; @@ -195,21 +192,24 @@ namespace detail inline std::string BuildAllocationTelemetryNote() noexcept { std::array snapshot{}; - std::size_t snapshotCount = 0; - const auto now = std::chrono::system_clock::now(); + std::size_t snapshotCount = 0; + const auto now = std::chrono::system_clock::now(); const auto& threadState = detail::GetThreadState(); - threadState.VisitNewestFirst([&](const Context& entry) { - if (snapshotCount < snapshot.size()) - snapshot[snapshotCount++] = entry; - }); + threadState.VisitNewestFirst( + [&](const Context& entry) + { + if (snapshotCount < snapshot.size()) + snapshot[snapshotCount++] = entry; + }); const std::size_t recordedSize = GetRecordedAllocationSize(); std::string note; note.reserve(640); - auto appendEntryLine = [&](const Context& entry, std::size_t index, bool includeIndexLabel) { + auto appendEntryLine = [&](const Context& entry, std::size_t index, bool includeIndexLabel) + { std::size_t sizeToReport = entry.requestedSize; if (includeIndexLabel && index == 0 && recordedSize != 0) { @@ -233,58 +233,26 @@ namespace detail { if (includeIndexLabel) { - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " #%zu requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu, age=%llims\n", - index, - sizeToReport, - resourceTag, - detailText, - entry.resourcePointer, - static_cast(threadId), - ageMs); + _snprintf_s(line, sizeof(line), _TRUNCATE, " #%zu requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu, age=%llims\n", index, + sizeToReport, resourceTag, detailText, entry.resourcePointer, static_cast(threadId), ageMs); } else { - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu, age=%llims\n", - sizeToReport, - resourceTag, - detailText, - entry.resourcePointer, - static_cast(threadId), - ageMs); + _snprintf_s(line, sizeof(line), _TRUNCATE, " requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu, age=%llims\n", sizeToReport, + resourceTag, detailText, entry.resourcePointer, static_cast(threadId), ageMs); } } else { if (includeIndexLabel) { - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " #%zu requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu\n", - index, - sizeToReport, - resourceTag, - detailText, - entry.resourcePointer, - static_cast(threadId)); + _snprintf_s(line, sizeof(line), _TRUNCATE, " #%zu requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu\n", index, sizeToReport, + resourceTag, detailText, entry.resourcePointer, static_cast(threadId)); } else { - _snprintf_s(line, - sizeof(line), - _TRUNCATE, - " requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu\n", - sizeToReport, - resourceTag, - detailText, - entry.resourcePointer, - static_cast(threadId)); + _snprintf_s(line, sizeof(line), _TRUNCATE, " requested=%zu bytes, tag=%s, detail=%s, object=0x%p, thread=%lu\n", sizeToReport, resourceTag, + detailText, entry.resourcePointer, static_cast(threadId)); } } @@ -294,11 +262,7 @@ namespace detail if (snapshotCount == 0) { char buffer[160]{}; - _snprintf_s(buffer, - sizeof(buffer), - _TRUNCATE, - "Allocation telemetry: requested=%zu bytes (no tagged context available)\n", - recordedSize); + _snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "Allocation telemetry: requested=%zu bytes (no tagged context available)\n", recordedSize); note += buffer; } else @@ -311,7 +275,7 @@ namespace detail } const bool hasManualScope = threadState.lastManualScopeValid && threadState.lastManualScope.hasData; - bool manualScopeCapturedInRing = false; + bool manualScopeCapturedInRing = false; if (hasManualScope) { for (std::size_t i = 0; i < snapshotCount; ++i) @@ -326,8 +290,7 @@ namespace detail if (!hasManualScope) { - note += - "CrashTelemetry::Scope annotations: none executed on this thread before crash; instrument entry points to capture context.\n"; + note += "CrashTelemetry::Scope annotations: none executed on this thread before crash; instrument entry points to capture context.\n"; } else if (!manualScopeCapturedInRing) { @@ -344,10 +307,7 @@ namespace detail class Scope { public: - Scope(std::size_t sizeBytes, - const void* resourcePtr, - const char* resourceTag, - const char* detail) noexcept + Scope(std::size_t sizeBytes, const void* resourcePtr, const char* resourceTag, const char* detail) noexcept : m_previous(CaptureContext()), m_restore(true) { SetAllocationContext(sizeBytes, resourcePtr, resourceTag, detail); @@ -373,21 +333,33 @@ namespace detail Context m_previous{}; bool m_restore{false}; }; -#else - inline void RecordAllocationFailureSize(std::size_t) noexcept {} - inline std::size_t GetRecordedAllocationSize() noexcept { return 0; } - inline void SetAllocationContext(std::size_t, - const void*, - const char*, - const char*) noexcept + #else + inline void RecordAllocationFailureSize(std::size_t) noexcept + { + } + inline std::size_t GetRecordedAllocationSize() noexcept + { + return 0; + } + inline void SetAllocationContext(std::size_t, const void*, const char*, const char*) noexcept { } - inline void ClearAllocationContext() noexcept {} + inline void ClearAllocationContext() noexcept + { + } - inline Context CaptureContext() noexcept { return Context{}; } - inline void RestoreContext(const Context&) noexcept {} - inline std::string BuildAllocationTelemetryNote() noexcept { return {}; } + inline Context CaptureContext() noexcept + { + return Context{}; + } + inline void RestoreContext(const Context&) noexcept + { + } + inline std::string BuildAllocationTelemetryNote() noexcept + { + return {}; + } class Scope { @@ -400,6 +372,6 @@ namespace detail Scope(Scope&&) = delete; Scope& operator=(Scope&&) = delete; }; -#endif -} // namespace CrashTelemetry + #endif +} // namespace CrashTelemetry #endif diff --git a/Shared/sdk/RTree.h b/Shared/sdk/RTree.h index 922c5183271..3f662e4b1b8 100644 --- a/Shared/sdk/RTree.h +++ b/Shared/sdk/RTree.h @@ -55,23 +55,23 @@ o Minor updates for MSVC 2005/08 compilers #include #ifndef _WIN32 -#define __cdecl + #define __cdecl #endif -#define ASSERT assert // RTree uses ASSERT( condition ) +#define ASSERT assert // RTree uses ASSERT( condition ) // // RTree.h // -#define RTREE_TEMPLATE template -#define RTREE_QUAL RTree +#define RTREE_TEMPLATE template +#define RTREE_QUAL RTree -#define RTREE_DONT_USE_MEMPOOLS // This version does not contain a fixed memory allocator, fill in lines with EXAMPLE to implement one. -#define RTREE_USE_SPHERICAL_VOLUME // Better split classification, may be slower on some systems +#define RTREE_DONT_USE_MEMPOOLS // This version does not contain a fixed memory allocator, fill in lines with EXAMPLE to implement one. +#define RTREE_USE_SPHERICAL_VOLUME // Better split classification, may be slower on some systems // Fwd decl -class RTFileStream; // File I/O helper class, look below for implementation and notes. +class RTFileStream; // File I/O helper class, look below for implementation and notes. /// \class RTree /// Implementation of RTree, a multidimensional bounding rectangle tree. @@ -93,15 +93,15 @@ template IsLeaf()) { @@ -268,10 +268,10 @@ class RTree return m_stack[m_tos]; } - StackElement m_stack[MAX_STACK]; ///< Stack as we are doing iteration instead of recursion - int m_tos; ///< Top Of Stack index + StackElement m_stack[MAX_STACK]; ///< Stack as we are doing iteration instead of recursion + int m_tos; ///< Top Of Stack index - friend class RTree; // Allow hiding of non-public functions while allowing manipulation by logical owner + friend class RTree; // Allow hiding of non-public functions while allowing manipulation by logical owner }; /// Get 'first' for iteration @@ -283,7 +283,7 @@ class RTree { if (first->IsInternalNode() && first->m_count > 1) { - a_it.Push(first, 1); // Descend sibling branch later + a_it.Push(first, 1); // Descend sibling branch later } else if (first->IsLeaf()) { @@ -310,8 +310,8 @@ class RTree /// Minimal bounding rectangle (n-dimensional) struct Rect { - ELEMTYPE m_min[NUMDIMS]; ///< Min dimensions of bounding box - ELEMTYPE m_max[NUMDIMS]; ///< Max dimensions of bounding box + ELEMTYPE m_min[NUMDIMS]; ///< Min dimensions of bounding box + ELEMTYPE m_max[NUMDIMS]; ///< Max dimensions of bounding box }; /// May be data or may be another subtree @@ -319,30 +319,30 @@ class RTree /// If the parents level is 0, then this is data struct Branch { - Rect m_rect; ///< Bounds + Rect m_rect; ///< Bounds union { - Node* m_child; ///< Child node - DATATYPE m_data; ///< Data Id or Ptr + Node* m_child; ///< Child node + DATATYPE m_data; ///< Data Id or Ptr }; }; /// Node for each branch level struct Node { - bool IsInternalNode() { return (m_level > 0); } // Not a leaf, but a internal node - bool IsLeaf() { return (m_level == 0); } // A leaf, contains data + bool IsInternalNode() { return (m_level > 0); } // Not a leaf, but a internal node + bool IsLeaf() { return (m_level == 0); } // A leaf, contains data - int m_count; ///< Count - int m_level; ///< Leaf is zero, others positive - Branch m_branch[MAXNODES]; ///< Branch + int m_count; ///< Count + int m_level; ///< Leaf is zero, others positive + Branch m_branch[MAXNODES]; ///< Branch }; /// A link list of nodes for reinsertion after a delete operation struct ListNode { - ListNode* m_next; ///< Next in list - Node* m_node; ///< Node + ListNode* m_next; ///< Next in list + Node* m_node; ///< Node }; /// Variables for finding a split partition @@ -397,8 +397,8 @@ class RTree bool SaveRec(Node* a_node, RTFileStream& a_stream); bool LoadRec(Node* a_node, RTFileStream& a_stream); - Node* m_root; ///< Root of tree - ELEMTYPEREAL m_unitSphereVolume; ///< Unit sphere constant for required number of dimensions + Node* m_root; ///< Root of tree + ELEMTYPEREAL m_unitSphereVolume; ///< Unit sphere constant for required number of dimensions }; // Because there is not stream support, this is a quick and dirty file I/O helper. @@ -482,13 +482,13 @@ RTREE_QUAL::RTree() // Precomputed volumes of the unit spheres for the first few dimensions const float UNIT_SPHERE_VOLUMES[] = { - 0.000000f, 2.000000f, 3.141593f, // Dimension 0,1,2 - 4.188790f, 4.934802f, 5.263789f, // Dimension 3,4,5 - 5.167713f, 4.724766f, 4.058712f, // Dimension 6,7,8 - 3.298509f, 2.550164f, 1.884104f, // Dimension 9,10,11 - 1.335263f, 0.910629f, 0.599265f, // Dimension 12,13,14 - 0.381443f, 0.235331f, 0.140981f, // Dimension 15,16,17 - 0.082146f, 0.046622f, 0.025807f, // Dimension 18,19,20 + 0.000000f, 2.000000f, 3.141593f, // Dimension 0,1,2 + 4.188790f, 4.934802f, 5.263789f, // Dimension 3,4,5 + 5.167713f, 4.724766f, 4.058712f, // Dimension 6,7,8 + 3.298509f, 2.550164f, 1.884104f, // Dimension 9,10,11 + 1.335263f, 0.910629f, 0.599265f, // Dimension 12,13,14 + 0.381443f, 0.235331f, 0.140981f, // Dimension 15,16,17 + 0.082146f, 0.046622f, 0.025807f, // Dimension 18,19,20 }; m_root = AllocNode(); @@ -499,7 +499,7 @@ RTREE_QUAL::RTree() RTREE_TEMPLATE RTREE_QUAL::~RTree() { - Reset(); // Free, or reset node memory + Reset(); // Free, or reset node memory } RTREE_TEMPLATE @@ -510,7 +510,7 @@ void RTREE_QUAL::Insert(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMD { ASSERT(a_min[index] <= a_max[index]); } -#endif //_DEBUG +#endif //_DEBUG Rect rect; @@ -531,7 +531,7 @@ void RTREE_QUAL::Remove(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMD { ASSERT(a_min[index] <= a_max[index]); } -#endif //_DEBUG +#endif //_DEBUG Rect rect; @@ -552,7 +552,7 @@ void RTREE_QUAL::Search(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMD { ASSERT(a_min[index] <= a_max[index]); } -#endif //_DEBUG +#endif //_DEBUG Rect rect; @@ -579,14 +579,14 @@ int RTREE_QUAL::Count() RTREE_TEMPLATE void RTREE_QUAL::CountRec(Node* a_node, int& a_count) { - if (a_node->IsInternalNode()) // not a leaf node + if (a_node->IsInternalNode()) // not a leaf node { for (int index = 0; index < a_node->m_count; ++index) { CountRec(a_node->m_branch[index].m_child, a_count); } } - else // A leaf node + else // A leaf node { a_count += a_node->m_count; } @@ -595,7 +595,7 @@ void RTREE_QUAL::CountRec(Node* a_node, int& a_count) RTREE_TEMPLATE bool RTREE_QUAL::Load(const char* a_fileName) { - RemoveAll(); // Clear existing tree + RemoveAll(); // Clear existing tree RTFileStream stream; if (!stream.OpenRead(a_fileName)) @@ -657,7 +657,7 @@ bool RTREE_QUAL::LoadRec(Node* a_node, RTFileStream& a_stream) a_stream.Read(a_node->m_level); a_stream.Read(a_node->m_count); - if (a_node->IsInternalNode()) // not a leaf node + if (a_node->IsInternalNode()) // not a leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -670,7 +670,7 @@ bool RTREE_QUAL::LoadRec(Node* a_node, RTFileStream& a_stream) LoadRec(curBranch->m_child, a_stream); } } - else // A leaf node + else // A leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -683,7 +683,7 @@ bool RTREE_QUAL::LoadRec(Node* a_node, RTFileStream& a_stream) } } - return true; // Should do more error checking on I/O operations + return true; // Should do more error checking on I/O operations } RTREE_TEMPLATE @@ -734,7 +734,7 @@ bool RTREE_QUAL::SaveRec(Node* a_node, RTFileStream& a_stream) a_stream.Write(a_node->m_level); a_stream.Write(a_node->m_count); - if (a_node->IsInternalNode()) // not a leaf node + if (a_node->IsInternalNode()) // not a leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -746,7 +746,7 @@ bool RTREE_QUAL::SaveRec(Node* a_node, RTFileStream& a_stream) SaveRec(curBranch->m_child, a_stream); } } - else // A leaf node + else // A leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -759,7 +759,7 @@ bool RTREE_QUAL::SaveRec(Node* a_node, RTFileStream& a_stream) } } - return true; // Should do more error checking on I/O operations + return true; // Should do more error checking on I/O operations } RTREE_TEMPLATE @@ -778,10 +778,10 @@ void RTREE_QUAL::Reset() #ifdef RTREE_DONT_USE_MEMPOOLS // Delete all existing nodes RemoveAllRec(m_root); -#else // RTREE_DONT_USE_MEMPOOLS +#else // RTREE_DONT_USE_MEMPOOLS // Just reset memory pools. We are not using complex types // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS +#endif // RTREE_DONT_USE_MEMPOOLS } RTREE_TEMPLATE @@ -790,7 +790,7 @@ void RTREE_QUAL::RemoveAllRec(Node* a_node) ASSERT(a_node); ASSERT(a_node->m_level >= 0); - if (a_node->IsInternalNode()) // This is an internal node in the tree + if (a_node->IsInternalNode()) // This is an internal node in the tree { for (int index = 0; index < a_node->m_count; ++index) { @@ -806,9 +806,9 @@ typename RTREE_QUAL::Node* RTREE_QUAL::AllocNode() Node* newNode; #ifdef RTREE_DONT_USE_MEMPOOLS newNode = new Node; -#else // RTREE_DONT_USE_MEMPOOLS +#else // RTREE_DONT_USE_MEMPOOLS // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS +#endif // RTREE_DONT_USE_MEMPOOLS InitNode(newNode); return newNode; } @@ -820,9 +820,9 @@ void RTREE_QUAL::FreeNode(Node* a_node) #ifdef RTREE_DONT_USE_MEMPOOLS delete a_node; -#else // RTREE_DONT_USE_MEMPOOLS +#else // RTREE_DONT_USE_MEMPOOLS // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS +#endif // RTREE_DONT_USE_MEMPOOLS } // Allocate space for a node in the list used in DeletRect to @@ -832,9 +832,9 @@ typename RTREE_QUAL::ListNode* RTREE_QUAL::AllocListNode() { #ifdef RTREE_DONT_USE_MEMPOOLS return new ListNode; -#else // RTREE_DONT_USE_MEMPOOLS +#else // RTREE_DONT_USE_MEMPOOLS // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS +#endif // RTREE_DONT_USE_MEMPOOLS } RTREE_TEMPLATE @@ -842,9 +842,9 @@ void RTREE_QUAL::FreeListNode(ListNode* a_listNode) { #ifdef RTREE_DONT_USE_MEMPOOLS delete a_listNode; -#else // RTREE_DONT_USE_MEMPOOLS +#else // RTREE_DONT_USE_MEMPOOLS // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS +#endif // RTREE_DONT_USE_MEMPOOLS } RTREE_TEMPLATE @@ -891,7 +891,7 @@ bool RTREE_QUAL::InsertRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, a_node->m_branch[index].m_rect = CombineRect(a_rect, &(a_node->m_branch[index].m_rect)); return false; } - else // Child was split + else // Child was split { a_node->m_branch[index].m_rect = NodeCover(a_node->m_branch[index].m_child); branch.m_child = otherNode; @@ -899,7 +899,7 @@ bool RTREE_QUAL::InsertRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, return AddBranch(&branch, a_node, a_newNode); } } - else if (a_node->m_level == a_level) // Have reached level for insertion. Add rect, split if necessary + else if (a_node->m_level == a_level) // Have reached level for insertion. Add rect, split if necessary { branch.m_rect = *a_rect; branch.m_child = (Node*)a_id; @@ -931,15 +931,15 @@ bool RTREE_QUAL::InsertRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root, i { ASSERT(a_rect->m_min[index] <= a_rect->m_max[index]); } -#endif //_DEBUG +#endif //_DEBUG Node* newRoot; Node* newNode; Branch branch; - if (InsertRectRec(a_rect, a_id, *a_root, &newNode, a_level)) // Root split + if (InsertRectRec(a_rect, a_id, *a_root, &newNode, a_level)) // Root split { - newRoot = AllocNode(); // Grow tree taller and new root + newRoot = AllocNode(); // Grow tree taller and new root newRoot->m_level = (*a_root)->m_level + 1; branch.m_rect = NodeCover(*a_root); branch.m_child = *a_root; @@ -990,7 +990,7 @@ bool RTREE_QUAL::AddBranch(Branch* a_branch, Node* a_node, Node** a_newNode) ASSERT(a_branch); ASSERT(a_node); - if (a_node->m_count < MAXNODES) // Split won't be necessary + if (a_node->m_count < MAXNODES) // Split won't be necessary { a_node->m_branch[a_node->m_count] = *a_branch; ++a_node->m_count; @@ -1163,10 +1163,10 @@ RTREE_TEMPLATE ELEMTYPEREAL RTREE_QUAL::CalcRectVolume(Rect* a_rect) { #ifdef RTREE_USE_SPHERICAL_VOLUME - return RectSphericalVolume(a_rect); // Slower but helps certain merge cases -#else // RTREE_USE_SPHERICAL_VOLUME - return RectVolume(a_rect); // Faster but can cause poor merges -#endif // RTREE_USE_SPHERICAL_VOLUME + return RectSphericalVolume(a_rect); // Slower but helps certain merge cases +#else // RTREE_USE_SPHERICAL_VOLUME + return RectVolume(a_rect); // Faster but can cause poor merges +#endif // RTREE_USE_SPHERICAL_VOLUME } // Load branch buffer with branches from full node plus the extra branch. @@ -1438,7 +1438,7 @@ bool RTREE_QUAL::RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, ASSERT(a_rect && a_node && a_listNode); ASSERT(a_node->m_level >= 0); - if (a_node->IsInternalNode()) // not a leaf node + if (a_node->IsInternalNode()) // not a leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -1455,7 +1455,7 @@ bool RTREE_QUAL::RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, { // child removed, not enough entries in node, eliminate node ReInsert(a_node->m_branch[index].m_child, a_listNode); - DisconnectBranch(a_node, index); // Must return after this call as count has changed + DisconnectBranch(a_node, index); // Must return after this call as count has changed } return false; } @@ -1463,13 +1463,13 @@ bool RTREE_QUAL::RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, } return true; } - else // A leaf node + else // A leaf node { for (int index = 0; index < a_node->m_count; ++index) { if (a_node->m_branch[index].m_child == (Node*)a_id) { - DisconnectBranch(a_node, index); // Must return after this call as count has changed + DisconnectBranch(a_node, index); // Must return after this call as count has changed return false; } } @@ -1514,7 +1514,7 @@ bool RTREE_QUAL::Search(Node* a_node, Rect* a_rect, std::vector& resul ASSERT(a_node->m_level >= 0); ASSERT(a_rect); - if (a_node->IsInternalNode()) // This is an internal node in the tree + if (a_node->IsInternalNode()) // This is an internal node in the tree { for (int index = 0; index < a_node->m_count; ++index) { @@ -1522,12 +1522,12 @@ bool RTREE_QUAL::Search(Node* a_node, Rect* a_rect, std::vector& resul { if (!Search(a_node->m_branch[index].m_child, a_rect, resultList)) { - return false; // Don't continue searching + return false; // Don't continue searching } } } } - else // This is a leaf node + else // This is a leaf node { for (int index = 0; index < a_node->m_count; ++index) { @@ -1541,10 +1541,10 @@ bool RTREE_QUAL::Search(Node* a_node, Rect* a_rect, std::vector& resul } } - return true; // Continue searching + return true; // Continue searching } #undef RTREE_TEMPLATE #undef RTREE_QUAL -#endif //RTREE_H +#endif // RTREE_H diff --git a/Shared/sdk/SString.h b/Shared/sdk/SString.h index 3d199858638..08ba333a781 100644 --- a/Shared/sdk/SString.h +++ b/Shared/sdk/SString.h @@ -17,9 +17,9 @@ #include "SharedUtil.IntTypes.h" #ifdef WIN32 -#ifndef va_copy - #define va_copy(dest, orig) (dest) = (orig) -#endif + #ifndef va_copy + #define va_copy(dest, orig) (dest) = (orig) + #endif #endif class SString : public std::string @@ -68,7 +68,7 @@ class SString : public std::string SString operator+(const SString& other) const { return std::string(*this) + other; } // Assignment - operator const char*() const { return c_str(); } // Auto assign to const char* without using c_str() + operator const char*() const { return c_str(); } // Auto assign to const char* without using c_str() const char* operator*() const { return c_str(); } // Functions diff --git a/Shared/sdk/SharedUtil.AllocTracking.h b/Shared/sdk/SharedUtil.AllocTracking.h index e23f6032ef3..7945c9e9b65 100644 --- a/Shared/sdk/SharedUtil.AllocTracking.h +++ b/Shared/sdk/SharedUtil.AllocTracking.h @@ -105,10 +105,10 @@ inline void _free_(void* Original) return myFree(Original); } - #define malloc _malloc_ - #define calloc _calloc_ + #define malloc _malloc_ + #define calloc _calloc_ #define realloc _realloc_ - #define free _free_ + #define free _free_ #endif #include @@ -181,7 +181,7 @@ namespace std inline bool operator==(Allocator const&) { return true; } inline bool operator!=(Allocator const& a) { return !operator==(a); } - }; // end of class Allocator + }; // end of class Allocator template class CArray : public std::vector<_Ty, Allocator<_Ty> > @@ -226,22 +226,22 @@ namespace std { public: }; -} // namespace std +} // namespace std // Replace std classes // Not safe - do not enable this in distributed builds - #define vector CArray - #define list CList - #define map CMap - #define set CSet - #define deque CDeque + #define vector CArray + #define list CList + #define map CMap + #define set CSet + #define deque CDeque #else - #define myMalloc(a,tag) malloc(a) - #define myCalloc(a,tag) calloc(a) - #define myRealloc(a,b,tag) realloc(a,b) - #define myFree free + #define myMalloc(a, tag) malloc(a) + #define myCalloc(a, tag) calloc(a) + #define myRealloc(a, b, tag) realloc(a, b) + #define myFree free #endif // WITH_ALLOC_TRACKING diff --git a/Shared/sdk/SharedUtil.AllocTracking.hpp b/Shared/sdk/SharedUtil.AllocTracking.hpp index fdb48e8fe81..aa364b4073c 100644 --- a/Shared/sdk/SharedUtil.AllocTracking.hpp +++ b/Shared/sdk/SharedUtil.AllocTracking.hpp @@ -18,17 +18,17 @@ // #if WITH_ALLOC_TRACKING -#undef map -#ifdef WIN32 - #undef malloc - #undef realloc - #undef calloc - #undef free - #define thread_id uint -#else - #define GetCurrentThreadId pthread_self - #define thread_id pthread_t -#endif + #undef map + #ifdef WIN32 + #undef malloc + #undef realloc + #undef calloc + #undef free + #define thread_id uint + #else + #define GetCurrentThreadId pthread_self + #define thread_id pthread_t + #endif namespace { @@ -76,7 +76,7 @@ namespace return NULL; return &it->second; } -} // namespace +} // namespace struct CAllocInfo { @@ -88,18 +88,18 @@ struct CAllocInfo }; static int stats_ready = 1; -#ifdef ALLOC_STATS_MODULE_NAME - #ifndef ALLOC_STATS_PRE_COUNT - #define ALLOC_STATS_PRE_COUNT 0 // Increase if crash at startup - #endif + #ifdef ALLOC_STATS_MODULE_NAME + #ifndef ALLOC_STATS_PRE_COUNT + #define ALLOC_STATS_PRE_COUNT 0 // Increase if crash at startup + #endif static int pre_count = ALLOC_STATS_PRE_COUNT; -#else - #define ALLOC_STATS_MODULE_NAME "none" + #else + #define ALLOC_STATS_MODULE_NAME "none" static int pre_count = -1; -#endif + #endif -static int no_stuff = 0; // No tracking when tracker is allocating -#define INVALID_THREAD_ID (-2) +static int no_stuff = 0; // No tracking when tracker is allocating + #define INVALID_THREAD_ID (-2) typedef unsigned char BYTE; @@ -309,7 +309,7 @@ class CAllocStats { thread_id dwThreadWanting = GetCurrentThreadId(); if (dwThreadWanting == dwThreadUsing) - return false; // No tracking when tracker is allocating + return false; // No tracking when tracker is allocating cs.Lock(); dwThreadUsing = dwThreadWanting; return true; @@ -463,12 +463,12 @@ MTAEXPORT unsigned long GetAllocStats(uint uiType, void* pOutData, unsigned long return 0; } -#define map CMap -#ifdef WIN32 - #define malloc _malloc_ - #define realloc _realloc_ - #define calloc _calloc_ - #define free _free_ -#endif + #define map CMap + #ifdef WIN32 + #define malloc _malloc_ + #define realloc _realloc_ + #define calloc _calloc_ + #define free _free_ + #endif #endif // WITH_ALLOC_TRACKING diff --git a/Shared/sdk/SharedUtil.AsyncTaskScheduler.h b/Shared/sdk/SharedUtil.AsyncTaskScheduler.h index b509070d3bd..e2d3bc071ba 100644 --- a/Shared/sdk/SharedUtil.AsyncTaskScheduler.h +++ b/Shared/sdk/SharedUtil.AsyncTaskScheduler.h @@ -4,14 +4,14 @@ // Workaround MultiplayerSA including this header for whatever reason.. #ifdef __cpp_lib_is_invocable -#define HAS_ASYNC_TASK_SCHED + #define HAS_ASYNC_TASK_SCHED -#include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include + #include namespace SharedUtil { @@ -96,5 +96,5 @@ namespace SharedUtil std::vector> m_TaskResults; std::mutex m_TaskResultsMutex; }; -} // namespace SharedUtil +} // namespace SharedUtil #endif diff --git a/Shared/sdk/SharedUtil.AsyncTaskScheduler.hpp b/Shared/sdk/SharedUtil.AsyncTaskScheduler.hpp index d547786eb19..5b26b41d5d3 100644 --- a/Shared/sdk/SharedUtil.AsyncTaskScheduler.hpp +++ b/Shared/sdk/SharedUtil.AsyncTaskScheduler.hpp @@ -67,5 +67,5 @@ namespace SharedUtil } } } -} // namespace SharedUtil +} // namespace SharedUtil #endif diff --git a/Shared/sdk/SharedUtil.Buffer.h b/Shared/sdk/SharedUtil.Buffer.h index be104c771e6..a70120141b1 100644 --- a/Shared/sdk/SharedUtil.Buffer.h +++ b/Shared/sdk/SharedUtil.Buffer.h @@ -35,8 +35,8 @@ namespace SharedUtil operator T*() { return buffer.empty() ? nullptr : reinterpret_cast(&buffer.at(0)); } }; - // Assuming compiled on little endian machine - #define CBUFFER_LITTLE_ENDIAN +// Assuming compiled on little endian machine +#define CBUFFER_LITTLE_ENDIAN // #define CBUFFER_BIG_ENDIAN ////////////////////////////////////////////////////// @@ -210,15 +210,15 @@ namespace SharedUtil Seek(Tell()); if (!pBuffer->GetBytes(pData, iLength, Tell(), bToFromNetwork)) - return false; // Not enough bytes left to fill request + return false; // Not enough bytes left to fill request // Adjust pos Seek(Tell() + iLength); return true; } - void Read(SString&); // Not defined as it won't work - void Read(CBuffer&); // Not defined as it won't work + void Read(SString&); // Not defined as it won't work + void Read(CBuffer&); // Not defined as it won't work bool ReadString(SString& result, bool bByteLength = false, bool bDoesLengthIncludeLengthOfLength = false) { result = ""; @@ -343,8 +343,8 @@ namespace SharedUtil Seek(Tell() + iLength); } - void Write(const SString&); // Not defined as it won't work - void Write(const CBuffer&); // Not defined as it won't work + void Write(const SString&); // Not defined as it won't work + void Write(const CBuffer&); // Not defined as it won't work void WriteString(const SString& str, bool bByteLength = false, bool bDoesLengthIncludeLengthOfLength = false) { ushort usLength = (ushort)str.length(); @@ -395,4 +395,4 @@ namespace SharedUtil #endif }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.ClassIdent.h b/Shared/sdk/SharedUtil.ClassIdent.h index 79d6f8a4157..7bfc4ae0ba9 100644 --- a/Shared/sdk/SharedUtil.ClassIdent.h +++ b/Shared/sdk/SharedUtil.ClassIdent.h @@ -20,58 +20,80 @@ namespace SharedUtil typedef uint64 ClassBits; typedef uchar ClassId; - #define DECLARE_BASE_CLASS(cls) \ - public: \ - static ClassId GetClassId ( void ) \ - { \ - return CLASS_##cls; \ - } \ - bool IsA( ClassId classId ) const \ - { \ - return ( ClassHierarchyBits & ( 1ULL << classId ) ) ? true : false; \ - } \ - const char* GetClassName ( void ) \ - { \ - return ClassName; \ - } \ - protected: \ - static const char* StaticGetClassName ( void ) \ - { \ - return #cls; \ - } \ - static ClassBits CalcClassHierarchyBits ( void ) \ - { \ - return ( 1ULL << GetClassId () ); \ - } \ - const char* ClassName; \ - ClassBits ClassHierarchyBits; \ - friend CAutoClassInit < cls >; \ - CAutoClassInit < cls > ClassInit; \ - public: \ - void* operator new ( size_t size ) { void* ptr = ::operator new(size); memset(ptr,0,size); return ptr; } \ - void* operator new ( size_t size, void* where ) { memset(where,0,size); return where; } +#define DECLARE_BASE_CLASS(cls) \ +public: \ + static ClassId GetClassId(void) \ + { \ + return CLASS_##cls; \ + } \ + bool IsA(ClassId classId) const \ + { \ + return (ClassHierarchyBits & (1ULL << classId)) ? true : false; \ + } \ + const char* GetClassName(void) \ + { \ + return ClassName; \ + } \ +\ +protected: \ + static const char* StaticGetClassName(void) \ + { \ + return #cls; \ + } \ + static ClassBits CalcClassHierarchyBits(void) \ + { \ + return (1ULL << GetClassId()); \ + } \ + const char* ClassName; \ + ClassBits ClassHierarchyBits; \ + friend CAutoClassInit; \ + CAutoClassInit ClassInit; \ +\ +public: \ + void* operator new(size_t size) \ + { \ + void* ptr = ::operator new(size); \ + memset(ptr, 0, size); \ + return ptr; \ + } \ + void* operator new(size_t size, void* where) \ + { \ + memset(where, 0, size); \ + return where; \ + } - #define DECLARE_CLASS(cls,super) \ - public: \ - static ClassId GetClassId ( void ) \ - { \ - return CLASS_##cls; \ - } \ - protected: \ - static const char* StaticGetClassName ( void ) \ - { \ - return #cls; \ - } \ - static ClassBits CalcClassHierarchyBits ( void ) \ - { \ - return ( 1ULL << GetClassId () ) | super::CalcClassHierarchyBits (); \ - } \ - friend CAutoClassInit < cls >; \ - CAutoClassInit < cls > ClassInit; \ - public: \ - typedef super Super; \ - void* operator new ( size_t size ) { void* ptr = ::operator new(size); memset(ptr,0,size); return ptr; } \ - void* operator new ( size_t size, void* where ) { memset(where,0,size); return where; } +#define DECLARE_CLASS(cls, super) \ +public: \ + static ClassId GetClassId(void) \ + { \ + return CLASS_##cls; \ + } \ +\ +protected: \ + static const char* StaticGetClassName(void) \ + { \ + return #cls; \ + } \ + static ClassBits CalcClassHierarchyBits(void) \ + { \ + return (1ULL << GetClassId()) | super::CalcClassHierarchyBits(); \ + } \ + friend CAutoClassInit; \ + CAutoClassInit ClassInit; \ +\ +public: \ + typedef super Super; \ + void* operator new(size_t size) \ + { \ + void* ptr = ::operator new(size); \ + memset(ptr, 0, size); \ + return ptr; \ + } \ + void* operator new(size_t size, void* where) \ + { \ + memset(where, 0, size); \ + return where; \ + } // // Auto init the class bit flags @@ -99,7 +121,7 @@ namespace SharedUtil return NULL; } - #ifdef WIN32 - #pragma warning( disable : 4355 ) // warning C4355: 'this' : used in base member initializer list - #endif -} // namespace SharedUtil +#ifdef WIN32 + #pragma warning(disable : 4355) // warning C4355: 'this' : used in base member initializer list +#endif +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Crypto.h b/Shared/sdk/SharedUtil.Crypto.h index 98978cdd482..21dd2b90dbb 100644 --- a/Shared/sdk/SharedUtil.Crypto.h +++ b/Shared/sdk/SharedUtil.Crypto.h @@ -257,7 +257,7 @@ namespace SharedUtil inline bool StringToZLibFormat(const std::string& format, int& outResult) { int value = atoi(format.c_str()); - if ((value >= 9 && value <= 31) || (value >= -15 && value <= -9)) // allowed values: 9..31, -9..-15 + if ((value >= 9 && value <= 31) || (value >= -15 && value <= -9)) // allowed values: 9..31, -9..-15 { outResult = value; return true; @@ -274,7 +274,7 @@ namespace SharedUtil if (result != Z_OK) return result; - output.resize(deflateBound(&stream, input.size())); // resize to the upper bound of what the compressed size might be + output.resize(deflateBound(&stream, input.size())); // resize to the upper bound of what the compressed size might be stream.next_out = (Bytef*)output.data(); stream.avail_out = output.size(); @@ -286,14 +286,14 @@ namespace SharedUtil result |= deflateEnd(&stream); if (result == Z_STREAM_END) - output.resize(stream.total_out); // resize to the actual size + output.resize(stream.total_out); // resize to the actual size return result; } inline int ZLibUncompress(const std::string& input, std::string& output, int windowBits = 0) { - if (windowBits == 0 && input.size() >= 2) // try to determine format automatically + if (windowBits == 0 && input.size() >= 2) // try to determine format automatically { if (input[0] == '\x1F' && input[1] == '\x8B') windowBits = (int)ZLibFormat::GZIP; @@ -313,7 +313,7 @@ namespace SharedUtil // Uncompress in chunks std::string buffer; - buffer.resize(std::min(stream.avail_in, 128000U)); // use input length for chunk size (capped to 128k bytes which should be efficient enough) + buffer.resize(std::min(stream.avail_in, 128000U)); // use input length for chunk size (capped to 128k bytes which should be efficient enough) while (true) { stream.next_out = (Bytef*)buffer.data(); @@ -323,7 +323,7 @@ namespace SharedUtil if (result != Z_OK && result != Z_STREAM_END) break; - output.append(buffer, 0, stream.total_out - output.size()); // append only what was written to buffer + output.append(buffer, 0, stream.total_out - output.size()); // append only what was written to buffer if (result == Z_STREAM_END) break; @@ -332,4 +332,4 @@ namespace SharedUtil return result; } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Defines.h b/Shared/sdk/SharedUtil.Defines.h index ee7d13ca83f..f17c9347326 100644 --- a/Shared/sdk/SharedUtil.Defines.h +++ b/Shared/sdk/SharedUtil.Defines.h @@ -17,16 +17,16 @@ // Enable WITH_ALLOC_TRACKING to monitor server module memory usage. *Has a negative performance impact* #ifndef WITH_ALLOC_TRACKING #ifndef MTA_CLIENT - #define WITH_ALLOC_TRACKING 0 // Alloc track server - (Can also be defined in individual modules, just above #include "SharedUtil.h") + #define WITH_ALLOC_TRACKING 0 // Alloc track server - (Can also be defined in individual modules, just above #include "SharedUtil.h") #else - #define WITH_ALLOC_TRACKING 0 // Alloc track client - (Can also be defined in individual modules, just above #include "SharedUtil.h") + #define WITH_ALLOC_TRACKING 0 // Alloc track client - (Can also be defined in individual modules, just above #include "SharedUtil.h") #endif #endif // // Architecture // -#if defined( _M_X64 ) || defined( __x86_64__ ) || defined( _M_AMD64 ) || defined( __amd64__ ) +#if defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) || defined(__amd64__) #define ANY_x64 #ifdef _WIN64 #define WIN_x64 @@ -81,39 +81,39 @@ // Location of server crash dumps // #ifdef WIN32 - #define SERVER_DUMP_PATH "dumps" + #define SERVER_DUMP_PATH "dumps" #else - #define SERVER_DUMP_PATH "mods/deathmatch/dumps" + #define SERVER_DUMP_PATH "mods/deathmatch/dumps" #endif // // vsnprintf with buffer full check // -#define VSNPRINTF( buffer, count, format, argptr ) \ +#define VSNPRINTF(buffer, count, format, argptr) \ { \ - int iResult = vsnprintf ( buffer, count, format, argptr ); \ - if( iResult == -1 || iResult == (count) ) \ - (buffer)[(count)-1] = 0; \ + int iResult = vsnprintf(buffer, count, format, argptr); \ + if (iResult == -1 || iResult == (count)) \ + (buffer)[(count) - 1] = 0; \ } // // strncpy with null termination // #ifndef STRNCPY - #define STRNCPY( dest, source, count ) \ + #define STRNCPY(dest, source, count) \ { \ - strncpy( dest, source, (count)-1 ); \ - (dest)[(count)-1] = 0; \ + strncpy(dest, source, (count) - 1); \ + (dest)[(count) - 1] = 0; \ } #endif // // Copy null terminated string to a temporary buffer on the stack // -#define COPY_CSTR_TO_TEMP_BUFFER( tempname, src, maxsize ) \ - char tempname [maxsize] = ""; \ - if ( src ) \ - STRNCPY( tempname, src, maxsize ); +#define COPY_CSTR_TO_TEMP_BUFFER(tempname, src, maxsize) \ + char tempname[maxsize] = ""; \ + if (src) \ + STRNCPY(tempname, src, maxsize); #ifndef _MSC_VER #define wcsicmp wcscasecmp @@ -122,15 +122,15 @@ // // Macro for counting the number of elements in a static array // -#ifndef NUMELMS // from DShow.h - #define NUMELMS(aa) (sizeof(aa)/sizeof((aa)[0])) +#ifndef NUMELMS // from DShow.h + #define NUMELMS(aa) (sizeof(aa) / sizeof((aa)[0])) #endif // // Stringize the result of expansion of a macro argument // #define MTA_STR_EXPAND(token) #token -#define MTA_STR(token) MTA_STR_EXPAND(token) +#define MTA_STR(token) MTA_STR_EXPAND(token) #ifdef WIN32 #define PATH_SEPERATOR "\\" @@ -140,31 +140,53 @@ // Auto clear a class when new'ed. (Won't work for inline creation.) #define ZERO_ON_NEW \ - void* operator new ( size_t size ) { void* ptr = ::operator new(size); memset(ptr == (void*)-1 ? 0 : ptr,0,size); return ptr; } \ - void* operator new ( size_t size, void* where ) { memset(where,0,size); return where; } + void* operator new(size_t size) \ + { \ + void* ptr = ::operator new(size); \ + memset(ptr == (void*)-1 ? 0 : ptr, 0, size); \ + return ptr; \ + } \ + void* operator new(size_t size, void* where) \ + { \ + memset(where, 0, size); \ + return where; \ + } // As NDEBUG is not defined across most MTA projects, assert() will always be enabled // Use dassert for debug build only assertations #if defined(MTA_DEBUG) || defined(DEBUG) || defined(_DEBUG) #define dassert assert #else - #define dassert(_Expression) ((void)0) + #define dassert(_Expression) ((void)0) #ifdef WIN32 // This, along with RedirectedSetUnhandledExceptionFilter means we can get reports from all crashes with the correct crash address in the file name #undef assert - #define assert(_Expression) (void)( (!!(_Expression)) || ( *((int*)NULL) = 0) ) + #define assert(_Expression) (void)((!!(_Expression)) || (*((int*)NULL) = 0)) #endif #endif -#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } -#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } +#define SAFE_DELETE(p) \ + { \ + if (p) \ + { \ + delete (p); \ + (p) = NULL; \ + } \ + } +#define SAFE_RELEASE(p) \ + { \ + if (p) \ + { \ + (p)->Release(); \ + (p) = NULL; \ + } \ + } #define PI (3.14159265358979323846f) // Clear all member variables to zero for a struct. // Note: Struct should have simple member variables and no virtual functions. -#define ZERO_POD_STRUCT(ptr) \ - memset ( ptr, 0, sizeof(*(ptr)) ) +#define ZERO_POD_STRUCT(ptr) memset(ptr, 0, sizeof(*(ptr))) #define BYTE_MASK(n) ((1 << (n)) - 1) @@ -181,40 +203,42 @@ // s char char wchar_t char // S wchar_t char char ???? // -#define PRSinS "%s" // i.e. SString ( "name:" PRSinS, "dave" ); -#define PRWinS "%ls" // i.e. SString ( "name:" PRWinS, L"dave" ); -#define PRWinW L"%ls" // i.e. WString ( L"name:" PRWinW, L"dave" ); +#define PRSinS "%s" // i.e. SString ( "name:" PRSinS, "dave" ); +#define PRWinS "%ls" // i.e. SString ( "name:" PRWinS, L"dave" ); +#define PRWinW L"%ls" // i.e. WString ( L"name:" PRWinW, L"dave" ); #ifdef _MSC_VER - #define PRSinW L"%S" // i.e. WString ( L"name:" PRSinW, "dave" ); + #define PRSinW L"%S" // i.e. WString ( L"name:" PRSinW, "dave" ); #else - #define PRSinW L"%s" // i.e. WString ( L"name:" PRSinW, "dave" ); + #define PRSinW L"%s" // i.e. WString ( L"name:" PRSinW, "dave" ); #endif // Generic way of showing a uchar index is not set #define UCHAR_INVALID_INDEX 0xFF // Tick count conversions -#define TICKS_FROM_SECONDS(m) ((m)*1000) -#define TICKS_FROM_MINUTES(m) (TICKS_FROM_SECONDS(m)*60) -#define TICKS_FROM_HOURS(m) (TICKS_FROM_MINUTES(m)*60) -#define TICKS_FROM_DAYS(m) (TICKS_FROM_HOURS(m)*24) +#define TICKS_FROM_SECONDS(m) ((m) * 1000) +#define TICKS_FROM_MINUTES(m) (TICKS_FROM_SECONDS(m) * 60) +#define TICKS_FROM_HOURS(m) (TICKS_FROM_MINUTES(m) * 60) +#define TICKS_FROM_DAYS(m) (TICKS_FROM_HOURS(m) * 24) // Export function #if defined _WIN32 #define MTAEXPORT extern "C" __declspec(dllexport) #else - #define MTAEXPORT extern "C" __attribute__ ((visibility ("default"))) + #define MTAEXPORT extern "C" __attribute__((visibility("default"))) #endif -#define BUILD_YEAR ((((__DATE__ [7]-'0')*10+(__DATE__ [8]-'0'))*10+(__DATE__ [9]-'0'))*10+(__DATE__ [10]-'0')) -#define BUILD_MONTH (__DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 0 : 5) \ - : __DATE__ [2] == 'b' ? 1 \ - : __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M'? 2 : 3) \ - : __DATE__ [2] == 'y' ? 4 \ - : __DATE__ [2] == 'l' ? 6 \ - : __DATE__ [2] == 'g' ? 7 \ - : __DATE__ [2] == 'p' ? 8 \ - : __DATE__ [2] == 't' ? 9 \ - : __DATE__ [2] == 'v' ? 10 : 11) -#define BUILD_DAY ((__DATE__ [4]==' ' ? 0 : __DATE__[4]-'0')*10+(__DATE__[5]-'0')) +#define BUILD_YEAR ((((__DATE__[7] - '0') * 10 + (__DATE__[8] - '0')) * 10 + (__DATE__[9] - '0')) * 10 + (__DATE__[10] - '0')) +#define BUILD_MONTH \ + (__DATE__[2] == 'n' ? (__DATE__[1] == 'a' ? 0 : 5) \ + : __DATE__[2] == 'b' ? 1 \ + : __DATE__[2] == 'r' ? (__DATE__[0] == 'M' ? 2 : 3) \ + : __DATE__[2] == 'y' ? 4 \ + : __DATE__[2] == 'l' ? 6 \ + : __DATE__[2] == 'g' ? 7 \ + : __DATE__[2] == 'p' ? 8 \ + : __DATE__[2] == 't' ? 9 \ + : __DATE__[2] == 'v' ? 10 \ + : 11) +#define BUILD_DAY ((__DATE__[4] == ' ' ? 0 : __DATE__[4] - '0') * 10 + (__DATE__[5] - '0')) static constexpr float FLOAT_EPSILON = 0.0001f; diff --git a/Shared/sdk/SharedUtil.Detours.h b/Shared/sdk/SharedUtil.Detours.h index 9c40c748e2f..9041766dbfc 100644 --- a/Shared/sdk/SharedUtil.Detours.h +++ b/Shared/sdk/SharedUtil.Detours.h @@ -10,7 +10,7 @@ #pragma once #if defined(WIN32) -#include + #include namespace SharedUtil { @@ -44,6 +44,6 @@ namespace SharedUtil DetourDetach(&reinterpret_cast(target), replacement); return DetourTransactionCommit() == NO_ERROR; } -} // namespace SharedUtil +} // namespace SharedUtil #endif diff --git a/Shared/sdk/SharedUtil.FastHashMap.h b/Shared/sdk/SharedUtil.FastHashMap.h index e00b2577e77..a379c818569 100644 --- a/Shared/sdk/SharedUtil.FastHashMap.h +++ b/Shared/sdk/SharedUtil.FastHashMap.h @@ -16,16 +16,16 @@ #define CFastHashMap std::CMap #else -#ifdef WIN32 - #pragma push_macro("assert") -#endif + #ifdef WIN32 + #pragma push_macro("assert") + #endif -#include -#undef BASE_TEMPLATE_UTIL_H_ // HACK: Sparsehash and CEF share the same include guard name (NEVER USE MACROS AS INCLUDE GUARDS) + #include + #undef BASE_TEMPLATE_UTIL_H_ // HACK: Sparsehash and CEF share the same include guard name (NEVER USE MACROS AS INCLUDE GUARDS) -#ifdef WIN32 - #pragma pop_macro("assert") -#endif + #ifdef WIN32 + #pragma pop_macro("assert") + #endif // // Default keys for pointers @@ -136,7 +136,7 @@ namespace SharedUtil } return it->second; } -} // namespace SharedUtil +} // namespace SharedUtil inline SString GetEmptyMapKey(SString*) { diff --git a/Shared/sdk/SharedUtil.FastHashSet.h b/Shared/sdk/SharedUtil.FastHashSet.h index ba292f33e88..2d968e7f5bd 100644 --- a/Shared/sdk/SharedUtil.FastHashSet.h +++ b/Shared/sdk/SharedUtil.FastHashSet.h @@ -16,15 +16,15 @@ #define CFastHashSet std::CSet #else -#ifdef WIN32 - #pragma push_macro("assert") -#endif + #ifdef WIN32 + #pragma push_macro("assert") + #endif -#include + #include -#ifdef WIN32 - #pragma pop_macro("assert") -#endif + #ifdef WIN32 + #pragma pop_macro("assert") + #endif namespace SharedUtil { @@ -67,6 +67,6 @@ namespace SharedUtil return true; } -} // namespace SharedUtil +} // namespace SharedUtil #endif // WITH_ALLOC_TRACKING diff --git a/Shared/sdk/SharedUtil.File.h b/Shared/sdk/SharedUtil.File.h index 2e67f1c2e28..0c8d5652ce5 100644 --- a/Shared/sdk/SharedUtil.File.h +++ b/Shared/sdk/SharedUtil.File.h @@ -34,7 +34,6 @@ namespace SharedUtil bool FileLoadWithTimeout(const SString& filePath, SString& outBuffer, DWORD timeoutMs) noexcept; #endif - // // Save to a file // @@ -117,10 +116,10 @@ namespace SharedUtil FILE* TryFopen(const char* szFilename, const char* szMode); FILE* TryFopenExclusive(const char* szFilename, const char* szMode); #endif - int Mkdir(const char* szPath, int iMode = 0775); - int Chdir(const char* szPath); - int Rmdir(const char* szPath); - int Delete(const char* szFilename); - int Rename(const char* szOldFilename, const char* szNewFilename); - } // namespace File -} // namespace SharedUtil + int Mkdir(const char* szPath, int iMode = 0775); + int Chdir(const char* szPath); + int Rmdir(const char* szPath); + int Delete(const char* szFilename); + int Rename(const char* szOldFilename, const char* szNewFilename); + } // namespace File +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.File.hpp b/Shared/sdk/SharedUtil.File.hpp index bcffbdf97b0..54695ab0cb2 100644 --- a/Shared/sdk/SharedUtil.File.hpp +++ b/Shared/sdk/SharedUtil.File.hpp @@ -24,13 +24,13 @@ #include #include -#if __cplusplus >= 201703L // C++17 +#if __cplusplus >= 201703L // C++17 #include #endif #ifdef _WIN32 #ifndef NOMINMAX - #define NOMINMAX + #define NOMINMAX #endif #include "Windows.h" #include "shellapi.h" @@ -245,17 +245,17 @@ bool SharedUtil::FileLoad(std::nothrow_t, const SString& filePath, SString& outB CloseHandle(handle); return true; #else -#ifdef __APPLE__ + #ifdef __APPLE__ struct stat info; if (stat(filePath, &info) != 0) return false; -#else + #else struct stat64 info; if (stat64(filePath, &info) != 0) return false; -#endif + #endif size_t fileSize = static_cast(info.st_size); @@ -286,11 +286,11 @@ bool SharedUtil::FileLoad(std::nothrow_t, const SString& filePath, SString& outB return false; } -#ifdef __APPLE__ + #ifdef __APPLE__ if (fseeko(handle, static_cast(offset), SEEK_SET) != 0) -#else + #else if (fseeko64(handle, static_cast(offset), SEEK_SET) != 0) -#endif + #endif { fclose(handle); outBuffer.clear(); @@ -500,7 +500,7 @@ void SharedUtil::MakeSureDirExists(const SString& strPath) } #else std::filesystem::path filePath = static_cast(PathConform(strPath)); - std::error_code ec{}; + std::error_code ec{}; std::filesystem::create_directories(filePath.parent_path(), ec); #endif } @@ -516,7 +516,7 @@ SString SharedUtil::PathConform(const SString& strPath) // Remove slash duplicates size_t iFirstDoubleSlash = strTemp.find(PATH_SEPERATOR PATH_SEPERATOR); if (iFirstDoubleSlash == std::string::npos) - return strTemp; // No duplicates present + return strTemp; // No duplicates present // If first double slash is not at the start, then treat as a normal duplicate if: // 1. It is not preceeded by a colon, or @@ -582,7 +582,7 @@ SString SharedUtil::GetSystemCurrentDirectory() } #ifdef _WIN32 -#ifdef MTA_CLIENT + #ifdef MTA_CLIENT SString SharedUtil::GetSystemDllDirectory() { @@ -733,12 +733,12 @@ SString SharedUtil::GetDriveNameWithNotEnoughSpace(uint uiResourcesPathMinMB, ui return ""; } -#endif // #ifdef MTA_CLIENT -#endif // #ifdef _WIN32 + #endif // #ifdef MTA_CLIENT +#endif // #ifdef _WIN32 WString SharedUtil::FromUTF8(const SString& strPath) { -#ifdef WIN32_TESTING // This might be faster - Needs testing +#ifdef WIN32_TESTING // This might be faster - Needs testing const char* szSrc = strPath; uint cCharacters = strlen(szSrc) + 1; uint cbUnicode = cCharacters * 4; @@ -759,7 +759,7 @@ WString SharedUtil::FromUTF8(const SString& strPath) SString SharedUtil::ToUTF8(const WString& strPath) { -#ifdef WIN32_TESTING // This might be faster - Needs testing +#ifdef WIN32_TESTING // This might be faster - Needs testing const wchar_t* pszW = strPath; uint cCharacters = wcslen(pszW) + 1; uint cbAnsi = cCharacters * 6; @@ -802,7 +802,7 @@ bool SharedUtil::DelTree(const SString& strPath, const SString& strInsideHere) sfos.hwnd = NULL; sfos.wFunc = FO_DELETE; - sfos.pFrom = szBuffer; // Double NULL terminated + sfos.pFrom = szBuffer; // Double NULL terminated sfos.pTo = NULL; sfos.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; @@ -898,7 +898,7 @@ std::vector SharedUtil::FindFiles(const SString& strInMatch, bool bFile strMatch += "*"; _WIN32_FIND_DATAW findData; - HANDLE hFind = FindFirstFileW(FromUTF8(strMatch), &findData); + HANDLE hFind = FindFirstFileW(FromUTF8(strMatch), &findData); if (hFind != INVALID_HANDLE_VALUE) { try @@ -1110,12 +1110,14 @@ SString SharedUtil::MakeGenericPath(const SString& uniqueFilePath) SString SharedUtil::ConformPathForSorting(const SString& strPathFilename) { SString strResult = strPathFilename; - std::transform(strResult.begin(), strResult.end(), strResult.begin(), [](int c) { - // Ignores locale and always does this: - if (c >= 'A' && c <= 'Z') - c = c - 'A' + 'a'; - return c; - }); + std::transform(strResult.begin(), strResult.end(), strResult.begin(), + [](int c) + { + // Ignores locale and always does this: + if (c >= 'A' && c <= 'Z') + c = c - 'A' + 'a'; + return c; + }); return strResult; } @@ -1161,101 +1163,96 @@ SString SharedUtil::GetSystemLongPathName(const SString& strPath) return strPath; return ToUTF8(szBuffer); } -#endif // _WIN32 +#endif // _WIN32 -namespace SharedUtil { namespace File { -#ifdef _WIN32 - inline bool IsReservedName(const char* path) noexcept +namespace SharedUtil +{ + namespace File { - const char* name = path; - for (const char* p = path; *p; ++p) +#ifdef _WIN32 + inline bool IsReservedName(const char* path) noexcept { - if (*p == '\\' || *p == '/') - name = p + 1; - } + const char* name = path; + for (const char* p = path; *p; ++p) + { + if (*p == '\\' || *p == '/') + name = p + 1; + } - std::size_t len = 0; - while (name[len] && name[len] != '.' && name[len] != ':') - ++len; + std::size_t len = 0; + while (name[len] && name[len] != '.' && name[len] != ':') + ++len; - while (len > 0 && (name[len - 1] == ' ' || name[len - 1] == '.')) - --len; + while (len > 0 && (name[len - 1] == ' ' || name[len - 1] == '.')) + --len; - auto up = [](char c) noexcept -> char { - return (c >= 'a' && c <= 'z') ? static_cast(c - 'a' + 'A') : c; - }; + auto up = [](char c) noexcept -> char { return (c >= 'a' && c <= 'z') ? static_cast(c - 'a' + 'A') : c; }; - if (len == 3) - { - char a = up(name[0]), b = up(name[1]), c = up(name[2]); - return (a == 'C' && b == 'O' && c == 'N') || - (a == 'P' && b == 'R' && c == 'N') || - (a == 'A' && b == 'U' && c == 'X') || - (a == 'N' && b == 'U' && c == 'L'); - } - if (len == 4 && name[3] >= '1' && name[3] <= '9') - { - char a = up(name[0]), b = up(name[1]), c = up(name[2]); - return (a == 'C' && b == 'O' && c == 'M') || - (a == 'L' && b == 'P' && c == 'T'); - } - if (len == 6 && name[5] == '$') - { - char a = up(name[0]), b = up(name[1]), c = up(name[2]); - char d = up(name[3]), e = up(name[4]); - return a == 'C' && b == 'O' && c == 'N' && d == 'I' && e == 'N'; - } - if (len == 7 && name[6] == '$') - { - char a = up(name[0]), b = up(name[1]), c = up(name[2]); - char d = up(name[3]), e = up(name[4]), f = up(name[5]); - return a == 'C' && b == 'O' && c == 'N' && d == 'O' && e == 'U' && f == 'T'; + if (len == 3) + { + char a = up(name[0]), b = up(name[1]), c = up(name[2]); + return (a == 'C' && b == 'O' && c == 'N') || (a == 'P' && b == 'R' && c == 'N') || (a == 'A' && b == 'U' && c == 'X') || + (a == 'N' && b == 'U' && c == 'L'); + } + if (len == 4 && name[3] >= '1' && name[3] <= '9') + { + char a = up(name[0]), b = up(name[1]), c = up(name[2]); + return (a == 'C' && b == 'O' && c == 'M') || (a == 'L' && b == 'P' && c == 'T'); + } + if (len == 6 && name[5] == '$') + { + char a = up(name[0]), b = up(name[1]), c = up(name[2]); + char d = up(name[3]), e = up(name[4]); + return a == 'C' && b == 'O' && c == 'N' && d == 'I' && e == 'N'; + } + if (len == 7 && name[6] == '$') + { + char a = up(name[0]), b = up(name[1]), c = up(name[2]); + char d = up(name[3]), e = up(name[4]), f = up(name[5]); + return a == 'C' && b == 'O' && c == 'N' && d == 'O' && e == 'U' && f == 'T'; + } + return false; } - return false; - } #endif - inline bool IsPathSafe(const char* filename) noexcept - { - if (!filename || !*filename) - return false; - - constexpr std::size_t maxPathLen = 4'096; - if (std::strlen(filename) > maxPathLen) - return false; - - const auto isSeparator = [](char c) noexcept { return c == '\\' || c == '/'; }; - for (const char* p = filename; *p; ++p) + inline bool IsPathSafe(const char* filename) noexcept { - if (p[0] == '.' && p[1] == '.' && - (p == filename || isSeparator(p[-1])) && - (p[2] == '\0' || isSeparator(p[2]))) + if (!filename || !*filename) return false; - } -#ifdef _WIN32 - const auto* colonPos = std::strchr(filename, ':'); - if (colonPos) - { - const bool isDriveLetter = (colonPos == filename + 1) && - std::isalpha(static_cast(filename[0])); - if (!isDriveLetter || std::strchr(colonPos + 1, ':')) + constexpr std::size_t maxPathLen = 4'096; + if (std::strlen(filename) > maxPathLen) return false; - } - if (isSeparator(filename[0]) && isSeparator(filename[1]) && - (filename[2] == '.' || filename[2] == '?') && isSeparator(filename[3])) - return false; + const auto isSeparator = [](char c) noexcept { return c == '\\' || c == '/'; }; + for (const char* p = filename; *p; ++p) + { + if (p[0] == '.' && p[1] == '.' && (p == filename || isSeparator(p[-1])) && (p[2] == '\0' || isSeparator(p[2]))) + return false; + } - if (filename[0] == '\\' && filename[1] == '?' && filename[2] == '?' && filename[3] == '\\') - return false; +#ifdef _WIN32 + const auto* colonPos = std::strchr(filename, ':'); + if (colonPos) + { + const bool isDriveLetter = (colonPos == filename + 1) && std::isalpha(static_cast(filename[0])); + if (!isDriveLetter || std::strchr(colonPos + 1, ':')) + return false; + } - if (IsReservedName(filename)) - return false; + if (isSeparator(filename[0]) && isSeparator(filename[1]) && (filename[2] == '.' || filename[2] == '?') && isSeparator(filename[3])) + return false; + + if (filename[0] == '\\' && filename[1] == '?' && filename[2] == '?' && filename[3] == '\\') + return false; + + if (IsReservedName(filename)) + return false; #endif - return true; + return true; + } } -}} +} #if defined(_WIN32) && defined(MTA_CLIENT) FILE* SharedUtil::File::TryFopen(const char* filename, const char* mode) @@ -1282,16 +1279,19 @@ FILE* SharedUtil::File::TryFopen(const char* filename, const char* mode) switch (mode[i]) { case '+': - if (hasPlus) return errno = EINVAL, nullptr; + if (hasPlus) + return errno = EINVAL, nullptr; hasPlus = true; break; case 'b': - if (hasBT) return errno = EINVAL, nullptr; + if (hasBT) + return errno = EINVAL, nullptr; hasBT = true; isBinary = true; break; case 't': - if (hasBT) return errno = EINVAL, nullptr; + if (hasBT) + return errno = EINVAL, nullptr; hasBT = true; break; default: @@ -1299,15 +1299,17 @@ FILE* SharedUtil::File::TryFopen(const char* filename, const char* mode) } } - char normalizedMode[4]; + char normalizedMode[4]; std::size_t modePos = 0; normalizedMode[modePos++] = baseMode; - if (hasPlus) normalizedMode[modePos++] = '+'; - if (isBinary) normalizedMode[modePos++] = 'b'; + if (hasPlus) + normalizedMode[modePos++] = '+'; + if (isBinary) + normalizedMode[modePos++] = 'b'; normalizedMode[modePos] = '\0'; DWORD accessFlags{}, creationMode{}; - int osFlags{}; + int osFlags{}; switch (baseMode) { case 'r': @@ -1329,28 +1331,60 @@ FILE* SharedUtil::File::TryFopen(const char* filename, const char* mode) osFlags |= isBinary ? _O_BINARY : _O_TEXT; WString wideFilename; - try { wideFilename = FromUTF8(filename); } - catch (...) { return errno = EINVAL, nullptr; } + try + { + wideFilename = FromUTF8(filename); + } + catch (...) + { + return errno = EINVAL, nullptr; + } if (wideFilename.empty()) return errno = EINVAL, nullptr; - const auto fileHandle = CreateFileW(wideFilename.c_str(), accessFlags, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, creationMode, FILE_ATTRIBUTE_NORMAL, nullptr); + const auto fileHandle = CreateFileW(wideFilename.c_str(), accessFlags, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, creationMode, + FILE_ATTRIBUTE_NORMAL, nullptr); if (fileHandle == INVALID_HANDLE_VALUE) { const auto errorCode = GetLastError(); switch (errorCode) { - case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: errno = ENOENT; break; - case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: case ERROR_LOCK_VIOLATION: errno = EACCES; break; - case ERROR_INVALID_NAME: case ERROR_BAD_PATHNAME: errno = EINVAL; break; - case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: errno = EEXIST; break; - case ERROR_DISK_FULL: case ERROR_HANDLE_DISK_FULL: errno = ENOSPC; break; - case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break; - case ERROR_WRITE_PROTECT: errno = EROFS; break; - case ERROR_NOT_READY: errno = ENXIO; break; - case ERROR_INVALID_DRIVE: errno = ENODEV; break; - default: errno = EIO; break; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errno = ENOENT; + break; + case ERROR_ACCESS_DENIED: + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errno = EACCES; + break; + case ERROR_INVALID_NAME: + case ERROR_BAD_PATHNAME: + errno = EINVAL; + break; + case ERROR_FILE_EXISTS: + case ERROR_ALREADY_EXISTS: + errno = EEXIST; + break; + case ERROR_DISK_FULL: + case ERROR_HANDLE_DISK_FULL: + errno = ENOSPC; + break; + case ERROR_TOO_MANY_OPEN_FILES: + errno = EMFILE; + break; + case ERROR_WRITE_PROTECT: + errno = EROFS; + break; + case ERROR_NOT_READY: + errno = ENXIO; + break; + case ERROR_INVALID_DRIVE: + errno = ENODEV; + break; + default: + errno = EIO; + break; } return nullptr; } @@ -1363,14 +1397,10 @@ FILE* SharedUtil::File::TryFopen(const char* filename, const char* mode) { wchar_t finalPath[1024]; - DWORD pathLen = GetFinalPathNameByHandleW(fileHandle, finalPath, 1024, FILE_NAME_NORMALIZED); - if (pathLen > 0 && pathLen < 1024 && pathLen >= 8 && - finalPath[0] == L'\\' && finalPath[1] == L'\\' && - finalPath[2] == L'?' && finalPath[3] == L'\\' && - (finalPath[4] == L'U' || finalPath[4] == L'u') && - (finalPath[5] == L'N' || finalPath[5] == L'n') && - (finalPath[6] == L'C' || finalPath[6] == L'c') && - finalPath[7] == L'\\') + DWORD pathLen = GetFinalPathNameByHandleW(fileHandle, finalPath, 1024, FILE_NAME_NORMALIZED); + if (pathLen > 0 && pathLen < 1024 && pathLen >= 8 && finalPath[0] == L'\\' && finalPath[1] == L'\\' && finalPath[2] == L'?' && finalPath[3] == L'\\' && + (finalPath[4] == L'U' || finalPath[4] == L'u') && (finalPath[5] == L'N' || finalPath[5] == L'n') && + (finalPath[6] == L'C' || finalPath[6] == L'c') && finalPath[7] == L'\\') { CloseHandle(fileHandle); return errno = EACCES, nullptr; @@ -1407,23 +1437,42 @@ FILE* SharedUtil::File::TryFopenExclusive(const char* filename, const char* mode return errno = EINVAL, nullptr; WString wideFilename; - try { wideFilename = FromUTF8(filename); } - catch (...) { return errno = EINVAL, nullptr; } + try + { + wideFilename = FromUTF8(filename); + } + catch (...) + { + return errno = EINVAL, nullptr; + } if (wideFilename.empty()) return errno = EINVAL, nullptr; - const auto fileHandle = CreateFileW(wideFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, - nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + const auto fileHandle = CreateFileW(wideFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (fileHandle == INVALID_HANDLE_VALUE) { const auto errorCode = GetLastError(); switch (errorCode) { - case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: errno = ENOENT; break; - case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: case ERROR_LOCK_VIOLATION: errno = EACCES; break; - case ERROR_INVALID_NAME: case ERROR_BAD_PATHNAME: errno = EINVAL; break; - case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break; - default: errno = EIO; break; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errno = ENOENT; + break; + case ERROR_ACCESS_DENIED: + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errno = EACCES; + break; + case ERROR_INVALID_NAME: + case ERROR_BAD_PATHNAME: + errno = EINVAL; + break; + case ERROR_TOO_MANY_OPEN_FILES: + errno = EMFILE; + break; + default: + errno = EIO; + break; } return nullptr; } @@ -1436,21 +1485,17 @@ FILE* SharedUtil::File::TryFopenExclusive(const char* filename, const char* mode { wchar_t finalPath[1024]; - DWORD pathLen = GetFinalPathNameByHandleW(fileHandle, finalPath, 1024, FILE_NAME_NORMALIZED); - if (pathLen > 0 && pathLen < 1024 && pathLen >= 8 && - finalPath[0] == L'\\' && finalPath[1] == L'\\' && - finalPath[2] == L'?' && finalPath[3] == L'\\' && - (finalPath[4] == L'U' || finalPath[4] == L'u') && - (finalPath[5] == L'N' || finalPath[5] == L'n') && - (finalPath[6] == L'C' || finalPath[6] == L'c') && - finalPath[7] == L'\\') + DWORD pathLen = GetFinalPathNameByHandleW(fileHandle, finalPath, 1024, FILE_NAME_NORMALIZED); + if (pathLen > 0 && pathLen < 1024 && pathLen >= 8 && finalPath[0] == L'\\' && finalPath[1] == L'\\' && finalPath[2] == L'?' && finalPath[3] == L'\\' && + (finalPath[4] == L'U' || finalPath[4] == L'u') && (finalPath[5] == L'N' || finalPath[5] == L'n') && + (finalPath[6] == L'C' || finalPath[6] == L'c') && finalPath[7] == L'\\') { CloseHandle(fileHandle); return errno = EACCES, nullptr; } } - const int osFlags = (mode[1] == 'b') ? (_O_RDONLY | _O_BINARY) : _O_RDONLY; + const int osFlags = (mode[1] == 'b') ? (_O_RDONLY | _O_BINARY) : _O_RDONLY; const auto fileDescriptor = _open_osfhandle(reinterpret_cast(fileHandle), osFlags); if (fileDescriptor == -1) { @@ -1482,7 +1527,7 @@ FILE* SharedUtil::File::FopenExclusive(const char* szFilename, const char* szMod #else FILE* SharedUtil::File::Fopen(const char* szFilename, const char* szMode) { -#ifdef _WIN32 + #ifdef _WIN32 try { return _wfsopen(FromUTF8(szFilename), FromUTF8(szMode), _SH_DENYNO); @@ -1492,14 +1537,14 @@ FILE* SharedUtil::File::Fopen(const char* szFilename, const char* szMode) errno = EINVAL; return nullptr; } -#else + #else return fopen(szFilename, szMode); -#endif + #endif } FILE* SharedUtil::File::FopenExclusive(const char* szFilename, const char* szMode) { -#ifdef _WIN32 + #ifdef _WIN32 try { return _wfsopen(FromUTF8(szFilename), FromUTF8(szMode), _SH_DENYWR); @@ -1509,9 +1554,9 @@ FILE* SharedUtil::File::FopenExclusive(const char* szFilename, const char* szMod errno = EINVAL; return nullptr; } -#else + #else return fopen(szFilename, szMode); -#endif + #endif } #endif @@ -1576,7 +1621,9 @@ std::vector SharedUtil::ListDir(const char* szPath) noexcept entries.push_back(entry.path().filename().string()); } } - catch (...) {} // catch all possible errors and ignore them + catch (...) + { + } // catch all possible errors and ignore them #else #ifdef _WIN32 std::string search_path = szPath; @@ -1591,9 +1638,9 @@ std::vector SharedUtil::ListDir(const char* szPath) noexcept try { - WString wideSearchPath = FromUTF8(search_path); + WString wideSearchPath = FromUTF8(search_path); WIN32_FIND_DATAW fd; - HANDLE hFind = ::FindFirstFileW(wideSearchPath.c_str(), &fd); + HANDLE hFind = ::FindFirstFileW(wideSearchPath.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { @@ -1651,8 +1698,14 @@ bool SharedUtil::FileLoadWithTimeout(const SString& filePath, SString& outBuffer return false; WString wideFilePath; - try { wideFilePath = FromUTF8(filePath); } - catch (...) { return false; } + try + { + wideFilePath = FromUTF8(filePath); + } + catch (...) + { + return false; + } if (wideFilePath.empty()) return false; @@ -1665,30 +1718,48 @@ bool SharedUtil::FileLoadWithTimeout(const SString& filePath, SString& outBuffer if (fileSize == 0) return true; - HANDLE fh = CreateFileW(wideFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr); + HANDLE fh = CreateFileW(wideFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr); if (fh == INVALID_HANDLE_VALUE) return false; HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!ev) { CloseHandle(fh); return false; } + if (!ev) + { + CloseHandle(fh); + return false; + } bool ok = false; - try { outBuffer.resize(fileSize); } catch (...) { goto done; } + try + { + outBuffer.resize(fileSize); + } + catch (...) + { + goto done; + } { - OVERLAPPED ov{}; ov.hEvent = ev; + OVERLAPPED ov{}; + ov.hEvent = ev; DWORD n = 0; if (!ReadFile(fh, &outBuffer[0], fileSize, &n, &ov) && GetLastError() == ERROR_IO_PENDING) { if (WaitForSingleObject(ev, timeoutMs) != WAIT_OBJECT_0) - { CancelIo(fh); GetOverlappedResult(fh, &ov, &n, TRUE); goto done; } + { + CancelIo(fh); + GetOverlappedResult(fh, &ov, &n, TRUE); + goto done; + } } ok = GetOverlappedResult(fh, &ov, &n, FALSE) && n == fileSize; } done: - CloseHandle(ev); CloseHandle(fh); - if (!ok) outBuffer.clear(); + CloseHandle(ev); + CloseHandle(fh); + if (!ok) + outBuffer.clear(); return ok; } -#endif \ No newline at end of file +#endif diff --git a/Shared/sdk/SharedUtil.Game.h b/Shared/sdk/SharedUtil.Game.h index 95e5cf17b36..a2632459a5e 100644 --- a/Shared/sdk/SharedUtil.Game.h +++ b/Shared/sdk/SharedUtil.Game.h @@ -29,7 +29,7 @@ namespace SharedUtil AUTO, DISABLED, }; - } // namespace TrafficLight + } // namespace TrafficLight unsigned char GetTrafficLightStateFromColors(TrafficLight::EColor eColorNS, TrafficLight::EColor eColorEW); @@ -79,14 +79,14 @@ namespace SharedUtil { } - uchar ucIntensity; // 0 to 255 - uchar ucRandomShift; // 0 to 255 - ushort usSpeedMin; // 0 to 1000 - ushort usSpeedMax; // 0 to 1000 - short sScanSizeX; // -1000 to 1000 - short sScanSizeY; // -1000 to 1000 - ushort usRenderSizeX; // 0 to 1000 - ushort usRenderSizeY; // 0 to 1000 + uchar ucIntensity; // 0 to 255 + uchar ucRandomShift; // 0 to 255 + ushort usSpeedMin; // 0 to 1000 + ushort usSpeedMax; // 0 to 1000 + short sScanSizeX; // -1000 to 1000 + short sScanSizeY; // -1000 to 1000 + ushort usRenderSizeX; // 0 to 1000 + ushort usRenderSizeY; // 0 to 1000 bool bInsideBuilding; }; @@ -109,27 +109,27 @@ namespace SharedUtil using EDiagnosticDebug::EDiagnosticDebugType; - // Common strings for SetApplicationSetting - #define DIAG_PRELOAD_UPGRADES_SLOW "diagnostics", "preloading-upgrades-slow" - #define DIAG_PRELOAD_UPGRADE_ATTEMPT_ID "diagnostics", "preloading-upgrade-attempt-id" - #define DIAG_PRELOAD_UPGRADES_LOWEST_UNSAFE "diagnostics", "preloading-upgrades-lowest-unsafe" - #define DIAG_PRELOAD_UPGRADES_HISCORE "diagnostics", "preloading-upgrades-hiscore" - #define DIAG_CRASH_EXTRA_MSG "diagnostics", "last-crash-reason" - #define DIAG_MINIDUMP_DETECTED_COUNT "diagnostics", "num-minidump-detected" - #define DIAG_MINIDUMP_CONFIRMED_COUNT "diagnostics", "num-minidump-confirmed" - #define DIAG_BSOD_DETECT_SKIP "diagnostics", "bsod-detect-skip" - #define GENERAL_PROGRESS_ANIMATION_DISABLE "progress-animation-disable" - - // Common strings for watchdog detections - #define WD_SECTION_PRELOAD_UPGRADES "preload-upgrades" - #define WD_SECTION_NOT_CLEAN_GTA_EXIT "L0" // Opened in loader, closed if GTA exits with no error - #define WD_SECTION_NOT_STARTED_ONLINE_GAME "L1" // Opened in loader, closed when online game has started - #define WD_SECTION_NOT_SHOWN_LOADING_SCREEN "L2" // Opened in loader, closed when loading screen is shown - #define WD_SECTION_STARTUP_FREEZE "L3" // Opened in loader, closed when loading screen is shown, or a startup problem is handled elsewhere - #define WD_SECTION_NOT_USED_MAIN_MENU "L4" // Opened in loader, closed when main menu is used - #define WD_SECTION_POST_INSTALL "L5" // Opened in when installer runs, closed when main menu is used - #define WD_SECTION_IS_QUITTING "Q0" // Open during quit - #define WD_COUNTER_CRASH_CHAIN_BEFORE_ONLINE_GAME "CR1" // Counts consecutive crashes before the online game starts - #define WD_COUNTER_CRASH_CHAIN_BEFORE_LOADING_SCREEN "CR2" // Counts consecutive crashes before the loading screen is shown - #define WD_COUNTER_CRASH_CHAIN_BEFORE_USED_MAIN_MENU "CR3" // Counts consecutive crashes before the main menu is used -} // namespace SharedUtil +// Common strings for SetApplicationSetting +#define DIAG_PRELOAD_UPGRADES_SLOW "diagnostics", "preloading-upgrades-slow" +#define DIAG_PRELOAD_UPGRADE_ATTEMPT_ID "diagnostics", "preloading-upgrade-attempt-id" +#define DIAG_PRELOAD_UPGRADES_LOWEST_UNSAFE "diagnostics", "preloading-upgrades-lowest-unsafe" +#define DIAG_PRELOAD_UPGRADES_HISCORE "diagnostics", "preloading-upgrades-hiscore" +#define DIAG_CRASH_EXTRA_MSG "diagnostics", "last-crash-reason" +#define DIAG_MINIDUMP_DETECTED_COUNT "diagnostics", "num-minidump-detected" +#define DIAG_MINIDUMP_CONFIRMED_COUNT "diagnostics", "num-minidump-confirmed" +#define DIAG_BSOD_DETECT_SKIP "diagnostics", "bsod-detect-skip" +#define GENERAL_PROGRESS_ANIMATION_DISABLE "progress-animation-disable" + +// Common strings for watchdog detections +#define WD_SECTION_PRELOAD_UPGRADES "preload-upgrades" +#define WD_SECTION_NOT_CLEAN_GTA_EXIT "L0" // Opened in loader, closed if GTA exits with no error +#define WD_SECTION_NOT_STARTED_ONLINE_GAME "L1" // Opened in loader, closed when online game has started +#define WD_SECTION_NOT_SHOWN_LOADING_SCREEN "L2" // Opened in loader, closed when loading screen is shown +#define WD_SECTION_STARTUP_FREEZE "L3" // Opened in loader, closed when loading screen is shown, or a startup problem is handled elsewhere +#define WD_SECTION_NOT_USED_MAIN_MENU "L4" // Opened in loader, closed when main menu is used +#define WD_SECTION_POST_INSTALL "L5" // Opened in when installer runs, closed when main menu is used +#define WD_SECTION_IS_QUITTING "Q0" // Open during quit +#define WD_COUNTER_CRASH_CHAIN_BEFORE_ONLINE_GAME "CR1" // Counts consecutive crashes before the online game starts +#define WD_COUNTER_CRASH_CHAIN_BEFORE_LOADING_SCREEN "CR2" // Counts consecutive crashes before the loading screen is shown +#define WD_COUNTER_CRASH_CHAIN_BEFORE_USED_MAIN_MENU "CR3" // Counts consecutive crashes before the main menu is used +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Game.hpp b/Shared/sdk/SharedUtil.Game.hpp index d23944dd9ff..ce1149da491 100644 --- a/Shared/sdk/SharedUtil.Game.hpp +++ b/Shared/sdk/SharedUtil.Game.hpp @@ -76,7 +76,7 @@ namespace SharedUtil CVehicleColor::CVehicleColor() { // Init - m_ucPaletteColors[0] = 0; // Palette color 0 is black + m_ucPaletteColors[0] = 0; // Palette color 0 is black m_ucPaletteColors[1] = 0; m_ucPaletteColors[2] = 0; m_ucPaletteColors[3] = 0; @@ -253,4 +253,4 @@ namespace SharedUtil return SColorRGBA(r, g, b, 0); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Hash.h b/Shared/sdk/SharedUtil.Hash.h index b1d65ad5410..79fc0d9bdfc 100644 --- a/Shared/sdk/SharedUtil.Hash.h +++ b/Shared/sdk/SharedUtil.Hash.h @@ -154,4 +154,4 @@ namespace SharedUtil SString GenerateHashHexString(EHashFunctionType hashFunction, const void* pData, uint uiLength); SString GenerateHashHexString(EHashFunctionType hashFunction, const SString& strData); SString GenerateHashHexStringFromFile(EHashFunctionType hashFunction, const SString& strFilename, int iMaxSize = INT_MAX, int iOffset = 0); -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Hash.hpp b/Shared/sdk/SharedUtil.Hash.hpp index a796f32b2d4..f5632208d7c 100644 --- a/Shared/sdk/SharedUtil.Hash.hpp +++ b/Shared/sdk/SharedUtil.Hash.hpp @@ -24,32 +24,36 @@ namespace bcrypt { extern "C" { - #include +#include } -} // namespace bcrypt +} // namespace bcrypt namespace SharedUtil { - #define S11 7 - #define S12 12 - #define S13 17 - #define S14 22 - #define S21 5 - #define S22 9 - #define S23 14 - #define S24 20 - #define S31 4 - #define S32 11 - #define S33 16 - #define S34 23 - #define S41 6 - #define S42 10 - #define S43 15 - #define S44 21 - - CMD5Hasher::CMD5Hasher() {} - - CMD5Hasher::~CMD5Hasher() {} +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + + CMD5Hasher::CMD5Hasher() + { + } + + CMD5Hasher::~CMD5Hasher() + { + } bool CMD5Hasher::Calculate(const char* szFilename, MD5& md5Result) { @@ -59,7 +63,7 @@ namespace SharedUtil Init(); constexpr size_t bufferSize = 65536; - unsigned char Buffer[bufferSize]; + unsigned char Buffer[bufferSize]; while (true) { size_t bytesRead = fread(Buffer, 1, bufferSize, pFile); @@ -154,7 +158,7 @@ namespace SharedUtil { // CRYPT_START unsigned int input_index, buffer_index; - unsigned int buffer_space; // how much space is left in buffer + unsigned int buffer_space; // how much space is left in buffer // Compute number of bytes mod 64 buffer_index = (unsigned int)((m_count[0] >> 3) & 0x3F); @@ -167,10 +171,10 @@ namespace SharedUtil m_count[1] += ((unsigned int)input_length >> 29); - buffer_space = 64 - buffer_index; // how much space is left in buffer + buffer_space = 64 - buffer_index; // how much space is left in buffer // Transform as many times as possible. - if (input_length >= buffer_space) // ie. we have enough to fill the buffer + if (input_length >= buffer_space) // ie. we have enough to fill the buffer { // fill the rest of the buffer and transform memcpy(m_buffer + buffer_index, input, buffer_space); @@ -182,11 +186,11 @@ namespace SharedUtil Transform(input + input_index); } - buffer_index = 0; // so we can buffer remaining + buffer_index = 0; // so we can buffer remaining } else { - input_index = 0; // so we can buffer the whole input + input_index = 0; // so we can buffer the whole input } // and here we do the buffering: @@ -219,7 +223,10 @@ namespace SharedUtil memset(m_buffer, 0, sizeof(m_buffer)); } - const unsigned char* CMD5Hasher::GetResult() const { return m_digest; } + const unsigned char* CMD5Hasher::GetResult() const + { + return m_digest; + } void CMD5Hasher::Transform(unsigned char block[64]) { @@ -330,15 +337,30 @@ namespace SharedUtil ((unsigned int)input[j]) | (((unsigned int)input[j + 1]) << 8) | (((unsigned int)input[j + 2]) << 16) | (((unsigned int)input[j + 3]) << 24); } - inline unsigned int CMD5Hasher::RotateLeft(unsigned int x, unsigned int n) { return (x << n) | (x >> (32 - n)); } + inline unsigned int CMD5Hasher::RotateLeft(unsigned int x, unsigned int n) + { + return (x << n) | (x >> (32 - n)); + } - inline unsigned int CMD5Hasher::F(unsigned int x, unsigned int y, unsigned int z) { return (x & y) | (~x & z); } + inline unsigned int CMD5Hasher::F(unsigned int x, unsigned int y, unsigned int z) + { + return (x & y) | (~x & z); + } - inline unsigned int CMD5Hasher::G(unsigned int x, unsigned int y, unsigned int z) { return (x & z) | (y & ~z); } + inline unsigned int CMD5Hasher::G(unsigned int x, unsigned int y, unsigned int z) + { + return (x & z) | (y & ~z); + } - inline unsigned int CMD5Hasher::H(unsigned int x, unsigned int y, unsigned int z) { return x ^ y ^ z; } + inline unsigned int CMD5Hasher::H(unsigned int x, unsigned int y, unsigned int z) + { + return x ^ y ^ z; + } - inline unsigned int CMD5Hasher::I(unsigned int x, unsigned int y, unsigned int z) { return y ^ (x | ~z); } + inline unsigned int CMD5Hasher::I(unsigned int x, unsigned int y, unsigned int z) + { + return y ^ (x | ~z); + } inline void CMD5Hasher::FF(unsigned int& a, unsigned int b, unsigned int c, unsigned int d, unsigned int x, unsigned int s, unsigned int ac) { @@ -368,18 +390,21 @@ namespace SharedUtil // Implementation of Bob Jenkin's awesome hash function // Ref: https://burtleburtle.net/bob/hash/doobs.html // - unsigned int HashString(const char* szString) { return HashString(szString, (unsigned int)strlen(szString)); } + unsigned int HashString(const char* szString) + { + return HashString(szString, (unsigned int)strlen(szString)); + } unsigned int HashString(const char* szString, unsigned int length) { - const char* k; //< pointer to the string data to be hashed - unsigned int a, b, c; //< temporary variables - unsigned int len; //< length of the string left + const char* k; //< pointer to the string data to be hashed + unsigned int a, b, c; //< temporary variables + unsigned int len; //< length of the string left k = szString; len = length; a = b = 0x9e3779b9; - c = 0xabcdef89; // initval, arbitrarily set + c = 0xabcdef89; // initval, arbitrarily set while (len >= 12) { @@ -423,7 +448,7 @@ namespace SharedUtil // Handle the last 11 remaining bytes // Note: All cases fall through - c += length; // Lower byte of c gets used for length + c += length; // Lower byte of c gets used for length switch (len) { @@ -552,20 +577,32 @@ namespace SharedUtil if (c < 16) { if ((i & 1) == 0) - pOutput[i / 2] = (c << 4); // First nibble + pOutput[i / 2] = (c << 4); // First nibble else - pOutput[i / 2] |= c; // Second nibble + pOutput[i / 2] |= c; // Second nibble } } } - void GenerateSha256(const void* pData, uint uiLength, uchar output[32]) { sha256((const uchar*)pData, uiLength, output); } + void GenerateSha256(const void* pData, uint uiLength, uchar output[32]) + { + sha256((const uchar*)pData, uiLength, output); + } - SString GenerateSha256HexString(const void* pData, uint uiLength) { return GenerateHashHexString(EHashFunction::SHA256, pData, uiLength); } + SString GenerateSha256HexString(const void* pData, uint uiLength) + { + return GenerateHashHexString(EHashFunction::SHA256, pData, uiLength); + } - SString GenerateSha256HexString(const SString& strData) { return GenerateHashHexString(EHashFunction::SHA256, strData); } + SString GenerateSha256HexString(const SString& strData) + { + return GenerateHashHexString(EHashFunction::SHA256, strData); + } - SString GenerateSha256HexStringFromFile(const SString& strFilename) { return GenerateHashHexStringFromFile(EHashFunction::SHA256, strFilename); } + SString GenerateSha256HexStringFromFile(const SString& strFilename) + { + return GenerateHashHexStringFromFile(EHashFunction::SHA256, strFilename); + } SString GenerateHashHexString(EHashFunctionType hashFunction, const void* pData, uint uiLength) { @@ -771,13 +808,12 @@ namespace SharedUtil return; size_t totalProbeSize = static_cast(strbuflen) * 3 + 8; - void* probe = std::malloc(totalProbeSize); + void* probe = std::malloc(totalProbeSize); if (!probe) return; std::free(probe); - std::unique_ptr strbuf( - static_cast(std::malloc(strbuflen)), &std::free); + std::unique_ptr strbuf(static_cast(std::malloc(strbuflen)), &std::free); if (!strbuf) return; @@ -838,13 +874,12 @@ namespace SharedUtil size_t workingSize = static_cast(numPasses) * 4 + 4; size_t outputSize = static_cast(numPasses) * 4; - void* probe = std::malloc(workingSize + outputSize); + void* probe = std::malloc(workingSize + outputSize); if (!probe) return; std::free(probe); - std::unique_ptr buffer( - static_cast(std::malloc(workingSize)), &std::free); + std::unique_ptr buffer(static_cast(std::malloc(workingSize)), &std::free); if (!buffer) return; @@ -863,4 +898,4 @@ namespace SharedUtil out->assign((char*)buffer.get(), numPasses * 4); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.HashMap.h b/Shared/sdk/SharedUtil.HashMap.h index 869d1947913..ea0e0e36cb3 100644 --- a/Shared/sdk/SharedUtil.HashMap.h +++ b/Shared/sdk/SharedUtil.HashMap.h @@ -14,9 +14,9 @@ #define CHashMap CMap #else -#include -#include -#include "SString.h" + #include + #include + #include "SString.h" namespace SharedUtil { @@ -95,7 +95,7 @@ namespace SharedUtil } return it->second; } -} // namespace SharedUtil +} // namespace SharedUtil // Calculate a hash value for SString namespace std @@ -105,6 +105,6 @@ namespace std { size_t operator()(const SString& str) const { return std::hash()(str); } }; -} // namespace std +} // namespace std #endif // WITH_ALLOC_TRACKING diff --git a/Shared/sdk/SharedUtil.IntTypes.h b/Shared/sdk/SharedUtil.IntTypes.h index e3b391b3543..6f8171852f9 100644 --- a/Shared/sdk/SharedUtil.IntTypes.h +++ b/Shared/sdk/SharedUtil.IntTypes.h @@ -12,27 +12,27 @@ *************************************************************************/ // VS GCC // Actual sizes: 32bit 64bit 64bit -typedef unsigned long ulong; // 32 32 64 -typedef unsigned int uint; // 32 -typedef unsigned short ushort; // 16 -typedef unsigned char uchar; // 8 +typedef unsigned long ulong; // 32 32 64 +typedef unsigned int uint; // 32 +typedef unsigned short ushort; // 16 +typedef unsigned char uchar; // 8 -typedef unsigned long long uint64; // 64 -typedef unsigned int uint32; // 32 -typedef unsigned short uint16; // 16 -typedef unsigned char uint8; // 8 +typedef unsigned long long uint64; // 64 +typedef unsigned int uint32; // 32 +typedef unsigned short uint16; // 16 +typedef unsigned char uint8; // 8 // signed types -typedef signed long long int64; // 64 -typedef signed int int32; // 32 -typedef signed short int16; // 16 -typedef signed char int8; // 8 +typedef signed long long int64; // 64 +typedef signed int int32; // 32 +typedef signed short int16; // 16 +typedef signed char int8; // 8 // Windowsesq types -typedef unsigned char BYTE; // 8 -typedef unsigned short WORD; // 16 -typedef unsigned long DWORD; // 32 32 64 -typedef float FLOAT; // 32 +typedef unsigned char BYTE; // 8 +typedef unsigned short WORD; // 16 +typedef unsigned long DWORD; // 32 32 64 +typedef float FLOAT; // 32 // Type: considerations: // a) long (and therefore DWORD) is 64 bits when compiled using 64 bit GCC diff --git a/Shared/sdk/SharedUtil.IntervalCounter.h b/Shared/sdk/SharedUtil.IntervalCounter.h index aa3e4a7fb21..39afe4c7532 100644 --- a/Shared/sdk/SharedUtil.IntervalCounter.h +++ b/Shared/sdk/SharedUtil.IntervalCounter.h @@ -51,4 +51,4 @@ namespace SharedUtil } shared; }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.IntervalCounter.hpp b/Shared/sdk/SharedUtil.IntervalCounter.hpp index a8b2d6d3bc3..8f3cd790110 100644 --- a/Shared/sdk/SharedUtil.IntervalCounter.hpp +++ b/Shared/sdk/SharedUtil.IntervalCounter.hpp @@ -119,4 +119,4 @@ namespace SharedUtil pTimer->Reset(); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Legacy.h b/Shared/sdk/SharedUtil.Legacy.h index 38778a04ee2..eba6ee78a1b 100644 --- a/Shared/sdk/SharedUtil.Legacy.h +++ b/Shared/sdk/SharedUtil.Legacy.h @@ -26,34 +26,34 @@ namespace SharedUtil { return a > b ? a : b; } -} // namespace SharedUtil +} // namespace SharedUtil #ifndef PRId64 - #define PRId64 "lld" + #define PRId64 "lld" #endif #ifndef PRIx64 - #define PRIx64 "llx" + #define PRIx64 "llx" #endif // Crazy thing -#define LOCAL_FUNCTION_START struct local { -#define LOCAL_FUNCTION_END }; -#define LOCAL_FUNCTION local +#define LOCAL_FUNCTION_START \ + struct local \ + { +#define LOCAL_FUNCTION_END \ + } \ + ; +#define LOCAL_FUNCTION local // Inline callback definition for std::sort -#define sort_inline(a,b,c) \ - { \ - LOCAL_FUNCTION_START \ - static bool SortPredicate c \ - LOCAL_FUNCTION_END \ - std::sort ( a, b, LOCAL_FUNCTION::SortPredicate ); \ - } +#define sort_inline(a, b, c) \ + { \ + LOCAL_FUNCTION_START \ + static bool SortPredicate c LOCAL_FUNCTION_END std::sort(a, b, LOCAL_FUNCTION::SortPredicate); \ + } // Inline callback definition for std::list::sort -#define sort_list_inline(a,c) \ - { \ - LOCAL_FUNCTION_START \ - static bool SortPredicate c \ - LOCAL_FUNCTION_END \ - a.sort ( LOCAL_FUNCTION::SortPredicate ); \ - } +#define sort_list_inline(a, c) \ + { \ + LOCAL_FUNCTION_START \ + static bool SortPredicate c LOCAL_FUNCTION_END a.sort(LOCAL_FUNCTION::SortPredicate); \ + } diff --git a/Shared/sdk/SharedUtil.Logging.h b/Shared/sdk/SharedUtil.Logging.h index 05422e15fc5..408e3806344 100644 --- a/Shared/sdk/SharedUtil.Logging.h +++ b/Shared/sdk/SharedUtil.Logging.h @@ -13,37 +13,44 @@ namespace SharedUtil { - // - // Output timestamped line into the debugger - // - #ifdef MTA_DEBUG +// +// Output timestamped line into the debugger +// +#ifdef MTA_DEBUG void OutputDebugLine(const char* szMessage); void SetDebugTagHidden(const SString& strTag, bool bHidden = true); bool IsDebugTagHidden(const SString& strTag); - #else - inline void OutputDebugLineDummy() {} - inline void SetDebugTagHiddenDummy() {} - inline bool IsDebugTagHiddenDummy() { return false; } - #define OutputDebugLine(x) OutputDebugLineDummy () - #define SetDebugTagHidden(x) SetDebugTagHiddenDummy () - #define IsDebugTagHidden(x) IsDebugTagHiddenDummy () - #endif +#else + inline void OutputDebugLineDummy() + { + } + inline void SetDebugTagHiddenDummy() + { + } + inline bool IsDebugTagHiddenDummy() + { + return false; + } + #define OutputDebugLine(x) OutputDebugLineDummy() + #define SetDebugTagHidden(x) SetDebugTagHiddenDummy() + #define IsDebugTagHidden(x) IsDebugTagHiddenDummy() +#endif void OutputReleaseLine(const char* szMessage); - // Instance counter - #ifdef MTA_DEBUG +// Instance counter +#ifdef MTA_DEBUG void DebugCreateCount(const SString& strName); void DebugDestroyCount(const SString& strName); - #define DEBUG_CREATE_COUNT(cls) DebugCreateCount(cls) - #define DEBUG_DESTROY_COUNT(cls) DebugDestroyCount(cls) - #else - #define DEBUG_CREATE_COUNT(cls) - #define DEBUG_DESTROY_COUNT(cls) - #endif + #define DEBUG_CREATE_COUNT(cls) DebugCreateCount(cls) + #define DEBUG_DESTROY_COUNT(cls) DebugDestroyCount(cls) +#else + #define DEBUG_CREATE_COUNT(cls) + #define DEBUG_DESTROY_COUNT(cls) +#endif // Cycle (log) files when they reach a certain size. void CycleFile(const SString& strPathFilename, uint uiCycleThreshKB = 1, uint uiNumBackups = 1); -}; // namespace SharedUtil +}; // namespace SharedUtil using namespace SharedUtil; diff --git a/Shared/sdk/SharedUtil.Logging.hpp b/Shared/sdk/SharedUtil.Logging.hpp index d5f163aece7..f295bc0175a 100644 --- a/Shared/sdk/SharedUtil.Logging.hpp +++ b/Shared/sdk/SharedUtil.Logging.hpp @@ -47,13 +47,13 @@ namespace SharedUtil SetDebugTagHidden("LogEvent"); SetDebugTagHidden("Mem"); - #ifdef Has_InitDebugTagsLocal + #ifdef Has_InitDebugTagsLocal InitDebugTagsLocal(); - #endif + #endif } static std::set ms_debugTagInvisibleMap; -}; // namespace SharedUtil +}; // namespace SharedUtil // // Set hiddeness of a debug tag @@ -96,11 +96,11 @@ void SharedUtil::OutputDebugLine(const char* szMessage) SString strMessage = GetLocalTimeString(false, true) + " - " + szMessage; if (strMessage.length() > 0 && strMessage[strMessage.length() - 1] != '\n') strMessage += "\n"; -#ifdef _WIN32 + #ifdef _WIN32 OutputDebugStringW(FromUTF8(strMessage)); -#else - // Other platforms here -#endif + #else + // Other platforms here + #endif } namespace SharedUtil @@ -131,7 +131,7 @@ namespace SharedUtil if (info.iCount < 0) OutputDebugLine(SString("[InstanceCount] Count is negative (%d) for %s", info.iCount, *strName)); } -} // namespace SharedUtil +} // namespace SharedUtil #endif // MTA_DEBUG @@ -146,7 +146,7 @@ void SharedUtil::OutputReleaseLine(const char* szMessage) #ifdef _WIN32 OutputDebugStringW(FromUTF8(strMessage)); #else - // Other platforms here + // Other platforms here #endif } diff --git a/Shared/sdk/SharedUtil.Map.h b/Shared/sdk/SharedUtil.Map.h index 8907932bf62..860a6ab149d 100644 --- a/Shared/sdk/SharedUtil.Map.h +++ b/Shared/sdk/SharedUtil.Map.h @@ -216,4 +216,4 @@ namespace SharedUtil return std::get(collection.insert(item)); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Math.h b/Shared/sdk/SharedUtil.Math.h index f8d29401321..3dc5cebddac 100644 --- a/Shared/sdk/SharedUtil.Math.h +++ b/Shared/sdk/SharedUtil.Math.h @@ -104,10 +104,13 @@ namespace SharedUtil } } - inline float DegreesToRadians(float fValue) { return fValue * 0.017453292f; } + inline float DegreesToRadians(float fValue) + { + return fValue * 0.017453292f; + } static std::random_device randomDevice; - static std::mt19937 randomEngine(randomDevice()); + static std::mt19937 randomEngine(randomDevice()); inline float GetRandomNumberInRange(float minRange, float maxRange) { @@ -116,7 +119,7 @@ namespace SharedUtil inline bool IsNearlyEqual(float a, float b, float epsilon = std::numeric_limits().epsilon()) noexcept { - return std::fabs(a - b) <= epsilon; + return std::fabs(a - b) <= epsilon; } inline bool ApproximatelyEqual(float a, float b, float epsilon = std::numeric_limits().epsilon()) noexcept @@ -139,4 +142,4 @@ namespace SharedUtil return (b - a) > std::max(std::fabs(a), std::fabs(b)) * epsilon; } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.MemAccess.h b/Shared/sdk/SharedUtil.MemAccess.h index 85e41f1f178..78625284741 100644 --- a/Shared/sdk/SharedUtil.MemAccess.h +++ b/Shared/sdk/SharedUtil.MemAccess.h @@ -46,4 +46,4 @@ namespace SharedUtil { \ dassert(IsSlowMem((const void*)(addr), size)); \ } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.MemAccess.hpp b/Shared/sdk/SharedUtil.MemAccess.hpp index 1a97a2e3ac8..8ff9ba09368 100644 --- a/Shared/sdk/SharedUtil.MemAccess.hpp +++ b/Shared/sdk/SharedUtil.MemAccess.hpp @@ -8,7 +8,7 @@ * *****************************************************************************/ -#pragma once +#pragma once #include #include #include "SharedUtil.MemAccess.h" @@ -111,8 +111,8 @@ namespace SharedUtil OutputDebugLine(SString("[MemAccess] OpenMemWrite at %08x for %d bytes (oldProt:%04x)", pAddr, uiAmount, hMem.oldProt)); #ifdef MTA_DEBUG -#if 0 // Annoying - // Checks + #if 0 // Annoying + // Checks if ( IsProtectedSlowMem( (const void*)hMem.dwFirstPage ) ) assert( hMem.oldProt == PAGE_EXECUTE_READ || hMem.oldProt == PAGE_READONLY ); else @@ -162,7 +162,7 @@ namespace SharedUtil dassert(oldProt == PAGE_EXECUTE_READWRITE); } - hMem.dwFirstPage = 0; // Invalidate handle + hMem.dwFirstPage = 0; // Invalidate handle } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Memory.h b/Shared/sdk/SharedUtil.Memory.h index 5cbd40a7b0f..563f5bfdb6b 100644 --- a/Shared/sdk/SharedUtil.Memory.h +++ b/Shared/sdk/SharedUtil.Memory.h @@ -12,7 +12,7 @@ #include -#define CUSTOM_EXCEPTION_CODE_OOM 0xE03B10C0 // -533000000 +#define CUSTOM_EXCEPTION_CODE_OOM 0xE03B10C0 // -533000000 namespace SharedUtil { @@ -27,4 +27,4 @@ namespace SharedUtil bool TryGetProcessMemoryStats(ProcessMemoryStats& out); void SetMemoryAllocationFailureHandler(); -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Memory.hpp b/Shared/sdk/SharedUtil.Memory.hpp index 2b2e79c954d..2834249d67a 100644 --- a/Shared/sdk/SharedUtil.Memory.hpp +++ b/Shared/sdk/SharedUtil.Memory.hpp @@ -102,7 +102,7 @@ namespace SharedUtil if (!success && GetLastError() == ERROR_BAD_LENGTH) { - workingSetInfo->NumberOfEntries += 64; // Insurance in case the number of entries changes. + workingSetInfo->NumberOfEntries += 64; // Insurance in case the number of entries changes. workingSetBuffer.resize(workingSetInfo->NumberOfEntries * sizeof(PSAPI_WORKING_SET_BLOCK) + sizeof(PSAPI_WORKING_SET_INFORMATION)); workingSetInfo = reinterpret_cast(workingSetBuffer.data()); success = QueryWorkingSet(process, workingSetBuffer.data(), workingSetBuffer.size()); @@ -192,4 +192,4 @@ namespace SharedUtil std::set_new_handler(&HandleMemoryAllocationFailure); #endif } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Misc.h b/Shared/sdk/SharedUtil.Misc.h index 5d9165ff436..2a80a7ca680 100644 --- a/Shared/sdk/SharedUtil.Misc.h +++ b/Shared/sdk/SharedUtil.Misc.h @@ -27,61 +27,62 @@ #include "SharedUtil.Map.h" #include "SharedUtil.Logging.h" -#if __cplusplus >= 201703L // C++17 +#if __cplusplus >= 201703L // C++17 #ifndef __GLIBCXX__ - namespace std - { - namespace filesystem - { - class path; - } - } +namespace std +{ + namespace filesystem + { + class path; + } +} #else - namespace std - { - namespace filesystem - { - inline namespace __cxx11 __attribute__((__abi_tag__("cxx11"))) {} - inline _GLIBCXX_BEGIN_NAMESPACE_CXX11 +namespace std +{ + namespace filesystem + { + inline namespace __cxx11 __attribute__((__abi_tag__("cxx11"))) { + } + inline _GLIBCXX_BEGIN_NAMESPACE_CXX11 - class path; + class path; - _GLIBCXX_END_NAMESPACE_CXX11 - } - } + _GLIBCXX_END_NAMESPACE_CXX11 + } +} #endif #endif #ifdef WIN32 -// Forward declare basic windows types to avoid including windows.h here -#ifdef STRICT + // Forward declare basic windows types to avoid including windows.h here + #ifdef STRICT struct HGLOBAL__; using WinHGlobalHandle = struct HGLOBAL__*; -#else + #else using WinHGlobalHandle = void*; -#endif + #endif struct HWND__; #ifndef _WINDOWS_ -typedef HWND__* HWND; +typedef HWND__* HWND; typedef unsigned int UINT; #ifndef HINSTANCE__ struct HINSTANCE__; #endif typedef HINSTANCE__* HINSTANCE; -typedef HINSTANCE HMODULE; - #ifndef BOOL +typedef HINSTANCE HMODULE; + #ifndef BOOL typedef int BOOL; - #endif - #ifndef WINAPI - #define WINAPI __stdcall - #endif - #ifndef NO_ERROR - #define NO_ERROR 0L - #endif - extern "C" __declspec(dllimport) void WINAPI SetLastError(DWORD dwErrCode); - extern "C" __declspec(dllimport) DWORD WINAPI GetLastError(void); - extern "C" __declspec(dllimport) BOOL WINAPI GlobalUnlock(WinHGlobalHandle hMem); + #endif + #ifndef WINAPI + #define WINAPI __stdcall + #endif + #ifndef NO_ERROR + #define NO_ERROR 0L + #endif +extern "C" __declspec(dllimport) void WINAPI SetLastError(DWORD dwErrCode); +extern "C" __declspec(dllimport) DWORD WINAPI GetLastError(void); +extern "C" __declspec(dllimport) BOOL WINAPI GlobalUnlock(WinHGlobalHandle hMem); #endif #endif @@ -94,15 +95,15 @@ namespace SharedUtil { inline void* GetProcAddressRaw(HMODULE hModule, const char* functionName) noexcept { -#ifdef _WINDOWS_ + #ifdef _WINDOWS_ if (hModule != nullptr) { return reinterpret_cast(::GetProcAddress(hModule, functionName)); } -#else + #else (void)hModule; (void)functionName; -#endif + #endif return nullptr; } } @@ -188,7 +189,7 @@ namespace SharedUtil class GlobalUnlockGuard { public: - using MutexGuard = std::scoped_lock; + using MutexGuard = std::scoped_lock; GlobalUnlockGuard() noexcept = default; explicit GlobalUnlockGuard(WinHGlobalHandle handle) noexcept : m_handle(handle) {} @@ -203,11 +204,13 @@ namespace SharedUtil { if (this != &other) { - WithLock([&]() noexcept { - DWORD errorCode = NO_ERROR; - UnlockLocked("during move assignment", &errorCode); - m_handle = other.release(); - }); + WithLock( + [&]() noexcept + { + DWORD errorCode = NO_ERROR; + UnlockLocked("during move assignment", &errorCode); + m_handle = other.release(); + }); } return *this; } @@ -217,21 +220,23 @@ namespace SharedUtil return WithLock([&]() noexcept { return UnlockInternal(failureCode); }); } - void reset(WinHGlobalHandle handle = nullptr) noexcept + void reset(WinHGlobalHandle handle = nullptr) noexcept { - WithLock([&]() noexcept { - DWORD errorCode = NO_ERROR; - UnlockLocked("during reset", &errorCode); - m_handle = handle; - }); + WithLock( + [&]() noexcept + { + DWORD errorCode = NO_ERROR; + UnlockLocked("during reset", &errorCode); + m_handle = handle; + }); } - [[nodiscard]] WinHGlobalHandle release() noexcept + [[nodiscard]] WinHGlobalHandle release() noexcept { return WithLock([&]() noexcept { return std::exchange(m_handle, nullptr); }); } - [[nodiscard]] WinHGlobalHandle get() const noexcept + [[nodiscard]] WinHGlobalHandle get() const noexcept { return WithLock([&]() noexcept { return m_handle; }); } @@ -241,10 +246,12 @@ namespace SharedUtil private: void UnlockAndLog(const char* context) noexcept { - WithLock([&]() noexcept { - DWORD errorCode = NO_ERROR; - UnlockLocked(context, &errorCode); - }); + WithLock( + [&]() noexcept + { + DWORD errorCode = NO_ERROR; + UnlockLocked(context, &errorCode); + }); } template @@ -278,9 +285,9 @@ namespace SharedUtil } SetLastError(NO_ERROR); - const BOOL unlocked = GlobalUnlock(m_handle); + const BOOL unlocked = GlobalUnlock(m_handle); const DWORD lastError = GetLastError(); - const bool failed = (unlocked == 0 && lastError != NO_ERROR); + const bool failed = (unlocked == 0 && lastError != NO_ERROR); if (failureCode) *failureCode = failed ? lastError : NO_ERROR; m_handle = nullptr; @@ -364,18 +371,18 @@ namespace SharedUtil // BrowseToSolution flags enum { - EXIT_GAME_FIRST = 1, // Exit from game before showing message - Useful only if game has started and has control of the screen - ASK_GO_ONLINE = 2, // Ask user if he wants to go online (otherwise, always go online) - TERMINATE_IF_YES = 4, // What to do at the end. Only relevant if EXIT_GAME_FIRST is not used - TERMINATE_IF_NO = 8, // '' + EXIT_GAME_FIRST = 1, // Exit from game before showing message - Useful only if game has started and has control of the screen + ASK_GO_ONLINE = 2, // Ask user if he wants to go online (otherwise, always go online) + TERMINATE_IF_YES = 4, // What to do at the end. Only relevant if EXIT_GAME_FIRST is not used + TERMINATE_IF_NO = 8, // '' TERMINATE_IF_YES_OR_NO = TERMINATE_IF_YES | TERMINATE_IF_NO, TERMINATE_PROCESS = TERMINATE_IF_YES_OR_NO, - ICON_ERROR = 0x10, // MB_ICONERROR - ICON_QUESTION = 0x20, // MB_ICONQUESTION - ICON_WARNING = 0x30, // MB_ICONWARNING - ICON_INFO = 0x40, // MB_ICONINFORMATION + ICON_ERROR = 0x10, // MB_ICONERROR + ICON_QUESTION = 0x20, // MB_ICONQUESTION + ICON_WARNING = 0x30, // MB_ICONWARNING + ICON_INFO = 0x40, // MB_ICONINFORMATION ICON_MASK_VALUE = ICON_ERROR | ICON_QUESTION | ICON_WARNING | ICON_INFO, - SHOW_MESSAGE_ONLY = 0x80, // Just show message without going online + SHOW_MESSAGE_ONLY = 0x80, // Just show message without going online }; void BrowseToSolution(const SString& strType, int uiFlags = 0, const SString& strMessageBoxMessage = "", const SString& strErrorCode = ""); bool ProcessPendingBrowseToSolution(); @@ -446,7 +453,7 @@ namespace SharedUtil // string stuff // -#if __cplusplus >= 201703L // C++17 +#if __cplusplus >= 201703L // C++17 std::string UTF8FilePath(const std::filesystem::path& input); #endif @@ -505,7 +512,10 @@ namespace SharedUtil } // Unlerp avoiding extrapolation - inline const float UnlerpClamped(const double dFrom, const double dPos, const double dTo) { return Clamp(0.0f, Unlerp(dFrom, dPos, dTo), 1.0f); } + inline const float UnlerpClamped(const double dFrom, const double dPos, const double dTo) + { + return Clamp(0.0f, Unlerp(dFrom, dPos, dTo), 1.0f); + } template int Round(T value) @@ -759,15 +769,39 @@ namespace SharedUtil // typedef SColor RGBA; - inline unsigned char COLOR_RGBA_R(SColor color) { return color.R; } - inline unsigned char COLOR_RGBA_G(SColor color) { return color.G; } - inline unsigned char COLOR_RGBA_B(SColor color) { return color.B; } - inline unsigned char COLOR_RGBA_A(SColor color) { return color.A; } - inline unsigned char COLOR_ARGB_A(SColor color) { return color.A; } + inline unsigned char COLOR_RGBA_R(SColor color) + { + return color.R; + } + inline unsigned char COLOR_RGBA_G(SColor color) + { + return color.G; + } + inline unsigned char COLOR_RGBA_B(SColor color) + { + return color.B; + } + inline unsigned char COLOR_RGBA_A(SColor color) + { + return color.A; + } + inline unsigned char COLOR_ARGB_A(SColor color) + { + return color.A; + } - inline SColor COLOR_RGBA(unsigned char R, unsigned char G, unsigned char B, unsigned char A) { return SColorRGBA(R, G, B, A); } - inline SColor COLOR_ARGB(unsigned char A, unsigned char R, unsigned char G, unsigned char B) { return SColorRGBA(R, G, B, A); } - inline SColor COLOR_ABGR(unsigned char A, unsigned char B, unsigned char G, unsigned char R) { return SColorRGBA(R, G, B, A); } + inline SColor COLOR_RGBA(unsigned char R, unsigned char G, unsigned char B, unsigned char A) + { + return SColorRGBA(R, G, B, A); + } + inline SColor COLOR_ARGB(unsigned char A, unsigned char R, unsigned char G, unsigned char B) + { + return SColorRGBA(R, G, B, A); + } + inline SColor COLOR_ABGR(unsigned char A, unsigned char B, unsigned char G, unsigned char R) + { + return SColorRGBA(R, G, B, A); + } // // Convert tocolor value to SColor @@ -815,9 +849,8 @@ namespace SharedUtil CCriticalSection& m_CS; }; - // Macro for instantiating automatic critical section locking procedure - #define LOCK_SCOPE( cs ) \ - volatile CAutoCSLock _lock ( cs ) +// Macro for instantiating automatic critical section locking procedure +#define LOCK_SCOPE(cs) volatile CAutoCSLock _lock(cs) // // Expiry stuff @@ -969,16 +1002,16 @@ namespace SharedUtil void RemoveMultiValues(); SString Escape(const SString& strIn) const; SString Unescape(const SString& strIn) const; - void Set(const SString& strInCmd, const SString& strInValue); // Set a unique key string value - void Set(const SString& strInCmd, int iValue); // Set a unique key int value - void Insert(const SString& strInCmd, int iValue); // Insert a key int value - void Insert(const SString& strInCmd, const SString& strInValue); // Insert a key string value - bool Contains(const SString& strInCmd) const; // Test if key exists - bool Get(const SString& strInCmd, SString& strOut, const char* szDefault = "") const; // First result as string - SString Get(const SString& strInCmd) const; // First result as string - bool Get(const SString& strInCmd, std::vector& outList) const; // All results as strings - bool Get(const SString& strInCmd, int& iValue, int iDefault = 0) const; // First result as int - void GetKeys(std::vector& outList) const; // All keys + void Set(const SString& strInCmd, const SString& strInValue); // Set a unique key string value + void Set(const SString& strInCmd, int iValue); // Set a unique key int value + void Insert(const SString& strInCmd, int iValue); // Insert a key int value + void Insert(const SString& strInCmd, const SString& strInValue); // Insert a key string value + bool Contains(const SString& strInCmd) const; // Test if key exists + bool Get(const SString& strInCmd, SString& strOut, const char* szDefault = "") const; // First result as string + SString Get(const SString& strInCmd) const; // First result as string + bool Get(const SString& strInCmd, std::vector& outList) const; // All results as strings + bool Get(const SString& strInCmd, int& iValue, int iDefault = 0) const; // First result as int + void GetKeys(std::vector& outList) const; // All keys }; // Some templated accessors for CArgMap derived classes @@ -1149,16 +1182,16 @@ namespace SharedUtil }; template - class CMappedList : public CMappedContainer > + class CMappedList : public CMappedContainer> { }; template - class CMappedArray : public CMappedContainer > + class CMappedArray : public CMappedContainer> { public: - const T& operator[](int idx) const { return CMappedContainer >::m_List[idx]; } - T& operator[](int idx) { return CMappedContainer >::m_List[idx]; } + const T& operator[](int idx) const { return CMappedContainer>::m_List[idx]; } + T& operator[](int idx) { return CMappedContainer>::m_List[idx]; } }; // Returns true if the item is in the itemList @@ -1204,7 +1237,7 @@ namespace SharedUtil CIntrusiveListNode(T* pOuterItem) : m_pOuterItem(pOuterItem), m_pPrev(NULL), m_pNext(NULL) {} - T* m_pOuterItem; // Item this node is inside + T* m_pOuterItem; // Item this node is inside Node* m_pPrev; Node* m_pNext; }; @@ -1219,7 +1252,7 @@ namespace SharedUtil template class CIntrusiveList { - void operator=(const CIntrusiveList& other); // Copy will probably not work as expected + void operator=(const CIntrusiveList& other); // Copy will probably not work as expected // CIntrusiveList ( const CIntrusiveList& other ); // Default copy constructor is required by dense_hash for some reason public: @@ -1231,8 +1264,8 @@ namespace SharedUtil size_t m_Size; Node* m_pFirst; Node* m_pLast; - Node T::* m_pNodePtr; // Pointer to the CIntrusiveListNode member variable in T - std::vector m_ActiveIterators; // Keep track of iterators + Node T::* m_pNodePtr; // Pointer to the CIntrusiveListNode member variable in T + std::vector m_ActiveIterators; // Keep track of iterators public: // @@ -1290,9 +1323,9 @@ namespace SharedUtil // // Constructor // - CIntrusiveList(Node T::*pNodePtr) : m_pNodePtr(pNodePtr) + CIntrusiveList(Node T::* pNodePtr) : m_pNodePtr(pNodePtr) { - assert(m_pNodePtr); // This must be set upon construction + assert(m_pNodePtr); // This must be set upon construction m_Size = 0; m_pFirst = NULL; m_pLast = NULL; @@ -1321,7 +1354,7 @@ namespace SharedUtil Node* pNode = &(pItem->*m_pNodePtr); if (!pNode->m_pPrev && !pNode->m_pNext && m_pFirst != pNode) - return; // Not in list + return; // Not in list // Keep active iterators valid for (int i = m_ActiveIterators.size() - 1; i >= 0; i--) @@ -1418,9 +1451,9 @@ namespace SharedUtil // Allow use of std iterator names typedef Iterator iterator; - typedef Iterator const_iterator; // TODO + typedef Iterator const_iterator; // TODO typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; // TODO + typedef ReverseIterator const_reverse_iterator; // TODO }; /////////////////////////////////////////////////////////////// @@ -1430,7 +1463,7 @@ namespace SharedUtil // Uses the member variable pointer declared in the template // /////////////////////////////////////////////////////////////// - template T::*member_ptr> + template T::* member_ptr> class CIntrusiveListExt : public CIntrusiveList { public: @@ -1530,42 +1563,54 @@ namespace SharedUtil const SString& GetTypeName() const { return m_strTypeName; } - SString m_strTypeName; - SString m_strDefaultName; - T m_DefaultValue; - std::map m_ValueMap; - std::map m_NameMap; + SString m_strTypeName; + SString m_strDefaultName; + T m_DefaultValue; + std::map m_ValueMap; + std::map m_NameMap; }; - #define DECLARE_ENUM(T) \ - CEnumInfo* GetEnumInfo ( const T* ); \ - inline const SString& EnumToString ( const T& value ) { return GetEnumInfo ( (T*)0 )->FindName ( value ); }\ - inline bool StringToEnum ( const SString& strName, T& outResult ) { return GetEnumInfo ( (T*)0 )->FindValue ( strName, outResult ); }\ - inline const SString& GetEnumTypeName ( const T& ) { return GetEnumInfo ( (T*)0 )->GetTypeName (); }\ - inline bool EnumValueValid ( const T& value ) { return GetEnumInfo ( (T*)0 )->ValueValid ( value ); }\ - - #define IMPLEMENT_ENUM_BEGIN(T) \ - CEnumInfo* GetEnumInfo( const T* ) \ - { \ - using CEnumInfo = CEnumInfo; \ - static const CEnumInfo::SEnumItem items[] = { - - #define IMPLEMENT_ENUM_END(name) \ - IMPLEMENT_ENUM_END_DEFAULTS(name, static_cast().iValue)>>(0), "") +#define DECLARE_ENUM(T) \ + CEnumInfo* GetEnumInfo(const T*); \ + inline const SString& EnumToString(const T& value) \ + { \ + return GetEnumInfo((T*)0)->FindName(value); \ + } \ + inline bool StringToEnum(const SString& strName, T& outResult) \ + { \ + return GetEnumInfo((T*)0)->FindValue(strName, outResult); \ + } \ + inline const SString& GetEnumTypeName(const T&) \ + { \ + return GetEnumInfo((T*)0)->GetTypeName(); \ + } \ + inline bool EnumValueValid(const T& value) \ + { \ + return GetEnumInfo((T*)0)->ValueValid(value); \ + } - #define IMPLEMENT_ENUM_END_DEFAULTS(name,defvalue,defname) \ - }; \ - static CEnumInfo info(name, items, NUMELMS(items), defvalue, defname); \ - return &info; \ - } +#define IMPLEMENT_ENUM_BEGIN(T) \ + CEnumInfo* GetEnumInfo(const T*) \ + { \ + using CEnumInfo = CEnumInfo; \ + static const CEnumInfo::SEnumItem items[] = { +#define IMPLEMENT_ENUM_END(name) \ + IMPLEMENT_ENUM_END_DEFAULTS(name, static_cast().iValue)>>(0), "") + +#define IMPLEMENT_ENUM_END_DEFAULTS(name, defvalue, defname) \ + } \ + ; \ + static CEnumInfo info(name, items, NUMELMS(items), defvalue, defname); \ + return &info; \ + } - #define ADD_ENUM(value,name) {value, name}, - #define ADD_ENUM1(value) {value, #value}, +#define ADD_ENUM(value, name) {value, name}, +#define ADD_ENUM1(value) {value, #value}, - // enum class - #define DECLARE_ENUM_CLASS(T) DECLARE_ENUM(T) - #define IMPLEMENT_ENUM_CLASS_BEGIN(T) IMPLEMENT_ENUM_BEGIN(T) - #define IMPLEMENT_ENUM_CLASS_END(name) IMPLEMENT_ENUM_END(name) +// enum class +#define DECLARE_ENUM_CLASS(T) DECLARE_ENUM(T) +#define IMPLEMENT_ENUM_CLASS_BEGIN(T) IMPLEMENT_ENUM_BEGIN(T) +#define IMPLEMENT_ENUM_CLASS_END(name) IMPLEMENT_ENUM_END(name) // // Fast wildcard matching @@ -1690,7 +1735,10 @@ namespace SharedUtil } } - inline void ReadCommaSeparatedList(const SString& strInput, std::vector& outList) { return ReadTokenSeparatedList(",", strInput, outList); } + inline void ReadCommaSeparatedList(const SString& strInput, std::vector& outList) + { + return ReadTokenSeparatedList(",", strInput, outList); + } /////////////////////////////////////////////////////////////// // @@ -1780,7 +1828,7 @@ namespace SharedUtil class CRefCountable { int m_iRefCount; - CCriticalSection* m_pCS; // Use a pointer incase the static variable exists more than once + CCriticalSection* m_pCS; // Use a pointer incase the static variable exists more than once static CCriticalSection ms_CS; protected: @@ -1847,9 +1895,8 @@ namespace SharedUtil } }; - // Use this macro if the size of the initializer list is unknown - #define IMPLEMENT_FIXED_ARRAY( vartype, varname ) \ - SFixedArrayInit < vartype, NUMELMS( _##varname ) > varname ( _##varname, NUMELMS( _##varname ) ) +// Use this macro if the size of the initializer list is unknown +#define IMPLEMENT_FIXED_ARRAY(vartype, varname) SFixedArrayInit varname(_##varname, NUMELMS(_##varname)) // // Ranges of numbers. i.e. 100-4000, 5000-6999, 7000-7010 @@ -1859,7 +1906,7 @@ namespace SharedUtil public: void SetRange(uint uiStart, uint uiLength); void UnsetRange(uint uiStart, uint uiLength); - bool IsRangeSet(uint uiStart, uint uiLength); // Returns true if any part of the range already exists in the map + bool IsRangeSet(uint uiStart, uint uiLength); // Returns true if any part of the range already exists in the map protected: typedef std::map::iterator IterType; @@ -1877,7 +1924,7 @@ namespace SharedUtil class CRefedPointer : public CRefCountable { private: - T* pData; // Target + T* pData; // Target virtual ~CRefedPointer() { SAFE_DELETE(pData); } CRefedPointer(const CRefedPointer& other); @@ -1912,7 +1959,7 @@ namespace SharedUtil CAutoRefedPointer& operator=(const CAutoRefedPointer& other) { // Assignment operator - if (this != &other) // Avoid self assignment + if (this != &other) // Avoid self assignment { CRefedPointer* pOldPointer = pPointer; @@ -1931,7 +1978,7 @@ namespace SharedUtil const T* operator->() const { return pPointer->GetData(); } }; -}; // namespace SharedUtil +}; // namespace SharedUtil using namespace SharedUtil; diff --git a/Shared/sdk/SharedUtil.Misc.hpp b/Shared/sdk/SharedUtil.Misc.hpp index 098d48ee241..0527b08a4c8 100644 --- a/Shared/sdk/SharedUtil.Misc.hpp +++ b/Shared/sdk/SharedUtil.Misc.hpp @@ -79,9 +79,9 @@ namespace SharedUtil::Details #undef GetModuleBaseNameW #endif -#if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L - #include -#endif + #if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L + #include + #endif struct HKeyDeleter { @@ -126,26 +126,26 @@ namespace SharedUtil::Details private: HGLOBAL m_handle = nullptr; }; -} // namespace SharedUtil::Details +} // namespace SharedUtil::Details static void InitializeProcessBaseDir(SString& strProcessBaseDir) { try { - constexpr auto bufferSize = MAX_PATH * 2; - constexpr auto MAX_UNICODE_PATH = 32767; - auto coreFileName = std::array{}; + constexpr auto bufferSize = MAX_PATH * 2; + constexpr auto MAX_UNICODE_PATH = 32767; + auto coreFileName = std::array{}; // Get core.dll module handle to determine base directory // Try debug build first (core_d.dll), then release build (core.dll) - constexpr auto coreDllDebug = std::wstring_view{L"core_d.dll"}; + constexpr auto coreDllDebug = std::wstring_view{L"core_d.dll"}; constexpr auto coreDllRelease = std::wstring_view{L"core.dll"}; - auto hCoreModule = HMODULE{}; - auto bCoreModuleFound = bool{false}; -#ifdef MTA_DEBUG + auto hCoreModule = HMODULE{}; + auto bCoreModuleFound = bool{false}; + #ifdef MTA_DEBUG if (bCoreModuleFound = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, coreDllDebug.data(), &hCoreModule); !bCoreModuleFound) -#endif + #endif bCoreModuleFound = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, coreDllRelease.data(), &hCoreModule); // Fallback: Use current module if core.dll isn't loaded yet @@ -157,8 +157,7 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) if (hCoreModule) { - if (DWORD lengthCore = GetModuleFileNameW(hCoreModule, coreFileName.data(), static_cast(coreFileName.size())); - lengthCore > 0) + if (DWORD lengthCore = GetModuleFileNameW(hCoreModule, coreFileName.data(), static_cast(coreFileName.size())); lengthCore > 0) { // Use std::wstring for flexible buffer management auto corePathBuffer = std::wstring{coreFileName.data(), static_cast(lengthCore)}; @@ -167,7 +166,7 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) if (const auto bufferTooSmall = (static_cast(lengthCore) == coreFileName.size()); bufferTooSmall) { corePathBuffer.resize(MAX_UNICODE_PATH); - + if (lengthCore = GetModuleFileNameW(hCoreModule, corePathBuffer.data(), static_cast(corePathBuffer.size())); lengthCore > 0 && static_cast(lengthCore) < corePathBuffer.size()) { @@ -180,27 +179,28 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) } auto fullPath = std::array{}; - + if (DWORD lengthFull = GetFullPathNameW(corePathBuffer.c_str(), static_cast(fullPath.size()), fullPath.data(), nullptr); lengthFull > 0) { // Process path and extract base directory // The directory above /MTA/ is always the base directory - const auto processPath = [&strProcessBaseDir](const std::wstring_view fullPathStr) { + const auto processPath = [&strProcessBaseDir](const std::wstring_view fullPathStr) + { if (const auto lastSeparator = fullPathStr.find_last_of(L"\\/"); lastSeparator != std::wstring_view::npos) { const auto moduleDir = fullPathStr.substr(0, lastSeparator); - auto currentPath = std::filesystem::path(moduleDir); - + auto currentPath = std::filesystem::path(moduleDir); + // Walk up to find MTA/ folder // Stop at first MTA folder found - it's guaranteed to be the correct one // Check current directory and up to 2 parent levels for (auto level = 0; level < 3; ++level) { auto folderName = currentPath.filename().wstring(); - + // Convert to lowercase for case-insensitive comparison std::transform(folderName.begin(), folderName.end(), folderName.begin(), ::towlower); - + if (folderName == L"mta") { // Found MTA folder - base directory is its parent @@ -211,7 +211,7 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) } return; // Always stop at first MTA folder found } - + // Move up one level if (currentPath.has_parent_path()) currentPath = currentPath.parent_path(); @@ -226,7 +226,7 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) { if (static_cast(lengthFull) > MAX_UNICODE_PATH) return; // Path too long, validation failed - + fullPathBuffer.resize(static_cast(lengthFull)); if (lengthFull = GetFullPathNameW(corePathBuffer.c_str(), static_cast(fullPathBuffer.size()), fullPathBuffer.data(), nullptr); lengthFull > 0 && static_cast(lengthFull) < fullPathBuffer.size()) @@ -250,7 +250,7 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) [[nodiscard]] const SString& SharedUtil::GetMTAProcessBaseDir() { static auto strProcessBaseDir = SString{}; - static auto initFlag = std::once_flag{}; + static auto initFlag = std::once_flag{}; std::call_once(initFlag, InitializeProcessBaseDir, std::ref(strProcessBaseDir)); @@ -260,17 +260,17 @@ static void InitializeProcessBaseDir(SString& strProcessBaseDir) #else #include #ifndef _GNU_SOURCE - # define _GNU_SOURCE /* See feature_test_macros(7) */ + #define _GNU_SOURCE /* See feature_test_macros(7) */ #endif #include #include #include #ifndef RUSAGE_THREAD - #define RUSAGE_THREAD 1 /* only the calling thread */ + #define RUSAGE_THREAD 1 /* only the calling thread */ #endif #endif -#if __cplusplus >= 201703L // C++17 +#if __cplusplus >= 201703L // C++17 #include #endif @@ -295,15 +295,15 @@ CDuplicateLineFilter ms_ReportLineFilter; #ifdef MTA_CLIENT -#define PRODUCT_REGISTRY_PATH "Software\\Multi Theft Auto: San Andreas All" // HKLM -#define PRODUCT_COMMON_DATA_DIR "MTA San Andreas All" // C:\ProgramData -#define TROUBLE_URL1 "https://help.multitheftauto.com/sa/trouble/?v=_VERSION_&id=_ID_&tr=_TROUBLE_" + #define PRODUCT_REGISTRY_PATH "Software\\Multi Theft Auto: San Andreas All" // HKLM + #define PRODUCT_COMMON_DATA_DIR "MTA San Andreas All" // C:\ProgramData + #define TROUBLE_URL1 "https://help.multitheftauto.com/sa/trouble/?v=_VERSION_&id=_ID_&tr=_TROUBLE_" -// -// Output a UTF8 encoded messagebox -// Used in the Win32 Client only -// -#ifdef _WINDOWS_ //Only for modules that use windows.h + // + // Output a UTF8 encoded messagebox + // Used in the Win32 Client only + // + #ifdef _WINDOWS_ // Only for modules that use windows.h int SharedUtil::MessageBoxUTF8(HWND hWnd, SString lpText, SString lpCaption, UINT uType) { // Default to warning icon @@ -316,7 +316,7 @@ int SharedUtil::MessageBoxUTF8(HWND hWnd, SString lpText, SString lpCaption, UIN WString strCaption = MbUTF8ToUTF16(lpCaption); return MessageBoxW(hWnd, strText.c_str(), strCaption.c_str(), uType); } -#endif + #endif // // Return full path and filename of parent exe @@ -337,7 +337,7 @@ SString SharedUtil::GetParentProcessPathFilename(int pid) WCHAR szModuleName[MAX_PATH * 2] = {0}; DWORD dwSize = GetModuleFileNameExW(hProcess, nullptr, szModuleName, NUMELMS(szModuleName) - 1); CloseHandle(hProcess); - + if (dwSize > 0) { // Ensure null termination @@ -408,25 +408,28 @@ bool SharedUtil::IsGTAProcess() bool SharedUtil::IsReadablePointer(const void* ptr, size_t size) { // Guard against null or overflow before touching platform APIs - if (!ptr || size == 0) return false; + if (!ptr || size == 0) + return false; - const uintptr_t start = reinterpret_cast(ptr); + const uintptr_t start = reinterpret_cast(ptr); constexpr uintptr_t maxAddress = std::numeric_limits::max(); - if (size > maxAddress - start) return false; + if (size > maxAddress - start) + return false; const uintptr_t end = start + size; -#ifdef SHAREDUTIL_PLATFORM_WINDOWS + #ifdef SHAREDUTIL_PLATFORM_WINDOWS constexpr DWORD readableMask = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; for (uintptr_t current = start; current < end;) { MEMORY_BASIC_INFORMATION mbi{}; - if (VirtualQuery(reinterpret_cast(current), &mbi, sizeof(mbi)) == 0) return false; + if (VirtualQuery(reinterpret_cast(current), &mbi, sizeof(mbi)) == 0) + return false; const uintptr_t regionStart = reinterpret_cast(mbi.BaseAddress); const uintptr_t regionSize = static_cast(mbi.RegionSize); const uintptr_t regionEnd = regionStart + regionSize; - const DWORD protection = mbi.Protect; + const DWORD protection = mbi.Protect; if (regionSize == 0 || current < regionStart || regionStart > maxAddress - regionSize || regionEnd <= current || mbi.State != MEM_COMMIT || (protection & PAGE_GUARD) || (protection & readableMask) == 0) return false; @@ -435,16 +438,17 @@ bool SharedUtil::IsReadablePointer(const void* ptr, size_t size) } return true; -#elif defined(LINUX_x86) || defined(LINUX_x64) || defined(LINUX_arm) || defined(LINUX_arm64) + #elif defined(LINUX_x86) || defined(LINUX_x64) || defined(LINUX_arm) || defined(LINUX_arm64) static_assert(sizeof(uintptr_t) <= sizeof(unsigned long long), "Unexpected uintptr_t size"); std::ifstream maps("/proc/self/maps"); if (!maps.is_open()) return false; - const auto parseAddress = [maxAddress](const std::string& token, uintptr_t& out) -> bool { + const auto parseAddress = [maxAddress](const std::string& token, uintptr_t& out) -> bool + { errno = 0; - char* endPtr = nullptr; + char* endPtr = nullptr; unsigned long long value = std::strtoull(token.c_str(), &endPtr, 16); if (errno != 0 || endPtr == token.c_str() || *endPtr != '\0' || value > maxAddress) return false; @@ -453,50 +457,59 @@ bool SharedUtil::IsReadablePointer(const void* ptr, size_t size) }; uintptr_t coverage = start; - bool coveringRange = false; + bool coveringRange = false; for (std::string line; std::getline(maps, line);) { - if (line.empty()) continue; + if (line.empty()) + continue; std::istringstream iss(line); - std::string range, perms; - if (!(iss >> range >> perms)) continue; + std::string range, perms; + if (!(iss >> range >> perms)) + continue; const size_t dashPos = range.find('-'); - if (dashPos == std::string::npos) continue; - uintptr_t regionStart = 0; - uintptr_t regionEnd = 0; - if (!parseAddress(range.substr(0, dashPos), regionStart) || !parseAddress(range.substr(dashPos + 1), regionEnd)) continue; - if (regionEnd <= regionStart || regionEnd <= coverage) continue; + if (dashPos == std::string::npos) + continue; + uintptr_t regionStart = 0; + uintptr_t regionEnd = 0; + if (!parseAddress(range.substr(0, dashPos), regionStart) || !parseAddress(range.substr(dashPos + 1), regionEnd)) + continue; + if (regionEnd <= regionStart || regionEnd <= coverage) + continue; if (coveringRange) { - if (regionStart > coverage) return false; + if (regionStart > coverage) + return false; } else if (regionStart > coverage || coverage >= regionEnd) { continue; } - else coveringRange = true; + else + coveringRange = true; - if (perms.empty() || perms[0] != 'r') return false; + if (perms.empty() || perms[0] != 'r') + return false; coverage = regionEnd; - if (coverage >= end) return true; + if (coverage >= end) + return true; } return false; -#elif defined(APPLE_x64) || defined(APPLE_arm64) - mach_vm_address_t queryAddress = static_cast(start); - const mach_vm_address_t targetEnd = static_cast(end); - constexpr mach_vm_address_t maxAddressMac = std::numeric_limits::max(); + #elif defined(APPLE_x64) || defined(APPLE_arm64) + mach_vm_address_t queryAddress = static_cast(start); + const mach_vm_address_t targetEnd = static_cast(end); + constexpr mach_vm_address_t maxAddressMac = std::numeric_limits::max(); vm_region_basic_info_data_64_t info; - mach_msg_type_number_t infoCount = VM_REGION_BASIC_INFO_COUNT_64; - mach_port_t objectName = MACH_PORT_NULL; + mach_msg_type_number_t infoCount = VM_REGION_BASIC_INFO_COUNT_64; + mach_port_t objectName = MACH_PORT_NULL; while (queryAddress < targetEnd) { mach_vm_size_t regionSize = 0; infoCount = VM_REGION_BASIC_INFO_COUNT_64; mach_vm_address_t regionAddress = queryAddress; - kern_return_t kr = mach_vm_region(mach_task_self(), ®ionAddress, ®ionSize, VM_REGION_BASIC_INFO_64, - reinterpret_cast(&info), &infoCount, &objectName); + kern_return_t kr = mach_vm_region(mach_task_self(), ®ionAddress, ®ionSize, VM_REGION_BASIC_INFO_64, reinterpret_cast(&info), + &infoCount, &objectName); if (objectName != MACH_PORT_NULL) { mach_port_deallocate(mach_task_self(), objectName); @@ -515,9 +528,9 @@ bool SharedUtil::IsReadablePointer(const void* ptr, size_t size) } return true; -#else + #else return false; -#endif + #endif } // @@ -547,7 +560,7 @@ static void WriteRegistryStringValue(HKEY hkRoot, const char* szSubKey, const ch // namespace { - constexpr DWORD kMaxRegistryValueBytes = 1024 * 1024; // Cap to avoid runaway allocations + constexpr DWORD kMaxRegistryValueBytes = 1024 * 1024; // Cap to avoid runaway allocations constexpr DWORD kMinStringAlloc = sizeof(wchar_t); constexpr DWORD kMinBinaryAlloc = static_cast(sizeof(unsigned long long)); @@ -564,14 +577,14 @@ namespace size_t ComputeWideBufferCapacity(DWORD bytes) { const size_t rounded = static_cast(bytes) + (sizeof(wchar_t) - 1u); - return (rounded / sizeof(wchar_t)) + 1u; // +1 for null terminator + return (rounded / sizeof(wchar_t)) + 1u; // +1 for null terminator } WString CollapseMultiSz(const wchar_t* data, size_t wcharCount) { const wchar_t* current = data; const wchar_t* end = current + wcharCount; - WString combined; + WString combined; while (current < end && *current != L'\0') { if (!combined.empty()) @@ -613,7 +626,7 @@ namespace return SString(); static const char hexDigits[] = "0123456789ABCDEF"; - std::string hex; + std::string hex; hex.reserve(static_cast(size) * 2u); for (DWORD i = 0; i < size; ++i) { @@ -628,7 +641,7 @@ namespace bool TryReadStringValue(HKEY key, const wchar_t* valueName, DWORD& dwType, DWORD initialSize, SString& outValue, int& status) { - DWORD allocSize = std::max(initialSize, kMinStringAlloc); + DWORD allocSize = std::max(initialSize, kMinStringAlloc); std::vector buffer(ComputeWideBufferCapacity(allocSize), L'\0'); while (true) @@ -689,7 +702,7 @@ namespace bool TryReadBinaryValue(HKEY key, const wchar_t* valueName, DWORD& dwType, DWORD initialSize, SString& outValue, int& status) { - DWORD allocSize = std::max(initialSize, kMinBinaryAlloc); + DWORD allocSize = std::max(initialSize, kMinBinaryAlloc); std::vector buffer(static_cast(allocSize), 0u); while (true) @@ -727,7 +740,7 @@ namespace { case REG_DWORD: { - DWORD value = 0; + DWORD value = 0; const DWORD copyBytes = std::min(dwTempSize, sizeof(DWORD)); for (DWORD i = 0; i < copyBytes; ++i) value |= static_cast(buffer[i]) << (8u * i); @@ -736,7 +749,7 @@ namespace } case REG_DWORD_BIG_ENDIAN: { - DWORD value = 0; + DWORD value = 0; const DWORD copyBytes = std::min(dwTempSize, sizeof(DWORD)); for (DWORD i = 0; i < copyBytes; ++i) { @@ -749,7 +762,7 @@ namespace case REG_QWORD: { unsigned long long value = 0ull; - const DWORD copyBytes = std::min(dwTempSize, static_cast(sizeof(value))); + const DWORD copyBytes = std::min(dwTempSize, static_cast(sizeof(value))); for (DWORD i = 0; i < copyBytes; ++i) value |= static_cast(buffer[i]) << (8ull * i); outValue.Format("%llu", static_cast(value)); @@ -791,11 +804,10 @@ namespace return false; } - int localStatus = 0; + int localStatus = 0; const bool isStringType = (dwType == REG_SZ || dwType == REG_EXPAND_SZ || dwType == REG_MULTI_SZ); - const bool success = isStringType - ? TryReadStringValue(key, valueName, dwType, dwBufferSize, outValue, localStatus) - : TryReadBinaryValue(key, valueName, dwType, dwBufferSize, outValue, localStatus); + const bool success = isStringType ? TryReadStringValue(key, valueName, dwType, dwBufferSize, outValue, localStatus) + : TryReadBinaryValue(key, valueName, dwType, dwBufferSize, outValue, localStatus); if (localStatus != 0) status = localStatus; @@ -813,7 +825,7 @@ static SString ReadRegistryStringValue(HKEY hkRoot, const char* szSubKey, const const char* szSafeSubKey = szSubKey ? szSubKey : ""; const char* szSafeValue = szValue ? szValue : ""; - WString wstrSubKey; + WString wstrSubKey; const wchar_t* pSubKey = L""; if (szSafeSubKey[0] != '\0') { @@ -830,20 +842,20 @@ static SString ReadRegistryStringValue(HKEY hkRoot, const char* szSubKey, const pValueName = wstrValue.c_str(); } - constexpr size_t kAccessMaskSlots = 3u; + constexpr size_t kAccessMaskSlots = 3u; std::array accessMasks{}; - size_t maskCount = 0; -#ifdef KEY_WOW64_64KEY + size_t maskCount = 0; + #ifdef KEY_WOW64_64KEY accessMasks[maskCount++] = KEY_READ | KEY_WOW64_64KEY; -#endif -#ifdef KEY_WOW64_32KEY + #endif + #ifdef KEY_WOW64_32KEY accessMasks[maskCount++] = KEY_READ | KEY_WOW64_32KEY; -#endif + #endif accessMasks[maskCount++] = KEY_READ; for (size_t maskIndex = 0; maskIndex < maskCount && !success; ++maskIndex) { - HKEY hkTemp = nullptr; + HKEY hkTemp = nullptr; const LONG openResult = RegOpenKeyExW(hkRoot, pSubKey, 0, accessMasks[maskIndex], &hkTemp); if (openResult != ERROR_SUCCESS) { @@ -1024,12 +1036,11 @@ SString SharedUtil::GetPostUpdateConnect() time_t timeThen = 0; if (!strTimeString.empty()) { - char* endptr; + char* endptr; long long result = strtoll(strTimeString.c_str(), &endptr, 10); - + // Check for valid conversion - if (endptr != strTimeString.c_str() && *endptr == '\0' && - result >= 0 && result <= LLONG_MAX) + if (endptr != strTimeString.c_str() && *endptr == '\0' && result >= 0 && result <= LLONG_MAX) { timeThen = static_cast(result); } @@ -1081,15 +1092,15 @@ int SharedUtil::GetApplicationSettingInt(const SString& strPath, const SString& return 0; char* endptr; - long result = strtol(strValue.c_str(), &endptr, 10); - + long result = strtol(strValue.c_str(), &endptr, 10); + // Check for conversion errors if (endptr == strValue.c_str() || *endptr != '\0') return 0; // Invalid conversion if (result > INT_MAX || result < INT_MIN) return 0; - + return static_cast(result); } @@ -1544,8 +1555,7 @@ void SharedUtil::AddReportLog(uint uiId, const SString& strText, uint uiAmountLi MakeSureDirExists(strPathFilename); SString strMessage; - strMessage.Format("%u: %s %s [%s] - ", uiId, GetTimeString(true, false).c_str(), GetReportLogHeaderText().c_str(), - GetReportLogProcessTag().c_str()); + strMessage.Format("%u: %s %s [%s] - ", uiId, GetTimeString(true, false).c_str(), GetReportLogHeaderText().c_str(), GetReportLogProcessTag().c_str()); strMessage += strText; strMessage += "\n"; FileAppend(strPathFilename, &strMessage.at(0), strMessage.length()); @@ -1569,11 +1579,9 @@ void SharedUtil::AddExceptionReportLog(uint uiId, const char* szExceptionName, c GetSystemTime(&s); // Use _snprintf_s to prevent buffer overflow and ensure null termination - int result = _snprintf_s(szOutput, TOTAL_BUFFER_SIZE, _TRUNCATE, - "%u: %04hu-%02hu-%02hu %02hu:%02hu:%02hu - Caught %.*s exception: %.*s\n", - uiId, s.wYear, s.wMonth, s.wDay, s.wHour, s.wMinute, s.wSecond, - (int)MAX_EXCEPTION_NAME_SIZE, szExceptionName ? szExceptionName : "Unknown", - (int)MAX_EXCEPTION_TEXT_SIZE, szExceptionText ? szExceptionText : "" ); + int result = _snprintf_s(szOutput, TOTAL_BUFFER_SIZE, _TRUNCATE, "%u: %04hu-%02hu-%02hu %02hu:%02hu:%02hu - Caught %.*s exception: %.*s\n", uiId, s.wYear, + s.wMonth, s.wDay, s.wHour, s.wMinute, s.wSecond, (int)MAX_EXCEPTION_NAME_SIZE, szExceptionName ? szExceptionName : "Unknown", + (int)MAX_EXCEPTION_TEXT_SIZE, szExceptionText ? szExceptionText : ""); OutputDebugString("[ReportLog] "); OutputDebugString(&szOutput[0]); @@ -1660,9 +1668,9 @@ void WriteEvent(const char* szType, const SString& strText) SString strPathFilename = CalcMTASAPath(PathJoin("mta", "logs", "logfile.txt")); SString strMessage("%s - %s %s", *GetLocalTimeString(), szType, *strText); FileAppend(strPathFilename, strMessage + "\n"); -#ifdef MTA_DEBUG + #ifdef MTA_DEBUG OutputDebugLine(strMessage); -#endif + #endif } void SharedUtil::WriteDebugEvent(const SString& strText) @@ -1800,7 +1808,7 @@ bool SharedUtil::ShellExecuteNonBlocking(const SString& strAction, const SString #endif // MTA_CLIENT #ifdef SHAREDUTIL_PLATFORM_WINDOWS -#define _WIN32_WINNT_WIN8 0x0602 + #define _WIN32_WINNT_WIN8 0x0602 /////////////////////////////////////////////////////////////////////////// // // SharedUtil::IsWindowsVersionOrGreater @@ -1987,14 +1995,14 @@ static LONG SafeNtQueryInformationThread(HANDLE ThreadHandle, INT ThreadInformat if (lookup.module) lookup.function = static_cast(static_cast(GetProcAddress(lookup.module, "NtQueryInformationThread"))); - else - return 0xC0000135L; // STATUS_DLL_NOT_FOUND + else + return 0xC0000135L; // STATUS_DLL_NOT_FOUND } if (lookup.function) return lookup.function(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength, ReturnLength); else - return 0xC00000BBL; // STATUS_NOT_SUPPORTED + return 0xC00000BBL; // STATUS_NOT_SUPPORTED } bool SharedUtil::QueryThreadEntryPointAddress(void* thread, DWORD* entryPointAddress) @@ -2116,7 +2124,7 @@ int SharedUtil::GetBuildAge() return (int)(time(NULL) - mktime(&when)) / (60 * 60 * 24); } -#if defined(MTA_DM_EXPIRE_DAYS) + #if defined(MTA_DM_EXPIRE_DAYS) int SharedUtil::GetDaysUntilExpire() { tm when; @@ -2127,7 +2135,7 @@ int SharedUtil::GetDaysUntilExpire() return (int)(mktime(&when) - time(NULL)) / (60 * 60 * 24); } -#endif + #endif #endif // @@ -2249,15 +2257,15 @@ char* SharedUtil::Trim(char* szText) return static_cast(memmove(szOriginal, szText, uiLen + 1)); } -#if __cplusplus >= 201703L // C++17 +#if __cplusplus >= 201703L // C++17 std::string SharedUtil::UTF8FilePath(const std::filesystem::path& input) { -#ifdef __cpp_lib_char8_t + #ifdef __cpp_lib_char8_t std::u8string raw = input.u8string(); - return std::string{ std::begin(raw), std::end(raw) }; -#else + return std::string{std::begin(raw), std::end(raw)}; + #else return input.u8string(); -#endif + #endif } #endif @@ -2296,16 +2304,16 @@ std::wstring SharedUtil::ANSIToUTF16(const SString& input) { if (input.empty()) return L""; - + size_t len = mbstowcs(NULL, input.c_str(), input.length()); if (len == (size_t)-1) return L"?"; - + std::vector wcsOutput(len + 1); // Use vector for automatic cleanup - size_t result = mbstowcs(wcsOutput.data(), input.c_str(), len); + size_t result = mbstowcs(wcsOutput.data(), input.c_str(), len); if (result == (size_t)-1 || result != len) return L"?"; - + wcsOutput[len] = 0; // Null terminate the string return std::wstring(wcsOutput.data()); } @@ -2326,14 +2334,14 @@ bool SharedUtil::IsLuaCompiledScript(const void* pData, uint uiLength) pCharData += 3; uiLength -= 3; } - return (uiLength > 0 && pCharData[0] == 0x1B); // Do the same check as what the Lua parser does + return (uiLength > 0 && pCharData[0] == 0x1B); // Do the same check as what the Lua parser does } // Check for obfuscated script bool SharedUtil::IsLuaObfuscatedScript(const void* pData, uint uiLength) { const uchar* pCharData = (const uchar*)pData; - return (uiLength > 0 && pCharData[0] == 0x1C); // Look for our special marker + return (uiLength > 0 && pCharData[0] == 0x1C); // Look for our special marker } // @@ -2426,9 +2434,15 @@ namespace SharedUtil m_cEscapeCharacter = '#'; } - void CArgMap::SetEscapeCharacter(char cEscapeCharacter) { m_cEscapeCharacter = cEscapeCharacter; } + void CArgMap::SetEscapeCharacter(char cEscapeCharacter) + { + m_cEscapeCharacter = cEscapeCharacter; + } - void CArgMap::Merge(const CArgMap& other, bool bAllowMultiValues) { MergeFromString(other.ToString(), bAllowMultiValues); } + void CArgMap::Merge(const CArgMap& other, bool bAllowMultiValues) + { + MergeFromString(other.ToString(), bAllowMultiValues); + } void CArgMap::SetFromString(const SString& strLine, bool bAllowMultiValues) { @@ -2446,7 +2460,7 @@ namespace SharedUtil parts[i].Split(m_strArgSep, &strCmd, &strArg); if (!bAllowMultiValues) m_Map.erase(strCmd); - if (strCmd.length()) // Key can not be empty + if (strCmd.length()) // Key can not be empty MapInsert(m_Map, strCmd, strArg); } } @@ -2481,9 +2495,15 @@ namespace SharedUtil SetFromString(ToString(), false); } - SString CArgMap::Escape(const SString& strIn) const { return EscapeString(strIn, m_strDisallowedChars, m_cEscapeCharacter); } + SString CArgMap::Escape(const SString& strIn) const + { + return EscapeString(strIn, m_strDisallowedChars, m_cEscapeCharacter); + } - SString CArgMap::Unescape(const SString& strIn) const { return UnescapeString(strIn, m_cEscapeCharacter); } + SString CArgMap::Unescape(const SString& strIn) const + { + return UnescapeString(strIn, m_cEscapeCharacter); + } // Set a unique key string value void CArgMap::Set(const SString& strCmd, const SString& strValue) @@ -2500,17 +2520,23 @@ namespace SharedUtil } // Insert a key int value - void CArgMap::Insert(const SString& strCmd, int iValue) { Insert(strCmd, SString("%d", iValue)); } + void CArgMap::Insert(const SString& strCmd, int iValue) + { + Insert(strCmd, SString("%d", iValue)); + } // Insert a key string value void CArgMap::Insert(const SString& strCmd, const SString& strValue) { - if (strCmd.length()) // Key can not be empty + if (strCmd.length()) // Key can not be empty MapInsert(m_Map, Escape(strCmd), Escape(strValue)); } // Test if key exists - bool CArgMap::Contains(const SString& strCmd) const { return MapFind(m_Map, Escape(strCmd)) != NULL; } + bool CArgMap::Contains(const SString& strCmd) const + { + return MapFind(m_Map, Escape(strCmd)) != NULL; + } // First result as string bool CArgMap::Get(const SString& strCmd, SString& strOut, const char* szDefault) const @@ -2612,7 +2638,6 @@ namespace SharedUtil }; static ProcessorNumberLookup lookup = {}; - if (!lookup.once) { @@ -2911,7 +2936,7 @@ namespace SharedUtil return false; } -} // namespace SharedUtil +} // namespace SharedUtil // // For checking MTA library module versions diff --git a/Shared/sdk/SharedUtil.Profiling.h b/Shared/sdk/SharedUtil.Profiling.h index 8b1ad9af4b9..fac23671392 100644 --- a/Shared/sdk/SharedUtil.Profiling.h +++ b/Shared/sdk/SharedUtil.Profiling.h @@ -74,25 +74,24 @@ namespace SharedUtil // Global CStatEvents instance extern class CStatEvents g_StatEvents; - // Macros for clocking areas - #define CLOCK(section,name) g_StatEvents.Add( section, name, STATS_CLOCK ) - #define UNCLOCK(section,name) g_StatEvents.Add( section, name, STATS_UNCLOCK ) - - // Macro for clocking enclosed code - #define CLOCK_CALL(section,code) \ - { \ - CLOCK( section, #code ); \ - code; \ - UNCLOCK( section, #code ); \ - } +// Macros for clocking areas +#define CLOCK(section, name) g_StatEvents.Add(section, name, STATS_CLOCK) +#define UNCLOCK(section, name) g_StatEvents.Add(section, name, STATS_UNCLOCK) + +// Macro for clocking enclosed code +#define CLOCK_CALL(section, code) \ + { \ + CLOCK(section, #code); \ + code; \ + UNCLOCK(section, #code); \ + } - // Macros using a common section name - #define CLOCK_SET_SECTION(tag) \ - const char* szClockSectionTag = tag +// Macros using a common section name +#define CLOCK_SET_SECTION(tag) const char* szClockSectionTag = tag - #define CLOCK1(name) CLOCK( szClockSectionTag, name ) - #define UNCLOCK1(name) UNCLOCK( szClockSectionTag, name) - #define CLOCK_CALL1(code) CLOCK_CALL( szClockSectionTag, code ) +#define CLOCK1(name) CLOCK(szClockSectionTag, name) +#define UNCLOCK1(name) UNCLOCK(szClockSectionTag, name) +#define CLOCK_CALL1(code) CLOCK_CALL(szClockSectionTag, code) // // Performance stat resulting @@ -145,4 +144,4 @@ namespace SharedUtil float m_fNextMaxClearTime; }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Profiling.hpp b/Shared/sdk/SharedUtil.Profiling.hpp index 9d2bf66b689..a0586fa5510 100644 --- a/Shared/sdk/SharedUtil.Profiling.hpp +++ b/Shared/sdk/SharedUtil.Profiling.hpp @@ -63,14 +63,14 @@ namespace SharedUtil public: }; - /////////////////////////////////////////////////////////////// - // - // GetNextUnclockIndex - // - // Search forward from supplied index looking for an (unpaired) unclock marker - // - /////////////////////////////////////////////////////////////// - #define INVALID_INDEX -1 +/////////////////////////////////////////////////////////////// +// +// GetNextUnclockIndex +// +// Search forward from supplied index looking for an (unpaired) unclock marker +// +/////////////////////////////////////////////////////////////// +#define INVALID_INDEX -1 int GetNextUnclockIndex(std::vector& eventList, int i) { if (i < 0 || i >= (int)eventList.size()) @@ -105,7 +105,7 @@ namespace SharedUtil { // check has even number of events if (eventList.size() & 1) - return; // Error + return; // Error // remove recursive Clock/Unclocks for (int i = 0; i < (int)eventList.size() - 1; i += 2) @@ -114,16 +114,16 @@ namespace SharedUtil SFrameEvent& endEvent = eventList[i + 1]; if (startEvent.type == STATS_CLOCK && endEvent.type == STATS_UNCLOCK) - continue; // Fast simple case of unclock following a clock + continue; // Fast simple case of unclock following a clock if (startEvent.type != STATS_CLOCK) - return; // Error + return; // Error int iClockIdx = i; int iUnclockIdx = GetNextUnclockIndex(eventList, iClockIdx + 1); if (iUnclockIdx == INVALID_INDEX) - return; // Error + return; // Error assert(iUnclockIdx != iClockIdx + 1); { @@ -176,7 +176,10 @@ namespace SharedUtil // // //////////////////////////////////////////////// - CStatEvents::CStatEvents() : m_bEnabled(false), m_ItemBuffer(0), m_BufferPos(0), m_BufferPosMax(0), m_BufferPosMaxUsing(0) { ClearBuffer(true); } + CStatEvents::CStatEvents() : m_bEnabled(false), m_ItemBuffer(0), m_BufferPos(0), m_BufferPosMax(0), m_BufferPosMaxUsing(0) + { + ClearBuffer(true); + } /////////////////////////////////////////////////////////////// // @@ -311,7 +314,7 @@ namespace SharedUtil continue; } - float StartMs = (StartEvent.timeStamp - baseTimeStamp) * (1 / 1000.0f); // TIMEUS to ms + float StartMs = (StartEvent.timeStamp - baseTimeStamp) * (1 / 1000.0f); // TIMEUS to ms float EndMs = (EndEvent.timeStamp - baseTimeStamp) * (1 / 1000.0f); float LengthMs = EndMs - StartMs; fTotalMs += LengthMs; @@ -347,7 +350,10 @@ namespace SharedUtil // // /////////////////////////////////////////////////////////////// - CStatResults::CStatResults() { m_fNextMaxClearTime = 0; } + CStatResults::CStatResults() + { + m_fNextMaxClearTime = 0; + } /////////////////////////////////////////////////////////////// // @@ -443,4 +449,4 @@ namespace SharedUtil UNCLOCK("Profiling", "Compile stats"); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.SysInfo.h b/Shared/sdk/SharedUtil.SysInfo.h index 76e6fa2ab0c..d6580b555bb 100644 --- a/Shared/sdk/SharedUtil.SysInfo.h +++ b/Shared/sdk/SharedUtil.SysInfo.h @@ -11,10 +11,10 @@ #pragma once #ifdef WIN32 -#include -#include "SString.h" -#include -#include "WinVer.h" + #include + #include "SString.h" + #include + #include "WinVer.h" namespace SharedUtil { @@ -45,6 +45,6 @@ namespace SharedUtil bool IsHotFixInstalled(const SString& strHotFixId); bool GetLibVersionInfo(const SString& strLibName, SLibVersionInfo* pOutLibVersionInfo); bool Is64BitOS(); -} // namespace SharedUtil +} // namespace SharedUtil #endif diff --git a/Shared/sdk/SharedUtil.SysInfo.hpp b/Shared/sdk/SharedUtil.SysInfo.hpp index e79751ca4f1..b32f40920f6 100644 --- a/Shared/sdk/SharedUtil.SysInfo.hpp +++ b/Shared/sdk/SharedUtil.SysInfo.hpp @@ -11,12 +11,12 @@ #ifdef MTA_CLIENT -#define _WIN32_DCOM -#include -#include + #define _WIN32_DCOM + #include + #include -# pragma comment(lib, "wbemuuid.lib") -#pragma comment(lib, "Version.lib") + #pragma comment(lib, "wbemuuid.lib") + #pragma comment(lib, "Version.lib") namespace { @@ -45,7 +45,7 @@ namespace /* [in] */ long lTimeout, /* [in] */ ULONG uCount, /* [length_is][size_is][out] */ __RPC__out_ecount_part(uCount, *puReturned) IWbemClassObject** apObjects, - /* [out] */ __RPC__out ULONG* puReturned) + /* [out] */ __RPC__out ULONG* puReturned) { __try { @@ -57,7 +57,7 @@ namespace return STATUS_ACCESS_VIOLATION; } } -} // namespace +} // namespace ///////////////////////////////////////////////////////////////////// // @@ -92,14 +92,14 @@ bool SharedUtil::QueryWMI(SQueryWMIResult& outResult, const SString& strQuery, c // parameter of CoInitializeSecurity ------------------------ hres = CoInitializeSecurity(NULL, - -1, // COM authentication - NULL, // Authentication services - NULL, // Reserved - RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication - RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation - NULL, // Authentication info - EOAC_NONE, // Additional capabilities - NULL // Reserved + -1, // COM authentication + NULL, // Authentication services + NULL, // Reserved + RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication + RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation + NULL, // Authentication info + EOAC_NONE, // Additional capabilities + NULL // Reserved ); // Error here can be non fatal @@ -131,14 +131,14 @@ bool SharedUtil::QueryWMI(SQueryWMIResult& outResult, const SString& strQuery, c // the current user and obtain pointer pSvc // to make IWbemServices calls. hres = CallConnectServer(pLoc, - _bstr_t(SStringX("ROOT\\") + strNamespace), // Object path of WMI namespace - NULL, // User name. NULL = current user - NULL, // User password. NULL = current - 0, // Locale. NULL indicates current - NULL, // Security flags. - 0, // Authority (e.g. Kerberos) - 0, // Context object - &pSvc // pointer to IWbemServices proxy + _bstr_t(SStringX("ROOT\\") + strNamespace), // Object path of WMI namespace + NULL, // User name. NULL = current user + NULL, // User password. NULL = current + 0, // Locale. NULL indicates current + NULL, // Security flags. + 0, // Authority (e.g. Kerberos) + 0, // Context object + &pSvc // pointer to IWbemServices proxy ); if (FAILED(hres)) @@ -151,14 +151,14 @@ bool SharedUtil::QueryWMI(SQueryWMIResult& outResult, const SString& strQuery, c // Step 5: -------------------------------------------------- // Set security levels on the proxy ------------------------- - hres = CoSetProxyBlanket(pSvc, // Indicates the proxy to set - RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx - RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx - NULL, // Server principal name - RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx - RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx - NULL, // client identity - EOAC_NONE // proxy capabilities + hres = CoSetProxyBlanket(pSvc, // Indicates the proxy to set + RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx + RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx + NULL, // Server principal name + RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx + RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx + NULL, // client identity + EOAC_NONE // proxy capabilities ); if (FAILED(hres)) @@ -314,7 +314,7 @@ long long SharedUtil::GetWMITotalPhysicalMemory() if (llResult == 0) { - llResult = 2LL * 1024 * 1024 * 1024; // 2GB + llResult = 2LL * 1024 * 1024 * 1024; // 2GB } return llResult; } @@ -350,7 +350,7 @@ unsigned int SharedUtil::GetWMIVideoAdapterMemorySize(const unsigned long ulVen, if ((iAvailability == 8 || iAvailability == 3) && PNPDeviceID.Contains(DevVen)) { uiResult = uiAdapterRAM; - break; // Found match + break; // Found match } } diff --git a/Shared/sdk/SharedUtil.Tests.hpp b/Shared/sdk/SharedUtil.Tests.hpp index ab35cf17e55..7f727b34ef4 100644 --- a/Shared/sdk/SharedUtil.Tests.hpp +++ b/Shared/sdk/SharedUtil.Tests.hpp @@ -47,20 +47,21 @@ void SharedUtil_Tests() // /////////////////////////////////////////////////////////////// #define TEST_FUNCTION \ - struct testStruct { \ - void Test(int testIndex) \ - { \ - testStruct dataCopy = *this; // Info when debugging + struct testStruct \ + { \ + void Test(int testIndex) \ + { \ + testStruct dataCopy = *this; // Info when debugging -#define TEST_VARS \ - } +#define TEST_VARS } #define TEST_DATA \ - } testData[] + } \ + testData[] #define TEST_END \ - for (uint i = 0 ; i < NUMELMS(testData) ; i++) \ - testData[i].Test(i); + for (uint i = 0; i < NUMELMS(testData); i++) \ + testData[i].Test(i); /////////////////////////////////////////////////////////////// // @@ -946,7 +947,11 @@ void SharedUtil_Hash_Tests() TEST_END } - #define szTempFilename "hash_""\xD0""\x98""_test" +#define szTempFilename \ + "hash_" \ + "\xD0" \ + "\x98" \ + "_test" // MD5 { diff --git a/Shared/sdk/SharedUtil.Thread.h b/Shared/sdk/SharedUtil.Thread.h index 2df1742422f..916a9a87bfc 100644 --- a/Shared/sdk/SharedUtil.Thread.h +++ b/Shared/sdk/SharedUtil.Thread.h @@ -15,13 +15,13 @@ #include #ifdef WIN32 -#ifndef _WINSOCKAPI_ + #ifndef _WINSOCKAPI_ struct timeval { long tv_sec; /* seconds */ long tv_usec; /* and microseconds */ }; -#endif + #endif #else #include #endif @@ -53,7 +53,7 @@ namespace SharedUtil { pthread_mutex_t mutex; pthread_cond_t cond; - bool m_bInCondWait; // Hacky flag to avoid deadlock on dll exit + bool m_bInCondWait; // Hacky flag to avoid deadlock on dll exit public: CComboMutex() { @@ -90,14 +90,14 @@ namespace SharedUtil { // Get time now struct timeval tv; - #ifdef WIN32 +#ifdef WIN32 _timeb timeb; _ftime(&timeb); tv.tv_sec = static_cast(timeb.time); tv.tv_usec = timeb.millitm * 1000; - #else +#else gettimeofday(&tv, NULL); - #endif +#endif // Add the timeout length tv.tv_sec += uiTimeout / 1000; tv.tv_usec += (uiTimeout % 1000) * 1000; @@ -119,4 +119,4 @@ namespace SharedUtil void Signal() { pthread_cond_signal(&cond); } }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.ThreadPool.h b/Shared/sdk/SharedUtil.ThreadPool.h index 6f63b4dbb6f..d28d5a08483 100644 --- a/Shared/sdk/SharedUtil.ThreadPool.h +++ b/Shared/sdk/SharedUtil.ThreadPool.h @@ -28,46 +28,48 @@ namespace SharedUtil m_vecThreads.reserve(threads); for (std::size_t i = 0; i < threads; ++i) { - m_vecThreads.emplace_back([this] { - while (true) + m_vecThreads.emplace_back( + [this] { - std::packaged_task task; + while (true) { - // Wait until either exit is signalled or a new task arrives - std::unique_lock lock(m_mutex); - m_cv.wait(lock, [this] { return m_exit || !m_tasks.empty(); }); - if (m_exit && m_tasks.empty()) - return; - task = std::move(m_tasks.front()); - m_tasks.pop(); + std::packaged_task task; + { + // Wait until either exit is signalled or a new task arrives + std::unique_lock lock(m_mutex); + m_cv.wait(lock, [this] { return m_exit || !m_tasks.empty(); }); + if (m_exit && m_tasks.empty()) + return; + task = std::move(m_tasks.front()); + m_tasks.pop(); + } + // Run the task (catch exceptions to prevent thread death) + try + { + task(false); + } + catch (...) + { + // Exception is automatically captured by std::packaged_task + // and will be re-thrown when future.get() is called. + // We must catch here to prevent the worker thread from terminating. + } } - // Run the task (catch exceptions to prevent thread death) - try - { - task(false); - } - catch (...) - { - // Exception is automatically captured by std::packaged_task - // and will be re-thrown when future.get() is called. - // We must catch here to prevent the worker thread from terminating. - } - } - }); + }); } }; template auto enqueue(Func&& f, Args&&... args) { -#if __cplusplus < 201703L // C++17 +#if __cplusplus < 201703L // C++17 using ReturnT = typename std::result_of::type; #else using ReturnT = std::invoke_result_t; #endif - auto ff = std::bind(std::forward(f), std::forward(args)...); - auto task = std::make_shared>(ff); + auto ff = std::bind(std::forward(f), std::forward(args)...); + auto task = std::make_shared>(ff); std::future res = task->get_future(); { @@ -77,16 +79,17 @@ namespace SharedUtil // Return failed future instead of throwing (avoids crash if caller ignores result) lock.unlock(); std::promise failedPromise; - failedPromise.set_exception(std::make_exception_ptr( - std::runtime_error("Cannot enqueue task: thread pool is shutting down"))); + failedPromise.set_exception(std::make_exception_ptr(std::runtime_error("Cannot enqueue task: thread pool is shutting down"))); return failedPromise.get_future(); } // Wrap task with skip flag for shutdown cleanup - std::packaged_task resultTask([task](bool skip) { - if (!skip) - (*task)(); - }); + std::packaged_task resultTask( + [task](bool skip) + { + if (!skip) + (*task)(); + }); m_tasks.emplace(std::move(resultTask)); } @@ -156,4 +159,4 @@ namespace SharedUtil { return CThreadPool::getDefaultThreadPool().enqueue(std::forward(args)...); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Time.h b/Shared/sdk/SharedUtil.Time.h index 284a91a9af9..c91eaa2f00e 100644 --- a/Shared/sdk/SharedUtil.Time.h +++ b/Shared/sdk/SharedUtil.Time.h @@ -23,9 +23,9 @@ namespace SharedUtil // uint GetTickCount32(); - // Forbid use of GetTickCount - #define GetTickCount GetTickCount_has_been_replaced_with_GetTickCount32 - #define GetTickCount64 GetTickCount64_wont_work_on_XP_you_IDIOT +// Forbid use of GetTickCount +#define GetTickCount GetTickCount_has_been_replaced_with_GetTickCount32 +#define GetTickCount64 GetTickCount64_wont_work_on_XP_you_IDIOT // // Retrieves the number of milliseconds that have elapsed since some arbitrary point in time. @@ -168,9 +168,9 @@ namespace SharedUtil m_ppIntervalCounter = NULL; m_ucUpdateCount = 0; m_uiElapsedTime = 0; - #ifndef SHARED_UTIL_MANUAL_TIMER_INITIALIZATION +#ifndef SHARED_UTIL_MANUAL_TIMER_INITIALIZATION StaticInitialize(this); - #endif +#endif } ~CElapsedTimeApprox() @@ -280,4 +280,4 @@ namespace SharedUtil std::vector itemList; }; -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.Time.hpp b/Shared/sdk/SharedUtil.Time.hpp index 1d575255745..ae2aedbc780 100644 --- a/Shared/sdk/SharedUtil.Time.hpp +++ b/Shared/sdk/SharedUtil.Time.hpp @@ -14,7 +14,7 @@ #include "sys/time.h" #else #ifndef NOMINMAX - #define NOMINMAX + #define NOMINMAX #endif #include #endif @@ -201,41 +201,41 @@ namespace SharedUtil public: CPerModuleTickCount() { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG m_TimeSinceUpdated.SetMaxIncrement(500); - #endif +#endif m_ResultValue.Initialize(GetTickCount64_()); } long long Get() { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG if (m_TimeSinceUpdated.Get() > 10000) { m_TimeSinceUpdated.Reset(); OutputDebugLine("WARNING: UpdateModuleTickCount64 might not be called for the current module"); } - #endif +#endif return m_ResultValue.GetValue(); } void Update() { - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG m_TimeSinceUpdated.Reset(); - #endif +#endif m_ResultValue.SetValue(GetTickCount64_()); } protected: CThreadResultValue m_ResultValue; - #ifdef MTA_DEBUG +#ifdef MTA_DEBUG CElapsedTime m_TimeSinceUpdated; - #endif +#endif }; CPerModuleTickCount ms_PerModuleTickCount; -} // namespace SharedUtil +} // namespace SharedUtil long long SharedUtil::GetModuleTickCount64() { @@ -257,8 +257,8 @@ void SharedUtil::UpdateModuleTickCount64() // #if defined(__APPLE__) -// Apple / Darwin platforms with Mach monotonic clock support -#include + // Apple / Darwin platforms with Mach monotonic clock support + #include unsigned long GetTickCountInternal() { mach_timebase_info_data_t info; @@ -280,7 +280,7 @@ unsigned long GetTickCountInternal() unsigned long GetTickCountInternal() { #if !defined(CLOCK_MONOTONIC) - #error "This platform does not have monotonic clock support." + #error "This platform does not have monotonic clock support." #endif /* @@ -315,9 +315,9 @@ unsigned long GetTickCountInternal() #else -// Win32 platforms -#include -#pragma comment(lib, "Winmm.lib") + // Win32 platforms + #include + #pragma comment(lib, "Winmm.lib") unsigned long GetTickCountInternal() { // Uses timeGetTime() as Win32 GetTickCount() has a resolution of 16ms. @@ -349,7 +349,7 @@ TIMEUS SharedUtil::GetTimeUs() return llDuration & 0xffffffff; } #else -#include // for gettimeofday() + #include // for gettimeofday() typedef long long LONGLONG; TIMEUS SharedUtil::GetTimeUs() @@ -369,8 +369,8 @@ TIMEUS SharedUtil::GetTimeUs() // compute elapsed time in us LONGLONG llDuration; - llDuration = (t2.tv_sec - t1.tv_sec) * 1000000LL; // sec to us - llDuration += (t2.tv_usec - t1.tv_usec); // us to us + llDuration = (t2.tv_sec - t1.tv_sec) * 1000000LL; // sec to us + llDuration += (t2.tv_usec - t1.tv_usec); // us to us return llDuration & 0xffffffff; } diff --git a/Shared/sdk/SharedUtil.Win32Utf8FileHooks.hpp b/Shared/sdk/SharedUtil.Win32Utf8FileHooks.hpp index c89f604f13a..4ef6c5a3ec1 100644 --- a/Shared/sdk/SharedUtil.Win32Utf8FileHooks.hpp +++ b/Shared/sdk/SharedUtil.Win32Utf8FileHooks.hpp @@ -70,14 +70,14 @@ auto ToACP(const std::filesystem::path& path) -> std::string namespace SharedUtil { - ///////////////////////////////////////////////////////////// - // - // Hook variables - // - ///////////////////////////////////////////////////////////// - #define HOOKVAR(name) \ - using FUNC_##name = decltype(&name); \ - FUNC_##name pfn##name; +///////////////////////////////////////////////////////////// +// +// Hook variables +// +///////////////////////////////////////////////////////////// +#define HOOKVAR(name) \ + using FUNC_##name = decltype(&name); \ + FUNC_##name pfn##name; HOOKVAR(CreateFileA) HOOKVAR(LoadLibraryA) @@ -173,13 +173,22 @@ namespace SharedUtil HMODULE WINAPI - MyLoadLibraryA(__in LPCSTR lpLibFileName) { return LoadLibraryW(FromUTF8(lpLibFileName)); } + MyLoadLibraryA(__in LPCSTR lpLibFileName) + { + return LoadLibraryW(FromUTF8(lpLibFileName)); + } HMODULE WINAPI - MyLoadLibraryExA(__in LPCSTR lpLibFileName, __reserved HANDLE hFile, __in DWORD dwFlags) { return LoadLibraryExW(FromUTF8(lpLibFileName), hFile, dwFlags); } + MyLoadLibraryExA(__in LPCSTR lpLibFileName, __reserved HANDLE hFile, __in DWORD dwFlags) + { + return LoadLibraryExW(FromUTF8(lpLibFileName), hFile, dwFlags); + } - BOOL WINAPI MySetDllDirectoryA(__in_opt LPCSTR lpPathName) { return SetDllDirectoryW(FromUTF8(lpPathName)); } + BOOL WINAPI MySetDllDirectoryA(__in_opt LPCSTR lpPathName) + { + return SetDllDirectoryW(FromUTF8(lpPathName)); + } BOOL WINAPI MySetCurrentDirectoryA(__in LPCSTR lpPathName) { @@ -191,9 +200,15 @@ namespace SharedUtil return SetCurrentDirectoryW(FromUTF8(strPathName)); } - int WINAPI MyAddFontResourceExA(__in LPCSTR name, __in DWORD fl, __reserved PVOID res) { return AddFontResourceExW(FromUTF8(name), fl, res); } + int WINAPI MyAddFontResourceExA(__in LPCSTR name, __in DWORD fl, __reserved PVOID res) + { + return AddFontResourceExW(FromUTF8(name), fl, res); + } - BOOL WINAPI MyRemoveFontResourceExA(__in LPCSTR name, __in DWORD fl, __reserved PVOID pdv) { return RemoveFontResourceExW(FromUTF8(name), fl, pdv); } + BOOL WINAPI MyRemoveFontResourceExA(__in LPCSTR name, __in DWORD fl, __reserved PVOID pdv) + { + return RemoveFontResourceExW(FromUTF8(name), fl, pdv); + } BOOL WINAPI MyRemoveDirectoryA(__in LPCSTR lpPathName) { @@ -284,11 +299,11 @@ namespace SharedUtil ///////////////////////////////////////////////////////////// void AddUtf8FileHooks() { - #define ADDHOOK(module,name) \ - static_assert(std::is_same_v, "invalid type of " MTA_STR(pfn##name)); \ - pfn##name = reinterpret_cast(DetourFindFunction(module, #name)); \ - DetourAttach(&reinterpret_cast(pfn##name), My##name); \ - assert(pfn##name); +#define ADDHOOK(module, name) \ + static_assert(std::is_same_v, "invalid type of " MTA_STR(pfn##name)); \ + pfn##name = reinterpret_cast(DetourFindFunction(module, #name)); \ + DetourAttach(&reinterpret_cast(pfn##name), My##name); \ + assert(pfn##name); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); @@ -321,12 +336,12 @@ namespace SharedUtil ///////////////////////////////////////////////////////////// void RemoveUtf8FileHooks() { - #define DELHOOK(name) \ - if (pfn##name != nullptr) \ - { \ - DetourDetach(&reinterpret_cast(pfn##name), My##name); \ - pfn##name = nullptr; \ - } +#define DELHOOK(name) \ + if (pfn##name != nullptr) \ + { \ + DetourDetach(&reinterpret_cast(pfn##name), My##name); \ + pfn##name = nullptr; \ + } DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); @@ -351,4 +366,4 @@ namespace SharedUtil DetourTransactionCommit(); } -} // namespace SharedUtil +} // namespace SharedUtil diff --git a/Shared/sdk/SharedUtil.h b/Shared/sdk/SharedUtil.h index 3d4ff256dc6..837e4e49644 100644 --- a/Shared/sdk/SharedUtil.h +++ b/Shared/sdk/SharedUtil.h @@ -29,13 +29,13 @@ // Vendor #ifndef _ -#define _ //Use a dummy localisation define for modules that don't need it + #define _ // Use a dummy localisation define for modules that don't need it #endif #include "SString.h" #include "WString.h" -#define _E(code) SString(" [%s]",code) +#define _E(code) SString(" [%s]", code) #include "SharedUtil.Legacy.h" #include "SharedUtil.Map.h" @@ -67,21 +67,21 @@ #include "CDuplicateLineFilter.h" #ifdef _MSC_VER -#define snprintf _snprintf + #define snprintf _snprintf #endif #ifndef stricmp -#ifdef _MSC_VER -#define stricmp _stricmp -#else -#define stricmp strcasecmp -#endif + #ifdef _MSC_VER + #define stricmp _stricmp + #else + #define stricmp strcasecmp + #endif #endif #ifndef strnicmp -#ifdef _MSC_VER -#define strnicmp _strnicmp -#else -#define strnicmp strncasecmp -#endif + #ifdef _MSC_VER + #define strnicmp _strnicmp + #else + #define strnicmp strncasecmp + #endif #endif diff --git a/Shared/sdk/UTF8.hpp b/Shared/sdk/UTF8.hpp index 50091956bd2..3f845b2413c 100644 --- a/Shared/sdk/UTF8.hpp +++ b/Shared/sdk/UTF8.hpp @@ -26,14 +26,14 @@ #include "UTF8.h" /* Return code if invalid. (xxx_mbtowc, xxx_wctomb) */ -#define RET_ILSEQ 0 +#define RET_ILSEQ 0 /* Return code if only a shift sequence of n bytes was read. (xxx_mbtowc) */ -#define RET_TOOFEW(n) (-1-(n)) +#define RET_TOOFEW(n) (-1 - (n)) /* Return code if output buffer is too small. (xxx_wctomb, xxx_reset) */ -#define RET_TOOSMALL -1 +#define RET_TOOSMALL -1 /* Replacement character for invalid multibyte sequence or wide character. */ -#define BAD_WCHAR ((wchar_t) 0xfffd) -#define BAD_CHAR '?' +#define BAD_WCHAR ((wchar_t)0xfffd) +#define BAD_CHAR '?' int utf8_mbtowc(wchar_t* pwc, const unsigned char* src, int src_len) { diff --git a/Shared/sdk/UTF8Detect.hpp b/Shared/sdk/UTF8Detect.hpp index 902e9c36ad5..a5be5e5492a 100644 --- a/Shared/sdk/UTF8Detect.hpp +++ b/Shared/sdk/UTF8Detect.hpp @@ -60,7 +60,7 @@ int icu_getUTF8Confidence(const unsigned char* input, int len) if ((b & 0x80) == 0) { - continue; // ASCII + continue; // ASCII } // Hi bit on char found. Figure out how long the sequence should be diff --git a/Shared/sdk/WString.h b/Shared/sdk/WString.h index ac3ca48abec..7bcd2852db8 100644 --- a/Shared/sdk/WString.h +++ b/Shared/sdk/WString.h @@ -16,9 +16,9 @@ #include "SString.h" #ifdef WIN32 -#ifndef va_copy - #define va_copy(dest, orig) (dest) = (orig) -#endif + #ifndef va_copy + #define va_copy(dest, orig) (dest) = (orig) + #endif #endif // @@ -36,7 +36,7 @@ class WString : public std::wstring WString(const char* szText); - WString(const char16_t* szText) : std::wstring(szText ? (const wchar_t*)szText : L""){}; + WString(const char16_t* szText) : std::wstring(szText ? (const wchar_t*)szText : L"") {}; explicit WString(const wchar_t* szFormat, ...) : std::wstring() { @@ -74,7 +74,7 @@ class WString : public std::wstring WString operator+(const WString& other) const { return std::wstring(*this) + other; } // Assignment - operator const wchar_t*() const { return c_str(); } // Auto assign to const wchar_t* without using c_str() + operator const wchar_t*() const { return c_str(); } // Auto assign to const wchar_t* without using c_str() const wchar_t* operator*() const { return c_str(); } // Functions diff --git a/Shared/sdk/enums/MarkerDisplay.h b/Shared/sdk/enums/MarkerDisplay.h index b41f46344ea..ed81618251c 100644 --- a/Shared/sdk/enums/MarkerDisplay.h +++ b/Shared/sdk/enums/MarkerDisplay.h @@ -14,8 +14,8 @@ enum class MarkerDisplay : std::uint8_t { - MARKER_DISPLAY_NEITHER = 0, // BLIPDISPLAY_NEITHER - MARKER_DISPLAY_MARKERONLY, // BLIPDISPLAY_MARKERONLY - MARKER_DISPLAY_BLIPONLY, // MARKER_DISPLAY_BLIPONLY - MARKER_DISPLAY_BOTH // BLIPDISPLAY_BOTH + MARKER_DISPLAY_NEITHER = 0, // BLIPDISPLAY_NEITHER + MARKER_DISPLAY_MARKERONLY, // BLIPDISPLAY_MARKERONLY + MARKER_DISPLAY_BLIPONLY, // MARKER_DISPLAY_BLIPONLY + MARKER_DISPLAY_BOTH // BLIPDISPLAY_BOTH }; diff --git a/Shared/sdk/enums/ObjectGroupPhysicalProperties.h b/Shared/sdk/enums/ObjectGroupPhysicalProperties.h index 774fd84b3c4..6532a1e95e1 100644 --- a/Shared/sdk/enums/ObjectGroupPhysicalProperties.h +++ b/Shared/sdk/enums/ObjectGroupPhysicalProperties.h @@ -74,4 +74,4 @@ namespace ObjectGroupPhysicalProperties BY_GUN, SMASHABLE, }; -} // namespace ObjectGroupPhysicalProperties +} // namespace ObjectGroupPhysicalProperties diff --git a/Shared/sdk/enums/PedState.h b/Shared/sdk/enums/PedState.h index 25d9c815fca..429c7199747 100644 --- a/Shared/sdk/enums/PedState.h +++ b/Shared/sdk/enums/PedState.h @@ -30,14 +30,14 @@ enum class PedState PED_DUMMY, PED_PAUSE, PED_ATTACK, - PED_FIGHT, // new close combat fist fight mode + PED_FIGHT, // new close combat fist fight mode PED_FACE_PHONE, PED_MAKE_PHONECALL, PED_CHAT, PED_MUG, PED_AIMGUN, PED_AI_CONTROL, - PED_SEEK_CAR, // 24 + PED_SEEK_CAR, // 24 PED_SEEK_BOAT_POSITION, PED_FOLLOW_ROUTE, PED_CPR, @@ -51,7 +51,7 @@ enum class PedState PED_JOG, PED_ANSWER_MOBILE, PED_HANG_OUT, - PED_STATES_NO_AI, // only put states after here that do not require AI, put other ones before this + PED_STATES_NO_AI, // only put states after here that do not require AI, put other ones before this PED_ABSEIL_FROM_HELI, PED_SIT, PED_JUMP, @@ -59,11 +59,11 @@ enum class PedState PED_GETUP, PED_STAGGER, PED_EVADE_DIVE, - PED_STATES_CAN_SHOOT, // only put states before here than ped can be shot during + PED_STATES_CAN_SHOOT, // only put states before here than ped can be shot during PED_ENTER_TRAIN, PED_EXIT_TRAIN, PED_ARREST_PLAYER, - PED_DRIVING, // 50 + PED_DRIVING, // 50 PED_PASSENGER, PED_TAXI_PASSENGER, PED_OPEN_DOOR, diff --git a/Shared/sdk/enums/SoundEffectParams.h b/Shared/sdk/enums/SoundEffectParams.h index b7b5b93ed4f..a246246d4bb 100644 --- a/Shared/sdk/enums/SoundEffectParams.h +++ b/Shared/sdk/enums/SoundEffectParams.h @@ -99,4 +99,4 @@ namespace eSoundEffectParams REVERB_TIME, HIGH_FREQ_RT_RATIO, }; -} // namespace eSoundEffectParams +} // namespace eSoundEffectParams diff --git a/Shared/sdk/enums/WeaponProperty.h b/Shared/sdk/enums/WeaponProperty.h index 79fc9dbee93..d6851a5f1f4 100644 --- a/Shared/sdk/enums/WeaponProperty.h +++ b/Shared/sdk/enums/WeaponProperty.h @@ -56,27 +56,27 @@ enum class WeaponProperty WEAPON_DEFAULT_COMBO, WEAPON_COMBOS_AVAILABLE, - WEAPON_FLAG_AIM_NO_AUTO, // 0x000001 - cant auto target to aim (disable automatic up/down adjustment when firing without aiming) + WEAPON_FLAG_AIM_NO_AUTO, // 0x000001 - cant auto target to aim (disable automatic up/down adjustment when firing without aiming) WEAPON_FLAG_FIRST = WEAPON_FLAG_AIM_NO_AUTO, - WEAPON_FLAG_AIM_ARM, // 0x000002 - only needs arm to aim (ie pistol/shotgun/tec9/uzi) - WEAPON_FLAG_AIM_1ST_PERSON, // 0x000004 - uses 1st person aim (ie sniper/rpg-hs - WEAPON_FLAG_AIM_FREE, // 0x000008 - can only use free aiming (ie country sniper/flame thrower/minigun/fire extinguisher) - WEAPON_FLAG_MOVE_AND_AIM, // 0x000010 - can move and aim at same time - WEAPON_FLAG_MOVE_AND_SHOOT, // 0x000020 - can move and fire at same time + WEAPON_FLAG_AIM_ARM, // 0x000002 - only needs arm to aim (ie pistol/shotgun/tec9/uzi) + WEAPON_FLAG_AIM_1ST_PERSON, // 0x000004 - uses 1st person aim (ie sniper/rpg-hs + WEAPON_FLAG_AIM_FREE, // 0x000008 - can only use free aiming (ie country sniper/flame thrower/minigun/fire extinguisher) + WEAPON_FLAG_MOVE_AND_AIM, // 0x000010 - can move and aim at same time + WEAPON_FLAG_MOVE_AND_SHOOT, // 0x000020 - can move and fire at same time WEAPON_FLAG_UNKNOWN_0040, WEAPON_FLAG_UNKNOWN_0080, - WEAPON_FLAG_TYPE_THROW, // 0x000100 - is a throwing weapon (ie satchel) - WEAPON_FLAG_TYPE_HEAVY, // 0x000200 - heavy weapon - can't jump (ie flame thrower/rpgs/minigun) - WEAPON_FLAG_TYPE_CONSTANT, // 0x000400 - fires every frame within loop (ie paint spray) - WEAPON_FLAG_TYPE_DUAL, // 0x000800 - can use 2x guns at same time (ie pistol/shotgun/tec9/uzi) - WEAPON_FLAG_ANIM_RELOAD, // 0x001000 - weapon has reload anims (ie everything except shotgun/snipers/flame thrower/rpgs/minigun/satchel) - WEAPON_FLAG_ANIM_CROUCH, // 0x002000 - weapon has crouching anims (ie everything except flame thrower/rpgs/minigun/satchel) - WEAPON_FLAG_ANIM_RELOAD_LOOP, // 0x004000 - loop from end of reload to fire loop start - WEAPON_FLAG_ANIM_RELOAD_LONG, // 0x008000 - force a longer reload time! (ie rpgs/snipers) - WEAPON_FLAG_SHOT_SLOWS, // 0x010000 - slows down (ie flame thrower) - WEAPON_FLAG_SHOT_RAND_SPEED, // 0x020000 - random speed (ie flame thrower) - WEAPON_FLAG_SHOT_ANIM_ABRUPT, // 0x040000 - force the anim to finish player after aim/fire rather than blending out (ie rpgs) - WEAPON_FLAG_SHOT_EXPANDS, // 0x080000 - expands + WEAPON_FLAG_TYPE_THROW, // 0x000100 - is a throwing weapon (ie satchel) + WEAPON_FLAG_TYPE_HEAVY, // 0x000200 - heavy weapon - can't jump (ie flame thrower/rpgs/minigun) + WEAPON_FLAG_TYPE_CONSTANT, // 0x000400 - fires every frame within loop (ie paint spray) + WEAPON_FLAG_TYPE_DUAL, // 0x000800 - can use 2x guns at same time (ie pistol/shotgun/tec9/uzi) + WEAPON_FLAG_ANIM_RELOAD, // 0x001000 - weapon has reload anims (ie everything except shotgun/snipers/flame thrower/rpgs/minigun/satchel) + WEAPON_FLAG_ANIM_CROUCH, // 0x002000 - weapon has crouching anims (ie everything except flame thrower/rpgs/minigun/satchel) + WEAPON_FLAG_ANIM_RELOAD_LOOP, // 0x004000 - loop from end of reload to fire loop start + WEAPON_FLAG_ANIM_RELOAD_LONG, // 0x008000 - force a longer reload time! (ie rpgs/snipers) + WEAPON_FLAG_SHOT_SLOWS, // 0x010000 - slows down (ie flame thrower) + WEAPON_FLAG_SHOT_RAND_SPEED, // 0x020000 - random speed (ie flame thrower) + WEAPON_FLAG_SHOT_ANIM_ABRUPT, // 0x040000 - force the anim to finish player after aim/fire rather than blending out (ie rpgs) + WEAPON_FLAG_SHOT_EXPANDS, // 0x080000 - expands WEAPON_FLAG_LAST = WEAPON_FLAG_SHOT_EXPANDS, WEAPON_FIRE_ROTATION, diff --git a/Shared/sdk/net/CNetHTTPDownloadManagerInterface.h b/Shared/sdk/net/CNetHTTPDownloadManagerInterface.h index 2bd5a647bf7..741cebf9659 100644 --- a/Shared/sdk/net/CNetHTTPDownloadManagerInterface.h +++ b/Shared/sdk/net/CNetHTTPDownloadManagerInterface.h @@ -20,14 +20,14 @@ struct SHttpRequestOptions { SHttpRequestOptions() {} SHttpRequestOptions(const struct SHttpRequestOptionsTx& in); - bool bIsLegacy = false; // true = sets CURLOPT_FAILONERROR - bool bIsLocal = false; // false = download aborts if < 10 bytes/s for uiConnectTimeoutMs - bool bCheckContents = false; // true = check for naughty things before saving file - bool bResumeFile = false; // true = attempt to resume previously interrupted download + bool bIsLegacy = false; // true = sets CURLOPT_FAILONERROR + bool bIsLocal = false; // false = download aborts if < 10 bytes/s for uiConnectTimeoutMs + bool bCheckContents = false; // true = check for naughty things before saving file + bool bResumeFile = false; // true = attempt to resume previously interrupted download SString strPostData; - bool bPostBinary = false; // false = truncate strPostData to first null character and send as text/plain - // (true = send as application/octet-stream) - std::map formFields; // If set, send items as multipart/formdata (and ignore strPostData) + bool bPostBinary = false; // false = truncate strPostData to first null character and send as text/plain + // (true = send as application/octet-stream) + std::map formFields; // If set, send items as multipart/formdata (and ignore strPostData) uint uiConnectionAttempts = 10; uint uiConnectTimeoutMs = 10000; SString strRequestMethod; @@ -152,9 +152,9 @@ inline SHttpRequestOptionsTx::SHttpRequestOptionsTx(const SHttpRequestOptions& i struct SDownloadStatus { - uint uiAttemptNumber = 0; // 0=Queued 1+=Downloading - uint uiContentLength = 0; // Item total size. Will be 0 if http header 'Content-Length' is missing - uint uiBytesReceived = 0; // Download progress + uint uiAttemptNumber = 0; // 0=Queued 1+=Downloading + uint uiContentLength = 0; // Item total size. Will be 0 if http header 'Content-Length' is missing + uint uiBytesReceived = 0; // Download progress }; // PFN_DOWNLOAD_FINISHED_CALLBACK is called once at the end of the download. diff --git a/Shared/sdk/net/SyncStructures.h b/Shared/sdk/net/SyncStructures.h index c30cf4ce504..8c3276be531 100644 --- a/Shared/sdk/net/SyncStructures.h +++ b/Shared/sdk/net/SyncStructures.h @@ -57,9 +57,9 @@ struct SFloatSync : public ISyncStructure double dValue = data.fValue; #ifdef WIN32 -#ifdef MTA_DEBUG + #ifdef MTA_DEBUG assert(!std::isnan(dValue)); -#endif + #endif #endif dValue = Clamp(limitsMin, dValue, limitsMax); @@ -547,15 +547,9 @@ struct SPlayerPuresyncFlags : public ISyncStructure BITCOUNT = 15 }; - bool Read(NetBitStreamInterface& stream) - { - return stream.ReadBits((char*)&data, BITCOUNT); - } + bool Read(NetBitStreamInterface& stream) { return stream.ReadBits((char*)&data, BITCOUNT); } - void Write(NetBitStreamInterface& stream) const - { - stream.WriteBits((const char*)&data, BITCOUNT); - } + void Write(NetBitStreamInterface& stream) const { stream.WriteBits((const char*)&data, BITCOUNT); } struct { @@ -1694,49 +1688,49 @@ struct SVehicleHandlingSync : public ISyncStructure struct { - float fMass; // +4 + float fMass; // +4 - float fTurnMass; // +12 - float fDragCoeff; // +16 - CVector vecCenterOfMass; // +20 - unsigned char ucPercentSubmerged; // +32 (unsigned int - sync changes) + float fTurnMass; // +12 + float fDragCoeff; // +16 + CVector vecCenterOfMass; // +20 + unsigned char ucPercentSubmerged; // +32 (unsigned int - sync changes) - float fTractionMultiplier; // +40 + float fTractionMultiplier; // +40 - unsigned char ucDriveType; // +112 - unsigned char ucEngineType; // +113 - unsigned char ucNumberOfGears; // +114 + unsigned char ucDriveType; // +112 + unsigned char ucEngineType; // +113 + unsigned char ucNumberOfGears; // +114 - float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) - float fEngineInertia; // +124 - float fMaxVelocity; // +128 + float fEngineAcceleration; // +120 (value in handling.cfg * 0x86A950) + float fEngineInertia; // +124 + float fMaxVelocity; // +128 - float fBrakeDeceleration; // +148 - float fBrakeBias; // +152 - bool bABS; // +156 + float fBrakeDeceleration; // +148 + float fBrakeBias; // +152 + bool bABS; // +156 - float fSteeringLock; // +160 - float fTractionLoss; // +164 - float fTractionBias; // +168 + float fSteeringLock; // +160 + float fTractionLoss; // +164 + float fTractionBias; // +168 - float fSuspensionForceLevel; // +172 - float fSuspensionDamping; // +176 - float fSuspensionHighSpdDamping; // +180 - float fSuspensionUpperLimit; // +184 - float fSuspensionLowerLimit; // +188 - float fSuspensionFrontRearBias; // +192 - float fSuspensionAntiDiveMultiplier; // +196 + float fSuspensionForceLevel; // +172 + float fSuspensionDamping; // +176 + float fSuspensionHighSpdDamping; // +180 + float fSuspensionUpperLimit; // +184 + float fSuspensionLowerLimit; // +188 + float fSuspensionFrontRearBias; // +192 + float fSuspensionAntiDiveMultiplier; // +196 - float fCollisionDamageMultiplier; // +200 + float fCollisionDamageMultiplier; // +200 - unsigned int uiModelFlags; // +204 - unsigned int uiHandlingFlags; // +208 - float fSeatOffsetDistance; // +212 + unsigned int uiModelFlags; // +204 + unsigned int uiHandlingFlags; // +208 + float fSeatOffsetDistance; // +212 // unsigned int uiMonetary; // +216 // unsigned char ucHeadLight; // +220 // unsigned char ucTailLight; // +221 - unsigned char ucAnimGroup; // +222 + unsigned char ucAnimGroup; // +222 } data; }; @@ -2407,26 +2401,26 @@ struct sWeaponPropertySync : public ISyncStructure struct { int weaponType; - FLOAT fTargetRange; // max targeting range - FLOAT fWeaponRange; // absolute gun range / default melee attack range + FLOAT fTargetRange; // max targeting range + FLOAT fWeaponRange; // absolute gun range / default melee attack range - int nFlags; // flags defining characteristics + int nFlags; // flags defining characteristics - short nAmmo; // ammo in one clip - short nDamage; // damage inflicted per hit + short nAmmo; // ammo in one clip + short nDamage; // damage inflicted per hit - FLOAT fAccuracy; // modify accuracy of weapon - FLOAT fMoveSpeed; // how fast can move with weapon + FLOAT fAccuracy; // modify accuracy of weapon + FLOAT fMoveSpeed; // how fast can move with weapon - FLOAT anim_loop_start; // start of animation loop - FLOAT anim_loop_stop; // end of animation loop - FLOAT anim_loop_bullet_fire; // time in animation when weapon should be fired + FLOAT anim_loop_start; // start of animation loop + FLOAT anim_loop_stop; // end of animation loop + FLOAT anim_loop_bullet_fire; // time in animation when weapon should be fired - FLOAT anim2_loop_start; // start of animation2 loop - FLOAT anim2_loop_stop; // end of animation2 loop - FLOAT anim2_loop_bullet_fire; // time in animation2 when weapon should be fired + FLOAT anim2_loop_start; // start of animation2 loop + FLOAT anim2_loop_stop; // end of animation2 loop + FLOAT anim2_loop_bullet_fire; // time in animation2 when weapon should be fired - FLOAT anim_breakout_time; // time after which player can break out of attack and run off + FLOAT anim_breakout_time; // time after which player can break out of attack and run off } data; }; diff --git a/Shared/sdk/net/bitstream.h b/Shared/sdk/net/bitstream.h index f38deb1dd0b..6b04aa6a305 100644 --- a/Shared/sdk/net/bitstream.h +++ b/Shared/sdk/net/bitstream.h @@ -24,7 +24,7 @@ #endif #ifdef __cpp_lib_string_view -#include + #include #endif struct ISyncStructure; @@ -67,7 +67,7 @@ class NetBitStreamInterface : public CRefCountable virtual void Write(const char* input, int numberOfBytes) = 0; virtual void Write(const ISyncStructure* syncStruct) = 0; -public: // Use char functions only when they will be 0 most times +public: // Use char functions only when they will be 0 most times virtual void WriteCompressed(const unsigned char& input) = 0; virtual void WriteCompressed(const char& input) = 0; @@ -77,7 +77,7 @@ class NetBitStreamInterface : public CRefCountable virtual void WriteCompressed(const unsigned int& input) = 0; virtual void WriteCompressed(const int& input) = 0; -private: // Float functions not used because they only cover -1 to +1 and are lossy +private: // Float functions not used because they only cover -1 to +1 and are lossy virtual void WriteCompressed(const float& input) = 0; virtual void WriteCompressed(const double& input) = 0; @@ -109,7 +109,7 @@ class NetBitStreamInterface : public CRefCountable virtual bool Read(char* output, int numberOfBytes) = 0; virtual bool Read(ISyncStructure* syncStruct) = 0; -public: // Use char functions only when they will be 0 most times +public: // Use char functions only when they will be 0 most times virtual bool ReadCompressed(unsigned char& output) = 0; virtual bool ReadCompressed(char& output) = 0; @@ -119,7 +119,7 @@ class NetBitStreamInterface : public CRefCountable virtual bool ReadCompressed(unsigned int& output) = 0; virtual bool ReadCompressed(int& output) = 0; -private: // Float functions not used because they only cover -1 to +1 and are lossy +private: // Float functions not used because they only cover -1 to +1 and are lossy virtual bool ReadCompressed(float& output) = 0; virtual bool ReadCompressed(double& output) = 0; @@ -320,15 +320,15 @@ class NetBitStreamInterface : public CRefCountable // Write variable size length void WriteLength(uint uiLength) { - if (uiLength <= 0x7F) // One byte for length up to 127 + if (uiLength <= 0x7F) // One byte for length up to 127 Write((uchar)uiLength); else if (uiLength <= 0x7EFF) - { // Two bytes for length from 128 to 32511 + { // Two bytes for length from 128 to 32511 Write((uchar)((uiLength >> 8) + 128)); Write((uchar)(uiLength & 0xFF)); } else - { // Five bytes for length 32512 and up + { // Five bytes for length 32512 and up Write((uchar)255); Write(uiLength); } @@ -344,18 +344,18 @@ class NetBitStreamInterface : public CRefCountable return false; if (ucValue <= 0x7F) - { // One byte for length up to 127 + { // One byte for length up to 127 uiOutLength = ucValue; } else if (ucValue != 255) - { // Two bytes for length from 128 to 32511 + { // Two bytes for length from 128 to 32511 uchar ucValue2 = 0; if (!Read(ucValue2)) return false; uiOutLength = ((ucValue - 128) << 8) + ucValue2; } else - { // Five bytes for length 32512 and up + { // Five bytes for length 32512 and up if (!Read(uiOutLength)) return false; } @@ -372,18 +372,18 @@ class NetBitStreamInterface : public CRefCountable return ReadStringCharacters(result, uiLength); } - #ifdef MTA_CLIENT - #define MAX_ELEMENTS MAX_CLIENT_ELEMENTS - #else - #define MAX_ELEMENTS MAX_SERVER_ELEMENTS - #endif +#ifdef MTA_CLIENT + #define MAX_ELEMENTS MAX_CLIENT_ELEMENTS +#else + #define MAX_ELEMENTS MAX_SERVER_ELEMENTS +#endif // Write an element ID void Write(const ElementID& ID) { static const unsigned int bitcount = NumberOfSignificantBits<(MAX_ELEMENTS - 1)>::COUNT; const unsigned int& IDref = ID.Value(); - #ifdef MTA_CLIENT +#ifdef MTA_CLIENT if (IDref != INVALID_ELEMENT_ID && IDref >= MAX_SERVER_ELEMENTS) { dassert("Sending client side element id to server" && 0); @@ -391,7 +391,7 @@ class NetBitStreamInterface : public CRefCountable WriteBits(reinterpret_cast(&uiInvalidId), bitcount); return; } - #endif +#endif WriteBits(reinterpret_cast(&IDref), bitcount); } @@ -418,4 +418,4 @@ struct ISyncStructure virtual ~ISyncStructure() {} virtual bool Read(NetBitStreamInterface& bitStream) = 0; virtual void Write(NetBitStreamInterface& bitStream) const = 0; -}; \ No newline at end of file +}; diff --git a/Shared/sdk/net/rpc_enums.h b/Shared/sdk/net/rpc_enums.h index 84c7518bc45..81ec05b0444 100644 --- a/Shared/sdk/net/rpc_enums.h +++ b/Shared/sdk/net/rpc_enums.h @@ -290,8 +290,8 @@ enum eElementRPCFunctions SPAWN_VEHICLE_FLYING_COMPONENT, SET_VEHICLE_NITRO_ACTIVATED, - + SET_ELEMENT_ON_FIRE, - NUM_RPC_FUNCS // Add above this line + NUM_RPC_FUNCS // Add above this line }; diff --git a/Shared/sdk/profiler/SharedUtil.Profiler.h b/Shared/sdk/profiler/SharedUtil.Profiler.h index 0c85c2df0d2..094c9c814dc 100644 --- a/Shared/sdk/profiler/SharedUtil.Profiler.h +++ b/Shared/sdk/profiler/SharedUtil.Profiler.h @@ -20,8 +20,7 @@ // #if MTASA_VERSION_TYPE >= VERSION_TYPE_UNSTABLE && defined(_DECLARE_PROFILER_SECTION) - #define DECLARE_PROFILER_SECTION(tag) \ - _DECLARE_PROFILER_SECTION(__FILE__, tag) + #define DECLARE_PROFILER_SECTION(tag) _DECLARE_PROFILER_SECTION(__FILE__, tag) #else #define DECLARE_PROFILER_SECTION(tag) #endif diff --git a/Shared/sdk/sha1.h b/Shared/sdk/sha1.h index 4d7dcab0c7a..4170fa2ae45 100644 --- a/Shared/sdk/sha1.h +++ b/Shared/sdk/sha1.h @@ -30,22 +30,22 @@ #include #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32) -#include + #include typedef UINT32 uint32_t; #else -#include + #include #endif -#define POLARSSL_ERR_SHA1_FILE_IO_ERROR -0x0076 /**< Read/write error in file. */ +#define POLARSSL_ERR_SHA1_FILE_IO_ERROR -0x0076 /**< Read/write error in file. */ #if !defined(POLARSSL_SHA1_ALT) // Regular implementation // -#ifdef __cplusplus + #ifdef __cplusplus extern "C" { -#endif + #endif /** * \brief SHA-1 context structure @@ -101,12 +101,12 @@ extern "C" /* Internal use */ void sha1_process(sha1_context* ctx, const unsigned char data[64]); -#ifdef __cplusplus + #ifdef __cplusplus } -#endif + #endif -#else /* POLARSSL_SHA1_ALT */ -#include "sha1_alt.h" +#else /* POLARSSL_SHA1_ALT */ + #include "sha1_alt.h" #endif /* POLARSSL_SHA1_ALT */ #ifdef __cplusplus diff --git a/Shared/sdk/sha1.hpp b/Shared/sdk/sha1.hpp index a160d1870ac..d73b9128dee 100644 --- a/Shared/sdk/sha1.hpp +++ b/Shared/sdk/sha1.hpp @@ -31,13 +31,13 @@ #include "sha1.h" #if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST) -#include + #include #endif #if defined(POLARSSL_PLATFORM_C) -#include "polarssl/platform.h" + #include "polarssl/platform.h" #else -#define polarssl_printf printf + #define polarssl_printf printf #endif /* Implementation that should never be optimized out by the compiler */ @@ -50,28 +50,25 @@ static void polarssl_zeroize(void* v, size_t n) #if !defined(POLARSSL_SHA1_ALT) -/* - * 32-bit integer manipulation macros (big endian) - */ -#ifndef GET_UINT32_BE -#define GET_UINT32_BE(n,b,i) \ -{ \ - (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ - | ( (uint32_t) (b)[(i) + 1] << 16 ) \ - | ( (uint32_t) (b)[(i) + 2] << 8 ) \ - | ( (uint32_t) (b)[(i) + 3] ); \ -} -#endif - -#ifndef PUT_UINT32_BE -#define PUT_UINT32_BE(n,b,i) \ -{ \ - (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ - (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ - (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ - (b)[(i) + 3] = (unsigned char) ( (n) ); \ -} -#endif + /* + * 32-bit integer manipulation macros (big endian) + */ + #ifndef GET_UINT32_BE + #define GET_UINT32_BE(n, b, i) \ + { \ + (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); \ + } + #endif + + #ifndef PUT_UINT32_BE + #define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (unsigned char)((n) >> 24); \ + (b)[(i) + 1] = (unsigned char)((n) >> 16); \ + (b)[(i) + 2] = (unsigned char)((n) >> 8); \ + (b)[(i) + 3] = (unsigned char)((n)); \ + } + #endif void sha1_init(sha1_context* ctx) { @@ -122,19 +119,15 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) GET_UINT32_BE(W[14], data, 56); GET_UINT32_BE(W[15], data, 60); -#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + #define S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) -#define R(t) \ -( \ - temp = W[( t - 3 ) & 0x0F] ^ W[( t - 8 ) & 0x0F] ^ \ - W[( t - 14 ) & 0x0F] ^ W[ t & 0x0F], \ - ( W[t & 0x0F] = S(temp,1) ) \ -) + #define R(t) (temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ W[t & 0x0F], (W[t & 0x0F] = S(temp, 1))) -#define P(a,b,c,d,e,x) \ -{ \ - e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ -} + #define P(a, b, c, d, e, x) \ + { \ + e += S(a, 5) + F(b, c, d) + K + x; \ + b = S(b, 30); \ + } A = ctx->state[0]; B = ctx->state[1]; @@ -142,8 +135,8 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) D = ctx->state[3]; E = ctx->state[4]; -#define F(x,y,z) (z ^ (x & (y ^ z))) -#define K 0x5A827999 + #define F(x, y, z) (z ^ (x & (y ^ z))) + #define K 0x5A827999 P(A, B, C, D, E, W[0]); P(E, A, B, C, D, W[1]); @@ -166,11 +159,11 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) P(C, D, E, A, B, R(18)); P(B, C, D, E, A, R(19)); -#undef K -#undef F + #undef K + #undef F -#define F(x,y,z) (x ^ y ^ z) -#define K 0x6ED9EBA1 + #define F(x, y, z) (x ^ y ^ z) + #define K 0x6ED9EBA1 P(A, B, C, D, E, R(20)); P(E, A, B, C, D, R(21)); @@ -193,11 +186,11 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) P(C, D, E, A, B, R(38)); P(B, C, D, E, A, R(39)); -#undef K -#undef F + #undef K + #undef F -#define F(x,y,z) ((x & y) | (z & (x | y))) -#define K 0x8F1BBCDC + #define F(x, y, z) ((x & y) | (z & (x | y))) + #define K 0x8F1BBCDC P(A, B, C, D, E, R(40)); P(E, A, B, C, D, R(41)); @@ -220,11 +213,11 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) P(C, D, E, A, B, R(58)); P(B, C, D, E, A, R(59)); -#undef K -#undef F + #undef K + #undef F -#define F(x,y,z) (x ^ y ^ z) -#define K 0xCA62C1D6 + #define F(x, y, z) (x ^ y ^ z) + #define K 0xCA62C1D6 P(A, B, C, D, E, R(60)); P(E, A, B, C, D, R(61)); @@ -247,11 +240,11 @@ void sha1_process(sha1_context* ctx, const unsigned char data[64]) P(C, D, E, A, B, R(78)); P(B, C, D, E, A, R(79)); -#undef K -#undef F -#undef S -#undef R -#undef P + #undef K + #undef F + #undef S + #undef R + #undef P ctx->state[0] += A; ctx->state[1] += B; diff --git a/Shared/sdk/sha2.h b/Shared/sdk/sha2.h index 2c0e59b20e5..dacedb92866 100644 --- a/Shared/sdk/sha2.h +++ b/Shared/sdk/sha2.h @@ -34,18 +34,18 @@ #ifndef SHA2_H #define SHA2_H -#define SHA224_DIGEST_SIZE ( 224 / 8) -#define SHA256_DIGEST_SIZE ( 256 / 8) -#define SHA384_DIGEST_SIZE ( 384 / 8) -#define SHA512_DIGEST_SIZE ( 512 / 8) +#define SHA224_DIGEST_SIZE (224 / 8) +#define SHA256_DIGEST_SIZE (256 / 8) +#define SHA384_DIGEST_SIZE (384 / 8) +#define SHA512_DIGEST_SIZE (512 / 8) -#define SHA256_BLOCK_SIZE ( 512 / 8) -#define SHA512_BLOCK_SIZE (1024 / 8) -#define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE -#define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE +#define SHA256_BLOCK_SIZE (512 / 8) +#define SHA512_BLOCK_SIZE (1024 / 8) +#define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE +#define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE #ifndef SHA2_TYPES -#define SHA2_TYPES + #define SHA2_TYPES typedef unsigned char uint8; typedef unsigned int uint32; typedef unsigned long long uint64; diff --git a/Shared/sdk/sha2.hpp b/Shared/sdk/sha2.hpp index bf633d1dbd4..d08b1c19c72 100644 --- a/Shared/sdk/sha2.hpp +++ b/Shared/sdk/sha2.hpp @@ -32,100 +32,87 @@ */ #if 0 -#define UNROLL_LOOPS /* Enable loops unrolling */ + #define UNROLL_LOOPS /* Enable loops unrolling */ #endif #include #include "sha2.h" -#define SHFR(x, n) (x >> n) +#define SHFR(x, n) (x >> n) #define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) #define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) #define CH(x, y, z) ((x & y) ^ (~x & z)) #define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) -#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) -#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) +#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) +#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) +#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) #define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10)) #define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39)) #define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41)) -#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7)) -#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6)) - -#define UNPACK32(x, str) \ -{ \ - *((str) + 3) = (uint8) ((x) ); \ - *((str) + 2) = (uint8) ((x) >> 8); \ - *((str) + 1) = (uint8) ((x) >> 16); \ - *((str) + 0) = (uint8) ((x) >> 24); \ -} +#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7)) +#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6)) + +#define UNPACK32(x, str) \ + { \ + *((str) + 3) = (uint8)((x)); \ + *((str) + 2) = (uint8)((x) >> 8); \ + *((str) + 1) = (uint8)((x) >> 16); \ + *((str) + 0) = (uint8)((x) >> 24); \ + } -#define PACK32(str, x) \ -{ \ - *(x) = ((uint32) *((str) + 3) ) \ - | ((uint32) *((str) + 2) << 8) \ - | ((uint32) *((str) + 1) << 16) \ - | ((uint32) *((str) + 0) << 24); \ -} +#define PACK32(str, x) \ + { \ + *(x) = ((uint32) * ((str) + 3)) | ((uint32) * ((str) + 2) << 8) | ((uint32) * ((str) + 1) << 16) | ((uint32) * ((str) + 0) << 24); \ + } -#define 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 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 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); \ -} +#define 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); \ + } /* Macros used for loops unrolling */ -#define SHA256_SCR(i) \ -{ \ - w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \ - + SHA256_F3(w[i - 15]) + w[i - 16]; \ -} +#define SHA256_SCR(i) \ + { \ + w[i] = SHA256_F4(w[i - 2]) + w[i - 7] + SHA256_F3(w[i - 15]) + w[i - 16]; \ + } -#define SHA512_SCR(i) \ -{ \ - w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \ - + SHA512_F3(w[i - 15]) + w[i - 16]; \ -} +#define SHA512_SCR(i) \ + { \ + w[i] = SHA512_F4(w[i - 2]) + w[i - 7] + SHA512_F3(w[i - 15]) + w[i - 16]; \ + } -#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ -{ \ - t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ - + sha256_k[j] + w[j]; \ - t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ - wv[d] += t1; \ - wv[h] = t1 + t2; \ -} +#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ + { \ + t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) + sha256_k[j] + w[j]; \ + t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ + wv[d] += t1; \ + wv[h] = t1 + t2; \ + } -#define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \ -{ \ - t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ - + sha512_k[j] + w[j]; \ - t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ - wv[d] += t1; \ - wv[h] = t1 + t2; \ -} +#define SHA512_EXP(a, b, c, d, e, f, g, h, j) \ + { \ + t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) + sha512_k[j] + w[j]; \ + t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ + wv[d] += t1; \ + wv[h] = t1 + t2; \ + } uint32 sha224_h0[8] = {0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4}; @@ -955,8 +942,8 @@ void sha224_final(sha224_ctx* ctx, unsigned char* digest) /* FIPS 180-2 Validation tests */ -#include -#include + #include + #include void test(const char* vector, unsigned char* digest, unsigned int digest_size) { diff --git a/Shared/sdk/version.h b/Shared/sdk/version.h index 301d064f13c..828d12b7ed1 100644 --- a/Shared/sdk/version.h +++ b/Shared/sdk/version.h @@ -42,99 +42,100 @@ *******************************************************************************/ // New version info -#define MTASA_VERSION_MAJOR 1 -#define MTASA_VERSION_MINOR 7 -#define MTASA_VERSION_MAINTENANCE 0 -#define MTASA_VERSION_TYPE VERSION_TYPE_CUSTOM -#define MTASA_VERSION_BUILD 0 +#define MTASA_VERSION_MAJOR 1 +#define MTASA_VERSION_MINOR 7 +#define MTASA_VERSION_MAINTENANCE 0 +#define MTASA_VERSION_TYPE VERSION_TYPE_CUSTOM +#define MTASA_VERSION_BUILD 0 #include "../build_overrides.h" // Old version info -#define MTA_DM_VERSION ( ( ( MTASA_VERSION_MAJOR ) << 8 ) | ( ( MTASA_VERSION_MINOR ) << 4 ) | ( ( MTASA_VERSION_MAINTENANCE ) << 0 ) ) +#define MTA_DM_VERSION (((MTASA_VERSION_MAJOR) << 8) | ((MTASA_VERSION_MINOR) << 4) | ((MTASA_VERSION_MAINTENANCE) << 0)) #if MTASA_VERSION_MAINTENANCE == 0 - #define MTA_DM_VERSIONSTRING QUOTE_DEFINE ( MTASA_VERSION_MAJOR ) "." QUOTE_DEFINE ( MTASA_VERSION_MINOR ) + #define MTA_DM_VERSIONSTRING QUOTE_DEFINE(MTASA_VERSION_MAJOR) "." QUOTE_DEFINE(MTASA_VERSION_MINOR) #else - #define MTA_DM_VERSIONSTRING QUOTE_DEFINE ( MTASA_VERSION_MAJOR ) "." QUOTE_DEFINE ( MTASA_VERSION_MINOR ) "." QUOTE_DEFINE ( MTASA_VERSION_MAINTENANCE ) + #define MTA_DM_VERSIONSTRING QUOTE_DEFINE(MTASA_VERSION_MAJOR) "." QUOTE_DEFINE(MTASA_VERSION_MINOR) "." QUOTE_DEFINE(MTASA_VERSION_MAINTENANCE) #endif #ifdef MTA_CLIENT -#define MTA_DM_FULL_STRING "MTA:SA Client" + #define MTA_DM_FULL_STRING "MTA:SA Client" #else -#define MTA_DM_FULL_STRING "MTA:SA Server" + #define MTA_DM_FULL_STRING "MTA:SA Server" #endif // Compile types -#define VERSION_TYPE_CUSTOM 0x01 -#define VERSION_TYPE_EXPERIMENTAL 0x03 -#define VERSION_TYPE_UNSTABLE 0x05 -#define VERSION_TYPE_UNTESTED 0x07 -#define VERSION_TYPE_RELEASE 0x09 +#define VERSION_TYPE_CUSTOM 0x01 +#define VERSION_TYPE_EXPERIMENTAL 0x03 +#define VERSION_TYPE_UNSTABLE 0x05 +#define VERSION_TYPE_UNTESTED 0x07 +#define VERSION_TYPE_RELEASE 0x09 #define QUOTE_DEFINE2(c) #c -#define QUOTE_DEFINE(x) QUOTE_DEFINE2(x) +#define QUOTE_DEFINE(x) QUOTE_DEFINE2(x) // Implement compile types #if MTASA_VERSION_TYPE == VERSION_TYPE_CUSTOM - #define MTA_DM_BUILDTYPE "custom" - #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE - #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE + #define MTA_DM_BUILDTYPE "custom" + #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE + #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE #elif MTASA_VERSION_TYPE == VERSION_TYPE_UNSTABLE - #define MTA_DM_BUILDTYPE "unstable" - #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE ( MTASA_VERSION_BUILD ) - #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE ( MTASA_VERSION_BUILD ) + #define MTA_DM_BUILDTYPE "unstable" + #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE(MTASA_VERSION_BUILD) + #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE(MTASA_VERSION_BUILD) #elif MTASA_VERSION_TYPE == VERSION_TYPE_UNTESTED - #define MTA_DM_BUILDTYPE "untested" - #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE ( MTASA_VERSION_BUILD ) - #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE ( MTASA_VERSION_BUILD ) + #define MTA_DM_BUILDTYPE "untested" + #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE(MTASA_VERSION_BUILD) + #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE(MTASA_VERSION_BUILD) #define MTA_DM_PUBLIC_CONNECTIONS - #define MTA_DM_EXPIRE_DAYS 60 + #define MTA_DM_EXPIRE_DAYS 60 #elif MTASA_VERSION_TYPE == VERSION_TYPE_RELEASE - #define MTA_DM_BUILDTYPE "release" - #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING - #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE ( MTASA_VERSION_BUILD ) + #define MTA_DM_BUILDTYPE "release" + #define MTA_DM_BUILDTAG_SHORT MTA_DM_VERSIONSTRING + #define MTA_DM_BUILDTAG_LONG MTA_DM_VERSIONSTRING "-" MTA_DM_BUILDTYPE "-" QUOTE_DEFINE(MTASA_VERSION_BUILD) #define MTA_DM_PUBLIC_CONNECTIONS #else #error "Incorrect MTASA_VERSION_TYPE" #endif -#define _ASE_VERSION QUOTE_DEFINE(MTASA_VERSION_MAJOR) "." QUOTE_DEFINE(MTASA_VERSION_MINOR) -#define _NETCODE_VERSION_BRANCH_ID 0x4 // Use 0x1 - 0xF to indicate an incompatible branch is being used (0x0 is reserved, 0x4 is trunk) -#define _CLIENT_NET_MODULE_VERSION 0x0B5 // (0x000 - 0xfff) Lvl9 wizards only -#define _SERVER_NET_MODULE_VERSION 0x0AD // (0x000 - 0xfff) Lvl9 wizards only -#define _NETCODE_VERSION 0x1DE // (0x000 - 0xfff) Increment when net messages change (pre-release) +#define _ASE_VERSION QUOTE_DEFINE(MTASA_VERSION_MAJOR) "." QUOTE_DEFINE(MTASA_VERSION_MINOR) +#define _NETCODE_VERSION_BRANCH_ID 0x4 // Use 0x1 - 0xF to indicate an incompatible branch is being used (0x0 is reserved, 0x4 is trunk) +#define _CLIENT_NET_MODULE_VERSION 0x0B5 // (0x000 - 0xfff) Lvl9 wizards only +#define _SERVER_NET_MODULE_VERSION 0x0AD // (0x000 - 0xfff) Lvl9 wizards only +#define _NETCODE_VERSION 0x1DE // (0x000 - 0xfff) Increment when net messages change (pre-release) // (0x000 - 0xfff) Update bitstream.h when net messages change (post-release). (Changing will also require additional backward compatibility code). #define MTA_DM_BITSTREAM_VERSION eBitStreamVersion::Latest // To avoid user confusion, make sure the ASE version matches only if communication is possible #if defined(MTA_DM_PUBLIC_CONNECTIONS) - #define MTA_DM_ASE_VERSION _ASE_VERSION - #define MTA_DM_NETCODE_VERSION _NETCODE_VERSION - #define MTA_DM_CLIENT_NET_MODULE_VERSION _CLIENT_NET_MODULE_VERSION - #define MTA_DM_SERVER_NET_MODULE_VERSION _SERVER_NET_MODULE_VERSION + #define MTA_DM_ASE_VERSION _ASE_VERSION + #define MTA_DM_NETCODE_VERSION _NETCODE_VERSION + #define MTA_DM_CLIENT_NET_MODULE_VERSION _CLIENT_NET_MODULE_VERSION + #define MTA_DM_SERVER_NET_MODULE_VERSION _SERVER_NET_MODULE_VERSION #else #if _NETCODE_VERSION_BRANCH_ID < 1 || _NETCODE_VERSION_BRANCH_ID > 15 #error "_NETCODE_VERSION_BRANCH_ID wrong" #endif - #define MTA_DM_ASE_VERSION _ASE_VERSION "n" - #define MTA_DM_NETCODE_VERSION ( _NETCODE_VERSION + ( _NETCODE_VERSION_BRANCH_ID << 12 ) ) - #define MTA_DM_CLIENT_NET_MODULE_VERSION ( _CLIENT_NET_MODULE_VERSION + ( 4 << 12 ) ) - #define MTA_DM_SERVER_NET_MODULE_VERSION _SERVER_NET_MODULE_VERSION + #define MTA_DM_ASE_VERSION _ASE_VERSION "n" + #define MTA_DM_NETCODE_VERSION (_NETCODE_VERSION + (_NETCODE_VERSION_BRANCH_ID << 12)) + #define MTA_DM_CLIENT_NET_MODULE_VERSION (_CLIENT_NET_MODULE_VERSION + (4 << 12)) + #define MTA_DM_SERVER_NET_MODULE_VERSION _SERVER_NET_MODULE_VERSION #endif // Handy self compile message #ifndef MTA_DM_PUBLIC_CONNECTIONS #if defined(SHOW_SELF_COMPILE_WARNING) && !defined(CI_BUILD) && !defined(MTA_CLIENT) - #pragma message("\n\ + #pragma message( \ + "\n\ ----------------------------------------------------------------------\n\ MTASA_VERSION_TYPE is not set to VERSION_TYPE_RELEASE\n\ Server will not work with release clients\n\ diff --git a/Shared/sdk/xml/CXML.h b/Shared/sdk/xml/CXML.h index 139ea350d66..db005aa84ee 100644 --- a/Shared/sdk/xml/CXML.h +++ b/Shared/sdk/xml/CXML.h @@ -19,7 +19,7 @@ class CXMLAttribute; typedef struct SXMLString { CXMLNode* node; - virtual ~SXMLString(){}; + virtual ~SXMLString() {}; } SXMLString; class CXML diff --git a/Shared/sdk/xml/CXMLAttribute.h b/Shared/sdk/xml/CXMLAttribute.h index ae7772f9ff7..9e1ca230df6 100644 --- a/Shared/sdk/xml/CXMLAttribute.h +++ b/Shared/sdk/xml/CXMLAttribute.h @@ -17,7 +17,7 @@ class CXMLAttribute : public CXMLCommon { public: - virtual ~CXMLAttribute(){}; + virtual ~CXMLAttribute() {}; virtual const std::string GetName() const = 0; virtual const std::string& GetValue() const = 0; diff --git a/Shared/sdk/xml/CXMLCommon.h b/Shared/sdk/xml/CXMLCommon.h index 96de694c5f7..fbff75e244c 100644 --- a/Shared/sdk/xml/CXMLCommon.h +++ b/Shared/sdk/xml/CXMLCommon.h @@ -23,7 +23,7 @@ enum eXMLClass class CXMLCommon { public: - virtual ~CXMLCommon(){}; + virtual ~CXMLCommon() {}; virtual eXMLClass GetClassType() = 0; virtual unsigned long GetID() = 0; diff --git a/Shared/sdk/xml/CXMLFile.h b/Shared/sdk/xml/CXMLFile.h index ab8f794cac7..ed57a77c371 100644 --- a/Shared/sdk/xml/CXMLFile.h +++ b/Shared/sdk/xml/CXMLFile.h @@ -22,7 +22,7 @@ class CXMLNode; class CXMLFile : public CXMLCommon { public: - virtual ~CXMLFile(){}; + virtual ~CXMLFile() {}; virtual const char* GetFilename() = 0; virtual void SetFilename(const char* szFilename) = 0; diff --git a/Shared/sdk/xml/CXMLNode.h b/Shared/sdk/xml/CXMLNode.h index 133687b36eb..d3974c7af6b 100644 --- a/Shared/sdk/xml/CXMLNode.h +++ b/Shared/sdk/xml/CXMLNode.h @@ -19,7 +19,7 @@ class CXMLNode : public CXMLCommon { public: - virtual ~CXMLNode(){}; + virtual ~CXMLNode() {}; virtual CXMLNode* CreateSubNode(const char* szTagName, CXMLNode* pInsertAfter = nullptr) = 0; virtual void DeleteSubNode(CXMLNode* pNode) = 0; diff --git a/utils/clang-format.ps1 b/utils/clang-format.ps1 old mode 100644 new mode 100755