Merge the PC keyboard and mouse layout

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-10-23 23:33:31 +03:00
commit eb12f260ad
8 files changed
+343 -44

No files matched your search

+26 -14
View File
@@ -1,20 +1,32 @@
# Controls
Input comes from the first SDL3 gamepad and the keyboard, merged into one Switch controller (`runtime/input_win.c`). Buttons are ORed; each stick takes the source with the larger deflection. Keys count only while the game window is in the foreground. `TOTK_INPUT=none` disables both (automated runs). `TOTK_*` settings can also be set in `totk.ini` next to `totk.exe` (`input = none`, `motion = 0`, `rumble = 0`); the environment overrides the file. `TOTK_RUMBLE_STRENGTH` is the rumble strength in percent (0 to 300, default 130; 0 is the same as `rumble = 0`). `TOTK_RUMBLE_CURVE` is the exponent applied to the amplitude before the strength (0.2 to 1.5, default 0.6; lower makes weak pulses stronger, 1 is linear). `TOTK_RUMBLE_TRIGGERS=1` also drives the impulse triggers of an Xbox pad.
Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into one Switch controller (`runtime/input_win.c`). Buttons are ORed; each stick takes the source with the larger deflection. Keys and mouse buttons count only while the game window is in the foreground. `TOTK_INPUT=none` disables both (automated runs). `TOTK_*` settings can also be set in `totk.ini` next to `totk.exe` (`input = none`, `motion = 0`, `rumble = 0`); the environment overrides the file. `TOTK_RUMBLE_STRENGTH` is the rumble strength in percent (0 to 300, default 130; 0 is the same as `rumble = 0`). `TOTK_RUMBLE_CURVE` is the exponent applied to the amplitude before the strength (0.2 to 1.5, default 0.6; lower makes weak pulses stronger, 1 is linear). `TOTK_RUMBLE_TRIGGERS=1` also drives the impulse triggers of an Xbox pad.
| Switch | Gamepad (by position) | Keyboard |
|---|---|---|
| Left stick | left stick | W A S D |
| Right stick | right stick | I J K L |
| D-pad | D-pad | Arrow keys |
| A | east | E |
| B | south | Left Shift |
| X | north | Space |
| Y | west | F |
| L / R | shoulders | Tab / R |
| ZL / ZR | triggers (over 50%) | Q / Z |
| Left / right stick click | stick clicks | C / V |
| Plus / Minus | Start / Back | Enter / Backspace |
| Switch | Gamepad (by position) | Keyboard and mouse | Action in the world |
|---|---|---|---|
| Left stick | left stick | W A S D | move |
| Right stick | right stick | mouse; arrow keys as a second source | camera |
| Y | west | left mouse button | attack |
| ZL | left trigger (over 50%) | right mouse button, Z | shield, lock on |
| ZR | right trigger (over 50%) | F, X | bow |
| X | north | Space | jump |
| B | south | Left Shift | run, cancel |
| A | east | E | interact, pick up |
| L | left shoulder | Q | abilities |
| R | right shoulder | R | throw weapon |
| Left stick click | left stick click | Left Ctrl | crouch |
| Right stick click | right stick click | C | first-person view |
| D-pad left, up, right, down | D-pad | 1 2 3 4 | quick-select |
| Plus | Start | Tab | menu, inventory |
| Minus | Back | M | map |
Esc is free. Z and X duplicate ZL and ZR so menu pages turn with two neighbouring keys; the menu tabs (L, R) are Q and R. The mouse wheel is unbound. The bindings are one table, `input_bindings` in `runtime/input_map.c` (platform-neutral key ids; `runtime/input_win.c` translates Win32 virtual keys), so a remapping page can edit it later.
## Mouse camera
Mouse motion (raw input) becomes right-stick deflection. Each presented frame takes the counts moved since the last frame, divides by the frame time and sets the deflection to `counts per second * TOTK_MOUSE_SENS / 3000` of full, held for that frame, so the turn rate does not depend on the frame rate. This is not mouselook: the game's stick curve and dead zone still apply, so very slow movements do nothing and a fast flick saturates. The mouse deflection competes with the gamepad and arrow keys by the larger-deflection rule.
`TOTK_MOUSE_SENS` (0 to 10, default 1; higher turns faster, 0 turns the mouse camera and the cursor capture off). While the window is the foreground window the cursor is hidden and confined to the client area. It is released on focus loss, minimise, while F11 changes the window, during a size or move loop and while a text entry is open. To resize or move the window by hand, alt-tab away first or use F11. `TOTK_INPUT=none` disables the capture too.
The stick direction bits (`StickLLeft` to `StickRDown`) are derived from the sticks at 50% deflection. A gamepad plugged in later is picked up within one second; with none connected the log says `input: no gamepad`.
+1 -1
View File
@@ -28,7 +28,7 @@ static const char *const known[] = {
"FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FREE_CORES", "GPL",
"GPL_DRAW_BUILD",
"GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MINIMAL_LAYOUT", "MOTION", "MOVIE_HOST",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MINIMAL_LAYOUT", "MOTION", "MOUSE_SENS", "MOVIE_HOST",
"MOVIE_PACE", "OPERATION_MODE", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_PREBUILD", "PIPE_SYNC", "PREWARM_XLATE",
"PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_RENDER", "PUSH_STAGE", "RDOC",
"RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
+43
View File
@@ -1,4 +1,5 @@
// --probe-cfg: totk.ini parsing, the environment override and a missing file (cfg.c). Needs no game files.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -6,6 +7,7 @@
#include "cfg.h"
#include "host.h"
#include "input.h"
#include "input_map.h"
#include "platform/platform.h"
static int fails;
@@ -58,6 +60,47 @@ int probe_cfg(void) {
CHECK(rumble_motor(0.25f, 1, 1) > 16000 && rumble_motor(0.25f, 1, 1) < 16800, "rumble: curve 1, strength 100% is linear");
CHECK(rumble_motor(0.1f, 0.6f, 1.3f) > rumble_motor(0.1f, 1, 1.3f), "rumble: curve lifts weak values");
CHECK(rumble_motor(0.3f, 0.6f, 1.3f) > rumble_motor(0.3f, 0.6f, 1), "rumble: strength scales");
// Keyboard and mouse bindings (input_map.c)
uint8_t dn[KEY_COUNT] = {0};
int32_t st[2];
CHECK(input_map_buttons(dn) == 0, "keys: nothing held, no buttons");
dn[KEY_MOUSE_L] = 1;
CHECK(input_map_buttons(dn) == 1ull << B_Y, "keys: left mouse button is Y");
dn[KEY_MOUSE_R] = dn[KEY_Z] = 1;
CHECK(input_map_buttons(dn) == (1ull << B_Y | 1ull << B_ZL), "keys: right mouse button and Z both press ZL");
memset(dn, 0, sizeof dn);
dn[KEY_X] = dn[KEY_TAB] = dn[KEY_M] = dn[KEY_LCTRL] = dn[KEY_3] = 1;
CHECK(input_map_buttons(dn) == (1ull << B_ZR | 1ull << B_PLUS | 1ull << B_MINUS | 1ull << B_STICK_L | 1ull << B_RIGHT),
"keys: X ZR, Tab Plus, M Minus, Left Ctrl stick click, 3 D-pad right");
memset(dn, 0, sizeof dn);
dn[KEY_W] = 1;
input_map_stick(dn, 0, st);
CHECK(st[0] == 0 && st[1] == 32767, "keys: W is left stick up");
dn[KEY_A] = 1;
input_map_stick(dn, 0, st);
CHECK(st[0] == -23170 && st[1] == 23170, "keys: W A is a diagonal on the unit circle");
dn[KEY_W] = dn[KEY_A] = dn[KEY_S] = 1;
dn[KEY_D] = 1;
input_map_stick(dn, 0, st);
CHECK(st[0] == 0 && st[1] == 0, "keys: opposite keys cancel");
memset(dn, 0, sizeof dn);
dn[KEY_LEFT] = 1;
input_map_stick(dn, 1, st);
CHECK(st[0] == -32767 && st[1] == 0, "keys: left arrow is right stick left");
input_map_stick(dn, 0, st);
CHECK(st[0] == 0 && st[1] == 0, "keys: arrows leave the left stick alone");
input_mouse_stick(30, 0, 1.0 / 60, 1, st);
CHECK(st[0] == 32767 * 1800 / 3000 && st[1] == 0, "mouse: 30 counts in 1/60 s is 60% right");
input_mouse_stick(0, -10, 1.0 / 60, 1, st);
CHECK(st[0] == 0 && st[1] > 0, "mouse: moving up is stick up");
input_mouse_stick(30, 0, 1.0 / 30, 1, st);
CHECK(st[0] == 32767 * 900 / 3000, "mouse: the same counts over twice the time are half the deflection");
input_mouse_stick(15, 0, 1.0 / 60, 2, st);
CHECK(st[0] == 32767 * 1800 / 3000, "mouse: doubling sensitivity halves the counts needed (15 counts at 2 = 30 at 1)");
input_mouse_stick(1000, 1000, 1.0 / 60, 1, st);
CHECK((int64_t)st[0] * st[0] + (int64_t)st[1] * st[1] <= 32768ll * 32768, "mouse: clamped to the unit circle");
input_mouse_stick(30, 0, 1.0 / 60, 0, st);
CHECK(st[0] == 0 && st[1] == 0, "mouse: sensitivity 0 is off");
printf("probe-cfg: %s\n", fails ? "FAIL" : "ok");
return fails ? 1 : 0;
}
+8 -1
View File
@@ -16,6 +16,7 @@
#include "cfg.h"
#include "flight.h"
#include "gfx.h"
#include "input.h"
#include "vk.h"
#define FRAMES 2
@@ -191,9 +192,15 @@ static void toggle_fullscreen(HWND h) {
}
static LRESULT CALLBACK wnd_proc(HWND h, UINT m, WPARAM w, LPARAM l) {
LRESULT input_res;
if (input_window_msg(h, m, w, l, &input_res)) return input_res;
switch (m) {
case WM_KEYDOWN:
if (w == VK_F11 && !(l & (1 << 30))) toggle_fullscreen(h); // bit 30: auto-repeat
if (w == VK_F11 && !(l & (1 << 30))) { // bit 30: auto-repeat
input_cursor_suspend(1);
toggle_fullscreen(h);
input_cursor_suspend(0);
}
break;
case WM_SIZE:
if (w != SIZE_MINIMIZED) InterlockedExchange(&g_dirty, 1);
+11
View File
@@ -1,6 +1,9 @@
// Host input sampling (runtime/input_win.c): SDL3 gamepad and the keyboard as one Switch npad.
#pragma once
#include <stdint.h>
#ifdef _WIN32
#include <windows.h>
#endif
// Bits of libnx HidNpadButton (A=0 B=1 X=2 Y=3 StickL=4 StickR=5 L=6 R=7 ZL=8 ZR=9 Plus=10 Minus=11 Left=12 Up=13 Right=14
// Down=15) and the stick directions (StickLLeft..Down 16-19, StickRLeft..Down 20-23, derived from the sticks).
@@ -11,6 +14,14 @@ void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_
void input_poll_ui(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
void input_block(int on);
// Mouse camera and cursor (input_win.c, Win32 window thread). The window procedure calls input_window_msg first for raw
// mouse input, cursor hiding and confinement; it returns 1 with *res set when the message is handled. input_cursor_suspend(1)
// releases the cursor around an F11 window change, (0) captures it again once the client area has its new size.
#ifdef _WIN32
int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res);
#endif
void input_cursor_suspend(int on);
// Rumble: SDL_RumbleGamepad on the open gamepad, low (heavy, left) and high (light, right) motor 0..65535 for ms
// milliseconds. 1 if a gamepad with rumble took it. Callable from any thread.
int input_rumble(uint16_t low, uint16_t high, uint32_t ms);
+48
View File
@@ -0,0 +1,48 @@
// Binding table and the pure mapping functions (input_map.h). No Win32 or SDL here.
#include <math.h>
#include "input_map.h"
#define STICK_MAX 32767
#define DIAGONAL 23170 // STICK_MAX / sqrt(2)
#define MOUSE_FULL_CPS 3000.0
const Binding input_bindings[] = {
{KEY_W, B_SL_UP}, {KEY_A, B_SL_LEFT}, {KEY_S, B_SL_DOWN}, {KEY_D, B_SL_RIGHT}, // move
{KEY_UP, B_SR_UP}, {KEY_LEFT, B_SR_LEFT}, {KEY_DOWN, B_SR_DOWN}, {KEY_RIGHT, B_SR_RIGHT}, // camera, second source
{KEY_MOUSE_L, B_Y}, {KEY_MOUSE_R, B_ZL}, {KEY_Z, B_ZL}, {KEY_F, B_ZR}, {KEY_X, B_ZR},
{KEY_SPACE, B_X}, {KEY_LSHIFT, B_B}, {KEY_E, B_A}, {KEY_Q, B_L}, {KEY_R, B_R},
{KEY_LCTRL, B_STICK_L}, {KEY_C, B_STICK_R},
{KEY_1, B_LEFT}, {KEY_2, B_UP}, {KEY_3, B_RIGHT}, {KEY_4, B_DOWN},
{KEY_TAB, B_PLUS}, {KEY_M, B_MINUS},
};
const int input_binding_count = (int)(sizeof input_bindings / sizeof *input_bindings);
uint64_t input_map_buttons(const uint8_t down[KEY_COUNT]) {
uint64_t b = 0;
for (int i = 0; i < input_binding_count; i++)
if (input_bindings[i].action < B_SL_LEFT && down[input_bindings[i].key]) b |= 1ull << input_bindings[i].action;
return b;
}
void input_map_stick(const uint8_t down[KEY_COUNT], int stick, int32_t out[2]) {
int first = stick ? B_SR_LEFT : B_SL_LEFT, dir[4] = {0, 0, 0, 0}; // left, up, right, down
for (int i = 0; i < input_binding_count; i++) {
int a = input_bindings[i].action - first;
if (a >= 0 && a < 4 && down[input_bindings[i].key]) dir[a] = 1;
}
int dx = dir[2] - dir[0], dy = dir[1] - dir[3];
int32_t m = dx && dy ? DIAGONAL : STICK_MAX;
out[0] = dx * m;
out[1] = dy * m;
}
void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t out[2]) {
out[0] = out[1] = 0;
if (!(dt_s > 0) || !(sens > 0)) return;
double k = STICK_MAX * (double)sens / (MOUSE_FULL_CPS * dt_s);
double x = dx * k, y = -dy * k, len = sqrt(x * x + y * y);
if (len > STICK_MAX) { x *= STICK_MAX / len; y *= STICK_MAX / len; }
out[0] = (int32_t)lrint(x);
out[1] = (int32_t)lrint(y);
}
+36
View File
@@ -0,0 +1,36 @@
// Keyboard and mouse bindings, free of any window system: the table maps platform-neutral key ids to Switch actions.
// input_win.c translates Win32 virtual keys to key ids (one place); a Linux port translates SDL scancodes the same way.
// A remapping page can later edit the table at run time. Layout in docs/controls.md.
#pragma once
#include <stdint.h>
// Actions are the bit numbers of libnx HidNpadButton (input.h); 16..23 are the stick directions, which keys drive as
// stick deflection.
enum {
B_A = 0, B_B, B_X, B_Y, B_STICK_L, B_STICK_R, B_L, B_R, B_ZL, B_ZR, B_PLUS, B_MINUS, B_LEFT, B_UP, B_RIGHT, B_DOWN,
B_SL_LEFT = 16, B_SL_UP, B_SL_RIGHT, B_SL_DOWN, B_SR_LEFT, B_SR_UP, B_SR_RIGHT, B_SR_DOWN,
ACTION_COUNT = 24
};
enum {
KEY_NONE = 0,
KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, // letters and digits are
KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, // consecutive
KEY_0, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9,
KEY_SPACE, KEY_TAB, KEY_LSHIFT, KEY_LCTRL, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT,
KEY_MOUSE_L, KEY_MOUSE_R, KEY_MOUSE_M,
KEY_COUNT
};
typedef struct { uint8_t key; uint8_t action; } Binding;
extern const Binding input_bindings[];
extern const int input_binding_count;
// down[key] != 0 for the keys held. Returns the Switch button bits (0..15) the table presses.
uint64_t input_map_buttons(const uint8_t down[KEY_COUNT]);
// out = x, y of the stick (0 left, 1 right) from its four direction actions; up is +y; a diagonal is scaled to the
// unit circle.
void input_map_stick(const uint8_t down[KEY_COUNT], int stick, int32_t out[2]);
// Mouse motion in raw counts over dt_s seconds to right-stick deflection: full deflection at 3000 / sens counts/s.
// Clamped to the unit circle, up (negative dy) is +y.
void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t out[2]);
+170 -28
View File
@@ -1,5 +1,7 @@
// Host input for nn::hid (runtime/ov_input.c): an SDL3 gamepad (no SDL window, no SDL video) and the keyboard, merged
// into Switch npad button bits and stick axes. Button order follows libnx HidNpadButton (ISC). Keys and their map: docs/controls.md.
// Host input for nn::hid (runtime/ov_input.c): an SDL3 gamepad (no SDL window, no SDL video), the keyboard and the mouse,
// merged into Switch npad button bits and stick axes. Button order follows libnx HidNpadButton (ISC). The key bindings are
// the table in input_map.c; this file translates Win32 virtual keys to its key ids, reads the mouse (raw input, WM_INPUT)
// and owns the cursor capture. Keys and their map: docs/controls.md.
// The gamepad also rumbles (input_rumble) and, when it has a gyro and an accelerometer, feeds the six-axis sensor from a
// thread of its own (input_motion_start). Every SDL call on the gamepad is made under `lock`.
#include <windows.h>
@@ -12,14 +14,11 @@
#include "cfg.h"
#include "host.h"
#include "input.h"
#include "input_map.h"
#include "nvn_api.h"
#include "vk.h"
enum {
B_A = 0, B_B, B_X, B_Y, B_STICK_L, B_STICK_R, B_L, B_R, B_ZL, B_ZR, B_PLUS, B_MINUS, B_LEFT, B_UP, B_RIGHT, B_DOWN,
B_SL_LEFT = 16, B_SL_UP, B_SL_RIGHT, B_SL_DOWN, B_SR_LEFT, B_SR_UP, B_SR_RIGHT, B_SR_DOWN,
STICK_MAX = 32767, STICK_DEAD = 2500, STICK_DIR = 16384, TRIGGER_ON = 16384, RESCAN_MS = 1000
};
enum { STICK_MAX = 32767, STICK_DEAD = 2500, STICK_DIR = 16384, TRIGGER_ON = 16384, RESCAN_MS = 1000 };
static SRWLOCK lock = SRWLOCK_INIT;
static int state; // 0 not started, 1 running, -1 disabled or SDL failed
@@ -30,12 +29,6 @@ static SDL_JoystickID sensor_pad; // the gamepad whose sensors the motion thr
static int sensor_ok; // ... and it has both sensors, enabled
static int motion_thread; // 0 not started, 1 running, -1 off (TOTK_MOTION=0, no SDL)
typedef struct { int vk; int bit; } KeyBtn;
static const KeyBtn key_buttons[] = {
{VK_LEFT, B_LEFT}, {VK_UP, B_UP}, {VK_RIGHT, B_RIGHT}, {VK_DOWN, B_DOWN}, {'E', B_A}, {VK_LSHIFT, B_B}, {VK_SPACE, B_X},
{'F', B_Y}, {'Q', B_ZL}, {'Z', B_ZR}, {VK_TAB, B_L}, {'R', B_R}, {'C', B_STICK_L}, {'V', B_STICK_R},
{VK_RETURN, B_PLUS}, {VK_BACK, B_MINUS},
};
// Gamepad buttons by position: south is Switch B, east A, west Y, north X (Nintendo layout).
static const struct { SDL_GamepadButton sdl; int bit; } pad_buttons[] = {
{SDL_GAMEPAD_BUTTON_SOUTH, B_B}, {SDL_GAMEPAD_BUTTON_EAST, B_A}, {SDL_GAMEPAD_BUTTON_WEST, B_Y},
@@ -172,8 +165,144 @@ static void rec_apply(uint64_t b, const int32_t sl[2], const int32_t sr[2]) {
if (wrote) fflush(rec);
}
// Win32 virtual key of a key id (the one place that knows them), 0 for an id without a key.
static int key_vk(int key) {
if (key >= KEY_A && key <= KEY_Z) return 'A' + (key - KEY_A);
if (key >= KEY_0 && key <= KEY_9) return '0' + (key - KEY_0);
switch (key) {
case KEY_SPACE: return VK_SPACE;
case KEY_TAB: return VK_TAB;
case KEY_LSHIFT: return VK_LSHIFT;
case KEY_LCTRL: return VK_LCONTROL;
case KEY_UP: return VK_UP;
case KEY_DOWN: return VK_DOWN;
case KEY_LEFT: return VK_LEFT;
case KEY_RIGHT: return VK_RIGHT;
case KEY_MOUSE_L: return VK_LBUTTON;
case KEY_MOUSE_R: return VK_RBUTTON;
case KEY_MOUSE_M: return VK_MBUTTON;
}
return 0;
}
// ---- mouse camera: raw motion accumulated by the window thread, one stick sample per presented frame
static volatile LONG mouse_dx, mouse_dy; // raw counts since the last frame sample
static volatile LONG cur_captured; // cursor hidden and confined to the client area
static volatile LONG cur_active; // WM_ACTIVATEAPP: the window's application is active
static volatile LONG cur_suspend; // F11 or a modal size or move loop under way
static SRWLOCK cur_lock = SRWLOCK_INIT; // serialises cursor_update (window thread, input_block callers)
static volatile LONG g_block; // text entry state, see input_block
static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off, read once
static float mouse_sens_get(void) {
if (mouse_sens >= 0) return mouse_sens;
const char *e = cfg_get("TOTK_MOUSE_SENS");
char *end;
double v = e ? strtod(e, &end) : 1;
if (!e || end == e || *end || v != v) v = 1;
mouse_sens = (float)(v < 0 ? 0 : v > 10 ? 10 : v);
return mouse_sens;
}
// Hide the cursor and confine it to the client area while the window is focused, not suspended, not behind a text entry
// and the mouse camera is on; release it otherwise. Safe from any thread.
static void cursor_update(HWND h) {
const char *in = cfg_get("TOTK_INPUT");
AcquireSRWLockExclusive(&cur_lock);
int want = h && cur_active && !cur_suspend && g_block != 1 && mouse_sens_get() > 0 && !(in && !strcmp(in, "none")) &&
GetForegroundWindow() == h && !IsIconic(h);
RECT r;
POINT tl = {0, 0};
if (want && GetClientRect(h, &r) && ClientToScreen(h, &tl)) {
RECT clip = {tl.x, tl.y, tl.x + r.right, tl.y + r.bottom};
ClipCursor(&clip);
if (!cur_captured) { InterlockedExchange(&mouse_dx, 0); InterlockedExchange(&mouse_dy, 0); }
InterlockedExchange(&cur_captured, 1);
} else {
if (cur_captured) ClipCursor(NULL);
InterlockedExchange(&cur_captured, 0);
}
ReleaseSRWLockExclusive(&cur_lock);
}
void input_cursor_suspend(int on) {
InterlockedExchange(&cur_suspend, on != 0);
cursor_update(gfx_window_handle());
}
// Window procedure hook (gfx_window.c calls it first). Returns 1 with *res set when the message is fully handled.
int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
switch (m) {
case WM_CREATE: {
RAWINPUTDEVICE rid = {.usUsagePage = 1, .usUsage = 2, .dwFlags = 0, .hwndTarget = h}; // generic mouse
if (!RegisterRawInputDevices(&rid, 1, sizeof rid)) rt_log("input: raw mouse registration failed (%lu)", GetLastError());
break;
}
case WM_INPUT: {
RAWINPUT ri;
UINT sz = sizeof ri;
if (cur_captured && GetRawInputData((HRAWINPUT)l, RID_INPUT, &ri, &sz, sizeof(RAWINPUTHEADER)) != (UINT)-1 &&
ri.header.dwType == RIM_TYPEMOUSE && !(ri.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
InterlockedAdd(&mouse_dx, ri.data.mouse.lLastX);
InterlockedAdd(&mouse_dy, ri.data.mouse.lLastY);
}
break; // DefWindowProc must see WM_INPUT for cleanup
}
case WM_SETCURSOR:
if (cur_captured && LOWORD(l) == HTCLIENT) { SetCursor(NULL); *res = TRUE; return 1; }
break;
case WM_ACTIVATEAPP:
InterlockedExchange(&cur_active, w != 0);
cursor_update(h);
break;
case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: case WM_MOVE:
cursor_update(h);
break;
case WM_ENTERSIZEMOVE:
input_cursor_suspend(1);
break;
case WM_EXITSIZEMOVE:
input_cursor_suspend(0);
break;
case WM_CLOSE:
InterlockedExchange(&cur_active, 0);
cursor_update(h);
break;
}
return 0;
}
static int key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; }
// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`.
static void mouse_camera(int32_t out[2]) {
static uint64_t frame = ~0ull;
static LARGE_INTEGER t0;
static int32_t held[2];
LARGE_INTEGER now, f;
QueryPerformanceCounter(&now);
QueryPerformanceFrequency(&f);
if (!cur_captured) {
InterlockedExchange(&mouse_dx, 0);
InterlockedExchange(&mouse_dy, 0);
held[0] = held[1] = 0;
frame = ~0ull;
} else {
uint64_t fr = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED);
double age = frame == ~0ull ? 0 : (double)(now.QuadPart - t0.QuadPart) / (double)f.QuadPart;
if (fr != frame) {
double dt = age < 0.004 ? 0.004 : age > 0.1 ? 0.1 : age;
input_mouse_stick(InterlockedExchange(&mouse_dx, 0), InterlockedExchange(&mouse_dy, 0), dt, mouse_sens_get(), held);
frame = fr;
t0 = now;
} else if (age > 0.1) {
held[0] = held[1] = 0; // frames stopped: do not hold a deflection
}
}
out[0] = held[0];
out[1] = held[1];
}
static int32_t axis(int16_t v) {
int32_t a = v < -STICK_MAX ? -STICK_MAX : v;
return a > -STICK_DEAD && a < STICK_DEAD ? 0 : a;
@@ -213,12 +342,6 @@ static void stick_bits(uint64_t *b, int32_t x, int32_t y, int first) {
if (y < -STICK_DIR) *b |= 1ull << (first + 3);
}
// Two keys as one axis; a diagonal is scaled to the unit circle.
static int32_t key_axis(int neg, int pos, int other) {
int d = key_down(pos) - key_down(neg);
return d * (other ? 23170 : STICK_MAX);
}
static void pick(int32_t *x, int32_t *y, int32_t kx, int32_t ky) {
int64_t a = (int64_t)*x * *x + (int64_t)*y * *y, b = (int64_t)kx * kx + (int64_t)ky * ky;
if (b > a) { *x = kx; *y = ky; }
@@ -246,12 +369,29 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
}
HWND w = gfx_window_handle();
if (w && w == GetForegroundWindow()) {
for (size_t i = 0; i < sizeof key_buttons / sizeof *key_buttons; i++)
if (key_down(key_buttons[i].vk)) b |= 1ull << key_buttons[i].bit;
int lh = key_down('A') || key_down('D'), lv = key_down('W') || key_down('S');
int rh = key_down('J') || key_down('L'), rv = key_down('I') || key_down('K');
pick(&sl[0], &sl[1], key_axis('A', 'D', lv), key_axis('S', 'W', lh));
pick(&sr[0], &sr[1], key_axis('J', 'L', rv), key_axis('K', 'I', rh));
uint8_t down[KEY_COUNT] = {0};
// Mouse buttons count only while the cursor is captured, and a button already held when the capture began
// (the click that refocused the window) is ignored until it is released.
static int was_captured;
static uint8_t mouse_ignore[KEY_COUNT];
int cap = cur_captured != 0;
for (int k = 1; k < KEY_COUNT; k++) {
int vk = key_vk(k);
down[k] = vk && key_down(vk);
if (k < KEY_MOUSE_L || k > KEY_MOUSE_M) continue;
if (cap && !was_captured) mouse_ignore[k] = down[k];
if (!down[k]) mouse_ignore[k] = 0;
if (!cap || mouse_ignore[k]) down[k] = 0;
}
was_captured = cap;
b |= input_map_buttons(down);
int32_t k[2];
input_map_stick(down, 0, k);
pick(&sl[0], &sl[1], k[0], k[1]);
input_map_stick(down, 1, k);
pick(&sr[0], &sr[1], k[0], k[1]);
mouse_camera(k);
pick(&sr[0], &sr[1], k[0], k[1]);
}
}
script_apply(&b, sl, sr);
@@ -264,9 +404,11 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
// Text entry (swkbd_win.c): while it is open the game reads no input, as behind the keyboard applet; after it closes
// the game reads none until every button and stick direction is released, so the press that closed it stays there.
static volatile LONG g_block; // 0 off, 1 text entry open, 2 closed, waiting for the release
void input_block(int on) { InterlockedExchange(&g_block, on ? 1 : 2); }
// g_block (above): 0 off, 1 text entry open, 2 closed, waiting for the release. The cursor is released while it is open.
void input_block(int on) {
InterlockedExchange(&g_block, on ? 1 : 2);
cursor_update(gfx_window_handle());
}
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
poll_merged(buttons, lx, ly, rx, ry);