From 27781f7f9b296fcdbac5c86792c2f2c2b308ba9b Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 18:41:32 +0500 Subject: [PATCH] d3d12: replay programmable sample positions (D3D-SAMPLE-POSITIONS) --- runtime/CMakeLists.txt | 4 +- runtime/shims/d3d12_com.cpp | 21 +++ runtime/shims/d3d12_com.h | 1 + runtime/shims/d3d12_vulkan_device.cpp | 66 +++++++- runtime/src/command_list.h | 18 ++- runtime/src/vulkan_backend.h | 3 +- runtime/src/vulkan_replay.h | 159 +++++++++++++------ runtime/test/command_list_test.cpp | 16 ++ runtime/test/d3d12_msaa_draw_test.cpp | 58 ++++++- runtime/test/replay_texture_barrier_test.cpp | 36 +++++ runtime/test/vk_test_device.h | 5 + 11 files changed, 329 insertions(+), 58 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..ac64700ca9 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2865,7 +2865,9 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) - set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_custom_samples COMMAND d3d12_msaa_draw_test --custom-samples) + add_test(NAME d3d12_sample_grid_reset COMMAND d3d12_msaa_draw_test --sample-grid) + set_tests_properties(d3d12_msaa_draw d3d12_custom_samples d3d12_sample_grid_reset PROPERTIES SKIP_RETURN_CODE 77) # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..3f52bcb1cb 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -376,6 +376,7 @@ class GraphicsCommandList final if (list_.closed()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!list_.closed()) check(list_.set_predication({0, 0, 0})); + if (custom_samples_) check(list_.set_sample_positions({})); reset_state(state); } @@ -651,6 +652,24 @@ class GraphicsCommandList final check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); } + void STDMETHODCALLTYPE SetSamplePositions(UINT samples, UINT pixels, D3D12_SAMPLE_POSITION* positions) override { + d3d12_trace::record("ID3D12GraphicsCommandList1::SetSamplePositions"); + if (list_.closed() || type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return; + leonida::SamplePositions pattern{}; + if (samples || pixels || positions) { + if (!positions || !leonida::SamplePositions::valid_grid(samples, pixels)) return; + pattern.samples = samples; + pattern.pixels = pixels; + for (UINT i = 0; i < samples * pixels; ++i) { + const auto p = positions[i]; + if (p.X < -8 || p.X > 7 || p.Y < -8 || p.Y > 7) return; + pattern.positions[i] = {p.X, p.Y}; + } + } + check(list_.set_sample_positions(pattern)); + custom_samples_ = samples != 0; + } + void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { @@ -1252,6 +1271,7 @@ class GraphicsCommandList final leonida::CommandList list_; bool invalid_ = false; UINT front_stencil_ref_ = 0; + bool custom_samples_ = false; UINT back_stencil_ref_ = 0; RootState compute_; RootState graphics_; @@ -1357,6 +1377,7 @@ class GraphicsCommandList final void reset_state(ID3D12PipelineState* state) { front_stencil_ref_ = back_stencil_ref_ = 0; + custom_samples_ = false; compute_ = {}; graphics_ = {}; cbv_srv_uav_heap_ = nullptr; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index d0f3b528aa..abf6b889d8 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -117,6 +117,7 @@ struct VulkanDeviceInfo { // VK_EXT_conservative_rasterization is enabled on the logical device. Tier 1/2 depend on the physical // precision/overestimation properties; Tier 2 also requires post-snap degenerate triangles. bool conservative_rasterization = false; + bool sample_locations = false; // Opt in only for shader libraries whose InnerCoverage input contract uses FullyCoveredEXT. The device // still checks physical Tier 2 and fullyCoveredFragmentShaderInputVariable properties. The standalone // device leaves this false until the Xbox PS input mapping is confirmed (synthetic GLSL is not that ABI). diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..d7c0d31255 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -495,7 +495,8 @@ struct TextureCreateInfo { VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; std::array view_formats{}; - TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) { + TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable, + VkSampleCountFlags programmable_samples) { const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; @@ -508,6 +509,9 @@ struct TextureCreateInfo { info.mipLevels = desc.MipLevels; info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); + if ((programmable_samples & info.samples) && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && + (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + info.flags |= VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT; info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; @@ -630,6 +634,8 @@ struct DeviceState { std::uint32_t f16_half_top_location = 29; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; + VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; + D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. VkResolveModeFlags depth_resolve_modes = 0; @@ -2112,7 +2118,7 @@ class Resource final HRESULT create_sparse_image() { auto& vk = device_.context->vk; const auto format = device_.texture_format(desc_); - TextureCreateInfo create(desc_, format, false); + TextureCreateInfo create(desc_, format, false, device_.sample_grid_1); create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; HRESULT support = device_.check_image_support(create.info); @@ -2190,7 +2196,7 @@ class Resource final const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); - TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); + TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format), device_.sample_grid_1); VkImageCreateInfo& info = create.info; if (!castable.empty()) { // D3D12 always allows a view in the resource's own format, whether or not the castable list names @@ -2260,6 +2266,7 @@ class Resource final binding.volume = volume; binding.line = one_d; binding.samples = samples; + binding.sample_locations_depth = (info.flags & VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT) != 0; binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; @@ -3946,6 +3953,8 @@ class PipelineState final recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; recipe_.multisample = multisample; graphics_.samples = samples; + graphics_.sample_grid_1 = device_.sample_grid_1; + graphics_.sample_grid_4 = device_.sample_grid_4; recipe_.sample_mask = sample_mask; recipe_.depth = depth; recipe_.blends = std::move(blends); @@ -4167,6 +4176,17 @@ class PipelineState final dynamic.pDynamicStates = dynamic_states; } + std::array custom_dynamic{}; + VkPipelineSampleLocationsStateCreateInfoEXT custom{VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT}; + if (unbound & leonida::GraphicsPipeline::custom_samples) { + std::copy_n(dynamic.pDynamicStates, dynamic.dynamicStateCount, custom_dynamic.begin()); + custom_dynamic[dynamic.dynamicStateCount++] = VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT; + dynamic.pDynamicStates = custom_dynamic.data(); + custom.sampleLocationsEnable = VK_TRUE; + custom.sampleLocationsInfo.sType = VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT; + custom.pNext = multisample.pNext; + multisample.pNext = &custom; + } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; info.stageCount = std::uint32_t(r.stages.size()); info.pStages = r.stages.data(); @@ -5101,6 +5121,38 @@ class Device final if (info.conservative_rasterization) resolve.pNext = &conservative; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; get_props2(info.physical, &props); + if (info.sample_locations) { + VkPhysicalDeviceSampleLocationsPropertiesEXT locations{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 sample_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &locations}; + get_props2(info.physical, &sample_props); + const auto get_grid = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); + if (get_grid && props.properties.limits.standardSampleLocations && locations.variableSampleLocations && locations.sampleLocationSubPixelBits >= 4 && + locations.sampleLocationCoordinateRange[0] <= 0 && locations.sampleLocationCoordinateRange[1] >= 15.f / 16) { + for (unsigned samples = 1; samples <= 16; samples *= 2) { + if (!(locations.sampleLocationSampleCounts & samples)) continue; + VkMultisamplePropertiesEXT grid{VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT}; + get_grid(info.physical, VkSampleCountFlagBits(samples), &grid); + const auto extent = grid.maxSampleLocationGridSize; + if (extent.width && extent.height) state_.sample_grid_1 |= samples; + if (samples <= 4 && extent.width >= 2 && extent.height >= 2 && + extent.width % 2 == 0 && extent.height % 2 == 0) state_.sample_grid_4 |= samples; + } + const auto counts = (props.properties.limits.framebufferColorSampleCounts | + props.properties.limits.framebufferDepthSampleCounts | + props.properties.limits.framebufferStencilSampleCounts | + props.properties.limits.framebufferNoAttachmentsSampleCounts) & 31u; + // Four repeating pixels can name at most sixteen sample locations altogether. + const auto grid_counts = counts & (VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT); + const auto tier1_counts = counts & (VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT); + if (counts && (state_.sample_grid_1 & counts) == counts && + (state_.sample_grid_4 & grid_counts) == grid_counts) + state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2; + else if (tier1_counts && (state_.sample_grid_1 & tier1_counts) == tier1_counts) + state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1; + } + } state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier( info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE, @@ -7646,7 +7698,7 @@ class Device final auto* opts = static_cast(data); *opts = {}; opts->DepthBoundsTestSupported = FALSE; - opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; + opts->ProgrammableSamplePositionsTier = state_.sample_positions_tier; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS3: { @@ -8379,7 +8431,7 @@ class Device final return kInvalidAllocation; } VkMemoryRequirements need{}; - const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format)); + const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format), state_.sample_grid_1); if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; if (tiled) { leonida::ResourceTiling tiling; @@ -9657,6 +9709,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); + info.sample_locations = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) == 0; + }); const bool has_host_image_copy = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) == 0; }); @@ -9900,6 +9955,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin std::vector device_extensions; v13.add_extensions(device_extensions); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); + if (info.sample_locations) device_extensions.push_back(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0ac..1ca301ab50 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -546,6 +546,20 @@ struct Predication { std::uint32_t op; // d3d12_predication }; +struct SamplePosition { + std::int8_t x, y; +}; + +struct SamplePositions { + std::uint32_t samples = 0; + std::uint32_t pixels = 0; + std::array positions{}; + + static constexpr bool valid_grid(std::uint32_t samples, std::uint32_t pixels) { + return (pixels == 1 || pixels == 4) && samples && !(samples & (samples - 1)) && samples <= 16 / pixels; + } +}; + // Query heaps are identified like resources, by the COM object's pointer value. A heap's type and size are checked // at replay, when the heap is known. using QueryHeapId = std::uintptr_t; @@ -653,7 +667,7 @@ struct AccelerationStructurePostbuild { using Command = std::variant; @@ -823,6 +837,8 @@ class CommandList { return true; } + bool set_sample_positions(const SamplePositions& pattern) { return append(pattern); } + // SetPredication. Turning it off ignores the offset and op, as D3D12 does. bool set_predication(const Predication& predication) { if (!predication.buffer) return append(Predication{0, 0, 0}); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..90efd4d4ba 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -102,7 +102,7 @@ struct VulkanDeviceFunctions { X(vkCmdPushConstants) X(vkCmdDispatch) \ X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ - X(vkCmdSetBlendConstants) X(vkCmdDraw) \ + X(vkCmdSetBlendConstants) X(vkCmdDraw) X(vkCmdSetSampleLocationsEXT) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ @@ -973,6 +973,7 @@ class VulkanContext { replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; replay_.set_stencil_reference = vk.vkCmdSetStencilReference; + replay_.set_sample_locations = vk.vkCmdSetSampleLocationsEXT; replay_.set_blend_constants = vk.vkCmdSetBlendConstants; replay_.draw = vk.vkCmdDraw; replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..4c3b41871c 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -89,6 +89,7 @@ struct ResourceBinding { // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (the GPU has no D24): footprint copies of the depth plane convert // (depth24.h) and clears quantise to 24 bits. bool depth24_as_float = false; + bool sample_locations_depth = false; bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first // A D3D12 R32G32B32 texture (12 bytes a texel) held in an R32G32B32A32 image (16): footprints keep D3D12's 12 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). @@ -773,8 +774,10 @@ struct GraphicsPipeline { // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // and stencil. Null when it cannot be built. static constexpr std::uint32_t unbound_depth = 1u << 8; + static constexpr std::uint32_t custom_samples = 1u << 9; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -853,6 +856,7 @@ struct ReplayFunctions { PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; + PFN_vkCmdSetSampleLocationsEXT set_sample_locations = nullptr; PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; PFN_vkCmdDraw draw = nullptr; PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported @@ -1313,14 +1317,53 @@ inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkI return range; } +// Vulkan's Standard Sample Locations table, expressed relative to the pixel centre in sixteenths. +inline const SamplePosition* standard_sample_positions(unsigned samples) { + static constexpr SamplePosition one[] = {{0, 0}}; + static constexpr SamplePosition two[] = {{4, 4}, {-4, -4}}; + static constexpr SamplePosition four[] = {{-2, -6}, {6, -2}, {-6, 2}, {2, 6}}; + static constexpr SamplePosition eight[] = {{1, -3}, {-1, 3}, {5, 1}, {-3, -5}, {-5, 5}, {-7, -1}, {3, 7}, {7, -7}}; + static constexpr SamplePosition sixteen[] = {{1, 1}, {-1, -3}, {-3, 2}, {4, -1}, {-5, -2}, {2, 5}, {5, 3}, {3, -5}, + {-2, 6}, {0, -7}, {-4, -6}, {-6, 4}, {-8, 0}, {7, -4}, {6, 7}, {-7, -8}}; + switch (samples) { + case 1: return one; + case 2: return two; + case 4: return four; + case 8: return eight; + case 16: return sixteen; + default: return nullptr; + } +} + +struct VulkanSampleLocations { + std::array positions; + VkSampleLocationsInfoEXT info; + + const VkSampleLocationsInfoEXT* set(unsigned samples, const SamplePositions* pattern) { + const bool custom = pattern && pattern->samples == samples && SamplePositions::valid_grid(samples, pattern->pixels); + const auto* source = custom ? pattern->positions.data() : standard_sample_positions(samples); + if (!source) return nullptr; + const unsigned side = custom && pattern->pixels == 4 ? 2 : 1; + const unsigned count = samples * side * side; + for (unsigned i = 0; i < count; ++i) + positions[i] = {(source[i].x + 8) / 16.f, (source[i].y + 8) / 16.f}; + info = {VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, VkSampleCountFlagBits(samples), {side, side}, + count, positions.data()}; + return &info; + } +}; + inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, - VkPipelineStageFlags dst_stages) { + VkPipelineStageFlags dst_stages, const SamplePositions* active_samples = nullptr) { restrict_to_queue(vk, src_stages, src_access); restrict_to_queue(vk, dst_stages, dst_access); VkImageMemoryBarrier barrier{}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + VulkanSampleLocations locations; + if (resource.sample_locations_depth && old_layout != VK_IMAGE_LAYOUT_UNDEFINED && old_layout != new_layout) + barrier.pNext = locations.set(resource.samples, active_samples); barrier.srcAccessMask = src_access; barrier.dstAccessMask = dst_access; barrier.oldLayout = old_layout; @@ -1501,7 +1544,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com // when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run // expects; with not_zeroed, it is only moved. The tracker records it. inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, - ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker) { + ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; for (auto& piece : pieces) { if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; @@ -1511,7 +1554,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer const bool compressed = fmt.block > 1 || (!can_clear && color); if (resource.not_zeroed || (!can_clear && !color)) { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } else if (compressed) { const bool can_zero = vk.copy_buffer_to_image && @@ -1520,21 +1563,21 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); image_barrier(vk, command_buffer, resource, piece.range, dst, layout, zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } else { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } } else { const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { const VkClearColorValue zero{}; vk.clear_color_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); @@ -1543,7 +1586,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); } image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } piece.layout = layout; if (tracker) tracker->set(id, piece.range, layout); @@ -2029,10 +2072,10 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) // promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, ResourceId id, const VkImageSubresourceRange& range, - VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker) { + VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { const VkImageLayout target = image_layout(resource, wanted); auto pieces = current(tracker, id, range, target); - initialize(vk, command_buffer, resource, id, pieces, target, tracker); + initialize(vk, command_buffer, resource, id, pieces, target, tracker, active_samples); // D3D12 orders back-to-back copies and resolves on a resource that stays in COPY_DEST or COPY_SOURCE without a // barrier from the application; Vulkan does not. A piece already in the transfer layout gets no layout // transition, so an earlier transfer write to it is ordered here instead (write-after-write and read-after-write, @@ -2054,7 +2097,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm } image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); } if (tracker) tracker->set(id, range, target); return target; @@ -2065,14 +2108,14 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm template void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state, - VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { + VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body, const SamplePositions* active_samples = nullptr) { for (const auto& piece : pieces) { if (piece.layout == target) { memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); continue; } image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages, - target_access, target_stages); + target_access, target_stages, active_samples); } body(); for (const auto& piece : pieces) { @@ -2081,7 +2124,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const continue; } image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages, - state.access, state.stages); + state.access, state.stages, active_samples); } } @@ -2092,7 +2135,8 @@ namespace detail { // Resolves a draw's pipeline, attachments and buffers. Attachment views take the pipeline's formats, so a // typeless texture is viewed as the format the pipeline renders. template -ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, PreparedDraw& p) { +ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, PreparedDraw& p, + const SamplePositions* pattern = nullptr) { if (!vk.graphics_pipeline || !vk.buffer_at || !vk.image_view || !vk.begin_rendering || !vk.end_rendering || !vk.bind_vertex_buffers2 || !vk.bind_index_buffer || !vk.set_viewport || !vk.set_scissor || !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference || @@ -2163,6 +2207,12 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct for (std::size_t slot = 0; slot < p.colors.size(); ++slot) if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; + if (pattern) { + const auto counts = pattern->pixels == 1 ? pipeline->sample_grid_1 : pipeline->sample_grid_4; + if (!vk.set_sample_locations || !SamplePositions::valid_grid(pattern->samples, pattern->pixels) || + pattern->samples != pipeline->samples || !(counts & pattern->samples)) return ReplayResult::unsupported; + unbound |= GraphicsPipeline::custom_samples; + } if (unbound) { p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; if (!p.pipeline) return ReplayResult::unsupported; @@ -2234,10 +2284,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, - LayoutTracker* tracker, bool separate) { + LayoutTracker* tracker, bool separate, const SamplePositions* active_samples = nullptr) { const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); auto pieces = current(tracker, a.id, range, layout); - initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); + initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker, active_samples); for (const auto& piece : pieces) { if (piece.layout == layout) { // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. @@ -2245,7 +2295,7 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf continue; } image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages); + VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages, active_samples); } if (tracker) tracker->set(a.id, range, layout); } @@ -2590,6 +2640,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun bool overlaps = false, statistics_overlaps = false, statistics_active = false; out.wrote_readback = false; out.readback_src_stages = 0; + const SamplePositions* sample_positions = nullptr; for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; @@ -2953,6 +3004,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; } + } else if (const auto* pattern = std::get_if(&command)) { + sample_positions = pattern->samples ? pattern : nullptr; } else if (const auto* predication = std::get_if(&command)) { predicated = predication->buffer != 0; if (!predicated) continue; @@ -3148,7 +3201,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun auto& prepared_draw = out.draws[out.draw_count]; prepared_draw.reset(); p.draw = std::uint32_t(out.draw_count++); - if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) + if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw, sample_positions); r != ReplayResult::success) return r; } } @@ -3410,6 +3463,7 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& // (close_labels). Without it, the list's own events are balanced at its end. inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { + const SamplePositions* active_samples = nullptr; std::uint32_t own_labels = 0; std::uint32_t& labels = open_labels ? *open_labels : own_labels; const auto commands = prepared.list->commands(); @@ -3447,6 +3501,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c end_statistics(); begin_statistics(); } + if (const auto* pattern = std::get_if(&command)) { + active_samples = pattern->samples ? pattern : nullptr; + continue; + } if (const auto* predication = std::get_if(&command)) { // Conditional rendering cannot nest, so a new predicate ends the previous one first. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); @@ -3488,10 +3546,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const auto range = detail::planes_for_layout(p.binding, p.range, separate); const VkImageLayout new_layout = image_layout(p.binding, to.layout); auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker, active_samples); for (const auto& piece : pieces) detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, - from.access, from.stages, to.access, to.stages); + from.access, from.stages, to.access, to.stages, active_samples); if (tracker) tracker->set(id, range, new_layout); } else if (std::holds_alternative(command)) { const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); @@ -3544,7 +3602,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout before = image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); pieces = detail::current(tracker, id, range, before); - detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker, active_samples); } const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); @@ -3554,6 +3612,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (pieces.size() > few.size()) many.resize(pieces.size()); VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); std::uint32_t barrier_count = 0; + detail::VulkanSampleLocations locations; + const auto* depth_locations = p.binding.sample_locations_depth ? locations.set(p.binding.samples, active_samples) : nullptr; for (const auto& piece : pieces) { VkImageMemoryBarrier2& b = barriers[barrier_count++]; b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; @@ -3562,6 +3622,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c b.srcAccessMask = src.access; b.dstAccessMask = dst.access; b.oldLayout = piece.layout; + if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED && piece.layout != new_layout) b.pNext = depth_locations; b.newLayout = new_layout; b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; @@ -3579,14 +3640,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (p.skip) continue; const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), state, transfer_dst.access, transfer_dst.stages, [&] { vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), &color, 1, &p.range); - }); + }, active_samples); continue; } const VkImageLayout attachment = image_layout(p.binding, state.layout); @@ -3607,14 +3668,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c attachment_clear.clearValue.color = color; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (const auto* depth_clear = std::get_if(&command)) { if (p.skip) continue; // With separate layouts only the cleared planes move; otherwise both do. const auto range = detail::planes_for_layout(p.binding, p.range, separate); const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h : p.binding.format == VK_FORMAT_D16_UNORM ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm @@ -3625,7 +3686,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c state, transfer_dst.access, transfer_dst.stages, [&] { vk.clear_depth_stencil_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); - }); + }, active_samples); continue; } const VkImageLayout attachment = image_layout(p.binding, state.layout); @@ -3646,7 +3707,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c attachment_clear.clearValue.depthStencil = value; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (const auto* uav = std::get_if(&command)) { if (p.skip) continue; // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the @@ -3672,12 +3733,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept. const VkImageLayout layout = image_layout(p.binding, state.layout); auto pieces = detail::current(tracker, id, p.range, layout); - detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker, active_samples); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range); - }); + }, active_samples); continue; } detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, @@ -3698,7 +3759,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c attachment_clear.clearValue.color = p.clear_color; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { const auto [dst_id, src_id] = copy_ids(command); @@ -3716,14 +3777,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // synchronization-validation run). const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged, std::uint32_t(p.staged_reads.size()), p.staged_reads.data()); detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); } else if (!p.image_copies.empty()) { @@ -3733,10 +3794,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, - tracker); + tracker, active_samples); const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); const auto count = std::uint32_t(p.image_copies.size()); const auto depth_stencil = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; if (std::holds_alternative(command) && @@ -3787,13 +3848,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.copy_buffer_to_image(command_buffer, source, p.binding.image, dst_layout, std::uint32_t(regions->size()), regions->data()); } else { const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); if (!p.has_depth24) { const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer; vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target, @@ -3842,15 +3903,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); auto source_pieces = detail::current( tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); - detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); + detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker, active_samples); auto dest_pieces = detail::current( tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); - detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); + detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker, active_samples); // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve). const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) { const VkImageLayout layout = image_layout(p.binding, wanted); detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access, - VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }); + VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }, active_samples); }; const auto bands = std::uint32_t(p.staged_reads.size()); if (p.staged) { @@ -3897,8 +3958,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c else rendering.pStencilAttachment = &info; vk.begin_rendering(command_buffer, &rendering); vk.end_rendering(command_buffer); - }); - }); + }, active_samples); + }, active_samples); if (p.staged) { keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) { vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands, @@ -3909,10 +3970,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); } else if (const auto* marker = std::get_if(&command)) { if (!vk.insert_label || !vk.begin_label || !vk.end_label) continue; @@ -3942,7 +4003,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) detail::image_barrier(vk, command_buffer, p.binding, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } } else if (const auto* write = std::get_if(&command)) { // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish @@ -4140,7 +4201,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c 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); + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate, active_samples); colors[slot].imageView = a.view; colors[slot].imageLayout = layout; colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; @@ -4150,7 +4211,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c 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); + separate, active_samples); depth.imageView = d.depth.view; depth.imageLayout = layout; depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; @@ -4197,6 +4258,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); } + if (active_samples) { + detail::VulkanSampleLocations locations; + vk.set_sample_locations(command_buffer, locations.set(active_samples->samples, active_samples)); + } vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); vk.set_blend_constants(command_buffer, draw->blend_factor.data()); diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index 4367df6ecf..7e95c5fc48 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -275,6 +275,22 @@ int main() { CHECK(std::get(predicated.commands()[1]).offset == 16); const auto& off = std::get(predicated.commands()[2]); CHECK(off.buffer == 0 && off.offset == 0 && off.op == 0); + CHECK(SamplePositions::valid_grid(16, 1)); + CHECK(SamplePositions::valid_grid(4, 4)); + CHECK(!SamplePositions::valid_grid(8, 4)); + CHECK(!SamplePositions::valid_grid(3, 1)); + CHECK(!SamplePositions::valid_grid(4, 0)); + CommandList sampled; + SamplePositions pattern{4, 4}; + pattern.positions[15] = {-8, 7}; + CHECK(sampled.set_sample_positions(pattern)); + pattern.positions[15] = {0, 0}; + CHECK(sampled.set_sample_positions({})); + CHECK(sampled.close()); + CHECK(!sampled.set_sample_positions(pattern)); + const auto& recorded_pattern = std::get(sampled.commands()[0]); + CHECK(recorded_pattern.positions[15].x == -8 && recorded_pattern.positions[15].y == 7); + CHECK(std::get(sampled.commands()[1]).samples == 0); // Queries: timestamps only end; other queries are begun and ended in one list, with the same type, and are not // begun twice or resolved while running. Resolve offsets are multiples of 8; a resolve of nothing records nothing. namespace q = d3d12_query; diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 5017a01a3d..34a20f8fe8 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -46,11 +46,23 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_start(ID3D12DescriptorHeap* heap) { } // namespace -int main() { +int main(int argc, char** argv) { + const bool grid = argc == 2 && std::strcmp(argv[1], "--sample-grid") == 0; + const bool custom = grid || (argc == 2 && std::strcmp(argv[1], "--custom-samples") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips EXPECT(device_status == vktest::DeviceStatus::ready); + if (custom && !d.sample_locations) return 77; + if (grid) { + const auto query = reinterpret_cast( + d.instance_proc(d.instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); + VkMultisamplePropertiesEXT props{VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT}; + if (!query) return 77; + query(d.physical, VK_SAMPLE_COUNT_4_BIT, &props); + if (props.maxSampleLocationGridSize.width % 2 || props.maxSampleLocationGridSize.height % 2 || + !props.maxSampleLocationGridSize.width || !props.maxSampleLocationGridSize.height) return 77; + } const auto vs_program = fssm_program({0x56530001, 0xbf810000}); const auto ps_program = fssm_program({0x50530001, 0xbf810000}); @@ -83,6 +95,7 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; + info.sample_locations = custom && d.sample_locations; info.shader_dir = library.string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); @@ -90,6 +103,12 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); + D3D12_FEATURE_DATA_D3D12_OPTIONS2 options{}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &options, sizeof(options)))); + if (!custom) EXPECT(options.ProgrammableSamplePositionsTier == D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED); + if (custom && options.ProgrammableSamplePositionsTier == D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) return 77; + if (grid && options.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2) return 77; + std::printf("OPTIONS2 programmable sample positions tier %u\n", unsigned(options.ProgrammableSamplePositionsTier)); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", rt::d3d12::device_max_push_constants_size(inner)); @@ -252,10 +271,39 @@ int main() { list->ResourceBarrier(1, &to_vertex); const FLOAT blue[4] = {0, 0, 1, 1}; list->ClearRenderTargetView(rtv, blue, 0, nullptr); + common_state(rtv, grid ? nullptr : &dsv); + if (custom) { + Ref list1; + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + D3D12_SAMPLE_POSITION locations[16]{}; + for (unsigned pixel = 0; pixel < 4; ++pixel) { + const int corner = (pixel & 1) ? 4 : -6; + for (int i = 0; i < 4; ++i) + locations[4 * pixel + i] = {INT8(corner + (i & 1)), INT8(corner + (i >> 1))}; + } + list1->SetSamplePositions(4, grid ? 4 : 1, locations); + } list->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); - common_state(rtv, &dsv); list->SetGraphicsRootConstantBufferView(1, upload_va + 512); // red + if (grid) { + const D3D12_RECT top{0, 0, size, size / 2}; + list->RSSetScissorRects(1, &top); + list->DrawInstanced(3, 1, 0, 0); + Ref list1; + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + list1->SetSamplePositions(0, 0, nullptr); + const D3D12_RECT bottom{0, size / 2, size, size}; + list->RSSetScissorRects(1, &bottom); + } list->DrawInstanced(3, 1, 0, 0); + if (!grid) { + const D3D12_RESOURCE_BARRIER depth_transitions[] = { + transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_DEPTH_WRITE)}; + list->ResourceBarrier(2, depth_transitions); + list->SetGraphicsRootConstantBufferView(1, upload_va + 768); + list->DrawInstanced(3, 1, 0, 0); // equal depth fails LESS, so the original red must survive + } list->SetPipelineState(masked.p); list->SetGraphicsRootConstantBufferView(1, upload_va + 768); // green, sample 0 only list->DrawIndexedInstanced(6, 1, 0, 0, 0); @@ -330,6 +378,10 @@ int main() { // One of four samples green, three blue: 63.75 and 191.25, rounded either way by the resolve. if (got[0] != 0 || std::abs(int(got[1]) - 64) > 1 || std::abs(int(got[2]) - 191) > 1 || got[3] != 255) report(col, row, got, "0,64,191,255 (+-1)"); + } else if (custom && col + row == size - 1) { + const int red = grid && row >= size / 2 ? 128 : grid && (col & 1) ? 0 : 255; + if (std::abs(int(got[0]) - red) > 1 || got[1] || std::abs(int(got[2]) - (255 - red)) > 1 || got[3] != 255) + report(col, row, got, "coverage from the active sample pattern"); } else if (distance > margin) { if (!(got[0] == 255 && got[1] == 0 && got[2] == 0 && got[3] == 255)) report(col, row, got, "red"); } else if (distance < -margin) { @@ -343,7 +395,7 @@ int main() { } } EXPECT(!mismatches); - EXPECT(edge_mixed > 0); // single-sampled rendering leaves no partial pixels + if (!custom) EXPECT(edge_mixed > 0); if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 66c594779e..94564653d9 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -170,6 +170,42 @@ int main() { } } + { + image.format = VK_FORMAT_D32_SFLOAT; + image.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + image.samples = 4; + image.mip_levels = 1; + image.sample_locations_depth = true; + LayoutTracker depth_tracker; + depth_tracker.track(id, image, transfer_src); + vk.pipeline_barrier2 = [](VkCommandBuffer, const VkDependencyInfo* info) { + const auto& barrier = info->pImageMemoryBarriers[0]; + const auto* pattern = static_cast(barrier.pNext); + expect(pattern && pattern->sType == VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, "depth sample locations"); + if (!pattern) return; + const bool custom = barrier.oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + expect(pattern->sampleLocationsCount == 4 && pattern->sampleLocationsPerPixel == VK_SAMPLE_COUNT_4_BIT && + pattern->sampleLocationGridSize.width == 1 && pattern->sampleLocationGridSize.height == 1, + "depth sample grid"); + expect(pattern->pSampleLocations[0].x == (custom ? 0.f : 0.375f) && + pattern->pSampleLocations[0].y == (custom ? 0.9375f : 0.125f), "depth sample before and after reset"); + ++g_calls; + }; + g_calls = 0; + SamplePositions pattern{4, 1}; + pattern.positions[0] = {-8, 7}; + CommandList list; + expect(list.set_sample_positions(pattern) && + list.barrier(TextureBarrier{y::copy, y::copy, a::copy_source, a::copy_dest, l::copy_source, l::copy_dest, id, all, 0}) && + list.set_sample_positions({}) && + list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source, l::copy_dest, l::copy_source, id, all, 0}) && + list.close(), "record depth transitions"); + PreparedList prepared; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare depth transitions"); + emit(prepared, cb, vk, &depth_tracker); + expect(g_calls == 2, "both depth transitions emitted"); + } + if (failures) return 1; std::printf("replay_texture_barrier_test: OK\n"); return 0; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 5cccd1836e..5c448bfb80 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -116,6 +116,7 @@ class Device { bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available + bool sample_locations = false; bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance @@ -571,6 +572,10 @@ class Device { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); if (conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); + sample_locations = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) == 0; + }); + if (sample_locations) device_extensions.push_back(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME); if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension);