書審261027

This commit is contained in:
Sahik committed 2026-10-27 23:50:26 +08:00
1 parent 48290de35e
commit 2d36e12f64
13 files changed
+103 -64

No files matched your search

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: aeeadfd0421657043b047d23f2112940
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 19f3b9a0980eb604497d2db8c8e4ea0e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 794ee5cb61c74864fa0ba7639fed2e73
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 718863dcff53b784aa0ffc114381cdd7
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 518d1c1a2372e38479ca8a25bc9b0ee8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0aab1b18335e60849a9f0e022e548980
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+14
View File
@@ -1127,6 +1127,7 @@ GameObject:
- component: {fileID: 343785181}
- component: {fileID: 343785180}
- component: {fileID: 343785179}
- component: {fileID: 343785182}
m_Layer: 0
m_Name: EventSystem
m_TagString: Untagged
@@ -1195,6 +1196,19 @@ Transform:
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &343785182
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 343785178}
m_Enabled: 0
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 8295b3ab5b13e99469d2aa0dda56b5f9, type: 3}
m_Name:
m_EditorClassIdentifier: Assembly-CSharp::InputCompareProbe
keepSeconds: 10
--- !u!1 &407272023
GameObject:
m_ObjectHideFlags: 0
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 58f7e79a87c79824597746e8c1bfe400
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f58d25b9e504a4f41ab4a71cf87c1845
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+31 -14
View File
@@ -7,17 +7,19 @@ using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
// Unity 內建輸入 vs Raw Input 對照工具 (開發用,不要放進正式場景)
// 同一段滑鼠移動,同時用兩條路徑收事件 : Unity Input System 的逐筆事件 (eventPtr.time) 與 RawMouseInput (QPC 時間戳)
// 掛在 Test 場景的任一物件上,移動滑鼠幾秒後按 F10,桌面會出現 unity_probe.csv 與 raw_probe.csv,給 Tools/plot_input_histogram.py 畫圖 3.4
// Windows 一個程式只能有一個視窗接收滑鼠的 Raw Input : RawMouseInput 執行時,Unity Input System 收不到滑鼠事件
// 所以兩邊要輪流錄 : F11 切換模式 (Raw Input ↔ Unity),各自移動滑鼠約 10 秒,F10 把兩邊錄到的存到桌面
// 存出的 unity_probe.csv / raw_probe.csv 給 Tools/plot_input_histogram.py 畫圖 3.4
public class InputCompareProbe : MonoBehaviour
{
[Tooltip("按 F10 存檔時保留最近幾秒")]
[Tooltip("每個模式最多保留最近幾秒")]
public float keepSeconds = 10f;
private struct Ev { public double t; public float dx, dy; }
private readonly List<Ev> unityHistory = new List<Ev>();
private readonly List<Ev> rawHistory = new List<Ev>();
private bool unityMode; // false = 錄 Raw Input、true = 停掉 Raw Input 錄 Unity
private int unityThisSecond, rawThisSecond, unityPerSecond, rawPerSecond;
private float secondTimer;
private string saveMessage = "";
@@ -32,10 +34,12 @@ public class InputCompareProbe : MonoBehaviour
void OnDisable()
{
InputSystem.onEvent -= OnInputEvent;
if (unityMode) RawMouseInput.Begin(); // 離開時把 Raw Input 開回來
}
void OnInputEvent(InputEventPtr eventPtr, InputDevice device)
{
if (!unityMode) return;
if (!eventPtr.IsA<StateEvent>() && !eventPtr.IsA<DeltaStateEvent>()) return;
if (!(device is Mouse mouse)) return;
if (!mouse.delta.ReadValueFromEvent(eventPtr, out Vector2 delta)) return;
@@ -47,15 +51,17 @@ public class InputCompareProbe : MonoBehaviour
void Update()
{
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
if (!unityMode)
{
rawHistory.Add(new Ev { t = e.t, dx = e.dx, dy = e.dy });
rawThisSecond++;
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
{
rawHistory.Add(new Ev { t = e.t, dx = e.dx, dy = e.dy });
rawThisSecond++;
}
}
double cut = Time.realtimeSinceStartupAsDouble - keepSeconds;
Trim(unityHistory, cut);
Trim(rawHistory, cut);
Trim(unityMode ? unityHistory : rawHistory, cut);
secondTimer += Time.unscaledDeltaTime;
if (secondTimer >= 1f)
@@ -64,7 +70,17 @@ public class InputCompareProbe : MonoBehaviour
unityThisSecond = rawThisSecond = 0; secondTimer = 0f;
}
if (Keyboard.current != null && Keyboard.current.f10Key.wasPressedThisFrame) Save();
if (Keyboard.current == null) return;
if (Keyboard.current.f11Key.wasPressedThisFrame) SwitchMode();
if (Keyboard.current.f10Key.wasPressedThisFrame) Save();
}
void SwitchMode()
{
unityMode = !unityMode;
if (unityMode) RawMouseInput.Stop(); // 還原成 Unity 原本的註冊
else RawMouseInput.Begin();
saveMessage = "";
}
static void Trim(List<Ev> list, double cut)
@@ -96,10 +112,11 @@ public class InputCompareProbe : MonoBehaviour
void OnGUI()
{
float y = Screen.height - 80;
GUI.Box(new Rect(10, y - 5, 640, 80), "");
GUI.Label(new Rect(20, y, 620, 22), $"Unity Input System : {unityPerSecond} 筆/秒 Raw Input : {rawPerSecond} 筆/秒 ({RawMouseInput.Status})");
GUI.Label(new Rect(20, y + 20, 620, 22), $"保留最近 {keepSeconds:F0} 秒 : Unity {unityHistory.Count} 筆、Raw {rawHistory.Count} 筆");
GUI.Label(new Rect(20, y + 40, 620, 22), string.IsNullOrEmpty(saveMessage) ? "移動滑鼠幾秒後按 F10 存到桌面 (unity_probe.csv / raw_probe.csv)" : saveMessage);
float y = Screen.height - 100;
GUI.Box(new Rect(10, y - 5, 700, 100), "");
GUI.Label(new Rect(20, y, 680, 22), $"目前模式 : {(unityMode ? "Unity Input System" : "Raw Input")} (F11 切換) Raw Input 狀態 : {RawMouseInput.Status}");
GUI.Label(new Rect(20, y + 20, 680, 22), $"每秒 : Unity {unityPerSecond} 筆、Raw {rawPerSecond} 筆");
GUI.Label(new Rect(20, y + 40, 680, 22), $"已錄 (最近 {keepSeconds:F0} 秒) : Unity {unityHistory.Count} 筆、Raw {rawHistory.Count} 筆");
GUI.Label(new Rect(20, y + 60, 680, 22), string.IsNullOrEmpty(saveMessage) ? "兩個模式都錄過之後按 F10 存到桌面" : saveMessage);
}
}
+2 -1
View File
@@ -177,7 +177,8 @@ public static class RawMouseInput
return RegisterRawInputDevices(rid, 1, (uint)Marshal.SizeOf<RAWINPUTDEVICE>());
}
static void Stop()
// 一般只在關遊戲時呼叫;InputCompareProbe 會暫時停掉,讓 Unity Input System 拿回滑鼠做對照
public static void Stop()
{
Application.quitting -= Stop;
if (!IsRunning) return;
Binary file not shown.
-49
View File
@@ -1,49 +0,0 @@
# -*- coding: utf-8 -*-
# 圖 3.4 : Unity 內建輸入 vs Raw Input 的相鄰回報時間間隔直方圖
# 用法 : python plot_input_histogram.py <unity_probe.csv> <raw_probe.csv> [輸出.jpg] [滑鼠回報率Hz]
# 兩個 csv 來自 InputCompareProbe (Test 場景按 F10 存到桌面),欄位 t,dx,dy
import sys, os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager
for name in ['Microsoft JhengHei', 'Noto Sans CJK TC', 'PingFang TC', 'Microsoft YaHei']:
if any(f.name == name for f in font_manager.fontManager.ttflist):
plt.rcParams['font.family'] = name; break
plt.rcParams['axes.unicode_minus'] = False
unity_path, raw_path = sys.argv[1], sys.argv[2]
out = sys.argv[3] if len(sys.argv) > 3 else os.path.join(os.path.dirname(os.path.abspath(unity_path)), 'fig3_4_input_histogram.jpg')
hz = float(sys.argv[4]) if len(sys.argv) > 4 else None
def gaps_ms(path):
t = np.loadtxt(path, delimiter=',', skiprows=1, usecols=0, ndmin=1)
t = np.sort(t)
return np.diff(t) * 1000.0
data = [('Unity Input System(引擎內建)', gaps_ms(unity_path)), ('Windows Raw Input(本研究)', gaps_ms(raw_path))]
lo, hi = 1e-3, 50.0
bins = np.logspace(np.log10(lo), np.log10(hi), 80)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), sharey=True)
for ax, (title, g) in zip(axes, data):
g = np.clip(g, lo, hi)
w = np.full(len(g), 100.0 / len(g)) # 縱軸 : 佔所有相鄰回報的百分比
ax.hist(g, bins=bins, weights=w, color='#4C78A8', edgecolor='white', linewidth=0.3)
ax.set_xscale('log'); ax.set_xlim(lo, hi); ax.grid(alpha=0.3, which='both', linewidth=0.5)
ax.set_title(title, fontsize=11); ax.set_xlabel('相鄰回報的時間間隔 (ms,對數刻度)')
med = np.median(g); near0 = 100.0 * (g < 0.01).mean()
ax.axvline(med, color='#333333', linestyle='--', linewidth=1)
ax.text(0.98, 0.95, f'事件數 {len(g) + 1:,}\n中位數 {med:.3f} ms\n< 0.01 ms 的比例 {near0:.0f}%',
transform=ax.transAxes, ha='right', va='top', fontsize=9,
bbox=dict(boxstyle='round,pad=0.4', facecolor='white', edgecolor='#999999', linewidth=0.6))
if hz:
ax.axvline(1000.0 / hz, color='#D62728', linestyle=':', linewidth=1)
ax.text(1000.0 / hz, ax.get_ylim()[1] if ax.get_ylim()[1] > 0 else 1, f' 1/{hz:.0f} Hz', color='#D62728', fontsize=8, va='top')
axes[0].set_ylabel('佔比 (%)')
fig.tight_layout(); fig.savefig(out, dpi=200); plt.close(fig)
print('已存', out)
for title, g in data:
print(f'{title} : 事件 {len(g) + 1},中位數 {np.median(g):.3f} ms,< 0.01 ms {100 * (g < 0.01).mean():.1f}%,10%~90% {np.percentile(g, 10):.3f}~{np.percentile(g, 90):.3f} ms')