diff --git a/.github/actions/build-windows-x86/action.yml b/.github/actions/build-windows-x86/action.yml index b578551..5038024 100644 --- a/.github/actions/build-windows-x86/action.yml +++ b/.github/actions/build-windows-x86/action.yml @@ -9,20 +9,9 @@ outputs: runs: using: composite steps: - - name: Clone MetaHook SDK headers - shell: pwsh - run: | - $metahookPath = Join-Path (Split-Path $env:GITHUB_WORKSPACE -Parent) 'MetaHook' - & git clone --depth 1 --branch main https://github.com/MetaHookSv/MetaHook $metahookPath - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - & git -C $metahookPath rev-parse HEAD - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - # The plugin consumes include/ only: it compiles interface.cpp and links no SDK library. - "METAHOOK_SOURCE_PATH=$metahookPath" >> $env:GITHUB_ENV - - name: Build and install shell: cmd - run: call scripts\build-SvenSoundcacheControl-x86-Release.bat "-DMETAHOOK_SOURCE_PATH=%METAHOOK_SOURCE_PATH%" + run: call scripts\build-SvenSoundcacheControl-x86-Release.bat "-DMETAHOOK_SOURCE_PATH=" - name: Test behavior shell: cmd @@ -30,7 +19,7 @@ runs: - name: Validate installed gamedata shell: cmd - run: python "%METAHOOK_SOURCE_PATH%\scripts\validate-gamedata.py" install\x86\Release\svencoop\metahook\gamedata\svensoundcachecontrol --manifest scripts\manifests\svensoundcachecontrol.json + run: python build\x86\Release\_deps\svensoundcachecontrol_metahook-src\scripts\validate-gamedata.py install\x86\Release\svencoop\metahook\gamedata\svensoundcachecontrol --manifest scripts\manifests\svensoundcachecontrol.json - name: Package plugin id: package diff --git a/README.md b/README.md index 696cc27..0ebc9f4 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,10 @@ not included; do not load both plugins. ## Behavior and limits The original sound engine clears its in-memory indices only when the map name -changes. This plugin calls its native `ClearSoundArrays` on every map start and -invalidates the native disk sound-list cache, then uses the original loader. +changes. This plugin marks each join at `HUD_VidInit`, then calls native +`ClearSoundArrays` and invalidates the native disk sound-list cache before the +first sound-list load or map-start callback. A later `MapStarted` callback keeps +sounds already loaded for that join. Loading still uses the original loader. It does not delete audio assets or implement a replacement sound engine. A remote join can require one automatic reconnect while the original `dlfile` @@ -42,13 +44,16 @@ remove the file the same server must serve to other players. Windows MSVC x86 only, MetaHook API 109 or newer, Sven client builds 8948/10257. Other clients and missing gamedata produce a clear startup error. Catalog coverage alone does not imply that every build has been tested in a live game. +Connection tracking uses the MetaHook SDK's `net_api_svengine.h` types: Sven's +network status ABI is 104 bytes, rather than the original HLSDK's 72 bytes. ## Build and test Requires Visual Studio 2022, CMake 3.21+, Python 3.9+, and network access to the symbol catalog. The MetaHook source tree supplies SDK headers, `interface.cpp` -and the shared gamedata synchronization/validation scripts. It is fetched from -`main` unless `METAHOOK_SOURCE_PATH` is set; no SDK library is linked. +and the shared gamedata synchronization/validation scripts. A pinned SDK commit +including `net_api_svengine.h` is fetched unless `METAHOOK_SOURCE_PATH` is set; +no SDK library is linked. ```powershell cmake -S . -B build/x86/Release -G "Visual Studio 17 2022" -A Win32 -DMETAHOOK_SOURCE_PATH=../../MetaHook -DCMAKE_INSTALL_PREFIX=install/x86/Release @@ -70,4 +75,6 @@ Optional Visual Studio F5 deployment uses `METAHOOKSV_ENABLE_LAUNCH_GAME=ON` and the shared LaunchGame module; it requires an existing MetaHook installation with this plugin already enabled. Normal builds do not deploy to a game. -Issue: https://github.com/MetaHookSv/MetaHookSv/issues/974 +Issues: +- https://github.com/MetaHookSv/MetaHookSv/issues/974 +- https://github.com/MetaHookSv/MetaHookSv/issues/975 diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 1e3a63a..427e10a 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -1,10 +1,11 @@ -set(METAHOOK_SOURCE_PATH "$ENV{METAHOOK_SOURCE_PATH}" CACHE PATH "MetaHook source tree; empty fetches main") +set(METAHOOK_SOURCE_PATH "$ENV{METAHOOK_SOURCE_PATH}" CACHE PATH "MetaHook source tree; empty fetches the pinned SDK") # The plugin compiles part of the SDK and includes its public headers, so an # external tree must provide both the sources and the interfaces it uses. function(svensoundcachecontrol_validate_metahook_source source) foreach(required include/metahook.h include/HLSDK/common/interface.cpp - include/HLSDK/common/cvardef.h include/Interface/IPlugins.h + include/HLSDK/common/cvardef.h include/HLSDK/common/net_api_svengine.h + include/Interface/IPlugins.h scripts/sync-gamedata.py scripts/validate-gamedata.py) if(NOT EXISTS "${source}/${required}" OR IS_DIRECTORY "${source}/${required}") message(FATAL_ERROR "METAHOOK_SOURCE_PATH is missing ${required}: ${source}") @@ -20,8 +21,8 @@ function(svensoundcachecontrol_prepare_dependencies) include(FetchContent) FetchContent_Declare(svensoundcachecontrol_metahook GIT_REPOSITORY https://github.com/MetaHookSv/MetaHook - # MetaHook is tracked as a branch: always fetch the latest main. - GIT_TAG origin/main + # Includes the SvEngine network ABI types required by this plugin. + GIT_TAG c7c2af7d9dbfee94ae3fb4514e97efb856835ec7 GIT_SUBMODULES "" # This SDK directory has no CMakeLists.txt: populate without building the launcher. SOURCE_SUBDIR include diff --git a/src/privatehook.cpp b/src/privatehook.cpp index 1a5a7ae..27b1fb5 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -2,7 +2,7 @@ #include "soundcache_control.h" #include #include -#include +#include #include static_assert(METAHOOK_API_VERSION >= svensoundcachecontrol::RequiredMetaHookAPIVersion, @@ -38,10 +38,12 @@ ClientCmdFn originalClientCmd = nullptr; // The engine keeps calling the wrapped exports after hooks are removed, so the // originals stay valid until the client is loaded again. HUD_INIT_FUNC originalHudInit = nullptr; +HUD_VIDINIT_FUNC originalHudVidInit = nullptr; HUD_SHUTDOWN_FUNC originalHudShutdown = nullptr; -cvar_t* alwaysFlush = nullptr; -bool loadingSoundList = false; +cvar_t* alwaysFlush = nullptr; +bool loadingSoundList = false; +bool mapRefreshPending = true; SoundcacheControl control; void ReportFailure(const char* symbol, const char* reason) @@ -85,18 +87,22 @@ bool IsEnabled() // Identify the join so a recovery reconnect can be told apart from a new one. void BeginMap() { - net_status_t status = {}; - const auto net = gEngfuncs.pNetAPI; + net_status_svengine_t status = {}; + const auto net = gEngfuncs.pNetAPI; if (net && net->Status) - net->Status(&status); - const char* server = net && net->AdrToString ? net->AdrToString(&status.remote_address) : nullptr; + reinterpret_cast(net->Status)(&status); + const char* server = net && net->AdrToString ? reinterpret_cast(net->AdrToString)(&status.remote_address) : nullptr; const char* map = gEngfuncs.pfnGetLevelName(); control.BeginMap(map ? map : "", server ? server : "", status.remote_address.type == NA_LOOPBACK); } -// The original engine clears its in-memory indices only when the map name changes. -void __fastcall MapStartedHook(void* self, int edx) +// StartSound can load the list before InitHUD calls MapStarted. Refresh once at +// whichever callback arrives first, so the later one preserves freshly loaded sounds. +void PrepareMap(void* self, int edx) { + if (!mapRefreshPending) + return; + mapRefreshPending = false; BeginMap(); if (IsEnabled()) { @@ -106,6 +112,11 @@ void __fastcall MapStartedHook(void* self, int edx) originalFlushCache(self, edx, true); clearSoundArrays(self, edx); } +} + +void __fastcall MapStartedHook(void* self, int edx) +{ + PrepareMap(self, edx); originalMapStarted(self, edx); } @@ -142,6 +153,7 @@ bool __fastcall LoadSoundListHook(void* self, int edx) { if (loadingSoundList) return originalLoadSoundList(self, edx); + PrepareMap(self, edx); // Only observe commands generated by this load, keeping the client's // existing command chain and the engine's asynchronous download behavior. loadingSoundList = true; @@ -169,6 +181,12 @@ void HudShutdownHook() originalHudShutdown(); } +int HudVidInitHook() +{ + mapRefreshPending = true; + return originalHudVidInit(); +} + template bool Hook(const char* symbol, void* address, Fn replacement, Fn* original, hook_t** handle) { @@ -209,8 +227,10 @@ bool InstallHooks(cl_exportfuncs_t* exports) !Hook(LoadSoundListSymbol, loadSoundListAddress, LoadSoundListHook, &originalLoadSoundList, &loadSoundListHook)) return false; originalHudInit = exports->HUD_Init; + originalHudVidInit = exports->HUD_VidInit; originalHudShutdown = exports->HUD_Shutdown; exports->HUD_Init = HudInitHook; + exports->HUD_VidInit = HudVidInitHook; exports->HUD_Shutdown = HudShutdownHook; return true; } @@ -231,6 +251,7 @@ void UninstallHooks() clearSoundArrays = nullptr; clientEngfuncs = nullptr; alwaysFlush = nullptr; + mapRefreshPending = true; control.Reset(); } } // namespace svensoundcachecontrol diff --git a/src/privatehook.h b/src/privatehook.h index c4ff843..f03f6ad 100644 --- a/src/privatehook.h +++ b/src/privatehook.h @@ -13,7 +13,7 @@ using ClearSoundArraysFn = void(__fastcall*)(void* self, int edx); using FlushCacheFn = void(__fastcall*)(void* self, int edx, bool includingLocal); using LoadSoundListFn = bool(__fastcall*)(void* self, int edx); -// Hooks the client sound engine and wraps HUD_Init/HUD_Shutdown in `exports`. +// Hooks the client sound engine and wraps HUD_Init/HUD_VidInit/HUD_Shutdown. bool InstallHooks(cl_exportfuncs_t* exports); void UninstallHooks(); } // namespace svensoundcachecontrol diff --git a/tests/hooks_test.cpp b/tests/hooks_test.cpp index 23d7bf8..07735a5 100644 --- a/tests/hooks_test.cpp +++ b/tests/hooks_test.cpp @@ -3,7 +3,7 @@ #include "soundcache_control.h" #include #include -#include +#include #include #include #include @@ -28,6 +28,16 @@ constexpr const char* FunctionSymbols[] = { }; constexpr const char* ClientEngfuncsSymbol = "gEngfuncs"; +// Byte offsets observed in both Sven engine builds, independent of SDK types. +constexpr std::size_t NativeAddressSize = 36; +constexpr std::size_t NativeStatusSize = 104; +constexpr std::size_t NativeLocalAddressOffset = 4; +constexpr std::size_t NativeRemoteAddressOffset = 40; +constexpr std::size_t NativePacketLossOffset = 76; +constexpr std::size_t NativeLatencyOffset = 80; +constexpr std::size_t NativeConnectionOffset = 88; +constexpr std::size_t NativeRateOffset = 96; + int failures = 0; int installs = 0; int failInstall = 0; @@ -51,6 +61,7 @@ int fullFlushes = 0; int retries = 0; int warnings = 0; int hudInits = 0; +int hudVidInits = 0; int hudShutdowns = 0; svensoundcachecontrol::MapStartedFn hookedMapStarted = nullptr; @@ -67,12 +78,37 @@ void Check(const char* label, int expected, int actual) } const char* Level() { return "maps/test.bsp"; } -char* Address(netadr_t*) { return const_cast(loopback ? "loopback" : "192.0.2.1:27015"); } -int Playback() { return demoPlayback; } -void Status(net_status_t* status) +void NativeAddress(unsigned char* bytes, bool local) +{ + std::memset(bytes, 0xA5, NativeAddressSize); + const int type = local ? NA_LOOPBACK : NA_IP; + std::memcpy(bytes, &type, sizeof(type)); +} +char* Address(netadr_svengine_t* address) +{ + unsigned char expected[NativeAddressSize]; + NativeAddress(expected, loopback); + Check("address conversion receives the complete native remote address", 0, std::memcmp(expected, address, sizeof(expected))); + return const_cast(loopback ? "loopback" : "192.0.2.1:27015"); +} +int Playback() { return demoPlayback; } +void Status(net_status_svengine_t* status) { - status->connected = 1; - status->remote_address.type = loopback ? NA_LOOPBACK : NA_IP; + unsigned char bytes[NativeStatusSize] = {}; + const int connected = 1; + const int packetLoss = 7; + const double latency = 0.125; + const double connectionTime = 12.5; + const double rate = 20000.0; + std::memcpy(bytes, &connected, sizeof(connected)); + NativeAddress(bytes + NativeLocalAddressOffset, true); + NativeAddress(bytes + NativeRemoteAddressOffset, loopback); + std::memcpy(bytes + NativePacketLossOffset, &packetLoss, sizeof(packetLoss)); + std::memcpy(bytes + NativeLatencyOffset, &latency, sizeof(latency)); + std::memcpy(bytes + NativeConnectionOffset, &connectionTime, sizeof(connectionTime)); + std::memcpy(bytes + NativeRateOffset, &rate, sizeof(rate)); + // Write the complete native layout, rather than mirroring SDK field access. + std::memcpy(status, bytes, sizeof(bytes)); } void Printf(const char*, ...) { ++warnings; } cvar_t* GetCvarPointer(const char*) { return nullptr; } @@ -88,6 +124,11 @@ int ClientCmd(const char* command) return 1; } void HudInit() { ++hudInits; } +int HudVidInit() +{ + ++hudVidInits; + return 1; +} void HudShutdown() { ++hudShutdowns; } void __fastcall OriginalMapStarted(void*, int) { ++mapStarts; } @@ -192,6 +233,7 @@ void Reset() clientEngfuncs.pfnClientCmd = ClientCmd; exports = {}; exports.HUD_Init = HudInit; + exports.HUD_VidInit = HudVidInit; exports.HUD_Shutdown = HudShutdown; alwaysFlush = {}; alwaysFlush.value = 1; @@ -203,6 +245,7 @@ void Reset() void Install() { + const int initsBefore = hudInits; Reset(); Check("install succeeds", 1, svensoundcachecontrol::InstallHooks(&exports)); Check("install hooks the sound engine", HookCount, installs); @@ -210,14 +253,75 @@ void Install() Check("repeated install adds no hooks", HookCount, installs); exports.HUD_Init(); Check("HUD_Init registers the cvar", 1, registeredCvar && std::strcmp(registeredCvar, "cl_soundcache_alwaysflush") == 0); - Check("HUD_Init calls the original", 1, hudInits); + Check("HUD_Init calls the original", initsBefore + 1, hudInits); } -void Recovery() +void NetworkABI() +{ + constexpr uint64_t Guard = 0x0123456789abcdef; + struct GuardedStatus + { + uint64_t before; + net_status_svengine_t status; + uint64_t after; + } guarded = {Guard, {}, Guard}; + Status(&guarded.status); + Check("native status write preserves leading guard", 1, guarded.before == Guard); + Check("native status write preserves trailing guard", 1, guarded.after == Guard); + Check("legacy network address ABI is unchanged", 20, sizeof(netadr_t)); + Check("legacy network status ABI is unchanged", 72, sizeof(net_status_t)); + Check("native connected field", 1, guarded.status.connected); + Check("native local address field", NA_LOOPBACK, guarded.status.local_address.type); + Check("native remote address field", NA_IP, guarded.status.remote_address.type); + Check("native packet loss field", 7, guarded.status.packet_loss); + Check("native latency field", 1, guarded.status.latency == 0.125); + Check("native connection time field", 1, guarded.status.connection_time == 12.5); + Check("native rate field", 1, guarded.status.rate == 20000.0); + Address(&guarded.status.remote_address); +} + +void StartMap() +{ + const int vidInitsBefore = hudVidInits; + Check("HUD_VidInit preserves the original result", 1, exports.HUD_VidInit()); + Check("HUD_VidInit calls the original", vidInitsBefore + 1, hudVidInits); + hookedMapStarted(nullptr, 0); +} + +void EarlySoundLoad() { Install(); + const int retriesBefore = retries; + diskList = true; + soundsLoaded = true; + exports.HUD_VidInit(); + Check("early missing list requests recovery", 0, hookedLoadSoundList(nullptr, 0)); + Check("early load invalidates the previous disk list", 0, diskList); + Check("early load discards previous sound indices", 0, soundsLoaded); + Check("early load permits one recovery retry", retriesBefore + 1, retries); + diskList = true; + exports.HUD_VidInit(); + Check("recovery loads sounds before the map callback", 1, hookedLoadSoundList(nullptr, 0)); + const int clearsBeforeCallback = clears; + const int flushesBeforeCallback = fullFlushes; hookedMapStarted(nullptr, 0); + Check("late map callback preserves freshly loaded sounds", 1, soundsLoaded); + Check("late map callback does not clear sounds again", clearsBeforeCallback, clears); + Check("late map callback does not invalidate the list again", flushesBeforeCallback, fullFlushes); + Check("late map callback cannot restart recovery", retriesBefore + 1, retries); + + diskList = true; + StartMap(); + Check("next same-map join still refreshes memory", 0, soundsLoaded); + Check("next same-map join still invalidates its list", 0, diskList); +} + +void Recovery() +{ + Install(); + diskList = true; + StartMap(); Check("join invalidates stale disk list", 0, diskList); Check("join resets memory", 1, clears); Check("join preserves original map callback", 1, mapStarts); @@ -228,7 +332,7 @@ void Recovery() diskList = true; // Simulate completion of the queued download. hookedFlushCache(nullptr, 0, false); Check("disconnect does not delete completed recovery download", 1, diskList); - hookedMapStarted(nullptr, 0); + StartMap(); Check("recovery join preserves downloaded file", 1, diskList); Check("recovery consumes the new list", 1, hookedLoadSoundList(nullptr, 0)); Check("sound indices are populated", 1, soundsLoaded); @@ -236,11 +340,11 @@ void Recovery() Check("command chain restored after successful load", 1, clientEngfuncs.pfnClientCmd == ClientCmd); diskList = true; // A queued request can recreate the file after loading. - hookedMapStarted(nullptr, 0); + StartMap(); Check("subsequent same-map join invalidates asynchronously recreated list", 0, diskList); Check("same-map join discards previous indices", 0, soundsLoaded); hookedLoadSoundList(nullptr, 0); - hookedMapStarted(nullptr, 0); + StartMap(); hookedLoadSoundList(nullptr, 0); // Download remains unavailable on recovery join. hookedLoadSoundList(nullptr, 0); Check("failed transfer does not produce a reconnect loop", 2, retries); @@ -254,7 +358,7 @@ void VanillaModes() const int clearsBeforeDisable = clears; const int flushesBeforeDisable = fullFlushes; diskList = true; - hookedMapStarted(nullptr, 0); + StartMap(); hookedLoadSoundList(nullptr, 0); Check("disabled mode retains vanilla disk behavior", 1, diskList); Check("disabled mode does not force a memory reset", clearsBeforeDisable, clears); @@ -263,13 +367,13 @@ void VanillaModes() alwaysFlush.value = 1; loopback = true; diskList = true; - hookedMapStarted(nullptr, 0); + StartMap(); Check("listen host loads generated sound list", 1, hookedLoadSoundList(nullptr, 0)); Check("listen host leaves server download source intact", 1, diskList); demoPlayback = true; const int clearsBeforeDemo = clears; - hookedMapStarted(nullptr, 0); + StartMap(); Check("demo playback uses original memory behavior", clearsBeforeDemo, clears); loopback = false; demoPlayback = false; @@ -300,7 +404,7 @@ void Failures() missingSymbol = symbol; Check("missing symbol fails", 0, svensoundcachecontrol::InstallHooks(&exports)); Check("missing symbol installs nothing", 0, installs); - Check("missing symbol keeps exports", 1, exports.HUD_Init == HudInit && exports.HUD_Shutdown == HudShutdown); + Check("missing symbol keeps exports", 1, exports.HUD_Init == HudInit && exports.HUD_VidInit == HudVidInit && exports.HUD_Shutdown == HudShutdown); Check("error names symbol", 1, std::strstr(error, symbol) != nullptr); Check("error contains CRC64", 1, std::strstr(error, "0000000000001234") != nullptr); Check("error contains build", 1, std::strstr(error, "10257") != nullptr); @@ -312,7 +416,7 @@ void Failures() failInstall = failed; Check("hook failure fails installation", 0, svensoundcachecontrol::InstallHooks(&exports)); Check("hook failure rolls back prior hooks", failed - 1, static_cast(removed.size())); - Check("hook failure keeps exports", 1, exports.HUD_Init == HudInit && exports.HUD_Shutdown == HudShutdown); + Check("hook failure keeps exports", 1, exports.HUD_Init == HudInit && exports.HUD_VidInit == HudVidInit && exports.HUD_Shutdown == HudShutdown); svensoundcachecontrol::UninstallHooks(); Check("rollback leaves no hooks", failed - 1, static_cast(removed.size())); Check("hook failure diagnostic", 1, std::strstr(error, "InlineHook failed") != nullptr); @@ -337,8 +441,8 @@ int main() api.UnHook = UnHook; g_pMetaHookAPI = &api; net_api_t net = {}; - net.Status = Status; - net.AdrToString = Address; + net.Status = reinterpret_cast(Status); + net.AdrToString = reinterpret_cast(Address); demo_api_t demo = {}; demo.IsPlayingback = Playback; gEngfuncs.pNetAPI = &net; @@ -347,9 +451,11 @@ int main() gEngfuncs.Con_Printf = Printf; gEngfuncs.pfnGetCvarPointer = GetCvarPointer; gEngfuncs.pfnRegisterVariable = RegisterVariable; + NetworkABI(); Recovery(); VanillaModes(); Shutdown(); + EarlySoundLoad(); Failures(); std::printf("SvenSoundcacheControl hooks: %d failure(s)\n", failures); return failures ? 1 : 0;