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:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 13:17:55 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 13:17:55 -0500
commitbbf861fbb4ea51ca18cd6f372797111984b6f8aa (patch)
tree81ac99a1a6d61841cca3562fab529cf38348c73f /runtime/shims/gameinput.cpp
parent4645a3f62a7655ce69b930da70bdc1a858d1d0a1 (diff)
parentbdbc7e9236465c5d6a1305de6edd3fc09c2d6fd9 (diff)
Merge main into fix/depth16-quantise-fallback
runtime/CMakeLists.txt: main added the heavy_pipeline_cache, pipeline_cache_journal and compile_helper tests where this branch adds depth24_fragment; both sides are kept. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp389
1 files changed, 230 insertions, 159 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index db685e71f..5abb2a2fe 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -45,6 +45,7 @@
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>
@@ -52,6 +53,8 @@
52 53
53#include "gameinput.h" 54#include "gameinput.h"
54#include "gameinput_abi.h" 55#include "gameinput_abi.h"
56#include "gameinput_script.h"
57#include "keyboard_pad_connection.h"
55#include "shims.h" 58#include "shims.h"
56 59
57using namespace gi; 60using namespace gi;
@@ -132,18 +135,30 @@ const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); }
132 135
133// ---- configuration ---------------------------------------------------------------------------------------------- 136// ---- configuration ----------------------------------------------------------------------------------------------
134 137
135std::string env(const char* name) { 138std::string env(const char* name) { return rt::gameinput::script::env_lower(name); }
136 // Any length: an input script (LEONIDA_INPUT_SCRIPT) is easily longer than a fixed buffer, and a value that did 139
137 // not fit used to read as unset. 140// The script's button numbers are SDL's (gameinput_script.h shares them with the shim built without SDL3).
138 const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator 141constexpr bool script_buttons_match_sdl() {
139 if (need == 0) return {}; 142 const struct {
140 std::string s(need, '\0'); 143 uint32_t bit;
141 const DWORD n = GetEnvironmentVariableA(name, s.data(), need); 144 SDL_GamepadButton sdl;
142 if (n == 0 || n >= need) return {}; 145 } expected[] = {{GameInputGamepadA, SDL_GAMEPAD_BUTTON_SOUTH}, {GameInputGamepadB, SDL_GAMEPAD_BUTTON_EAST},
143 s.resize(n); 146 {GameInputGamepadX, SDL_GAMEPAD_BUTTON_WEST}, {GameInputGamepadY, SDL_GAMEPAD_BUTTON_NORTH},
144 for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); 147 {GameInputGamepadMenu, SDL_GAMEPAD_BUTTON_START}, {GameInputGamepadView, SDL_GAMEPAD_BUTTON_BACK},
145 return s; 148 {GameInputGamepadLeftShoulder, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
149 {GameInputGamepadRightShoulder, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
150 {GameInputGamepadDPadUp, SDL_GAMEPAD_BUTTON_DPAD_UP}, {GameInputGamepadDPadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN},
151 {GameInputGamepadDPadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT},
152 {GameInputGamepadDPadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT}};
153 if (std::size(expected) != std::size(rt::gameinput::script::kButtons)) return false;
154 for (const auto& e : expected) {
155 bool found = false;
156 for (const auto& b : rt::gameinput::script::kButtons) found |= b.bit == e.bit && b.sdl == e.sdl;
157 if (!found) return false;
158 }
159 return true;
146} 160}
161static_assert(script_buttons_match_sdl(), "gameinput_script.h's SDL button numbers drifted from SDL_GamepadButton");
147 162
148rt::gameinput::Config read_config() { 163rt::gameinput::Config read_config() {
149 rt::gameinput::Config c; 164 rt::gameinput::Config c;
@@ -991,6 +1006,9 @@ leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) {
991// in bits 0-7, forced in bit 8, the generation from bit 16. 1006// in bits 0-7, forced in bit 8, the generation from bit 16.
992leonida::ActiveInputTracker g_tracker; 1007leonida::ActiveInputTracker g_tracker;
993std::atomic<uint64_t> g_active{0}; 1008std::atomic<uint64_t> g_active{0};
1009// GetCurrentReading calls so far, any device: a scripted press is held until the title has read the pads a few
1010// times since it began (update_keyboard_pad).
1011std::atomic<uint64_t> g_reading_calls{0};
994 1012
995void publish_active() { 1013void publish_active() {
996 g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | 1014 g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) |
@@ -1103,30 +1121,7 @@ Snapshot read_pad(Device* d) {
1103 } 1121 }
1104 } 1122 }
1105 1123
1106 // UI navigation derived from the gamepad (VERIFY against the console's own mapping). 1124 s.ui = rt::gameinput::script::ui_navigation(s.gamepad);
1107 const uint32_t b = s.gamepad.buttons;
1108 const float t = 0.5f;
1109 uint32_t& u = s.ui;
1110 if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu;
1111 if (b & GameInputGamepadView) u |= GameInputUiNavigationView;
1112 if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept;
1113 if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel;
1114 if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1;
1115 if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2;
1116 if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3;
1117 if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4;
1118 if ((b & GameInputGamepadDPadUp) || s.gamepad.leftThumbstickY > t) u |= GameInputUiNavigationUp;
1119 if ((b & GameInputGamepadDPadDown) || s.gamepad.leftThumbstickY < -t) u |= GameInputUiNavigationDown;
1120 if ((b & GameInputGamepadDPadLeft) || s.gamepad.leftThumbstickX < -t) u |= GameInputUiNavigationLeft;
1121 if ((b & GameInputGamepadDPadRight) || s.gamepad.leftThumbstickX > t) u |= GameInputUiNavigationRight;
1122 if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft;
1123 if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight;
1124 if (s.gamepad.leftTrigger > t) u |= GameInputUiNavigationPageUp;
1125 if (s.gamepad.rightTrigger > t) u |= GameInputUiNavigationPageDown;
1126 if (s.gamepad.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp;
1127 if (s.gamepad.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown;
1128 if (s.gamepad.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft;
1129 if (s.gamepad.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight;
1130 return s; 1125 return s;
1131} 1126}
1132 1127
@@ -1776,10 +1771,7 @@ std::atomic<rt::gameinput::KeyDownFn> g_key_down{async_key_down};
1776std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours}; 1771std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours};
1777std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos}; 1772std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos};
1778 1773
1779struct KeyboardPad { 1774struct KeyboardPad : rt::gameinput::detail::KeyboardPadConnection<SDL_JoystickID, SDL_Joystick*> {
1780 SDL_JoystickID id = 0;
1781 SDL_Joystick* js = nullptr;
1782 bool failed = false; // attaching failed once; not retried every 2 ms
1783 int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) 1775 int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down)
1784 int cursor_x = 0, cursor_y = 0; // the cursor at the last poll 1776 int cursor_x = 0, cursor_y = 0; // the cursor at the last poll
1785 bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing 1777 bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing
@@ -1788,13 +1780,6 @@ KeyboardPad g_keyboard;
1788 1780
1789bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } 1781bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; }
1790 1782
1791void detach_keyboard_pad() {
1792 if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js);
1793 if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id);
1794 if (g_keyboard.id) std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n");
1795 g_keyboard = {};
1796}
1797
1798// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases 1783// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases
1799// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for 1784// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for
1800// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. 1785// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus.
@@ -1822,29 +1807,34 @@ void clip_cursor(bool want) {
1822 } 1807 }
1823} 1808}
1824 1809
1825bool attach_keyboard_pad() { 1810struct KeyboardPadBackend {
1826 SDL_VirtualJoystickDesc d; 1811 static uint64_t now() { return now_us(); }
1827 SDL_INIT_INTERFACE(&d); 1812 static SDL_JoystickID attach() {
1828 d.type = SDL_JOYSTICK_TYPE_GAMEPAD; 1813 SDL_VirtualJoystickDesc d;
1829 d.naxes = SDL_GAMEPAD_AXIS_COUNT; 1814 SDL_INIT_INTERFACE(&d);
1830 d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; 1815 d.type = SDL_JOYSTICK_TYPE_GAMEPAD;
1831 d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; 1816 d.naxes = SDL_GAMEPAD_AXIS_COUNT;
1832 d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; 1817 d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT;
1833 d.name = "Keyboard pad (Leonida)"; 1818 d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1;
1834 g_keyboard.id = SDL_AttachVirtualJoystick(&d); 1819 d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1;
1835 g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; 1820 d.name = "Keyboard pad (Leonida)";
1836 if (!g_keyboard.js) { 1821 return SDL_AttachVirtualJoystick(&d);
1822 }
1823 static SDL_Joystick* open(SDL_JoystickID id) { return SDL_OpenJoystick(id); }
1824 static void close(SDL_Joystick* js) { SDL_CloseJoystick(js); }
1825 static bool detach(SDL_JoystickID id) { return SDL_DetachVirtualJoystick(id); }
1826 static bool is_virtual(SDL_JoystickID id) { return SDL_IsJoystickVirtual(id); }
1827 static void removed() { std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); }
1828 static void failed() {
1837 std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); 1829 std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError());
1838 detach_keyboard_pad();
1839 g_keyboard.failed = true;
1840 return false;
1841 } 1830 }
1842 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " 1831 static void attached() {
1843 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " 1832 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, "
1844 "button LT/RT)\n"); 1833 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left "
1845 start_raw_mouse(); 1834 "button LT/RT)\n");
1846 return true; 1835 start_raw_mouse();
1847} 1836 }
1837};
1848 1838
1849// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. 1839// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading.
1850void update_keyboard_pad() { 1840void update_keyboard_pad() {
@@ -1855,13 +1845,14 @@ void update_keyboard_pad() {
1855 mode = g().config.keyboard_pad; 1845 mode = g().config.keyboard_pad;
1856 sens = g().config.mouse_sensitivity; 1846 sens = g().config.mouse_sensitivity;
1857 } 1847 }
1858 if (mode == rt::gameinput::KeyboardPadMode::Off) { 1848 KeyboardPadBackend backend;
1849 const bool enabled = mode != rt::gameinput::KeyboardPadMode::Off;
1850 if (!enabled) {
1859 clip_cursor(false); 1851 clip_cursor(false);
1860 if (g_keyboard.id) detach_keyboard_pad(); 1852 g_keyboard.right_x = g_keyboard.right_y = 0;
1861 g_keyboard.failed = false; 1853 g_keyboard.have_cursor = false;
1862 return;
1863 } 1854 }
1864 if (!g_keyboard.js && (g_keyboard.failed || !attach_keyboard_pad())) return; 1855 if (!g_keyboard.update(enabled, backend)) return;
1865 1856
1866 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1857 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {};
1867 int lx = 0, ly = 0; 1858 int lx = 0, ly = 0;
@@ -1896,81 +1887,101 @@ void update_keyboard_pad() {
1896 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); 1887 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours());
1897 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1888 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
1898 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard 1889 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard
1899 // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt 1890 // pad, in seconds since the pad's first update, each held 300 ms or its own button@seconds:hold, and then until the
1900 // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). Buttons: a b x y start back lb rb 1891 // title has read the pads kReads times since it began (never past kMaxHold seconds, or the hold if it is longer, so
1901 // up down left right. The rsup and rsdown entries replay the right-stick throws logged below. 1892 // 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
1894 // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3.
1895 namespace script = rt::gameinput::script;
1902 int right_y = g_keyboard.right_y; 1896 int right_y = g_keyboard.right_y;
1903 struct ScriptedPress { 1897 static const script::Script scripted = [] {
1904 SDL_GamepadButton button; 1898 script::Script s = script::parse(env("LEONIDA_INPUT_SCRIPT"));
1899 if (!s.empty() || s.rejected)
1900 std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n",
1901 s.presses.size(), s.rejected);
1902 return s;
1903 }();
1904 // LEONIDA_INPUT_FILE=<path> (local, for headless runs whose display takes no keyboard input): every line appended
1905 // to the file names one button of gameinput_script.h's table ("a", "down", ...) and becomes a press at once, held
1906 // like a scripted one (300 ms and six readings, at most 5 s). The file is read again at most every 250 ms.
1907 struct FilePress {
1908 uint32_t bit;
1905 double at; 1909 double at;
1906 int right_y = 0; 1910 uint64_t began;
1911 bool started;
1907 }; 1912 };
1908 static const std::vector<ScriptedPress> script = [] { 1913 static std::vector<FilePress> file_presses;
1909 std::vector<ScriptedPress> out; 1914 static const std::string input_file = [] {
1910 static const std::pair<const char*, SDL_GamepadButton> names[] = { 1915 const char* v = std::getenv("LEONIDA_INPUT_FILE");
1911 {"a", SDL_GAMEPAD_BUTTON_SOUTH}, {"b", SDL_GAMEPAD_BUTTON_EAST}, 1916 return std::string(v ? v : "");
1912 {"x", SDL_GAMEPAD_BUTTON_WEST}, {"y", SDL_GAMEPAD_BUTTON_NORTH}, 1917 }();
1913 {"start", SDL_GAMEPAD_BUTTON_START}, {"back", SDL_GAMEPAD_BUTTON_BACK}, 1918 if (!scripted.empty() || !input_file.empty()) {
1914 {"lb", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER}, {"rb", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER}, 1919 static const ULONGLONG origin = GetTickCount64();
1915 {"up", SDL_GAMEPAD_BUTTON_DPAD_UP}, {"down", SDL_GAMEPAD_BUTTON_DPAD_DOWN}, 1920 const double now = (GetTickCount64() - origin) / 1000.0;
1916 {"left", SDL_GAMEPAD_BUTTON_DPAD_LEFT}, {"right", SDL_GAMEPAD_BUTTON_DPAD_RIGHT}}; 1921 script::Held held{};
1917 const std::string text = env("LEONIDA_INPUT_SCRIPT"); 1922 static constexpr uint64_t kReads = 6;
1918 if (text.empty()) return out; 1923 static constexpr double kMaxHold = 5.0;
1919 constexpr char whitespace[] = " \t\r\n\f\v"; 1924 static std::vector<uint64_t> began(scripted.presses.size(), 0);
1920 size_t items = 0; 1925 static std::vector<char> started(scripted.presses.size(), 0);
1921 for (size_t at = 0, end; at <= text.size(); at = end + 1) { 1926 const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed);
1922 ++items; 1927 if (!input_file.empty()) {
1923 end = std::min(text.find(',', at), text.size()); 1928 static ULONGLONG last_read = 0;
1924 const std::string item = text.substr(at, end - at); 1929 static std::size_t lines_done = 0;
1925 const size_t first = item.find_first_not_of(whitespace); 1930 const ULONGLONG tick = GetTickCount64();
1926 const size_t sep = item.find('@'); 1931 if (tick - last_read >= 250) {
1927 if (sep == std::string::npos || first >= sep) continue; 1932 last_read = tick;
1928 const char* time = item.c_str() + sep + 1; 1933 if (FILE* f = std::fopen(input_file.c_str(), "r")) {
1929 char* tail; 1934 char line[64];
1930 const double seconds = std::strtod(time, &tail); 1935 std::size_t n = 0;
1931 if (tail == time || !std::isfinite(seconds) || seconds < 0 || 1936 while (std::fgets(line, sizeof(line), f)) {
1932 item.find_first_not_of(whitespace, tail - item.c_str()) != std::string::npos) continue; 1937 if (++n <= lines_done) continue;
1933 if (item.compare(first, sep - first, "rsup") == 0 || item.compare(first, sep - first, "rsdown") == 0) { 1938 lines_done = n;
1934 const bool up = item.compare(first, sep - first, "rsup") == 0; 1939 std::string name(line);
1935 out.push_back({SDL_GAMEPAD_BUTTON_INVALID, seconds, up ? -kStickFull : kStickFull}); 1940 while (!name.empty() && (name.back() == '\n' || name.back() == '\r' || name.back() == ' '))
1936 continue; 1941 name.pop_back();
1942 bool known = false;
1943 for (const script::Button& b : script::kButtons)
1944 if (name == b.name) {
1945 file_presses.push_back({b.bit, now, 0, false});
1946 known = true;
1947 }
1948 std::fprintf(stderr, "[rt] gameinput: input file line %zu \"%s\" at %.1f s%s\n", n,
1949 name.c_str(), now, known ? "" : " (unknown button, ignored)");
1950 }
1951 std::fclose(f);
1952 }
1937 } 1953 }
1938 for (const auto& [name, button] : names) { 1954 for (auto& p : file_presses) {
1939 if (item.compare(first, sep - first, name) == 0) { 1955 if (now < p.at || now >= p.at + kMaxHold) continue;
1940 out.push_back({button, seconds}); 1956 if (!p.started) {
1941 break; 1957 p.started = true;
1958 p.began = calls;
1942 } 1959 }
1960 if (now < p.at + 0.3 || calls - p.began < kReads) held.buttons |= p.bit;
1943 } 1961 }
1944 } 1962 }
1945 std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n", 1963 for (std::size_t i = 0; i < scripted.presses.size(); ++i) {
1946 out.size(), items - out.size()); 1964 const auto& press = scripted.presses[i];
1947 return out; 1965 bool active = false;
1948 }(); 1966 if (now >= press.at && now < press.at + std::max(press.hold, kMaxHold)) {
1949 if (!script.empty()) { 1967 if (!started[i]) {
1950 static const ULONGLONG origin = GetTickCount64(); 1968 started[i] = 1;
1951 const double now = (GetTickCount64() - origin) / 1000.0; 1969 began[i] = calls;
1952 // One decision per button: a later entry for the same button must not release what an earlier entry holds 1970 }
1953 // (it did: with several entries only the last one ever reached the title). 1971 active = now < press.at + press.hold || calls - began[i] < kReads;
1954 bool scripted[SDL_GAMEPAD_BUTTON_COUNT] = {};
1955 bool named[SDL_GAMEPAD_BUTTON_COUNT] = {};
1956 for (const auto& press : script) {
1957 const bool held = now >= press.at && now < press.at + 0.3;
1958 if (press.right_y) {
1959 if (held) right_y = press.right_y;
1960 } else {
1961 named[press.button] = true;
1962 scripted[press.button] |= held;
1963 } 1972 }
1973 if (!active) continue;
1974 if (press.stick) held.stick = press.stick;
1975 else held.buttons |= press.button;
1964 } 1976 }
1965 for (int button = 0; button < SDL_GAMEPAD_BUTTON_COUNT; ++button) { 1977 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down
1966 if (!named[button]) continue; 1978 for (const script::Button& b : script::kButtons) {
1967 SDL_SetJoystickVirtualButton(g_keyboard.js, static_cast<SDL_GamepadButton>(button), 1979 if (!(scripted.named & b.bit) && input_file.empty()) continue;
1968 scripted[button] || down[button]); 1980 const auto button = static_cast<SDL_GamepadButton>(b.sdl);
1969 static bool was[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1981 SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]);
1970 if (scripted[button] && !was[button])
1971 std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", button, now);
1972 was[button] = scripted[button];
1973 } 1982 }
1983 static uint32_t was = 0;
1984 script::log_scripted(held.buttons, &was, now);
1974 } 1985 }
1975 const int reach = lx && ly ? kStickDiagonal : kStickFull; 1986 const int reach = lx && ly ? kStickDiagonal : kStickFull;
1976 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach)); 1987 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach));
@@ -2020,6 +2031,10 @@ void poll_once() {
2020 SDL_JoystickID* ids = SDL_GetGamepads(&count); 2031 SDL_JoystickID* ids = SDL_GetGamepads(&count);
2021 std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0)); 2032 std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0));
2022 SDL_free(ids); 2033 SDL_free(ids);
2034 // An unopened virtual device may still be waiting for SDL to finish detaching it.
2035 // Do not advertise it to the title until it has a working keyboard handle.
2036 if (g_keyboard.id && !g_keyboard.js)
2037 present.erase(std::remove(present.begin(), present.end(), g_keyboard.id), present.end());
2023 2038
2024 std::vector<Device*> connected; 2039 std::vector<Device*> connected;
2025 { 2040 {
@@ -2053,26 +2068,10 @@ void poll_once() {
2053 { 2068 {
2054 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; 2069 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0";
2055 static const ULONGLONG log_origin = GetTickCount64(); 2070 static const ULONGLONG log_origin = GetTickCount64();
2056 if (log_presses) { 2071 if (log_presses)
2057 static const std::pair<uint32_t, const char*> kNames[] = { 2072 rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons,
2058 {GameInputGamepadA, "a"}, {GameInputGamepadB, "b"}, 2073 d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY,
2059 {GameInputGamepadX, "x"}, {GameInputGamepadY, "y"}, 2074 (GetTickCount64() - log_origin) / 1000.0, d->name.c_str());
2060 {GameInputGamepadMenu, "start"}, {GameInputGamepadView, "back"},
2061 {GameInputGamepadLeftShoulder, "lb"}, {GameInputGamepadRightShoulder, "rb"},
2062 {GameInputGamepadDPadUp, "up"}, {GameInputGamepadDPadDown, "down"},
2063 {GameInputGamepadDPadLeft, "left"}, {GameInputGamepadDPadRight, "right"}};
2064 const double at = (GetTickCount64() - log_origin) / 1000.0;
2065 const uint32_t pressed = snap.gamepad.buttons & ~d->last_snap.gamepad.buttons;
2066 for (const auto& n : kNames)
2067 if (pressed & n.first)
2068 std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", n.second, at, d->name.c_str());
2069 const auto throw_of = [](float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; };
2070 const int was = throw_of(d->last_snap.gamepad.rightThumbstickY);
2071 const int is = throw_of(snap.gamepad.rightThumbstickY);
2072 if (is != was && is != 0)
2073 std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", at,
2074 d->name.c_str());
2075 }
2076 } 2075 }
2077 d->last_snap = snap; 2076 d->last_snap = snap;
2078 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button 2077 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button
@@ -2488,7 +2487,75 @@ public:
2488 2487
2489 uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } 2488 uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); }
2490 2489
2490 // LEONIDA_INPUT_STATS=1 (diagnostic): every 10 s, how the title asked for readings (by method and device
2491 // argument) and what it got (by the reading's device, and whether a gamepad button was down in it).
2492 static void note_reading(int method, IGameInputDevice* asked, HRESULT hr, IGameInputReading* got) {
2493 static const bool on = env("LEONIDA_INPUT_STATS") == "1";
2494 if (!on) return;
2495 struct Stats {
2496 std::mutex mu;
2497 uint64_t calls[3][3] = {}; // method x (null, aggregate, a device)
2498 uint64_t found[3] = {}, pressed[3] = {};
2499 std::map<std::string, std::pair<uint64_t, uint64_t>> by_device; // name -> (readings, with buttons)
2500 uint64_t since = 0;
2501 };
2502 static Stats st;
2503 std::string name;
2504 bool buttons = false;
2505 if (SUCCEEDED(hr) && got) {
2506 IGameInputDevice* d = nullptr;
2507 got->GetDevice(&d);
2508 if (d) {
2509 name = as_device(d)->name;
2510 d->Release();
2511 }
2512 GameInputGamepadState g{};
2513 if (got->GetGamepadState(&g)) buttons = g.buttons != 0;
2514 }
2515 const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2;
2516 std::lock_guard lock(st.mu);
2517 ++st.calls[method][arg];
2518 if (SUCCEEDED(hr) && got) {
2519 ++st.found[method];
2520 st.pressed[method] += buttons;
2521 auto& e = st.by_device[name];
2522 ++e.first;
2523 e.second += buttons;
2524 }
2525 const uint64_t now = now_us();
2526 if (!st.since) st.since = now;
2527 if (now - st.since < 10'000'000) return;
2528 static const char* methods[] = {"GetCurrentReading", "GetNextReading", "GetPreviousReading"};
2529 std::string line;
2530 for (int m = 0; m < 3; ++m) {
2531 char t[200];
2532 std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu;", methods[m],
2533 (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1],
2534 (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m],
2535 (unsigned long long)st.pressed[m]);
2536 line += t;
2537 }
2538 for (const auto& [n, c] : st.by_device) {
2539 char t[160];
2540 std::snprintf(t, sizeof(t), " [%s: %llu readings, %llu with buttons]", n.c_str(), (unsigned long long)c.first,
2541 (unsigned long long)c.second);
2542 line += t;
2543 }
2544 std::fprintf(stderr, "[rt] gameinput stats (calls null/aggregate/device): %s\n", line.c_str());
2545 std::memset(st.calls, 0, sizeof(st.calls));
2546 std::memset(st.found, 0, sizeof(st.found));
2547 std::memset(st.pressed, 0, sizeof(st.pressed));
2548 st.by_device.clear();
2549 st.since = now;
2550 }
2551
2491 HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { 2552 HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override {
2553 g_reading_calls.fetch_add(1, std::memory_order_relaxed);
2554 const HRESULT hr = current_reading(kind, device, out);
2555 note_reading(0, device, hr, out ? *out : nullptr);
2556 return hr;
2557 }
2558 HRESULT current_reading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) {
2492 if (!out) return E_POINTER; 2559 if (!out) return E_POINTER;
2493 *out = nullptr; 2560 *out = nullptr;
2494 if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; 2561 if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND;
@@ -2522,11 +2589,15 @@ public:
2522 2589
2523 HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, 2590 HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
2524 IGameInputReading** out) override { 2591 IGameInputReading** out) override {
2525 return find_reading(ref, kind, device, out, true); 2592 const HRESULT hr = find_reading(ref, kind, device, out, true);
2593 note_reading(1, device, hr, out ? *out : nullptr);
2594 return hr;
2526 } 2595 }
2527 HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, 2596 HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
2528 IGameInputReading** out) override { 2597 IGameInputReading** out) override {
2529 return find_reading(ref, kind, device, out, false); 2598 const HRESULT hr = find_reading(ref, kind, device, out, false);
2599 note_reading(2, device, hr, out ? *out : nullptr);
2600 return hr;
2530 } 2601 }
2531 // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in 2602 // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in
2532 // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. 2603 // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does.