My mouse polling rate is low so could you add extra function that will interpolating the mouse position between samples so its smoother in the code below without changing anything? Just use same mouse method that is already used in code since only this works for me.
#include <windows.h>
#include
#include
#include
// Function to simulate key press using scan codes
void PressKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
// Helper class to manage key states
class KeyState {
public:
std::atomic aPressed;
std::atomic dPressed;
code
KeyState() : aPressed(false), dPressed(false) {}
void PressA() {
if (!aPressed.load()) {
PressKey(0x1E); // Scan code for 'A'
aPressed = true;
}
}
void ReleaseA() {
if (aPressed.load()) {
ReleaseKey(0x1E); // Scan code for 'A'
aPressed = false;
}
}
void PressD() {
if (!dPressed.load()) {
PressKey(0x20); // Scan code for 'D'
dPressed = true;
}
}
void ReleaseD() {
if (dPressed.load()) {
ReleaseKey(0x20); // Scan code for 'D'
dPressed = false;
}
}
void ReleaseAll() {
ReleaseA();
ReleaseD();
}
};
// Function to bring Roblox window to foreground
HWND GetRobloxWindow() {
HWND hwnd = FindWindow(NULL, NULL);
while (hwnd != NULL) {
wchar_t title[256];
GetWindowText(hwnd, title, sizeof(title) / sizeof(wchar_t));
std::wstring windowTitle(title);
if (windowTitle.find(L"Roblox") != std::wstring::npos) {
return hwnd;
}
hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
}
return NULL;
}
// Constants for thresholds and timings
const LONG MOVEMENT_THRESHOLD = 5; // Minimum pixels of movement before switching keys
const DWORD KEY_PRESS_DURATION = 10; // Minimum duration to hold a key in milliseconds
// Function to get the current time in milliseconds
DWORD GetCurrentTimeMs() {
return GetTickCount();
}
if (!isAdmin) {
std::cerr << "Please run the application as an administrator." << std::endl;
return 1;
}
const wchar_t CLASS_NAME[] = L"MouseCaptureWindow";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (!RegisterClass(&wc)) {
std::cerr << "Failed to register window class." << std::endl;
return 1;
}
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Strafe Helper",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 100,
NULL,
NULL,
GetModuleHandle(NULL),
NULL
);
if (hwnd == NULL) {
std::cerr << "Failed to create window." << std::endl;
return 0;
}
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02;
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hwnd;
if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
std::cerr << "Failed to register raw input device." << std::endl;
return 1;
}
ShowWindow(hwnd, SW_SHOWMINIMIZED);
std::cout << "Strafe Helper is running.\n"
<< "Hold down the RIGHT mouse button and move the mouse left or right to strafe.\n"
<< "Press ESC to exit.\n";
std::atomic<bool> running(true);
std::thread exitThread([&running]() {
while (running.load()) {
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
PostMessage(NULL, WM_CLOSE, 0, 0);
running = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
running = false;
if (exitThread.joinable()) {
exitThread.join();
}
return 0;
}
To address the issue of a low mouse polling rate and implement interpolation for smoother mouse movements, we can introduce an additional thread that processes mouse movement deltas in smaller increments. This approach ensures that even with occasional large deltas, the key presses (A and D) are triggered smoothly over time.
Here's how to incorporate this functionality into your existing code:
Introduce Shared Variables and Synchronization Mechanisms:
Use std::atomic<long> for thread-safe accumulation of pending mouse deltas.
Use a mutex to protect shared variables like cumulativeMouseX and lastSwitchTime.
Modify the WindowProc Function:
Instead of directly adding deltaX to cumulativeMouseX, accumulate it in a pendingDeltaX variable.
Add an Interpolating Thread:
Create a separate thread that periodically (e.g., every 10ms) processes small steps from pendingDeltaX and updates cumulativeMouseX.
This thread will handle the key press/release logic based on the interpolated cumulative movement.
Below is the complete modified code with detailed comments explaining each addition and change:
cpp
#include <windows.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <chrono>
// Function to simulate key press using scan codes
void PressKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
void ReleaseKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
}
// Helper class to manage key states
class KeyState {
public:
std::atomic<bool> aPressed;
std::atomic<bool> dPressed;
KeyState() : aPressed(false), dPressed(false) {}
void PressA() {
if (!aPressed.load()) {
PressKey(0x1E); // Scan code for 'A'
aPressed = true;
}
}
void ReleaseA() {
if (aPressed.load()) {
ReleaseKey(0x1E); // Scan code for 'A'
aPressed = false;
}
}
void PressD() {
if (!dPressed.load()) {
PressKey(0x20); // Scan code for 'D'
dPressed = true;
}
}
void ReleaseD() {
if (dPressed.load()) {
ReleaseKey(0x20); // Scan code for 'D'
dPressed = false;
}
}
void ReleaseAll() {
ReleaseA();
ReleaseD();
}
};
// Function to bring Roblox window to foreground
HWND GetRobloxWindow() {
HWND hwnd = FindWindow(NULL, NULL);
while (hwnd != NULL) {
wchar_t title[256];
GetWindowText(hwnd, title, sizeof(title) / sizeof(wchar_t));
std::wstring windowTitle(title);
if (windowTitle.find(L"Roblox") != std::wstring::npos) {
return hwnd;
}
hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
}
return NULL;
}
// Constants for thresholds and timings
const LONG MOVEMENT_THRESHOLD = 5; // Minimum pixels of movement before switching keys
const DWORD KEY_PRESS_DURATION = 10; // Minimum duration to hold a key in milliseconds
// Function to get the current time in milliseconds
DWORD GetCurrentTimeMs() {
return GetTickCount();
}
// Shared variables for interpolation
std::atomic<long> pendingDeltaX(0); // Accumulated pending mouse delta
long cumulativeMouseX_global = 0; // Accumulated mouse movement for processing
DWORD lastSwitchTime_global = 0; // Last time keys were switched
std::mutex movementMutex; // Mutex to protect shared variables
KeyState keyState_global; // Shared KeyState instance
std::atomic<bool> running(true); // Flag to control thread execution
// Function to process cumulative mouse movement
void ProcessCumulativeMovement() {
std::lock_guard<std::mutex> lock(movementMutex);
DWORD currentTime = GetCurrentTimeMs();
if (currentTime - lastSwitchTime_global >= KEY_PRESS_DURATION) {
if (cumulativeMouseX_global >= MOVEMENT_THRESHOLD) {
keyState_global.PressD();
keyState_global.ReleaseA();
cumulativeMouseX_global = 0;
lastSwitchTime_global = currentTime;
}
else if (cumulativeMouseX_global <= -MOVEMENT_THRESHOLD) {
keyState_global.PressA();
keyState_global.ReleaseD();
cumulativeMouseX_global = 0;
lastSwitchTime_global = currentTime;
}
}
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
static bool isRightButtonDown = false;
static HWND robloxHwnd = NULL;
switch (uMsg) {
case WM_INPUT: {
BYTE lpb[sizeof(RAWINPUT)];
UINT dwSize = sizeof(lpb);
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,
sizeof(RAWINPUTHEADER)) != dwSize) {
std::cerr << "GetRawInputData does not return correct size!" << std::endl;
break;
}
RAWINPUT* raw = (RAWINPUT*)lpb;
// Check if the right mouse button is held down
if (GetAsyncKeyState(VK_RBUTTON) & 0x8000) {
if (!isRightButtonDown) {
isRightButtonDown = true;
if (!robloxHwnd) {
robloxHwnd = GetRobloxWindow();
if (robloxHwnd) {
SetForegroundWindow(robloxHwnd);
}
else {
std::cerr << "Roblox window not found." << std::endl;
}
}
else {
SetForegroundWindow(robloxHwnd);
}
}
}
else {
if (isRightButtonDown) {
keyState_global.ReleaseAll();
}
isRightButtonDown = false;
// Optionally reset cumulative movement
// cumulativeMouseX_global = 0;
break;
}
if (raw->header.dwType == RIM_TYPEMOUSE && isRightButtonDown) {
LONG deltaX = raw->data.mouse.lLastX;
// Accumulate mouse movement in pendingDeltaX for interpolation
pendingDeltaX += deltaX;
}
break;
}
case WM_DESTROY:
keyState_global.ReleaseAll();
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
int main() {
BOOL isAdmin = FALSE;
PSID administratorsGroup = NULL;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&administratorsGroup)) {
CheckTokenMembership(NULL, administratorsGroup, &isAdmin);
FreeSid(administratorsGroup);
}
if (!isAdmin) {
std::cerr << "Please run the application as an administrator." << std::endl;
return 1;
}
const wchar_t CLASS_NAME[] = L"MouseCaptureWindow";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (!RegisterClass(&wc)) {
std::cerr << "Failed to register window class." << std::endl;
return 1;
}
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Strafe Helper",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 100,
NULL,
NULL,
GetModuleHandle(NULL),
NULL
);
if (hwnd == NULL) {
std::cerr << "Failed to create window." << std::endl;
return 0;
}
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02;
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hwnd;
if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
std::cerr << "Failed to register raw input device." << std::endl;
return 1;
}
ShowWindow(hwnd, SW_SHOWMINIMIZED);
std::cout << "Strafe Helper is running.\n"
<< "Hold down the RIGHT mouse button and move the mouse left or right to strafe.\n"
<< "Press ESC to exit.\n";
// Start the interpolating thread
std::thread interpolatingThread([&]() {
while (running.load()) {
// Sleep for 10ms between steps (adjust for smoother or faster interpolation)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
long delta = pendingDeltaX.load();
if (delta != 0) {
// Determine the step direction
long step = (delta > 0) ? 1 : -1;
// Attempt to decrement the pendingDeltaX by the step
// This ensures atomicity
if (pendingDeltaX.compare_exchange_strong(delta, delta - step)) {
// Successfully reserved this step
{
std::lock_guard<std::mutex> lock(movementMutex);
cumulativeMouseX_global += step;
DWORD currentTime = GetCurrentTimeMs();
if (currentTime - lastSwitchTime_global >= KEY_PRESS_DURATION) {
if (cumulativeMouseX_global >= MOVEMENT_THRESHOLD) {
keyState_global.PressD();
keyState_global.ReleaseA();
cumulativeMouseX_global = 0;
lastSwitchTime_global = currentTime;
}
else if (cumulativeMouseX_global <= -MOVEMENT_THRESHOLD) {
keyState_global.PressA();
keyState_global.ReleaseD();
cumulativeMouseX_global = 0;
lastSwitchTime_global = currentTime;
}
}
}
}
// If compare_exchange_strong failed, another thread modified pendingDeltaX
// In this simple case, we can ignore and let the next loop handle it
}
}
});
// Thread to monitor ESC key for exiting
std::thread exitThread([&]() {
while (running.load()) {
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
PostMessage(NULL, WM_CLOSE, 0, 0);
running = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Cleanup
running = false;
if (interpolatingThread.joinable()) {
interpolatingThread.join();
}
if (exitThread.joinable()) {
exitThread.join();
}
// Ensure all keys are released before exiting
keyState_global.ReleaseAll();
return 0;
}
Explanation of Changes:
Shared Variables and Mutex:
pendingDeltaX: An atomic variable that accumulates all incoming mouse deltaX values from WindowProc. This ensures thread-safe operations when accessed by both the main thread and the interpolating thread.
cumulativeMouseX_global & lastSwitchTime_global: These variables are protected by a mutex (movementMutex) to prevent race conditions when being accessed or modified by multiple threads.
keyState_global: A global instance of KeyState to manage the key presses across threads.
running: An atomic boolean flag to control the execution of the interpolating thread and ensure proper shutdown.
Modification in WindowProc:
Instead of directly adding deltaX to cumulativeMouseX, we now accumulate it in pendingDeltaX. This change delegates the smoothing logic to the separate interpolating thread.
Interpolating Thread:
Purpose: This thread processes the accumulated pendingDeltaX in smaller increments to simulate a higher polling rate and achieve smoother key presses.
Operation:
Sleep Interval: The thread sleeps for 10 milliseconds between each processing step. You can adjust this interval (std::chrono::milliseconds(10)) to make the interpolation smoother or more responsive based on your preference and system performance.
Processing Steps:
Determine Step Direction: Based on whether pendingDeltaX is positive or negative.
Atomic Decrement: Use compare_exchange_strong to safely decrement pendingDeltaX by one step. This ensures that multiple threads do not interfere with each other's modifications.
Update cumulativeMouseX_global: Add the step to cumulativeMouseX_global and then check if it crosses the MOVEMENT_THRESHOLD. If it does, trigger the corresponding key press/release logic.
Exit Thread:
Additional Considerations:
Adjusting Interpolation Smoothness:
Sleep Duration: You can modify the std::this_thread::sleep_for(std::chrono::milliseconds(10)); to a smaller value (e.g., 5ms) for a higher interpolation rate, making the movement appear smoother. However, be cautious as too short intervals might increase CPU usage.
Step Size: Currently, the step size is fixed at 1 or -1. Depending on your requirements, you might adjust this to handle larger or variable step sizes, but ensure it aligns with how cumulativeMouseX_global is processed.
Thread Safety:
All modifications to shared variables are protected either by atomic operations or mutex locks to ensure thread safety.
Responsiveness:
The KEY_PRESS_DURATION and MOVEMENT_THRESHOLD constants dictate how responsive the key presses are to mouse movements. You might need to tweak these values based on your specific use case and desired sensitivity.
This implementation ensures that mouse movements are interpolated smoothly, mitigating the effects of a low polling rate by breaking down larger movements into smaller, more frequent steps. The separation of concerns via threading allows the main event processing to remain efficient while handling the smoothing logic independently.
Monitors the ESC key to allow the user to exit the application gracefully. It sets the running flag to false, which signals both the interpolating and exit threads to terminate.
Cleanup:
After the message loop ends, ensure that both threads are properly joined, and all keys are released to prevent any unintended key presses lingering after the application exits.