Files
MouseTrailCollector/Assets/Stript/Common/RawMouseInput.cs
T
2026-10-27 23:50:26 +08:00

381 lines
16 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
using UnityEngine.InputSystem;
using Debug = UnityEngine.Debug;
// 每一幀最先執行,把 Raw Input 的事件取出來給這一幀的所有腳本用
[DefaultExecutionOrder(-10000)]
public class RawMouseInputRunner : MonoBehaviour
{
void Update() => RawMouseInput.BeginFrame();
}
// Windows Raw Input : 在背景執行緒接收每一筆滑鼠原始回報,收到的當下就蓋上高精度時間戳
// 遊戲一啟動就自動開始,關遊戲 (或編輯器停止 Play) 時還原
// 只接管「滑鼠原始位移」; 游標移動和點擊 UI 走的是 Windows 另一條訊息,不受影響
public static class RawMouseInput
{
public struct Event
{
public double t; // 秒,跟 Time.realtimeSinceStartupAsDouble 同一條時間軸
public int dx; // 往右為正
public int dy; // 往上為正 (Windows 原始資料往下為正,這裡已經翻過來)
public bool left; // 這一筆之後左鍵是否按著
}
public static bool IsRunning { get; private set; }
public static string Status { get; private set; } = "尚未啟動";
public static bool LeftDown => leftDown;
// 統計 (除錯用)
public static long Received => Interlocked.Read(ref received);
public static long IgnoredUnfocused => Interlocked.Read(ref ignoredUnfocused);
public static long IgnoredAbsolute => Interlocked.Read(ref ignoredAbsolute);
public static long Reregistrations => Interlocked.Read(ref reregistrations);
private static readonly ConcurrentQueue<Event> queue = new ConcurrentQueue<Event>();
private static Thread thread;
private static IntPtr hwnd;
private static WndProcDelegate wndProc; // 要留著參照,不然會被 GC 回收
private static string className;
private static volatile bool appFocused;
private static volatile bool leftDown;
private static long received, ignoredUnfocused, ignoredAbsolute, reregistrations;
private static double nextRegistrationCheck;
private static long baseTicks;
private static double baseRealtime;
private static RAWINPUTDEVICE[] previousRegistration; // 啟動前別人 (Unity) 的註冊,關閉時還原
// ===== 每一幀給遊戲用的資料 (每幀開頭統一取出一次,大家讀同一份) =====
// 這一幀收到的所有原始事件 (時間由舊到新) ; 記錄器逐筆寫進 mouse_N.csv
public static IReadOnlyList<Event> FrameEvents => frameEvents;
// 這一幀的位移總和 (滑鼠單位,往右、往上為正) ; 視角讀這個,所以等於 FrameEvents 的加總
public static Vector2 FrameDelta { get; private set; }
// 左鍵 : 按著 / 這一幀剛按下 (就算按下又放開都在同一幀也算到)
public static bool LeftHeld => IsRunning ? leftDown : (Mouse.current != null && Mouse.current.leftButton.isPressed);
public static bool LeftPressedThisFrame { get; private set; }
private static readonly List<Event> frameEvents = new List<Event>();
private static bool lastFrameLeft;
// 由 RawMouseInputRunner 在每一幀最前面呼叫
internal static void BeginFrame()
{
frameEvents.Clear();
if (!IsRunning)
{
// Raw Input 沒成功啟動 (例如非 Windows) : 退回 Unity 的滑鼠,遊戲照樣能玩,但沒有逐筆時間
FrameDelta = Mouse.current != null ? Mouse.current.delta.ReadValue() : Vector2.zero;
LeftPressedThisFrame = Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame;
return;
}
CheckRegistration();
while (queue.TryDequeue(out Event e)) frameEvents.Add(e);
Vector2 sum = Vector2.zero;
bool pressed = false;
bool prev = lastFrameLeft;
foreach (Event e in frameEvents)
{
sum.x += e.dx;
sum.y += e.dy;
if (e.left && !prev) pressed = true;
prev = e.left;
}
if (leftDown && !lastFrameLeft) pressed = true; // 視窗不在前景時按下的,事件被略過但狀態有記
lastFrameLeft = leftDown;
FrameDelta = sum;
LeftPressedThisFrame = pressed;
}
// ===== 啟動與關閉 =====
// 遊戲一啟動就自動開始,並建立每幀取資料的物件
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void AutoStart()
{
Begin();
GameObject runner = new GameObject("RawMouseInput");
runner.hideFlags = HideFlags.HideInHierarchy;
UnityEngine.Object.DontDestroyOnLoad(runner);
runner.AddComponent<RawMouseInputRunner>();
}
public static void Begin()
{
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
if (IsRunning) return;
// 時間軸對齊 : 記下同一刻的 Stopwatch 與 Unity 時間
baseTicks = Stopwatch.GetTimestamp();
baseRealtime = Time.realtimeSinceStartupAsDouble;
appFocused = Application.isFocused;
Application.focusChanged -= OnFocusChanged;
Application.focusChanged += OnFocusChanged;
Application.quitting -= Stop;
Application.quitting += Stop;
previousRegistration = GetCurrentMouseRegistration();
while (queue.TryDequeue(out _)) { }
Interlocked.Exchange(ref received, 0);
Interlocked.Exchange(ref ignoredUnfocused, 0);
Interlocked.Exchange(ref ignoredAbsolute, 0);
// 等背景執行緒註冊完成 (不 Dispose : 執行緒結束時還會用到它)
ManualResetEventSlim ready = new ManualResetEventSlim(false);
// 最高優先權 : 遊戲忙的時候 (載入場景、GC) 這條執行緒也要盡快醒來蓋時間戳
thread = new Thread(() => ThreadMain(ready)) { IsBackground = true, Name = "RawMouseInput", Priority = System.Threading.ThreadPriority.Highest };
thread.Start();
ready.Wait(2000);
#else
Status = "此平台不支援 (僅 Windows)";
#endif
}
// Unity 重新取得焦點時會重新註冊自己的 Raw Input,把我們的蓋掉,所以切回來就搶回來
static void OnFocusChanged(bool focused)
{
appFocused = focused;
if (focused) RequestReregister();
}
// 每 0.5 秒確認一次滑鼠還是註冊在我們的視窗 (Unity 也可能在其他時機重新註冊)
static void CheckRegistration()
{
if (!IsRunning) return;
double now = Time.realtimeSinceStartupAsDouble;
if (now < nextRegistrationCheck) return;
nextRegistrationCheck = now + 0.5;
RAWINPUTDEVICE[] current = GetCurrentMouseRegistration();
bool ours = current != null && current.Length > 0 && current[0].hwndTarget == hwnd;
if (!ours) RequestReregister();
}
static void RequestReregister()
{
if (IsRunning && hwnd != IntPtr.Zero) PostMessage(hwnd, WM_APP_REREGISTER, IntPtr.Zero, IntPtr.Zero);
}
// 在背景執行緒上做 (註冊的視窗屬於它)
static bool RegisterOurWindow()
{
RAWINPUTDEVICE[] rid = { new RAWINPUTDEVICE { usUsagePage = 0x01, usUsage = 0x02, dwFlags = RIDEV_INPUTSINK, hwndTarget = hwnd } };
return RegisterRawInputDevices(rid, 1, (uint)Marshal.SizeOf<RAWINPUTDEVICE>());
}
// 一般只在關遊戲時呼叫;InputCompareProbe 會暫時停掉,讓 Unity Input System 拿回滑鼠做對照
public static void Stop()
{
Application.quitting -= Stop;
if (!IsRunning) return;
IsRunning = false;
// 還原成啟動前的註冊 (在主執行緒做,因為 Unity 的視窗屬於主執行緒)
RAWINPUTDEVICE[] restore = previousRegistration != null && previousRegistration.Length > 0
? previousRegistration
: new[] { new RAWINPUTDEVICE { usUsagePage = 0x01, usUsage = 0x02, dwFlags = RIDEV_REMOVE, hwndTarget = IntPtr.Zero } };
if (!RegisterRawInputDevices(restore, (uint)restore.Length, (uint)Marshal.SizeOf<RAWINPUTDEVICE>()))
{
Debug.LogWarning($"[RawMouseInput] 還原滑鼠註冊失敗 (錯誤碼 {Marshal.GetLastWin32Error()})");
}
if (hwnd != IntPtr.Zero) PostMessage(hwnd, WM_APP_STOP, IntPtr.Zero, IntPtr.Zero);
thread?.Join(1000);
Status = "已停止";
}
// ===== 背景執行緒 =====
static void ThreadMain(ManualResetEventSlim ready)
{
IntPtr buffer = Marshal.AllocHGlobal(128);
try
{
IntPtr hInstance = GetModuleHandle(null);
className = "MTC_RawMouseInput_" + Guid.NewGuid().ToString("N");
wndProc = (h, msg, w, l) => WndProc(h, msg, w, l, buffer);
WNDCLASSEX wc = new WNDCLASSEX
{
cbSize = (uint)Marshal.SizeOf<WNDCLASSEX>(),
lpfnWndProc = wndProc,
hInstance = hInstance,
lpszClassName = className,
};
if (RegisterClassEx(ref wc) == 0) { Fail("RegisterClassEx"); return; }
// 不顯示的訊息視窗,只用來收 WM_INPUT
hwnd = CreateWindowEx(0, className, "", 0, 0, 0, 0, 0, HWND_MESSAGE, IntPtr.Zero, hInstance, IntPtr.Zero);
if (hwnd == IntPtr.Zero) { Fail("CreateWindowEx"); return; }
// RIDEV_INPUTSINK : 視窗不在前景也收得到 (我們自己用 appFocused 過濾)
// 不加 RIDEV_NOLEGACY : 游標移動與點擊的一般訊息照常送給 Unity
if (!RegisterOurWindow()) { Fail("RegisterRawInputDevices"); return; }
IsRunning = true;
Status = "運作中";
ready.Set();
while (GetMessage(out MSG msg, IntPtr.Zero, 0, 0) > 0)
{
DispatchMessage(ref msg);
}
}
catch (Exception e)
{
Status = "錯誤 : " + e.Message;
IsRunning = false;
}
finally
{
if (hwnd != IntPtr.Zero) { DestroyWindow(hwnd); hwnd = IntPtr.Zero; }
if (className != null) UnregisterClass(className, GetModuleHandle(null));
Marshal.FreeHGlobal(buffer);
ready.Set();
}
}
static IntPtr WndProc(IntPtr h, uint msg, IntPtr wParam, IntPtr lParam, IntPtr buffer)
{
if (msg == WM_INPUT)
{
long now = Stopwatch.GetTimestamp(); // 第一件事就是蓋時間
HandleInput(lParam, buffer, now);
return DefWindowProc(h, msg, wParam, lParam); // 讓系統清理 WM_INPUT
}
if (msg == WM_APP_REREGISTER)
{
if (RegisterOurWindow()) Interlocked.Increment(ref reregistrations);
return IntPtr.Zero;
}
if (msg == WM_APP_STOP)
{
PostQuitMessage(0);
return IntPtr.Zero;
}
return DefWindowProc(h, msg, wParam, lParam);
}
static void HandleInput(IntPtr hRawInput, IntPtr buffer, long ticks)
{
uint size = 128;
int headerSize = Marshal.SizeOf<RAWINPUTHEADER>();
if (GetRawInputData(hRawInput, RID_INPUT, buffer, ref size, (uint)headerSize) == uint.MaxValue) return;
if (Marshal.ReadInt32(buffer, 0) != RIM_TYPEMOUSE) return;
int m = headerSize; // RAWMOUSE 的開頭
ushort flags = (ushort)Marshal.ReadInt16(buffer, m);
ushort buttons = (ushort)Marshal.ReadInt16(buffer, m + 4);
int dx = Marshal.ReadInt32(buffer, m + 12);
int dy = Marshal.ReadInt32(buffer, m + 16);
if ((buttons & RI_MOUSE_LEFT_BUTTON_DOWN) != 0) leftDown = true;
if ((buttons & RI_MOUSE_LEFT_BUTTON_UP) != 0) leftDown = false;
// 遊戲不在前景 : 不記錄 (只記遊戲內的操作)
if (!appFocused) { Interlocked.Increment(ref ignoredUnfocused); return; }
// 絕對座標 (遠端桌面、繪圖板) 不是相對位移,略過
if ((flags & MOUSE_MOVE_ABSOLUTE) != 0) { Interlocked.Increment(ref ignoredAbsolute); return; }
// 只有按鍵變化、沒有位移的回報也要記,因為左鍵狀態改變了
if (dx == 0 && dy == 0 && buttons == 0) return;
Interlocked.Increment(ref received);
queue.Enqueue(new Event
{
t = baseRealtime + (double)(ticks - baseTicks) / Stopwatch.Frequency,
dx = dx,
dy = -dy,
left = leftDown,
});
}
static void Fail(string api)
{
Status = $"{api} 失敗 (錯誤碼 {Marshal.GetLastWin32Error()})";
IsRunning = false;
Debug.LogWarning("[RawMouseInput] " + Status);
}
static RAWINPUTDEVICE[] GetCurrentMouseRegistration()
{
uint count = 0;
uint size = (uint)Marshal.SizeOf<RAWINPUTDEVICE>();
GetRegisteredRawInputDevices(null, ref count, size);
if (count == 0) return null;
RAWINPUTDEVICE[] all = new RAWINPUTDEVICE[count];
if (GetRegisteredRawInputDevices(all, ref count, size) == uint.MaxValue) return null;
List<RAWINPUTDEVICE> mice = new List<RAWINPUTDEVICE>();
foreach (RAWINPUTDEVICE d in all)
{
if (d.usUsagePage == 0x01 && d.usUsage == 0x02) mice.Add(d);
}
return mice.ToArray();
}
// ===== Win32 =====
const uint WM_INPUT = 0x00FF;
const uint WM_APP_STOP = 0x8000 + 1;
const uint WM_APP_REREGISTER = 0x8000 + 2;
const uint RID_INPUT = 0x10000003;
const int RIM_TYPEMOUSE = 0;
const uint RIDEV_REMOVE = 0x00000001;
const uint RIDEV_INPUTSINK = 0x00000100;
const ushort MOUSE_MOVE_ABSOLUTE = 0x01;
const ushort RI_MOUSE_LEFT_BUTTON_DOWN = 0x0001;
const ushort RI_MOUSE_LEFT_BUTTON_UP = 0x0002;
static readonly IntPtr HWND_MESSAGE = new IntPtr(-3);
delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
struct RAWINPUTDEVICE { public ushort usUsagePage; public ushort usUsage; public uint dwFlags; public IntPtr hwndTarget; }
[StructLayout(LayoutKind.Sequential)]
struct RAWINPUTHEADER { public uint dwType; public uint dwSize; public IntPtr hDevice; public IntPtr wParam; }
[StructLayout(LayoutKind.Sequential)]
struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam; public IntPtr lParam; public uint time; public int ptX; public int ptY; }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct WNDCLASSEX
{
public uint cbSize; public uint style; public WndProcDelegate lpfnWndProc; public int cbClsExtra; public int cbWndExtra;
public IntPtr hInstance; public IntPtr hIcon; public IntPtr hCursor; public IntPtr hbrBackground;
public string lpszMenuName; public string lpszClassName; public IntPtr hIconSm;
}
[DllImport("user32.dll", SetLastError = true)] static extern bool RegisterRawInputDevices([In] RAWINPUTDEVICE[] devices, uint count, uint size);
[DllImport("user32.dll", SetLastError = true)] static extern uint GetRegisteredRawInputDevices([In, Out] RAWINPUTDEVICE[] devices, ref uint count, uint size);
[DllImport("user32.dll", SetLastError = true)] static extern uint GetRawInputData(IntPtr hRawInput, uint command, IntPtr data, ref uint size, uint headerSize);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern ushort RegisterClassEx(ref WNDCLASSEX wc);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool UnregisterClass(string className, IntPtr hInstance);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr CreateWindowEx(uint exStyle, string className, string windowName, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr hInstance, IntPtr param);
[DllImport("user32.dll", SetLastError = true)] static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr DefWindowProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetMessage(out MSG msg, IntPtr hWnd, uint min, uint max);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr DispatchMessage(ref MSG msg);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")] static extern void PostQuitMessage(int exitCode);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetModuleHandle(string moduleName);
}