diff --git a/nx2navi.ini.example b/nx2navi.ini.example index d4bef1bb..faa5a70b 100644 --- a/nx2navi.ini.example +++ b/nx2navi.ini.example @@ -782,6 +782,14 @@ # rumble_strength = 130 # rumble_curve = 0.6 # rumble_triggers = 0 +# HD rumble for a Switch Pro Controller, a Joy-Con or a pair of them: 1 sends the game's vibration to the controller as +# the game makes it, each side's low and high band with its own frequency and amplitude, in place of two motor +# strengths. rumble_strength still scales the amplitude (100 = exactly the game's; the controller's safe maximum is +# never passed) and rumble_curve does not apply. 0 (default), and every other gamepad: the motors, as before. Changes +# while the game runs take effect at once. rumble_hd_ms is the shortest time between two rumble reports in +# milliseconds (5 to 50, default 15): raise it if a controller on Bluetooth stutters or disconnects with HD rumble on. +# rumble_hd = 0 +# rumble_hd_ms = 15 # PlayStation 3 controller (DualShock 3), Windows: 1 reads its buttons, sticks and rumble directly from the controller # when no driver presents it to the game as a gamepad; 0 (default) leaves it to SDL and XInput. Changes while the game # runs take effect at once. diff --git a/runtime/boot.c b/runtime/boot.c index 12203c1c..1b7e75b6 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -21,6 +21,7 @@ #include "kernel.h" #include "ipc.h" #include "gfx.h" +#include "input.h" #include "mods.h" #include "nvn_api.h" #include "platform/platform.h" @@ -325,6 +326,7 @@ void rt_frame_presented(const tex_t *t, uint64_t n) { fflush(stdout); fflush(stderr); coop_shutdown(); // LEAVE and BYE to the room, before the process ends + input_rumble_hd_stop(); // a controller on HD rumble gets the neutral value before the exit fs_save_flush(); vk_pipeline_prewarm_marker_clear(); // an orderly end, not a driver crash in the boot's builds (vk_pipeline.c pm_skipped) vk_pipeline_save_exit(); // no-op without the Vulkan back end diff --git a/runtime/cfg.c b/runtime/cfg.c index 89db280b..f0ccdf94 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -68,7 +68,7 @@ static const char *const known[] = { "REFLEX", "RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_PIPE", "REPLAY_RUNS", "REPLAY_WORKERS", "RTSS", "RTSS_ENUM", "SCENE_SHARE", "PRESNAP_PLACE", "REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", - "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", + "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_HD", "RUMBLE_HD_MS", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", "SHADER_CACHE_FLUSH", "SHADER_CARRY", "SHADER_MEMO", "SHADOW_BULK_WRITE", "SHADOW_CHECK", "SHADOW_COMPARE", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_TABLE_STORES", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SVC_SLOW_MS", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_IDLE", "SPLIT_IN_PASS", "SPLIT_US", "SPV_MARK_TEST", "SPV_OVERRIDE", "STICK_DEADZONE", "STICK_SENS", @@ -123,7 +123,7 @@ static const struct { const char *key, *section; } sections[] = { {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"AUDIO_CHANNELS", "audio"}, {"AUDIO_DEVICE", "audio"}, {"MICROPHONE", "audio"}, {"MENU_SOUND_VOLUME", "audio"}, {"AUDIO_RAMP", "audio"}, {"AUDIO_CATCHUP", "audio"}, - {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, {"DS3", "input"}, + {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, {"RUMBLE_HD", "input"}, {"DS3", "input"}, {"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"}, {"STICK_SENS", "input"}, {"DEBUG_MENU", "input"}, {"MENU_CURSOR", "input"}, {"MOUSE_MODE", "input"}, {"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"}, @@ -241,6 +241,8 @@ static const CfgMeta metas[] = { {"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE}, {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "nintendo", "auto|nintendo|xbox|playstation", LIVE}, {"DS3", "0", "0|1", LIVE}, // input_ds3_win.c ds3_read: read a DualShock 3 directly; off: no HID scan + // input.c hd_setting: a Switch Pro Controller or Joy-Con gets the game's vibration values as they are + {"RUMBLE_HD", "0", "0|1", LIVE}, {"PROMPTS", "nintendo", "nintendo|xbox|playstation|steamdeck|pc", RESTART}, {"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", LIVE}, // camera_speed.c cam_speed_tick {"DEBUG_MENU", "0", "0|1", LIVE}, // ui/menu.cpp menu_debug_toggle diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index 06344f7f..a1f46b98 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -23,6 +23,7 @@ #include "fs.h" #include "gfx.h" #include "gfx_wsys.h" +#include "input.h" #include "nvn_api.h" #include "ov.h" #include "platform/platform.h" @@ -91,6 +92,7 @@ void gfx_window_closed(void) { prof_write(); // plat_exit runs no atexit handlers rtss_limit_restore(); // RivaTuner Statistics Server's profile as it was coop_shutdown(); // LEAVE and BYE to the room, before the process ends + input_rumble_hd_stop(); // a controller on HD rumble gets the neutral value: nothing renews or stops it after the exit fs_save_flush(); // last: the game's threads still run until plat_exit, and a Commit after this one is refused if (restart) { cfg_setenv("NX2NAVI_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) diff --git a/runtime/input.c b/runtime/input.c index 452183b9..1bb0cd33 100644 --- a/runtime/input.c +++ b/runtime/input.c @@ -3,8 +3,9 @@ // bindings are the tables in input_map.c (nx2navi.ini overrides them). The keyboard and the mouse come from the window // system's back end (input_wsys.h: input_win.c with Win32, input_sdl.c with SDL), which also 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`. +// The gamepad also rumbles (input_rumble; a Switch controller's linear actuators can take the game's own values instead, +// "HD rumble" below) 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 #include #include @@ -15,6 +16,7 @@ #include "cfg.h" #include "host.h" #include "input.h" +#include "input_hd_pair.h" #include "input_map.h" #include "input_wsys.h" #ifdef _WIN32 @@ -498,6 +500,242 @@ static int sdl_enter(void) { static void sdl_leave(void) { plat_mutex_unlock(&sdl_lock); } +// ---- HD rumble: the game's vibration values as they are, for a controller with linear actuators +// A Switch Pro Controller and a Joy-Con play a frequency and an amplitude per band, which is what the game sends +// (ov_input.c VibrationValue); SDL_RumbleGamepad drives them at two fixed frequencies. With NX2NAVI_RUMBLE_HD=1 (live, +// off by default) the primary gamepad, when it is one of these, gets the game's values in the controller's own rumble +// report (rumble_hd.c) and no dual-motor call any more (input_rumble): +// - HD_SDL, a Pro Controller or a single Joy-Con: SDL_SendGamepadEffect takes the report for these controllers and +// writes it with SDL's own report number, over USB and over Bluetooth. With the setting on, hd_probe tries the call +// with the neutral value when the gamepad becomes the primary, so the log says at once whether it is taken. With the +// setting off nothing is written: the controller is known by its ids, and the first report after the setting is +// turned on is the trial (hd_wrote; a refusal sends the gamepad back to its motors). +// - HD_PAIR, a left and a right Joy-Con that SDL presents as one gamepad: SDL refuses the call for that gamepad, so the +// reports go to the two HID devices directly (input_hd_pair.c). +// Every other gamepad keeps the motors' path, the Switch 2 controllers too (other product ids, another protocol). +// The game's thread only posts its newest values (input_rumble_hd). A thread of its own writes the reports (hd_main): +// every HD_TICK_NS while there is something to write it asks rumble_hd_due, which spaces the reports, keeps only the +// newest value, repeats a held one, and turns values the game stopped renewing into the neutral one, so a paused or +// frozen game does not leave the controller vibrating. The thread sleeps once the neutral value is out. The neutral +// value is also written when another gamepad becomes the primary (hd_pad_leave), when the setting is turned off +// (hd_tick) and before the process ends (input_rumble_hd_stop). +enum { HD_NONE, HD_SDL, HD_PAIR }; +enum { VID_NINTENDO = 0x057E, PID_JOYCON_LEFT = 0x2006, PID_JOYCON_RIGHT = 0x2007, PID_SWITCH_PRO = 0x2009, + PID_JOYCON_GRIP = 0x200E }; +#define HD_TICK_NS 5000000ull +static int pad_hd; // under lock: how the primary takes rumble reports (HD_*) +static volatile int32_t hd_shown; // any thread: 0 the primary takes none, 1 it takes them, 2 for its single actuator +static int sdl_rumbling; // under lock: the primary's motors were last set to more than 0 (input_rumble) +static PlatMutex hd_lock = PLAT_MUTEX_INIT; // guards the fields below; taken after `lock`, never before it +static PlatCond hd_go = PLAT_COND_INIT; +static RumbleHd hd; // what the primary is to get and what it got +static int hd_kick; // work for the thread: a post, or a pair that left +static int hd_pair_left; // the pair stopped being the primary: its two devices are to be closed +static int hd_ended; // input_rumble_hd_stop ran: nothing is written any more +static int hd_first_logged; // under lock: the primary's first report was logged (hd_wrote) +static volatile int32_t hd_thread; // 0 not started, 1 running, -1 it could not be started (set under hd_lock) + +// NX2NAVI_RUMBLE_HD is on and rumble is not off altogether (NX2NAVI_RUMBLE=0); live (cfg_version). Any thread. +static int hd_setting(void) { + static volatile int32_t on = -1; + static volatile uint32_t seen; + unsigned ver = cfg_version(); + if (__atomic_load_n(&on, __ATOMIC_RELAXED) < 0 || ver != __atomic_load_n(&seen, __ATOMIC_RELAXED)) { + const char *all = cfg_get("NX2NAVI_RUMBLE"); + __atomic_store_n(&on, cfg_bool("NX2NAVI_RUMBLE_HD") && !(all && !strcmp(all, "0")), __ATOMIC_RELAXED); + __atomic_store_n(&seen, ver, __ATOMIC_RELAXED); + } + return __atomic_load_n(&on, __ATOMIC_RELAXED); +} + +// The time between two reports: NX2NAVI_RUMBLE_HD_MS, 5 to 50 ms, RUMBLE_HD_GAP_NS when unset; live. The HD thread only. +static uint64_t hd_gap_ns(void) { + static uint64_t gap = RUMBLE_HD_GAP_NS; + static unsigned seen = ~0u; + unsigned ver = cfg_version(); + if (ver == seen) return gap; + seen = ver; + const char *e = cfg_get("NX2NAVI_RUMBLE_HD_MS"); + long ms = e && *e ? strtol(e, NULL, 10) : 0; + uint64_t set = ms ? (uint64_t)(ms < 5 ? 5 : ms > 50 ? 50 : ms) * 1000000u : RUMBLE_HD_GAP_NS; + if (set != gap) rt_log("input: HD rumble: a report at most every %llu ms", (unsigned long long)(set / 1000000u)); + return gap = set; +} + +// Under lock and sdl_lock: how gamepad p takes rumble reports (HD_*), with *one set for a single actuator and the +// words for the log in how. The controllers are known by Nintendo's vendor id, their product ids and the kind SDL +// reads from the controller itself: a pad of another make that only looks like one to SDL stays on its motors. +static int hd_probe(SDL_Gamepad *p, int *one, char *how, size_t cap) { + *one = 0; + uint16_t vid = SDL_GetGamepadVendor(p), pid = SDL_GetGamepadProduct(p); + SDL_GamepadType t = SDL_GetRealGamepadType(p); + int pro = vid == VID_NINTENDO && pid == PID_SWITCH_PRO && t == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO; + int single = vid == VID_NINTENDO && (pid == PID_JOYCON_LEFT || pid == PID_JOYCON_RIGHT || pid == PID_JOYCON_GRIP) && + (t == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT || t == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT); + if (t == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR) { + if (hd_pair_find()) { + snprintf(how, cap, "a Joy-Con pair, written to its two HID devices"); + return HD_PAIR; + } + snprintf(how, cap, "a Joy-Con pair whose two Joy-Con are not both listed as HID devices"); + return HD_NONE; + } + if (!pro && !single) { + snprintf(how, cap, "%04x:%04x is not a Switch Pro Controller or Joy-Con", vid, pid); + return HD_NONE; + } + const char *what = single ? "a single Joy-Con, one actuator" : "a Pro Controller"; + *one = single; + if (!hd_setting()) { // off: nothing is written to the controller + snprintf(how, cap, "%s, through SDL, whose driver is asked once rumble_hd is 1", what); + return HD_SDL; + } + uint8_t r[RUMBLE_HD_REPORT]; + rumble_hd_report(rumble_hd_neutral, 0, r, sizeof r); + if (!SDL_SendGamepadEffect(p, r, sizeof r)) { + snprintf(how, cap, "%s, but its gamepad driver takes no rumble data: %s", what, SDL_GetError()); + return HD_NONE; + } + snprintf(how, cap, "%s, through SDL", what); + return HD_SDL; +} + +// Under lock, and under sdl_lock when connected is set: the primary stops being the primary (another gamepad takes +// over, or it went away). A controller the HD path left vibrating gets the neutral value, and what was written to it +// does not count for the next primary. +static void hd_pad_leave(int connected) { + if (!pad) return; + plat_mutex_lock(&hd_lock); + int buzzing = rumble_hd_buzzing(&hd); + rumble_hd_forget(&hd); + if (pad_hd == HD_PAIR) { // the HD thread closes the two devices, after a neutral report to each + hd_pair_left = 1, hd_kick = 1; + plat_cond_signal(&hd_go); + } + plat_mutex_unlock(&hd_lock); + if (pad_hd == HD_SDL && buzzing && connected) { + uint8_t r[RUMBLE_HD_REPORT]; + rumble_hd_report(rumble_hd_neutral, 0, r, sizeof r); + SDL_SendGamepadEffect(pad, r, sizeof r); + } + pad_hd = HD_NONE, sdl_rumbling = 0, hd_first_logged = 0; + __atomic_store_n(&hd_shown, 0, __ATOMIC_RELAXED); +} + +// Under lock: the report with data d was written at `now` (ok), or the controller or its driver did not take it: the +// gamepad then goes back to its motors until it becomes the primary again. The primary's first report is logged with +// its bytes, so a log shows that the path is in use and what the controller was sent. +static void hd_wrote(int ok, const uint8_t d[RUMBLE_HD_DATA], uint64_t now, const char *err) { + plat_mutex_lock(&hd_lock); + if (ok) rumble_hd_sent(&hd, d, now); + else rumble_hd_forget(&hd); + plat_mutex_unlock(&hd_lock); + if (ok) { + if (!hd_first_logged) + rt_log("input: HD rumble: first report written (left %02x %02x %02x %02x, right %02x %02x %02x %02x)", d[0], d[1], + d[2], d[3], d[4], d[5], d[6], d[7]); + hd_first_logged = 1; + return; + } + rt_log("input: HD rumble: a report for the gamepad was not taken (%s); it rumbles through its motors from here on", err); + pad_hd = HD_NONE; + __atomic_store_n(&hd_shown, 0, __ATOMIC_RELAXED); +} + +// One round of the HD rumble thread: writes the report that is due, if one is. 1 when nothing is left to write until +// the game posts again. +static int hd_tick(void) { + uint8_t d[RUMBLE_HD_DATA]; + uint64_t now = plat_now_ns(), gap = hd_gap_ns(); + plat_mutex_lock(&lock); + int kind = pad ? pad_hd : HD_NONE, on = kind != HD_NONE && hd_setting(); + plat_mutex_lock(&hd_lock); + int close_pair = hd_pair_left; + hd_pair_left = 0; + int due = !hd_ended && kind != HD_NONE && rumble_hd_due(&hd, on, now, gap, d); + int idle = hd_ended || kind == HD_NONE || (!due && rumble_hd_idle(&hd, on, now)); + plat_mutex_unlock(&hd_lock); + if (due && kind == HD_SDL && plat_mutex_trylock(&sdl_lock)) { // a round later while SDL updates + if (SDL_GamepadConnected(pad)) { // a gamepad that went away is let go by the next scan (scan_pads) + uint8_t r[RUMBLE_HD_REPORT]; + rumble_hd_report(d, 0, r, sizeof r); // SDL puts its own number in + int ok = SDL_SendGamepadEffect(pad, r, sizeof r); + hd_wrote(ok, d, now, ok ? "" : SDL_GetError()); + } + sdl_leave(); + } + plat_mutex_unlock(&lock); + if (close_pair) hd_pair_close(1, 0); + if (due && kind == HD_PAIR) { + int ok = hd_pair_write(d); // waits for the two writes, so not under lock + plat_mutex_lock(&lock); + if (pad && pad_hd == HD_PAIR) hd_wrote(ok, d, now, ok ? "" : SDL_GetError()); // unless the pair left meanwhile + plat_mutex_unlock(&lock); + } + return idle; +} + +static void hd_main(void *arg) { + (void)arg; + for (int idle = 1;;) { + plat_mutex_lock(&hd_lock); + while (idle && !hd_kick) plat_cond_wait(&hd_go, &hd_lock); + hd_kick = 0; + plat_mutex_unlock(&hd_lock); + if (!idle) plat_wait_ns(HD_TICK_NS); + idle = hd_tick(); + } +} + +int input_rumble_hd_available(void) { return __atomic_load_n(&hd_shown, __ATOMIC_RELAXED) != 0; } + +int input_rumble_hd_on(void) { + return __atomic_load_n(&hd_shown, __ATOMIC_RELAXED) && __atomic_load_n(&hd_thread, __ATOMIC_RELAXED) >= 0 && hd_setting(); +} + +void input_rumble_hd(const RumbleHdValue v[2], const int live[2], float strength) { + int32_t shown = __atomic_load_n(&hd_shown, __ATOMIC_RELAXED); + if (!shown) return; + uint8_t d[RUMBLE_HD_DATA]; + rumble_hd_data(v, live, strength, shown == 2, d); + plat_mutex_lock(&hd_lock); + rumble_hd_post(&hd, d, plat_now_ns()); + if (!hd_thread) { + int ok = plat_thread_spawn(hd_main, NULL, "rumble", 0); + __atomic_store_n(&hd_thread, ok ? 1 : -1, __ATOMIC_RELAXED); + if (!ok) rt_log("input: HD rumble: its thread could not be started; the gamepad rumbles through its motors"); + } + hd_kick = 1; + plat_cond_signal(&hd_go); + plat_mutex_unlock(&hd_lock); +} + +void input_rumble_hd_stop(void) { + int got = 0, wait = 0; + // The locks are tried for a while and not waited for: a thread of the game may hold one for good by now. + for (int i = 0; i < 50 && !(got = plat_mutex_trylock(&lock)); i++) plat_wait_ns(1000000); + if (!got) return; + plat_mutex_lock(&hd_lock); + hd_ended = 1; + int buzzing = rumble_hd_buzzing(&hd); + rumble_hd_forget(&hd); + plat_mutex_unlock(&hd_lock); + int pair = pad && pad_hd == HD_PAIR; + if (pad && pad_hd == HD_SDL && buzzing) { + got = 0; + for (int i = 0; i < 50 && !(got = plat_mutex_trylock(&sdl_lock)); i++) plat_wait_ns(1000000); + if (got) { + uint8_t r[RUMBLE_HD_REPORT]; + rumble_hd_report(rumble_hd_neutral, 0, r, sizeof r); + wait = SDL_GamepadConnected(pad) && SDL_SendGamepadEffect(pad, r, sizeof r); + sdl_leave(); + } + } + plat_mutex_unlock(&lock); + if (pair) hd_pair_close(1, 100); + if (wait) plat_wait_ns(30000000); // SDL writes the report on a thread of its own: time for it before the process ends +} + // Every connected gamepad is kept open; `pad` is the one the game reads (and the one that rumbles and feeds motion): // the first one found, then whichever one the player presses (pad_follow). Taking only the first gamepad SDL lists // left the game deaf when that one was a device nobody holds: a virtual pad of Steam Input or DS4Windows, a wheel, a @@ -510,6 +748,7 @@ static int pad_pressed_logged; // the primary's first press was logged (on // Under lock: makes p the gamepad the game reads, with its labels, rumble and layout; logs it. static void pad_primary(SDL_Gamepad *p, const char *why) { + hd_pad_leave(1); pad = p; sensor_pad = 0, sensor_ok = 0, pad_pressed_logged = 0; pad_rumble = SDL_GetBooleanProperty(SDL_GetGamepadProperties(pad), SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); @@ -531,6 +770,12 @@ static void pad_primary(SDL_Gamepad *p, const char *why) { rt_log("input: gamepad \"%s\" %s (%s, %s, east button %s)", SDL_GetGamepadName(pad), why, pad_rumble ? "rumble" : "no rumble", motion ? "gyro and accelerometer" : "no motion sensors", pad_east_a ? "labelled A" : "not labelled A"); + char how[200]; + int one; + pad_hd = hd_probe(pad, &one, how, sizeof how); + __atomic_store_n(&hd_shown, pad_hd == HD_NONE ? 0 : 1 + one, __ATOMIC_RELAXED); + rt_log("input: HD rumble %s for this gamepad: %s (rumble_hd = %s)", pad_hd == HD_NONE ? "not available" : "available", + how, cfg_value("NX2NAVI_RUMBLE_HD")); } // Joysticks SDL has no gamepad mapping for are not gamepads to it, and this file opens gamepads only. Known ones get a @@ -589,6 +834,7 @@ static void scan_pads(void) { if (SDL_GamepadConnected(pads[i])) { i++; continue; } rt_log("input: gamepad \"%s\" disconnected", SDL_GetGamepadName(pads[i]) ? SDL_GetGamepadName(pads[i]) : "?"); if (pads[i] == pad) { + hd_pad_leave(0); pad = NULL, sensor_pad = 0, sensor_ok = 0; plat_xchg32(&pad_layout_shown, -1); for (int k = 0; k < 4; k++) plat_xchg32(&pad_labels[k], PAD_LABEL_NONE); @@ -1183,8 +1429,17 @@ int input_rumble(uint16_t low, uint16_t high, uint32_t ms) { if (triggers < 0 || seen != cfg_version()) seen = cfg_version(), triggers = input_rumble_triggers_enabled(); plat_mutex_lock(&lock); if (state == 1 && pad && pad_rumble && plat_mutex_trylock(&sdl_lock)) { // one skipped while SDL updates - ok = SDL_RumbleGamepad(pad, low, high, ms); - if (triggers) SDL_RumbleGamepadTriggers(pad, high, high, ms); // unsupported pads return false: ignored + if (pad_hd != HD_NONE && input_rumble_hd_on()) { + // HD rumble has this gamepad (hd_tick): its motors are stopped once and get nothing more, so the reports + // with the game's values are the only rumble it is sent + if (sdl_rumbling) SDL_RumbleGamepad(pad, 0, 0, 0); + sdl_rumbling = 0; + ok = 1; + } else { + ok = SDL_RumbleGamepad(pad, low, high, ms); + sdl_rumbling = low || high; + if (triggers) SDL_RumbleGamepadTriggers(pad, high, high, ms); // unsupported pads return false: ignored + } sdl_leave(); } #ifdef _WIN32 diff --git a/runtime/input.h b/runtime/input.h index 9e0fea87..410c17e0 100644 --- a/runtime/input.h +++ b/runtime/input.h @@ -2,6 +2,8 @@ #pragma once #include +#include "rumble_hd.h" + // Bits of 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). // Sticks are -32767..32767, up is +y. NX2NAVI_INPUT=none reports no input. Callable from any thread. @@ -88,6 +90,19 @@ int input_rumble(uint16_t low, uint16_t high, uint32_t ms); uint16_t rumble_motor(float a, float curve, float strength); // NX2NAVI_RUMBLE_TRIGGERS=1: input_rumble also drives the impulse triggers (Xbox) with the high motor's value. int input_rumble_triggers_enabled(void); +// HD rumble (input.c "HD rumble", rumble_hd.h): the game's vibration values as they are, for a gamepad with linear +// actuators (a Switch Pro Controller, a Joy-Con or a pair of them). All callable from any thread. +// input_rumble_hd_available: the gamepad the game reads is one of these (the menu's row). +// input_rumble_hd_on: ... and NX2NAVI_RUMBLE_HD is 1 (live) and NX2NAVI_RUMBLE is not 0: input_rumble then leaves that +// gamepad's motors alone, and the caller posts every new value with input_rumble_hd. +// input_rumble_hd: the game's newest value per side (v[0] left, v[1] right; live[s] 0: that side is at rest), the +// amplitudes scaled by strength (1 = as they are). Returns at once: a thread of input.c writes the reports, the newest +// value only, and the neutral value once the game stops posting. +// input_rumble_hd_stop: before the process ends, the neutral value for a controller that is still vibrating. +int input_rumble_hd_available(void); +int input_rumble_hd_on(void); +void input_rumble_hd(const RumbleHdValue v[2], const int live[2], float strength); +void input_rumble_hd_stop(void); // Motion (NX2NAVI_MOTION=0 turns it off, live). input_motion_start starts the sensor thread once: every 4 ms it reads the // gamepad's gyro and accelerometer (when it has them) and feeds motion_global(). Callable from any thread. diff --git a/runtime/input_hd_pair.c b/runtime/input_hd_pair.c new file mode 100644 index 00000000..2cee6eb5 --- /dev/null +++ b/runtime/input_hd_pair.c @@ -0,0 +1,113 @@ +// HD rumble for a pair of Joy-Con (input_hd_pair.h). +// +// SDL presents a left and a right Joy-Con as one gamepad and drives its two halves at fixed frequencies; the call +// that hands a Switch controller raw rumble data (input.c hd_tick, SDL_SendGamepadEffect) is refused for the combined +// gamepad. So for a pair this file writes the rumble output report itself, through SDL's HID interface, to the two +// HID devices SDL also has open: +// - Each Joy-Con is opened a second time (the system shares a HID device between handles) and gets output report +// 0x10 (rumble_hd.c rumble_hd_report), 49 bytes, the length of a Bluetooth output report. A Joy-Con by itself has no +// other connection: its USB charging grip is another product id and is left to the motors' path. +// - The report carries a number that goes round 0..15. Each handle here counts its own; the controller plays a report +// whatever number it carries, so SDL's count for its own reports is not disturbed. +// - While HD rumble is on, input.c makes no dual-motor call for the gamepad (input_rumble), so these reports are the +// only rumble the Joy-Con get. SDL still writes its own commands (player lights, sensors on), which carry the rumble +// value SDL last set, the one at rest: such a command silences the actuators until the next report from here, at most +// RUMBLE_HD_REFRESH_NS later. +// - A report holds a left and a right value and a Joy-Con plays the one of its side; both halves get the same value +// here, so nothing depends on which half a Joy-Con reads. +// With several pairs connected the first left and the first right Joy-Con listed are taken. +#include +#include +#include +#include + +#include "input_hd_pair.h" +#include "platform/platform.h" + +enum { VID_NINTENDO = 0x057E, PID_JOYCON_LEFT = 0x2006, PID_JOYCON_RIGHT = 0x2007, BLUETOOTH_REPORT = 49 }; + +static PlatMutex path_lock = PLAT_MUTEX_INIT; // guards path[] +static char *path[2]; // the HID paths hd_pair_find saw last: left, right +static PlatMutex dev_lock = PLAT_MUTEX_INIT; // guards dev[] and number[], and is held across a write +static SDL_hid_device *dev[2]; +static unsigned number[2]; // the next report's number, per device + +int hd_pair_find(void) { + char *found[2] = {NULL, NULL}; + SDL_hid_device_info *list = SDL_hid_enumerate(VID_NINTENDO, 0); + for (SDL_hid_device_info *d = list; d; d = d->next) { + int s = d->product_id == PID_JOYCON_LEFT ? 0 : d->product_id == PID_JOYCON_RIGHT ? 1 : -1; + if (s >= 0 && !found[s] && d->path) found[s] = strdup(d->path); + } + SDL_hid_free_enumeration(list); + int both = found[0] && found[1]; + plat_mutex_lock(&path_lock); + for (int s = 0; s < 2; s++) { + free(path[s]); + path[s] = both ? found[s] : NULL; + if (!both) free(found[s]); + } + plat_mutex_unlock(&path_lock); + return both; +} + +// Under dev_lock. +static void close_devices(void) { + for (int s = 0; s < 2; s++) { + if (dev[s]) SDL_hid_close(dev[s]); + dev[s] = NULL; + } +} + +// Under dev_lock: one report with v in both halves to device s. 1 when the whole report was taken. +static int write_side(int s, const uint8_t v[RUMBLE_HD_SIDE]) { + uint8_t data[RUMBLE_HD_DATA], report[BLUETOOTH_REPORT]; + memcpy(data, v, RUMBLE_HD_SIDE); + memcpy(data + RUMBLE_HD_SIDE, v, RUMBLE_HD_SIDE); + rumble_hd_report(data, number[s]++, report, sizeof report); + return SDL_hid_write(dev[s], report, sizeof report) == (int)sizeof report; +} + +int hd_pair_write(const uint8_t data[RUMBLE_HD_DATA]) { + int ok = 1; + plat_mutex_lock(&dev_lock); + if (!dev[0] || !dev[1]) { + close_devices(); + char *p[2]; + plat_mutex_lock(&path_lock); + for (int s = 0; s < 2; s++) p[s] = path[s] ? strdup(path[s]) : NULL; + plat_mutex_unlock(&path_lock); + if (!p[0] || !p[1]) ok = 0, SDL_SetError("the two Joy-Con are not both listed as HID devices"); + for (int s = 0; s < 2 && ok; s++) { + dev[s] = SDL_hid_open_path(p[s]); + number[s] = 0; + if (!dev[s]) ok = 0; + } + free(p[0]); + free(p[1]); + } + for (int s = 0; s < 2 && ok; s++) ok = write_side(s, data + s * RUMBLE_HD_SIDE); + if (!ok) close_devices(); + plat_mutex_unlock(&dev_lock); + return ok; +} + +int hd_pair_is_open(void) { + plat_mutex_lock(&dev_lock); + int open = dev[0] && dev[1]; + plat_mutex_unlock(&dev_lock); + return open; +} + +void hd_pair_close(int neutral, unsigned wait_ms) { + if (!wait_ms) plat_mutex_lock(&dev_lock); + else { + int got = 0; + for (unsigned i = 0; i < wait_ms && !(got = plat_mutex_trylock(&dev_lock)); i++) plat_wait_ns(1000000); + if (!got) return; + } + for (int s = 0; s < 2 && neutral; s++) + if (dev[s]) write_side(s, rumble_hd_neutral); + close_devices(); + plat_mutex_unlock(&dev_lock); +} diff --git a/runtime/input_hd_pair.h b/runtime/input_hd_pair.h new file mode 100644 index 00000000..f17e57f4 --- /dev/null +++ b/runtime/input_hd_pair.h @@ -0,0 +1,19 @@ +// HD rumble for a pair of Joy-Con (input_hd_pair.c): the rumble output report written to each Joy-Con's HID device, +// next to SDL, which reads the two as one gamepad and takes no rumble data for it. input.c calls it (hd_tick). +#pragma once +#include + +#include "rumble_hd.h" + +// Looks for a left and a right Joy-Con among the HID devices and keeps their paths for hd_pair_write. 1 when both are +// there. Opens nothing. Any thread; takes the time of a HID device listing. +int hd_pair_find(void); +// Writes one rumble report to each Joy-Con: the left half of data to the left one, the right half to the right one. +// The first call after hd_pair_find opens the two devices. 0 when a device could not be opened or written (both are +// closed then, and SDL's error text says why). Blocks for as long as the writes take: the HD rumble thread only. +int hd_pair_write(const uint8_t data[RUMBLE_HD_DATA]); +// 1 while the two devices are open. +int hd_pair_is_open(void); +// Writes the neutral value to both Joy-Con, when neutral is set, and closes them. wait_ms: how long to wait for a +// write that is still running on another thread before giving up (the process is ending); 0 waits for it. +void hd_pair_close(int neutral, unsigned wait_ms); diff --git a/runtime/ov_input.c b/runtime/ov_input.c index 76cf70bd..582cb2e2 100644 --- a/runtime/ov_input.c +++ b/runtime/ov_input.c @@ -3,7 +3,8 @@ // runtime/input_win.c; nothing pressed with NX2NAVI_INPUT=none). Docked (default) it is a full-key controller as player 1 (id 0, style bit 0); with // NX2NAVI_OPERATION_MODE=handheld it is the handheld controller (id 0x20, style bit 1) and player 1 is not connected, // which is the controller the game reads in that mode. Mouse and keyboard report no input. The controller has two -// vibration devices (left, right) played on the gamepad's motors (NX2NAVI_RUMBLE=0: none) and a six-axis sensor fed by +// vibration devices (left, right), played on the gamepad's motors or, with NX2NAVI_RUMBLE_HD=1, as they are on a Switch +// controller's linear actuators (NX2NAVI_RUMBLE=0: no devices), and a six-axis sensor fed by // the gamepad's gyro and accelerometer (NX2NAVI_MOTION=0, live: reads at rest). State layouts follow the HID shared-memory format. #include #include @@ -297,6 +298,22 @@ static float clamp01(float v) { return v > 0 ? (v < 1 ? v : 1) : 0; } // NaN - // neutral frequency), all at 320 Hz and above (the high band's), log scale between. static float light_share(float f) { return f > 160 ? (f < 320 ? log2f(f / 160) : 1) : 0; } +// Switch HD rumble as it is, for a gamepad whose actuators take it (input.h input_rumble_hd_on; NX2NAVI_RUMBLE_HD): +// each side's newest value goes on with both bands' frequency and amplitude, the amplitude scaled by the rumble +// strength alone (100 % = as the game sent it; the curve is for motors). A side the game has not updated for 250 ms, +// or any side while vibration is not permitted, is at rest. input.c writes the reports and no longer drives that +// gamepad's motors, so rumble_update's own call below reaches only the DualShock 3 reader then. Under vib_lock. +static void hd_update(uint64_t now) { + if (!input_rumble_hd_on()) return; + RumbleHdValue v[2]; + int live[2]; + for (int s = 0; s < 2; s++) { + v[s] = (RumbleHdValue){vib_last[s].amp_low, vib_last[s].freq_low, vib_last[s].amp_high, vib_last[s].freq_high}; + live[s] = vib_allowed && vib_at[s] && now - vib_at[s] <= RUMBLE_STALE_NS; + } + input_rumble_hd(v, live, rumble_strength); +} + // Switch HD rumble -> SDL_RumbleGamepad. Each side's two bands split by frequency between the heavy (low) and the light // (high) motor (light_share) and add up as energy per motor (root of the summed squares); the stronger side drives each // motor. A side the game has not updated for 250 ms is silent. Each send lasts 250 ms and is renewed every 50 ms while @@ -304,6 +321,7 @@ static float light_share(float f) { return f > 160 ? (f < 320 ? log2f(f / 160) : static void rumble_update(uint64_t now) { float heavy = 0, light = 0; rumble_cfg(); + hd_update(now); for (int s = 0; s < 2 && vib_allowed; s++) { if (!vib_at[s] || now - vib_at[s] > RUMBLE_STALE_NS) continue; const VibrationValue *v = &vib_last[s];