新增軌跡記錄器與匯出至unity內(滑鼠軌跡本身將改為raw input)

This commit is contained in:
Sahik committed 2026-10-23 01:15:01 +08:00
1 parent 9e8b520bec
commit 14140797ba
30 files changed
+2299 -22

No files matched your search

+4
View File
@@ -26,6 +26,9 @@ public class BotSpawner : MonoBehaviour
// 目前活著的機器人,倒下到重生之間是 null (給方位指示等 UI 用)
public BotHealth CurrentBot { get; private set; }
// 新的一隻生成時通知 (記錄器用來開始一回合)
public event System.Action<BotHealth> BotSpawned;
void Start()
{
Spawn();
@@ -44,6 +47,7 @@ public class BotSpawner : MonoBehaviour
{
health.Died += OnBotDied;
CurrentBot = health;
BotSpawned?.Invoke(health);
}
}
+97
View File
@@ -0,0 +1,97 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
// 遊戲中按 Esc 暫停 : 時間停止、放開滑鼠,選「繼續」或「回到主畫面」
// 暫停期間記錄器不記錄,回合照樣有效
public class PauseMenu : MonoBehaviour
{
[Header("UI 參照")]
[Tooltip("暫停視窗 (Panel),平常隱藏")]
public GameObject pausePanel;
[Tooltip("繼續 Button")]
public Button resumeButton;
[Tooltip("回到主畫面 Button")]
public Button menuButton;
[Header("場景")]
public string startSceneName = "StartUI";
// 給其他腳本判斷 (視角、記錄器)
public static bool IsPaused { get; private set; }
void Start()
{
EnsureButtonsClickable();
if (pausePanel != null) pausePanel.SetActive(false);
if (resumeButton != null) resumeButton.onClick.AddListener(Resume);
if (menuButton != null) menuButton.onClick.AddListener(BackToMenu);
}
void Update()
{
if (Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)
{
if (IsPaused) Resume();
else Pause();
}
}
void OnDestroy()
{
// 離開場景時一定要恢復,不然下一個場景會停住
IsPaused = false;
Time.timeScale = 1f;
}
// 按鈕要能點,需要 : 場景裡有 EventSystem、Canvas 上有 Graphic Raycaster
// 地圖場景不一定有 (例如沙漠是從 Demo 場景改的),缺的話這裡自動補上
void EnsureButtonsClickable()
{
if (EventSystem.current == null && FindAnyObjectByType<EventSystem>() == null)
{
GameObject es = new GameObject("EventSystem");
es.AddComponent<EventSystem>();
es.AddComponent<InputSystemUIInputModule>();
}
Canvas canvas = pausePanel != null ? pausePanel.GetComponentInParent<Canvas>(true) : null;
if (canvas != null && canvas.GetComponent<GraphicRaycaster>() == null)
{
canvas.gameObject.AddComponent<GraphicRaycaster>();
}
}
void Pause()
{
IsPaused = true;
Time.timeScale = 0f;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
if (pausePanel != null) pausePanel.SetActive(true);
}
void Resume()
{
IsPaused = false;
Time.timeScale = 1f;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
if (pausePanel != null) pausePanel.SetActive(false);
}
void BackToMenu()
{
IsPaused = false;
Time.timeScale = 1f;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
SceneManager.LoadScene(startSceneName);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0b543f6432600754399dfc02c04847b2
+11 -1
View File
@@ -65,6 +65,12 @@ public class PlayerLook : MonoBehaviour
timeSinceRecoil = 0f;
}
// ===== 給記錄器用 =====
public float Yaw => yaw; // 滑鼠 + 輔助累積的水平角度 (度),不含後座力
public float Pitch => -pitch; // 同上的垂直角度,往上為正
public Vector2 LastMouseDelta { get; private set; } // 這一幀玩家的滑鼠位移 (滑鼠單位)
public Vector2 LastAssistDelta { get; private set; } // 這一幀平滑跟槍加的量 (滑鼠單位)
// =============================
void Start()
@@ -84,7 +90,11 @@ public class PlayerLook : MonoBehaviour
void Update()
{
Vector2 mouseDelta = Mouse.current != null ? Mouse.current.delta.ReadValue() : Vector2.zero;
// 暫停時不讀滑鼠,視角不會跟著轉
Vector2 mouseDelta = Mouse.current != null && !PauseMenu.IsPaused ? Mouse.current.delta.ReadValue() : Vector2.zero;
LastMouseDelta = mouseDelta;
LastAssistDelta = pendingAssistDelta;
// 玩家輸入套用 (可被動態靈敏度改變) + 輔助位移
Vector2 totalDelta = mouseDelta * sensitivityScale + pendingAssistDelta;
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 46f1c84b8ced7174aaaf8311490b0424
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+87
View File
@@ -0,0 +1,87 @@
using System.Globalization;
using System.IO;
using System.Text;
// 寫 CSV 的小工具 : 先寫到 .tmp,回合完成才 Commit 改成正式檔名,沒完成就 Discard 刪掉
// 數字一律用 InvariantCulture (小數點是 .,不受電腦語言設定影響)
public class CsvWriter
{
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
private readonly string finalPath;
private readonly string tmpPath;
private readonly StreamWriter writer;
private readonly StringBuilder row = new StringBuilder(512);
public int Rows { get; private set; }
public CsvWriter(string path, string header)
{
finalPath = path;
tmpPath = path + ".tmp";
writer = new StreamWriter(tmpPath, false, new UTF8Encoding(false), 1 << 16);
writer.WriteLine(header);
}
public CsvWriter Add(double value, string format = "0.######")
{
Separator();
row.Append(value.ToString(format, Inv));
return this;
}
public CsvWriter Add(float value) => Add((double)value);
public CsvWriter Add(int value)
{
Separator();
row.Append(value.ToString(Inv));
return this;
}
public CsvWriter Add(bool value)
{
Separator();
row.Append(value ? '1' : '0');
return this;
}
public CsvWriter Add(string value)
{
Separator();
if (!string.IsNullOrEmpty(value)) row.Append(value.Replace(',', ' '));
return this;
}
// 空欄位 (這個事件沒有這項資料)
public CsvWriter Empty()
{
Separator();
return this;
}
public void EndRow()
{
writer.WriteLine(row.ToString());
row.Clear();
Rows++;
}
public void Commit()
{
writer.Dispose();
if (File.Exists(finalPath)) File.Delete(finalPath);
File.Move(tmpPath, finalPath);
}
public void Discard()
{
writer.Dispose();
if (File.Exists(tmpPath)) File.Delete(tmpPath);
}
void Separator()
{
if (row.Length > 0) row.Append(',');
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 119eb7ddc12151a469d98be1f99814a3
@@ -0,0 +1,151 @@
// 自動產生 : 內容與 Docs/Dataset.md 相同,修改時請兩邊一起改 (打包資料時寫成 zip 裡的 README.md)
public static class DatasetReadme
{
public const string Text = @"# Mouse Trail Collector 資料集說明
本資料集記錄玩家在簡化的 FPS 靶場中,追蹤並射擊移動目標時的**原始滑鼠輸入**與遊戲狀態。每一回合可能是「無輔助」(純人手),也可能是「模擬 AI 視覺外掛輔助」,用途是訓練分辨兩者的模型。
## 資料夾結構
每次執行遊戲會產生一個 zip:
```
MouseTrail_<ID>_<yyyyMMdd_HHmmss>.zip
├─ README.md 本文件
├─ config_0.json 第 0 回合的設定與摘要
├─ mouse_0.csv 第 0 回合的原始滑鼠事件
├─ frames_0.csv 第 0 回合每一幀的狀態
├─ events_0.csv 第 0 回合的離散事件
├─ config_1.json
└─ ...
```
- **一回合 = 一隻敵人**:從敵人出現開始,到敵人被擊倒為止。
- 只收錄完整打完的回合;打到一半就離開的回合不會出現。
- 同一個 zip 裡的回合,設定可能不同,因為玩家可以中途回主畫面調整,所以每一回合都有自己的 `config_N.json`。
- 測試模式不會產生資料。
## 慣例
| 項目 | 慣例 |
|---|---|
| 時間 | 秒,`Time.realtimeSinceStartupAsDouble` 時間軸(遊戲啟動後的秒數)。同一個 zip 裡的所有檔案共用這條時間軸 |
| 角度 | 度。水平往右、垂直往上為正 |
| 滑鼠位移 | 滑鼠回報的原始單位(counts),往右、往上為正 |
| 位置 / 速度 | 公尺、公尺/秒,Unity 世界座標(Y 軸朝上) |
| 螢幕座標 | 像素,相對畫面中心,往右、往上為正 |
| 布林值 | 0 / 1 |
| 小數點 | `.`(不受系統語言影響) |
**靈敏度換算**:視角角度 = 滑鼠位移 × 0.022 × 靈敏度(跟 Apex Legends / Source 引擎相同),靈敏度記錄在 config。
## `mouse_N.csv`:原始滑鼠事件
每一筆滑鼠回報一列,**不重新取樣、不等間隔**,筆數隨滑鼠回報率而定(約 1000–8000 筆/秒)。只包含玩家的手,**不含**輔助與後座力。
| 欄位 | 說明 |
|---|---|
| `t` | 事件時間戳 |
| `dx` | 水平位移(往右為正) |
| `dy` | 垂直位移(往上為正) |
| `left` | 左鍵是否按著 |
## `frames_N.csv`:每一幀的狀態
每一個渲染幀一列(約等於遊戲 FPS)。
| 分類 | 欄位 | 說明 |
|---|---|---|
| 時間 | `t` | 這一幀的時間 |
| | `dt` | 與上一幀的間隔 |
| 視角 | `yaw`、`pitch` | 滑鼠+輔助累積的角度,不含後座力 |
| | `recoil_x`、`recoil_y` | 後座力造成的視角偏移,停火後會自動回正 |
| | `view_yaw`、`view_pitch` | 畫面實際的視角 = 前兩組相加 |
| 輸入 | `mouse_dx`、`mouse_dy` | 這一幀所有滑鼠事件的總和 |
| | `assist_dx`、`assist_dy` | 平滑跟槍這一幀加上的量(滑鼠單位) |
| | `sens_scale` | 動態靈敏度的倍率,1 = 沒有作用 |
| 玩家 | `px`、`py`、`pz` | 位置 |
| | `vx`、`vy`、`vz` | 速度 |
| | `state` | 移動狀態(MotionCore 的狀態名稱):Idle / Moving / Jumping / Falling / Crouching / PlayerSlide(滑鏟)/ Sliding(斜坡下滑)/ Vaulting(翻越) |
| 敵人 | `bx`、`by`、`bz` | 位置 |
| | `bvx`、`bvy`、`bvz` | 速度 |
| | `bot_hp` | 剩餘血量(滿血 500) |
| 感知器真值 | `truth_detected` | 這一幀實際上能不能偵測到敵人 |
| | `truth_visible` | 敵人沒被擋住的比例(0–1) |
| | `truth_err_x`、`truth_err_y` | 準心到敵人胸口的角度誤差 |
| | `truth_screen_x`、`truth_screen_y` | 敵人胸口的螢幕座標 |
| 外掛拿到的結果 | `out_detected` | 經過取樣與延遲後,外掛手上的結果有沒有偵測到 |
| | `out_err_x`、`out_err_y` | 外掛手上的角度誤差(是擷取當時的舊畫面) |
| | `out_age_ms` | 這份結果是多久以前擷取的(毫秒),也就是外掛手上的資訊有多舊 |
| | `out_delay_ms` | 這份結果的延遲 |
| 輔助 | `assist_engaged` | 這一幀輔助有沒有作用 |
| | `assist_fov` | 輔助作用範圍半徑(度) |
| 武器 | `ammo` | 彈匣剩餘 |
| | `reloading` | 是否換彈中 |
## `events_N.csv`:離散事件
| 欄位 | 說明 |
|---|---|
| `t` | 事件時間 |
| `type` | 事件種類(見下表) |
| `key` | 按鍵名稱(只有 `key_down` / `key_up` 有) |
| `weapon` | 當下的武器 |
| `part` | 命中部位:Head / Body / Leg(只有 `hit` 有) |
| `damage` | 實際傷害(只有 `hit` 有) |
| `bot_hp` | 事件後敵人剩餘的血量 |
| `ammo` | 事件後彈匣剩餘 |
| `type` | 說明 |
|---|---|
| `round_start` | 敵人出現,回合開始 |
| `shot` | 開一槍(霰彈槍一發只記一次) |
| `hit` | 命中一次(霰彈的每顆彈丸各記一次) |
| `kill` | 敵人倒下,回合結束 |
| `reload_start` | 開始換彈 |
| `pause` / `resume` | 暫停 / 繼續。暫停期間 mouse 和 frames 不會有資料 |
| `key_down` / `key_up` | 按下 / 放開按鍵:W A S D、Space(跳)、LeftShift(蹲 / 滑鏟)、R(換彈) |
## `config_N.json`:回合設定與摘要
| 欄位 | 說明 |
|---|---|
| `contributorID` | 貢獻者 ID,匿名時為 `Anonymous` |
| `sensitivity`、`fov` | 靈敏度、FOV(以 4:3 畫面為基準的水平 FOV,跟 Apex 相同) |
| `assistMode` | 0 = 無輔助、1 = 平滑跟槍、2 = 動態靈敏度 |
| `assistStrength` | 輔助強度 1–100(無輔助時為 0) |
| `assistDelayMs`、`assistDelayJitter` | 模擬辨識延遲(ms)、是否加上 ±5ms 抖動 |
| `disableHorizontalAssist`、`disableVerticalAssist` | 是否停用水平 / 垂直方向的輔助 |
| `map`、`weapon` | 地圖、武器 |
| `screenWidth`、`screenHeight`、`refreshRate` | 解析度與螢幕刷新率 |
| `roundIndex` | 回合編號(同一次執行中由 0 往上加) |
| `startTimeLocal` | 回合開始的實際時間(ISO 8601) |
| `startTime`、`endTime`、`duration`、`pausedSeconds` | 開始與結束時間(同 CSV 的時間軸)、時長、暫停總秒數 |
| `shots`、`hits`、`mouseEvents`、`frames` | 開槍數、命中數、滑鼠事件數、幀數 |
| `recoilSeed` | 後座力隨機部分的種子 |
| `cameraVerticalFov`、`fixedDeltaTime` | 相機實際的垂直 FOV、物理更新間隔 |
| `appVersion`、`unityVersion` | 程式與 Unity 版本 |
| `savedTime`、`isTest` | StartUI 存檔的時間、是否為測試模式(資料集中一律為 false) |
## 模擬視覺模型
有輔助的回合中,輔助使用的敵人位置來自「模擬 AI 視覺模型」。它直接讀取敵人的骨架位置(完美感知器),只加上三個真實外掛本來就有的限制,**不做插值或預測**:
1. **依螢幕刷新率取樣**:外掛是擷取畫面,畫面一秒只更新刷新率那麼多次。
2. **辨識延遲**:擷取 → 辨識 → 輸出需要時間,延遲值記錄在 `assistDelayMs`。
3. **被擋住 25% 以上就偵測不到**:視覺辨識看不到被遮住的目標。
`truth_*` 是每一幀的真實狀態,`out_*` 是外掛實際拿到、拿來輔助的結果。兩者的差距就是上面三個限制造成的。
## 分析時要注意
- **後座力與玩家輸入是分開的**:`mouse_*` 只有手的動作。玩家往下拉,可能是在壓槍,也可能是在追蹤目標,要對照 `recoil_*` 來判斷。
- **輔助後的軌跡** = 玩家輸入 + `assist_*`(平滑跟槍),或是玩家輸入 × `sens_scale`(動態靈敏度)。
- 每一回合的開頭通常包含「找敵人」的轉身,可以用 `truth_detected` 或螢幕座標,把「找人」和「追蹤瞄準」兩段切開。
- 移動方式接近 Apex Legends:按住 W 自動衝刺、可以滑鏟、空中可以轉向。
## 隱私
資料不含姓名或帳號等個人資訊,只有貢獻者自己填的 ID(可匿名)。只在遊戲回合中記錄,不記錄遊戲以外的任何操作。
";
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6ec9c17bd52f8ae45915a1b7e208bb13
@@ -0,0 +1,93 @@
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)");
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8552a1057f97a9d42a7f1354ea2c95ee
@@ -0,0 +1,43 @@
using System;
using UnityEngine;
// config_N.json 的內容 : 當下完整的 GameSettings + 這一回合的資訊
// 直接繼承 GameSettings,之後 StartUI 多了什麼設定,這裡會自動跟著記錄
[Serializable]
public class RoundConfig : GameSettings
{
// 回合資訊 (時間都是 Time.realtimeSinceStartupAsDouble 時間軸,跟 CSV 一致)
public int roundIndex;
public string startTimeLocal; // 開始的實際時間 (ISO 8601)
public double startTime;
public double endTime;
public double duration;
public double pausedSeconds;
// 摘要
public int shots;
public int hits;
public int mouseEvents;
public int frames;
// 重現與分析用
public int recoilSeed;
public float cameraVerticalFov;
public float fixedDeltaTime;
public string appVersion;
public string unityVersion;
public static RoundConfig Create(int index)
{
RoundConfig c = new RoundConfig();
JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(Load()), c); // 複製目前存檔的設定
c.roundIndex = index;
c.startTimeLocal = DateTime.Now.ToString("o");
c.startTime = Time.realtimeSinceStartupAsDouble;
c.fixedDeltaTime = Time.fixedDeltaTime;
c.appVersion = Application.version;
c.unityVersion = Application.unityVersion;
return c;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1a061d08391ff024f87ee9b0bdb89964
@@ -0,0 +1,288 @@
using System;
using System.IO;
using UnityEngine;
using CharacterMovement;
// 一隻機器人 = 一回合 : 生成時開始記錄,倒下時存成 config_N.json + mouse_N.csv + frames_N.csv + events_N.csv
// 打到一半離開場景的回合直接丟掉 ; 暫停期間不記錄 (回合照樣有效)
// 欄位說明見 Docs/Dataset.md
[DefaultExecutionOrder(100)] // 等視角、感知器、輔助都更新完才寫這一幀
public class RoundRecorder : MonoBehaviour
{
[Header("參照")]
[Tooltip("場景裡的 BotSpawner")]
public BotSpawner spawner;
public InputEventCapture inputCapture;
public PlayerLook playerLook;
public PlayerController playerController;
public WeaponLoadout loadout;
public EnemyPerceptor perceptor;
public AimAssist aimAssist;
[Header("開發用")]
[Tooltip("測試模式預設不記錄,開發時勾起來可以在 Test 場景驗證")]
public bool recordInTestMode = false;
// 一回合進行中的資料 ; 沒有回合時是 null
private class Round
{
public RoundConfig config;
public BotHealth bot;
public CsvWriter mouse;
public CsvWriter frames;
public CsvWriter events;
public double pauseStart;
public bool finishing; // 機器人倒下了,等這一幀結束再存 (同一幀最後一發的命中也要記到)
}
private Round round;
private bool active;
private bool wasPaused;
private bool wasReloading;
private HitscanWeapon subscribedWeapon;
void OnEnable()
{
GameSettings settings = GameSettings.Load();
active = !settings.isTest || recordInTestMode;
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);
}
void OnDisable()
{
if (spawner != null) spawner.BotSpawned -= StartRound;
if (inputCapture != null)
{
inputCapture.MouseEvent -= OnMouseEvent;
inputCapture.KeyEvent -= OnKeyEvent;
}
SubscribeWeapon(null);
// 離開場景或關遊戲 : 沒打完的回合不存
DiscardRound();
}
// ===== 回合 =====
void StartRound(BotHealth bot)
{
DiscardRound();
int index = SessionStorage.TakeRoundIndex();
string folder = SessionStorage.Folder;
round = new Round
{
bot = bot,
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"),
};
if (perceptor != null && perceptor.viewCamera != null) round.config.cameraVerticalFov = perceptor.viewCamera.fieldOfView;
if (loadout != null && loadout.Current != null) round.config.recoilSeed = loadout.Current.RecoilSeed;
bot.Died += OnBotDied;
WriteEvent("round_start");
}
void OnBotDied(BotHealth bot)
{
if (round == null || round.bot != bot) return;
bot.Died -= OnBotDied;
WriteEvent("kill");
round.finishing = true;
}
void FinishRound()
{
RoundConfig c = round.config;
c.endTime = Now;
c.duration = c.endTime - c.startTime;
c.mouseEvents = round.mouse.Rows;
c.frames = round.frames.Rows;
round.mouse.Commit();
round.frames.Commit();
round.events.Commit();
File.WriteAllText(Path.Combine(SessionStorage.Folder, $"config_{c.roundIndex}.json"), JsonUtility.ToJson(c, true));
SessionStorage.MarkRoundSaved();
Debug.Log($"第 {c.roundIndex} 回合已存檔 ({c.duration:F1} 秒,{c.mouseEvents} 筆滑鼠事件,{c.frames} 幀)");
round = null;
}
void DiscardRound()
{
if (round == null) return;
if (round.bot != null) round.bot.Died -= OnBotDied;
round.mouse.Discard();
round.frames.Discard();
round.events.Discard();
round = null;
}
// ===== 每一幀 =====
void LateUpdate()
{
if (!active) return;
HitscanWeapon weapon = loadout != null ? loadout.Current : null;
if (weapon != subscribedWeapon) SubscribeWeapon(weapon);
if (round == null) return;
// 暫停 / 繼續
bool paused = PauseMenu.IsPaused;
if (paused != wasPaused)
{
wasPaused = paused;
if (paused)
{
round.pauseStart = Now;
WriteEvent("pause");
}
else
{
round.config.pausedSeconds += Now - round.pauseStart;
WriteEvent("resume");
}
}
// 換彈開始
bool reloading = weapon != null && weapon.IsReloading;
if (reloading && !wasReloading) WriteEvent("reload_start");
wasReloading = reloading;
if (!paused) WriteFrame(weapon);
if (round.finishing) FinishRound();
}
const string FrameHeader =
"t,dt,yaw,pitch,recoil_x,recoil_y,view_yaw,view_pitch," +
"mouse_dx,mouse_dy,assist_dx,assist_dy,sens_scale," +
"px,py,pz,vx,vy,vz,state," +
"bx,by,bz,bvx,bvy,bvz,bot_hp," +
"truth_detected,truth_visible,truth_err_x,truth_err_y,truth_screen_x,truth_screen_y," +
"out_detected,out_err_x,out_err_y,out_age_ms,out_delay_ms," +
"assist_engaged,assist_fov,ammo,reloading";
void WriteFrame(HitscanWeapon weapon)
{
CsvWriter w = round.frames;
w.Add(Now).Add(Time.unscaledDeltaTime);
// 視角
Vector2 recoil = playerLook != null ? playerLook.RecoilOffset : Vector2.zero;
float yaw = playerLook != null ? playerLook.Yaw : 0f;
float pitch = playerLook != null ? playerLook.Pitch : 0f;
w.Add(yaw).Add(pitch).Add(recoil.x).Add(recoil.y).Add(yaw + recoil.x).Add(pitch + recoil.y);
// 這一幀的輸入
Vector2 mouse = playerLook != null ? playerLook.LastMouseDelta : Vector2.zero;
Vector2 assist = playerLook != null ? playerLook.LastAssistDelta : Vector2.zero;
w.Add(mouse.x).Add(mouse.y).Add(assist.x).Add(assist.y).Add(playerLook != null ? playerLook.sensitivityScale : 1f);
// 玩家
Vector3 p = playerController != null ? playerController.transform.position : Vector3.zero;
Vector3 v = playerController != null && playerController.RigidBody != null ? playerController.RigidBody.linearVelocity : Vector3.zero;
w.Add(p.x).Add(p.y).Add(p.z).Add(v.x).Add(v.y).Add(v.z).Add(StateName());
// 機器人
BotHealth bot = round.bot;
Vector3 bp = bot != null ? bot.transform.position : Vector3.zero;
Vector3 bv = bot != null && bot.TryGetComponent(out Rigidbody rb) ? rb.linearVelocity : Vector3.zero;
w.Add(bp.x).Add(bp.y).Add(bp.z).Add(bv.x).Add(bv.y).Add(bv.z).Add(bot != null ? bot.Health : 0f);
// 感知器真值與外掛拿到的結果
EnemyPerceptor.Detection truth = perceptor != null ? perceptor.Truth : default;
EnemyPerceptor.Detection output = perceptor != null ? perceptor.Output : default;
w.Add(truth.detected).Add(truth.visibleRatio).Add(truth.angleError.x).Add(truth.angleError.y)
.Add(truth.screenOffset.x).Add(truth.screenOffset.y);
w.Add(output.detected).Add(output.angleError.x).Add(output.angleError.y)
.Add((Time.time - output.captureTime) * 1000f).Add(output.delay * 1000f);
// 輔助與武器
w.Add(aimAssist != null && aimAssist.Engaged).Add(aimAssist != null ? aimAssist.FovRadius : 0f);
w.Add(weapon != null ? weapon.Ammo : 0).Add(weapon != null && weapon.IsReloading);
w.EndRow();
}
// MotionCore 的狀態名稱,去掉結尾的 State : Idle / Moving / Jumping / Falling / Crouching / PlayerSlide ...
string StateName()
{
if (playerController == null || playerController.CurrentState == null) return "";
string name = playerController.CurrentState.GetType().Name;
return name.EndsWith("State") ? name.Substring(0, name.Length - 5) : name;
}
// ===== 事件 =====
void OnMouseEvent(double t, Vector2 delta, bool left)
{
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);
}
void SubscribeWeapon(HitscanWeapon weapon)
{
if (subscribedWeapon != null)
{
subscribedWeapon.Fired -= OnFired;
subscribedWeapon.HitLanded -= OnHitLanded;
}
subscribedWeapon = weapon;
if (subscribedWeapon != null)
{
subscribedWeapon.Fired += OnFired;
subscribedWeapon.HitLanded += OnHitLanded;
}
}
void OnFired()
{
if (round == null) return;
round.config.shots++;
WriteEvent("shot");
}
void OnHitLanded(BodyPart part, float damage)
{
if (round == null) return;
round.config.hits++;
WriteEvent("hit", null, Now, part.ToString(), damage);
}
void WriteEvent(string type, string key = null, double t = -1, 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);
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();
}
static double Now => Time.realtimeSinceStartupAsDouble;
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 78cc55a9d725ad64eb4bd5c563014985
@@ -0,0 +1,74 @@
using System;
using System.IO;
using System.IO.Compression;
using UnityEngine;
// 這次執行遊戲的資料夾與回合編號 ; 關遊戲時把整個資料夾打包成 zip 放到桌面
// 跨場景共用 (回主畫面調參數再回來,回合編號會接著往下)
public static class SessionStorage
{
private static string folder;
private static string startStamp;
private static int nextRoundIndex;
private static int savedRounds;
// 第一次用到時才建立 : persistentDataPath/Sessions/<開始時間>/
public static string Folder
{
get
{
if (folder == null)
{
startStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
folder = Path.Combine(Application.persistentDataPath, "Sessions", startStamp);
Directory.CreateDirectory(folder);
}
return folder;
}
}
public static int TakeRoundIndex() => nextRoundIndex++;
public static void MarkRoundSaved() => savedRounds++;
// 每次進入 Play 都重設 (編輯器關掉 Domain Reload 時,static 不會自動清空)
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void Init()
{
folder = null;
nextRoundIndex = 0;
savedRounds = 0;
Application.quitting -= OnQuitting;
Application.quitting += OnQuitting;
}
// 關遊戲 (或編輯器停止 Play) 時 : 有完成的回合才打包
static void OnQuitting()
{
if (folder == null || savedRounds == 0) return;
try
{
File.WriteAllText(Path.Combine(folder, "README.md"), DatasetReadme.Text);
string id = SafeFileName(GameSettings.Load().contributorID);
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string zipPath = Path.Combine(desktop, $"MouseTrail_{id}_{startStamp}.zip");
if (File.Exists(zipPath)) File.Delete(zipPath);
ZipFile.CreateFromDirectory(folder, zipPath);
Debug.Log($"資料已打包到 : {zipPath} (原始資料保留在 {folder})");
}
catch (Exception e)
{
Debug.LogError($"打包資料失敗,原始資料仍在 {folder} : {e.Message}");
}
}
static string SafeFileName(string name)
{
if (string.IsNullOrEmpty(name)) return "Anonymous";
foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_');
return name;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8d1c481656837f241a06013dc84c3378