Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions native/common/hook_protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
namespace inputsplit::proto {

constexpr uint32_t kMagic = 0x4C505349; // "ISPL" in little-endian
constexpr uint16_t kProtocolVersion = 6; // 2: DirectInput / Raw Input counters, 3: frame stats,
// 4: tuning, 5: player order, 6: pad bridge
constexpr uint16_t kProtocolVersion = 7; // 2: DirectInput / Raw Input counters, 3: frame stats,
// 4: tuning, 5: player order, 6: pad bridge,
// 7: keys in tuning

// Pipe name prefix; the game PID (decimal) is appended.
constexpr wchar_t kPipePrefix[] = L"\\\\.\\pipe\\InputSplit.Hook.";
Expand Down Expand Up @@ -118,10 +119,28 @@ struct TuningMessage {
// Without slot lock (the game reads every controller): the physical slot behind the
// game's player 1..4. Identity (0, 1, 2, 3) = Windows' own order.
uint8_t playerSlots[4];
// Keys pressed in the game by the controller (games without controller support): a
// virtual-key code per KeyBinding, 0 = none. All zeros = off.
uint8_t keyMap[24];
uint32_t reserved2;
};
constexpr uint8_t kButtonOff = 0xFF;

// Indexes into TuningMessage::keyMap: 0..15 are the XInput button bits, then these.
enum KeyBinding : uint8_t {
kKeyLeftTrigger = 16,
kKeyRightTrigger = 17,
kKeyStickUp = 18,
kKeyStickDown = 19,
kKeyStickLeft = 20,
kKeyStickRight = 21,
kKeyBindings = 22,
};

// Set in lParam of the keyboard messages InputSplit posts for those keys (a bit Windows
// leaves reserved), so the keyboard block lets them through.
constexpr uint32_t kSyntheticKeyBit = 1u << 25;

struct StatusMessage {
Header header;
uint32_t requested; // Feature bits currently requested
Expand Down Expand Up @@ -197,7 +216,7 @@ static_assert(sizeof(Header) == 16, "Header layout changed");
static_assert(sizeof(HelloMessage) == 40, "HelloMessage layout changed");
static_assert(sizeof(ConfigureMessage) == 32, "ConfigureMessage layout changed");
static_assert(sizeof(FrameStatsMessage) == 24, "FrameStatsMessage layout changed");
static_assert(sizeof(TuningMessage) == 48, "TuningMessage layout changed");
static_assert(sizeof(TuningMessage) == 72, "TuningMessage layout changed");
static_assert(sizeof(BridgedPad) == 40, "BridgedPad layout changed");
static_assert(sizeof(PadBridgeMemory) == 168, "PadBridgeMemory layout changed");
static_assert(sizeof(StatusMessage) == 160, "StatusMessage layout changed");
Expand Down
6 changes: 6 additions & 0 deletions native/helper/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ Json Handle(const std::string& method, const Json& params) {
tuning.playerSlots[i] = slots[i].get<uint8_t>();
}
}
if (params.contains("keyMap")) {
const Json& keys = params["keyMap"];
for (int i = 0; i < proto::kKeyBindings && i < static_cast<int>(keys.size()); ++i) {
tuning.keyMap[i] = keys[i].get<uint8_t>();
}
}
if (!SessionManager::Instance().SetTuning(params.at("sessionId").get<int>(), tuning)) {
throw HelperError{"sessionNotFound", "No such session."};
}
Expand Down
1 change: 1 addition & 0 deletions native/hook/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ add_library(InputSplitHook SHARED
detection.cpp
frame_stats.cpp
tuning.cpp
key_emulation.cpp
minhook_util.cpp
log.cpp
hook.def)
Expand Down
6 changes: 6 additions & 0 deletions native/hook/activation_shield.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ LRESULT CALLBACK ShieldProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
return result;
}

// Keys from the controller (key_emulation.cpp): delivered without the marker bit.
if (IsKeyboardMessage(msg) && (lParam & proto::kSyntheticKeyBit)) {
lParam &= ~static_cast<LPARAM>(proto::kSyntheticKeyBit);
return callOriginal();
}

LRESULT syncResult = 0;
if (HandleRawInputSyncMessage(msg, syncResult)) return syncResult;

Expand Down
8 changes: 8 additions & 0 deletions native/hook/input_block.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ void FilterMessage(MSG* msg) {
if (msg == nullptr) return;
bool hide = false;
if (IsKeyboardMessage(msg->message)) {
// Keys from the controller (key_emulation.cpp) pass; the window procedure removes the
// marker. TranslateMessage copies it into the WM_CHAR it makes, so those pass too.
if (msg->lParam & proto::kSyntheticKeyBit) return;
hide = IsActive(proto::kFeatureBlockKeyboard);
if (hide) Count(g_counters.blockedKeyboard);
} else if (IsMouseMessage(msg->message)) {
Expand Down Expand Up @@ -101,6 +104,7 @@ BOOL WINAPI DetourPeekMessageA(LPMSG msg, HWND hwnd, UINT min, UINT max, UINT re
// --- 2. Key state polling ---------------------------------------------------------------

SHORT WINAPI DetourGetAsyncKeyState(int vk) {
if (SyntheticKeyDown(vk)) return static_cast<SHORT>(0x8000);
SHORT real = g_realGetAsyncKeyState(vk);
if (real != 0 && ShouldHideKey(vk)) {
Count(IsMouseButtonKey(vk) ? g_counters.blockedMouse : g_counters.blockedKeyboard);
Expand All @@ -110,6 +114,7 @@ SHORT WINAPI DetourGetAsyncKeyState(int vk) {
}

SHORT WINAPI DetourGetKeyState(int vk) {
if (SyntheticKeyDown(vk)) return static_cast<SHORT>(0x8000);
SHORT real = g_realGetKeyState(vk);
if (real != 0 && ShouldHideKey(vk)) {
return 0; // not counted: GetAsyncKeyState already counts real presses
Expand All @@ -127,6 +132,9 @@ BOOL WINAPI DetourGetKeyboardState(PBYTE keys) {
if (IsMouseButtonKey(vk) ? hideMouse : hideKeyboard) keys[vk] = 0;
}
}
for (int vk = 1; vk < 256; ++vk) {
if (SyntheticKeyDown(vk)) keys[vk] |= 0x80;
}
}
return result;
}
Expand Down
137 changes: 137 additions & 0 deletions native/hook/key_emulation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// key_emulation.cpp — the controller presses keys inside the game, for games that only
// understand a keyboard (InputSplit's own).
//
// A thread reads the game's controller about 125 times per second and, for every bound
// button, trigger or left-stick direction that changes, posts WM_KEYDOWN / WM_KEYUP to the
// game window. The messages carry kSyntheticKeyBit, so the keyboard block lets them through
// while the shared keyboard stays hidden (input_block.cpp, activation_shield.cpp). Key-state
// queries (GetAsyncKeyState & co.) report these keys as pressed. Nothing is sent to other
// programs: Windows' own input queue (SendInput) is never used.
//
// Not covered: games that read the keyboard through Raw Input or DirectInput.
#include "modules.h"

#include <atomic>

#include "hook_state.h"
#include "log.h"

namespace inputsplit::hook {
namespace {

std::atomic<uint8_t> g_keyMap[proto::kKeyBindings];
std::atomic<bool> g_enabled{false};
std::atomic<bool> g_down[256]; // keys this module holds down in the game
bool g_threadStarted = false; // pipe thread only

constexpr int kTriggerOn = 64, kTriggerOff = 40; // 0..255
constexpr int kStickOn = 16000, kStickOff = 11000; // thumb units

bool IsExtendedKey(UINT vk) {
switch (vk) {
case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN:
case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT:
case VK_RCONTROL: case VK_RMENU: case VK_DIVIDE: case VK_NUMLOCK:
return true;
default:
return false;
}
}

void PostKey(UINT vk, bool down) {
g_down[vk].store(down, std::memory_order_relaxed);
HWND game = GameWindow();
if (game == nullptr) return;
LPARAM lParam = 1 | (static_cast<LPARAM>(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) & 0xFF) << 16) |
static_cast<LPARAM>(proto::kSyntheticKeyBit);
if (IsExtendedKey(vk)) lParam |= 1 << 24;
if (!down) lParam |= (static_cast<LPARAM>(1) << 30) | (static_cast<LPARAM>(1) << 31);
PostMessageW(game, down ? WM_KEYDOWN : WM_KEYUP, vk, lParam);
}

void ReleaseAll() {
for (UINT vk = 1; vk < 256; ++vk) {
if (g_down[vk].load(std::memory_order_relaxed)) PostKey(vk, false);
}
}

// Which bindings are held, with a gap between "press" and "release" so a stick resting
// near the threshold does not flicker the key.
void ReadBindings(const XINPUT_GAMEPAD& pad, bool held[proto::kKeyBindings]) {
for (int bit = 0; bit < 16; ++bit) held[bit] = (pad.wButtons & (1u << bit)) != 0;
auto over = [&](int index, int value, int on, int off) {
held[index] = value > (held[index] ? off : on);
};
over(proto::kKeyLeftTrigger, pad.bLeftTrigger, kTriggerOn, kTriggerOff);
over(proto::kKeyRightTrigger, pad.bRightTrigger, kTriggerOn, kTriggerOff);
over(proto::kKeyStickUp, pad.sThumbLY, kStickOn, kStickOff);
over(proto::kKeyStickDown, -static_cast<int>(pad.sThumbLY), kStickOn, kStickOff);
over(proto::kKeyStickLeft, -static_cast<int>(pad.sThumbLX), kStickOn, kStickOff);
over(proto::kKeyStickRight, pad.sThumbLX, kStickOn, kStickOff);
}

DWORD WINAPI Worker(LPVOID) {
bool held[proto::kKeyBindings] = {};
for (;;) {
if (!g_enabled.load(std::memory_order_acquire) || g_active.load() == 0) {
for (bool& h : held) h = false;
ReleaseAll();
Sleep(100);
continue;
}
XINPUT_STATE state{};
if (ReadPlayerOnePad(&state)) {
ReadBindings(state.Gamepad, held);
} else {
for (bool& h : held) h = false;
}
bool want[256] = {};
for (int i = 0; i < proto::kKeyBindings; ++i) {
const uint8_t vk = g_keyMap[i].load(std::memory_order_relaxed);
if (vk != 0 && held[i]) want[vk] = true;
}
for (UINT vk = 1; vk < 256; ++vk) {
if (want[vk] != g_down[vk].load(std::memory_order_relaxed)) PostKey(vk, want[vk]);
}
Sleep(8);
}
}

} // namespace

void SetKeyMap(const uint8_t (&keyMap)[24]) {
bool any = false;
for (int i = 0; i < proto::kKeyBindings; ++i) {
g_keyMap[i].store(keyMap[i], std::memory_order_relaxed);
any = any || keyMap[i] != 0;
}
g_enabled.store(any, std::memory_order_release);
// Key-state queries must report these keys even when the keyboard block is off.
if (any && !InstallInputBlockHooks()) Log(LogLevel::Warn, "Key-state hooks not available");
if (any && !g_threadStarted) {
HANDLE thread = CreateThread(nullptr, 0, &Worker, nullptr, 0, nullptr);
if (thread == nullptr) {
Log(LogLevel::Error, "Could not start the controller-to-keys thread");
return;
}
CloseHandle(thread);
g_threadStarted = true;
}
if (any) Log(LogLevel::Info, "Controller presses keys in the game");
}

void ClearKeyMap() { g_enabled.store(false, std::memory_order_release); }

bool SyntheticKeyDown(int vk) {
if (vk <= 0 || vk > 255) return false;
if (g_down[vk].load(std::memory_order_relaxed)) return true;
// Games often ask for the left/right variant of a modifier the binding names generically.
switch (vk) {
case VK_LSHIFT: case VK_RSHIFT: return g_down[VK_SHIFT].load(std::memory_order_relaxed);
case VK_LCONTROL: case VK_RCONTROL: return g_down[VK_CONTROL].load(std::memory_order_relaxed);
case VK_LMENU: case VK_RMENU: return g_down[VK_MENU].load(std::memory_order_relaxed);
default: return false;
}
}

} // namespace inputsplit::hook
6 changes: 6 additions & 0 deletions native/hook/modules.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ bool IsMouseMessage(UINT message);
bool InstallXInputHooks();
void OnXInputBackgroundEnabled();
void OnXInputBackgroundDisabled();
bool ReadPlayerOnePad(XINPUT_STATE* state); // the game's player 1, tuning applied

// key_emulation.cpp (the controller presses keys in the game)
void SetKeyMap(const uint8_t (&keyMap)[24]);
void ClearKeyMap();
bool SyntheticKeyDown(int vk); // a key the controller holds down in the game

// directinput_bridge.cpp
bool InstallDirectInputHooks();
Expand Down
2 changes: 2 additions & 0 deletions native/hook/tuning.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,15 @@ void SetTuning(const proto::TuningMessage& tuning) {
Log(LogLevel::Info, "Player order: slots %u %u %u %u", tuning.playerSlots[0] + 1u,
tuning.playerSlots[1] + 1u, tuning.playerSlots[2] + 1u, tuning.playerSlots[3] + 1u);
}
SetKeyMap(tuning.keyMap);
Log(LogLevel::Info, "Tuning %s: dead zones L=%d R=%d triggers=%d, buttons %s",
enabled ? "on" : "off", left, right, trigger, identity ? "unchanged" : "remapped");
}

void ClearTuning() {
g_enabled.store(false, std::memory_order_release);
g_orderEnabled.store(false, std::memory_order_release);
ClearKeyMap();
}

bool PlayerOrderSlot(DWORD userIndex, DWORD& physical) {
Expand Down
11 changes: 11 additions & 0 deletions native/hook/xinput_bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ bool InstallXInputHooks() {
return installed;
}

bool ReadPlayerOnePad(XINPUT_STATE* state) {
if (g_real.getState == nullptr && !InstallXInputHooks()) return false;
DWORD physical = 0;
if (!MapUserIndex(0, physical)) return false;
if (g_real.getState(physical, state) != ERROR_SUCCESS && !ReadBridged(physical, state)) {
return false;
}
ApplyTuning(state);
return true;
}

void OnXInputBackgroundEnabled() {
// The game may already have disabled XInput before isolation started.
if (g_real.enable != nullptr) g_real.enable(TRUE);
Expand Down
1 change: 1 addition & 0 deletions src/main/native/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export const helperMethods = {
triggerDeadzone: z.number().int(),
buttonMap: z.array(z.number().int()),
playerSlots: z.array(z.number().int()).optional(),
keyMap: z.array(z.number().int()).optional(),
}),
result: empty,
},
Expand Down
Loading
Loading