diff --git a/docs/gameinput.md b/docs/gameinput.md index 21421351e5..9acce54431 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -128,6 +128,35 @@ stick does not jump). `LEONIDA_KEYBOARD_PAD=always` reads them whatever has focu To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys. +## Keyboard and mouse devices + +For a title that reads the keyboard and mouse through GameInput itself (RT-159), `LEONIDA_KEYBOARD_MOUSE` connects +two more devices, `Keyboard (Leonida)` and `Mouse (Leonida)`, next to the pads. It is off by default; the keyboard pad +above is the route for a title that reads only gamepads, and the two can be on together. + +- Their readings carry `GameInputKindKeyboard` or `GameInputKindMouse` and nothing else: no gamepad, UI navigation or + controller state. A reading is added when the keys, buttons or position change. +- Keyboard: `GetKeyCount`/`GetKeyState` list the held keys in virtual-key order, at most 16 + (`maxSimultaneousKeys`). The side-neutral Shift, Ctrl and Alt and the mouse buttons are left out; the left and right + keys are listed themselves. `scanCode` is `MapVirtualKey`'s scan code (0xE0xx for extended keys), `codePoint` its + unshifted character (upper case for letters), `isDeadKey` its dead-key flag. +- Mouse: `GetMouseState` gives the left, right, middle and X1/X2 buttons, and `positionX`/`positionY` as the sum of the + cursor's movement between polls, as GameInput's relative positions are. There is no wheel (no window, so no wheel + messages); the mouse info says so (`hasWheelX`/`hasWheelY` false). +- Device info: the keyboard's `layout` is the active layout's identifier (`GetKeyboardLayoutNameW`, e.g. 0x0000040E), + read when the device is made; `keyCount` counts the reportable virtual keys that have a scan code; + `functionKeyCount` is `GetKeyboardType(2)` (12 if Windows doesn't say); `nativeLanguage` is an empty string. The + mouse's `sampleRate` is 500, one sample per 2 ms poll; `sensorDpi` is 0 (unknown from the cursor). A key's scan code + or character changing while it is held (a layout switch) is a new reading, like a key going down or up. +- Keys and buttons come from `GetAsyncKeyState` with the keyboard pad's focus rule: with `1` only while this + process's window has focus, with `always` whatever has focus. Out of focus nothing is held and cursor movement is + not counted. Cursor deltas stop at the screen edge, as the keyboard pad's do. +- They are not gamepads: `connected_count` does not count them, and a gamepad query never answers with their + readings. Enumeration, `GetCurrentReading`/`GetNextReading`/`GetPreviousReading`, aggregate devices, + `FindDeviceFromId` and reading callbacks registered for their kind cover them. +- **VERIFY:** the device family (`GameInputFamilyHid` here), keyboard kind and layout a console title expects, and + whether it reads `codePoint` (shifted or not). + ## Rumble and triggers `IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on @@ -252,6 +281,7 @@ sensors are enabled when the pad is opened, at SDL's requested rate, and every p | `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) | | `LEONIDA_KEYBOARD_PAD` | `off` | `1` adds the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus | | `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 | +| `LEONIDA_KEYBOARD_MOUSE` | `off` | `1` adds the [keyboard and mouse devices](#keyboard-and-mouse-devices), read while this process has focus; `always` whatever has focus | SDL's own hints (`SDL_JOYSTICK_*`, see SDL's `SDL_hints.h`) also apply, for example `SDL_JOYSTICK_HIDAPI_PS5=0` to leave a DualSense to the generic driver, or `SDL_GAMECONTROLLERCONFIG` to add a mapping for an unknown pad. @@ -272,7 +302,7 @@ 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) | +| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state, keys and mouse state (with `LEONIDA_KEYBOARD_MOUSE`) | raw report, touch, arcade/flight stick, racing wheel (all return nothing) | | `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState` | raw device I/O, power off, input synchronization (no-ops) | | `IGameInputDispatcher` | `Dispatch`, `OpenWaitHandle` | the quota (the queue is short) | | `IGameInputDevice` | device info, status, battery, `SetRumbleState` | force feedback and haptic motors (none reported), raw device I/O, power off, input synchronization (no-ops) | diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 89b66364d9..6c5789aebb 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -56,7 +56,9 @@ namespace { constexpr uint32_t kBaseKinds = GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; -constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion; // everything a reading may carry +constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion; // everything a pad reading may carry +// What a reading search may ask for: a pad's kinds, or the keyboard and mouse devices'. +constexpr uint32_t kReadableKinds = kSupportedKinds | GameInputKindKeyboard | GameInputKindMouse; 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; @@ -163,6 +165,12 @@ rt::gameinput::Config read_config() { } if (env("LEONIDA_RUMBLE") == "0") c.rumble = false; if (env("LEONIDA_GAMEINPUT_THREAD") == "0") c.background_thread = false; + const std::string km = env("LEONIDA_KEYBOARD_MOUSE"); + if (km == "1" || km == "on" || km == "focus") c.keyboard_mouse = rt::gameinput::KeyboardPadMode::Focused; + else if (km == "always") c.keyboard_mouse = rt::gameinput::KeyboardPadMode::Always; + else if (!km.empty() && km != "0" && km != "off") + std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_MOUSE=%s unknown (1, always or off), keyboard and mouse " + "devices off\n", km.c_str()); const std::string k = env("LEONIDA_KEYBOARD_PAD"); if (k == "1" || k == "on" || k == "focus") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Focused; else if (k == "always") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Always; @@ -177,7 +185,15 @@ rt::gameinput::Config read_config() { class Device; class ForceFeedbackEffect; +constexpr uint32_t kMaxKeys = 16; // keys one keyboard reading holds (GameInputKeyboardInfo::maxSimultaneousKeys) + struct Snapshot { + // Set on the keyboard and mouse devices' readings only (GameInputKindKeyboard or GameInputKindMouse): such a + // reading carries keys or mouse state and none of the pad parts below. + uint32_t kbm_kind = 0; + uint32_t key_count = 0; + GameInputKeyState keys[kMaxKeys]{}; + GameInputMouseState mouse{}; GameInputGamepadState gamepad{}; uint32_t ui = 0; float axes[kAxisCount] = {}; @@ -217,6 +233,7 @@ class Reading final : public IGameInputReading { } uint32_t STDMETHODCALLTYPE GetInputKind() override { + if (s_.kbm_kind) return s_.kbm_kind; // a keyboard or mouse reading return s_.has_motion ? kSupportedKinds : kBaseKinds; // a reading of a pad without sensors carries no motion } uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } @@ -226,23 +243,36 @@ class Reading final : public IGameInputReading { if (report) *report = nullptr; return false; } - uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; } + // A keyboard or mouse reading has no controller axes or buttons, no gamepad and no UI navigation state. + uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return s_.kbm_kind ? 0 : kAxisCount; } uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override { - const uint32_t n = out ? std::min(count, kAxisCount) : 0; - std::memcpy(out, s_.axes, n * sizeof(float)); + const uint32_t n = out && !s_.kbm_kind ? std::min(count, kAxisCount) : 0; + if (n) std::memcpy(out, s_.axes, n * sizeof(float)); return n; } - uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; } + uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return s_.kbm_kind ? 0 : kButtonCount; } uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t count, bool* out) override { - const uint32_t n = out ? std::min(count, kButtonCount) : 0; - std::memcpy(out, s_.buttons, n * sizeof(bool)); + const uint32_t n = out && !s_.kbm_kind ? std::min(count, kButtonCount) : 0; + if (n) std::memcpy(out, s_.buttons, n * sizeof(bool)); return n; } uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; } - uint32_t STDMETHODCALLTYPE GetKeyCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t, void*) override { return 0; } - bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } + // The pressed keys, in virtual-key order. Copies at most `count` and returns how many it copied. + uint32_t STDMETHODCALLTYPE GetKeyCount() override { + return (s_.kbm_kind & GameInputKindKeyboard) ? s_.key_count : 0; + } + uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t count, void* out) override { + if (!out || !(s_.kbm_kind & GameInputKindKeyboard)) return 0; + const uint32_t n = std::min(count, s_.key_count); + std::memcpy(out, s_.keys, n * sizeof(GameInputKeyState)); + return n; + } + bool STDMETHODCALLTYPE GetMouseState(void* out) override { + if (!out || !(s_.kbm_kind & GameInputKindMouse)) return false; + *static_cast(out) = s_.mouse; + return true; + } uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } bool STDMETHODCALLTYPE GetMotionState(void* state) override { @@ -253,19 +283,20 @@ class Reading final : public IGameInputReading { bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { - if (!state) return false; + if (!state || s_.kbm_kind) return false; *state = s_.gamepad; return true; } bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override { - if (!state) return false; + if (!state || s_.kbm_kind) return false; state->buttons = s_.ui; return true; } Device* device() const { return device_; } uint64_t order() const { return order_; } + uint32_t kbm_kind() const { return s_.kbm_kind; } private: std::atomic refs_{1}; @@ -483,6 +514,9 @@ class Device final : public IGameInputDevice { GameInputForceFeedbackMotorInfo ff_motor_info{}; // filled when SDL opened the pad as a haptic device GameInputHapticFeedbackMotorInfo haptic_motor_info[kHapticMotors]{}; // the trigger motors, when the pad has them GameInputHapticWaveformInfo haptic_waveform_info[kHapticMotors]{}; // one waveform each, an intensity + GameInputKeyboardInfo keyboard_info{}; // the keyboard device's; info.keyboardInfo points at it + GameInputMouseInfo mouse_info{}; // the mouse device's; info.mouseInfo points at it + GameInputString native_language{0, 0, ""}; // keyboard_info.nativeLanguage points at it: unknown, never null std::atomic status{GameInputDeviceNoStatus}; std::deque history; // one reference each, oldest first; the newest is the current reading uint64_t evicted_order = 0; // order of the newest reading dropped from history @@ -605,6 +639,11 @@ struct State { std::recursive_mutex deliver_mu; // held while callbacks run; UnregisterCallback waits on it std::vector devices; // every device seen, for the process lifetime std::vector connected; // open now, in connection order + // The keyboard and mouse devices (LEONIDA_KEYBOARD_MOUSE), kept apart from the pads: nothing that drives a pad + // (SDL, rumble, battery, player slots) applies to them. kbm_devices lives for the process, kbm is the connected + // ones. Every reading search and enumeration covers both lists (readable()). + Device* kbm_devices[2] = {nullptr, nullptr}; // keyboard, mouse + std::vector kbm; std::vector callbacks; std::vector queue; GameInputCallbackToken next_token = 1; @@ -624,6 +663,13 @@ State& g() { return *s; } +// The connected devices a reading search or an enumeration covers: the pads, then the keyboard and mouse. Under mu. +std::vector readable() { + std::vector all = g().connected; + all.insert(all.end(), g().kbm.begin(), g().kbm.end()); + return all; +} + void queue_event(const Event& e) { if (e.device) e.device->AddRef(); if (e.reading) e.reading->AddRef(); @@ -639,6 +685,9 @@ bool matches(const Callback& c, const Event& e) { if (!(c.kind & e.device->info.supportedInput) && c.kind != GameInputKindUnknown) return false; return e.only || ((e.current ^ e.previous) & c.status_filter); case CbType::Reading: + // A keyboard or mouse reading goes to callbacks for its own kind (or any); pad readings as before. + if (e.reading && e.reading->kbm_kind()) + return c.kind == GameInputKindUnknown || (c.kind & e.reading->kbm_kind()); return (c.kind & kSupportedKinds) || c.kind == GameInputKindUnknown; default: return true; @@ -1479,6 +1528,192 @@ void update_keyboard_pad() { SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, fire ? 32767 : -32768); } +// ---- keyboard and mouse devices (poll thread only) -------------------------------------------------------------- +// +// RT-159. With LEONIDA_KEYBOARD_MOUSE the shim connects one keyboard device and one mouse device, for a title that +// reads keys and the mouse through GameInput itself (the keyboard pad above is for a title that reads only pads). +// Their readings carry GameInputKindKeyboard or GameInputKindMouse and nothing else. Keys and mouse buttons come from +// the same source as the keyboard pad (GetAsyncKeyState, or the test's set_keyboard_source) under the same focus +// rule; mouse motion is the cursor's movement between polls (set_cursor_source in tests), summed into GameInput's +// relative positionX/Y. There is no wheel: without a window there are no wheel messages, and the mouse info says +// so (hasWheelX/Y false). A reading is pushed when the state changes. +// +// VERIFY: the device family, keyboard kind and layout a console title expects, and whether it reads codePoint; +// codePoint is MapVirtualKey's unshifted character (upper case for letters), not ToUnicode's shifted one. +struct KbmPoll { + int cursor_x = 0, cursor_y = 0; + bool have_cursor = false; // false after focus loss, so the first poll after it moves nothing + int64_t position_x = 0, position_y = 0; + Snapshot keyboard{}, mouse{}; + bool keyboard_read = false, mouse_read = false; // a reading exists for this connection +}; +KbmPoll g_kbm; + +constexpr const char* kKbmNames[2] = {"Keyboard (Leonida)", "Mouse (Leonida)"}; + +// The mouse buttons GetAsyncKeyState reports as virtual keys: they are the mouse's, not the keyboard's. +bool is_mouse_key(int vk) { + return vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON || vk == VK_XBUTTON1 || vk == VK_XBUTTON2; +} + +// A virtual key the keyboard reading lists: not a mouse button, and not the side-neutral Shift/Ctrl/Alt (their left +// and right keys are reported themselves). +bool reportable_key(int vk) { + return !is_mouse_key(vk) && vk != VK_SHIFT && vk != VK_CONTROL && vk != VK_MENU; +} + +Device* kbm_device(int which) { + State& s = g(); + if (s.kbm_devices[which]) return s.kbm_devices[which]; + Device* d = new Device; + GameInputDeviceInfo& i = d->info; + i.infoSize = sizeof(GameInputDeviceInfo); + AppLocalDeviceId id{}; + id_bytes(which == 0 ? "leonida-keyboard" : "leonida-mouse", SDL_GUID{}, &id); + i.deviceId = id; + i.deviceRootId = id; + i.deviceFamily = GameInputFamilyHid; // VERIFY + if (which == 0) { + i.usage = {0x01, 0x06}; // HID generic desktop / keyboard + i.supportedInput = GameInputKindKeyboard; + // The active layout's identifier (KLID, e.g. 0x0000040E), the keys the reading can report, and the function + // keys Windows counts for this keyboard. Layout id and key count after @justr4mzi's #2426. VERIFY what the + // console reports for a USB keyboard. + uint32_t layout = 0; + wchar_t klid[KL_NAMELENGTH] = {}; + if (GetKeyboardLayoutNameW(klid)) layout = static_cast(std::wcstoul(klid, nullptr, 16)); + uint32_t keys = 0; + for (int vk = 1; vk < 255; ++vk) keys += reportable_key(vk) && MapVirtualKeyW(vk, MAPVK_VK_TO_VSC_EX) != 0; + const int function_keys = GetKeyboardType(2); + d->keyboard_info = {GameInputUnknownKeyboard, layout, keys, function_keys > 0 ? uint32_t(function_keys) : 12u, + kMaxKeys, 0, 0, &d->native_language}; + d->keyboard_info.platformType = static_cast(std::max(0, GetKeyboardType(0))); + d->keyboard_info.platformSubtype = static_cast(std::max(0, GetKeyboardType(1))); + i.keyboardInfo = &d->keyboard_info; + } else { + i.usage = {0x01, 0x02}; // HID generic desktop / mouse + i.supportedInput = GameInputKindMouse; + d->mouse_info = {GameInputMouseLeftButton | GameInputMouseRightButton | GameInputMouseMiddleButton | + GameInputMouseButton4 | GameInputMouseButton5, + 500, 0, false, false}; // one sample per 2 ms poll_thread() pass; DPI unknown from the cursor + i.mouseInfo = &d->mouse_info; + } + d->name = kKbmNames[which]; + d->display_name = {static_cast(d->name.size()), static_cast(d->name.size()), d->name.c_str()}; + i.displayName = &d->display_name; + s.kbm_devices[which] = d; + return d; +} + +// Under g().mu. +void kbm_connect(Device* d, uint64_t ts) { + State& s = g(); + if (d->status != GameInputDeviceNoStatus) return; + d->status = GameInputDeviceConnected | GameInputDeviceInputEnabled; + s.kbm.push_back(d); + queue_event({CbType::Device, d, nullptr, ts, d->status, GameInputDeviceNoStatus, false, 0}); + std::fprintf(stderr, "[rt] gameinput: connected %s\n", d->name.c_str()); +} + +// Under g().mu. +void kbm_disconnect(Device* d, uint64_t ts) { + State& s = g(); + const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); + if (old == GameInputDeviceNoStatus) return; + if (!d->history.empty()) d->evicted_order = d->history.back()->order(); + for (Reading* r : d->history) r->Release(); + d->history.clear(); + s.kbm.erase(std::remove(s.kbm.begin(), s.kbm.end(), d), s.kbm.end()); + queue_event({CbType::Device, d, nullptr, ts, GameInputDeviceNoStatus, old, false, 0}); + std::fprintf(stderr, "[rt] gameinput: disconnected %s\n", d->name.c_str()); +} + +// Every field: a layout switch while a key is held changes its scan code or character, and is a new reading. +bool same_keys(const Snapshot& a, const Snapshot& b) { + if (a.key_count != b.key_count) return false; + for (uint32_t k = 0; k < a.key_count; ++k) { + const GameInputKeyState &x = a.keys[k], &y = b.keys[k]; + if (x.virtualKey != y.virtualKey || x.scanCode != y.scanCode || x.codePoint != y.codePoint || + x.isDeadKey != y.isDeadKey) + return false; + } + return true; +} + +bool same_mouse(const Snapshot& a, const Snapshot& b) { + return a.mouse.buttons == b.mouse.buttons && a.mouse.positionX == b.mouse.positionX && + a.mouse.positionY == b.mouse.positionY; +} + +void update_keyboard_mouse(uint64_t now) { + State& s = g(); + rt::gameinput::KeyboardPadMode mode; + { + std::lock_guard lock(s.mu); + mode = s.config.keyboard_mouse; + if (mode == rt::gameinput::KeyboardPadMode::Off) { + for (Device* d : s.kbm_devices) + if (d) kbm_disconnect(d, now); + g_kbm = {}; + return; + } + for (int which = 0; which < 2; ++which) kbm_connect(kbm_device(which), now); + } + const bool focus = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()(); + const rt::gameinput::KeyDownFn key_down = g_key_down.load(); + + Snapshot keys{}; + keys.kbm_kind = GameInputKindKeyboard; + Snapshot mouse{}; + mouse.kbm_kind = GameInputKindMouse; + if (focus) { + // The reportable keys that are down, in virtual-key order, up to kMaxKeys. + for (int vk = 1; vk < 255 && keys.key_count < kMaxKeys; ++vk) { + if (!reportable_key(vk) || !key_down(vk)) continue; + GameInputKeyState& k = keys.keys[keys.key_count++]; + k.virtualKey = static_cast(vk); + k.scanCode = MapVirtualKeyW(static_cast(vk), MAPVK_VK_TO_VSC_EX); + const UINT ch = MapVirtualKeyW(static_cast(vk), MAPVK_VK_TO_CHAR); + k.isDeadKey = (ch & 0x80000000u) != 0; + k.codePoint = ch & 0xFFFFu; + } + uint32_t buttons = GameInputMouseNone; + if (key_down(VK_LBUTTON)) buttons |= GameInputMouseLeftButton; + if (key_down(VK_RBUTTON)) buttons |= GameInputMouseRightButton; + if (key_down(VK_MBUTTON)) buttons |= GameInputMouseMiddleButton; + if (key_down(VK_XBUTTON1)) buttons |= GameInputMouseButton4; + if (key_down(VK_XBUTTON2)) buttons |= GameInputMouseButton5; + mouse.mouse.buttons = buttons; + int x = 0, y = 0; + const bool have = g_cursor_pos.load()(&x, &y); + if (have && g_kbm.have_cursor) { + g_kbm.position_x += x - g_kbm.cursor_x; + g_kbm.position_y += y - g_kbm.cursor_y; + } + g_kbm.have_cursor = have; + g_kbm.cursor_x = x; + g_kbm.cursor_y = y; + } else { + g_kbm.have_cursor = false; // out of focus nothing is held, and the cursor is read afresh on return + } + mouse.mouse.positionX = g_kbm.position_x; + mouse.mouse.positionY = g_kbm.position_y; + + std::lock_guard lock(s.mu); + Device* kd = s.kbm_devices[0]; + Device* md = s.kbm_devices[1]; + if (!g_kbm.keyboard_read || !same_keys(g_kbm.keyboard, keys)) { + g_kbm.keyboard = keys; + g_kbm.keyboard_read = true; + queue_event({CbType::Reading, kd, push_reading(kd, keys, now), now, 0, 0, false, 0}); + } + if (!g_kbm.mouse_read || !same_mouse(g_kbm.mouse, mouse)) { + g_kbm.mouse = mouse; + g_kbm.mouse_read = true; + queue_event({CbType::Reading, md, push_reading(md, mouse, now), now, 0, 0, false, 0}); + } +} + bool init_sdl() { State& s = g(); if (s.sdl_ready) return true; @@ -1558,6 +1793,7 @@ void poll_once() { refresh_battery(d, now); apply_output(d, now); } + update_keyboard_mouse(now); } void poll_and_deliver() { @@ -1863,11 +2099,13 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* de if (!out) return E_POINTER; *out = nullptr; if (!ref) return E_INVALIDARG; - if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; + if (kind != GameInputKindUnknown && !(kind & kReadableKinds)) return GAMEINPUT_E_READING_NOT_FOUND; const Reading* r = static_cast(ref); State& s = g(); std::lock_guard lock(s.mu); - std::vector scope = s.connected; + std::vector scope; + for (Device* d : readable()) // without a device, the devices that do this kind + if (kind == GameInputKindUnknown || (kind & d->info.supportedInput)) scope.push_back(d); uint64_t horizon = 0; if (device) { Device* dev = as_device(device); @@ -1876,7 +2114,7 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* de return GAMEINPUT_E_READING_NOT_FOUND; const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & dev->info.supportedInput) : dev->info.supportedInput; scope.clear(); - for (Device* cd : s.connected) { + for (Device* cd : readable()) { if (effective_kind & cd->info.supportedInput) { scope.push_back(cd); } @@ -1924,7 +2162,7 @@ class GameInput final : public IGameInput { HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { if (!out) return E_POINTER; *out = nullptr; - if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; + if (kind != GameInputKindUnknown && !(kind & kReadableKinds)) return GAMEINPUT_E_READING_NOT_FOUND; std::lock_guard lock(g().mu); Reading* best = nullptr; if (device) { @@ -1933,7 +2171,7 @@ class GameInput final : public IGameInput { if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) return GAMEINPUT_E_READING_NOT_FOUND; const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & d->info.supportedInput) : d->info.supportedInput; - for (Device* cd : g().connected) { + for (Device* cd : readable()) { if (!(effective_kind & cd->info.supportedInput)) continue; if (Reading* r = cd->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r; } @@ -1944,8 +2182,12 @@ class GameInput final : public IGameInput { best = d->latest(); } } else { - for (Device* d : g().connected) // the most recent reading from any gamepad + // The most recent reading from any device that does this kind: a gamepad query never answers with a + // keyboard reading. + for (Device* d : readable()) { + if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) continue; if (Reading* r = d->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r; + } } if (!best) return GAMEINPUT_E_READING_NOT_FOUND; best->AddRef(); @@ -1993,7 +2235,7 @@ class GameInput final : public IGameInput { reinterpret_cast(fn), true}); if (enumeration != GameInputNoEnumeration) { const uint64_t ts = now_us(); - for (Device* d : s.connected) { + for (Device* d : readable()) { if (device && as_device(device) != d) continue; if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) continue; const uint32_t st = d->status; @@ -2100,7 +2342,10 @@ class GameInput final : public IGameInput { *out = nullptr; if (!id) return E_INVALIDARG; std::lock_guard lock(g().mu); - for (Device* d : g().devices) + std::vector known = g().devices; + for (Device* d : g().kbm_devices) + if (d) known.push_back(d); + for (Device* d : known) if (std::memcmp(&d->info.deviceId, id, sizeof *id) == 0) { d->AddRef(); *out = d; diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h index b3197f58e7..d96e0d779a 100644 --- a/runtime/shims/gameinput.h +++ b/runtime/shims/gameinput.h @@ -22,6 +22,9 @@ struct Config { bool rumble = true; // LEONIDA_RUMBLE=0 turns all rumble off bool background_thread = true; // LEONIDA_GAMEINPUT_THREAD=0: poll only from poll() KeyboardPadMode keyboard_pad = KeyboardPadMode::Off; // LEONIDA_KEYBOARD_PAD=1|focus|always|off + // A keyboard device and a mouse device whose readings carry keys and mouse state (RT-159), for a title that + // reads them through GameInput. Same focus modes as the keyboard pad. LEONIDA_KEYBOARD_MOUSE=1|focus|always|off + KeyboardPadMode keyboard_mouse = KeyboardPadMode::Off; }; // The configuration in use. Read from the environment on the first GameInputCreate. diff --git a/runtime/shims/gameinput_abi.h b/runtime/shims/gameinput_abi.h index c5c0cd3215..559fbc258b 100644 --- a/runtime/shims/gameinput_abi.h +++ b/runtime/shims/gameinput_abi.h @@ -655,6 +655,69 @@ struct IGameInputDispatcher : IUnknown { virtual HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* waitHandle) = 0; }; +// Keyboard and mouse (RT-159). Layouts checked against the v0 header of Microsoft.GameInput 0.2303.22621.3038; the +// asserts below pin them. +enum GameInputKeyboardKind : int32_t { + GameInputUnknownKeyboard = -1, + GameInputAnsiKeyboard = 0, + GameInputIsoKeyboard = 1, + GameInputKsKeyboard = 2, + GameInputAbntKeyboard = 3, + GameInputJisKeyboard = 4, +}; + +enum GameInputMouseButtons : uint32_t { + GameInputMouseNone = 0x00, + GameInputMouseLeftButton = 0x01, + GameInputMouseRightButton = 0x02, + GameInputMouseMiddleButton = 0x04, + GameInputMouseButton4 = 0x08, + GameInputMouseButton5 = 0x10, + GameInputMouseWheelTiltLeft = 0x20, + GameInputMouseWheelTiltRight = 0x40, +}; + +// One pressed key of a keyboard reading. +struct GameInputKeyState { + uint32_t scanCode; // set-1 scan code, 0xE0xx for extended keys + uint32_t codePoint; // the character the key gives under the current layout, 0 when it gives none + uint8_t virtualKey; + bool isDeadKey; +}; + +// Positions and wheels are running sums of relative motion since the device appeared, not screen coordinates. +struct GameInputMouseState { + uint32_t buttons; // GameInputMouseButtons + int64_t positionX; + int64_t positionY; + int64_t wheelX; + int64_t wheelY; +}; + +struct GameInputKeyboardInfo { + GameInputKeyboardKind kind; + uint32_t layout; + uint32_t keyCount; + uint32_t functionKeyCount; + uint32_t maxSimultaneousKeys; + uint32_t platformType; + uint32_t platformSubtype; + const GameInputString* nativeLanguage; +}; + +struct GameInputMouseInfo { + uint32_t supportedButtons; // GameInputMouseButtons + uint32_t sampleRate; + uint32_t sensorDpi; + bool hasWheelX; + bool hasWheelY; +}; + +static_assert(sizeof(GameInputKeyState) == 12 && offsetof(GameInputKeyState, virtualKey) == 8); +static_assert(sizeof(GameInputMouseState) == 40 && offsetof(GameInputMouseState, positionX) == 8); +static_assert(sizeof(GameInputKeyboardInfo) == 40 && offsetof(GameInputKeyboardInfo, nativeLanguage) == 32); +static_assert(sizeof(GameInputMouseInfo) == 16 && offsetof(GameInputMouseInfo, hasWheelX) == 12); + using GameInputCreateFn = HRESULT(WINAPI*)(IGameInput** gameInput); } // namespace gi diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index 99e74a0820..8520743d8f 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -1086,6 +1087,151 @@ void test_haptic_motors(IGameInput* input) { } // namespace +// The keyboard and mouse devices (LEONIDA_KEYBOARD_MOUSE, RT-159), driven by the same fake keys, focus and cursor as +// the keyboard pad. No pad is connected while this runs. +void test_keyboard_mouse(IGameInput* input) { + rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); + rt::gameinput::set_cursor_source(fake_cursor); + for (bool& k : g_keys) k = false; + g_focus = true; + g_cursor_x = 100; + g_cursor_y = 100; + + set_env("LEONIDA_KEYBOARD_MOUSE", nullptr); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + IGameInputReading* r = nullptr; + check(input->GetCurrentReading(GameInputKindKeyboard, nullptr, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r, + "keyboard/mouse: off by default, no keyboard reading"); + + set_env("LEONIDA_KEYBOARD_MOUSE", "1"); + rt::gameinput::reload_config(); + check(rt::gameinput::config().keyboard_mouse == rt::gameinput::KeyboardPadMode::Focused, + "keyboard/mouse: LEONIDA_KEYBOARD_MOUSE=1 is the focused mode"); + rt::gameinput::poll(); + check(rt::gameinput::connected_count() == 0, "keyboard/mouse: not counted as gamepads"); + + IGameInputDevice* kbd = nullptr; + IGameInputDevice* mse = nullptr; + if (input->GetCurrentReading(GameInputKindKeyboard, nullptr, &r) == S_OK && r) { + r->GetDevice(&kbd); + r->Release(); + } + if (input->GetCurrentReading(GameInputKindMouse, nullptr, &r) == S_OK && r) { + r->GetDevice(&mse); + r->Release(); + } + check(kbd && mse && kbd != mse, "keyboard/mouse: a keyboard device and a mouse device, each with a reading"); + if (!kbd || !mse) return; + const GameInputDeviceInfo* ki = kbd->GetDeviceInfo(); + const GameInputDeviceInfo* mi = mse->GetDeviceInfo(); + check(ki->supportedInput == GameInputKindKeyboard && ki->keyboardInfo && !ki->gamepadInfo && + static_cast(ki->keyboardInfo)->maxSimultaneousKeys == 16, + "keyboard/mouse: keyboard info (16 keys at once, no gamepad info)"); + if (const auto* kinfo = static_cast(ki->keyboardInfo)) { + wchar_t klid[KL_NAMELENGTH] = {}; + const uint32_t layout = GetKeyboardLayoutNameW(klid) ? uint32_t(std::wcstoul(klid, nullptr, 16)) : 0; + check(kinfo->layout == layout && layout != 0, "keyboard/mouse: layout is the active KLID"); + const int function_keys = GetKeyboardType(2); + check(kinfo->keyCount > 0 && kinfo->keyCount < 255 && + kinfo->functionKeyCount == (function_keys > 0 ? uint32_t(function_keys) : 12u), + "keyboard/mouse: key count, and the function keys Windows counts"); + check(kinfo->nativeLanguage && kinfo->nativeLanguage->data && kinfo->nativeLanguage->sizeInBytes == 0, + "keyboard/mouse: nativeLanguage is an empty string, not null"); + } + check(mi->mouseInfo && static_cast(mi->mouseInfo)->sampleRate == 500, + "keyboard/mouse: mouse sample rate is the 2 ms poll"); + check(mi->supportedInput == GameInputKindMouse && mi->mouseInfo && + !static_cast(mi->mouseInfo)->hasWheelY, + "keyboard/mouse: mouse info (no wheel)"); + check(ki->displayName && std::strcmp(ki->displayName->data, "Keyboard (Leonida)") == 0, + "keyboard/mouse: keyboard display name"); + IGameInputDevice* found = nullptr; + check(input->FindDeviceFromId(&ki->deviceId, &found) == S_OK && found == kbd, + "keyboard/mouse: FindDeviceFromId finds the keyboard"); + if (found) found->Release(); + + // Two keys, plus the side-neutral Shift (left out: LShift itself is reported) and a mouse button (the mouse's). + g_keys['W'] = g_keys[VK_LSHIFT] = g_keys[VK_SHIFT] = g_keys[VK_LBUTTON] = true; + rt::gameinput::poll(); + if (input->GetCurrentReading(GameInputKindKeyboard, kbd, &r) == S_OK && r) { + GameInputKeyState keys[4]{}; + const uint32_t n = r->GetKeyState(4, keys); + check(r->GetInputKind() == GameInputKindKeyboard && r->GetKeyCount() == 2 && n == 2, + "keyboard/mouse: two keys held"); + check(keys[0].virtualKey == 'W' && keys[1].virtualKey == VK_LSHIFT, + "keyboard/mouse: keys in virtual-key order"); + check(keys[0].scanCode == MapVirtualKeyW('W', MAPVK_VK_TO_VSC_EX) && keys[0].scanCode != 0 && + keys[0].codePoint == 'W' && !keys[0].isDeadKey, + "keyboard/mouse: W's scan code and character"); + GameInputGamepadState pad{}; + GameInputMouseState none{}; + check(!r->GetGamepadState(&pad) && !r->GetMouseState(&none) && r->GetControllerButtonCount() == 0, + "keyboard/mouse: a keyboard reading has no pad or mouse state"); + check(r->GetKeyState(1, keys) == 1, "keyboard/mouse: GetKeyState copies at most the count asked for"); + r->Release(); + } else { + check(false, "keyboard/mouse: a keyboard reading after keys are pressed"); + } + + // The mouse: buttons, and motion summed from the cursor's movement. + g_cursor_x = 105; + g_cursor_y = 97; + rt::gameinput::poll(); + g_cursor_x = 108; + rt::gameinput::poll(); + if (input->GetCurrentReading(GameInputKindMouse, mse, &r) == S_OK && r) { + GameInputMouseState m{}; + check(r->GetMouseState(&m) && r->GetKeyCount() == 0, "keyboard/mouse: a mouse reading has mouse state"); + check(m.buttons == GameInputMouseLeftButton, "keyboard/mouse: the left button"); + check(m.positionX == 8 && m.positionY == -3 && m.wheelY == 0, + "keyboard/mouse: positions sum the cursor's movement (+5 then +3, -3)"); + r->Release(); + } else { + check(false, "keyboard/mouse: a mouse reading after the cursor moves"); + } + + // A gamepad query, with no pad connected, never answers with a keyboard or mouse reading. + check(input->GetCurrentReading(GameInputKindGamepad, nullptr, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r, + "keyboard/mouse: no gamepad reading from them"); + + // Out of focus nothing is held and moving the cursor does not count. + g_focus = false; + g_cursor_x = 300; + rt::gameinput::poll(); + g_focus = true; + rt::gameinput::poll(); // the first poll back in focus takes the cursor as it is + if (input->GetCurrentReading(GameInputKindMouse, mse, &r) == S_OK && r) { + GameInputMouseState m{}; + r->GetMouseState(&m); + check(m.positionX == 8, "keyboard/mouse: cursor movement out of focus is not counted"); + r->Release(); + } + g_focus = false; + rt::gameinput::poll(); + if (input->GetCurrentReading(GameInputKindKeyboard, kbd, &r) == S_OK && r) { + check(r->GetKeyCount() == 0, "keyboard/mouse: no keys while another window has focus"); + r->Release(); + } + + set_env("LEONIDA_KEYBOARD_MOUSE", "off"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(kbd->GetDeviceStatus() == GameInputDeviceNoStatus && mse->GetDeviceStatus() == GameInputDeviceNoStatus, + "keyboard/mouse: off again disconnects both"); + check(input->GetCurrentReading(GameInputKindKeyboard, nullptr, &r) == GAMEINPUT_E_READING_NOT_FOUND && !r, + "keyboard/mouse: no keyboard reading once off"); + kbd->Release(); + mse->Release(); + + for (bool& k : g_keys) k = false; + g_focus = false; + set_env("LEONIDA_KEYBOARD_MOUSE", nullptr); + rt::gameinput::reload_config(); + rt::gameinput::set_keyboard_source(nullptr, nullptr); + rt::gameinput::set_cursor_source(nullptr); +} + int main() { // Only virtual pads: no real controller on the test machine may show up. for (const char* hint : {SDL_HINT_JOYSTICK_HIDAPI, SDL_HINT_JOYSTICK_RAWINPUT, SDL_HINT_JOYSTICK_WGI, @@ -1571,6 +1717,7 @@ int main() { test_twins(input); test_keyboard_pad(input); + test_keyboard_mouse(input); test_motion(input); test_aggregate_device(input); test_force_feedback(input);