diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 23b758897d..621a7d2867 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1067,8 +1067,52 @@ The compute path, end to end: - **Buffers:** vertex and index views resolve to buffers by VA (arena or upload). A view that runs past its buffer is cut at the buffer's end. An unbound vertex slot, or an indexed draw with no index buffer, reads the arena's reserved first 64 KiB, which is kept zero (stride 0), so it gets the zeros D3D12 gives. - - **Attachments:** they move to attachment layouts through the tracker, and the draw runs in a - dynamic-rendering scope. Its layer count is the smallest layer count of the bound views. + - **Attachments:** they move to attachment layouts through the tracker. Consecutive resolved direct draws share + a dynamic-rendering scope when the prepared graphics pipeline, attachment slots/images/views/ranges/layouts, + render area and layer count match. Its layer count is the smallest layer count of the bound views. Every other + command, skipped draw, indirect draw, statistics segment endpoint or GPU helper closes the scope first. Each + draw still binds its own state and push constants; only redundant attachment dependencies and scope boundaries + are removed (D3D-REPLAY-DRAW-SCOPE-RUNS). Vulkan guarantees fixed-function depth/stencil/blend ordering in + [rasterization order](https://docs.vulkan.org/spec/latest/chapters/primsrast.html#primsrast-order) within the + scope. `replay_rendering_scope_test` checks the boundaries with CPU mocks; `vk_rendering_scope_test` checks + overlapping depth-tested and blended draws against independently calculated pixels and offers `--bench` for + CPU replay and GPU/frame timings, without game files. + Build `vk_rendering_scope_test` with CMake and run it once with `LEONIDA_VK_VALIDATION=1` for correctness, + then without validation with `--bench` for timings. It compares 1,000/10,000 draws in compatible runs of + 1/4/16/64/all draws separated by global UAV barriers. Preparation and pipeline creation are outside the + measurements; `emit_ms` measures Vulkan command recording, `gpu_ms` brackets replay after draining the clears, + and `frame_ms` includes recording, submission, readback and waiting for GPU completion. Those are serialized + synthetic frame costs, not the game's FPS. Timings have no pass/fail threshold. + `--bench-mixed` adds runs of 2/3 draws split by UAV barriers, actual pipeline switches or color/depth target + switches, and direct runs interrupted by a single indirect draw. Its mixed case repeats 12 draw commands: + 2 direct, switch pipeline, 3 direct, switch targets, 2 direct, 1 indirect, 3 direct, barrier, 1 direct; + a barrier separates repetitions. Both target pairs are checked against independent pixel/depth expectations. + The default correctness run also covers this mixed case. Indirect/mixed cases print `SKIP` on a device + without `drawIndirectFirstInstance`; barrier/pipeline/target benchmarks still run. The fixture uses a + hand-written triangle and is not evidence of the frequency of compatible runs in a retail workload. + + `LEONIDA_RENDERING_SCOPE_STATS=1` enables aggregate-only scope diagnostics (D3D-REPLAY-SCOPE-METRICS). + The default emitter has no per-draw counter updates; a cached environment check selects an instrumented + template once per emitted list, including when device-fault checkpoints are enabled. The instrumented + emitter accumulates locally and merges once per list under a process-wide lock. Reports appear at 1/2/4/8/... + emitted lists and at normal exit if the totals have changed; abnormal termination can leave a partial report. + No identities, addresses, shader contents or title text are recorded. + + - `draws` counts non-skipped application draw commands reaching emission, including indirect commands, each + counted once irrespective of GPU arguments or quad expansion. `skipped` counts dropped stateful draw + commands separately. `indirect` is a subset of `draws`; `eligible` counts direct commands allowed to carry a + scope forward (no skip, indirect arguments, helper or statistics segment endpoint). + - `scopes` counts application draw rendering scopes, excluding scopes owned by clears and other helpers. + `shared_draws = draws - scopes` counts avoided per-draw scope pairs. `max_run` is the largest number of + application draw commands in a scope; `runs` bins scopes at 1/2/3/4–7/8–15/16–63/64–255/256+ commands. + - `ends` assigns exactly one reason to each closed draw scope. For an ineligible draw the first applicable + reason is skipped/indirect/helper/statistics; otherwise pipeline identity precedes attachment/area/layer + changes. Non-draw commands use barrier/copy/clear/query/predicate/dispatch/label/other. An isolated indirect + or helper draw can end both its preceding run and its own singleton scope, so reasons count scope ends, + rather than boundary commands. `list_end` closes any remaining scope. + - Totals count CPU replay attempts across all queues, including re-emitted lists and work that later fails + to submit or complete. They measure reuse opportunities, not completed GPU draws, frame time or retail FPS. + Disable the counters and validation when collecting benchmark timings. - **Viewport:** it is flipped (negative height), because translated vertex shaders write D3D clip coordinates; front-face winding then matches D3D12's. - Only the first viewport and scissor are used, and primitive restart is not modelled yet. @@ -3650,8 +3694,9 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a - Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with - the same attachments and `LOAD`/`STORE`. If the game does not use render passes, build a rendering scope per draw - from the bound RTVs/DSV and let explicit `Clear*View` calls do the clears. + the same attachments and `LOAD`/`STORE`. Draws recorded outside explicit render passes use the bound RTVs/DSV + with `LOAD`/`STORE`; consecutive compatible direct draws share a scope as described in section 3.2. + Explicit `Clear*View` calls still do the clears and end any preceding draw scope. ### 4.4 Fences, queues and frames in flight diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b9c726f6f3..51461eb9fa 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1993,6 +1993,7 @@ if(TARGET Vulkan::Headers) endif() foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test + vk_rendering_scope_test vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test vk_xdxr_build_test vk_queue_test vk_sandbox vk_console_heap_gpu_test) add_executable(${tool} test/${tool}.cpp) @@ -2079,10 +2080,10 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME depth24_convert COMMAND depth24_convert_test) set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) - # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). + # Self-checking Vulkan tests with synthetic inputs; each exits 77 without a Vulkan device (TEST-514). # indirect_clamp is registered next to its own add_executable above, where tests/test_ctest_registration.py # can see it. - foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu) + foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu vk_rendering_scope) add_test(NAME ${test} COMMAND ${test}_test) set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) endforeach() @@ -4660,6 +4661,15 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_cpu_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test) + # Compatible direct draws share rendering; all non-draw/helper/query boundaries close it (no GPU or game data). + add_executable(replay_rendering_scope_test test/replay_rendering_scope_test.cpp) + target_link_libraries(replay_rendering_scope_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_rendering_scope_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_rendering_scope COMMAND replay_rendering_scope_test) + add_test(NAME replay_rendering_scope_stats COMMAND replay_rendering_scope_test) + set_tests_properties(replay_rendering_scope_stats PROPERTIES ENVIRONMENT "LEONIDA_RENDERING_SCOPE_STATS=1") add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test) # mods.h: mod.json manifests and archetype swaps (docs/modding.md) add_executable(mods_test test/mods_test.cpp) diff --git a/runtime/README.md b/runtime/README.md index 07315a4b78..d6466c9453 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -325,6 +325,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | variable | default | what it changes | |---|---|---| +| `LEONIDA_RENDERING_SCOPE_STATS` | unset | *Diagnostic.* Exactly `1` enables aggregate draw rendering-scope counters in `src/vulkan_replay.h`: emitted/eligible/indirect/skipped draw commands, scopes, shared draws, run-length histogram and scope-end reasons. Counts are cumulative replay attempts, including repeated lists, rather than completed GPU work or FPS. Reports contain fixed labels and totals only, at powers of two emitted lists and normal exit. See [section 3.2](../docs/d3d12_vulkan.md#32-record-and-replay) for definitions. | | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | diff --git a/runtime/src/rendering_scope_stats.h b/runtime/src/rendering_scope_stats.h new file mode 100644 index 0000000000..316c4cdfa7 --- /dev/null +++ b/runtime/src/rendering_scope_stats.h @@ -0,0 +1,87 @@ +// Opt-in, aggregate-only diagnostics for application draw rendering scopes. No resource or shader identities. +#pragma once +#include +#include +#include +#include +#include +#include + +namespace leonida::scope_stats { +enum class End { pipeline, attachments, barrier, copy, clear, query, predicate, dispatch, label, + indirect, skipped, helper, statistics, other, list_end, count }; +inline constexpr std::array end_names{"pipeline", "attachments", "barrier", "copy", "clear", "query", "predicate", + "dispatch", "label", "indirect", "skipped", "helper", "statistics", "other", "list_end"}; +static_assert(end_names.size() == static_cast(End::count)); +inline constexpr std::array run_names{"1", "2", "3", "4-7", "8-15", "16-63", "64-255", "256+"}; + +struct Counts { + std::uint64_t lists = 0, draws = 0, eligible = 0, indirect = 0, skipped = 0, scopes = 0, max_run = 0; + std::array runs{}; + std::array ends{}; + + void add(const Counts& b) { + lists += b.lists; draws += b.draws; eligible += b.eligible; indirect += b.indirect; skipped += b.skipped; + scopes += b.scopes; + max_run = std::max(max_run, b.max_run); + for (unsigned i = 0; i < runs.size(); ++i) runs[i] += b.runs[i]; + for (unsigned i = 0; i < ends.size(); ++i) ends[i] += b.ends[i]; + } + + void finish(std::uint64_t length, End reason) { + ++scopes; + max_run = std::max(max_run, length); + const unsigned bucket = length <= 3 ? unsigned(length - 1) : length < 8 ? 3 : length < 16 ? 4 : + length < 64 ? 5 : length < 256 ? 6 : 7; + ++runs[bucket]; + ++ends[static_cast(reason)]; + } + + void report(std::FILE* out = stderr) const { + // One bounded line: at most 31 unsigned 64-bit values, with fixed, non-title labels. + char line[2048]; + int pos = std::snprintf(line, sizeof(line), + "[rt] rendering scopes: lists=%llu draws=%llu eligible=%llu indirect=%llu skipped=%llu scopes=%llu " + "shared_draws=%llu max_run=%llu runs=[", + ull(lists), ull(draws), ull(eligible), ull(indirect), ull(skipped), ull(scopes), + ull(draws - scopes), ull(max_run)); + for (unsigned i = 0; i < runs.size(); ++i) + pos += std::snprintf(line + pos, sizeof(line) - pos, "%s%s=%llu", i ? "," : "", run_names[i], ull(runs[i])); + pos += std::snprintf(line + pos, sizeof(line) - pos, "] ends=["); + for (unsigned i = 0; i < ends.size(); ++i) + pos += std::snprintf(line + pos, sizeof(line) - pos, "%s%s=%llu", i ? "," : "", end_names[i], ull(ends[i])); + std::fprintf(out, "%s]\n", line); + } +private: + static unsigned long long ull(std::uint64_t n) { return static_cast(n); } +}; + +inline bool enabled() { + static const bool value = [] { + const char* env = std::getenv("LEONIDA_RENDERING_SCOPE_STATS"); + return env && env[0] == '1' && env[1] == '\0'; + }(); + return value; +} + +// Merge once per emitted list, never once per draw. A lock keeps each report internally consistent when queues +// record on different threads. Powers of two bound the log volume; normal process exit reports the final totals. +struct Totals { + std::mutex mutex; + Counts counts; + std::uint64_t last_report = 0; + void add(const Counts& part) { + const std::lock_guard lock(mutex); + counts.add(part); + if ((counts.lists & (counts.lists - 1)) == 0) { + counts.report(); + last_report = counts.lists; + } + } + ~Totals() { if (counts.lists != last_report) counts.report(); } +}; +inline void publish(const Counts& part) { + static Totals totals; + totals.add(part); +} +} // namespace leonida::scope_stats diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 548fb4c17a..c91bed8598 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -35,6 +35,7 @@ #include "command_list.h" #include "indirect_draw_stats.h" +#include "rendering_scope_stats.h" #include "deferred_image_binding.h" #include "vulkan_device_fault.h" #include "depth24.h" @@ -1540,6 +1541,29 @@ struct PreparedDraw { } }; +// Fixed-function attachment operations are ordered within a rendering scope. Keep compatible direct draws in +// that scope instead of storing/loading the same attachments and ordering them again between every draw. +// Pipeline identity deliberately keeps this conservative (including depth/stencil attachment selection). +inline bool same_rendering_scope(const PreparedDraw& a, const PreparedDraw& b) { + if (a.graphics != b.graphics || a.pipeline != b.pipeline || a.area.width != b.area.width || + a.area.height != b.area.height || a.layers != b.layers || a.colors.size() != b.colors.size()) + return false; + const auto same_attachment = [](const PreparedDraw::Attachment& x, const PreparedDraw::Attachment& y, + VkImageLayout wanted) { + if (x.id != y.id) return false; + if (!x.id) return true; // neither slot participates in rendering + return x.view == y.view && x.binding.image == y.binding.image && + image_layout(x.binding, wanted) == image_layout(y.binding, wanted) && + x.range.aspectMask == y.range.aspectMask && x.range.baseMipLevel == y.range.baseMipLevel && + x.range.levelCount == y.range.levelCount && x.range.baseArrayLayer == y.range.baseArrayLayer && + x.range.layerCount == y.range.layerCount; + }; + for (std::size_t slot = 0; slot < a.colors.size(); ++slot) + if (!same_attachment(a.colors[slot], b.colors[slot], VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)) + return false; + return same_attachment(a.depth, b.depth, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); +} + // D3D converts a float clear value to a normalised format by rounding to nearest even, so an exact tie goes to the // even neighbour (0.5 on 8 bits is 128). Vulkan leaves the rounding of ties to the GPU, and NVIDIA writes 127, one // step below WARP and AMD. The value is rounded here and handed over as the exact fraction, which no GPU rounds @@ -3210,8 +3234,8 @@ inline constexpr VkQueryPipelineStatisticFlags kForbiddenMeshStatisticsFlags = // 0. A query that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in // the full pool or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of // its own kind. -// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw -// has its own rendering scope, so a split before one stays outside rendering, as a helper's does. +// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Replay +// closes any shared draw rendering scope before a segment boundary or helper, keeping both outside rendering. inline void plan_statistics_segments(PreparedList& out) { detail::PreparedQuery* begin = nullptr; // A split point (a helper or a resolve), or a draw: kind 0 vertex, 1 mesh. @@ -4637,9 +4661,10 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& // `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open // is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer // (close_labels). Without it, the list's own events are balanced at its end. -template -inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, - LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { +template +inline void emit_commands_impl(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, + LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints, + scope_stats::Counts* collected = nullptr) { std::uint32_t own_labels = 0; std::uint32_t& labels = open_labels ? *open_labels : own_labels; const auto commands = prepared.list->commands(); @@ -4649,6 +4674,19 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const bool predicates = vk.begin_conditional_rendering != nullptr; VkConditionalRenderingBeginInfoEXT predicate{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; std::size_t next_query = 0; + const detail::PreparedDraw* rendering_draw = nullptr; + std::uint64_t run_length = 0; + if constexpr (Profile) ++collected->lists; + const auto end_rendering = [&](scope_stats::End reason = scope_stats::End::list_end) { + if (rendering_draw) { + vk.end_rendering(command_buffer); + rendering_draw = nullptr; + if constexpr (Profile) { + collected->finish(run_length, reason); + run_length = 0; + } + } + }; // A dispatch honours conditional rendering and a copy does not (the layer runs copies unpredicated), so the // conversion around a copy must run whatever the predicate says: end it for the dispatch and begin it again. const auto run_depth24 = [&](const Depth24Job& job) { @@ -4672,6 +4710,50 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const auto& command = commands[i]; const auto& p = prepared.commands[i]; const auto raster = draw_command(command); + const auto* next_draw = raster.state ? &prepared.draws[p.draw] : nullptr; + const bool keep_rendering = next_draw && !raster.arguments && !next_draw->skipped && + !next_draw->quad_indices.buffer && !p.indirect_clamp.buffer && + p.statistics_end == detail::PreparedQuery::no_segment && + p.statistics_begin == detail::PreparedQuery::no_segment; + scope_stats::End boundary = scope_stats::End::other; + if constexpr (Profile) { + // The first applicable reason wins. Reasons count scope ends, so an isolated indirect/helper draw + // can close both the preceding direct run and its own singleton scope for the same reason. + if (next_draw) { + if (next_draw->skipped) { ++collected->skipped; boundary = scope_stats::End::skipped; } + else { + ++collected->draws; + collected->eligible += keep_rendering; + collected->indirect += raster.arguments != nullptr; + boundary = raster.arguments ? scope_stats::End::indirect : + next_draw->quad_indices.buffer || p.indirect_clamp.buffer ? scope_stats::End::helper : + !keep_rendering ? scope_stats::End::statistics : + rendering_draw && (rendering_draw->graphics != next_draw->graphics || + rendering_draw->pipeline != next_draw->pipeline) ? scope_stats::End::pipeline : + scope_stats::End::attachments; + } + } else if (std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command) || std::holds_alternative(command)) + boundary = scope_stats::End::barrier; + else if (std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command) || + std::holds_alternative(command)) + boundary = scope_stats::End::copy; + else if (std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command)) boundary = scope_stats::End::clear; + else if (std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command)) boundary = scope_stats::End::query; + else if (std::holds_alternative(command)) boundary = scope_stats::End::predicate; + else if (std::holds_alternative(command) || std::holds_alternative(command)) + boundary = scope_stats::End::dispatch; + else if (std::holds_alternative(command)) boundary = scope_stats::End::label; + } + // Close before queries, barriers, copies, predicate changes, helper dispatches and segment resets. Even a + // dropped draw ends the run: only consecutive compatible direct draws share a scope. + if (rendering_draw && (!keep_rendering || !detail::same_rendering_scope(*rendering_draw, *next_draw))) + end_rendering(boundary); if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { if constexpr (Checkpoints) if (std::holds_alternative(command)) @@ -4679,7 +4761,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); continue; } - // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too. + // Helpers and both segment endpoints run outside rendering scopes. const auto end_statistics = [&] { detail::end_statistics_segment(prepared, p.statistics_end, command_buffer, vk); }; @@ -5499,6 +5581,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const Draw* draw = raster.state; const detail::PreparedDraw& d = prepared.draws[p.draw]; if (d.skipped) continue; // could not be resolved in prepare: dropped + if constexpr (Profile) ++run_length; // The clamp pass for a stateful indirect draw (vulkan_indirect_clamp.h) runs before vkCmdBeginRendering, // because its copy and transfer barrier are not allowed inside a dynamic-rendering scope. It is a helper // dispatch, so a pipeline-statistics query must not count it, and it runs even under a false predicate. @@ -5512,44 +5595,47 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::draw, d.pipeline, draw->pipeline); - constexpr VkAccessFlags color_access = - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - constexpr VkAccessFlags depth_access = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - constexpr VkPipelineStageFlags depth_stages = - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - std::array colors; - colors.fill({VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}); - for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { - const auto& a = d.colors[slot]; - if (!a.id) continue; // an unbound slot: no image view, writes are dropped - const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, a, layout, color_access, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); - colors[slot].imageView = a.view; - colors[slot].imageLayout = layout; - colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - if (d.depth.id) { - const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, - separate); - depth.imageView = d.depth.view; - depth.imageLayout = layout; - depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, d.area}; - rendering.layerCount = d.layers; // array views: SV_RenderTargetArrayIndex picks the layer - rendering.colorAttachmentCount = std::uint32_t(d.colors.size()); - rendering.pColorAttachments = colors.data(); const GraphicsPipeline& graphics = *d.graphics; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.pDepthAttachment = &depth; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; - vk.begin_rendering(command_buffer, &rendering); + if (!rendering_draw) { + constexpr VkAccessFlags color_access = + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + constexpr VkAccessFlags depth_access = + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + constexpr VkPipelineStageFlags depth_stages = + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + std::array colors; + colors.fill({VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}); + for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { + const auto& a = d.colors[slot]; + if (!a.id) continue; // an unbound slot: no image view, writes are dropped + const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + detail::to_attachment(vk, command_buffer, a, layout, color_access, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); + colors[slot].imageView = a.view; + colors[slot].imageLayout = layout; + colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; + if (d.depth.id) { + const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, + separate); + depth.imageView = d.depth.view; + depth.imageLayout = layout; + depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + } + VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; + rendering.renderArea = {{0, 0}, d.area}; + rendering.layerCount = d.layers; // array views: SV_RenderTargetArrayIndex picks the layer + rendering.colorAttachmentCount = std::uint32_t(d.colors.size()); + rendering.pColorAttachments = colors.data(); + if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.pDepthAttachment = &depth; + if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; + vk.begin_rendering(command_buffer, &rendering); + rendering_draw = &d; + } ShaderUserData data{}; std::copy(draw->user_data.begin(), draw->user_data.end(), data.s); @@ -5699,14 +5785,27 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } else { vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); } - vk.end_rendering(command_buffer); + if (!keep_rendering) end_rendering(boundary); } } + end_rendering(); // Predication does not carry over to the next command list. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); if (!open_labels) close_labels(command_buffer, vk, own_labels); } +template +inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, + LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { + if (scope_stats::enabled()) { + scope_stats::Counts counts; + emit_commands_impl(prepared, command_buffer, vk, tracker, open_labels, checkpoints, &counts); + scope_stats::publish(counts); + } else { + emit_commands_impl(prepared, command_buffer, vk, tracker, open_labels, checkpoints); + } +} + inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { emit_commands(prepared, command_buffer, vk, tracker, open_labels, nullptr); diff --git a/runtime/test/replay_rendering_scope_test.cpp b/runtime/test/replay_rendering_scope_test.cpp new file mode 100644 index 0000000000..a825c6a0e4 --- /dev/null +++ b/runtime/test/replay_rendering_scope_test.cpp @@ -0,0 +1,594 @@ +// CPU regression for replay's consecutive draw rendering scopes. Synthetic prepared resources and recording +// Vulkan functions check draw state/order and scope boundaries without a driver, GPU or game files. +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace leonida; + +template T handle(std::uintptr_t value) { return reinterpret_cast(value); } + +bool ok = true; +void check(bool condition, const char* description) { + if (!condition) { std::fprintf(stderr, "FAIL: %s\n", description); ok = false; } +} + +struct DrawState { + VkPipeline pipeline{}; + VkDescriptorSet descriptors{}; + ShaderUserData data{}; + std::vector viewports; + std::vector scissors; + VkPrimitiveTopology topology{}; + VkBool32 restart{}; + std::uint32_t front = 0, back = 0; + std::array blend{}; + VkBuffer vertex{}, index{}; + VkDeviceSize vertex_offset = 0, vertex_size = 0, stride = 0, index_offset = 0; + VkIndexType index_type{}; + std::string kind; + std::uint32_t count = 0, instances = 0, first = 0, first_instance = 0; + std::int32_t base = 0; +}; + +struct Rendering { + VkRect2D area{}; + std::uint32_t layers = 0; + std::vector colors; + VkRenderingAttachmentInfo depth{}, stencil{}; + bool has_depth = false, has_stencil = false; +}; + +struct Recorder { + static Recorder* current; + bool rendering = false; + DrawState state; + std::vector draws; + std::vector scopes; + std::vector events; + std::size_t ends = 0; + + void outside(const char* event) { + check(!rendering, "barriers, helpers and non-draw commands execute outside rendering"); + events.emplace_back(event); + } + void draw(const char* kind, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + check(rendering, "every draw executes inside rendering"); + state.kind = kind; + state.count = count; state.instances = instances; state.first = first; + state.base = base; state.first_instance = first_instance; + draws.push_back(state); + events.emplace_back(kind); + } + + ReplayFunctions functions() { + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo* info) { + auto& r = *current; + check(!r.rendering, "rendering scopes never nest"); + r.rendering = true; + Rendering scope{}; + scope.area = info->renderArea; scope.layers = info->layerCount; + if (info->colorAttachmentCount) + scope.colors.assign(info->pColorAttachments, info->pColorAttachments + info->colorAttachmentCount); + if (info->pDepthAttachment) { scope.has_depth = true; scope.depth = *info->pDepthAttachment; } + if (info->pStencilAttachment) { scope.has_stencil = true; scope.stencil = *info->pStencilAttachment; } + r.scopes.push_back(std::move(scope)); + r.events.emplace_back("begin"); + }; + vk.end_rendering = +[](VkCommandBuffer) { + auto& r = *current; + check(r.rendering, "end rendering has a matching begin"); + r.rendering = false; ++r.ends; r.events.emplace_back("end"); + }; + vk.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) { current->outside("barrier"); }; + vk.pipeline_barrier2 = +[](VkCommandBuffer, const VkDependencyInfo*) { current->outside("barrier2"); }; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint point, VkPipeline pipeline) { + if (point == VK_PIPELINE_BIND_POINT_COMPUTE) current->outside("bind_compute"); + else current->state.pipeline = pipeline; + }; + vk.bind_descriptor_sets = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout, std::uint32_t, + std::uint32_t count, const VkDescriptorSet* sets, std::uint32_t, + const std::uint32_t*) { + check(count == 1, "one bindless descriptor set is bound"); + current->state.descriptors = sets[0]; + }; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t offset, + std::uint32_t size, const void* data) { + check(offset == 0 && size == sizeof(ShaderUserData), "draw user-data block stays complete"); + std::memcpy(¤t->state.data, data, sizeof(ShaderUserData)); + }; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t first, std::uint32_t count, const VkViewport* values) { + check(first == 0, "viewports start at zero"); + current->state.viewports.assign(values, values + count); + }; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t first, std::uint32_t count, const VkRect2D* values) { + check(first == 0, "scissors start at zero"); + current->state.scissors.assign(values, values + count); + }; + vk.set_viewport_with_count = +[](VkCommandBuffer, std::uint32_t count, const VkViewport* values) { + current->state.viewports.assign(values, values + count); + }; + vk.set_scissor_with_count = +[](VkCommandBuffer, std::uint32_t count, const VkRect2D* values) { + current->state.scissors.assign(values, values + count); + }; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology value) { current->state.topology = value; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32 value) { current->state.restart = value; }; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags face, std::uint32_t value) { + if (face & VK_STENCIL_FACE_FRONT_BIT) current->state.front = value; + if (face & VK_STENCIL_FACE_BACK_BIT) current->state.back = value; + }; + vk.set_blend_constants = +[](VkCommandBuffer, const float* values) { + std::copy_n(values, 4, current->state.blend.begin()); + }; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t count, const VkBuffer* buffers, + const VkDeviceSize* offsets, const VkDeviceSize* sizes, const VkDeviceSize* strides) { + check(count == 1, "vertex buffer binding is recorded"); + auto& s = current->state; + s.vertex = buffers[0]; s.vertex_offset = offsets[0]; s.vertex_size = sizes[0]; s.stride = strides[0]; + }; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + current->state.index = buffer; current->state.index_offset = offset; current->state.index_type = type; + }; + vk.draw = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::uint32_t first_instance) { current->draw("draw", count, instances, first, 0, first_instance); }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + current->draw("indexed", count, instances, first, base, first_instance); + }; + vk.draw_mesh_tasks = +[](VkCommandBuffer, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + current->draw("mesh", x, y, z, 0, 0); + }; + vk.draw_indirect = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, std::uint32_t count, std::uint32_t stride) { + current->draw("indirect", count, stride, 0, 0, 0); + }; + vk.copy_buffer = +[](VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t, const VkBufferCopy*) { + current->outside("copy"); + }; + vk.dispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) { current->outside("dispatch"); }; + vk.clear_color_image = +[](VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue*, + std::uint32_t, const VkImageSubresourceRange*) { current->outside("clear_image"); }; + vk.clear_attachments = +[](VkCommandBuffer, std::uint32_t, const VkClearAttachment*, std::uint32_t, + const VkClearRect*) { + check(current->rendering, "rectangle clear owns a rendering scope"); + current->events.emplace_back("clear_rect"); + }; + vk.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) { current->outside("reset_query"); }; + vk.begin_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) { current->outside("begin_query"); }; + vk.end_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t) { current->outside("end_query"); }; + vk.emit_quad_indices = [](VkCommandBuffer, const QuadIndexExpansion&) { current->outside("quad_helper"); }; + vk.emit_indirect_clamp = [](VkCommandBuffer, const ClampedIndirect&) { current->outside("clamp_helper"); }; + vk.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) { current->outside("capture_predicate"); }; + vk.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) { + current->outside("begin_predicate"); + }; + vk.end_conditional_rendering = +[](VkCommandBuffer) { current->outside("end_predicate"); }; + vk.begin_label = +[](VkCommandBuffer, const VkDebugUtilsLabelEXT*) { current->outside("begin_label"); }; + vk.end_label = +[](VkCommandBuffer) { current->outside("end_label"); }; + vk.insert_label = +[](VkCommandBuffer, const VkDebugUtilsLabelEXT*) { current->outside("insert_label"); }; + vk.quad_indices = handle(90); + vk.quad_index_count = 12; + vk.heap_base = 0x12340000; + return vk; + } +}; +Recorder* Recorder::current = nullptr; + +struct Fixture { + Recorder recorder; + ReplayFunctions vk = recorder.functions(); + GraphicsPipeline graphics{}, other{}; + QueryPool query{}; + CommandList list; + PreparedList prepared; + + Fixture() { + graphics.pipeline = handle(10); + graphics.layout = handle(11); + graphics.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + graphics.bindless_set = handle(12); + graphics.code_base = 0x87650000; + graphics.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + graphics.strip_cut = 1; + other = graphics; + query.pool = handle(80); + prepared.list = &list; + prepared.statistics_pool = query.pool; + prepared.statistics_mesh = {0, 0}; + } + + static detail::PreparedDraw::Attachment attachment(ResourceId id, bool depth = false) { + detail::PreparedDraw::Attachment a{}; + a.id = id; + a.binding.image = handle(100 + id); + a.binding.format = depth ? VK_FORMAT_D32_SFLOAT_S8_UINT : VK_FORMAT_R8G8B8A8_UNORM; + a.binding.aspects = depth ? depth_stencil_aspects : VK_IMAGE_ASPECT_COLOR_BIT; + a.binding.width = 640; a.binding.height = 480; + a.binding.array_layers = 4; a.binding.mip_levels = 2; + a.range = {a.binding.aspects, 0, 1, 0, 1}; + a.view = handle(200 + id); + return a; + } + + static Draw draw(std::uint32_t n = 0) { + Draw d{}; + d.pipeline = 1; d.count = 3 + n; d.instances = 2; d.first = n; d.first_instance = 4 + n; + d.topology = 4; // triangle list + d.viewport = {float(n), float(n + 1), 320, 240, 0, 1}; + d.scissor = {std::int32_t(n), std::int32_t(n + 1), 300, 200}; + d.stencil_front = 10 + n; d.stencil_back = 20 + n; + d.blend_factor = {float(n), 0.25f, 0.5f, 1}; + d.user_data.fill(0x100 + n); + return d; + } + + std::size_t add_draw(Draw draw = Fixture::draw(), const IndirectDrawArgs* indirect = nullptr) { + check(indirect ? list.draw_indirect(std::move(draw), *indirect) : list.draw(draw), "draw records"); + const auto index = prepared.commands.size(); + auto& command = prepared.commands.emplace_back(); + command.draw = std::uint32_t(prepared.draws.size()); + auto& d = prepared.draws.emplace_back(); + d.graphics = &graphics; d.pipeline = graphics.pipeline; + d.colors = {attachment(1)}; d.depth = attachment(2, true); + d.area = {640, 480}; d.layers = 1; + d.vertex_buffers = {handle(30)}; + d.vertex_offsets = {0}; d.vertex_sizes = {1024}; d.vertex_strides = {16}; + d.index_buffer = handle(31); d.index_offset = 32; d.index_type = VK_INDEX_TYPE_UINT16; + d.indirect_buffer = handle(32); + return index; + } + + detail::PreparedDraw& at(std::size_t command) { return prepared.draws[prepared.commands[command].draw]; } + detail::Prepared& add_command() { return prepared.commands.emplace_back(); } + void emit(scope_stats::Counts* counts = nullptr) { + if (!list.closed()) check(list.close(), "list closes"); + check(list.commands().size() == prepared.commands.size(), "prepared commands match the list"); + Recorder::current = &recorder; + if (counts) emit_commands_impl(prepared, VK_NULL_HANDLE, vk, nullptr, nullptr, nullptr, counts); + else leonida::emit(prepared, VK_NULL_HANDLE, vk); + check(!recorder.rendering && recorder.ends == recorder.scopes.size(), "list ends with all rendering scopes closed"); + } +}; + +std::vector actions(const Recorder& r) { + std::vector out; + for (const auto& event : r.events) + if (event != "barrier" && event != "barrier2" && event != "bind_compute") out.push_back(event); + return out; +} + +void compatible_state() { + Fixture f; + f.add_draw(Fixture::draw()); + Draw second = Fixture::draw(1); + second.indexed = true; second.topology = 5; second.base_vertex = -7; + const auto id = f.add_draw(second); + auto& d = f.at(id); + d.vertex_buffers[0] = handle(40); d.vertex_offsets[0] = 128; d.vertex_sizes[0] = 512; + d.vertex_strides[0] = 24; d.index_buffer = handle(41); d.index_offset = 64; + f.emit(); + check(f.recorder.scopes.size() == 1, "consecutive compatible direct and indexed draws share one scope"); + check(actions(f.recorder) == std::vector{"begin", "draw", "indexed", "end"}, "draw order is unchanged"); + check(std::count(f.recorder.events.begin(), f.recorder.events.end(), "barrier") == 2, + "shared color and depth attachments are ordered once before the run"); + check(f.recorder.draws.size() == 2, "both draws are emitted"); + if (f.recorder.draws.size() != 2 || f.recorder.scopes.empty()) return; + const auto& a = f.recorder.draws[0]; const auto& b = f.recorder.draws[1]; + check(a.data.s[0] == 0x100 && b.data.s[31] == 0x101 && b.data.heap_base == f.vk.heap_base && + b.data.code_base == f.graphics.code_base, "user data and address bases are pushed for each draw"); + check(a.viewports[0].x == 0 && b.viewports[0].x == 1 && b.viewports[0].y == 242 && + b.viewports[0].height == -240 && b.scissors[0].offset.x == 1 && b.scissors[0].offset.y == 2, + "viewport and scissor changes reach the second draw"); + check(a.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && b.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP && + !a.restart && b.restart, "topology and primitive restart change inside the shared scope"); + check(b.front == 11 && b.back == 21 && b.blend == second.blend_factor, + "both stencil references and blend constants update for every draw"); + check(b.pipeline == f.graphics.pipeline && b.descriptors == f.graphics.bindless_set && + b.vertex == handle(40) && b.vertex_offset == 128 && b.vertex_size == 512 && b.stride == 24 && + b.index == handle(41) && b.index_offset == 64 && b.index_type == VK_INDEX_TYPE_UINT16, + "pipeline, descriptors, vertex and index bindings remain per draw"); + check(b.count == second.count && b.instances == second.instances && b.first == second.first && + b.base == -7 && b.first_instance == second.first_instance, "indexed draw arguments preserve bases and instances"); + const auto& scope = f.recorder.scopes[0]; + check(scope.colors.size() == 1 && scope.colors[0].imageView == Fixture::attachment(1).view && + scope.colors[0].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD && scope.colors[0].storeOp == VK_ATTACHMENT_STORE_OP_STORE && + scope.has_depth && scope.has_stencil && scope.depth.imageView == scope.stencil.imageView && + scope.area.extent.width == 640 && scope.area.extent.height == 480 && scope.layers == 1, + "merged rendering keeps the original attachment load/store, depth/stencil, extent and layers"); +} + +void changed_targets() { + using Change = std::function; + const std::vector> changes = { + {"different color image", [](auto&, auto& d) { d.colors[0] = Fixture::attachment(3); }}, + {"different color mip view", [](auto&, auto& d) { d.colors[0].view = handle(301); d.colors[0].range.baseMipLevel = 1; }}, + {"different depth view", [](auto&, auto& d) { d.depth.view = handle(302); }}, + {"unbound color slot", [](auto&, auto& d) { d.colors[0] = {}; }}, + {"additional MRT slot", [](auto&, auto& d) { d.colors.push_back(Fixture::attachment(3)); }}, + {"different color layout", [](auto&, auto& d) { d.colors[0].binding.simultaneous_access = true; }}, + {"different rendering width", [](auto&, auto& d) { d.area.width = 320; }}, + {"different rendering height", [](auto&, auto& d) { d.area.height = 240; }}, + {"different array layer count", [](auto&, auto& d) { d.layers = 2; d.colors[0].range.layerCount = 2; }}, + {"different array layer slice", [](auto&, auto& d) { d.colors[0].range.baseArrayLayer = 1; d.colors[0].view = handle(303); }}, + {"different pipeline variant", [](auto&, auto& d) { d.pipeline = handle(50); }}, + {"different depth/stencil pipeline", [](auto& f, auto& d) { f.other.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; d.graphics = &f.other; }}, + {"no depth attachment", [](auto&, auto& d) { d.depth = {}; }}, + }; + for (const auto& [description, change] : changes) { + Fixture f; + f.add_draw(); + const auto b = f.add_draw(); change(f, f.at(b)); + const auto c = f.add_draw(); f.at(c) = f.at(b); + f.emit(); + check(f.recorder.scopes.size() == 2, description); + check(actions(f.recorder) == std::vector{"begin", "draw", "end", "begin", "draw", "draw", "end"}, + "a changed rendering configuration closes the old scope and begins a compatible new run"); + } + Fixture mrt; + for (int n = 0; n < 2; ++n) { + auto& d = mrt.at(mrt.add_draw()); + d.colors = n ? std::vector{Fixture::attachment(3), Fixture::attachment(1)} + : std::vector{Fixture::attachment(1), Fixture::attachment(3)}; + } + mrt.emit(); + check(mrt.recorder.scopes.size() == 2 && mrt.recorder.scopes[1].colors[0].imageView == Fixture::attachment(3).view, + "MRT attachment order is significant"); +} + +void attachmentless_and_multiple_viewports() { + Fixture f; + f.graphics.viewport_with_count = true; + f.graphics.depth_aspects = 0; + f.vk.graphics_pipeline = [&](std::uintptr_t) -> const GraphicsPipeline* { return &f.graphics; }; + f.vk.buffer_at = [](std::uint64_t, std::uint64_t&, VkBuffer&, VkDeviceSize&) { return false; }; + f.vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return VkImageView{}; }; + for (std::uint32_t n = 0; n < 3; ++n) { + auto draw = Fixture::draw(n); + draw.viewport = {0, 0, 320, 240, 0, 1}; + auto views = std::make_shared(); + views->viewport_count = views->scissor_count = 2; + views->viewports[0] = draw.viewport; + views->viewports[1] = n == 2 ? Viewport{400, 20, 400, 32, 0, 1} : Viewport{10 + float(n), 20, 64, 32, 0, 1}; + views->scissors[0] = draw.scissor; views->scissors[1] = {10, 20, 74, 52}; + draw.viewports = views; + check(f.list.draw(draw), "attachmentless draw records"); + } + check(f.list.close(), "attachmentless list closes"); + check(prepare(f.list, [](ResourceId) -> const ResourceBinding* { return nullptr; }, f.vk, f.prepared) == ReplayResult::success, + "attachmentless rendering extents prepare from real viewport snapshots"); + f.emit(); + check(f.recorder.scopes.size() == 2 && f.recorder.scopes[0].area.extent.width == 320 && + f.recorder.scopes[1].area.extent.width == 800, + "attachmentless draws split when their viewport-derived rendering extent changes"); + check(f.recorder.draws.size() == 3 && f.recorder.draws[1].viewports.size() == 2 && + f.recorder.draws[1].viewports[1].x == 11 && f.recorder.draws[1].scissors.size() == 2, + "multiple viewport/scissor snapshots update inside a shared scope"); +} + +void non_draw_boundaries() { + for (int kind = 0; kind < 4; ++kind) { + Fixture f; + f.add_draw(); + auto& p = f.add_command(); + if (kind == 0) check(f.list.uav_barrier({0}), "UAV barrier records"); + if (kind == 1) { + check(f.list.copy_buffer({5, 0, 6, 0, 32}), "copy records"); + p.binding.buffer = handle(60); p.source.buffer = handle(61); + p.buffer_copies = {{0, 0, 32}}; + } + if (kind == 2) { + check(f.list.dispatch({2, {}, 1, 1, 1}), "dispatch records"); + p.pipeline.pipeline = handle(62); p.pipeline.layout = f.graphics.layout; + } + if (kind == 3) { + check(f.list.clear_render_target({1, 0, 0, 1}, {0, 0, 0, 1}), "clear records"); + p.binding = Fixture::attachment(1).binding; p.range = Fixture::attachment(1).range; + p.clear_format = p.binding.format; + } + f.add_draw(); f.add_draw(); + scope_stats::Counts counts; + f.emit(&counts); + check(f.recorder.scopes.size() == 2 && f.recorder.draws.size() == 3, + "barrier, copy, dispatch and image clear each split consecutive draw runs"); + const auto reason = std::array{scope_stats::End::barrier, scope_stats::End::copy, + scope_stats::End::dispatch, scope_stats::End::clear}[kind]; + check(counts.draws == 3 && counts.eligible == 3 && counts.scopes == 2 && + counts.runs[0] == 1 && counts.runs[1] == 1 && counts.ends[unsigned(reason)] == 1 && + counts.ends[unsigned(scope_stats::End::list_end)] == 1, + "non-draw boundaries report application scopes and their actual end reasons"); + } + Fixture rect; + rect.add_draw(); + check(rect.list.clear_render_target({1, 0, 0, 1}, {0, 0, 0, 1}), "rectangle clear records"); + auto& p = rect.add_command(); + p.binding = Fixture::attachment(1).binding; p.range = Fixture::attachment(1).range; + p.view = Fixture::attachment(1).view; p.clear_format = p.binding.format; + p.rects = {{{{0, 0}, {16, 16}}, 0, 1}}; + rect.add_draw(); + scope_stats::Counts rect_counts; + rect.emit(&rect_counts); + check(rect_counts.draws == 2 && rect_counts.scopes == 2 && rect_counts.runs[0] == 2, + "internal rectangle-clear rendering is excluded from draw scope metrics"); + check(actions(rect.recorder) == std::vector{"begin", "draw", "end", "begin", "clear_rect", "end", "begin", "draw", "end"}, + "rectangle clears own a separate balanced rendering scope"); +} + +void ineligible_draws() { + for (int kind = 0; kind < 6; ++kind) { + Fixture f; + f.add_draw(); + Draw draw = Fixture::draw(); + IndirectDrawArgs arguments{7, 0, 16, 1}; + if (kind == 2) { draw.indexed = true; draw.topology = topology_quad_list; draw.count = 8; } + const auto b = f.add_draw(draw, kind == 1 ? &arguments : nullptr); + auto& p = f.prepared.commands[b]; auto& d = f.at(b); + if (kind == 0) d.skipped = true; + if (kind == 2) { d.quad_indices.buffer = handle(70); d.quad_indices.quads = 2; } + if (kind == 3) p.indirect_clamp.buffer = handle(71); + if (kind == 4) p.statistics_end = 0; + if (kind == 5) p.statistics_begin = 1; + f.add_draw(); f.add_draw(); + scope_stats::Counts counts; + f.emit(&counts); + check(f.recorder.scopes.size() == (kind == 0 ? 2u : 3u), + "skipped, indirect, helper and statistics-endpoint draws cannot carry rendering into the next draw"); + auto expected = std::vector{"begin", "draw", "end"}; + if (kind != 0) { + if (kind == 2) expected.emplace_back("quad_helper"); + if (kind == 3) expected.emplace_back("clamp_helper"); + if (kind == 4) expected.emplace_back("end_query"); + if (kind == 5) { expected.emplace_back("reset_query"); expected.emplace_back("begin_query"); } + expected.emplace_back("begin"); expected.emplace_back(kind == 1 ? "indirect" : kind == 2 ? "indexed" : "draw"); + expected.emplace_back("end"); + } + expected.insert(expected.end(), {"begin", "draw", "draw", "end"}); + check(actions(f.recorder) == expected, "ineligible draw closes before helpers and immediately after its draw"); + const auto reason = kind == 0 ? scope_stats::End::skipped : kind == 1 ? scope_stats::End::indirect : + kind < 4 ? scope_stats::End::helper : scope_stats::End::statistics; + check(counts.draws == (kind == 0 ? 3u : 4u) && counts.skipped == (kind == 0 ? 1u : 0u) && + counts.eligible == 3 && counts.indirect == (kind == 1 ? 1u : 0u) && + counts.scopes == f.recorder.scopes.size() && counts.max_run == 2 && + counts.ends[unsigned(reason)] == (kind == 0 ? 1u : 2u), + "ineligible draws count skipped inputs and both scope ends around an isolated draw"); + } + for (bool mesh : {false, true}) { + Fixture f; + f.graphics.mesh = mesh; + for (int i = 0; i < 2; ++i) { + auto draw = Fixture::draw(); draw.mesh = mesh; draw.first = 1; + if (!mesh) { draw.topology = topology_quad_list; draw.count = 8; } + f.add_draw(draw); + } + f.emit(); + check(f.recorder.scopes.size() == 1 && f.recorder.draws.size() == 2, + "direct mesh and non-indexed quad draws without helpers can share a scope"); + } +} + +void queries_predicates_labels_and_list_end() { + Fixture f; + f.add_draw(); + check(f.list.begin_query({1, d3d12_query::occlusion, 0}), "query begins"); f.add_command(); + f.prepared.queries.push_back({}); f.prepared.queries.back().command = 1; f.prepared.queries.back().heap = &f.query; + f.add_draw(); f.add_draw(); + check(f.list.end_query({1, d3d12_query::occlusion, 0}), "query ends"); f.add_command(); + f.prepared.queries.push_back({}); f.prepared.queries.back().command = 4; f.prepared.queries.back().heap = &f.query; + f.add_draw(); + scope_stats::Counts query_counts; + f.emit(&query_counts); + check(query_counts.scopes == 3 && query_counts.ends[unsigned(scope_stats::End::query)] == 2 && + query_counts.ends[unsigned(scope_stats::End::list_end)] == 1, + "query boundaries have one reason per completed scope"); + check(actions(f.recorder) == std::vector{"begin", "draw", "end", "reset_query", "begin_query", "begin", "draw", "draw", "end", "end_query", "begin", "draw", "end"}, + "query commands end rendering before query resets and endpoints"); + + Fixture predicate; + predicate.add_draw(); + check(predicate.list.set_predication({8, 0, d3d12_predication::equal_zero}), "predicate records"); + predicate.add_command().predicate.scratch = handle(81); + predicate.add_draw(); predicate.add_draw(); + scope_stats::Counts predicate_counts; + predicate.emit(&predicate_counts); + check(predicate_counts.ends[unsigned(scope_stats::End::predicate)] == 1 && predicate_counts.scopes == 2, + "predicate capture closes the preceding scope before the next run"); + check(actions(predicate.recorder) == std::vector{"begin", "draw", "end", "capture_predicate", "begin_predicate", "begin", "draw", "draw", "end", "end_predicate"}, + "predicate capture and final conditional-rendering closure execute outside rendering"); + + Fixture label; + check(label.list.marker(DebugMarker::Kind::begin, "synthetic pass"), "label records"); label.add_command(); + label.add_draw(); label.add_draw(); label.emit(); + check(actions(label.recorder) == std::vector{"begin_label", "begin", "draw", "draw", "end", "end_label"}, + "final rendering scope closes before unbalanced labels are closed"); + label.emit(); + check(label.recorder.scopes.size() == 2 && label.recorder.ends == 2, + "emitting another list never reuses a scope from the previous emit call"); +} + +void diagnostics() { + Fixture f; + constexpr std::array lengths{1u, 2u, 3u, 4u, 7u, 8u, 15u, 16u, 63u, 64u, 255u, 256u}; + for (unsigned run = 0; run < lengths.size(); ++run) { + if (run) { check(f.list.uav_barrier({0}), "histogram barrier records"); f.add_command(); } + for (unsigned i = 0; i < lengths[run]; ++i) f.add_draw(); + } + scope_stats::Counts counts; + f.emit(&counts); + check(counts.lists == 1 && counts.draws == std::accumulate(lengths.begin(), lengths.end(), 0u) && + counts.scopes == lengths.size() && counts.max_run == 256 && + counts.runs == std::array{1, 1, 1, 2, 2, 2, 2, 1}, + "real emitted runs populate every histogram bucket, including its lower and upper edges"); + check(std::accumulate(counts.runs.begin(), counts.runs.end(), std::uint64_t{}) == counts.scopes && + std::accumulate(counts.ends.begin(), counts.ends.end(), std::uint64_t{}) == counts.scopes, + "every application scope has exactly one histogram bucket and end reason"); + scope_stats::Counts repeated; + f.emit(&repeated); + counts.add(repeated); + check(counts.lists == 2 && counts.scopes == 24 && counts.max_run == 256 && counts.runs[7] == 2, + "replayed lists add counts while preserving the maximum run"); + + Fixture switches; + switches.add_draw(); switches.add_draw(); + auto b = switches.add_draw(); switches.at(b).graphics = &switches.other; + b = switches.add_draw(); switches.at(b).graphics = &switches.other; + switches.at(b).pipeline = handle(75); + b = switches.add_draw(); switches.at(b).colors[0] = Fixture::attachment(3); + b = switches.add_draw(); switches.at(b).colors[0] = Fixture::attachment(3); + switches.at(b).area.width = 320; + scope_stats::Counts changed; + switches.emit(&changed); + check(changed.ends[unsigned(scope_stats::End::pipeline)] == 3 && + changed.ends[unsigned(scope_stats::End::attachments)] == 1 && changed.scopes == 5, + "pipeline identity takes precedence over attachment changes; extent changes count as attachments"); + + Fixture empty; + scope_stats::Counts nothing; + empty.emit(¬hing); + check(nothing.lists == 1 && nothing.draws == 0 && nothing.scopes == 0 && nothing.max_run == 0, + "empty lists do not fabricate a zero-length scope"); + + Fixture checkpointed; + checkpointed.add_draw(); checkpointed.add_draw(); + check(checkpointed.list.close(), "checkpointed list closes"); + static unsigned checkpoint_calls; + checkpoint_calls = 0; + CheckpointSubmission submission; + submission.sequence = 1; + submission.lists.resize(1); + const std::unordered_map names; + const CheckpointRecorder recorder{+[](VkCommandBuffer, const void* marker) { + check(marker != nullptr, "each draw retains its device-fault checkpoint"); ++checkpoint_calls; + }, submission, names, 0}; + Recorder::current = &checkpointed.recorder; + scope_stats::Counts with_checkpoints; + emit_commands_impl(checkpointed.prepared, VK_NULL_HANDLE, checkpointed.vk, + nullptr, nullptr, &recorder, &with_checkpoints); + check(checkpoint_calls == 2 && with_checkpoints.draws == 2 && with_checkpoints.scopes == 1 && + checkpointed.recorder.ends == 1 && !checkpointed.recorder.rendering, + "scope diagnostics and per-draw device-fault checkpoints work together"); +} +} + +int main() { + compatible_state(); + changed_targets(); + attachmentless_and_multiple_viewports(); + non_draw_boundaries(); + ineligible_draws(); + queries_predicates_labels_and_list_end(); + diagnostics(); + if (ok) std::puts("replay rendering scopes: PASS (synthetic CPU recording)"); + return ok ? 0 : 1; +} diff --git a/runtime/test/vk_rendering_scope_test.cpp b/runtime/test/vk_rendering_scope_test.cpp new file mode 100644 index 0000000000..23eec6e164 --- /dev/null +++ b/runtime/test/vk_rendering_scope_test.cpp @@ -0,0 +1,543 @@ +// Consecutive draws retain their colour and depth attachments in one dynamic rendering scope. +// Hand-written shaders below use only a full-screen triangle and colour/depth push constants. Each draw scissors +// one pixel; the CPU applies the same LEQUAL depth test and alpha blend in order, then checks every colour/depth +// texel. --bench prints CPU emit, record/submit/wait and GPU timestamp medians (3 warmups, 7 samples) for compatible +// runs of 1, 4, 16, 64 and all draws. No timing threshold is tested. +// No game files or external shader compiler are needed. LEONIDA_VK_VALIDATION=1 enables the usual validation layer. +#include "vk_test_device.h" +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include + +namespace { +using namespace leonida; +using Clock = std::chrono::steady_clock; +constexpr std::uint32_t side = 32, pixels = side * side; +constexpr VkFormat color_format = VK_FORMAT_R32G32B32A32_SFLOAT; +constexpr VkFormat depth_format = VK_FORMAT_D32_SFLOAT; + +// Generated solely from these hand-written synthetic GLSL sources with glslangValidator -V: +// scope.vert: +// #version 450 +// layout(push_constant) uniform Inputs { vec4 color; float depth; } input_data; +// void main() { +// vec2 positions[3] = vec2[3](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); +// gl_Position = vec4(positions[gl_VertexIndex], input_data.depth, 1.0); +// } +// scope.frag: +// #version 450 +// layout(push_constant) uniform Inputs { vec4 color; float depth; } input_data; +// layout(location = 0) out vec4 output_color; +// void main() { output_color = input_data.color; } +constexpr std::uint32_t vertex_words[] = { + 0x07230203u, 0x00010000u, 0x0008000bu, 0x0000002eu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0007000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000018u, 0x0000001cu, 0x00030003u, + 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00050005u, 0x0000000cu, + 0x69736f70u, 0x6e6f6974u, 0x00000073u, 0x00060005u, 0x00000016u, 0x505f6c67u, 0x65567265u, 0x78657472u, + 0x00000000u, 0x00060006u, 0x00000016u, 0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u, + 0x00000016u, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u, 0x00000000u, 0x00070006u, 0x00000016u, + 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu, 0x00070006u, 0x00000016u, 0x00000003u, + 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x00000018u, 0x00000000u, 0x00060005u, + 0x0000001cu, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u, 0x00040005u, 0x00000021u, 0x75706e49u, + 0x00007374u, 0x00050006u, 0x00000021u, 0x00000000u, 0x6f6c6f63u, 0x00000072u, 0x00050006u, 0x00000021u, + 0x00000001u, 0x74706564u, 0x00000068u, 0x00050005u, 0x00000023u, 0x75706e69u, 0x61645f74u, 0x00006174u, + 0x00030047u, 0x00000016u, 0x00000002u, 0x00050048u, 0x00000016u, 0x00000000u, 0x0000000bu, 0x00000000u, + 0x00050048u, 0x00000016u, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x00000016u, 0x00000002u, + 0x0000000bu, 0x00000003u, 0x00050048u, 0x00000016u, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, + 0x0000001cu, 0x0000000bu, 0x0000002au, 0x00030047u, 0x00000021u, 0x00000002u, 0x00050048u, 0x00000021u, + 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000021u, 0x00000001u, 0x00000023u, 0x00000010u, + 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, + 0x00040017u, 0x00000007u, 0x00000006u, 0x00000002u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, + 0x0004002bu, 0x00000008u, 0x00000009u, 0x00000003u, 0x0004001cu, 0x0000000au, 0x00000007u, 0x00000009u, + 0x00040020u, 0x0000000bu, 0x00000007u, 0x0000000au, 0x0004002bu, 0x00000006u, 0x0000000du, 0xbf800000u, + 0x0005002cu, 0x00000007u, 0x0000000eu, 0x0000000du, 0x0000000du, 0x0004002bu, 0x00000006u, 0x0000000fu, + 0x40400000u, 0x0005002cu, 0x00000007u, 0x00000010u, 0x0000000fu, 0x0000000du, 0x0005002cu, 0x00000007u, + 0x00000011u, 0x0000000du, 0x0000000fu, 0x0006002cu, 0x0000000au, 0x00000012u, 0x0000000eu, 0x00000010u, + 0x00000011u, 0x00040017u, 0x00000013u, 0x00000006u, 0x00000004u, 0x0004002bu, 0x00000008u, 0x00000014u, + 0x00000001u, 0x0004001cu, 0x00000015u, 0x00000006u, 0x00000014u, 0x0006001eu, 0x00000016u, 0x00000013u, + 0x00000006u, 0x00000015u, 0x00000015u, 0x00040020u, 0x00000017u, 0x00000003u, 0x00000016u, 0x0004003bu, + 0x00000017u, 0x00000018u, 0x00000003u, 0x00040015u, 0x00000019u, 0x00000020u, 0x00000001u, 0x0004002bu, + 0x00000019u, 0x0000001au, 0x00000000u, 0x00040020u, 0x0000001bu, 0x00000001u, 0x00000019u, 0x0004003bu, + 0x0000001bu, 0x0000001cu, 0x00000001u, 0x00040020u, 0x0000001eu, 0x00000007u, 0x00000007u, 0x0004001eu, + 0x00000021u, 0x00000013u, 0x00000006u, 0x00040020u, 0x00000022u, 0x00000009u, 0x00000021u, 0x0004003bu, + 0x00000022u, 0x00000023u, 0x00000009u, 0x0004002bu, 0x00000019u, 0x00000024u, 0x00000001u, 0x00040020u, + 0x00000025u, 0x00000009u, 0x00000006u, 0x0004002bu, 0x00000006u, 0x00000028u, 0x3f800000u, 0x00040020u, + 0x0000002cu, 0x00000003u, 0x00000013u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, + 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000bu, 0x0000000cu, 0x00000007u, 0x0003003eu, 0x0000000cu, + 0x00000012u, 0x0004003du, 0x00000019u, 0x0000001du, 0x0000001cu, 0x00050041u, 0x0000001eu, 0x0000001fu, + 0x0000000cu, 0x0000001du, 0x0004003du, 0x00000007u, 0x00000020u, 0x0000001fu, 0x00050041u, 0x00000025u, + 0x00000026u, 0x00000023u, 0x00000024u, 0x0004003du, 0x00000006u, 0x00000027u, 0x00000026u, 0x00050051u, + 0x00000006u, 0x00000029u, 0x00000020u, 0x00000000u, 0x00050051u, 0x00000006u, 0x0000002au, 0x00000020u, + 0x00000001u, 0x00070050u, 0x00000013u, 0x0000002bu, 0x00000029u, 0x0000002au, 0x00000027u, 0x00000028u, + 0x00050041u, 0x0000002cu, 0x0000002du, 0x00000018u, 0x0000001au, 0x0003003eu, 0x0000002du, 0x0000002bu, + 0x000100fdu, 0x00010038u, +}; +constexpr std::uint32_t fragment_words[] = { + 0x07230203u, 0x00010000u, 0x0008000bu, 0x00000012u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0006000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x00030010u, 0x00000004u, + 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, + 0x00060005u, 0x00000009u, 0x7074756fu, 0x635f7475u, 0x726f6c6fu, 0x00000000u, 0x00040005u, 0x0000000au, + 0x75706e49u, 0x00007374u, 0x00050006u, 0x0000000au, 0x00000000u, 0x6f6c6f63u, 0x00000072u, 0x00050006u, + 0x0000000au, 0x00000001u, 0x74706564u, 0x00000068u, 0x00050005u, 0x0000000cu, 0x75706e69u, 0x61645f74u, + 0x00006174u, 0x00040047u, 0x00000009u, 0x0000001eu, 0x00000000u, 0x00030047u, 0x0000000au, 0x00000002u, + 0x00050048u, 0x0000000au, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x0000000au, 0x00000001u, + 0x00000023u, 0x00000010u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, + 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u, 0x00000008u, + 0x00000003u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000009u, 0x00000003u, 0x0004001eu, 0x0000000au, + 0x00000007u, 0x00000006u, 0x00040020u, 0x0000000bu, 0x00000009u, 0x0000000au, 0x0004003bu, 0x0000000bu, + 0x0000000cu, 0x00000009u, 0x00040015u, 0x0000000du, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000000du, + 0x0000000eu, 0x00000000u, 0x00040020u, 0x0000000fu, 0x00000009u, 0x00000007u, 0x00050036u, 0x00000002u, + 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, 0x0000000fu, 0x00000010u, + 0x0000000cu, 0x0000000eu, 0x0004003du, 0x00000007u, 0x00000011u, 0x00000010u, 0x0003003eu, 0x00000009u, + 0x00000011u, 0x000100fdu, 0x00010038u, +}; + +PFN_vkCmdBeginRendering real_begin = nullptr; +PFN_vkCmdEndRendering real_end = nullptr; +std::uint32_t begins = 0, ends = 0; +void VKAPI_CALL count_begin(VkCommandBuffer cb, const VkRenderingInfo* info) { + ++begins; + real_begin(cb, info); +} +void VKAPI_CALL count_end(VkCommandBuffer cb) { + ++ends; + real_end(cb); +} + +struct Fixture { + vktest::Device& d; + VkImage color{}, depth{}; + VkImageView color_view{}, depth_view{}; + VkBuffer readback{}; + void* mapped = nullptr; + VkShaderModule vs{}, fs{}; + VkQueryPool timestamps{}; + GraphicsPipeline graphics; + ResourceBinding color_binding, depth_binding, argument_binding; + VkPhysicalDeviceProperties properties{}; + std::uint32_t timestamp_bits = 0; + + ~Fixture() { + if (graphics.pipeline) d.fn("vkDestroyPipeline")(d.device, graphics.pipeline, nullptr); + if (graphics.layout) d.fn("vkDestroyPipelineLayout")(d.device, graphics.layout, nullptr); + for (auto module : {vs, fs}) + if (module) d.fn("vkDestroyShaderModule")(d.device, module, nullptr); + for (auto view : {color_view, depth_view}) + if (view) d.fn("vkDestroyImageView")(d.device, view, nullptr); + if (timestamps) d.fn("vkDestroyQueryPool")(d.device, timestamps, nullptr); + } + + bool initialize() { + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + timestamp_bits = d.families[d.family].timestampValidBits; + color = d.image(color_format, side, side, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + depth = d.image(depth_format, side, side, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + readback = d.buffer(pixels * (sizeof(float) * 4 + sizeof(float)), VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); + if (!color || !depth || !readback || !mapped) return false; + void* arguments = nullptr; + argument_binding.buffer = d.buffer(sizeof(VkDrawIndirectCommand), VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, &arguments); + argument_binding.size = sizeof(VkDrawIndirectCommand); + argument_binding.indirect_arguments = true; + if (!argument_binding.buffer || !arguments) return false; + const VkDrawIndirectCommand triangle{3, 1, 0, 0}; + std::memcpy(arguments, &triangle, sizeof(triangle)); + const auto view = [&](VkImage image, VkFormat format, VkImageAspectFlags aspects, VkImageView& out) { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + info.image = image; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = format; + info.subresourceRange = {aspects, 0, 1, 0, 1}; + return d.fn("vkCreateImageView")(d.device, &info, nullptr, &out) == VK_SUCCESS; + }; + if (!view(color, color_format, VK_IMAGE_ASPECT_COLOR_BIT, color_view) || + !view(depth, depth_format, VK_IMAGE_ASPECT_DEPTH_BIT, depth_view)) return false; + color_binding.image = color; + color_binding.format = color_format; + color_binding.width = color_binding.height = side; + color_binding.color_attachment = true; + depth_binding.image = depth; + depth_binding.format = depth_format; + depth_binding.width = depth_binding.height = side; + depth_binding.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + const auto shader = [&](auto& words, VkShaderModule& out) { + VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + info.codeSize = sizeof(words); + info.pCode = words; + return d.fn("vkCreateShaderModule")(d.device, &info, nullptr, &out) == VK_SUCCESS; + }; + if (!shader(vertex_words, vs) || !shader(fragment_words, fs)) return false; + graphics.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; + VkPushConstantRange push{graphics.push_stages, 0, sizeof(ShaderUserData)}; + VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout.pushConstantRangeCount = 1; + layout.pPushConstantRanges = &push; + if (d.fn("vkCreatePipelineLayout")(d.device, &layout, nullptr, &graphics.layout) != VK_SUCCESS) + return false; + VkPipelineShaderStageCreateInfo stages[2]{}; + for (unsigned k = 0; k < 2; ++k) { + stages[k].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[k].stage = k ? VK_SHADER_STAGE_FRAGMENT_BIT : VK_SHADER_STAGE_VERTEX_BIT; + stages[k].module = k ? fs : vs; + stages[k].pName = "main"; + } + VkPipelineVertexInputStateCreateInfo vertex{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo input{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + input.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + viewport.viewportCount = viewport.scissorCount = 1; + VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + raster.polygonMode = VK_POLYGON_MODE_FILL; + raster.cullMode = VK_CULL_MODE_NONE; + raster.lineWidth = 1; + VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + VkPipelineDepthStencilStateCreateInfo ds{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + ds.depthTestEnable = ds.depthWriteEnable = VK_TRUE; + ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; + VkPipelineColorBlendAttachmentState blend{}; + blend.blendEnable = VK_TRUE; + blend.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; + blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + blend.colorBlendOp = blend.alphaBlendOp = VK_BLEND_OP_ADD; + blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + blend.colorWriteMask = 0xf; + VkPipelineColorBlendStateCreateInfo color_blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + color_blend.attachmentCount = 1; + color_blend.pAttachments = &blend; + const VkDynamicState dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, + VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS}; + VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dynamic.dynamicStateCount = std::size(dynamic_states); + dynamic.pDynamicStates = dynamic_states; + VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; + rendering.colorAttachmentCount = 1; + rendering.pColorAttachmentFormats = &color_format; + rendering.depthAttachmentFormat = depth_format; + VkGraphicsPipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; + pipeline.stageCount = 2; + pipeline.pStages = stages; + pipeline.pVertexInputState = &vertex; + pipeline.pInputAssemblyState = &input; + pipeline.pViewportState = &viewport; + pipeline.pRasterizationState = &raster; + pipeline.pMultisampleState = &multisample; + pipeline.pDepthStencilState = &ds; + pipeline.pColorBlendState = &color_blend; + pipeline.pDynamicState = &dynamic; + pipeline.layout = graphics.layout; + if (d.fn("vkCreateGraphicsPipelines")(d.device, VK_NULL_HANDLE, 1, &pipeline, + nullptr, &graphics.pipeline) != VK_SUCCESS) return false; + graphics.color_formats = {color_format}; + graphics.depth_format = depth_format; + graphics.depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + if (timestamp_bits) { + VkQueryPoolCreateInfo query{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; + query.queryType = VK_QUERY_TYPE_TIMESTAMP; + query.queryCount = 2; + if (d.fn("vkCreateQueryPool")(d.device, &query, nullptr, ×tamps) != VK_SUCCESS) + return false; + } + real_begin = d.fn("vkCmdBeginRendering"); + real_end = d.fn("vkCmdEndRendering"); + return true; + } + + ReplayFunctions functions() { + ReplayFunctions vk; +#define FN(field, type, name) vk.field = d.fn(name) + FN(pipeline_barrier, PFN_vkCmdPipelineBarrier, "vkCmdPipelineBarrier"); + FN(bind_pipeline, PFN_vkCmdBindPipeline, "vkCmdBindPipeline"); + FN(push_constants, PFN_vkCmdPushConstants, "vkCmdPushConstants"); + FN(bind_vertex_buffers2, PFN_vkCmdBindVertexBuffers2, "vkCmdBindVertexBuffers2"); + FN(bind_index_buffer, PFN_vkCmdBindIndexBuffer, "vkCmdBindIndexBuffer"); + FN(set_viewport, PFN_vkCmdSetViewport, "vkCmdSetViewport"); + FN(set_scissor, PFN_vkCmdSetScissor, "vkCmdSetScissor"); + FN(set_primitive_topology, PFN_vkCmdSetPrimitiveTopology, "vkCmdSetPrimitiveTopology"); + FN(set_primitive_restart_enable, PFN_vkCmdSetPrimitiveRestartEnable, "vkCmdSetPrimitiveRestartEnable"); + FN(set_stencil_reference, PFN_vkCmdSetStencilReference, "vkCmdSetStencilReference"); + FN(set_blend_constants, PFN_vkCmdSetBlendConstants, "vkCmdSetBlendConstants"); + FN(draw, PFN_vkCmdDraw, "vkCmdDraw"); + FN(draw_indexed, PFN_vkCmdDrawIndexed, "vkCmdDrawIndexed"); + FN(draw_indirect, PFN_vkCmdDrawIndirect, "vkCmdDrawIndirect"); +#undef FN + vk.draw_indirect_first_instance = d.enabled.drawIndirectFirstInstance == VK_TRUE; + vk.begin_rendering = count_begin; + vk.end_rendering = count_end; + vk.graphics_pipeline = [&](std::uintptr_t id) { return id == 1 ? &graphics : nullptr; }; + vk.buffer_at = [](std::uint64_t, std::uint64_t&, VkBuffer&, VkDeviceSize&) { return false; }; + vk.image_view = [&](const ResourceBinding& binding, const VkImageSubresourceRange&) { + return binding.image == color ? color_view : binding.image == depth ? depth_view : VK_NULL_HANDLE; + }; + return vk; + } + + void barrier(VkCommandBuffer cb, VkImage image, VkImageAspectFlags aspect, VkImageLayout before, + VkImageLayout after, VkAccessFlags source_access, VkAccessFlags target_access, + VkPipelineStageFlags source_stage, VkPipelineStageFlags target_stage) { + VkImageMemoryBarrier memory{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + memory.srcAccessMask = source_access; + memory.dstAccessMask = target_access; + memory.oldLayout = before; + memory.newLayout = after; + memory.srcQueueFamilyIndex = memory.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + memory.image = image; + memory.subresourceRange = {aspect, 0, 1, 0, 1}; + d.fn("vkCmdPipelineBarrier")(cb, source_stage, target_stage, 0, 0, nullptr, 0, nullptr, + 1, &memory); + } + + void clear(VkCommandBuffer cb) { + d.initial_layout(cb, color, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + d.initial_layout(cb, depth, VK_IMAGE_ASPECT_DEPTH_BIT, 1, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + const VkImageSubresourceRange color_range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + const VkImageSubresourceRange depth_range{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}; + const VkClearColorValue zero{}; + const VkClearDepthStencilValue depth_clear{1, 0}; + d.fn("vkCmdClearColorImage")(cb, color, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zero, + 1, &color_range); + d.fn("vkCmdClearDepthStencilImage")(cb, depth, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + &depth_clear, 1, &depth_range); + barrier(cb, color, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + barrier(cb, depth, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); + } + + void read(VkCommandBuffer cb) { + barrier(cb, color, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + barrier(cb, depth, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + d.read_back(cb, color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, side, side, 1, readback, 0); + d.read_back(cb, depth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, side, side, 1, readback, + pixels * sizeof(float) * 4); + } +}; + +float depth_at(std::uint32_t draw) { return std::array{0.25f, 0.75f, 0.125f}[(draw / pixels) % 3]; } +std::array color_at(std::uint32_t draw) { + std::array color{0, 0, 0, 0.5f}; + color[(draw / pixels) % 3] = 1; + return color; +} + +double median(std::vector values) { + std::sort(values.begin(), values.end()); + return values[values.size() / 2]; +} + +enum class Workload { barrier, pipeline, target, indirect, mixed }; +constexpr const char* workload_name(Workload workload) { + return std::array{"barrier", "pipeline", "target", "indirect", "mixed"}[unsigned(workload)]; +} + +bool run_case(Fixture& f, std::uint32_t count, std::uint32_t run_length, bool benchmark, + Workload workload = Workload::barrier, Fixture* alternate = nullptr) { + CommandList list; + std::array, 2> views; + for (unsigned target = 0; target < 2; ++target) { + views[target] = std::make_shared(); + views[target]->render_target_count = 1; + views[target]->render_targets[0] = {target ? 4u : 1u, 0, 0, 1}; + } + const bool two_targets = workload == Workload::target || workload == Workload::mixed; + std::array expected{std::vector>(pixels), std::vector>(pixels)}; + std::array expected_depth{std::vector(pixels, 1), std::vector(pixels, 1)}; + unsigned expected_scopes = 0, previous_target = 0, previous_pipeline = 1; + bool previous_indirect = false; + for (std::uint32_t i = 0; i < count; ++i) { + // A global UAV barrier must finish a rendering scope. Identical barriers in baseline and optimized + // replay measure short compatible runs as well as the best case where the whole list is compatible. + const bool mixed = workload == Workload::mixed; + const unsigned phase = i % 12; + const bool barrier = mixed ? i && (phase == 0 || phase == 11) : + workload == Workload::barrier && run_length && i && i % run_length == 0; + const unsigned pipeline = mixed ? (phase >= 2 && phase <= 10 ? 2 : 1) : + workload == Workload::pipeline ? 1 + (i / run_length) % 2 : 1; + const unsigned target = mixed ? unsigned(phase >= 5 && phase <= 10) : + workload == Workload::target ? (i / run_length) % 2 : 0; + const bool indirect = mixed ? phase == 7 : + workload == Workload::indirect && i % (run_length + 1) == run_length; + if (!i || barrier || pipeline != previous_pipeline || target != previous_target || indirect || previous_indirect) + ++expected_scopes; + previous_pipeline = pipeline; previous_target = target; previous_indirect = indirect; + if (barrier && !list.uav_barrier({0})) return false; + Draw draw; + draw.pipeline = pipeline; + draw.views = views[target]; + draw.depth = {target ? 5u : 2u, 0, 0, 1}; + draw.viewport = {0, 0, float(side), float(side), 0, 1}; + const auto pixel = i * 37 % pixels, x = pixel % side, y = pixel / side; + draw.scissor = {std::int32_t(x), std::int32_t(y), std::int32_t(x + 1), std::int32_t(y + 1)}; + draw.topology = 4; + draw.count = 3; + draw.instances = 1; + const auto color = color_at(i); + const auto depth = depth_at(i); + for (unsigned k = 0; k < 4; ++k) draw.user_data[k] = std::bit_cast(color[k]); + draw.user_data[4] = std::bit_cast(depth); + if (!(indirect ? list.draw_indirect(std::move(draw), {3, 0, sizeof(VkDrawIndirectCommand), 1}) : + list.draw(std::move(draw)))) return false; + if (depth <= expected_depth[target][pixel]) { + for (unsigned k = 0; k < 3; ++k) + expected[target][pixel][k] = color[k] * 0.5f + expected[target][pixel][k] * 0.5f; + expected[target][pixel][3] = 0.5f; + expected_depth[target][pixel] = depth; + } + } + if (!list.close()) return false; + auto vk = f.functions(); + vk.graphics_pipeline = [&](std::uintptr_t id) { + return id == 1 ? &f.graphics : id == 2 && alternate ? &alternate->graphics : nullptr; + }; + vk.image_view = [&](const ResourceBinding& binding, const VkImageSubresourceRange&) { + for (const auto* fixture : {&f, alternate}) { + if (!fixture) continue; + if (binding.image == fixture->color) return fixture->color_view; + if (binding.image == fixture->depth) return fixture->depth_view; + } + return VkImageView{}; + }; + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + return id == 1 ? &f.color_binding : id == 2 ? &f.depth_binding : id == 3 ? &f.argument_binding : + id == 4 && alternate ? &alternate->color_binding : id == 5 && alternate ? &alternate->depth_binding : nullptr; + }; + PreparedList prepared; + const auto ready = prepare(list, resolve, vk, prepared); + if (ready != ReplayResult::success || prepared.draw_count != count) { + std::fprintf(stderr, "prepare failed: result=%d draws=%zu, expected=%u\n", int(ready), prepared.draw_count, count); + return false; + } + std::vector emit_ms, frame_ms, gpu_ms; + const unsigned passes = benchmark ? 10 : 1, warmup = benchmark ? 3 : 0; + bool ok = true; + for (unsigned pass = 0; pass < passes; ++pass) { + begins = ends = 0; + double emit_time = 0; + const auto start = Clock::now(); + if (!f.d.run([&](VkCommandBuffer cb) { + f.clear(cb); + if (two_targets) alternate->clear(cb); + if (f.timestamps) { + // Finish the common clear/transition work before the interval starts. These execution stages + // cover both earlier writes and the following timestamp, independently of the CPU record time. + f.d.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 0, nullptr); + f.d.fn("vkCmdResetQueryPool")(cb, f.timestamps, 0, 2); + f.d.fn("vkCmdWriteTimestamp")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, f.timestamps, 0); + } + const auto emit_start = Clock::now(); + emit(prepared, cb, vk); + emit_time = std::chrono::duration(Clock::now() - emit_start).count(); + if (f.timestamps) + f.d.fn("vkCmdWriteTimestamp")(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, f.timestamps, 1); + f.read(cb); + if (two_targets) alternate->read(cb); + return true; + })) return false; + const auto frame_time = std::chrono::duration(Clock::now() - start).count(); + if (pass >= warmup) { + emit_ms.push_back(emit_time); + frame_ms.push_back(frame_time); + if (f.timestamps) { + std::array values{}; + if (f.d.fn("vkGetQueryPoolResults")(f.d.device, f.timestamps, 0, 2, + sizeof(values), values.data(), sizeof(values[0]), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT) != VK_SUCCESS) + return false; + const auto mask = f.timestamp_bits == 64 ? UINT64_MAX : (std::uint64_t(1) << f.timestamp_bits) - 1; + gpu_ms.push_back(double((values[1] - values[0]) & mask) * f.properties.limits.timestampPeriod / 1e6); + } + } + for (unsigned target = 0; target < (two_targets ? 2u : 1u); ++target) { + const auto* color = static_cast(target ? alternate->mapped : f.mapped); + const auto* depth = color + pixels * 4; + for (unsigned p = 0; p < pixels; ++p) { + for (unsigned k = 0; k < 4; ++k) { + if (!std::isfinite(color[p * 4 + k]) || std::abs(color[p * 4 + k] - expected[target][p][k]) > 1e-6f) { + std::fprintf(stderr, "draws=%u target=%u pixel=%u component=%u got=%g expected=%g\n", count, target, + p, k, double(color[p * 4 + k]), double(expected[target][p][k])); + return false; + } + } + if (depth[p] != expected_depth[target][p]) { + std::fprintf(stderr, "draws=%u target=%u depth pixel=%u got=%g expected=%g\n", count, target, + p, double(depth[p]), double(expected_depth[target][p])); + return false; + } + } + } + if (begins != expected_scopes || ends != begins) ok = false; + } + std::printf("draws=%u run_length=%u workload=%s scopes=%u/%u pixel-depth-blend=PASS emit_ms=%.4f frame_ms=%.4f gpu_ms=%.4f\n", + count, workload == Workload::mixed ? 0u : run_length ? run_length : count, workload_name(workload), + begins, ends, median(emit_ms), median(frame_ms), + gpu_ms.empty() ? 0.0 : median(gpu_ms)); + if (!ok) std::fprintf(stderr, "expected %u rendering scope(s), got %u/%u\n", + expected_scopes, begins, ends); + return ok; +} +} // namespace + +int main(int argc, char** argv) { + if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "--bench") && std::strcmp(argv[1], "--bench-mixed"))) { + std::fprintf(stderr, "usage: vk_rendering_scope_test [--bench|--bench-mixed]\n"); + return 2; + } + vktest::Device device; + device.request_draw_indirect_first_instance = true; + const auto status = device.initialize(); + if (status != vktest::DeviceStatus::ready) return status == vktest::DeviceStatus::unavailable ? 77 : 1; + VkFormatProperties format{}; + device.instance_fn("vkGetPhysicalDeviceFormatProperties")( + device.physical, color_format, &format); + if (!(format.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) || + !device.depth_format_usable(depth_format)) { + std::printf("SKIP: RGBA32F blending or D32 attachment unavailable\n"); + return 77; + } + VkPhysicalDeviceProperties properties{}; + device.instance_fn("vkGetPhysicalDeviceProperties")(device.physical, &properties); + if (properties.limits.maxPushConstantsSize < sizeof(ShaderUserData)) { + std::printf("SKIP: the replay's 144-byte push constants are unavailable\n"); + return 77; + } + Fixture fixture{device}; + if (!fixture.initialize()) return 1; + bool ok = run_case(fixture, 4096, 0, false); + ok = run_case(fixture, 4096, 2048, false) && ok; + Fixture alternate{device}; + if (!alternate.initialize()) return 1; + if (device.enabled.drawIndirectFirstInstance) { + ok = run_case(fixture, 4096, 0, false, Workload::mixed, &alternate) && ok; + } else std::puts("SKIP: indirect/mixed cases require drawIndirectFirstInstance"); + if (argc == 2 && !std::strcmp(argv[1], "--bench")) { + for (const auto count : {1000u, 10000u}) + for (const auto run_length : {1u, 4u, 16u, 64u, 0u}) + ok = run_case(fixture, count, run_length, true) && ok; + } else if (argc == 2) { + for (const auto count : {1000u, 10000u}) { + for (const auto workload : {Workload::barrier, Workload::pipeline, Workload::target, Workload::indirect}) { + if (workload == Workload::indirect && !device.enabled.drawIndirectFirstInstance) continue; + for (const auto run_length : {2u, 3u}) + ok = run_case(fixture, count, run_length, true, workload, &alternate) && ok; + } + if (device.enabled.drawIndirectFirstInstance) + ok = run_case(fixture, count, 0, true, Workload::mixed, &alternate) && ok; + } + } + return ok && device.validation_errors() == 0 ? 0 : 1; +}