diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 0000000..d2ff733 --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,5 @@ +# Repository-relative exclusions for shared FormatValidation. +# Only src/, include/, and tests/ are selected; dependencies and artifacts are excluded. +**/thirdparty/** +**/build/** +**/install/** diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 0000000..e7736b0 --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,31 @@ +name: clang-format + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: clang-format-${{ github.ref }} + cancel-in-progress: true + +jobs: + clang-format: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install pinned formatter + run: python -m pip install clang-format==23.1.3 + - name: Configure formatting targets + run: cmake -S . -B build/format -DFORMAT_VALIDATION_ONLY=ON + - name: Check all owned C/C++ sources + run: cmake --build build/format --target format-check diff --git a/.gitignore b/.gitignore index f87b4da..def45c3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ __pycache__/ *.pyc *.user + +# Generated from the shared FormatValidation source during CMake configuration. +/.clang-format diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c8001c..76530ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,10 @@ cmake_minimum_required(VERSION 3.21) +option(FORMAT_VALIDATION_ONLY "Configure only clang-format targets without native dependencies" OFF) +if(FORMAT_VALIDATION_ONLY) + project(FormatValidation LANGUAGES NONE) + include(cmake/FormatValidation.cmake) + return() +endif() cmake_policy(SET CMP0091 NEW) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") project(SteamScreenshots LANGUAGES C CXX) @@ -107,3 +113,6 @@ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) metahooksv_add_launch_game() endif() endif() + +# Shared formatting targets are explicit; ordinary native builds do not run them. +include(cmake/FormatValidation.cmake) diff --git a/README.md b/README.md index ed497fb..c710dd1 100644 --- a/README.md +++ b/README.md @@ -48,3 +48,36 @@ Merge the extracted `svencoop/` into the target mod directory (`svencoop/` for S ## License Licensed under the [MIT License](LICENSE); each dependency keeps its own license. + +## C/C++ formatting + +Formatting uses [MetaHookSv/FormatValidation](https://github.com/MetaHookSv/FormatValidation) +and clang-format **23.1.3**, with the DiligentCore style (4 spaces, preserved include +order). Install the formatter for the Python interpreter used by CMake: + +```sh +python -m pip install clang-format==23.1.3 +cmake -S . -B build/format "-DFORMAT_VALIDATION_ONLY=ON" +cmake --build build/format --target format-check +cmake --build build/format --target format +``` + +The format-only configuration needs CMake 3.21+, Git, Python 3.9+ (CI uses 3.12), +and a build generator; `-G Ninja` works without Visual Studio. It prepares no native +SDK or game dependencies. Formatting targets are explicit and are not part of a +normal DLL build. With a Visual Studio generator, add `--config Debug` or +`--config Release` when building a formatting target. + +The aggregate provides `FORMAT_VALIDATION_SOURCE_PATH=thirdparty/FormatValidation`. +Standalone components accept that CMake variable or its environment counterpart; +if empty, FetchContent downloads the fixed tooling commit. Quote relative paths, +for example `"-DFORMAT_VALIDATION_SOURCE_PATH=../../thirdparty/FormatValidation"`. +Configuration generates the ignored root `.clang-format` for editors; change the +shared style rather than that generated copy. An optional +`FORMAT_VALIDATION_CLANG_FORMAT_EXECUTABLE` selects an explicit formatter, whose +version must still match the pin. + +Checks cover owned C/C++ files in `src/`, `include/`, and `tests/`, including +non-ignored new files. Repository-relative exclusions live in `.clang-format-ignore`. +Third-party sources and build artifacts are excluded. The `clang-format` workflow +checks the full scope on pushes, pull requests, and manual runs. diff --git a/README.zh-CN.md b/README.zh-CN.md index a807b07..f57bda7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -46,3 +46,33 @@ SteamScreenshots 是 MetaHook 截图插件,本插件会接管引擎的 `snapsh ## 许可证 项目采用 [MIT License](LICENSE);各依赖保留自己的许可证。 + +## C/C++ 格式化 + +使用 [MetaHookSv/FormatValidation](https://github.com/MetaHookSv/FormatValidation) +共享工具及固定版本 **clang-format 23.1.3**,采用 DiligentCore 风格(4 空格,保留 +include 顺序)。为 CMake 使用的 Python 解释器安装格式工具: + +```sh +python -m pip install clang-format==23.1.3 +cmake -S . -B build/format "-DFORMAT_VALIDATION_ONLY=ON" +cmake --build build/format --target format-check +cmake --build build/format --target format +``` + +格式专用配置需要 CMake 3.21+、Git、Python 3.9+(CI 使用 3.12)及构建生成器; +使用 `-G Ninja` 可无需 Visual Studio。它不准备原生 SDK 或游戏依赖。 +格式目标需显式执行,不加入普通 DLL 构建。使用 Visual Studio 生成器时,执行目标 +需追加 `--config Debug` 或 `--config Release`。 + +聚合仓库注入 `FORMAT_VALIDATION_SOURCE_PATH=thirdparty/FormatValidation`。 +独立组件支持该 CMake 参数及同名环境变量;为空时通过 FetchContent 获取固定工具 +提交。相对路径应加引号,例如 +`"-DFORMAT_VALIDATION_SOURCE_PATH=../../thirdparty/FormatValidation"`。 +配置时在仓库根目录生成被 gitignore 的 `.clang-format` 供编辑器使用;格式规则应 +在共享仓库修改,不修改生成副本。可通过 `FORMAT_VALIDATION_CLANG_FORMAT_EXECUTABLE` +指定工具路径,但版本仍须与固定版本一致。 + +检查覆盖 `src/`、`include/`、`tests/` 中维护的 C/C++ 文件,包括未被 Git 忽略的新文件。 +相对仓库根目录的排除规则位于 `.clang-format-ignore`;第三方源和构建产物不纳入检查。 +`clang-format` workflow 在 push、pull request 和手动运行时执行全量检查。 diff --git a/cmake/FormatValidation.cmake b/cmake/FormatValidation.cmake new file mode 100644 index 0000000..505bd51 --- /dev/null +++ b/cmake/FormatValidation.cmake @@ -0,0 +1,26 @@ +# Shared tool implementation; only this dependency bootstrap belongs to the consumer. +if(NOT DEFINED FORMAT_VALIDATION_SOURCE_PATH) + set(FORMAT_VALIDATION_SOURCE_PATH "$ENV{FORMAT_VALIDATION_SOURCE_PATH}" CACHE PATH + "FormatValidation source tree; empty fetches the pinned tooling") +endif() +if(FORMAT_VALIDATION_SOURCE_PATH) + get_filename_component(_format_validation_source "${FORMAT_VALIDATION_SOURCE_PATH}" + ABSOLUTE BASE_DIR "${CMAKE_CURRENT_LIST_DIR}/..") +else() + include(FetchContent) + FetchContent_Declare(steamscreenshots_format_validation + GIT_REPOSITORY https://github.com/MetaHookSv/FormatValidation.git + GIT_TAG 13c9fabe058e1f887ad1b03bb6884de911192c6a # v1.0.0; retained immutable tooling commit + GIT_SUBMODULES "" + # Populate the tooling without configuring its own test project. + SOURCE_SUBDIR cmake) + FetchContent_MakeAvailable(steamscreenshots_format_validation) + set(_format_validation_source "${steamscreenshots_format_validation_SOURCE_DIR}") +endif() +foreach(_format_validation_file .clang-format clang-format-validate.py cmake/FormatValidation.cmake) + if(NOT EXISTS "${_format_validation_source}/${_format_validation_file}") + message(FATAL_ERROR "FORMAT_VALIDATION_SOURCE_PATH is missing ${_format_validation_file}: ${_format_validation_source}") + endif() +endforeach() +include("${_format_validation_source}/cmake/FormatValidation.cmake") +format_validation_add_component(SteamScreenshots "${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/src/exportfuncs.cpp b/src/exportfuncs.cpp index e4b9fa4..2ce3791 100644 --- a/src/exportfuncs.cpp +++ b/src/exportfuncs.cpp @@ -8,267 +8,267 @@ #include "gl_capture.h" #include -cl_enginefunc_t gEngfuncs; -engine_studio_api_t IEngineStudio; -r_studio_interface_t **gpStudioInterface; +cl_enginefunc_t gEngfuncs; +engine_studio_api_t IEngineStudio; +r_studio_interface_t** gpStudioInterface; char g_szServerName[256] = {0}; namespace { - bool g_bLoggedSteamUserUnavailable = false; - bool g_bLoggedSteamScreenshotsWriteUnavailable = false; +bool g_bLoggedSteamUserUnavailable = false; +bool g_bLoggedSteamScreenshotsWriteUnavailable = false; - void Con_Printf_Once(bool& bAlreadyPrinted, const char* pszMessage) - { - if (bAlreadyPrinted) - return; +void Con_Printf_Once(bool& bAlreadyPrinted, const char* pszMessage) +{ + if (bAlreadyPrinted) + return; - bAlreadyPrinted = true; - gEngfuncs.Con_Printf(pszMessage); - } + bAlreadyPrinted = true; + gEngfuncs.Con_Printf(pszMessage); } +} // namespace static hook_t* g_pPresentHook = NULL; class CSnapshotManager { public: - static void __cdecl OnSnapshotCallback(void*, uint32_t screenshot, int32_t result); - void TryRegisterCallback(); - void UnregisterCallback(); - SteamBridgeContextHandle Context() const { return m_Context; } + static void __cdecl OnSnapshotCallback(void*, uint32_t screenshot, int32_t result); + void TryRegisterCallback(); + void UnregisterCallback(); + SteamBridgeContextHandle Context() const { return m_Context; } private: - bool m_bCallbackRegistered = false; - SteamBridgeContextHandle m_Context = nullptr; + bool m_bCallbackRegistered = false; + SteamBridgeContextHandle m_Context = nullptr; }; CSnapshotManager g_SnapshotManager; void CSnapshotManager::TryRegisterCallback() { - if (m_bCallbackRegistered) - return; + if (m_bCallbackRegistered) + return; - if (!m_Context) - m_Context = SteamBridge_CreateContext(); - if ((SteamBridge_GetCapabilities(m_Context) & (SB_CAP_SCREENSHOTS | SB_CAP_USER)) != (SB_CAP_SCREENSHOTS | SB_CAP_USER)) - return; + if (!m_Context) + m_Context = SteamBridge_CreateContext(); + if ((SteamBridge_GetCapabilities(m_Context) & (SB_CAP_SCREENSHOTS | SB_CAP_USER)) != (SB_CAP_SCREENSHOTS | SB_CAP_USER)) + return; - m_bCallbackRegistered = SteamBridge_SubscribeScreenshots(m_Context, OnSnapshotCallback, this) == SB_OK; + m_bCallbackRegistered = SteamBridge_SubscribeScreenshots(m_Context, OnSnapshotCallback, this) == SB_OK; } void CSnapshotManager::UnregisterCallback() { - SteamBridge_DestroyContext(m_Context); - m_Context = nullptr; - m_bCallbackRegistered = false; + SteamBridge_DestroyContext(m_Context); + m_Context = nullptr; + m_bCallbackRegistered = false; } void __cdecl CSnapshotManager::OnSnapshotCallback(void* opaque, uint32_t screenshot, int32_t result) { - auto context = static_cast(opaque)->Context(); - - if (result == SB_STEAM_RESULT_OK) - { - SteamBridge_SetScreenshotLocation(context, screenshot, g_szServerName); - - uint64_t steamId = 0; - if (SteamBridge_GetSteamID(context, &steamId) == SB_OK) - { - SteamBridge_TagScreenshotUser(context, screenshot, steamId); - } - else - { - Con_Printf_Once(g_bLoggedSteamUserUnavailable, "[SteamScreenshots] Cannot tag user because Steam user interface is unavailable.\n"); - } - - gEngfuncs.Con_Printf("[SteamScreenshots] Snapshot saved.\n"); - } - else if (result == SB_STEAM_RESULT_IO_FAILURE) - { - gEngfuncs.Con_Printf("[SteamScreenshots] Cannot save snapshot. Got an IO error.\n"); - } - else - { - gEngfuncs.Con_Printf("[SteamScreenshots] Cannot save snapshot. Got an unknown error.\n"); - } + auto context = static_cast(opaque)->Context(); + + if (result == SB_STEAM_RESULT_OK) + { + SteamBridge_SetScreenshotLocation(context, screenshot, g_szServerName); + + uint64_t steamId = 0; + if (SteamBridge_GetSteamID(context, &steamId) == SB_OK) + { + SteamBridge_TagScreenshotUser(context, screenshot, steamId); + } + else + { + Con_Printf_Once(g_bLoggedSteamUserUnavailable, "[SteamScreenshots] Cannot tag user because Steam user interface is unavailable.\n"); + } + + gEngfuncs.Con_Printf("[SteamScreenshots] Snapshot saved.\n"); + } + else if (result == SB_STEAM_RESULT_IO_FAILURE) + { + gEngfuncs.Con_Printf("[SteamScreenshots] Cannot save snapshot. Got an IO error.\n"); + } + else + { + gEngfuncs.Con_Printf("[SteamScreenshots] Cannot save snapshot. Got an unknown error.\n"); + } } void HUD_Shutdown(void) { - ShutdownSteamBridge(); + ShutdownSteamBridge(); - GL_ShutdownCapture(); + GL_ShutdownCapture(); - gExportfuncs.HUD_Shutdown(); + gExportfuncs.HUD_Shutdown(); } void ShutdownSteamBridge() { - g_SnapshotManager.UnregisterCallback(); + g_SnapshotManager.UnregisterCallback(); } void ScreenshotCallback(void* pBuf, size_t cbBufSize, int width, int height) { - uint32_t screenshot = 0; - if (SteamBridge_WriteScreenshot(g_SnapshotManager.Context(), pBuf, static_cast(cbBufSize), width, height, &screenshot) != SB_OK) - { - Con_Printf_Once(g_bLoggedSteamScreenshotsWriteUnavailable, "[SteamScreenshots] Cannot write screenshot because Steam screenshots interface is unavailable.\n"); - } + uint32_t screenshot = 0; + if (SteamBridge_WriteScreenshot(g_SnapshotManager.Context(), pBuf, static_cast(cbBufSize), width, height, &screenshot) != SB_OK) + { + Con_Printf_Once(g_bLoggedSteamScreenshotsWriteUnavailable, "[SteamScreenshots] Cannot write screenshot because Steam screenshots interface is unavailable.\n"); + } } void __cdecl SDL_GL_SwapWindow(void* window) { - GL_CapturePendingBeforeSwap(ScreenshotCallback); + GL_CapturePendingBeforeSwap(ScreenshotCallback); - // With Renderer enabled, its final blit runs before this engine flip. - gPrivateFuncs.SDL_GL_SwapWindow(window); + // With Renderer enabled, its final blit runs before this engine flip. + gPrivateFuncs.SDL_GL_SwapWindow(window); } void __cdecl Sys_VID_FlipScreen(void) { - // With Renderer enabled, its final blit runs before this engine flip. - GL_CapturePendingBeforeSwap(ScreenshotCallback); + // With Renderer enabled, its final blit runs before this engine flip. + GL_CapturePendingBeforeSwap(ScreenshotCallback); - gPrivateFuncs.Sys_VID_FlipScreen(); + gPrivateFuncs.Sys_VID_FlipScreen(); } void InstallSDL2Hook() { - if (g_pPresentHook) - return; + if (g_pPresentHook) + return; - auto engine = g_pMetaHookAPI->GetEngineModule(); - if (engine && g_pMetaHookAPI->ModuleHasImportEx(engine, "SDL2.dll", "SDL_GL_SwapWindow")) - { - g_pPresentHook = g_pMetaHookAPI->IATHook(engine, "SDL2.dll", "SDL_GL_SwapWindow", SDL_GL_SwapWindow, (void**)&gPrivateFuncs.SDL_GL_SwapWindow); - } + auto engine = g_pMetaHookAPI->GetEngineModule(); + if (engine && g_pMetaHookAPI->ModuleHasImportEx(engine, "SDL2.dll", "SDL_GL_SwapWindow")) + { + g_pPresentHook = g_pMetaHookAPI->IATHook(engine, "SDL2.dll", "SDL_GL_SwapWindow", SDL_GL_SwapWindow, (void**)&gPrivateFuncs.SDL_GL_SwapWindow); + } - if (!g_pPresentHook) - gEngfuncs.Con_Printf("[SteamScreenshots] SDL hook unavailable; keeping the engine snapshot command.\n"); + if (!g_pPresentHook) + gEngfuncs.Con_Printf("[SteamScreenshots] SDL hook unavailable; keeping the engine snapshot command.\n"); } void InstallFlipScreenHook() { - if (g_pPresentHook) - return; - - if (gPrivateFuncs.VID_FlipScreen) - return; - - if (g_pInterface->MetaHookAPIVersion < 109) - { - gEngfuncs.Con_Printf("[SteamScreenshots] Gamedata API unavailable; keeping the engine snapshot command.\n"); - return; - } - - PVOID flipScreenSlot = NULL; - auto status = g_pMetaHookAPI->ResolveGameSymbol(g_pMetaHookAPI->GetEngineBase(), - "VID_FlipScreen", MH_GAMESYMBOL_KIND_GLOBAL, &flipScreenSlot); - if (status != MH_GAMESYMBOL_OK) - { - gEngfuncs.Con_Printf("[SteamScreenshots] VID_FlipScreen unavailable (%s); keeping the engine snapshot command.\n", - g_pMetaHookAPI->GetGameSymbolStatusString(status)); - return; - } - - // The gamedata GLOBAL is the engine's own flip function-pointer slot: GL_EndRendering - // calls through it and Sys_InitGame writes it once at startup, so swapping the pointer - // redirects every flip without patching code. - if (flipScreenSlot) - { - gPrivateFuncs.VID_FlipScreen = (void(__cdecl**)(void))flipScreenSlot; - gPrivateFuncs.Sys_VID_FlipScreen = *gPrivateFuncs.VID_FlipScreen; - (*gPrivateFuncs.VID_FlipScreen) = Sys_VID_FlipScreen; - } - - if (!gPrivateFuncs.VID_FlipScreen) - gEngfuncs.Con_Printf("[SteamScreenshots] VID_FlipScreen hook unavailable; keeping the engine snapshot command.\n"); + if (g_pPresentHook) + return; + + if (gPrivateFuncs.VID_FlipScreen) + return; + + if (g_pInterface->MetaHookAPIVersion < 109) + { + gEngfuncs.Con_Printf("[SteamScreenshots] Gamedata API unavailable; keeping the engine snapshot command.\n"); + return; + } + + PVOID flipScreenSlot = NULL; + auto status = g_pMetaHookAPI->ResolveGameSymbol(g_pMetaHookAPI->GetEngineBase(), + "VID_FlipScreen", MH_GAMESYMBOL_KIND_GLOBAL, &flipScreenSlot); + if (status != MH_GAMESYMBOL_OK) + { + gEngfuncs.Con_Printf("[SteamScreenshots] VID_FlipScreen unavailable (%s); keeping the engine snapshot command.\n", + g_pMetaHookAPI->GetGameSymbolStatusString(status)); + return; + } + + // The gamedata GLOBAL is the engine's own flip function-pointer slot: GL_EndRendering + // calls through it and Sys_InitGame writes it once at startup, so swapping the pointer + // redirects every flip without patching code. + if (flipScreenSlot) + { + gPrivateFuncs.VID_FlipScreen = (void(__cdecl**)(void))flipScreenSlot; + gPrivateFuncs.Sys_VID_FlipScreen = *gPrivateFuncs.VID_FlipScreen; + (*gPrivateFuncs.VID_FlipScreen) = Sys_VID_FlipScreen; + } + + if (!gPrivateFuncs.VID_FlipScreen) + gEngfuncs.Con_Printf("[SteamScreenshots] VID_FlipScreen hook unavailable; keeping the engine snapshot command.\n"); } void UninstallPresentHook() { - if (g_pPresentHook) - { - g_pMetaHookAPI->UnHook(g_pPresentHook); - g_pPresentHook = NULL; - gPrivateFuncs.SDL_GL_SwapWindow = NULL; - } - - if (gPrivateFuncs.VID_FlipScreen) - { - (*gPrivateFuncs.VID_FlipScreen) = gPrivateFuncs.Sys_VID_FlipScreen; - gPrivateFuncs.VID_FlipScreen = NULL; - gPrivateFuncs.Sys_VID_FlipScreen = NULL; - } + if (g_pPresentHook) + { + g_pMetaHookAPI->UnHook(g_pPresentHook); + g_pPresentHook = NULL; + gPrivateFuncs.SDL_GL_SwapWindow = NULL; + } + + if (gPrivateFuncs.VID_FlipScreen) + { + (*gPrivateFuncs.VID_FlipScreen) = gPrivateFuncs.Sys_VID_FlipScreen; + gPrivateFuncs.VID_FlipScreen = NULL; + gPrivateFuncs.Sys_VID_FlipScreen = NULL; + } } bool IsPresentHookInstalled() { - return g_pPresentHook != NULL || gPrivateFuncs.VID_FlipScreen != NULL; + return g_pPresentHook != NULL || gPrivateFuncs.VID_FlipScreen != NULL; } void VID_Snapshot_f(void) { - GL_RequestCapture(); + GL_RequestCapture(); } void HUD_Frame(double time) { - gExportfuncs.HUD_Frame(time); + gExportfuncs.HUD_Frame(time); - g_SnapshotManager.TryRegisterCallback(); + g_SnapshotManager.TryRegisterCallback(); - auto levelname = gEngfuncs.pfnGetLevelName(); + auto levelname = gEngfuncs.pfnGetLevelName(); - if (!levelname || !levelname[0]) - { - g_szServerName[0] = 0; - } + if (!levelname || !levelname[0]) + { + g_szServerName[0] = 0; + } - GL_QueryAsyncCapture(ScreenshotCallback); + GL_QueryAsyncCapture(ScreenshotCallback); } pfnUserMsgHook m_pfnServerName = NULL; -int __MsgFunc_ServerName(const char *pszName, int iSize, void *pbuf) +int __MsgFunc_ServerName(const char* pszName, int iSize, void* pbuf) { - BEGIN_READ(pbuf, iSize); + BEGIN_READ(pbuf, iSize); - char *szServerName = READ_STRING(); + char* szServerName = READ_STRING(); - strncpy(g_szServerName, szServerName, sizeof(g_szServerName) - 1); - g_szServerName[sizeof(g_szServerName) - 1] = 0; + strncpy(g_szServerName, szServerName, sizeof(g_szServerName) - 1); + g_szServerName[sizeof(g_szServerName) - 1] = 0; - if (m_pfnServerName) - return m_pfnServerName(pszName, iSize, pbuf); + if (m_pfnServerName) + return m_pfnServerName(pszName, iSize, pbuf); - return 0; + return 0; } void IN_ActivateMouse(void) { - gExportfuncs.IN_ActivateMouse(); + gExportfuncs.IN_ActivateMouse(); - static bool init = false; + static bool init = false; - if (!init) - { - InstallSDL2Hook(); - InstallFlipScreenHook(); + if (!init) + { + InstallSDL2Hook(); + InstallFlipScreenHook(); - if (IsPresentHookInstalled() && GL_InitCapture()) - { - //cmd "snapshot" is registered after HUD_Init - g_pMetaHookAPI->HookCmd("snapshot", VID_Snapshot_f); - } + if (IsPresentHookInstalled() && GL_InitCapture()) + { + //cmd "snapshot" is registered after HUD_Init + g_pMetaHookAPI->HookCmd("snapshot", VID_Snapshot_f); + } - m_pfnServerName = HOOK_MESSAGE(ServerName); + m_pfnServerName = HOOK_MESSAGE(ServerName); - g_SnapshotManager.TryRegisterCallback(); + g_SnapshotManager.TryRegisterCallback(); - init = true; - } + init = true; + } } diff --git a/src/exportfuncs.h b/src/exportfuncs.h index 2f990b1..b51dd0e 100644 --- a/src/exportfuncs.h +++ b/src/exportfuncs.h @@ -5,7 +5,7 @@ void IN_ActivateMouse(void); void HUD_Init(void); -void HUD_StudioEvent(const struct mstudioevent_s *ev, const struct cl_entity_s *ent); +void HUD_StudioEvent(const struct mstudioevent_s* ev, const struct cl_entity_s* ent); void HUD_Frame(double time); void HUD_Shutdown(void); void ShutdownSteamBridge(); diff --git a/src/gl_capture.cpp b/src/gl_capture.cpp index 94f1438..b752dd9 100644 --- a/src/gl_capture.cpp +++ b/src/gl_capture.cpp @@ -2,268 +2,272 @@ #include #include "gl_capture.h" -GLuint g_CapturePBO = 0; -GLsync g_CaptureSyncObject = 0; -int g_CaptureImageWidth = 0; -int g_CaptureImageHeight = 0; -void* g_CaptureImageBuffer = NULL; +GLuint g_CapturePBO = 0; +GLsync g_CaptureSyncObject = 0; +int g_CaptureImageWidth = 0; +int g_CaptureImageHeight = 0; +void* g_CaptureImageBuffer = NULL; bool (*g_pfnBeginCapture)(fnGLQueryCaptureCallback callback) = NULL; -bool g_CapturePending = false; +bool g_CapturePending = false; void GL_InitCaptureImageBuffer(int width, int height) { - g_CaptureImageBuffer = (byte*)malloc(width * height * 3); + g_CaptureImageBuffer = (byte*)malloc(width * height * 3); } void GL_ShutdownCaptureImageBuffer() { - if (g_CaptureImageBuffer) - { - free(g_CaptureImageBuffer); - g_CaptureImageBuffer = NULL; - } + if (g_CaptureImageBuffer) + { + free(g_CaptureImageBuffer); + g_CaptureImageBuffer = NULL; + } } void GL_InitCapturePBO(int width, int height) { - int originalPBO = 0; - glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); + int originalPBO = 0; + glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); - glGenBuffers(1, &g_CapturePBO); - glBindBuffer(GL_PIXEL_PACK_BUFFER, g_CapturePBO); - glBufferData(GL_PIXEL_PACK_BUFFER, width * height * 3, 0, GL_STREAM_READ); - glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); + glGenBuffers(1, &g_CapturePBO); + glBindBuffer(GL_PIXEL_PACK_BUFFER, g_CapturePBO); + glBufferData(GL_PIXEL_PACK_BUFFER, width * height * 3, 0, GL_STREAM_READ); + glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); } void GL_ShutdownCapturePBO() { - if (g_CapturePBO) - { - glDeleteBuffers(1, &g_CapturePBO); - g_CapturePBO = 0; - } + if (g_CapturePBO) + { + glDeleteBuffers(1, &g_CapturePBO); + g_CapturePBO = 0; + } } void GL_ShutdownCaptureSyncObject() { - if (g_CaptureSyncObject) - { - glDeleteSync(g_CaptureSyncObject); - g_CaptureSyncObject = 0; - } + if (g_CaptureSyncObject) + { + glDeleteSync(g_CaptureSyncObject); + g_CaptureSyncObject = 0; + } } static void GL_ReadCapturePixels(GLuint pbo, void* pixels) { - int originalFBO = 0; - int originalDefaultReadBuffer = 0; - int originalPBO = 0; - int originalAlignment = 0; - int originalRowLength = 0; - int originalSkipRows = 0; - int originalSkipPixels = 0; - const bool hasPBO = (GLEW_VERSION_2_1 || GLEW_ARB_pixel_buffer_object) && glBindBuffer; - - glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &originalFBO); - glGetIntegerv(GL_PACK_ALIGNMENT, &originalAlignment); - glGetIntegerv(GL_PACK_ROW_LENGTH, &originalRowLength); - glGetIntegerv(GL_PACK_SKIP_ROWS, &originalSkipRows); - glGetIntegerv(GL_PACK_SKIP_PIXELS, &originalSkipPixels); - if (hasPBO) - { - glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); - glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo); - } - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - glGetIntegerv(GL_READ_BUFFER, &originalDefaultReadBuffer); - glReadBuffer(GL_BACK); - - // Both the allocation and the image flip use tightly packed RGB rows. - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - glPixelStorei(GL_PACK_SKIP_ROWS, 0); - glPixelStorei(GL_PACK_SKIP_PIXELS, 0); - glReadPixels(0, 0, g_CaptureImageWidth, g_CaptureImageHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels); - glReadBuffer(originalDefaultReadBuffer); - - glPixelStorei(GL_PACK_ALIGNMENT, originalAlignment); - glPixelStorei(GL_PACK_ROW_LENGTH, originalRowLength); - glPixelStorei(GL_PACK_SKIP_ROWS, originalSkipRows); - glPixelStorei(GL_PACK_SKIP_PIXELS, originalSkipPixels); - if (hasPBO) - glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); - glBindFramebuffer(GL_READ_FRAMEBUFFER, originalFBO); + int originalFBO = 0; + int originalDefaultReadBuffer = 0; + int originalPBO = 0; + int originalAlignment = 0; + int originalRowLength = 0; + int originalSkipRows = 0; + int originalSkipPixels = 0; + const bool hasPBO = (GLEW_VERSION_2_1 || GLEW_ARB_pixel_buffer_object) && glBindBuffer; + + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &originalFBO); + glGetIntegerv(GL_PACK_ALIGNMENT, &originalAlignment); + glGetIntegerv(GL_PACK_ROW_LENGTH, &originalRowLength); + glGetIntegerv(GL_PACK_SKIP_ROWS, &originalSkipRows); + glGetIntegerv(GL_PACK_SKIP_PIXELS, &originalSkipPixels); + if (hasPBO) + { + glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); + glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo); + } + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glGetIntegerv(GL_READ_BUFFER, &originalDefaultReadBuffer); + glReadBuffer(GL_BACK); + + // Both the allocation and the image flip use tightly packed RGB rows. + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_SKIP_ROWS, 0); + glPixelStorei(GL_PACK_SKIP_PIXELS, 0); + glReadPixels(0, 0, g_CaptureImageWidth, g_CaptureImageHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels); + glReadBuffer(originalDefaultReadBuffer); + + glPixelStorei(GL_PACK_ALIGNMENT, originalAlignment); + glPixelStorei(GL_PACK_ROW_LENGTH, originalRowLength); + glPixelStorei(GL_PACK_SKIP_ROWS, originalSkipRows); + glPixelStorei(GL_PACK_SKIP_PIXELS, originalSkipPixels); + if (hasPBO) + glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); + glBindFramebuffer(GL_READ_FRAMEBUFFER, originalFBO); } bool GL_BeginSyncCapture(fnGLQueryCaptureCallback callback) { - int glwidth, glheight; - g_pMetaHookAPI->GetVideoMode(&glwidth, &glheight, NULL, NULL); - if (glwidth <= 0 || glheight <= 0) - return false; - - if (glwidth != g_CaptureImageWidth || glheight != g_CaptureImageHeight) - { - GL_ShutdownCaptureImageBuffer(); - g_CaptureImageWidth = glwidth; - g_CaptureImageHeight = glheight; - } - if (!g_CaptureImageBuffer) - GL_InitCaptureImageBuffer(glwidth, glheight); - if (!g_CaptureImageBuffer) - return false; - - GL_ReadCapturePixels(0, g_CaptureImageBuffer); - - GLubyte* pBuf = (GLubyte*)g_CaptureImageBuffer; - - //Flip the image up-side down - for (int y = 0; y < g_CaptureImageHeight / 2; ++y) { - for (int x = 0; x < g_CaptureImageWidth; ++x) { - byte temp[3]; - memcpy(temp, &pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], 3); - memcpy(&pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], &pBuf[y * g_CaptureImageWidth * 3 + x * 3], 3); - memcpy(&pBuf[y * g_CaptureImageWidth * 3 + x * 3], temp, 3); - } - } - - callback(g_CaptureImageBuffer, g_CaptureImageWidth * g_CaptureImageHeight * 3, g_CaptureImageWidth, g_CaptureImageHeight); - return true; + int glwidth, glheight; + g_pMetaHookAPI->GetVideoMode(&glwidth, &glheight, NULL, NULL); + if (glwidth <= 0 || glheight <= 0) + return false; + + if (glwidth != g_CaptureImageWidth || glheight != g_CaptureImageHeight) + { + GL_ShutdownCaptureImageBuffer(); + g_CaptureImageWidth = glwidth; + g_CaptureImageHeight = glheight; + } + if (!g_CaptureImageBuffer) + GL_InitCaptureImageBuffer(glwidth, glheight); + if (!g_CaptureImageBuffer) + return false; + + GL_ReadCapturePixels(0, g_CaptureImageBuffer); + + GLubyte* pBuf = (GLubyte*)g_CaptureImageBuffer; + + //Flip the image up-side down + for (int y = 0; y < g_CaptureImageHeight / 2; ++y) + { + for (int x = 0; x < g_CaptureImageWidth; ++x) + { + byte temp[3]; + memcpy(temp, &pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], 3); + memcpy(&pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], &pBuf[y * g_CaptureImageWidth * 3 + x * 3], 3); + memcpy(&pBuf[y * g_CaptureImageWidth * 3 + x * 3], temp, 3); + } + } + + callback(g_CaptureImageBuffer, g_CaptureImageWidth * g_CaptureImageHeight * 3, g_CaptureImageWidth, g_CaptureImageHeight); + return true; } bool GL_BeginAsyncCapture(fnGLQueryCaptureCallback callback) { - if (g_CaptureSyncObject) - return false; - - int glwidth, glheight; - g_pMetaHookAPI->GetVideoMode(&glwidth, &glheight, NULL, NULL); - if (glwidth <= 0 || glheight <= 0) - return false; - - if (glwidth != g_CaptureImageWidth || glheight != g_CaptureImageHeight) - { - GL_ShutdownCaptureImageBuffer(); - GL_ShutdownCapturePBO(); - g_CaptureImageWidth = glwidth; - g_CaptureImageHeight = glheight; - } - if (!g_CapturePBO) - GL_InitCapturePBO(glwidth, glheight); - if (!g_CaptureImageBuffer) - GL_InitCaptureImageBuffer(glwidth, glheight); - if (!g_CapturePBO || !g_CaptureImageBuffer) - return false; - - GL_ReadCapturePixels(g_CapturePBO, nullptr); - - g_CaptureSyncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); - return g_CaptureSyncObject != 0; + if (g_CaptureSyncObject) + return false; + + int glwidth, glheight; + g_pMetaHookAPI->GetVideoMode(&glwidth, &glheight, NULL, NULL); + if (glwidth <= 0 || glheight <= 0) + return false; + + if (glwidth != g_CaptureImageWidth || glheight != g_CaptureImageHeight) + { + GL_ShutdownCaptureImageBuffer(); + GL_ShutdownCapturePBO(); + g_CaptureImageWidth = glwidth; + g_CaptureImageHeight = glheight; + } + if (!g_CapturePBO) + GL_InitCapturePBO(glwidth, glheight); + if (!g_CaptureImageBuffer) + GL_InitCaptureImageBuffer(glwidth, glheight); + if (!g_CapturePBO || !g_CaptureImageBuffer) + return false; + + GL_ReadCapturePixels(g_CapturePBO, nullptr); + + g_CaptureSyncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + return g_CaptureSyncObject != 0; } bool GL_BeginCapture(fnGLQueryCaptureCallback callback) { - return g_pfnBeginCapture && g_pfnBeginCapture(callback); + return g_pfnBeginCapture && g_pfnBeginCapture(callback); } void GL_RequestCapture() { - g_CapturePending = true; + g_CapturePending = true; } void GL_DiscardPendingCapture() { - g_CapturePending = false; + g_CapturePending = false; } bool GL_CapturePendingBeforeSwap(fnGLQueryCaptureCallback callback) { - if (!g_CapturePending || !GL_BeginCapture(callback)) - return false; + if (!g_CapturePending || !GL_BeginCapture(callback)) + return false; - GL_DiscardPendingCapture(); - return true; + GL_DiscardPendingCapture(); + return true; } void GL_QueryAsyncCapture(fnGLQueryCaptureCallback callback) { - if (!g_CaptureSyncObject) - return; - - GLenum wait = glClientWaitSync(g_CaptureSyncObject, GL_SYNC_FLUSH_COMMANDS_BIT, 0); - if (wait == GL_WAIT_FAILED) - { - GL_ShutdownCaptureSyncObject(); - gEngfuncs.Con_Printf("[SteamScreenshots] Cannot capture screenshot: GPU fence wait failed.\n"); - return; - } - - if (wait == GL_ALREADY_SIGNALED || wait == GL_CONDITION_SATISFIED) - { - int originalPBO = 0; - glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); - - glBindBuffer(GL_PIXEL_PACK_BUFFER, g_CapturePBO); - - GLubyte* ptr = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); - if (ptr) - { - memcpy(g_CaptureImageBuffer, ptr, g_CaptureImageWidth * g_CaptureImageHeight * 3); - - GLubyte* pBuf = (GLubyte*)g_CaptureImageBuffer; - - //Flip the image up-side down - for (int y = 0; y < g_CaptureImageHeight / 2; ++y) { - for (int x = 0; x < g_CaptureImageWidth; ++x) { - byte temp[3]; - memcpy(temp, &pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], 3); - memcpy(&pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], &pBuf[y * g_CaptureImageWidth * 3 + x * 3], 3); - memcpy(&pBuf[y * g_CaptureImageWidth * 3 + x * 3], temp, 3); - } - } - - callback(g_CaptureImageBuffer, g_CaptureImageWidth * g_CaptureImageHeight * 3, g_CaptureImageWidth, g_CaptureImageHeight); - - glUnmapBuffer(GL_PIXEL_PACK_BUFFER); - } - - glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); - - glDeleteSync(g_CaptureSyncObject); - g_CaptureSyncObject = 0; - } + if (!g_CaptureSyncObject) + return; + + GLenum wait = glClientWaitSync(g_CaptureSyncObject, GL_SYNC_FLUSH_COMMANDS_BIT, 0); + if (wait == GL_WAIT_FAILED) + { + GL_ShutdownCaptureSyncObject(); + gEngfuncs.Con_Printf("[SteamScreenshots] Cannot capture screenshot: GPU fence wait failed.\n"); + return; + } + + if (wait == GL_ALREADY_SIGNALED || wait == GL_CONDITION_SATISFIED) + { + int originalPBO = 0; + glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &originalPBO); + + glBindBuffer(GL_PIXEL_PACK_BUFFER, g_CapturePBO); + + GLubyte* ptr = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); + if (ptr) + { + memcpy(g_CaptureImageBuffer, ptr, g_CaptureImageWidth * g_CaptureImageHeight * 3); + + GLubyte* pBuf = (GLubyte*)g_CaptureImageBuffer; + + //Flip the image up-side down + for (int y = 0; y < g_CaptureImageHeight / 2; ++y) + { + for (int x = 0; x < g_CaptureImageWidth; ++x) + { + byte temp[3]; + memcpy(temp, &pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], 3); + memcpy(&pBuf[(g_CaptureImageHeight - y - 1) * g_CaptureImageWidth * 3 + x * 3], &pBuf[y * g_CaptureImageWidth * 3 + x * 3], 3); + memcpy(&pBuf[y * g_CaptureImageWidth * 3 + x * 3], temp, 3); + } + } + + callback(g_CaptureImageBuffer, g_CaptureImageWidth * g_CaptureImageHeight * 3, g_CaptureImageWidth, g_CaptureImageHeight); + + glUnmapBuffer(GL_PIXEL_PACK_BUFFER); + } + + glBindBuffer(GL_PIXEL_PACK_BUFFER, originalPBO); + + glDeleteSync(g_CaptureSyncObject); + g_CaptureSyncObject = 0; + } } void GL_ShutdownCapture() { - GL_DiscardPendingCapture(); - g_pfnBeginCapture = NULL; - GL_ShutdownCaptureImageBuffer(); - GL_ShutdownCapturePBO(); - GL_ShutdownCaptureSyncObject(); + GL_DiscardPendingCapture(); + g_pfnBeginCapture = NULL; + GL_ShutdownCaptureImageBuffer(); + GL_ShutdownCapturePBO(); + GL_ShutdownCaptureSyncObject(); } bool GL_InitCapture() { - // GL_READ_FRAMEBUFFER requires core/ARB framebuffer support, not just EXT_framebuffer_object. - if (!(GLEW_VERSION_3_0 || GLEW_ARB_framebuffer_object) || !glBindFramebuffer) - { - gEngfuncs.Con_Printf("[SteamScreenshots] Framebuffer capture unavailable; keeping the engine snapshot command.\n"); - return false; - } - - g_pMetaHookAPI->GetVideoMode(&g_CaptureImageWidth, &g_CaptureImageHeight, NULL, NULL); - - if (GLEW_VERSION_3_2 && glFenceSync && glClientWaitSync) - { - GL_InitCapturePBO(g_CaptureImageWidth, g_CaptureImageHeight); - g_pfnBeginCapture = GL_BeginAsyncCapture; - } - else - { - g_pfnBeginCapture = GL_BeginSyncCapture; - } - - GL_InitCaptureImageBuffer(g_CaptureImageWidth, g_CaptureImageHeight); - return g_CaptureImageBuffer && (g_pfnBeginCapture != GL_BeginAsyncCapture || g_CapturePBO); + // GL_READ_FRAMEBUFFER requires core/ARB framebuffer support, not just EXT_framebuffer_object. + if (!(GLEW_VERSION_3_0 || GLEW_ARB_framebuffer_object) || !glBindFramebuffer) + { + gEngfuncs.Con_Printf("[SteamScreenshots] Framebuffer capture unavailable; keeping the engine snapshot command.\n"); + return false; + } + + g_pMetaHookAPI->GetVideoMode(&g_CaptureImageWidth, &g_CaptureImageHeight, NULL, NULL); + + if (GLEW_VERSION_3_2 && glFenceSync && glClientWaitSync) + { + GL_InitCapturePBO(g_CaptureImageWidth, g_CaptureImageHeight); + g_pfnBeginCapture = GL_BeginAsyncCapture; + } + else + { + g_pfnBeginCapture = GL_BeginSyncCapture; + } + + GL_InitCaptureImageBuffer(g_CaptureImageWidth, g_CaptureImageHeight); + return g_CaptureImageBuffer && (g_pfnBeginCapture != GL_BeginAsyncCapture || g_CapturePBO); } diff --git a/src/plugins.cpp b/src/plugins.cpp index ce1e0eb..2cc5059 100644 --- a/src/plugins.cpp +++ b/src/plugins.cpp @@ -4,79 +4,78 @@ #include "exportfuncs.h" #include "gl_capture.h" -cl_exportfuncs_t gExportfuncs = { 0 }; -mh_interface_t* g_pInterface = NULL; -metahook_api_t* g_pMetaHookAPI = NULL; -mh_enginesave_t* g_pMetaSave = NULL; -IFileSystem* g_pFileSystem = NULL; +cl_exportfuncs_t gExportfuncs = {0}; +mh_interface_t* g_pInterface = NULL; +metahook_api_t* g_pMetaHookAPI = NULL; +mh_enginesave_t* g_pMetaSave = NULL; +IFileSystem* g_pFileSystem = NULL; IFileSystem_HL25* g_pFileSystem_HL25 = NULL; -int g_iEngineType = 0; +int g_iEngineType = 0; DWORD g_dwEngineBuildnum = 0; -private_funcs_t gPrivateFuncs = { 0 }; +private_funcs_t gPrivateFuncs = {0}; -void IPluginsV4::Init(metahook_api_t *pAPI, mh_interface_t *pInterface, mh_enginesave_t *pSave) +void IPluginsV4::Init(metahook_api_t* pAPI, mh_interface_t* pInterface, mh_enginesave_t* pSave) { - g_pInterface = pInterface; - g_pMetaHookAPI = pAPI; - g_pMetaSave = pSave; + g_pInterface = pInterface; + g_pMetaHookAPI = pAPI; + g_pMetaSave = pSave; } void IPluginsV4::Shutdown(void) { - ShutdownSteamBridge(); + ShutdownSteamBridge(); } -void IPluginsV4::LoadEngine(cl_enginefunc_t *pEngfuncs) +void IPluginsV4::LoadEngine(cl_enginefunc_t* pEngfuncs) { - g_pFileSystem = g_pInterface->FileSystem; - if (!g_pFileSystem) - g_pFileSystem_HL25 = g_pInterface->FileSystem_HL25; + g_pFileSystem = g_pInterface->FileSystem; + if (!g_pFileSystem) + g_pFileSystem_HL25 = g_pInterface->FileSystem_HL25; - g_iEngineType = g_pMetaHookAPI->GetEngineType(); - g_dwEngineBuildnum = g_pMetaHookAPI->GetEngineBuildnum(); + g_iEngineType = g_pMetaHookAPI->GetEngineType(); + g_dwEngineBuildnum = g_pMetaHookAPI->GetEngineBuildnum(); - memcpy(&gEngfuncs, pEngfuncs, sizeof(gEngfuncs)); + memcpy(&gEngfuncs, pEngfuncs, sizeof(gEngfuncs)); } -void IPluginsV4::LoadClient(cl_exportfuncs_t *pExportFunc) +void IPluginsV4::LoadClient(cl_exportfuncs_t* pExportFunc) { - memcpy(&gExportfuncs, pExportFunc, sizeof(gExportfuncs)); + memcpy(&gExportfuncs, pExportFunc, sizeof(gExportfuncs)); - glewInit(); + glewInit(); - pExportFunc->HUD_Frame = HUD_Frame; - pExportFunc->HUD_Shutdown = HUD_Shutdown; - pExportFunc->IN_ActivateMouse = IN_ActivateMouse; + pExportFunc->HUD_Frame = HUD_Frame; + pExportFunc->HUD_Shutdown = HUD_Shutdown; + pExportFunc->IN_ActivateMouse = IN_ActivateMouse; } void IPluginsV4::ExitGame(int iResult) { - ShutdownSteamBridge(); - GL_DiscardPendingCapture(); - UninstallPresentHook(); + ShutdownSteamBridge(); + GL_DiscardPendingCapture(); + UninstallPresentHook(); } const char completeVersion[] = -{ - BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3, - '-', - BUILD_MONTH_CH0, BUILD_MONTH_CH1, - '-', - BUILD_DAY_CH0, BUILD_DAY_CH1, - 'T', - BUILD_HOUR_CH0, BUILD_HOUR_CH1, - ':', - BUILD_MIN_CH0, BUILD_MIN_CH1, - ':', - BUILD_SEC_CH0, BUILD_SEC_CH1, - '\0' -}; + { + BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3, + '-', + BUILD_MONTH_CH0, BUILD_MONTH_CH1, + '-', + BUILD_DAY_CH0, BUILD_DAY_CH1, + 'T', + BUILD_HOUR_CH0, BUILD_HOUR_CH1, + ':', + BUILD_MIN_CH0, BUILD_MIN_CH1, + ':', + BUILD_SEC_CH0, BUILD_SEC_CH1, + '\0'}; -const char *IPluginsV4::GetVersion(void) +const char* IPluginsV4::GetVersion(void) { - return completeVersion; + return completeVersion; } EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4); diff --git a/src/plugins.h b/src/plugins.h index 7c77a54..4907dca 100644 --- a/src/plugins.h +++ b/src/plugins.h @@ -5,7 +5,7 @@ class IFileSystem; extern IFileSystem* g_pFileSystem; -extern int g_iEngineType; +extern int g_iEngineType; extern DWORD g_dwEngineBuildnum; extern mh_dll_info_t g_EngineDLLInfo; @@ -15,37 +15,48 @@ extern mh_dll_info_t g_MirrorClientDLLInfo; typedef struct { - void(__cdecl* SDL_GL_SwapWindow)(void* window); - // The engine's VID_FlipScreen pointer slot and the function it held before we swapped it. - void(__cdecl** VID_FlipScreen)(void); - void(__cdecl* Sys_VID_FlipScreen)(void); -}private_funcs_t; + void(__cdecl* SDL_GL_SwapWindow)(void* window); + // The engine's VID_FlipScreen pointer slot and the function it held before we swapped it. + void(__cdecl** VID_FlipScreen)(void); + void(__cdecl* Sys_VID_FlipScreen)(void); +} private_funcs_t; extern private_funcs_t gPrivateFuncs; -#define MHPluginName "SteamScreenshots" -#define Sys_Error(msg, ...) g_pMetaHookAPI->SysError("[" MHPluginName "] " msg, __VA_ARGS__); -#define Sig_NotFound(name) Sys_Error("Could not found: %s\nEngine buildnum: %d", #name, g_dwEngineBuildnum); -#define Sig_VarNotFound(name) if(!name) Sig_NotFound(name) -#define Sig_AddrNotFound(name) if(!addr) Sig_NotFound(name) -#define Sig_FuncNotFound(name) if(!gPrivateFuncs.name) Sig_NotFound(name) - -#define Sig_Length(a) (sizeof(a)-1) -#define Search_Pattern(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) -#define Search_Pattern_Data(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) -#define Search_Pattern_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) -#define Search_Pattern_From_Size(fn, size, sig) g_pMetaHookAPI->SearchPattern((void *)(fn), size, sig, Sig_Length(sig)) -#define Search_Pattern_From(fn, sig, dllinfo) g_pMetaHookAPI->SearchPattern((void *)(fn), ((PUCHAR)dllinfo.TextBase + dllinfo.TextSize) - (PUCHAR)(fn), sig, Sig_Length(sig)) - -#define Search_Pattern_NoWildCard(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) -#define Search_Pattern_NoWildCard_Data(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) +#define MHPluginName "SteamScreenshots" +#define Sys_Error(msg, ...) g_pMetaHookAPI->SysError("[" MHPluginName "] " msg, __VA_ARGS__); +#define Sig_NotFound(name) Sys_Error("Could not found: %s\nEngine buildnum: %d", #name, g_dwEngineBuildnum); +#define Sig_VarNotFound(name) \ + if (!name) Sig_NotFound(name) +#define Sig_AddrNotFound(name) \ + if (!addr) Sig_NotFound(name) +#define Sig_FuncNotFound(name) \ + if (!gPrivateFuncs.name) Sig_NotFound(name) + +#define Sig_Length(a) (sizeof(a) - 1) +#define Search_Pattern(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) +#define Search_Pattern_Data(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) +#define Search_Pattern_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) +#define Search_Pattern_From_Size(fn, size, sig) g_pMetaHookAPI->SearchPattern((void*)(fn), size, sig, Sig_Length(sig)) +#define Search_Pattern_From(fn, sig, dllinfo) g_pMetaHookAPI->SearchPattern((void*)(fn), ((PUCHAR)dllinfo.TextBase + dllinfo.TextSize) - (PUCHAR)(fn), sig, Sig_Length(sig)) + +#define Search_Pattern_NoWildCard(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) +#define Search_Pattern_NoWildCard_Data(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) #define Search_Pattern_NoWildCard_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) -#define Install_InlineHook(fn) if(!g_phook_##fn) { g_phook_##fn = g_pMetaHookAPI->InlineHook((void *)gPrivateFuncs.fn, fn, (void **)&gPrivateFuncs.fn); } -#define Uninstall_Hook(fn) if(g_phook_##fn){g_pMetaHookAPI->UnHook(g_phook_##fn);g_phook_##fn = NULL;} +#define Install_InlineHook(fn) \ + if (!g_phook_##fn) { g_phook_##fn = g_pMetaHookAPI->InlineHook((void*)gPrivateFuncs.fn, fn, (void**)&gPrivateFuncs.fn); } +#define Uninstall_Hook(fn) \ + if (g_phook_##fn) \ + { \ + g_pMetaHookAPI->UnHook(g_phook_##fn); \ + g_phook_##fn = NULL; \ + } #define GetCallAddress(addr) g_pMetaHookAPI->GetNextCallAddr((PUCHAR)addr, 1) #define RVA_from_VA(name, dllinfo) (ULONG)((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) #define VA_from_RVA(name, dllinfo) ((ULONG_PTR)dllinfo.ImageBase + (ULONG_PTR)name##_RVA) -#define Convert_VA_to_RVA(name, dllinfo) if(name##_VA) name##_RVA = ((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) -#define Convert_RVA_to_VA(name, dllinfo) if(name##_RVA) name##_VA = (decltype(name##_VA))VA_from_RVA(name, dllinfo) +#define Convert_VA_to_RVA(name, dllinfo) \ + if (name##_VA) name##_RVA = ((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) +#define Convert_RVA_to_VA(name, dllinfo) \ + if (name##_RVA) name##_VA = (decltype(name##_VA))VA_from_RVA(name, dllinfo) diff --git a/tests/capture_tests.cpp b/tests/capture_tests.cpp index ae9cdda..7c869bc 100644 --- a/tests/capture_tests.cpp +++ b/tests/capture_tests.cpp @@ -14,324 +14,323 @@ namespace { - constexpr int CanvasWidth = 1400; - constexpr int CanvasHeight = 128; - constexpr int CaptureHeight = 7; - constexpr int RGBChannels = 3; - constexpr auto CaptureTimeout = std::chrono::seconds(5); +constexpr int CanvasWidth = 1400; +constexpr int CanvasHeight = 128; +constexpr int CaptureHeight = 7; +constexpr int RGBChannels = 3; +constexpr auto CaptureTimeout = std::chrono::seconds(5); - int captureWidth = 1366; - int captureHeight = CaptureHeight; - int callbackCount = 0; - int logCount = 0; - int receivedWidth = 0; - int receivedHeight = 0; - std::vector receivedPixels; +int captureWidth = 1366; +int captureHeight = CaptureHeight; +int callbackCount = 0; +int logCount = 0; +int receivedWidth = 0; +int receivedHeight = 0; +std::vector receivedPixels; - void Require(bool condition, const char* message) - { - if (!condition) - throw std::runtime_error(message); - } +void Require(bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} - void CheckGLError() - { - const auto error = glGetError(); - if (error != GL_NO_ERROR) - throw std::runtime_error("OpenGL error: " + std::to_string(error)); - } +void CheckGLError() +{ + const auto error = glGetError(); + if (error != GL_NO_ERROR) + throw std::runtime_error("OpenGL error: " + std::to_string(error)); +} - void ReceiveCapture(void* pixels, size_t size, int width, int height) - { - ++callbackCount; - receivedWidth = width; - receivedHeight = height; - const auto begin = static_cast(pixels); - receivedPixels.assign(begin, begin + size); - } +void ReceiveCapture(void* pixels, size_t size, int width, int height) +{ + ++callbackCount; + receivedWidth = width; + receivedHeight = height; + const auto begin = static_cast(pixels); + receivedPixels.assign(begin, begin + size); +} - struct GLState +struct GLState +{ + GLint readFBO, drawFBO, readBuffer, defaultReadBuffer, pbo, alignment, rowLength, skipRows, skipPixels; + bool operator==(const GLState&) const = default; + + static GLState Read() { - GLint readFBO, drawFBO, readBuffer, defaultReadBuffer, pbo, alignment, rowLength, skipRows, skipPixels; - bool operator==(const GLState&) const = default; + GLState state{}; + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &state.readFBO); + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &state.drawFBO); + glGetIntegerv(GL_READ_BUFFER, &state.readBuffer); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glGetIntegerv(GL_READ_BUFFER, &state.defaultReadBuffer); + glBindFramebuffer(GL_READ_FRAMEBUFFER, state.readFBO); + glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &state.pbo); + glGetIntegerv(GL_PACK_ALIGNMENT, &state.alignment); + glGetIntegerv(GL_PACK_ROW_LENGTH, &state.rowLength); + glGetIntegerv(GL_PACK_SKIP_ROWS, &state.skipRows); + glGetIntegerv(GL_PACK_SKIP_PIXELS, &state.skipPixels); + return state; + } +}; - static GLState Read() - { - GLState state{}; - glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &state.readFBO); - glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &state.drawFBO); - glGetIntegerv(GL_READ_BUFFER, &state.readBuffer); - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - glGetIntegerv(GL_READ_BUFFER, &state.defaultReadBuffer); - glBindFramebuffer(GL_READ_FRAMEBUFFER, state.readFBO); - glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &state.pbo); - glGetIntegerv(GL_PACK_ALIGNMENT, &state.alignment); - glGetIntegerv(GL_PACK_ROW_LENGTH, &state.rowLength); - glGetIntegerv(GL_PACK_SKIP_ROWS, &state.skipRows); - glGetIntegerv(GL_PACK_SKIP_PIXELS, &state.skipPixels); - return state; - } - }; +struct Context +{ + GLFWwindow* window = nullptr; + GLuint callerPBO = 0; + std::array callerFBOs{}; - struct Context + Context() { - GLFWwindow* window = nullptr; - GLuint callerPBO = 0; - std::array callerFBOs{}; - - Context() + glfwSetErrorCallback([](int error, const char* message) { + std::fprintf(stderr, "GLFW %d: %s\n", error, message); + }); + Require(glfwInit() == GLFW_TRUE, "GLFW initialization failed"); + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + window = glfwCreateWindow(CanvasWidth, CanvasHeight, "Capture tests", nullptr, nullptr); + if (!window) { - glfwSetErrorCallback([](int error, const char* message) { - std::fprintf(stderr, "GLFW %d: %s\n", error, message); - }); - Require(glfwInit() == GLFW_TRUE, "GLFW initialization failed"); - glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - window = glfwCreateWindow(CanvasWidth, CanvasHeight, "Capture tests", nullptr, nullptr); - if (!window) - { - glfwTerminate(); - throw std::runtime_error("OpenGL 3.3 context unavailable"); - } - glfwMakeContextCurrent(window); - glewExperimental = GL_TRUE; - const auto result = glewInit(); - if (result != GLEW_OK) - { - glfwDestroyWindow(window); - glfwTerminate(); - throw std::runtime_error("GLEW initialization failed"); - } - // Some GLEW versions probe GL_EXTENSIONS in a core context. - while (glGetError() != GL_NO_ERROR) {} - std::printf("OpenGL: %s / %s\n", glGetString(GL_VERSION), glGetString(GL_RENDERER)); + glfwTerminate(); + throw std::runtime_error("OpenGL 3.3 context unavailable"); } - - ~Context() + glfwMakeContextCurrent(window); + glewExperimental = GL_TRUE; + const auto result = glewInit(); + if (result != GLEW_OK) { - GL_ShutdownCapture(); - glDeleteBuffers(1, &callerPBO); - glDeleteFramebuffers(static_cast(callerFBOs.size()), callerFBOs.data()); glfwDestroyWindow(window); glfwTerminate(); + throw std::runtime_error("GLEW initialization failed"); } + // Some GLEW versions probe GL_EXTENSIONS in a core context. + while (glGetError() != GL_NO_ERROR) {} + std::printf("OpenGL: %s / %s\n", glGetString(GL_VERSION), glGetString(GL_RENDERER)); + } - void SetCallerState(bool dirtyPacking) - { - glGenBuffers(1, &callerPBO); - glBindBuffer(GL_PIXEL_PACK_BUFFER, callerPBO); - constexpr GLsizeiptr CallerBufferSize = 64; - glBufferData(GL_PIXEL_PACK_BUFFER, CallerBufferSize, nullptr, GL_STREAM_READ); - glGenFramebuffers(static_cast(callerFBOs.size()), callerFBOs.data()); - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - glReadBuffer(GL_FRONT); - glBindFramebuffer(GL_READ_FRAMEBUFFER, callerFBOs[0]); - glReadBuffer(GL_COLOR_ATTACHMENT1); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, callerFBOs[1]); - if (dirtyPacking) - { - glPixelStorei(GL_PACK_ALIGNMENT, 8); - glPixelStorei(GL_PACK_ROW_LENGTH, CanvasWidth + 10); - glPixelStorei(GL_PACK_SKIP_ROWS, 2); - glPixelStorei(GL_PACK_SKIP_PIXELS, 3); - } - } - - void Paint(bool invert = false) - { - int framebufferWidth = 0, framebufferHeight = 0; - glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight); - Require(framebufferWidth >= captureWidth && framebufferHeight >= captureHeight, - "Hidden window framebuffer is too small for the capture region"); - const auto original = GLState::Read(); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - glDrawBuffer(GL_BACK); - glDisable(GL_DITHER); - glEnable(GL_SCISSOR_TEST); - for (int y = 0; y < captureHeight; ++y) - { - glScissor(0, y, captureWidth, 1); - const bool red = (y % 2 == 0) != invert; - glClearColor(red ? 1.0f : 0.0f, red ? 0.0f : 1.0f, 0, 1); - glClear(GL_COLOR_BUFFER_BIT); - } - // A vertical blue edge catches horizontal offsets and row-stride errors. - glScissor(captureWidth - 1, 0, 1, captureHeight); - glClearColor(0, 0, 1, 1); - glClear(GL_COLOR_BUFFER_BIT); - glDisable(GL_SCISSOR_TEST); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, original.drawFBO); - CheckGLError(); - } - }; + ~Context() + { + GL_ShutdownCapture(); + glDeleteBuffers(1, &callerPBO); + glDeleteFramebuffers(static_cast(callerFBOs.size()), callerFBOs.data()); + glfwDestroyWindow(window); + glfwTerminate(); + } - void AwaitCapture(int expectedCount) + void SetCallerState(bool dirtyPacking) { - const auto deadline = std::chrono::steady_clock::now() + CaptureTimeout; - while (callbackCount < expectedCount && std::chrono::steady_clock::now() < deadline) + glGenBuffers(1, &callerPBO); + glBindBuffer(GL_PIXEL_PACK_BUFFER, callerPBO); + constexpr GLsizeiptr CallerBufferSize = 64; + glBufferData(GL_PIXEL_PACK_BUFFER, CallerBufferSize, nullptr, GL_STREAM_READ); + glGenFramebuffers(static_cast(callerFBOs.size()), callerFBOs.data()); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glReadBuffer(GL_FRONT); + glBindFramebuffer(GL_READ_FRAMEBUFFER, callerFBOs[0]); + glReadBuffer(GL_COLOR_ATTACHMENT1); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, callerFBOs[1]); + if (dirtyPacking) { - GL_QueryAsyncCapture(ReceiveCapture); - std::this_thread::sleep_for(std::chrono::milliseconds(1)); + glPixelStorei(GL_PACK_ALIGNMENT, 8); + glPixelStorei(GL_PACK_ROW_LENGTH, CanvasWidth + 10); + glPixelStorei(GL_PACK_SKIP_ROWS, 2); + glPixelStorei(GL_PACK_SKIP_PIXELS, 3); } - Require(callbackCount == expectedCount, "Screenshot callback count or completion timeout"); } - void CheckPixels(bool invert = false) + void Paint(bool invert = false) { - Require(receivedWidth == captureWidth && receivedHeight == captureHeight, "Incorrect screenshot dimensions"); - Require(receivedPixels.size() == size_t(captureWidth * captureHeight * RGBChannels), "Incorrect RGB byte count"); + int framebufferWidth = 0, framebufferHeight = 0; + glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight); + Require(framebufferWidth >= captureWidth && framebufferHeight >= captureHeight, + "Hidden window framebuffer is too small for the capture region"); + const auto original = GLState::Read(); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + glDrawBuffer(GL_BACK); + glDisable(GL_DITHER); + glEnable(GL_SCISSOR_TEST); for (int y = 0; y < captureHeight; ++y) { - const int sourceY = captureHeight - y - 1; - for (int x = 0; x < captureWidth; ++x) - { - const bool edge = x == captureWidth - 1; - const std::array expected{ - byte(!edge && ((sourceY % 2 == 0) != invert) ? 255 : 0), - byte(!edge && ((sourceY % 2 != 0) != invert) ? 255 : 0), - byte(edge ? 255 : 0) - }; - for (int channel = 0; channel < RGBChannels; ++channel) - Require(expected[channel] == receivedPixels[(y * captureWidth + x) * RGBChannels + channel], - "RGB content, row stride, or vertical orientation mismatch"); - } + glScissor(0, y, captureWidth, 1); + const bool red = (y % 2 == 0) != invert; + glClearColor(red ? 1.0f : 0.0f, red ? 0.0f : 1.0f, 0, 1); + glClear(GL_COLOR_BUFFER_BIT); } + // A vertical blue edge catches horizontal offsets and row-stride errors. + glScissor(captureWidth - 1, 0, 1, captureHeight); + glClearColor(0, 0, 1, 1); + glClear(GL_COLOR_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, original.drawFBO); + CheckGLError(); } +}; - GLenum APIENTRY FailedWait(GLsync, GLbitfield, GLuint64) { return GL_WAIT_FAILED; } - GLenum APIENTRY TimedOutWait(GLsync, GLbitfield, GLuint64) { return GL_TIMEOUT_EXPIRED; } - - void TestTimeout(Context& context) +void AwaitCapture(int expectedCount) +{ + const auto deadline = std::chrono::steady_clock::now() + CaptureTimeout; + while (callbackCount < expectedCount && std::chrono::steady_clock::now() < deadline) { - context.SetCallerState(true); - Require(GL_InitCapture(), "Capture initialization failed"); - const auto original = GLState::Read(); - context.Paint(); - GL_BeginCapture(ReceiveCapture); - const auto realWait = glClientWaitSync; - glClientWaitSync = TimedOutWait; GL_QueryAsyncCapture(ReceiveCapture); - glClientWaitSync = realWait; - Require(callbackCount == 0, "Timeout delivered an unfinished screenshot"); - // Resume the existing request without issuing a replacement capture. - AwaitCapture(1); - Require(original == GLState::Read(), "Timeout/resume changed caller GL state"); - CheckGLError(); - CheckPixels(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); } + Require(callbackCount == expectedCount, "Screenshot callback count or completion timeout"); +} - void TestCapture(Context& context, bool dirtyPacking) +void CheckPixels(bool invert = false) +{ + Require(receivedWidth == captureWidth && receivedHeight == captureHeight, "Incorrect screenshot dimensions"); + Require(receivedPixels.size() == size_t(captureWidth * captureHeight * RGBChannels), "Incorrect RGB byte count"); + for (int y = 0; y < captureHeight; ++y) { - context.SetCallerState(dirtyPacking); - const auto original = GLState::Read(); - Require(GL_InitCapture(), "Capture initialization failed"); - Require(original == GLState::Read(), "Initialization changed caller GL state"); - - // Exercise every RGB row remainder, including both growth and shrinkage. - for (const int width : {1366, 1367, 1365, 1364}) + const int sourceY = captureHeight - y - 1; + for (int x = 0; x < captureWidth; ++x) { - captureWidth = width; - captureHeight = width == 1367 ? CaptureHeight + 1 : CaptureHeight; - context.Paint(); - const int expectedCount = callbackCount + 1; - GL_BeginCapture(ReceiveCapture); - Require(original == GLState::Read(), "Begin/resize changed caller GL state"); - AwaitCapture(expectedCount); - Require(original == GLState::Read(), "Async query changed caller GL state"); - CheckGLError(); - CheckPixels(); + const bool edge = x == captureWidth - 1; + const std::array expected{ + byte(!edge && ((sourceY % 2 == 0) != invert) ? 255 : 0), + byte(!edge && ((sourceY % 2 != 0) != invert) ? 255 : 0), + byte(edge ? 255 : 0)}; + for (int channel = 0; channel < RGBChannels; ++channel) + Require(expected[channel] == receivedPixels[(y * captureWidth + x) * RGBChannels + channel], + "RGB content, row stride, or vertical orientation mismatch"); } } +} + +GLenum APIENTRY FailedWait(GLsync, GLbitfield, GLuint64) { return GL_WAIT_FAILED; } +GLenum APIENTRY TimedOutWait(GLsync, GLbitfield, GLuint64) { return GL_TIMEOUT_EXPIRED; } + +void TestTimeout(Context& context) +{ + context.SetCallerState(true); + Require(GL_InitCapture(), "Capture initialization failed"); + const auto original = GLState::Read(); + context.Paint(); + GL_BeginCapture(ReceiveCapture); + const auto realWait = glClientWaitSync; + glClientWaitSync = TimedOutWait; + GL_QueryAsyncCapture(ReceiveCapture); + glClientWaitSync = realWait; + Require(callbackCount == 0, "Timeout delivered an unfinished screenshot"); + // Resume the existing request without issuing a replacement capture. + AwaitCapture(1); + Require(original == GLState::Read(), "Timeout/resume changed caller GL state"); + CheckGLError(); + CheckPixels(); +} + +void TestCapture(Context& context, bool dirtyPacking) +{ + context.SetCallerState(dirtyPacking); + const auto original = GLState::Read(); + Require(GL_InitCapture(), "Capture initialization failed"); + Require(original == GLState::Read(), "Initialization changed caller GL state"); - void TestFailedWait(Context& context) + // Exercise every RGB row remainder, including both growth and shrinkage. + for (const int width : {1366, 1367, 1365, 1364}) { - context.SetCallerState(true); - Require(GL_InitCapture(), "Capture initialization failed"); - const auto original = GLState::Read(); + captureWidth = width; + captureHeight = width == 1367 ? CaptureHeight + 1 : CaptureHeight; context.Paint(); - GL_RequestCapture(); - Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "First request did not start"); - GL_RequestCapture(); - const auto realWait = glClientWaitSync; - // Inject only the wait status; pixels, PBOs, mappings and fences remain real GL. - glClientWaitSync = TimedOutWait; - GL_QueryAsyncCapture(ReceiveCapture); - const bool timeoutKeptPending = callbackCount == 0; - glClientWaitSync = FailedWait; - GL_QueryAsyncCapture(ReceiveCapture); - glClientWaitSync = realWait; - Require(timeoutKeptPending, "Timeout delivered an unfinished screenshot"); - Require(callbackCount == 0 && logCount == 1, "Wait failure was not discarded and reported"); - // A different size distinguishes a new capture from the failed request. - captureWidth = 1367; - context.Paint(); - Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Pending request was lost after wait failure"); - AwaitCapture(1); - Require(original == GLState::Read(), "Failure/recovery changed caller GL state"); + const int expectedCount = callbackCount + 1; + GL_BeginCapture(ReceiveCapture); + Require(original == GLState::Read(), "Begin/resize changed caller GL state"); + AwaitCapture(expectedCount); + Require(original == GLState::Read(), "Async query changed caller GL state"); CheckGLError(); CheckPixels(); } +} - void TestAsyncFrameAndPending(Context& context) - { - context.SetCallerState(true); - const auto original = GLState::Read(); - Require(GL_InitCapture(), "Capture initialization failed"); - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Idle swap started a readback"); +void TestFailedWait(Context& context) +{ + context.SetCallerState(true); + Require(GL_InitCapture(), "Capture initialization failed"); + const auto original = GLState::Read(); + context.Paint(); + GL_RequestCapture(); + Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "First request did not start"); + GL_RequestCapture(); + const auto realWait = glClientWaitSync; + // Inject only the wait status; pixels, PBOs, mappings and fences remain real GL. + glClientWaitSync = TimedOutWait; + GL_QueryAsyncCapture(ReceiveCapture); + const bool timeoutKeptPending = callbackCount == 0; + glClientWaitSync = FailedWait; + GL_QueryAsyncCapture(ReceiveCapture); + glClientWaitSync = realWait; + Require(timeoutKeptPending, "Timeout delivered an unfinished screenshot"); + Require(callbackCount == 0 && logCount == 1, "Wait failure was not discarded and reported"); + // A different size distinguishes a new capture from the failed request. + captureWidth = 1367; + context.Paint(); + Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Pending request was lost after wait failure"); + AwaitCapture(1); + Require(original == GLState::Read(), "Failure/recovery changed caller GL state"); + CheckGLError(); + CheckPixels(); +} - GL_RequestCapture(); - captureWidth = 0; - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Invalid capture size started a readback"); - captureWidth = 1366; - context.Paint(); - GL_RequestCapture(); - Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Pending request did not start before swap"); +void TestAsyncFrameAndPending(Context& context) +{ + context.SetCallerState(true); + const auto original = GLState::Read(); + Require(GL_InitCapture(), "Capture initialization failed"); + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Idle swap started a readback"); - context.Paint(true); - GL_RequestCapture(); - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Busy PBO replaced the first frame"); - AwaitCapture(1); - CheckPixels(); + GL_RequestCapture(); + captureWidth = 0; + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Invalid capture size started a readback"); + captureWidth = 1366; + context.Paint(); + GL_RequestCapture(); + Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Pending request did not start before swap"); - Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Busy request was lost"); - AwaitCapture(2); - CheckPixels(true); - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Completed request was captured twice"); - Require(original == GLState::Read(), "Pending capture changed caller GL state"); + context.Paint(true); + GL_RequestCapture(); + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Busy PBO replaced the first frame"); + AwaitCapture(1); + CheckPixels(); - GL_RequestCapture(); - GL_ShutdownCapture(); - Require(GL_InitCapture(), "Capture reinitialization failed"); - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Shutdown retained a pending request"); - CheckGLError(); - } + Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Busy request was lost"); + AwaitCapture(2); + CheckPixels(true); + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Completed request was captured twice"); + Require(original == GLState::Read(), "Pending capture changed caller GL state"); - void TestSyncPending(Context& context) - { - context.SetCallerState(true); - const auto original = GLState::Read(); - Require(GL_InitCapture(), "Capture initialization failed"); - context.Paint(); - GL_RequestCapture(); - GL_RequestCapture(); - Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Synchronous request did not start before swap"); - Require(callbackCount == 1, "Coalesced requests produced multiple captures"); - CheckPixels(); - Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Completed synchronous request was captured twice"); - Require(original == GLState::Read(), "Synchronous pending capture changed caller GL state"); - CheckGLError(); - } + GL_RequestCapture(); + GL_ShutdownCapture(); + Require(GL_InitCapture(), "Capture reinitialization failed"); + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Shutdown retained a pending request"); + CheckGLError(); +} + +void TestSyncPending(Context& context) +{ + context.SetCallerState(true); + const auto original = GLState::Read(); + Require(GL_InitCapture(), "Capture initialization failed"); + context.Paint(); + GL_RequestCapture(); + GL_RequestCapture(); + Require(GL_CapturePendingBeforeSwap(ReceiveCapture), "Synchronous request did not start before swap"); + Require(callbackCount == 1, "Coalesced requests produced multiple captures"); + CheckPixels(); + Require(!GL_CapturePendingBeforeSwap(ReceiveCapture), "Completed synchronous request was captured twice"); + Require(original == GLState::Read(), "Synchronous pending capture changed caller GL state"); + CheckGLError(); } +} // namespace -CaptureTestVideoAPI videoAPI; +CaptureTestVideoAPI videoAPI; CaptureTestVideoAPI* g_pMetaHookAPI = &videoAPI; -CaptureTestEngine gEngfuncs; +CaptureTestEngine gEngfuncs; void CaptureTestVideoAPI::GetVideoMode(int* width, int* height, void*, void*) { - *width = captureWidth; + *width = captureWidth; *height = captureHeight; } @@ -350,24 +349,24 @@ int main(int argc, char** argv) { Require(argc == 2, "Expected a CTest case name"); const std::string testCase = argv[1]; - Context context; + Context context; if (testCase == "framebuffer-unavailable" || testCase == "framebuffer-entrypoint-unavailable") { const auto original = GLState::Read(); - const auto core = GLEW_VERSION_3_0; - const auto arb = GLEW_ARB_framebuffer_object; - const auto bind = glBindFramebuffer; + const auto core = GLEW_VERSION_3_0; + const auto arb = GLEW_ARB_framebuffer_object; + const auto bind = glBindFramebuffer; if (testCase == "framebuffer-unavailable") { - __GLEW_VERSION_3_0 = GL_FALSE; + __GLEW_VERSION_3_0 = GL_FALSE; __GLEW_ARB_framebuffer_object = GL_FALSE; } else glBindFramebuffer = nullptr; - const bool initialized = GL_InitCapture(); - __GLEW_VERSION_3_0 = core; + const bool initialized = GL_InitCapture(); + __GLEW_VERSION_3_0 = core; __GLEW_ARB_framebuffer_object = arb; - glBindFramebuffer = bind; + glBindFramebuffer = bind; Require(!initialized, "Missing framebuffer capability must reject capture initialization"); Require(original == GLState::Read(), "Rejected initialization changed GL state"); CheckGLError(); @@ -385,13 +384,12 @@ int main(int argc, char** argv) } else { - Require(testCase == "sync-default" || testCase == "sync-dirty" || testCase == "async-default" - || testCase == "async-dirty" || testCase == "arb-framebuffer", "Unknown test case"); + Require(testCase == "sync-default" || testCase == "sync-dirty" || testCase == "async-default" || testCase == "async-dirty" || testCase == "arb-framebuffer", "Unknown test case"); if (testCase.starts_with("sync") || testCase == "arb-framebuffer") __GLEW_VERSION_3_2 = GL_FALSE; if (testCase == "arb-framebuffer") { - __GLEW_VERSION_3_0 = GL_FALSE; + __GLEW_VERSION_3_0 = GL_FALSE; __GLEW_ARB_framebuffer_object = GL_TRUE; } TestCapture(context, testCase.ends_with("dirty")); diff --git a/tests/support/metahook.h b/tests/support/metahook.h index a075290..0552ea4 100644 --- a/tests/support/metahook.h +++ b/tests/support/metahook.h @@ -19,4 +19,4 @@ struct CaptureTestEngine }; extern CaptureTestVideoAPI* g_pMetaHookAPI; -extern CaptureTestEngine gEngfuncs; +extern CaptureTestEngine gEngfuncs;