Skip to content

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++

test(fg): XeSS motion-input experiment through the present path

Veyra Goal Agent7fe3ea652b24
diff --git a/AGENTS.md b/AGENTS.md
index 30e7d35f..148ea42a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# Veyra 项目 Agent 执行规则
-> **2026-10-12 补帧人物边缘果冻 J0(Claude)**:用户要求先排查果冻(延迟暂缓),按 reports/jelly-latency-20261012/方案选项.md 先做 J0 判定,只测 DLSS(XeSS 在送显端无法直接读回)。存档 `checkpoint/pre-claude-jelly-20261012`(main 76f41b3)与 E 盘 `archives/claude-jelly-20261012`;分支 `claude/jelly-20261012` 只新增诊断测试 `veyra_fg_motion_boundary_tests` 及文档,不改产品、默认设置、运行库/模型/驱动/用户配置;无 merge/push/Release。结论见 docs/JELLY_J0_2026-10-12.md。
+> **2026-10-12 补帧人物边缘果冻 J0(Claude)**:用户要求先排查果冻(延迟暂缓),按 reports/jelly-latency-20261012/方案选项.md 先做 J0 判定,先测 DLSS/FSR,随后按用户“主要是XESS”补测 XeSS(SDK 只显示插值帧加桌面复制抓屏)。存档 `checkpoint/pre-claude-jelly-20261012`(main 76f41b3)与 E 盘 `archives/claude-jelly-20261012`;分支 `claude/jelly-20261012` 新增诊断测试 `veyra_fg_motion_boundary_tests`、`veyra_fg_xess_boundary_tests` 及文档;产品代码只加默认不生效的测试开关(XeSS 只显示插值帧、fgMotionProbe 进 XeSS 链路、NVOF 网格),不改默认行为、运行库/模型/驱动/用户配置;无 merge/push/Release。结论见 docs/JELLY_J0_2026-10-12.md。
> **2026-10-11 当前修复已合入本地main**:Codex4557ab6(含e8300d9)与Claude1d4c33f经隔离整合、42依赖闭包/13EXE构建、完整CMake、16组回归、12真实GUI状态/6布局及SR+VFG组合持久化/重启通过;实测产品4904b73、记录tip adcf509通过功能merge d2e1396进入main,完整Git树相同。VFG默认中档、DLSS K、33ms统计/250ms状态及负优化撤回保持。59开工树中唯main按授权更新,其余58树/504脏文件、来源分支及原包1626文件保持;final.json见reports/merge-current-fixes-20261011。首次组合GUI夹具漏FG节点失败,修夹具后通过,原证据保留;没有新的性能A/B或全硬件/长期显存通过声明。无push/打包/Release/关机。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index fd273020..814d3d05 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -917,6 +917,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_fg_motion_boundary_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_compile_definitions(veyra_fg_motion_boundary_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(veyra_fg_motion_boundary_tests PRIVATE veyra_engine)
+ add_executable(veyra_fg_xess_boundary_tests tests/integration/FgXessBoundaryTests.cpp)
+ target_compile_features(veyra_fg_xess_boundary_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_fg_xess_boundary_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_compile_definitions(veyra_fg_xess_boundary_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_fg_xess_boundary_tests PRIVATE veyra_engine d3d11 dxgi)
# 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/JELLY_J0_2026-10-12.md b/docs/JELLY_J0_2026-10-12.md
index 31fef981..5ed70bd8 100644
--- a/docs/JELLY_J0_2026-10-12.md
+++ b/docs/JELLY_J0_2026-10-12.md
@@ -5,7 +5,12 @@
- 用户先拿到排查方案 `E:/项目/Veyra/reports/jelly-latency-20261012/方案选项.md`,回复:
- “1.光流来源 2.几倍都一样,一般都用NV12 或者yuy 3.延迟这块先放着吧,先搞果冻的问题,看看能不能想办法解决一下,推荐VFG不是解决办法,你先做J0判定吧”;
- 随后补充“测试xess即可,不要浪费时间”“那就测dlss”。
-- J0 只加诊断测试程序,不改产品代码、默认设置、运行库、模型、驱动或用户配置。
+ - 看完 DLSS/FSR 结果后说明“主要是XESS,并且这个问题会在人物侧向奔跑的时候更为严重和明显,或者画面高速运动的时候”,于是补测 XeSS(见下文“XeSS”一节)。
+- J0 只加诊断测试程序,不改默认行为、运行库、模型、驱动或用户配置。
+- 为了能测 XeSS,产品代码里加了三个只在测试时生效的开关,产品默认路径不变:
+ - `XessPresenter.cpp`:`VEYRA_TEST_XESS_ONLY_INTERPOLATED`,调用 SDK 调试功能“只显示插值帧”;
+ - `EnhanceGraph.cpp`:测试钩子 `fgMotionProbe` 也能送进 XeSS 送显链路(产品中该钩子恒为空);
+ - `EnhanceGraph.cpp`:`VEYRA_TEST_NVOF_GRID`,NVOF 网格可设为 1/2/4,默认仍为 4。
- 存档:
- 标签 `checkpoint/pre-claude-jelly-20261012`,指向 main 76f41b3;
- `archives/claude-jelly-20261012/` 下有 `source-before.bundle`(已 verify)和 `start.json`(61 个工作树、504 个脏文件)。
@@ -88,14 +93,67 @@
- NR 会改变画面,所以“与真值的误差”里包含正常的增强效果。
- 用产品光流时,轮廓带偏离原图更多,但静止人物内侧的逐帧抖动没有增加(3 组都在 0.5 级以下)。合成画面里没有复现出由 NR 引起的轮廓晃动。
+## XeSS(玩家主要使用)
+
+### 方法
+
+- 程序:`tests/integration/FgXessBoundaryTests.cpp` → `veyra_fg_xess_boundary_tests <输出目录> <run|orbit> <速度> <变体> [标签]`。
+- 链路:产品处理图加 VideoPresenter,XeSS 在送显端补帧,与产品同一路径。
+ - 2560×1440 全屏无边框窗口,与本机显示器相同,XeSS 缓冲 1:1;
+ - 光流 1280×720,与 4K 加实时 NR 时的比例相同;
+ - 补帧 2X,源时间戳按 30fps 给出;
+ - 每 100 ms 送一帧,保证每张插值帧都能被抓到。
+- 抓屏:DXGI 桌面复制。本机开着 Windows HDR,所以按 FP16 抓取,再用系统 SDR 白电平(4.75,即 380 nit)还原成 SDR 8 位。插值帧与真值的匹配误差为 2.1–2.9 级。
+- 场景 run(侧向奔跑):
+ - 镜头跟随,人物躯干和头在屏幕上静止;
+ - 四肢以 8 帧为周期摆动 ±35°;
+ - 背景每帧平移 27 px(中速,相当于 4K 下 40 px)或 80 px(高速,相当于 4K 下 120 px);
+ - 理想矢量包含四肢旋转。
+- 指标:每对原帧都把抓到的插值帧与真值比较。轮廓带指距任何部件边缘 40 px 以内,统计第 5–15 对,共 11 对。21 组全部有效。
+- 证据:`logs/claude-jelly-20261012/xess/`(`xess-results.json`、每组日志、裁切图、`sheet-run80-*.png`)。
+
+### 结果(轮廓带误差 / 明显出错像素比例)
+
+| 运动输入 | 中速 27 px/帧 | 高速 80 px/帧 |
+| --- | --- | --- |
+| 零(XeSS 在“自动”下的默认值) | 7.68 / 9.64% | 9.65 / 11.53% |
+| 产品光流(运动来源选“光流”) | 6.88 / 8.76% | 8.21 / 9.99% |
+| 产品光流,关闭逐像素清零校验 | 6.43 / 8.29% | 7.56 / 9.36% |
+| 理想矢量 | **5.47 / 6.30%** | **6.01 / 6.62%** |
+| 理想取反(方向对照) | 8.05 / 10.58% | 10.12 / 12.15% |
+| 理想矢量 + 分层深度 | 5.37 / 6.16% | 5.81 / 6.34% |
+| 产品光流 + 分层深度 | 6.75 / 8.33% | 8.08 / 9.57% |
+
+高速时,产品光流的其他现有参数:
+
+| 参数 | 轮廓带误差 / 明显出错像素 |
+| --- | --- |
+| 全分辨率光流 | 8.20 / 10.15% |
+| 质量档“质量” | 8.17 / 9.99% |
+| NVOF 网格 2 | 8.21 / 9.68% |
+| NVOF 网格 1 | 8.44 / 10.55% |
+| 网格 1 + 关闭校验 | 8.36 / 10.64% |
+| 全分辨率 + 网格 1 + 关闭校验 | 8.33 / 10.49% |
+| GPU DIS | 9.43 / 11.23% |
+
+对比图里能直接看到三种输入的差别:
+- **零矢量**:摆动的腿明显拖影、重影,腿附近的背景竖杆断开错位。这就是用户说的果冻。
+- **产品光流**:腿的边缘出现 8×8 方块锯齿,腿上的纹理对不齐。
+- **理想矢量**:只剩边缘一圈细误差。
+
## 判定
-1. DLSS 用户的果冻不是我们的光流造成的,也不能靠改光流来修:DLSS 补帧不读这些矢量。
-2. 吃矢量的补帧(以 FSR 代表)在干净的合成画面上,产品光流已经与理想矢量相当。方案 J1(光流精修)在 J0 里没有收益,**不建议实施**。
-3. 合成场景(刚体、无模糊、无压缩噪声、每帧 40 px)里,DLSS 和 FSR 的轮廓误差都只是一条窄边,**没能复现**用户看到的明显果冻。真正的诱因还在真实画面的特性里:位移更大、运动模糊、压缩噪声、人物肢体动画、背景视差,或者游戏自身的 TAA 拖影。这些需要真实素材才能确认。
-4. XeSS 没有测:它在送显端由提供方自行生成和显示,处理图读不回生成帧。SDK 3.0.2 有 `XEFG_SWAPCHAIN_DEBUG_FEATURE_SHOW_ONLY_INTERPOLATION`,可以配合抓屏单独实施。
+1. **DLSS**:不读我们的运动矢量,也基本不读深度。改光流修不了 DLSS 的果冻。
+2. **XeSS:画质直接取决于我们给的运动矢量。**
+ - 理想矢量比零矢量少 29%(中速)到 38%(高速)的轮廓误差;取反比零更差,说明方向约定正确。
+ - 默认“自动”给 XeSS 的是零矢量,是所有有效选项里最差的一档。
+ - 速度越快、零矢量与理想矢量的差距越大,与用户说的“侧向奔跑、高速运动时最明显”一致。
+3. 产品光流只拿到“零 → 理想”差距的 36–40%。关闭逐像素清零后合计约 55%。剩下的差距在运动边界上:方块化的矢量、错误的遮挡处理。
+4. NVOF 更细的网格、全分辨率光流、质量档都无效,GPU DIS 更差。**要缩小剩下的差距,需要新的逐像素矢量精修(方案 J1),调参数解决不了。**
+5. 正确的分层深度只带来 2–4%,不值得为此引入深度模型。
+6. FSR 同样依赖矢量。在干净的刚体场景里,产品光流已接近理想(DLSS/FSR 一节)。附带缺陷:只开 FSR 补帧时光流不会被创建。
## 边界
-- 只测了合成画面和本机 RTX 5070、DLSS 310.9.1、FSR 3.1.6。没有真实游戏画面,没有 XeSS,没有其他显卡。
+- 只测了合成画面和本机 RTX 5070、DLSS 310.9.1、FSR 3.1.6、XeSS 3.0.2(本机 2560×1440 HDR 桌面)。没有真实游戏画面,也没有其他显卡。XeSS 的结论来自抓屏,送帧节奏放慢到 10 fps,但时间戳仍按 30fps 给出。
- 首次重跑 dlss-*-zero 时裁切图文件已存在、保存失败,所以那两条记为 pass=false;指标与之后的有效重跑一致,后来已改为覆盖保存。FSR 首轮因为测试程序按错误状态上传矢量,触发了调试层报错,修正后整组重跑,报错为 0。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b268f79c..9ed5cc7c 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9156,3 +9156,4 @@ seal.py validate逐项核对源码/输入/EXE/QML/原包1626文件及旧树;
- 构建:py -3.11 -I E:/项目/Veyra/tmp/claude-jelly-20261012/build.py(产品源码逐个对照 Codex 合并构建回执,只编译新测试并用其链接文件链接,6–8 秒)。运行目录为私有副本 tests/claude-jelly-latency-20261012/app,D3D12 调试层开启。
- 结果(4K 合成场景,30fps 位移,FG 2X,光流 1080p):DLSS 补帧对零、产品光流、理想、取反、全屏 +120 px 的矢量结果相同(轮廓带误差 2.77/2.58),即不读矢量。FSR 依赖矢量:零 6.59/10.52(镜头转动时背景整体 16.26),产品光流 1.54/2.04,与理想 1.71/2.05 相当。开 NR 后轮廓带偏离原图更多(NR 光流 13.00 对 NR 零 10.77),但静止人物内侧抖动没有增加。判定:光流精修(J1)没有收益,不实施。附带发现 initNvof 只给 DLSS 补帧建光流,只开 FSR 补帧时“光流”实际为 0。
- 证据:logs/claude-jelly-20261012/j0/(j0-results.json、每组日志、裁切图/误差图/sheet)。详细结论与边界见 docs/JELLY_J0_2026-10-12.md。合成场景没有复现明显果冻,XeSS 未测;不 merge/push/Release。
+- XeSS 补测(用户:“主要是XESS……人物侧向奔跑……画面高速运动的时候”):新增 veyra_fg_xess_boundary_tests。2560×1440 全屏,产品图 + VideoPresenter 的 XeSS 送显链路,SDK 调试功能“只显示插值帧”,用 DXGI 桌面复制抓屏(HDR 桌面按 SDR 白电平 4.75 还原)。侧跑场景每帧 27/80 px:零矢量(XeSS“自动”默认)7.68/9.65,产品光流 6.88/8.21,关闭清零校验 6.43/7.56,理想 5.47/6.01,取反 8.05/10.12。加分层深度只改善 2–4%;NVOF 网格 1/2、全分辨率光流、质量档无效,GPU DIS 更差。判定:XeSS 依赖我们的矢量,默认零矢量最差,逐像素精修(J1)对 XeSS 有收益。产品代码只加测试开关(VEYRA_TEST_XESS_ONLY_INTERPOLATED、fgMotionProbe 送入 XeSS 链路、VEYRA_TEST_NVOF_GRID),默认路径不变。证据 logs/claude-jelly-20261012/xess/。
diff --git a/src/gfx/XessPresenter.cpp b/src/gfx/XessPresenter.cpp
index 0fd80294..d995b7fb 100644
--- a/src/gfx/XessPresenter.cpp
+++ b/src/gfx/XessPresenter.cpp
@@ -7,6 +7,7 @@
#include <atomic>
#ifdef VEYRA_HAS_XESS
#include <xess_fg/xefg_swapchain_d3d12.h>
+#include <xess_fg/xefg_swapchain_debug.h>
#include <xell/xell_d3d12.h>
#endif
@@ -192,6 +193,12 @@ bool XessPresenter::initialize(ID3D12Device* device,ID3D12CommandQueue* queue,ID
if(!p.check(p.xefgSwapChainD3D12InitFromSwapChainDescFn(p.fg,window,&desc,nullptr,queue,factory,&init),"Init",true))return false;
}
if(p.requestedGenerated>0&&!p.check(p.xefgSwapChainSetNumInterpolatedFramesFn(p.fg,p.requestedGenerated),"SetNumInterpolatedFrames",true))return false;
+ // Test-only (frame-generation quality experiments): present only interpolated
+ // frames so a screen capture can score them. The product never sets this.
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_ONLY_INTERPOLATED",nullptr,0)>0){
+ const auto enableDebug=reinterpret_cast<decltype(&xefgSwapChainEnableDebugFeature)>(GetProcAddress(p.fgDll,"xefgSwapChainEnableDebugFeature"));
+ if(!enableDebug||!p.check(enableDebug(p.fg,XEFG_SWAPCHAIN_DEBUG_FEATURE_SHOW_ONLY_INTERPOLATION,1,nullptr),"Debug show-only-interpolation (test)",true))return false;
+ }
return p.check(p.xefgSwapChainD3D12GetSwapChainPtrFn(p.fg,__uuidof(IDXGISwapChain3),reinterpret_cast<void**>(swapchain)),"GetSwapChain",true);
#else
(void)device;(void)queue;(void)factory;(void)window;(void)desc;(void)swapchain;(void)fgMultiplier;(void)lowLatencySleep;
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index b2d223d1..9bf1581a 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -664,6 +664,8 @@ bool EnhanceGraph::createResources()
}
nrZeroMotion_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16_FLOAT, false);
nrZeroDepth_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);
+ // Test-only grid override for flow-quality experiments (1/2/4 per the caps list).
+ nvofGrid_=4;if(wchar_t grid[4]{};GetEnvironmentVariableW(L"VEYRA_TEST_NVOF_GRID",grid,4)){const unsigned g=unsigned(_wtoi(grid));if(g==1||g==2||g==4)nvofGrid_=g;}
rawW_ = (nvofW_ + nvofGrid_ - 1) / nvofGrid_;
rawH_ = (nvofH_ + nvofGrid_ - 1) / nvofGrid_;
nvofRawTex_ = makeTexture(context_.device(), rawW_, rawH_, DXGI_FORMAT_R16G16_SINT, false);
@@ -832,7 +834,7 @@ bool EnhanceGraph::initNvof()
nd.width = nvofW_; nd.height = nvofH_;
nd.inFence = context_.fence();
nd.outFence = nvofOutFence_.Get();
- nd.gridSize = 4;nd.quality=uint32_t(desc_.flowQuality);
+ 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.
Status st = Status::Ok;
@@ -2819,7 +2821,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
if(presentSinkFg()){
- auto* input=desc_.fgUsesFlow()&&haveFlow&&!reset?baseFlow_.Get():nrZeroMotion_.Get();
+ // Test-only: fgMotionProbe (never set by the product) also feeds the XeSS
+ // present path, held in COMMON, same current->previous pixel convention.
+ auto* input=desc_.fgMotionProbe&&!reset?desc_.fgMotionProbe:desc_.fgUsesFlow()&&haveFlow&&!reset?baseFlow_.Get():nrZeroMotion_.Get();
tracker_.transition(list,input,D3D12_RESOURCE_STATE_COPY_SOURCE);
tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
list->CopyResource(presentMotion_[parity].Get(),input);
@@ -2827,7 +2831,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list,presentMotion_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
// Zero guidance still has valid source history. Marking it invalid
// would reset XeSS on every frame and suppress interpolation.
- presentMotionValid_[parity]=(desc_.fgUsesFlow()?haveFlow:prevValid_)&&!reset;
+ presentMotionValid_[parity]=(desc_.fgUsesFlow()&&!desc_.fgMotionProbe?haveFlow:prevValid_)&&!reset;
motionPreviousSource_[parity]=previousSource_;
}
previousSource_=sourceFrameId;
diff --git a/tests/integration/FgXessBoundaryTests.cpp b/tests/integration/FgXessBoundaryTests.cpp
new file mode 100644
index 00000000..68108d8c
--- /dev/null
+++ b/tests/integration/FgXessBoundaryTests.cpp
@@ -0,0 +1,358 @@
+// XeSS counterpart of FgMotionBoundaryTests (J0 for the "jelly" field report, 2026-10-12).
+// XeSS generates and presents its frames inside the provider swapchain, so this test drives
+// the product EnhanceGraph + VideoPresenter in a borderless full-screen window, asks the
+// provider to present only interpolated frames (VEYRA_TEST_XESS_ONLY_INTERPOLATED, test-only
+// switch in XessPresenter) and scores what reaches the screen through DXGI desktop duplication.
+// Scene: a side-running third-person character (static torso/head, swinging limbs) over a
+// background that pans D px per 30 fps source frame (the camera follows the character).
+// Motion inputs the provider receives:
+// zero - the product default for XeSS (motion source Automatic -> zero motion)
+// product - the product flow (motion source OpticalFlow), flow at half resolution
+// ideal - exact current->previous motion, limb rotation included (fgMotionProbe)
+// 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
+// usage: veyra_fg_xess_boundary_tests <outDir> <run|orbit> <speedPx> <variant> [tag]
+// Product-flow knobs for experiments (environment): VEYRA_TEST_FLOW_FULL=1 (flow at full
+// resolution), VEYRA_TEST_FLOW_QUALITY=0|1|2, VEYRA_TEST_FLOW_VALIDATE=0, VEYRA_TEST_FLOW_BACKEND=
+// dis|amd, VEYRA_TEST_NVOF_GRID=1|2|4 (read by EnhanceGraph).
+#include "veyra/engine/VideoPresenter.h"
+#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 <d3d11.h>
+#include <dxgi1_6.h>
+#include <d3d12sdklayers.h>
+#include <DirectXPackedVector.h>
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <cstring>
+#include <filesystem>
+#include <format>
+#include <iostream>
+#include <mutex>
+#include <numbers>
+#include <string>
+#include <thread>
+#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=4,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);});
+}
+// Parts in draw order (back to front). Limbs rotate about a pivot; angle 0 points down,
+// positive angles swing the far end towards +x. Static parts use world texture coordinates.
+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));}
+ // Local capsule coordinates of a world point for part i at time t.
+ 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};
+ }
+ // Composite colour, topmost part with >= 50% coverage (-1 background) and nearest part edge.
+ 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]))};
+ }
+ // Exact current(frame)->previous(frame-1) motion in pixels.
+ 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){
+ 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);}
+ 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;
+}
+struct Image{std::vector<std::array<uint8_t,3>> rgb;}; // CW x H crop at X0
+struct Accumulator {
+ double sum=0;uint64_t samples=0,bad=0;
+ void add(int r,int g,int b){sum+=r+g+b;samples+=3;bad+=std::max({r,g,b})>32;}
+ double mae()const{return samples?sum/samples:-1;}
+ double badPercent()const{return samples?100.0*bad/(samples/3):-1;}
+};
+bool save(const std::filesystem::path& path,const Image& im,int cx,int cy,int size,bool error=false,const Image* other=nullptr){
+ 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,0,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& p=im.rgb[size_t(y0+y)*CW+x0+x];auto* q=&out.pixels[(size_t(y)*size+x)*4];
+ if(error&&other){const auto& o=other->rgb[size_t(y0+y)*CW+x0+x];const int e=std::min(255,(std::abs(p[0]-o[0])+std::abs(p[1]-o[1])+std::abs(p[2]-o[2]))*4/3);q[0]=q[1]=q[2]=uint8_t(e);}
+ else{q[0]=p[0];q[1]=p[1];q[2]=p[2];}
+ q[3]=255;
+ }
+ std::error_code ec;std::filesystem::remove(path,ec);return sink::saveImage(path.wstring(),out);
+}
+LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){return DefWindowProcW(h,m,w,l);}
+// SDR content on an HDR (advanced colour) desktop is composed as scRGB with the user's SDR
+// white level (1000 = 80 nits = scRGB 1.0). Returns that scale for the monitor, 0 if unknown.
+float sdrWhiteScale(HMONITOR monitor){
+ MONITORINFOEXW info{};info.cbSize=sizeof(info);if(!GetMonitorInfoW(monitor,&info))return 0;
+ UINT32 paths=0,modes=0;if(GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS,&paths,&modes)!=ERROR_SUCCESS)return 0;
+ std::vector<DISPLAYCONFIG_PATH_INFO> path(paths);std::vector<DISPLAYCONFIG_MODE_INFO> mode(modes);
+ if(QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS,&paths,path.data(),&modes,mode.data(),nullptr)!=ERROR_SUCCESS)return 0;
+ for(UINT32 i=0;i<paths;++i){
+ DISPLAYCONFIG_SOURCE_DEVICE_NAME source{};source.header.type=DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;source.header.size=sizeof(source);
+ source.header.adapterId=path[i].sourceInfo.adapterId;source.header.id=path[i].sourceInfo.id;
+ if(DisplayConfigGetDeviceInfo(&source.header)!=ERROR_SUCCESS||std::wstring_view(source.viewGdiDeviceName)!=std::wstring_view(info.szDevice))continue;
+ DISPLAYCONFIG_SDR_WHITE_LEVEL white{};white.header.type=DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;white.header.size=sizeof(white);
+ white.header.adapterId=path[i].targetInfo.adapterId;white.header.id=path[i].targetInfo.id;
+ if(DisplayConfigGetDeviceInfo(&white.header)==ERROR_SUCCESS)return float(white.SDRWhiteLevel)/1000.f;
+ }
+ return 0;
+}
+uint8_t encodeSrgb(float linear){
+ const float c=std::clamp(linear,0.f,1.f);const float v=c<=.0031308f?12.92f*c:1.055f*std::pow(c,1/2.4f)-.055f;
+ return uint8_t(std::lround(std::clamp(v,0.f,1.f)*255));
+}
+} // namespace
+
+int wmain(int argc,wchar_t** argv){
+ if(argc!=5&&argc!=6)return 2;
+ 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";if(!run&&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;
+ std::filesystem::create_directories(dir);CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ const std::string label=std::format("xess-{}{}-{}{}",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");
+ const HMONITOR monitor=MonitorFromPoint({0,0},MONITOR_DEFAULTTOPRIMARY);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(monitor,&mi);
+ if(mi.rcMonitor.right-mi.rcMonitor.left!=W||mi.rcMonitor.bottom-mi.rcMonitor.top!=H){std::cerr<<"primary monitor must be 2560x1440"<<std::endl;return 2;}
+ WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraXessBoundary";wc.hCursor=nullptr;RegisterClassW(&wc);
+ HWND window=CreateWindowExW(WS_EX_TOPMOST,wc.lpszClassName,L"XeSS boundary test",WS_POPUP,mi.rcMonitor.left,mi.rcMonitor.top,W,H,nullptr,nullptr,wc.hInstance,nullptr);
+ if(!window)return 2;ShowWindow(window,SW_SHOW);SetForegroundWindow(window);UpdateWindow(window);
+ auto pump=[]{MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}};
+ pump();
+ const Scene scene=makeScene(run,speed);
+ 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;
+ 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.fgMultiplier=2;gd.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;
+ gd.fgMotion=mode==1||mode==5?engine::MotionSource::OpticalFlow:engine::MotionSource::Zero;
+ auto knob=[](const wchar_t* name)->std::wstring{wchar_t v[16]{};return GetEnvironmentVariableW(name,v,16)?std::wstring(v):std::wstring();};
+ 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;
+ 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;
+ 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);
+ if(!motion||!upload)return 2;gd.fgMotionProbe=motion.Get();
+ }
+ engine::VideoPresenter presenter;
+ if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){std::cerr<<"graph/presenter open failed"<<std::endl;return 2;}
+ if(!presenter.xessActive()){std::cerr<<"XeSS presenter not active"<<std::endl;return 2;}
+ {engine::PresentationSettings requested;std::wstring text;presenter.configurePresentation(ctx,requested,true,text);}
+ // Desktop duplication of the primary output (the window covers it exactly).
+ ComPtr<IDXGIFactory1> factory;if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return 2;
+ ComPtr<IDXGIAdapter1> adapter;ComPtr<IDXGIOutput> output;
+ for(UINT a=0;!output&&factory->EnumAdapters1(a,&adapter)!=DXGI_ERROR_NOT_FOUND;++a)
+ for(UINT o=0;adapter->EnumOutputs(o,&output)!=DXGI_ERROR_NOT_FOUND;++o){DXGI_OUTPUT_DESC od{};output->GetDesc(&od);if(od.Monitor==monitor)break;output.Reset();}
+ if(!output)return 2;
+ ComPtr<ID3D11Device> device11;ComPtr<ID3D11DeviceContext> context11;
+ if(FAILED(D3D11CreateDevice(adapter.Get(),D3D_DRIVER_TYPE_UNKNOWN,nullptr,D3D11_CREATE_DEVICE_BGRA_SUPPORT,nullptr,0,D3D11_SDK_VERSION,&device11,nullptr,&context11)))return 2;
+ // HDR desktop: duplicate as scRGB FP16 and undo the SDR white-level mapping (piecewise sRGB).
+ ComPtr<IDXGIOutput6> output6;DXGI_OUTPUT_DESC1 desc1{};const bool hdrDesktop=SUCCEEDED(output.As(&output6))&&SUCCEEDED(output6->GetDesc1(&desc1))&&desc1.ColorSpace==DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
+ const float white=hdrDesktop?sdrWhiteScale(monitor):1.f;if(hdrDesktop&&white<=0){std::cerr<<"SDR white level unavailable"<<std::endl;return 2;}
+ const DXGI_FORMAT captureFormat=hdrDesktop?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_B8G8R8A8_UNORM;
+ ComPtr<IDXGIOutput5> output5;ComPtr<IDXGIOutputDuplication> duplication;const DXGI_FORMAT formats[]={captureFormat};
+ if(FAILED(output.As(&output5))||FAILED(output5->DuplicateOutput1(device11.Get(),0,1,formats,&duplication))){std::cerr<<"DuplicateOutput1 failed"<<std::endl;return 2;}
+ // Half-float bit pattern -> SDR 8-bit, white level folded in (a table keeps capture real-time).
+ std::vector<uint8_t> decode(65536);for(uint32_t h=0;h<65536;++h)decode[h]=encodeSrgb(DirectX::PackedVector::XMConvertHalfToFloat(uint16_t(h))/white);
+ D3D11_TEXTURE2D_DESC sd{};sd.Width=CW;sd.Height=H;sd.MipLevels=1;sd.ArraySize=1;sd.Format=captureFormat;sd.SampleDesc.Count=1;sd.Usage=D3D11_USAGE_STAGING;sd.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
+ ComPtr<ID3D11Texture2D> staging;if(FAILED(device11->CreateTexture2D(&sd,nullptr,&staging)))return 2;
+ std::vector<Image> captures;std::mutex captureLock;std::atomic<bool> stop=false;std::atomic<unsigned> captureErrors=0;
+ std::jthread capture([&]{
+ while(!stop){
+ DXGI_OUTDUPL_FRAME_INFO fi{};ComPtr<IDXGIResource> resource;
+ const HRESULT hr=duplication->AcquireNextFrame(20,&fi,&resource);
+ if(hr==DXGI_ERROR_WAIT_TIMEOUT)continue;
+ if(FAILED(hr)){++captureErrors;break;}
+ if(fi.LastPresentTime.QuadPart&&captures.size()<64){
+ ComPtr<ID3D11Texture2D> texture;
+ if(SUCCEEDED(resource.As(&texture))){
+ D3D11_BOX box{UINT(X0),0,0,UINT(X0+CW),UINT(H),1};context11->CopySubresourceRegion(staging.Get(),0,0,0,0,texture.Get(),0,&box);
+ D3D11_MAPPED_SUBRESOURCE map{};
+ if(SUCCEEDED(context11->Map(staging.Get(),0,D3D11_MAP_READ,0,&map))){
+ Image im;im.rgb.resize(size_t(CW)*H);
+ for(int y=0;y<H;++y){const auto* row=static_cast<const uint8_t*>(map.pData)+size_t(y)*map.RowPitch;
+ if(hdrDesktop){const auto* h=reinterpret_cast<const uint16_t*>(row);
+ for(int x=0;x<CW;++x)im.rgb[size_t(y)*CW+x]={decode[h[x*4]],decode[h[x*4+1]],decode[h[x*4+2]]};}
+ else for(int x=0;x<CW;++x)im.rgb[size_t(y)*CW+x]={row[x*4+2],row[x*4+1],row[x*4]};}
+ context11->Unmap(staging.Get(),0);std::lock_guard lock(captureLock);captures.push_back(std::move(im));
+ }
+ }
+ }
+ duplication->ReleaseFrame();
+ }
+ });
+ 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);
+ 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();
+ 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.
+ constexpr float kDepth[]={.35f,.35f,.3f,.3f,.25f,.25f};auto* depth=graph.diagnosticDepthResource(true);
+ void* data=nullptr;if(!depth||FAILED(depthUpload->Map(0,nullptr,&data))){ok=false;break;}
+ auto* d=static_cast<float*>(data);for(size_t i=0;i<tops.size();++i)d[i]=tops[i]<0?.95f:kDepth[tops[i]];depthUpload->Unmap(0,nullptr);
+ unsigned slot=0;auto* list=ring.acquireNext(slot,st);if(!list){ok=false;break;}
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition={depth,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=depth;dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=depthUpload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R32_FLOAT,UINT(W),UINT(H),1,UINT(W*4)};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ 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];}
+ 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);
+ unsigned slot=0;auto* list=ring.acquireNext(slot,st);if(!list){ok=false;break;}
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition={motion.Get(),D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=motion.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R16G16_FLOAT,UINT(W),UINT(H),1,UINT(W*4)};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ ok=ring.submitAndSignal(slot)&&ring.waitIdle();
+ }
+ pipeline::EnhanceGraph::FrameOutputs out;
+ ok=ok&&presenter.beginSourceProcessing()&&graph.process(f,k*(1000.0/30),k==0,out,uint64_t(k+1));
+ if(!ok)break;
+ presenter.sourceProcessed(out.batch.identity);
+ ok=presenter.present(ctx,ring,graph,out.videoSlot,false,true,0,false,.5f,out.batch.identity,{},int64_t(k)*333333);
+ ok=ok&&ring.waitIdle()&&graph.resolveGeneration(out);
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(250));pump();
+ stop=true;capture.join();
+ const auto generatedBySdk=presenter.xessGeneratedCount();
+ av_frame_free(&f);ok=ring.drainQueue()&&ok;presenter.close();graph.shutdown();
+ // Ground truth (crop) for every evaluated pair midpoint and real frame, plus band masks.
+ auto render=[&](double t,Image& im,std::vector<float>* edge,std::vector<int8_t>* top){
+ im.rgb.resize(size_t(CW)*H);if(edge)edge->resize(size_t(CW)*H);if(top)top->resize(size_t(CW)*H);
+ parallelRows(H,[&](int y){for(int x=0;x<CW;++x){float e=0;int id=-1;im.rgb[size_t(y)*CW+x]=scene.pixel(X0+x,y,t,&id,&e);if(edge)(*edge)[size_t(y)*CW+x]=e;if(top)(*top)[size_t(y)*CW+x]=int8_t(id);}});
+ };
+ std::vector<Image> mids(N),reals(N);std::vector<std::vector<float>> midEdge(N),realEdge(N);std::vector<std::vector<int8_t>> midTop(N);
+ for(int k=0;k<N;++k){render(k,reals[k],&realEdge[k],nullptr);if(k>0)render(k-.5,mids[k],&midEdge[k],&midTop[k]);}
+ auto distance=[&](const Image& a,const Image& b){double s=0;uint64_t n=0;for(int y=0;y<H;y+=8)for(int x=0;x<CW;x+=8){const auto& p=a.rgb[size_t(y)*CW+x];const auto& q=b.rgb[size_t(y)*CW+x];s+=std::abs(p[0]-q[0])+std::abs(p[1]-q[1])+std::abs(p[2]-q[2]);++n;}return s/(3.0*n);};
+ std::vector<int> bestCapture(N,-1);std::vector<double> bestDistance(N,1e9);unsigned matchedReal=0,unmatched=0;std::string matches;
+ for(size_t c=0;c<captures.size();++c){
+ int pair=-1;double best=1e9;bool real=false;
+ for(int k=1;k<N;++k){const double d=distance(captures[c],mids[k]);if(d<best){best=d;pair=k;real=false;}}
+ for(int k=0;k<N;++k){const double d=distance(captures[c],reals[k]);if(d<best){best=d;pair=k;real=true;}}
+ matches+=std::format("{}\"{}{}:{:.1f}\"",matches.empty()?"":",",real?"r":"m",pair,best);
+ if(c==0||c==captures.size()/2||c+1==captures.size())save(dir/std::format("{}-capture{}.png",label,c),captures[c],1280,720,1400);
+ if(best>12){++unmatched;continue;}
+ if(real){++matchedReal;continue;}
+ if(best<bestDistance[pair]){bestDistance[pair]=best;bestCapture[pair]=int(c);}
+ }
+ Accumulator band,outside,inner;unsigned evaluated=0;int last=-1;std::string distances;
+ for(int k=Warmup+1;k<N;++k){
+ distances+=std::format("{}{:.2f}",distances.empty()?"":",",bestCapture[k]<0?-1.0:bestDistance[k]);
+ if(bestCapture[k]<0)continue;++evaluated;last=k;const auto& got=captures[size_t(bestCapture[k])];
+ for(int y=0;y<H;++y)for(int x=0;x<CW;++x){
+ const size_t i=size_t(y)*CW+x;const auto& p=got.rgb[i];const auto& q=mids[k].rgb[i];
+ const int r=std::abs(p[0]-q[0]),g=std::abs(p[1]-q[1]),b=std::abs(p[2]-q[2]);
+ const float e=std::min({midEdge[k][i],realEdge[k][i],realEdge[k-1][i]});
+ if(e<=Band)band.add(r,g,b);else(midTop[k][i]>=0?inner:outside).add(r,g,b);
+ }
+ }
+ if(last>0){
+ const auto& got=captures[size_t(bestCapture[last])];
+ const std::array<std::array<int,2>,4> centers{{{1080,900},{1480,900},{1280,1250},{1280,560}}};const char* names[]={"back","front","legs","arm"};
+ for(size_t c=0;c<centers.size()&&ok;++c){
+ const std::string stem=label+"-"+names[c];
+ ok=save(dir/(stem+"-cap.png"),got,centers[c][0],centers[c][1],448)&&save(dir/(stem+"-err.png"),got,centers[c][0],centers[c][1],448,true,&mids[last]);
+ if(ok&&mode==0)ok=save(dir/(std::format("xess-{}{}-{}-gt.png",run?"run":"orbit",speed,names[c])),mids[last],centers[c][0],centers[c][1],448);
+ }
+ }
+ 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 complete=evaluated>=unsigned(N-Warmup-1)*2/3;
+ std::cout<<std::format("FG_XESS_BOUNDARY {{\"label\":\"{}\",\"captures\":{},\"matchedReal\":{},\"unmatched\":{},\"evaluated\":{},\"sdkGenerated\":{},\"bandMae\":{:.4f},\"bandBadPct\":{:.4f},"
+ "\"outsideMae\":{:.4f},\"outsideBadPct\":{:.4f},\"innerMae\":{:.4f},\"pairDistances\":[{}],\"captureMatches\":[{}],\"hdrDesktop\":{},\"sdrWhite\":{:.3f},\"captureErrors\":{},\"errors\":{},\"pass\":{}}}",
+ label,captures.size(),matchedReal,unmatched,evaluated,generatedBySdk,band.mae(),band.badPercent(),outside.mae(),outside.badPercent(),inner.mae(),distances,matches,
+ hdrDesktop,white,captureErrors.load(),errors,ok&&complete&&!errors?"true":"false")<<std::endl;
+ ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();
+ return ok&&complete&&!errors?0:1;
+}