upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/gameinput.cpp
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 11:42:23 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 11:42:23 -0500
commitd159969a1b5e1018900bb40cf5e9f2a79fb2a7f7 (patch)
treeb341daf0274a883ba6cf4c2c52999a3107ea1373 /runtime/shims/gameinput.cpp
parentd8c5a10f3518a58d74ef199c4bbd655a7d64b549 (diff)
parent3ff74e8d58cb9420e4dae884378b98eb55ce62b2 (diff)
Merge pull request #2162 from Cozma
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp111
1 files changed, 107 insertions, 4 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index d9c62fec5..5a7981725 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -106,6 +106,8 @@ rt::gameinput::Config read_config() {
106 else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); 106 else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str());
107 if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty()) 107 if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty())
108 c.ds_trigger_gain = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.0f, 4.0f); 108 c.ds_trigger_gain = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.0f, 4.0f);
109 if (const std::string g = env("LEONIDA_MOUSE_SENSITIVITY"); !g.empty())
110 c.mouse_sensitivity = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.1f, 10.0f);
109 if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty()) 111 if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty())
110 c.ds_trigger_frequency = static_cast<uint8_t>(std::clamp(std::atoi(f.c_str()), 1, 255)); 112 c.ds_trigger_frequency = static_cast<uint8_t>(std::clamp(std::atoi(f.c_str()), 1, 255));
111 if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) { 113 if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) {
@@ -875,8 +877,76 @@ constexpr int kMouseDecayNum = 7, kMouseDecayDen = 8;
875 877
876bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; } 878bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; }
877 879
878// shortcut: plain cursor deltas stop at the screen edge; capture or recenter the cursor if that matters in game. 880// ---- raw mouse input (its own thread) ----
881//
882// The cursor stops at the edge of the screen, so cursor deltas stop too. Raw input reports what the mouse itself
883// moved, with no edge and no pointer acceleration. A message-only window (never shown) on its own thread receives
884// WM_INPUT and adds each movement to a running total; system_cursor_pos then returns that total as an edgeless
885// "cursor", and update_keyboard_pad takes the difference between polls exactly as it did with the real cursor.
886std::atomic<long long> g_raw_x{0}, g_raw_y{0}; // total raw movement since the thread started, mouse counts
887std::atomic<bool> g_raw_ready{false}; // registration worked; system_cursor_pos uses the totals
888std::atomic<bool> g_raw_started{false}; // the thread is started once per process
889
890LRESULT CALLBACK raw_mouse_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
891 if (msg == WM_INPUT) {
892 RAWINPUT raw{};
893 UINT size = sizeof(raw);
894 if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lp), RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER)) !=
895 static_cast<UINT>(-1) &&
896 raw.header.dwType == RIM_TYPEMOUSE && !(raw.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
897 // Relative movement only: absolute reports (remote desktop, some VMs, tablets) are positions, not
898 // movement, and would make the stick jump.
899 g_raw_x += raw.data.mouse.lLastX;
900 g_raw_y += raw.data.mouse.lLastY; // +Y is down, as for the cursor
901 }
902 }
903 return DefWindowProcW(hwnd, msg, wp, lp); // also for WM_INPUT, which lets Windows clean up the input
904}
905
906void raw_mouse_thread() {
907 const HINSTANCE inst = GetModuleHandleW(nullptr);
908 WNDCLASSEXW wc{};
909 wc.cbSize = sizeof(wc);
910 wc.lpfnWndProc = raw_mouse_proc;
911 wc.hInstance = inst;
912 wc.lpszClassName = L"LeonidaRawMouse";
913 RegisterClassExW(&wc);
914 // HWND_MESSAGE: a window that is never shown and only receives messages. It must be created on the thread that
915 // runs the message loop below, because a window's messages go to the thread that created it.
916 HWND hwnd = CreateWindowExW(0, L"LeonidaRawMouse", L"", 0, 0, 0, 0, 0,
917 HWND_MESSAGE, nullptr, inst, nullptr);
918 if (!hwnd) {
919 std::fprintf(stderr, "[rt] gameinput: no raw mouse input (window: error %lu); using the cursor position\n",
920 GetLastError());
921 return;
922 }
923 RAWINPUTDEVICE dev{};
924 dev.usUsagePage = 0x01; // HID generic desktop
925 dev.usUsage = 0x02; // mouse
926 dev.dwFlags = RIDEV_INPUTSINK; // also while this (invisible) window has no focus; focus is checked per poll
927 dev.hwndTarget = hwnd;
928 if (!RegisterRawInputDevices(&dev, 1, sizeof(dev))) {
929 std::fprintf(stderr, "[rt] gameinput: no raw mouse input (register: error %lu); using the cursor position\n",
930 GetLastError());
931 DestroyWindow(hwnd);
932 return;
933 }
934 g_raw_ready = true;
935 std::fprintf(stderr, "[rt] gameinput: raw mouse input on (the right stick does not stop at the screen edge)\n");
936 MSG m;
937 while (GetMessageW(&m, nullptr, 0, 0) > 0) DispatchMessageW(&m);
938}
939
940void start_raw_mouse() {
941 if (!g_raw_started.exchange(true)) std::thread(raw_mouse_thread).detach();
942}
943
879bool system_cursor_pos(int* x, int* y) { 944bool system_cursor_pos(int* x, int* y) {
945 if (g_raw_ready) { // the edgeless total; it wraps only after ±2^31 counts, and the poll uses differences
946 *x = static_cast<int>(g_raw_x.load());
947 *y = static_cast<int>(g_raw_y.load());
948 return true;
949 }
880 POINT p; 950 POINT p;
881 if (!GetCursorPos(&p)) return false; 951 if (!GetCursorPos(&p)) return false;
882 *x = p.x; 952 *x = p.x;
@@ -911,6 +981,33 @@ void detach_keyboard_pad() {
911 g_keyboard = {}; 981 g_keyboard = {};
912} 982}
913 983
984// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases
985// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for
986// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus.
987// Re-applied every 100 ms, because Windows drops the clip on some focus and resize changes.
988bool g_clipped = false;
989uint64_t g_clip_at = 0;
990
991void clip_cursor(bool want) {
992 if (!want) {
993 if (g_clipped) ClipCursor(nullptr);
994 g_clipped = false;
995 return;
996 }
997 const uint64_t now = now_us();
998 if (g_clipped && now - g_clip_at < 100'000) return;
999 const HWND w = GetForegroundWindow();
1000 RECT r;
1001 if (!w || !GetClientRect(w, &r)) return;
1002 POINT top_left{r.left, r.top}, bottom_right{r.right, r.bottom};
1003 if (!ClientToScreen(w, &top_left) || !ClientToScreen(w, &bottom_right)) return;
1004 const RECT screen{top_left.x, top_left.y, bottom_right.x, bottom_right.y};
1005 if (screen.right > screen.left && screen.bottom > screen.top && ClipCursor(&screen)) {
1006 g_clipped = true;
1007 g_clip_at = now;
1008 }
1009}
1010
914bool attach_keyboard_pad() { 1011bool attach_keyboard_pad() {
915 SDL_VirtualJoystickDesc d; 1012 SDL_VirtualJoystickDesc d;
916 SDL_INIT_INTERFACE(&d); 1013 SDL_INIT_INTERFACE(&d);
@@ -931,17 +1028,21 @@ bool attach_keyboard_pad() {
931 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " 1028 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, "
932 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " 1029 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left "
933 "button LT/RT)\n"); 1030 "button LT/RT)\n");
1031 start_raw_mouse();
934 return true; 1032 return true;
935} 1033}
936 1034
937// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. 1035// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading.
938void update_keyboard_pad() { 1036void update_keyboard_pad() {
1037 float sens;
939 rt::gameinput::KeyboardPadMode mode; 1038 rt::gameinput::KeyboardPadMode mode;
940 { 1039 {
941 std::lock_guard lock(g().mu); 1040 std::lock_guard lock(g().mu);
942 mode = g().config.keyboard_pad; 1041 mode = g().config.keyboard_pad;
1042 sens = g().config.mouse_sensitivity;
943 } 1043 }
944 if (mode == rt::gameinput::KeyboardPadMode::Off) { 1044 if (mode == rt::gameinput::KeyboardPadMode::Off) {
1045 clip_cursor(false);
945 if (g_keyboard.id) detach_keyboard_pad(); 1046 if (g_keyboard.id) detach_keyboard_pad();
946 g_keyboard.failed = false; 1047 g_keyboard.failed = false;
947 return; 1048 return;
@@ -953,7 +1054,8 @@ void update_keyboard_pad() {
953 bool aim = false, fire = false; 1054 bool aim = false, fire = false;
954 // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay 1055 // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay
955 // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick. 1056 // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick.
956 if (mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()()) { 1057 const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()();
1058 if (active) {
957 const rt::gameinput::KeyDownFn key_down = g_key_down.load(); 1059 const rt::gameinput::KeyDownFn key_down = g_key_down.load();
958 for (const auto& b : kKeyBindings) down[b.sdl_button] |= key_down(b.virtual_key); 1060 for (const auto& b : kKeyBindings) down[b.sdl_button] |= key_down(b.virtual_key);
959 lx = key_down('D') - key_down('A'); // opposite keys cancel 1061 lx = key_down('D') - key_down('A'); // opposite keys cancel
@@ -964,9 +1066,9 @@ void update_keyboard_pad() {
964 int x = 0, y = 0; 1066 int x = 0, y = 0;
965 const bool have = g_cursor_pos.load()(&x, &y); 1067 const bool have = g_cursor_pos.load()(&x, &y);
966 const bool moved = have && g_keyboard.have_cursor; 1068 const bool moved = have && g_keyboard.have_cursor;
967 auto step = [](int v, int pixels) { 1069 auto step = [sens](int v, int pixels) {
968 const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen + 1070 const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen +
969 static_cast<long long>(pixels) * kMouseAxisPerPixel; 1071 std::lround(static_cast<long long>(pixels) * kMouseAxisPerPixel * sens);
970 return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull)); 1072 return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull));
971 }; 1073 };
972 g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0); 1074 g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0);
@@ -977,6 +1079,7 @@ void update_keyboard_pad() {
977 g_keyboard.right_x = g_keyboard.right_y = 0; 1079 g_keyboard.right_x = g_keyboard.right_y = 0;
978 g_keyboard.have_cursor = false; 1080 g_keyboard.have_cursor = false;
979 } 1081 }
1082 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours());
980 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1083 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
981 const int reach = lx && ly ? kStickDiagonal : kStickFull; 1084 const int reach = lx && ly ? kStickDiagonal : kStickFull;
982 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach)); 1085 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach));