軌跡記錄器更改成Raw Input
This commit is contained in:
1 parent
14140797ba
commit
ec0708d05b
17 files changed
+605
-316
No files matched your search
@@ -5950,6 +5950,7 @@ MonoBehaviour:
|
||||
m_EditorClassIdentifier: Assembly-CSharp::Polling
|
||||
pollingDisplay: {fileID: 1859848480}
|
||||
updateInterval: 0.5
|
||||
idleTimeout: 2
|
||||
--- !u!114 &577747346
|
||||
MonoBehaviour:
|
||||
m_ObjectHideFlags: 0
|
||||
|
||||
@@ -3916,9 +3916,6 @@ PrefabInstance:
|
||||
- targetCorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3}
|
||||
insertIndex: -1
|
||||
addedObject: {fileID: 4147227459518174559}
|
||||
- targetCorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3}
|
||||
insertIndex: -1
|
||||
addedObject: {fileID: 4147227459518174569}
|
||||
- targetCorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3}
|
||||
insertIndex: -1
|
||||
addedObject: {fileID: 4147227459518174568}
|
||||
@@ -4034,27 +4031,12 @@ MonoBehaviour:
|
||||
m_Name:
|
||||
m_EditorClassIdentifier: Assembly-CSharp::RoundRecorder
|
||||
spawner: {fileID: 727757762}
|
||||
inputCapture: {fileID: 4147227459518174569}
|
||||
playerLook: {fileID: 547904313}
|
||||
playerController: {fileID: 4147227459518174564}
|
||||
loadout: {fileID: 644171849}
|
||||
perceptor: {fileID: 4147227459518174560}
|
||||
aimAssist: {fileID: 4147227459518174559}
|
||||
recordInTestMode: 1
|
||||
--- !u!114 &4147227459518174569
|
||||
MonoBehaviour:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 799735551}
|
||||
m_Enabled: 1
|
||||
m_EditorHideFlags: 0
|
||||
m_Script: {fileID: 11500000, guid: 8552a1057f97a9d42a7f1354ea2c95ee, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier: Assembly-CSharp::InputEventCapture
|
||||
trackedKeys: 250000000f0000002100000012000000010000003300000020000000290000002a0000002b0000002c000000
|
||||
showDebug: 1
|
||||
--- !u!1001 &4458914454911198105
|
||||
PrefabInstance:
|
||||
m_ObjectHideFlags: 0
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
// Raw Input 除錯工具 (開發用,不要放進正式場景)
|
||||
// 掛在任何場景的任一物件上 : 畫面左下角顯示統計,按 F9 把最近 10 秒的原始事件存到桌面
|
||||
public class RawInputProbe : MonoBehaviour
|
||||
{
|
||||
[Tooltip("按 F9 存檔時保留最近幾秒")]
|
||||
public float keepSeconds = 10f;
|
||||
|
||||
private readonly List<RawMouseInput.Event> frameEvents = new List<RawMouseInput.Event>();
|
||||
private readonly List<RawMouseInput.Event> history = new List<RawMouseInput.Event>();
|
||||
private readonly List<double> gaps = new List<double>();
|
||||
|
||||
private int rawPerSecond;
|
||||
private int rawThisSecond;
|
||||
private float secondTimer;
|
||||
private double lastT;
|
||||
private string gapText = "";
|
||||
private int unityDeltaFrames; // 這一秒內 Unity 自己的 Mouse.delta 有動的幀數
|
||||
private int unityDeltaFramesShown;
|
||||
private Vector2 rawSumThisFrame;
|
||||
private Vector2 unityDeltaThisFrame;
|
||||
private string saveMessage = "";
|
||||
|
||||
void Update()
|
||||
{
|
||||
frameEvents.Clear();
|
||||
frameEvents.AddRange(RawMouseInput.FrameEvents);
|
||||
|
||||
rawSumThisFrame = Vector2.zero;
|
||||
foreach (RawMouseInput.Event e in frameEvents)
|
||||
{
|
||||
rawSumThisFrame += new Vector2(e.dx, e.dy);
|
||||
if (lastT > 0) gaps.Add(e.t - lastT);
|
||||
lastT = e.t;
|
||||
history.Add(e);
|
||||
}
|
||||
rawThisSecond += frameEvents.Count;
|
||||
|
||||
// Unity 自己還收不收得到滑鼠位移 (用來確認 Raw Input 接管後的影響)
|
||||
unityDeltaThisFrame = Mouse.current != null ? Mouse.current.delta.ReadValue() : Vector2.zero;
|
||||
if (unityDeltaThisFrame != Vector2.zero) unityDeltaFrames++;
|
||||
|
||||
double cut = Time.realtimeSinceStartupAsDouble - keepSeconds;
|
||||
int remove = 0;
|
||||
while (remove < history.Count && history[remove].t < cut) remove++;
|
||||
if (remove > 0) history.RemoveRange(0, remove);
|
||||
|
||||
secondTimer += Time.unscaledDeltaTime;
|
||||
if (secondTimer >= 1f)
|
||||
{
|
||||
rawPerSecond = rawThisSecond;
|
||||
unityDeltaFramesShown = unityDeltaFrames;
|
||||
gapText = DescribeGaps();
|
||||
rawThisSecond = 0;
|
||||
unityDeltaFrames = 0;
|
||||
gaps.Clear();
|
||||
secondTimer = 0f;
|
||||
}
|
||||
|
||||
if (Keyboard.current != null && Keyboard.current.f9Key.wasPressedThisFrame) SaveHistory();
|
||||
}
|
||||
|
||||
// 這一秒內事件間隔的分布 : 真的逐筆的話,間隔會集中在 1/回報率 附近,幾乎沒有 0
|
||||
string DescribeGaps()
|
||||
{
|
||||
if (gaps.Count < 2) return "(移動滑鼠看看)";
|
||||
gaps.Sort();
|
||||
int zero = 0;
|
||||
foreach (double g in gaps) if (g < 0.00001) zero++;
|
||||
double median = gaps[gaps.Count / 2] * 1000.0;
|
||||
double p10 = gaps[gaps.Count / 10] * 1000.0;
|
||||
double p90 = gaps[gaps.Count * 9 / 10] * 1000.0;
|
||||
return $"間隔中位數 {median:F3}ms (10%~90% : {p10:F3}~{p90:F3}ms),幾乎同時 (<0.01ms) 的比例 {100f * zero / gaps.Count:F0}%";
|
||||
}
|
||||
|
||||
void SaveHistory()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder("t,dx,dy,left\n");
|
||||
foreach (RawMouseInput.Event e in history)
|
||||
{
|
||||
sb.Append(e.t.ToString("F6", CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(e.dx).Append(',').Append(e.dy).Append(',').Append(e.left ? 1 : 0).Append('\n');
|
||||
}
|
||||
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), "raw_probe.csv");
|
||||
File.WriteAllText(path, sb.ToString());
|
||||
saveMessage = $"已存 {history.Count} 筆到 {path}";
|
||||
}
|
||||
|
||||
void OnGUI()
|
||||
{
|
||||
float y = Screen.height - 120;
|
||||
GUI.Box(new Rect(10, y - 5, 760, 120), "");
|
||||
GUI.Label(new Rect(20, y, 740, 22), $"Raw Input : {RawMouseInput.Status} 左鍵 {(RawMouseInput.LeftDown ? "按著" : "放開")} 重新註冊 {RawMouseInput.Reregistrations} 次");
|
||||
GUI.Label(new Rect(20, y + 20, 740, 22), $"每秒 {rawPerSecond} 筆 {gapText}");
|
||||
GUI.Label(new Rect(20, y + 40, 740, 22), $"這一幀 Raw 總和 ({rawSumThisFrame.x:F0}, {rawSumThisFrame.y:F0}) Unity Mouse.delta ({unityDeltaThisFrame.x:F0}, {unityDeltaThisFrame.y:F0}) Unity 有動的幀數 {unityDeltaFramesShown}/秒");
|
||||
GUI.Label(new Rect(20, y + 60, 740, 22), $"略過 : 視窗不在前景 {RawMouseInput.IgnoredUnfocused} 筆、絕對座標 {RawMouseInput.IgnoredAbsolute} 筆");
|
||||
GUI.Label(new Rect(20, y + 80, 740, 22), string.IsNullOrEmpty(saveMessage) ? "按 F9 存最近 10 秒到桌面 raw_probe.csv" : saveMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 85f5fdb7e8ef9c943bc98fdfde6ff2ab
|
||||
@@ -0,0 +1,379 @@
|
||||
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>());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b34e400d9e1e37849aa454ef49cbc8e5
|
||||
@@ -90,8 +90,8 @@ public class PlayerLook : MonoBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
// 暫停時不讀滑鼠,視角不會跟著轉
|
||||
Vector2 mouseDelta = Mouse.current != null && !PauseMenu.IsPaused ? Mouse.current.delta.ReadValue() : Vector2.zero;
|
||||
// 玩家輸入來自 Raw Input (跟記錄器寫進 mouse_N.csv 的是同一份) ; 暫停時不讀,視角不會跟著轉
|
||||
Vector2 mouseDelta = PauseMenu.IsPaused ? Vector2.zero : RawMouseInput.FrameDelta;
|
||||
|
||||
LastMouseDelta = mouseDelta;
|
||||
LastAssistDelta = pendingAssistDelta;
|
||||
|
||||
@@ -16,8 +16,8 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
├─ mouse_0.csv 第 0 回合的原始滑鼠事件
|
||||
├─ frames_0.csv 第 0 回合每一幀的狀態
|
||||
├─ events_0.csv 第 0 回合的離散事件
|
||||
├─ config_1.json
|
||||
└─ ...
|
||||
├─ config_1.json 第 1 回合的設定與摘要
|
||||
└─ mouse_1... 第 1 回合...
|
||||
```
|
||||
|
||||
- **一回合 = 一隻敵人**:從敵人出現開始,到敵人被擊倒為止。
|
||||
@@ -39,17 +39,28 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
|
||||
**靈敏度換算**:視角角度 = 滑鼠位移 × 0.022 × 靈敏度(跟 Apex Legends / Source 引擎相同),靈敏度記錄在 config。
|
||||
|
||||
### 時間精度
|
||||
|
||||
| 資料 | 時間精度 | 說明 |
|
||||
|---|---|---|
|
||||
| `mouse_N.csv` | 每一筆回報各自的到達時間(約數十微秒) | 用 Windows Raw Input 在獨立的高優先權執行緒接收,收到當下就蓋時間戳,不等遊戲的幀。系統很忙時(例如載入場景),這條執行緒偶爾會晚一點醒來,幾筆回報會拿到幾乎相同的時間(間隔 < 0.01ms)。實測約佔 0–2%,多數集中在回合剛開始的時候,分析時可以把這種連續的同時間戳視為一小段誤差 |
|
||||
| `frames_N.csv` | 幀 | 遊戲每一幀的狀態 |
|
||||
| `events_N.csv` | 幀 | 開槍、命中等都是遊戲邏輯在幀上產生的 |
|
||||
|
||||
## `mouse_N.csv`:原始滑鼠事件
|
||||
|
||||
每一筆滑鼠回報一列,**不重新取樣、不等間隔**,筆數隨滑鼠回報率而定(約 1000–8000 筆/秒)。只包含玩家的手,**不含**輔助與後座力。
|
||||
每一筆滑鼠回報一列,**不重新取樣、不等間隔**,筆數隨滑鼠回報率而定(約 125–8000 筆/秒)。只包含玩家的手,**不含**輔助與後座力。
|
||||
|
||||
| 欄位 | 說明 |
|
||||
|---|---|
|
||||
| `t` | 事件時間戳 |
|
||||
| `t` | 這一筆回報到達的時間 |
|
||||
| `dx` | 水平位移(往右為正) |
|
||||
| `dy` | 垂直位移(往上為正) |
|
||||
| `left` | 左鍵是否按著 |
|
||||
|
||||
- 遊戲的視角也是讀這份資料,所以**遊戲實際用到的玩家輸入,就是這裡記錄的輸入**。
|
||||
- 只記錄滑鼠真正送出的回報,沒有移動就沒有資料列。
|
||||
|
||||
## `frames_N.csv`:每一幀的狀態
|
||||
|
||||
每一個渲染幀一列(約等於遊戲 FPS)。
|
||||
@@ -61,8 +72,8 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
| 視角 | `yaw`、`pitch` | 滑鼠+輔助累積的角度,不含後座力 |
|
||||
| | `recoil_x`、`recoil_y` | 後座力造成的視角偏移,停火後會自動回正 |
|
||||
| | `view_yaw`、`view_pitch` | 畫面實際的視角 = 前兩組相加 |
|
||||
| 輸入 | `mouse_dx`、`mouse_dy` | 這一幀所有滑鼠事件的總和 |
|
||||
| | `assist_dx`、`assist_dy` | 平滑跟槍這一幀加上的量(滑鼠單位) |
|
||||
| 輸入 | `mouse_dx`、`mouse_dy` | 這一幀套用的所有滑鼠回報總和(= `mouse_N.csv` 中這一幀內的 `dx`、`dy` 加總) |
|
||||
| | `assist_dx`、`assist_dy` | 平滑跟槍這一幀加上的量(滑鼠單位),每一幀套用一次 |
|
||||
| | `sens_scale` | 動態靈敏度的倍率,1 = 沒有作用 |
|
||||
| 玩家 | `px`、`py`、`pz` | 位置 |
|
||||
| | `vx`、`vy`、`vz` | 速度 |
|
||||
@@ -89,7 +100,6 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
|---|---|
|
||||
| `t` | 事件時間 |
|
||||
| `type` | 事件種類(見下表) |
|
||||
| `key` | 按鍵名稱(只有 `key_down` / `key_up` 有) |
|
||||
| `weapon` | 當下的武器 |
|
||||
| `part` | 命中部位:Head / Body / Leg(只有 `hit` 有) |
|
||||
| `damage` | 實際傷害(只有 `hit` 有) |
|
||||
@@ -104,7 +114,8 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
| `kill` | 敵人倒下,回合結束 |
|
||||
| `reload_start` | 開始換彈 |
|
||||
| `pause` / `resume` | 暫停 / 繼續。暫停期間 mouse 和 frames 不會有資料 |
|
||||
| `key_down` / `key_up` | 按下 / 放開按鍵:W A S D、Space(跳)、LeftShift(蹲 / 滑鏟)、R(換彈) |
|
||||
|
||||
不記錄鍵盤按鍵。玩家的移動用 `frames_N.csv` 的位置、速度和 `state` 表示,這是物理引擎實際算出的結果(包含加速度、滑鏟、空中轉向),比按鍵本身更能描述「畫面相對於玩家怎麼動」。
|
||||
|
||||
## `config_N.json`:回合設定與摘要
|
||||
|
||||
@@ -137,10 +148,21 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
|
||||
`truth_*` 是每一幀的真實狀態,`out_*` 是外掛實際拿到、拿來輔助的結果。兩者的差距就是上面三個限制造成的。
|
||||
|
||||
### 輔助的頻率
|
||||
|
||||
| 頻率 | 數值 | 說明 |
|
||||
|---|---|---|
|
||||
| 判斷頻率 | 螢幕刷新率(`refreshRate`) | 外掛每看到一張新畫面,就重新判斷一次要修正多少 |
|
||||
| 輸出頻率 | 遊戲 FPS(可從 `dt` 算出) | 平滑跟槍在每一幀送出一部分修正;兩次判斷之間,會繼續把上一次算出的修正量送完 |
|
||||
|
||||
這對應最常見的軟體外掛行為:每次判斷後,由程式直接修正視角。輔助的修正量不會混進 `mouse_N.csv`,只記錄在 `frames_N.csv` 的 `assist_*`。
|
||||
|
||||
## 分析時要注意
|
||||
|
||||
- **後座力與玩家輸入是分開的**:`mouse_*` 只有手的動作。玩家往下拉,可能是在壓槍,也可能是在追蹤目標,要對照 `recoil_*` 來判斷。
|
||||
- **輔助後的軌跡** = 玩家輸入 + `assist_*`(平滑跟槍),或是玩家輸入 × `sens_scale`(動態靈敏度)。
|
||||
- **玩家輸入與輔助的頻率不同**:`mouse_N.csv` 是原始回報(不等間隔),`assist_*` 是每幀一次。要比較兩者時,可以把滑鼠回報依 `t` 歸到所屬的幀(加總後就是 `mouse_dx`、`mouse_dy`)。
|
||||
- **相對於視角的移動**:用 `yaw` 把 `vx`、`vz` 轉到視角座標,就能得到玩家往準心左右、前後移動的速度。
|
||||
- 每一回合的開頭通常包含「找敵人」的轉身,可以用 `truth_detected` 或螢幕座標,把「找人」和「追蹤瞄準」兩段切開。
|
||||
- 移動方式接近 Apex Legends:按住 W 自動衝刺、可以滑鏟、空中可以轉向。
|
||||
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.InputSystem.Controls;
|
||||
using UnityEngine.InputSystem.LowLevel;
|
||||
|
||||
// 逐筆抓原始輸入 : 每一筆滑鼠回報、每一次有效按鍵都帶自己的時間戳,不對齊到幀、不重新取樣
|
||||
public class InputEventCapture : MonoBehaviour
|
||||
{
|
||||
// t : 事件時間 (秒,跟 Time.realtimeSinceStartupAsDouble 同一條時間軸)
|
||||
public event Action<double, Vector2, bool> MouseEvent; // 時間、位移 (往右、往上為正)、左鍵
|
||||
public event Action<double, string, bool> KeyEvent; // 時間、按鍵名稱、按下 (true) / 放開 (false)
|
||||
|
||||
[Header("要記錄的按鍵 (遊戲裡有作用的才記)")]
|
||||
public Key[] trackedKeys = { Key.W, Key.A, Key.S, Key.D, Key.Space, Key.LeftShift, Key.R, Key.Digit1, Key.Digit2, Key.Digit3, Key.Digit4 };
|
||||
|
||||
[Header("除錯")]
|
||||
[Tooltip("在畫面左上角第二行顯示每秒滑鼠事件數與時間間隔,用來確認有沒有抓到每一筆")]
|
||||
public bool showDebug = true;
|
||||
|
||||
private bool[] keyDown;
|
||||
private int eventsThisSecond;
|
||||
private int eventsPerSecond;
|
||||
private double secondStart;
|
||||
private double lastEventTime;
|
||||
private double minGap = double.MaxValue;
|
||||
private double shownMinGap;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
// 預設 Input System 會把同一幀內的滑鼠事件合併成一筆,關掉才拿得到每一筆
|
||||
InputSystem.settings.disableRedundantEventsMerging = true;
|
||||
InputSystem.onEvent += OnInputEvent;
|
||||
keyDown = new bool[trackedKeys.Length];
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
InputSystem.onEvent -= OnInputEvent;
|
||||
}
|
||||
|
||||
void OnInputEvent(InputEventPtr eventPtr, InputDevice device)
|
||||
{
|
||||
if (!eventPtr.IsA<StateEvent>() && !eventPtr.IsA<DeltaStateEvent>()) return;
|
||||
|
||||
if (device is Mouse mouse)
|
||||
{
|
||||
if (!mouse.delta.ReadValueFromEvent(eventPtr, out Vector2 delta)) return;
|
||||
mouse.leftButton.ReadValueFromEvent(eventPtr, out float left);
|
||||
|
||||
CountForDebug(eventPtr.time);
|
||||
MouseEvent?.Invoke(eventPtr.time, delta, left > 0.5f);
|
||||
}
|
||||
else if (device is Keyboard keyboard)
|
||||
{
|
||||
for (int i = 0; i < trackedKeys.Length; i++)
|
||||
{
|
||||
KeyControl key = keyboard[trackedKeys[i]];
|
||||
if (!key.ReadValueFromEvent(eventPtr, out float value)) continue;
|
||||
|
||||
bool down = value > 0.5f;
|
||||
if (down == keyDown[i]) continue;
|
||||
|
||||
keyDown[i] = down;
|
||||
KeyEvent?.Invoke(eventPtr.time, trackedKeys[i].ToString(), down);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 每秒事件數,以及這一秒內最小的事件間隔 (如果最小間隔接近 0 或剛好等於一幀,代表時間戳是批次蓋的)
|
||||
void CountForDebug(double t)
|
||||
{
|
||||
if (lastEventTime > 0) minGap = Math.Min(minGap, t - lastEventTime);
|
||||
lastEventTime = t;
|
||||
|
||||
eventsThisSecond++;
|
||||
if (t - secondStart >= 1.0)
|
||||
{
|
||||
eventsPerSecond = eventsThisSecond;
|
||||
shownMinGap = minGap == double.MaxValue ? 0 : minGap;
|
||||
eventsThisSecond = 0;
|
||||
minGap = double.MaxValue;
|
||||
secondStart = t;
|
||||
}
|
||||
}
|
||||
|
||||
void OnGUI()
|
||||
{
|
||||
if (!showDebug) return;
|
||||
GUI.Label(new Rect(10, 32, 600, 22),
|
||||
$"滑鼠事件 : {eventsPerSecond} 筆/秒 最小間隔 {shownMinGap * 1000.0:F3}ms (事件時間 {lastEventTime:F4}s / 幀時間 {Time.realtimeSinceStartupAsDouble:F4}s)");
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8552a1057f97a9d42a7f1354ea2c95ee
|
||||
@@ -12,7 +12,6 @@ public class RoundRecorder : MonoBehaviour
|
||||
[Header("參照")]
|
||||
[Tooltip("場景裡的 BotSpawner")]
|
||||
public BotSpawner spawner;
|
||||
public InputEventCapture inputCapture;
|
||||
public PlayerLook playerLook;
|
||||
public PlayerController playerController;
|
||||
public WeaponLoadout loadout;
|
||||
@@ -48,11 +47,6 @@ public class RoundRecorder : MonoBehaviour
|
||||
if (!active) return;
|
||||
|
||||
if (spawner != null) spawner.BotSpawned += StartRound;
|
||||
if (inputCapture != null)
|
||||
{
|
||||
inputCapture.MouseEvent += OnMouseEvent;
|
||||
inputCapture.KeyEvent += OnKeyEvent;
|
||||
}
|
||||
|
||||
// 機器人已經先生成了的話,直接從它開始
|
||||
if (spawner != null && spawner.CurrentBot != null) StartRound(spawner.CurrentBot);
|
||||
@@ -61,11 +55,6 @@ public class RoundRecorder : MonoBehaviour
|
||||
void OnDisable()
|
||||
{
|
||||
if (spawner != null) spawner.BotSpawned -= StartRound;
|
||||
if (inputCapture != null)
|
||||
{
|
||||
inputCapture.MouseEvent -= OnMouseEvent;
|
||||
inputCapture.KeyEvent -= OnKeyEvent;
|
||||
}
|
||||
SubscribeWeapon(null);
|
||||
|
||||
// 離開場景或關遊戲 : 沒打完的回合不存
|
||||
@@ -87,7 +76,7 @@ public class RoundRecorder : MonoBehaviour
|
||||
config = RoundConfig.Create(index),
|
||||
mouse = new CsvWriter(Path.Combine(folder, $"mouse_{index}.csv"), "t,dx,dy,left"),
|
||||
frames = new CsvWriter(Path.Combine(folder, $"frames_{index}.csv"), FrameHeader),
|
||||
events = new CsvWriter(Path.Combine(folder, $"events_{index}.csv"), "t,type,key,weapon,part,damage,bot_hp,ammo"),
|
||||
events = new CsvWriter(Path.Combine(folder, $"events_{index}.csv"), "t,type,weapon,part,damage,bot_hp,ammo"),
|
||||
};
|
||||
|
||||
if (perceptor != null && perceptor.viewCamera != null) round.config.cameraVerticalFov = perceptor.viewCamera.fieldOfView;
|
||||
@@ -101,12 +90,12 @@ public class RoundRecorder : MonoBehaviour
|
||||
{
|
||||
if (round == null || round.bot != bot) return;
|
||||
bot.Died -= OnBotDied;
|
||||
WriteEvent("kill");
|
||||
round.finishing = true;
|
||||
round.finishing = true; // kill 等到這一幀結束才寫,排在致命那一發的 hit 後面
|
||||
}
|
||||
|
||||
void FinishRound()
|
||||
{
|
||||
WriteEvent("kill");
|
||||
RoundConfig c = round.config;
|
||||
c.endTime = Now;
|
||||
c.duration = c.endTime - c.startTime;
|
||||
@@ -166,7 +155,11 @@ public class RoundRecorder : MonoBehaviour
|
||||
if (reloading && !wasReloading) WriteEvent("reload_start");
|
||||
wasReloading = reloading;
|
||||
|
||||
if (!paused) WriteFrame(weapon);
|
||||
if (!paused)
|
||||
{
|
||||
WriteMouseEvents();
|
||||
WriteFrame(weapon);
|
||||
}
|
||||
|
||||
if (round.finishing) FinishRound();
|
||||
}
|
||||
@@ -231,16 +224,14 @@ public class RoundRecorder : MonoBehaviour
|
||||
|
||||
// ===== 事件 =====
|
||||
|
||||
void OnMouseEvent(double t, Vector2 delta, bool left)
|
||||
// 這一幀 Raw Input 收到的每一筆原始回報 (時間是各自到達的時間,不是幀時間)
|
||||
// 跟 PlayerLook 用的是同一份,所以加總會等於 frames 的 mouse_dx / mouse_dy
|
||||
void WriteMouseEvents()
|
||||
{
|
||||
if (round == null || PauseMenu.IsPaused) return;
|
||||
round.mouse.Add(t).Add(delta.x).Add(delta.y).Add(left).EndRow();
|
||||
}
|
||||
|
||||
void OnKeyEvent(double t, string key, bool down)
|
||||
{
|
||||
if (round == null || PauseMenu.IsPaused) return;
|
||||
WriteEvent(down ? "key_down" : "key_up", key, t);
|
||||
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
|
||||
{
|
||||
round.mouse.Add(e.t).Add(e.dx).Add(e.dy).Add(e.left).EndRow();
|
||||
}
|
||||
}
|
||||
|
||||
void SubscribeWeapon(HitscanWeapon weapon)
|
||||
@@ -269,16 +260,16 @@ public class RoundRecorder : MonoBehaviour
|
||||
{
|
||||
if (round == null) return;
|
||||
round.config.hits++;
|
||||
WriteEvent("hit", null, Now, part.ToString(), damage);
|
||||
WriteEvent("hit", part.ToString(), damage);
|
||||
}
|
||||
|
||||
void WriteEvent(string type, string key = null, double t = -1, string part = null, float damage = -1f)
|
||||
void WriteEvent(string type, string part = null, float damage = -1f)
|
||||
{
|
||||
if (round == null) return;
|
||||
|
||||
HitscanWeapon weapon = loadout != null ? loadout.Current : null;
|
||||
CsvWriter w = round.events;
|
||||
w.Add(t >= 0 ? t : Now).Add(type).Add(key).Add(weapon != null && weapon.data != null ? weapon.data.weaponName : "").Add(part);
|
||||
w.Add(Now).Add(type).Add(weapon != null && weapon.data != null ? weapon.data.weaponName : "").Add(part);
|
||||
if (damage >= 0f) w.Add(damage); else w.Empty();
|
||||
w.Add(round.bot != null ? round.bot.Health : 0f).Add(weapon != null ? weapon.Ammo : 0);
|
||||
w.EndRow();
|
||||
|
||||
@@ -65,7 +65,7 @@ public class HitscanWeapon : MonoBehaviour
|
||||
UpdateModelKick();
|
||||
|
||||
// 選單開著 (滑鼠沒鎖定) 時不能開槍
|
||||
if (Cursor.lockState != CursorLockMode.Locked || Mouse.current == null) return;
|
||||
if (Cursor.lockState != CursorLockMode.Locked) return;
|
||||
|
||||
if (Keyboard.current != null && Keyboard.current.rKey.wasPressedThisFrame)
|
||||
{
|
||||
@@ -73,8 +73,8 @@ public class HitscanWeapon : MonoBehaviour
|
||||
}
|
||||
|
||||
bool trigger = data.fullAuto
|
||||
? Mouse.current.leftButton.isPressed
|
||||
: Mouse.current.leftButton.wasPressedThisFrame;
|
||||
? RawMouseInput.LeftHeld
|
||||
: RawMouseInput.LeftPressedThisFrame;
|
||||
|
||||
if (trigger && !IsReloading && Time.time >= nextFireTime)
|
||||
{
|
||||
@@ -106,6 +106,9 @@ public class HitscanWeapon : MonoBehaviour
|
||||
sprayIndex++;
|
||||
lastShotTime = Time.time;
|
||||
|
||||
// 先通知開槍,再判定命中 : 記錄裡的順序才會是 shot → hit
|
||||
Fired?.Invoke();
|
||||
|
||||
// 先射擊再加後座力 : 這一發打在準心上,後座力影響的是下一發
|
||||
for (int i = 0; i < Mathf.Max(1, data.pellets); i++)
|
||||
{
|
||||
@@ -123,8 +126,6 @@ public class HitscanWeapon : MonoBehaviour
|
||||
{
|
||||
Destroy(Instantiate(muzzleFlashPrefab, muzzlePoint.position, muzzlePoint.rotation, muzzlePoint), 0.05f);
|
||||
}
|
||||
|
||||
Fired?.Invoke();
|
||||
}
|
||||
|
||||
// 霰彈的固定圖案 : 第 0 顆在正中間,其餘平均排在散布半徑的圓上
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using UnityEngine;
|
||||
using TMPro;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
public class Movement : MonoBehaviour
|
||||
{
|
||||
@@ -17,22 +16,16 @@ public class Movement : MonoBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (Mouse.current != null)
|
||||
{
|
||||
Vector2 currentDelta = Mouse.current.delta.ReadValue();
|
||||
// 跟遊戲內視角讀同一份 Raw Input 的位移
|
||||
Vector2 currentDelta = RawMouseInput.FrameDelta;
|
||||
|
||||
if (smoothedDelta == Vector2.zero)
|
||||
{
|
||||
smoothedDelta = currentDelta;
|
||||
}
|
||||
else
|
||||
{
|
||||
smoothedDelta = (alpha * currentDelta) + ((1.0f - alpha) * smoothedDelta);
|
||||
}
|
||||
if (smoothedDelta == Vector2.zero)
|
||||
{
|
||||
smoothedDelta = currentDelta;
|
||||
}
|
||||
else
|
||||
{
|
||||
smoothedDelta = Vector2.zero;
|
||||
smoothedDelta = (alpha * currentDelta) + ((1.0f - alpha) * smoothedDelta);
|
||||
}
|
||||
|
||||
displayTimer += Time.unscaledDeltaTime;
|
||||
|
||||
@@ -1,172 +1,71 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using TMPro;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Collections.Generic;
|
||||
|
||||
// 滑鼠回報率 : 用 Raw Input 每一筆回報的真實時間戳算出來 (跟遊戲中記錄的是同一份資料)
|
||||
// 同時也是 Raw Input 有沒有正常運作的檢查
|
||||
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("文字更新間隔 (秒),偵測仍然每幀進行")]
|
||||
[Tooltip("文字更新間隔 (秒)")]
|
||||
public float updateInterval = 0.5f;
|
||||
private float displayTimer = 0f;
|
||||
private int shownHz = -1; // 上次顯示的數值,沒變就不重設文字
|
||||
|
||||
// 與 hook 交換用的暫存 List,避免每幀 new 一個新的
|
||||
private List<double> currentBatch = new List<double>();
|
||||
[Tooltip("超過這麼久沒移動就顯示 0 (秒)")]
|
||||
public float idleTimeout = 2f;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
stopwatch.Start();
|
||||
_proc = HookCallback;
|
||||
_hookID = SetHook(_proc);
|
||||
}
|
||||
// 間隔超過這個就算是停下來了,不拿來算回報率 (秒)
|
||||
private const double MaxGap = 0.02;
|
||||
|
||||
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);
|
||||
}
|
||||
private readonly List<double> gaps = new List<double>();
|
||||
private double lastEventTime;
|
||||
private float displayTimer;
|
||||
private float idleTimer;
|
||||
private int shownHz = -1;
|
||||
|
||||
void Update()
|
||||
{
|
||||
// 把 hook 收集的資料換過來,hook 改寫進清空的那一份
|
||||
currentBatch.Clear();
|
||||
lock (lockObj)
|
||||
if (!RawMouseInput.IsRunning)
|
||||
{
|
||||
List<double> temp = intervals;
|
||||
intervals = currentBatch;
|
||||
currentBatch = temp;
|
||||
SetText("滑鼠回報率: 無法偵測 (" + RawMouseInput.Status + ")", -2);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentBatch.Count > 0)
|
||||
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
|
||||
{
|
||||
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 (e.dx == 0 && e.dy == 0) continue; // 只有按鍵變化的回報不算
|
||||
double gap = e.t - lastEventTime;
|
||||
if (lastEventTime > 0 && gap > 0 && gap < MaxGap) gaps.Add(gap);
|
||||
lastEventTime = e.t;
|
||||
idleTimer = 0f;
|
||||
}
|
||||
idleTimer += 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)
|
||||
// 取間隔的中位數 : 滑鼠慢慢動時偶爾會少送幾筆,中位數比平均穩定
|
||||
if (gaps.Count >= 10)
|
||||
{
|
||||
pollingDisplay.text = $"滑鼠回報率: {maxHz} Hz";
|
||||
shownHz = maxHz;
|
||||
gaps.Sort();
|
||||
int hz = Mathf.RoundToInt((float)(1.0 / gaps[gaps.Count / 2]));
|
||||
SetText($"滑鼠回報率: {hz} Hz", hz);
|
||||
}
|
||||
else if (idleTimer > idleTimeout)
|
||||
{
|
||||
SetText("滑鼠回報率: 0 Hz", 0);
|
||||
}
|
||||
gaps.Clear();
|
||||
}
|
||||
|
||||
#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
|
||||
}
|
||||
void SetText(string text, int code)
|
||||
{
|
||||
if (pollingDisplay == null || code == shownHz) return;
|
||||
shownHz = code;
|
||||
pollingDisplay.text = text;
|
||||
}
|
||||
}
|
||||
@@ -92,17 +92,23 @@ public class SettingsSaver : MonoBehaviour
|
||||
}
|
||||
}
|
||||
|
||||
// 要勾同意書,而且 Raw Input 正常運作 (沒有它就拿不到每一筆的真實時間,資料不能用) ; 測試不受影響
|
||||
void OnConsentChanged(bool isOn)
|
||||
{
|
||||
if (startButton != null)
|
||||
{
|
||||
startButton.interactable = isOn;
|
||||
startButton.interactable = isOn && RawMouseInput.IsRunning;
|
||||
}
|
||||
}
|
||||
|
||||
void OnStartClicked()
|
||||
{
|
||||
if (consentToggle != null && !consentToggle.isOn) return;
|
||||
if (!RawMouseInput.IsRunning)
|
||||
{
|
||||
Debug.LogWarning($"Raw Input 沒有運作 ({RawMouseInput.Status}),無法開始收集資料");
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectPanel != null)
|
||||
{
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
|
||||
|
||||
| 資料 | 時間精度 | 說明 |
|
||||
|---|---|---|
|
||||
| `mouse_N.csv` | 每一筆回報各自的到達時間(約數十微秒) | 用 Windows Raw Input 在獨立執行緒接收,收到當下就蓋時間戳,不等遊戲的幀 |
|
||||
| `mouse_N.csv` | 每一筆回報各自的到達時間(約數十微秒) | 用 Windows Raw Input 在獨立的高優先權執行緒接收,收到當下就蓋時間戳,不等遊戲的幀。系統很忙時(例如載入場景),這條執行緒偶爾會晚一點醒來,幾筆回報會拿到幾乎相同的時間(間隔 < 0.01ms)。實測約佔 0–2%,多數集中在回合剛開始的時候,分析時可以把這種連續的同時間戳視為一小段誤差 |
|
||||
| `frames_N.csv` | 幀 | 遊戲每一幀的狀態 |
|
||||
| `events_N.csv` | 幀 | 開槍、命中等都是遊戲邏輯在幀上產生的 |
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@
|
||||
|
||||
- 螢幕解析度與更新率
|
||||
- StartUI 上的設定(ID、靈敏度、FOV、輔助設定、地圖與武器)
|
||||
- 回合中的滑鼠移動、按鍵、開槍與命中,以及敵人的位置
|
||||
- 回合中的滑鼠移動、開槍與命中,以及你和敵人的位置與移動(不記錄鍵盤按鍵)
|
||||
|
||||
每打倒一隻敵人算一回合,每回合存一份當下的設定和軌跡;打到一半就離開的回合不會保存。暫停期間不記錄。
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
|
||||
匿名貢獻者不需要填 ID;若希望出現在貢獻者名單中,可以在 StartUI 填寫自定義 ID。
|
||||
|
||||
StartUI 顯示的滑鼠回報率,是在 StartUI 開啟期間透過 Windows 的低階滑鼠鉤子(`WH_MOUSE_LL`)量測滑鼠事件的間隔算出來的;只計算間隔、不儲存任何內容,離開 StartUI 就會解除。
|
||||
本程式透過 Windows 的 Raw Input 讀取滑鼠的原始回報(遊戲視角也是用這份資料),以取得每一筆回報的精確時間。**只有遊戲視窗在前景時才會讀取**;切到其他視窗時,滑鼠的任何操作都不會被記錄,關閉遊戲後就會解除。StartUI 顯示的滑鼠回報率也是用這份資料算出來的,在 StartUI 時只顯示、不儲存。
|
||||
|
||||
---
|
||||
|
||||
@@ -123,7 +123,7 @@ StartUI 顯示的滑鼠回報率,是在 StartUI 開啟期間透過 Windows 的
|
||||
- Unity **6000.5.8f1**
|
||||
- Universal Render Pipeline(URP)
|
||||
- Input System(新版輸入系統)
|
||||
- 目前只支援 Windows(回報率偵測使用 Win32 API)
|
||||
- 目前只支援 Windows(滑鼠輸入使用 Win32 Raw Input;其他平台會退回 Unity 的輸入,但無法開始收集資料)
|
||||
|
||||
### 開啟方式
|
||||
|
||||
@@ -146,7 +146,9 @@ Assets/
|
||||
├─ Data/Weapons/ 四把槍的數值 (WeaponData 資產)
|
||||
└─ Stript/
|
||||
├─ Common/
|
||||
│ └─ GameSettings.cs StartUI 與遊戲場景共用的設定 (存成 JSON)
|
||||
│ ├─ GameSettings.cs StartUI 與遊戲場景共用的設定 (存成 JSON)
|
||||
│ ├─ RawMouseInput.cs Raw Input : 背景執行緒接收每一筆滑鼠回報並蓋時間戳,視角與記錄器共用
|
||||
│ └─ RawInputProbe.cs Raw Input 除錯工具 (開發用,F9 存原始資料)
|
||||
├─ StartUI_Interactions/ StartUI 上每個 UI 功能各一支小腳本
|
||||
└─ InGame/
|
||||
├─ PlayerLook.cs 第一人稱視角、靈敏度與 FOV 換算、後座力與輔助接口
|
||||
@@ -169,7 +171,6 @@ Assets/
|
||||
│ ├─ EnemyPerceptor.cs 模擬視覺模型 (遮擋、刷新率取樣、延遲)
|
||||
│ └─ AimAssist.cs 平滑跟槍、動態靈敏度
|
||||
├─ Record/
|
||||
│ ├─ InputEventCapture.cs 逐筆抓原始滑鼠與按鍵事件 (各自帶時間戳)
|
||||
│ ├─ RoundRecorder.cs 一隻敵人一回合,寫出 config / mouse / frames / events
|
||||
│ ├─ RoundConfig.cs config_N.json 的內容
|
||||
│ ├─ CsvWriter.cs 寫 CSV (完成才存,沒打完就刪掉)
|
||||
|
||||
Reference in new issue
Block a user