diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 18:48:12 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 18:48:12 -0500 |
| commit | fb2afdccc2314d7b5a59fac10e6d6df7f5df35ab (patch) | |
| tree | 9e0b7e2e39b42823f148d135ce781e57fab52155 /runtime/src | |
| parent | 862890c893eb19eb39eb2fd95e7786e42ff4b18c (diff) | |
| parent | 864337351bc11a250db77c2fcdd3ba6f1d0f455f (diff) | |
Merge main into RT-QUEUE18 (#403)
Merged on top of the merge made for #396 (main 507029d1e plus RT-QUEUE35,
RT-ALLOC9 and RT-LIST139). No conflicts.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/active_input.h | 17 | ||||
| -rw-r--r-- | runtime/src/arena_size.h | 5 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 15 | ||||
| -rw-r--r-- | runtime/src/cpu_emulation.h | 97 | ||||
| -rw-r--r-- | runtime/src/crt_timed_wait.cpp | 29 | ||||
| -rw-r--r-- | runtime/src/frame_pacer.h | 224 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 6 | ||||
| -rw-r--r-- | runtime/src/mods.h | 4 | ||||
| -rw-r--r-- | runtime/src/retire_tickets.h | 16 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 23 | ||||
| -rw-r--r-- | runtime/src/statistics_sum.comp | 10 | ||||
| -rw-r--r-- | runtime/src/statistics_sum_spirv.h | 65 | ||||
| -rw-r--r-- | runtime/src/uav_clear.h | 4 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 100 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 243 | ||||
| -rw-r--r-- | runtime/src/vulkan_scratch.h | 16 | ||||
| -rw-r--r-- | runtime/src/xdxr_build.h | 14 | ||||
| -rw-r--r-- | runtime/src/xdxr_descs.h | 7 |
18 files changed, 697 insertions, 198 deletions
diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h index c0f7451b1..55b67d3bb 100644 --- a/runtime/src/active_input.h +++ b/runtime/src/active_input.h | |||
| @@ -95,7 +95,8 @@ public: | |||
| 95 | const InputEdge edge = edge_between(it->second, now); | 95 | const InputEdge edge = edge_between(it->second, now); |
| 96 | it->second = now; | 96 | it->second = now; |
| 97 | if (edge == InputEdge::None || family == tracked_) return InputEdge::None; | 97 | if (edge == InputEdge::None || family == tracked_) return InputEdge::None; |
| 98 | if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; | 98 | if (changed_once_ && (time_us < changed_at_ || time_us - changed_at_ < thresholds_.min_switch_us)) |
| 99 | return InputEdge::None; | ||
| 99 | const InputFamily before = active(); | 100 | const InputFamily before = active(); |
| 100 | tracked_ = family; | 101 | tracked_ = family; |
| 101 | changed_at_ = time_us; | 102 | changed_at_ = time_us; |
| @@ -125,11 +126,17 @@ private: | |||
| 125 | InputEdge edge_between(const InputSample& was, const InputSample& now) const { | 126 | InputEdge edge_between(const InputSample& was, const InputSample& now) const { |
| 126 | if (now.buttons & ~was.buttons) return InputEdge::Button; | 127 | if (now.buttons & ~was.buttons) return InputEdge::Button; |
| 127 | const float t = thresholds_.trigger; | 128 | const float t = thresholds_.trigger; |
| 128 | if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) | 129 | const auto trigger_rose = [t](float prev, float cur) { |
| 130 | return std::isfinite(prev) && std::isfinite(cur) && prev <= t && cur > t; | ||
| 131 | }; | ||
| 132 | if (trigger_rose(was.left_trigger, now.left_trigger) || trigger_rose(was.right_trigger, now.right_trigger)) | ||
| 129 | return InputEdge::Trigger; | 133 | return InputEdge::Trigger; |
| 130 | const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; | 134 | const auto stick_left = [this](float px, float py, float cx, float cy) { |
| 131 | if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || | 135 | if (!std::isfinite(px) || !std::isfinite(py) || !std::isfinite(cx) || !std::isfinite(cy)) return false; |
| 132 | (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) | 136 | return std::hypot(px, py) <= thresholds_.stick && std::hypot(cx, cy) > thresholds_.stick; |
| 137 | }; | ||
| 138 | if (stick_left(was.left_x, was.left_y, now.left_x, now.left_y) || | ||
| 139 | stick_left(was.right_x, was.right_y, now.right_x, now.right_y)) | ||
| 133 | return InputEdge::Stick; | 140 | return InputEdge::Stick; |
| 134 | return InputEdge::None; | 141 | return InputEdge::None; |
| 135 | } | 142 | } |
diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h index 8f4ca4caf..196b03e3e 100644 --- a/runtime/src/arena_size.h +++ b/runtime/src/arena_size.h | |||
| @@ -60,7 +60,10 @@ struct ArenaSize { | |||
| 60 | // invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). | 60 | // invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). |
| 61 | inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { | 61 | inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { |
| 62 | VkDeviceSize megabytes = kArenaDefaultMiB; | 62 | VkDeviceSize megabytes = kArenaDefaultMiB; |
| 63 | if (env && *env) megabytes = std::clamp<VkDeviceSize>(std::strtoull(env, nullptr, 10), kArenaMinMiB, kArenaMaxMiB); | 63 | // Signed, so "-5" clamps to the floor (strtoull wraps it to a huge value, which clamps to the maximum). |
| 64 | if (env && *env) | ||
| 65 | megabytes = VkDeviceSize(std::clamp<long long>(std::strtoll(env, nullptr, 10), (long long)kArenaMinMiB, | ||
| 66 | (long long)kArenaMaxMiB)); | ||
| 64 | ArenaSize size; | 67 | ArenaSize size; |
| 65 | size.requested = size.bytes = megabytes * kArenaMiB; | 68 | size.requested = size.bytes = megabytes * kArenaMiB; |
| 66 | VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; | 69 | VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; |
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 595110f36..c28904efe 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -414,6 +414,15 @@ struct DrawViews { | |||
| 414 | std::uint32_t render_target_count = 8; | 414 | std::uint32_t render_target_count = 8; |
| 415 | }; | 415 | }; |
| 416 | 416 | ||
| 417 | // Shared across draws that keep the same multi-viewport / multi-scissor state (null for the common 1-viewport case). | ||
| 418 | struct DrawViewports { | ||
| 419 | static constexpr std::uint32_t max_count = 16; | ||
| 420 | std::array<Viewport, max_count> viewports{}; | ||
| 421 | std::uint32_t viewport_count = 0; | ||
| 422 | std::array<Rect, max_count> scissors{}; | ||
| 423 | std::uint32_t scissor_count = 0; | ||
| 424 | }; | ||
| 425 | |||
| 417 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: | 426 | // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: |
| 418 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the | 427 | // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the |
| 419 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw | 428 | // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw |
| @@ -440,6 +449,7 @@ struct Draw { | |||
| 440 | std::int32_t base_vertex = 0; | 449 | std::int32_t base_vertex = 0; |
| 441 | std::uint32_t first_instance = 0; | 450 | std::uint32_t first_instance = 0; |
| 442 | bool mesh = false; | 451 | bool mesh = false; |
| 452 | std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound | ||
| 443 | }; | 453 | }; |
| 444 | 454 | ||
| 445 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. | 455 | // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. |
| @@ -691,10 +701,11 @@ public: | |||
| 691 | return append(barrier); | 701 | return append(barrier); |
| 692 | } | 702 | } |
| 693 | 703 | ||
| 704 | // LayoutAfter UNDEFINED is legal: the subresources' contents are no longer needed, as before their memory is | ||
| 705 | // aliased (the retail title ends a depth buffer's use this way, #984; WARP closes such a list, | ||
| 706 | // d3d12_close_parity_test). Replay keeps the image's Vulkan layout and orders the accesses only. | ||
| 694 | bool barrier(const TextureBarrier& barrier) { | 707 | bool barrier(const TextureBarrier& barrier) { |
| 695 | if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; | 708 | if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; |
| 696 | if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined) | ||
| 697 | return false; | ||
| 698 | if (barrier.flags & ~texture_barrier_discard) return false; | 709 | if (barrier.flags & ~texture_barrier_discard) return false; |
| 699 | if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; | 710 | if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; |
| 700 | if (barrier.sync_after == d3d12_sync::split) return !closed_; | 711 | if (barrier.sync_after == d3d12_sync::split) return !closed_; |
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index fac13eeee..8df3b55d0 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h | |||
| @@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt | |||
| 272 | return true; | 272 | return true; |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | inline uint64_t gpr_read(const CONTEXT* c, int r) { | ||
| 276 | switch (r) { | ||
| 277 | case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx; | ||
| 278 | case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi; | ||
| 279 | case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11; | ||
| 280 | case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15; | ||
| 281 | default: return 0; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 285 | enum class ClzeroLoopResult { no_match, ok, faulted }; | ||
| 286 | |||
| 287 | inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) { | ||
| 288 | const uint64_t diff = lhs - rhs; | ||
| 289 | uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11) | ||
| 290 | if (lhs < rhs) flags |= 0x1u; // CF | ||
| 291 | uint8_t lo8 = static_cast<uint8_t>(diff); | ||
| 292 | lo8 ^= lo8 >> 4; | ||
| 293 | lo8 ^= lo8 >> 2; | ||
| 294 | lo8 ^= lo8 >> 1; | ||
| 295 | if ((lo8 & 1u) == 0) flags |= 0x4u; // PF | ||
| 296 | if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF | ||
| 297 | if (diff == 0) flags |= 0x40u; // ZF | ||
| 298 | if (diff >> 63) flags |= 0x80u; // SF | ||
| 299 | if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF | ||
| 300 | c->EFlags = flags; | ||
| 301 | } | ||
| 302 | |||
| 303 | // Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes). | ||
| 304 | // Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line. | ||
| 305 | inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) { | ||
| 306 | if (avail < 12) return ClzeroLoopResult::no_match; | ||
| 307 | if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match; | ||
| 308 | if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match; | ||
| 309 | if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) | ||
| 310 | return ClzeroLoopResult::no_match; | ||
| 311 | if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match; | ||
| 312 | |||
| 313 | const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1); | ||
| 314 | if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match; | ||
| 315 | |||
| 316 | const uint64_t start = c->Rax; | ||
| 317 | const uint64_t limit = gpr_read(c, limit_reg); | ||
| 318 | if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match; | ||
| 319 | |||
| 320 | uint64_t total = (limit - start + 63) & ~uint64_t(63); | ||
| 321 | constexpr uint64_t kMaxBatch = uint64_t(64) << 20; | ||
| 322 | if (total > kMaxBatch) total = kMaxBatch; | ||
| 323 | const uint64_t end = start + total; | ||
| 324 | |||
| 325 | for (uint64_t cur = start; cur < end;) { | ||
| 326 | const DWORD err = writable(cur); | ||
| 327 | if (err) { | ||
| 328 | if (cur > start) { | ||
| 329 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start)); | ||
| 330 | c->Rax = cur; | ||
| 331 | apply_cmp_flags(c, cur, limit); | ||
| 332 | } | ||
| 333 | if (fault) { | ||
| 334 | std::memset(fault, 0, sizeof *fault); | ||
| 335 | fault->ExceptionCode = err; | ||
| 336 | fault->NumberParameters = 2; | ||
| 337 | fault->ExceptionInformation[0] = 1; | ||
| 338 | fault->ExceptionInformation[1] = ULONG_PTR(cur); | ||
| 339 | } | ||
| 340 | return ClzeroLoopResult::faulted; | ||
| 341 | } | ||
| 342 | const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000; | ||
| 343 | cur = next_page < end ? next_page : end; | ||
| 344 | } | ||
| 345 | |||
| 346 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total)); | ||
| 347 | c->Rax = end; | ||
| 348 | apply_cmp_flags(c, end, limit); | ||
| 349 | if (end >= limit) c->Rip += 12; | ||
| 350 | return ClzeroLoopResult::ok; | ||
| 351 | } | ||
| 352 | |||
| 275 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | 353 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { |
| 276 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; | 354 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; |
| 277 | CONTEXT* c = info->ContextRecord; | 355 | CONTEXT* c = info->ContextRecord; |
| @@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | |||
| 281 | const Decoded d = decode(code, avail); | 359 | const Decoded d = decode(code, avail); |
| 282 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; | 360 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; |
| 283 | EXCEPTION_RECORD fault; | 361 | EXCEPTION_RECORD fault; |
| 362 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { | ||
| 363 | const uint64_t fault_rip = c->Rip; | ||
| 364 | const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault); | ||
| 365 | if (lr == ClzeroLoopResult::ok) { | ||
| 366 | if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) | ||
| 367 | std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), | ||
| 368 | reinterpret_cast<void*>(fault_rip)); | ||
| 369 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 370 | } | ||
| 371 | if (lr == ClzeroLoopResult::faulted) { | ||
| 372 | EXCEPTION_RECORD* r = info->ExceptionRecord; | ||
| 373 | r->ExceptionCode = fault.ExceptionCode; | ||
| 374 | r->ExceptionFlags = 0; | ||
| 375 | r->NumberParameters = fault.NumberParameters; | ||
| 376 | r->ExceptionInformation[0] = fault.ExceptionInformation[0]; | ||
| 377 | r->ExceptionInformation[1] = fault.ExceptionInformation[1]; | ||
| 378 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 379 | } | ||
| 380 | } | ||
| 284 | if (!apply(d, c, &fault)) { | 381 | if (!apply(d, c, &fault)) { |
| 285 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers | 382 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers |
| 286 | // see it instead of the #UD (RIP still points at the instruction). | 383 | // see it instead of the #UD (RIP still points at the instruction). |
diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp index 6441f2868..cd26e7d3a 100644 --- a/runtime/src/crt_timed_wait.cpp +++ b/runtime/src/crt_timed_wait.cpp | |||
| @@ -25,7 +25,9 @@ extern "C" { | |||
| 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). | 25 | // absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). |
| 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; | 26 | __declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; |
| 27 | 27 | ||
| 28 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 28 | namespace { |
| 29 | |||
| 30 | _Thrd_result timedwait_for_impl(_Cnd_t cond, _Mtx_t mtx, unsigned int ms, bool unchecked) noexcept { | ||
| 29 | _timespec64 deadline{}; | 31 | _timespec64 deadline{}; |
| 30 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; | 32 | if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; |
| 31 | deadline.tv_sec += ms / 1000; | 33 | deadline.tv_sec += ms / 1000; |
| @@ -34,13 +36,32 @@ _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, uns | |||
| 34 | deadline.tv_sec += 1; | 36 | deadline.tv_sec += 1; |
| 35 | deadline.tv_nsec -= 1000000000L; | 37 | deadline.tv_nsec -= 1000000000L; |
| 36 | } | 38 | } |
| 37 | // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves. | 39 | // Preserve the caller's LastError across the wait while detecting OS timer timeouts cleanly. |
| 38 | return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | 40 | const DWORD saved_error = GetLastError(); |
| 41 | SetLastError(ERROR_SUCCESS); | ||
| 42 | const auto res = static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); | ||
| 43 | const DWORD wait_error = GetLastError(); | ||
| 44 | SetLastError(saved_error); | ||
| 45 | // msvcp140's _Cnd_timedwait checks _Xtime_diff_to_millis2(target, &now) == 0 after SleepConditionVariableSRW | ||
| 46 | // returns FALSE/ERROR_TIMEOUT, so an OS timer wake even <1 ms before `deadline` turns into _Thrd_result::_Success. | ||
| 47 | // STL wait_for/wait_until callers treat _Success from _Cnd_timedwait_for_unchecked as a notification/spurious | ||
| 48 | // wake (cv_status::no_timeout) instead of looping until steady_clock reaches the target; report _Timedout here | ||
| 49 | // so the caller checks steady_clock and waits for the remaining time. | ||
| 50 | if (unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT) { | ||
| 51 | return _Thrd_result::_Timedout; | ||
| 52 | } | ||
| 53 | return res; | ||
| 54 | } | ||
| 55 | |||
| 56 | } // namespace | ||
| 57 | |||
| 58 | _Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | ||
| 59 | return timedwait_for_impl(cond, mtx, ms, true); | ||
| 39 | } | 60 | } |
| 40 | 61 | ||
| 41 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. | 62 | // Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. |
| 42 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { | 63 | _Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { |
| 43 | return _Cnd_timedwait_for_unchecked(cond, mtx, ms); | 64 | return timedwait_for_impl(cond, mtx, ms, false); |
| 44 | } | 65 | } |
| 45 | 66 | ||
| 46 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { | 67 | void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { |
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index fa9c20df1..afeaf191e 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h | |||
| @@ -30,14 +30,17 @@ | |||
| 30 | // suspended) is unchanged. | 30 | // suspended) is unchanged. |
| 31 | 31 | ||
| 32 | #include <algorithm> | 32 | #include <algorithm> |
| 33 | #include <array> | ||
| 33 | #include <atomic> | 34 | #include <atomic> |
| 34 | #include <chrono> | 35 | #include <chrono> |
| 35 | #include <condition_variable> | 36 | #include <condition_variable> |
| 37 | #include <cstddef> | ||
| 36 | #include <cstdint> | 38 | #include <cstdint> |
| 37 | #include <deque> | 39 | #include <deque> |
| 38 | #include <functional> | 40 | #include <functional> |
| 39 | #include <limits> | 41 | #include <limits> |
| 40 | #include <mutex> | 42 | #include <mutex> |
| 43 | #include <vector> | ||
| 41 | 44 | ||
| 42 | namespace leonida { | 45 | namespace leonida { |
| 43 | 46 | ||
| @@ -102,8 +105,14 @@ private: | |||
| 102 | std::function<void()> wake_; | 105 | std::function<void()> wake_; |
| 103 | }; | 106 | }; |
| 104 | 107 | ||
| 105 | // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. | 108 | // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. Frame event |
| 109 | // kinds (0: origin, 1: vblank, 2: flip) and wait flags. | ||
| 106 | inline constexpr std::uint32_t frame_event_origin = 0; | 110 | inline constexpr std::uint32_t frame_event_origin = 0; |
| 111 | inline constexpr std::uint32_t frame_event_vblank = 1; | ||
| 112 | inline constexpr std::uint32_t frame_event_flip = 2; | ||
| 113 | inline constexpr std::uint32_t frame_event_count = 3; | ||
| 114 | // Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE). | ||
| 115 | inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2; | ||
| 107 | // Statistics types (bit mask). Interval and render entries are never produced here. | 116 | // Statistics types (bit mask). Interval and render entries are never produced here. |
| 108 | inline constexpr std::uint32_t stat_frame_interval = 0x01; | 117 | inline constexpr std::uint32_t stat_frame_interval = 0x01; |
| 109 | inline constexpr std::uint32_t stat_frame_event = 0x02; | 118 | inline constexpr std::uint32_t stat_frame_event = 0x02; |
| @@ -143,6 +152,25 @@ struct FrameStatistic { | |||
| 143 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) | 152 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) |
| 144 | }; | 153 | }; |
| 145 | 154 | ||
| 155 | // Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6). | ||
| 156 | inline constexpr std::size_t frame_pacing_window = 1024; | ||
| 157 | |||
| 158 | // Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target). | ||
| 159 | struct FramePacingSummary { | ||
| 160 | std::uint64_t frames = 0; // total presented frames recorded | ||
| 161 | std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window) | ||
| 162 | std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped) | ||
| 163 | double mean_us = 0.0; // mean present-to-present interval over `samples` | ||
| 164 | double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0) | ||
| 165 | std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us | ||
| 166 | std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us | ||
| 167 | std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us | ||
| 168 | std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer | ||
| 169 | std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us | ||
| 170 | std::uint64_t latency_p95_us = 0; // nearest-rank 95th percentile origin-to-present latency in us | ||
| 171 | std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us | ||
| 172 | }; | ||
| 173 | |||
| 146 | class FramePacer { | 174 | class FramePacer { |
| 147 | public: | 175 | public: |
| 148 | explicit FramePacer(FrameClock& clock) : clock_(clock) { | 176 | explicit FramePacer(FrameClock& clock) : clock_(clock) { |
| @@ -177,38 +205,42 @@ public: | |||
| 177 | latency_ = std::max(latency, 1u); | 205 | latency_ = std::max(latency, 1u); |
| 178 | epoch_us_ = clock_.now_us(); | 206 | epoch_us_ = clock_.now_us(); |
| 179 | interval_set_ = true; | 207 | interval_set_ = true; |
| 180 | offset_us_ = std::min(offset_us_, period_us - 1); | 208 | for (std::uint32_t k = 0; k < frame_event_count; ++k) { |
| 181 | last_origin_ = 0; // origin 0 is the epoch itself, which has passed | 209 | event_offset_us_[k] = std::min(event_offset_us_[k], period_us - 1); |
| 210 | last_event_tick_[k] = 0; // tick 0 is the epoch itself, which has passed | ||
| 211 | } | ||
| 182 | cv_.notify_all(); | 212 | cv_.notify_all(); |
| 183 | return pacer_hr::ok; | 213 | return pacer_hr::ok; |
| 184 | } | 214 | } |
| 185 | 215 | ||
| 186 | // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. | 216 | // ScheduleFrameEventX(event, offset, ..., flags). Supports origin (0), vblank (1), and flip (2). |
| 187 | std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { | 217 | std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { |
| 188 | (void)flags; | 218 | (void)flags; |
| 189 | if (event != frame_event_origin) return pacer_hr::invalid_arg; | 219 | if (event >= frame_event_count) return pacer_hr::invalid_arg; |
| 190 | std::lock_guard guard(mutex_); | 220 | std::lock_guard guard(mutex_); |
| 191 | if (suspended_ || !interval_set_) return pacer_hr::invalid_state; | 221 | if (suspended_ || !interval_set_) return pacer_hr::invalid_state; |
| 192 | if (offset_us >= period_us_) return pacer_hr::invalid_arg; | 222 | if (offset_us >= period_us_) return pacer_hr::invalid_arg; |
| 193 | offset_us_ = offset_us; | 223 | event_offset_us_[event] = offset_us; |
| 194 | armed_ = true; | 224 | event_armed_[event] = true; |
| 195 | // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. | 225 | // The first event is the next one that has not come yet: tick n is due at epoch + n * period + offset. |
| 196 | const std::uint64_t now = clock_.now_us(); | 226 | const std::uint64_t now = clock_.now_us(); |
| 197 | last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; | 227 | last_event_tick_[event] = |
| 228 | now >= epoch_us_ + offset_us ? std::int64_t((now - epoch_us_ - offset_us) / period_us_) : 0; | ||
| 198 | cv_.notify_all(); | 229 | cv_.notify_all(); |
| 199 | return pacer_hr::ok; | 230 | return pacer_hr::ok; |
| 200 | } | 231 | } |
| 201 | 232 | ||
| 202 | // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames | 233 | // WaitFrameEventX(event, timeout, ..., flags, &token). Origin waits block until the next origin tick and while |
| 203 | // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left | 234 | // `latency` frames are in flight, issuing a consecutive token on success (or on timeout with |
| 204 | // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. | 235 | // frame_wait_flag_token_on_timeout, returning S_FALSE). Vblank/flip waits pace independently per event kind and |
| 236 | // leave `*token` untouched. | ||
| 205 | std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, | 237 | std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, |
| 206 | std::uint64_t* token) { | 238 | std::uint64_t* token) { |
| 207 | (void)flags; | 239 | if (event >= frame_event_count) return pacer_hr::invalid_arg; |
| 208 | if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; | 240 | if (event == frame_event_origin && !token) return pacer_hr::invalid_arg; |
| 209 | std::unique_lock lock(mutex_); | 241 | std::unique_lock lock(mutex_); |
| 210 | ++waiters_; | 242 | ++waiters_; |
| 211 | const std::int32_t result = wait_locked(lock, timeout_ms, token); | 243 | const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token); |
| 212 | if (--waiters_ == 0) cv_.notify_all(); | 244 | if (--waiters_ == 0) cv_.notify_all(); |
| 213 | return result; | 245 | return result; |
| 214 | } | 246 | } |
| @@ -301,8 +333,9 @@ public: | |||
| 301 | std::lock_guard guard(mutex_); | 333 | std::lock_guard guard(mutex_); |
| 302 | const std::uint64_t now = clock_.now_us(); | 334 | const std::uint64_t now = clock_.now_us(); |
| 303 | retire_locked(now); | 335 | retire_locked(now); |
| 336 | record_present_timing_locked(now, token); | ||
| 304 | last_presented_ = std::max(last_presented_, token); | 337 | last_presented_ = std::max(last_presented_, token); |
| 305 | if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once | 338 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once |
| 306 | for (Record& r : records_) | 339 | for (Record& r : records_) |
| 307 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } | 340 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } |
| 308 | return; | 341 | return; |
| @@ -330,8 +363,9 @@ public: | |||
| 330 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. | 363 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. |
| 331 | void note_untokened_present() { | 364 | void note_untokened_present() { |
| 332 | std::lock_guard guard(mutex_); | 365 | std::lock_guard guard(mutex_); |
| 333 | if (!interval_set_ || !armed_ || uncapped_) return; | ||
| 334 | const std::uint64_t now = clock_.now_us(); | 366 | const std::uint64_t now = clock_.now_us(); |
| 367 | record_present_timing_locked(now, 0); | ||
| 368 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 335 | retire_locked(now); | 369 | retire_locked(now); |
| 336 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 370 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; |
| 337 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | 371 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; |
| @@ -344,7 +378,9 @@ public: | |||
| 344 | void suspend() { | 378 | void suspend() { |
| 345 | std::lock_guard guard(mutex_); | 379 | std::lock_guard guard(mutex_); |
| 346 | suspended_ = true; | 380 | suspended_ = true; |
| 347 | interval_set_ = armed_ = false; | 381 | interval_set_ = false; |
| 382 | has_last_present_ = false; // do not count the suspended pause as a frame interval after resume | ||
| 383 | for (bool& a : event_armed_) a = false; | ||
| 348 | pending_.clear(); | 384 | pending_.clear(); |
| 349 | cv_.notify_all(); | 385 | cv_.notify_all(); |
| 350 | } | 386 | } |
| @@ -352,7 +388,8 @@ public: | |||
| 352 | void resume() { | 388 | void resume() { |
| 353 | std::lock_guard guard(mutex_); | 389 | std::lock_guard guard(mutex_); |
| 354 | suspended_ = false; | 390 | suspended_ = false; |
| 355 | interval_set_ = armed_ = false; | 391 | interval_set_ = false; |
| 392 | for (bool& a : event_armed_) a = false; | ||
| 356 | cv_.notify_all(); | 393 | cv_.notify_all(); |
| 357 | } | 394 | } |
| 358 | 395 | ||
| @@ -366,13 +403,54 @@ public: | |||
| 366 | // Frames that were flipped mid-scan because of ImmediateThresholdPercent. | 403 | // Frames that were flipped mid-scan because of ImmediateThresholdPercent. |
| 367 | std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } | 404 | std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } |
| 368 | std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } | 405 | std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } |
| 369 | bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } | 406 | bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && any_armed_locked(); } |
| 370 | 407 | ||
| 371 | // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown | 408 | // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown |
| 372 | // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. | 409 | // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. |
| 373 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } | 410 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } |
| 374 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } | 411 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } |
| 375 | 412 | ||
| 413 | // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over | ||
| 414 | // the last `frame_pacing_window` presented frames (BL-6). | ||
| 415 | FramePacingSummary pacing_summary() const { | ||
| 416 | FramePacingSummary out; | ||
| 417 | std::vector<std::uint64_t> intervals; | ||
| 418 | std::vector<std::uint64_t> latencies; | ||
| 419 | { | ||
| 420 | std::lock_guard guard(mutex_); | ||
| 421 | out.frames = presents_recorded_; | ||
| 422 | out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u; | ||
| 423 | intervals.reserve(interval_count_); | ||
| 424 | for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]); | ||
| 425 | latencies.reserve(latency_count_); | ||
| 426 | for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]); | ||
| 427 | } | ||
| 428 | auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t { | ||
| 429 | if (sorted.empty()) return 0; | ||
| 430 | const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1; | ||
| 431 | return sorted[std::min(idx, sorted.size() - 1)]; | ||
| 432 | }; | ||
| 433 | if (!intervals.empty()) { | ||
| 434 | out.samples = intervals.size(); | ||
| 435 | double sum = 0.0; | ||
| 436 | for (std::uint64_t v : intervals) sum += double(v); | ||
| 437 | out.mean_us = sum / double(intervals.size()); | ||
| 438 | if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us); | ||
| 439 | std::sort(intervals.begin(), intervals.end()); | ||
| 440 | out.p50_us = percentile(intervals, 50); | ||
| 441 | out.p95_us = percentile(intervals, 95); | ||
| 442 | out.p99_us = percentile(intervals, 99); | ||
| 443 | } | ||
| 444 | if (!latencies.empty()) { | ||
| 445 | out.latency_samples = latencies.size(); | ||
| 446 | std::sort(latencies.begin(), latencies.end()); | ||
| 447 | out.latency_p50_us = percentile(latencies, 50); | ||
| 448 | out.latency_p95_us = percentile(latencies, 95); | ||
| 449 | out.latency_p99_us = percentile(latencies, 99); | ||
| 450 | } | ||
| 451 | return out; | ||
| 452 | } | ||
| 453 | |||
| 376 | private: | 454 | private: |
| 377 | struct Pending { | 455 | struct Pending { |
| 378 | std::uint64_t token; | 456 | std::uint64_t token; |
| @@ -386,6 +464,29 @@ private: | |||
| 386 | bool presented = false, displayed = false; | 464 | bool presented = false, displayed = false; |
| 387 | }; | 465 | }; |
| 388 | 466 | ||
| 467 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { | ||
| 468 | ++presents_recorded_; | ||
| 469 | if (has_last_present_ && now >= last_present_us_) { | ||
| 470 | interval_ring_[interval_head_] = now - last_present_us_; | ||
| 471 | interval_head_ = (interval_head_ + 1) % frame_pacing_window; | ||
| 472 | if (interval_count_ < frame_pacing_window) ++interval_count_; | ||
| 473 | } | ||
| 474 | has_last_present_ = true; | ||
| 475 | last_present_us_ = now; | ||
| 476 | if (token != 0) { | ||
| 477 | for (const Record& r : records_) { | ||
| 478 | if (r.token == token) { | ||
| 479 | if (now >= r.origin_us) { | ||
| 480 | latency_ring_[latency_head_] = now - r.origin_us; | ||
| 481 | latency_head_ = (latency_head_ + 1) % frame_pacing_window; | ||
| 482 | if (latency_count_ < frame_pacing_window) ++latency_count_; | ||
| 483 | } | ||
| 484 | break; | ||
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | } | ||
| 489 | |||
| 389 | // Frames whose vblank has come are shown. | 490 | // Frames whose vblank has come are shown. |
| 390 | void retire_locked(std::uint64_t now) { | 491 | void retire_locked(std::uint64_t now) { |
| 391 | while (!pending_.empty() && pending_.front().flip_us <= now) { | 492 | while (!pending_.empty() && pending_.front().flip_us <= now) { |
| @@ -399,45 +500,67 @@ private: | |||
| 399 | } | 500 | } |
| 400 | } | 501 | } |
| 401 | 502 | ||
| 402 | std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { | 503 | bool any_armed_locked() const { |
| 504 | return event_armed_[0] || event_armed_[1] || event_armed_[2]; | ||
| 505 | } | ||
| 506 | |||
| 507 | std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) { | ||
| 508 | const std::uint64_t tok = ++issued_; | ||
| 509 | Record record; | ||
| 510 | record.token = tok; | ||
| 511 | record.origin_us = origin_us; | ||
| 512 | record.due_us = due_us; | ||
| 513 | records_.push_back(record); | ||
| 514 | if (records_.size() > 64) records_.pop_front(); | ||
| 515 | return tok; | ||
| 516 | } | ||
| 517 | |||
| 518 | std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t event, std::uint32_t timeout_ms, | ||
| 519 | std::uint32_t flags, std::uint64_t* token) { | ||
| 520 | const bool is_origin = (event == frame_event_origin); | ||
| 521 | const bool token_on_timeout = (flags & frame_wait_flag_token_on_timeout) != 0; | ||
| 403 | const std::uint64_t start = clock_.now_us(); | 522 | const std::uint64_t start = clock_.now_us(); |
| 404 | const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline | 523 | const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline |
| 405 | : start + std::uint64_t(timeout_ms) * 1000; | 524 | : start + std::uint64_t(timeout_ms) * 1000; |
| 406 | for (;;) { | 525 | for (;;) { |
| 407 | if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; | 526 | if (shutdown_ || suspended_ || !interval_set_) return pacer_hr::invalid_state; |
| 527 | if (is_origin ? !event_armed_[frame_event_origin] | ||
| 528 | : (!event_armed_[event] && !event_armed_[frame_event_origin])) { | ||
| 529 | return pacer_hr::invalid_state; | ||
| 530 | } | ||
| 408 | const std::uint64_t now = clock_.now_us(); | 531 | const std::uint64_t now = clock_.now_us(); |
| 409 | retire_locked(now); | 532 | retire_locked(now); |
| 410 | if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now | 533 | if (uncapped_) { // no vblank grid and no latency throttle |
| 411 | *token = ++issued_; | 534 | if (is_origin) *token = issue_token_locked(now, now); |
| 412 | Record record; | ||
| 413 | record.token = *token; | ||
| 414 | record.origin_us = now; | ||
| 415 | record.due_us = now; | ||
| 416 | records_.push_back(record); | ||
| 417 | if (records_.size() > 64) records_.pop_front(); | ||
| 418 | return pacer_hr::ok; | 535 | return pacer_hr::ok; |
| 419 | } | 536 | } |
| 420 | const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 | 537 | const std::uint32_t offset = event_offset_us_[event]; |
| 421 | const std::int64_t next = last_origin_ + 1; | 538 | const std::uint64_t first = epoch_us_ + offset; // tick 0 |
| 539 | const std::int64_t next = last_event_tick_[event] + 1; | ||
| 422 | const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; | 540 | const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; |
| 423 | std::uint64_t wake = next_us; | 541 | std::uint64_t wake = next_us; |
| 424 | if (now >= next_us) { | 542 | if (now >= next_us) { |
| 425 | if (pending_.size() < latency_) { | 543 | if (!is_origin || pending_.size() < latency_) { |
| 426 | const std::int64_t newest = std::int64_t((now - first) / period_us_); | 544 | const std::int64_t newest = std::int64_t((now - first) / period_us_); |
| 427 | const std::int64_t origin = std::max(next, newest); | 545 | const std::int64_t tick = std::max(next, newest); |
| 428 | last_origin_ = origin; | 546 | last_event_tick_[event] = tick; |
| 429 | *token = ++issued_; | 547 | if (is_origin) { |
| 430 | Record record; | 548 | const std::uint64_t origin_us = first + std::uint64_t(tick) * period_us_; |
| 431 | record.token = *token; | 549 | const std::uint64_t due_us = origin_us - offset + period_us_; |
| 432 | record.origin_us = first + std::uint64_t(origin) * period_us_; | 550 | *token = issue_token_locked(origin_us, due_us); |
| 433 | record.due_us = record.origin_us - offset_us_ + period_us_; | 551 | } |
| 434 | records_.push_back(record); | ||
| 435 | if (records_.size() > 64) records_.pop_front(); | ||
| 436 | return pacer_hr::ok; | 552 | return pacer_hr::ok; |
| 437 | } | 553 | } |
| 438 | wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown | 554 | wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown |
| 439 | } | 555 | } |
| 440 | if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; | 556 | if (give_up != no_deadline && now >= give_up) { |
| 557 | if (is_origin && token_on_timeout) { | ||
| 558 | // Frame started early on timeout: issue a consecutive token without consuming the tick. | ||
| 559 | *token = issue_token_locked(now, next_us - offset + period_us_); | ||
| 560 | return pacer_hr::false_; | ||
| 561 | } | ||
| 562 | return token_on_timeout ? pacer_hr::false_ : pacer_hr::timeout; | ||
| 563 | } | ||
| 441 | clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); | 564 | clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); |
| 442 | } | 565 | } |
| 443 | } | 566 | } |
| @@ -450,16 +573,25 @@ private: | |||
| 450 | 573 | ||
| 451 | bool suspended_ = false; | 574 | bool suspended_ = false; |
| 452 | bool interval_set_ = false; | 575 | bool interval_set_ = false; |
| 453 | bool armed_ = false; | 576 | bool event_armed_[frame_event_count] = {false, false, false}; |
| 454 | bool uncapped_ = false; | 577 | bool uncapped_ = false; |
| 455 | std::uint32_t period_us_ = 0; | 578 | std::uint32_t period_us_ = 0; |
| 456 | std::uint32_t latency_ = 1; | 579 | std::uint32_t latency_ = 1; |
| 457 | std::uint32_t offset_us_ = 0; | 580 | std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0}; |
| 458 | std::uint64_t epoch_us_ = 0; | 581 | std::uint64_t epoch_us_ = 0; |
| 459 | std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed | 582 | std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed |
| 460 | std::uint64_t issued_ = 0; | 583 | std::uint64_t issued_ = 0; |
| 461 | std::uint64_t last_presented_ = 0; | 584 | std::uint64_t last_presented_ = 0; |
| 462 | std::uint64_t immediate_presents_ = 0; | 585 | std::uint64_t immediate_presents_ = 0; |
| 586 | std::uint64_t presents_recorded_ = 0; | ||
| 587 | bool has_last_present_ = false; | ||
| 588 | std::uint64_t last_present_us_ = 0; | ||
| 589 | std::array<std::uint64_t, frame_pacing_window> interval_ring_{}; | ||
| 590 | std::size_t interval_head_ = 0; | ||
| 591 | std::size_t interval_count_ = 0; | ||
| 592 | std::array<std::uint64_t, frame_pacing_window> latency_ring_{}; | ||
| 593 | std::size_t latency_head_ = 0; | ||
| 594 | std::size_t latency_count_ = 0; | ||
| 463 | std::deque<Pending> pending_; | 595 | std::deque<Pending> pending_; |
| 464 | std::deque<Record> records_; | 596 | std::deque<Record> records_; |
| 465 | }; | 597 | }; |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b225cddef..a4a9b4448 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -631,8 +631,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 631 | if (sampler.unnormalized) { | 631 | if (sampler.unnormalized) { |
| 632 | info.unnormalizedCoordinates = VK_TRUE; | 632 | info.unnormalizedCoordinates = VK_TRUE; |
| 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a | 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a |
| 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. | 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag; |
| 635 | // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). | 635 | // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and |
| 636 | // WRAP is its default (word 0 = 0). | ||
| 636 | const auto clamp_or_border = [](VkSamplerAddressMode m) { | 637 | const auto clamp_or_border = [](VkSamplerAddressMode m) { |
| 637 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; | 638 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; |
| 638 | }; | 639 | }; |
| @@ -640,6 +641,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 640 | info.addressModeV = clamp_or_border(info.addressModeV); | 641 | info.addressModeV = clamp_or_border(info.addressModeV); |
| 641 | info.minFilter = info.magFilter; | 642 | info.minFilter = info.magFilter; |
| 642 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; | 643 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; |
| 644 | info.mipLodBias = 0.0f; | ||
| 643 | info.minLod = info.maxLod = 0.0f; | 645 | info.minLod = info.maxLod = 0.0f; |
| 644 | info.anisotropyEnable = VK_FALSE; | 646 | info.anisotropyEnable = VK_FALSE; |
| 645 | info.maxAnisotropy = 1.0f; | 647 | info.maxAnisotropy = 1.0f; |
diff --git a/runtime/src/mods.h b/runtime/src/mods.h index 10155bf19..bd635e9a0 100644 --- a/runtime/src/mods.h +++ b/runtime/src/mods.h | |||
| @@ -78,8 +78,8 @@ struct LoadResult { | |||
| 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. | 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. |
| 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { | 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { |
| 80 | if (text.empty()) return false; | 80 | if (text.empty()) return false; |
| 81 | if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { | 81 | if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { |
| 82 | if (text.size() > 10) return false; | 82 | if (text.size() == 2 || text.size() > 10) return false; |
| 83 | uint32_t v = 0; | 83 | uint32_t v = 0; |
| 84 | for (std::size_t i = 2; i < text.size(); ++i) { | 84 | for (std::size_t i = 2; i < text.size(); ++i) { |
| 85 | const char c = text[i]; | 85 | const char c = text[i]; |
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h index a48302859..675460cac 100644 --- a/runtime/src/retire_tickets.h +++ b/runtime/src/retire_tickets.h | |||
| @@ -24,7 +24,7 @@ public: | |||
| 24 | while (!pending_.empty()) { | 24 | while (!pending_.empty()) { |
| 25 | const Entry& front = pending_.front(); | 25 | const Entry& front = pending_.front(); |
| 26 | if (!front.idle && !query(front.semaphore, front.value)) break; | 26 | if (!front.idle && !query(front.semaphore, front.value)) break; |
| 27 | completed_ = front.ticket; | 27 | if (front.ticket > completed_) completed_ = front.ticket; |
| 28 | pending_.pop_front(); | 28 | pending_.pop_front(); |
| 29 | } | 29 | } |
| 30 | return completed_; | 30 | return completed_; |
| @@ -34,8 +34,18 @@ public: | |||
| 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. | 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. |
| 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { | 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { |
| 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; | 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; |
| 37 | for (const Entry& entry : pending_) | 37 | for (const Entry& entry : pending_) { |
| 38 | if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); | 38 | if (entry.ticket > ticket || entry.idle) continue; |
| 39 | bool merged = false; | ||
| 40 | for (auto& [sem, val] : out) { | ||
| 41 | if (sem == entry.semaphore) { | ||
| 42 | if (entry.value > val) val = entry.value; | ||
| 43 | merged = true; | ||
| 44 | break; | ||
| 45 | } | ||
| 46 | } | ||
| 47 | if (!merged) out.emplace_back(entry.semaphore, entry.value); | ||
| 48 | } | ||
| 39 | return out; | 49 | return out; |
| 40 | } | 50 | } |
| 41 | 51 | ||
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 9f752317e..596ad0ae9 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -246,7 +246,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co | |||
| 246 | if (d < 0 || d >= 30) return ZlibError::data; | 246 | if (d < 0 || d >= 30) return ZlibError::data; |
| 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); | 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); |
| 248 | if (in.failed() || distance > out.size()) return ZlibError::data; | 248 | if (in.failed() || distance > out.size()) return ZlibError::data; |
| 249 | if (out.size() + length > limit) return ZlibError::limit; | 249 | if (out.size() > limit || length > limit - out.size()) return ZlibError::limit; |
| 250 | const std::size_t from = out.size() - distance; | 250 | const std::size_t from = out.size() - distance; |
| 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); | 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); |
| 252 | } | 252 | } |
| @@ -284,7 +284,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 284 | if (!reader.byte(x)) return fail(ZlibError::data); | 284 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); | 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); |
| 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); | 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); |
| 287 | if (out.size() + length > limit) return fail(ZlibError::limit); | 287 | if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit); |
| 288 | for (unsigned i = 0; i < length; ++i) { | 288 | for (unsigned i = 0; i < length; ++i) { |
| 289 | std::uint8_t x; | 289 | std::uint8_t x; |
| 290 | if (!reader.byte(x)) return fail(ZlibError::data); | 290 | if (!reader.byte(x)) return fail(ZlibError::data); |
| @@ -349,7 +349,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 349 | } | 349 | } |
| 350 | // Adler-32, big-endian, after the deflate data's last whole byte. | 350 | // Adler-32, big-endian, after the deflate data's last whole byte. |
| 351 | const std::size_t at = 2 + reader.position(); | 351 | const std::size_t at = 2 + reader.position(); |
| 352 | if (at + 4 > in.size()) return fail(ZlibError::data); | 352 | if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data); |
| 353 | std::uint32_t a = 1, b = 0; | 353 | std::uint32_t a = 1, b = 0; |
| 354 | for (const std::uint8_t x : out) { | 354 | for (const std::uint8_t x : out) { |
| 355 | a = (a + x) % 65521; | 355 | a = (a + x) % 65521; |
| @@ -1045,9 +1045,20 @@ private: | |||
| 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { | 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { |
| 1046 | for (const auto& [key, val] : fh->object) { | 1046 | for (const auto& [key, val] : fh->object) { |
| 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; | 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; |
| 1048 | char* end = nullptr; | 1048 | std::uint64_t param = 0; |
| 1049 | const unsigned long param = std::strtoul(key.c_str(), &end, 10); | 1049 | bool ok = true; |
| 1050 | if (!end || *end != '\0') continue; | 1050 | for (const char c : key) { |
| 1051 | if (c < '0' || c > '9') { | ||
| 1052 | ok = false; | ||
| 1053 | break; | ||
| 1054 | } | ||
| 1055 | param = param * 10u + std::uint64_t(c - '0'); | ||
| 1056 | if (param > UINT32_MAX) { | ||
| 1057 | ok = false; | ||
| 1058 | break; | ||
| 1059 | } | ||
| 1060 | } | ||
| 1061 | if (!ok) continue; | ||
| 1051 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; | 1062 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; |
| 1052 | } | 1063 | } |
| 1053 | } | 1064 | } |
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp index c4960347c..c4a02a459 100644 --- a/runtime/src/statistics_sum.comp +++ b/runtime/src/statistics_sum.comp | |||
| @@ -2,9 +2,11 @@ | |||
| 2 | 2 | ||
| 3 | // Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one | 3 | // Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one |
| 4 | // invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. | 4 | // invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. |
| 5 | // `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and | 5 | // `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only the fragment and compute |
| 6 | // compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly, | 6 | // invocations: they are copied to counters 7 and 8 of their record, so PSInvocations takes the fragment one and |
| 7 | // vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing. | 7 | // CSInvocations the compute one, and every other counter adds nothing. |
| 8 | // The clipping invocations of a mesh segment come from the mesh-primitives count of that segment, copied to | ||
| 9 | // counter 5 (D3D-MESH-CLIPPING-COUNTER); without that count the field stays 0. | ||
| 8 | layout(local_size_x = 11) in; | 10 | layout(local_size_x = 11) in; |
| 9 | layout(set = 0, binding = 0, std430) buffer QueryResults { | 11 | layout(set = 0, binding = 0, std430) buffer QueryResults { |
| 10 | uvec2 total[11]; | 12 | uvec2 total[11]; |
| @@ -15,7 +17,7 @@ layout(push_constant) uniform ResolveRange { uint count; uint mesh; }; | |||
| 15 | void main() { | 17 | void main() { |
| 16 | const uint counter = gl_LocalInvocationID.x; | 18 | const uint counter = gl_LocalInvocationID.x; |
| 17 | uvec2 sum = total[counter]; | 19 | uvec2 sum = total[counter]; |
| 18 | const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u; | 20 | const bool counted = mesh == 0u || counter == 5u || counter == 7u || counter == 10u; |
| 19 | const uint source = mesh != 0u && counter == 10u ? 8u : counter; | 21 | const uint source = mesh != 0u && counter == 10u ? 8u : counter; |
| 20 | for (uint i = 0; counted && i < count; ++i) { | 22 | for (uint i = 0; counted && i < count; ++i) { |
| 21 | uvec2 segment = segments[i * 11 + source]; | 23 | uvec2 segment = segments[i * 11 + source]; |
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h index 9c67f0429..a147cd4df 100644 --- a/runtime/src/statistics_sum_spirv.h +++ b/runtime/src/statistics_sum_spirv.h | |||
| @@ -7,7 +7,7 @@ namespace leonida { | |||
| 7 | // From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, | 7 | // From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, |
| 8 | // then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. | 8 | // then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. |
| 9 | inline constexpr std::uint32_t statistics_sum_spirv[] = { | 9 | inline constexpr std::uint32_t statistics_sum_spirv[] = { |
| 10 | 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, | 10 | 0x07230203, 0x00010000, 0x0008000b, 0x00000084, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, |
| 11 | 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, | 11 | 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, |
| 12 | 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, | 12 | 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, |
| 13 | 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, | 13 | 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, |
| @@ -16,7 +16,7 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = { | |||
| 16 | 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, | 16 | 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, |
| 17 | 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, | 17 | 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, |
| 18 | 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, | 18 | 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, |
| 19 | 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, | 19 | 0x00000023, 0x00000004, 0x00040047, 0x0000006f, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, |
| 20 | 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, | 20 | 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, |
| 21 | 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, | 21 | 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, |
| 22 | 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, | 22 | 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, |
| @@ -28,42 +28,39 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = { | |||
| 28 | 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, | 28 | 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, |
| 29 | 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, | 29 | 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, |
| 30 | 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, | 30 | 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, |
| 31 | 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007, | 31 | 0x0004002b, 0x00000006, 0x0000002b, 0x00000005, 0x0004002b, 0x00000006, 0x0000002f, 0x00000007, |
| 32 | 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008, | 32 | 0x0004002b, 0x00000006, 0x00000033, 0x0000000a, 0x0004002b, 0x00000006, 0x0000003d, 0x00000008, |
| 33 | 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013, | 33 | 0x0004002b, 0x00000006, 0x0000005b, 0x00000001, 0x0006002c, 0x00000009, 0x0000006f, 0x00000013, |
| 34 | 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, | 34 | 0x0000005b, 0x0000005b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, |
| 35 | 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, | 35 | 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, |
| 36 | 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, | 36 | 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, |
| 37 | 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, | 37 | 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, |
| 38 | 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, | 38 | 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, |
| 39 | 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c, | 39 | 0x00000028, 0x0000000c, 0x000500aa, 0x0000001f, 0x0000002c, 0x0000000f, 0x0000002b, 0x000500a6, |
| 40 | 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae, | 40 | 0x0000001f, 0x0000002d, 0x00000029, 0x0000002c, 0x000500aa, 0x0000001f, 0x00000030, 0x0000000f, |
| 41 | 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f, | 41 | 0x0000002f, 0x000500a6, 0x0000001f, 0x00000031, 0x0000002d, 0x00000030, 0x000500aa, 0x0000001f, |
| 42 | 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c, | 42 | 0x00000034, 0x0000000f, 0x00000033, 0x000500a6, 0x0000001f, 0x00000035, 0x00000031, 0x00000034, |
| 43 | 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033, | 43 | 0x000500ab, 0x0000001f, 0x00000039, 0x00000028, 0x0000000c, 0x000500a7, 0x0000001f, 0x0000003c, |
| 44 | 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f, | 44 | 0x00000039, 0x00000034, 0x000600a9, 0x00000006, 0x0000003f, 0x0000003c, 0x0000003d, 0x0000000f, |
| 45 | 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c, | 45 | 0x000200f9, 0x00000041, 0x000200f8, 0x00000041, 0x000700f5, 0x00000010, 0x00000082, 0x0000001e, |
| 46 | 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042, | 46 | 0x00000005, 0x00000083, 0x00000042, 0x000700f5, 0x00000006, 0x00000071, 0x0000000c, 0x00000005, |
| 47 | 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5, | 47 | 0x0000006b, 0x00000042, 0x000400f6, 0x00000043, 0x00000042, 0x00000000, 0x000200f9, 0x00000045, |
| 48 | 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006, | 48 | 0x000200f8, 0x00000045, 0x000300f7, 0x00000048, 0x00000000, 0x000400fa, 0x00000035, 0x00000047, |
| 49 | 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045, | 49 | 0x00000048, 0x000200f8, 0x00000047, 0x00050041, 0x00000026, 0x0000004a, 0x00000024, 0x0000001a, |
| 50 | 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000, | 50 | 0x0004003d, 0x00000006, 0x0000004b, 0x0000004a, 0x000500b0, 0x0000001f, 0x0000004c, 0x00000071, |
| 51 | 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026, | 51 | 0x0000004b, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000700f5, 0x0000001f, 0x0000004d, |
| 52 | 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0, | 52 | 0x00000035, 0x00000045, 0x0000004c, 0x00000047, 0x000400fa, 0x0000004d, 0x00000042, 0x00000043, |
| 53 | 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b, | 53 | 0x000200f8, 0x00000042, 0x00050084, 0x00000006, 0x00000050, 0x00000071, 0x00000013, 0x00050080, |
| 54 | 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa, | 54 | 0x00000006, 0x00000052, 0x00000050, 0x0000003f, 0x00060041, 0x0000001c, 0x00000053, 0x00000018, |
| 55 | 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053, | 55 | 0x00000025, 0x00000052, 0x0004003d, 0x00000010, 0x00000054, 0x00000053, 0x00050051, 0x00000006, |
| 56 | 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041, | 56 | 0x00000057, 0x00000082, 0x00000000, 0x00050051, 0x00000006, 0x00000059, 0x00000054, 0x00000000, |
| 57 | 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057, | 57 | 0x00050080, 0x00000006, 0x0000005a, 0x00000057, 0x00000059, 0x00050051, 0x00000006, 0x0000005d, |
| 58 | 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006, | 58 | 0x00000054, 0x00000001, 0x000500b0, 0x0000001f, 0x00000061, 0x0000005a, 0x00000057, 0x000600a9, |
| 59 | 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c, | 59 | 0x00000006, 0x00000062, 0x00000061, 0x0000005b, 0x0000000c, 0x00050080, 0x00000006, 0x00000063, |
| 60 | 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064, | 60 | 0x0000005d, 0x00000062, 0x00050051, 0x00000006, 0x00000065, 0x00000082, 0x00000001, 0x00050080, |
| 61 | 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c, | 61 | 0x00000006, 0x00000066, 0x00000065, 0x00000063, 0x00050050, 0x00000010, 0x00000083, 0x0000005a, |
| 62 | 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068, | 62 | 0x00000066, 0x00050080, 0x00000006, 0x0000006b, 0x00000071, 0x00000025, 0x000200f9, 0x00000041, |
| 63 | 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050, | 63 | 0x000200f8, 0x00000043, 0x0003003e, 0x0000001d, 0x00000082, 0x000100fd, 0x00010038, |
| 64 | 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d, | ||
| 65 | 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f, | ||
| 66 | 0x000100fd, 0x00010038, | ||
| 67 | }; | 64 | }; |
| 68 | 65 | ||
| 69 | } // namespace leonida | 66 | } // namespace leonida |
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index b73ec50e1..385d55950 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h | |||
| @@ -91,6 +91,10 @@ inline constexpr Layout layouts[] = { | |||
| 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, | 91 | {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). | 92 | // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). |
| 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, | 93 | {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, |
| 94 | // B5G6R5, B5G5R5A1 and B4G4R4A4_UNORM, likewise (WARP has all three). | ||
| 95 | {VK_FORMAT_R5G6B5_UNORM_PACK16, Kind::unorm, 2, {{{11, 5}, {5, 6}, {0, 5}, {}}}}, | ||
| 96 | {VK_FORMAT_A1R5G5B5_UNORM_PACK16, Kind::unorm, 2, {{{10, 5}, {5, 5}, {0, 5}, {15, 1}}}}, | ||
| 97 | {VK_FORMAT_A4R4G4B4_UNORM_PACK16, Kind::unorm, 2, {{{8, 4}, {4, 4}, {0, 4}, {12, 4}}}}, | ||
| 94 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, | 98 | {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, |
| 95 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, | 99 | {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, |
| 96 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, | 100 | {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe8..ab6786a51 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -101,6 +101,7 @@ struct VulkanDeviceFunctions { | |||
| 101 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ | 101 | X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ |
| 102 | X(vkCmdPushConstants) X(vkCmdDispatch) \ | 102 | X(vkCmdPushConstants) X(vkCmdDispatch) \ |
| 103 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ | 103 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ |
| 104 | X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ | ||
| 104 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ | 105 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ |
| 105 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ | 106 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ |
| 106 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ | 107 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ |
| @@ -244,12 +245,16 @@ public: | |||
| 244 | 245 | ||
| 245 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the | 246 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the |
| 246 | // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). | 247 | // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). |
| 247 | // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see | 248 | // Segment i is in `mesh_queries` when mesh[i] is set (two counters: fragment and compute; see |
| 248 | // statistics_sum.comp), otherwise in `queries` (all eleven). | 249 | // statistics_sum.comp), otherwise in `queries` (all eleven). A mesh segment's clipping invocations come from |
| 249 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, | 250 | // `primitives_queries`, the mesh-primitives count of that segment (D3D-MESH-CLIPPING-COUNTER); it is null when |
| 250 | std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { | 251 | // the device has no meshShaderQueries, and the field then reads 0. |
| 252 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, | ||
| 253 | VkQueryPool primitives_queries, const std::uint8_t* mesh, std::uint32_t first, | ||
| 254 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { | ||
| 251 | constexpr VkDeviceSize result = statistics_counters * word_size; | 255 | constexpr VkDeviceSize result = statistics_counters * word_size; |
| 252 | constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes | 256 | constexpr VkDeviceSize mesh_slot = 7 * word_size; // PSInvocations, where the mesh pool's first counter goes |
| 257 | constexpr VkDeviceSize clipping_slot = 5 * word_size; // CInvocations, where the mesh-primitives count goes | ||
| 253 | begin_scratch_write(cb); | 258 | begin_scratch_write(cb); |
| 254 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); | 259 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); |
| 255 | bind(cb, statistics_pipeline_); | 260 | bind(cb, statistics_pipeline_); |
| @@ -258,9 +263,18 @@ public: | |||
| 258 | std::uint32_t chunk = 1; | 263 | std::uint32_t chunk = 1; |
| 259 | while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) | 264 | while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) |
| 260 | ++chunk; | 265 | ++chunk; |
| 266 | if (in_mesh) { | ||
| 267 | // The mesh pool holds only the fragment and compute counters, so the clipping field of a mesh | ||
| 268 | // segment reads 0 unless the mesh-primitives count fills it (D3D-MESH-CLIPPING-COUNTER). | ||
| 269 | vk_.vkCmdFillBuffer(cb, scratch_, result, chunk * result, 0); | ||
| 270 | barrier(cb, transfer, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); | ||
| 271 | } | ||
| 261 | vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, | 272 | vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, |
| 262 | result + (in_mesh ? mesh_slot : 0), result, | 273 | result + (in_mesh ? mesh_slot : 0), result, |
| 263 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | 274 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); |
| 275 | if (in_mesh && primitives_queries) | ||
| 276 | vk_.vkCmdCopyQueryPoolResults(cb, primitives_queries, first, chunk, scratch_, result + clipping_slot, | ||
| 277 | result, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 264 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, | 278 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, |
| 265 | shader_access); | 279 | shader_access); |
| 266 | dispatch(cb, chunk, 1, in_mesh); | 280 | dispatch(cb, chunk, 1, in_mesh); |
| @@ -923,6 +937,10 @@ struct TileRange { | |||
| 923 | #endif | 937 | #endif |
| 924 | class VulkanContext { | 938 | class VulkanContext { |
| 925 | public: | 939 | public: |
| 940 | // mesh_queries: VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so a mesh segment's | ||
| 941 | // clipping invocations can come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Set by the device | ||
| 942 | // that created the context. | ||
| 943 | bool mesh_queries = false; | ||
| 926 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). | 944 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). |
| 927 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. | 945 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. |
| 928 | // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. | 946 | // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. |
| @@ -970,6 +988,8 @@ public: | |||
| 970 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; | 988 | replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; |
| 971 | replay_.set_viewport = vk.vkCmdSetViewport; | 989 | replay_.set_viewport = vk.vkCmdSetViewport; |
| 972 | replay_.set_scissor = vk.vkCmdSetScissor; | 990 | replay_.set_scissor = vk.vkCmdSetScissor; |
| 991 | replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount; | ||
| 992 | replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount; | ||
| 973 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; | 993 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; |
| 974 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; | 994 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; |
| 975 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; | 995 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; |
| @@ -1000,7 +1020,7 @@ public: | |||
| 1000 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. | 1020 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. |
| 1001 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { | 1021 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { |
| 1002 | BufferVaIndex<ResourceId>::Hit hit{}; | 1022 | BufferVaIndex<ResourceId>::Hit hit{}; |
| 1003 | if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; | 1023 | if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent; |
| 1004 | const ResourceBinding* b = resolve(hit.id); | 1024 | const ResourceBinding* b = resolve(hit.id); |
| 1005 | if (!b) return HostReadStatus::absent; | 1025 | if (!b) return HostReadStatus::absent; |
| 1006 | if (!b->host) return HostReadStatus::not_cpu_written; | 1026 | if (!b->host) return HostReadStatus::not_cpu_written; |
| @@ -1268,6 +1288,11 @@ public: | |||
| 1268 | replay_.zero_size = size; | 1288 | replay_.zero_size = size; |
| 1269 | } | 1289 | } |
| 1270 | 1290 | ||
| 1291 | void set_depth_range_unrestricted(bool enabled) { | ||
| 1292 | std::unique_lock lock(resource_mutex_); | ||
| 1293 | replay_.depth_range_unrestricted = enabled; | ||
| 1294 | } | ||
| 1295 | |||
| 1271 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. | 1296 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. |
| 1272 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { | 1297 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { |
| 1273 | std::unique_lock lock(resource_mutex_); | 1298 | std::unique_lock lock(resource_mutex_); |
| @@ -1483,12 +1508,23 @@ public: | |||
| 1483 | void note_bindless_upload() { bindless_upload_pending_ = true; } | 1508 | void note_bindless_upload() { bindless_upload_pending_ = true; } |
| 1484 | 1509 | ||
| 1485 | std::uint64_t completed_retire_ticket() { | 1510 | std::uint64_t completed_retire_ticket() { |
| 1486 | std::lock_guard lock(submit_mutex_); | 1511 | bool lost = false; |
| 1487 | if (is_device_lost()) return 0; | 1512 | std::uint64_t ticket = 0; |
| 1488 | return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { | 1513 | { |
| 1489 | std::uint64_t done = 0; | 1514 | std::lock_guard lock(submit_mutex_); |
| 1490 | return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; | 1515 | if (is_device_lost()) return 0; |
| 1491 | }); | 1516 | ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { |
| 1517 | std::uint64_t done = 0; | ||
| 1518 | const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); | ||
| 1519 | if (result == VK_ERROR_DEVICE_LOST) lost = true; | ||
| 1520 | return result == VK_SUCCESS && done >= value; | ||
| 1521 | }); | ||
| 1522 | } | ||
| 1523 | // Outside submit_mutex_, as in submit(): notifying the fence dispatcher can run callbacks that submit. | ||
| 1524 | // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for | ||
| 1525 | // "this ticket has not completed". | ||
| 1526 | if (lost) mark_device_lost(); | ||
| 1527 | return lost ? 0 : ticket; | ||
| 1492 | } | 1528 | } |
| 1493 | 1529 | ||
| 1494 | void drain_deleted_resources(std::uint64_t current_ticket) { | 1530 | void drain_deleted_resources(std::uint64_t current_ticket) { |
| @@ -2394,9 +2430,11 @@ private: | |||
| 2394 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); | 2430 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); |
| 2395 | }; | 2431 | }; |
| 2396 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, | 2432 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, |
| 2397 | const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, | 2433 | VkQueryPool primitives_pool, const std::uint8_t* mesh, |
| 2398 | VkBuffer dst, VkDeviceSize offset) { | 2434 | std::uint32_t first, std::uint32_t count, VkBuffer dst, |
| 2399 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); | 2435 | VkDeviceSize offset) { |
| 2436 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, | ||
| 2437 | offset); | ||
| 2400 | }; | 2438 | }; |
| 2401 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 2439 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, |
| 2402 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 2440 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { |
| @@ -2443,18 +2481,26 @@ private: | |||
| 2443 | if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { | 2481 | if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { |
| 2444 | statistics->mesh.clear(); | 2482 | statistics->mesh.clear(); |
| 2445 | } else { | 2483 | } else { |
| 2446 | // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping | 2484 | // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): the |
| 2447 | // invocations and primitives, fragment and compute invocations (D3D-291). | 2485 | // fragment and compute invocations, and no other (D3D-291). |
| 2448 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | 2486 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; |
| 2449 | info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; | 2487 | info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; |
| 2450 | info.queryCount = statistics_segments; | 2488 | info.queryCount = statistics_segments; |
| 2451 | info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | | 2489 | info.pipelineStatistics = kMeshStatisticsFlags; |
| 2452 | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | | ||
| 2453 | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | | ||
| 2454 | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; | ||
| 2455 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != | 2490 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != |
| 2456 | VK_SUCCESS) | 2491 | VK_SUCCESS) |
| 2457 | return ReplayResult::unsupported; | 2492 | return ReplayResult::unsupported; |
| 2493 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, | ||
| 2494 | // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, | ||
| 2495 | // or the clipping field of a mesh segment stays 0. | ||
| 2496 | if (context_.mesh_queries) { | ||
| 2497 | VkQueryPoolCreateInfo primitives{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | ||
| 2498 | primitives.queryType = VK_QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT; | ||
| 2499 | primitives.queryCount = statistics_segments; | ||
| 2500 | if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, | ||
| 2501 | &statistics->primitives_pool) != VK_SUCCESS) | ||
| 2502 | return ReplayResult::unsupported; | ||
| 2503 | } | ||
| 2458 | } | 2504 | } |
| 2459 | } | 2505 | } |
| 2460 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after | 2506 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after |
| @@ -2515,6 +2561,18 @@ private: | |||
| 2515 | discard(); | 2561 | discard(); |
| 2516 | return ReplayResult::unsupported; | 2562 | return ReplayResult::unsupported; |
| 2517 | } | 2563 | } |
| 2564 | // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the | ||
| 2565 | // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: | ||
| 2566 | // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their | ||
| 2567 | // barriers say, so this one starts with a full memory barrier against everything submitted before it | ||
| 2568 | // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies). | ||
| 2569 | if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out | ||
| 2570 | VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 2571 | full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2572 | full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2573 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | ||
| 2574 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); | ||
| 2575 | } | ||
| 2518 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2576 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 2519 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 2577 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 2520 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | 2578 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f7..7dcc7e2c0 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -216,7 +216,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) { | |||
| 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, | 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, |
| 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, | 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, |
| 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| 219 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, | 219 | // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate |
| 220 | // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2 | ||
| 221 | // puts both in the CLEAR stage, not COPY. | ||
| 222 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT}, | ||
| 220 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, | 223 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, |
| 221 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, | 224 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, |
| 222 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 225 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| @@ -716,6 +719,9 @@ struct OcclusionSegmentPool { | |||
| 716 | // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. | 719 | // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. |
| 717 | VkQueryPool mesh_pool = VK_NULL_HANDLE; | 720 | VkQueryPool mesh_pool = VK_NULL_HANDLE; |
| 718 | std::vector<std::uint8_t> mesh; | 721 | std::vector<std::uint8_t> mesh; |
| 722 | // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER): one query per segment, begun and | ||
| 723 | // ended with the mesh segment. Null when the device has no meshShaderQueries. | ||
| 724 | VkQueryPool primitives_pool = VK_NULL_HANDLE; | ||
| 719 | 725 | ||
| 720 | OcclusionSegmentPool() = default; | 726 | OcclusionSegmentPool() = default; |
| 721 | OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; | 727 | OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; |
| @@ -723,6 +729,7 @@ struct OcclusionSegmentPool { | |||
| 723 | ~OcclusionSegmentPool() { | 729 | ~OcclusionSegmentPool() { |
| 724 | if (pool) destroy(device, pool, nullptr); | 730 | if (pool) destroy(device, pool, nullptr); |
| 725 | if (mesh_pool) destroy(device, mesh_pool, nullptr); | 731 | if (mesh_pool) destroy(device, mesh_pool, nullptr); |
| 732 | if (primitives_pool) destroy(device, primitives_pool, nullptr); | ||
| 726 | } | 733 | } |
| 727 | }; | 734 | }; |
| 728 | 735 | ||
| @@ -769,6 +776,7 @@ struct GraphicsPipeline { | |||
| 769 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time | 776 | std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time |
| 770 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) | 777 | std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) |
| 771 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only | 778 | bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only |
| 779 | bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT | ||
| 772 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots | 780 | // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots |
| 773 | // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth | 781 | // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth |
| 774 | // and stencil. Null when it cannot be built. | 782 | // and stencil. Null when it cannot be built. |
| @@ -810,6 +818,7 @@ struct ReplayFunctions { | |||
| 810 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; | 818 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; |
| 811 | PFN_vkCmdClearColorImage clear_color_image = nullptr; | 819 | PFN_vkCmdClearColorImage clear_color_image = nullptr; |
| 812 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; | 820 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; |
| 821 | bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values. | ||
| 813 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. | 822 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. |
| 814 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers | 823 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers |
| 815 | VkPipelineStageFlags2 queue_stages = 0; | 824 | VkPipelineStageFlags2 queue_stages = 0; |
| @@ -850,6 +859,8 @@ struct ReplayFunctions { | |||
| 850 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; | 859 | PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; |
| 851 | PFN_vkCmdSetViewport set_viewport = nullptr; | 860 | PFN_vkCmdSetViewport set_viewport = nullptr; |
| 852 | PFN_vkCmdSetScissor set_scissor = nullptr; | 861 | PFN_vkCmdSetScissor set_scissor = nullptr; |
| 862 | PFN_vkCmdSetViewportWithCount set_viewport_with_count = nullptr; | ||
| 863 | PFN_vkCmdSetScissorWithCount set_scissor_with_count = nullptr; | ||
| 853 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; | 864 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; |
| 854 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; | 865 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; |
| 855 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; | 866 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; |
| @@ -875,9 +886,12 @@ struct ReplayFunctions { | |||
| 875 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; | 886 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; |
| 876 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional | 887 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional |
| 877 | // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). | 888 | // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). |
| 878 | // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). | 889 | // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). The third pool holds the |
| 879 | std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh, | 890 | // mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER); it is null when the device has no |
| 880 | std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)> | 891 | // meshShaderQueries. |
| 892 | std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, VkQueryPool primitives_pool, | ||
| 893 | const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, VkBuffer dst, | ||
| 894 | VkDeviceSize offset)> | ||
| 881 | sum_statistics; | 895 | sum_statistics; |
| 882 | // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional | 896 | // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional |
| 883 | // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). | 897 | // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). |
| @@ -958,6 +972,8 @@ struct QueryResolveRun { | |||
| 958 | bool sum = false; | 972 | bool sum = false; |
| 959 | // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). | 973 | // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). |
| 960 | VkQueryPool mesh_pool = VK_NULL_HANDLE; | 974 | VkQueryPool mesh_pool = VK_NULL_HANDLE; |
| 975 | // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER); null without meshShaderQueries. | ||
| 976 | VkQueryPool primitives_pool = VK_NULL_HANDLE; | ||
| 961 | const std::uint8_t* mesh = nullptr; | 977 | const std::uint8_t* mesh = nullptr; |
| 962 | }; | 978 | }; |
| 963 | 979 | ||
| @@ -1598,6 +1614,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, | |||
| 1598 | if (offset > UINT64_MAX - p.binding.buffer_offset || | 1614 | if (offset > UINT64_MAX - p.binding.buffer_offset || |
| 1599 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; | 1615 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; |
| 1600 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset | 1616 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset |
| 1617 | if (offset % std::min(e, 4u)) return ReplayResult::unsupported; | ||
| 1601 | if (e > 4 && bytes % 4) { | 1618 | if (e > 4 && bytes % 4) { |
| 1602 | return ReplayResult::unsupported; | 1619 | return ReplayResult::unsupported; |
| 1603 | } | 1620 | } |
| @@ -1869,27 +1886,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1869 | return ReplayResult::success; | 1886 | return ReplayResult::success; |
| 1870 | } | 1887 | } |
| 1871 | 1888 | ||
| 1872 | // RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel | 1889 | // CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block |
| 1873 | // alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. | 1890 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned |
| 1874 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { | 1891 | // transfer scratch; leave partial-tile padding alone. |
| 1892 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, | ||
| 1893 | const BlockFormat& fmt, bool upload) { | ||
| 1875 | auto& region = p.buffer_image_copies.front(); | 1894 | auto& region = p.buffer_image_copies.front(); |
| 1876 | const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; | 1895 | if (!fmt.bytes || !fmt.block || image.rgb96 || |
| 1877 | const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; | 1896 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) |
| 1878 | const auto rows = region.imageExtent.height; | 1897 | return false; |
| 1898 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; | ||
| 1899 | const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block; | ||
| 1900 | const VkDeviceSize depth = region.imageExtent.depth; | ||
| 1901 | const VkDeviceSize row_bytes = blocks_w * fmt.bytes; | ||
| 1902 | const VkDeviceSize pitch = | ||
| 1903 | region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes; | ||
| 1904 | const VkDeviceSize slice_rows = | ||
| 1905 | region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows; | ||
| 1906 | const VkDeviceSize slice_pitch = slice_rows * pitch; | ||
| 1907 | const VkDeviceSize slice_bytes = row_bytes * rows; | ||
| 1908 | const VkDeviceSize total_bytes = slice_bytes * depth; | ||
| 1879 | VkDeviceSize scratch_offset = 0; | 1909 | VkDeviceSize scratch_offset = 0; |
| 1880 | if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; | 1910 | if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false; |
| 1881 | const auto app_offset = region.bufferOffset; | 1911 | const auto app_offset = region.bufferOffset; |
| 1882 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { | 1912 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { |
| 1883 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); | 1913 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); |
| 1884 | }; | 1914 | }; |
| 1885 | if (row_bytes == pitch) { | 1915 | if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) { |
| 1886 | add_copy(app_offset, scratch_offset, row_bytes * rows); | 1916 | add_copy(app_offset, scratch_offset, total_bytes); |
| 1917 | } else if (row_bytes == pitch) { | ||
| 1918 | for (VkDeviceSize z = 0; z < depth; ++z) | ||
| 1919 | add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes); | ||
| 1887 | } else { | 1920 | } else { |
| 1888 | for (std::uint32_t row = 0; row < rows; ++row) | 1921 | for (VkDeviceSize z = 0; z < depth; ++z) { |
| 1889 | add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); | 1922 | const VkDeviceSize linear_slice = app_offset + z * slice_pitch; |
| 1923 | const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes; | ||
| 1924 | for (VkDeviceSize row = 0; row < rows; ++row) | ||
| 1925 | add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes); | ||
| 1926 | } | ||
| 1890 | } | 1927 | } |
| 1891 | region.bufferOffset = scratch_offset; | 1928 | region.bufferOffset = scratch_offset; |
| 1892 | region.bufferRowLength = 0; | 1929 | region.bufferRowLength = 0; |
| 1930 | region.bufferImageHeight = 0; | ||
| 1893 | return true; | 1931 | return true; |
| 1894 | } | 1932 | } |
| 1895 | 1933 | ||
| @@ -2103,6 +2141,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2103 | if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; | 2141 | if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; |
| 2104 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; | 2142 | if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; |
| 2105 | if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; | 2143 | if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; |
| 2144 | if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) | ||
| 2145 | return ReplayResult::unsupported; | ||
| 2106 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; | 2146 | if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; |
| 2107 | if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; | 2147 | if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; |
| 2108 | p.graphics = pipeline; | 2148 | p.graphics = pipeline; |
| @@ -2151,9 +2191,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct | |||
| 2151 | if (!a.view) return ReplayResult::unsupported; | 2191 | if (!a.view) return ReplayResult::unsupported; |
| 2152 | shrink(a.binding, draw.depth, a.range); | 2192 | shrink(a.binding, draw.depth, a.range); |
| 2153 | } | 2193 | } |
| 2154 | if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering | 2194 | if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering |
| 2155 | p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), | 2195 | std::uint32_t max_w = std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)); |
| 2156 | std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; | 2196 | std::uint32_t max_h = std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height)); |
| 2197 | if (draw.viewports) { | ||
| 2198 | for (std::uint32_t i = 0; i < draw.viewports->viewport_count; ++i) { | ||
| 2199 | const Viewport& v = draw.viewports->viewports[i]; | ||
| 2200 | max_w = std::max(max_w, std::uint32_t(std::max(0.0f, v.x + v.width))); | ||
| 2201 | max_h = std::max(max_h, std::uint32_t(std::max(0.0f, v.y + v.height))); | ||
| 2202 | } | ||
| 2203 | } | ||
| 2204 | p.area = {max_w, max_h}; | ||
| 2157 | } | 2205 | } |
| 2158 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); | 2206 | p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); |
| 2159 | 2207 | ||
| @@ -2300,6 +2348,8 @@ public: | |||
| 2300 | // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). | 2348 | // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). |
| 2301 | std::vector<std::uint8_t> statistics_mesh; | 2349 | std::vector<std::uint8_t> statistics_mesh; |
| 2302 | VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; | 2350 | VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; |
| 2351 | // The mesh-primitives pool of the list's mesh segments (D3D-MESH-CLIPPING-COUNTER). | ||
| 2352 | VkQueryPool statistics_primitives_pool = VK_NULL_HANDLE; | ||
| 2303 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them | 2353 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them |
| 2304 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run | 2354 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run |
| 2305 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. | 2355 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. |
| @@ -2344,10 +2394,26 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) { | |||
| 2344 | // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and | 2394 | // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and |
| 2345 | // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements | 2395 | // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements |
| 2346 | // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. | 2396 | // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. |
| 2347 | // A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active | 2397 | // The counters a mesh draw may count: VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the input |
| 2348 | // (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query | 2398 | // assembly, vertex, geometry, tessellation and clipping bits out of the pipelineStatistics flags of every pool that |
| 2349 | // that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool | 2399 | // is active during a mesh draw, so a mesh segment runs in a pool with the fragment and compute counters only |
| 2350 | // or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind. | 2400 | // (D3D-291). D3D12 counts the clipping invocations and primitives of a mesh pipeline, but Vulkan has no counter for |
| 2401 | // them during a mesh draw, so those two fields read 0. | ||
| 2402 | inline constexpr VkQueryPipelineStatisticFlags kMeshStatisticsFlags = | ||
| 2403 | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; | ||
| 2404 | // The bits the same VUID forbids in a pool that is active during a mesh draw. | ||
| 2405 | inline constexpr VkQueryPipelineStatisticFlags kForbiddenMeshStatisticsFlags = | ||
| 2406 | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT | | ||
| 2407 | VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT | | ||
| 2408 | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | | ||
| 2409 | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | | ||
| 2410 | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT | | ||
| 2411 | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT; | ||
| 2412 | // A mesh draw cannot run while a query with the input-assembly, vertex, geometry, tessellation or clipping counters | ||
| 2413 | // is active (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as | ||
| 2414 | // 0. A query that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in | ||
| 2415 | // the full pool or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of | ||
| 2416 | // its own kind. | ||
| 2351 | // Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw | 2417 | // Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw |
| 2352 | // has its own rendering scope, so a split before one stays outside rendering, as a helper's does. | 2418 | // has its own rendering scope, so a split before one stays outside rendering, as a helper's does. |
| 2353 | inline void plan_statistics_segments(PreparedList& out) { | 2419 | inline void plan_statistics_segments(PreparedList& out) { |
| @@ -2785,9 +2851,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2785 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. | 2851 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. |
| 2786 | const bool upload = texture_copy->src.footprint; | 2852 | const bool upload = texture_copy->src.footprint; |
| 2787 | const ResourceBinding& image = upload ? p.binding : p.source; | 2853 | const ResourceBinding& image = upload ? p.binding : p.source; |
| 2788 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && | 2854 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) { |
| 2789 | p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) | 2855 | const auto& region = p.buffer_image_copies.front(); |
| 2790 | return ReplayResult::unsupported; | 2856 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); |
| 2857 | const std::uint32_t alignment = | ||
| 2858 | (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; | ||
| 2859 | if (alignment > 1 && region.bufferOffset % alignment && | ||
| 2860 | !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) | ||
| 2861 | return ReplayResult::unsupported; | ||
| 2862 | } | ||
| 2791 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && | 2863 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && |
| 2792 | !p.buffer_image_copies.empty() && | 2864 | !p.buffer_image_copies.empty() && |
| 2793 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; | 2865 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; |
| @@ -3016,13 +3088,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3016 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); | 3088 | const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); |
| 3017 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) | 3089 | if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) |
| 3018 | return ReplayResult::invalid_indirect_arguments; | 3090 | return ReplayResult::invalid_indirect_arguments; |
| 3019 | // The span is max_count * stride, the bytes the signature can walk, as D3D12 measures it: a record that | 3091 | // The range is the bytes the commands read, (max_count - 1) * stride + record_size: the rule recording |
| 3020 | // fits at the end of the buffer while its stride runs past it is refused (`240` with stride `20` in a | 3092 | // applies (d3d12_com.cpp, ExecuteIndirect) and the one vkCmdDraw*Indirect states. A zero max_count is a |
| 3021 | // `256`-byte buffer). A zero max_count still has to name an offset inside the buffer. | 3093 | // no-op that recording never passes on; if one arrives it reads nothing and needs no range. |
| 3022 | if (ind->argument_offset > p.binding.size || | 3094 | if (ind->max_count |
| 3023 | ind->max_count > (p.binding.size - ind->argument_offset) / ind->stride || | 3095 | ? !detail::indirect_range(p.binding, ind->argument_offset, |
| 3024 | !detail::indirect_range(p.binding, ind->argument_offset, | 3096 | VkDeviceSize(ind->max_count - 1) * ind->stride + record_size) |
| 3025 | VkDeviceSize(ind->max_count) * ind->stride)) | 3097 | : (p.binding.buffer_offset | ind->argument_offset) % sizeof(std::uint32_t) != 0) |
| 3026 | return ReplayResult::invalid_indirect_arguments; | 3098 | return ReplayResult::invalid_indirect_arguments; |
| 3027 | if (ind->count_buffer) { | 3099 | if (ind->count_buffer) { |
| 3028 | const ResourceBinding* cnt = resolve(ind->count_buffer); | 3100 | const ResourceBinding* cnt = resolve(ind->count_buffer); |
| @@ -3103,6 +3175,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3103 | VkDeviceSize offset = 0; | 3175 | VkDeviceSize offset = 0; |
| 3104 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; | 3176 | if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; |
| 3105 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; | 3177 | if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; |
| 3178 | if (!info->sources.empty()) { | ||
| 3179 | // dest_va is resolved by VA and may target a host-readable buffer; XDXR postbuild writes from compute. | ||
| 3180 | out.wrote_readback = true; | ||
| 3181 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; | ||
| 3182 | } | ||
| 3106 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && | 3183 | } else if (info->type == 0 && vk.write_acceleration_structures_properties && |
| 3107 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && | 3184 | vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && |
| 3108 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { | 3185 | vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { |
| @@ -3191,6 +3268,7 @@ public: | |||
| 3191 | retain(statistics_pool); | 3268 | retain(statistics_pool); |
| 3192 | list.statistics_pool = statistics_pool->pool; | 3269 | list.statistics_pool = statistics_pool->pool; |
| 3193 | list.statistics_mesh_pool = statistics_pool->mesh_pool; | 3270 | list.statistics_mesh_pool = statistics_pool->mesh_pool; |
| 3271 | list.statistics_primitives_pool = statistics_pool->primitives_pool; | ||
| 3194 | list.statistics_base = statistics_base; | 3272 | list.statistics_base = statistics_base; |
| 3195 | } else if (mesh) { | 3273 | } else if (mesh) { |
| 3196 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. | 3274 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. |
| @@ -3247,7 +3325,8 @@ public: | |||
| 3247 | const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, | 3325 | const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, |
| 3248 | std::uint8_t(1)) != kinds + saved.first + saved.count; | 3326 | std::uint8_t(1)) != kinds + saved.first + saved.count; |
| 3249 | run = {saved.segments->pool, saved.first, saved.count, run.offset, | 3327 | run = {saved.segments->pool, saved.first, saved.count, run.offset, |
| 3250 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds}; | 3328 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, |
| 3329 | saved.segments->primitives_pool, kinds}; | ||
| 3251 | if (any_mesh && !statistics) return ReplayResult::invalid_query; | 3330 | if (any_mesh && !statistics) return ReplayResult::invalid_query; |
| 3252 | if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; | 3331 | if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; |
| 3253 | if (statistics) needs_statistics_sum |= run.sum; | 3332 | if (statistics) needs_statistics_sum |= run.sum; |
| @@ -3314,6 +3393,9 @@ inline void end_statistics_segment(const PreparedList& list, std::uint32_t segme | |||
| 3314 | const ReplayFunctions& vk) { | 3393 | const ReplayFunctions& vk) { |
| 3315 | if (segment == PreparedQuery::no_segment) return; | 3394 | if (segment == PreparedQuery::no_segment) return; |
| 3316 | vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); | 3395 | vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); |
| 3396 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER). | ||
| 3397 | if (list.statistics_primitives_pool && list.statistics_mesh[segment]) | ||
| 3398 | vk.end_query(cb, list.statistics_primitives_pool, list.statistics_base + segment); | ||
| 3317 | } | 3399 | } |
| 3318 | 3400 | ||
| 3319 | inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, | 3401 | inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, |
| @@ -3322,6 +3404,12 @@ inline void begin_statistics_segment(const PreparedList& list, std::uint32_t seg | |||
| 3322 | const auto pool = statistics_segment_pool(list, segment); | 3404 | const auto pool = statistics_segment_pool(list, segment); |
| 3323 | vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); | 3405 | vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); |
| 3324 | vk.begin_query(cb, pool, list.statistics_base + segment, 0); | 3406 | vk.begin_query(cb, pool, list.statistics_base + segment, 0); |
| 3407 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, which the | ||
| 3408 | // mesh statistics pool cannot hold. | ||
| 3409 | if (list.statistics_primitives_pool && list.statistics_mesh[segment]) { | ||
| 3410 | vk.reset_query_pool(cb, list.statistics_primitives_pool, list.statistics_base + segment, 1); | ||
| 3411 | vk.begin_query(cb, list.statistics_primitives_pool, list.statistics_base + segment, 0); | ||
| 3412 | } | ||
| 3325 | } | 3413 | } |
| 3326 | 3414 | ||
| 3327 | } // namespace detail | 3415 | } // namespace detail |
| @@ -3382,7 +3470,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu | |||
| 3382 | if (!run.pool) { | 3470 | if (!run.pool) { |
| 3383 | vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); | 3471 | vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); |
| 3384 | } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { | 3472 | } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { |
| 3385 | vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset); | 3473 | vk.sum_statistics(cb, run.pool, run.mesh_pool, run.primitives_pool, run.mesh, run.first, run.count, |
| 3474 | dst, run.offset); | ||
| 3386 | } else if (run.sum && binary) { | 3475 | } else if (run.sum && binary) { |
| 3387 | vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); | 3476 | vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); |
| 3388 | } else if (run.sum || binary) { | 3477 | } else if (run.sum || binary) { |
| @@ -3535,16 +3624,23 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3535 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 3624 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 3536 | const bool discard = (texture->flags & texture_barrier_discard) || | 3625 | const bool discard = (texture->flags & texture_barrier_discard) || |
| 3537 | texture->layout_before == d3d12_layout::undefined; | 3626 | texture->layout_before == d3d12_layout::undefined; |
| 3627 | // LayoutAfter UNDEFINED from a defined layout: the contents are no longer needed (the memory is about to | ||
| 3628 | // be aliased, say). Vulkan has no transition into UNDEFINED (VUID-VkImageMemoryBarrier2-newLayout-01198), | ||
| 3629 | // so each piece keeps the layout it is in and the barrier only orders the accesses; the tracker keeps | ||
| 3630 | // that layout too. D3D12 has the next barrier on these subresources start from UNDEFINED, which discards | ||
| 3631 | // from whatever layout they are in. | ||
| 3632 | const bool release = texture->layout_after == d3d12_layout::undefined && | ||
| 3633 | texture->layout_before != d3d12_layout::undefined; | ||
| 3538 | const VkImageLayout new_layout = | 3634 | const VkImageLayout new_layout = |
| 3539 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); | 3635 | image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); |
| 3540 | LayoutPieces pieces; | 3636 | LayoutPieces pieces; |
| 3541 | if (discard) | 3637 | if (discard && !release) |
| 3542 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); | 3638 | pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); |
| 3543 | else { | 3639 | else { |
| 3544 | const VkImageLayout before = | 3640 | const VkImageLayout before = |
| 3545 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); | 3641 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); |
| 3546 | pieces = detail::current(tracker, id, range, before); | 3642 | pieces = detail::current(tracker, id, range, before); |
| 3547 | detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); | 3643 | if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); |
| 3548 | } | 3644 | } |
| 3549 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); | 3645 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); |
| 3550 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); | 3646 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); |
| @@ -3555,6 +3651,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3555 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); | 3651 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); |
| 3556 | std::uint32_t barrier_count = 0; | 3652 | std::uint32_t barrier_count = 0; |
| 3557 | for (const auto& piece : pieces) { | 3653 | for (const auto& piece : pieces) { |
| 3654 | // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. | ||
| 3655 | if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; | ||
| 3558 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; | 3656 | VkImageMemoryBarrier2& b = barriers[barrier_count++]; |
| 3559 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; | 3657 | b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; |
| 3560 | b.srcStageMask = src.stages; | 3658 | b.srcStageMask = src.stages; |
| @@ -3562,7 +3660,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3562 | b.srcAccessMask = src.access; | 3660 | b.srcAccessMask = src.access; |
| 3563 | b.dstAccessMask = dst.access; | 3661 | b.dstAccessMask = dst.access; |
| 3564 | b.oldLayout = piece.layout; | 3662 | b.oldLayout = piece.layout; |
| 3565 | b.newLayout = new_layout; | 3663 | b.newLayout = release ? piece.layout : new_layout; |
| 3566 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 3664 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3567 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 3665 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 3568 | b.image = p.binding.image; | 3666 | b.image = p.binding.image; |
| @@ -3570,11 +3668,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3570 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); | 3668 | if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); |
| 3571 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); | 3669 | if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); |
| 3572 | } | 3670 | } |
| 3573 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; | 3671 | if (barrier_count) { |
| 3574 | dependency.imageMemoryBarrierCount = barrier_count; | 3672 | VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; |
| 3575 | dependency.pImageMemoryBarriers = barriers; | 3673 | dependency.imageMemoryBarrierCount = barrier_count; |
| 3576 | vk.pipeline_barrier2(command_buffer, &dependency); | 3674 | dependency.pImageMemoryBarriers = barriers; |
| 3577 | if (tracker) tracker->set(id, range, new_layout); | 3675 | vk.pipeline_barrier2(command_buffer, &dependency); |
| 3676 | } | ||
| 3677 | if (tracker && !release) tracker->set(id, range, new_layout); | ||
| 3578 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { | 3678 | } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { |
| 3579 | if (p.skip) continue; | 3679 | if (p.skip) continue; |
| 3580 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); | 3680 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); |
| @@ -3615,10 +3715,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3615 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); | 3715 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); |
| 3616 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); | 3716 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); |
| 3617 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 3717 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); |
| 3618 | const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h | 3718 | float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h |
| 3619 | : p.binding.format == VK_FORMAT_D16_UNORM | 3719 | : p.binding.format == VK_FORMAT_D16_UNORM |
| 3620 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm | 3720 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm |
| 3621 | : depth_clear->depth; | 3721 | : depth_clear->depth; |
| 3722 | // Without the extension both clear commands require a depth in [0, 1], including for float images. | ||
| 3723 | if (!vk.depth_range_unrestricted) | ||
| 3724 | depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f); | ||
| 3622 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; | 3725 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; |
| 3623 | if (p.rects.empty()) { | 3726 | if (p.rects.empty()) { |
| 3624 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), | 3727 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), |
| @@ -4179,14 +4282,46 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 4179 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); | 4282 | vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); |
| 4180 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the | 4283 | // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the |
| 4181 | // image upright, and winding as D3D12 sees it. | 4284 | // image upright, and winding as D3D12 sees it. |
| 4182 | const Viewport& v = draw->viewport; | 4285 | if (graphics.viewport_with_count) { |
| 4183 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | 4286 | std::array<VkViewport, DrawViewports::max_count> vps{}; |
| 4184 | vk.set_viewport(command_buffer, 0, 1, &viewport); | 4287 | std::array<VkRect2D, DrawViewports::max_count> scs{}; |
| 4185 | const Rect& s = draw->scissor; | 4288 | const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; |
| 4186 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | 4289 | const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; |
| 4187 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | 4290 | const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count); |
| 4188 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | 4291 | for (std::uint32_t k = 0; k < count; ++k) { |
| 4189 | vk.set_scissor(command_buffer, 0, 1, &scissor); | 4292 | const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] |
| 4293 | : (k == 0 ? draw->viewport : Viewport{}); | ||
| 4294 | const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); | ||
| 4295 | if (valid_vp) { | ||
| 4296 | vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4297 | } else { | ||
| 4298 | // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing | ||
| 4299 | // rasterizes into an unbound/empty D3D12 viewport slot. | ||
| 4300 | vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; | ||
| 4301 | } | ||
| 4302 | if (valid_vp && k < sc_n) { | ||
| 4303 | const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; | ||
| 4304 | const std::int32_t left = std::max(0, s.left); | ||
| 4305 | const std::int32_t top = std::max(0, s.top); | ||
| 4306 | scs[k] = {{left, top}, | ||
| 4307 | {std::uint32_t(std::max(0, s.right - left)), | ||
| 4308 | std::uint32_t(std::max(0, s.bottom - top))}}; | ||
| 4309 | } else { | ||
| 4310 | scs[k] = {{0, 0}, {0, 0}}; | ||
| 4311 | } | ||
| 4312 | } | ||
| 4313 | vk.set_viewport_with_count(command_buffer, count, vps.data()); | ||
| 4314 | vk.set_scissor_with_count(command_buffer, count, scs.data()); | ||
| 4315 | } else { | ||
| 4316 | const Viewport& v = draw->viewport; | ||
| 4317 | const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; | ||
| 4318 | vk.set_viewport(command_buffer, 0, 1, &viewport); | ||
| 4319 | const Rect& s = draw->scissor; | ||
| 4320 | const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, | ||
| 4321 | {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), | ||
| 4322 | std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; | ||
| 4323 | vk.set_scissor(command_buffer, 0, 1, &scissor); | ||
| 4324 | } | ||
| 4190 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology | 4325 | // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology |
| 4191 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). | 4326 | // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). |
| 4192 | if (!draw->mesh) { | 4327 | if (!draw->mesh) { |
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd..33d84bf72 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h | |||
| @@ -46,12 +46,16 @@ public: | |||
| 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; | 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; |
| 47 | if (!loaded_ || !bytes) return false; | 47 | if (!loaded_ || !bytes) return false; |
| 48 | for (auto& chunk : current_.chunks) { | 48 | for (auto& chunk : current_.chunks) { |
| 49 | const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; | 49 | const VkDeviceSize rem = chunk.used % alignment; |
| 50 | if (start <= chunk.size && bytes <= chunk.size - start) { | 50 | const VkDeviceSize pad = rem ? alignment - rem : 0; |
| 51 | chunk.used = start + bytes; | 51 | if (pad <= chunk.size - chunk.used) { |
| 52 | buffer = chunk.buffer; | 52 | const VkDeviceSize start = chunk.used + pad; |
| 53 | offset = start; | 53 | if (bytes <= chunk.size - start) { |
| 54 | return true; | 54 | chunk.used = start + bytes; |
| 55 | buffer = chunk.buffer; | ||
| 56 | offset = start; | ||
| 57 | return true; | ||
| 58 | } | ||
| 55 | } | 59 | } |
| 56 | } | 60 | } |
| 57 | Chunk chunk; | 61 | Chunk chunk; |
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h index e0851098f..e1c1a233e 100644 --- a/runtime/src/xdxr_build.h +++ b/runtime/src/xdxr_build.h | |||
| @@ -133,7 +133,13 @@ public: | |||
| 133 | // update ignores `pair`. | 133 | // update ignores `pair`. |
| 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, | 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, |
| 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { | 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { |
| 136 | if (!loaded_ || layout.tlas) return false; | 136 | if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false; |
| 137 | std::uint64_t total = 0; | ||
| 138 | for (const auto& geo : geometries) { | ||
| 139 | total += geo.triangle_count; | ||
| 140 | if (total > layout.elements) return false; | ||
| 141 | } | ||
| 142 | if (total != layout.elements) return false; | ||
| 137 | Push p = base(layout, dst, scratch); | 143 | Push p = base(layout, dst, scratch); |
| 138 | if (pair && !update_from) p.flags |= flag_pair; | 144 | if (pair && !update_from) p.flags |= flag_pair; |
| 139 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 145 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -155,7 +161,6 @@ public: | |||
| 155 | dispatch(cb, t, t.count); | 161 | dispatch(cb, t, t.count); |
| 156 | first += geo.triangle_count; | 162 | first += geo.triangle_count; |
| 157 | } | 163 | } |
| 158 | if (first != layout.elements) return false; | ||
| 159 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); | 164 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); |
| 160 | return true; | 165 | return true; |
| 161 | } | 166 | } |
| @@ -164,7 +169,8 @@ public: | |||
| 164 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. | 169 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. |
| 165 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, | 170 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, |
| 166 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { | 171 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { |
| 167 | if (!loaded_ || !layout.tlas) return false; | 172 | if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances)) |
| 173 | return false; | ||
| 168 | Push p = base(layout, dst, scratch); | 174 | Push p = base(layout, dst, scratch); |
| 169 | p.bias = split(bias); | 175 | p.bias = split(bias); |
| 170 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 176 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -341,7 +347,7 @@ private: | |||
| 341 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). | 347 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). |
| 342 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { | 348 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { |
| 343 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); | 349 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); |
| 344 | vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); | 350 | vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1); |
| 345 | if (!barrier) return; | 351 | if (!barrier) return; |
| 346 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 352 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 347 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 353 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h index b44ce0372..3798b0fe7 100644 --- a/runtime/src/xdxr_descs.h +++ b/runtime/src/xdxr_descs.h | |||
| @@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10; | |||
| 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping | 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping |
| 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. | 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. |
| 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { | 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { |
| 102 | if (desc.size_in_bytes == 0 || desc.stream == nullptr) | 102 | if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr) |
| 103 | return nullptr; | 103 | return nullptr; |
| 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); | 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); |
| 105 | const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + | 105 | const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord); |
| 106 | desc.size_in_bytes); | 106 | for (uint64_t i = 0; i < count; ++i, ++record) { |
| 107 | for (; record < end; ++record) { | ||
| 108 | if (record->type == type) | 107 | if (record->type == type) |
| 109 | return record; | 108 | return record; |
| 110 | if (record->type > 2) | 109 | if (record->type > 2) |