Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
01 automap shotgate_pages/automap.json
02 camp_e shotgate_pages/camp_e.json
03 char_stats shotgate_pages/char_stats.json
04 charselect shotgate_pages/charselect.json
05 cube shotgate_pages/cube.json
06 inventory shotgate_pages/inventory.json
07 newchar shotgate_pages/newchar.json
08 npc shotgate_pages/npc.json
09 options shotgate_pages/options.json
10 quest_log shotgate_pages/quest_log.json
11 skilltree shotgate_pages/skilltree.json
12 stash shotgate_pages/stash.json
13 warlock_camp shotgate_pages/warlock_camp.json
14 warlock_skilltree shotgate_pages/warlock_skilltree.json
15 waypoint shotgate_pages/waypoint.json
16 wild shotgate_pages/wild.json
17 combat_548 run_page.sh:combat:548
18 combat_615 run_page.sh:combat:615
19 combat_632 run_page.sh:combat:632
20 combat_712 run_page.sh:combat:712
1 01 automap shotgate_pages/automap.json
2 02 camp_e shotgate_pages/camp_e.json
3 03 char_stats shotgate_pages/char_stats.json
4 04 charselect shotgate_pages/charselect.json
5 05 cube shotgate_pages/cube.json
6 06 inventory shotgate_pages/inventory.json
7 07 newchar shotgate_pages/newchar.json
8 08 npc shotgate_pages/npc.json
9 09 options shotgate_pages/options.json
10 10 quest_log shotgate_pages/quest_log.json
11 11 skilltree shotgate_pages/skilltree.json
12 12 stash shotgate_pages/stash.json
13 13 warlock_camp shotgate_pages/warlock_camp.json
14 14 warlock_skilltree shotgate_pages/warlock_skilltree.json
15 15 waypoint shotgate_pages/waypoint.json
16 16 wild shotgate_pages/wild.json
17 17 combat_548 run_page.sh:combat:548
18 18 combat_615 run_page.sh:combat:615
19 19 combat_632 run_page.sh:combat:632
20 20 combat_712 run_page.sh:combat:712
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""用 NVIDIA FLIP 对同名 PNG 做 G1 逐帧对比。 | Use NVIDIA FLIP to do the G1 frame-by-frame comparison of PNGs with the same name."""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from PIL import Image
RED = "\033[31m"
RESET = "\033[0m"
MEAN_RE = re.compile(r"^\s*Mean:\s*([0-9]+(?:\.[0-9]+)?)\s*$", re.MULTILINE)
def pngs(directory: Path) -> dict[str, Path]:
return {
path.relative_to(directory).as_posix(): path
for path in directory.rglob("*")
if path.is_file() and path.suffix.lower() == ".png"
}
def flip_one(job: tuple[str, str, str, str]) -> tuple[str, float]:
name, flip, reference, test = job
result = subprocess.run(
[flip, "-r", reference, "-t", test, "-ppd", "95", "-v", "1", "-nerm"],
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
raise RuntimeError(f"FLIP 失败:{name}\n{result.stdout}{result.stderr}")
match = MEAN_RE.search(result.stdout + result.stderr)
if not match:
raise RuntimeError(f"FLIP 输出没有 Mean:{name}\n{result.stdout}{result.stderr}")
return name, float(match.group(1))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("reference", type=Path)
parser.add_argument("test", type=Path)
parser.add_argument(
"--flip",
type=Path,
default=Path(__file__).resolve().parents[3] / "dm/third_party/flip/flip",
)
args = parser.parse_args()
reference = pngs(args.reference)
test = pngs(args.test)
missing = sorted(set(reference) - set(test))
if missing:
for name in missing:
print(f"{RED}缺帧:{name}{RESET}", file=sys.stderr)
common = sorted(set(reference) & set(test))
jobs: list[tuple[str, str, str, str]] = []
invalid = bool(missing)
for name in common:
with Image.open(reference[name]) as reference_image, Image.open(test[name]) as test_image:
if reference_image.size != test_image.size:
print(
f"{RED}尺寸不同:{name} 真值={reference_image.size} 被测={test_image.size}{RESET}",
file=sys.stderr,
)
invalid = True
continue
jobs.append((name, str(args.flip), str(reference[name]), str(test[name])))
if invalid:
return 1
if not args.flip.is_file() or not os.access(args.flip, os.X_OK):
print(f"{RED}FLIP 不可执行:{args.flip}{RESET}", file=sys.stderr)
return 1
# PPD 推导:iPhone 17 Pro Max ≈460 ppi、观看 30 cm,
# 0.30·tan(1°)/0.0254·460 ≈ 95。
# PPD derivation: iPhone 17 Pro Max ≈460 ppi, viewed at 30 cm,
# 0.30·tan(1°)/0.0254·460 ≈ 95.
with ProcessPoolExecutor(max_workers=8) as pool:
results = list(pool.map(flip_one, jobs))
values = sorted(results)
for name, mean in values:
print(f"{name} {mean:.6f}")
overall = sum(mean for _, mean in values) / len(values) if values else 0.0
worst = sorted(values, key=lambda item: item[1], reverse=True)[:3]
worst_text = ", ".join(f"{name} {mean:.6f}" for name, mean in worst) or "无"
print(f"G1 均值 {overall:.6f} 最差 3 帧 {worst_text}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+86
View File
@@ -0,0 +1,86 @@
# Image Quality Metric
中文:[image_quality.zh-CN.md](image_quality.zh-CN.md)
This directory holds two rulers for measuring the picture, both measured on a Mac from offline screenshots taken with the host (`dmhost` from `dm/host`):
- **G1** (`shoot.sh` + `g1.py`): how far the picture at a given internal resolution is from "the best picture achievable on this phone screen". Used to choose the internal resolution.
- **Visual-equivalence ruler** (`ruler.sh`): whether, after a given rendering optimization is turned on, the picture is equivalent to the picture without it. Used to gate optimizations in the graphics layer.
Both use NVIDIA FLIP to measure the difference between two images. FLIP is an image difference metric that models human viewing, 0 = no visible difference; the source is in `dm/third_party/flip/` (BSD-3); first run `make -C dm/third_party/flip` to build `dm/third_party/flip/flip`.
## G1: how far from native resolution
### Definitions
- **Reference frame**: the same frozen frame, drawn at the screen's native resolution 2868x1320, without upscaling.
- **Frame under test**: the same frame drawn at some internal resolution (`DM_GAME_RES`), then upscaled to 2868x1320 through the real presentation path (the graphics layer's `present_encode`). The screenshot size is fixed by `DM_NVN_SHOT_OUT=2868x1320`, which `shoot.sh` already sets.
- **Switch baseline**: 900 high, bilinear upscaling. The width is taken as 1952 by the screen's aspect ratio (1952x900), not the 16:9 1600x900 — 16:9 output would be centered with black bars and the UI layout would differ as well, so it could not be matched pixel for pixel with the reference frame.
- **G1** = the FLIP (LDR) mean, `-ppd 95`, averaged over all frames. `ppd` is the number of pixels per degree of visual angle: the iPhone 17 Pro Max is about 460 ppi at a viewing distance of 30 cm, 0.30 × tan 1° ÷ 0.0254 × 460 ≈ 95.
- **Target**: the phone configuration's G1 ≤ half of the Switch baseline's G1.
What is measured is sharpness: the internal resolution changes only sharpness, not the field of view or the layout.
### Frame list
`frames.tsv` lists 20 frames, each line being "number, name, source":
- 01–16 take the trigger, key sequence and environment variables directly from the [screenshot gate](../screenshot_gate.md) page specs (`shotgate_pages/*.json`).
- 17–20 are four combat frames: they replay the command packets recorded from a ground-truth run (ground truth = reference data obtained by running the original game in a patched Ryujinx emulator) and use `DM_TICK_HOLD=<tick>:SHOT` to stop at the specified tick and take the screenshot.
Prerequisites:
- The standard save `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001` (`DM_GATE_SAVE` overrides it).
- The ground-truth replay files referenced in the page specs; the replay file path for the combat frames is hard-coded in `shoot.sh` and `ruler.sh`, pointing to a ground-truth run directory under `$DM_ROOT/run/verify/ryu/`. None of these are in the repository, and the emulator driver scripts used to record them are not shipped either, so the frames that rely on ground-truth replay cannot be run with this repository alone; see [../README.md](../README.md).
### Commands
```
make -C dm/third_party/flip
bash dm/verify/gfxq/shoot.sh dm/host/dmhost <build output dir> <WxH> <output dir> [parallel jobs=4] [number or name…]
python3 dm/verify/gfxq/g1.py <reference dir> <test dir> [--flip <flip path>]
```
- `shoot.sh` starts one host per frame and outputs `<output dir>/<number>.png` and `<number>.log`; with no numbers given it runs all 20 frames. When frames fail it lists the failed frames, exit code 1.
- `g1.py` compares the PNGs with the same name in the two directories: it prints the FLIP mean frame by frame, and the last line gives the G1 mean and the 3 worst frames. When the test directory is missing frames or the sizes on the two sides differ it reports red, exit code 1. `--flip` defaults to `dm/third_party/flip/flip`.
One complete measurement: first produce the reference directory at `2868x1320`, then produce one test directory for each candidate resolution, and compute G1 for each against the reference directory.
### About the video memory budget
The game's own video memory allocator has a budget constant (`main + 0x8524c4`), which is 260 MB in the original. Under this budget, as soon as the internal resolution is high the render targets no longer fit and the game crashes at startup, so a reference frame at native resolution cannot be drawn.
The rewriter has already registered this constant as a cut (`CUTS` in `dm/tools/patch_nso.py`), and it is 512 MB in all build outputs, so reference frames can simply be produced with an ordinary build output. `truth_out.sh` is the approach from before this cut went into the rewriter: it copies a build output that is still at 260 MB to `<source>-truth` and changes this one instruction. It first checks whether the source build output still has the original instruction at that location; for current build outputs it reports red and exits, and it no longer needs to be used.
### Rules
- **The reference frames and the frames under test must be produced with the same host binary.** Once the host's replay pacing changes, the two binaries are not drawing the same instant, and the difference that comes out is a systematic offset rather than a change in image quality. So every time readings are produced, first reproduce the reference frames with the current host, then produce the frames under test.
- **Run the frames at product pacing; do not set `DM_DETCLOCK`.** (`DM_DETCLOCK` is the deterministic clock for logic-type tests.) With it set, game ticks run ahead of asynchronous loading and the UI, and the behavior of panels and the loading screen is neither like the product nor deterministic.
- **Measure the noise floor every time.** Frozen frames cannot be made byte-for-byte reproducible: things the client itself animates, such as flames and animations, will not stop at the same instant in two runs. Run the same binary with the same configuration twice, and the FLIP between the two runs is the noise floor (record both the per-frame values and the mean); only more than 2 times the noise floor counts as a difference. The noise floor is not carried over from old numbers.
- **The width of the native setting must be exactly equal to the screen width.** If it is off by even a few columns, the output still has to be resampled across the whole screen, and every pixel gets interpolated once.
## Visual-equivalence ruler: `ruler.sh`
G1 has to be compared across runs, its noise floor is on the high side, and it cannot measure small differences. To judge "whether the picture is still the same one after a given optimization is turned on", use this ruler: it takes three shots in a row within **the same process and the same frozen tick**.
```
bash dm/verify/gfxq/ruler.sh <dmhost> <build output dir> <WxH> <output dir> [frame number…]
```
- One host is started per frame. `DM_NVN_RULER=1` makes the host first take the two shots A and B with the "reference settings" (the batch of rendering optimizations the graphics layer makes for Apple GPUs all turned off), then switch to the settings under test (everything on by default, plus the environment variables passed through by the caller) and take C. The three shots are 8 frames apart.
- **Noise** = FLIP(A, B), **difference** = FLIP(B, C), both with `-ppd 95`.
- With no frame numbers given it runs 4 frames: `02` camp, `16` wilderness, `18` combat, `06` inventory.
- Output is `<output dir>/<frame number>_{A,B,C}.png` and `<frame number>.log`; each frame prints one line of readings and the verdict, and the last line is 「汇总:n/m 帧等价」 (summary: n/m frames equivalent); if any frame is not equivalent the exit code is 1.
There are two modes of judgment, selected with the environment variable `RULER_MODE`:
| Mode | Applies to | Condition for judging equivalent |
|---|---|---|
| `exact` (default) | Optimizations such as merging and skipping, which ought to produce the same image | FLIP difference ≤ 0.01 and ≤ 2 × noise + 0.002; and the count of "large-difference pixels" (any channel differing by > 30/255): B–C ≤ 2 × A–B + 0.005% of the picture's pixels |
| `approx` | Approximations such as lowering resolution or changing the filter | FLIP difference ≤ 0.02; and the number of pixels differing by > 60/255: B–C ≤ 2 × A–B + 0.05% of the picture's pixels |
Why count large-difference pixels: the FLIP mean is insensitive to local defects; when a small patch is not drawn, the mean hardly moves.
Negative control: `DM_NVN_RULER_NEG=<fragment shader key>` makes the settings under test drop the draws that use that shader, and the ruler must report non-equivalent. After adding a new criterion or changing the switching timing, run a negative control once first to confirm the ruler is not running idle.
Limitation: this ruler can only measure settings that can be switched at run time.
+86
View File
@@ -0,0 +1,86 @@
# 画质度量
English: [image_quality.md](image_quality.md)
这个目录里是两把量画面的尺子,都在 Mac 上用宿主(`dm/host` 的 `dmhost`)离线截图来量:
- **G1**(`shoot.sh` + `g1.py`):某个内部分辨率下的画面,离「这块手机屏幕上能达到的最好画面」有多远。用来选内部分辨率。
- **视觉等价尺子**(`ruler.sh`):打开某项渲染优化之后,画面是否与不开时等价。用来给图形层的优化把关。
两者都用 NVIDIA FLIP 度量两张图的差异。FLIP 是一种模拟人眼观看的图像差异指标,0 = 看不出差别;源码在 `dm/third_party/flip/`(BSD-3),先 `make -C dm/third_party/flip` 编出 `dm/third_party/flip/flip`。
## G1:离原生分辨率有多远
### 口径
- **参照帧**:同一冻结帧,按屏幕原生分辨率 2868x1320 画出,不经放大。
- **被测帧**:同一帧按某个内部分辨率(`DM_GAME_RES`)画,再经真实的出图路径(图形层的 `present_encode`)放大到 2868x1320。截图尺寸由 `DM_NVN_SHOT_OUT=2868x1320` 固定,`shoot.sh` 已经带上。
- **Switch 基线**:900 高、双线性放大。宽度按屏幕比例取 1952(1952x900),不用 16:9 的 1600x900——16:9 出图会居中加黑边、界面布局也不同,没法与参照帧逐像素对上。
- **G1** = FLIP(LDR)均值,`-ppd 95`,对全部帧取平均。`ppd` 是每度视角的像素数:iPhone 17 Pro Max 约 460 ppi、观看距离 30 cm,0.30 × tan 1° ÷ 0.0254 × 460 ≈ 95。
- **目标**:手机方案的 G1 ≤ Switch 基线 G1 的一半。
量的是清晰度:内部分辨率只改清晰度,不改视野与布局。
### 帧清单
`frames.tsv` 列了 20 帧,每行「编号、名字、来源」:
- 01–16 直接取[画面闸门](../screenshot_gate.zh-CN.md)页规格(`shotgate_pages/*.json`)里的触发、键序与环境变量。
- 17–20 是四个战斗帧:回放一份真值局录下的命令包(真值 = 用打了补丁的 Ryujinx 模拟器跑原版游戏得到的参照数据),用 `DM_TICK_HOLD=<拍>:SHOT` 停在指定的拍截图。
前提:
- 标准存档 `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001`(`DM_GATE_SAVE` 可换)。
- 页规格里引用的真值回放文件;战斗帧的回放文件路径写死在 `shoot.sh` 与 `ruler.sh` 里,指向 `$DM_ROOT/run/verify/ryu/` 下的一个真值局目录。这些仓库里没有;录制用的模拟器驱动脚本也不随仓库提供,所以用到真值回放的帧在仓库外跑不了,见 [../README.zh-CN.md](../README.zh-CN.md)。
### 命令
```
make -C dm/third_party/flip
bash dm/verify/gfxq/shoot.sh dm/host/dmhost <产物目录> <宽x高> <输出目录> [并行数=4] [编号或名字…]
python3 dm/verify/gfxq/g1.py <参照目录> <被测目录> [--flip <flip 路径>]
```
- `shoot.sh` 每帧起一个宿主,输出 `<输出目录>/<编号>.png` 与 `<编号>.log`;不给编号就跑全部 20 帧。有帧失败时列出失败帧,退出码 1。
- `g1.py` 比两个目录里同名的 PNG:逐帧打印 FLIP 均值,末行给出 G1 均值与最差的 3 帧。被测目录缺帧或两边尺寸不同时报红,退出码 1。`--flip` 缺省就是 `dm/third_party/flip/flip`。
一次完整的量法:先用 `2868x1320` 出参照目录,再用各个候选分辨率各出一个被测目录,分别与参照目录算 G1。
### 关于显存预算
游戏自己的显存分配器有一个预算常数(`main + 0x8524c4`),原版是 260 MB。这个预算下内部分辨率一高,渲染目标就放不下、游戏启动即崩,画不出原生分辨率的参照帧。
改写器已经把这个常数登记为剪口(`dm/tools/patch_nso.py` 的 `CUTS`),所有产物里都是 512 MB,所以参照帧直接用普通产物出即可。`truth_out.sh` 是这条剪口进改写器之前的做法:把一份仍是 260 MB 的产物复制成 `<源>-truth` 并改这一条指令。它会先核对源产物该处是不是原来的指令,对现行产物会报红退出,不需要再用。
### 规矩
- **参照帧与被测帧必须用同一个宿主二进制出。** 宿主的回放节拍一变,两个二进制画的就不是同一刻,差出来的是系统偏差而不是画质变化。所以每次出读数都先用当前宿主重出参照帧,再出被测帧。
- **跑帧用产品节奏,不设 `DM_DETCLOCK`。**(`DM_DETCLOCK` 是给逻辑类测试用的确定性时钟。)设了它,游戏拍会跑在异步加载与界面前面,面板与读取画面的行为既不像产品也不确定。
- **噪声底每次实测。** 冻结帧做不到逐字节可复现:火焰、动画这类客户端自己在动的东西,两次运行不会停在同一刻。同一个二进制、同一个配置跑两遍,两遍之间的 FLIP 就是噪声底(逐帧与均值都记);超过噪声底 2 倍才算差异。噪声底不沿用旧数。
- **原生档的宽必须恰好等于屏幕宽。** 只差几列,出图也要整屏重采样,每个像素都被插值一遍。
## 视觉等价尺子:`ruler.sh`
G1 要跨运行比,噪声底偏高,量不出小差异。判断「开了某项优化之后画面还是不是同一张」用这把尺子:它在**同一个进程、同一冻结拍**里连截三张。
```
bash dm/verify/gfxq/ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…]
```
- 每帧起一个宿主。`DM_NVN_RULER=1` 让宿主先用「参照设置」(图形层针对苹果显卡做的那批渲染优化全部关掉)截 A、B 两张,然后切到被测设置(缺省全开,加上调用方透传的环境变量)截 C。三张各隔 8 帧。
- **噪声** = FLIP(A, B),**差异** = FLIP(B, C),都用 `-ppd 95`。
- 不给帧号时跑 4 帧:`02` 营地、`16` 野外、`18` 战斗、`06` 物品栏。
- 输出 `<输出目录>/<帧号>_{A,B,C}.png` 与 `<帧号>.log`;每帧打一行读数与判定,末行「汇总:n/m 帧等价」;有不等价的帧则退出码 1。
判定分两种口径,用环境变量 `RULER_MODE` 选:
| 口径 | 适用 | 判等价的条件 |
|---|---|---|
| `exact`(缺省) | 合并、跳过这类应当出同一张图的优化 | FLIP 差异 ≤ 0.01 且 ≤ 2 × 噪声 + 0.002;并且「大差像素」(任一通道差 > 30/255)的个数:B–C ≤ 2 × A–B + 画面像素的 0.005% |
| `approx` | 降分辨率、换滤波这类近似 | FLIP 差异 ≤ 0.02;并且差 > 60/255 的像素数:B–C ≤ 2 × A–B + 画面像素的 0.05% |
为什么要数大差像素:FLIP 均值对局部缺损不敏感,一小块没画出来,均值几乎不动。
负对照:`DM_NVN_RULER_NEG=<片元着色器键>` 让被测设置丢掉用该着色器的绘制,尺子必须报不等价。新加判据或改了切换时机之后,先跑一次负对照,确认尺子没有空转。
限制:这把尺子只能量运行中可以切换的设置。
+112
View File
@@ -0,0 +1,112 @@
#!/bin/bash
# 视觉等价尺子(同进程 A/B/C):每帧一个宿主、同一冻结拍连截三张——A、B 用真值设置(DM_NVN_RULER=1:TBDR 优化全关),
# 提交边界切到被测设置(缺省全开 + 调用方透传的环境)截 C。噪声 = FLIP(A,B),差异 = FLIP(B,C),-ppd 95;判「FLIP 差异 ≤ 0.01 且 ≤ 2×噪声 + 0.002」并且「大差像素(任一通道差 > 30/255)数:差异 ≤ 2×噪声 + 画面像素的 0.005%」。
# 跨运行比不可用:两次同设置独立运行的噪声底营地单帧 0.0108。只能测运行中可切换的设置。
# 用法:ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…,缺省 02 营地 16 野外 18 战斗 06 菜单] 产物:<输出目录>/<帧号>_{A,B,C}.png、<帧号>.log
# 口径(RULER_MODE):exact(缺省)= 合并 / 跳过类,应与真值同图,按 2×噪声线判;
# approx = 降分辨率 / 换滤波 / 近似类,按「FLIP(B,C) ≤ 0.02」判(实机上 3D 内部 0.75–0.80 倍、FLIP 0.017–0.023 肉眼无差别),
# 局部缺损判据放宽为「差 > 60/255 的像素数 B–C ≤ 2×A–B + 画面 0.05%」(边缘本来就会动;阈值待用 X1 的图校准,行里把两档像素数都打出来)。
# 负对照:DM_NVN_RULER_NEG=<片元键> 被测设置下丢掉该着色器的绘制,尺子必须报不等价。
# Visual-equivalence ruler (same process A/B/C): one host per frame, three consecutive shots of the same frozen tick - A and B use the ground-truth settings (DM_NVN_RULER=1: all TBDR optimizations off),
# at a commit boundary switch to the settings under test (default all on + the environment passed through by the caller) and shoot C. Noise = FLIP(A,B), difference = FLIP(B,C), -ppd 95; the verdict is "FLIP difference ≤ 0.01 and ≤ 2×noise + 0.002" and "count of large-difference pixels (any channel difference > 30/255): difference ≤ 2×noise + 0.005% of the frame's pixels".
# Cross-run comparison is unusable: the noise floor between two independent runs with the same settings is 0.0108 for a single camp frame. Only settings that can be switched at run time can be tested.
# Usage: ruler.sh <dmhost> <build output dir> <WxH> <output dir> [frame ids..., default 02 camp 16 wilderness 18 combat 06 menu] Build output: <output dir>/<frame id>_{A,B,C}.png, <frame id>.log
# Mode (RULER_MODE): exact (default) = merge / skip class, should produce the same image as ground truth, judged by the 2×noise line;
# approx = lower-resolution / filter-change / approximation class, judged by "FLIP(B,C) ≤ 0.02" (on a real device, with the 3D internal scale at 0.75–0.80×, FLIP 0.017–0.023 shows no difference to the naked eye),
# the local-defect criterion is relaxed to "count of pixels with difference > 60/255: B–C ≤ 2×A–B + 0.05% of the frame" (edges move anyway; the threshold is pending calibration with X1 images, and the line prints the pixel counts for both tiers).
# Negative control: DM_NVN_RULER_NEG=<fragment key> drops the draws of that shader under the settings under test; the ruler must report non-equivalence.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
FRAMES="$HERE/frames.tsv"
BIN=${1:?用法:ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…]}
PRODUCTS=${2:?缺少产物目录}
GAME_RES=${3:?缺少宽x高}
OUTPUT=${4:?缺少输出目录}
shift 4 || true
mkdir -p "$OUTPUT/tmp" || exit 2
selected=''
if [ "$#" -gt 0 ]; then
for wanted in "$@"; do
row=$(awk -F '\t' -v w="$wanted" '$1 == w || $2 == w { print; exit }' "$FRAMES")
[ -n "$row" ] || { echo "失败:未知帧编号或名称 $wanted" >&2; exit 2; }
selected="$selected$row"$'\n'
done
else
selected=$(printf '%s\n' 02 16 18 06 | while IFS= read -r wanted; do awk -F '\t' -v w="$wanted" '$1 == w { print; exit }' "$FRAMES"; done)
fi
run_frame() {
local row id name source frame_tmp log page trigger keys env_json key value trig_base shot_ui pid
row=$1
local -a env_args
id=$(printf '%s\n' "$row" | cut -f1); name=$(printf '%s\n' "$row" | cut -f2); source=$(printf '%s\n' "$row" | cut -f3)
frame_tmp="$OUTPUT/tmp/$id"; mkdir -p "$frame_tmp"; log="$OUTPUT/$id.log"
env_args=(DM_NVN_RULER=1 DM_NVN_SHOT_OUT="$GAME_RES" DM_GAME_RES="$GAME_RES" DM_TEMP="$frame_tmp")
if [[ "$source" == shotgate_pages/*.json ]]; then
page="$HERE/../$source"
IFS=$'\t' read -r trigger keys env_json < <(python3 -c 'import json,sys; h=json.load(open(sys.argv[1]))["host"]; print("\t".join((h["trigger"],h.get("keys") or "-",json.dumps(h.get("env",{}),separators=(",",":")))))' "$page")
[ "$keys" = - ] || env_args+=("DM_KEYS=$keys")
while IFS=$'\t' read -r key value; do [ -n "$key" ] && env_args+=("$key=$value"); done < <(python3 -c 'import json,os,sys; [print(k+"\t"+os.path.expanduser(v)) for k,v in json.loads(sys.argv[1]).items()]' "$env_json")
else
IFS=: read -r _ combat tick <<<"$source"
trigger="DM:Tick:${tick}#+20"
env_args+=(DM_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame' DM_C2S_REPLAY=${DM_ROOT:-$HOME/dm-work}/run/verify/ryu/war_summon13_1002_takeover/c2s.jsonl DM_GAME_SEED=305419896 DM_FIXED_TIME=1790895128 "DM_TICK_HOLD=${tick}:SHOT")
fi
trig_base=$(printf '%s' "$trigger" | sed -E 's/\+[0-9]+$//')
# 三张等间隔(各隔 8 帧):切换在 B 写盘后的下一次提交才生效,C 紧跟 B 一帧会赶在切换之前出图(负对照实测:尺子变成空转)
# Three shots at equal spacing (8 frames apart each): the switch only takes effect at the next commit after B is written to disk; a C that follows B by one frame would be rendered before the switch (negative control, measured: the ruler becomes a no-op)
shot_ui="$trig_base+20:$frame_tmp/A.png,$trig_base+28:$frame_tmp/B.png,$trig_base+36:$frame_tmp/C.png"
env_args+=("DM_NVN_SHOT_UI=$shot_ui")
SV=${DM_GATE_SAVE:-${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001}
W=$(mktemp -d "$frame_tmp/save.XXXX")
cp -R "$SV/0" "$W/save" && chmod -R u+w "$W/save" || { echo "失败 ${id}:拷存档失败" >&2; return 1; }
mkdir -p "$W/temp"
timeout 45s env "${env_args[@]}" DM_SAVE="$W/save" DM_TEMP="$W/temp" DM_WATCH_STALL=15 DM_WATCH=225 "$BIN" "$PRODUCTS" main sdk >"$frame_tmp/host.log" 2>&1 & pid=$!
while [ ! -s "$frame_tmp/A.png" ] || [ ! -s "$frame_tmp/B.png" ] || [ ! -s "$frame_tmp/C.png" ]; do
kill -0 "$pid" 2>/dev/null || { echo "失败 ${id}:宿主提前退出" >&2; cp "$frame_tmp/host.log" "$log"; rm -rf "$W"; return 1; }
sleep 1
done
kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null; cp "$frame_tmp/host.log" "$log"; rm -rf "$W"
for x in A B C; do cp "$frame_tmp/$x.png" "$OUTPUT/${id}_$x.png"; done # 留图:报红时要能看差在哪 | Keep the images: when it reports a failure, one must be able to see where the difference is
flip="$HERE/../../third_party/flip/flip"
noise=$(timeout 20s "$flip" -r "$frame_tmp/A.png" -t "$frame_tmp/B.png" -ppd 95 -v 1 -nerm 2>&1 | awk '/Mean:/{print $2; exit}')
diff=$(timeout 20s "$flip" -r "$frame_tmp/B.png" -t "$frame_tmp/C.png" -ppd 95 -v 1 -nerm 2>&1 | awk '/Mean:/{print $2; exit}')
[ -n "$noise" ] && [ -n "$diff" ] || { echo "失败 ${id}:FLIP 无 Mean" >&2; return 1; }
# 局部判据:FLIP 均值对局部缺损不敏感(负对照:战斗帧丢 FXAA 有 4051 个像素差 > 30,均值只有 0.0016)——再数「大差像素」(任一通道差 > 30/255)
# Local criterion: the FLIP mean is insensitive to local defects (negative control: a combat frame that drops FXAA has 4051 pixels with difference > 30, yet the mean is only 0.0016) - so also count "large-difference pixels" (any channel difference > 30/255)
read -r big_ab big_bc npx big60_ab big60_bc < <(python3 - "$frame_tmp/A.png" "$frame_tmp/B.png" "$frame_tmp/C.png" <<'PY2'
import sys
import numpy as np
from PIL import Image
a, b, c = (np.asarray(Image.open(p).convert('RGB')).astype(np.int16) for p in sys.argv[1:4])
big = lambda x, y, th: int((np.abs(x - y).max(axis=2) > th).sum())
print(big(a, b, 30), big(b, c, 30), a.shape[0] * a.shape[1], big(a, b, 60), big(b, c, 60))
PY2
)
[ -n "${npx:-}" ] || { echo "失败 ${id}:大差像素统计失败" >&2; return 1; }
if [ "${RULER_MODE:-exact}" = approx ]; then
verdict=$(awk -v d="$diff" -v ab="$big60_ab" -v bc="$big60_bc" -v px="$npx" 'BEGIN { print (d <= 0.02 && bc <= 2*ab + px*0.0005) ? "等价" : "不等价" }')
else
verdict=$(awk -v d="$diff" -v n="$noise" -v ab="$big_ab" -v bc="$big_bc" -v px="$npx" 'BEGIN { print (d <= 0.01 && d <= 2*n + 0.002 && bc <= 2*ab + px*0.00005) ? "等价" : "不等价" }')
fi
printf '%s 噪声 %.6f 差异 %.6f 大差像素(>30) 噪声 %d 差异 %d (>60) 噪声 %d 差异 %d 判定[%s] %s\n' "$id" "$noise" "$diff" "$big_ab" "$big_bc" "$big60_ab" "$big60_bc" "${RULER_MODE:-exact}" "$verdict"
[ "$verdict" = 等价 ]
}
fail=0; total=0; equivalent=0
sem="$OUTPUT/tmp/sem.$$"
mkfifo "$sem" || exit 2
exec 9<>"$sem"; rm -f "$sem"
for _ in 1 2 3 4; do printf '\n' >&9; done
result_dir="$OUTPUT/tmp/results"; mkdir -p "$result_dir"
while IFS= read -r row; do
[ -n "$row" ] || continue
total=$((total + 1)); id=$(printf '%s\n' "$row" | cut -f1)
read -u 9
{ if run_frame "$row"; then printf '1\n' >"$result_dir/$id"; else printf '0\n' >"$result_dir/$id"; fi; printf '\n' >&9; } &
done <<< "$selected"
wait
exec 9>&-
for result in "$result_dir"/*; do [ -f "$result" ] || continue; read -r ok <"$result"; [ "$ok" = 1 ] && equivalent=$((equivalent + 1)) || fail=1; done
echo "汇总:$equivalent/$total 帧等价"
rm -rf "$OUTPUT/tmp"
exit "$fail"
+119
View File
@@ -0,0 +1,119 @@
#!/bin/bash
# 批量截取画质度量帧;输出目录由调用方提供,不向工作树写产物。
# Batch-capture the image-quality metric frames; the output directory is provided by the caller, and no build output is written to the working tree.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
FRAMES="$HERE/frames.tsv"
HOSTSHOT="$HERE/../hostshot.sh"
BIN=${1:?用法:shoot.sh <dmhost> <产物目录> <DM_GAME_RES> <输出目录> [并行数=4(本机自起宿主上限)] [编号…]}
PRODUCTS=${2:?缺少产物目录}
GAME_RES=${3:?缺少 DM_GAME_RES}
OUTPUT=${4:?缺少输出目录}
JOBS=${5:-4}
shift 5 || true
case "$JOBS" in ''|*[!0-9]*|0) echo "失败:并行数必须是正整数" >&2; exit 2 ;; esac
mkdir -p "$OUTPUT/tmp" || exit 2
# 统一从 frames.tsv 读取,支持传编号或名称;未指定时跑全部 20 帧。
# Always read from frames.tsv; accepts ids or names; when unspecified, runs all 20 frames.
selected=''
if [ "$#" -gt 0 ]; then
for wanted in "$@"; do
row=$(awk -F '\t' -v w="$wanted" '$1 == w || $2 == w { print; exit }' "$FRAMES")
[ -n "$row" ] || { echo "失败:未知帧编号或名称 $wanted" >&2; exit 2; }
selected="$selected$row
"
done
else
selected=$(cat "$FRAMES")
fi
start=$SECONDS
fail_file="$OUTPUT/tmp/failed.$$"
: > "$fail_file"
run_frame() {
local row=$1 id name source png log frame_tmp trigger keys env_json page key value
local -a env_args
id=$(printf '%s\n' "$row" | cut -f1)
name=$(printf '%s\n' "$row" | cut -f2)
source=$(printf '%s\n' "$row" | cut -f3)
png="$OUTPUT/$id.png"
log="$OUTPUT/$id.log"
frame_tmp="$OUTPUT/tmp/$id"
mkdir -p "$frame_tmp"
: > "$frame_tmp/run.log"
env_args=(DM_NVN_SHOT_OUT=2868x1320 DM_GAME_RES="$GAME_RES" DM_TEMP="$frame_tmp")
if [[ "$source" == shotgate_pages/*.json ]]; then
page="$HERE/../$source"
IFS=$'\t' read -r trigger keys env_json <<EOF2
$(python3 - "$page" <<'PY'
import json, sys
page = json.load(open(sys.argv[1]))
host = page['host']
print('\t'.join((host['trigger'], host.get('keys') or '-', json.dumps(host.get('env', {}), separators=(',', ':')))))
PY
)
EOF2
[ "$keys" = - ] || env_args+=("DM_KEYS=$keys")
while IFS=$'\t' read -r key value; do
[ -n "$key" ] && env_args+=("$key=$value")
done < <(python3 - "$env_json" <<'PY'
import json, os, sys
for key, value in json.loads(sys.argv[1]).items():
print(key + '\t' + os.path.expanduser(value))
PY
)
else
IFS=: read -r _ combat tick <<EOF2
$source
EOF2
trigger="DM:Tick:${tick}#+20"
env_args+=(
'DM_KEYS=X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame'
"DM_C2S_REPLAY=${DM_ROOT:-$HOME/dm-work}/run/verify/ryu/war_summon13_1002_takeover/c2s.jsonl"
DM_GAME_SEED=305419896
DM_FIXED_TIME=1790895128
"DM_TICK_HOLD=${tick}:SHOT"
)
fi
if env "${env_args[@]}" "$HOSTSHOT" "$BIN" "$PRODUCTS" "$trigger" "$png" 180 >"$frame_tmp/run.log" 2>&1; then
if [ -f "$log" ]; then cat "$frame_tmp/run.log" >> "$log"; else cp "$frame_tmp/run.log" "$log"; fi
echo "完成 $id $name"
else
if [ -f "$log" ]; then cat "$frame_tmp/run.log" >> "$log"; else cp "$frame_tmp/run.log" "$log"; fi
printf '%s\t%s\n' "$id" "$name" >> "$fail_file"
echo "失败 $id $name(见 $log)" >&2
fi
}
# Bash 3.2 无 wait -n,用 FIFO 令牌池维持并行上限。
# Bash 3.2 has no wait -n; use a FIFO token pool to keep the parallelism cap.
sem="$OUTPUT/tmp/sem.$$"
mkfifo "$sem" || exit 2
exec 9<>"$sem"
rm -f "$sem"
for _ in $(seq 1 "$JOBS"); do printf '\n' >&9; done
while IFS= read -r row; do
[ -n "$row" ] || continue
read -u 9
{ run_frame "$row"; printf '\n' >&9; } &
done <<EOF2
$selected
EOF2
wait
exec 9>&-
rc=0
if [ -s "$fail_file" ]; then
rc=1
echo "失败帧:"
cat "$fail_file"
fi
rm -rf "$OUTPUT/tmp"
elapsed=$((SECONDS - start))
echo "总墙钟:${elapsed}s"
exit "$rc"
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# 画质真值专用产物(只给离线画真值帧用,产品构建绝不带):复制产物目录到 <源>-truth,
# 把游戏显存分配器预算常数 main+0x8524c4 `mov x8,#0x10400000`(260 MB)改成 `mov x8,#0x20000000`(512 MB)。
# 依据:内部分辨率 > 约 345 万像素时该分配器放不下渲染目标、游戏启动即崩;真值要按屏幕原生 2868x1320 画。
# 该常数只是显存池预算,不进游戏逻辑——由 V1 逐拍对拍核(见 image_quality.md)。
# 用法:truth_out.sh [源产物目录=$DM_ROOT/build/cache/dm/out/<当前代号>-keypage] 输出:<源>-truth,打印其路径
# Build output dedicated to image-quality ground truth (only for rendering ground-truth frames offline; product builds never carry it): copy the build output directory to <source>-truth,
# and change the game's video memory allocator budget constant at main+0x8524c4 from `mov x8,#0x10400000` (260 MB) to `mov x8,#0x20000000` (512 MB).
# Rationale: when the internal resolution is > about 3.45 million pixels, this allocator cannot fit the render targets and the game crashes at startup; ground truth must be rendered at the screen's native 2868x1320.
# This constant is only the video memory pool budget and does not enter game logic - checked by the V1 per-tick comparison (see image_quality.md).
# Usage: truth_out.sh [source build output dir=$DM_ROOT/build/cache/dm/out/<current codename>-keypage] Output: <source>-truth, prints its path
set -eu
SRC=${1:-$(bash "$(dirname "$0")/../../tools/product.sh" path keypage)}; DST=$SRC-truth
OFF=$((0x8524c4)); OLD=d2a20808; NEW=d2a40008 # MOVZ X8,#0x1040,LSL#16 → MOVZ X8,#0x2000,LSL#16(小端存放) | MOVZ X8,#0x1040,LSL#16 → MOVZ X8,#0x2000,LSL#16 (stored little-endian)
le() { echo "$1" | sed -E 's/(..)(..)(..)(..)/\4\3\2\1/'; }
cur=$(xxd -s $OFF -l 4 -p "$SRC/main.patched.bin")
[ "$cur" = "$(le $OLD)" ] || { echo "【红】源产物 main+0x8524c4 不是预期指令 $OLD(读到小端 $cur),构建号变了?不改" >&2; exit 2; }
rm -rf "$DST"; cp -R "$SRC" "$DST"
printf "$(le $NEW | sed 's/../\\x&/g')" | dd of="$DST/main.patched.bin" bs=1 seek=$OFF conv=notrunc 2>/dev/null
[ "$(xxd -s $OFF -l 4 -p "$DST/main.patched.bin")" = "$(le $NEW)" ] || { echo "【红】写入核对失败" >&2; exit 1; }
cmp -l "$SRC/main.patched.bin" "$DST/main.patched.bin" | wc -l | awk '{ if ($1 > 4) { print "【红】改动字节数 " $1 " > 4" > "/dev/stderr"; exit 1 } }'
echo "$DST"