Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
fix(xess): fill uncovered background using NVOF forward-backward consistency
Veyra Goal Agente1183e700a55
diff --git a/AGENTS.md b/AGENTS.mdindex bc08b816..bfc90be2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-12 XeSS 光流修复复审(Claude)**:用户“codex完成了后续的修复工作,但实际效果一般,你可以审一下,看看还有没有可以优化的地方,有没有可能是默认光流是1080p的问题?当然codex还在处理其他的任务,你不要打断他,你们不要互相影响到”。只读 Codex 分支/构建/回执;存档 `checkpoint/pre-claude-xess-tune-20261012`(f0fafdf)与 E 盘 `archives/claude-xess-tune-20261012`,分支 `claude/xess-flow-tune-20261012`,产物统一 `{用途}/claude-xess-tune-20261012`。屏幕/GUI/GPU 计时前检查无其他 Veyra 进程,Codex 测试期间等待。结论:Codex 接线无缺陷;1080p 默认光流不是原因(全分辨率几乎无改善且更贵);新增 NVOF 后向光流的前后向一致性只用于判定/填补人物移开露出的背景(候选选择保持 Codex 版),仅 XeSS+光流+NVIDIA NVOF,NR/SR 光流逐字节不变;`VEYRA_TEST_FLOW_CONSISTENCY=0` 恢复 Codex 版。一致性参与选择的负收益方案已撤回。四肢与栏杆残差未解决。不改自动模式/其他补帧/运行库/模型/用户配置;无 merge/push/Release、无子 Agent。详见 docs/XESS_FLOW_REVIEW_2026-10-12.md。+> **2026-10-12 Claude 计划漏项补齐**:用户追问 FSR bug 和 Claude 其他工作完成情况。重新核对其最后获准的 JELLY_FIX_PLAN,FSR 单独开启补帧时初始化光流本来在接手范围内,初次接手排除它是 Agent 漏项。保留 f468dfb 和初次验收存档,在同一本地隔离分支按 docs/FSR_FLOW_FOLLOWUP_2026-10-12.md 补齐 FSR 光流消费者条件及真实 GPU/GUI 回归;不把 XeSS 精修扩到 FSR,不改自动选择规则、其他算法/UI节奏/默认优先级/运行组件/真实配置。新产物 E:/项目/Veyra/{用途}/fsr-flow-followup-20261012,初次所有回执和旧树基线保持。无子Agent、main合并、push、发布、关机。已证旧代码 NR/SR/standalone 全关时NVOF=0且合同失败,修复后显式光流/Automatic各9次、Zero0次,八组回归、真实FSR GUI及双入口通过;同时补齐密集竖条横移11/11中间帧A/B,无本组负收益。代码/本机回归完成,真实游戏观感待用户,栏杆模型问题/延迟仍暂缓。> **2026-10-12 XeSS 修复接手**:用户要求接手 Claude 额度耗尽的 XeSS 修复。按 docs/XESS_HANDOFF_PLAN_2026-10-12.md 在 codex/xess-handoff-20261012 从 7fe3ea6 继承独立封存的五文件未完成修改,只完成 XeSS 开启光流时的运动边界精修及必要生命周期/构建/真实画质和耗时验证。61 旧工作树/509 脏文件由 archives/xess-handoff-20261012/start.json 保护,Claude 原树不改;此具体范围覆盖历史冻结。不派 Agent、不修改运行库/模型/驱动/真实配置;33ms 统计和默认 GPU 优先级保持。全部产物 E 盘、每测试≤300秒/构建≤900秒;无 main 合并/push/Release/关机。未获益的精修撤回,合成画面结果不冒充真实游戏或其他硬件通过。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3d19d2fd..15112217 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -929,6 +929,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_include_directories(veyra_xess_motion_contract_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})target_compile_definitions(veyra_xess_motion_contract_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")target_link_libraries(veyra_xess_motion_contract_tests PRIVATE veyra_engine)+ add_executable(veyra_xess_motion_quality_tests tests/integration/XessMotionQualityTests.cpp)+ target_compile_features(veyra_xess_motion_quality_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_xess_motion_quality_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_compile_definitions(veyra_xess_motion_quality_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")+ target_link_libraries(veyra_xess_motion_quality_tests PRIVATE veyra_engine)# Qt 6.8.3 is staged under deps/ (the user allowed the latest Qt). The probe is# opt-in so a normal product build never depends on Qt being present.option(VEYRA_BUILD_QT_PROBE "Build the Qt + D3D12 host probe" OFF)diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 3ca48c39..fee94336 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -9209,3 +9209,15 @@ logs/.../results.json与reports/.../measurement.json:中速侧跑轮廓带MAE8images.py生成reports/.../images/xess-side-run-comparison.png和xess-fast-error-comparison.png。固定帧对14→15中点14.5、448×448腿部、左合成真值/中旧光流/右精修;原像素未缩放或修饰,拼图每区域逐字节与原图验证。相同×4绝对RGB误差图(越黑越好);该单帧高速整个裁切MAE6.6951→6.2269、中速7.0968→6.9294,不混淆为11帧轮廓带均值。原图、拼图、坐标及SHA见reports/.../images.json,已实际查看布局/文字/像素图。audit.py核对测试/GUI/所有app原件、两份旧final、旧JSON和源码bundle、当前两个文档范围、原61树/509脏文件、main及数据/图片原件,最终回执reports/.../final.json;诊断EXE SHA050740291e5cbb07a39da07da801dae03c192737a2f95b2a3bc07708f9ea49b7保持。没有真实游戏逐帧真值/观感或新性能验证,无main合并、push、打包、Release、二进制入Git或关机。++## 2026-10-12 XeSS 光流修复复审与前后向一致性(Claude)++用户要求审查 Codex 已完成的 XeSS 开启光流修复(实际效果一般),判断默认 1080p 光流是否为原因,且不得打断/影响仍在工作的 Codex。只读 codex/xess-handoff-20261012(f0fafdf)及其构建/回执;新工作树 worktrees/xess-flow-tune-20261012、分支 claude/xess-flow-tune-20261012,存档标签 checkpoint/pre-claude-xess-tune-20261012 与 archives/claude-xess-tune-20261012/start.json、source-before.bundle(verify)。构建 tmp/claude-xess-tune-20261012/build.py 复制自 Codex 构建脚本,依赖闭包 16 对象、17 EXE,读入对象/着色器哈希核对、着色器改用复制。capture.py/gui.py/motion.py 每次启动前检查其他 Veyra 进程;Codex 运行 capture_cadence_fg、live_presentation、qml_ui 期间三次拒绝启动并等待。++复审:Codex 接线(资源/描述符/状态/A=上一帧 B=当前帧/首帧 reset/NR-SR 保持/计时)未发现缺陷。新增无窗口测试 veyra_xess_motion_quality_tests(读回送 XeSS 的运动,按区域比真值 EPE,含 4K perf 模式):Codex 版主要残差是人物移开露出的背景(run80 EPE 38.5、63%>4px,颜色阈值不触发且错误向量被当可信来源扩散)与快速摆动四肢(各版 20–50px)。XeSS 敏感度:理想 6.0076,露出区置零 7.5111,四肢置零 7.2748。默认光流 1080p 不是原因:全分辨率 EPE 3.09→3.06(Codex 版),本版全分辨率反更差;J0 XeSS 8.2148→8.1977;NVOF 4K 成本约 3.5 倍。++改动:仅 XeSS+光流+NVIDIA NVOF 时 NVOF 输出后向光流(NvOfSession 已有 BOTH),FlowRefine 选择不变、记录选中向量的前后向不一致量,FlowFill 不一致 >2 光流像素即填补、只从 ≤0.5 的像素借向量;EnhanceGraph 新增两张网格纹理、SRV 槽与常量,测试开关 VEYRA_TEST_FLOW_CONSISTENCY=0;FgXessBoundaryTests 加 ideal-uncovered0/ideal-limbs0 敏感度变体;新测试入 CMake。撤回:一致性参与候选选择(bars27 9.7037→9.9149 负收益)、填补代价下限(只是误差互换);触发 2/4/8、来源 0.25/0.5/2 无实质差异。++结果(XeSS 抓屏 11/11 帧、采集/D3D12 0 错误,Codex 版数字本构建逐位复现):run27 6.3781→6.4016(+0.37%),run80 7.4180→7.3042(−1.53%),orbit80 3.0332→2.5901(−14.61%,距理想 2.0984 的差距缩小 47%),bars27 9.7037→9.6196(−0.87%);侧跑场景 >32 级像素比例略增(7.96→8.88、9.01→9.63)。无窗口运动:露出区 run80 38.5→6.6、orbit80 41.9→7.5。成本:4K 无窗口光流阶段 1.52→2.27 ms;真实 GUI(GTA VI 4K30、原版 NR 1080p、XeSS 2X、class2、帧 300–840 共 541 帧)光流阶段 1.53→2.26 ms,整图 9.52→9.19 ms 属波动不声称提速,提交 60/60。回归:Codex 合同测试 160/0、debug 0;GUI 生命周期(Codex ProbeXess 原样复制)52.6s 通过,三种运动路径与 NVOF 双向仅在 XeSS 分支。++本地测试版 tests/claude-xess-tune-20261012/delivery(Codex 测试包复制、去测试 EXE、换本版 EXE 与两个着色器;New/Codex/Original 三入口共用一份设置)。全部数字与来源见 reports/claude-xess-tune-20261012/results.json,报告 docs/XESS_FLOW_REVIEW_2026-10-12.md。四肢、栏杆残差,真实游戏观感、AMD/Intel、长期显存、屏幕延迟未验;无 merge/push/Release/子 Agent/关机。diff --git a/docs/XESS_FLOW_REVIEW_2026-10-12.md b/docs/XESS_FLOW_REVIEW_2026-10-12.mdnew file mode 100644index 00000000..a258a203--- /dev/null+++ b/docs/XESS_FLOW_REVIEW_2026-10-12.md@@ -0,0 +1,163 @@+# XeSS 开启光流:Codex 修复复审与前后向一致性改进(2026-10-12,Claude)++## 授权与范围++用户:“你没额度了,codex完成了后续的修复工作,但实际效果一般,你可以审一下,看看还有没有可以优化的地方,有没有可能是默认光流是1080p的问题?当然codex还在处理其他的任务,你不要打断他,你们不要互相影响到”。++- **只读 Codex 的成果**:分支 `codex/xess-handoff-20261012`(f0fafdf)、它的构建对象、回执和测试包,均不修改。+- **本轮自己的位置**:+ - 工作树 `worktrees/xess-flow-tune-20261012`,分支 `claude/xess-flow-tune-20261012`;+ - 构建、测试、日志、报告目录统一为 `{build,tests,logs,reports,tmp,archives}/claude-xess-tune-20261012`。+- **存档**:标签 `checkpoint/pre-claude-xess-tune-20261012`(f0fafdf),以及 `archives/claude-xess-tune-20261012/start.json` 和 `source-before.bundle`(已 verify)。+- **与 Codex 互不干扰**:+ - 抓屏、GUI 和 GPU 计时脚本启动前,都会检查有没有其他 Veyra 进程。Codex 运行 `veyra_capture_cadence_fg_tests`、`veyra_live_presentation_tests`、`veyra_qml_ui` 期间,脚本拒绝启动并等待。+ - 构建时读取 Codex 的对象和着色器前先核对哈希;着色器用复制,不用硬链接。+- **不做**:不派子 Agent;不 merge、push、Release。++## 1. Codex 实现复审++- **接线正确**,未发现功能缺陷:+ - 资源、描述符、状态转换和屏障;+ - NVOF 输入角色:`nvofInA_` 为上一帧,`nvofInB_` 为当前帧;+ - 首帧和 reset 时送零运动;+ - NR/SR 仍用校验后的光流;+ - 新增工作计入光流阶段的计时。+- **效果有限,原因在算法而不在接线**(见第 3 节)。++## 2. “默认光流 1080p”是不是原因:不是++- **产品默认**:4K 源在实时 NR 策略下,光流尺寸等于 NR 尺寸 1920×1080(`ResolutionPlan`)。每个 NVOF 向量覆盖 4K 画面的 8×8 像素块。+- **证据 1,运动误差**(下文“无窗口运动质量测试”,侧跑 80 px/帧,半分辨率 → 全分辨率,即 1440p 测试里的 1080p 等价 → 4K 等价):+ - 修复前光流:总 EPE 4.69 → 4.47;+ - Codex 版:3.09 → 3.06;+ - 本版在全分辨率下反而变差:背景横移露出区 7.6 → 16.7,因为填补的搜索半径按光流像素计。+- **证据 2,XeSS 实测**(J0):修复前光流改用全分辨率,轮廓带误差 8.2148 → 8.1977,基本没变。+- **代价**:NVOF 1080p 约 0.84 ms,4K 约 2.97 ms(09-08 实测);而且会改变 NR 使用的光流输入。+- **结论**:不建议改默认光流分辨率。++## 3. 剩余误差在哪里++新增无窗口测试 `veyra_xess_motion_quality_tests`:+- 场景与 `veyra_fg_xess_boundary_tests` 相同;+- 经产品 `EnhanceGraph` 读回送给 XeSS 的运动矢量,按区域与场景真值比较 EPE;+- 无窗口、无抓屏,可以和 Codex 的工作并行。++侧跑 80 px/帧,1280×720 光流(单位:像素 EPE;括号内为误差 >4 px 的比例):++| 区域 | 修复前 | Codex 版 |+| --- | ---: | ---: |+| 轮廓附近背景 | 6.42 | 3.09 |+| 人物刚移开、新露出的背景 | 73.7(99%) | 38.5(63%) |+| 人物自身轮廓带 | 12.6 | 12.2 |+| 远处背景 | 0.04 | 0.02 |++**问题 1:新露出的背景。** FlowFill 只在“最佳候选的颜色代价 > 0.06”时触发。在平滑背景上,错误的“人物向量”代价并不高:+- 这些像素本身不触发填补;+- 它们还被当成“可信像素”,把错误向量扩散给旁边颜色相近的像素。++**问题 2:快速摆动的四肢。** 所有版本的四肢 EPE 都在 20–50 px,NVOF 本身跟不上旋转加条纹纹理。++**XeSS 对各区域的敏感度**(侧跑 80,实际插值帧,轮廓带 MAE):++| 送给 XeSS 的运动 | 轮廓带 MAE | 相对理想向量 |+| --- | ---: | ---: |+| 理想向量 | 6.0076 | — |+| 理想向量,露出区置零 | 7.5111 | +1.50 |+| 理想向量,四肢置零 | 7.2748 | +1.27 |++## 4. 改进:NVOF 前后向一致性判定露出区++**做法**+- 仅在 XeSS + 运动来源“光流” + NVIDIA NVOF 时,让 NVOF 同时输出后向光流(`NV_OF_PRED_DIRECTION_BOTH`,现有 `NvOfSession` 已支持)。+- FlowRefine 的候选选择与 Codex 版完全相同(颜色代价)。选定后,查后向光流:当前像素按选定向量落到上一帧,再按那里的后向向量回到当前帧,偏离多少记为“前后向不一致量”。+- 新露出的背景没有任何向量能前后一致:+ - 真实向量落在当时挡住它的人物上;+ - 人物的向量落在已经移走的背景上。+- FlowFill 规则:+ - 不一致量 > 2 光流像素,或颜色代价 > 0.06:填补;+ - 只有不一致量 ≤ 0.5 且代价 ≤ 0.06 的像素可以提供向量(一致的背景、身体 P90 约 0.2);+ - 在同色、一致的邻近像素里取向量。++**影响范围**+- NR/SR 的光流逐字节不变(Codex 合同测试第 160 项检查);其他补帧、AMD 光流、GPU DIS、“自动”(零运动)都不变。+- 测试开关:`VEYRA_TEST_FLOW_CONSISTENCY=0` 恢复 Codex 版;`VEYRA_TEST_FLOW_REFINE=0` 恢复修复前光流。++**撤回或未采用的尝试**(同一 EXE,同场景 A/B)+- **一致性参与候选选择**:密集竖条 9.7037 → 9.9149,负收益。撤回,改为只用于判定填补。+- **填补额外要求代价下限**:只是把露出区误差和四肢误差互换。撤回。+- **触发阈值 4 或 8 px**:与 2 px 无差异,保留 2。+- **来源阈值 2 或 0.25**:与 0.5 基本一致,保留 0.5。++## 5. 结果++### 运动误差(无窗口,1280×720 光流,像素 EPE)++| 场景 | 总 EPE:Codex → 本版 | 露出区:Codex → 本版 | 轮廓附近背景:Codex → 本版 | 人物轮廓带:Codex → 本版 |+| --- | --- | --- | --- | --- |+| 侧跑 27 | 1.92 → 1.87 | 27.8 → 3.1 | 2.13 → 0.87 | 9.43 → 14.10 |+| 侧跑 80 | 3.09 → 2.07 | 38.5 → 6.6 | 3.09 → 1.87 | 12.20 → 14.65 |+| 背景横移 80 | 1.60 → 0.35 | 41.9 → 7.5 | 2.34 → 2.51 | 0.09 → 0.08 |+| 密集竖条 27 | 1.35 → 0.79 | 27.7 → 7.1 | 6.92 → 5.46 | 0.03 → 0.04 |++### XeSS 实际插值帧(SDK 只显示插值帧,桌面复制抓屏,11 帧轮廓带 MAE8)++条件:RTX 5070,2560×1440,XeSS 2X,NR/SR 关。Codex 版的数字在本构建里逐位复现。++| 场景 | 修复前 | Codex 版 | 本版 | 理想向量 | 本版 vs Codex |+| --- | ---: | ---: | ---: | ---: | ---: |+| 侧跑 27 | 6.8755 | 6.3781 | 6.4016 | 5.4667 | +0.37% |+| 侧跑 80 | 8.2148 | 7.4180 | 7.3042 | 6.0076 | −1.53% |+| 背景横移 80 | 3.7651 | 3.0332 | **2.5901** | 2.0984 | **−14.61%** |+| 密集竖条 27 | 10.1397 | 9.7037 | 9.6196 | 4.8518 | −0.87% |++误差 >32 级的像素比例:+- 背景横移 80 由 2.72% 降到 2.51%;+- 密集竖条 27 由 8.73% 降到 8.71%;+- 侧跑 27 由 7.96% 升到 8.88%,侧跑 80 由 9.01% 升到 9.63%。++**解读**+- **人物轮廓 + 高速横移背景**(镜头跟随人物、人物在画面中基本不动):本版明显改善,与理想向量的剩余差距缩小 47%。人物内部误差也从 Codex 版的 0.0483 回到 0.0002。+- **侧跑场景**:剩余误差几乎全部来自高速摆动的四肢。本版 7.30,约等于“理想向量 + 四肢置零”的 7.27。四肢上前后向不一致的像素被填补时,可能借到另一肢体或背景的向量,所以坏像素比例略增。+- **密集竖条**:理想向量 4.85,两版光流约 9.6–9.7。按用户判断,这属于光流混叠和 XeSS 模型问题,本轮不处理。++### 性能(RTX 5070)++**无窗口 4K**(4K 源,NVOF 1920×1080,XeSS,无 NR,152 帧中位数):++| 版本 | 光流阶段 | 整图 |+| --- | ---: | ---: |+| 修复前 | 1.02 ms | 1.31 ms |+| Codex 版 | 1.52 ms | 1.81 ms |+| 本版 | 2.27 ms | 2.57 ms |++**真实 GUI**(GTA VI 原生 4K30,原版 NR 一层 1080p,NVOF 1080p,XeSS 2X,普通 GPU 优先级,同一批源帧 300–840,共 541 帧):+- 光流阶段:Codex 版 1.53 ms → 本版 2.26 ms(+0.72 ms);+- 整图:9.52 → 9.19 ms。这一对的差在两次运行的波动范围内,不声称提速;+- 提交帧率:都是 60。++**增量来源**:主要是 NVOF 在光流专用硬件上多算一次后向光流,与 09-08 实测的 +0.67 ms 一致。显存增加两张网格尺寸纹理(1080p 光流时约 0.6 MB)。++## 6. 回归++- **Codex 合同测试** `veyra_xess_motion_contract_tests`:160 项检查,0 失败,D3D12 调试层 0 错误。覆盖首帧/reset/自动模式送零运动、NR/SR 光流逐字节不变、重建与释放。+- **GUI 生命周期**(Codex 的 ProbeXess 原样复制,52.6 s 通过):+ - 覆盖:起播、seek、暂停与恢复、2X→4X、零运动、AMD 光流 ⇄ NVIDIA 光流、补帧关与开;+ - 日志显示三种运动路径都出现(前后向、校验光流、零),NVOF 只在 XeSS + 光流分支用双向。+- **抓屏**:四场景各 11/11 帧,采集与 D3D12 错误均为 0。++## 7. 本地测试版++位置:`E:/项目/Veyra/tests/claude-xess-tune-20261012/delivery`。+- 同一个 EXE、同一份设置(XeSS 2X、运动来源光流、NVIDIA 光流、原版 NR 1080p),三个入口:+ - `Start-XeSS-New.cmd`:本版;+ - `Start-XeSS-Codex.cmd`:Codex 版;+ - `Start-XeSS-Original.cmd`:修复前。+- 日志:`logs/claude-xess-tune-20261012/manual/`。+- 程序 SHA256、着色器哈希、全部数字及来源文件见 `reports/claude-xess-tune-20261012/results.json`。++## 8. 限制++- 合成场景的改善不等于真实游戏的观感比例,以用户实机为准。+- **四肢**:需要更强的光流,例如能处理旋转或周期纹理,本轮未做。+- **栏杆**:属于光流混叠和 XeSS 模型问题,按用户要求不处理。+- 本机只有 RTX 5070。AMD、Intel 显卡、长期显存、屏幕端到端延迟都未验证。diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex d2e4ce0f..41416050 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -611,6 +611,8 @@ public:// Isolated diagnostics only: existing constant guidance, borrowed lifetime.// A caller writing before the first real frame must restore COMMON state.ID3D12Resource* diagnosticDepthResource(bool frameGeneration) const { return frameGeneration?depthTex_.Get():nrZeroDepth_.Get(); }+ // Test-only: FlowRefine output (flow extent RGBA16F: vector, cost, forward-backward disagreement).+ ID3D12Resource* diagnosticRefinedFlow() const { return fgFlowRefined_.Get(); }uint32_t nvofRawWidth() const { return rawW_; }uint32_t nvofRawHeight() const { return rawH_; }@@ -707,6 +709,11 @@ private:// the validated baseFlow_. VEYRA_TEST_FLOW_REFINE=0 restores the previous input.bool flowRefine_=false;ComPtr<ID3D12Resource> fgFlowRefined_,fgFlowFilled_,fgBaseFlow_;+ // NVOF backward output (previous->current) for the refinement's forward-backward check+ // (uncovered background). Only with flowRefine_; VEYRA_TEST_FLOW_CONSISTENCY=0 leaves+ // NVOF forward-only (photometric refinement). NR/SR never read it.+ bool flowConsistency_=false;+ ComPtr<ID3D12Resource> nvofReverseTex_,nvofReverseCostTex_;uint64_t motionPreviousSource_[2]={},previousSource_=0;ComPtr<ID3D12Resource> proxyTex_;ComPtr<ID3D12Resource> neuralTex_;diff --git a/shaders/FlowFill.hlsl b/shaders/FlowFill.hlslindex 760115ec..1f7eb244 100644--- a/shaders/FlowFill.hlsl+++ b/shaders/FlowFill.hlsl@@ -4,7 +4,11 @@// interpolator drag that background with the object (the "jelly" around characters).// Take the vector of the most similar-coloured confident pixel nearby instead; uncovered// background resembles the background beside it, which moves with the background.-Texture2D<float4> refined : register(t0); // xy vector, z best cost (FlowRefine)+// With backward flow a pixel whose best candidate fails the forward-backward check has no+// correspondence either. Only pixels that pass it clearly lend their vector: next to an+// object NVOF's backward vectors lean towards the object too, so a few uncovered pixels+// pass narrowly and must not spread the object's vector over the background beside them.+Texture2D<float4> refined : register(t0); // xy vector, z cost, w disagreement (FlowRefine)Texture2D<float4> currentColor : register(t1); // flow extentRWTexture2D<float2> output : register(u0); // flow extent, current->previous pixels@@ -14,8 +18,8 @@ cbuffer FlowFillConstants : register(b0)uint flowH;float threshold; // best cost above this has no correspondencefloat distanceWeight; // colour distance added per pixel of search distance- uint unused0;- uint unused1;+ float consistencyThreshold; // disagreement above this (flow pixels) has none; 0 = unused+ float sourceThreshold; // disagreement up to this lends its vectoruint unused2;uint unused3;};@@ -23,13 +27,16 @@ cbuffer FlowFillConstants : register(b0)static const int2 kDirections[8] = { int2(1, 0), int2(-1, 0), int2(0, 1), int2(0, -1), int2(1, 1), int2(-1, 1), int2(1, -1), int2(-1, -1) };static const int kRadii[9] = { 2, 4, 8, 12, 16, 24, 32, 48, 64 };+bool confident(float4 r) { return r.z <= threshold && (consistencyThreshold <= 0 || r.w <= sourceThreshold); }+bool filled(float4 r) { return r.z > threshold || (consistencyThreshold > 0 && r.w > consistencyThreshold); }+[numthreads(16, 16, 1)]void main(uint3 id : SV_DispatchThreadID){if (id.x >= flowW || id.y >= flowH) return;const int2 p = int2(id.xy);const float4 own = refined[p];- if (own.z <= threshold) { output[p] = own.xy; return; }+ if (!filled(own)) { output[p] = own.xy; return; }const float3 colour = currentColor[p].rgb;float bestScore = 1e9;float2 vector = own.xy;@@ -38,7 +45,7 @@ void main(uint3 id : SV_DispatchThreadID)const int2 q = p + kDirections[d] * kRadii[r];if (any(q < 0) || q.x >= int(flowW) || q.y >= int(flowH)) continue;const float4 candidate = refined[q];- if (candidate.z > threshold) continue;+ if (!confident(candidate)) continue;const float3 delta = currentColor[q].rgb - colour;const float score = dot(abs(delta), float3(1, 1, 1)) + distanceWeight * kRadii[r];if (score < bestScore) { bestScore = score; vector = candidate.xy; }diff --git a/shaders/FlowRefine.hlsl b/shaders/FlowRefine.hlslindex aa3bd84a..b8c66ca0 100644--- a/shaders/FlowRefine.hlsl+++ b/shaders/FlowRefine.hlsl@@ -5,10 +5,17 @@// frame best: motion boundaries follow the picture instead of the grid. Unlike// NvofDensify nothing is zeroed; the best cost is kept for FlowFill to find pixels that// have no correspondence at all (background uncovered by a moving object).+// With NVOF's backward output (previous->current) the chosen vector is also checked for+// forward-backward agreement: the previous-frame point it lands on must flow back to this+// pixel. Uncovered background has no vector that does - its true vector lands on the object+// that covered it, the object's vector on background that moved on - even where a wrong+// vector matches the smooth background beside it photometrically. The choice itself stays+// photometric: on rotating limbs and repetitive texture the check is too noisy to rank by.Texture2D<int2> rawFlow : register(t0); // grid extent, S10.5 flow pixelsTexture2D<float4> previousColor : register(t1); // flow extentTexture2D<float4> currentColor : register(t2); // flow extent-RWTexture2D<float4> refined : register(u0); // xy vector, z best cost, w own-cell cost+Texture2D<int2> reverseFlow : register(t3); // grid extent, S10.5, previous->current+RWTexture2D<float4> refined : register(u0); // xy vector, z best cost, w forward-backward disagreementcbuffer FlowRefineConstants : register(b0){@@ -18,8 +25,8 @@ cbuffer FlowRefineConstants : register(b0)uint flowH;uint gridSize;float tieBias; // added to every neighbour cell's cost: the own cell wins ties+ uint backward; // 1: reverseFlow holds NVOF's backward output (else w = 0)uint unused0;- uint unused1;};float luma(float3 c) { return dot(c, float3(.2126, .7152, .0722)); }@@ -35,7 +42,7 @@ void main(uint3 id : SV_DispatchThreadID)current[j] = luma(currentColor[clamp(p + int2(j % 3 - 1, j / 3 - 1), int2(0, 0), limit)].rgb);const int2 cell = p / int(gridSize);const int2 cellLimit = int2(gridW - 1, gridH - 1);- float bestCost = 1e9, ownCost = 0;+ float bestCost = 1e9;float2 best = 0;[unroll] for (int k = 0; k < 9; ++k) {const int2 offset = int2(k % 3 - 1, k / 3 - 1);@@ -45,8 +52,13 @@ void main(uint3 id : SV_DispatchThreadID)[unroll] for (int j = 0; j < 9; ++j)cost += abs(current[j] - luma(previousColor[clamp(q + int2(j % 3 - 1, j / 3 - 1), int2(0, 0), limit)].rgb));cost /= 9;- if (k == 4) ownCost = cost; else cost += tieBias;+ if (k != 4) cost += tieBias;if (cost < bestCost) { bestCost = cost; best = v; }}- refined[p] = float4(best, bestCost, ownCost);+ float disagreement = 0;+ if (backward) {+ const int2 back = clamp(int2(floor((float2(p) + .5 + best) / float(gridSize))), int2(0, 0), cellLimit);+ disagreement = length(best + float2(reverseFlow[back]) / 32.0);+ }+ refined[p] = float4(best, bestCost, disagreement);}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex f0df74b8..2484ec90 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -459,6 +459,8 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)const bool refineDisabled=GetEnvironmentVariableW(L"VEYRA_TEST_FLOW_REFINE",refine,4)&&refine[0]==L'0';flowRefine_=presentSinkFg()&&desc_.fgUsesFlow()&&desc_.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia&&!refineDisabled;+ wchar_t consistency[4]{};+ flowConsistency_=flowRefine_&&!(GetEnvironmentVariableW(L"VEYRA_TEST_FLOW_CONSISTENCY",consistency,4)&&consistency[0]==L'0');uint64_t budget=0,usage=0;// Every NR layer allocates its own full set of textures, and a stabilised// layer adds two history/guide pairs on top. The stack is bounded (16 nodes),@@ -485,7 +487,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)const uint64_t estimate=uint64_t(workW_)*workH_*(76u+4u*generatedTextures)+vfgSharedBytes+nrTextureBytes+fullLayerBytes+uint64_t(srcW_)*srcH_*(32u+(desc_.protectionBeforeSr()?8u:0u))+temporalBytes+tailColorBytes+interProtectionBytes- +(flowRefine_?uint64_t(nvofW_)*nvofH_*12u+uint64_t(workW_)*workH_*4u:0);+ +(flowRefine_?uint64_t(nvofW_)*nvofH_*(flowConsistency_?13u:12u)+uint64_t(workW_)*workH_*4u:0);if(context_.videoMemoryInfo(budget,usage)){veyra::log::info("memory",std::format("graph lower-bound={}MiB budget={}MiB usage={}MiB; SDK allocations additional",estimate>>20,budget>>20,usage>>20));if(usage>=budget||estimate>budget-usage){veyra::log::error("memory","insufficient adapter budget for requested graph textures");return false;}@@ -615,7 +617,7 @@ bool EnhanceGraph::createResources()fgBaseFlow_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,true);if(!fgFlowRefined_||!fgFlowFilled_||!fgBaseFlow_)return false;}- if(presentSinkFg())veyra::log::info("graph",std::format("present-sink FG motion: {}",!desc_.fgUsesFlow()?"zero":flowRefine_?"refined NVOF (FlowRefine+FlowFill)":"validated flow"));+ if(presentSinkFg())veyra::log::info("graph",std::format("present-sink FG motion: {}",!desc_.fgUsesFlow()?"zero":flowConsistency_?"refined NVOF (FlowRefine+FlowFill, forward-backward)":flowRefine_?"refined NVOF (FlowRefine+FlowFill)":"validated flow"));// Colour grade tables (v4): only allocated when the stage is enabled.colorActive_=desc_.color.enabled&&!desc_.nodeColor(0);if(colorActive_){@@ -684,6 +686,11 @@ bool EnhanceGraph::createResources()rawH_ = (nvofH_ + nvofGrid_ - 1) / nvofGrid_;nvofRawTex_ = makeTexture(context_.device(), rawW_, rawH_, DXGI_FORMAT_R16G16_SINT, false);nvofCostTex_ = makeTexture(context_.device(), rawW_, rawH_, DXGI_FORMAT_R8_UINT, false);+ if(flowConsistency_){+ nvofReverseTex_=makeTexture(context_.device(),rawW_,rawH_,DXGI_FORMAT_R16G16_SINT,false);+ nvofReverseCostTex_=makeTexture(context_.device(),rawW_,rawH_,DXGI_FORMAT_R8_UINT,false);+ if(!nvofReverseTex_||!nvofReverseCostTex_)return false;+ }nvofInA_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_B8G8R8A8_UNORM, true);nvofInB_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_B8G8R8A8_UNORM, true);@@ -855,6 +862,7 @@ bool EnhanceGraph::initNvof()nd.gridSize = nvofGrid_;nd.quality=uint32_t(desc_.flowQuality);// s6 contract: B8G8R8A8 inputs, raw R16G16_SINT + R8_UINT cost at grid// extent, passed explicitly; allocation failure = fail closed.+ if(flowConsistency_){nd.reverseFlow=nvofReverseTex_.Get();nd.reverseCost=nvofReverseCostTex_.Get();}Status st = Status::Ok;if (!nvof_->initialize(context_.device(), nvofInA_.Get(), nvofInB_.Get(),nvofRawTex_.Get(), nvofCostTex_.Get(), nd, st)) {@@ -1533,7 +1541,7 @@ bool EnhanceGraph::createComputePasses()if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3+UINT(nrInstances_.size()),1,1))return false;if(flowRefine_){if(!fgFlowAdaptPass_.create(context_.device(),cs,2,1,1))return false;- if(!flowRefinePass_.loadShader("FlowRefine.dxil",cs)||!flowRefinePass_.create(context_.device(),cs,4,3,1))return false;+ if(!flowRefinePass_.loadShader("FlowRefine.dxil",cs)||!flowRefinePass_.create(context_.device(),cs,5,4,1))return false;if(!flowFillPass_.loadShader("FlowFill.dxil",cs)||!flowFillPass_.create(context_.device(),cs,3,2,1))return false;}// Stage-5 output stabiliser. Only allocated when the setting is non-zero:@@ -1733,13 +1741,15 @@ bool EnhanceGraph::createViews()for(size_t i=0;i<nrInstances_.size();++i)makeUav(context_.device(),nrInstances_[i]->motion(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,3+UINT(i)));if(flowRefine_){- // FlowRefine: 0 raw grid vectors, 1 previous, 2 current; 3 refined. FlowFill: 0 refined,+ // FlowRefine: 0 raw grid vectors, 1 previous, 2 current, 3 backward grid vectors (null+ // without flowConsistency_); 4 refined. FlowFill: 0 refined,// 1 current; 2 filled. Adapt: 0 filled; 1 work-extent XeSS motion.D3D12_SHADER_RESOURCE_VIEW_DESC raw{};raw.Format=DXGI_FORMAT_R16G16_SINT;raw.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2D;raw.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;raw.Texture2D.MipLevels=1;stager_.stageSrv(nvofRawTex_.Get(),&raw,flowRefinePass_.heap.Get(),0);stagedSrv(nvofInA_.Get(),DXGI_FORMAT_B8G8R8A8_UNORM,flowRefinePass_,1);stagedSrv(nvofInB_.Get(),DXGI_FORMAT_B8G8R8A8_UNORM,flowRefinePass_,2);- makeUav(context_.device(),fgFlowRefined_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(flowRefinePass_,3));+ stager_.stageSrv(nvofReverseTex_.Get(),&raw,flowRefinePass_.heap.Get(),3);+ makeUav(context_.device(),fgFlowRefined_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(flowRefinePass_,4));stagedSrv(fgFlowRefined_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,flowFillPass_,0);stagedSrv(nvofInB_.Get(),DXGI_FORMAT_B8G8R8A8_UNORM,flowFillPass_,1);makeUav(context_.device(),fgFlowFilled_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowFillPass_,2));stagedSrv(fgFlowFilled_.Get(),DXGI_FORMAT_R16G16_FLOAT,fgFlowAdaptPass_,0);@@ -2401,17 +2411,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(flowRefine_){// XeSS motion: per-pixel candidate choice, then disocclusion fill.tracker_.transition(list,fgFlowRefined_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- const float rc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(nvofW_),uintBits(nvofH_),uintBits(selectedGrid_),.004f,0,0};- flowRefinePass_.bind(list,rc,gpuHandleOf(flowRefinePass_,0).ptr,gpuHandleOf(flowRefinePass_,3).ptr);+ if(flowConsistency_)tracker_.transition(list,nvofReverseTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ const float rc[8]={uintBits(rawW_),uintBits(rawH_),uintBits(nvofW_),uintBits(nvofH_),uintBits(selectedGrid_),.004f,uintBits(flowConsistency_?1u:0u),0};+ flowRefinePass_.bind(list,rc,gpuHandleOf(flowRefinePass_,0).ptr,gpuHandleOf(flowRefinePass_,4).ptr);list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);tracker_.uavBarrier(list,fgFlowRefined_.Get());tracker_.transition(list,fgFlowRefined_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,fgFlowFilled_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- const float fc[8]={uintBits(nvofW_),uintBits(nvofH_),.06f,.002f,0,0,0,0};+ // A chosen vector off by more than 2 flow pixels forward-backward is filled, from+ // pixels within 0.5 (consistent background/body: ~0.2 at P90).+ const float fc[8]={uintBits(nvofW_),uintBits(nvofH_),.06f,.002f,flowConsistency_?2.f:0.f,flowConsistency_?.5f:0.f,0,0};flowFillPass_.bind(list,fc,gpuHandleOf(flowFillPass_,0).ptr,gpuHandleOf(flowFillPass_,2).ptr);list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);tracker_.uavBarrier(list,fgFlowFilled_.Get());tracker_.transition(list,fgFlowFilled_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ if(flowConsistency_)tracker_.transition(list,nvofReverseTex_.Get(),D3D12_RESOURCE_STATE_COMMON);}tracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_COMMON);@@ -3380,6 +3394,7 @@ void EnhanceGraph::shutdown()}nvofCostTex_.Reset();nvofRawTex_.Reset();+ nvofReverseCostTex_.Reset();nvofReverseTex_.Reset();nvofInB_.Reset();nvofInA_.Reset();if (nvof_) nvof_->shutdown();@@ -3441,7 +3456,7 @@ void EnhanceGraph::shutdown()nrInstances_.clear();for(auto& layer:nrAutoPool_)layer.reset();nrAutoLevel_=0;nrAutoPoolReady_=nrAutoResetPending_=false;residualRgba_.Reset();preSrProtectionRgba_.Reset();interNrProtectionRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();- fgFlowRefined_.Reset();fgFlowFilled_.Reset();fgBaseFlow_.Reset();flowRefinePass_={};flowFillPass_={};fgFlowAdaptPass_={};flowRefine_=false;+ fgFlowRefined_.Reset();fgFlowFilled_.Reset();fgBaseFlow_.Reset();flowRefinePass_={};flowFillPass_={};fgFlowAdaptPass_={};flowRefine_=flowConsistency_=false;for(unsigned i=0;i<kGeneratedPoolSlots;++i){if(fgDisableMapped_[i]&&fgDisableReadback_[i]){D3D12_RANGE written{0,0};fgDisableReadback_[i]->Unmap(0,&written);}fgDisableMapped_[i]=nullptr;fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();encPass_ = ComputePass{};blitPass_ = ComputePass{};hdrVideoSrPass_={};diff --git a/tests/integration/FgXessBoundaryTests.cpp b/tests/integration/FgXessBoundaryTests.cppindex 2180a481..47385ea7 100644--- a/tests/integration/FgXessBoundaryTests.cpp+++ b/tests/integration/FgXessBoundaryTests.cpp@@ -12,6 +12,8 @@// inverted - ideal with the opposite sign (motion-sign convention control)// idealdepth / productdepth - ideal or product motion plus a layered depth (character// near, front limbs nearest, background far) instead of the constant depth+// ideal-uncovered0 / ideal-limbs0 - ideal motion with zero in just-uncovered background or on+// the limbs: how much each region's motion matters to the interpolated result// bars adds dense vertical background rails for the accepted repeated-texture regression.// usage: veyra_fg_xess_boundary_tests <outDir> <run|orbit|bars> <speedPx> <variant> [tag]// Product-flow knobs for experiments (environment): VEYRA_TEST_FLOW_FULL=1 (flow at full@@ -191,7 +193,7 @@ int wmain(int argc,wchar_t** argv){SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);const std::filesystem::path dir=argv[1];const std::wstring sceneName=argv[2],variant=argv[4];const int speed=_wtoi(argv[3]);const bool run=sceneName==L"run",bars=sceneName==L"bars";if(!run&&!bars&&sceneName!=L"orbit")return 2;if(speed<1||speed>200)return 2;- const int mode=variant==L"zero"?0:variant==L"product"?1:variant==L"ideal"?2:variant==L"inverted"?3:variant==L"idealdepth"?4:variant==L"productdepth"?5:-1;if(mode<0)return 2;+ const int mode=variant==L"zero"?0:variant==L"product"?1:variant==L"ideal"?2:variant==L"inverted"?3:variant==L"idealdepth"?4:variant==L"productdepth"?5:variant==L"ideal-uncovered0"?6:variant==L"ideal-limbs0"?7:-1;if(mode<0)return 2;std::filesystem::create_directories(dir);CoInitializeEx(nullptr,COINIT_MULTITHREADED);const std::string label=std::format("xess-{}{}-{}{}",bars?"bars":run?"run":"orbit",speed,std::filesystem::path(variant).string(),argc==6?"-"+std::filesystem::path(argv[5]).string():std::string());SetEnvironmentVariableW(L"VEYRA_TEST_XESS_ONLY_INTERPOLATED",L"1");@@ -214,7 +216,7 @@ int wmain(int argc,wchar_t** argv){if(const auto q=knob(L"VEYRA_TEST_FLOW_QUALITY");!q.empty())gd.flowQuality=engine::FlowQuality(std::clamp(_wtoi(q.c_str()),0,2));if(knob(L"VEYRA_TEST_FLOW_VALIDATE")==L"0")gd.validateMotion=false;if(const auto b=knob(L"VEYRA_TEST_FLOW_BACKEND");b==L"dis")gd.opticalFlowBackend=engine::OpticalFlowBackend::GpuDis;else if(b==L"amd")gd.opticalFlowBackend=engine::OpticalFlowBackend::AmdFidelityFx;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();- ComPtr<ID3D12Resource> motion,upload,depthUpload;const bool probe=mode>=2&&mode<=4,layered=mode>=4;+ ComPtr<ID3D12Resource> motion,upload,depthUpload;const bool probe=(mode>=2&&mode<=4)||mode>=6,layered=mode==4||mode==5;if(layered&&!(depthUpload=pipeline::makeUploadBuffer(ctx.device(),uint64_t(W)*H*4)))return 2;if(probe){motion=pipeline::makeTexture(ctx.device(),W,H,DXGI_FORMAT_R16G16_FLOAT,false);upload=pipeline::makeUploadBuffer(ctx.device(),uint64_t(W)*H*4);@@ -277,13 +279,14 @@ int wmain(int argc,wchar_t** argv){AVFrame* f=av_frame_alloc();if(!f)return 2;f->width=W;f->height=H;f->format=AV_PIX_FMT_RGBA;f->color_range=AVCOL_RANGE_JPEG;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->colorspace=AVCOL_SPC_RGB;if(av_frame_get_buffer(f,32)<0)return 2;- std::vector<uint16_t> halves(size_t(W)*H*2);std::vector<int> tops(size_t(W)*H);+ std::vector<uint16_t> halves(size_t(W)*H*2);std::vector<int> tops(size_t(W)*H),previousTops(size_t(W)*H,-1);bool ok=true;const auto start=std::chrono::steady_clock::now();for(int k=0;k<N&&ok;++k){// 10 presents/s so every interpolated frame is captured; the provider still gets// 30 fps source timestamps (frameRenderTime), which is what its interpolation uses.std::this_thread::sleep_until(start+std::chrono::milliseconds(int64_t(k)*100));pump();ok=presenter.beginSourceInput();+ tops.swap(previousTops);parallelRows(H,[&](int y){auto* row=f->data[0]+size_t(y)*f->linesize[0];for(int x=0;x<W;++x){int top=-1;const auto p=scene.pixel(x,y,k,&top);tops[size_t(y)*W+x]=top;row[x*4]=p[0];row[x*4+1]=p[1];row[x*4+2]=p[2];row[x*4+3]=255;}});if(ok&&layered){// Depth of this frame (non-inverted: smaller is nearer) into the graph's FG depth texture.@@ -298,7 +301,10 @@ int wmain(int argc,wchar_t** argv){ok=ring.submitAndSignal(slot)&&ring.waitIdle();}if(ok&&probe){- parallelRows(H,[&](int y){for(int x=0;x<W;++x){auto v=k>0?scene.ideal(x,y,k,tops[size_t(y)*W+x]):std::array<float,2>{0,0};if(mode==3){v[0]=-v[0];v[1]=-v[1];}+ parallelRows(H,[&](int y){for(int x=0;x<W;++x){auto v=k>0?scene.ideal(x,y,k,tops[size_t(y)*W+x]):std::array<float,2>{0,0};if(mode==3){v[0]=-v[0];v[1]=-v[1];}const int top=tops[size_t(y)*W+x];+ if(mode==6&&k>0&&top<0&&previousTops[size_t(std::clamp(int(std::lround(y+v[1])),0,H-1))*W+std::clamp(int(std::lround(x+v[0])),0,W-1)]>=0)v={0,0};+ if(mode==7&&top>=0&&kParts[top].limb)v={0,0};+halves[(size_t(y)*W+x)*2]=DirectX::PackedVector::XMConvertFloatToHalf(v[0]);halves[(size_t(y)*W+x)*2+1]=DirectX::PackedVector::XMConvertFloatToHalf(v[1]);}});void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data))){ok=false;break;}std::memcpy(data,halves.data(),halves.size()*2);upload->Unmap(0,nullptr);diff --git a/tests/integration/XessMotionQualityTests.cpp b/tests/integration/XessMotionQualityTests.cppnew file mode 100644index 00000000..8bb5b3c7--- /dev/null+++ b/tests/integration/XessMotionQualityTests.cpp@@ -0,0 +1,319 @@+// Headless motion-quality check for the XeSS present path (2026-10-12, follow-up to+// FgXessBoundaryTests). The same deterministic scenes (side-running character over a+// panning background, the static-character orbit and the dense rails) run through the+// product EnhanceGraph with motion source "optical flow"; the motion the XeSS presenter+// would receive is read back and scored against the exact scene motion. There is no window,+// provider or screen capture, so it can run beside other work; what XeSS makes of the+// motion stays the job of FgXessBoundaryTests.+// Each run scores, on the same frames, the previous path (VEYRA_TEST_FLOW_REFINE=0), the+// photometric-only refinement (VEYRA_TEST_FLOW_CONSISTENCY=0) and the default refinement. Regions (current frame, crop X0..X0+CW as the capture test):+// bgBand background within Band px of a part edge, not uncovered+// uncovered background whose previous position was covered by the character+// fgBand character within Band px of a part edge+// far background beyond Band px+// usage: veyra_xess_motion_quality_tests <outDir> <run|orbit|bars> <speedPx> [tag]+// veyra_xess_motion_quality_tests <outDir> perf <frames> [tag]+// perf: product extents (3840x2160 source/work, 1920x1080 flow, the run scene upscaled), GPU+// time of the optical-flow stage (NVOF wait, densify, refinement, adaptation) and of the whole+// graph per path; median and P95 after 8 warm-up frames.+// Knobs (environment) as FgXessBoundaryTests: VEYRA_TEST_FLOW_FULL=1, VEYRA_TEST_FLOW_QUALITY,+// VEYRA_TEST_FLOW_VALIDATE=0, VEYRA_TEST_NVOF_GRID (read by EnhanceGraph).+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/pipeline/GpuPassUtils.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include "veyra/Log.h"+#include <DirectXPackedVector.h>+#include <d3d12sdklayers.h>+#include <algorithm>+#include <array>+#include <cmath>+#include <cstring>+#include <filesystem>+#include <format>+#include <iostream>+#include <numbers>+#include <string>+#include <thread>+#include <map>+#include <vector>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}+using namespace veyra;+using Microsoft::WRL::ComPtr;+namespace {+constexpr int W=2560,H=1440,FlowW=1280,FlowH=720,N=16,Warmup=2,Band=40,X0=480,CW=1600;++float hash01(int x,int y,uint32_t seed){+ uint32_t v=uint32_t(x)*0x9e3779b9u^uint32_t(y)*0x85ebca6bu^seed*0xc2b2ae35u;+ v^=v>>16;v*=0x7feb352du;v^=v>>15;v*=0x846ca68bu;v^=v>>16;return float(v&0xffffu)/65535.f;+}+float noise(float x,float y,float cell,uint32_t seed){+ const float gx=x/cell,gy=y/cell;const int ix=int(std::floor(gx)),iy=int(std::floor(gy));+ float tx=gx-ix,ty=gy-iy;tx=tx*tx*(3-2*tx);ty=ty*ty*(3-2*ty);+ const float a=hash01(ix,iy,seed),b=hash01(ix+1,iy,seed),c=hash01(ix,iy+1,seed),d=hash01(ix+1,iy+1,seed);+ return (a*(1-tx)+b*tx)*(1-ty)+(c*(1-tx)+d*tx)*ty;+}+template<class F> void parallelRows(int rows,F&& f){+ const int n=std::max(1u,std::thread::hardware_concurrency());std::vector<std::jthread> pool;+ for(int t=0;t<n;++t)pool.emplace_back([&,t]{for(int y=t;y<rows;y+=n)f(y);});+}+// Scene identical to FgXessBoundaryTests (parts back to front, limbs swing about a pivot).+struct Part{float px,py,len,r;int kind;float swing;bool limb;};+constexpr Part kParts[]={+ {1280,560,300,45,3,+.8f,true}, // back arm+ {1280,900,400,58,2,-1.f,true}, // back leg+ {1280,520,340,150,1,0,false}, // torso: capsule from (1280,520) downwards+ {1280,380,0,80,0,0,false}, // head+ {1280,900,400,58,2,+1.f,true}, // front leg+ {1280,560,300,45,3,-.8f,true}}; // front arm+constexpr std::array<std::array<float,3>,4> kBase{{{205,160,130},{48,66,118},{46,46,52},{52,70,124}}};+struct Scene {+ bool run=true;int speed=0;std::vector<std::array<uint8_t,3>> background;int bw=0;+ float angle(const Part& p,double t)const{+ if(!p.limb||!run)return 0;+ return float(p.swing*35.0*std::numbers::pi/180.0*std::sin(2*std::numbers::pi*t/8.0));+ }+ int bgOffset(double t)const{return int(std::lround(t*speed));}+ void local(const Part& p,double t,float x,float y,float& u,float& v)const{+ const float a=angle(p,t),dx=std::sin(a),dy=std::cos(a);const float rx=x-p.px,ry=y-p.py;+ u=rx*dx+ry*dy;v=rx*dy-ry*dx;+ }+ float sdf(const Part& p,double t,float x,float y)const{+ float u,v;local(p,t,x,y,u,v);+ if(u<0)return std::hypot(u,v)-p.r;if(u>p.len)return std::hypot(u-p.len,v)-p.r;return std::abs(v)-p.r;+ }+ std::array<float,3> partColor(const Part& p,double t,float x,float y,int index)const{+ float u,v;if(p.limb)local(p,t,x,y,u,v);else{u=y;v=x;}+ const float n=.7f+.6f*noise(u+300.f*index,v+500.f*index,7,21+index);+ const float stripe=(int(std::floor(u/18))&1)?16.f:0.f;+ const auto& c=kBase[size_t(p.kind)];+ return {c[0]*n+stripe,c[1]*n+stripe,c[2]*n+stripe};+ }+ std::array<uint8_t,3> pixel(int x,int y,double t,int* top=nullptr,float* edge=nullptr)const{+ const auto& b=background[size_t(y)*bw+x+bgOffset(t)];+ float c[3]={float(b[0]),float(b[1]),float(b[2])};int id=-1;float nearest=1e9f;+ for(int i=0;i<6;++i){+ const auto& p=kParts[i];const float d=sdf(p,t,x+.5f,y+.5f);nearest=std::min(nearest,std::abs(d));+ const float a=std::clamp(.5f-d,0.f,1.f);if(a<=0)continue;+ const auto pc=partColor(p,t,x+.5f,y+.5f,i);+ for(int k=0;k<3;++k)c[k]=c[k]*(1-a)+std::clamp(pc[k],0.f,255.f)*a;+ if(a>=.5f)id=i;+ }+ if(top)*top=id;if(edge)*edge=nearest;+ return {uint8_t(std::lround(c[0])),uint8_t(std::lround(c[1])),uint8_t(std::lround(c[2]))};+ }+ std::array<float,2> ideal(int x,int y,int frame,int top)const{+ if(top<0)return {float(speed),0.f};+ const auto& p=kParts[top];if(!p.limb||!run)return {0.f,0.f};+ float u,v;local(p,frame,x+.5f,y+.5f,u,v);+ const float a=angle(p,frame-1),dx=std::sin(a),dy=std::cos(a);+ const float px=p.px+u*dx+v*dy,py=p.py+u*dy-v*dx;+ return {px-(x+.5f),py-(y+.5f)};+ }+};+Scene makeScene(bool run,int speed,bool bars){+ Scene s;s.run=run;s.speed=speed;s.bw=W+(N+2)*speed;s.background.resize(size_t(s.bw)*H);+ parallelRows(H,[&](int y){+ for(int x=0;x<s.bw;++x){+ const float n=.5f*noise(float(x),float(y),80,1)+.3f*noise(float(x),float(y),20,2)+.2f*noise(float(x),float(y),5,3);+ const float t=float(y)/H;float r=110*(1-t)+86*t,g=138*(1-t)+112*t,b=168*(1-t)+70*t;+ const float m=.55f+.9f*n;r*=m;g*=m;b*=m;+ if(x%211<13){r*=.35f;g*=.32f;b*=.3f;}+ if((y/120)%3==1&&x%67<4){r=std::min(255.f,r+60);g=std::min(255.f,g+55);b=std::min(255.f,b+40);}+ if(bars&&y<H*3/4){const float rail=x%22<4?.18f:1.f;r=(150.f+20.f*n)*rail;g=(160.f+18.f*n)*rail;b=(170.f+16.f*n)*rail;}+ s.background[size_t(y)*s.bw+x]={uint8_t(std::clamp(r,0.f,255.f)),uint8_t(std::clamp(g,0.f,255.f)),uint8_t(std::clamp(b,0.f,255.f))};+ }+ });+ return s;+}+std::vector<uint8_t> readTexture(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,+ pipeline::EnhanceGraph& graph,ID3D12Resource* texture) {+ if(!texture)return {};+ const auto desc=texture->GetDesc();+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};UINT rows=0;UINT64 rowBytes=0,total=0;+ ctx.device()->GetCopyableFootprints(&desc,0,1,0,&footprint,&rows,&rowBytes,&total);+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;+ buffer.Width=total;buffer.Height=1;buffer.DepthOrArraySize=buffer.MipLevels=1;+ buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ ComPtr<ID3D12Resource> readback;+ if(FAILED(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,+ D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return {};+ Status status=Status::Ok;unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list)return {};+ const auto state=graph.diagnosticResourceState(texture);+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition={texture,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,state,D3D12_RESOURCE_STATE_COPY_SOURCE};+ if(state!=D3D12_RESOURCE_STATE_COPY_SOURCE)list->ResourceBarrier(1,&barrier);+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};+ dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=footprint;+ src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);+ if(state!=D3D12_RESOURCE_STATE_COPY_SOURCE){std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);}+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return {};+ void* data=nullptr;D3D12_RANGE range{0,SIZE_T(total)};if(FAILED(readback->Map(0,&range,&data)))return {};+ std::vector<uint8_t> result(size_t(rowBytes)*rows);+ for(UINT y=0;y<rows;++y)std::memcpy(result.data()+size_t(y)*rowBytes,+ static_cast<uint8_t*>(data)+footprint.Offset+size_t(y)*footprint.Footprint.RowPitch,size_t(rowBytes));+ D3D12_RANGE written{0,0};readback->Unmap(0,&written);return result;+}+struct Region {+ double sum=0;uint64_t n=0,over1=0,over4=0;+ void add(float e){sum+=e;++n;over1+=e>1;over4+=e>4;}+ std::string json()const{return std::format("{{\"epe\":{:.4f},\"over1Pct\":{:.3f},\"over4Pct\":{:.3f},\"pixels\":{}}}",n?sum/n:-1.0,n?100.0*over1/n:-1.0,n?100.0*over4/n:-1.0,n);}+};+// Crop images for inspection: EPE x16 (white = 16 px wrong) and motion (128 + 2 px per level).+bool save(const std::filesystem::path& path,int size,int cx,int cy,auto&& colour){+ sink::RgbaImage out;out.width=out.height=uint32_t(size);out.pixels.resize(size_t(size)*size*4);+ const int x0=std::clamp(cx-size/2,X0,X0+CW-size),y0=std::clamp(cy-size/2,0,H-size);+ for(int y=0;y<size;++y)for(int x=0;x<size;++x){const auto c=colour(x0+x,y0+y);auto* q=&out.pixels[(size_t(y)*size+x)*4];q[0]=c[0];q[1]=c[1];q[2]=c[2];q[3]=255;}+ std::error_code ec;std::filesystem::remove(path,ec);return sink::saveImage(path.wstring(),out);+}+uint8_t level(float v){return uint8_t(std::clamp(128.f+v*2.f,0.f,255.f));}+std::string percentiles(std::vector<double> v){+ if(v.empty())return "null";std::sort(v.begin(),v.end());+ return std::format("{{\"median\":{:.4f},\"p95\":{:.4f},\"samples\":{}}}",v[v.size()/2],v[std::min(v.size()-1,size_t(v.size()*.95))],v.size());+}+int perf(const std::filesystem::path& dir,int frames,const std::string& label){+ constexpr unsigned PW=3840,PH=2160;+ const Scene scene=makeScene(true,40,false);+ std::vector<std::vector<std::array<uint8_t,3>>> source(N);+ for(int k=0;k<N;++k){source[k].resize(size_t(W)*H);parallelRows(H,[&](int y){for(int x=0;x<W;++x)source[k][size_t(y)*W+x]=scene.pixel(x,y,k);});}+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st=Status::Ok;gfx::DeviceContextDesc dd;+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))return 2;+ AVFrame* f=av_frame_alloc();if(!f)return 2;+ f->width=PW;f->height=PH;f->format=AV_PIX_FMT_RGBA;f->color_range=AVCOL_RANGE_JPEG;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(f,32)<0)return 2;+ constexpr const char* kPaths[]={"previous","photometric","refined"};bool ok=true;+ for(int path=0;path<3&&ok;++path){+ SetEnvironmentVariableW(L"VEYRA_TEST_FLOW_REFINE",path?L"1":L"0");+ SetEnvironmentVariableW(L"VEYRA_TEST_FLOW_CONSISTENCY",path==1?L"0":nullptr);+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.workWidth=PW;gd.sourceHeight=gd.workHeight=PH;gd.flowWidth=PW/2;gd.flowHeight=PH/2;gd.rgbInput=true;+ gd.enableNr=false;gd.enableSr=false;gd.enableFg=true;gd.noNgx=true;gd.fgMultiplier=2;+ gd.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;gd.fgMotion=engine::MotionSource::OpticalFlow;+ gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ if(!graph.initialize(gd)||!graph.createViews()){std::cerr<<"graph open failed"<<std::endl;ok=false;break;}+ graph.recordGpuTimings();std::vector<double> flow,span;+ for(int k=0;k<frames&&ok;++k){+ const auto& s=source[size_t(k%N)];+ parallelRows(int(PH),[&](int y){auto* row=f->data[0]+size_t(y)*f->linesize[0];const int sy=y*H/int(PH);for(int x=0;x<int(PW);++x){const auto& c=s[size_t(sy)*W+x*W/int(PW)];row[x*4]=c[0];row[x*4+1]=c[1];row[x*4+2]=c[2];row[x*4+3]=255;}});+ pipeline::EnhanceGraph::FrameOutputs out;+ ok=graph.process(f,k*(1000.0/30),k==0,out,uint64_t(k+1))&&ring.waitIdle();+ for(const auto& timing:graph.takeGpuTimings()){+ if(timing.identity.sourceFrameId<=8)continue;+ if(const auto& v=timing.gpu[size_t(diagnostics::GpuStage::Flow)];v.milliseconds)flow.push_back(*v.milliseconds);+ if(const auto whole=diagnostics::graphExecutionSpanMs(timing))span.push_back(*whole);+ }+ }+ std::cout<<std::format("XESS_MOTION_PERF {{\"label\":\"{}\",\"path\":\"{}\",\"flow\":\"{}x{}\",\"nvof\":{},\"flowStageMs\":{},\"graphMs\":{}}}",+ label,kPaths[path],graph.flowWidth(),graph.flowHeight(),graph.metrics().nvofExecuteCount,percentiles(flow),percentiles(span))<<std::endl;+ ok=ring.drainQueue()&&ok;graph.shutdown();+ }+ av_frame_free(&f);ring.shutdown();ctx.shutdown();+ return ok?0:1;+}+} // namespace++int wmain(int argc,wchar_t** argv){+ if(argc!=4&&argc!=5)return 2;+ const std::filesystem::path dir=argv[1];const std::wstring sceneName=argv[2];const int speed=_wtoi(argv[3]);+ if(sceneName==L"perf"){std::filesystem::create_directories(dir);const std::string label=std::format("perf{}",argc==5?"-"+std::filesystem::path(argv[4]).string():std::string());+ Logger::instance().openFile((dir/(label+".log")).wstring());return speed>=16&&speed<=600?perf(dir,speed,label):2;}+ const bool run=sceneName==L"run",bars=sceneName==L"bars";if(!run&&!bars&&sceneName!=L"orbit")return 2;if(speed<1||speed>200)return 2;+ std::filesystem::create_directories(dir);CoInitializeEx(nullptr,COINIT_MULTITHREADED); // WIC image export+ const std::string label=std::format("motion-{}{}{}",bars?"bars":run?"run":"orbit",speed,argc==5?"-"+std::filesystem::path(argv[4]).string():std::string());+ Logger::instance().openFile((dir/(label+".log")).wstring());+ const Scene scene=makeScene(run,speed,bars);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))return 2;+ auto knob=[](const wchar_t* name)->std::wstring{wchar_t v[16]{};return GetEnvironmentVariableW(name,v,16)?std::wstring(v):std::wstring();};+ AVFrame* f=av_frame_alloc();if(!f)return 2;+ f->width=W;f->height=H;f->format=AV_PIX_FMT_RGBA;f->color_range=AVCOL_RANGE_JPEG;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(f,32)<0)return 2;+ std::vector<int> tops(size_t(W)*H),previousTops(size_t(W)*H);std::vector<float> edges(size_t(W)*H);+ const int scoreH=bars?H*3/4:H,shown=N-2;bool ok=true;unsigned scored=0;+ std::vector<float> shownError[3];+ constexpr const char* kPaths[]={"previous","photometric","refined"};+ for(int path=0;path<3;++path){+ const bool refine=path>0;+ SetEnvironmentVariableW(L"VEYRA_TEST_FLOW_REFINE",refine?L"1":L"0");+ SetEnvironmentVariableW(L"VEYRA_TEST_FLOW_CONSISTENCY",path==1?L"0":nullptr);+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.workWidth=W;gd.sourceHeight=gd.workHeight=H;gd.flowWidth=FlowW;gd.flowHeight=FlowH;gd.rgbInput=true;+ gd.enableNr=false;gd.enableSr=false;gd.enableFg=true;gd.noNgx=true;gd.fgMultiplier=2;+ gd.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;gd.fgMotion=engine::MotionSource::OpticalFlow;+ if(knob(L"VEYRA_TEST_FLOW_FULL")==L"1"){gd.flowWidth=W;gd.flowHeight=H;}+ if(const auto q=knob(L"VEYRA_TEST_FLOW_QUALITY");!q.empty())gd.flowQuality=engine::FlowQuality(std::clamp(_wtoi(q.c_str()),0,2));+ if(knob(L"VEYRA_TEST_FLOW_VALIDATE")==L"0")gd.validateMotion=false;+ gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ if(!graph.initialize(gd)||!graph.createViews()){std::cerr<<"graph open failed"<<std::endl;ok=false;break;}+ Region bgBand,uncovered,fgBand,outside,all,parts[6];std::vector<uint16_t> motion(size_t(W)*H*2);+ std::map<std::string,std::array<std::vector<float>,3>> samples;+ for(int k=0;k<N&&ok;++k){+ std::swap(tops,previousTops);+ parallelRows(H,[&](int y){auto* row=f->data[0]+size_t(y)*f->linesize[0];for(int x=0;x<W;++x){int top=-1;float edge=0;const auto p=scene.pixel(x,y,k,&top,&edge);tops[size_t(y)*W+x]=top;edges[size_t(y)*W+x]=edge;row[x*4]=p[0];row[x*4+1]=p[1];row[x*4+2]=p[2];row[x*4+3]=255;}});+ pipeline::EnhanceGraph::FrameOutputs out;+ ok=graph.process(f,k*(1000.0/30),k==0,out,uint64_t(k+1))&&ring.waitIdle();+ if(!ok||k<Warmup)continue;+ if(!graph.presentMotionValid(out.videoSlot)){std::cerr<<"motion not valid at frame "<<k<<std::endl;ok=false;break;}+ const auto bytes=readTexture(ctx,ring,graph,graph.presentMotion(out.videoSlot));+ if(bytes.size()!=motion.size()*2){ok=false;break;}+ std::memcpy(motion.data(),bytes.data(),bytes.size());+ auto at=[&](int x,int y){const size_t i=(size_t(y)*W+x)*2;return std::array<float,2>{DirectX::PackedVector::XMConvertHalfToFloat(motion[i]),DirectX::PackedVector::XMConvertHalfToFloat(motion[i+1])};};+ for(int y=0;y<scoreH;++y)for(int x=X0;x<X0+CW;++x){+ const size_t i=size_t(y)*W+x;const int top=tops[i];const auto v=scene.ideal(x,y,k,top);const auto m=at(x,y);+ const float e=std::hypot(m[0]-v[0],m[1]-v[1]);all.add(e);+ if(k==shown)shownError[path].push_back(e);+ if(top>=0){if(edges[i]<Band){fgBand.add(e);parts[top].add(e);}continue;}+ const int px=std::clamp(int(std::lround(x+v[0])),0,W-1),py=std::clamp(int(std::lround(y+v[1])),0,H-1);+ if(previousTops[size_t(py)*W+px]>=0)uncovered.add(e);else if(edges[i]<Band)bgBand.add(e);else outside.add(e);+ }+ if(const auto refinedBytes=readTexture(ctx,ring,graph,graph.diagnosticRefinedFlow());!refinedBytes.empty()){+ const unsigned fw=graph.flowWidth(),fh=unsigned(refinedBytes.size()/(size_t(fw)*8));const auto* r=reinterpret_cast<const uint16_t*>(refinedBytes.data());+ for(unsigned fy=0;fy<fh;fy+=2)for(unsigned fx=0;fx<fw;fx+=2){+ const int x=int((fx+.5)*W/fw),y=int((fy+.5)*H/fh);if(x<X0||x>=X0+CW||y>=scoreH)continue;+ const size_t i=size_t(y)*W+x;const int top=tops[i];const auto v=scene.ideal(x,y,k,top);std::string region;+ if(top>=0)region=edges[i]<Band?(kParts[top].limb?"limbBand":"bodyBand"):"inner";+ else{const int px=std::clamp(int(std::lround(x+v[0])),0,W-1),py=std::clamp(int(std::lround(y+v[1])),0,H-1);region=previousTops[size_t(py)*W+px]>=0?"uncovered":edges[i]<Band?"bgBand":"far";}+ auto half=[&](int c){return DirectX::PackedVector::XMConvertHalfToFloat(r[(size_t(fy)*fw+fx)*4+c]);};+ auto& s=samples[region];s[0].push_back(half(2));s[1].push_back(half(3));s[2].push_back(half(3)/std::max(1.f,std::hypot(half(0),half(1))));+ }+ }+ ++scored;+ if(k==shown){+ const std::string stem=label+"-"+kPaths[path];+ auto epe=[&](int x,int y){const auto v=scene.ideal(x,y,k,tops[size_t(y)*W+x]);const auto m=at(x,y);const auto e=uint8_t(std::min(255.f,16.f*std::hypot(m[0]-v[0],m[1]-v[1])));return std::array<uint8_t,3>{e,e,e};};+ auto vec=[&](int x,int y){const auto m=at(x,y);return std::array<uint8_t,3>{level(m[0]),level(m[1]),128};};+ ok=save(dir/(stem+"-legs-epe.png"),448,1280,1250,epe)&&save(dir/(stem+"-legs-motion.png"),448,1280,1250,vec)&&+ save(dir/(stem+"-arms-epe.png"),448,1280,650,epe)&&save(dir/(stem+"-arms-motion.png"),448,1280,650,vec);+ if(ok&&!refine){auto truth=[&](int x,int y){const auto v=scene.ideal(x,y,k,tops[size_t(y)*W+x]);return std::array<uint8_t,3>{level(v[0]),level(v[1]),128};};+ ok=save(dir/(label+"-ideal-legs-motion.png"),448,1280,1250,truth)&&save(dir/(label+"-ideal-arms-motion.png"),448,1280,650,truth);}+ }+ }+ const auto m=graph.metrics();+ std::cout<<std::format("XESS_MOTION_QUALITY {{\"label\":\"{}\",\"path\":\"{}\",\"flow\":\"{}x{}\",\"nvof\":{},\"all\":{},\"bgBand\":{},\"uncovered\":{},\"fgBand\":{},\"far\":{},\"parts\":[{},{},{},{},{},{}]}}",+ label,kPaths[path],graph.flowWidth(),gd.flowHeight?gd.flowHeight:H,m.nvofExecuteCount,all.json(),bgBand.json(),uncovered.json(),fgBand.json(),outside.json(),parts[0].json(),parts[1].json(),parts[2].json(),parts[3].json(),parts[4].json(),parts[5].json())<<std::endl;+ for(auto& [region,s]:samples){std::string text;+ for(auto& values:s){std::sort(values.begin(),values.end());auto q=[&](double f){return values.empty()?-1.f:values[size_t(f*(values.size()-1))];};text+=std::format("[{:.3f},{:.3f},{:.3f},{:.3f}]",q(.1),q(.5),q(.9),q(.97));}+ std::cout<<std::format("XESS_REFINE_STATS {} {} n={} cost/mismatch/relative p10,p50,p90,p97 {}",kPaths[path],region,s[0].size(),text)<<std::endl;}+ ok=ring.drainQueue()&&ok;graph.shutdown();+ }+ if(ok&&shownError[1].size()==size_t(scoreH)*CW&&shownError[2].size()==shownError[1].size()){+ auto delta=[&](int x,int y)->std::array<uint8_t,3>{if(y>=scoreH)return {0,0,0};const size_t i=size_t(y)*CW+(x-X0);const float d=shownError[2][i]-shownError[1][i];+ const auto m=uint8_t(std::min(255.f,4.f*std::abs(d)));return std::abs(d)<1?std::array<uint8_t,3>{40,40,40}:d>0?std::array<uint8_t,3>{m,0,0}:std::array<uint8_t,3>{0,m,0};};+ ok=save(dir/(label+"-delta-legs.png"),448,1280,1250,delta)&&save(dir/(label+"-delta-arms.png"),448,1280,650,delta);+ }+ unsigned errors=0;ComPtr<ID3D12InfoQueue> iq;+ if(SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&iq))))+ for(UINT64 i=0;i<iq->GetNumStoredMessages();++i){SIZE_T bytes=0;if(FAILED(iq->GetMessage(i,nullptr,&bytes)))continue;std::vector<uint8_t>b(bytes);auto* msg=reinterpret_cast<D3D12_MESSAGE*>(b.data());+ if(SUCCEEDED(iq->GetMessage(i,msg,&bytes))&&msg->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<msg->pDescription<<std::endl;}}+ const bool pass=ok&&!errors&&scored==3u*(N-Warmup);+ std::cout<<std::format("XESS_MOTION_QUALITY_DONE {{\"label\":\"{}\",\"scoredFrames\":{},\"errors\":{},\"pass\":{}}}",label,scored,errors,pass?"true":"false")<<std::endl;+ av_frame_free(&f);iq.Reset();ring.shutdown();ctx.shutdown();CoUninitialize();+ return pass?0:1;+}