diff options
| author | kotorvr <332716892+kotorvr@users.noreply.github.com> | 2026-11-22 01:49:49 +0000 |
|---|---|---|
| committer | kotorvr <332716892+kotorvr@users.noreply.github.com> | 2026-11-22 02:54:55 +0000 |
| commit | 0e59c75b7ba15013b5939b9177bfd2aa93c8f155 (patch) | |
| tree | 545d9b6a58227fe1aa1f69b62e5e1fe5f6efd935 /runtime/shims/gameinput.cpp | |
| parent | 67204bf8c0471335d9046890288b33e8d5e2875b (diff) | |
Runtime: GameInput shim on SDL3 (any controller; DualSense trigger effects, lightbar)
GameInputCreate and the v0 IGameInput/IGameInputDevice/IGameInputReading/IGameInputDispatcher surface a title uses
for gamepads, served from SDL3 gamepads so DualSense, DualShock 4, Switch Pro and Xbox pads all work. Rumble goes to
SDL_RumbleGamepad, impulse-trigger rumble to SDL_RumbleGamepadTriggers, and on a DualSense to adaptive-trigger effects
through SDL_SendGamepadEffect (LEONIDA_DS_TRIGGERS=off|rumble|resistance). Lightbar via LEONIDA_DS_LIGHTBAR.
SDL3 (zlib) comes from an installed package or a pinned, hash-checked release tarball via FetchContent;
-DLEONIDA_SDL3=OFF skips the shim. gameinput_test covers the shim on SDL virtual joysticks; gameinput_probe is the
manual check on a real pad. docs/gameinput.md has the mapping, settings and VERIFY list.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/gameinput.cpp')
| -rw-r--r-- | runtime/shims/gameinput.cpp | 1134 |
1 files changed, 1134 insertions, 0 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp new file mode 100644 index 000000000..9595f59dd --- /dev/null +++ b/runtime/shims/gameinput.cpp | |||
| @@ -0,0 +1,1134 @@ | |||
| 1 | // gameinput: Microsoft's GameInput API (v0) for gamepads, backed by SDL3, so any controller SDL knows works: | ||
| 2 | // DualSense, DualShock 4, Switch Pro, Xbox and the rest of SDL's gamepad database. | ||
| 3 | // | ||
| 4 | // The Xbox build reads controllers through GameInput. This shim answers GameInputCreate with a COM object whose | ||
| 5 | // vtables follow the public v0 API (gameinput_abi.h) and serves gamepads from SDL3: | ||
| 6 | // | ||
| 7 | // - device enumeration, connect/disconnect and device callbacks (blocking and async enumeration) | ||
| 8 | // - GetCurrentReading / GetNextReading, GetGamepadState, GetUiNavigationState, controller axes and buttons | ||
| 9 | // - SetRumbleState: the two body motors through SDL_RumbleGamepad, the impulse-trigger motors through | ||
| 10 | // SDL_RumbleGamepadTriggers on pads that have them; on a DualSense the trigger signal becomes an adaptive-trigger | ||
| 11 | // effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse | ||
| 12 | // trigger signal, not the PS5 version's authored effects. | ||
| 13 | // - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order | ||
| 14 | // | ||
| 15 | // One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when | ||
| 16 | // LEONIDA_GAMEINPUT_THREAD=0. Title calls never touch SDL: they read the latest snapshot and leave rumble requests | ||
| 17 | // that the next poll applies (2 ms at most with the thread). Callbacks run on the poll thread, as GameInput runs them | ||
| 18 | // on its own threads, unless the title created a dispatcher; then IGameInputDispatcher::Dispatch delivers them. | ||
| 19 | // | ||
| 20 | // Buttons are positional, as on an Xbox pad: A is the bottom face button (Cross on a DualSense, B on a Switch Pro), | ||
| 21 | // B the right one, X the left, Y the top. View is Back/Create/Share/Minus, Menu is Start/Options/Plus. | ||
| 22 | // | ||
| 23 | // Nothing here goes online. docs/gameinput.md has the mapping, the environment variables and the VERIFY list. | ||
| 24 | // | ||
| 25 | // ASSUMPTION: the console executable is not available, so the DLL it imports GameInputCreate from is unknown. The PC | ||
| 26 | // API lives in gameinput.dll; on console the GDK links it through xgameruntime. Both names are registered. | ||
| 27 | #include <windows.h> | ||
| 28 | |||
| 29 | #include <SDL3/SDL.h> | ||
| 30 | |||
| 31 | #include <algorithm> | ||
| 32 | #include <atomic> | ||
| 33 | #include <cmath> | ||
| 34 | #include <cstdio> | ||
| 35 | #include <cstdlib> | ||
| 36 | #include <cstring> | ||
| 37 | #include <mutex> | ||
| 38 | #include <string> | ||
| 39 | #include <thread> | ||
| 40 | #include <vector> | ||
| 41 | |||
| 42 | #include "gameinput.h" | ||
| 43 | #include "gameinput_abi.h" | ||
| 44 | #include "shims.h" | ||
| 45 | |||
| 46 | using namespace gi; | ||
| 47 | |||
| 48 | namespace { | ||
| 49 | |||
| 50 | constexpr uint32_t kSupportedKinds = | ||
| 51 | GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; | ||
| 52 | constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT | ||
| 53 | constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT; | ||
| 54 | constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; | ||
| 55 | constexpr Uint32 kRumbleDurationMs = 0xFFFF; // SDL's maximum; refreshed well before it runs out | ||
| 56 | constexpr uint64_t kRumbleRefreshUs = 20'000'000; | ||
| 57 | constexpr uint64_t kBatteryRefreshUs = 1'000'000; | ||
| 58 | constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) | ||
| 59 | |||
| 60 | uint64_t now_us() { | ||
| 61 | static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); | ||
| 62 | LARGE_INTEGER c; | ||
| 63 | QueryPerformanceCounter(&c); | ||
| 64 | return static_cast<uint64_t>(c.QuadPart / freq.QuadPart * 1'000'000 + c.QuadPart % freq.QuadPart * 1'000'000 / freq.QuadPart); | ||
| 65 | } | ||
| 66 | |||
| 67 | // Release for objects the shim keeps for the process: the count never drops below one, so they are never freed. | ||
| 68 | ULONG release_floor(std::atomic<ULONG>& refs) { | ||
| 69 | ULONG r = refs.load(); | ||
| 70 | while (r > 1 && !refs.compare_exchange_weak(r, r - 1)) {} | ||
| 71 | return r > 1 ? r - 1 : 1; | ||
| 72 | } | ||
| 73 | |||
| 74 | bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } | ||
| 75 | |||
| 76 | // ---- configuration ---------------------------------------------------------------------------------------------- | ||
| 77 | |||
| 78 | std::string env(const char* name) { | ||
| 79 | char buf[64]; | ||
| 80 | const DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf); | ||
| 81 | if (n == 0 || n >= sizeof buf) return {}; | ||
| 82 | std::string s(buf, n); | ||
| 83 | for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); | ||
| 84 | return s; | ||
| 85 | } | ||
| 86 | |||
| 87 | rt::gameinput::Config read_config() { | ||
| 88 | rt::gameinput::Config c; | ||
| 89 | const std::string t = env("LEONIDA_DS_TRIGGERS"); | ||
| 90 | if (t == "off" || t == "0") c.ds_triggers = rt::gameinput::DsTriggerMode::Off; | ||
| 91 | else if (t == "resistance") c.ds_triggers = rt::gameinput::DsTriggerMode::Resistance; | ||
| 92 | else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); | ||
| 93 | if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty()) | ||
| 94 | c.ds_trigger_gain = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.0f, 4.0f); | ||
| 95 | if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty()) | ||
| 96 | c.ds_trigger_frequency = static_cast<uint8_t>(std::clamp(std::atoi(f.c_str()), 1, 255)); | ||
| 97 | if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) { | ||
| 98 | if (l == "off") { | ||
| 99 | c.lightbar_set = true; | ||
| 100 | } else if (l.size() == 6 && l.find_first_not_of("0123456789abcdef") == std::string::npos) { | ||
| 101 | const unsigned long rgb = std::strtoul(l.c_str(), nullptr, 16); | ||
| 102 | c.lightbar_set = true; | ||
| 103 | c.lightbar[0] = static_cast<uint8_t>(rgb >> 16); | ||
| 104 | c.lightbar[1] = static_cast<uint8_t>(rgb >> 8); | ||
| 105 | c.lightbar[2] = static_cast<uint8_t>(rgb); | ||
| 106 | } else { | ||
| 107 | std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_LIGHTBAR=%s is not RRGGBB or off, ignored\n", l.c_str()); | ||
| 108 | } | ||
| 109 | } | ||
| 110 | if (env("LEONIDA_RUMBLE") == "0") c.rumble = false; | ||
| 111 | if (env("LEONIDA_GAMEINPUT_THREAD") == "0") c.background_thread = false; | ||
| 112 | return c; | ||
| 113 | } | ||
| 114 | |||
| 115 | // ---- objects ---------------------------------------------------------------------------------------------------- | ||
| 116 | |||
| 117 | class Device; | ||
| 118 | |||
| 119 | struct Snapshot { | ||
| 120 | GameInputGamepadState gamepad{}; | ||
| 121 | uint32_t ui = 0; | ||
| 122 | float axes[kAxisCount] = {}; | ||
| 123 | bool buttons[kButtonCount] = {}; | ||
| 124 | bool guide = false; | ||
| 125 | bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised | ||
| 126 | const GameInputGamepadState &a = gamepad, &b = o.gamepad; | ||
| 127 | return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && | ||
| 128 | a.leftThumbstickX == b.leftThumbstickX && a.leftThumbstickY == b.leftThumbstickY && | ||
| 129 | a.rightThumbstickX == b.rightThumbstickX && a.rightThumbstickY == b.rightThumbstickY && ui == o.ui && | ||
| 130 | std::memcmp(buttons, o.buttons, sizeof buttons) == 0 && guide == o.guide; | ||
| 131 | } | ||
| 132 | }; | ||
| 133 | |||
| 134 | class Reading final : public IGameInputReading { | ||
| 135 | public: | ||
| 136 | Reading(Device* device, const Snapshot& s, uint64_t seq, uint64_t ts); | ||
| 137 | ~Reading(); | ||
| 138 | |||
| 139 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { | ||
| 140 | if (!out) return E_POINTER; | ||
| 141 | if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputReading)) { | ||
| 142 | AddRef(); | ||
| 143 | *out = static_cast<IGameInputReading*>(this); | ||
| 144 | return S_OK; | ||
| 145 | } | ||
| 146 | *out = nullptr; | ||
| 147 | return E_NOINTERFACE; | ||
| 148 | } | ||
| 149 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 150 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 151 | const ULONG r = --refs_; | ||
| 152 | if (r == 0) delete this; | ||
| 153 | return r; | ||
| 154 | } | ||
| 155 | |||
| 156 | uint32_t STDMETHODCALLTYPE GetInputKind() override { return kSupportedKinds; } | ||
| 157 | uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } | ||
| 158 | uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } | ||
| 159 | void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; | ||
| 160 | bool STDMETHODCALLTYPE GetRawReport(void** report) override { | ||
| 161 | if (report) *report = nullptr; | ||
| 162 | return false; | ||
| 163 | } | ||
| 164 | uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; } | ||
| 165 | uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override { | ||
| 166 | const uint32_t n = out ? std::min(count, kAxisCount) : 0; | ||
| 167 | std::memcpy(out, s_.axes, n * sizeof(float)); | ||
| 168 | return n; | ||
| 169 | } | ||
| 170 | uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; } | ||
| 171 | uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t count, bool* out) override { | ||
| 172 | const uint32_t n = out ? std::min(count, kButtonCount) : 0; | ||
| 173 | std::memcpy(out, s_.buttons, n * sizeof(bool)); | ||
| 174 | return n; | ||
| 175 | } | ||
| 176 | uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } | ||
| 177 | uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; } | ||
| 178 | uint32_t STDMETHODCALLTYPE GetKeyCount() override { return 0; } | ||
| 179 | uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t, void*) override { return 0; } | ||
| 180 | bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } | ||
| 181 | uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } | ||
| 182 | uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } | ||
| 183 | bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; } | ||
| 184 | bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } | ||
| 185 | bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } | ||
| 186 | bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { | ||
| 187 | if (!state) return false; | ||
| 188 | *state = s_.gamepad; | ||
| 189 | return true; | ||
| 190 | } | ||
| 191 | bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } | ||
| 192 | bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override { | ||
| 193 | if (!state) return false; | ||
| 194 | state->buttons = s_.ui; | ||
| 195 | return true; | ||
| 196 | } | ||
| 197 | |||
| 198 | Device* device() const { return device_; } | ||
| 199 | uint64_t seq() const { return seq_; } | ||
| 200 | |||
| 201 | private: | ||
| 202 | std::atomic<ULONG> refs_{1}; | ||
| 203 | Device* device_; | ||
| 204 | Snapshot s_; | ||
| 205 | uint64_t seq_, ts_; | ||
| 206 | }; | ||
| 207 | |||
| 208 | struct Rumble { | ||
| 209 | float low = 0, high = 0, left = 0, right = 0; | ||
| 210 | }; | ||
| 211 | |||
| 212 | class Device final : public IGameInputDevice { | ||
| 213 | public: | ||
| 214 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { | ||
| 215 | if (!out) return E_POINTER; | ||
| 216 | if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDevice)) { | ||
| 217 | AddRef(); | ||
| 218 | *out = static_cast<IGameInputDevice*>(this); | ||
| 219 | return S_OK; | ||
| 220 | } | ||
| 221 | *out = nullptr; | ||
| 222 | return E_NOINTERFACE; | ||
| 223 | } | ||
| 224 | // Devices live for the process: the registry keeps every device it has seen, so that a title holding one across a | ||
| 225 | // disconnect gets the same object back when the pad returns. | ||
| 226 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 227 | ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } | ||
| 228 | |||
| 229 | const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } | ||
| 230 | uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } | ||
| 231 | void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; | ||
| 232 | HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { | ||
| 233 | if (effect) *effect = nullptr; | ||
| 234 | return E_INVALIDARG; // forceFeedbackMotorCount is 0 | ||
| 235 | } | ||
| 236 | bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; } | ||
| 237 | void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {} | ||
| 238 | HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; } | ||
| 239 | void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; | ||
| 240 | void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} | ||
| 241 | void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} | ||
| 242 | void STDMETHODCALLTYPE PowerOff() override {} | ||
| 243 | HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t, int32_t, void** report) override { | ||
| 244 | if (report) *report = nullptr; | ||
| 245 | return E_NOTIMPL; | ||
| 246 | } | ||
| 247 | HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t, void** report) override { | ||
| 248 | if (report) *report = nullptr; | ||
| 249 | return E_NOTIMPL; | ||
| 250 | } | ||
| 251 | HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void*) override { return E_NOTIMPL; } | ||
| 252 | HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void*) override { return E_NOTIMPL; } | ||
| 253 | HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { | ||
| 254 | if (response) *response = nullptr; | ||
| 255 | return E_NOTIMPL; | ||
| 256 | } | ||
| 257 | HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* size) override { | ||
| 258 | if (size) *size = 0; | ||
| 259 | return E_NOTIMPL; | ||
| 260 | } | ||
| 261 | bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t) override { return false; } | ||
| 262 | void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() override {} | ||
| 263 | |||
| 264 | // Shared state, under g().mu unless noted. | ||
| 265 | GameInputDeviceInfo info{}; | ||
| 266 | std::string name; | ||
| 267 | GameInputString display_name{}; | ||
| 268 | GameInputControllerAxisInfo axis_info[kAxisCount]{}; | ||
| 269 | GameInputControllerButtonInfo button_info[kButtonCount]{}; | ||
| 270 | GameInputGamepadInfo gamepad_info{}; | ||
| 271 | GameInputUiNavigationInfo ui_info{}; | ||
| 272 | std::atomic<uint32_t> status{GameInputDeviceNoStatus}; | ||
| 273 | Reading* latest = nullptr; // one reference held | ||
| 274 | uint64_t seq = 0; | ||
| 275 | Rumble wanted; | ||
| 276 | GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; | ||
| 277 | |||
| 278 | // Poll-thread state. | ||
| 279 | SDL_Gamepad* pad = nullptr; | ||
| 280 | SDL_JoystickID id = 0; | ||
| 281 | int player = -1; | ||
| 282 | bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false; | ||
| 283 | rt::gameinput::OutputState sent{}; | ||
| 284 | Snapshot last_snap{}; // what the latest reading holds | ||
| 285 | uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; | ||
| 286 | bool ds_sent_once = false; | ||
| 287 | |||
| 288 | private: | ||
| 289 | std::atomic<ULONG> refs_{1}; | ||
| 290 | }; | ||
| 291 | |||
| 292 | Reading::Reading(Device* device, const Snapshot& s, uint64_t seq, uint64_t ts) : device_(device), s_(s), seq_(seq), ts_(ts) { | ||
| 293 | device_->AddRef(); | ||
| 294 | } | ||
| 295 | Reading::~Reading() { device_->Release(); } | ||
| 296 | void Reading::GetDevice(IGameInputDevice** device) { | ||
| 297 | if (!device) return; | ||
| 298 | device_->AddRef(); | ||
| 299 | *device = device_; | ||
| 300 | } | ||
| 301 | |||
| 302 | // ---- callbacks -------------------------------------------------------------------------------------------------- | ||
| 303 | |||
| 304 | enum class CbType { Device, Reading, Guide, KeyboardLayout }; | ||
| 305 | |||
| 306 | struct Callback { | ||
| 307 | GameInputCallbackToken token; | ||
| 308 | CbType type; | ||
| 309 | Device* device; // filter, or null for all | ||
| 310 | uint32_t kind; | ||
| 311 | uint32_t status_filter; | ||
| 312 | void* context; | ||
| 313 | void* fn; | ||
| 314 | bool active; | ||
| 315 | }; | ||
| 316 | |||
| 317 | struct Event { | ||
| 318 | CbType type; | ||
| 319 | Device* device; // referenced | ||
| 320 | Reading* reading; // referenced, Reading events only | ||
| 321 | uint64_t timestamp; | ||
| 322 | uint32_t current, previous; | ||
| 323 | bool pressed; | ||
| 324 | GameInputCallbackToken only; // enumeration: deliver to this callback only | ||
| 325 | }; | ||
| 326 | |||
| 327 | class Dispatcher; | ||
| 328 | |||
| 329 | struct State { | ||
| 330 | std::recursive_mutex mu; // everything below | ||
| 331 | std::mutex poll_mu; // one poller at a time | ||
| 332 | std::recursive_mutex deliver_mu; // held while callbacks run; UnregisterCallback waits on it | ||
| 333 | std::vector<Device*> devices; // every device seen, for the process lifetime | ||
| 334 | std::vector<Device*> connected; // open now, in connection order | ||
| 335 | std::vector<Callback> callbacks; | ||
| 336 | std::vector<Event> queue; | ||
| 337 | GameInputCallbackToken next_token = 1; | ||
| 338 | int dispatchers = 0; | ||
| 339 | HANDLE wait_event = nullptr; // auto-reset, signalled when a dispatcher has work | ||
| 340 | rt::gameinput::Config config; | ||
| 341 | bool config_read = false; | ||
| 342 | bool sdl_ready = false, sdl_failed = false; | ||
| 343 | bool thread_started = false; | ||
| 344 | DWORD delivering_thread = 0; | ||
| 345 | }; | ||
| 346 | |||
| 347 | // Never destroyed: the poll thread may still run while the process exits. | ||
| 348 | State& g() { | ||
| 349 | static State* s = new State; | ||
| 350 | return *s; | ||
| 351 | } | ||
| 352 | |||
| 353 | void queue_event(const Event& e) { | ||
| 354 | if (e.device) e.device->AddRef(); | ||
| 355 | if (e.reading) e.reading->AddRef(); | ||
| 356 | g().queue.push_back(e); | ||
| 357 | } | ||
| 358 | |||
| 359 | bool matches(const Callback& c, const Event& e) { | ||
| 360 | if (!c.active || c.type != e.type) return false; | ||
| 361 | if (e.only && e.only != c.token) return false; | ||
| 362 | if (c.device && c.device != e.device) return false; | ||
| 363 | switch (e.type) { | ||
| 364 | case CbType::Device: | ||
| 365 | if (!(c.kind & e.device->info.supportedInput) && c.kind != GameInputKindUnknown) return false; | ||
| 366 | return e.only || ((e.current ^ e.previous) & c.status_filter); | ||
| 367 | case CbType::Reading: | ||
| 368 | return (c.kind & kSupportedKinds) || c.kind == GameInputKindUnknown; | ||
| 369 | default: | ||
| 370 | return true; | ||
| 371 | } | ||
| 372 | } | ||
| 373 | |||
| 374 | void call(const Callback& c, const Event& e) { | ||
| 375 | switch (c.type) { | ||
| 376 | case CbType::Device: | ||
| 377 | reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, e.device, e.timestamp, e.current, e.previous); | ||
| 378 | break; | ||
| 379 | case CbType::Reading: | ||
| 380 | reinterpret_cast<GameInputReadingCallback>(c.fn)(c.token, c.context, e.reading, false); | ||
| 381 | break; | ||
| 382 | case CbType::Guide: | ||
| 383 | reinterpret_cast<GameInputGuideButtonCallback>(c.fn)(c.token, c.context, e.device, e.timestamp, e.pressed); | ||
| 384 | break; | ||
| 385 | case CbType::KeyboardLayout: | ||
| 386 | break; | ||
| 387 | } | ||
| 388 | } | ||
| 389 | |||
| 390 | // Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived | ||
| 391 | // meanwhile. | ||
| 392 | bool deliver() { | ||
| 393 | State& s = g(); | ||
| 394 | std::lock_guard dl(s.deliver_mu); | ||
| 395 | std::vector<Event> events; | ||
| 396 | { | ||
| 397 | std::lock_guard lock(s.mu); | ||
| 398 | events.swap(s.queue); | ||
| 399 | } | ||
| 400 | const DWORD self = GetCurrentThreadId(); | ||
| 401 | s.delivering_thread = self; | ||
| 402 | for (const Event& e : events) { | ||
| 403 | std::vector<Callback> targets; | ||
| 404 | { | ||
| 405 | std::lock_guard lock(s.mu); | ||
| 406 | for (const Callback& c : s.callbacks) | ||
| 407 | if (matches(c, e)) targets.push_back(c); | ||
| 408 | } | ||
| 409 | for (const Callback& c : targets) { | ||
| 410 | bool still = false; | ||
| 411 | { | ||
| 412 | std::lock_guard lock(s.mu); | ||
| 413 | for (const Callback& now : s.callbacks) | ||
| 414 | if (now.token == c.token) still = now.active; | ||
| 415 | } | ||
| 416 | if (still) call(c, e); | ||
| 417 | } | ||
| 418 | if (e.device) e.device->Release(); | ||
| 419 | if (e.reading) e.reading->Release(); | ||
| 420 | } | ||
| 421 | s.delivering_thread = 0; | ||
| 422 | std::lock_guard lock(s.mu); | ||
| 423 | return !s.queue.empty(); | ||
| 424 | } | ||
| 425 | |||
| 426 | // ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- | ||
| 427 | |||
| 428 | uint16_t to_u16(float v) { return static_cast<uint16_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } | ||
| 429 | |||
| 430 | float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); } | ||
| 431 | |||
| 432 | Snapshot read_pad(SDL_Gamepad* p) { | ||
| 433 | Snapshot s; | ||
| 434 | auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; | ||
| 435 | struct Map { SDL_GamepadButton sdl; uint32_t gi; }; | ||
| 436 | static const Map kMap[] = { | ||
| 437 | {SDL_GAMEPAD_BUTTON_START, GameInputGamepadMenu}, | ||
| 438 | {SDL_GAMEPAD_BUTTON_BACK, GameInputGamepadView}, | ||
| 439 | {SDL_GAMEPAD_BUTTON_SOUTH, GameInputGamepadA}, | ||
| 440 | {SDL_GAMEPAD_BUTTON_EAST, GameInputGamepadB}, | ||
| 441 | {SDL_GAMEPAD_BUTTON_WEST, GameInputGamepadX}, | ||
| 442 | {SDL_GAMEPAD_BUTTON_NORTH, GameInputGamepadY}, | ||
| 443 | {SDL_GAMEPAD_BUTTON_DPAD_UP, GameInputGamepadDPadUp}, | ||
| 444 | {SDL_GAMEPAD_BUTTON_DPAD_DOWN, GameInputGamepadDPadDown}, | ||
| 445 | {SDL_GAMEPAD_BUTTON_DPAD_LEFT, GameInputGamepadDPadLeft}, | ||
| 446 | {SDL_GAMEPAD_BUTTON_DPAD_RIGHT, GameInputGamepadDPadRight}, | ||
| 447 | {SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, GameInputGamepadLeftShoulder}, | ||
| 448 | {SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, GameInputGamepadRightShoulder}, | ||
| 449 | {SDL_GAMEPAD_BUTTON_LEFT_STICK, GameInputGamepadLeftThumbstick}, | ||
| 450 | {SDL_GAMEPAD_BUTTON_RIGHT_STICK, GameInputGamepadRightThumbstick}, | ||
| 451 | }; | ||
| 452 | for (const Map& m : kMap) | ||
| 453 | if (down(m.sdl)) s.gamepad.buttons |= m.gi; | ||
| 454 | // GameInput: sticks in -1..1 with +Y up, triggers in 0..1. SDL: +Y down, -32768..32767, triggers 0..32767. | ||
| 455 | s.gamepad.leftThumbstickX = axis(p, SDL_GAMEPAD_AXIS_LEFTX); | ||
| 456 | s.gamepad.leftThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_LEFTY); | ||
| 457 | s.gamepad.rightThumbstickX = axis(p, SDL_GAMEPAD_AXIS_RIGHTX); | ||
| 458 | s.gamepad.rightThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_RIGHTY); | ||
| 459 | s.gamepad.leftTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_LEFT_TRIGGER)); | ||
| 460 | s.gamepad.rightTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)); | ||
| 461 | |||
| 462 | // Controller axes, 0..1 with 0.5 at rest for the sticks (VERIFY: the raw-axis convention of a GameInput gamepad). | ||
| 463 | s.axes[0] = (s.gamepad.leftThumbstickX + 1) * 0.5f; | ||
| 464 | s.axes[1] = (s.gamepad.leftThumbstickY + 1) * 0.5f; | ||
| 465 | s.axes[2] = (s.gamepad.rightThumbstickX + 1) * 0.5f; | ||
| 466 | s.axes[3] = (s.gamepad.rightThumbstickY + 1) * 0.5f; | ||
| 467 | s.axes[4] = s.gamepad.leftTrigger; | ||
| 468 | s.axes[5] = s.gamepad.rightTrigger; | ||
| 469 | for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i)); | ||
| 470 | s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE); | ||
| 471 | |||
| 472 | // UI navigation derived from the gamepad (VERIFY against the console's own mapping). | ||
| 473 | const uint32_t b = s.gamepad.buttons; | ||
| 474 | const float t = 0.5f; | ||
| 475 | uint32_t& u = s.ui; | ||
| 476 | if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu; | ||
| 477 | if (b & GameInputGamepadView) u |= GameInputUiNavigationView; | ||
| 478 | if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept; | ||
| 479 | if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel; | ||
| 480 | if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1; | ||
| 481 | if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2; | ||
| 482 | if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3; | ||
| 483 | if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4; | ||
| 484 | if ((b & GameInputGamepadDPadUp) || s.gamepad.leftThumbstickY > t) u |= GameInputUiNavigationUp; | ||
| 485 | if ((b & GameInputGamepadDPadDown) || s.gamepad.leftThumbstickY < -t) u |= GameInputUiNavigationDown; | ||
| 486 | if ((b & GameInputGamepadDPadLeft) || s.gamepad.leftThumbstickX < -t) u |= GameInputUiNavigationLeft; | ||
| 487 | if ((b & GameInputGamepadDPadRight) || s.gamepad.leftThumbstickX > t) u |= GameInputUiNavigationRight; | ||
| 488 | if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft; | ||
| 489 | if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight; | ||
| 490 | if (s.gamepad.leftTrigger > t) u |= GameInputUiNavigationPageUp; | ||
| 491 | if (s.gamepad.rightTrigger > t) u |= GameInputUiNavigationPageDown; | ||
| 492 | if (s.gamepad.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp; | ||
| 493 | if (s.gamepad.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown; | ||
| 494 | if (s.gamepad.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft; | ||
| 495 | if (s.gamepad.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight; | ||
| 496 | return s; | ||
| 497 | } | ||
| 498 | |||
| 499 | void id_bytes(const std::string& identity, const SDL_GUID& guid, AppLocalDeviceId* out) { | ||
| 500 | std::memcpy(out->value, guid.data, 16); | ||
| 501 | for (int half = 0; half < 2; ++half) { // FNV-1a, two seeds | ||
| 502 | uint64_t h = half ? 0x84222325cbf29ce4ull : 0xcbf29ce484222325ull; | ||
| 503 | for (unsigned char c : identity) h = (h ^ c) * 0x100000001b3ull; | ||
| 504 | std::memcpy(out->value + 16 + half * 8, &h, 8); | ||
| 505 | } | ||
| 506 | } | ||
| 507 | |||
| 508 | void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) { | ||
| 509 | GameInputDeviceInfo& i = d->info; | ||
| 510 | i = {}; | ||
| 511 | i.infoSize = sizeof(GameInputDeviceInfo); | ||
| 512 | i.vendorId = SDL_GetGamepadVendor(p); | ||
| 513 | i.productId = SDL_GetGamepadProduct(p); | ||
| 514 | i.revisionNumber = SDL_GetGamepadProductVersion(p); | ||
| 515 | i.usage = {0x01, 0x05}; // HID generic desktop / game pad | ||
| 516 | const uint16_t fw = SDL_GetGamepadFirmwareVersion(p); | ||
| 517 | i.firmwareVersion = {static_cast<uint16_t>(fw >> 8), static_cast<uint16_t>(fw & 0xFF), 0, 0}; | ||
| 518 | i.deviceId = id; | ||
| 519 | i.deviceRootId = id; | ||
| 520 | // Every pad is presented as an Xbox gamepad, which is all a console title expects (VERIFY: whether a title | ||
| 521 | // filters on the family). | ||
| 522 | i.deviceFamily = GameInputFamilyXboxOne; | ||
| 523 | if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless; | ||
| 524 | i.supportedInput = kSupportedKinds; | ||
| 525 | if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; | ||
| 526 | if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) | ||
| 527 | i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; | ||
| 528 | i.controllerAxisCount = kAxisCount; | ||
| 529 | i.controllerButtonCount = kButtonCount; | ||
| 530 | for (uint32_t a = 0; a < kAxisCount; ++a) { | ||
| 531 | d->axis_info[a] = {}; | ||
| 532 | d->axis_info[a].mappedInputKinds = GameInputKindGamepad; | ||
| 533 | d->axis_info[a].isContinuous = true; | ||
| 534 | d->axis_info[a].hasRestValue = true; | ||
| 535 | d->axis_info[a].restValue = a < 4 ? 0.5f : 0.0f; | ||
| 536 | d->axis_info[a].resolution = 65536; | ||
| 537 | d->axis_info[a].legacyHidIndex = static_cast<uint16_t>(a); | ||
| 538 | d->axis_info[a].legacyDInputIndex = static_cast<uint16_t>(a); | ||
| 539 | } | ||
| 540 | for (uint32_t b = 0; b < kButtonCount; ++b) { | ||
| 541 | d->button_info[b] = {}; | ||
| 542 | d->button_info[b].mappedInputKinds = GameInputKindGamepad; | ||
| 543 | d->button_info[b].legacyHidIndex = static_cast<uint16_t>(b); | ||
| 544 | d->button_info[b].legacyDInputIndex = static_cast<uint16_t>(b); | ||
| 545 | } | ||
| 546 | i.controllerAxisInfo = d->axis_info; | ||
| 547 | i.controllerButtonInfo = d->button_info; | ||
| 548 | i.gamepadInfo = &d->gamepad_info; | ||
| 549 | i.uiNavigationInfo = &d->ui_info; | ||
| 550 | const char* n = SDL_GetGamepadName(p); | ||
| 551 | d->name = n ? n : "Gamepad"; | ||
| 552 | uint32_t points = 0; | ||
| 553 | for (unsigned char c : d->name) points += (c & 0xC0) != 0x80; | ||
| 554 | d->display_name = {static_cast<uint32_t>(d->name.size()), points, d->name.c_str()}; | ||
| 555 | i.displayName = &d->display_name; | ||
| 556 | } | ||
| 557 | |||
| 558 | void open_pad(SDL_JoystickID jid, uint64_t ts) { | ||
| 559 | State& s = g(); | ||
| 560 | SDL_Gamepad* p = SDL_OpenGamepad(jid); | ||
| 561 | if (!p) { | ||
| 562 | std::fprintf(stderr, "[rt] gameinput: cannot open gamepad %u: %s\n", static_cast<unsigned>(jid), SDL_GetError()); | ||
| 563 | return; | ||
| 564 | } | ||
| 565 | const char* serial = SDL_GetGamepadSerial(p); | ||
| 566 | const char* path = SDL_GetGamepadPath(p); | ||
| 567 | const std::string identity = (serial && *serial) ? std::string("s:") + serial : (path && *path) ? std::string("p:") + path : ""; | ||
| 568 | AppLocalDeviceId id{}; | ||
| 569 | id_bytes(identity, SDL_GetGamepadGUIDForID(jid), &id); | ||
| 570 | |||
| 571 | const SDL_PropertiesID props = SDL_GetGamepadProperties(p); | ||
| 572 | std::lock_guard lock(s.mu); | ||
| 573 | Device* d = nullptr; | ||
| 574 | for (Device* old : s.devices) // the same pad coming back gets its old object | ||
| 575 | if (old->status == GameInputDeviceNoStatus && std::memcmp(&old->info.deviceId, &id, sizeof id) == 0) d = old; | ||
| 576 | if (!d) { | ||
| 577 | d = new Device; | ||
| 578 | s.devices.push_back(d); | ||
| 579 | } | ||
| 580 | d->pad = p; | ||
| 581 | d->id = jid; | ||
| 582 | d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; | ||
| 583 | d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); | ||
| 584 | d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); | ||
| 585 | d->sent = {}; | ||
| 586 | d->sent.is_dualsense = d->is_dualsense; | ||
| 587 | d->sent.trigger_rumble = d->has_trigger_rumble; | ||
| 588 | d->ds_sent_once = false; | ||
| 589 | d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; | ||
| 590 | d->wanted = {}; | ||
| 591 | fill_info(d, p, id); | ||
| 592 | |||
| 593 | // Player LEDs and SDL's default lightbar colour follow the slot: the lowest one not in use. | ||
| 594 | int player = 0; | ||
| 595 | for (bool used = true; used; ++player) { | ||
| 596 | used = false; | ||
| 597 | for (Device* c : s.connected) used |= c->player == player; | ||
| 598 | if (!used) break; | ||
| 599 | } | ||
| 600 | d->player = player; | ||
| 601 | SDL_SetGamepadPlayerIndex(p, player); | ||
| 602 | if (s.config.lightbar_set && SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN, false)) | ||
| 603 | SDL_SetGamepadLED(p, s.config.lightbar[0], s.config.lightbar[1], s.config.lightbar[2]); | ||
| 604 | |||
| 605 | uint32_t status = kConnectedStatus; | ||
| 606 | if (d->info.capabilities & GameInputDeviceCapabilityWireless) status |= GameInputDeviceWireless; | ||
| 607 | d->status = status; | ||
| 608 | s.connected.push_back(d); | ||
| 609 | |||
| 610 | const Snapshot snap = read_pad(p); | ||
| 611 | d->last_snap = snap; | ||
| 612 | if (d->latest) d->latest->Release(); | ||
| 613 | d->latest = new Reading(d, snap, ++d->seq, ts); | ||
| 614 | queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); | ||
| 615 | std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s)\n", d->name.c_str(), d->info.vendorId, | ||
| 616 | d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", | ||
| 617 | d->has_trigger_rumble ? ", trigger rumble" : ""); | ||
| 618 | } | ||
| 619 | |||
| 620 | void close_pad(Device* d, uint64_t ts) { | ||
| 621 | State& s = g(); | ||
| 622 | std::lock_guard lock(s.mu); | ||
| 623 | const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); | ||
| 624 | SDL_CloseGamepad(d->pad); | ||
| 625 | d->pad = nullptr; | ||
| 626 | d->player = -1; | ||
| 627 | s.connected.erase(std::remove(s.connected.begin(), s.connected.end(), d), s.connected.end()); | ||
| 628 | queue_event({CbType::Device, d, nullptr, ts, GameInputDeviceNoStatus, old, false, 0}); | ||
| 629 | std::fprintf(stderr, "[rt] gameinput: disconnected %s\n", d->name.c_str()); | ||
| 630 | } | ||
| 631 | |||
| 632 | void ds_effect(float strength, uint8_t out[11]) { | ||
| 633 | const rt::gameinput::Config& c = g().config; | ||
| 634 | std::memset(out, 0, 11); | ||
| 635 | const uint8_t v = static_cast<uint8_t>(std::lround(std::clamp(strength * c.ds_trigger_gain, 0.0f, 1.0f) * 255.0f)); | ||
| 636 | if (v == 0) { | ||
| 637 | out[0] = 0x05; // effect off | ||
| 638 | } else if (c.ds_triggers == rt::gameinput::DsTriggerMode::Resistance) { | ||
| 639 | out[0] = 0x01; // continuous resistance: start position, force | ||
| 640 | out[1] = 0; | ||
| 641 | out[2] = v; | ||
| 642 | } else { | ||
| 643 | out[0] = 0x06; // vibration: frequency, amplitude, start position | ||
| 644 | out[1] = c.ds_trigger_frequency; | ||
| 645 | out[2] = v; | ||
| 646 | out[3] = 0; | ||
| 647 | } | ||
| 648 | } | ||
| 649 | |||
| 650 | void apply_output(Device* d, uint64_t now) { | ||
| 651 | State& s = g(); | ||
| 652 | Rumble want; | ||
| 653 | { | ||
| 654 | std::lock_guard lock(s.mu); | ||
| 655 | want = d->wanted; | ||
| 656 | } | ||
| 657 | if (!s.config.rumble) want = {}; | ||
| 658 | rt::gameinput::OutputState& o = d->sent; | ||
| 659 | |||
| 660 | if (d->has_rumble) { | ||
| 661 | const uint16_t lo = to_u16(want.low), hi = to_u16(want.high); | ||
| 662 | const bool stale = (lo || hi) && now - d->motors_sent_at > kRumbleRefreshUs; | ||
| 663 | if (lo != o.low || hi != o.high || stale) { | ||
| 664 | SDL_RumbleGamepad(d->pad, lo, hi, kRumbleDurationMs); | ||
| 665 | o.low = lo; | ||
| 666 | o.high = hi; | ||
| 667 | d->motors_sent_at = now; | ||
| 668 | } | ||
| 669 | } | ||
| 670 | if (d->is_dualsense) { | ||
| 671 | if (s.config.ds_triggers == rt::gameinput::DsTriggerMode::Off) return; // leave the triggers alone | ||
| 672 | uint8_t right[11], left[11]; | ||
| 673 | ds_effect(want.right, right); | ||
| 674 | ds_effect(want.left, left); | ||
| 675 | if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { | ||
| 676 | uint8_t block[kDsEffectSize] = {}; | ||
| 677 | block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect | ||
| 678 | std::memcpy(block + 10, right, 11); | ||
| 679 | std::memcpy(block + 21, left, 11); | ||
| 680 | if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { | ||
| 681 | std::memcpy(o.ds_right, right, 11); | ||
| 682 | std::memcpy(o.ds_left, left, 11); | ||
| 683 | d->ds_sent_once = true; | ||
| 684 | } | ||
| 685 | } | ||
| 686 | } else if (d->has_trigger_rumble) { | ||
| 687 | const uint16_t l = to_u16(want.left), r = to_u16(want.right); | ||
| 688 | const bool stale = (l || r) && now - d->triggers_sent_at > kRumbleRefreshUs; | ||
| 689 | if (l != o.left || r != o.right || stale) { | ||
| 690 | SDL_RumbleGamepadTriggers(d->pad, l, r, kRumbleDurationMs); | ||
| 691 | o.left = l; | ||
| 692 | o.right = r; | ||
| 693 | d->triggers_sent_at = now; | ||
| 694 | } | ||
| 695 | } | ||
| 696 | } | ||
| 697 | |||
| 698 | void refresh_battery(Device* d, uint64_t now) { | ||
| 699 | if (now - d->battery_at < kBatteryRefreshUs && d->battery_at) return; | ||
| 700 | d->battery_at = now; | ||
| 701 | int percent = -1; | ||
| 702 | const SDL_PowerState ps = SDL_GetGamepadPowerInfo(d->pad, &percent); | ||
| 703 | GameInputBatteryState b{0, 0, 0, 0, GameInputBatteryUnknown}; | ||
| 704 | switch (ps) { | ||
| 705 | case SDL_POWERSTATE_ON_BATTERY: b.status = GameInputBatteryDischarging; break; | ||
| 706 | case SDL_POWERSTATE_CHARGING: b.status = GameInputBatteryCharging; break; | ||
| 707 | case SDL_POWERSTATE_CHARGED: b.status = GameInputBatteryIdle; break; | ||
| 708 | case SDL_POWERSTATE_NO_BATTERY: b.status = GameInputBatteryNotPresent; break; | ||
| 709 | default: break; | ||
| 710 | } | ||
| 711 | if (percent >= 0) { // relative capacity (VERIFY: GameInput reports the capacity in device units) | ||
| 712 | b.remainingCapacity = percent / 100.0f; | ||
| 713 | b.fullChargeCapacity = 1.0f; | ||
| 714 | } | ||
| 715 | std::lock_guard lock(g().mu); | ||
| 716 | d->battery = b; | ||
| 717 | } | ||
| 718 | |||
| 719 | bool init_sdl() { | ||
| 720 | State& s = g(); | ||
| 721 | if (s.sdl_ready) return true; | ||
| 722 | if (s.sdl_failed) return false; | ||
| 723 | // No window: keep reading pads when another application has focus. | ||
| 724 | SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); | ||
| 725 | SDL_SetGamepadEventsEnabled(false); // the shim reads state directly; nothing drains an event queue | ||
| 726 | if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { | ||
| 727 | std::fprintf(stderr, "[rt] gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); | ||
| 728 | s.sdl_failed = true; | ||
| 729 | return false; | ||
| 730 | } | ||
| 731 | SDL_SetGamepadEventsEnabled(false); | ||
| 732 | s.sdl_ready = true; | ||
| 733 | const int v = SDL_GetVersion(); | ||
| 734 | std::fprintf(stderr, "[rt] gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), | ||
| 735 | SDL_VERSIONNUM_MICRO(v)); | ||
| 736 | return true; | ||
| 737 | } | ||
| 738 | |||
| 739 | void poll_once() { | ||
| 740 | State& s = g(); | ||
| 741 | std::lock_guard pl(s.poll_mu); | ||
| 742 | if (!init_sdl()) return; | ||
| 743 | SDL_UpdateGamepads(); | ||
| 744 | const uint64_t now = now_us(); | ||
| 745 | |||
| 746 | int count = 0; | ||
| 747 | SDL_JoystickID* ids = SDL_GetGamepads(&count); | ||
| 748 | std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0)); | ||
| 749 | SDL_free(ids); | ||
| 750 | |||
| 751 | std::vector<Device*> connected; | ||
| 752 | { | ||
| 753 | std::lock_guard lock(s.mu); | ||
| 754 | connected = s.connected; | ||
| 755 | } | ||
| 756 | for (Device* d : connected) | ||
| 757 | if (std::find(present.begin(), present.end(), d->id) == present.end() || !SDL_GamepadConnected(d->pad)) | ||
| 758 | close_pad(d, now); | ||
| 759 | for (SDL_JoystickID jid : present) { | ||
| 760 | bool known = false; | ||
| 761 | { | ||
| 762 | std::lock_guard lock(s.mu); | ||
| 763 | for (Device* d : s.connected) known |= d->id == jid; | ||
| 764 | } | ||
| 765 | if (!known) open_pad(jid, now); | ||
| 766 | } | ||
| 767 | |||
| 768 | { | ||
| 769 | std::lock_guard lock(s.mu); | ||
| 770 | connected = s.connected; | ||
| 771 | } | ||
| 772 | for (Device* d : connected) { | ||
| 773 | const Snapshot snap = read_pad(d->pad); | ||
| 774 | const bool guide_changed = d->last_snap.guide != snap.guide; | ||
| 775 | const bool changed = !(d->last_snap == snap); | ||
| 776 | d->last_snap = snap; | ||
| 777 | if (changed) { | ||
| 778 | std::lock_guard lock(s.mu); | ||
| 779 | if (d->latest) d->latest->Release(); | ||
| 780 | d->latest = new Reading(d, snap, ++d->seq, now); | ||
| 781 | queue_event({CbType::Reading, d, d->latest, now, 0, 0, false, 0}); | ||
| 782 | } | ||
| 783 | if (guide_changed) { | ||
| 784 | std::lock_guard lock(s.mu); | ||
| 785 | queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0}); | ||
| 786 | } | ||
| 787 | refresh_battery(d, now); | ||
| 788 | apply_output(d, now); | ||
| 789 | } | ||
| 790 | } | ||
| 791 | |||
| 792 | void poll_and_deliver() { | ||
| 793 | poll_once(); | ||
| 794 | State& s = g(); | ||
| 795 | bool dispatch; | ||
| 796 | bool pending; | ||
| 797 | { | ||
| 798 | std::lock_guard lock(s.mu); | ||
| 799 | dispatch = s.dispatchers > 0; | ||
| 800 | pending = !s.queue.empty(); | ||
| 801 | } | ||
| 802 | if (!pending) return; | ||
| 803 | if (dispatch) SetEvent(s.wait_event); | ||
| 804 | else deliver(); | ||
| 805 | } | ||
| 806 | |||
| 807 | void poll_thread() { | ||
| 808 | HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); | ||
| 809 | if (!timer) timer = CreateWaitableTimerW(nullptr, FALSE, nullptr); | ||
| 810 | LARGE_INTEGER due; | ||
| 811 | due.QuadPart = -20'000; // 2 ms, relative | ||
| 812 | for (;;) { | ||
| 813 | poll_and_deliver(); | ||
| 814 | if (timer && SetWaitableTimer(timer, &due, 0, nullptr, nullptr, FALSE)) WaitForSingleObject(timer, INFINITE); | ||
| 815 | else Sleep(1); | ||
| 816 | } | ||
| 817 | } | ||
| 818 | |||
| 819 | void ensure_started() { | ||
| 820 | State& s = g(); | ||
| 821 | std::lock_guard lock(s.mu); | ||
| 822 | if (!s.config_read) { | ||
| 823 | s.config = read_config(); | ||
| 824 | s.config_read = true; | ||
| 825 | s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 826 | } | ||
| 827 | if (s.config.background_thread && !s.thread_started) { | ||
| 828 | s.thread_started = true; | ||
| 829 | std::thread(poll_thread).detach(); | ||
| 830 | } | ||
| 831 | } | ||
| 832 | |||
| 833 | // ---- IGameInputDevice methods that need State ---- | ||
| 834 | |||
| 835 | void Device::GetBatteryState(GameInputBatteryState* state) { | ||
| 836 | if (!state) return; | ||
| 837 | std::lock_guard lock(g().mu); | ||
| 838 | *state = battery; | ||
| 839 | } | ||
| 840 | |||
| 841 | void Device::SetRumbleState(const GameInputRumbleParams* params) { | ||
| 842 | std::lock_guard lock(g().mu); | ||
| 843 | wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; | ||
| 844 | } | ||
| 845 | |||
| 846 | // ---- IGameInputDispatcher ---- | ||
| 847 | |||
| 848 | class Dispatcher final : public IGameInputDispatcher { | ||
| 849 | public: | ||
| 850 | Dispatcher() { | ||
| 851 | std::lock_guard lock(g().mu); | ||
| 852 | ++g().dispatchers; | ||
| 853 | } | ||
| 854 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { | ||
| 855 | if (!out) return E_POINTER; | ||
| 856 | if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDispatcher)) { | ||
| 857 | AddRef(); | ||
| 858 | *out = static_cast<IGameInputDispatcher*>(this); | ||
| 859 | return S_OK; | ||
| 860 | } | ||
| 861 | *out = nullptr; | ||
| 862 | return E_NOINTERFACE; | ||
| 863 | } | ||
| 864 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 865 | ULONG STDMETHODCALLTYPE Release() override { | ||
| 866 | const ULONG r = --refs_; | ||
| 867 | if (r == 0) { | ||
| 868 | { | ||
| 869 | std::lock_guard lock(g().mu); | ||
| 870 | --g().dispatchers; | ||
| 871 | } | ||
| 872 | delete this; | ||
| 873 | } | ||
| 874 | return r; | ||
| 875 | } | ||
| 876 | // Runs the queued callbacks on the caller's thread. The quota is not enforced: the queue is short. | ||
| 877 | bool STDMETHODCALLTYPE Dispatch(uint64_t) override { return deliver(); } | ||
| 878 | HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { | ||
| 879 | if (!handle) return E_POINTER; | ||
| 880 | *handle = nullptr; | ||
| 881 | if (!DuplicateHandle(GetCurrentProcess(), g().wait_event, GetCurrentProcess(), handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) | ||
| 882 | return HRESULT_FROM_WIN32(GetLastError()); | ||
| 883 | return S_OK; | ||
| 884 | } | ||
| 885 | |||
| 886 | private: | ||
| 887 | std::atomic<ULONG> refs_{1}; | ||
| 888 | }; | ||
| 889 | |||
| 890 | // ---- IGameInput ---- | ||
| 891 | |||
| 892 | Device* as_device(IGameInputDevice* d) { return static_cast<Device*>(d); } | ||
| 893 | |||
| 894 | class GameInput final : public IGameInput { | ||
| 895 | public: | ||
| 896 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { | ||
| 897 | if (!out) return E_POINTER; | ||
| 898 | if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInput)) { | ||
| 899 | AddRef(); | ||
| 900 | *out = static_cast<IGameInput*>(this); | ||
| 901 | return S_OK; | ||
| 902 | } | ||
| 903 | *out = nullptr; | ||
| 904 | return E_NOINTERFACE; | ||
| 905 | } | ||
| 906 | ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } | ||
| 907 | ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } // a process-wide singleton | ||
| 908 | |||
| 909 | uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } | ||
| 910 | |||
| 911 | HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { | ||
| 912 | if (!out) return E_POINTER; | ||
| 913 | *out = nullptr; | ||
| 914 | if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; | ||
| 915 | std::lock_guard lock(g().mu); | ||
| 916 | Reading* best = nullptr; | ||
| 917 | if (device) { | ||
| 918 | Device* d = as_device(device); | ||
| 919 | if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; | ||
| 920 | best = d->latest; | ||
| 921 | } else { | ||
| 922 | for (Device* d : g().connected) // the most recent reading from any gamepad | ||
| 923 | if (d->latest && (!best || d->latest->GetTimestamp() >= best->GetTimestamp())) best = d->latest; | ||
| 924 | } | ||
| 925 | if (!best) return GAMEINPUT_E_READING_NOT_FOUND; | ||
| 926 | best->AddRef(); | ||
| 927 | *out = best; | ||
| 928 | return S_OK; | ||
| 929 | } | ||
| 930 | |||
| 931 | // No history is kept: the next reading is the current one when it is newer than the reference, and there is no | ||
| 932 | // previous one. A title that walks GetNextReading in a loop sees each poll's state once. | ||
| 933 | HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, | ||
| 934 | IGameInputReading** out) override { | ||
| 935 | if (!out) return E_POINTER; | ||
| 936 | *out = nullptr; | ||
| 937 | if (!ref) return E_INVALIDARG; | ||
| 938 | Reading* r = static_cast<Reading*>(ref); | ||
| 939 | if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; | ||
| 940 | Device* d = device ? as_device(device) : r->device(); | ||
| 941 | std::lock_guard lock(g().mu); | ||
| 942 | if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; | ||
| 943 | if (!d->latest || d->latest->seq() <= r->seq() || d->latest->device() != r->device()) return GAMEINPUT_E_READING_NOT_FOUND; | ||
| 944 | d->latest->AddRef(); | ||
| 945 | *out = d->latest; | ||
| 946 | return S_OK; | ||
| 947 | } | ||
| 948 | HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading*, uint32_t, IGameInputDevice*, IGameInputReading** out) override { | ||
| 949 | if (!out) return E_POINTER; | ||
| 950 | *out = nullptr; | ||
| 951 | return GAMEINPUT_E_READING_NOT_FOUND; | ||
| 952 | } | ||
| 953 | HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override { | ||
| 954 | if (!out) return E_POINTER; | ||
| 955 | *out = nullptr; | ||
| 956 | return E_NOTIMPL; | ||
| 957 | } | ||
| 958 | |||
| 959 | HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice* device, uint32_t kind, float, void* context, | ||
| 960 | GameInputReadingCallback fn, GameInputCallbackToken* token) override { | ||
| 961 | return add({0, CbType::Reading, as_device(device), kind, 0, context, reinterpret_cast<void*>(fn), true}, token); | ||
| 962 | } | ||
| 963 | |||
| 964 | HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t kind, uint32_t status_filter, | ||
| 965 | GameInputEnumerationKind enumeration, void* context, | ||
| 966 | GameInputDeviceCallback fn, GameInputCallbackToken* token) override { | ||
| 967 | if (token) *token = kInvalidCallbackToken; | ||
| 968 | if (!fn) return E_INVALIDARG; | ||
| 969 | State& s = g(); | ||
| 970 | GameInputCallbackToken t; | ||
| 971 | std::vector<Event> now; | ||
| 972 | { | ||
| 973 | std::lock_guard lock(s.mu); | ||
| 974 | t = s.next_token++; | ||
| 975 | s.callbacks.push_back({t, CbType::Device, as_device(device), kind, status_filter, context, | ||
| 976 | reinterpret_cast<void*>(fn), true}); | ||
| 977 | if (enumeration != GameInputNoEnumeration) { | ||
| 978 | const uint64_t ts = now_us(); | ||
| 979 | for (Device* d : s.connected) { | ||
| 980 | if (device && as_device(device) != d) continue; | ||
| 981 | if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) continue; | ||
| 982 | const uint32_t st = d->status; | ||
| 983 | if (!(st & status_filter)) continue; | ||
| 984 | const Event e{CbType::Device, d, nullptr, ts, st, GameInputDeviceNoStatus, false, t}; | ||
| 985 | if (enumeration == GameInputBlockingEnumeration) { | ||
| 986 | d->AddRef(); | ||
| 987 | now.push_back(e); | ||
| 988 | } else { | ||
| 989 | queue_event(e); | ||
| 990 | } | ||
| 991 | } | ||
| 992 | } | ||
| 993 | } | ||
| 994 | if (token) *token = t; | ||
| 995 | // Blocking enumeration: every connected device is reported before this returns, on the caller's thread. | ||
| 996 | for (const Event& e : now) { | ||
| 997 | fn(t, context, e.device, e.timestamp, e.current, e.previous); | ||
| 998 | e.device->Release(); | ||
| 999 | } | ||
| 1000 | return S_OK; | ||
| 1001 | } | ||
| 1002 | |||
| 1003 | HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice* device, void* context, | ||
| 1004 | GameInputGuideButtonCallback fn, GameInputCallbackToken* token) override { | ||
| 1005 | return add({0, CbType::Guide, as_device(device), 0, 0, context, reinterpret_cast<void*>(fn), true}, token); | ||
| 1006 | } | ||
| 1007 | // Gamepads have no keyboard layout; the callback is accepted and never runs. | ||
| 1008 | HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice* device, void* context, | ||
| 1009 | GameInputKeyboardLayoutCallback fn, GameInputCallbackToken* token) override { | ||
| 1010 | return add({0, CbType::KeyboardLayout, as_device(device), 0, 0, context, reinterpret_cast<void*>(fn), true}, token); | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { | ||
| 1014 | std::lock_guard lock(g().mu); | ||
| 1015 | for (Callback& c : g().callbacks) | ||
| 1016 | if (c.token == token) c.active = false; | ||
| 1017 | } | ||
| 1018 | |||
| 1019 | // Removes the callback and, unless called from inside a callback, waits for one that is running to return. | ||
| 1020 | // VERIFY: the timeout is not honoured; the wait is for at most one callback. | ||
| 1021 | bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override { | ||
| 1022 | State& s = g(); | ||
| 1023 | bool found = false; | ||
| 1024 | { | ||
| 1025 | std::lock_guard lock(s.mu); | ||
| 1026 | auto it = std::find_if(s.callbacks.begin(), s.callbacks.end(), [token](const Callback& c) { return c.token == token; }); | ||
| 1027 | if (it != s.callbacks.end()) { | ||
| 1028 | s.callbacks.erase(it); | ||
| 1029 | found = true; | ||
| 1030 | } | ||
| 1031 | } | ||
| 1032 | if (found && s.delivering_thread != GetCurrentThreadId()) std::lock_guard wait(s.deliver_mu); | ||
| 1033 | return found; | ||
| 1034 | } | ||
| 1035 | |||
| 1036 | HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { | ||
| 1037 | if (!out) return E_POINTER; | ||
| 1038 | *out = new Dispatcher; | ||
| 1039 | return S_OK; | ||
| 1040 | } | ||
| 1041 | HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t, IGameInputDevice** out) override { | ||
| 1042 | if (out) *out = nullptr; | ||
| 1043 | return E_NOTIMPL; | ||
| 1044 | } | ||
| 1045 | HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* id, IGameInputDevice** out) override { | ||
| 1046 | if (!out) return E_POINTER; | ||
| 1047 | *out = nullptr; | ||
| 1048 | if (!id) return E_INVALIDARG; | ||
| 1049 | std::lock_guard lock(g().mu); | ||
| 1050 | for (Device* d : g().devices) | ||
| 1051 | if (std::memcmp(&d->info.deviceId, id, sizeof *id) == 0) { | ||
| 1052 | d->AddRef(); | ||
| 1053 | *out = d; | ||
| 1054 | return S_OK; | ||
| 1055 | } | ||
| 1056 | return GAMEINPUT_E_DEVICE_NOT_FOUND; | ||
| 1057 | } | ||
| 1058 | HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown*, IGameInputDevice** out) override { return not_found(out); } | ||
| 1059 | HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE, IGameInputDevice** out) override { return not_found(out); } | ||
| 1060 | HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR, IGameInputDevice** out) override { return not_found(out); } | ||
| 1061 | HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) override { return S_OK; } | ||
| 1062 | // Input keeps arriving in the background: the runtime has no focus model yet. | ||
| 1063 | void STDMETHODCALLTYPE SetFocusPolicy(uint32_t) override {} | ||
| 1064 | |||
| 1065 | private: | ||
| 1066 | static HRESULT not_found(IGameInputDevice** out) { | ||
| 1067 | if (out) *out = nullptr; | ||
| 1068 | return GAMEINPUT_E_DEVICE_NOT_FOUND; | ||
| 1069 | } | ||
| 1070 | static HRESULT add(Callback c, GameInputCallbackToken* token) { | ||
| 1071 | if (token) *token = kInvalidCallbackToken; | ||
| 1072 | if (!c.fn) return E_INVALIDARG; | ||
| 1073 | std::lock_guard lock(g().mu); | ||
| 1074 | c.token = g().next_token++; | ||
| 1075 | g().callbacks.push_back(c); | ||
| 1076 | if (token) *token = c.token; | ||
| 1077 | return S_OK; | ||
| 1078 | } | ||
| 1079 | std::atomic<ULONG> refs_{1}; | ||
| 1080 | }; | ||
| 1081 | |||
| 1082 | GameInput& instance() { | ||
| 1083 | static GameInput* gi = new GameInput; | ||
| 1084 | return *gi; | ||
| 1085 | } | ||
| 1086 | |||
| 1087 | // HRESULT GameInputCreate(IGameInput** gameInput). One instance per process; each call adds a reference. | ||
| 1088 | HRESULT WINAPI GameInputCreate(IGameInput** out) { | ||
| 1089 | if (!out) return E_POINTER; | ||
| 1090 | ensure_started(); | ||
| 1091 | GameInput& gi = instance(); | ||
| 1092 | gi.AddRef(); | ||
| 1093 | *out = &gi; | ||
| 1094 | return S_OK; | ||
| 1095 | } | ||
| 1096 | |||
| 1097 | } // namespace | ||
| 1098 | |||
| 1099 | namespace rt::gameinput { | ||
| 1100 | |||
| 1101 | const Config& config() { | ||
| 1102 | ensure_started(); | ||
| 1103 | return g().config; | ||
| 1104 | } | ||
| 1105 | |||
| 1106 | void reload_config() { | ||
| 1107 | std::lock_guard lock(g().mu); | ||
| 1108 | g().config = read_config(); | ||
| 1109 | g().config_read = true; | ||
| 1110 | } | ||
| 1111 | |||
| 1112 | void poll() { | ||
| 1113 | ensure_started(); | ||
| 1114 | poll_and_deliver(); | ||
| 1115 | } | ||
| 1116 | |||
| 1117 | int connected_count() { | ||
| 1118 | std::lock_guard lock(g().mu); | ||
| 1119 | return static_cast<int>(g().connected.size()); | ||
| 1120 | } | ||
| 1121 | |||
| 1122 | bool output_state(int i, OutputState* out) { | ||
| 1123 | std::lock_guard lock(g().mu); | ||
| 1124 | if (i < 0 || i >= static_cast<int>(g().connected.size()) || !out) return false; | ||
| 1125 | *out = g().connected[static_cast<size_t>(i)]->sent; | ||
| 1126 | return true; | ||
| 1127 | } | ||
| 1128 | |||
| 1129 | } // namespace rt::gameinput | ||
| 1130 | |||
| 1131 | SHIM_TABLE(gameinput, | ||
| 1132 | {"gameinput.dll", "GameInputCreate", reinterpret_cast<void*>(&GameInputCreate)}, | ||
| 1133 | {"xgameruntime.dll", "GameInputCreate", reinterpret_cast<void*>(&GameInputCreate)}, | ||
| 1134 | ); | ||