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: measure optional same-pair bidirectional optical flow

Veyra Goal Agentbfbfcbd40e30
diff --git a/CMakeLists.txt b/CMakeLists.txt
index de9f51d9..bbb652ad 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -433,6 +433,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_repair_parameter_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)
add_executable(veyra_repair_fg_tests tests/integration/RepairFgTests.cpp)
add_executable(veyra_motion_validation_tests tests/integration/MotionValidationTests.cpp)
+ add_executable(veyra_bidirectional_flow_tests tests/integration/BidirectionalFlowTests.cpp)
+ target_compile_features(veyra_bidirectional_flow_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_bidirectional_flow_tests PRIVATE veyra_pipeline veyra_nvof)
target_compile_features(veyra_motion_validation_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_motion_validation_tests PRIVATE veyra_pipeline)
add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)
diff --git a/docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md b/docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md
new file mode 100644
index 00000000..461a8d47
--- /dev/null
+++ b/docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md
@@ -0,0 +1,35 @@
+# Same-pair bidirectional flow experiment
+
+Cycle74, base3fc3e22. Phase7 optimization remains in progress. The shared `NvOfSession` now accepts optional reverse flow/cost textures together. Defaults are null and preserve forward-only behavior. No UI, EnhanceGraph default, export integrity, model, lookahead or shader was changed.
+
+## Contract and actual test
+
+Local NVIDIA Optical Flow SDK5.0.7 D3D12 exposes `NV_OF_PRED_DIRECTION_BOTH`, `bwdOutputBuffer` and `bwdOutputCostBuffer`. With current B as input and previous A as reference, primary vectors are current→previous and reverse vectors previous→current. Both use the same pair; no C frame is required. Reverse R16G16_SINT/R8_UINT textures must match hardware-grid extent, be single-slice/mip/sample, and not alias primary outputs. Partial reverse pairs reject before disturbing a live session. Registration rollback and unregister/release/destroy include reverse handles in reverse order. Runtime remains System32 NVOF.
+
+`veyra_bidirectional_flow_tests [width height]` uses the product session, real GPU output readback only in this diagnostic, and known translated nonperiodic textures. It validates +8/-8 source-pixel directions, wrong-format/alias rejection, preservation on partial-pair rejection, actual output, and teardown/debug errors. Novel constant foreground exists only in current B: its interior has no previous correspondence. The CPU diagnostic compares existing cost/bounds/photometric acceptance with an additional reverse-cost and nearest-grid round-trip error <1.5px test. This is not a production shader or perceptual-quality oracle.
+
+Build command: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root "$PWD" -Preset x64-release` (`build-cycle74-contract.log`, exit0).
+
+Final maker matrix: `logs/optimization-goal-20260908/bidir-matrix-e47ef77e21b44baaa4eace596d6080cd/`. Runner `logs/optimization-goal-20260908/run-bidir.ps1` executes360p/1080p/4K separately with275-second watchdogs. Each invokes four cases, all exit0/debug0. NVOF init/execute/unregister statuses0. Direction median endpoint error .0442px for both directions. Tests read InfoQueue after unregister/resource release/shutdown. Initial and previous matrices retained, no hidden failures.
+
+| Source | Novel-region grid points | Accepted by base test | Still accepted with consistency | Correct-background accepted before/after |
+|---|---:|---:|---:|---:|
+| 640×360 | 1,274 | 644 | 4 | 8,338 / 8,338 |
+| 1920×1080 | 13,416 | 6,330 | 12 | 101,392 / 101,392 |
+| 3840×2160 | 55,616 | 25,992 | 44 | 432,992 / 432,992 |
+
+Measurements are warmed throughput: four warmup calls, then60 repeated evaluations of the **same fixed pair**, final GPU fence completion included. CPU+GPU elapsed divided by60; not single-frame latency, GPU timestamp duration or P95. Input upload/readback excluded. No temporal hints. The forward and BOTH harness cases allocate the same textures; the reverse output allocation below is an incremental requirement if integrated, and excludes internal driver allocations.
+
+| Source | Forward mean ms/pair (plain/occluded) | BOTH mean ms/pair | Reverse output texture allocation |
+|---|---:|---:|---:|
+| 640×360 | .229 / .265 | .349 / .367 | 131,072 bytes |
+| 1920×1080 | .825 / .836 | 1.497 / 1.510 | 786,432 bytes |
+| 3840×2160 | 3.073 / 2.974 | 5.703 / 5.571 | 2,818,048 bytes |
+
+## Decision and limits
+
+The hypothesis is supported for this constructed occlusion: consistency rejects many wrong correspondences that luma/cost checks retain. Cost is material at4K (about2.6ms extra in this experiment). Keep the capability as an opt-in candidate, **do not enable it by default or claim reduced NR/FG artifacts yet**. No product path requests reverse outputs, so these measurements do not prove changed user-visible quality. Before adoption, test changing/natural frame pairs, unequal motions and repeated/isoluminant textures, GPU consistency sampling, then actual NR/FG output against baseline. Reduced/zero motion alone does not prove safe exclusion of model history.
+
+Independent gate/review is recorded separately after execution. Physical capture, long stability, natural reconstruction and Q7 remain outside this scoped experiment.
+
+Reviewer first verdict FAIL identified a diagnostic-only P2: non-512-aligned cost readback offsets for accepted odd grid heights (640x129). Product/default paths and standard-size evidence unaffected. Fixed per-footprint placement alignment and total buffer extent. Maker actual640x129 all fourcases exit0/debug0, bidir-odd-428ef6956ced4584808b6ccd2e95da90; medianEPE.0442, novel base191->73, correctbackground1411unchanged. The weaker small-height occlusion rejection reinforces that benefits are case-specific. Final reviewer revalidation pending; initial verdict retained.
diff --git a/docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md b/docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md
new file mode 100644
index 00000000..7dad0872
--- /dev/null
+++ b/docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md
@@ -0,0 +1,11 @@
+# Independent bidirectional candidate review
+
+Fresh-context read-only `review_bidirectional_candidate`, scoped diff vs3fc3e22. Final **PASS**, no remaining introduced P0/P1/P2. Default FORWARD, product graph/UI/export integrity unchanged. No natural NR/FG quality or full Goal claim.
+
+Initial review: independent preflight71/phase7 75 exit0, delivery `logs/delivery/d63406d71034438c9b461502da3ffb73/result.json`; test evidence `logs/optimization-goal-20260908/review-bidir-53ef67d5a404489c84050b408ea57879/`. Actual1080p/4K four combinations each pass/debug0. Both direction EPE .0441942px. Novel wrong acceptance6330→12 and25992→44; correct background101392/432992 unchanged. Occlusion warmed fixed-pair throughput .829→1.506ms and2.973→5.475ms, not latency/P95. Tracked fingerprint unchanged `d2e87a8fd1e12f1179e766014df1d439edf29e29`.
+
+Initial verdict FAIL: P2 in diagnostic readback offsets for640×129 (gridheight33). Per-footprint offsets25344/59136 were256mod512. Maker corrected independent512-byte alignment and final allocation extent; this did not alter standard-size layouts or product behavior.
+
+Final independent640×129: all four cases exit0/debug0, EPE .0441942px. Novel wrong acceptance191→73, correct background1411 unchanged. Evidence `logs/optimization-goal-20260908/review-bidir-fix-e6fbc793d4824054b7465f6361075361/`. Final phase7 75 exit0: `logs/delivery/aea3d88148bf4e6b9c793cd99f95f7fb/result.json`. Tracked fingerprint unchanged `2d3745d722cd9931e12d9ec6200d14d4d66f9924`. Original P2 closed.
+
+Normal register/unregister→resource-release→destroy ran on GPU. Driver registration-failure rollback was inspected, not fault-injected. CPU consistency diagnostic does not prove production GPU consistency or NR/FG benefits on changing/natural pairs. Same fixed-pair batch mean is not latency/P95. No additional source-frame lookahead introduced. Physical capture, long stability and distribution remain outside scope.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 23e2c76c..b14113dc 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1219,3 +1219,9 @@ See docs/SCENE_MOTION_CORPUS_2026-09-08.md. Motion vertical/cost GPU checks and
## Cycles71-73 independent scoped PASS
review_scene_boundaries no introducedP0/P1/P2; docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md. Independentpreflight71/phase7delivery55725c1cd58846c59342d5e62456277341.568s75PASS. Freshreview-scene-fc558d881d0b404fbe51e5f6f2ebd6e0:scene14/motionbothaxesdebug0;RTXNR600NVOF594/Create0x1SEH0;actualFG600source594generated6holds1200output andindependentfull1200decode. BoundarypreviousYerror<=.048694/255. Trackedfingerprint4343fa50af201ad1393b6bec4228e3c18fb4447dunchanged. Q6/Q7/natural/physical/long-term/distribution not passed.
+
+## Cycle74 bidirectional candidate evidence
+Shared optional BOTH session and realGPU diagnostic; defaults unchanged. docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md. Finalbidir-matrix-e47ef77e21b44baaa4eace596d6080cd360p/1080p/4Kall exit0/debug0, known+8/-8EPE.0442px.1080pnovelwrongaccept6330->12, correctbackground101392unchanged;4K25992->44/correct432992unchanged. Fixed-pair warmedthroughput1080p.836->1.510ms,4K2.974->5.571ms; notlatency/P95/naturalquality. Default remainsforward; no graph/exportintegrity/newmodel changes. Frozen gate/review pending.
+
+## Cycle74 independent final scopedPASS
+review_bidirectional_candidate: initialP2diagnosticfootprintalignmentFAIL repaired; independent640x129all4casesPASS/debug0 (novel191->73,good1411unchanged). Initial1080/4KindependentmatrixPASS remainsvalid. Finalphase7aea3d88148bf4e6b9c793cd99f95f7fb75PASSexit0; docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md. Reviewerfinalfingerprint2d3745d722cd9931e12d9ec6200d14d4d66f9924unchanged. Optionalsharedcapabilityonly; defaultforward, no graph/shader/exportintegrity/model changes. Retaincandidatependingnatural/changingframeNR/FGROI; fullGoalopen.
diff --git a/include/veyra/ngx/NvOfSession.h b/include/veyra/ngx/NvOfSession.h
index 677f2304..75f7e88b 100644
--- a/include/veyra/ngx/NvOfSession.h
+++ b/include/veyra/ngx/NvOfSession.h
@@ -1,9 +1,11 @@
#pragma once
// Reusable NVOF D3D12 session (extracted from the Phase 5 probe).
-// Produces forward optical flow as raw SHORT2 (S10.5) at the hardware-grid
-// extent, plus the SDK cost buffer; a densify pass converts to workingExtent
-// pixels for DLSSG (see shaders/NvofDensify.hlsl). Synchronization is fence-based:
+// Produces current->previous optical flow as raw SHORT2 (S10.5) at the
+// hardware-grid extent, plus SDK cost. Vectors use source-input pixels; densify
+// expands the grid, and any working-extent scaling happens downstream.
+// Optional paired reverse outputs also produce previous->current from the
+// same A/B frames. Synchronization is fence-based:
// the caller signals `inFence`/`inValue` when both input textures are ready;
// NVOF signals `outFence`/nextOutValue when the flow texture is complete.
// The caller must make its D3D12 queue wait on outFence before consuming the
@@ -38,6 +40,11 @@ public:
// P0.4: raw output lives at hardware-grid extent in SHORT2 (S10.5).
uint32_t quality=1; // 0 performance / 1 balanced / 2 quality; mapped to SDK symbols
uint32_t gridSize = 4; // requested grid (validated vs caps)
+ // Optional diagnostic/candidate path: BOTH produces previous->current
+ // as well, using the same A/B pair. Caller owns both grid textures and
+ // follows the same fence and unregister-before-release contract.
+ ID3D12Resource* reverseFlow = nullptr; // R16G16_SINT, paired with reverseCost
+ ID3D12Resource* reverseCost = nullptr; // R8_UINT
};
struct Caps {
@@ -115,6 +122,7 @@ private:
Caps caps_;
uint32_t gridW_ = 0, gridH_ = 0;
NvOfOpaqueHandle hCost_ = nullptr;
+ NvOfOpaqueHandle hReverseFlow_ = nullptr, hReverseCost_ = nullptr;
};
} // namespace veyra::ngx
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
index 89ea2b1c..ea5bec9b 100644
--- a/loop/EVIDENCE.md
+++ b/loop/EVIDENCE.md
@@ -522,3 +522,9 @@ See docs/SCENE_MOTION_CORPUS_2026-09-08.md. Motion vertical/cost GPU checks and
## Cycles71-73 independent scoped PASS
review_scene_boundaries no introducedP0/P1/P2; docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md. Independentpreflight71/phase7delivery55725c1cd58846c59342d5e62456277341.568s75PASS. Freshreview-scene-fc558d881d0b404fbe51e5f6f2ebd6e0:scene14/motionbothaxesdebug0;RTXNR600NVOF594/Create0x1SEH0;actualFG600source594generated6holds1200output andindependentfull1200decode. BoundarypreviousYerror<=.048694/255. Trackedfingerprint4343fa50af201ad1393b6bec4228e3c18fb4447dunchanged. Q6/Q7/natural/physical/long-term/distribution not passed.
+
+## Cycle74 bidirectional candidate evidence
+Shared optional BOTH session and realGPU diagnostic; defaults unchanged. docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md. Finalbidir-matrix-e47ef77e21b44baaa4eace596d6080cd360p/1080p/4Kall exit0/debug0, known+8/-8EPE.0442px.1080pnovelwrongaccept6330->12, correctbackground101392unchanged;4K25992->44/correct432992unchanged. Fixed-pair warmedthroughput1080p.836->1.510ms,4K2.974->5.571ms; notlatency/P95/naturalquality. Default remainsforward; no graph/exportintegrity/newmodel changes. Frozen gate/review pending.
+
+## Cycle74 independent final scopedPASS
+review_bidirectional_candidate: initialP2diagnosticfootprintalignmentFAIL repaired; independent640x129all4casesPASS/debug0 (novel191->73,good1411unchanged). Initial1080/4KindependentmatrixPASS remainsvalid. Finalphase7aea3d88148bf4e6b9c793cd99f95f7fb75PASSexit0; docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md. Reviewerfinalfingerprint2d3745d722cd9931e12d9ec6200d14d4d66f9924unchanged. Optionalsharedcapabilityonly; defaultforward, no graph/shader/exportintegrity/model changes. Retaincandidatependingnatural/changingframeNR/FGROI; fullGoalopen.
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index 9a7ac378..7e911b02 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -1542,3 +1542,12 @@ Cycle73 gate initial wrapper FAIL: phase.state needs_review is not accepted by t
## Cycles71-73 independent scoped PASS
review_scene_boundaries no introducedP0/P1/P2; docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md. Independentpreflight71/phase7delivery55725c1cd58846c59342d5e62456277341.568s75PASS. Freshreview-scene-fc558d881d0b404fbe51e5f6f2ebd6e0:scene14/motionbothaxesdebug0;RTXNR600NVOF594/Create0x1SEH0;actualFG600source594generated6holds1200output andindependentfull1200decode. BoundarypreviousYerror<=.048694/255. Trackedfingerprint4343fa50af201ad1393b6bec4228e3c18fb4447dunchanged. Q6/Q7/natural/physical/long-term/distribution not passed.
+## Cycle74 - shared bidirectional NVOF diagnostic
+Previous Goal turn is progress:3fc3e22 fixed all3missed authoredcuts and independently verified boundaryholds. Clean tree/noSTOP. Add optional paired reverse flow/cost outputs to shared NvOfSession, default null unchanged. Validate resource contract and rollback/lifetime. Standalone product-library diagnostic measures sameA/B forward vsboth, known displacement and occlusion consistency, cost/time; no graph/default integration before evidence. Eachprocess<=275seconds. No Cframe, exportintegrity or control changes.
+
+## Cycle74 bidirectional candidate evidence
+Shared optional BOTH session and realGPU diagnostic; defaults unchanged. docs/BIDIRECTIONAL_FLOW_EXPERIMENT_2026-09-08.md. Finalbidir-matrix-e47ef77e21b44baaa4eace596d6080cd360p/1080p/4Kall exit0/debug0, known+8/-8EPE.0442px.1080pnovelwrongaccept6330->12, correctbackground101392unchanged;4K25992->44/correct432992unchanged. Fixed-pair warmedthroughput1080p.836->1.510ms,4K2.974->5.571ms; notlatency/P95/naturalquality. Default remainsforward; no graph/exportintegrity/newmodel changes. Frozen gate/review pending.
+Cycle74 reviewer FAIL P2diagnosticcopyalignment:accepted640x129hasgridheight33,costfootprint offsets256mod512. Standard1080/4K independentlyPASS andgate75PASS; not finalreviewpass. Fix diagnostic footprint alignment only, retainfailure and testoddgridheight before reviewerrevalidation.
+
+## Cycle74 independent final scopedPASS
+review_bidirectional_candidate: initialP2diagnosticfootprintalignmentFAIL repaired; independent640x129all4casesPASS/debug0 (novel191->73,good1411unchanged). Initial1080/4KindependentmatrixPASS remainsvalid. Finalphase7aea3d88148bf4e6b9c793cd99f95f7fb75PASSexit0; docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md. Reviewerfinalfingerprint2d3745d722cd9931e12d9ec6200d14d4d66f9924unchanged. Optionalsharedcapabilityonly; defaultforward, no graph/shader/exportintegrity/model changes. Retaincandidatependingnatural/changingframeNR/FGROI; fullGoalopen.
diff --git a/loop/STATE.json b/loop/STATE.json
index d90b2c57..43a3438a 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -76,19 +76,19 @@
}
],
"cycle": {
- "completed": 73,
+ "completed": 74,
"maximum": 120,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "Cycles71-73 moderate-luma scene reset and motion boundaries independently reviewed PASS; remaining Q6/Q7 optimization ongoing",
+ "currentTask": "Cycle74 optional bidirectional NVOF candidate and cost/occlusion evidence independently reviewed PASS; not default-integrated",
"lastGate": {
"name": "phase7",
"status": "passed",
"exitCode": 0,
- "evidence": "logs/delivery/55725c1cd58846c59342d5e624562773/result.json 41.568s;75checks"
+ "evidence": "logs/delivery/aea3d88148bf4e6b9c793cd99f95f7fb/result.json;75checks"
},
"lastFailureFingerprint": "",
"failureLedger": [
@@ -107,8 +107,8 @@
"Current USB2 1080p50 physical throughput passed; user perceived latency/audio/actual FG display cadence still need confirmation.",
"Public proprietary runtime distribution rights unresolved; local delivery only."
],
- "nextAction": "Q6 A/B bidirectional flow cost/benefit and FG occlusion quality; Q7 controlled depth response before model investment, RTX Video SR SDK dependency and natural SR reconstruction",
- "updatedAt": "2026-09-08T11:32:50.944787+00:00",
+ "nextAction": "Controlled depth input-response experiment before investing in model; remaining changing-frame/natural NR/FG and SR reconstruction evidence, RTXVideo SDK dependency",
+ "updatedAt": "2026-09-08T11:49:11.544171+00:00",
"deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",
"captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending",
"testInvocationLimitSeconds": 300,
@@ -130,7 +130,8 @@
"Cycle66 independent scoped PASS: image-e8c7b9377cd94f68bd50fb189bd8b49c 21.916s; feather2/32, disjoint, central tile seams. No product changes.",
"Cycles67-68 independent scoped PASS: temporal image6508c7cc PASS; optional R8d5f8d738/RGBAd9974360 reproduce expected-contract FAIL, no product integration.",
"Cycles69-70 independentPASS: motionshader/debug0; repairedresidual24constants; image29e690f3 andSR60A/B GBV0. Natural/FGquality still open.",
- "Cycles71-73 independent scopedPASS: scene14/motionverticalcostboundary; NR600NVOF594; actualFG600source594generated6hold1200output independentlydecoded, docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md"
+ "Cycles71-73 independent scopedPASS: scene14/motionverticalcostboundary; NR600NVOF594; actualFG600source594generated6hold1200output independentlydecoded, docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md",
+ "Cycle74 independent scopedPASS, docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md:360/1080/4K controlledbidirectional plus640x129alignmentfix; no defaultintegration"
],
"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb",
"localDelivery": "capture_fix_candidate_needs_review",
@@ -268,8 +269,8 @@
"testInvocationLimitSeconds": 300,
"productModified": true,
"consecutiveBlockedGoalTurns": 0,
- "previousGoalTurnClassification": "progress: fixed residual harness P2; fused motion bounds/photometric validation implemented and independently tested",
- "currentGoalTurnClassification": "progress: motion corpus found all3authoredcuts missed; repaired moderate-luma scene reset and independently verified actual2Xboundaryholds",
+ "previousGoalTurnClassification": "progress: motion corpus found all3authoredcuts missed; repaired moderate-luma scene reset and independently verified actual2Xboundaryholds",
+ "currentGoalTurnClassification": "progress: actual sharedNVOFBOTH validated, constructedocclusion benefitandcost measured, diagnosticoddheightP2fixed andindependentlyreviewed",
"controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization",
"diagnosticFindings": [
"Q7 read-only dependency check: RTXVideoSDK not present in third_party_local; official1.1download redirects NVIDIA login. Localdepthfile vitl is Large, not permitted Small; no verified Small ONNX/provider. No dependency integrated or performance claimed."
diff --git a/src/ngx/NvOfSession.cpp b/src/ngx/NvOfSession.cpp
index 76e098ad..8a41830d 100644
--- a/src/ngx/NvOfSession.cpp
+++ b/src/ngx/NvOfSession.cpp
@@ -45,11 +45,13 @@ bool NvOfSession::initialize(ID3D12Device* device,
// WITHOUT destroying or altering that session.
if (device == nullptr || inputA == nullptr || inputB == nullptr ||
flowOut == nullptr || costOut == nullptr ||
- desc.inFence == nullptr || desc.outFence == nullptr) {
+ desc.inFence == nullptr || desc.outFence == nullptr ||
+ ((desc.reverseFlow == nullptr) != (desc.reverseCost == nullptr))) {
log::error("nvof-session", std::format(
- "initialize rejected: device={} inputA={} inputB={} flowOut={} costOut={} inFence={} outFence={}",
+ "initialize rejected: device={} inputA={} inputB={} flowOut={} costOut={} inFence={} outFence={} reversePairValid={}",
device ? 1 : 0, inputA ? 1 : 0, inputB ? 1 : 0, flowOut ? 1 : 0,
- costOut ? 1 : 0, desc.inFence ? 1 : 0, desc.outFence ? 1 : 0));
+ costOut ? 1 : 0, desc.inFence ? 1 : 0, desc.outFence ? 1 : 0,
+ (desc.reverseFlow == nullptr) == (desc.reverseCost == nullptr)));
status = Status::InvalidArgument;
return false;
}
@@ -224,6 +226,17 @@ bool NvOfSession::initialize(ID3D12Device* device,
status = Status::InvalidArgument;
return false;
}
+ if(desc.reverseFlow){
+ const auto rf=desc.reverseFlow->GetDesc(),rc=desc.reverseCost->GetDesc();
+ const bool valid=rf.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D&&rc.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D&&
+ rf.Format==DXGI_FORMAT_R16G16_SINT&&rc.Format==DXGI_FORMAT_R8_UINT&&
+ rf.Width==gridW_&&rf.Height==gridH_&&rc.Width==gridW_&&rc.Height==gridH_&&
+ rf.DepthOrArraySize==1&&rc.DepthOrArraySize==1&&rf.MipLevels==1&&rc.MipLevels==1&&
+ rf.SampleDesc.Count==1&&rc.SampleDesc.Count==1&&
+ desc.reverseFlow!=flowOut&&desc.reverseCost!=costOut;
+ log::info("nvof-session",std::format("reverse contract valid={} flowFormat={} costFormat={} extent={}x{} costExtent={}x{}",valid,int(rf.Format),int(rc.Format),rf.Width,rf.Height,rc.Width,rc.Height));
+ if(!valid){status=Status::InvalidArgument;return false;}
+ }
}
NV_OF_INIT_PARAMS init{};
@@ -240,14 +253,15 @@ bool NvOfSession::initialize(ID3D12Device* device,
init.enableExternalHints = NV_OF_FALSE;
init.enableOutputCost = NV_OF_TRUE; // cost is mandatory (explicit costOut param)
init.hPrivData = nullptr;
- init.predDirection = NV_OF_PRED_DIRECTION_FORWARD;
+ init.predDirection = desc.reverseFlow ? NV_OF_PRED_DIRECTION_BOTH : NV_OF_PRED_DIRECTION_FORWARD;
+ log::info("nvof-session",std::format("prediction direction={} (1=forward,2=both)",int(init.predDirection)));
init.enableGlobalFlow = NV_OF_FALSE;
init.inputBufferFormat = NV_OF_BUFFER_FORMAT_ABGR8;
// Output contract: SHORT2 (S10.5) at grid extent; the caller registers
// an R16G16_SINT grid-extent resource as flowOut (never half-float).
const NV_OF_STATUS initSt = fn_->list.nvOFInit(ofHandle, &init);
- log::info("nvof-session", std::format("nvOFInit status={} ({}x{} grid{} fwd ABGR8 flowExtent={}x{})",
- static_cast<int>(initSt), desc.width, desc.height, grid, gridW_, gridH_));
+ log::info("nvof-session", std::format("nvOFInit status={} ({}x{} grid{} direction={} ABGR8 flowExtent={}x{})",
+ static_cast<int>(initSt), desc.width, desc.height, grid, int(init.predDirection), gridW_, gridH_));
if (initSt != NV_OF_SUCCESS) {
log::error("nvof-session", std::format("nvOFInit failed status={}", int(initSt)));
status = Status::DeviceFailure;
@@ -267,6 +281,8 @@ bool NvOfSession::initialize(ID3D12Device* device,
if (us == NV_OF_SUCCESS) h = nullptr;
};
auto rollbackAll = [&]() {
+ unregisterOne(hReverseCost_, "reverseCost");
+ unregisterOne(hReverseFlow_, "reverseFlow");
unregisterOne(hCost_, "costOut");
unregisterOne(hFlow_, "flowOut");
unregisterOne(hInputB_, "inputB");
@@ -291,7 +307,9 @@ bool NvOfSession::initialize(ID3D12Device* device,
if (!registerResource(inputA, hInputA_, "inputA") ||
!registerResource(inputB, hInputB_, "inputB") ||
!registerResource(flowOut, hFlow_, "flowOut") ||
- !registerResource(costOut, hCost_, "costOut")) {
+ !registerResource(costOut, hCost_, "costOut") ||
+ (desc.reverseFlow && (!registerResource(desc.reverseFlow,hReverseFlow_,"reverseFlow") ||
+ !registerResource(desc.reverseCost,hReverseCost_,"reverseCost")))) {
status = Status::DeviceFailure;
return false;
}
@@ -328,6 +346,8 @@ bool NvOfSession::execute(uint64_t inValue, Status& status)
out.outputBuffer = reinterpret_cast<NvOfBufferT>(hFlow_);
out.outputCostBuffer = reinterpret_cast<NvOfBufferT>(hCost_);
+ out.bwdOutputBuffer = reinterpret_cast<NvOfBufferT>(hReverseFlow_);
+ out.bwdOutputCostBuffer = reinterpret_cast<NvOfBufferT>(hReverseCost_);
outFencePoint.fence = outFence_;
outFencePoint.value = nextOutValue_;
out.fencePoint = &outFencePoint;
@@ -369,6 +389,8 @@ bool NvOfSession::unregisterAll(Status& status)
if (st == NV_OF_SUCCESS) h = nullptr;
else allOk = false;
};
+ unregisterOne(hReverseCost_, "reverseCost");
+ unregisterOne(hReverseFlow_, "reverseFlow");
unregisterOne(hCost_, "costOut");
unregisterOne(hFlow_, "flowOut");
unregisterOne(hInputB_, "inputB");
@@ -391,6 +413,8 @@ void NvOfSession::shutdown()
(st == NV_OF_SUCCESS ? log::info : log::error)("nvof-session", std::format("unregister {} status={}", name, static_cast<int>(st)));
if (st == NV_OF_SUCCESS) h = nullptr;
};
+ unregister(hReverseCost_, "reverseCost");
+ unregister(hReverseFlow_, "reverseFlow");
unregister(hCost_, "costOut");
unregister(hFlow_, "flowOut");
unregister(hInputB_, "inputB");
@@ -403,6 +427,7 @@ void NvOfSession::shutdown()
}
hInputA_ = hInputB_ = hFlow_ = nullptr;
hCost_ = nullptr;
+ hReverseFlow_ = hReverseCost_ = nullptr;
delete fn_;
fn_ = nullptr;
if (dll_ != nullptr) {
diff --git a/tests/integration/BidirectionalFlowTests.cpp b/tests/integration/BidirectionalFlowTests.cpp
new file mode 100644
index 00000000..33dff940
--- /dev/null
+++ b/tests/integration/BidirectionalFlowTests.cpp
@@ -0,0 +1,105 @@
+#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/ngx/NvOfSession.h"
+#include <d3d12sdklayers.h>
+#include <array>
+#include <chrono>
+#include <cmath>
+#include <cstring>
+#include <functional>
+#include <iostream>
+using namespace veyra;using namespace veyra::pipeline;
+namespace {
+struct Cleanup{std::function<void()> fn;~Cleanup(){fn();}};
+float texture(int x,int y){
+ // Deterministic, non-periodic broad-band field, translated without resampling.
+ uint32_t v=uint32_t(x/4)*747796405u+uint32_t(y/4)*2891336453u+12345u;
+ v=((v>>((v>>28)+4))^v)*277803737u;v=(v>>22)^v;
+ return float(40+(v%176));
+}
+double median(std::vector<double> x){std::sort(x.begin(),x.end());return x[x.size()/2];}
+int run(unsigned w,unsigned h,bool both,bool occlusion){
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
+ const unsigned gw=(w+3)/4,gh=(h+3)/4;
+ std::array<ComPtr<ID3D12Resource>,6> tex;
+ for(unsigned i=0;i<6;++i)tex[i]=makeTexture(ctx.device(),i<2?w:gw,i<2?h:gh,i<2?DXGI_FORMAT_B8G8R8A8_UNORM:i%2==0?DXGI_FORMAT_R16G16_SINT:DXGI_FORMAT_R8_UINT,false);
+ for(auto& t:tex)if(!t)return 2;
+ ComPtr<ID3D12Fence> ready;if(FAILED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&ready))))return 2;
+ ngx::NvOfSession session;
+ bool cleaned=false,cleanupOk=true;
+ Cleanup cleanup{[&]{if(cleaned)return;cleaned=true;cleanupOk=ring.drainQueue();if(session.initialized())cleanupOk=session.unregisterAll(st)&&cleanupOk;for(auto& t:tex)t.Reset();session.shutdown();}};
+ ngx::NvOfSession::Desc desc;desc.width=w;desc.height=h;desc.inFence=ctx.fence();desc.outFence=ready.Get();
+ if(both){desc.reverseFlow=tex[4].Get();desc.reverseCost=tex[5].Get();}
+ if(both){
+ auto invalid=desc;invalid.reverseFlow=tex[5].Get();
+ if(session.initialize(ctx.device(),tex[0].Get(),tex[1].Get(),tex[2].Get(),tex[3].Get(),invalid,st)||session.initialized()||st!=Status::InvalidArgument)return 2;
+ session.shutdown();invalid=desc;invalid.reverseFlow=tex[2].Get();
+ if(session.initialize(ctx.device(),tex[0].Get(),tex[1].Get(),tex[2].Get(),tex[3].Get(),invalid,st)||session.initialized()||st!=Status::InvalidArgument)return 2;
+ session.shutdown();
+ }
+ if(!session.initialize(ctx.device(),tex[0].Get(),tex[1].Get(),tex[2].Get(),tex[3].Get(),desc,st))return 2;
+ // A malformed paired call must preserve the initialized session.
+ auto malformed=desc;malformed.reverseFlow=tex[4].Get();malformed.reverseCost=nullptr;
+ if(session.initialize(ctx.device(),tex[0].Get(),tex[1].Get(),tex[2].Get(),tex[3].Get(),malformed,st)||!session.initialized())return 2;
+ std::vector<ComPtr<ID3D12Resource>> uploads;StateTracker states;uint32_t slot=0;auto* list=ring.acquireNext(slot,st);if(!list)return 2;
+ const unsigned pitch=(w*4+255)&~255u;
+ for(unsigned i=0;i<2;++i){
+ auto up=makeUploadBuffer(ctx.device(),size_t(pitch)*h);void* ptr=nullptr;if(!up||FAILED(up->Map(0,nullptr,&ptr)))return 2;
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ auto* p=static_cast<uint8_t*>(ptr)+size_t(y)*pitch+x*4;
+ const bool novel=occlusion&&i==1&&x>=w/3&&x<w*2/3&&y>=h/3&&y<h*2/3;
+ uint8_t v=uint8_t(novel?128:texture(int(x)+(i?8:0),int(y)));
+ p[0]=p[1]=p[2]=v;p[3]=255;
+ }
+ up->Unmap(0,nullptr);states.transition(list,tex[i].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=tex[i].Get();a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=up.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;b.PlacedFootprint.Footprint={DXGI_FORMAT_B8G8R8A8_UNORM,w,h,1,pitch};list->CopyTextureRegion(&a,0,0,0,&b,nullptr);states.transition(list,tex[i].Get(),D3D12_RESOURCE_STATE_COMMON);uploads.push_back(up);
+ }
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ auto batch=[&](unsigned n){for(unsigned i=0;i<n;++i)if(!session.execute(ring.lastSignaledValue(),st))return false;
+ if(FAILED(ctx.directQueue()->Wait(ready.Get(),session.nextOutValue()-1)))return false;
+ return ring.drainQueue();};
+ if(!batch(4))return 2;
+ const auto start=std::chrono::steady_clock::now();if(!batch(60))return 2;
+ const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/60;
+ const unsigned fp=(gw*4+255)&~255u,cp=(gw+255)&~255u;
+ std::array<size_t,4> offsets{};size_t bytes=0;
+ for(unsigned i=0;i<4;++i){
+ offsets[i]=(bytes+D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1)&~size_t(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1);
+ bytes=offsets[i]+size_t(i%2?cp:fp)*gh;
+ }
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=bytes;bd.Height=1;bd.DepthOrArraySize=bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ ComPtr<ID3D12Resource> rb;if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&rb))))return 2;
+ list=ring.acquireNext(slot,st);if(!list)return 2;
+ for(unsigned i=0;i<(both?4u:2u);++i){states.transition(list,tex[i+2].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=tex[i+2].Get();a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=rb.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;b.PlacedFootprint.Offset=offsets[i];b.PlacedFootprint.Footprint={tex[i+2]->GetDesc().Format,gw,gh,1,i%2?cp:fp};list->CopyTextureRegion(&b,0,0,0,&a,nullptr);states.transition(list,tex[i+2].Get(),D3D12_RESOURCE_STATE_COMMON);}
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ void* ptr=nullptr;D3D12_RANGE range{0,bytes};if(FAILED(rb->Map(0,&range,&ptr)))return 2;
+ auto vectorAt=[&](unsigned which,unsigned x,unsigned y){auto* p=reinterpret_cast<int16_t*>(static_cast<uint8_t*>(ptr)+offsets[which]+y*fp+x*4);return std::array<float,2>{p[0]/32.f,p[1]/32.f};};
+ std::vector<double> errors,reverseErrors;
+ unsigned novelTotal=0,novelBase=0,novelConsistent=0,goodTotal=0,goodBase=0,goodConsistent=0;
+ for(unsigned y=8;y+8<gh;++y)for(unsigned x=8;x+8<gw;++x){
+ const float px=float(x*4),py=float(y*4);auto v=vectorAt(0,x,y);float qx=px+v[0],qy=py+v[1];
+ const bool novel=occlusion&&px>=w/3+8&&px<w*2/3-8&&py>=h/3+8&&py<h*2/3-8;
+ const bool clean=!occlusion||px<w/3-16||px>=w*2/3+16||py<h/3-16||py>=h*2/3+16;
+ if(clean){errors.push_back(std::hypot(v[0]-8,v[1]));if(both){auto r=vectorAt(2,x,y);reverseErrors.push_back(std::hypot(r[0]+8,r[1]));}}
+ if(!novel&&!clean)continue;
+ bool base=static_cast<uint8_t*>(ptr)[offsets[1]+y*cp+x]<32&&qx>=0&&qx<w-1&&qy>=0&&qy<h-1;
+ // Same encoded-luma endpoint test as product's rejection boundary.
+ if(base){int ix=int(qx),iy=int(qy);float tx=qx-ix,ty=qy-iy;float a=texture(ix,iy)*(1-tx)+texture(ix+1,iy)*tx,b=texture(ix,iy+1)*(1-tx)+texture(ix+1,iy+1)*tx;
+ float current=novel?128:texture(int(px)+8,int(py));base=std::abs(a*(1-ty)+b*ty-current)/255<.15f;}
+ bool consistent=base;
+ if(both&&base){unsigned rx=std::min(unsigned(qx/4),gw-1),ry=std::min(unsigned(qy/4),gh-1);auto r=vectorAt(2,rx,ry);consistent=static_cast<uint8_t*>(ptr)[offsets[3]+ry*cp+rx]<32&&std::hypot(v[0]+r[0],v[1]+r[1])<1.5f;}
+ if(novel){++novelTotal;novelBase+=base;novelConsistent+=consistent;}else{++goodTotal;goodBase+=base;goodConsistent+=consistent;}
+ }
+ D3D12_RANGE written{0,0};rb->Unmap(0,&written);
+ bool ok=!errors.empty()&&median(errors)<=1&&(!both||median(reverseErrors)<=1);
+ UINT64 reverseBytes=0;for(unsigned i=4;i<6;++i){auto d=tex[i]->GetDesc();reverseBytes+=ctx.device()->GetResourceAllocationInfo(0,1,&d).SizeInBytes;}
+ cleanup.fn();ok=ok&&cleanupOk;
+ ComPtr<ID3D12InfoQueue> iq;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&iq))))return 2;unsigned debugErrors=0;
+ for(UINT64 i=0;i<iq->GetNumStoredMessages();++i){SIZE_T n=0;if(FAILED(iq->GetMessage(i,nullptr,&n)))return 2;std::vector<uint8_t>b(n);auto* m=reinterpret_cast<D3D12_MESSAGE*>(b.data());if(FAILED(iq->GetMessage(i,m,&n)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++debugErrors;std::cerr<<m->pDescription<<std::endl;}}
+ std::cout<<"BIDIRECTIONAL width="<<w<<" height="<<h<<" both="<<both<<" occlusion="<<occlusion<<" meanBatchMs="<<ms<<" reverseAllocationBytes="<<reverseBytes<<" medianEpe="<<median(errors)<<" reverseMedianEpe="<<(both?median(reverseErrors):-1)<<" novel="<<novelTotal<<" novelBaseAccepted="<<novelBase<<" novelConsistent="<<novelConsistent<<" good="<<goodTotal<<" goodBaseAccepted="<<goodBase<<" goodConsistent="<<goodConsistent<<" debugErrors="<<debugErrors<<" pass="<<(ok&&!debugErrors)<<std::endl;
+ return ok&&!debugErrors?0:1;
+}
+}
+int main(int argc,char** argv){unsigned w=argc>1?unsigned(std::stoi(argv[1])):640,h=argc>2?unsigned(std::stoi(argv[2])):360;if(w<128||h<128||w>3840||h>2160)return 2;for(bool occlusion:{false,true})for(bool both:{false,true}){int r=run(w,h,both,occlusion);if(r)return r;}return 0;}