From 7d50f3b749ab8c2902bef94ef8cc76885c22712a Mon Sep 17 00:00:00 2001 From: Juju Date: Tue, 24 Nov 2026 01:38:53 -0500 Subject: [PATCH] d3d12/vulkan: implement multi-viewport and multi-scissor rendering (1..16 viewports/scissors) --- runtime/CMakeLists.txt | 9 + runtime/shims/d3d12_com.cpp | 69 ++- runtime/shims/d3d12_vulkan_device.cpp | 44 +- runtime/src/command_list.h | 10 + runtime/src/vulkan_backend.h | 3 + runtime/src/vulkan_replay.h | 67 ++- runtime/test/d3d12_multi_viewport_test.cpp | 484 +++++++++++++++++++++ runtime/test/replay_cpu_bench.cpp | 2 + runtime/test/vk_test_device.h | 4 + 9 files changed, 652 insertions(+), 40 deletions(-) create mode 100644 runtime/test/d3d12_multi_viewport_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..e39e7661f6 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2294,6 +2294,15 @@ if(TARGET Vulkan::Headers) target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) + + # Multi-viewport & multi-scissor rendering (RSSetViewports / RSSetScissorRects 1..16) against host D3D12. + add_executable(d3d12_multi_viewport_test test/d3d12_multi_viewport_test.cpp) + target_link_libraries(d3d12_multi_viewport_test PRIVATE gta6rt_d3d12_com d3d12 dxgi dxguid) + target_compile_definitions(d3d12_multi_viewport_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_multi_viewport_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_multi_viewport COMMAND d3d12_multi_viewport_test) + set_tests_properties(d3d12_multi_viewport PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..9928b74bcd 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -411,12 +411,20 @@ class GraphicsCommandList final if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!count) { viewport_ = {}; + viewports_.fill({}); + viewport_count_ = 0; + draw_viewports_stale_ = true; return; } if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false); - if (count > 1) stub("ID3D12GraphicsCommandList::RSSetViewports (more than one viewport; the first is used)"); - const D3D12_VIEWPORT& v = viewports[0]; - viewport_ = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; + viewports_.fill({}); + for (UINT i = 0; i < count; ++i) { + const D3D12_VIEWPORT& v = viewports[i]; + viewports_[i] = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; + } + viewport_count_ = count; + viewport_ = viewports_[0]; + draw_viewports_stale_ = true; } void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override { @@ -425,11 +433,20 @@ class GraphicsCommandList final // With no scissor bound, the rasterizer clips every fragment, as on native D3D12. if (!count) { scissor_ = {}; + scissors_.fill({}); + scissor_count_ = 0; + draw_viewports_stale_ = true; return; } if (!rects) return; - if (count > 1) stub("ID3D12GraphicsCommandList::RSSetScissorRects (more than one rectangle; the first is used)"); - scissor_ = {rects[0].left, rects[0].top, rects[0].right, rects[0].bottom}; + if (count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false); + scissors_.fill({}); + for (UINT i = 0; i < count; ++i) { + scissors_[i] = {rects[i].left, rects[i].top, rects[i].right, rects[i].bottom}; + } + scissor_count_ = count; + scissor_ = scissors_[0]; + draw_viewports_stale_ = true; } // D3D12 reads render-target and depth descriptors here, so their views are copied now. @@ -486,10 +503,11 @@ class GraphicsCommandList final d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); if (!graphics_pipeline_ || !graphics_.layout) return check(false); - if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized + if (!any_nonempty_viewport()) return; // as record_draw: nothing is rasterized leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; draw.mesh = true; + draw.viewports = draw_viewports(); check(list_.draw(std::move(draw))); } @@ -1266,6 +1284,12 @@ class GraphicsCommandList final leonida::IndexBufferView index_{}; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; + std::array viewports_{}; + UINT viewport_count_ = 0; + std::array scissors_{}; + UINT scissor_count_ = 0; + std::shared_ptr draw_viewports_; + bool draw_viewports_stale_ = true; std::array render_targets_{}; UINT render_target_count_ = 0; // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a @@ -1368,6 +1392,12 @@ class GraphicsCommandList final index_ = {}; viewport_ = {}; scissor_ = {}; + viewports_.fill({}); + viewport_count_ = 0; + scissors_.fill({}); + scissor_count_ = 0; + draw_viewports_.reset(); + draw_viewports_stale_ = true; render_targets_.fill({}); render_target_count_ = 0; draw_views_stale_ = true; @@ -1408,16 +1438,37 @@ class GraphicsCommandList final return draw_views_; } + bool any_nonempty_viewport() const { + for (UINT i = 0; i < viewport_count_; ++i) + if (viewports_[i].width > 0.0f && viewports_[i].height > 0.0f) return true; + return false; + } + + std::shared_ptr draw_viewports() { + if (viewport_count_ <= 1 && scissor_count_ <= 1) return nullptr; + if (draw_viewports_stale_) { + auto block = std::make_shared(); + block->viewports = viewports_; + block->viewport_count = viewport_count_; + block->scissors = scissors_; + block->scissor_count = scissor_count_; + draw_viewports_ = std::move(block); + draw_viewports_stale_ = false; + } + return draw_viewports_; + } + // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); note_direct_heap_indexing(graphics_.layout); - // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, - // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. - if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; + // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes + // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. + if (!any_nonempty_viewport()) return; leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, base_vertex, first_instance}; + draw.viewports = draw_viewports(); check(list_.draw(std::move(draw))); } }; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..e4238e8b17 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3850,6 +3850,9 @@ class PipelineState final if (raster.depthClampEnable && !features.depthClamp) return refuse("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); + graphics_.viewport_with_count = + features.multiViewport && vk.vkCmdSetViewportWithCount && vk.vkCmdSetScissorWithCount; + graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; @@ -4103,14 +4106,6 @@ class PipelineState final // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. VkPipeline build(std::uint32_t unbound) const { - // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices - // from SV_VertexID) leaves it out, since no vkCmdBindVertexBuffers2 would ever set it - // (VUID-vkCmdDraw-pStrides-04913). - static constexpr VkDynamicState dynamic_states[] = { - VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, - VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS, - VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE}; const Recipe& r = recipe_; std::vector colors = graphics_.color_formats; for (std::size_t slot = 0; slot < colors.size(); ++slot) @@ -4137,8 +4132,10 @@ class PipelineState final vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size()); vertex_input.pVertexAttributeDescriptions = r.attributes.data(); VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewport.viewportCount = 1; - viewport.scissorCount = 1; + if (!graphics_.viewport_with_count) { + viewport.viewportCount = 1; + viewport.scissorCount = 1; + } VkPipelineMultisampleStateCreateInfo multisample = r.multisample; VkPipelineRasterizationStateCreateInfo raster = r.raster; VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{ @@ -4155,17 +4152,23 @@ class PipelineState final blend.pAttachments = r.blends.data(); // A mesh pipeline takes neither the topology nor the strides as dynamic state // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). - static constexpr VkDynamicState mesh_dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_STENCIL_REFERENCE, - VK_DYNAMIC_STATE_BLEND_CONSTANTS}; + // With multiViewport enabled, VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT allow 1..16 dynamic viewports/scissors. + VkDynamicState dyn_list[8]{}; + std::uint32_t dyn_count = 0; + dyn_list[dyn_count++] = + graphics_.viewport_with_count ? VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT : VK_DYNAMIC_STATE_VIEWPORT; + dyn_list[dyn_count++] = + graphics_.viewport_with_count ? VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT : VK_DYNAMIC_STATE_SCISSOR; + if (!r.mesh) { + dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY; + dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE; + } + dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; + dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; + if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - if (r.mesh) { - dynamic.dynamicStateCount = std::uint32_t(std::size(mesh_dynamic_states)); - dynamic.pDynamicStates = mesh_dynamic_states; - } else { - dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0); - dynamic.pDynamicStates = dynamic_states; - } + dynamic.dynamicStateCount = dyn_count; + dynamic.pDynamicStates = dyn_list; VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; info.stageCount = std::uint32_t(r.stages.size()); @@ -9796,6 +9799,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.dualSrcBlend = chosen_features.dualSrcBlend; enable.logicOp = chosen_features.logicOp; enable.depthClamp = chosen_features.depthClamp; + enable.multiViewport = chosen_features.multiViewport; enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0ac..a7578b8ff8 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -414,6 +414,15 @@ struct DrawViews { std::uint32_t render_target_count = 8; }; +// Shared across draws that keep the same multi-viewport / multi-scissor state (null for the common 1-viewport case). +struct DrawViewports { + static constexpr std::uint32_t max_count = 16; + std::array viewports{}; + std::uint32_t viewport_count = 0; + std::array scissors{}; + std::uint32_t scissor_count = 0; +}; + // DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: // D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the // list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw @@ -440,6 +449,7 @@ struct Draw { std::int32_t base_vertex = 0; std::uint32_t first_instance = 0; bool mesh = false; + std::shared_ptr viewports; // non-null when >1 viewport or >1 scissor was bound }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..a82d2b1014 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -101,6 +101,7 @@ struct VulkanDeviceFunctions { X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ X(vkCmdPushConstants) X(vkCmdDispatch) \ X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ + X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ @@ -970,6 +971,8 @@ class VulkanContext { replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; replay_.set_viewport = vk.vkCmdSetViewport; replay_.set_scissor = vk.vkCmdSetScissor; + replay_.set_viewport_with_count = vk.vkCmdSetViewportWithCount; + replay_.set_scissor_with_count = vk.vkCmdSetScissorWithCount; replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; replay_.set_stencil_reference = vk.vkCmdSetStencilReference; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..469528f6ae 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -769,6 +769,7 @@ struct GraphicsPipeline { std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only + bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots // 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. @@ -850,6 +851,8 @@ struct ReplayFunctions { PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; PFN_vkCmdSetViewport set_viewport = nullptr; PFN_vkCmdSetScissor set_scissor = nullptr; + PFN_vkCmdSetViewportWithCount set_viewport_with_count = nullptr; + PFN_vkCmdSetScissorWithCount set_scissor_with_count = nullptr; PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; @@ -2103,6 +2106,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; + if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) + return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; p.graphics = pipeline; @@ -2151,9 +2156,17 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct if (!a.view) return ReplayResult::unsupported; shrink(a.binding, draw.depth, a.range); } - if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering - p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), - std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; + if (p.area.width == UINT32_MAX) { // no attachment: the viewports bound the rendering + std::uint32_t max_w = std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)); + std::uint32_t max_h = std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height)); + if (draw.viewports) { + for (std::uint32_t i = 0; i < draw.viewports->viewport_count; ++i) { + const Viewport& v = draw.viewports->viewports[i]; + max_w = std::max(max_w, std::uint32_t(std::max(0.0f, v.x + v.width))); + max_h = std::max(max_h, std::uint32_t(std::max(0.0f, v.y + v.height))); + } + } + p.area = {max_w, max_h}; } p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); @@ -4179,14 +4192,46 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the // image upright, and winding as D3D12 sees it. - const Viewport& v = draw->viewport; - const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; - vk.set_viewport(command_buffer, 0, 1, &viewport); - const Rect& s = draw->scissor; - const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, - {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), - std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; - vk.set_scissor(command_buffer, 0, 1, &scissor); + if (graphics.viewport_with_count) { + std::array vps{}; + std::array scs{}; + const std::uint32_t vp_n = draw->viewports ? draw->viewports->viewport_count : 1u; + const std::uint32_t sc_n = draw->viewports ? draw->viewports->scissor_count : 1u; + const std::uint32_t count = std::clamp(std::max(vp_n, sc_n), 1u, DrawViewports::max_count); + for (std::uint32_t k = 0; k < count; ++k) { + const Viewport v = (draw->viewports && k < vp_n) ? draw->viewports->viewports[k] + : (k == 0 ? draw->viewport : Viewport{}); + const bool valid_vp = (k < vp_n) && (v.width > 0.0f) && (v.height > 0.0f); + if (valid_vp) { + vps[k] = {v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; + } else { + // Vulkan forbids width/height == 0; pair a 1x1 dummy viewport with an empty scissor so nothing + // rasterizes into an unbound/empty D3D12 viewport slot. + vps[k] = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; + } + if (valid_vp && k < sc_n) { + const Rect s = draw->viewports ? draw->viewports->scissors[k] : draw->scissor; + const std::int32_t left = std::max(0, s.left); + const std::int32_t top = std::max(0, s.top); + scs[k] = {{left, top}, + {std::uint32_t(std::max(0, s.right - left)), + std::uint32_t(std::max(0, s.bottom - top))}}; + } else { + scs[k] = {{0, 0}, {0, 0}}; + } + } + vk.set_viewport_with_count(command_buffer, count, vps.data()); + vk.set_scissor_with_count(command_buffer, count, scs.data()); + } else { + const Viewport& v = draw->viewport; + const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; + vk.set_viewport(command_buffer, 0, 1, &viewport); + const Rect& s = draw->scissor; + const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, + {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), + std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; + vk.set_scissor(command_buffer, 0, 1, &scissor); + } // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { diff --git a/runtime/test/d3d12_multi_viewport_test.cpp b/runtime/test/d3d12_multi_viewport_test.cpp new file mode 100644 index 0000000000..a05b713afd --- /dev/null +++ b/runtime/test/d3d12_multi_viewport_test.cpp @@ -0,0 +1,484 @@ +// Live GPU host-parity test for multi-viewport and multi-scissor rendering (D3D-MULTI-VIEWPORT): +// - RSSetViewports(1..16) and RSSetScissorRects(1..16) -> vkCmdSetViewportWithCount / vkCmdSetScissorWithCount +// - Single DrawInstanced routing 4 fullscreen quads via SV_ViewportArrayIndex to 4 quadrants (TL/TR/BL/BR) +// - Independent per-viewport scissor clipping (each quadrant half-clipped by its own scissor rect) +// - Mismatched counts (4 viewports, 2 scissors -> slots 2 and 3 clipped as on D3D12) +// - Empty viewport 0 with active viewports 1..3 (draw still rasterizes slots 1..3) +// Compares all 64/64 pixels of the 8x8 RGBA8_UNORM render target byte-for-byte against the host Windows D3D12 +// runtime on the same adapter (matched by LUID). Self-contained: builds minimal SPIR-V 1.5 shaders in memory. +#include "vk_test_device.h" +#include "host_wine.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using d3d12test::Ref; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + return 1; \ + } \ + } while (0) + +struct Vertex { + float x, y; + float r, g, b, a; + std::uint32_t vp; +}; + +void emit_op(std::vector& out, std::uint16_t opcode, std::initializer_list ops) { + out.push_back((std::uint32_t(ops.size() + 1) << 16) | opcode); + out.insert(out.end(), ops.begin(), ops.end()); +} + +// Minimal valid SPIR-V 1.5 vertex shader: reads vec2 POSITION (loc 0), vec4 COLOR (loc 1), uint TEXCOORD0 (loc 2), +// writes gl_Position and gl_ViewportIndex (BuiltIn 4440), and passes COLOR to fragment loc 0. +std::vector make_multi_vp_vs_spv() { + std::vector w = {0x07230203u, 0x00010500u, 0u, 38u, 0u}; + emit_op(w, 17, {1}); // OpCapability Shader + emit_op(w, 17, {57}); // OpCapability MultiViewport + emit_op(w, 17, {70}); // OpCapability ShaderViewportIndex + emit_op(w, 14, {0, 1}); // OpMemoryModel Logical GLSL450 + // Entry point: Vertex %main(4) "main" %per_vertex(10) %out_col(11) %in_pos(12) %in_col(13) %in_vp(14). + emit_op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11, 12, 13, 14}); + // Decorations. + emit_op(w, 71, {20, 2}); // OpDecorate %20 Block + emit_op(w, 72, {20, 0, 11, 0}); // OpMemberDecorate %20 0 BuiltIn Position + emit_op(w, 72, {20, 1, 11, 10}); // OpMemberDecorate %20 1 BuiltIn ViewportIndex + emit_op(w, 71, {11, 30, 0}); // OpDecorate %out_col Location 0 + emit_op(w, 71, {12, 30, 0}); // OpDecorate %in_pos Location 0 + emit_op(w, 71, {13, 30, 1}); // OpDecorate %in_col Location 1 + emit_op(w, 71, {14, 30, 2}); // OpDecorate %in_vp Location 2 + // Types & variables. + emit_op(w, 19, {1}); // %1 = OpTypeVoid + emit_op(w, 33, {2, 1}); // %2 = OpTypeFunction %1 + emit_op(w, 22, {3, 32}); // %3 = OpTypeFloat 32 + emit_op(w, 23, {5, 3, 2}); // %5 = OpTypeVector %3 2 + emit_op(w, 23, {6, 3, 4}); // %6 = OpTypeVector %3 4 + emit_op(w, 21, {15, 32, 1}); // %15 = OpTypeInt 32 1 (signed int) + emit_op(w, 21, {16, 32, 0}); // %16 = OpTypeInt 32 0 (uint) + emit_op(w, 30, {20, 6, 15}); // %20 = OpTypeStruct %vec4 %int + emit_op(w, 32, {21, 3, 20}); // %21 = OpTypePointer Output %20 + emit_op(w, 32, {7, 3, 6}); // %7 = OpTypePointer Output %vec4 + emit_op(w, 32, {22, 3, 15}); // %22 = OpTypePointer Output %int + emit_op(w, 32, {8, 1, 5}); // %8 = OpTypePointer Input %vec2 + emit_op(w, 32, {9, 1, 6}); // %9 = OpTypePointer Input %vec4 + emit_op(w, 32, {23, 1, 16}); // %23 = OpTypePointer Input %uint + emit_op(w, 59, {21, 10, 3}); // %10 = OpVariable %21 Output (PerVertex) + emit_op(w, 59, {7, 11, 3}); // %11 = OpVariable %7 Output (out_col) + emit_op(w, 59, {8, 12, 1}); // %12 = OpVariable %8 Input (in_pos) + emit_op(w, 59, {9, 13, 1}); // %13 = OpVariable %9 Input (in_col) + emit_op(w, 59, {23, 14, 1}); // %14 = OpVariable %23 Input (in_vp) + emit_op(w, 43, {15, 24, 0}); // %24 = OpConstant %int 0 + emit_op(w, 43, {15, 25, 1}); // %25 = OpConstant %int 1 + emit_op(w, 43, {3, 26, std::bit_cast(0.0f)}); + emit_op(w, 43, {3, 27, std::bit_cast(1.0f)}); + // Function %main(4). + emit_op(w, 54, {1, 4, 0, 2}); + emit_op(w, 248, {28}); // OpLabel + emit_op(w, 61, {5, 29, 12}); // %29 = OpLoad pos2 + emit_op(w, 81, {3, 30, 29, 0}); // %30 = x + emit_op(w, 81, {3, 31, 29, 1}); // %31 = y + emit_op(w, 80, {6, 32, 30, 31, 26, 27}); // %32 = vec4(x, y, 0.0, 1.0) + emit_op(w, 65, {7, 33, 10, 24}); // %33 = &PerVertex.Position + emit_op(w, 62, {33, 32}); // store Position + emit_op(w, 61, {16, 34, 14}); // %34 = OpLoad uint in_vp + emit_op(w, 124, {15, 35, 34}); // %35 = OpBitcast %int %34 + emit_op(w, 65, {22, 36, 10, 25}); // %36 = &PerVertex.ViewportIndex + emit_op(w, 62, {36, 35}); // store ViewportIndex + emit_op(w, 61, {6, 37, 13}); // %37 = OpLoad col + emit_op(w, 62, {11, 37}); // store out_col + emit_op(w, 253, {}); + emit_op(w, 56, {}); + return w; +} + +std::vector make_col_ps_spv() { + std::vector w = {0x07230203u, 0x00010500u, 0u, 16u, 0u}; + emit_op(w, 17, {1}); // OpCapability Shader + emit_op(w, 14, {0, 1}); // OpMemoryModel Logical GLSL450 + emit_op(w, 15, {4, 4, 0x6e69616du, 0u, 8, 9}); + emit_op(w, 16, {4, 7}); // OriginUpperLeft + emit_op(w, 71, {8, 30, 0}); // Location 0 + emit_op(w, 71, {9, 30, 0}); // Location 0 + emit_op(w, 19, {1}); + emit_op(w, 33, {2, 1}); + emit_op(w, 22, {3, 32}); + emit_op(w, 23, {5, 3, 4}); + emit_op(w, 32, {6, 1, 5}); + emit_op(w, 32, {7, 3, 5}); + emit_op(w, 59, {6, 8, 1}); + emit_op(w, 59, {7, 9, 3}); + emit_op(w, 54, {1, 4, 0, 2}); + emit_op(w, 248, {10}); + emit_op(w, 61, {5, 11, 8}); + emit_op(w, 62, {9, 11}); + emit_op(w, 253, {}); + emit_op(w, 56, {}); + return w; +} + +bool write_spv(const std::filesystem::path& path, const std::vector& words) { + std::ofstream f(path, std::ios::binary | std::ios::trunc); + if (!f) return false; + f.write(reinterpret_cast(words.data()), static_cast(words.size() * 4)); + return bool(f); +} + +constexpr char kHostVs[] = + "struct VsIn { float2 pos : POSITION; float4 col : COLOR; uint vp : TEXCOORD0; };\n" + "struct VsOut { float4 pos : SV_Position; float4 col : COLOR; uint vp : SV_ViewportArrayIndex; };\n" + "VsOut main(VsIn i) { VsOut o; o.pos = float4(i.pos, 0.0, 1.0); o.col = i.col; o.vp = i.vp; return o; }\n"; +constexpr char kHostPs[] = "float4 main(float4 pos : SV_Position, float4 col : COLOR) : SV_Target { return col; }\n"; + +bool compile_hlsl(pD3DCompile compile, const char* source, std::vector& out, bool vertex) { + ID3DBlob* code = nullptr; + ID3DBlob* errors = nullptr; + const HRESULT hr = compile(source, std::strlen(source), nullptr, nullptr, nullptr, "main", vertex ? "vs_5_0" : "ps_5_0", + 0, 0, &code, &errors); + if (errors) { + std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + errors->Release(); + } + if (FAILED(hr) || !code) return false; + const auto* bytes = static_cast(code->GetBufferPointer()); + out.assign(bytes, bytes + code->GetBufferSize()); + code->Release(); + return true; +} + +bool host_device_for_vk(const vktest::Device& vk, Ref& out, std::string& name) { + VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; + VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; + vk.instance_fn("vkGetPhysicalDeviceProperties2")(vk.physical, &props); + Ref factory; + if (!id.deviceLUIDValid || FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return false; + LUID luid{}; + std::memcpy(&luid, id.deviceLUID, sizeof(luid)); + Ref adapter; + if (FAILED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter.p)))) return false; + DXGI_ADAPTER_DESC1 desc{}; + adapter->GetDesc1(&desc); + char utf8[256]{}; + WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, utf8, sizeof(utf8), nullptr, nullptr); + name = utf8; + return SUCCEEDED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&out.p))); +} + +struct Programs { + std::vector root, vs, ps; +}; + +struct ViewportCase { + const char* name; + std::vector viewports; + std::vector scissors; +}; + +// 4 fullscreen quads routed to viewports 0, 1, 2, 3 with distinct solid colors: +// vp 0 = Red, vp 1 = Green, vp 2 = Blue, vp 3 = Yellow. +std::vector make_quads() { + const float cols[4][4] = { + {1.0f, 0.0f, 0.0f, 1.0f}, // vp 0: red + {0.0f, 1.0f, 0.0f, 1.0f}, // vp 1: green + {0.0f, 0.0f, 1.0f, 1.0f}, // vp 2: blue + {1.0f, 1.0f, 0.0f, 1.0f}, // vp 3: yellow + }; + const float xy[6][2] = {{-1, -1}, {1, -1}, {1, 1}, {-1, -1}, {1, 1}, {-1, 1}}; + std::vector out; + for (std::uint32_t vp = 0; vp < 4; ++vp) { + for (int i = 0; i < 6; ++i) + out.push_back({xy[i][0], xy[i][1], cols[vp][0], cols[vp][1], cols[vp][2], cols[vp][3], vp}); + } + return out; +} + +bool run_case(ID3D12Device* dev, const Programs& p, const ViewportCase& c, std::vector& pixels_out) { + Ref root; + if (FAILED(dev->CreateRootSignature(0, p.root.data(), p.root.size(), IID_PPV_ARGS(&root.p)))) return false; + + const D3D12_INPUT_ELEMENT_DESC layout[3] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32_UINT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + }; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + pd.VS = {p.vs.data(), p.vs.size()}; + pd.PS = {p.ps.data(), p.ps.size()}; + for (auto& rt : pd.BlendState.RenderTarget) { + rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + } + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.DepthStencilState.DepthEnable = FALSE; + pd.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pd.InputLayout = {layout, 3}; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc = {1, 0}; + + Ref pso; + if (FAILED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p)))) return false; + + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES up_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; + + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = 8; + td.DepthOrArraySize = td.MipLevels = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc = {1, 0}; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref target; + if (FAILED(dev->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, + nullptr, IID_PPV_ARGS(&target.p)))) + return false; + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, &rows, &row_bytes, &total); + Ref readback; + const auto rb_desc = d3d12test::buffer_desc(total); + if (FAILED(dev->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)))) + return false; + + const auto verts = make_quads(); + const auto vb_desc = d3d12test::buffer_desc(verts.size() * sizeof(Vertex)); + Ref vb_up, vb_def; + if (FAILED(dev->CreateCommittedResource(&up_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&vb_up.p))) || + FAILED(dev->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&vb_def.p)))) + return false; + { + void* mapped = nullptr; + const D3D12_RANGE empty{0, 0}; + if (FAILED(vb_up->Map(0, &empty, &mapped)) || !mapped) return false; + std::memcpy(mapped, verts.data(), verts.size() * sizeof(Vertex)); + vb_up->Unmap(0, nullptr); + } + + Ref rtv_heap; + const D3D12_DESCRIPTOR_HEAP_DESC rh{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + if (FAILED(dev->CreateDescriptorHeap(&rh, IID_PPV_ARGS(&rtv_heap.p)))) return false; + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(target.p, nullptr, rtv); + + Ref queue; + Ref alloc; + Ref list; + Ref fence; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))) || + FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))) || + FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, pso.p, IID_PPV_ARGS(&list.p))) || + FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) + return false; + + list->CopyResource(vb_def.p, vb_up.p); + const auto vb_ready = + d3d12test::transition(vb_def.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + list->ResourceBarrier(1, &vb_ready); + + const FLOAT clear_gray[4] = {0.25f, 0.25f, 0.25f, 1.0f}; + list->ClearRenderTargetView(rtv, clear_gray, 0, nullptr); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->RSSetViewports(UINT(c.viewports.size()), c.viewports.empty() ? nullptr : c.viewports.data()); + list->RSSetScissorRects(UINT(c.scissors.size()), c.scissors.empty() ? nullptr : c.scissors.data()); + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VERTEX_BUFFER_VIEW vbv{vb_def->GetGPUVirtualAddress(), UINT(verts.size() * sizeof(Vertex)), + sizeof(Vertex)}; + list->IASetVertexBuffers(0, 1, &vbv); + list->DrawInstanced(UINT(verts.size()), 1, 0, 0); + + const auto to_src = d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_src); + D3D12_TEXTURE_COPY_LOCATION src_loc{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src_loc.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION dst_loc{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst_loc.PlacedFootprint = foot; + list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr); + if (FAILED(list->Close())) return false; + + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr))) return false; + + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(total)}; + if (FAILED(readback->Map(0, &range, &mapped)) || !mapped) return false; + pixels_out.resize(8 * 8 * 4); + for (UINT y = 0; y < 8; ++y) { + std::memcpy(pixels_out.data() + y * 32, + static_cast(mapped) + foot.Offset + y * foot.Footprint.RowPitch, 32); + } + const D3D12_RANGE empty{0, 0}; + readback->Unmap(0, &empty); + return true; +} + +} // namespace + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.enabled.multiViewport || !vk.shader_output_viewport_index) { + std::printf("GPU lacks multiViewport or shaderOutputViewportIndex; skipping\n"); + return 77; + } + + const auto vs_program = d3d12test::fssm_program({0x56534d56u, 0xbf810000u}); + const auto ps_program = d3d12test::fssm_program({0x50534d56u, 0xbf810000u}); + const auto library = std::filesystem::temp_directory_path() / + ("leonida_multi_viewport_test_" + std::to_string(GetCurrentProcessId())); + std::filesystem::create_directories(library); + CHECK(write_spv(library / "vs.spv", make_multi_vp_vs_spv())); + CHECK(write_spv(library / "ps.spv", make_col_ps_spv())); + { + std::ofstream index(library / "index.json", std::ios::binary | std::ios::trunc); + index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" + "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 0, \"system_value\": 0}," + "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 1, \"system_value\": 0}," + "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 0, \"register\": 2, \"system_value\": 0}]}," + " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [0], \"outputs\": [0]}}"; + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.host_image_copy = vk.host_image_copy; + info.buffer_device_address = vk.buffer_device_address; + info.features = vk.enabled; + info.shader_output_viewport_index = vk.shader_output_viewport_index; + info.shader_dir = library.string(); + + Ref ours; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + Programs our_programs; + our_programs.root = d3d12test::serialize_root_signature(root_desc); + CHECK(!our_programs.root.empty()); + our_programs.vs = d3d12test::shader_container(vs_program); + our_programs.ps = d3d12test::shader_container(ps_program); + + Ref host; + std::string adapter; + Programs host_programs; + bool have_host = false; + if (!hostwine::host_is_wine() && host_device_for_vk(vk, host, adapter)) { + D3D12_FEATURE_DATA_D3D12_OPTIONS host_o{}; + if (SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &host_o, sizeof(host_o))) && + host_o.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation) { + const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto compile = compiler ? reinterpret_cast(reinterpret_cast( + GetProcAddress(compiler, "D3DCompile"))) + : nullptr; + host_programs.root = our_programs.root; + if (compile && compile_hlsl(compile, kHostVs, host_programs.vs, true) && + compile_hlsl(compile, kHostPs, host_programs.ps, false)) { + have_host = true; + std::printf("host reference: %s\n", adapter.c_str()); + } + } + } + + const D3D12_VIEWPORT q0{0, 0, 4, 4, 0, 1}; + const D3D12_VIEWPORT q1{4, 0, 4, 4, 0, 1}; + const D3D12_VIEWPORT q2{0, 4, 4, 4, 0, 1}; + const D3D12_VIEWPORT q3{4, 4, 4, 4, 0, 1}; + const D3D12_VIEWPORT empty_vp{0, 0, 0, 0, 0, 1}; + const D3D12_RECT full{0, 0, 8, 8}; + + const ViewportCase cases[] = { + {"4 quadrant viewports + 4 full scissors", {q0, q1, q2, q3}, {full, full, full, full}}, + {"4 viewports + 4 independent half-clipping scissors", + {q0, q1, q2, q3}, + {{0, 0, 2, 4}, {6, 0, 8, 4}, {0, 4, 4, 6}, {4, 6, 8, 8}}}, + {"4 viewports + 2 scissors (slots 2,3 clipped)", {q0, q1, q2, q3}, {full, full}}, + {"empty vp0 + active vp1..3", {empty_vp, q1, q2, q3}, {full, full, full, full}}, + }; + + auto px_at = [](const std::vector& buf, int x, int y) { + return buf.data() + (y * 8 + x) * 4; + }; + + for (std::size_t ci = 0; ci < std::size(cases); ++ci) { + const auto& c = cases[ci]; + std::vector ours_px; + CHECK(run_case(ours.p, our_programs, c, ours_px)); + const auto* tl = px_at(ours_px, 1, 1); + const auto* tr = px_at(ours_px, 6, 1); + const auto* bl = px_at(ours_px, 1, 6); + const auto* br = px_at(ours_px, 6, 6); + std::printf(" %-52s TL=(%3u,%3u,%3u) TR=(%3u,%3u,%3u) BL=(%3u,%3u,%3u) BR=(%3u,%3u,%3u)", c.name, tl[0], + tl[1], tl[2], tr[0], tr[1], tr[2], bl[0], bl[1], bl[2], br[0], br[1], br[2]); + if (ci == 0) { + CHECK(tl[0] == 255 && tl[1] == 0 && tl[2] == 0); + CHECK(tr[0] == 0 && tr[1] == 255 && tr[2] == 0); + CHECK(bl[0] == 0 && bl[1] == 0 && bl[2] == 255); + CHECK(br[0] == 255 && br[1] == 255 && br[2] == 0); + } else if (ci == 2) { + CHECK(tl[0] == 255 && tr[1] == 255 && bl[0] == 64 && br[0] == 64); + } else if (ci == 3) { + CHECK(tl[0] == 64 && tr[1] == 255 && bl[2] == 255 && br[0] == 255 && br[1] == 255); + } + if (have_host) { + std::vector host_px; + CHECK(run_case(host.p, host_programs, c, host_px)); + CHECK(ours_px == host_px); + std::printf(" [64/64 px EXACT vs host]"); + } + std::printf(" OK\n"); + } + + std::filesystem::remove_all(library); + CHECK(vk.validation_errors() == 0); + std::printf("d3d12_multi_viewport_test: ALL %zu CASES PASSED%s\n", std::size(cases), + have_host ? " (EXACT MATCH vs host D3D12)" : ""); + return 0; +} diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index a3957d1669..0da65357bb 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -226,6 +226,8 @@ struct Scene { vk.bind_index_buffer = nop(); vk.set_viewport = nop(); vk.set_scissor = nop(); + vk.set_viewport_with_count = nop(); + vk.set_scissor_with_count = nop(); vk.set_primitive_topology = nop(); vk.set_primitive_restart_enable = nop(); vk.set_stencil_reference = nop(); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 5cccd1836e..4b9200ed2e 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -123,6 +123,7 @@ class Device { leonida::SubgroupSizeCaps subgroup; bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled bool custom_border_color_without_format = false; + bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. VkDeviceSize host_pointer_alignment = 0; @@ -398,6 +399,8 @@ class Device { enable12.descriptorBindingPartiallyBound = partially_bound; sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE; enable12.samplerFilterMinmax = sampler_filter_minmax; + shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE; + enable12.shaderOutputViewportIndex = shader_output_viewport_index; enable12.bufferDeviceAddress = VK_TRUE; const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count)); @@ -433,6 +436,7 @@ class Device { enable.shaderSampledImageArrayDynamicIndexing = bindless; enable.shaderStorageImageArrayDynamicIndexing = bindless; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available + enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME;