diff --git a/CMakeLists.txt b/CMakeLists.txt index 673fa38..09291fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,27 @@ if(MSVC) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() +# --- SDL3 via FetchContent ---------------------------------------------------- +# Static-only build, no tests, no install. SDL3 inherits CMAKE_MSVC_RUNTIME_LIBRARY +# (policy CMP0091 NEW), so it links the same /MT[d] CRT as 4JLibs and the host exe. +include(FetchContent) + +set(SDL_SHARED OFF CACHE BOOL "" FORCE) +set(SDL_STATIC ON CACHE BOOL "" FORCE) +set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) +set(SDL_TESTS OFF CACHE BOOL "" FORCE) +set(SDL_INSTALL OFF CACHE BOOL "" FORCE) +set(SDL_DISABLE_INSTALL ON CACHE BOOL "" FORCE) + +FetchContent_Declare( + SDL3 + GIT_REPOSITORY https://github.com/libsdl-org/SDL.git + GIT_TAG release-3.2.0 + GIT_SHALLOW TRUE +) +FetchContent_MakeAvailable(SDL3) +# ----------------------------------------------------------------------------- + if(WIN32) add_subdirectory(impls/Windows_Libs) else() diff --git a/build_libs.bat b/build_libs.bat new file mode 100644 index 0000000..18ecfa5 --- /dev/null +++ b/build_libs.bat @@ -0,0 +1,30 @@ +@echo off +setlocal +call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >NUL 2>&1 +cd /d "C:\Users\MrTheShy\Documents\ghubb\4JLibs-master\4JLibs" + +echo === Configure Debug === +cmake -S . -B out\build\x64-Debug -G Ninja -DCMAKE_BUILD_TYPE=Debug +if errorlevel 1 exit /b 1 + +echo === Build Debug (Input + Render) === +cmake --build out\build\x64-Debug --target 4JLibs.Windows64.Input 4JLibs.Windows64.Render +if errorlevel 1 exit /b 1 + +echo === Configure Release === +cmake -S . -B out\build\x64-Release -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo +if errorlevel 1 exit /b 1 + +echo === Build Release (Input + Render) === +cmake --build out\build\x64-Release --target 4JLibs.Windows64.Input 4JLibs.Windows64.Render +if errorlevel 1 exit /b 1 + +echo === Copy SDL3 static libs to libs/ === +copy /Y out\build\x64-Debug\_deps\sdl3-build\SDL3-static_d.lib libs\ >NUL +copy /Y out\build\x64-Debug\_deps\sdl3-build\SDL_uclibc_d.lib libs\ >NUL +copy /Y out\build\x64-Release\_deps\sdl3-build\SDL3-static.lib libs\ >NUL +copy /Y out\build\x64-Release\_deps\sdl3-build\SDL_uclibc.lib libs\ >NUL + +echo === Done. Output libs at: === +dir /b libs\*.lib 2>nul +exit /b 0 diff --git a/configure_only.bat b/configure_only.bat new file mode 100644 index 0000000..8fc5e23 --- /dev/null +++ b/configure_only.bat @@ -0,0 +1,7 @@ +@echo off +setlocal +call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >NUL 2>&1 +cd /d "C:\Users\MrTheShy\Documents\ghubb\4JLibs-master\4JLibs" +echo === Configure Debug (SDL3 fetch test) === +cmake -S . -B out\build\x64-Debug -G Ninja -DCMAKE_BUILD_TYPE=Debug +exit /b %ERRORLEVEL% diff --git a/impls/Windows_Libs/Input/CMakeLists.txt b/impls/Windows_Libs/Input/CMakeLists.txt index 3f91148..7290bf5 100644 --- a/impls/Windows_Libs/Input/CMakeLists.txt +++ b/impls/Windows_Libs/Input/CMakeLists.txt @@ -7,15 +7,21 @@ add_library(${PROJECT_NAME} STATIC src/INP_ForceFeedback.cpp src/INP_Keyboard.cpp src/INP_Main.cpp + src/INP_SdlBridge.cpp src/INP_StringCheck.cpp src/LinkedList.cpp src/stdafx.cpp ) -target_link_libraries(${PROJECT_NAME} PUBLIC +target_link_libraries(${PROJECT_NAME} PUBLIC 4JLibs.Globals ) +# SDL3 (static) — used by INP_SdlBridge to replace XInput as the gamepad backend. +target_link_libraries(${PROJECT_NAME} PRIVATE + SDL3::SDL3-static +) + target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/inc ) diff --git a/impls/Windows_Libs/Input/inc/INP_Main.h b/impls/Windows_Libs/Input/inc/INP_Main.h index 63d24b9..8f87459 100644 --- a/impls/Windows_Libs/Input/inc/INP_Main.h +++ b/impls/Windows_Libs/Input/inc/INP_Main.h @@ -26,7 +26,13 @@ SOFTWARE. #include "INP_ForceFeedback.h" #include "INP_Keyboard.h" -#define MAX_JOYPADS 4 +// Bumped from 4 to 8 for N-player splitscreen on Win64. The original +// 4-pad limit reflected the XInput hardware cap (one of the lib's input +// backends), but the per-pad arrays below (m_Joypads, m_bIsMenuDisplayed, +// m_Timers, m_LastActivityTime) live entirely in our address space and +// can be sized to whatever the project needs. Calls into XInput still +// silently no-op for indices >= 4 — that's a hardware truth, not a lib limit. +#define MAX_JOYPADS 8 class CInput { diff --git a/impls/Windows_Libs/Input/inc/INP_SdlBridge.h b/impls/Windows_Libs/Input/inc/INP_SdlBridge.h new file mode 100644 index 0000000..090fe66 --- /dev/null +++ b/impls/Windows_Libs/Input/inc/INP_SdlBridge.h @@ -0,0 +1,13 @@ +#pragma once + +#include "stdafx.h" + +namespace SdlBridge +{ + void Init(); + void Shutdown(); + void Tick(); + + DWORD PollPadAsXInput(int padIdx, XINPUT_STATE* out); + DWORD SetRumble(int padIdx, WORD lo, WORD hi); +} diff --git a/impls/Windows_Libs/Input/src/4J_Input.cpp b/impls/Windows_Libs/Input/src/4J_Input.cpp index 8fec45d..033e3ae 100644 --- a/impls/Windows_Libs/Input/src/4J_Input.cpp +++ b/impls/Windows_Libs/Input/src/4J_Input.cpp @@ -25,17 +25,20 @@ SOFTWARE. #include "4J_Input.h" #include "INP_Keyboard.h" #include "INP_Main.h" +#include "INP_SdlBridge.h" C_4JInput InputManager; CKeyboard InternalKeyboard; void C_4JInput::Initialise(int iInputStateC, unsigned char ucMapC, unsigned char ucActionC, unsigned char ucMenuActionC) { + SdlBridge::Init(); InternalInputManager.Initialise(iInputStateC, ucMapC, ucActionC, ucMenuActionC); } void C_4JInput::Tick(void) { + SdlBridge::Tick(); InternalInputManager.Tick(); } @@ -154,6 +157,11 @@ void C_4JInput::SetMenuDisplayed(int iPad, bool bVal) InternalInputManager.SetMenuDisplayed(iPad, bVal); } +DWORD C_4JInput::PollPadAsXInput(int iPad, struct _XINPUT_STATE* outState) +{ + return SdlBridge::PollPadAsXInput(iPad, outState); +} + EKeyboardResult C_4JInput::RequestKeyboard(LPCWSTR Title, LPCWSTR Text, DWORD dwPad, UINT uiMaxChars, int (*Func)(LPVOID, const bool), LPVOID lpParam, C_4JInput::EKeyboardMode eMode) { diff --git a/impls/Windows_Libs/Input/src/INP_ForceFeedback.cpp b/impls/Windows_Libs/Input/src/INP_ForceFeedback.cpp index 804615c..69fe2ee 100644 --- a/impls/Windows_Libs/Input/src/INP_ForceFeedback.cpp +++ b/impls/Windows_Libs/Input/src/INP_ForceFeedback.cpp @@ -23,6 +23,7 @@ SOFTWARE. */ #include "INP_ForceFeedback.h" +#include "INP_SdlBridge.h" void CForceFeedback::Initialise(int iInputStateC, unsigned char ucMapC, unsigned char ucActionC, unsigned char ucMenuActionC) { @@ -115,7 +116,9 @@ void CForceFeedback::Tick(void) pRumble->m_RumbleData.wLeftMotorSpeed = 0; pRumble->m_RumbleData.wRightMotorSpeed = 0; - XInputSetState(pRumble->m_Pad, &pRumble->m_RumbleData); + SdlBridge::SetRumble(pRumble->m_Pad, + pRumble->m_RumbleData.wLeftMotorSpeed, + pRumble->m_RumbleData.wRightMotorSpeed); m_RumbleList.RemoveNode(pRumbleNode); @@ -127,7 +130,9 @@ void CForceFeedback::Tick(void) } else { - XInputSetState(pRumbleNode->GetDataAs()->m_Pad, &pRumbleNode->GetDataAs()->m_RumbleData); + SdlBridge::SetRumble(pRumbleNode->GetDataAs()->m_Pad, + pRumbleNode->GetDataAs()->m_RumbleData.wLeftMotorSpeed, + pRumbleNode->GetDataAs()->m_RumbleData.wRightMotorSpeed); pRumbleNode = pRumbleNode->m_Next; } } diff --git a/impls/Windows_Libs/Input/src/INP_Main.cpp b/impls/Windows_Libs/Input/src/INP_Main.cpp index 9953243..39ab836 100644 --- a/impls/Windows_Libs/Input/src/INP_Main.cpp +++ b/impls/Windows_Libs/Input/src/INP_Main.cpp @@ -23,6 +23,7 @@ SOFTWARE. */ #include "INP_Main.h" +#include "INP_SdlBridge.h" CInput InternalInputManager; @@ -32,7 +33,7 @@ CInput::CInput() m_Keyboard = CKeyboard(); m_uiSigninJoypadMask = 0; - for (int i = 0; i < 4; ++i) + for (int i = 0; i < MAX_JOYPADS; ++i) m_bIsMenuDisplayed[i] = 0; InitTime(); @@ -621,7 +622,7 @@ bool CInput::UpdateJoypads() pThisPad->m_ucInputStateIndex = 0; } - pThisPad->m_bIsConnected = XInputGetState(i, &pThisPad->m_pInputStates[pThisPad->m_ucInputStateIndex]) == 0; + pThisPad->m_bIsConnected = SdlBridge::PollPadAsXInput(i, &pThisPad->m_pInputStates[pThisPad->m_ucInputStateIndex]) == 0; bool bWasConnected = bOldIsConnected && !pThisPad->m_bIsConnected; pThisPad->m_bWasConnected = bWasConnected; diff --git a/impls/Windows_Libs/Input/src/INP_SdlBridge.cpp b/impls/Windows_Libs/Input/src/INP_SdlBridge.cpp new file mode 100644 index 0000000..9fa891f --- /dev/null +++ b/impls/Windows_Libs/Input/src/INP_SdlBridge.cpp @@ -0,0 +1,410 @@ +#include "INP_SdlBridge.h" +#include "INP_Main.h" + +#include + +#include +#include + +namespace +{ + SDL_Gamepad* g_pads[MAX_JOYPADS] = {}; + bool g_initialised = false; + + // Last reported XInput button bitmask, for per-poll delta logging. + WORD g_lastButtons[MAX_JOYPADS] = {}; + + FILE* g_logFile = nullptr; + + void LogV(const char* fmt, va_list ap) + { + char buf[2048]; + vsnprintf(buf, sizeof(buf), fmt, ap); + OutputDebugStringA("[SdlBridge] "); + OutputDebugStringA(buf); + OutputDebugStringA("\n"); + if (g_logFile) + { + fputs("[SdlBridge] ", g_logFile); + fputs(buf, g_logFile); + fputc('\n', g_logFile); + fflush(g_logFile); + } + } + + void Log(const char* fmt, ...) + { + va_list ap; + va_start(ap, fmt); + LogV(fmt, ap); + va_end(ap); + } + + void SDLCALL SdlLogSink(void*, int category, SDL_LogPriority priority, const char* message) + { + const char* p = "?"; + switch (priority) + { + case SDL_LOG_PRIORITY_TRACE: p = "TRC"; break; + case SDL_LOG_PRIORITY_VERBOSE: p = "VRB"; break; + case SDL_LOG_PRIORITY_DEBUG: p = "DBG"; break; + case SDL_LOG_PRIORITY_INFO: p = "INF"; break; + case SDL_LOG_PRIORITY_WARN: p = "WRN"; break; + case SDL_LOG_PRIORITY_ERROR: p = "ERR"; break; + case SDL_LOG_PRIORITY_CRITICAL: p = "CRT"; break; + default: break; + } + char buf[2048]; + snprintf(buf, sizeof(buf), "[SDL/%s/cat=%d] %s", p, category, message); + OutputDebugStringA(buf); + OutputDebugStringA("\n"); + if (g_logFile) + { + fputs(buf, g_logFile); + fputc('\n', g_logFile); + fflush(g_logFile); + } + } + + const char* GamepadTypeName(SDL_GamepadType t) + { + switch (t) + { + case SDL_GAMEPAD_TYPE_UNKNOWN: return "UNKNOWN"; + case SDL_GAMEPAD_TYPE_STANDARD: return "STANDARD"; + case SDL_GAMEPAD_TYPE_XBOX360: return "XBOX360"; + case SDL_GAMEPAD_TYPE_XBOXONE: return "XBOXONE"; + case SDL_GAMEPAD_TYPE_PS3: return "PS3"; + case SDL_GAMEPAD_TYPE_PS4: return "PS4"; + case SDL_GAMEPAD_TYPE_PS5: return "PS5"; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: return "SWITCH_PRO"; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: return "JOYCON_L"; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: return "JOYCON_R"; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return "JOYCON_PAIR"; + default: return "?"; + } + } + + void DumpPad(int slot, SDL_Gamepad* gp) + { + SDL_JoystickID id = SDL_GetGamepadID(gp); + const char* name = SDL_GetGamepadName(gp); + SDL_GamepadType type = SDL_GetGamepadType(gp); + Uint16 vendor = SDL_GetGamepadVendor(gp); + Uint16 product= SDL_GetGamepadProduct(gp); + Uint16 pver = SDL_GetGamepadProductVersion(gp); + const char* path = SDL_GetGamepadPath(gp); + const char* serial = SDL_GetGamepadSerial(gp); + const char* mapping= SDL_GetGamepadMapping(gp); + + SDL_PropertiesID props = SDL_GetGamepadProperties(gp); + bool capRumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); + bool capTrigRum = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); + bool capLED = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN, false); + bool capPlayerLED= SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN, false); + bool capGyro = SDL_GamepadHasSensor(gp, SDL_SENSOR_GYRO); + bool capAccel = SDL_GamepadHasSensor(gp, SDL_SENSOR_ACCEL); + + Log("PAD slot=%d id=%u type=%s name='%s' vid=%04x pid=%04x ver=%04x", + slot, (unsigned)id, GamepadTypeName(type), + name ? name : "(null)", vendor, product, pver); + Log(" path='%s'", path ? path : "(null)"); + Log(" serial='%s'", serial ? serial : "(null)"); + Log(" caps: rumble=%d trigRumble=%d LED=%d playerLED=%d gyro=%d accel=%d", + capRumble, capTrigRum, capLED, capPlayerLED, capGyro, capAccel); + if (mapping) + { + Log(" mapping='%s'", mapping); + SDL_free((void*)mapping); + } + } + + int FindSlotByJoystickID(SDL_JoystickID id) + { + for (int i = 0; i < MAX_JOYPADS; ++i) + if (g_pads[i] && SDL_GetGamepadID(g_pads[i]) == id) + return i; + return -1; + } + + int FindFreeSlot() + { + for (int i = 0; i < MAX_JOYPADS; ++i) + if (!g_pads[i]) + return i; + return -1; + } + + void OpenIntoFreeSlot(SDL_JoystickID id) + { + if (FindSlotByJoystickID(id) >= 0) + { + Log("OpenIntoFreeSlot: id=%u already open, skipping", (unsigned)id); + return; + } + int slot = FindFreeSlot(); + if (slot < 0) + { + Log("OpenIntoFreeSlot: id=%u — NO FREE SLOT (all %d full)", (unsigned)id, MAX_JOYPADS); + return; + } + SDL_Gamepad* gp = SDL_OpenGamepad(id); + if (!gp) + { + Log("OpenIntoFreeSlot: id=%u — SDL_OpenGamepad FAILED: %s", (unsigned)id, SDL_GetError()); + return; + } + g_pads[slot] = gp; + g_lastButtons[slot] = 0; + Log("OPENED into slot %d:", slot); + DumpPad(slot, gp); + } + + void CloseSlotByJoystickID(SDL_JoystickID id) + { + int slot = FindSlotByJoystickID(id); + if (slot < 0) + { + Log("CloseSlotByJoystickID: id=%u not found in any slot", (unsigned)id); + return; + } + Log("CLOSED slot %d (id=%u)", slot, (unsigned)id); + SDL_CloseGamepad(g_pads[slot]); + g_pads[slot] = nullptr; + g_lastButtons[slot] = 0; + } + + Sint16 InvertY(Sint16 v) + { + return v == -32768 ? 32767 : -v; + } + + void LogButtonDelta(int slot, WORD prev, WORD now, BYTE lt, BYTE rt) + { + WORD diff = prev ^ now; + if (!diff) + return; + char downs[256] = {0}; + char ups[256] = {0}; + struct { WORD bit; const char* n; } map[] = { + {XINPUT_GAMEPAD_DPAD_UP, "DUP"}, {XINPUT_GAMEPAD_DPAD_DOWN, "DDN"}, + {XINPUT_GAMEPAD_DPAD_LEFT,"DLT"}, {XINPUT_GAMEPAD_DPAD_RIGHT,"DRT"}, + {XINPUT_GAMEPAD_START,"STA"}, {XINPUT_GAMEPAD_BACK,"BCK"}, + {XINPUT_GAMEPAD_LEFT_THUMB,"LSC"}, {XINPUT_GAMEPAD_RIGHT_THUMB,"RSC"}, + {XINPUT_GAMEPAD_LEFT_SHOULDER,"LB"}, {XINPUT_GAMEPAD_RIGHT_SHOULDER,"RB"}, + {XINPUT_GAMEPAD_A,"A"}, {XINPUT_GAMEPAD_B,"B"}, + {XINPUT_GAMEPAD_X,"X"}, {XINPUT_GAMEPAD_Y,"Y"}, + }; + for (auto& m : map) + { + if (diff & m.bit) + { + char* dst = (now & m.bit) ? downs : ups; + size_t cur = strlen(dst); + snprintf(dst + cur, sizeof(downs) - cur, "%s%s", cur ? "+" : "", m.n); + } + } + Log("slot=%d DOWN=[%s] UP=[%s] LT=%u RT=%u", slot, downs, ups, lt, rt); + } +} + +namespace SdlBridge +{ + void Init() + { + if (g_initialised) + return; + + g_logFile = fopen("sdl_input.log", "w"); + if (g_logFile) + fputs("=== SdlBridge log start ===\n", g_logFile); + + SDL_SetLogOutputFunction(SdlLogSink, nullptr); + SDL_SetLogPriorities(SDL_LOG_PRIORITY_VERBOSE); + + int cv = SDL_GetVersion(); + Log("Init: SDL runtime version = %d.%d.%d (compiled %d.%d.%d)", + SDL_VERSIONNUM_MAJOR(cv), SDL_VERSIONNUM_MINOR(cv), SDL_VERSIONNUM_MICRO(cv), + SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION); + Log("Init: revision='%s'", SDL_GetRevision()); + Log("Init: MAX_JOYPADS=%d", MAX_JOYPADS); + + SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); + Log("Init: hint JOYSTICK_ALLOW_BACKGROUND_EVENTS=1"); + + if (!SDL_Init(SDL_INIT_GAMEPAD)) + { + Log("Init: SDL_Init(GAMEPAD) FAILED: %s", SDL_GetError()); + return; + } + Log("Init: SDL_Init(GAMEPAD) ok"); + + // Community SDL_GameControllerDB: covers DInput pads (8BitDo, generic + // USB, Switch Pro etc.) that SDL3's built-in mapping list misses. + // Try the asset-relative path first (cwd is exe dir at runtime), then + // a flat fallback for users who run the exe from elsewhere. + const char* dbPaths[] = { + "Common/res/gamecontrollerdb.txt", + "gamecontrollerdb.txt", + }; + bool dbLoaded = false; + for (const char* path : dbPaths) + { + int n = SDL_AddGamepadMappingsFromFile(path); + if (n >= 0) + { + Log("Init: loaded %d mappings from '%s'", n, path); + dbLoaded = true; + break; + } + Log("Init: tried '%s' -> %s", path, SDL_GetError()); + } + if (!dbLoaded) + Log("Init: WARNING gamecontrollerdb.txt not loaded — DInput-only pads will not be recognised"); + + int count = 0; + SDL_JoystickID* ids = SDL_GetGamepads(&count); + Log("Init: SDL_GetGamepads returned count=%d", count); + if (ids) + { + for (int i = 0; i < count; ++i) + { + Log("Init: enumerating index %d -> id=%u name='%s'", + i, (unsigned)ids[i], + SDL_GetGamepadNameForID(ids[i]) ? SDL_GetGamepadNameForID(ids[i]) : "(null)"); + OpenIntoFreeSlot(ids[i]); + } + SDL_free(ids); + } + + // Also enumerate raw joysticks SDL sees but didn't recognize as gamepads. + // Useful when the user reports "SDL doesn't see my pad" — if it shows up + // here but not as a gamepad, the pad is missing a controller mapping. + int jcount = 0; + SDL_JoystickID* jids = SDL_GetJoysticks(&jcount); + Log("Init: SDL_GetJoysticks returned count=%d (vs %d gamepads)", jcount, count); + if (jids) + { + for (int i = 0; i < jcount; ++i) + { + bool isGp = SDL_IsGamepad(jids[i]); + SDL_GUID guid = SDL_GetJoystickGUIDForID(jids[i]); + char guidStr[33] = {0}; + SDL_GUIDToString(guid, guidStr, sizeof(guidStr)); + Log("Init: joystick idx=%d id=%u isGamepad=%d guid=%s name='%s'", + i, (unsigned)jids[i], isGp, guidStr, + SDL_GetJoystickNameForID(jids[i]) ? SDL_GetJoystickNameForID(jids[i]) : "(null)"); + } + SDL_free(jids); + } + + g_initialised = true; + Log("Init: done"); + } + + void Shutdown() + { + if (!g_initialised) + return; + Log("Shutdown: closing %d slot(s)", MAX_JOYPADS); + for (int i = 0; i < MAX_JOYPADS; ++i) + { + if (g_pads[i]) + { + SDL_CloseGamepad(g_pads[i]); + g_pads[i] = nullptr; + } + } + SDL_QuitSubSystem(SDL_INIT_GAMEPAD); + g_initialised = false; + if (g_logFile) + { + fputs("=== SdlBridge log end ===\n", g_logFile); + fclose(g_logFile); + g_logFile = nullptr; + } + } + + void Tick() + { + if (!g_initialised) + return; + + SDL_PumpEvents(); + + SDL_Event ev; + while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, + SDL_EVENT_GAMEPAD_ADDED, SDL_EVENT_GAMEPAD_REMOVED) > 0) + { + if (ev.type == SDL_EVENT_GAMEPAD_ADDED) + { + Log("EVENT: GAMEPAD_ADDED id=%u", (unsigned)ev.gdevice.which); + OpenIntoFreeSlot(ev.gdevice.which); + } + else if (ev.type == SDL_EVENT_GAMEPAD_REMOVED) + { + Log("EVENT: GAMEPAD_REMOVED id=%u", (unsigned)ev.gdevice.which); + CloseSlotByJoystickID(ev.gdevice.which); + } + } + } + + DWORD PollPadAsXInput(int padIdx, XINPUT_STATE* out) + { + if (!out) + return ERROR_BAD_ARGUMENTS; + ZeroMemory(out, sizeof(*out)); + + if (!g_initialised || padIdx < 0 || padIdx >= MAX_JOYPADS || !g_pads[padIdx]) + return ERROR_DEVICE_NOT_CONNECTED; + + SDL_Gamepad* gp = g_pads[padIdx]; + if (!SDL_GamepadConnected(gp)) + return ERROR_DEVICE_NOT_CONNECTED; + + XINPUT_GAMEPAD* p = &out->Gamepad; + WORD bts = 0; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_DPAD_UP)) bts |= XINPUT_GAMEPAD_DPAD_UP; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_DPAD_DOWN)) bts |= XINPUT_GAMEPAD_DPAD_DOWN; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_DPAD_LEFT)) bts |= XINPUT_GAMEPAD_DPAD_LEFT; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_DPAD_RIGHT)) bts |= XINPUT_GAMEPAD_DPAD_RIGHT; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_START)) bts |= XINPUT_GAMEPAD_START; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_BACK)) bts |= XINPUT_GAMEPAD_BACK; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_LEFT_STICK)) bts |= XINPUT_GAMEPAD_LEFT_THUMB; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_RIGHT_STICK)) bts |= XINPUT_GAMEPAD_RIGHT_THUMB; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER)) bts |= XINPUT_GAMEPAD_LEFT_SHOULDER; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER)) bts |= XINPUT_GAMEPAD_RIGHT_SHOULDER; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_SOUTH)) bts |= XINPUT_GAMEPAD_A; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_EAST)) bts |= XINPUT_GAMEPAD_B; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_WEST)) bts |= XINPUT_GAMEPAD_X; + if (SDL_GetGamepadButton(gp, SDL_GAMEPAD_BUTTON_NORTH)) bts |= XINPUT_GAMEPAD_Y; + p->wButtons = bts; + + Sint16 lt = SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFT_TRIGGER); + Sint16 rt = SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER); + p->bLeftTrigger = (BYTE)(lt < 0 ? 0 : (lt > 32767 ? 255 : (lt * 255 / 32767))); + p->bRightTrigger = (BYTE)(rt < 0 ? 0 : (rt > 32767 ? 255 : (rt * 255 / 32767))); + + p->sThumbLX = SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFTX); + p->sThumbLY = InvertY( SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFTY) ); + p->sThumbRX = SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHTX); + p->sThumbRY = InvertY( SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHTY) ); + + out->dwPacketNumber = SDL_GetTicks(); + + LogButtonDelta(padIdx, g_lastButtons[padIdx], bts, p->bLeftTrigger, p->bRightTrigger); + g_lastButtons[padIdx] = bts; + + return ERROR_SUCCESS; + } + + DWORD SetRumble(int padIdx, WORD lo, WORD hi) + { + if (!g_initialised || padIdx < 0 || padIdx >= MAX_JOYPADS || !g_pads[padIdx]) + return ERROR_DEVICE_NOT_CONNECTED; + Uint32 dur = (lo == 0 && hi == 0) ? 0 : 250; + bool ok = SDL_RumbleGamepad(g_pads[padIdx], lo, hi, dur); + Log("Rumble slot=%d lo=%u hi=%u dur=%ums ok=%d", padIdx, lo, hi, (unsigned)dur, ok); + return ERROR_SUCCESS; + } +} diff --git a/impls/Windows_Libs/Render/inc/Renderer.h b/impls/Windows_Libs/Render/inc/Renderer.h index 66378bd..6c9fdfa 100644 --- a/impls/Windows_Libs/Render/inc/Renderer.h +++ b/impls/Windows_Libs/Render/inc/Renderer.h @@ -142,6 +142,7 @@ public: void StateSetLightDirection(int light, float x, float y, float z); void StateSetLightEnable(int light, bool enable); void StateSetViewport(C4JRender::eViewportType viewportType); + void StateSetViewportRect(float x, float y, float w, float h); void StateSetEnableViewportClipPlanes(bool enable); void StateSetTexGenCol(int col, float x, float y, float z, float w, bool eyeSpace); void StateSetStencil(D3D11_COMPARISON_FUNC function, uint8_t stencil_ref, uint8_t stencil_func_mask, uint8_t stencil_write_mask); diff --git a/impls/Windows_Libs/Render/src/4J_Render.cpp b/impls/Windows_Libs/Render/src/4J_Render.cpp index 8eaab0b..6d78ec1 100644 --- a/impls/Windows_Libs/Render/src/4J_Render.cpp +++ b/impls/Windows_Libs/Render/src/4J_Render.cpp @@ -457,6 +457,11 @@ void C4JRender::StateSetViewport(eViewportType viewportType) InternalRenderManager.StateSetViewport(viewportType); } +void C4JRender::StateSetViewportRect(float x, float y, float w, float h) +{ + InternalRenderManager.StateSetViewportRect(x, y, w, h); +} + void C4JRender::StateSetEnableViewportClipPlanes(bool enable) { InternalRenderManager.StateSetEnableViewportClipPlanes(enable); diff --git a/impls/Windows_Libs/Render/src/RendererState.cpp b/impls/Windows_Libs/Render/src/RendererState.cpp index 49ab0b5..75a0d56 100644 --- a/impls/Windows_Libs/Render/src/RendererState.cpp +++ b/impls/Windows_Libs/Render/src/RendererState.cpp @@ -579,6 +579,52 @@ void Renderer::StateSetViewport(C4JRender::eViewportType viewportType) m_pDeviceContext->RSSetViewports(1, &viewport); m_pDeviceContext->OMSetRenderTargets(1, &mainRenderTargetView, depthStencilView); + + // 4-player splitscreen fix: a viewport switch happens between every pad's + // GameRenderer::render. The dirty-flag cache (matrices, shaders, lighting) + // must be invalidated so the next CBuffCall re-uploads everything for the + // new pad. In Debug the heap fill pattern (0xCD) accidentally kept these + // marked dirty; in Release they could stay false and pad N would draw + // with pad N-1's matrices/state -> world rendered off-screen / black. + { + Context &c = getContext(); + for (UINT i = 0; i < MATRIX_MODE_MODELVIEW_MAX; ++i) + c.matrixDirty[i] = true; + c.lightingDirty = true; + activeVertexType = static_cast(-1); + activePixelType = static_cast(-1); + } +} + + +void Renderer::StateSetViewportRect(float x, float y, float w, float h) +{ + getContext(); + // Sentinel so legacy code paths (e.g. CaptureThumbnail's switch on m_ViewportType) + // see a known enum and don't fall into a default that leaves stack-uninit values + // on a D3D11_VIEWPORT before RSSetViewports. + m_ViewportType = C4JRender::VIEWPORT_TYPE_FULLSCREEN; + + D3D11_VIEWPORT viewport = {}; + viewport.TopLeftX = x; + viewport.TopLeftY = y; + viewport.Width = w; + viewport.Height = h; + viewport.MinDepth = 0.0f; + viewport.MaxDepth = 1.0f; + + m_pDeviceContext->RSSetViewports(1, &viewport); + m_pDeviceContext->OMSetRenderTargets(1, &mainRenderTargetView, depthStencilView); + + // Same invalidation as StateSetViewport — N-player grid path also needs it. + { + Context &c = getContext(); + for (UINT i = 0; i < MATRIX_MODE_MODELVIEW_MAX; ++i) + c.matrixDirty[i] = true; + c.lightingDirty = true; + activeVertexType = static_cast(-1); + activePixelType = static_cast(-1); + } } diff --git a/inc/4J_Input.h b/inc/4J_Input.h index 3083e99..b66627f 100644 --- a/inc/4J_Input.h +++ b/inc/4J_Input.h @@ -107,6 +107,11 @@ public: void SetMenuDisplayed(int iPad, bool bVal); + // SDL3-backed alternative to XInputGetState. Use this for any code that + // previously read pad state directly via XInput — going through the bridge + // makes DInput/HIDAPI pads visible past the XInput 4-pad cap. + DWORD PollPadAsXInput(int iPad, struct _XINPUT_STATE* outState); + // EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); // EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); EKeyboardResult RequestKeyboard(LPCWSTR Title, LPCWSTR Text, DWORD dwPad, UINT uiMaxChars, int(*Func)(LPVOID, const bool), LPVOID lpParam, C_4JInput::EKeyboardMode eMode); diff --git a/inc/4J_Render.h b/inc/4J_Render.h index d794b10..50f1e0c 100644 --- a/inc/4J_Render.h +++ b/inc/4J_Render.h @@ -206,6 +206,11 @@ public: void StateSetLightDirection(int light, float x, float y, float z); void StateSetLightEnable(int light, bool enable); void StateSetViewport(eViewportType viewportType); + // Parametric viewport for N-player splitscreen (5+ pads). The eViewportType + // enum can't carry the per-pad cell rect, so the host computes (x, y, w, h) + // in backbuffer pixels and passes it directly. Mirrors what StateSetViewport + // does for the legacy enum cases (RSSetViewports + OMSetRenderTargets). + void StateSetViewportRect(float x, float y, float w, float h); void StateSetEnableViewportClipPlanes(bool enable); void StateSetTexGenCol(int col, float x, float y, float z, float w, bool eyeSpace); void StateSetStencil(int Function, uint8_t stencil_ref, uint8_t stencil_func_mask, uint8_t stencil_write_mask);