diff options
| author | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-11-28 21:25:16 +0100 |
|---|---|---|
| committer | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-11-28 21:25:16 +0100 |
| commit | 2f99fd2caed4524217306d19c40801e7c9dafedc (patch) | |
| tree | e8284cbe62e68a459a795e29fb40b311808eb58d /runtime/shims/gameinput.cpp | |
| parent | 9a96b8ba6aaf2fc8ed3f3ad5177d0e3f420dc62c (diff) | |
| parent | 30fc2d68cc509ae9eeb2e39a900dbe1a98b2e745 (diff) | |
Merge main into carry/old-9966 (resolve conflict in runtime/test/gameinput_test.cpp)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/gameinput.cpp')
| -rw-r--r-- | runtime/shims/gameinput.cpp | 349 |
1 files changed, 289 insertions, 60 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index d9cef893c..15f243654 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp | |||
| @@ -45,14 +45,17 @@ | |||
| 45 | #include <cstring> | 45 | #include <cstring> |
| 46 | #include <deque> | 46 | #include <deque> |
| 47 | #include <mutex> | 47 | #include <mutex> |
| 48 | #include <map> | ||
| 48 | #include <string> | 49 | #include <string> |
| 49 | #include <thread> | 50 | #include <thread> |
| 50 | #include <utility> | 51 | #include <utility> |
| 51 | #include <vector> | 52 | #include <vector> |
| 52 | 53 | ||
| 53 | #include "gameinput.h" | 54 | #include "gameinput.h" |
| 55 | #include "gameinput_clip.h" | ||
| 54 | #include "gameinput_abi.h" | 56 | #include "gameinput_abi.h" |
| 55 | #include "gameinput_script.h" | 57 | #include "gameinput_script.h" |
| 58 | #include "keyboard_pad_connection.h" | ||
| 56 | #include "shims.h" | 59 | #include "shims.h" |
| 57 | 60 | ||
| 58 | using namespace gi; | 61 | using namespace gi; |
| @@ -862,10 +865,19 @@ State& g() { | |||
| 862 | return *s; | 865 | return *s; |
| 863 | } | 866 | } |
| 864 | 867 | ||
| 868 | bool matches(const Callback& c, const Event& e); | ||
| 869 | |||
| 870 | // Under g().mu. Queues an event only when a registered callback wants it: GameInput dispatches callbacks, and with | ||
| 871 | // none listening there is no work. Otherwise every reading (a pad's moving stick, a sensor pad's 125 Hz stream) would | ||
| 872 | // queue an item nobody hears, and a title holding a dispatcher that runs one item a frame (Dispatch(0)) would fall | ||
| 873 | // further behind every frame: a pad plugged in after start would have its connect event stuck behind that backlog and | ||
| 874 | // never reach the title (RT-GAMEINPUT-LATE-PAD). | ||
| 865 | void queue_event(const Event& e) { | 875 | void queue_event(const Event& e) { |
| 876 | State& s = g(); | ||
| 877 | if (std::none_of(s.callbacks.begin(), s.callbacks.end(), [&e](const Callback& c) { return matches(c, e); })) return; | ||
| 866 | if (e.device) e.device->AddRef(); | 878 | if (e.device) e.device->AddRef(); |
| 867 | if (e.reading) e.reading->AddRef(); | 879 | if (e.reading) e.reading->AddRef(); |
| 868 | g().queue.push_back(e); | 880 | s.queue.push_back(e); |
| 869 | } | 881 | } |
| 870 | 882 | ||
| 871 | bool matches(const Callback& c, const Event& e) { | 883 | bool matches(const Callback& c, const Event& e) { |
| @@ -883,7 +895,19 @@ bool matches(const Callback& c, const Event& e) { | |||
| 883 | } | 895 | } |
| 884 | } | 896 | } |
| 885 | 897 | ||
| 898 | // The token of the callback running on this thread, for kCurrentCallbackToken; 0 outside a callback. | ||
| 899 | thread_local GameInputCallbackToken t_running_token = kInvalidCallbackToken; | ||
| 900 | |||
| 901 | GameInputCallbackToken resolve_token(GameInputCallbackToken token) { | ||
| 902 | return token == kCurrentCallbackToken ? t_running_token : token; | ||
| 903 | } | ||
| 904 | |||
| 886 | void call(const Callback& c, const Event& e) { | 905 | void call(const Callback& c, const Event& e) { |
| 906 | struct Running { // restored on return, so a callback that drives another delivery keeps its own token | ||
| 907 | GameInputCallbackToken saved = t_running_token; | ||
| 908 | explicit Running(GameInputCallbackToken t) { t_running_token = t; } | ||
| 909 | ~Running() { t_running_token = saved; } | ||
| 910 | } running(c.token); | ||
| 887 | switch (c.type) { | 911 | switch (c.type) { |
| 888 | case CbType::Device: | 912 | case CbType::Device: |
| 889 | reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, e.device, e.timestamp, e.current, e.previous); | 913 | reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, e.device, e.timestamp, e.current, e.previous); |
| @@ -1002,6 +1026,9 @@ leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) { | |||
| 1002 | // in bits 0-7, forced in bit 8, the generation from bit 16. | 1026 | // in bits 0-7, forced in bit 8, the generation from bit 16. |
| 1003 | leonida::ActiveInputTracker g_tracker; | 1027 | leonida::ActiveInputTracker g_tracker; |
| 1004 | std::atomic<uint64_t> g_active{0}; | 1028 | std::atomic<uint64_t> g_active{0}; |
| 1029 | // GetCurrentReading calls so far, any device: a scripted press is held until the title has read the pads a few | ||
| 1030 | // times since it began (update_keyboard_pad). | ||
| 1031 | std::atomic<uint64_t> g_reading_calls{0}; | ||
| 1005 | 1032 | ||
| 1006 | void publish_active() { | 1033 | void publish_active() { |
| 1007 | g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | | 1034 | g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | |
| @@ -1686,10 +1713,10 @@ bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; } | |||
| 1686 | // | 1713 | // |
| 1687 | // The cursor stops at the edge of the screen, so cursor deltas stop too. Raw input reports what the mouse itself | 1714 | // The cursor stops at the edge of the screen, so cursor deltas stop too. Raw input reports what the mouse itself |
| 1688 | // moved, with no edge and no pointer acceleration. A message-only window (never shown) on its own thread receives | 1715 | // moved, with no edge and no pointer acceleration. A message-only window (never shown) on its own thread receives |
| 1689 | // WM_INPUT and adds each movement to a running total; system_cursor_pos then returns that total as an edgeless | 1716 | // WM_INPUT and adds each movement to a running total; raw_cursor_pos then returns that total as an edgeless |
| 1690 | // "cursor", and update_keyboard_pad takes the difference between polls exactly as it did with the real cursor. | 1717 | // "cursor", and update_keyboard_pad takes the difference between polls exactly as it did with the real cursor. |
| 1691 | std::atomic<long long> g_raw_x{0}, g_raw_y{0}; // total raw movement since the thread started, mouse counts | 1718 | std::atomic<long long> g_raw_x{0}, g_raw_y{0}; // total raw movement since the thread started, mouse counts |
| 1692 | std::atomic<bool> g_raw_ready{false}; // registration worked; system_cursor_pos uses the totals | 1719 | std::atomic<bool> g_raw_ready{false}; // registration worked; the pad can use the totals |
| 1693 | std::atomic<bool> g_raw_started{false}; // the thread is started once per process | 1720 | std::atomic<bool> g_raw_started{false}; // the thread is started once per process |
| 1694 | 1721 | ||
| 1695 | LRESULT CALLBACK raw_mouse_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { | 1722 | LRESULT CALLBACK raw_mouse_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { |
| @@ -1746,12 +1773,13 @@ void start_raw_mouse() { | |||
| 1746 | if (!g_raw_started.exchange(true)) std::thread(raw_mouse_thread).detach(); | 1773 | if (!g_raw_started.exchange(true)) std::thread(raw_mouse_thread).detach(); |
| 1747 | } | 1774 | } |
| 1748 | 1775 | ||
| 1776 | bool raw_cursor_pos(int* x, int* y) { | ||
| 1777 | *x = static_cast<int>(g_raw_x.load()); | ||
| 1778 | *y = static_cast<int>(g_raw_y.load()); | ||
| 1779 | return true; | ||
| 1780 | } | ||
| 1781 | |||
| 1749 | bool system_cursor_pos(int* x, int* y) { | 1782 | bool system_cursor_pos(int* x, int* y) { |
| 1750 | if (g_raw_ready) { // the edgeless total; it wraps only after ±2^31 counts, and the poll uses differences | ||
| 1751 | *x = static_cast<int>(g_raw_x.load()); | ||
| 1752 | *y = static_cast<int>(g_raw_y.load()); | ||
| 1753 | return true; | ||
| 1754 | } | ||
| 1755 | POINT p; | 1783 | POINT p; |
| 1756 | if (!GetCursorPos(&p)) return false; | 1784 | if (!GetCursorPos(&p)) return false; |
| 1757 | *x = p.x; | 1785 | *x = p.x; |
| @@ -1769,33 +1797,42 @@ std::atomic<rt::gameinput::KeyDownFn> g_key_down{async_key_down}; | |||
| 1769 | std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours}; | 1797 | std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours}; |
| 1770 | std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos}; | 1798 | std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos}; |
| 1771 | 1799 | ||
| 1772 | struct KeyboardPad { | 1800 | struct KeyboardPad : rt::gameinput::detail::KeyboardPadConnection<SDL_JoystickID, SDL_Joystick*> { |
| 1773 | SDL_JoystickID id = 0; | ||
| 1774 | SDL_Joystick* js = nullptr; | ||
| 1775 | bool failed = false; // attaching failed once; not retried every 2 ms | ||
| 1776 | int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) | 1801 | int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) |
| 1777 | int cursor_x = 0, cursor_y = 0; // the cursor at the last poll | 1802 | int cursor_x = 0, cursor_y = 0; // the cursor at the last poll |
| 1803 | rt::gameinput::CursorPosFn cursor_source = nullptr; | ||
| 1778 | bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing | 1804 | bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing |
| 1779 | }; | 1805 | }; |
| 1780 | KeyboardPad g_keyboard; | 1806 | KeyboardPad g_keyboard; |
| 1781 | 1807 | ||
| 1782 | bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } | 1808 | bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } |
| 1783 | 1809 | ||
| 1784 | void detach_keyboard_pad() { | ||
| 1785 | if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); | ||
| 1786 | if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); | ||
| 1787 | if (g_keyboard.id) std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); | ||
| 1788 | g_keyboard = {}; | ||
| 1789 | } | ||
| 1790 | |||
| 1791 | // Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases | 1810 | // Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases |
| 1792 | // it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for | 1811 | // it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for |
| 1793 | // a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. | 1812 | // a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. |
| 1794 | // Re-applied every 100 ms, because Windows drops the clip on some focus and resize changes. | 1813 | // Re-applied every 100 ms, because Windows drops the clip on some focus and resize changes. Never while the window is |
| 1814 | // dragged or sized, or a press that began on its title bar or border is held (gameinput_clip.h has why). | ||
| 1795 | bool g_clipped = false; | 1815 | bool g_clipped = false; |
| 1796 | uint64_t g_clip_at = 0; | 1816 | uint64_t g_clip_at = 0; |
| 1817 | rt::gameinput::detail::CursorClipGate g_clip_gate; | ||
| 1797 | 1818 | ||
| 1798 | void clip_cursor(bool want) { | 1819 | void clip_cursor(bool want) { |
| 1820 | const HWND w = want ? GetForegroundWindow() : nullptr; | ||
| 1821 | if (w) { | ||
| 1822 | GUITHREADINFO gui{}; | ||
| 1823 | gui.cbSize = sizeof(gui); | ||
| 1824 | const bool modal_loop = GetGUIThreadInfo(GetWindowThreadProcessId(w, nullptr), &gui) && | ||
| 1825 | (gui.flags & (GUI_INMOVESIZE | GUI_INMENUMODE | GUI_SYSTEMMENUMODE)); | ||
| 1826 | const bool button_down = ((GetAsyncKeyState(VK_LBUTTON) | GetAsyncKeyState(VK_RBUTTON) | | ||
| 1827 | GetAsyncKeyState(VK_MBUTTON)) & 0x8000) != 0; | ||
| 1828 | POINT cursor; | ||
| 1829 | RECT client; | ||
| 1830 | const bool in_client = GetCursorPos(&cursor) && ScreenToClient(w, &cursor) && GetClientRect(w, &client) && | ||
| 1831 | PtInRect(&client, cursor); | ||
| 1832 | want = g_clip_gate.update(true, modal_loop, button_down, in_client); | ||
| 1833 | } else { | ||
| 1834 | want = g_clip_gate.update(false, false, false, false); | ||
| 1835 | } | ||
| 1799 | if (!want) { | 1836 | if (!want) { |
| 1800 | if (g_clipped) ClipCursor(nullptr); | 1837 | if (g_clipped) ClipCursor(nullptr); |
| 1801 | g_clipped = false; | 1838 | g_clipped = false; |
| @@ -1803,9 +1840,8 @@ void clip_cursor(bool want) { | |||
| 1803 | } | 1840 | } |
| 1804 | const uint64_t now = now_us(); | 1841 | const uint64_t now = now_us(); |
| 1805 | if (g_clipped && now - g_clip_at < 100'000) return; | 1842 | if (g_clipped && now - g_clip_at < 100'000) return; |
| 1806 | const HWND w = GetForegroundWindow(); | ||
| 1807 | RECT r; | 1843 | RECT r; |
| 1808 | if (!w || !GetClientRect(w, &r)) return; | 1844 | if (!GetClientRect(w, &r)) return; |
| 1809 | POINT top_left{r.left, r.top}, bottom_right{r.right, r.bottom}; | 1845 | POINT top_left{r.left, r.top}, bottom_right{r.right, r.bottom}; |
| 1810 | if (!ClientToScreen(w, &top_left) || !ClientToScreen(w, &bottom_right)) return; | 1846 | if (!ClientToScreen(w, &top_left) || !ClientToScreen(w, &bottom_right)) return; |
| 1811 | const RECT screen{top_left.x, top_left.y, bottom_right.x, bottom_right.y}; | 1847 | const RECT screen{top_left.x, top_left.y, bottom_right.x, bottom_right.y}; |
| @@ -1815,29 +1851,34 @@ void clip_cursor(bool want) { | |||
| 1815 | } | 1851 | } |
| 1816 | } | 1852 | } |
| 1817 | 1853 | ||
| 1818 | bool attach_keyboard_pad() { | 1854 | struct KeyboardPadBackend { |
| 1819 | SDL_VirtualJoystickDesc d; | 1855 | static uint64_t now() { return now_us(); } |
| 1820 | SDL_INIT_INTERFACE(&d); | 1856 | static SDL_JoystickID attach() { |
| 1821 | d.type = SDL_JOYSTICK_TYPE_GAMEPAD; | 1857 | SDL_VirtualJoystickDesc d; |
| 1822 | d.naxes = SDL_GAMEPAD_AXIS_COUNT; | 1858 | SDL_INIT_INTERFACE(&d); |
| 1823 | d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; | 1859 | d.type = SDL_JOYSTICK_TYPE_GAMEPAD; |
| 1824 | d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; | 1860 | d.naxes = SDL_GAMEPAD_AXIS_COUNT; |
| 1825 | d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; | 1861 | d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; |
| 1826 | d.name = "Keyboard pad (Leonida)"; | 1862 | d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; |
| 1827 | g_keyboard.id = SDL_AttachVirtualJoystick(&d); | 1863 | d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; |
| 1828 | g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; | 1864 | d.name = "Keyboard pad (Leonida)"; |
| 1829 | if (!g_keyboard.js) { | 1865 | return SDL_AttachVirtualJoystick(&d); |
| 1866 | } | ||
| 1867 | static SDL_Joystick* open(SDL_JoystickID id) { return SDL_OpenJoystick(id); } | ||
| 1868 | static void close(SDL_Joystick* js) { SDL_CloseJoystick(js); } | ||
| 1869 | static bool detach(SDL_JoystickID id) { return SDL_DetachVirtualJoystick(id); } | ||
| 1870 | static bool is_virtual(SDL_JoystickID id) { return SDL_IsJoystickVirtual(id); } | ||
| 1871 | static void removed() { std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); } | ||
| 1872 | static void failed() { | ||
| 1830 | std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); | 1873 | std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); |
| 1831 | detach_keyboard_pad(); | ||
| 1832 | g_keyboard.failed = true; | ||
| 1833 | return false; | ||
| 1834 | } | 1874 | } |
| 1835 | std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " | 1875 | static void attached() { |
| 1836 | "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " | 1876 | std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " |
| 1837 | "button LT/RT)\n"); | 1877 | "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " |
| 1838 | start_raw_mouse(); | 1878 | "button LT/RT)\n"); |
| 1839 | return true; | 1879 | start_raw_mouse(); |
| 1840 | } | 1880 | } |
| 1881 | }; | ||
| 1841 | 1882 | ||
| 1842 | // Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. | 1883 | // Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. |
| 1843 | void update_keyboard_pad() { | 1884 | void update_keyboard_pad() { |
| @@ -1848,17 +1889,19 @@ void update_keyboard_pad() { | |||
| 1848 | mode = g().config.keyboard_pad; | 1889 | mode = g().config.keyboard_pad; |
| 1849 | sens = g().config.mouse_sensitivity; | 1890 | sens = g().config.mouse_sensitivity; |
| 1850 | } | 1891 | } |
| 1851 | if (mode == rt::gameinput::KeyboardPadMode::Off) { | 1892 | KeyboardPadBackend backend; |
| 1893 | const bool enabled = mode != rt::gameinput::KeyboardPadMode::Off; | ||
| 1894 | if (!enabled) { | ||
| 1852 | clip_cursor(false); | 1895 | clip_cursor(false); |
| 1853 | if (g_keyboard.id) detach_keyboard_pad(); | 1896 | g_keyboard.right_x = g_keyboard.right_y = 0; |
| 1854 | g_keyboard.failed = false; | 1897 | g_keyboard.have_cursor = false; |
| 1855 | return; | ||
| 1856 | } | 1898 | } |
| 1857 | if (!g_keyboard.js && (g_keyboard.failed || !attach_keyboard_pad())) return; | 1899 | if (!g_keyboard.update(enabled, backend)) return; |
| 1858 | 1900 | ||
| 1859 | bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; | 1901 | bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; |
| 1860 | int lx = 0, ly = 0; | 1902 | int lx = 0, ly = 0; |
| 1861 | bool aim = false, fire = false; | 1903 | bool aim = false, fire = false; |
| 1904 | bool raw_mouse = false; | ||
| 1862 | // Focus gates physical keyboard and mouse input. Read the cursor afresh on return to avoid a jump. | 1905 | // Focus gates physical keyboard and mouse input. Read the cursor afresh on return to avoid a jump. |
| 1863 | // Scripted presses still run while the window is unfocused. | 1906 | // Scripted presses still run while the window is unfocused. |
| 1864 | const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()(); | 1907 | const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()(); |
| @@ -1871,25 +1914,39 @@ void update_keyboard_pad() { | |||
| 1871 | fire = key_down(VK_LBUTTON); | 1914 | fire = key_down(VK_LBUTTON); |
| 1872 | 1915 | ||
| 1873 | int x = 0, y = 0; | 1916 | int x = 0, y = 0; |
| 1874 | const bool have = g_cursor_pos.load()(&x, &y); | 1917 | auto cursor_source = g_cursor_pos.load(); |
| 1918 | raw_mouse = cursor_source == system_cursor_pos && g_raw_ready; | ||
| 1919 | if (raw_mouse) cursor_source = raw_cursor_pos; | ||
| 1920 | // The first sample from a new coordinate source establishes its baseline. | ||
| 1921 | if (cursor_source != g_keyboard.cursor_source) { | ||
| 1922 | g_keyboard.cursor_source = cursor_source; | ||
| 1923 | g_keyboard.have_cursor = false; | ||
| 1924 | } | ||
| 1925 | const bool have = cursor_source(&x, &y); | ||
| 1875 | const bool moved = have && g_keyboard.have_cursor; | 1926 | const bool moved = have && g_keyboard.have_cursor; |
| 1927 | // Raw input exposes the low bits of a running total. Keep subtraction modular across a wrap. | ||
| 1928 | auto delta = [](int current, int previous) { | ||
| 1929 | return static_cast<int>(static_cast<unsigned>(current) - static_cast<unsigned>(previous)); | ||
| 1930 | }; | ||
| 1876 | auto step = [sens](int v, int pixels) { | 1931 | auto step = [sens](int v, int pixels) { |
| 1877 | const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen + | 1932 | const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen + |
| 1878 | std::lround(static_cast<long long>(pixels) * kMouseAxisPerPixel * sens); | 1933 | std::llround(static_cast<long long>(pixels) * kMouseAxisPerPixel * sens); |
| 1879 | return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull)); | 1934 | return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull)); |
| 1880 | }; | 1935 | }; |
| 1881 | g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0); | 1936 | g_keyboard.right_x = step(g_keyboard.right_x, moved ? delta(x, g_keyboard.cursor_x) : 0); |
| 1882 | g_keyboard.right_y = step(g_keyboard.right_y, moved ? y - g_keyboard.cursor_y : 0); | 1937 | g_keyboard.right_y = step(g_keyboard.right_y, moved ? delta(y, g_keyboard.cursor_y) : 0); |
| 1883 | if (have) g_keyboard.cursor_x = x, g_keyboard.cursor_y = y; | 1938 | if (have) g_keyboard.cursor_x = x, g_keyboard.cursor_y = y; |
| 1884 | g_keyboard.have_cursor = have; | 1939 | g_keyboard.have_cursor = have; |
| 1885 | } else { | 1940 | } else { |
| 1886 | g_keyboard.right_x = g_keyboard.right_y = 0; | 1941 | g_keyboard.right_x = g_keyboard.right_y = 0; |
| 1887 | g_keyboard.have_cursor = false; | 1942 | g_keyboard.have_cursor = false; |
| 1888 | } | 1943 | } |
| 1889 | clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); | 1944 | clip_cursor(raw_mouse && foreground_is_ours()); |
| 1890 | for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); | 1945 | for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); |
| 1891 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard | 1946 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard |
| 1892 | // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt | 1947 | // pad, in seconds since the pad's first update, each held 300 ms or its own button@seconds:hold, and then until the |
| 1948 | // title has read the pads kReads times since it began (never past kMaxHold seconds, or the hold if it is longer, so | ||
| 1949 | // a title that stops reading does not keep the button). For unattended boots: the title's first prompt | ||
| 1893 | // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the | 1950 | // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the |
| 1894 | // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. | 1951 | // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. |
| 1895 | namespace script = rt::gameinput::script; | 1952 | namespace script = rt::gameinput::script; |
| @@ -1901,13 +1958,82 @@ void update_keyboard_pad() { | |||
| 1901 | s.presses.size(), s.rejected); | 1958 | s.presses.size(), s.rejected); |
| 1902 | return s; | 1959 | return s; |
| 1903 | }(); | 1960 | }(); |
| 1904 | if (!scripted.empty()) { | 1961 | // LEONIDA_INPUT_FILE=<path> (local, for headless runs whose display takes no keyboard input): every line appended |
| 1962 | // to the file names one button of gameinput_script.h's table ("a", "down", ...) and becomes a press at once, held | ||
| 1963 | // like a scripted one (300 ms and six readings, at most 5 s). The file is read again at most every 250 ms. | ||
| 1964 | struct FilePress { | ||
| 1965 | uint32_t bit; | ||
| 1966 | double at; | ||
| 1967 | uint64_t began; | ||
| 1968 | bool started; | ||
| 1969 | }; | ||
| 1970 | static std::vector<FilePress> file_presses; | ||
| 1971 | static const std::string input_file = [] { | ||
| 1972 | const char* v = std::getenv("LEONIDA_INPUT_FILE"); | ||
| 1973 | return std::string(v ? v : ""); | ||
| 1974 | }(); | ||
| 1975 | if (!scripted.empty() || !input_file.empty()) { | ||
| 1905 | static const ULONGLONG origin = GetTickCount64(); | 1976 | static const ULONGLONG origin = GetTickCount64(); |
| 1906 | const double now = (GetTickCount64() - origin) / 1000.0; | 1977 | const double now = (GetTickCount64() - origin) / 1000.0; |
| 1907 | const script::Held held = script::held_at(scripted, now); | 1978 | script::Held held{}; |
| 1979 | static constexpr uint64_t kReads = 6; | ||
| 1980 | static constexpr double kMaxHold = 5.0; | ||
| 1981 | static std::vector<uint64_t> began(scripted.presses.size(), 0); | ||
| 1982 | static std::vector<char> started(scripted.presses.size(), 0); | ||
| 1983 | const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); | ||
| 1984 | if (!input_file.empty()) { | ||
| 1985 | static ULONGLONG last_read = 0; | ||
| 1986 | static std::size_t lines_done = 0; | ||
| 1987 | const ULONGLONG tick = GetTickCount64(); | ||
| 1988 | if (tick - last_read >= 250) { | ||
| 1989 | last_read = tick; | ||
| 1990 | if (FILE* f = std::fopen(input_file.c_str(), "r")) { | ||
| 1991 | char line[64]; | ||
| 1992 | std::size_t n = 0; | ||
| 1993 | while (std::fgets(line, sizeof(line), f)) { | ||
| 1994 | if (++n <= lines_done) continue; | ||
| 1995 | lines_done = n; | ||
| 1996 | std::string name(line); | ||
| 1997 | while (!name.empty() && (name.back() == '\n' || name.back() == '\r' || name.back() == ' ')) | ||
| 1998 | name.pop_back(); | ||
| 1999 | bool known = false; | ||
| 2000 | for (const script::Button& b : script::kButtons) | ||
| 2001 | if (name == b.name) { | ||
| 2002 | file_presses.push_back({b.bit, now, 0, false}); | ||
| 2003 | known = true; | ||
| 2004 | } | ||
| 2005 | std::fprintf(stderr, "[rt] gameinput: input file line %zu \"%s\" at %.1f s%s\n", n, | ||
| 2006 | name.c_str(), now, known ? "" : " (unknown button, ignored)"); | ||
| 2007 | } | ||
| 2008 | std::fclose(f); | ||
| 2009 | } | ||
| 2010 | } | ||
| 2011 | for (auto& p : file_presses) { | ||
| 2012 | if (now < p.at || now >= p.at + kMaxHold) continue; | ||
| 2013 | if (!p.started) { | ||
| 2014 | p.started = true; | ||
| 2015 | p.began = calls; | ||
| 2016 | } | ||
| 2017 | if (now < p.at + 0.3 || calls - p.began < kReads) held.buttons |= p.bit; | ||
| 2018 | } | ||
| 2019 | } | ||
| 2020 | for (std::size_t i = 0; i < scripted.presses.size(); ++i) { | ||
| 2021 | const auto& press = scripted.presses[i]; | ||
| 2022 | bool active = false; | ||
| 2023 | if (now >= press.at && now < press.at + std::max(press.hold, kMaxHold)) { | ||
| 2024 | if (!started[i]) { | ||
| 2025 | started[i] = 1; | ||
| 2026 | began[i] = calls; | ||
| 2027 | } | ||
| 2028 | active = now < press.at + press.hold || calls - began[i] < kReads; | ||
| 2029 | } | ||
| 2030 | if (!active) continue; | ||
| 2031 | if (press.stick) held.stick = press.stick; | ||
| 2032 | else held.buttons |= press.button; | ||
| 2033 | } | ||
| 1908 | if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down | 2034 | if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down |
| 1909 | for (const script::Button& b : script::kButtons) { | 2035 | for (const script::Button& b : script::kButtons) { |
| 1910 | if (!(scripted.named & b.bit)) continue; | 2036 | if (!(scripted.named & b.bit) && input_file.empty()) continue; |
| 1911 | const auto button = static_cast<SDL_GamepadButton>(b.sdl); | 2037 | const auto button = static_cast<SDL_GamepadButton>(b.sdl); |
| 1912 | SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); | 2038 | SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); |
| 1913 | } | 2039 | } |
| @@ -2031,6 +2157,10 @@ void poll_once() { | |||
| 2031 | SDL_JoystickID* ids = SDL_GetGamepads(&count); | 2157 | SDL_JoystickID* ids = SDL_GetGamepads(&count); |
| 2032 | std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0)); | 2158 | std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0)); |
| 2033 | SDL_free(ids); | 2159 | SDL_free(ids); |
| 2160 | // An unopened virtual device may still be waiting for SDL to finish detaching it. | ||
| 2161 | // Do not advertise it to the title until it has a working keyboard handle. | ||
| 2162 | if (g_keyboard.id && !g_keyboard.js) | ||
| 2163 | present.erase(std::remove(present.begin(), present.end(), g_keyboard.id), present.end()); | ||
| 2034 | 2164 | ||
| 2035 | std::vector<Device*> connected; | 2165 | std::vector<Device*> connected; |
| 2036 | { | 2166 | { |
| @@ -2374,7 +2504,13 @@ public: | |||
| 2374 | return r; | 2504 | return r; |
| 2375 | } | 2505 | } |
| 2376 | // Runs the queued callbacks on the caller's thread within the quota (see deliver_within). | 2506 | // Runs the queued callbacks on the caller's thread within the quota (see deliver_within). |
| 2377 | bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { return deliver_within(quotaInMicroseconds); } | 2507 | bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { |
| 2508 | static std::atomic<bool> s_logged{false}; | ||
| 2509 | if (!s_logged.exchange(true)) | ||
| 2510 | std::fprintf(stderr, "[rt] gameinput: Dispatch first call (quota %llu us)\n", | ||
| 2511 | static_cast<unsigned long long>(quotaInMicroseconds)); | ||
| 2512 | return deliver_within(quotaInMicroseconds); | ||
| 2513 | } | ||
| 2378 | HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { | 2514 | HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { |
| 2379 | if (!handle) return E_POINTER; | 2515 | if (!handle) return E_POINTER; |
| 2380 | *handle = nullptr; | 2516 | *handle = nullptr; |
| @@ -2459,7 +2595,80 @@ public: | |||
| 2459 | 2595 | ||
| 2460 | uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } | 2596 | uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } |
| 2461 | 2597 | ||
| 2598 | // LEONIDA_INPUT_STATS=1 (diagnostic): every 10 s, how the title asked for readings (by method and device | ||
| 2599 | // argument) and what it got (by the reading's device, and whether a gamepad button was down in it). | ||
| 2600 | static void note_reading(int method, IGameInputDevice* asked, HRESULT hr, IGameInputReading* got) { | ||
| 2601 | static const bool on = env("LEONIDA_INPUT_STATS") == "1"; | ||
| 2602 | if (!on) return; | ||
| 2603 | struct Stats { | ||
| 2604 | std::mutex mu; | ||
| 2605 | uint64_t calls[3][3] = {}; // method x (null, aggregate, a device) | ||
| 2606 | uint64_t found[3] = {}, pressed[3] = {}, a_pressed[3] = {}; | ||
| 2607 | std::map<std::string, std::pair<uint64_t, uint64_t>> by_device; // name -> (readings, with buttons) | ||
| 2608 | uint64_t since = 0; | ||
| 2609 | }; | ||
| 2610 | static Stats st; | ||
| 2611 | std::string name; | ||
| 2612 | bool buttons = false, a_button = false; | ||
| 2613 | if (SUCCEEDED(hr) && got) { | ||
| 2614 | IGameInputDevice* d = nullptr; | ||
| 2615 | got->GetDevice(&d); | ||
| 2616 | if (d) { | ||
| 2617 | name = as_device(d)->name; | ||
| 2618 | d->Release(); | ||
| 2619 | } | ||
| 2620 | GameInputGamepadState g{}; | ||
| 2621 | if (got->GetGamepadState(&g)) { | ||
| 2622 | buttons = g.buttons != 0; | ||
| 2623 | a_button = (g.buttons & GameInputGamepadA) != 0; | ||
| 2624 | } | ||
| 2625 | } | ||
| 2626 | const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2; | ||
| 2627 | std::lock_guard lock(st.mu); | ||
| 2628 | ++st.calls[method][arg]; | ||
| 2629 | if (SUCCEEDED(hr) && got) { | ||
| 2630 | ++st.found[method]; | ||
| 2631 | st.pressed[method] += buttons; | ||
| 2632 | st.a_pressed[method] += a_button; | ||
| 2633 | auto& e = st.by_device[name]; | ||
| 2634 | ++e.first; | ||
| 2635 | e.second += buttons; | ||
| 2636 | } | ||
| 2637 | const uint64_t now = now_us(); | ||
| 2638 | if (!st.since) st.since = now; | ||
| 2639 | if (now - st.since < 10'000'000) return; | ||
| 2640 | static const char* methods[] = {"GetCurrentReading", "GetNextReading", "GetPreviousReading"}; | ||
| 2641 | std::string line; | ||
| 2642 | for (int m = 0; m < 3; ++m) { | ||
| 2643 | char t[200]; | ||
| 2644 | std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu A %llu;", methods[m], | ||
| 2645 | (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1], | ||
| 2646 | (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m], | ||
| 2647 | (unsigned long long)st.pressed[m], (unsigned long long)st.a_pressed[m]); | ||
| 2648 | line += t; | ||
| 2649 | } | ||
| 2650 | for (const auto& [n, c] : st.by_device) { | ||
| 2651 | char t[160]; | ||
| 2652 | std::snprintf(t, sizeof(t), " [%s: %llu readings, %llu with buttons]", n.c_str(), (unsigned long long)c.first, | ||
| 2653 | (unsigned long long)c.second); | ||
| 2654 | line += t; | ||
| 2655 | } | ||
| 2656 | std::fprintf(stderr, "[rt] gameinput stats (calls null/aggregate/device): %s\n", line.c_str()); | ||
| 2657 | std::memset(st.calls, 0, sizeof(st.calls)); | ||
| 2658 | std::memset(st.found, 0, sizeof(st.found)); | ||
| 2659 | std::memset(st.pressed, 0, sizeof(st.pressed)); | ||
| 2660 | std::memset(st.a_pressed, 0, sizeof(st.a_pressed)); | ||
| 2661 | st.by_device.clear(); | ||
| 2662 | st.since = now; | ||
| 2663 | } | ||
| 2664 | |||
| 2462 | HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { | 2665 | HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { |
| 2666 | g_reading_calls.fetch_add(1, std::memory_order_relaxed); | ||
| 2667 | const HRESULT hr = current_reading(kind, device, out); | ||
| 2668 | note_reading(0, device, hr, out ? *out : nullptr); | ||
| 2669 | return hr; | ||
| 2670 | } | ||
| 2671 | HRESULT current_reading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) { | ||
| 2463 | if (!out) return E_POINTER; | 2672 | if (!out) return E_POINTER; |
| 2464 | *out = nullptr; | 2673 | *out = nullptr; |
| 2465 | if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; | 2674 | if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; |
| @@ -2493,11 +2702,15 @@ public: | |||
| 2493 | 2702 | ||
| 2494 | HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, | 2703 | HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, |
| 2495 | IGameInputReading** out) override { | 2704 | IGameInputReading** out) override { |
| 2496 | return find_reading(ref, kind, device, out, true); | 2705 | const HRESULT hr = find_reading(ref, kind, device, out, true); |
| 2706 | note_reading(1, device, hr, out ? *out : nullptr); | ||
| 2707 | return hr; | ||
| 2497 | } | 2708 | } |
| 2498 | HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, | 2709 | HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, |
| 2499 | IGameInputReading** out) override { | 2710 | IGameInputReading** out) override { |
| 2500 | return find_reading(ref, kind, device, out, false); | 2711 | const HRESULT hr = find_reading(ref, kind, device, out, false); |
| 2712 | note_reading(2, device, hr, out ? *out : nullptr); | ||
| 2713 | return hr; | ||
| 2501 | } | 2714 | } |
| 2502 | // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in | 2715 | // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in |
| 2503 | // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. | 2716 | // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. |
| @@ -2521,6 +2734,15 @@ public: | |||
| 2521 | if (token) *token = kInvalidCallbackToken; | 2734 | if (token) *token = kInvalidCallbackToken; |
| 2522 | if (!fn) return E_INVALIDARG; | 2735 | if (!fn) return E_INVALIDARG; |
| 2523 | if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL; | 2736 | if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL; |
| 2737 | // How a title learns of its pads decides whether one plugged in later reaches it, so the first few | ||
| 2738 | // registrations are logged. | ||
| 2739 | static std::atomic<int> s_logged{0}; | ||
| 2740 | if (s_logged.fetch_add(1) < 8) | ||
| 2741 | std::fprintf(stderr, "[rt] gameinput: RegisterDeviceCallback(%s, kind 0x%x, status 0x%x, %s enumeration)\n", | ||
| 2742 | device ? "one device" : "all devices", kind, status_filter, | ||
| 2743 | enumeration == GameInputBlockingEnumeration ? "blocking" | ||
| 2744 | : enumeration == GameInputAsyncEnumeration ? "async" | ||
| 2745 | : "no"); | ||
| 2524 | State& s = g(); | 2746 | State& s = g(); |
| 2525 | GameInputCallbackToken t; | 2747 | GameInputCallbackToken t; |
| 2526 | std::vector<Event> now; | 2748 | std::vector<Event> now; |
| @@ -2566,6 +2788,8 @@ public: | |||
| 2566 | } | 2788 | } |
| 2567 | 2789 | ||
| 2568 | void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { | 2790 | void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { |
| 2791 | token = resolve_token(token); | ||
| 2792 | if (token == kInvalidCallbackToken) return; | ||
| 2569 | std::lock_guard lock(g().mu); | 2793 | std::lock_guard lock(g().mu); |
| 2570 | for (Callback& c : g().callbacks) | 2794 | for (Callback& c : g().callbacks) |
| 2571 | if (c.token == token) c.active = false; | 2795 | if (c.token == token) c.active = false; |
| @@ -2574,6 +2798,8 @@ public: | |||
| 2574 | // Removes the callback and, unless called from inside a callback, waits for one that is running to return. | 2798 | // Removes the callback and, unless called from inside a callback, waits for one that is running to return. |
| 2575 | // VERIFY: the timeout is not honoured; the wait is for at most one callback. | 2799 | // VERIFY: the timeout is not honoured; the wait is for at most one callback. |
| 2576 | bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override { | 2800 | bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override { |
| 2801 | token = resolve_token(token); | ||
| 2802 | if (token == kInvalidCallbackToken) return false; | ||
| 2577 | State& s = g(); | 2803 | State& s = g(); |
| 2578 | bool found = false; | 2804 | bool found = false; |
| 2579 | { | 2805 | { |
| @@ -2590,6 +2816,9 @@ public: | |||
| 2590 | 2816 | ||
| 2591 | HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { | 2817 | HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { |
| 2592 | if (!out) return E_POINTER; | 2818 | if (!out) return E_POINTER; |
| 2819 | static std::atomic<bool> s_logged{false}; | ||
| 2820 | if (!s_logged.exchange(true)) | ||
| 2821 | std::fprintf(stderr, "[rt] gameinput: CreateDispatcher first call (callbacks now run in Dispatch)\n"); | ||
| 2593 | *out = new Dispatcher; | 2822 | *out = new Dispatcher; |
| 2594 | return S_OK; | 2823 | return S_OK; |
| 2595 | } | 2824 | } |