From e7c83353c7aabdffa873f963f20d9ab6a1b938a9 Mon Sep 17 00:00:00 2001 From: marquezini Date: Sun, 22 Nov 2026 16:32:10 -0300 Subject: RT-176: Dispatch runs only the batch queued when it starts Review follow-up. Dispatch took events one at a time from the live queue, so readings queued during the call (by the poll thread, or by a callback) were delivered in the same call: with an unlimited quota a busy queue could keep the title inside Dispatch, and each erase at the front made a drain O(n^2) under deliver_mu. Dispatch now swaps out the batch present at entry and walks it in order; events it leaves (quota spent) go back to the front of the queue, ahead of newer ones. gameinput_test adds a callback that queues a reading from inside the call: each Dispatch(UINT64_MAX) runs exactly its starting batch and returns true (the previous version never returned). The docs say so, and the dispatcher row's open column reads a dash instead of a blank. --- runtime/test/gameinput_test.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'runtime/test/gameinput_test.cpp') diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index d9b5d57e2..5156cbe82 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -131,10 +131,17 @@ void CALLBACK on_device(GameInputCallbackToken token, void*, IGameInputDevice* d g_device_events.push_back({device, current, previous, token}); } DWORD g_reading_sleep_ms = 0; // makes on_reading slow, for the Dispatch quota checks +SDL_Joystick* g_requeue_pad = nullptr; // set: on_reading queues one more reading from inside the callback +bool g_requeue_down = false; void CALLBACK on_reading(GameInputCallbackToken, void*, IGameInputReading* reading, bool) { if (reading) ++g_reading_events; if (g_reading_sleep_ms) Sleep(g_reading_sleep_ms); + if (g_requeue_pad) { + g_requeue_down = !g_requeue_down; + SDL_SetJoystickVirtualButton(g_requeue_pad, SDL_GAMEPAD_BUTTON_WEST, g_requeue_down); + rt::gameinput::poll(); + } } void CALLBACK on_guide(GameInputCallbackToken, void*, IGameInputDevice*, uint64_t, bool pressed) { g_guide_events.push_back(pressed); @@ -998,6 +1005,8 @@ int main() { if (wait) WaitForSingleObject(wait, 0); // consume the signal from queueing check(dispatcher->Dispatch(0) && g_reading_events == before_quota + 1, "Dispatch(0) runs exactly one event and reports more"); check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled again while events remain"); + // The callback sleeps 5 ms, so at least 5 ms have passed after the first event however loaded the machine + // is; a slower run only makes the 1 ms quota more clearly spent. g_reading_sleep_ms = 5; before_quota = g_reading_events; check(dispatcher->Dispatch(1000) && g_reading_events == before_quota + 1, @@ -1007,6 +1016,26 @@ int main() { check(!dispatcher->Dispatch(1'000'000) && g_reading_events >= before_quota + 2, "a large quota drains the queue and returns false"); check(!dispatcher->Dispatch(0), "Dispatch on an empty queue returns false"); + + // Events queued during a call wait for the next one: each callback here queues another reading, so a + // Dispatch that kept draining would never return. With two events queued, each call runs exactly the batch + // it started with and reports the readings queued meanwhile. + queue_changes(2); + g_requeue_pad = xbox.js; + before_quota = g_reading_events; + check(dispatcher->Dispatch(UINT64_MAX) && g_reading_events == before_quota + 2, + "Dispatch runs only the events queued when it started"); + before_quota = g_reading_events; + check(dispatcher->Dispatch(UINT64_MAX) && g_reading_events == before_quota + 2, + "the events queued during the call run on the next one"); + g_requeue_pad = nullptr; + while (dispatcher->Dispatch(UINT64_MAX)) {} + if (g_requeue_down) { + g_requeue_down = false; + SDL_SetJoystickVirtualButton(xbox.js, SDL_GAMEPAD_BUTTON_WEST, false); + rt::gameinput::poll(); + while (dispatcher->Dispatch(UINT64_MAX)) {} + } } if (wait) CloseHandle(wait); if (dispatcher) dispatcher->Release(); -- cgit v1.2.3 From 364fdcbd28feb1708fd28b4727b3cc8f4a1ad1a7 Mon Sep 17 00:00:00 2001 From: Bora Sevim Date: Sun, 22 Nov 2026 22:35:50 +0300 Subject: gameinput: raw HID reports and raw device I/O through SDL's hidapi (RT-175) The shim opens each pad's HID device with SDL_hid_* (by SDL's device path, else the one game-pad collection with the pad's vendor and product id) and reads its report descriptor for every input, output and feature report's id and size. Such a pad reports GameInputKindRawDeviceReport and GameInputDeviceRawIoEnabled and fills inputReportInfo, outputReportInfo and featureReportInfo (no item tables). Readings carry the newest raw input report, and IGameInputReading::GetRawReport returns it as an IGameInputRawDeviceReport. CreateRawDeviceReport, GetRawDeviceFeature, SetRawDeviceFeature and SendRawDeviceOutput work through the backend; an undeclared id or kind is E_INVALIDARG, a failed transfer E_FAIL, and a pad without a HID device keeps E_NOTIMPL. gameinput_abi.h declares IGameInputRawDeviceReport, GameInputRawDeviceReportKind and the three raw report info structs, checked against Microsoft's v0 header (offsetof for every field, the 12 vtable slots, the IID). Xbox pads on Windows go through XInput, whose HID interface SDL's hidapi skips, so they have no raw I/O; the log says so. gameinput_test covers the descriptor parser and the whole path with a fake HID backend (24 checks); gameinput_probe prints each pad's report tables and newest raw input report. docs/gameinput.md: "Raw HID". --- docs/gameinput.md | 67 ++++++- runtime/shims/gameinput.cpp | 376 +++++++++++++++++++++++++++++++++++++-- runtime/shims/gameinput.h | 33 ++++ runtime/shims/gameinput_abi.h | 71 +++++++- runtime/test/gameinput_probe.cpp | 29 ++- runtime/test/gameinput_test.cpp | 218 +++++++++++++++++++++++ 6 files changed, 769 insertions(+), 25 deletions(-) (limited to 'runtime/test/gameinput_test.cpp') diff --git a/docs/gameinput.md b/docs/gameinput.md index ab5fa2feb..4496820e6 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -201,14 +201,56 @@ The API surface: | interface | implemented | not implemented | |---|---|---| | `IGameInput` | `GetCurrentTimestamp` (µs), `GetCurrentReading`, `GetNextReading`, `GetPreviousReading`, `RegisterReadingCallback`, `RegisterDeviceCallback` (blocking and async enumeration), `RegisterGuideButtonCallback`, `RegisterKeyboardLayoutCallback` (never fires), `StopCallback`, `UnregisterCallback`, `CreateDispatcher`, `FindDeviceFromId`, `EnableOemDeviceSupport` (no-op), `SetFocusPolicy` (no-op) | `GetTemporalReading` (`E_NOTIMPL`, as in GameInput v0 itself; see below), `CreateAggregateDevice`, `FindDeviceFromObject/PlatformHandle/PlatformString` | -| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state | raw report, keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | -| `IGameInputDevice` | device info, status, battery, `SetRumbleState` | force feedback and haptic motors (none reported), raw device I/O, power off, input synchronization (no-ops) | +| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state, raw report (pads opened through HID, see [Raw HID](#raw-hid)) | keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | +| `IGameInputDevice` | device info, status, battery, `SetRumbleState`, `CreateRawDeviceReport`, `GetRawDeviceFeature`, `SetRawDeviceFeature`, `SendRawDeviceOutput` (pads opened through HID) | force feedback and haptic motors (none reported), `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl`, exclusive raw access, power off, input synchronization (no-ops) | +| `IGameInputRawDeviceReport` | device, report info (kind, id, size), raw data size, get and set raw data | item values (`Get/Set/ResetItemValue`, `ResetAllItems` answer false: no item tables) | | `IGameInputDispatcher` | `Dispatch`, `OpenWaitHandle` | the quota (the queue is short) | A device object stays alive for the whole process. When a pad is unplugged its status drops to `GameInputDeviceNoStatus` and its device callback runs; when the same pad is plugged in again (matched by SDL GUID and serial or device path) the title gets the same object back, connected again. +## Raw HID + +A title can read a pad's raw HID input reports and send it output and feature reports (RT-175). The shim opens each +pad's HID device through SDL's hidapi (`SDL_hid_*`), by the device path SDL reports for the pad. When that path is not +a HID path, it falls back to the pad's vendor and product id, but only when exactly one game-pad collection (usage page +1, usage 5) has them, so twins never mix. It reads the report descriptor to find every input, output and feature +report: its id (0 when the descriptor declares none) and its payload size in bytes, without the id byte. + +A pad opened this way gets the following: + +- `GameInputKindRawDeviceReport` in `supportedInput` and `GameInputDeviceRawIoEnabled` in its status. +- `inputReportInfo`, `outputReportInfo` and `featureReportInfo` tables with their counts. Every report has `itemCount` + 0: the descriptor's items (usages, logical ranges, units) are not decoded. +- Readings that carry the newest raw input report. Each poll drains the reports that arrived, the last declared one + wins, and a report with new bytes makes a reading of its own. Before the first report, a reading carries none. +- These device calls, each on any `IGameInputRawDeviceReport` of the right kind whose id the pad declares: + - `CreateRawDeviceReport(id, kind)` makes a zeroed report. + - `GetRawDeviceFeature(id)` reads a feature report. + - `SetRawDeviceFeature` sends one. + - `SendRawDeviceOutput` writes an output report. + + An undeclared id or kind is `E_INVALIDARG`, and a failed transfer `E_FAIL`. + +`SetRawData` takes a buffer of exactly the report's size and refuses any other size, so a report is never half old and +half new. The item calls answer false. `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl` and exclusive +access still return `E_NOTIMPL` / false. + +A pad without such a HID device keeps the old answers: no raw kind, no tables, `E_NOTIMPL` from the raw calls. + +- **Xbox pads on Windows** are read by SDL through XInput (path `XInput#n`). SDL's hidapi skips their XInput HID + interface (`&IG_` in the path), noting that it carries no full HID reports. So they have no raw I/O here, and the log + says so. +- **SDL virtual joysticks and the keyboard pad** have no path, so no HID device either. +- **Pads SDL reads through hidapi** can have raw I/O: DualSense, DualShock 4, Switch Pro, and most others in DirectInput + mode. + +`rt::gameinput::set_hid_backend` replaces the hidapi backend (tests). `rt::gameinput::parse_report_descriptor` is the +descriptor walk: main items Input, Output and Feature add Report Size × Report Count bits to the current Report ID, Push +and Pop save and restore the globals, and long items are skipped. It refuses a truncated item, Report ID 0 or above +255, a Pop without a Push, and a report over 64 KiB. + ## Reading history Each pad keeps the readings the poll took for it, one per change it saw, so `GetNextReading` and `GetPreviousReading` @@ -280,8 +322,16 @@ shim fills (`GameInputDeviceInfo` 320 bytes with `deviceFamily` at 96 and the in binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and triggers on focus loss, the `always` mode, and turning it off and on again. -- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads, plays each motor and - trigger for a second with `--rumble`, then prints the live reading. + Raw HID (RT-175) is tested in two ways: + - `parse_report_descriptor` runs on synthetic descriptors: report ids, none, Push/Pop, a long item, and the refused + forms. + - A fake backend (`set_hid_backend`) stands behind a virtual pad with pid.codes test ids. The test checks the report + tables, the kind and status bits, a reading's raw report (newest declared id, without the id byte, an undeclared id + ignored), creating, sending and reading back output and feature reports with their id byte, `SetRawData`'s exact + size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, and the HID device closing on unplug. +- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads with each one's raw HID + report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, then prints the live + reading and the newest raw input report. ## VERIFY @@ -323,3 +373,12 @@ These need the game executable or a test on hardware: near center or jumpy. - **DualSense effect parameters**: the `06` (vibration) and `01` (resistance) byte meanings follow SDL's `testcontroller.c`; how strong 255 feels and what frequency suits the Xbox signal needs a session on a real pad. +- **Raw HID on a real pad**: only the synthetic tests and the XInput refusal have run. + - What ran: an Xbox Series X controller over Bluetooth on Windows 11 connects and plays normally, with no raw I/O, + and the log names the reason. + - Still to confirm: a DualSense, DualShock 4 or Switch Pro through `gameinput_probe`, which should print the + descriptor's reports and changing raw input bytes. + - Size convention: report sizes exclude the id byte, and `GetRawData` returns the payload without it. What + Microsoft's runtime does for a device with report ids is not documented on the reference pages. + - Readings: a pad that streams reports makes a reading for each changed one, like the runtime's + `GameInputKindRawDeviceReport` stream, but whether the title asks for raw reports at all is unknown. diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 21924801c..003efdc32 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -52,7 +52,8 @@ namespace { constexpr uint32_t kBaseKinds = GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; -constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion; // everything a reading may carry +// Everything a reading may carry: motion on pads with sensors, raw reports on pads opened through HID (RT-175). +constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion | GameInputKindRawDeviceReport; constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT; constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; @@ -146,12 +147,18 @@ struct Snapshot { bool guide = false; GameInputMotionState motion{}; // valid only when has_motion; does not take part in operator== bool has_motion = false; + // The newest raw input report of a pad opened through HID (RT-175): its report id and payload, without the id + // byte. A new report with other bytes is a change, so it makes a reading of its own. + bool has_raw = false; + uint32_t raw_id = 0; + std::vector raw; bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised const GameInputGamepadState &a = gamepad, &b = o.gamepad; return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && a.leftThumbstickX == b.leftThumbstickX && a.leftThumbstickY == b.leftThumbstickY && a.rightThumbstickX == b.rightThumbstickX && a.rightThumbstickY == b.rightThumbstickY && ui == o.ui && - std::memcmp(buttons, o.buttons, sizeof buttons) == 0 && guide == o.guide; + std::memcmp(buttons, o.buttons, sizeof buttons) == 0 && guide == o.guide && has_raw == o.has_raw && + raw_id == o.raw_id && raw == o.raw; } }; @@ -178,15 +185,13 @@ public: } uint32_t STDMETHODCALLTYPE GetInputKind() override { - return s_.has_motion ? kSupportedKinds : kBaseKinds; // a reading of a pad without sensors carries no motion + // A reading of a pad without sensors carries no motion, and one without a raw report no raw report. + return kBaseKinds | (s_.has_motion ? GameInputKindMotion : 0u) | (s_.has_raw ? GameInputKindRawDeviceReport : 0u); } uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; - bool STDMETHODCALLTYPE GetRawReport(void** report) override { - if (report) *report = nullptr; - return false; - } + bool STDMETHODCALLTYPE GetRawReport(void** report) override; uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; } uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override { const uint32_t n = out ? std::min(count, kAxisCount) : 0; @@ -271,16 +276,11 @@ public: void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} void STDMETHODCALLTYPE PowerOff() override {} - HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t, int32_t, void** report) override { - if (report) *report = nullptr; - return E_NOTIMPL; - } - HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t, void** report) override { - if (report) *report = nullptr; - return E_NOTIMPL; - } - HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void*) override { return E_NOTIMPL; } - HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void*) override { return E_NOTIMPL; } + // Raw HID (RT-175): reports of the pad's HID device through rt::gameinput::HidBackend (SDL_hid_* by default). + HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t reportId, int32_t reportKind, void** report) override; + HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t reportId, void** report) override; + HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void* report) override; + HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void* report) override; HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { if (response) *response = nullptr; return E_NOTIMPL; @@ -321,6 +321,17 @@ public: uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; bool ds_sent_once = false; + // Raw HID (RT-175). hid is the backend's handle, null when the pad has no HID device the backend could open; + // hid_mu serialises every call on it, from the poll thread (reads) and the title's threads (output, features). + // The report tables come from the HID report descriptor; info.input/output/featureReportInfo point into them. + std::mutex hid_mu; + void* hid = nullptr; + const rt::gameinput::HidBackend* hid_backend = nullptr; // the backend hid was opened with + bool hid_ids = false; // the descriptor declares report ids, so an input report starts with its id byte + std::vector raw_in, raw_out, raw_feature; + const GameInputRawDeviceReportInfo* find_raw(int32_t kind, uint32_t report_id) const; + HRESULT send_raw(void* report, GameInputRawDeviceReportKind kind); + private: std::atomic refs_{1}; }; @@ -336,6 +347,179 @@ void Reading::GetDevice(IGameInputDevice** device) { *device = device_; } +// ---- raw HID (RT-175) ------------------------------------------------------------------------------------------- + +// One raw report: its own copy of the report info (so it outlives a reconnect that rebuilds the device's tables) and +// payload. There are no item tables (itemCount 0), so the item calls answer false; see docs/gameinput.md "Raw HID". +class RawReport final : public IGameInputRawDeviceReport { +public: + RawReport(Device* device, const GameInputRawDeviceReportInfo& info, const uint8_t* data, size_t size) + : device_(device), info_(info), data_(info.size, 0) { + info_.itemCount = 0; + info_.items = nullptr; + if (data) std::memcpy(data_.data(), data, std::min(size, data_.size())); + device_->AddRef(); + } + ~RawReport() { device_->Release(); } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputRawDeviceReport)) { + AddRef(); + *out = static_cast(this); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG r = --refs_; + if (r == 0) delete this; + return r; + } + + void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; + const GameInputRawDeviceReportInfo* STDMETHODCALLTYPE GetReportInfo() override { return &info_; } + size_t STDMETHODCALLTYPE GetRawDataSize() override { return data_.size(); } + size_t STDMETHODCALLTYPE GetRawData(size_t bufferSize, void* buffer) override { + const size_t n = buffer ? std::min(bufferSize, data_.size()) : 0; + if (n) std::memcpy(buffer, data_.data(), n); + return n; + } + // The whole payload at once: a buffer of another size is refused, so a report is never half old, half new. + bool STDMETHODCALLTYPE SetRawData(size_t bufferSize, const void* buffer) override { + if (!buffer || bufferSize != data_.size()) return false; + std::memcpy(data_.data(), buffer, bufferSize); + return true; + } + bool STDMETHODCALLTYPE GetItemValue(uint32_t, int64_t* value) override { + if (value) *value = 0; + return false; + } + bool STDMETHODCALLTYPE SetItemValue(uint32_t, int64_t) override { return false; } + bool STDMETHODCALLTYPE ResetItemValue(uint32_t) override { return false; } + bool STDMETHODCALLTYPE ResetAllItems() override { return false; } + +private: + std::atomic refs_{1}; + Device* device_; + GameInputRawDeviceReportInfo info_; + std::vector data_; +}; + +void RawReport::GetDevice(IGameInputDevice** device) { + if (!device) return; + device_->AddRef(); + *device = device_; +} + +// The default backend: SDL's hidapi. A pad is opened by the path SDL reports for it; with no such HID path, by its +// vendor and product id when exactly one game-pad collection (usage page 1, usage 5) matches, so twins never mix. +// A pad without a path (SDL virtual joysticks, the keyboard pad) gets no HID device. +void* sdl_hid_open(const char* path, uint16_t vendor, uint16_t product) { + if (!path || !*path) return nullptr; + static const bool ok = SDL_hid_init() == 0; + if (!ok) return nullptr; + if (SDL_hid_device* h = SDL_hid_open_path(path)) return h; + SDL_hid_device_info* list = SDL_hid_enumerate(vendor, product); + const char* only = nullptr; + int matches = 0; + for (SDL_hid_device_info* i = list; i; i = i->next) + if (i->usage_page == 0x01 && i->usage == 0x05 && ++matches == 1) only = i->path; + SDL_hid_device* h = (matches == 1 && only) ? SDL_hid_open_path(only) : nullptr; + SDL_hid_free_enumeration(list); + return h; +} +void sdl_hid_close(void* h) { SDL_hid_close(static_cast(h)); } +int sdl_hid_descriptor(void* h, uint8_t* buf, size_t size) { + return SDL_hid_get_report_descriptor(static_cast(h), buf, size); +} +int sdl_hid_read(void* h, uint8_t* buf, size_t size) { + return SDL_hid_read_timeout(static_cast(h), buf, size, 0); +} +int sdl_hid_write(void* h, const uint8_t* buf, size_t size) { + return SDL_hid_write(static_cast(h), buf, size); +} +int sdl_hid_get_feature(void* h, uint8_t* buf, size_t size) { + return SDL_hid_get_feature_report(static_cast(h), buf, size); +} +int sdl_hid_send_feature(void* h, const uint8_t* buf, size_t size) { + return SDL_hid_send_feature_report(static_cast(h), buf, size); +} +const rt::gameinput::HidBackend kSdlHid = {sdl_hid_open, sdl_hid_close, sdl_hid_descriptor, sdl_hid_read, + sdl_hid_write, sdl_hid_get_feature, sdl_hid_send_feature}; +std::atomic g_hid{&kSdlHid}; + +bool Reading::GetRawReport(void** report) { + if (!report) return false; + *report = nullptr; + if (!s_.has_raw) return false; + const GameInputRawDeviceReportInfo* info = device_->find_raw(GameInputRawInputReport, s_.raw_id); + if (!info) return false; + *report = static_cast(new RawReport(device_, *info, s_.raw.data(), s_.raw.size())); + return true; +} + +const GameInputRawDeviceReportInfo* Device::find_raw(int32_t kind, uint32_t report_id) const { + const std::vector* list = kind == GameInputRawInputReport ? &raw_in + : kind == GameInputRawOutputReport ? &raw_out + : kind == GameInputRawFeatureReport ? &raw_feature + : nullptr; + if (!list) return nullptr; + for (const GameInputRawDeviceReportInfo& r : *list) + if (r.id == report_id) return &r; + return nullptr; +} + +HRESULT Device::CreateRawDeviceReport(uint32_t reportId, int32_t reportKind, void** report) { + if (!report) return E_POINTER; + *report = nullptr; + std::lock_guard lock(hid_mu); + if (!hid) return E_NOTIMPL; // no raw I/O on this pad (GameInputDeviceRawIoEnabled is not set) + const GameInputRawDeviceReportInfo* ri = find_raw(reportKind, reportId); + if (!ri) return E_INVALIDARG; + *report = static_cast(new RawReport(this, *ri, nullptr, 0)); + return S_OK; +} + +HRESULT Device::GetRawDeviceFeature(uint32_t reportId, void** report) { + if (!report) return E_POINTER; + *report = nullptr; + std::lock_guard lock(hid_mu); + if (!hid) return E_NOTIMPL; + const GameInputRawDeviceReportInfo* ri = find_raw(GameInputRawFeatureReport, reportId); + if (!ri) return E_INVALIDARG; + std::vector buf(ri->size + 1, 0); + buf[0] = static_cast(reportId); // hidapi: the id goes first, 0 for a device without ids + const int n = hid_backend->get_feature(hid, buf.data(), buf.size()); + if (n < 1) return E_FAIL; + *report = static_cast(new RawReport(this, *ri, buf.data() + 1, static_cast(n) - 1)); + return S_OK; +} + +// SetRawDeviceFeature and SendRawDeviceOutput: any IGameInputRawDeviceReport of the right kind whose id this pad +// declares; the payload is sent with the id byte in front, as hidapi takes it. +HRESULT Device::send_raw(void* report, GameInputRawDeviceReportKind kind) { + if (!report) return E_INVALIDARG; + auto* r = static_cast(report); + const GameInputRawDeviceReportInfo* given = r->GetReportInfo(); + std::lock_guard lock(hid_mu); + if (!hid) return E_NOTIMPL; + if (!given || given->kind != kind) return E_INVALIDARG; + const GameInputRawDeviceReportInfo* ri = find_raw(kind, given->id); + if (!ri) return E_INVALIDARG; + std::vector buf(ri->size + 1, 0); + buf[0] = static_cast(ri->id); + r->GetRawData(ri->size, buf.data() + 1); + const rt::gameinput::HidBackend* b = hid_backend; + const int n = kind == GameInputRawFeatureReport ? b->send_feature(hid, buf.data(), buf.size()) + : b->write(hid, buf.data(), buf.size()); + return n < 0 ? E_FAIL : S_OK; +} +HRESULT Device::SetRawDeviceFeature(void* report) { return send_raw(report, GameInputRawFeatureReport); } +HRESULT Device::SendRawDeviceOutput(void* report) { return send_raw(report, GameInputRawOutputReport); } + // ---- callbacks -------------------------------------------------------------------------------------------------- enum class CbType { Device, Reading, Guide, KeyboardLayout }; @@ -651,6 +835,92 @@ Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) { return h.back(); } +// Raw HID (RT-175): opens the pad's HID device with the current backend and builds the report tables from its report +// descriptor. A pad the backend cannot open, or whose descriptor cannot be read or declares no report, gets no raw +// I/O: no GameInputKindRawDeviceReport, no report tables, and E_NOTIMPL from the raw device calls. Under g().mu. +void open_raw(Device* d, const char* path) { + std::lock_guard lock(d->hid_mu); + if (d->hid) d->hid_backend->close(d->hid); + d->hid = nullptr; + d->hid_ids = false; + d->raw_in.clear(); + d->raw_out.clear(); + d->raw_feature.clear(); + const rt::gameinput::HidBackend* b = g_hid.load(); + void* h = b->open(path, d->info.vendorId, d->info.productId); + if (!h) { + // SDL reads Xbox pads on Windows through XInput ("XInput#n"); SDL's hidapi skips their XInput HID interface + // (&IG_ in the path), which carries no full HID reports, so they have no raw I/O here. + const bool xinput = path && std::strncmp(path, "XInput#", 7) == 0; + std::fprintf(stderr, "[rt] gameinput: %s: no raw HID (%s)\n", d->name.c_str(), + xinput ? "an XInput pad: SDL's hidapi does not open XInput HID interfaces" + : path && *path ? "its HID device could not be opened" + : "SDL reports no device path"); + return; + } + std::vector desc(4096); + const int n = b->descriptor(h, desc.data(), desc.size()); + std::vector reports; + const bool parsed = n > 0 && rt::gameinput::parse_report_descriptor(desc.data(), static_cast(n), &reports); + if (!parsed || reports.empty()) { + std::fprintf(stderr, "[rt] gameinput: %s: no raw HID (%s)\n", d->name.c_str(), + n <= 0 ? "no report descriptor" : !parsed ? "malformed report descriptor" : "no reports declared"); + b->close(h); + return; + } + for (const rt::gameinput::RawReportSize& r : reports) { + const GameInputRawDeviceReportInfo info{static_cast(r.kind), r.id, r.bytes, 0, nullptr}; + (r.kind == GameInputRawInputReport ? d->raw_in : r.kind == GameInputRawOutputReport ? d->raw_out : d->raw_feature) + .push_back(info); + d->hid_ids |= r.id != 0; + } + d->hid = h; + d->hid_backend = b; + GameInputDeviceInfo& i = d->info; + i.supportedInput |= GameInputKindRawDeviceReport; + i.inputReportCount = static_cast(d->raw_in.size()); + i.inputReportInfo = d->raw_in.empty() ? nullptr : d->raw_in.data(); + i.outputReportCount = static_cast(d->raw_out.size()); + i.outputReportInfo = d->raw_out.empty() ? nullptr : d->raw_out.data(); + i.featureReportCount = static_cast(d->raw_feature.size()); + i.featureReportInfo = d->raw_feature.empty() ? nullptr : d->raw_feature.data(); +} + +void close_raw(Device* d) { + std::lock_guard lock(d->hid_mu); + if (d->hid) d->hid_backend->close(d->hid); + d->hid = nullptr; +} + +// Drains the input reports pending since the last poll; the newest one the pad declares goes into snap. With none +// pending, snap keeps the previous report, so a quiet pad makes no new reading. Poll thread. +void read_raw(Device* d, Snapshot* snap) { + snap->has_raw = d->last_snap.has_raw; + snap->raw_id = d->last_snap.raw_id; + snap->raw = d->last_snap.raw; + std::lock_guard lock(d->hid_mu); + if (!d->hid) return; + std::vector buf(4096); + for (int k = 0; k < 64; ++k) { // bounded: a pad that floods cannot hold up the poll + const int n = d->hid_backend->read(d->hid, buf.data(), buf.size()); + if (n <= 0) break; + uint32_t id = 0; + const uint8_t* p = buf.data(); + size_t len = static_cast(n); + if (d->hid_ids) { + id = buf[0]; + ++p; + --len; + } + const GameInputRawDeviceReportInfo* info = d->find_raw(GameInputRawInputReport, id); + if (!info) continue; + snap->has_raw = true; + snap->raw_id = id; + snap->raw.assign(p, p + std::min(len, static_cast(info->size))); + snap->raw.resize(info->size, 0); + } +} + void open_pad(SDL_JoystickID jid, uint64_t ts) { State& s = g(); SDL_Gamepad* p = SDL_OpenGamepad(jid); @@ -710,6 +980,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; d->wanted = {}; fill_info(d, p, id); + open_raw(d, path); // Player LEDs and SDL's default lightbar colour follow the slot: the lowest one not in use. int player = 0; @@ -725,6 +996,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { uint32_t status = kConnectedStatus; if (d->info.capabilities & GameInputDeviceCapabilityWireless) status |= GameInputDeviceWireless; + if (d->hid) status |= GameInputDeviceRawIoEnabled; d->status = status; s.connected.push_back(d); @@ -742,6 +1014,7 @@ void close_pad(Device* d, uint64_t ts) { std::lock_guard lock(s.mu); const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); SDL_CloseGamepad(d->pad); + close_raw(d); d->pad = nullptr; d->player = -1; if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session @@ -1151,7 +1424,8 @@ void poll_once() { connected = s.connected; } for (Device* d : connected) { - const Snapshot snap = read_pad(d); + Snapshot snap = read_pad(d); + read_raw(d, &snap); const bool guide_changed = d->last_snap.guide != snap.guide; const bool changed = !(d->last_snap == snap); d->last_snap = snap; @@ -1612,6 +1886,72 @@ const KeyBinding* keyboard_bindings(int* count) { return kKeyBindings; } +// HID 1.11 section 6.2.2: a short item is one prefix byte (bSize in bits 0-1, 3 meaning 4 bytes; bType in bits 2-3; +// bTag in bits 4-7) and up to four data bytes, little-endian. 0xFE starts a long item (data size, tag, data). +bool parse_report_descriptor(const uint8_t* data, size_t size, std::vector* out) { + if (!out || (!data && size)) return false; + out->clear(); + struct Globals { + uint32_t report_size = 0, report_count = 0, report_id = 0; + }; + Globals g; + std::vector stack; + struct Key { + int kind; + uint32_t id; + uint64_t bits; + }; + std::vector reports; // first-seen order; sorted at the end + size_t i = 0; + while (i < size) { + const uint8_t prefix = data[i++]; + if (prefix == 0xFE) { // long item: bDataSize, bLongItemTag, data + if (i + 2 > size) return false; + i += 2 + data[i]; + if (i > size) return false; + continue; + } + const size_t n = (prefix & 3) == 3 ? 4 : (prefix & 3); + if (i + n > size) return false; + uint32_t v = 0; + for (size_t k = 0; k < n; ++k) v |= static_cast(data[i + k]) << (8 * k); + i += n; + const int type = (prefix >> 2) & 3, tag = prefix >> 4; + if (type == 1) { // global + if (tag == 7) g.report_size = v; + else if (tag == 8) { + if (v == 0 || v > 255) return false; + g.report_id = v; + } else if (tag == 9) g.report_count = v; + else if (tag == 10) stack.push_back(g); + else if (tag == 11) { + if (stack.empty()) return false; + g = stack.back(); + stack.pop_back(); + } + } else if (type == 0) { // main: Input 8, Output 9, Feature 11 (Collection 10 and End Collection 12 add nothing) + const int kind = tag == 8 ? 0 : tag == 9 ? 1 : tag == 11 ? 2 : -1; + if (kind < 0) continue; + const uint64_t add = static_cast(g.report_size) * g.report_count; + Key* k = nullptr; + for (Key& r : reports) + if (r.kind == kind && r.id == g.report_id) k = &r; + if (!k) { + reports.push_back({kind, g.report_id, 0}); + k = &reports.back(); + } + k->bits += add; + if (k->bits > 65536ull * 8) return false; + } + } + for (const Key& k : reports) out->push_back({k.kind, k.id, static_cast((k.bits + 7) / 8)}); + std::sort(out->begin(), out->end(), + [](const RawReportSize& a, const RawReportSize& b) { return a.kind != b.kind ? a.kind < b.kind : a.id < b.id; }); + return true; +} + +void set_hid_backend(const HidBackend* backend) { g_hid = backend ? backend : &kSdlHid; } + } // namespace rt::gameinput SHIM_TABLE(gameinput, diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h index 0aa3cf38d..29d3cc815 100644 --- a/runtime/shims/gameinput.h +++ b/runtime/shims/gameinput.h @@ -1,7 +1,9 @@ // GameInput shim on SDL3: runtime-side controls and test seams. The GameInput API itself is reached the way a title // reaches it, through GameInputCreate in the shim registry (gameinput.dll / xgameruntime.dll). See docs/gameinput.md. #pragma once +#include #include +#include namespace rt::gameinput { @@ -59,6 +61,37 @@ void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus); using CursorPosFn = bool (*)(int* x, int* y); void set_cursor_source(CursorPosFn cursor_pos); +// Raw HID (RT-175, docs/gameinput.md "Raw HID"). One report a HID report descriptor declares: its kind +// (GameInputRawDeviceReportKind: 0 input, 1 output, 2 feature), its report id (0 when the descriptor declares none) +// and its payload size in bytes, without the id byte. +struct RawReportSize { + int kind; + uint32_t id; + uint32_t bytes; +}; +// Reads the reports out of a HID report descriptor, sorted by kind then id. Main items Input/Output/Feature add +// Report Size x Report Count bits to the current report id; Push and Pop save and restore the globals; long items are +// skipped. False on a truncated descriptor, a Report ID of 0 or above 255, a Pop without a Push, or a report over +// 64 KiB. +bool parse_report_descriptor(const uint8_t* data, size_t size, std::vector* out); + +// Where the shim does a pad's HID I/O. The default is SDL's hidapi (SDL_hid_*). Report buffers follow hidapi: they +// start with the report id byte (0 for a device without ids) for write, get_feature and send_feature, and read +// returns it first only when the device uses ids. read never blocks: it returns 0 when nothing is pending. Every +// call returns a byte count, or a negative value on error. +struct HidBackend { + void* (*open)(const char* path, uint16_t vendor, uint16_t product); // nullptr: no HID device for this pad + void (*close)(void* hid); + int (*descriptor)(void* hid, uint8_t* buf, size_t size); + int (*read)(void* hid, uint8_t* buf, size_t size); + int (*write)(void* hid, const uint8_t* buf, size_t size); + int (*get_feature)(void* hid, uint8_t* buf, size_t size); + int (*send_feature)(void* hid, const uint8_t* buf, size_t size); +}; +// Test seam: the backend for pads opened from now on (pads already open keep theirs until they reconnect). nullptr +// restores SDL's. +void set_hid_backend(const HidBackend* backend); + // One row of the keyboard pad's key map: a Windows virtual-key code and the SDL gamepad button it presses. struct KeyBinding { int virtual_key; diff --git a/runtime/shims/gameinput_abi.h b/runtime/shims/gameinput_abi.h index 053b00cc9..f1b4d654f 100644 --- a/runtime/shims/gameinput_abi.h +++ b/runtime/shims/gameinput_abi.h @@ -193,8 +193,54 @@ struct GameInputVersion { uint16_t major, minor, build, revision; }; -struct GameInputRawDeviceReportInfo; -struct GameInputRawDeviceReportItemInfo; +// Raw HID reports (RT-175). Layouts and order match Microsoft's v0 header (NuGet Microsoft.GameInput +// 0.2303.22621.3038), checked with offsetof against it (docs/gameinput.md, "ABI"); the shim fills reportInfo with +// each report's kind, id and size and no items (itemCount 0, see docs/gameinput.md "Raw HID"). +enum GameInputRawDeviceReportKind : int32_t { + GameInputRawInputReport = 0, + GameInputRawOutputReport = 1, + GameInputRawFeatureReport = 2, +}; + +struct GameInputRawDeviceItemCollectionInfo { + int32_t kind; // GameInputRawDeviceItemCollectionKind + uint32_t childCount; + uint32_t siblingCount; + uint32_t usageCount; + const GameInputUsage* usages; + const GameInputRawDeviceItemCollectionInfo* parent; + const GameInputRawDeviceItemCollectionInfo* firstSibling; + const GameInputRawDeviceItemCollectionInfo* previousSibling; + const GameInputRawDeviceItemCollectionInfo* nextSibling; + const GameInputRawDeviceItemCollectionInfo* lastSibling; + const GameInputRawDeviceItemCollectionInfo* firstChild; + const GameInputRawDeviceItemCollectionInfo* lastChild; +}; + +struct GameInputRawDeviceReportItemInfo { + uint32_t bitOffset; + uint32_t bitSize; + int64_t logicalMin; + int64_t logicalMax; + double physicalMin; + double physicalMax; + int32_t physicalUnits; // GameInputRawDevicePhysicalUnitKind + uint32_t rawPhysicalUnits; + int32_t rawPhysicalUnitsExponent; + uint32_t flags; // GameInputRawDeviceReportItemFlags + uint32_t usageCount; + const GameInputUsage* usages; + const GameInputRawDeviceItemCollectionInfo* collection; + const GameInputString* itemString; +}; + +struct GameInputRawDeviceReportInfo { + GameInputRawDeviceReportKind kind; + uint32_t id; + uint32_t size; + uint32_t itemCount; + const GameInputRawDeviceReportItemInfo* items; +}; struct GameInputControllerAxisInfo { uint32_t mappedInputKinds; // GameInputKind @@ -331,6 +377,13 @@ static_assert(offsetof(GameInputDeviceInfo, inputReportInfo) == 160); static_assert(offsetof(GameInputDeviceInfo, gamepadInfo) == 256); static_assert(offsetof(GameInputDeviceInfo, displayName) == 296); static_assert(sizeof(GameInputDeviceInfo) == 320); +static_assert(sizeof(GameInputRawDeviceItemCollectionInfo) == 80); +static_assert(offsetof(GameInputRawDeviceItemCollectionInfo, usages) == 16); +static_assert(offsetof(GameInputRawDeviceReportItemInfo, physicalUnits) == 40); +static_assert(offsetof(GameInputRawDeviceReportItemInfo, usages) == 64); +static_assert(sizeof(GameInputRawDeviceReportItemInfo) == 88); +static_assert(offsetof(GameInputRawDeviceReportInfo, items) == 16); +static_assert(sizeof(GameInputRawDeviceReportInfo) == 24); struct IGameInputDevice; struct IGameInputReading; @@ -352,6 +405,8 @@ constexpr GUID IID_IGameInput = {0x11BE2A7E, 0x4254, 0x445A, {0x9C, 0x09, 0xFF, constexpr GUID IID_IGameInputReading = {0x2156947A, 0xE1FA, 0x4DE0, {0xA3, 0x0B, 0xD8, 0x12, 0x93, 0x1D, 0xBD, 0x8D}}; // {31DD86FB-4C1B-408A-868F-439B3CD47125} constexpr GUID IID_IGameInputDevice = {0x31DD86FB, 0x4C1B, 0x408A, {0x86, 0x8F, 0x43, 0x9B, 0x3C, 0xD4, 0x71, 0x25}}; +// {61F08CF1-1FFC-40CA-A2B8-E1AB8BC5B6DC} +constexpr GUID IID_IGameInputRawDeviceReport = {0x61F08CF1, 0x1FFC, 0x40CA, {0xA2, 0xB8, 0xE1, 0xAB, 0x8B, 0xC5, 0xB6, 0xDC}}; // {415EED2E-98CB-42C2-8F28-B94601074E31} constexpr GUID IID_IGameInputDispatcher = {0x415EED2E, 0x98CB, 0x42C2, {0x8F, 0x28, 0xB9, 0x46, 0x01, 0x07, 0x4E, 0x31}}; @@ -445,6 +500,18 @@ struct IGameInputDevice : IUnknown { virtual void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() = 0; }; +struct IGameInputRawDeviceReport : IUnknown { + virtual void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) = 0; + virtual const GameInputRawDeviceReportInfo* STDMETHODCALLTYPE GetReportInfo() = 0; + virtual size_t STDMETHODCALLTYPE GetRawDataSize() = 0; + virtual size_t STDMETHODCALLTYPE GetRawData(size_t bufferSize, void* buffer) = 0; + virtual bool STDMETHODCALLTYPE SetRawData(size_t bufferSize, const void* buffer) = 0; + virtual bool STDMETHODCALLTYPE GetItemValue(uint32_t itemIndex, int64_t* value) = 0; + virtual bool STDMETHODCALLTYPE SetItemValue(uint32_t itemIndex, int64_t value) = 0; + virtual bool STDMETHODCALLTYPE ResetItemValue(uint32_t itemIndex) = 0; + virtual bool STDMETHODCALLTYPE ResetAllItems() = 0; +}; + struct IGameInputDispatcher : IUnknown { virtual bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) = 0; virtual HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* waitHandle) = 0; diff --git a/runtime/test/gameinput_probe.cpp b/runtime/test/gameinput_probe.cpp index 32ddf5d91..297ca16db 100644 --- a/runtime/test/gameinput_probe.cpp +++ b/runtime/test/gameinput_probe.cpp @@ -2,7 +2,8 @@ // // gameinput_probe [--seconds N] [--rumble] // -// Lists the gamepads the shim sees, then prints the live gamepad reading of each for N seconds (default 10). With +// Lists the gamepads the shim sees, with the raw HID report tables of each pad opened through HID, then prints the +// live gamepad reading (and its newest raw input report, when there is one) for N seconds (default 10). With // --rumble it first plays, on every pad: the low-frequency motor, the high-frequency motor, the left and the right // impulse trigger, one second each. On a DualSense the trigger steps run in the LEONIDA_DS_TRIGGERS mode (rumble by // default; set it to resistance to feel that one). Everything goes through GameInputCreate from the shim registry, @@ -28,6 +29,22 @@ void CALLBACK on_device(GameInputCallbackToken, void*, IGameInputDevice* device, const GameInputDeviceInfo* i = device->GetDeviceInfo(); std::printf("\n%s %s (%04x:%04x) motors=0x%x\n", (current & GameInputDeviceConnected) ? "connected " : "disconnected", i->displayName ? i->displayName->data : "?", i->vendorId, i->productId, i->supportedRumbleMotors); + // Raw HID (RT-175): the report tables read from the pad's HID report descriptor, or why there are none. + if (current & GameInputDeviceConnected) { + if (!(current & GameInputDeviceRawIoEnabled)) { + std::printf("raw hid: no raw I/O (no HID device the backend could open, or no readable descriptor)\n"); + } else { + const auto list = [](const char* kind, uint32_t n, const void* p) { + const auto* r = static_cast(p); + std::printf("raw hid: %u %s report(s):", n, kind); + for (uint32_t k = 0; k < n; ++k) std::printf(" id %u = %u bytes;", r[k].id, r[k].size); + std::printf("\n"); + }; + list("input", i->inputReportCount, i->inputReportInfo); + list("output", i->outputReportCount, i->outputReportInfo); + list("feature", i->featureReportCount, i->featureReportInfo); + } + } if ((current & GameInputDeviceConnected) && !(previous & GameInputDeviceConnected)) { device->AddRef(); g_devices.push_back(device); @@ -96,6 +113,16 @@ int main(int argc, char** argv) { if (motion) // fractions of motionInfo's maxima: accel includes gravity, so a resting pad shows ~0.5 g std::printf("\n[a]=(%+.2f,%+.2f,%+.2f) [w]=(%+.2f,%+.2f,%+.2f) ", m.accelerationX, m.accelerationY, m.accelerationZ, m.angularVelocityX, m.angularVelocityY, m.angularVelocityZ); + void* raw = nullptr; + if (r->GetRawReport(&raw) && raw) { // the newest raw input report: id and its first 16 bytes + auto* rr = static_cast(raw); + unsigned char b[16] = {}; + const size_t n = rr->GetRawData(sizeof b, b); + std::printf("\nraw id %u (%zu bytes):", rr->GetReportInfo()->id, rr->GetRawDataSize()); + for (size_t k = 0; k < n; ++k) std::printf(" %02x", b[k]); + std::printf(" "); + rr->Release(); + } std::fflush(stdout); r->Release(); } diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index a65b444a1..47fd599c7 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -11,10 +11,12 @@ #include +#include #include #include #include #include +#include #include #include @@ -229,6 +231,221 @@ GameInputMotionState motion_state(IGameInput* input, IGameInputDevice* dev, bool return ms; } +// ---- raw HID (RT-175) ------------------------------------------------------------------------------------------- + +using rt::gameinput::RawReportSize; + +bool same_reports(const std::vector& got, std::initializer_list want) { + if (got.size() != want.size()) return false; + size_t i = 0; + for (const RawReportSize& w : want) { + if (got[i].kind != w.kind || got[i].id != w.id || got[i].bytes != w.bytes) return false; + ++i; + } + return true; +} + +// A game pad with numbered reports: input 1 (3 bytes), output 2 (2 bytes), feature 3 (4 bytes). +const uint8_t kRawPadDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, // usage page generic desktop, usage game pad, collection application + 0x85, 0x01, 0x75, 0x08, 0x95, 0x03, 0x81, 0x02, // report id 1, size 8, count 3, input + 0x85, 0x02, 0x95, 0x02, 0x91, 0x02, // report id 2, count 2, output + 0x85, 0x03, 0x95, 0x04, 0xB1, 0x02, // report id 3, count 4, feature + 0xC0, // end collection +}; + +void test_parse_report_descriptor() { + std::vector r; + check(rt::gameinput::parse_report_descriptor(kRawPadDescriptor, sizeof kRawPadDescriptor, &r) && + same_reports(r, {{0, 1, 3}, {1, 2, 2}, {2, 3, 4}}), + "raw hid: a descriptor with report ids gives input 1 (3), output 2 (2), feature 3 (4)"); + // No report id: one 16-bit input report under id 0, from two main items that add up (12 + 4 bits). + const uint8_t no_ids[] = {0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x75, 0x0C, 0x95, 0x01, 0x81, 0x02, + 0x75, 0x04, 0x81, 0x03, 0xC0}; + check(rt::gameinput::parse_report_descriptor(no_ids, sizeof no_ids, &r) && same_reports(r, {{0, 0, 2}}), + "raw hid: without report ids one input report of the summed bits (12 + 4 bits = 2 bytes)"); + // Push saves the globals (size 8, count 2) and Pop restores them after a 32-bit item; a long item is skipped. + const uint8_t push_pop[] = {0x75, 0x08, 0x95, 0x02, 0xA4, 0x75, 0x20, 0x95, 0x01, 0x81, 0x02, 0xB4, + 0xFE, 0x02, 0x10, 0xAA, 0xBB, 0x81, 0x02}; + check(rt::gameinput::parse_report_descriptor(push_pop, sizeof push_pop, &r) && same_reports(r, {{0, 0, 6}}), + "raw hid: Push/Pop restore Report Size and Count, a long item is skipped (4 + 2 bytes)"); + const uint8_t truncated[] = {0x75, 0x08, 0x96, 0x01}; // a two-byte Report Count cut after one byte + const uint8_t id_zero[] = {0x85, 0x00, 0x81, 0x02}; // Report ID 0 is reserved + const uint8_t pop_empty[] = {0xB4, 0x81, 0x02}; // Pop without Push + const uint8_t huge[] = {0x77, 0xFF, 0xFF, 0x00, 0x00, 0x97, 0xFF, 0xFF, 0x00, 0x00, 0x81, 0x02}; // > 64 KiB + check(!rt::gameinput::parse_report_descriptor(truncated, sizeof truncated, &r) && + !rt::gameinput::parse_report_descriptor(id_zero, sizeof id_zero, &r) && + !rt::gameinput::parse_report_descriptor(pop_empty, sizeof pop_empty, &r) && + !rt::gameinput::parse_report_descriptor(huge, sizeof huge, &r), + "raw hid: a truncated item, Report ID 0, Pop without Push and a report over 64 KiB are refused"); + check(rt::gameinput::parse_report_descriptor(nullptr, 0, &r) && r.empty(), "raw hid: an empty descriptor declares nothing"); +} + +// The fake HID device behind the raw pad: input reports to hand out, what the shim wrote, the feature reply. +struct FakeHid { + uint16_t vendor = 0x1209, product = 0x0001; // pid.codes test ids, not a real pad + int opens = 0, closes = 0; + std::deque> inputs; + std::vector> writes, features_sent; + std::vector feature_reply; + bool fail = false; +}; +FakeHid g_fake; +void* fake_open(const char*, uint16_t vendor, uint16_t product) { + if (vendor != g_fake.vendor || product != g_fake.product) return nullptr; + ++g_fake.opens; + return &g_fake; +} +void fake_close(void*) { ++g_fake.closes; } +int fake_descriptor(void*, uint8_t* buf, size_t size) { + if (size < sizeof kRawPadDescriptor) return -1; + std::memcpy(buf, kRawPadDescriptor, sizeof kRawPadDescriptor); + return static_cast(sizeof kRawPadDescriptor); +} +int fake_read(void*, uint8_t* buf, size_t size) { + if (g_fake.inputs.empty()) return 0; + const std::vector r = g_fake.inputs.front(); + g_fake.inputs.pop_front(); + const size_t n = std::min(size, r.size()); + std::memcpy(buf, r.data(), n); + return static_cast(n); +} +int fake_write(void*, const uint8_t* buf, size_t size) { + if (g_fake.fail) return -1; + g_fake.writes.emplace_back(buf, buf + size); + return static_cast(size); +} +int fake_get_feature(void*, uint8_t* buf, size_t size) { + if (g_fake.fail || g_fake.feature_reply.empty() || g_fake.feature_reply[0] != buf[0]) return -1; + const size_t n = std::min(size, g_fake.feature_reply.size()); + std::memcpy(buf, g_fake.feature_reply.data(), n); + return static_cast(n); +} +int fake_send_feature(void*, const uint8_t* buf, size_t size) { + if (g_fake.fail) return -1; + g_fake.features_sent.emplace_back(buf, buf + size); + return static_cast(size); +} +const rt::gameinput::HidBackend kFakeHid = {fake_open, fake_close, fake_descriptor, fake_read, + fake_write, fake_get_feature, fake_send_feature}; + +std::vector raw_bytes(IGameInputRawDeviceReport* r) { + std::vector v(r ? r->GetRawDataSize() : 0); + if (r) r->GetRawData(v.size(), v.data()); + return v; +} + +void test_raw_hid(IGameInput* input) { + test_parse_report_descriptor(); + rt::gameinput::set_hid_backend(&kFakeHid); + const size_t events_before = g_device_events.size(); + Pad raw_pad, plain; + attach(raw_pad, "Leonida virtual raw pad", g_fake.vendor, g_fake.product, false); + attach(plain, "Leonida virtual pad without HID", 0x045E, 0x02FF, false); + rt::gameinput::poll(); + std::vector found; // attach order: the raw pad first (see test_motion) + for (size_t i = events_before; i < g_device_events.size() && found.size() < 2; ++i) { + const DeviceEvent& e = g_device_events[i]; + if ((e.current & GameInputDeviceConnected) && std::find(found.begin(), found.end(), e.device) == found.end()) + found.push_back(e.device); + } + IGameInputDevice* rdev = found.size() > 0 ? found[0] : nullptr; + IGameInputDevice* pdev = found.size() > 1 ? found[1] : nullptr; + check(rdev && pdev && g_fake.opens == 1, "raw hid: both pads connected, the backend opened the raw pad only"); + if (!rdev || !pdev) return; + rdev->AddRef(); + pdev->AddRef(); + + const GameInputDeviceInfo* ri = rdev->GetDeviceInfo(); + check((ri->supportedInput & GameInputKindRawDeviceReport) && (rdev->GetDeviceStatus() & GameInputDeviceRawIoEnabled), + "raw hid: the raw pad reports GameInputKindRawDeviceReport and GameInputDeviceRawIoEnabled"); + const auto* in = static_cast(ri->inputReportInfo); + const auto* out = static_cast(ri->outputReportInfo); + const auto* feat = static_cast(ri->featureReportInfo); + check(ri->inputReportCount == 1 && in && in->kind == GameInputRawInputReport && in->id == 1 && in->size == 3 && + in->itemCount == 0 && ri->outputReportCount == 1 && out && out->id == 2 && out->size == 2 && + ri->featureReportCount == 1 && feat && feat->id == 3 && feat->size == 4, + "raw hid: the report tables follow the descriptor (input 1/3, output 2/2, feature 3/4, no items)"); + const GameInputDeviceInfo* pi = pdev->GetDeviceInfo(); + check(!(pi->supportedInput & GameInputKindRawDeviceReport) && pi->inputReportCount == 0 && + !(pdev->GetDeviceStatus() & GameInputDeviceRawIoEnabled), + "raw hid: a pad without a HID device has no raw reports"); + + IGameInputReading* reading = nullptr; + void* report = nullptr; + check(input->GetCurrentReading(GameInputKindGamepad, rdev, &reading) == S_OK && reading && + !(reading->GetInputKind() & GameInputKindRawDeviceReport) && !reading->GetRawReport(&report) && !report, + "raw hid: before the first input report a reading carries no raw report"); + if (reading) reading->Release(); + + g_fake.inputs.push_back({0x01, 0x11, 0x22, 0x33}); + g_fake.inputs.push_back({0x09, 0x99}); // an id the descriptor does not declare: ignored + rt::gameinput::poll(); + reading = nullptr; + check(input->GetCurrentReading(GameInputKindRawDeviceReport, rdev, &reading) == S_OK && reading && + (reading->GetInputKind() & GameInputKindRawDeviceReport), + "raw hid: an input report makes a reading of kind GameInputKindRawDeviceReport"); + IGameInputRawDeviceReport* rr = nullptr; + if (reading && reading->GetRawReport(&report)) rr = static_cast(report); + const GameInputRawDeviceReportInfo* rinfo = rr ? rr->GetReportInfo() : nullptr; + IGameInputDevice* owner = nullptr; + if (rr) rr->GetDevice(&owner); + check(rr && rinfo && rinfo->kind == GameInputRawInputReport && rinfo->id == 1 && + raw_bytes(rr) == std::vector({0x11, 0x22, 0x33}) && owner == rdev, + "raw hid: GetRawReport gives the newest declared input report, without its id byte, of this device"); + if (owner) owner->Release(); + int64_t item = 7; + check(rr && !rr->GetItemValue(0, &item) && item == 0 && !rr->SetItemValue(0, 1) && !rr->ResetAllItems(), + "raw hid: the item calls answer false (no item tables)"); + if (rr) rr->Release(); + if (reading) reading->Release(); + + void* created = nullptr; + check(rdev->CreateRawDeviceReport(2, GameInputRawOutputReport, &created) == S_OK && created, + "raw hid: CreateRawDeviceReport(2, output)"); + auto* outr = static_cast(created); + const uint8_t payload[] = {0xAA, 0xBB}; + check(outr && outr->GetRawDataSize() == 2 && raw_bytes(outr) == std::vector({0, 0}) && + !outr->SetRawData(1, payload) && outr->SetRawData(2, payload), + "raw hid: a new report is zeroed, and SetRawData takes exactly its size"); + check(rdev->SendRawDeviceOutput(outr) == S_OK && !g_fake.writes.empty() && + g_fake.writes.back() == std::vector({0x02, 0xAA, 0xBB}), + "raw hid: SendRawDeviceOutput writes the id byte then the payload"); + check(rdev->SetRawDeviceFeature(outr) == E_INVALIDARG && rdev->SendRawDeviceOutput(nullptr) == E_INVALIDARG, + "raw hid: an output report is not a feature report, and a null report is refused"); + g_fake.fail = true; + check(rdev->SendRawDeviceOutput(outr) == E_FAIL, "raw hid: a failed write is E_FAIL"); + g_fake.fail = false; + if (outr) outr->Release(); + + g_fake.feature_reply = {0x03, 0x01, 0x02, 0x03, 0x04}; + void* fr = nullptr; + check(rdev->GetRawDeviceFeature(3, &fr) == S_OK && fr && + raw_bytes(static_cast(fr)) == std::vector({1, 2, 3, 4}), + "raw hid: GetRawDeviceFeature(3) reads the feature report"); + check(fr && rdev->SetRawDeviceFeature(fr) == S_OK && !g_fake.features_sent.empty() && + g_fake.features_sent.back() == std::vector({0x03, 1, 2, 3, 4}), + "raw hid: SetRawDeviceFeature sends it back with its id byte"); + if (fr) static_cast(fr)->Release(); + void* none = reinterpret_cast(1); + check(rdev->CreateRawDeviceReport(9, GameInputRawOutputReport, &none) == E_INVALIDARG && !none && + rdev->CreateRawDeviceReport(1, 7, &none) == E_INVALIDARG && rdev->GetRawDeviceFeature(2, &none) == E_INVALIDARG, + "raw hid: an undeclared id or kind is E_INVALIDARG"); + check(pdev->CreateRawDeviceReport(1, GameInputRawInputReport, &none) == E_NOTIMPL && !none && + pdev->GetRawDeviceFeature(3, &none) == E_NOTIMPL, + "raw hid: a pad without raw I/O answers E_NOTIMPL, as before"); + + detach(raw_pad); + detach(plain); + rt::gameinput::poll(); + check(g_fake.closes == 1 && rt::gameinput::connected_count() == 0, "raw hid: unplugging closes the HID device"); + check(rdev->CreateRawDeviceReport(2, GameInputRawOutputReport, &none) == E_NOTIMPL, + "raw hid: no raw I/O once the pad is gone"); + rdev->Release(); + pdev->Release(); + rt::gameinput::set_hid_backend(nullptr); +} + void test_motion(IGameInput* input) { const size_t events_before = g_device_events.size(); // other tests' events are still queued in the vector Pad gyro_pad, plain; @@ -1226,6 +1443,7 @@ int main() { test_keyboard_pad(input); test_motion(input); test_aggregate_device(input); + test_raw_hid(input); input->Release(); std::printf("%d checks, %d failures\n", g_checks, g_failures); -- cgit v1.2.3