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++
phase-0 work: P0.6 veyra_gfx device context + 4-slot ring, device-info passes on RTX 5070
Veyra Goal Agent384699714db7
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 66c6b954..5846f87d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -36,6 +36,14 @@ target_compile_definitions(veyra_base PUBLICtarget_include_directories(veyra_base PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)target_link_libraries(veyra_base PUBLIC bcrypt wintrust crypt32 version)+add_library(veyra_gfx STATIC+ src/gfx/D3D12DeviceContext.cpp+ src/gfx/CommandSlotRing.cpp+)+veyra_apply_warnings(veyra_gfx)+target_compile_features(veyra_gfx PUBLIC cxx_std_20)+target_link_libraries(veyra_gfx PUBLIC veyra_base d3d12 dxgi dxguid)+add_executable(veyra_runtime_probetools/runtime_probe/main.cpp)@@ -43,4 +51,4 @@ veyra_apply_warnings(veyra_runtime_probe)target_compile_features(veyra_runtime_probe PRIVATE cxx_std_20)target_compile_definitions(veyra_runtime_probe PRIVATEUNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)-target_link_libraries(veyra_runtime_probe PRIVATE veyra_base)+target_link_libraries(veyra_runtime_probe PRIVATE veyra_gfx)diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.hnew file mode 100644index 00000000..621169e7--- /dev/null+++ b/include/veyra/gfx/CommandSlotRing.h@@ -0,0 +1,76 @@+#pragma once++#include <d3d12.h>+#include <wrl/client.h>++#include <cstdint>+#include <vector>++#include "veyra/Result.h"++namespace veyra::gfx {++template <typename T>+using ComPtr = Microsoft::WRL::ComPtr<T>;++// Rotating command-slot ring (Playbook section 6.2). Each slot owns its+// command allocator, recycled command list, fence value and two timestamp+// query indices. A frame only ever waits on the fence of the slot it is about+// to reuse, never on the frame it just submitted.+class CommandSlotRing {+public:+ CommandSlotRing() = default;+ ~CommandSlotRing();++ CommandSlotRing(const CommandSlotRing&) = delete;+ CommandSlotRing& operator=(const CommandSlotRing&) = delete;++ // `fenceEvent` is shared with the owning device context; waits use+ // SetEventOnCompletion + WaitForSingleObject on that event.+ bool initialize(ID3D12Device* device,+ ID3D12CommandQueue* queue,+ ID3D12Fence* fence,+ HANDLE fenceEvent,+ uint32_t slotCount,+ Status& status);+ void shutdown();++ uint32_t slotCount() const { return slotCount_; }+ bool initialized() const { return initialized_; }++ // Waits for this slot's outstanding fence value (if any), then resets the+ // allocator and command list. Returns the recycled list ready for record.+ ID3D12GraphicsCommandList* acquire(uint32_t slot, Status& status);++ // Closes, submits and signals the slot; advances the fence timeline.+ bool submitAndSignal(uint32_t slot);++ // Blocks until every slot's work completed.+ bool waitIdle();++ // Phase 0 skeleton proof: for each slot, acquire (wait+reset), record a+ // real begin/end timestamp query pair, submit, signal, then wait idle.+ bool exerciseAll();++ // Two timestamp query indices per slot (begin at 2*slot, end at 2*slot+1).+ uint32_t timestampQueryIndex(uint32_t slot, bool end) const;++private:+ struct Slot {+ ComPtr<ID3D12CommandAllocator> allocator;+ ComPtr<ID3D12GraphicsCommandList> list;+ uint64_t fenceValue = 0; // 0 means "never submitted"+ };++ bool initialized_ = false;+ uint32_t slotCount_ = 0;+ ID3D12Device* device_ = nullptr;+ ID3D12CommandQueue* queue_ = nullptr;+ ID3D12Fence* fence_ = nullptr;+ HANDLE fenceEvent_ = nullptr;+ uint64_t nextFenceValue_ = 1;+ ComPtr<ID3D12QueryHeap> timestampHeap_;+ std::vector<Slot> slots_;+};++} // namespace veyra::gfxdiff --git a/include/veyra/gfx/D3D12DeviceContext.h b/include/veyra/gfx/D3D12DeviceContext.hnew file mode 100644index 00000000..2de495b9--- /dev/null+++ b/include/veyra/gfx/D3D12DeviceContext.h@@ -0,0 +1,93 @@+#pragma once++#include <d3d12.h>+#include <dxgi1_6.h>+#include <wrl/client.h>++#include <cstdint>+#include <string>++#include "veyra/Result.h"++namespace veyra::gfx {++template <typename T>+using ComPtr = Microsoft::WRL::ComPtr<T>;++struct AdapterInfo {+ std::wstring description;+ uint32_t vendorId = 0;+ std::string vendorIdHex; // "0x10DE"+ std::string luidString; // "0xHigh:0xLow"+ uint64_t dedicatedVideoMemoryBytes = 0;+ bool isNvidia = false;+ bool isSoftware = false;+ std::wstring driverVersion; // registry DisplayVersion when found+ std::wstring driverVersionSource; // "registry" or "dxgi-raw"+};++struct DeviceContextDesc {+ bool enableDebugLayer = false;+ uint32_t commandSlotCount = 4;+};++// One DXGI adapter + one ID3D12Device + one direct command queue + one fence+// timeline with a rotating command-slot ring (Playbook sections 6.1/6.2).+class D3D12DeviceContext {+public:+ D3D12DeviceContext() = default;+ ~D3D12DeviceContext();++ D3D12DeviceContext(const D3D12DeviceContext&) = delete;+ D3D12DeviceContext& operator=(const D3D12DeviceContext&) = delete;++ // Initialization order: optional debug layer -> factory -> NVIDIA adapter+ // (vendor 0x10DE, non-software) -> device at >= 12_0 -> direct queue ->+ // fence/event -> command slot ring. Every step logs its real result.+ bool initialize(const DeviceContextDesc& desc, Status& status);+ void shutdown(); // reverse-order teardown++ bool initialized() const { return initialized_; }+ bool debugLayerEnabled() const { return debugLayerEnabled_; }++ ID3D12Device* device() const { return device_.Get(); }+ ID3D12CommandQueue* directQueue() const { return queue_.Get(); }+ ID3D12Fence* fence() const { return fence_.Get(); }+ HANDLE fenceEvent() const { return fenceEvent_; }+ uint64_t fenceCompletedValue() const { return fence_->GetCompletedValue(); }+ uint64_t nextFenceValue() const { return nextFenceValue_; }+ uint64_t signalNextFenceValue(); // Signal(queue) with ++nextFenceValue_++ const AdapterInfo& adapter() const { return adapterInfo_; }+ const std::string& featureLevelString() const { return featureLevel_; }+ uint32_t commandSlotCount() const { return commandSlotCount_; }++ // CPU wait until `value` completes; returns false on wait timeout/failure.+ bool waitForFenceValue(uint64_t value, uint32_t timeoutMs = 10000);++ // GetDeviceRemovedReason; returns true when the device is still alive.+ bool checkDeviceAlive(uint32_t& removedReason) const;++ // Exercises the full slot ring: acquire (wait+reset), empty command list+ // with timestamp begin/end markers, execute, signal, wait idle. Phase 0+ // skeleton proof that allocator/list/fence plumbing works end to end.+ bool exerciseSlotRing();++private:+ bool initialized_ = false;+ bool debugLayerEnabled_ = false;+ uint32_t commandSlotCount_ = 0;++ ComPtr<IDXGIFactory6> factory_;+ ComPtr<IDXGIAdapter1> adapter_;+ ComPtr<ID3D12Device> device_;+ ComPtr<ID3D12CommandQueue> queue_;+ ComPtr<ID3D12Fence> fence_;+ HANDLE fenceEvent_ = nullptr;+ uint64_t nextFenceValue_ = 1;++ AdapterInfo adapterInfo_{};+ std::string featureLevel_;+};++} // namespace veyra::gfxdiff --git a/loop/BACKLOG.md b/loop/BACKLOG.mdindex b8b8b68e..a0dd286c 100644--- a/loop/BACKLOG.md+++ b/loop/BACKLOG.md@@ -9,7 +9,7 @@- [x] P0.3 先创建 fail-closed 的 scripts/gates/phase0.ps1,编码 Playbook 的 Phase 0 门槛;此时因为工程/输出不存在必须失败。(2026-09-02:gate 建立并 AST-clean;负向运行 exit 1,5 项缺失输入全报;无项目变异。)- [x] P0.4 建立最小 CMake/C++20 Win32 x64 工程与 Debug/Release presets,不引入 FFmpeg/UI。(2026-09-02:Ninja presets 双配置构建 exit 0,stub 运行 exit 0,build.ps1 解析 vswhere/vcvars,presets 无机器路径。)- [x] P0.5 实现结构化 logger、HRESULT/NGX result 字符串、文件 size/hash/signature 检查。(2026-09-02:--self-test 实测 BCrypt SHA256、WinVerifyTrust、CryptQueryObject 签名者、版本提取;staged DLL 身份与固定契约全匹配;双 preset 构建 exit 0。)-- [ ] P0.6 实现 D3D12DeviceContext:RTX adapter、device、direct queue、debug layer、4-slot command allocator/list/fence/event ring。+- [x] P0.6 实现 D3D12DeviceContext:RTX adapter、device、direct queue、debug layer、4-slot command allocator/list/fence/event ring。(2026-09-02:--device-info 实测 RTX 5070/0x10DE/FL 12_2/4-slot ring + timestamp query 全通过;debug layer 缺失记 INBOX。)- [ ] P0.7 实现 veyra_runtime_probe:受限绝对路径加载本地复制的 nvngx_dlssnr.dll,验证 required exports;不得加载 addon。- [ ] P0.8 Debug/Release 构建并实际运行 probe;D3D12 窗口循环 5 分钟无 device removed;记录命令、exit code、GPU/driver、hash/signature/exports、日志路径。- [ ] P0.9 当前 gate 通过、只读 Reviewer 通过、修完 P0/P1、写 checkpoint。diff --git a/loop/INBOX.md b/loop/INBOX.mdindex bb44003e..9a1b4add 100644--- a/loop/INBOX.md+++ b/loop/INBOX.md@@ -4,6 +4,17 @@当前没有需要用户处理的阻塞。+## 2026-09-02 · Phase 0 · D3D12 debug layer 未安装(影响 Phase 1,不阻塞 Phase 0)++- 发现时间与 Phase:2026-09-02,Phase 0(P0.6 实测时发现)。+- 精确阻塞:`D3D12GetDebugInterface` 返回 0x887A002D(DXGI_ERROR_SDK_COMPONENT_MISSING)——本机未安装 Windows "Graphics Tools" 可选功能,无法启用 D3D12 debug layer。+- 已做的验证:probe `--device-info --debug-layer` 实测两次,均 hr=0x887A002D;无 debug layer 时 device/queue/slot ring 全部正常,Phase 0 门禁不依赖 debug layer。+- 为什么不能安全自动决定:安装 Windows optional capability 是系统级变更,AGENTS.md/LOOP_ENGINE 禁止 Agent 修改系统设置。+- 不受它影响、已经继续执行的工作:Phase 0 全部任务正常推进。+- 用户只需回答的最小问题:是否同意在 Phase 1 开始前运行+ `DISM /Online /Add-Capability /CapabilityName:Tools.Graphics.DirectX~~~~0.0.1.0`+ (或 设置→应用→可选功能→添加"图形工具")?Phase 1 的"D3D12 debug layer 无 resource-state error"门禁需要它。+新增条目必须包含:- 发现时间与 Phase;diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex 92c086e2..c2a05d17 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -170,6 +170,33 @@ Result:---+## Cycle 006 — P0.6 veyra_gfx D3D12DeviceContext++### Before++- Phase: 0+- 唯一任务: 实现 veyra_gfx(RTX adapter 枚举/筛选、D3D12 device ≥12_0、direct queue、fence/event、4-slot allocator+list ring + timestamp query heap),probe 增加 --device-info 在真实 GPU 上实测并 exercise ring。+- 可证伪假设: 若 adapter 筛选、FL、queue/fence 或 slot ring 有误,--device-info 将失败或报告非 NVIDIA adapter;成功时日志必须显示 RTX 5070/0x10DE/12_x/4 slots。+- 预计修改文件: include/veyra/gfx/{D3D12DeviceContext.h,CommandSlotRing.h}、src/gfx/{D3D12DeviceContext.cpp,CommandSlotRing.cpp}、CMakeLists.txt(+veyra_gfx)、tools/runtime_probe/main.cpp(--device-info)。+- 快速检查命令: `scripts/build.ps1 -Preset x64-debug` → 0;`veyra_runtime_probe.exe --device-info` → 0 且日志含 NVIDIA adapter 与 slot ring exercise。+- 预期新增证据: 真实 D3D12 device 初始化日志(adapter/driver/FL/LUID/VRAM、debug layer 状态、fence signal/wait)。++### After++- 实际修改: 新增 include/veyra/gfx/{D3D12DeviceContext.h,CommandSlotRing.h}、src/gfx/{D3D12DeviceContext.cpp,CommandSlotRing.cpp};CMakeLists 增加 veyra_gfx(d3d12/dxgi/dxguid);main.cpp 增加 --device-info/--debug-layer。+- 实际命令与 exit code:+ - `scripts/build.ps1 -Preset x64-debug/-release` → 修复 3 轮编译错误(adapter_ 成员重名/ComPtr 冲突、DXGI_ADAPTER_DESC3 不在 IDXGIAdapter1 上、queue_->Signal 需 .Get())后双双 exit 0。+ - `veyra_runtime_probe.exe --device-info [--debug-layer]` → exit 0(PASS)。+- 新证据/日志路径: probe 输出:adapter[0] NVIDIA GeForce RTX 5070 vendorId=0x10DE software=false dedicatedVideoMiB=11943;featureLevelMax=12_2;device context driver=32.0.16.1656 (registry/nvlddmkm.sys);4-slot ring acquire→timestamp pair→submit→signal(fenceValue 1..4)→waitIdle 全通过;timestamp heap 8 indices,frequency=1000000000 Hz。+- 失败 fingerprint: 无遗留。调试期三个修正:DXGI adapter desc 无 Version 字段(改用注册表 ImagePath→DriverStore nvlddmkm.sys 文件版本);`\SystemRoot` 前缀不被 ExpandEnvironmentStringsW 展开(手动替换);DisplayVersion 值本驱动不存在。+- 本 fingerprint 第几次不同尝试: 不适用。+- 是否有进展,依据: 是——真实 RTX 5070 上完成 device/queue/fence/4-slot ring 的创建、提交、timestamp query 与同步,全部有日志。+- 附加发现: D3D12 debug layer 未安装(0x887A002D,需 Windows Graphics Tools 可选功能),已记 INBOX;不阻塞 Phase 0。+- STATE/BACKLOG 更新: cycle.completed=6、currentTask 指向 P0.7;BACKLOG P0.6 → DONE。+- 下一唯一动作: P0.7 完整 probe:受限绝对路径 LoadLibraryExW 加载 staged DLL、5 exports 验证、System32 nvofapi64 探测、Win32 窗口+flip swapchain 循环、JSON+log 输出。++---+复制下面模板开始每个新 cycle。必须先填 Before,再改代码;完成后填 After。## Cycle NNN — 简短任务名diff --git a/loop/STATE.json b/loop/STATE.jsonindex b14cf3ec..b00679ec 100644--- a/loop/STATE.json+++ b/loop/STATE.json@@ -76,14 +76,14 @@}],"cycle": {- "completed": 5,+ "completed": 6,"maximum": 80,"sameFailureAttempts": 0,"maximumSameFailureAttempts": 3,"noProgressCycles": 0,"maximumNoProgressCycles": 5},- "currentTask": "P0.6: implement veyra_gfx D3D12DeviceContext (RTX adapter, device, direct queue, debug layer, 4-slot allocator/list/fence/event ring) and verify with probe --device-info on the real GPU.",+ "currentTask": "P0.7: implement the full veyra_runtime_probe (restricted LoadLibraryExW of the staged DLL, five required exports, System32 nvofapi64 probe, Win32 window + flip-model swapchain loop, structured log + JSON summary output).","lastGate": {"name": "phase0","status": "failed",@@ -96,6 +96,6 @@"lastGoodCommit": null,"openP0P1Findings": [],"blockers": [],- "nextAction": "Implement P0.6 veyra_gfx, P0.7 probe DLL load/window/JSON, P0.8 gate runs.",- "updatedAt": "2026-09-02T21:40:00+08:00"+ "nextAction": "Implement P0.7 full probe, then P0.8 real gate runs (Debug 3s + Release 300s window).",+ "updatedAt": "2026-09-02T21:50:00+08:00"}diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cppnew file mode 100644index 00000000..c1970cd8--- /dev/null+++ b/src/gfx/CommandSlotRing.cpp@@ -0,0 +1,224 @@+#include "veyra/gfx/CommandSlotRing.h"++#include <format>++#include "veyra/Log.h"+#include "veyra/NgxResult.h"++namespace veyra::gfx {++CommandSlotRing::~CommandSlotRing()+{+ shutdown();+}++bool CommandSlotRing::initialize(ID3D12Device* device,+ ID3D12CommandQueue* queue,+ ID3D12Fence* fence,+ HANDLE fenceEvent,+ uint32_t slotCount,+ Status& status)+{+ if (initialized_) {+ shutdown();+ }+ device_ = device;+ queue_ = queue;+ fence_ = fence;+ fenceEvent_ = fenceEvent;+ slotCount_ = slotCount;++ if (device_ == nullptr || queue_ == nullptr || fence_ == nullptr || fenceEvent_ == nullptr || slotCount_ == 0) {+ status = Status::InvalidArgument;+ veyra::log::error("gfx", "slot-ring: invalid initialize arguments");+ return false;+ }++ D3D12_QUERY_HEAP_DESC timestampHeapDesc{};+ timestampHeapDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;+ timestampHeapDesc.Count = slotCount_ * 2; // begin+end pair per slot+ timestampHeapDesc.NodeMask = 0;+ const HRESULT heapResult = device_->CreateQueryHeap(×tampHeapDesc, IID_PPV_ARGS(×tampHeap_));+ if (FAILED(heapResult)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: CreateQueryHeap failed hr={}", veyra::hresultString(heapResult)));+ return false;+ }+ UINT64 frequency = 0;+ const HRESULT freqResult = queue_->GetTimestampFrequency(&frequency);+ veyra::log::info("gfx", std::format("slot-ring: timestamp heap created slots={} pairs={} frequencyHz={} freqQuery={}",+ slotCount_, timestampHeapDesc.Count, frequency, veyra::hresultString(freqResult)));++ slots_.resize(slotCount_);+ for (uint32_t i = 0; i < slotCount_; ++i) {+ HRESULT result = device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&slots_[i].allocator));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: CreateCommandAllocator slot={} failed hr={}", i, veyra::hresultString(result)));+ return false;+ }+ result = device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, slots_[i].allocator.Get(), nullptr, IID_PPV_ARGS(&slots_[i].list));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: CreateCommandList slot={} failed hr={}", i, veyra::hresultString(result)));+ return false;+ }+ // Command lists are created in the recording state; close them so+ // acquire() can reset them deterministically.+ result = slots_[i].list->Close();+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: initial Close slot={} failed hr={}", i, veyra::hresultString(result)));+ return false;+ }+ slots_[i].fenceValue = 0;+ }++ initialized_ = true;+ veyra::log::info("gfx", std::format("slot-ring: initialized slots={}", slotCount_));+ return true;+}++void CommandSlotRing::shutdown()+{+ if (!initialized_) {+ return;+ }+ (void)waitIdle();+ slots_.clear();+ timestampHeap_.Reset();+ initialized_ = false;+ veyra::log::info("gfx", "slot-ring: shutdown complete");+}++ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& status)+{+ if (!initialized_ || slot >= slotCount_) {+ status = Status::InvalidArgument;+ veyra::log::error("gfx", std::format("slot-ring: acquire slot={} out of range", slot));+ return nullptr;+ }+ Slot& target = slots_[slot];++ if (target.fenceValue != 0) {+ const uint64_t completed = fence_->GetCompletedValue();+ if (completed < target.fenceValue) {+ const HRESULT waitResult = fence_->SetEventOnCompletion(target.fenceValue, fenceEvent_);+ if (FAILED(waitResult)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: SetEventOnCompletion slot={} failed hr={}", slot, veyra::hresultString(waitResult)));+ return nullptr;+ }+ const DWORD wait = WaitForSingleObject(fenceEvent_, 10000);+ if (wait != WAIT_OBJECT_0) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: fence wait slot={} waitResult={} fenceValue={}", slot, wait, target.fenceValue));+ return nullptr;+ }+ }+ }++ HRESULT result = target.allocator->Reset();+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: allocator reset slot={} failed hr={}", slot, veyra::hresultString(result)));+ return nullptr;+ }+ result = target.list->Reset(target.allocator.Get(), nullptr);+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("slot-ring: list reset slot={} failed hr={}", slot, veyra::hresultString(result)));+ return nullptr;+ }+ return target.list.Get();+}++bool CommandSlotRing::submitAndSignal(uint32_t slot)+{+ if (!initialized_ || slot >= slotCount_) {+ veyra::log::error("gfx", std::format("slot-ring: submit slot={} out of range", slot));+ return false;+ }+ Slot& target = slots_[slot];++ const HRESULT closeResult = target.list->Close();+ if (FAILED(closeResult)) {+ veyra::log::error("gfx", std::format("slot-ring: close slot={} failed hr={}", slot, veyra::hresultString(closeResult)));+ return false;+ }+ ID3D12CommandList* lists[] = { target.list.Get() };+ queue_->ExecuteCommandLists(1, lists);++ const uint64_t value = nextFenceValue_++;+ const HRESULT signalResult = queue_->Signal(fence_, value);+ if (FAILED(signalResult)) {+ veyra::log::error("gfx", std::format("slot-ring: signal slot={} failed hr={}", slot, veyra::hresultString(signalResult)));+ return false;+ }+ target.fenceValue = value;+ return true;+}++bool CommandSlotRing::waitIdle()+{+ if (!initialized_) {+ return true;+ }+ uint64_t highest = 0;+ for (const Slot& slot : slots_) {+ if (slot.fenceValue > highest) {+ highest = slot.fenceValue;+ }+ }+ if (highest == 0) {+ return true;+ }+ if (fence_->GetCompletedValue() >= highest) {+ return true;+ }+ const HRESULT setResult = fence_->SetEventOnCompletion(highest, fenceEvent_);+ if (FAILED(setResult)) {+ veyra::log::error("gfx", std::format("slot-ring: waitIdle SetEventOnCompletion failed hr={}", veyra::hresultString(setResult)));+ return false;+ }+ const DWORD wait = WaitForSingleObject(fenceEvent_, 30000);+ if (wait != WAIT_OBJECT_0) {+ veyra::log::error("gfx", std::format("slot-ring: waitIdle wait={} fenceValue={}", wait, highest));+ return false;+ }+ return true;+}++uint32_t CommandSlotRing::timestampQueryIndex(uint32_t slot, bool end) const+{+ return slot * 2 + (end ? 1u : 0u);+}++bool CommandSlotRing::exerciseAll()+{+ if (!initialized_) {+ veyra::log::error("gfx", "slot-ring: exerciseAll before initialize");+ return false;+ }+ for (uint32_t slot = 0; slot < slotCount_; ++slot) {+ Status status = Status::Ok;+ ID3D12GraphicsCommandList* list = acquire(slot, status);+ if (list == nullptr) {+ return false;+ }+ list->EndQuery(timestampHeap_.Get(), D3D12_QUERY_TYPE_TIMESTAMP, timestampQueryIndex(slot, false));+ list->EndQuery(timestampHeap_.Get(), D3D12_QUERY_TYPE_TIMESTAMP, timestampQueryIndex(slot, true));+ if (!submitAndSignal(slot)) {+ return false;+ }+ veyra::log::info("gfx", std::format("slot-ring: slot={} recorded timestamp pair [{}..{}] and signaled fenceValue={}",+ slot, timestampQueryIndex(slot, false), timestampQueryIndex(slot, true), slots_[slot].fenceValue));+ }+ if (!waitIdle()) {+ return false;+ }+ veyra::log::info("gfx", std::format("slot-ring: exercised {} slots acquire->timestamps->submit->signal->waitIdle ok", slotCount_));+ return true;+}++} // namespace veyra::gfxdiff --git a/src/gfx/D3D12DeviceContext.cpp b/src/gfx/D3D12DeviceContext.cppnew file mode 100644index 00000000..c9174ff8--- /dev/null+++ b/src/gfx/D3D12DeviceContext.cpp@@ -0,0 +1,314 @@+#include "veyra/gfx/D3D12DeviceContext.h"++#include <windows.h>++#include <format>+#include <string>+#include <vector>++#include "veyra/Log.h"+#include "veyra/NgxResult.h"+#include "veyra/gfx/CommandSlotRing.h"++namespace veyra::gfx {++namespace {++std::string narrow(const std::wstring& text)+{+ if (text.empty()) {+ return {};+ }+ const int length = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);+ if (length <= 0) {+ return {};+ }+ std::string converted(static_cast<size_t>(length), '\0');+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()), converted.data(), length, nullptr, nullptr);+ return converted;+}++// Driver version from the kernel service key: first the friendly+// DisplayVersion string when present, otherwise the file version of the+// nvlddmkm.sys image the ImagePath value points at.+std::wstring queryNvidiaDriverVersion()+{+ HKEY key = nullptr;+ const LONG openResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\nvlddmkm",+ 0, KEY_QUERY_VALUE, &key);+ if (openResult != ERROR_SUCCESS) {+ return {};+ }++ wchar_t display[64]{};+ DWORD displaySize = sizeof(display);+ if (RegQueryValueExW(key, L"DisplayVersion", nullptr, nullptr, reinterpret_cast<LPBYTE>(display), &displaySize) == ERROR_SUCCESS &&+ displaySize >= sizeof(wchar_t) && display[0] != L'\0') {+ RegCloseKey(key);+ return std::wstring(display);+ }++ wchar_t imagePath[512]{};+ DWORD imagePathSize = sizeof(imagePath);+ if (RegQueryValueExW(key, L"ImagePath", nullptr, nullptr, reinterpret_cast<LPBYTE>(imagePath), &imagePathSize) != ERROR_SUCCESS ||+ imagePathSize < sizeof(wchar_t) || imagePath[0] == L'\0') {+ RegCloseKey(key);+ return {};+ }+ RegCloseKey(key);++ // ImagePath uses the kernel form "\SystemRoot\..."; ExpandEnvironmentStrings+ // only handles %%-references, so translate the prefix manually.+ std::wstring driverFile(imagePath);+ const wchar_t* systemRootPrefix = L"\\SystemRoot";+ const size_t prefixLength = 11; // wcslen(L"\\SystemRoot")+ if (_wcsnicmp(driverFile.c_str(), systemRootPrefix, prefixLength) == 0) {+ wchar_t windowsDir[MAX_PATH]{};+ const UINT windowsLength = GetWindowsDirectoryW(windowsDir, MAX_PATH);+ if (windowsLength == 0 || windowsLength >= MAX_PATH) {+ return {};+ }+ driverFile = std::wstring(windowsDir) + driverFile.substr(prefixLength);+ }++ DWORD handle = 0;+ const DWORD versionSize = GetFileVersionInfoSizeW(driverFile.c_str(), &handle);+ if (versionSize == 0) {+ return {};+ }+ std::vector<unsigned char> buffer(versionSize);+ if (!GetFileVersionInfoW(driverFile.c_str(), 0, versionSize, buffer.data())) {+ return {};+ }+ VS_FIXEDFILEINFO* fixedInfo = nullptr;+ UINT length = 0;+ if (VerQueryValueW(buffer.data(), L"\\", reinterpret_cast<void**>(&fixedInfo), &length) && length >= sizeof(VS_FIXEDFILEINFO)) {+ return std::format(L"{}.{}.{}.{}",+ HIWORD(fixedInfo->dwFileVersionMS), LOWORD(fixedInfo->dwFileVersionMS),+ HIWORD(fixedInfo->dwFileVersionLS), LOWORD(fixedInfo->dwFileVersionLS));+ }+ return {};+}++bool fillAdapterInfo(const DXGI_ADAPTER_DESC1& desc, AdapterInfo& info)+{+ info.description = desc.Description;+ info.vendorId = desc.VendorId;+ info.vendorIdHex = std::format("0x{:04X}", desc.VendorId);+ info.luidString = std::format("0x{:08X}:0x{:016X}",+ static_cast<uint32_t>(desc.AdapterLuid.HighPart),+ static_cast<uint64_t>(desc.AdapterLuid.LowPart));+ info.dedicatedVideoMemoryBytes = desc.DedicatedVideoMemory;+ info.isNvidia = desc.VendorId == 0x10DE;+ info.isSoftware = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;+ info.driverVersion = queryNvidiaDriverVersion();+ info.driverVersionSource = info.driverVersion.empty() ? L"unavailable" : L"registry";+ return info.isNvidia && !info.isSoftware;+}++} // namespace++D3D12DeviceContext::~D3D12DeviceContext()+{+ shutdown();+}++bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& status)+{+ if (initialized_) {+ shutdown();+ }++ // 1. Optional debug layer.+ if (desc.enableDebugLayer) {+ ComPtr<ID3D12Debug> debug;+ HRESULT result = D3D12GetDebugInterface(IID_PPV_ARGS(&debug));+ if (SUCCEEDED(result)) {+ debug->EnableDebugLayer();+ debugLayerEnabled_ = true;+ veyra::log::info("gfx", "d3d12 debug layer enabled");+ }+ else {+ veyra::log::warn("gfx", std::format("d3d12 debug layer unavailable hr={}; continuing without it", veyra::hresultString(result)));+ }+ }++ // 2. DXGI factory.+ const UINT factoryFlags = debugLayerEnabled_ ? DXGI_CREATE_FACTORY_DEBUG : 0;+ HRESULT result = CreateDXGIFactory2(factoryFlags, IID_PPV_ARGS(&factory_));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("CreateDXGIFactory2 failed hr={}", veyra::hresultString(result)));+ return false;+ }++ // 3. Highest-performance NVIDIA adapter (vendor 0x10DE, non-software).+ DXGI_ADAPTER_DESC1 chosenDesc{};+ bool chosen = false;+ for (UINT index = 0;; ++index) {+ ComPtr<IDXGIAdapter1> candidate;+ const HRESULT enumResult = factory_->EnumAdapterByGpuPreference(+ index, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate));+ if (enumResult == DXGI_ERROR_NOT_FOUND) {+ break;+ }+ if (FAILED(enumResult)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("EnumAdapterByGpuPreference index={} failed hr={}", index, veyra::hresultString(enumResult)));+ return false;+ }++ DXGI_ADAPTER_DESC1 candidateDesc{};+ result = candidate->GetDesc1(&candidateDesc);+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("adapter GetDesc1 index={} failed hr={}", index, veyra::hresultString(result)));+ return false;+ }++ const bool isSoftware = (candidateDesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;+ veyra::log::info("gfx", std::format("adapter[{}] vendorId=0x{:04X} software={} dedicatedVideoMiB={} desc={}",+ index, candidateDesc.VendorId, isSoftware,+ candidateDesc.DedicatedVideoMemory / (1024 * 1024),+ narrow(candidateDesc.Description)));++ if (candidateDesc.VendorId == 0x10DE && !isSoftware) {+ adapter_ = candidate;+ chosenDesc = candidateDesc;+ chosen = true;+ break;+ }+ }++ if (!chosen) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", "no NVIDIA (vendor 0x10DE) hardware adapter found; refusing WARP fallback");+ return false;+ }+ fillAdapterInfo(chosenDesc, adapterInfo_);++ // 4. Device at minimum feature level 12_0, reporting the highest level.+ result = D3D12CreateDevice(adapter_.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device_));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("D3D12CreateDevice failed hr={}", veyra::hresultString(result)));+ return false;+ }++ const D3D_FEATURE_LEVEL requested[] = { D3D_FEATURE_LEVEL_12_2, D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0 };+ D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevels{};+ featureLevels.pFeatureLevelsRequested = requested;+ featureLevels.NumFeatureLevels = static_cast<UINT>(std::size(requested));+ const HRESULT flResult = device_->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevels, sizeof(featureLevels));+ if (SUCCEEDED(flResult)) {+ const uint32_t packed = static_cast<uint32_t>(featureLevels.MaxSupportedFeatureLevel);+ featureLevel_ = std::format("{}_{}", packed >> 12, (packed >> 8) & 0xF);+ }+ else {+ featureLevel_ = "12_0";+ }+ veyra::log::info("gfx", std::format("device created featureLevelMax={} checkHr={}", featureLevel_, veyra::hresultString(flResult)));++ // 5. Direct command queue.+ D3D12_COMMAND_QUEUE_DESC queueDesc{};+ queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;+ queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;+ queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;+ queueDesc.NodeMask = 0;+ result = device_->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&queue_));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("CreateCommandQueue failed hr={}", veyra::hresultString(result)));+ return false;+ }++ // 6. Fence + event.+ result = device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_));+ if (FAILED(result)) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("CreateFence failed hr={}", veyra::hresultString(result)));+ return false;+ }+ fenceEvent_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ if (fenceEvent_ == nullptr) {+ status = Status::DeviceFailure;+ veyra::log::error("gfx", std::format("CreateEventW failed lastError={}", GetLastError()));+ return false;+ }++ commandSlotCount_ = desc.commandSlotCount;+ initialized_ = true;+ veyra::log::info("gfx", std::format("device context initialized adapter={} vendor={} luid={} driver={} ({}) featureLevel={} slots={}",+ narrow(adapterInfo_.description), adapterInfo_.vendorIdHex, adapterInfo_.luidString,+ narrow(adapterInfo_.driverVersion.empty() ? std::wstring(L"<none>") : adapterInfo_.driverVersion),+ narrow(adapterInfo_.driverVersionSource),+ featureLevel_, commandSlotCount_));+ return true;+}++void D3D12DeviceContext::shutdown()+{+ if (!initialized_) {+ return;+ }+ if (fence_ != nullptr && fenceEvent_ != nullptr) {+ (void)waitForFenceValue(nextFenceValue_ - 1, 5000);+ }+ if (fenceEvent_ != nullptr) {+ CloseHandle(fenceEvent_);+ fenceEvent_ = nullptr;+ }+ queue_.Reset();+ device_.Reset();+ adapter_.Reset();+ factory_.Reset();+ initialized_ = false;+ veyra::log::info("gfx", "device context shutdown complete");+}++uint64_t D3D12DeviceContext::signalNextFenceValue()+{+ const uint64_t value = nextFenceValue_++;+ const HRESULT result = queue_->Signal(fence_.Get(), value);+ if (FAILED(result)) {+ veyra::log::error("gfx", std::format("fence signal failed hr={}", veyra::hresultString(result)));+ }+ return value;+}++bool D3D12DeviceContext::waitForFenceValue(uint64_t value, uint32_t timeoutMs)+{+ if (fence_->GetCompletedValue() >= value) {+ return true;+ }+ const HRESULT result = fence_->SetEventOnCompletion(value, fenceEvent_);+ if (FAILED(result)) {+ veyra::log::error("gfx", std::format("SetEventOnCompletion failed hr={} value={}", veyra::hresultString(result), value));+ return false;+ }+ return WaitForSingleObject(fenceEvent_, timeoutMs) == WAIT_OBJECT_0;+}++bool D3D12DeviceContext::checkDeviceAlive(uint32_t& removedReason) const+{+ const HRESULT reason = device_->GetDeviceRemovedReason();+ removedReason = static_cast<uint32_t>(reason);+ return SUCCEEDED(reason);+}++bool D3D12DeviceContext::exerciseSlotRing()+{+ CommandSlotRing ring;+ Status status = Status::Ok;+ if (!ring.initialize(device_.Get(), queue_.Get(), fence_.Get(), fenceEvent_, commandSlotCount_, status)) {+ veyra::log::error("gfx", std::format("exerciseSlotRing: ring init failed status={}", veyra::statusString(status)));+ return false;+ }+ if (!ring.exerciseAll()) {+ return false;+ }+ ring.shutdown();+ return true;+}++} // namespace veyra::gfxdiff --git a/tools/runtime_probe/main.cpp b/tools/runtime_probe/main.cppindex 4694b4ac..3238fca6 100644--- a/tools/runtime_probe/main.cpp+++ b/tools/runtime_probe/main.cpp@@ -12,6 +12,7 @@#include "veyra/Log.h"#include "veyra/NgxResult.h"#include "veyra/Result.h"+#include "veyra/gfx/D3D12DeviceContext.h"namespace {@@ -111,17 +112,63 @@ int runSelfTest(const std::wstring& runtimeDir)return 0;}+int runDeviceInfo(bool debugLayer)+{+ veyra::gfx::D3D12DeviceContext context;+ veyra::gfx::DeviceContextDesc desc{};+ desc.enableDebugLayer = debugLayer;+ desc.commandSlotCount = 4;++ veyra::Status status = veyra::Status::Ok;+ if (!context.initialize(desc, status)) {+ veyra::log::error("probe", std::format("device-info: initialize failed status={}", veyra::statusString(status)));+ return 6;+ }++ const veyra::gfx::AdapterInfo& adapter = context.adapter();+ veyra::log::info("probe", std::format("device-info: adapter={} vendor={} nvidia={} luid={} vramMiB={} driver={} ({})",+ narrow(adapter.description), adapter.vendorIdHex, adapter.isNvidia, adapter.luidString,+ adapter.dedicatedVideoMemoryBytes / (1024 * 1024),+ narrow(adapter.driverVersion.empty() ? std::wstring(L"<none>") : adapter.driverVersion),+ narrow(adapter.driverVersionSource)));+ veyra::log::info("probe", std::format("device-info: featureLevel={} debugLayer={} slots={}",+ context.featureLevelString(), context.debugLayerEnabled(), context.commandSlotCount()));++ if (!context.exerciseSlotRing()) {+ veyra::log::error("probe", "device-info: slot ring exercise failed");+ return 7;+ }++ uint32_t removedReason = 0;+ const bool alive = context.checkDeviceAlive(removedReason);+ context.shutdown();+ if (!alive) {+ veyra::log::error("probe", std::format("device-info: device removed reason={}", veyra::hresultString(static_cast<long>(removedReason))));+ return 8;+ }+ veyra::log::info("probe", "device-info: PASS");+ return 0;+}+} // namespaceint wmain(int argc, wchar_t** argv){std::wstring runtimeDir;bool selfTest = false;+ bool deviceInfo = false;+ bool debugLayer = false;for (int i = 1; i < argc; ++i) {const std::wstring arg = argv[i];if (arg == L"--self-test") {selfTest = true;}+ else if (arg == L"--device-info") {+ deviceInfo = true;+ }+ else if (arg == L"--debug-layer") {+ debugLayer = true;+ }else if (arg == L"--runtime-dir" && i + 1 < argc) {runtimeDir = argv[++i];}@@ -130,7 +177,10 @@ int wmain(int argc, wchar_t** argv)if (selfTest) {return runSelfTest(runtimeDir);}+ if (deviceInfo) {+ return runDeviceInfo(debugLayer);+ }- veyra::log::info("probe", "no mode selected; use --self-test (full probe arrives in P0.6/P0.7)");+ veyra::log::info("probe", "no mode selected; use --self-test or --device-info (full probe arrives in P0.7)");return 0;}