Files
MouseTrailCollector/Assets/Stript/StartUI_Interactions/Polling.cs
T
2026-10-19 18:17:22 +08:00

172 lines
5.2 KiB
C#

using UnityEngine;
using TMPro;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
public class Polling : MonoBehaviour
{
[Header("UI 參照")]
[Tooltip("Text (TMP) ")]
public TextMeshProUGUI pollingDisplay;
private const int WH_MOUSE_LL = 14;
private const int WM_MOUSEMOVE = 0x0200;
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
private static LowLevelMouseProc _proc;
private static IntPtr _hookID = IntPtr.Zero;
private static Stopwatch stopwatch = new Stopwatch();
private static long lastTicks = 0;
private static List<double> intervals = new List<double>();
private static readonly object lockObj = new object();
// EMA
private double smoothedMs = 0;
private const double alpha = 0.25;
// 無動作計時
private List<int> recentRates = new List<int>();
private float timeSinceLastEvent = 0f;
private const float idleTimeout = 2f; // 超過 2 秒沒動就歸零
[Header("顯示")]
[Tooltip("文字更新間隔 (秒),偵測仍然每幀進行")]
public float updateInterval = 0.5f;
private float displayTimer = 0f;
private int shownHz = -1; // 上次顯示的數值,沒變就不重設文字
// 與 hook 交換用的暫存 List,避免每幀 new 一個新的
private List<double> currentBatch = new List<double>();
void OnEnable()
{
stopwatch.Start();
_proc = HookCallback;
_hookID = SetHook(_proc);
}
void OnDisable()
{
UnhookWindowsHookEx(_hookID);
}
private IntPtr SetHook(LowLevelMouseProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_MOUSEMOVE)
{
long currentTicks = stopwatch.ElapsedTicks;
if (lastTicks != 0)
{
double ms = (double)(currentTicks - lastTicks) / Stopwatch.Frequency * 1000.0;
lock (lockObj)
{
if (ms > 0.001 && ms < 100.0)
{
intervals.Add(ms);
}
}
}
lastTicks = currentTicks;
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
void Update()
{
// 把 hook 收集的資料換過來,hook 改寫進清空的那一份
currentBatch.Clear();
lock (lockObj)
{
List<double> temp = intervals;
intervals = currentBatch;
currentBatch = temp;
}
if (currentBatch.Count > 0)
{
timeSinceLastEvent = 0f;
double sum = 0;
foreach (var val in currentBatch) sum += val;
double batchAvgMs = sum / currentBatch.Count;
if (smoothedMs == 0)
{
smoothedMs = batchAvgMs;
}
else
{
smoothedMs = (alpha * batchAvgMs) + ((1.0 - alpha) * smoothedMs);
}
if (smoothedMs > 0)
{
// 直接用實測值,不對齊到 250 / 500 / 1000... 等標準值
recentRates.Add((int)Math.Round(1000.0 / smoothedMs));
}
}
else
{
timeSinceLastEvent += Time.unscaledDeltaTime;
}
if (timeSinceLastEvent >= idleTimeout)
{
recentRates.Clear();
smoothedMs = 0;
}
int maxHz = 0;
if (recentRates.Count > 0)
{
foreach (int rate in recentRates)
{
if (rate >= maxHz) maxHz = rate;
}
if (recentRates.Count > 60)
{
recentRates.RemoveAt(0);
}
}
// 每 updateInterval 秒才更新一次文字,數值沒變就不重設
displayTimer += Time.unscaledDeltaTime;
if (displayTimer < updateInterval) return;
displayTimer = 0f;
if (pollingDisplay != null && maxHz != shownHz)
{
pollingDisplay.text = $"滑鼠回報率: {maxHz} Hz";
shownHz = maxHz;
}
}
#region Win32 API 匯入
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
#endregion
}