upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt18
-rw-r--r--runtime/shims/d3d12_com.h4
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp11
-rw-r--r--runtime/src/conservative_raster.h12
-rw-r--r--runtime/test/conservative_raster_fixture.h220
-rw-r--r--runtime/test/conservative_raster_test.cpp11
-rw-r--r--runtime/test/d3d12_conservative_raster_test.cpp205
-rw-r--r--runtime/test/d3d12_conservative_tier2_test.cpp215
-rw-r--r--runtime/test/glsl/ps_conservative_tier2.frag4
-rw-r--r--runtime/test/glsl/vs_conservative_tier2.vert5
10 files changed, 503 insertions, 202 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 52157011f..0fa39b9e2 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -1708,6 +1708,24 @@ if(TARGET Vulkan::Headers)
1708 add_test(NAME d3d12_conservative_raster COMMAND d3d12_conservative_raster_test) 1708 add_test(NAME d3d12_conservative_raster COMMAND d3d12_conservative_raster_test)
1709 set_tests_properties(d3d12_conservative_raster PROPERTIES SKIP_RETURN_CODE 77 1709 set_tests_properties(d3d12_conservative_raster PROPERTIES SKIP_RETURN_CODE 77
1710 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") 1710 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp")
1711 set(LEONIDA_CONSERVATIVE_TIER2_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative_tier2.spv)
1712 set(LEONIDA_CONSERVATIVE_TIER2_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier2.spv)
1713 foreach(pair "vs_conservative_tier2.vert;${LEONIDA_CONSERVATIVE_TIER2_VS}" "ps_conservative_tier2.frag;${LEONIDA_CONSERVATIVE_TIER2_PS}")
1714 list(GET pair 0 source)
1715 list(GET pair 1 output)
1716 add_custom_command(OUTPUT ${output}
1717 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output}
1718 ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source}
1719 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM)
1720 endforeach()
1721 add_executable(d3d12_conservative_tier2_test test/d3d12_conservative_tier2_test.cpp
1722 ${LEONIDA_CONSERVATIVE_TIER2_VS} ${LEONIDA_CONSERVATIVE_TIER2_PS})
1723 target_link_libraries(d3d12_conservative_tier2_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1724 target_compile_definitions(d3d12_conservative_tier2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1725 LEONIDA_CONSERVATIVE_TIER2_VS="${LEONIDA_CONSERVATIVE_TIER2_VS}" LEONIDA_CONSERVATIVE_TIER2_PS="${LEONIDA_CONSERVATIVE_TIER2_PS}")
1726 target_compile_options(d3d12_conservative_tier2_test PRIVATE /W4 /permissive- /utf-8)
1727 add_test(NAME d3d12_conservative_tier2 COMMAND d3d12_conservative_tier2_test)
1728 set_tests_properties(d3d12_conservative_tier2 PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp")
1711 add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp 1729 add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp
1712 ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) 1730 ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS})
1713 target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) 1731 target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com)
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index bf8c12b91..e70b6ddde 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -106,8 +106,8 @@ struct VulkanDeviceInfo {
106 // rejected at ExecuteCommandLists. 106 // rejected at ExecuteCommandLists.
107 bool conditional_rendering = false; 107 bool conditional_rendering = false;
108 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled: byte-granular predicated buffer copies. 108 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled: byte-granular predicated buffer copies.
109 // VK_EXT_conservative_rasterization is enabled on the logical device. Tier 1 is exposed only when its 109 // VK_EXT_conservative_rasterization is enabled on the logical device. Tier 1/2 depend on the physical
110 // physical-device precision/overestimation properties also meet the implemented requirements. 110 // precision/overestimation properties; Tier 2 also requires post-snap degenerate triangles.
111 bool conservative_rasterization = false; 111 bool conservative_rasterization = false;
112 // VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and 112 // VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and
113 // ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit. 113 // ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit.
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 4c4638501..b53756075 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -430,7 +430,7 @@ struct DeviceState {
430 // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. 430 // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19.
431 UINT no_output_sample_counts = 0; 431 UINT no_output_sample_counts = 0;
432 float max_sampler_lod_bias = 0; 432 float max_sampler_lod_bias = 0;
433 bool conservative_raster_tier1 = false; 433 D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED;
434 // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. 434 // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use.
435 VkResolveModeFlags depth_resolve_modes = 0; 435 VkResolveModeFlags depth_resolve_modes = 0;
436 VkResolveModeFlags stencil_resolve_modes = 0; 436 VkResolveModeFlags stencil_resolve_modes = 0;
@@ -2685,7 +2685,7 @@ public:
2685 if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && 2685 if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF &&
2686 r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) return E_INVALIDARG; 2686 r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) return E_INVALIDARG;
2687 if (r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) { 2687 if (r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) {
2688 if (!device_.conservative_raster_tier1) { 2688 if (device_.conservative_raster_tier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) {
2689 log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); 2689 log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1);
2690 return E_INVALIDARG; 2690 return E_INVALIDARG;
2691 } 2691 }
@@ -3918,9 +3918,9 @@ public:
3918 if (info.conservative_rasterization) resolve.pNext = &conservative; 3918 if (info.conservative_rasterization) resolve.pNext = &conservative;
3919 VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; 3919 VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve};
3920 get_props2(info.physical, &props); 3920 get_props2(info.physical, &props);
3921 state_.conservative_raster_tier1 = leonida::conservative_raster::tier1( 3921 state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier(
3922 info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, 3922 info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits,
3923 conservative.primitiveOverestimationSize); 3923 conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE));
3924 state_.depth_resolve_modes = resolve.supportedDepthResolveModes; 3924 state_.depth_resolve_modes = resolve.supportedDepthResolveModes;
3925 state_.stencil_resolve_modes = resolve.supportedStencilResolveModes; 3925 state_.stencil_resolve_modes = resolve.supportedStencilResolveModes;
3926 } 3926 }
@@ -5862,8 +5862,7 @@ public:
5862 opts->PSSpecifiedStencilRefSupported = TRUE; 5862 opts->PSSpecifiedStencilRefSupported = TRUE;
5863 opts->TypedUAVLoadAdditionalFormats = TRUE; 5863 opts->TypedUAVLoadAdditionalFormats = TRUE;
5864 opts->ROVsSupported = TRUE; 5864 opts->ROVsSupported = TRUE;
5865 opts->ConservativeRasterizationTier = state_.conservative_raster_tier1 5865 opts->ConservativeRasterizationTier = state_.conservative_raster_tier;
5866 ? D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 : D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED;
5867 opts->MaxGPUVirtualAddressBitsPerResource = 40; 5866 opts->MaxGPUVirtualAddressBitsPerResource = 40;
5868 opts->StandardSwizzle64KBSupported = FALSE; 5867 opts->StandardSwizzle64KBSupported = FALSE;
5869 opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; 5868 opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED;
diff --git a/runtime/src/conservative_raster.h b/runtime/src/conservative_raster.h
index cf2f5f2c0..82c1330a2 100644
--- a/runtime/src/conservative_raster.h
+++ b/runtime/src/conservative_raster.h
@@ -1,14 +1,24 @@
1#pragma once 1#pragma once
2#include <cmath> 2#include <cmath>
3#include <cstdint> 3#include <cstdint>
4#include <algorithm>
4 5
5namespace leonida::conservative_raster { 6namespace leonida::conservative_raster {
6// Tier 1 bounds the outer uncertainty to half a pixel and requires a 16.8 rasterization grid. Leave room for 7// Tier 1 bounds the outer uncertainty to half a pixel and requires a 16.8 rasterization grid. Leave room for
7// half a grid step at that minimum precision in addition to Vulkan's fixed primitive overestimation. Do not 8// half a grid step at that minimum precision in addition to Vulkan's fixed primitive overestimation. Do not
8// infer Tier 2/3 from degenerate-triangle support: their tighter bounds and InnerCoverage need separate work. 9// infer Tier 3 from degenerate-triangle support: InnerCoverage needs separate work.
9inline bool tier1(bool extension_enabled, std::uint32_t subpixel_bits, float overestimate) { 10inline bool tier1(bool extension_enabled, std::uint32_t subpixel_bits, float overestimate) {
10 constexpr float maximum = 0.5f - 1.0f / 512.0f; 11 constexpr float maximum = 0.5f - 1.0f / 512.0f;
11 return extension_enabled && subpixel_bits >= 8 && std::isfinite(overestimate) && 12 return extension_enabled && subpixel_bits >= 8 && std::isfinite(overestimate) &&
12 overestimate >= 0.0f && overestimate <= maximum; 13 overestimate >= 0.0f && overestimate <= maximum;
13} 14}
15
16inline std::uint32_t tier(bool extension_enabled, std::uint32_t subpixel_bits, float overestimate,
17 bool degenerate_triangles) {
18 if (!tier1(extension_enabled, subpixel_bits, overestimate)) return 0;
19 // Tier 2 allows 1/256 pixel total uncertainty and requires post-snap degenerates. Reserve half of the
20 // device's actual raster grid step, conservatively capped at float's useful precision, for snapping.
21 const float snap = std::ldexp(0.5f, -int(std::min(subpixel_bits, 24u)));
22 return degenerate_triangles && overestimate <= 1.0f / 256.0f - snap ? 2u : 1u;
23}
14} // namespace leonida::conservative_raster 24} // namespace leonida::conservative_raster
diff --git a/runtime/test/conservative_raster_fixture.h b/runtime/test/conservative_raster_fixture.h
new file mode 100644
index 000000000..1035ea667
--- /dev/null
+++ b/runtime/test/conservative_raster_fixture.h
@@ -0,0 +1,220 @@
1#pragma once
2// Synthetic D3D12/Vulkan conservative coverage. Required/forbidden pixels come from geometric clipping,
3// not a driver snapshot: Tier 1 may over-cover by half a pixel, so uncertain pixels are not compared exactly.
4#include "vk_test_device.h"
5#include "d3d12_copy_compare.h"
6#include "d3d12_test_shaders.h"
7#include "host_wine.h"
8#include "../src/conservative_raster.h"
9#include "../src/shader_library.h"
10#include <d3dcompiler.h>
11#include <array>
12#include <cmath>
13#include <climits>
14#include <span>
15
16#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0)
17namespace conservative_test {
18constexpr UINT width = 32, height = 32, pitch = 256;
19struct Point { double x, y; };
20using Triangle = std::array<Point, 3>;
21using Mask = std::array<bool, width * height>;
22struct Fixture {
23 copycmp::Run run;
24 copycmp::Ptr<ID3D12RootSignature> root;
25 D3D12_SHADER_BYTECODE vs{}, ps{};
26 std::span<const D3D12_INPUT_ELEMENT_DESC> input;
27};
28struct VertexInput {
29 std::vector<float> data;
30 UINT stride = 16;
31 std::vector<std::uint16_t> indices;
32 D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
33};
34
35inline bool setup(Fixture& f, ID3D12Device* device, bool ours, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) {
36 f.vs = vs; f.ps = ps;
37 CHECK(f.run.init(device, ours));
38 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
39 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
40 desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
41 const auto bytes = d3d12test::serialize_root_signature(desc);
42 CHECK(!bytes.empty());
43 CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&f.root.p))));
44 return true;
45}
46
47inline D3D12_GRAPHICS_PIPELINE_STATE_DESC description(const Fixture& f, bool conservative, UINT samples, bool variant) {
48 static const D3D12_INPUT_ELEMENT_DESC element{
49 "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0};
50 D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
51 d.pRootSignature = f.root.p;
52 d.VS = f.vs; d.PS = f.ps;
53 d.InputLayout = f.input.empty() ? D3D12_INPUT_LAYOUT_DESC{&element, 1}
54 : D3D12_INPUT_LAYOUT_DESC{f.input.data(), UINT(f.input.size())};
55 d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
56 d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
57 d.RasterizerState.DepthClipEnable = TRUE;
58 d.RasterizerState.MultisampleEnable = samples > 1;
59 d.RasterizerState.ConservativeRaster = conservative ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
60 : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
61 d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
62 d.NumRenderTargets = variant ? 2 : 1;
63 d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
64 if (variant) d.RTVFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM;
65 d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
66 d.SampleDesc.Count = samples;
67 d.SampleMask = UINT_MAX;
68 return d;
69}
70
71// Clip the triangle to a pixel rectangle and return its intersection area.
72inline double area(const Triangle& triangle, double left, double top, double right, double bottom, bool* intersects = nullptr) {
73 std::vector<Point> p(triangle.begin(), triangle.end());
74 for (unsigned side = 0; side < 4 && !p.empty(); ++side) {
75 const auto distance = [&](Point v) {
76 return side == 0 ? v.x - left : side == 1 ? right - v.x : side == 2 ? v.y - top : bottom - v.y;
77 };
78 std::vector<Point> out;
79 Point a = p.back(); double da = distance(a);
80 for (const Point b : p) {
81 const double db = distance(b);
82 if ((da >= 0) != (db >= 0)) {
83 const double t = da / (da - db);
84 out.push_back({a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)});
85 }
86 if (db >= 0) out.push_back(b);
87 a = b; da = db;
88 }
89 p = std::move(out);
90 }
91 double sum = 0;
92 if (intersects) *intersects = !p.empty(); // a degenerate triangle may cover pixels despite having zero area
93 for (std::size_t i = 0; i < p.size(); ++i) {
94 const Point a = p[i], b = p[(i + 1) % p.size()];
95 sum += a.x * b.y - a.y * b.x;
96 }
97 return std::abs(sum) * 0.5;
98}
99
100inline bool render(Fixture& f, const Triangle& triangle, bool conservative, UINT samples, bool variant,
101 const D3D12_RECT& scissor, Mask& mask, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE,
102 const VertexInput* input = nullptr, std::vector<unsigned char>* rgba = nullptr) {
103 auto& r = f.run;
104 auto desc = description(f, conservative, samples, variant);
105 desc.RasterizerState.CullMode = cull;
106 copycmp::Ptr<ID3D12PipelineState> pso;
107 const auto created = r.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p));
108 if (FAILED(created)) {
109 std::fprintf(stderr, "%s CreateGraphicsPipelineState=%08x conservative=%d samples=%u variant=%d\n",
110 r.ours ? "Vulkan" : "host", unsigned(created), int(conservative), samples, int(variant));
111 return false;
112 }
113 D3D12_RESOURCE_DESC tex{};
114 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
115 tex.Width = width; tex.Height = height;
116 tex.DepthOrArraySize = tex.MipLevels = 1;
117 tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
118 tex.SampleDesc.Count = samples;
119 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
120 copycmp::Ptr<ID3D12Resource> target, resolved, vertices, indices, readback;
121 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target));
122 if (samples > 1) {
123 tex.SampleDesc.Count = 1; tex.Flags = D3D12_RESOURCE_FLAG_NONE;
124 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RESOLVE_DEST, resolved));
125 }
126 const UINT vertex_bytes = input ? UINT(input->data.size() * sizeof(float)) : 24;
127 CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, vertex_bytes, D3D12_RESOURCE_STATE_GENERIC_READ, vertices));
128 CHECK(r.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback));
129 void* data = nullptr;
130 const D3D12_RANGE none{};
131 CHECK(SUCCEEDED(vertices->Map(0, &none, &data)));
132 if (input) std::memcpy(data, input->data.data(), vertex_bytes);
133 else {
134 auto* positions = static_cast<float*>(data);
135 for (unsigned i = 0; i < 3; ++i) {
136 positions[i * 2] = float(triangle[i].x * 2 / width - 1);
137 positions[i * 2 + 1] = float(1 - triangle[i].y * 2 / height);
138 }
139 }
140 vertices->Unmap(0, nullptr);
141 if (input && !input->indices.empty()) {
142 CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, input->indices.size() * sizeof(std::uint16_t),
143 D3D12_RESOURCE_STATE_GENERIC_READ, indices));
144 CHECK(SUCCEEDED(indices->Map(0, &none, &data)));
145 std::memcpy(data, input->indices.data(), input->indices.size() * sizeof(std::uint16_t));
146 indices->Unmap(0, nullptr);
147 }
148 copycmp::Ptr<ID3D12DescriptorHeap> heap;
149 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
150 CHECK(SUCCEEDED(r.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p))));
151 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
152 r.device->CreateRenderTargetView(target.p, nullptr, handle);
153 r.begin();
154 const float clear[4] = {};
155 r.list->ClearRenderTargetView(handle, clear, 0, nullptr);
156 r.list->OMSetRenderTargets(1, &handle, FALSE, nullptr);
157 r.list->SetGraphicsRootSignature(f.root.p);
158 r.list->SetPipelineState(pso.p);
159 const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1};
160 r.list->RSSetViewports(1, &viewport);
161 r.list->RSSetScissorRects(1, &scissor);
162 const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), vertex_bytes, input ? input->stride : 8};
163 r.list->IASetVertexBuffers(0, 1, &vb);
164 r.list->IASetPrimitiveTopology(input ? input->topology : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
165 if (indices.p) {
166 const D3D12_INDEX_BUFFER_VIEW ib{indices->GetGPUVirtualAddress(), UINT(input->indices.size() * 2), DXGI_FORMAT_R16_UINT};
167 r.list->IASetIndexBuffer(&ib);
168 r.list->DrawIndexedInstanced(UINT(input->indices.size()), 1, 0, 0, 0);
169 } else r.list->DrawInstanced(input ? vertex_bytes / input->stride : 3, 1, 0, 0);
170 ID3D12Resource* source = target.p;
171 if (samples > 1) {
172 r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
173 r.list->ResolveSubresource(resolved.p, 0, target.p, 0, tex.Format);
174 r.barrier(resolved.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
175 source = resolved.p;
176 } else r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
177 D3D12_TEXTURE_COPY_LOCATION from{}, to{};
178 from.pResource = source; from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
179 to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
180 to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch};
181 r.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
182 const auto error = r.submit();
183 if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; }
184 CHECK(SUCCEEDED(readback->Map(0, nullptr, &data)));
185 const auto* pixels = static_cast<const unsigned char*>(data);
186 if (rgba) rgba->resize(width * height * 4);
187 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
188 const auto* p = pixels + y * pitch + x * 4;
189 if (rgba) {
190 std::copy(p, p + 4, rgba->begin() + (y * width + x) * 4);
191 mask[y * width + x] = (p[0] | p[1] | p[2] | p[3]) != 0;
192 } else {
193 CHECK(p[1] == 0 && p[2] == 0 && p[0] == p[3]);
194 if (conservative) CHECK(p[0] == 0 || p[0] == 255); // every MSAA sample is covered
195 mask[y * width + x] = p[0] != 0;
196 }
197 }
198 readback->Unmap(0, &none);
199 return true;
200}
201
202inline bool coverage(const Triangle& triangle, const D3D12_RECT& scissor, const Mask& mask) {
203 constexpr double epsilon = 1.0 / 256;
204 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
205 const bool in = LONG(x) >= scissor.left && LONG(x) < scissor.right && LONG(y) >= scissor.top && LONG(y) < scissor.bottom;
206 const bool required = in && area(triangle, x + epsilon, y + epsilon, x + 1 - epsilon, y + 1 - epsilon) > 1e-9;
207 bool intersects = false;
208 area(triangle, x - 0.5 - epsilon, y - 0.5 - epsilon, x + 1.5 + epsilon, y + 1.5 + epsilon, &intersects);
209 const bool allowed = in && intersects;
210 if ((required && !mask[y * width + x]) || (!allowed && mask[y * width + x])) {
211 std::fprintf(stderr, "coverage (%u,%u): required=%d allowed=%d actual=%d\n", x, y,
212 int(required), int(allowed), int(mask[y * width + x]));
213 return false;
214 }
215 }
216 return true;
217}
218
219
220} // namespace conservative_test
diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp
index b16053f1e..726bd9f32 100644
--- a/runtime/test/conservative_raster_test.cpp
+++ b/runtime/test/conservative_raster_test.cpp
@@ -15,6 +15,17 @@ int main() {
15 check(!tier1(true, 8, -0.001f)); 15 check(!tier1(true, 8, -0.001f));
16 check(!tier1(true, 8, std::numeric_limits<float>::infinity())); 16 check(!tier1(true, 8, std::numeric_limits<float>::infinity()));
17 check(!tier1(true, 8, std::numeric_limits<float>::quiet_NaN())); 17 check(!tier1(true, 8, std::numeric_limits<float>::quiet_NaN()));
18 using leonida::conservative_raster::tier;
19 check(tier(false, 8, 0, true) == 0);
20 check(tier(true, 7, 0, true) == 0);
21 check(tier(true, 8, 0, true) == 2);
22 check(tier(true, 8, 0, false) == 1);
23 check(tier(true, 8, 1.0f / 512.0f, true) == 2);
24 check(tier(true, 8, std::nextafter(1.0f / 512.0f, 1.0f), true) == 1);
25 check(tier(true, 8, 1.0f / 256.0f, true) == 1);
26 check(tier(true, 16, 0.003f, true) == 2);
27 check(tier(true, 16, 0.003f, false) == 1);
28 check(tier(true, 8, std::numeric_limits<float>::quiet_NaN(), true) == 0);
18 if (failures) std::fprintf(stderr, "conservative raster capability checks: %u failures\n", failures); 29 if (failures) std::fprintf(stderr, "conservative raster capability checks: %u failures\n", failures);
19 else std::puts("conservative raster: enabled extension, precision and uncertainty bounds checked"); 30 else std::puts("conservative raster: enabled extension, precision and uncertainty bounds checked");
20 return failures ? 1 : 0; 31 return failures ? 1 : 0;
diff --git a/runtime/test/d3d12_conservative_raster_test.cpp b/runtime/test/d3d12_conservative_raster_test.cpp
index 31a861af2..85d26834a 100644
--- a/runtime/test/d3d12_conservative_raster_test.cpp
+++ b/runtime/test/d3d12_conservative_raster_test.cpp
@@ -1,189 +1,7 @@
1// Synthetic D3D12/Vulkan conservative coverage. Required/forbidden pixels come from geometric clipping, 1// Tier 1 regression coverage and public-device capability checks.
2// not a driver snapshot: Tier 1 may over-cover by half a pixel, so uncertain pixels are not compared exactly. 2#include "conservative_raster_fixture.h"
3#include "vk_test_device.h" 3using namespace conservative_test;
4#include "d3d12_copy_compare.h"
5#include "d3d12_test_shaders.h"
6#include "host_wine.h"
7#include "../src/conservative_raster.h"
8#include "../src/shader_library.h"
9#include <d3dcompiler.h>
10#include <array>
11#include <cmath>
12#include <climits>
13
14#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0)
15namespace { 4namespace {
16constexpr UINT width = 32, height = 32, pitch = 256;
17struct Point { double x, y; };
18using Triangle = std::array<Point, 3>;
19using Mask = std::array<bool, width * height>;
20struct Fixture {
21 copycmp::Run run;
22 copycmp::Ptr<ID3D12RootSignature> root;
23 D3D12_SHADER_BYTECODE vs{}, ps{};
24};
25
26bool setup(Fixture& f, ID3D12Device* device, bool ours, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) {
27 f.vs = vs; f.ps = ps;
28 CHECK(f.run.init(device, ours));
29 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
30 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
31 desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
32 const auto bytes = d3d12test::serialize_root_signature(desc);
33 CHECK(!bytes.empty());
34 CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&f.root.p))));
35 return true;
36}
37
38D3D12_GRAPHICS_PIPELINE_STATE_DESC description(const Fixture& f, bool conservative, UINT samples, bool variant) {
39 static const D3D12_INPUT_ELEMENT_DESC element{
40 "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0};
41 D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
42 d.pRootSignature = f.root.p;
43 d.VS = f.vs; d.PS = f.ps;
44 d.InputLayout = {&element, 1};
45 d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
46 d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
47 d.RasterizerState.DepthClipEnable = TRUE;
48 d.RasterizerState.MultisampleEnable = samples > 1;
49 d.RasterizerState.ConservativeRaster = conservative ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
50 : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
51 d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
52 d.NumRenderTargets = variant ? 2 : 1;
53 d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
54 if (variant) d.RTVFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM;
55 d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
56 d.SampleDesc.Count = samples;
57 d.SampleMask = UINT_MAX;
58 return d;
59}
60
61// Clip the triangle to a pixel rectangle and return its intersection area.
62double area(const Triangle& triangle, double left, double top, double right, double bottom, bool* intersects = nullptr) {
63 std::vector<Point> p(triangle.begin(), triangle.end());
64 for (unsigned side = 0; side < 4 && !p.empty(); ++side) {
65 const auto distance = [&](Point v) {
66 return side == 0 ? v.x - left : side == 1 ? right - v.x : side == 2 ? v.y - top : bottom - v.y;
67 };
68 std::vector<Point> out;
69 Point a = p.back(); double da = distance(a);
70 for (const Point b : p) {
71 const double db = distance(b);
72 if ((da >= 0) != (db >= 0)) {
73 const double t = da / (da - db);
74 out.push_back({a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)});
75 }
76 if (db >= 0) out.push_back(b);
77 a = b; da = db;
78 }
79 p = std::move(out);
80 }
81 double sum = 0;
82 if (intersects) *intersects = !p.empty(); // a degenerate triangle may cover pixels despite having zero area
83 for (std::size_t i = 0; i < p.size(); ++i) {
84 const Point a = p[i], b = p[(i + 1) % p.size()];
85 sum += a.x * b.y - a.y * b.x;
86 }
87 return std::abs(sum) * 0.5;
88}
89
90bool render(Fixture& f, const Triangle& triangle, bool conservative, UINT samples, bool variant,
91 const D3D12_RECT& scissor, Mask& mask, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE) {
92 auto& r = f.run;
93 auto desc = description(f, conservative, samples, variant);
94 desc.RasterizerState.CullMode = cull;
95 copycmp::Ptr<ID3D12PipelineState> pso;
96 const auto created = r.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p));
97 if (FAILED(created)) {
98 std::fprintf(stderr, "%s CreateGraphicsPipelineState=%08x conservative=%d samples=%u variant=%d\n",
99 r.ours ? "Vulkan" : "host", unsigned(created), int(conservative), samples, int(variant));
100 return false;
101 }
102 D3D12_RESOURCE_DESC tex{};
103 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
104 tex.Width = width; tex.Height = height;
105 tex.DepthOrArraySize = tex.MipLevels = 1;
106 tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
107 tex.SampleDesc.Count = samples;
108 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
109 copycmp::Ptr<ID3D12Resource> target, resolved, vertices, readback;
110 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target));
111 if (samples > 1) {
112 tex.SampleDesc.Count = 1; tex.Flags = D3D12_RESOURCE_FLAG_NONE;
113 CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RESOLVE_DEST, resolved));
114 }
115 CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, 24, D3D12_RESOURCE_STATE_GENERIC_READ, vertices));
116 CHECK(r.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback));
117 void* data = nullptr;
118 const D3D12_RANGE none{};
119 CHECK(SUCCEEDED(vertices->Map(0, &none, &data)));
120 auto* positions = static_cast<float*>(data);
121 for (unsigned i = 0; i < 3; ++i) {
122 positions[i * 2] = float(triangle[i].x * 2 / width - 1);
123 positions[i * 2 + 1] = float(1 - triangle[i].y * 2 / height);
124 }
125 vertices->Unmap(0, nullptr);
126 copycmp::Ptr<ID3D12DescriptorHeap> heap;
127 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
128 CHECK(SUCCEEDED(r.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p))));
129 const auto handle = heap->GetCPUDescriptorHandleForHeapStart();
130 r.device->CreateRenderTargetView(target.p, nullptr, handle);
131 r.begin();
132 const float clear[4] = {};
133 r.list->ClearRenderTargetView(handle, clear, 0, nullptr);
134 r.list->OMSetRenderTargets(1, &handle, FALSE, nullptr);
135 r.list->SetGraphicsRootSignature(f.root.p);
136 r.list->SetPipelineState(pso.p);
137 const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1};
138 r.list->RSSetViewports(1, &viewport);
139 r.list->RSSetScissorRects(1, &scissor);
140 const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), 24, 8};
141 r.list->IASetVertexBuffers(0, 1, &vb);
142 r.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
143 r.list->DrawInstanced(3, 1, 0, 0);
144 ID3D12Resource* source = target.p;
145 if (samples > 1) {
146 r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
147 r.list->ResolveSubresource(resolved.p, 0, target.p, 0, tex.Format);
148 r.barrier(resolved.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
149 source = resolved.p;
150 } else r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
151 D3D12_TEXTURE_COPY_LOCATION from{}, to{};
152 from.pResource = source; from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
153 to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
154 to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch};
155 r.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
156 const auto error = r.submit();
157 if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; }
158 CHECK(SUCCEEDED(readback->Map(0, nullptr, &data)));
159 const auto* pixels = static_cast<const unsigned char*>(data);
160 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
161 const auto* p = pixels + y * pitch + x * 4;
162 CHECK(p[1] == 0 && p[2] == 0 && p[0] == p[3]);
163 if (conservative) CHECK(p[0] == 0 || p[0] == 255); // every MSAA sample is covered
164 mask[y * width + x] = p[0] != 0;
165 }
166 readback->Unmap(0, &none);
167 return true;
168}
169
170bool coverage(const Triangle& triangle, const D3D12_RECT& scissor, const Mask& mask) {
171 constexpr double epsilon = 1.0 / 256;
172 for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) {
173 const bool in = LONG(x) >= scissor.left && LONG(x) < scissor.right && LONG(y) >= scissor.top && LONG(y) < scissor.bottom;
174 const bool required = in && area(triangle, x + epsilon, y + epsilon, x + 1 - epsilon, y + 1 - epsilon) > 1e-9;
175 bool intersects = false;
176 area(triangle, x - 0.5 - epsilon, y - 0.5 - epsilon, x + 1.5 + epsilon, y + 1.5 + epsilon, &intersects);
177 const bool allowed = in && intersects;
178 if ((required && !mask[y * width + x]) || (!allowed && mask[y * width + x])) {
179 std::fprintf(stderr, "coverage (%u,%u): required=%d allowed=%d actual=%d\n", x, y,
180 int(required), int(allowed), int(mask[y * width + x]));
181 return false;
182 }
183 }
184 return true;
185}
186
187bool rejected_states(Fixture& f, bool enabled) { 5bool rejected_states(Fixture& f, bool enabled) {
188 auto desc = description(f, true, 1, false); 6 auto desc = description(f, true, 1, false);
189 copycmp::Ptr<ID3D12PipelineState> pso; 7 copycmp::Ptr<ID3D12PipelineState> pso;
@@ -228,12 +46,12 @@ bool owned_device_caps() {
228 if (available) properties.pNext = &conservative; 46 if (available) properties.pNext = &conservative;
229 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(info->get_instance_proc(info->instance, 47 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(info->get_instance_proc(info->instance,
230 "vkGetPhysicalDeviceProperties2"))(info->physical, &properties); 48 "vkGetPhysicalDeviceProperties2"))(info->physical, &properties);
231 const bool expected = leonida::conservative_raster::tier1(available, 49 const auto expected = leonida::conservative_raster::tier(available,
232 properties.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize); 50 properties.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize,
51 conservative.degenerateTrianglesRasterized == VK_TRUE);
233 D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; 52 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
234 CHECK(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); 53 CHECK(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))));
235 CHECK(options.ConservativeRasterizationTier == (expected ? D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 54 CHECK(unsigned(options.ConservativeRasterizationTier) == expected);
236 : D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED));
237 return true; 55 return true;
238} 56}
239} // namespace 57} // namespace
@@ -280,13 +98,14 @@ int main(int argc, char** argv) {
280 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; 98 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
281 D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; 99 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
282 if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1; 100 if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1;
283 const bool expected_tier1 = leonida::conservative_raster::tier1(vk.conservative_rasterization, 101 const auto expected_tier = leonida::conservative_raster::tier(vk.conservative_rasterization,
284 properties.properties.limits.subPixelPrecisionBits, conservative_properties.primitiveOverestimationSize); 102 properties.properties.limits.subPixelPrecisionBits, conservative_properties.primitiveOverestimationSize,
285 if ((options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_1) != expected_tier1) return 1; 103 conservative_properties.degenerateTrianglesRasterized == VK_TRUE);
104 if (unsigned(options.ConservativeRasterizationTier) != expected_tier) return 1;
286 if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { 105 if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) {
287 std::puts("SKIP: Vulkan device does not meet conservative raster Tier 1 requirements"); return 77; 106 std::puts("SKIP: Vulkan device does not meet conservative raster Tier 1 requirements"); return 77;
288 } 107 }
289 if (options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_1) return 1; 108 if (options.ConservativeRasterizationTier > D3D12_CONSERVATIVE_RASTERIZATION_TIER_2) return 1;
290 if (!owned_device_caps()) return 1; 109 if (!owned_device_caps()) return 1;
291 std::string adapter; 110 std::string adapter;
292 if (!copycmp::create_host(host, adapter)) return 1; 111 if (!copycmp::create_host(host, adapter)) return 1;
diff --git a/runtime/test/d3d12_conservative_tier2_test.cpp b/runtime/test/d3d12_conservative_tier2_test.cpp
new file mode 100644
index 000000000..81eaa4eef
--- /dev/null
+++ b/runtime/test/d3d12_conservative_tier2_test.cpp
@@ -0,0 +1,215 @@
1// Tier 2: tight uncertainty, exact and post-snap degenerates. RGB independently encodes varying colour,
2// constant depth and facing. No game data.
3#include "conservative_raster_fixture.h"
4using namespace conservative_test;
5
6namespace {
7double cross(const Triangle& t) {
8 return (t[1].x-t[0].x)*(t[2].y-t[0].y) - (t[1].y-t[0].y)*(t[2].x-t[0].x);
9}
10
11bool tight_coverage(const Triangle& original, const Triangle* snapped, const D3D12_RECT& scissor,
12 const Mask& mask, bool log = true) {
13 constexpr double epsilon = 1e-7, uncertainty = 1.0 / 256;
14 unsigned required_count = 0, covered = 0;
15 for (UINT y=0;y<height;++y) for (UINT x=0;x<width;++x) {
16 const bool in = LONG(x)>=scissor.left && LONG(x)<scissor.right && LONG(y)>=scissor.top && LONG(y)<scissor.bottom;
17 bool hits = false;
18 const double intersection = area(snapped ? *snapped : original,
19 x+epsilon,y+epsilon,x+1-epsilon,y+1-epsilon,&hits);
20 const bool required = in && (snapped ? hits : intersection > 1e-12);
21 area(original,x-uncertainty-epsilon,y-uncertainty-epsilon,
22 x+1+uncertainty+epsilon,y+1+uncertainty+epsilon,&hits);
23 const bool allowed = in && hits;
24 if ((required && !mask[y*width+x]) || (!allowed && mask[y*width+x])) {
25 if (log) std::fprintf(stderr,"Tier 2 coverage (%u,%u): required=%d allowed=%d actual=%d\n",
26 x,y,int(required),int(allowed),int(mask[y*width+x]));
27 return false;
28 }
29 required_count += unsigned(required); covered += unsigned(mask[y*width+x]);
30 }
31 // A snapped point on a pixel corner has no required open-pixel intersection, but must cover at least one
32 // adjacent pixel. Its particular edge/corner tie-breaking is not asserted.
33 if (snapped && !required_count && !covered && log) std::fprintf(stderr,"snapped corner produced no fragments\n");
34 return !snapped || required_count || covered;
35}
36
37VertexInput vertices(const std::vector<Point>& points, std::vector<std::uint16_t> indices,
38 D3D_PRIMITIVE_TOPOLOGY topology) {
39 // Keep depth planar: native D3D12 and Vulkan may extrapolate SV_Position.z for screen-space degenerates.
40 static constexpr float depths[] = {0.375f,0.375f,0.375f,0.375f};
41 static constexpr float markers[] = {0.25f,0.75f,0.375f,0.875f};
42 VertexInput out; out.indices=std::move(indices); out.topology=topology;
43 for (std::size_t i=0;i<points.size();++i) {
44 out.data.push_back(float(points[i].x*2/width-1));
45 out.data.push_back(float(1-points[i].y*2/height));
46 out.data.push_back(depths[i]); out.data.push_back(markers[i]);
47 }
48 return out;
49}
50
51Triangle actual_triangle(const VertexInput& input, unsigned first = 0) {
52 Triangle t{};
53 for (unsigned i=0;i<3;++i) {
54 const auto at=std::size_t(input.indices[first+i])*4;
55 t[i]={(double(input.data[at])+1)*width/2,(1-double(input.data[at+1]))*height/2};
56 }
57 return t;
58}
59
60Triangle quantized(Triangle t, unsigned bits) {
61 const double grid=std::ldexp(1.0,int(bits));
62 for (auto& p:t) { p.x=std::nearbyint(p.x*grid)/grid; p.y=std::nearbyint(p.y*grid)/grid; }
63 return t;
64}
65
66bool attributes(const Mask& mask, const std::vector<unsigned char>& rgba, unsigned provoking) {
67 static constexpr std::array<unsigned char,4> expected[] = {
68 {64,96,0,255},{191,96,0,255},{96,96,0,255},{223,96,0,255}};
69 for (unsigned i=0;i<mask.size();++i) {
70 const auto* p=rgba.data()+i*4;
71 if (!mask[i]) { CHECK(!(p[0]|p[1]|p[2]|p[3])); continue; }
72 for (unsigned lane=0;lane<4;++lane) {
73 if (p[lane]!=expected[provoking][lane]) {
74 std::fprintf(stderr,"post-snap pixel %u lane %u: got %02x, provoking %u expects %02x\n",
75 i,lane,unsigned(p[lane]),provoking,unsigned(expected[provoking][lane]));
76 return false;
77 }
78 }
79 }
80 return true;
81}
82
83bool oracle_control() {
84 const Triangle triangle{{{8.015625,4.25},{9.25,4.25},{8.015625,24.25}}};
85 const D3D12_RECT full{0,0,32,32};
86 Mask mask{};
87 for (UINT y=0;y<height;++y) for (UINT x=0;x<width;++x)
88 mask[y*width+x]=area(triangle,x+1e-7,y+1e-7,x+1-1e-7,y+1-1e-7)>1e-12;
89 CHECK(tight_coverage(triangle,nullptr,full,mask));
90 mask[8*width+7]=true; // within Tier 1's half-pixel margin, outside Tier 2's 1/256 margin
91 CHECK(coverage(triangle,full,mask));
92 CHECK(!tight_coverage(triangle,nullptr,full,mask,false));
93 return true;
94}
95} // namespace
96
97int main(int argc, char** argv) {
98 const bool warp_corner = argc > 1 && std::strcmp(argv[1], "--warp-corner") == 0;
99 if (!oracle_control()) return 1;
100 if (hostwine::host_is_wine()) return 77;
101 vktest::Device vk; vk.request_buffer_device_address=true;
102 const auto status=vk.initialize();
103 if(status==vktest::DeviceStatus::unavailable)return 77;
104 if(status!=vktest::DeviceStatus::ready)return 1;
105 VkPhysicalDeviceConservativeRasterizationPropertiesEXT cr{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT};
106 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
107 if(vk.conservative_rasterization)properties.pNext=&cr;
108 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(vk.instance_proc(vk.instance,"vkGetPhysicalDeviceProperties2"))(vk.physical,&properties);
109 const auto tier=leonida::conservative_raster::tier(vk.conservative_rasterization,
110 properties.properties.limits.subPixelPrecisionBits,cr.primitiveOverestimationSize,cr.degenerateTrianglesRasterized==VK_TRUE);
111 if(!vk.buffer_device_address||properties.properties.limits.maxPushConstantsSize<144)return 77;
112 const auto vs_program=d3d12test::fssm_program({0x54325653,0xbf810000});
113 const auto ps_program=d3d12test::fssm_program({0x54325053,0xbf810000});
114 const auto vs_bytes=d3d12test::shader_container(vs_program),ps_bytes=d3d12test::shader_container(ps_program);
115 const auto directory=std::filesystem::temp_directory_path()/("leonida_conservative_tier2_"+std::to_string(GetCurrentProcessId()));
116 std::filesystem::create_directories(directory);
117 std::filesystem::copy_file(LEONIDA_CONSERVATIVE_TIER2_VS,directory/"vs.spv",std::filesystem::copy_options::overwrite_existing);
118 std::filesystem::copy_file(LEONIDA_CONSERVATIVE_TIER2_PS,directory/"ps.spv",std::filesystem::copy_options::overwrite_existing);
119 {
120 std::ofstream index(directory/"index.json",std::ios::binary);
121 index<<"{\"vs\":{\"stage\":\"vs\",\"fssm_sha256\":\""<<leonida::sha256_hex(vs_program)
122 <<"\",\"bindings\":[],\"push_constant_bytes\":0,\"input_signature\":["
123 "{\"semantic\":\"POSITION\",\"semantic_index\":0,\"register\":0,\"mask\":7,\"rw_mask\":7,\"system_value\":0,\"component_type\":\"float\"},"
124 "{\"semantic\":\"COLOR\",\"semantic_index\":0,\"register\":1,\"mask\":1,\"rw_mask\":1,\"system_value\":0,\"component_type\":\"float\"}]},"
125 "\"ps\":{\"stage\":\"ps\",\"fssm_sha256\":\""<<leonida::sha256_hex(ps_program)
126 <<"\",\"bindings\":[],\"push_constant_bytes\":0,\"outputs\":[0]}}";
127 }
128 rt::d3d12::VulkanDeviceInfo info{};
129 info.get_instance_proc=vk.instance_proc;info.instance=vk.instance;info.physical=vk.physical;
130 info.device=vk.device;info.queue=vk.queue;info.queue_family=vk.family;
131 info.buffer_device_address=vk.buffer_device_address;info.conservative_rasterization=vk.conservative_rasterization;
132 info.shader_dir=directory.string();
133 copycmp::Ptr<ID3D12Device> ours,host;
134 if(FAILED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&ours.p))))return 1;
135 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
136 if(FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options)))||unsigned(options.ConservativeRasterizationTier)!=tier)return 1;
137 if(tier<2){std::puts("SKIP: device does not meet conservative raster Tier 2 requirements");return 77;}
138 std::string adapter;if(!copycmp::create_host(host,adapter))return 1;
139 if(FAILED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options))))return 1;
140 if(options.ConservativeRasterizationTier<D3D12_CONSERVATIVE_RASTERIZATION_TIER_2)return 77;
141 const HMODULE compiler=LoadLibraryExA("d3dcompiler_47.dll",nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);
142 const auto compile=compiler?reinterpret_cast<pD3DCompile>(reinterpret_cast<void*>(GetProcAddress(compiler,"D3DCompile"))):nullptr;
143 if(!compile)return 77;
144 const char* hlsl="struct O{float4 p:SV_Position;float m:COLOR;}; O vs(float3 p:POSITION,float m:COLOR){O o;o.p=float4(p,1);o.m=m;return o;} float4 ps(O o,bool front:SV_IsFrontFace):SV_Target{return float4(o.m,o.p.z,front?1:0,1);}";
145 copycmp::Ptr<ID3DBlob> vs,ps,error;
146 if(FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"vs","vs_5_0",0,0,&vs.p,&error.p))||
147 FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"ps","ps_5_0",0,0,&ps.p,nullptr)))return 1;
148 Fixture a,b;
149 if(!setup(a,ours.p,true,{vs_bytes.data(),vs_bytes.size()},{ps_bytes.data(),ps_bytes.size()})||
150 !setup(b,host.p,false,{vs->GetBufferPointer(),vs->GetBufferSize()},{ps->GetBufferPointer(),ps->GetBufferSize()}))return 1;
151 const D3D12_INPUT_ELEMENT_DESC elements[]={
152 {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0},
153 {"COLOR",0,DXGI_FORMAT_R32_FLOAT,0,12,D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0}};
154 a.input=b.input=elements;
155 const D3D12_RECT full{0,0,32,32},inset{8,8,24,24};
156 unsigned tight_cases=0,degenerate_cases=0;
157 const Triangle tight_scenes[]={
158 {{{8.015625,4.25},{9.25,4.25},{8.015625,24.25}}},
159 {{{3.125,8.001953125},{28.125,8.005859375},{3.125,9.125}}},
160 {{{3.125,3.125},{28.125,28.125},{3.125,3.140625}}},
161 {{{-0.125,8.125},{12.125,8.125},{8.125,28.125}}},
162 };
163 for(auto* fixture:{&a,&b})for(const auto& triangle:tight_scenes)for(const auto scissor:{full,inset}) {
164 Mask mask{};std::vector<unsigned char> rgba;
165 const auto input=vertices(std::vector<Point>(triangle.begin(),triangle.end()),{0,1,2},D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
166 if(!render(*fixture,triangle,true,1,false,scissor,mask,D3D12_CULL_MODE_NONE,&input,&rgba)||
167 !tight_coverage(triangle,nullptr,scissor,mask))return 1;
168 ++tight_cases;
169 }
170 constexpr double delta=1.0/(1u<<20);
171 const std::vector<std::vector<Point>> collapsed={
172 {{16.125,16.125},{16.125+delta,16.125},{16.125,16.125+delta}},
173 {{4.125,16.125},{24.125,16.125},{4.125,16.125+delta}},
174 {{4.125,4.125},{24.125,24.125},{4.125,4.125+delta}},
175 {{16,16},{16+delta,16},{16,16+delta}},
176 {{4.125,16.125},{24.125,16.125},{12.125,16.125}},
177 {{16.125,16.125},{16.125,16.125},{16.125,16.125}},
178 {{16.125,16.125},{16.125+delta,16.125},{16.125,16.125+delta},{16.125+delta,16.125+delta}},
179 };
180 for(auto* fixture:{&a,&b})for(const auto& points:collapsed)
181 for(const auto scissor:{full,inset})for(const bool variant:{false,true}) {
182 std::vector<std::vector<std::uint16_t>> orders=points.size()==4
183 ?std::vector<std::vector<std::uint16_t>>{{0,1,2,3},{3,2,1,0}}
184 :std::vector<std::vector<std::uint16_t>>{{0,1,2},{2,1,0},{1,2,0}};
185 // WARP drops the exact pixel-corner fixture; retain a strict opt-in reproducer.
186 if (!fixture->run.ours && adapter.find("Microsoft Basic") != std::string::npos && points[0].x == 16 && !warp_corner) {
187 std::puts("WARP reference: corner fixture excluded (use --warp-corner to reproduce); Vulkan still checks it");
188 continue;
189 }
190 for(const auto& order:orders) {
191 const bool strip=points.size()==4;
192 const auto input=vertices(points,order,strip?D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP:D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
193 const auto triangle=actual_triangle(input);
194 const auto snapped=quantized(triangle,properties.properties.limits.subPixelPrecisionBits);
195 const bool must_have_area = points.size() == 4 || points[2].y != points[0].y;
196 if (cross(snapped) != 0 || (must_have_area && cross(triangle) == 0)) {
197 std::fprintf(stderr,"fixture lost its intended pre/post-snap area\n"); return 1;
198 }
199 for(const auto cull:{D3D12_CULL_MODE_NONE,D3D12_CULL_MODE_FRONT,D3D12_CULL_MODE_BACK}) {
200 Mask mask{};std::vector<unsigned char> rgba;
201 if(!render(*fixture,triangle,true,1,variant,scissor,mask,cull,&input,&rgba))return 1;
202 if(cull==D3D12_CULL_MODE_BACK) {
203 if(std::any_of(mask.begin(),mask.end(),[](bool x){return x;})){std::fprintf(stderr,"post-snap degenerate was not back-facing\n");return 1;}
204 } else if(!tight_coverage(triangle,&snapped,scissor,mask)||!attributes(mask,rgba,order[strip?1:0])) {
205 std::fprintf(stderr,"%s degenerate points=%zu first=%u strip=%d cull=%u\n",
206 fixture->run.ours?"Vulkan":adapter.c_str(),points.size(),order[0],int(strip),unsigned(cull)); std::fprintf(stderr,"point=(%.9f,%.9f) scissor=%ld variant=%d\n",points[0].x,points[0].y,scissor.left,int(variant));return 1;
207 }
208 ++degenerate_cases;
209 }
210 }
211 }
212 std::printf("Tier 2: %u tight-bound scenes and %u degenerate draw cases across Vulkan and %s; colour/constant-depth/facing, index permutations, strips, culling, scissor and variants checked\n",
213 tight_cases,degenerate_cases,adapter.c_str());
214 return vk.validation_errors()?1:0;
215}
diff --git a/runtime/test/glsl/ps_conservative_tier2.frag b/runtime/test/glsl/ps_conservative_tier2.frag
new file mode 100644
index 000000000..4bb7e03c9
--- /dev/null
+++ b/runtime/test/glsl/ps_conservative_tier2.frag
@@ -0,0 +1,4 @@
1#version 450
2layout(location=0) in float marker;
3layout(location=0) out vec4 color;
4void main() { color = vec4(marker, gl_FragCoord.z, gl_FrontFacing ? 1.0 : 0.0, 1.0); }
diff --git a/runtime/test/glsl/vs_conservative_tier2.vert b/runtime/test/glsl/vs_conservative_tier2.vert
new file mode 100644
index 000000000..a61407382
--- /dev/null
+++ b/runtime/test/glsl/vs_conservative_tier2.vert
@@ -0,0 +1,5 @@
1#version 450
2layout(location=0) in vec3 position;
3layout(location=1) in float marker;
4layout(location=0) out float out_marker;
5void main() { gl_Position = vec4(position, 1.0); out_marker = marker; }