Răsfoiți Sursa

【初始】实现镜内 PiP 分辨率调节插件

SPT 4.1.x 客户端插件,可调节光学瞄具镜内 PiP 相机的方形 RenderTexture 边长。

- 通过 Harmony prefix 覆盖 OpticCameraManager.SetResolution 入参,使游戏 Init() 直接按目标分辨率创建 RT,避免二次重建造成的闪烁。
- 支持「游戏默认 / 屏幕高度比例 / 绝对像素」三种取值,默认不改变游戏行为。
- 调参复用 BepInEx ConfigurationManager 菜单,不提供自定义界面与热键。
- 分辨率换算与应用决策为纯逻辑层,配套单元测试。
- 公共 CI 无法获取专有客户端程序集,仅运行纯逻辑单测;发行包需本地打包。
PJ568 1 lună în urmă
comite
12512ac104

+ 23 - 0
.githooks/commit-msg

@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# commit-msg 钩子:检查提交信息(语法 + 排版)
+# 1. 语法检查:scripts/check-grammar.mjs(基于 git-commit-regulation 规范)
+# 2. 排版检查:autocorrect --lint(汉字与英文、数字、符号间空格)
+# 启用:git config core.hooksPath .githooks
+# 可绕过:git commit --no-verify(远程 CI 门禁不可绕过)
+
+# 当前钩子所在目录 | Current Hook Directory
+HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# 1. 语法检查(透传退出码)
+node "$HOOK_DIR/../scripts/check-grammar.mjs" --file "$1" || exit $?
+
+# 2. 排版检查:过滤 git 注释行后交给 autocorrect --lint --stdin
+#    未安装 autocorrect 时跳过(语法检查仍生效)
+if command -v autocorrect > /dev/null 2>&1; then
+  grep -v '^#' "$1" | autocorrect --lint --stdin || {
+    echo "错误:提交信息排版不符合 AutoCorrect 规则(汉字与英文、数字、符号间应留空格)"
+    echo "提示:运行 autocorrect --fix --stdin 或手动调整后重试"
+    exit 1
+  }
+fi
+exit 0

+ 27 - 0
.githooks/pre-commit

@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# pre-commit 钩子:对暂存文件执行 autocorrect --lint 排版检查
+# 启用:git config core.hooksPath .githooks
+# 可绕过:git commit --no-verify(远程 CI 门禁不可绕过)
+
+# 未安装 autocorrect 时跳过
+if ! command -v autocorrect > /dev/null 2>&1; then
+  exit 0
+fi
+
+# 暂存文件(新增、修改、复制和重命名,排除删除;尊重 .autocorrectignore)
+# 逐文件检查便于定位错误;autocorrect 自动跳过二进制与不支持的类型。
+staged="$(git diff --cached --name-only --diff-filter=ACMR)"
+[ -z "$staged" ] && exit 0
+
+failed=0
+while IFS= read -r file; do
+  [ -f "$file" ] || continue
+  autocorrect --lint "$file" || failed=1
+done <<< "$staged"
+
+if [ "$failed" -ne 0 ]; then
+  echo "错误:暂存文件排版不符合 AutoCorrect 规则"
+  echo "提示:运行 autocorrect --fix <文件> 或手动调整后重新 git add"
+  exit 1
+fi
+exit 0

+ 27 - 0
.github/workflows/release.yml

@@ -0,0 +1,27 @@
+# 发行:需要一台已安装 SPT 客户端的自托管 runner(客户端程序集为专有文件,无法在公共 runner 构建)。
+# 用法:在 Actions 页手动触发,或推送 v* 标签。
+name: 发行
+
+on:
+  workflow_dispatch:
+  push:
+    tags: ["v*"]
+
+jobs:
+  package:
+    runs-on: [self-hosted, linux, spt]
+    steps:
+      - uses: actions/checkout@v4
+      - name: 打包
+        run: scripts/package.sh
+        env:
+          SPT_DIR: ${{ vars.SPT_DIR }}
+      - uses: actions/upload-artifact@v4
+        with:
+          name: PerformanceScope
+          path: artifacts/*.zip
+      - name: 创建 Release
+        if: startsWith(github.ref, 'refs/tags/v')
+        uses: softprops/action-gh-release@v2
+        with:
+          files: artifacts/*.zip

+ 19 - 0
.github/workflows/test.yml

@@ -0,0 +1,19 @@
+name: 测试
+
+on:
+  push:
+    branches: [master, main]
+  pull_request:
+  workflow_dispatch:
+
+jobs:
+  test:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-dotnet@v4
+        with:
+          dotnet-version: "10.0.x"
+      # 纯逻辑层无游戏依赖,可在 CI 直接测试
+      - name: 运行单元测试
+        run: dotnet test tests/PerformanceScope.Tests/PerformanceScope.Tests.csproj -c Release

+ 15 - 0
.gitignore

@@ -0,0 +1,15 @@
+# 构建产物
+bin/
+obj/
+artifacts/
+
+# 本地覆盖与 IDE
+local.props
+Directory.Build.local.props
+*.user
+.vs/
+.idea/
+
+# 反编译/临时研究产物
+/re/
+*.orig

+ 23 - 0
Directory.Build.props

@@ -0,0 +1,23 @@
+<Project>
+
+  <!--
+    游戏(SPT 客户端)根目录与引用路径。
+    优先使用环境变量 SPT_DIR;未设置时回退到本机 Lutris 前缀默认路径。
+    客户端程序集为专有文件,不随仓库分发,构建前需自备 SPT 客户端安装。
+  -->
+  <PropertyGroup>
+    <SPT_DIR Condition="'$(SPT_DIR)' == ''">$(HOME)/.local/lutris/escape-from-tarkov/drive_c/Battlestate Games/Escape from Tarkov</SPT_DIR>
+    <SPT_MANAGED>$(SPT_DIR)/EscapeFromTarkov_Data/Managed</SPT_MANAGED>
+    <SPT_BEPINEX_CORE>$(SPT_DIR)/BepInEx/core</SPT_BEPINEX_CORE>
+    <DeployToGame Condition="'$(DeployToGame)' == ''">true</DeployToGame>
+  </PropertyGroup>
+
+  <PropertyGroup>
+    <LangVersion>latest</LangVersion>
+    <Nullable>disable</Nullable>
+    <ImplicitUsings>disable</ImplicitUsings>
+    <Deterministic>true</Deterministic>
+    <GenerateDocumentationFile>false</GenerateDocumentationFile>
+  </PropertyGroup>
+
+</Project>

+ 8 - 0
PerformanceScope.slnx

@@ -0,0 +1,8 @@
+<Solution>
+  <Folder Name="/src/">
+    <Project Path="src/PerformanceScope.Plugin/PerformanceScope.Plugin.csproj" />
+  </Folder>
+  <Folder Name="/tests/">
+    <Project Path="tests/PerformanceScope.Tests/PerformanceScope.Tests.csproj" />
+  </Folder>
+</Solution>

+ 124 - 0
README.md

@@ -0,0 +1,124 @@
+# PerformanceScope
+
+> 调整《逃离塔科夫》光学瞄具**镜内放大(PiP)相机**渲染分辨率的 SPT 客户端插件。
+
+镜内画中画(PiP)是原生瞄具最吃 GPU 的部分:游戏会为瞄具单独创建一台相机,把一个 `N×N` 的方形 RenderTexture(默认 `1024²`)贴到镜片上。本插件让这个 `N` 可配置,从而在画质与帧数之间自行取舍。
+
+## 原理
+
+客户端反编译(EFT 0.16 / SPT 4.1.x)确认:
+
+- `EFT.CameraControl.OpticCameraManager` 中字段 `public int OpticFinalResolution = 1024;`,方法 `SetResolution(int)` 会销毁并重建一个 `N×N` 方形 `RenderTexture`(`name = "SSAAOpticCurrent"`),赋给 `Camera.targetTexture` 并 `Shader.SetGlobalTexture("_CamTex")`。
+- 该值在当前版本**没有任何设置项暴露**,唯一调用点是 `Init()`。
+- 体积光(`VolumetricLightRenderer`)、草地运动矢量(`GPUInstancer`)、远距阴影(`DistantShadow`)、MBOIT(`WindowsManager`)都会在下一帧检测到尺寸变化并自动重建,无需插件干预。
+
+因此本插件用 Harmony **prefix** 覆盖 `SetResolution` 的入参,使游戏自身的 `Init()` 就直接建到目标分辨率,避免二次重建造成的闪烁。
+
+镜内画面最终由主相机的 `SSAA`/`SSAAImpl` 随整帧上采样到屏幕——**本插件不改变超分(DLSS/FSR)设置**,只调整镜内源分辨率。
+
+## 支持版本
+
+- SPT `4.1.x`(EFT 客户端 `0.16`)。
+- 客户端插件依赖 `Assembly-CSharp.dll` 中的具体类型与方法,跨版本可能失效。
+
+## 安装
+
+1. 构建或下载 `PerformanceScope-v{版本}.zip`。
+2. 解压到游戏根目录,使 dll 位于
+   `BepInEx/plugins/PerformanceScope/PerformanceScope.dll`。
+3. 启动游戏。
+
+## 调参方式
+
+安装 [BepInEx ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager) 后,
+游戏内按 **F1**(可在其配置文件中改键)打开菜单,在 `PerformanceScope` 分区调整。
+**本插件不自带任何自定义界面或热键**;改动在游戏内即时生效(由服务层每帧同步)。
+
+## 配置
+
+配置文件:`BepInEx/config/com.pj568.performancescope.cfg`(也可用 ConfigurationManager 修改)。
+
+| 节 | 键 | 默认值 | 说明 |
+| --- | --- | --- | --- |
+| 1. 通用 | 启用模组 | `true` | 总开关,关闭后恢复游戏默认分辨率。 |
+| 1. 通用 | 启用日志 | `false` | 输出常规/诊断/警告日志(错误日志始终输出)。 |
+| 1. 通用 | 详细日志 | `false` | 更详细的诊断信息。 |
+| 2. 镜内分辨率 | 取值方式 | `游戏默认` | 游戏默认 / 屏幕高度比例 / 绝对像素。 |
+| 2. 镜内分辨率 | 屏幕高度比例 | `0.5` | 镜内边长 = round(屏幕高度 × 该值)。 |
+| 2. 镜内分辨率 | 绝对像素 | `1024` | 镜内方形 RenderTexture 的边长。 |
+| 2. 镜内分辨率 | 瞄准中立即应用 | `true` | 关闭时,瞄准期间的改动推迟到退出镜内后应用。 |
+
+> 默认取值方式为「游戏默认」,即安装后不改变游戏行为;请显式选择模式。
+> 注意:`屏幕高度比例` 在 4K(2160p)下 `0.7` 会得到 1512,**高于**游戏默认 1024,反而增加负载。
+
+## 构建
+
+前置:本机已安装 SPT 客户端(客户端程序集为专有文件,不随仓库分发)。
+
+```shellscript
+# 指定游戏根目录(未设置时回退到本机 Lutris 前缀默认路径)
+export SPT_DIR="/path/to/Escape from Tarkov"
+dotnet build src/PerformanceScope.Plugin/PerformanceScope.Plugin.csproj -c Release
+```
+
+Release 构建会自动把 dll 复制到 `$SPT_DIR/BepInEx/plugins/PerformanceScope/`;
+可用 `-p:DeployToGame=false` 关闭。
+
+## 测试
+
+纯逻辑层(分辨率换算与应用决策)无游戏依赖,可直接测试:
+
+```shellscript
+dotnet test tests/PerformanceScope.Tests/PerformanceScope.Tests.csproj
+```
+
+## 打包
+
+```shellscript
+scripts/package.sh
+# 产物:artifacts/PerformanceScope-v{版本}.zip
+```
+
+## 部署(本机)
+
+```shellscript
+scripts/package.sh
+# 解压 zip 到游戏根目录,或直接依赖 Release 构建的自动复制
+```
+
+启动后 `BepInEx/LogOutput.log` 应出现:
+
+```
+[Info   :PerformanceScope] PerformanceScope 已加载(在 ConfigurationManager 菜单中调参)
+[Info   :PerformanceScope] 镜内分辨率 1024 → 720
+```
+
+## 验证
+
+1. 在 ConfigurationManager 里开启「启用日志」。
+2. 进入战局,按住右键进入瞄具。
+3. 打开 ConfigurationManager(默认 F1),把「取值方式」切到「屏幕高度比例」或「绝对像素」。
+4. 观察 `BepInEx/LogOutput.log` 的 `镜内分辨率 1024 → …` 与镜内画质/帧数变化。
+5. 关闭「瞄准中立即应用」后瞄准时改值,确认改动在退出镜内后才生效。
+
+## 与其它模组的交互
+
+- **PiP-Disabler**(`com.fiodor.pipdisabler`):它是对 `SetResolution` 的 **postfix 门控**(不改写入参、不改字段),与本插件共存;被它抑制的镜内渲染不会触发本插件的冲突重试。
+- **Fontaine's FOV Fix / Amands's Graphics**:patch 的是 `OpticComponentUpdater` 等与本插件不重叠的目标,无直接冲突。
+- **DERP(Dynamic External Resolution Patch)**:改的是**主相机/全局**分辨率与超分档,与本插件(镜内方形 RT 尺寸)机制不同;可同时使用,但两者都会影响分辨率,注意叠加效果。
+- **DLSS / FSR**:本插件**不切换超分档**;但开启超分时改变镜内 RT 尺寸可能产生一帧闪烁,可关闭「瞄准中立即应用」规避。SPT 官方亦记录过「DLSS/FSR 下进镜切换档位会黑屏闪烁」。
+
+> 本插件涉及的游戏符号(`OpticCameraManager.SetResolution`、`OpticFinalResolution`、`_CamTex`、`SSAAOpticCurrent` 等)均直接取自**本机安装的 SPT 4.1.x 实际 `Assembly-CSharp.dll`** 反编译结果,而非公开资料。
+
+## 已知限制与风险
+
+- **无法独立设置镜内超分档**:全游戏只有一套挂在主相机上的 `SSAA`/`SSAAImpl`,镜内画面是其一部分;独立的镜内 FSR/DLSS 需要另挂一套组件,本插件不做。
+- **瞄准中改分辨率可能有一帧闪烁**:因为会销毁并重建 RenderTexture;可将「瞄准中立即应用」关闭以规避。
+- **镜内低分辨率下纹理锯齿会更明显**:镜内相机的 mipmap bias 只在 `Init()` 时设置一次,插件不做补偿。
+- **与其它改 `SetResolution` 的模组可能冲突**:若第三方 prefix 改写同一入参,插件检测到目标未生效后会暂停重试直至你更改目标值,避免每帧重建 RenderTexture。
+- **版本敏感**:依赖具体类型与方法,EFT 更新后可能失效。
+- **CI 限制**:公共 runner 无法构建客户端插件(缺少专有程序集),`test.yml` 只跑纯逻辑单测;发行包需在装有 SPT 的机器(或自托管 runner)上通过 `scripts/package.sh` 生成。
+
+## 许可证
+
+(待定)

+ 164 - 0
scripts/check-grammar.mjs

@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+// 基于 git-commit-regulation 规范的自包含提交信息语法检查
+// 规则源:https://github.com/PJ-568/git-commit-regulation(CC BY-SA 4.0)
+// 用法:node scripts/check-grammar.mjs            自测(正反例断言 + 历史提交报告)
+//       node scripts/check-grammar.mjs --file X  检查提交信息文件(commit-msg 钩子)
+
+import assert from "node:assert/strict";
+import { execSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+const REPO_DIR = fileURLToPath(new URL("..", import.meta.url));
+
+// 标题语法正则(与 git-commit-regulation README 附录「标题语法」同步维护)
+const TITLE_RE =
+  /^【(?<type>初始|更改|新增|修复|格式|文档|测试|维护)(?:,(?<scope>[\p{Script=Han}A-Za-z0-9_-]{1,16}))?】(?<summary>[^\n]{1,60})$/u;
+const HAN_ONLY_RE = /^[\p{Script=Han}]+$/u;
+const ISSUE_RE = /#\d+/u;
+
+// 解析提交信息;结构违规时抛出带原因的错误
+function parse(message) {
+  const text = message.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "");
+  const lines = text.split("\n");
+  const titleLine = lines[0] ?? "";
+  const m = TITLE_RE.exec(titleLine);
+  if (!m) {
+    throw new Error(titleLine === "" ? "标题缺失" : "标题不符合语法");
+  }
+  const rest = lines.slice(1);
+  if (rest.length > 0 && rest[0] !== "") {
+    throw new Error("描述必须以一个空行与标题相隔");
+  }
+  let description = null;
+  if (rest.length > 1) {
+    const body = rest.slice(1).join("\n").replace(/\n+$/, "");
+    if (body !== "") description = body;
+  }
+  return {
+    type: m.groups.type,
+    scope: m.groups.scope ?? null,
+    summary: m.groups.summary,
+    description,
+  };
+}
+
+// 警告项(解析器应接受并提示)
+function warnings(parsed) {
+  const ws = [];
+  if (HAN_ONLY_RE.test(parsed.summary) && [...parsed.summary].length > 30) {
+    ws.push("摘要为纯汉字且超过 30 汉字(人工建议)");
+  }
+  if (ISSUE_RE.test(parsed.summary)) {
+    ws.push("标题包含问题编号,应移至描述");
+  }
+  return ws;
+}
+
+// —— 命令行模式:检查提交信息文件(commit-msg 钩子)——
+// simp: 只过滤 git 注释行(# 开头);正文中顶格的 #568 行同样被过滤,
+//       与 git 默认 cleanup 行为一致,故钩子不单独校验描述中的问题编号。
+const [mode, filePath] = process.argv.slice(2);
+if (mode === "--file") {
+  if (!filePath) {
+    console.error("用法:node scripts/check-grammar.mjs --file <路径>");
+    process.exit(2);
+  }
+  const cleaned = readFileSync(filePath, "utf8")
+    .split("\n")
+    .filter((line) => !line.startsWith("#"))
+    .join("\n")
+    .trim();
+  if (cleaned === "") {
+    console.error("错误:提交信息为空");
+    process.exit(1);
+  }
+  try {
+    const parsed = parse(cleaned);
+    const ws = warnings(parsed);
+    if (ws.length > 0) {
+      console.warn("警告:\n" + ws.map((w) => `- ${w}`).join("\n"));
+    }
+  } catch (e) {
+    console.error(`错误:${e.message}`);
+    process.exit(1);
+  }
+  process.exit(0);
+}
+
+// 正例与反例(与 git-commit-regulation README 附录表格一致)
+const positives = [
+  ["最小提交", "【修复】解决登录界面的输入验证问题"],
+  ["带范围", "【修复,认证】解决登录界面的输入验证问题"],
+  ["摘要 60 码点上限", "【新增】" + "a".repeat(60)],
+  [
+    "带描述",
+    "【修复,认证】解决登录界面的输入验证问题\n\n修复了登录界面中输入验证逻辑的问题。\n\n相关问题编号:\n\n#568",
+  ],
+];
+
+const negatives = [
+  ["摘要为空", "【初始】"],
+  ["类型不在枚举内", "【验证】执行检查"],
+  ["缺少左括号", "修复】解决登录界面的输入验证问题"],
+  ["半角逗号", "【修复,认证】解决登录界面的输入验证问题"],
+  ["范围含空格", "【修复, 认证】解决登录界面的输入验证问题"],
+  ["摘要超过 60 码点", "【新增】" + "a".repeat(61)],
+  ["描述未以空行相隔", "【修复】解决登录界面的输入验证问题\n第二行直接开始"],
+  ["空消息", ""],
+];
+
+let checked = 0;
+for (const [name, msg] of positives) {
+  assert.doesNotThrow(() => parse(msg), `正例应合法:${name}`);
+  checked++;
+}
+for (const [name, msg] of negatives) {
+  assert.throws(() => parse(msg), `反例应非法:${name}`);
+  checked++;
+}
+// 警告项断言
+assert.equal(
+  warnings(parse("【新增】" + "功".repeat(31))).length,
+  1,
+  "纯汉字摘要超过 30 汉字应发出警告",
+);
+assert.equal(
+  warnings(parse("【修复】解决 #568 问题")).length,
+  1,
+  "标题包含问题编号应发出警告",
+);
+checked += 2;
+
+// 项目历史提交检查(报告,不阻塞)
+// simp: 历史提交本身存在违规(如【初始】),故只报告不断言,避免脚本永远失败。
+let history = [];
+try {
+  const log = execSync("git log --format=%s%x00", { cwd: REPO_DIR }).toString();
+  // git 每条记录后附加换行,NUL 分割后需去除首尾空白
+  history = log
+    .split("\0")
+    .map((m) => m.trim())
+    .filter((m) => m !== "");
+} catch {
+  console.log("(跳过历史检查:非 git 环境)");
+}
+const report = [];
+for (const msg of history) {
+  try {
+    const ws = warnings(parse(msg));
+    if (ws.length > 0) report.push(`${msg}:${ws.join(";")}`);
+  } catch (e) {
+    report.push(`${msg}:${e.message}`);
+  }
+}
+
+console.log(
+  `断言通过:${checked} 个正反例与警告断言、${history.length} 条历史提交`,
+);
+if (report.length > 0) {
+  console.log("历史提交检查报告(不阻塞):");
+  for (const r of report) console.log(`- ${r}`);
+} else {
+  console.log("历史提交检查报告:全部合规");
+}

+ 33 - 0
scripts/package.sh

@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# 本地打包:构建 Release 并把 dll 按游戏根目录结构打成 zip
+# 用法:scripts/package.sh
+# 前置:本机已安装 SPT 客户端(用 SPT_DIR 指定其根目录)
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+
+export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
+export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"
+
+VERSION="$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' src/PerformanceScope.Plugin/PerformanceScope.Plugin.csproj | head -1)"
+[ -n "$VERSION" ] || { echo "错误:未能从 csproj 读取 Version" >&2; exit 1; }
+
+OUT="artifacts"
+STAGE="$OUT/PerformanceScope"
+
+rm -rf "$OUT"
+mkdir -p "$STAGE/BepInEx/plugins/PerformanceScope"
+
+dotnet build src/PerformanceScope.Plugin/PerformanceScope.Plugin.csproj -c Release -p:DeployToGame=false
+
+cp "src/PerformanceScope.Plugin/bin/Release/PerformanceScope.dll" \
+   "$STAGE/BepInEx/plugins/PerformanceScope/"
+
+(
+  cd "$STAGE"
+  zip -qr "../PerformanceScope-v${VERSION}.zip" .
+)
+rm -rf "$STAGE"
+
+echo "已生成 artifacts/PerformanceScope-v${VERSION}.zip"

+ 39 - 0
src/PerformanceScope.Core/OpticResolutionDecision.cs

@@ -0,0 +1,39 @@
+namespace PerformanceScope.Core
+{
+    /// <summary>一次决策应执行的动作。</summary>
+    public enum OpticApplyAction
+    {
+        /// <summary>无需动作。</summary>
+        None = 0,
+
+        /// <summary>立即应用目标分辨率。</summary>
+        Apply = 1,
+
+        /// <summary>推迟到退出镜内后再应用。</summary>
+        Defer = 2
+    }
+
+    /// <summary>
+    /// 镜内分辨率应用的纯决策逻辑:输入游戏当前状态,输出该做什么。
+    /// 与游戏 API 解耦,便于单元测试。
+    /// </summary>
+    public static class OpticResolutionDecision
+    {
+        /// <summary>
+        /// 决策。
+        /// </summary>
+        /// <param name="current">游戏当前镜内分辨率。</param>
+        /// <param name="target">配置目标分辨率。</param>
+        /// <param name="isScoped">是否正在镜内瞄准。</param>
+        /// <param name="applyWhileScoped">是否允许瞄准中立即应用。</param>
+        public static OpticApplyAction Decide(int current, int target, bool isScoped, bool applyWhileScoped)
+        {
+            if (current == target)
+            {
+                return OpticApplyAction.None;
+            }
+
+            return isScoped && !applyWhileScoped ? OpticApplyAction.Defer : OpticApplyAction.Apply;
+        }
+    }
+}

+ 17 - 0
src/PerformanceScope.Core/OpticResolutionMode.cs

@@ -0,0 +1,17 @@
+namespace PerformanceScope.Core
+{
+    /// <summary>
+    /// 镜内(PiP)渲染分辨率的取值方式。
+    /// </summary>
+    public enum OpticResolutionMode
+    {
+        /// <summary>使用游戏默认值(当前版本为 1024)。</summary>
+        GameDefault = 0,
+
+        /// <summary>按屏幕高度的比例取值:round(屏幕高度 × 比例)。</summary>
+        ScreenHeightRatio = 1,
+
+        /// <summary>取固定的绝对像素值。</summary>
+        AbsolutePixels = 2
+    }
+}

+ 76 - 0
src/PerformanceScope.Core/ResolutionMath.cs

@@ -0,0 +1,76 @@
+using System;
+
+namespace PerformanceScope.Core
+{
+    /// <summary>
+    /// 镜内渲染分辨率换算:纯函数,无游戏依赖,便于单元测试。
+    /// </summary>
+    public static class ResolutionMath
+    {
+        /// <summary>游戏当前版本的镜内方形 RenderTexture 默认边长。</summary>
+        public const int GameDefaultResolution = 1024;
+
+        /// <summary>允许的最小边长。</summary>
+        public const int MinResolution = 64;
+
+        /// <summary>允许的最大边长。</summary>
+        public const int MaxResolution = 4096;
+
+        /// <summary>允许的最小比例。</summary>
+        public const float MinRatio = 0.05f;
+
+        /// <summary>允许的最大比例。</summary>
+        public const float MaxRatio = 4f;
+
+        /// <summary>把边长夹取到 [MinResolution, MaxResolution]。</summary>
+        public static int ClampResolution(int value)
+        {
+            if (value < MinResolution)
+            {
+                return MinResolution;
+            }
+
+            return value > MaxResolution ? MaxResolution : value;
+        }
+
+        /// <summary>比例是否有效(有限且落在允许区间内)。</summary>
+        public static bool IsValidRatio(float ratio)
+        {
+            return !float.IsNaN(ratio) && !float.IsInfinity(ratio) && ratio >= MinRatio && ratio <= MaxRatio;
+        }
+
+        /// <summary>
+        /// 计算镜内渲染分辨率边长。非法或缺失输入一律回退到 <paramref name="gameDefault"/>。
+        /// </summary>
+        /// <param name="mode">取值方式。</param>
+        /// <param name="screenHeight">当前屏幕高度(像素)。</param>
+        /// <param name="gameDefault">游戏默认边长,默认 <see cref="GameDefaultResolution"/>。</param>
+        /// <param name="screenHeightRatio">屏幕高度比例(仅 <see cref="OpticResolutionMode.ScreenHeightRatio"/> 用)。</param>
+        /// <param name="absolutePixels">绝对像素边长(仅 <see cref="OpticResolutionMode.AbsolutePixels"/> 用)。</param>
+        public static int Resolve(
+            OpticResolutionMode mode,
+            int screenHeight,
+            float screenHeightRatio,
+            int absolutePixels,
+            int gameDefault = GameDefaultResolution)
+        {
+            switch (mode)
+            {
+                case OpticResolutionMode.ScreenHeightRatio:
+                    if (IsValidRatio(screenHeightRatio) && screenHeight > 0)
+                    {
+                        return ClampResolution(
+                            (int)Math.Round(screenHeight * (double)screenHeightRatio, MidpointRounding.AwayFromZero));
+                    }
+
+                    return ClampResolution(gameDefault);
+
+                case OpticResolutionMode.AbsolutePixels:
+                    return absolutePixels > 0 ? ClampResolution(absolutePixels) : ClampResolution(gameDefault);
+
+                default:
+                    return ClampResolution(gameDefault);
+            }
+        }
+    }
+}

+ 33 - 0
src/PerformanceScope.Plugin/ConfigurationManagerAttributes.cs

@@ -0,0 +1,33 @@
+using System;
+using BepInEx.Configuration;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 供 BepInEx.ConfigurationManager 通过反射读取的附加显示属性。
+    /// 字段名与上游 ConfigurationManager 约定保持一致,勿随意改名。
+    /// </summary>
+    public sealed class ConfigurationManagerAttributes
+    {
+        /// <summary>自定义绘制回调;为 null 时使用默认绘制。</summary>
+        public Action<ConfigEntryBase> CustomDrawer;
+
+        /// <summary>是否把数值范围显示为百分比。</summary>
+        public bool? ShowRangeAsPercent;
+
+        /// <summary>是否在插件列表中可见。</summary>
+        public bool? Browsable;
+
+        /// <summary>是否属于高级选项(仅在展开高级设置时显示)。</summary>
+        public bool? IsAdvanced;
+
+        /// <summary>是否隐藏“恢复默认”按钮。</summary>
+        public bool? HideDefaultButton;
+
+        /// <summary>是否隐藏设置项名称。</summary>
+        public bool? HideSettingName;
+
+        /// <summary>同一节内的排序权重,越小越靠前。</summary>
+        public int? Order;
+    }
+}

+ 64 - 0
src/PerformanceScope.Plugin/Log.cs

@@ -0,0 +1,64 @@
+using BepInEx.Logging;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 统一的日志出口。普通日志受配置开关控制,错误日志始终输出以便排障。
+    /// </summary>
+    internal static class Log
+    {
+        private static ManualLogSource _logger;
+
+        /// <summary>注入 BepInEx 提供的日志源。</summary>
+        public static void Init(ManualLogSource logger)
+        {
+            _logger = logger;
+        }
+
+        /// <summary>常规信息,仅在启用日志时输出。</summary>
+        public static void Info(string message)
+        {
+            if (_logger == null || PluginConfig.EnableLogging?.Value != true)
+            {
+                return;
+            }
+
+            _logger.LogInfo(message);
+        }
+
+        /// <summary>诊断信息,需同时启用日志与详细日志。</summary>
+        public static void Verbose(string message)
+        {
+            if (_logger == null
+                || PluginConfig.EnableLogging?.Value != true
+                || PluginConfig.VerboseLogging?.Value != true)
+            {
+                return;
+            }
+
+            _logger.LogInfo(message);
+        }
+
+        /// <summary>警告,仅在启用日志时输出。</summary>
+        public static void Warn(string message)
+        {
+            if (_logger == null || PluginConfig.EnableLogging?.Value != true)
+            {
+                return;
+            }
+
+            _logger.LogWarning(message);
+        }
+
+        /// <summary>错误,始终输出。</summary>
+        public static void Error(string message)
+        {
+            if (_logger == null)
+            {
+                return;
+            }
+
+            _logger.LogError(message);
+        }
+    }
+}

+ 151 - 0
src/PerformanceScope.Plugin/OpticResolutionService.cs

@@ -0,0 +1,151 @@
+using System;
+using EFT.CameraControl;
+using PerformanceScope.Core;
+using UnityEngine;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 镜内 PiP 分辨率的决策与应用。每帧由插件调用 <see cref="Tick"/>,
+    /// 根据配置与当前游戏状态决定何时调用 <see cref="OpticCameraManager.SetResolution"/>。
+    /// 普通类,由插件在 Awake 中创建并注册到 <see cref="Instance"/>。
+    /// </summary>
+    internal sealed class OpticResolutionService
+    {
+        private bool _loggedNoCamera;
+
+        private int _pendingTarget = ResolutionMath.GameDefaultResolution;
+
+        private int _conflictTarget = int.MinValue;
+
+        /// <summary>当前服务实例;插件未加载时为 null,补丁据此透传原值。</summary>
+        public static OpticResolutionService Instance { get; set; }
+
+        /// <summary>最近一次解析出的目标边长,供叠加显示。</summary>
+        public int LastTarget { get; private set; } = ResolutionMath.GameDefaultResolution;
+
+        /// <summary>是否有因瞄准中而推迟应用的目标。</summary>
+        public bool PendingApply { get; private set; }
+
+        /// <summary>是否因第三方改写导致目标无法生效而暂停重试。</summary>
+        public bool ConflictLocked { get; private set; }
+
+        /// <summary>
+        /// 计算当前配置对应的目标边长。模组关闭时返回游戏默认值,
+        /// 从而让游戏恢复其原生 1024。
+        /// </summary>
+        public int ComputeTarget()
+        {
+            if (PluginConfig.EnableMod?.Value != true)
+            {
+                return ResolutionMath.GameDefaultResolution;
+            }
+
+            return ResolutionMath.Resolve(
+                PluginConfig.Mode.Value,
+                Screen.height,
+                PluginConfig.ScreenHeightRatio.Value,
+                PluginConfig.AbsolutePixels.Value);
+        }
+
+        /// <summary>每帧调用:在相机就绪时把配置分辨率同步给游戏。</summary>
+        public void Tick()
+        {
+            OpticCameraManager ocm = GetOpticCameraManager();
+            if (ocm == null || ocm.Camera == null)
+            {
+                if (!_loggedNoCamera)
+                {
+                    _loggedNoCamera = true;
+                    Log.Verbose("镜内相机尚未就绪,暂不应用。");
+                }
+
+                return;
+            }
+
+            _loggedNoCamera = false;
+
+            int target = ComputeTarget();
+            LastTarget = target;
+
+            if (ConflictLocked)
+            {
+                // 仅在目标变化(例如玩家改了配置)时解除锁定,避免每帧重建。
+                if (target == _conflictTarget)
+                {
+                    return;
+                }
+
+                ConflictLocked = false;
+            }
+
+            OpticApplyAction action = OpticResolutionDecision.Decide(
+                ocm.OpticFinalResolution,
+                target,
+                ocm.IsAnyOpticCameraRendering,
+                PluginConfig.ApplyWhileScoped?.Value == true);
+
+            switch (action)
+            {
+                case OpticApplyAction.Apply:
+                    Apply(ocm, target);
+                    break;
+
+                case OpticApplyAction.Defer:
+                    if (!PendingApply || _pendingTarget != target)
+                    {
+                        _pendingTarget = target;
+                        PendingApply = true;
+                        Log.Info($"镜内瞄准中,推迟应用分辨率 {ocm.OpticFinalResolution} → {target}");
+                    }
+
+                    break;
+
+                default:
+                    PendingApply = false;
+                    break;
+            }
+        }
+
+        /// <summary>安全地调用游戏接口重建镜内 RenderTexture。</summary>
+        private void Apply(OpticCameraManager ocm, int target)
+        {
+            int old = ocm.OpticFinalResolution;
+            if (old == target)
+            {
+                PendingApply = false;
+                LastTarget = target;
+                return;
+            }
+
+            try
+            {
+                ocm.SetResolution(target);
+            }
+            catch (Exception e)
+            {
+                Log.Error($"设置镜内分辨率失败({old} → {target}):{e}");
+                return;
+            }
+
+            PendingApply = false;
+            LastTarget = target;
+            Log.Info($"镜内分辨率 {old} → {target}");
+
+            if (ocm.OpticFinalResolution != target)
+            {
+                // 第三方 prefix/postfix 可能改写了结果;锁定以避免每帧重建 RenderTexture。
+                ConflictLocked = true;
+                _conflictTarget = target;
+                Log.Warn($"镜内分辨率未生效(仍为 {ocm.OpticFinalResolution}),可能存在冲突模组;已暂停重试直至目标变化。");
+            }
+        }
+
+        private static OpticCameraManager GetOpticCameraManager()
+        {
+            // 读取静态字段而非 Instance 属性:避免在菜单等场景中触发 CameraManager 的懒创建。
+            CameraManager manager = CameraManager.instance;
+            return manager == null ? null : manager.OpticCameraManager;
+        }
+    }
+}

+ 51 - 0
src/PerformanceScope.Plugin/PerformanceScope.Plugin.csproj

@@ -0,0 +1,51 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net471</TargetFramework>
+    <AssemblyName>PerformanceScope</AssemblyName>
+    <RootNamespace>PerformanceScope</RootNamespace>
+    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+    <Version>0.1.0</Version>
+  </PropertyGroup>
+
+  <!-- 共享纯逻辑:与测试工程同源编译,避免多出一个运行时依赖 dll -->
+  <ItemGroup>
+    <Compile Include="..\PerformanceScope.Core\**\*.cs" Link="Core\%(RecursiveDir)%(Filename)%(Extension)" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Reference Include="BepInEx">
+      <HintPath>$(SPT_BEPINEX_CORE)/BepInEx.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="0Harmony">
+      <HintPath>$(SPT_BEPINEX_CORE)/0Harmony.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="Assembly-CSharp">
+      <HintPath>$(SPT_MANAGED)/Assembly-CSharp.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine.CoreModule">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.CoreModule.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+  </ItemGroup>
+
+  <!-- 本地 Release 构建后自动部署到游戏插件目录(可用 -p:DeployToGame=false 关闭) -->
+  <Target Name="DeployToGame" AfterTargets="Build"
+          Condition="'$(DeployToGame)' == 'true' And '$(Configuration)' == 'Release' And Exists('$(SPT_DIR)')">
+    <MakeDir Directories="$(SPT_DIR)/BepInEx/plugins/PerformanceScope" />
+    <Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SPT_DIR)/BepInEx/plugins/PerformanceScope" />
+    <Message Importance="high" Text="已部署:$(SPT_DIR)/BepInEx/plugins/PerformanceScope/$(TargetFileName)" />
+  </Target>
+
+</Project>

+ 66 - 0
src/PerformanceScope.Plugin/Plugin.cs

@@ -0,0 +1,66 @@
+using System;
+using BepInEx;
+using HarmonyLib;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 插件入口:初始化配置、日志、Harmony 补丁与分辨率服务。
+    /// 所有调参通过 BepInEx ConfigurationManager 在游戏内完成(默认 F1,可在其配置中改键),
+    /// 服务层每帧读取配置并即时生效;本插件不提供自定义 UI 或热键。
+    /// </summary>
+    [BepInPlugin("com.pj568.performancescope", "PerformanceScope", "0.1.0")]
+    public class PerformanceScopePlugin : BaseUnityPlugin
+    {
+        private const string HarmonyId = "com.pj568.performancescope";
+
+        private Harmony _harmony;
+
+        private void Awake()
+        {
+            Log.Init(Logger);
+            PluginConfig.Init(Config);
+            ApplyHarmonyPatches();
+
+            OpticResolutionService.Instance = new OpticResolutionService();
+
+            Log.Info("PerformanceScope 已加载(在 ConfigurationManager 菜单中调参)");
+        }
+
+        private void Update()
+        {
+            // 每帧同步:ConfigurationManager 里改动配置后立即生效,并处理瞄准中的延迟应用。
+            OpticResolutionService.Instance?.Tick();
+        }
+
+        private void OnDestroy()
+        {
+            if (_harmony == null)
+            {
+                return;
+            }
+
+            try
+            {
+                _harmony.UnpatchSelf();
+            }
+            catch (Exception e)
+            {
+                Log.Error("卸载 Harmony 补丁失败:" + e);
+            }
+        }
+
+        private void ApplyHarmonyPatches()
+        {
+            try
+            {
+                _harmony = new Harmony(HarmonyId);
+                _harmony.PatchAll(typeof(SetResolutionPatch));
+            }
+            catch (Exception e)
+            {
+                Log.Error("应用 Harmony 补丁失败:" + e);
+            }
+        }
+    }
+}

+ 100 - 0
src/PerformanceScope.Plugin/PluginConfig.cs

@@ -0,0 +1,100 @@
+using BepInEx.Configuration;
+using PerformanceScope.Core;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 插件配置项定义。所有绑定项以静态属性暴露,供服务层直接读取。
+    /// 配置界面由 BepInEx ConfigurationManager 提供(默认 F1,可在其配置中改键)。
+    /// </summary>
+    internal static class PluginConfig
+    {
+        private const string SectionGeneral = "1. 通用";
+        private const string SectionResolution = "2. 镜内分辨率";
+
+        public static ConfigEntry<bool> EnableMod { get; private set; }
+
+        public static ConfigEntry<bool> EnableLogging { get; private set; }
+
+        public static ConfigEntry<bool> VerboseLogging { get; private set; }
+
+        public static ConfigEntry<OpticResolutionMode> Mode { get; private set; }
+
+        public static ConfigEntry<float> ScreenHeightRatio { get; private set; }
+
+        public static ConfigEntry<int> AbsolutePixels { get; private set; }
+
+        public static ConfigEntry<bool> ApplyWhileScoped { get; private set; }
+
+        /// <summary>绑定全部配置项并立即落盘,生成带注释的初始配置文件。</summary>
+        public static void Init(ConfigFile config)
+        {
+            EnableMod = config.Bind(
+                SectionGeneral,
+                "启用模组",
+                true,
+                new ConfigDescription(
+                    "总开关。关闭后恢复游戏默认镜内分辨率。",
+                    null,
+                    new ConfigurationManagerAttributes { Order = 1 }));
+
+            EnableLogging = config.Bind(
+                SectionGeneral,
+                "启用日志",
+                false,
+                new ConfigDescription(
+                    "输出本模组的常规/诊断/警告日志(错误日志始终输出)。",
+                    null,
+                    new ConfigurationManagerAttributes { Order = 2 }));
+
+            VerboseLogging = config.Bind(
+                SectionGeneral,
+                "详细日志",
+                false,
+                new ConfigDescription(
+                    "在启用日志的基础上输出更详细的诊断信息。",
+                    null,
+                    new ConfigurationManagerAttributes { IsAdvanced = true, Order = 3 }));
+
+            Mode = config.Bind(
+                SectionResolution,
+                "取值方式",
+                // 默认不改变游戏行为;玩家显式选择后再生效(4K 下 0.7 反而会高于默认 1024)。
+                OpticResolutionMode.GameDefault,
+                new ConfigDescription(
+                    "游戏默认 / 屏幕高度比例 / 绝对像素。",
+                    // 枚举无需 AcceptableValueList(ConfigurationManager 会自动渲染为下拉框)
+                    null,
+                    new ConfigurationManagerAttributes { Order = 1 }));
+
+            ScreenHeightRatio = config.Bind(
+                SectionResolution,
+                "屏幕高度比例",
+                0.5f,
+                new ConfigDescription(
+                    "镜内边长 = round(屏幕高度 × 该值)。",
+                    new AcceptableValueRange<float>(ResolutionMath.MinRatio, ResolutionMath.MaxRatio),
+                    new ConfigurationManagerAttributes { ShowRangeAsPercent = true, Order = 2 }));
+
+            AbsolutePixels = config.Bind(
+                SectionResolution,
+                "绝对像素",
+                ResolutionMath.GameDefaultResolution,
+                new ConfigDescription(
+                    "镜内方形 RenderTexture 的边长(像素)。",
+                    new AcceptableValueRange<int>(ResolutionMath.MinResolution, ResolutionMath.MaxResolution),
+                    new ConfigurationManagerAttributes { Order = 3 }));
+
+            ApplyWhileScoped = config.Bind(
+                SectionResolution,
+                "瞄准中立即应用",
+                true,
+                new ConfigDescription(
+                    "关闭时,瞄准镜内期间的改动会推迟到退出镜内后应用,以避免画面闪烁。",
+                    null,
+                    new ConfigurationManagerAttributes { Order = 4 }));
+
+            config.Save();
+        }
+    }
+}

+ 29 - 0
src/PerformanceScope.Plugin/SetResolutionPatch.cs

@@ -0,0 +1,29 @@
+using EFT.CameraControl;
+using HarmonyLib;
+
+namespace PerformanceScope
+{
+    /// <summary>
+    /// 覆盖游戏传入的镜内分辨率参数。游戏自身 Init() 调用
+    /// <c>SetResolution(OpticFinalResolution)</c>(初值 1024)时,prefix 会直接改成目标值,
+    /// 从而避免先建 1024 再重建造成的闪烁。
+    /// </summary>
+    [HarmonyPatch(typeof(OpticCameraManager), nameof(OpticCameraManager.SetResolution))]
+    internal static class SetResolutionPatch
+    {
+        // HarmonyWrapSafe:prefix 抛异常时包裹并跳过原方法而非中断游戏 Init 流程。
+        [HarmonyWrapSafe]
+        [HarmonyPrefix]
+        private static void Prefix(ref int resolution)
+        {
+            OpticResolutionService service = OpticResolutionService.Instance;
+            if (service == null)
+            {
+                // 插件尚未初始化完成,保持游戏原值透传。
+                return;
+            }
+
+            resolution = service.ComputeTarget();
+        }
+    }
+}

+ 48 - 0
tests/PerformanceScope.Tests/OpticResolutionDecisionTests.cs

@@ -0,0 +1,48 @@
+using PerformanceScope.Core;
+using Xunit;
+
+namespace PerformanceScope.Tests
+{
+    public class OpticResolutionDecisionTests
+    {
+        [Fact]
+        public void 当前值与目标一致_不动作()
+        {
+            Assert.Equal(
+                OpticApplyAction.None,
+                OpticResolutionDecision.Decide(1024, 1024, isScoped: false, applyWhileScoped: true));
+        }
+
+        [Fact]
+        public void 未瞄准_立即应用()
+        {
+            Assert.Equal(
+                OpticApplyAction.Apply,
+                OpticResolutionDecision.Decide(1024, 720, isScoped: false, applyWhileScoped: false));
+        }
+
+        [Fact]
+        public void 瞄准中且允许立即应用_立即应用()
+        {
+            Assert.Equal(
+                OpticApplyAction.Apply,
+                OpticResolutionDecision.Decide(1024, 720, isScoped: true, applyWhileScoped: true));
+        }
+
+        [Fact]
+        public void 瞄准中且禁止立即应用_推迟()
+        {
+            Assert.Equal(
+                OpticApplyAction.Defer,
+                OpticResolutionDecision.Decide(1024, 720, isScoped: true, applyWhileScoped: false));
+        }
+
+        [Fact]
+        public void 一致优先于推迟()
+        {
+            Assert.Equal(
+                OpticApplyAction.None,
+                OpticResolutionDecision.Decide(720, 720, isScoped: true, applyWhileScoped: false));
+        }
+    }
+}

+ 20 - 0
tests/PerformanceScope.Tests/PerformanceScope.Tests.csproj

@@ -0,0 +1,20 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net10.0</TargetFramework>
+    <RootNamespace>PerformanceScope.Tests</RootNamespace>
+    <IsPackable>false</IsPackable>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <Compile Include="..\..\src\PerformanceScope.Core\**\*.cs" Link="Core\%(RecursiveDir)%(Filename)%(Extension)" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
+    <PackageReference Include="xunit" Version="2.9.2" />
+    <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
+  </ItemGroup>
+
+</Project>

+ 71 - 0
tests/PerformanceScope.Tests/ResolutionMathTests.cs

@@ -0,0 +1,71 @@
+using PerformanceScope.Core;
+using Xunit;
+
+namespace PerformanceScope.Tests
+{
+    public class ResolutionMathTests
+    {
+        [Theory]
+        [InlineData(0.5f, 1440, 720)]
+        [InlineData(0.7f, 1080, 756)]
+        [InlineData(1.0f, 1080, 1080)]
+        [InlineData(0.666f, 1440, 959)] // 959.04 → 四舍五入 959
+        public void ScreenHeightRatio_按屏幕高度换算(float ratio, int screenHeight, int expected)
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.ScreenHeightRatio, screenHeight, ratio, 0);
+            Assert.Equal(expected, actual);
+        }
+
+        [Fact]
+        public void AbsolutePixels_直接取给定值()
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.AbsolutePixels, 1080, 0f, 512);
+            Assert.Equal(512, actual);
+        }
+
+        [Fact]
+        public void GameDefault_返回默认值()
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.GameDefault, 1080, 0.5f, 512);
+            Assert.Equal(ResolutionMath.GameDefaultResolution, actual);
+        }
+
+        [Theory]
+        [InlineData(0f)]
+        [InlineData(-1f)]
+        [InlineData(float.NaN)]
+        [InlineData(float.PositiveInfinity)]
+        [InlineData(0.001f)]
+        [InlineData(99f)]
+        public void 非法比例_回退默认值(float ratio)
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.ScreenHeightRatio, 1080, ratio, 0);
+            Assert.Equal(ResolutionMath.GameDefaultResolution, actual);
+        }
+
+        [Theory]
+        [InlineData(0)]
+        [InlineData(-5)]
+        public void 非法像素_回退默认值(int pixels)
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.AbsolutePixels, 1080, 0f, pixels);
+            Assert.Equal(ResolutionMath.GameDefaultResolution, actual);
+        }
+
+        [Theory]
+        [InlineData(1, ResolutionMath.MinResolution)]
+        [InlineData(99999, ResolutionMath.MaxResolution)]
+        public void 结果被夹取到合法区间(int input, int expected)
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.AbsolutePixels, 1080, 0f, input);
+            Assert.Equal(expected, actual);
+        }
+
+        [Fact]
+        public void 屏幕高度为零时_回退默认值()
+        {
+            int actual = ResolutionMath.Resolve(OpticResolutionMode.ScreenHeightRatio, 0, 0.5f, 0);
+            Assert.Equal(ResolutionMath.GameDefaultResolution, actual);
+        }
+    }
+}