From 483f0128ebf9c50dedcda5f2caf5a65b60c6f843 Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 23:10:53 -0300 Subject: [PATCH 1/2] runtime/d3d12: synthesize --bary-fallback geometry shader in graphics PSOs When a translated pixel shader carries `"bary_fallback_input": {"location": N}` in `spirv/index.json` (`rdna2spirv.py --bary-fallback` for GPUs without `VK_KHR_fragment_shader_barycentric`), `PipelineState::create_graphics` now synthesizes the triangle pass-through Geometry SPIR-V 1.5 module in memory (`leonida::build_bary_fallback_gs` in `runtime/src/spirv_bary_fallback.h`) after `--f16-interp-fallback` VS/PS location linking: - Parses `bary_fallback_input.location` in `ShaderLibrary::load_index` into `ShaderEntry::bary_fallback_location`. - Copies `BuiltIn Position` and every `vec4` `Location` input read by the PS (other than `bary_location`) that the VS exports, while zero-filling any unexported PS `Location` input without declaring a dangling GS `Input` and leaving unread VS outputs unconsumed (`VUID-RuntimeSpirv-OpEntryPoint-08743`). - Forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array (checking `shaderClipDistance` / `shaderCullDistance`), and emits `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` across the 3 strip vertices so perspective interpolation matches `BaryCoordKHR`. - Supports both eager and lazy graphics pipeline builds (`StageSource::bary_fallback` in `stage_words`), clamps `--f16-interp-fallback` `top_location` against `maxGeometryInputComponents` / `maxGeometryOutputComponents`, and refuses mesh PSOs, explicit GS or rectangle-list stages, missing `geometryShader`, or non-triangle topologies with clear HRESULTs (`E_NOTIMPL` / `E_INVALIDARG`). - Adds `spirv_bary_fallback` (portable CPU test) and `d3d12_bary_fallback` (end-to-end Vulkan GPU D3D12 PSO test). Claim: RT-BARY-FALLBACK-PSO AI-assisted: yes (Antigravity) --- runtime/CMakeLists.txt | 10 + runtime/shims/d3d12_vulkan_device.cpp | 96 ++- runtime/src/shader_library.h | 10 + runtime/src/spirv_bary_fallback.h | 428 ++++++++++++++ runtime/test/d3d12_bary_fallback_test.cpp | 678 ++++++++++++++++++++++ runtime/test/shader_library_test.cpp | 34 ++ runtime/test/spirv_bary_fallback_test.cpp | 495 ++++++++++++++++ runtime/test/vk_test_device.h | 2 + 8 files changed, 1746 insertions(+), 7 deletions(-) create mode 100644 runtime/src/spirv_bary_fallback.h create mode 100644 runtime/test/d3d12_bary_fallback_test.cpp create mode 100644 runtime/test/spirv_bary_fallback_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 86378dfc86..5720712683 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1403,6 +1403,8 @@ if(BUILD_TESTING) add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) add_executable(dual_source_fragment_test test/dual_source_fragment_test.cpp) add_test(NAME dual_source_fragment COMMAND dual_source_fragment_test) + add_executable(spirv_bary_fallback_test test/spirv_bary_fallback_test.cpp) + add_test(NAME spirv_bary_fallback COMMAND spirv_bary_fallback_test) # Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) @@ -3124,6 +3126,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test) set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77) + # Per-pipeline --bary-fallback GS synthesis (RT-BARY-FALLBACK-PSO): perspective barycentrics + ClipDistance + f16 halves. + add_executable(d3d12_bary_fallback_test test/d3d12_bary_fallback_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_bary_fallback_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_bary_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_bary_fallback_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_bary_fallback COMMAND d3d12_bary_fallback_test) + set_tests_properties(d3d12_bary_fallback PROPERTIES SKIP_RETURN_CODE 77) + # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. add_executable(xbox_present_test test/xbox_present_test.cpp) target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index aeecf05b0d..80d04f15a7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -58,6 +58,7 @@ #include "../src/title_texture_refresh.h" #include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" +#include "../src/spirv_bary_fallback.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" #include "../src/title_window_plan.h" @@ -2026,6 +2027,7 @@ struct DeviceState { // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t f16_half_top_location = 29; + std::uint32_t bary_f16_half_top_location = 29; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; @@ -8467,19 +8469,48 @@ class PipelineState final Stage& vs_stage = stages[0]; Stage& gs_stage = stages[1]; Stage& ps_stage = stages[2]; + const bool bary_fallback = ps_stage.entry && ps_stage.entry->bary_fallback_location.has_value(); + if (bary_fallback) { + const int bary_loc = int(*ps_stage.entry->bary_fallback_location); + if (mesh) { + return stream_unsupported( + "--bary-fallback pixel shader needs a geometry stage, which a mesh PSO cannot include; location", + bary_loc); + } + if (gs_stage.entry) { + return stream_unsupported( + "--bary-fallback pixel shader cannot pair with an explicit geometry shader; location", bary_loc); + } + if (rect_list) { + return stream_unsupported( + "--bary-fallback pixel shader cannot pair with a rectangle-list geometry stage; location", + bary_loc); + } + if (!device_.info.features.geometryShader) { + return stream_unsupported( + "--bary-fallback pixel shaders need the Vulkan geometryShader feature; location", bary_loc); + } + if (desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a --bary-fallback geometry stage takes triangles; topology type", desc.PrimitiveTopologyType); + return E_INVALIDARG; + } + } if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; + const std::uint32_t top_loc = + bary_fallback ? device_.bary_f16_half_top_location : device_.f16_half_top_location; if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, - &link_error, device_.f16_half_top_location)) { + &link_error, top_loc)) { std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } f16_linked_ = true; } + bary_fallback_ = bary_fallback; // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them // again, the same way, and drops them once the pipeline exists. lazy_ = lazy_graphics_pipelines(); @@ -8534,8 +8565,8 @@ class PipelineState final module = shader_module(stage.words); if (!module) return E_FAIL; } - if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && - topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && !bary_fallback && + device_.info.features.geometryShader && topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { rectangle_capable_ = true; if (!lazy_) rectangle_vertex_ = modules_.back(); } @@ -8568,6 +8599,40 @@ class PipelineState final info.pName = "main"; stage_infos.push_back(info); } + if (bary_fallback) { // the stage that supplies (1,0,0)/(0,1,0)/(0,0,1) at bary_fallback_input.location + std::vector words; + leonida::BaryFallbackGsInfo bary_info{}; + std::string bary_error; + if (!leonida::build_bary_fallback_gs(vs_stage.words, ps_stage.words, + *ps_stage.entry->bary_fallback_location, words, &bary_info, + &bary_error)) { + std::fprintf(stderr, "[rt] d3d12: %s\n", bary_error.c_str()); + return E_FAIL; + } + if (bary_info.clip_count && !device_.info.features.shaderClipDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards ClipDistance, which needs shaderClipDistance; count", + int(bary_info.clip_count)); + } + if (bary_info.cull_count && !device_.info.features.shaderCullDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards CullDistance, which needs shaderCullDistance; count", + int(bary_info.cull_count)); + } + if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); + VkShaderModule module = VK_NULL_HANDLE; + if (lazy_) { + sources_.push_back({StageSource::bary_fallback}); + } else { + module = shader_module(words); + if (!module) return E_FAIL; + } + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); if (words.empty()) return E_FAIL; @@ -9511,8 +9576,11 @@ class PipelineState final if (source.slot == 2) ps = i; } if (f16_linked_) { + const std::uint32_t top_loc = + bary_fallback_ ? device_.bary_f16_half_top_location : device_.f16_half_top_location; if (vs == SIZE_MAX || ps == SIZE_MAX || - !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) + !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why, + top_loc)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -9525,6 +9593,12 @@ class PipelineState final if (sources_[i].kind == StageSource::rect_list) { if (vs == SIZE_MAX) return false; words[i] = leonida::rect_list_geometry(words[vs], why); + } else if (sources_[i].kind == StageSource::bary_fallback) { + if (vs == SIZE_MAX || ps == SIZE_MAX || !sources_[ps].entry->bary_fallback_location || + !leonida::build_bary_fallback_gs(words[vs], words[ps], + *sources_[ps].entry->bary_fallback_location, words[i], nullptr, + &why)) + return false; } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { @@ -9552,7 +9626,7 @@ class PipelineState final // Where a lazy graphics pipeline's stage modules come from, in recipe_.stages order (stage_words). struct StageSource { - enum Kind : std::uint8_t { library, rect_list, depth_only } kind = library; + enum Kind : std::uint8_t { library, rect_list, bary_fallback, depth_only } kind = library; std::uint8_t slot = 0; // library: the create_graphics stage table entry (0 VS or MS, 1 GS, 2 PS) bool depth24 = false; // library: the D24 fragment patch applies const leonida::ShaderEntry* entry = nullptr; // library: the translated shader @@ -9565,8 +9639,9 @@ class PipelineState final const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged - bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) - bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked + bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) + bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked + bool bary_fallback_ = false; // graphics: synthesized --bary-fallback geometry stage leonida::Depth24Bias depth24_bias_{}; unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 @@ -10794,6 +10869,13 @@ class Device final static_cast(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); state_.f16_half_top_location = leonida::f16_half_top_location( props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); + state_.bary_f16_half_top_location = state_.f16_half_top_location; + if (props.limits.maxGeometryInputComponents && props.limits.maxGeometryOutputComponents) { + state_.bary_f16_half_top_location = std::min( + state_.f16_half_top_location, + leonida::f16_half_top_location(props.limits.maxGeometryInputComponents, + props.limits.maxGeometryOutputComponents)); + } } if (const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index a359287cb1..41a7769278 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -873,6 +874,8 @@ struct ShaderEntry { std::vector outputs; // pixel/vertex shaders: output locations written // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). std::map> f16_halves; + // --bary-fallback: input location where a pass-through GS supplies one-hot barycentrics (RT-BARY-FALLBACK-PSO). + std::optional bary_fallback_location; // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). std::vector> literal_samplers; @@ -1224,6 +1227,13 @@ class ShaderLibrary { e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; } } + if (const Json* bf = meta.find("bary_fallback_input"); bf && bf->kind == Json::Kind::object) { + if (const Json* loc = bf->find("location"); loc && loc->kind == Json::Kind::number && + loc->number >= 0.0 && loc->number <= 4294967295.0 && + double(std::uint32_t(loc->number)) == loc->number) { + e.bary_fallback_location = std::uint32_t(loc->number); + } + } if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) { for (const Json& item : l->array) { if (item.kind != Json::Kind::array || item.array.size() != 4) continue; diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h new file mode 100644 index 0000000000..01194b8b67 --- /dev/null +++ b/runtime/src/spirv_bary_fallback.h @@ -0,0 +1,428 @@ +#pragma once + +// Per-pipeline `--bary-fallback` geometry-shader synthesis for D3D12 graphics PSOs (RT-BARY-FALLBACK-PSO). +// +// On GPUs without `VK_KHR_fragment_shader_barycentric`, `tools/rdna2spirv.py --bary-fallback` declares the raw +// barycentric pair a pixel shader reads as an ordinary smooth `vec3` input at the location recorded in +// `index.json` under `"bary_fallback_input": {"location": N}`. At graphics PSO creation, after any +// `--f16-interp-fallback` VS/PS location linking (`spirv_f16_halves.h`), `build_bary_fallback_gs` synthesizes the +// triangle pass-through Geometry SPIR-V module (`tools/bary_fallback_gs.py` equivalent) in memory for the exact +// `(VS, PS)` pair: +// - copies `BuiltIn Position` across the triangle's 3 vertices (`Triangles` -> `OutputTriangleStrip`, 3 vertices); +// - copies every `vec4` `Location` input the PS reads (other than `bary_location`) that the VS exports, and +// zero-fills any declared PS `Location` input the VS omits without declaring a dangling GS `Input` (preserving +// `VUID-RuntimeSpirv-OpEntryPoint-08743` on both `VS -> GS` and `GS -> PS` interfaces); +// - forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array when present (rejecting +// mixed clip+cull and `ShaderLayer` / `ShaderViewportIndex`, which a pass-through helper cannot forward); +// - writes `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` so perspective interpolation yields +// `BaryCoordKHR` (`.y` / `.z` = AMD's `i` / `j`). +// +// Pure C++20 stdlib, no Vulkan or Windows headers required. + +#include "spirv_f16_halves.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +struct BaryFallbackGsInfo { + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; +}; + +inline bool build_bary_fallback_gs(std::span vs_words, + std::span ps_words, + std::uint32_t bary_location, + std::vector& gs_words, + BaryFallbackGsInfo* out_info = nullptr, + std::string* error = nullptr) { + const auto fail = [&](const std::string& msg) { + if (error) *error = msg; + return false; + }; + + using namespace spirv_detail; + constexpr std::uint32_t kSpirvVersion15 = 0x00010500u; + constexpr std::uint16_t kOpTypeVoid = 19; + constexpr std::uint16_t kOpTypeArray = 28; + constexpr std::uint16_t kOpTypeStruct = 30; + constexpr std::uint16_t kOpTypeFunction = 33; + constexpr std::uint16_t kOpConstant = 43; + constexpr std::uint16_t kOpConstantComposite = 44; + constexpr std::uint16_t kOpEmitVertex = 218; + constexpr std::uint16_t kOpEndPrimitive = 219; + constexpr std::uint16_t kOpLabel = 248; + + constexpr std::uint32_t kExecModelGeometry = 3; + constexpr std::uint32_t kCapGeometry = 2; + constexpr std::uint32_t kCapClipDistance = 32; + constexpr std::uint32_t kCapCullDistance = 33; + constexpr std::uint32_t kCapShaderLayer = 69; + constexpr std::uint32_t kCapShaderViewportIndex = 70; + + constexpr std::uint32_t kExecModeInvocations = 0; + constexpr std::uint32_t kExecModeTriangles = 22; + constexpr std::uint32_t kExecModeOutputVertices = 26; + constexpr std::uint32_t kExecModeOutputTriangleStrip = 29; + + constexpr std::uint32_t kDecorationBuiltIn = 11; + constexpr std::uint32_t kDecorationComponent = 31; + constexpr std::uint32_t kBuiltInPosition = 0; + constexpr std::uint32_t kBuiltInClipDistance = 3; + constexpr std::uint32_t kBuiltInCullDistance = 4; + constexpr std::uint32_t kBuiltInLayer = 9; + constexpr std::uint32_t kBuiltInViewportIndex = 10; + + Module vs_mod, ps_mod; + if (!vs_mod.parse(vs_words)) return fail("bary_fallback: malformed VS SPIR-V"); + if (!ps_mod.parse(ps_words)) return fail("bary_fallback: malformed PS SPIR-V"); + + // --- Inspect VS --- + bool has_vs_ep = false; + std::set vs_float32_tys; + std::map vs_int32_signed; // int_type_id -> is_signed + std::set vs_v4float_tys; + std::map vs_pos_int_consts; // const_id -> value (> 0) + std::map> vs_arr_tys; // arr_id -> (elem_ty, len_id) + std::map> vs_struct_tys; // struct_id -> member_tys + std::map vs_ptr_out_pointee; // ptr_id -> pointee_ty + std::map vs_out_var_pointee; // var_id -> pointee_ty + std::map vs_var_builtins; // var_id -> BuiltIn + std::map>> vs_member_builtins; + std::vector> vs_loc_decs; // (target_id, loc) + + for (const Inst& inst : vs_mod.insts) { + if (inst.opcode == kOpFunction) break; + if (inst.opcode == kOpCapability && inst.words.size() >= 2) { + if (inst.words[1] == kCapShaderLayer) + return fail("bary_fallback: VS declares ShaderLayer, which the fallback GS cannot forward"); + if (inst.words[1] == kCapShaderViewportIndex) + return fail("bary_fallback: VS declares ShaderViewportIndex, which the fallback GS cannot forward"); + } else if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelVertex) { + has_vs_ep = true; + } else if (inst.opcode == kOpDecorate && inst.words.size() >= 4) { + if (inst.words[2] == kDecorationBuiltIn) vs_var_builtins[inst.words[1]] = inst.words[3]; + if (inst.words[2] == kDecorationLocation) vs_loc_decs.emplace_back(inst.words[1], inst.words[3]); + } else if (inst.opcode == kOpMemberDecorate && inst.words.size() >= 5 && inst.words[3] == kDecorationBuiltIn) { + vs_member_builtins[inst.words[1]].emplace_back(inst.words[2], inst.words[4]); + } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { + vs_float32_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32) { + vs_int32_signed[inst.words[1]] = (inst.words[3] != 0); + } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4 && inst.words[3] == 4 && + vs_float32_tys.count(inst.words[2])) { + vs_v4float_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpConstant && inst.words.size() == 4) { + const auto it = vs_int32_signed.find(inst.words[1]); + if (it != vs_int32_signed.end()) { + const std::uint32_t raw = inst.words[3]; + const bool positive = it->second ? (static_cast(raw) > 0) : (raw > 0); + if (positive) vs_pos_int_consts[inst.words[2]] = raw; + } + } else if (inst.opcode == kOpTypeArray && inst.words.size() == 4) { + vs_arr_tys[inst.words[1]] = {inst.words[2], inst.words[3]}; + } else if (inst.opcode == kOpTypeStruct && inst.words.size() >= 2) { + vs_struct_tys[inst.words[1]].assign(inst.words.begin() + 2, inst.words.end()); + } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4 && inst.words[2] == kStorageOutput) { + vs_ptr_out_pointee[inst.words[1]] = inst.words[3]; + } else if (inst.opcode == kOpVariable && inst.words.size() >= 4 && inst.words[3] == kStorageOutput) { + const auto pt = vs_ptr_out_pointee.find(inst.words[1]); + if (pt != vs_ptr_out_pointee.end()) vs_out_var_pointee[inst.words[2]] = pt->second; + } + } + if (!has_vs_ep) return fail("bary_fallback: VS has no Vertex entry point"); + + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; + const auto record_vs_builtin = [&](std::uint32_t bi, std::uint32_t ty_id) -> bool { + if (bi == kBuiltInLayer) + return fail("bary_fallback: VS writes BuiltIn Layer, which the fallback GS cannot forward"); + if (bi == kBuiltInViewportIndex) + return fail("bary_fallback: VS writes BuiltIn ViewportIndex, which the fallback GS cannot forward"); + if (bi != kBuiltInClipDistance && bi != kBuiltInCullDistance) return true; + const auto arr_it = vs_arr_tys.find(ty_id); + if (arr_it == vs_arr_tys.end() || !vs_float32_tys.count(arr_it->second.first)) + return fail("bary_fallback: VS ClipDistance/CullDistance output is not float[N]"); + const auto len_it = vs_pos_int_consts.find(arr_it->second.second); + if (len_it == vs_pos_int_consts.end() || len_it->second < 1 || len_it->second > 8) + return fail("bary_fallback: VS ClipDistance/CullDistance length must be in 1..8"); + std::uint32_t& dst = (bi == kBuiltInClipDistance) ? clip_count : cull_count; + if (dst != 0 && dst != len_it->second) + return fail("bary_fallback: conflicting VS ClipDistance/CullDistance output declarations"); + dst = len_it->second; + return true; + }; + + for (const auto& [var_id, pt_ty] : vs_out_var_pointee) { + if (const auto bi_it = vs_var_builtins.find(var_id); bi_it != vs_var_builtins.end()) { + if (!record_vs_builtin(bi_it->second, pt_ty)) return false; + } + if (const auto m_it = vs_member_builtins.find(pt_ty); m_it != vs_member_builtins.end()) { + const auto st_it = vs_struct_tys.find(pt_ty); + if (st_it != vs_struct_tys.end()) { + for (const auto& [member_idx, bi] : m_it->second) { + if (member_idx >= st_it->second.size()) + return fail("bary_fallback: out-of-range MemberDecorate on VS output struct"); + if (!record_vs_builtin(bi, st_it->second[member_idx])) return false; + } + } + } + } + if (clip_count && cull_count) + return fail("bary_fallback: cannot forward mixed ClipDistance and CullDistance"); + + std::map vs_out_loc_pointee; // loc -> pointee_ty + for (const auto& [target, loc] : vs_loc_decs) { + const auto it = vs_out_var_pointee.find(target); + if (it == vs_out_var_pointee.end()) continue; + if (!vs_out_loc_pointee.emplace(loc, it->second).second) + return fail("bary_fallback: duplicate VS Output Location " + std::to_string(loc)); + } + + // --- Inspect PS --- + bool has_ps_ep = false; + std::set ps_float32_tys; + std::set ps_v3float_tys; + std::set ps_v4float_tys; + std::map ps_ptr_in_pointee; + std::map ps_in_var_pointee; + std::vector> ps_loc_decs; + std::set ps_component_targets; + + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) break; + if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelFragment) { + has_ps_ep = true; + } else if (inst.opcode == kOpDecorate && inst.words.size() >= 4) { + if (inst.words[2] == kDecorationLocation) ps_loc_decs.emplace_back(inst.words[1], inst.words[3]); + if (inst.words[2] == kDecorationComponent) ps_component_targets.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { + ps_float32_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4 && ps_float32_tys.count(inst.words[2])) { + if (inst.words[3] == 3) ps_v3float_tys.insert(inst.words[1]); + if (inst.words[3] == 4) ps_v4float_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4 && inst.words[2] == kStorageInput) { + ps_ptr_in_pointee[inst.words[1]] = inst.words[3]; + } else if (inst.opcode == kOpVariable && inst.words.size() >= 4 && inst.words[3] == kStorageInput) { + const auto pt = ps_ptr_in_pointee.find(inst.words[1]); + if (pt != ps_ptr_in_pointee.end()) ps_in_var_pointee[inst.words[2]] = pt->second; + } + } + if (!has_ps_ep) return fail("bary_fallback: PS has no Fragment entry point"); + + std::map ps_in_loc_pointee; + for (const auto& [target, loc] : ps_loc_decs) { + const auto it = ps_in_var_pointee.find(target); + if (it == ps_in_var_pointee.end()) continue; + if (ps_component_targets.count(target)) + return fail("bary_fallback: Component-decorated PS Input at Location " + std::to_string(loc)); + if (!ps_in_loc_pointee.emplace(loc, it->second).second) + return fail("bary_fallback: duplicate PS Input Location " + std::to_string(loc)); + } + + if (const auto bary_it = ps_in_loc_pointee.find(bary_location); + bary_it != ps_in_loc_pointee.end() && !ps_v3float_tys.count(bary_it->second)) { + return fail("bary_fallback: bary_location " + std::to_string(bary_location) + + " collides with a non-vec3 PS Input"); + } + + std::vector pass_locs; + std::vector forwarded_locs; + std::set zero_loc_set; + for (const auto& [loc, pt_ty] : ps_in_loc_pointee) { + if (loc == bary_location) continue; + if (!ps_v4float_tys.count(pt_ty)) + return fail("bary_fallback: PS pass-through Input at Location " + std::to_string(loc) + " is not vec4"); + pass_locs.push_back(loc); + const auto vs_it = vs_out_loc_pointee.find(loc); + if (vs_it != vs_out_loc_pointee.end()) { + if (!vs_v4float_tys.count(vs_it->second)) + return fail("bary_fallback: VS Output at Location " + std::to_string(loc) + " is not vec4"); + forwarded_locs.push_back(loc); + } else { + zero_loc_set.insert(loc); + } + } + + // --- Synthesize Geometry SPIR-V module --- + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_int = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v3float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_uint_3 = alloc(); + const std::uint32_t id_arr_v4_3 = alloc(); + const std::uint32_t id_ptr_in_arr = alloc(); + const std::uint32_t id_ptr_in_v4 = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_ptr_out_v3 = alloc(); + const std::uint32_t id_null_v4 = zero_loc_set.empty() ? 0 : alloc(); + + const std::uint32_t dist_count = clip_count ? clip_count : cull_count; + const std::uint32_t dist_cap = cull_count ? kCapCullDistance : kCapClipDistance; + const std::uint32_t dist_builtin = cull_count ? kBuiltInCullDistance : kBuiltInClipDistance; + std::uint32_t id_dist_count = 0; + std::uint32_t id_arr_dist = 0; + std::uint32_t id_tri_dist = 0; + std::uint32_t id_ptr_in_tri_dist = 0; + std::uint32_t id_ptr_in_dist = 0; + std::uint32_t id_ptr_out_dist = 0; + if (dist_count) { + id_dist_count = (dist_count == 3) ? id_uint_3 : alloc(); + id_arr_dist = alloc(); + id_tri_dist = alloc(); + id_ptr_in_tri_dist = alloc(); + id_ptr_in_dist = alloc(); + id_ptr_out_dist = alloc(); + } + + const std::uint32_t id_f0 = alloc(); + const std::uint32_t id_f1 = alloc(); + const std::uint32_t id_bary[3] = {alloc(), alloc(), alloc()}; + const std::uint32_t id_int_v[3] = {alloc(), alloc(), alloc()}; + + const std::uint32_t id_in_pos = alloc(); + const std::uint32_t id_out_pos = alloc(); + std::map id_in_loc; + std::map id_out_loc; + for (std::uint32_t loc : forwarded_locs) id_in_loc[loc] = alloc(); + for (std::uint32_t loc : pass_locs) id_out_loc[loc] = alloc(); + const std::uint32_t id_out_bary = alloc(); + const std::uint32_t id_in_dist = dist_count ? alloc() : 0; + const std::uint32_t id_out_dist = dist_count ? alloc() : 0; + + Module gs; + // 1. Capabilities + gs.insts.push_back(make_inst(kOpCapability, {kCapGeometry})); + if (dist_count) gs.insts.push_back(make_inst(kOpCapability, {dist_cap})); + + // 2. MemoryModel + gs.insts.push_back(make_inst(kOpMemoryModel, {0, 1})); // Logical GLSL450 + + // 3. EntryPoint ("main\0") + std::vector ep = {kExecModelGeometry, id_main, 0x6e69616du, 0x00000000u, id_in_pos, id_out_pos}; + for (std::uint32_t loc : forwarded_locs) ep.push_back(id_in_loc[loc]); + for (std::uint32_t loc : pass_locs) ep.push_back(id_out_loc[loc]); + ep.push_back(id_out_bary); + if (dist_count) { + ep.push_back(id_in_dist); + ep.push_back(id_out_dist); + } + gs.insts.push_back(make_inst_vec(kOpEntryPoint, ep)); + + // 4. ExecutionModes + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeTriangles})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeInvocations, 1})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeOutputTriangleStrip})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeOutputVertices, 3})); + + // 5. Decorations + gs.insts.push_back(make_inst(kOpDecorate, {id_in_pos, kDecorationBuiltIn, kBuiltInPosition})); + gs.insts.push_back(make_inst(kOpDecorate, {id_out_pos, kDecorationBuiltIn, kBuiltInPosition})); + if (dist_count) { + gs.insts.push_back(make_inst(kOpDecorate, {id_in_dist, kDecorationBuiltIn, dist_builtin})); + gs.insts.push_back(make_inst(kOpDecorate, {id_out_dist, kDecorationBuiltIn, dist_builtin})); + } + for (std::uint32_t loc : forwarded_locs) + gs.insts.push_back(make_inst(kOpDecorate, {id_in_loc[loc], kDecorationLocation, loc})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpDecorate, {id_out_loc[loc], kDecorationLocation, loc})); + gs.insts.push_back(make_inst(kOpDecorate, {id_out_bary, kDecorationLocation, bary_location})); + + // 6. Types, Constants, Global Variables + gs.insts.push_back(make_inst(kOpTypeVoid, {id_void})); + gs.insts.push_back(make_inst(kOpTypeFunction, {id_fn, id_void})); + gs.insts.push_back(make_inst(kOpTypeInt, {id_uint, 32, 0})); + gs.insts.push_back(make_inst(kOpTypeInt, {id_int, 32, 1})); + gs.insts.push_back(make_inst(kOpTypeFloat, {id_float, 32})); + gs.insts.push_back(make_inst(kOpTypeVector, {id_v3float, id_float, 3})); + gs.insts.push_back(make_inst(kOpTypeVector, {id_v4float, id_float, 4})); + gs.insts.push_back(make_inst(kOpConstant, {id_uint, id_uint_3, 3})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_arr_v4_3, id_v4float, id_uint_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_arr, kStorageInput, id_arr_v4_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_v3, kStorageOutput, id_v3float})); + if (id_null_v4) gs.insts.push_back(make_inst(kOpConstantNull, {id_v4float, id_null_v4})); + if (dist_count) { + if (id_dist_count != id_uint_3) gs.insts.push_back(make_inst(kOpConstant, {id_uint, id_dist_count, dist_count})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_arr_dist, id_float, id_dist_count})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_tri_dist, id_arr_dist, id_uint_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_tri_dist, kStorageInput, id_tri_dist})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_dist, kStorageInput, id_arr_dist})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_dist, kStorageOutput, id_arr_dist})); + } + gs.insts.push_back(make_inst(kOpConstant, {id_float, id_f0, 0x00000000u})); + gs.insts.push_back(make_inst(kOpConstant, {id_float, id_f1, 0x3f800000u})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[0], id_f1, id_f0, id_f0})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[1], id_f0, id_f1, id_f0})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[2], id_f0, id_f0, id_f1})); + for (std::uint32_t v = 0; v < 3; ++v) gs.insts.push_back(make_inst(kOpConstant, {id_int, id_int_v[v], v})); + + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id_in_pos, kStorageInput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v4, id_out_pos, kStorageOutput})); + for (std::uint32_t loc : forwarded_locs) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id_in_loc[loc], kStorageInput})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v4, id_out_loc[loc], kStorageOutput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v3, id_out_bary, kStorageOutput})); + if (dist_count) { + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_tri_dist, id_in_dist, kStorageInput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_dist, id_out_dist, kStorageOutput})); + } + + // 7. Function main + gs.insts.push_back(make_inst(kOpFunction, {id_void, id_main, 0, id_fn})); + gs.insts.push_back(make_inst(kOpLabel, {id_entry})); + for (std::uint32_t v = 0; v < 3; ++v) { + const std::uint32_t pos_ptr = alloc(); + const std::uint32_t pos_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_v4, pos_ptr, id_in_pos, id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_v4float, pos_val, pos_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_pos, pos_val})); + + for (std::uint32_t loc : pass_locs) { + if (zero_loc_set.count(loc)) { + gs.insts.push_back(make_inst(kOpStore, {id_out_loc[loc], id_null_v4})); + } else { + const std::uint32_t attr_ptr = alloc(); + const std::uint32_t attr_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_v4, attr_ptr, id_in_loc[loc], id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_v4float, attr_val, attr_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_loc[loc], attr_val})); + } + } + if (dist_count) { + const std::uint32_t d_ptr = alloc(); + const std::uint32_t d_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_dist, d_ptr, id_in_dist, id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_arr_dist, d_val, d_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_dist, d_val})); + } + gs.insts.push_back(make_inst(kOpStore, {id_out_bary, id_bary[v]})); + gs.insts.push_back(make_inst(kOpEmitVertex, {})); + } + gs.insts.push_back(make_inst(kOpEndPrimitive, {})); + gs.insts.push_back(make_inst(kOpReturn, {})); + gs.insts.push_back(make_inst(kOpFunctionEnd, {})); + + gs.header = {kSpirvMagic, kSpirvVersion15, 0u, next_id, 0u}; + gs_words = gs.serialize(); + if (out_info) *out_info = {clip_count, cull_count}; + return true; +} + +} // namespace leonida diff --git a/runtime/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp new file mode 100644 index 0000000000..6f94d4dc05 --- /dev/null +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -0,0 +1,678 @@ +// End-to-end Vulkan GPU test for `--bary-fallback` D3D12 graphics PSOs (RT-BARY-FALLBACK-PSO). +// +// Exercises graphics PSOs whose pixel shader carries `bary_fallback_input` in `index.json` through the Xbox-ABI +// device proxy on a real Vulkan 1.3 GPU (including GPUs without `VK_KHR_fragment_shader_barycentric`, such as NVIDIA +// Pascal). SPIR-V 1.5 modules are constructed directly in memory — no glslangValidator, llvm-mc or game files needed: +// 1. Perspective-correct barycentrics + pass-through vec4 attribute: draws a fullscreen-covering triangle with +// non-uniform clip W = (1, 2, 4) and verifies all 16x16 pixels match exact perspective-weighted `(b0, b1, b2)` +// plus pass-through `Location 0` alpha (`0.75`), separating perspective interpolation from affine by >40 LSB. +// 2. VS `ClipDistance[1]` forwarding (when `shaderClipDistance` is enabled): clips `ndc_x < 0` to the clear color +// while keeping `ndc_x > 0` with intact barycentrics. +// 3. Combined `--f16-interp-fallback` + `--bary-fallback`: a 16-param VS (with packed f16 pairs in `param7` and +// colliding static halves) paired with a PS reading raw `0..13`, `bary_fallback_input` at `Location 14`, and +// `f16_halves` for `param7` at `[15, 16]` (relocated to `[28, 29]` before GS synthesis). +// 4. Refusals: non-triangle topology (`E_INVALIDARG`), explicit GS (`E_NOTIMPL`), and disabled `geometryShader` +// feature (`E_NOTIMPL`). +// Skips (77) when no usable Vulkan 1.3 device or `geometryShader` feature is present. No game data. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" +#include "../src/spirv_bary_fallback.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ +} while (0) + +using namespace d3d12test; +using namespace leonida::spirv_detail; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +void put_inst(std::vector& w, std::uint16_t op, std::initializer_list args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + for (std::uint32_t a : args) w.push_back(a); +} + +void put_inst_vec(std::vector& w, std::uint16_t op, const std::vector& args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + w.insert(w.end(), args.begin(), args.end()); +} + +void write_spv(const std::filesystem::path& path, const std::vector& words) { + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); +} + +// Triangle VS from VertexIndex (0, 1, 2): +// - If `non_uniform_w` is true: V0 = (-1, -1, 0, 1), V1 = (6, -2, 0, 2), V2 = (-4, 12, 0, 4) +// (same NDC (-1,-1), (3,-1), (-1,3), with w = 1, 2, 4). +// - Else: V0 = (-1, -1, 0, 1), V1 = (3, -1, 0, 1), V2 = (-1, 3, 0, 1). +// Exports Location 0 = vec4(0.5, 0.25, 0.75, 1.0), and optionally BuiltIn ClipDistance float[1] = {ndc_x}. +std::vector make_bary_vs(bool non_uniform_w, bool with_clip_x) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_int = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_bool = alloc(); + const std::uint32_t id_ptr_in_int = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + + const std::uint32_t id_u1 = with_clip_x ? alloc() : 0; + const std::uint32_t id_clip_arr = with_clip_x ? alloc() : 0; + const std::uint32_t id_ptr_out_clip = with_clip_x ? alloc() : 0; + const std::uint32_t id_ptr_out_f = with_clip_x ? alloc() : 0; + + const std::uint32_t id_f0 = alloc(); // 0.0 + const std::uint32_t id_f1 = alloc(); // 1.0 + const std::uint32_t id_fm1 = alloc(); // -1.0 + const std::uint32_t id_f3 = alloc(); // 3.0 + const std::uint32_t id_f2 = alloc(); // 2.0 + const std::uint32_t id_f4 = alloc(); // 4.0 + const std::uint32_t id_f6 = alloc(); // 6.0 + const std::uint32_t id_fm2 = alloc(); // -2.0 + const std::uint32_t id_fm4 = alloc(); // -4.0 + const std::uint32_t id_f12 = alloc(); // 12.0 + const std::uint32_t id_f025 = alloc(); // 0.25 + const std::uint32_t id_f05 = alloc(); // 0.50 + const std::uint32_t id_f075 = alloc(); // 0.75 + + const std::uint32_t id_p0 = alloc(); + const std::uint32_t id_p1 = alloc(); + const std::uint32_t id_p2 = alloc(); + const std::uint32_t id_attr0_val = alloc(); + const std::uint32_t id_i0 = alloc(); + const std::uint32_t id_i1 = alloc(); + + const std::uint32_t id_vid_var = alloc(); + const std::uint32_t id_pos_var = alloc(); + const std::uint32_t id_out0_var = alloc(); + const std::uint32_t id_clip_var = with_clip_x ? alloc() : 0; + + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_vid = alloc(); + const std::uint32_t id_is0 = alloc(); + const std::uint32_t id_is1 = alloc(); + const std::uint32_t id_p12 = alloc(); + const std::uint32_t id_pos = alloc(); + const std::uint32_t id_cx12 = with_clip_x ? alloc() : 0; + const std::uint32_t id_cx = with_clip_x ? alloc() : 0; + const std::uint32_t id_cptr = with_clip_x ? alloc() : 0; + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + put_inst(w, kOpCapability, {1}); // Shader + if (with_clip_x) put_inst(w, kOpCapability, {32}); // ClipDistance + put_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelVertex, id_main, 0x6e69616du, 0x00000000u, + id_vid_var, id_pos_var, id_out0_var}; + if (with_clip_x) ep.push_back(id_clip_var); + put_inst_vec(w, kOpEntryPoint, ep); + + put_inst(w, kOpDecorate, {id_vid_var, 11, 42}); // BuiltIn VertexIndex + put_inst(w, kOpDecorate, {id_pos_var, 11, 0}); // BuiltIn Position + put_inst(w, kOpDecorate, {id_out0_var, kDecorationLocation, 0}); + if (with_clip_x) put_inst(w, kOpDecorate, {id_clip_var, 11, 3}); // BuiltIn ClipDistance + + put_inst(w, 19, {id_void}); + put_inst(w, 33, {id_fn, id_void}); + put_inst(w, kOpTypeFloat, {id_float, 32}); + put_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + put_inst(w, kOpTypeInt, {id_int, 32, 1}); + put_inst(w, kOpTypeInt, {id_uint, 32, 0}); + put_inst(w, 20, {id_bool}); + put_inst(w, kOpTypePointer, {id_ptr_in_int, kStorageInput, id_int}); + put_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + if (with_clip_x) { + put_inst(w, 43, {id_uint, id_u1, 1u}); + put_inst(w, 28, {id_clip_arr, id_float, id_u1}); + put_inst(w, kOpTypePointer, {id_ptr_out_clip, kStorageOutput, id_clip_arr}); + put_inst(w, kOpTypePointer, {id_ptr_out_f, kStorageOutput, id_float}); + } + + put_inst(w, 43, {id_float, id_f0, 0x00000000u}); + put_inst(w, 43, {id_float, id_f1, 0x3f800000u}); + put_inst(w, 43, {id_float, id_fm1, 0xbf800000u}); + put_inst(w, 43, {id_float, id_f3, 0x40400000u}); + put_inst(w, 43, {id_float, id_f2, 0x40000000u}); + put_inst(w, 43, {id_float, id_f4, 0x40800000u}); + put_inst(w, 43, {id_float, id_f6, 0x40c00000u}); + put_inst(w, 43, {id_float, id_fm2, 0xc0000000u}); + put_inst(w, 43, {id_float, id_fm4, 0xc0800000u}); + put_inst(w, 43, {id_float, id_f12, 0x41400000u}); + put_inst(w, 43, {id_float, id_f025, 0x3e800000u}); + put_inst(w, 43, {id_float, id_f05, 0x3f000000u}); + put_inst(w, 43, {id_float, id_f075, 0x3f400000u}); + + put_inst(w, 44, {id_v4float, id_p0, id_fm1, id_fm1, id_f0, id_f1}); + if (non_uniform_w) { + put_inst(w, 44, {id_v4float, id_p1, id_f6, id_fm2, id_f0, id_f2}); + put_inst(w, 44, {id_v4float, id_p2, id_fm4, id_f12, id_f0, id_f4}); + } else { + put_inst(w, 44, {id_v4float, id_p1, id_f3, id_fm1, id_f0, id_f1}); + put_inst(w, 44, {id_v4float, id_p2, id_fm1, id_f3, id_f0, id_f1}); + } + put_inst(w, 44, {id_v4float, id_attr0_val, id_f05, id_f025, id_f075, id_f1}); + put_inst(w, 43, {id_int, id_i0, 0u}); + put_inst(w, 43, {id_int, id_i1, 1u}); + + put_inst(w, kOpVariable, {id_ptr_in_int, id_vid_var, kStorageInput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_pos_var, kStorageOutput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_out0_var, kStorageOutput}); + if (with_clip_x) put_inst(w, kOpVariable, {id_ptr_out_clip, id_clip_var, kStorageOutput}); + + put_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + put_inst(w, 248, {id_entry}); + put_inst(w, kOpLoad, {id_int, id_vid, id_vid_var}); + put_inst(w, 170, {id_bool, id_is0, id_vid, id_i0}); // OpIEqual vid 0 + put_inst(w, 170, {id_bool, id_is1, id_vid, id_i1}); // OpIEqual vid 1 + put_inst(w, 169, {id_v4float, id_p12, id_is1, id_p1, id_p2}); + put_inst(w, 169, {id_v4float, id_pos, id_is0, id_p0, id_p12}); + put_inst(w, kOpStore, {id_pos_var, id_pos}); + put_inst(w, kOpStore, {id_out0_var, id_attr0_val}); + if (with_clip_x) { + // ndc_x = (-1 for V0, +3 for V1, -1 for V2) -> clips left half (ndc_x < 0). + put_inst(w, 169, {id_float, id_cx12, id_is1, id_f3, id_fm1}); + put_inst(w, 169, {id_float, id_cx, id_is0, id_fm1, id_cx12}); + put_inst(w, kOpAccessChain, {id_ptr_out_f, id_cptr, id_clip_var, id_i0}); + put_inst(w, kOpStore, {id_cptr, id_cx}); + } + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// PS reading Location 0 (vec4 attr0) and Location 1 (vec3 bary), writing vec4(bary.x, bary.y, bary.z, attr0.z). +std::vector make_bary_ps(std::uint32_t bary_loc) { + // 1=void, 2=fn, 3=float, 4=v3float, 5=v4float, 6=ptr_in_v3, 7=ptr_in_v4, 8=ptr_out_v4, + // 9=out0, 10=in_attr0, 11=in_bary, 12=main, 13=entry, + // 14=attr0, 15=bary, 16=bx, 17=by, 18=bz, 19=az, 20=rgba + constexpr std::uint32_t kBound = 21; + std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + put_inst(w, kOpEntryPoint, {kExecModelFragment, 12, 0x6e69616du, 0x00000000u, 9, 10, 11}); + put_inst(w, kOpExecutionMode, {12, 7}); // OriginUpperLeft + + put_inst(w, kOpDecorate, {9, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {10, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {11, kDecorationLocation, bary_loc}); + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 3}); + put_inst(w, kOpTypeVector, {5, 3, 4}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 4}); + put_inst(w, kOpTypePointer, {7, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {8, kStorageOutput, 5}); + + put_inst(w, kOpVariable, {8, 9, kStorageOutput}); + put_inst(w, kOpVariable, {7, 10, kStorageInput}); + put_inst(w, kOpVariable, {6, 11, kStorageInput}); + + put_inst(w, kOpFunction, {1, 12, 0, 2}); + put_inst(w, 248, {13}); + put_inst(w, kOpLoad, {5, 14, 10}); + put_inst(w, kOpLoad, {4, 15, 11}); + put_inst(w, kOpCompositeExtract, {3, 16, 15, 0}); + put_inst(w, kOpCompositeExtract, {3, 17, 15, 1}); + put_inst(w, kOpCompositeExtract, {3, 18, 15, 2}); + put_inst(w, kOpCompositeExtract, {3, 19, 14, 2}); + put_inst(w, kOpCompositeConstruct, {5, 20, 16, 17, 18, 19}); + put_inst(w, kOpStore, {9, 20}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// 16-param VS (param0..param15, static f16_halves for 0..6, param7.x = packHalf2x16(0.25, 0.75) = 0x3a003400). +std::vector make_16param_vs() { + constexpr std::uint32_t kBound = 61; + std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelVertex, 24, 0x6e69616du, 0x00000000u, 8, 9}; + for (std::uint32_t id = 31; id <= 60; ++id) ep.push_back(id); + put_inst_vec(w, kOpEntryPoint, ep); + + put_inst(w, kOpDecorate, {8, 11, 42}); // BuiltIn VertexIndex + put_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position + for (std::uint32_t p = 0; p < 16; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p}); + for (std::uint32_t n = 0; n <= 6; ++n) { + put_inst(w, kOpDecorate, {47 + 2 * n, kDecorationLocation, 28 - 2 * n}); + put_inst(w, kOpDecorate, {48 + 2 * n, kDecorationLocation, 29 - 2 * n}); + } + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 4}); + put_inst(w, kOpTypeInt, {5, 32, 1}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {7, kStorageOutput, 4}); + put_inst(w, 20, {20}); + + put_inst(w, kOpConstantNull, {4, 10}); + put_inst(w, 43, {3, 11, 0xbf800000u}); // -1.0f + put_inst(w, 43, {3, 12, 0x40400000u}); // 3.0f + put_inst(w, 43, {3, 13, 0x00000000u}); // 0.0f + put_inst(w, 43, {3, 14, 0x3f800000u}); // 1.0f + put_inst(w, 44, {4, 15, 11, 11, 13, 14}); + put_inst(w, 44, {4, 16, 12, 11, 13, 14}); + put_inst(w, 44, {4, 17, 11, 12, 13, 14}); + put_inst(w, 43, {5, 18, 0u}); + put_inst(w, 43, {5, 19, 1u}); + put_inst(w, 43, {3, 21, 0x3a003400u}); // packHalf2x16(0.25, 0.75) + put_inst(w, 43, {3, 22, 0x3c003800u}); + put_inst(w, 44, {4, 23, 21, 22, 13, 14}); + + put_inst(w, kOpVariable, {6, 8, kStorageInput}); + put_inst(w, kOpVariable, {7, 9, kStorageOutput}); + for (std::uint32_t id = 31; id <= 60; ++id) put_inst(w, kOpVariable, {7, id, kStorageOutput}); + + put_inst(w, kOpFunction, {1, 24, 0, 2}); + put_inst(w, 248, {25}); + put_inst(w, kOpLoad, {5, 26, 8}); + put_inst(w, 170, {20, 27, 26, 18}); + put_inst(w, 170, {20, 28, 26, 19}); + put_inst(w, 169, {4, 29, 28, 16, 17}); + put_inst(w, 169, {4, 30, 27, 15, 29}); + put_inst(w, kOpStore, {9, 30}); + for (std::uint32_t p = 0; p < 16; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u}); + for (std::uint32_t id = 47; id <= 60; ++id) put_inst(w, kOpStore, {id, 10}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// Combined f16 + bary PS: reads raw 0..num_raw-1, bary vec3 at `bary_loc`, and f16 halves at `lo_loc`/`hi_loc`, +// writing vec4(lo.x, hi.x, bary.y, bary.z) to MRT 0. +std::vector make_bary_f16_ps(std::uint32_t num_raw, std::uint32_t bary_loc, + std::uint32_t lo_loc, std::uint32_t hi_loc) { + // 1=void, 2=fn, 3=float, 4=v3float, 5=v4float, 6=ptr_in_v3, 7=ptr_in_v4, 8=ptr_out_v4, + // 9=out0, 10=in_bary, 11=in_lo, 12=in_hi, 13=main, 14=entry, + // 15=bary, 16=vlo, 17=vhi, 18=lox, 19=hix, 20=by, 21=bz, 22=rgba, 23..=raw + const std::uint32_t bound = 23 + num_raw; + std::vector w = {kSpirvMagic, 0x00010500u, 0, bound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelFragment, 13, 0x6e69616du, 0x00000000u, 9, 10, 11, 12}; + for (std::uint32_t i = 0; i < num_raw; ++i) ep.push_back(23 + i); + put_inst_vec(w, kOpEntryPoint, ep); + put_inst(w, kOpExecutionMode, {13, 7}); + + put_inst(w, kOpDecorate, {9, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {10, kDecorationLocation, bary_loc}); + put_inst(w, kOpDecorate, {11, kDecorationLocation, lo_loc}); + put_inst(w, kOpDecorate, {12, kDecorationLocation, hi_loc}); + for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpDecorate, {23 + i, kDecorationLocation, i}); + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 3}); + put_inst(w, kOpTypeVector, {5, 3, 4}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 4}); + put_inst(w, kOpTypePointer, {7, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {8, kStorageOutput, 5}); + + put_inst(w, kOpVariable, {8, 9, kStorageOutput}); + put_inst(w, kOpVariable, {6, 10, kStorageInput}); + put_inst(w, kOpVariable, {7, 11, kStorageInput}); + put_inst(w, kOpVariable, {7, 12, kStorageInput}); + for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpVariable, {7, 23 + i, kStorageInput}); + + put_inst(w, kOpFunction, {1, 13, 0, 2}); + put_inst(w, 248, {14}); + put_inst(w, kOpLoad, {4, 15, 10}); + put_inst(w, kOpLoad, {5, 16, 11}); + put_inst(w, kOpLoad, {5, 17, 12}); + put_inst(w, kOpCompositeExtract, {3, 18, 16, 0}); // lo.x = 0.25 + put_inst(w, kOpCompositeExtract, {3, 19, 17, 0}); // hi.x = 0.75 + put_inst(w, kOpCompositeExtract, {3, 20, 15, 1}); // bary.y = i + put_inst(w, kOpCompositeExtract, {3, 21, 15, 2}); // bary.z = j + put_inst(w, kOpCompositeConstruct, {5, 22, 18, 19, 20, 21}); + put_inst(w, kOpStore, {9, 22}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +int to_unorm8(float v) { + if (v <= 0.0f) return 0; + if (v >= 1.0f) return 255; + return int(std::lround(v * 255.0f)); +} + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + + const auto vs_persp_prog = fssm_program({0x5653ba01, 0xbf810000}); + const auto vs_clip_prog = fssm_program({0x5653ba02, 0xbf810000}); + const auto vs_16p_prog = fssm_program({0x5653ba03, 0xbf810000}); + const auto gs_dummy_prog = fssm_program({0x4753ba01, 0xbf810000}); + const auto ps_bary_prog = fssm_program({0x5053ba01, 0xbf810000}); + const auto ps_f16_prog = fssm_program({0x5053ba02, 0xbf810000}); + + const auto vs_persp_c = shader_container(vs_persp_prog); + const auto vs_clip_c = shader_container(vs_clip_prog); + const auto vs_16p_c = shader_container(vs_16p_prog); + const auto gs_dummy_c = shader_container(gs_dummy_prog); + const auto ps_bary_c = shader_container(ps_bary_prog); + const auto ps_f16_c = shader_container(ps_f16_prog); + + const auto vs_persp_spv = make_bary_vs(true, false); + const auto ps_bary_spv = make_bary_ps(1); + std::vector gs_dummy_spv; + EXPECT(leonida::build_bary_fallback_gs(vs_persp_spv, ps_bary_spv, 1, gs_dummy_spv)); + + const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_bary_fallback_gpu_test"; + std::filesystem::create_directories(lib_dir); + write_spv(lib_dir / "vs_persp.spv", vs_persp_spv); + write_spv(lib_dir / "vs_clip.spv", make_bary_vs(false, true)); + write_spv(lib_dir / "vs_16p.spv", make_16param_vs()); + write_spv(lib_dir / "gs_dummy.spv", gs_dummy_spv); + write_spv(lib_dir / "ps_bary.spv", ps_bary_spv); + write_spv(lib_dir / "ps_bary_f16.spv", make_bary_f16_ps(14, 14, 15, 16)); + { + std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc); + idx << "{\"vs_persp\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_persp_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"vs_clip\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_clip_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_16p_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], " + "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], " + "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n" + " \"gs_dummy\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_dummy_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n" + " \"ps_bary\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_bary_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"inputs\": [0], " + "\"bary_fallback_input\": {\"location\": 1}},\n" + " \"ps_bary_f16\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_f16_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " + "\"bary_fallback_input\": {\"location\": 14}, \"f16_halves\": {\"7\": [15, 16]}}}"; + } + + constexpr UINT kSize = 16; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; + info.subgroup = d.subgroup; + info.shader_dir = lib_dir.string(); + + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + D3D12_HEAP_PROPERTIES default_hp{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = kSize; + rt_desc.Height = kSize; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref rt_res; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&rt_res.p)))); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv_h{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(rt_res.p, nullptr, rtv_h); + + D3D12_HEAP_PROPERTIES rb_hp{D3D12_HEAP_TYPE_READBACK}; + const auto rb_desc = buffer_desc(kSize * 256); + Ref rb_res; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_hp, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&rb_res.p)))); + + const auto make_pso_desc = [&](const std::vector& vs, const std::vector& ps) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = 0xffffffffu; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc.Count = 1; + return pd; + }; + + UINT64 fence_val = 0; + const auto draw_and_readback = [&](ID3D12PipelineState* pso, std::vector& out_bytes) -> bool { + if (FAILED(alloc->Reset()) || FAILED(list->Reset(alloc.p, pso))) return false; + const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + list->ClearRenderTargetView(rtv_h, clear_col, 0, nullptr); + list->OMSetRenderTargets(1, &rtv_h, FALSE, nullptr); + const D3D12_VIEWPORT vp = {0.0f, 0.0f, float(kSize), float(kSize), 0.0f, 1.0f}; + const D3D12_RECT sc = {0, 0, LONG(kSize), LONG(kSize)}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &sc); + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + + const D3D12_RESOURCE_BARRIER to_copy = + transition(rt_res.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = rb_res.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = rt_res.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + const D3D12_RESOURCE_BARRIER to_rt = + transition(rt_res.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_rt); + if (FAILED(list->Close())) return false; + + ID3D12CommandList* cl = list.p; + queue->ExecuteCommandLists(1, &cl); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + ++fence_val; + if (FAILED(queue->Signal(fence.p, fence_val))) return false; + if (FAILED(fence->SetEventOnCompletion(fence_val, nullptr))) return false; + + void* mapped = nullptr; + const D3D12_RANGE read_range = {0, kSize * 256}; + if (FAILED(rb_res->Map(0, &read_range, &mapped)) || !mapped) return false; + out_bytes.assign(static_cast(mapped), + static_cast(mapped) + kSize * 256); + rb_res->Unmap(0, nullptr); + return true; + }; + + // 1. Perspective-correct barycentrics + pass-through vec4 attribute across all 16x16 pixels. + { + auto pd = make_pso_desc(vs_persp_c, ps_bary_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + const float denom = l0 / 1.0f + l1 / 2.0f + l2 / 4.0f; + const int want_r = to_unorm8((l0 / 1.0f) / denom); + const int want_g = to_unorm8((l1 / 2.0f) / denom); + const int want_b = to_unorm8((l2 / 4.0f) / denom); + const auto* px = pixels.data() + row * 256 + col * 4; + if (std::abs(int(px[0]) - want_r) > 2 || std::abs(int(px[1]) - want_g) > 2 || + std::abs(int(px[2]) - want_b) > 2 || std::abs(int(px[3]) - 191) > 1) { + std::fprintf(stderr, "persp (%u,%u): got (%u,%u,%u,%u) want (%d,%d,%d,191)\n", + col, row, px[0], px[1], px[2], px[3], want_r, want_g, want_b); + return 1; + } + } + } + const auto* mid = pixels.data() + (kSize / 2) * 256 + (kSize / 2) * 4; + std::printf("ps_bary (perspective w=1,2,4): center=(%u,%u,%u,%u) OK\n", + mid[0], mid[1], mid[2], mid[3]); + } + + // 2. VS ClipDistance[1] forwarding (clips ndc_x < 0 to clear color). + if (d.enabled.shaderClipDistance) { + auto pd = make_pso_desc(vs_clip_c, ps_bary_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const auto* px = pixels.data() + row * 256 + col * 4; + if (col < kSize / 2 - 1) { + EXPECT(px[0] == 0 && px[1] == 0 && px[2] == 0 && px[3] == 0); + } else if (col > kSize / 2) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + EXPECT(std::abs(int(px[0]) - to_unorm8(l0)) <= 2); + EXPECT(std::abs(int(px[1]) - to_unorm8(l1)) <= 2); + EXPECT(std::abs(int(px[2]) - to_unorm8(l2)) <= 2); + EXPECT(std::abs(int(px[3]) - 191) <= 1); + } + } + } + std::printf("ps_bary + ClipDistance[1]: left half clipped, right half interpolated OK\n"); + } + + // 3. Combined --f16-interp-fallback + --bary-fallback (relocated f16 halves + synthesized GS). + { + auto pd = make_pso_desc(vs_16p_c, ps_f16_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const int want_i = to_unorm8(0.25f * (ndc_x + 1.0f)); + const int want_j = to_unorm8(0.25f * (ndc_y + 1.0f)); + const auto* px = pixels.data() + row * 256 + col * 4; + EXPECT(std::abs(int(px[0]) - 64) <= 1); + EXPECT(std::abs(int(px[1]) - 191) <= 1); + EXPECT(std::abs(int(px[2]) - want_i) <= 2); + EXPECT(std::abs(int(px[3]) - want_j) <= 2); + } + } + std::printf("ps_bary_f16 (combined f16_halves relocation + bary GS): all 256 pixels OK\n"); + } + + // 4a & 4b. Refusals: non-triangle topology -> E_INVALIDARG; explicit GS -> E_NOTIMPL. + { + auto pd_lines = make_pso_desc(vs_persp_c, ps_bary_c); + pd_lines.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; + Ref bad; + EXPECT(device->CreateGraphicsPipelineState(&pd_lines, IID_PPV_ARGS(&bad.p)) == E_INVALIDARG && !bad.p); + + auto pd_gs = make_pso_desc(vs_persp_c, ps_bary_c); + pd_gs.GS = {gs_dummy_c.data(), gs_dummy_c.size()}; + EXPECT(device->CreateGraphicsPipelineState(&pd_gs, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + } + + // 4c. Refusal when geometryShader is not enabled on VulkanDeviceInfo -> E_NOTIMPL. + { + rt::d3d12::VulkanDeviceInfo info_no_gs = info; + info_no_gs.features.geometryShader = VK_FALSE; + ID3D12Device* inner_no_gs = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info_no_gs, IID_PPV_ARGS(&inner_no_gs)))); + Ref dev_no_gs; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner_no_gs, __uuidof(ID3D12Device), + reinterpret_cast(&dev_no_gs.p)))); + rt::d3d12::set_device_outer(inner_no_gs, dev_no_gs.p); + Ref root2; + EXPECT(SUCCEEDED(dev_no_gs->CreateRootSignature(0, root_blob.data(), root_blob.size(), + IID_PPV_ARGS(&root2.p)))); + auto pd = make_pso_desc(vs_persp_c, ps_bary_c); + pd.pRootSignature = root2.p; + Ref bad; + EXPECT(dev_no_gs->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + } + } + + std::error_code ec; + std::filesystem::remove_all(lib_dir, ec); + EXPECT(!d.validation || d.validation_errors() == 0); + return 0; +} diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 2448ab7b82..e1f79d64f4 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1215,6 +1215,40 @@ int main() { CHECK(huffman_lut_checks() == 0); + // bary_fallback_input.location: exact non-negative u32 parsed; absent or malformed values stay nullopt. + { + const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_bary_test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const std::string h0(64, 'a'), h1(64, 'b'), h2(64, 'c'), h3(64, 'd'), h4(64, 'e'); + { + std::ofstream out(dir / "index.json", std::ios::binary | std::ios::trunc); + out << "{\"ps_ok\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h0 + << "\", \"bary_fallback_input\": {\"location\": 3}},\n" + " \"ps_zero\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h1 + << "\", \"bary_fallback_input\": {\"location\": 0}},\n" + " \"ps_neg\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h2 + << "\", \"bary_fallback_input\": {\"location\": -1}},\n" + " \"ps_frac\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h3 + << "\", \"bary_fallback_input\": {\"location\": 1.5}},\n" + " \"ps_none\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h4 << "\"}}"; + } + ShaderLibrary lib; + std::string err; + CHECK(lib.load(dir, &err)); + const ShaderEntry* ok = lib.find("ps", h0); + const ShaderEntry* zero = lib.find("ps", h1); + const ShaderEntry* neg = lib.find("ps", h2); + const ShaderEntry* frac = lib.find("ps", h3); + const ShaderEntry* none = lib.find("ps", h4); + CHECK(ok && ok->bary_fallback_location.has_value() && *ok->bary_fallback_location == 3u); + CHECK(zero && zero->bary_fallback_location.has_value() && *zero->bary_fallback_location == 0u); + CHECK(neg && !neg->bary_fallback_location.has_value()); + CHECK(frac && !frac->bary_fallback_location.has_value()); + CHECK(none && !none->bary_fallback_location.has_value()); + std::filesystem::remove_all(dir); + } + std::printf("SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK\n"); return 0; } diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp new file mode 100644 index 0000000000..5e06c555bb --- /dev/null +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -0,0 +1,495 @@ +// Pure-CPU tests for runtime/src/spirv_bary_fallback.h (RT-BARY-FALLBACK-PSO): +// 1. Basic VS + PS pair: copies BuiltIn Position and pass-through vec4 Locations, emits one-hot vec3 barycentrics. +// 2. Extra unread VS outputs (including at bary_location itself): left unconsumed on VS->GS while GS->PS writes vec3. +// 3. Unexported PS Input Location: zero-filled via OpConstantNull without declaring a dangling GS Input. +// 4. VS ClipDistance[2] and CullDistance[3] forwarding (capabilities, BuiltIn arrays, no duplicate types). +// 5. Combined link_f16_halves + build_bary_fallback_gs: f16 relocation preserves bary_location and forwards relocated halves. +// 6. Clean refusals: mixed ClipDistance + CullDistance, ShaderLayer / ShaderViewportIndex, non-vec3 collision at bary_location. +// Optional `--dump-dir ` writes each synthesized GS binary for external `spirv-val` inspection. +// No GPU or game files required. +#include "../src/spirv_bary_fallback.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ +} while (0) + +namespace { + +using namespace leonida::spirv_detail; + +void append_inst(std::vector& w, std::uint16_t op, std::initializer_list args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + for (std::uint32_t a : args) w.push_back(a); +} + +void append_inst_vec(std::vector& w, std::uint16_t op, const std::vector& args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + w.insert(w.end(), args.begin(), args.end()); +} + +struct VsSpec { + std::vector raw_locs; + std::map> static_halves; + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; + std::vector extra_caps; +}; + +std::vector build_vs(const VsSpec& spec) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_null_v4 = alloc(); + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_pos = alloc(); + + std::uint32_t id_clip_len = 0, id_clip_arr = 0, id_ptr_clip = 0, id_clip_var = 0, id_null_clip = 0; + if (spec.clip_count) { + id_clip_len = alloc(); + id_clip_arr = alloc(); + id_ptr_clip = alloc(); + id_clip_var = alloc(); + id_null_clip = alloc(); + } + std::uint32_t id_cull_len = 0, id_cull_arr = 0, id_ptr_cull = 0, id_cull_var = 0, id_null_cull = 0; + if (spec.cull_count) { + id_cull_len = alloc(); + id_cull_arr = alloc(); + id_ptr_cull = alloc(); + id_cull_var = alloc(); + id_null_cull = alloc(); + } + + std::vector> out_vars; + for (std::uint32_t loc : spec.raw_locs) out_vars.push_back({alloc(), loc}); + for (const auto& [param, pair] : spec.static_halves) { + out_vars.push_back({alloc(), pair[0]}); + out_vars.push_back({alloc(), pair[1]}); + } + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + append_inst(w, kOpCapability, {1}); // Shader + if (spec.clip_count) append_inst(w, kOpCapability, {32}); + if (spec.cull_count) append_inst(w, kOpCapability, {33}); + for (std::uint32_t cap : spec.extra_caps) append_inst(w, kOpCapability, {cap}); + append_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelVertex, id_main, 0x6e69616du, 0x00000000u, id_pos}; + if (id_clip_var) ep.push_back(id_clip_var); + if (id_cull_var) ep.push_back(id_cull_var); + for (const auto& [v, loc] : out_vars) ep.push_back(v); + append_inst_vec(w, kOpEntryPoint, ep); + + append_inst(w, kOpDecorate, {id_pos, 11, 0}); // BuiltIn Position + if (id_clip_var) append_inst(w, kOpDecorate, {id_clip_var, 11, 3}); // BuiltIn ClipDistance + if (id_cull_var) append_inst(w, kOpDecorate, {id_cull_var, 11, 4}); // BuiltIn CullDistance + for (const auto& [v, loc] : out_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); + + append_inst(w, 19, {id_void}); + append_inst(w, 33, {id_fn, id_void}); + append_inst(w, kOpTypeFloat, {id_float, 32}); + append_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + append_inst(w, kOpTypeInt, {id_uint, 32, 0}); + append_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + append_inst(w, kOpConstantNull, {id_v4float, id_null_v4}); + if (spec.clip_count) { + append_inst(w, 43, {id_uint, id_clip_len, spec.clip_count}); + append_inst(w, 28, {id_clip_arr, id_float, id_clip_len}); + append_inst(w, kOpTypePointer, {id_ptr_clip, kStorageOutput, id_clip_arr}); + append_inst(w, kOpConstantNull, {id_clip_arr, id_null_clip}); + } + if (spec.cull_count) { + append_inst(w, 43, {id_uint, id_cull_len, spec.cull_count}); + append_inst(w, 28, {id_cull_arr, id_float, id_cull_len}); + append_inst(w, kOpTypePointer, {id_ptr_cull, kStorageOutput, id_cull_arr}); + append_inst(w, kOpConstantNull, {id_cull_arr, id_null_cull}); + } + + append_inst(w, kOpVariable, {id_ptr_out_v4, id_pos, kStorageOutput}); + if (id_clip_var) append_inst(w, kOpVariable, {id_ptr_clip, id_clip_var, kStorageOutput}); + if (id_cull_var) append_inst(w, kOpVariable, {id_ptr_cull, id_cull_var, kStorageOutput}); + for (const auto& [v, loc] : out_vars) append_inst(w, kOpVariable, {id_ptr_out_v4, v, kStorageOutput}); + + append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + append_inst(w, 248, {id_entry}); + append_inst(w, kOpStore, {id_pos, id_null_v4}); + if (id_clip_var) append_inst(w, kOpStore, {id_clip_var, id_null_clip}); + if (id_cull_var) append_inst(w, kOpStore, {id_cull_var, id_null_cull}); + for (const auto& [v, loc] : out_vars) append_inst(w, kOpStore, {v, id_null_v4}); + append_inst(w, kOpReturn, {}); + append_inst(w, kOpFunctionEnd, {}); + return w; +} + +std::vector build_ps(const std::vector& raw_locs, + const std::set& flat_locs, + std::optional bary_v3_loc, + const std::map>& f16_halves = {}) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v3float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_ptr_in_v3 = alloc(); + const std::uint32_t id_ptr_in_v4 = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_null_v4 = alloc(); + const std::uint32_t id_out0 = alloc(); + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_bary = bary_v3_loc ? alloc() : 0; + + std::vector> in_v4_vars; + for (std::uint32_t loc : raw_locs) in_v4_vars.push_back({alloc(), loc}); + for (const auto& [param, pair] : f16_halves) { + in_v4_vars.push_back({alloc(), pair[0]}); + in_v4_vars.push_back({alloc(), pair[1]}); + } + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + append_inst(w, kOpCapability, {1}); + append_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelFragment, id_main, 0x6e69616du, 0x00000000u, id_out0}; + if (id_bary) ep.push_back(id_bary); + for (const auto& [v, loc] : in_v4_vars) ep.push_back(v); + append_inst_vec(w, kOpEntryPoint, ep); + append_inst(w, kOpExecutionMode, {id_main, 7}); // OriginUpperLeft + + append_inst(w, kOpDecorate, {id_out0, kDecorationLocation, 0}); + if (id_bary) append_inst(w, kOpDecorate, {id_bary, kDecorationLocation, *bary_v3_loc}); + for (const auto& [v, loc] : in_v4_vars) { + append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); + if (flat_locs.count(loc)) append_inst(w, kOpDecorate, {v, 14}); // Flat + } + + append_inst(w, 19, {id_void}); + append_inst(w, 33, {id_fn, id_void}); + append_inst(w, kOpTypeFloat, {id_float, 32}); + append_inst(w, kOpTypeVector, {id_v3float, id_float, 3}); + append_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + append_inst(w, kOpTypePointer, {id_ptr_in_v3, kStorageInput, id_v3float}); + append_inst(w, kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float}); + append_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + append_inst(w, kOpConstantNull, {id_v4float, id_null_v4}); + + append_inst(w, kOpVariable, {id_ptr_out_v4, id_out0, kStorageOutput}); + if (id_bary) append_inst(w, kOpVariable, {id_ptr_in_v3, id_bary, kStorageInput}); + for (const auto& [v, loc] : in_v4_vars) append_inst(w, kOpVariable, {id_ptr_in_v4, v, kStorageInput}); + + append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + append_inst(w, 248, {id_entry}); + append_inst(w, kOpStore, {id_out0, id_null_v4}); + append_inst(w, kOpReturn, {}); + append_inst(w, kOpFunctionEnd, {}); + return w; +} + +struct GsInspection { + std::set caps; + std::set in_locs; + std::map out_loc_vec_len; // loc -> 3 or 4 + int emit_vertices = 0; + int end_primitives = 0; + bool has_in_pos = false; + bool has_out_pos = false; + std::uint32_t builtin_dist_in = 0; + std::uint32_t builtin_dist_out = 0; +}; + +bool verify_gs_module(const std::vector& words, GsInspection& out) { + Module mod; + if (!mod.parse(words)) return false; + if (mod.header[1] != 0x00010500u) return false; + out = {}; + + int section = 0; // 0=cap, 1=mem, 2=ep, 3=execmode, 4=dec, 5=types/consts/vars, 6=fn + std::set defined_ids; + std::set ep_iface; + std::set global_vars; + std::uint32_t float_ty = 0; + std::set exec_modes; + std::map vec_len; + std::map ptr_pointee; + std::map> var_info; // var_id -> (storage, pointee) + bool saw_fn_end = false; + + const auto record_def = [&](std::uint32_t id) { + return id > 0 && id < mod.header[3] && defined_ids.insert(id).second; + }; + + for (const Inst& inst : mod.insts) { + if (saw_fn_end) return false; + switch (inst.opcode) { + case kOpCapability: + if (section > 0 || inst.words.size() != 2) return false; + out.caps.insert(inst.words[1]); + break; + case kOpMemoryModel: + if (section > 1 || inst.words.size() != 3 || inst.words[1] != 0 || inst.words[2] != 1) return false; + section = 1; + break; + case kOpEntryPoint: { + if (section > 2 || inst.words.size() < 5 || inst.words[1] != 3) return false; + section = 2; + const std::size_t s = entry_point_interface_start(inst); + for (std::size_t i = s; i < inst.words.size(); ++i) ep_iface.insert(inst.words[i]); + break; + } + case kOpExecutionMode: + if (section < 2 || section > 3 || inst.words.size() < 3) return false; + if ((inst.words[2] == 0 || inst.words[2] == 26) ? (inst.words.size() != 4) : (inst.words.size() != 3)) + return false; + exec_modes.insert(inst.words[2]); + section = 3; + break; + case kOpDecorate: + if (section < 3 || section > 4) return false; + section = 4; + break; + case kOpFunction: + if (section < 5 || inst.words.size() != 5) return false; + if (!record_def(inst.words[2])) return false; + section = 6; + break; + case kOpFunctionEnd: + if (section != 6) return false; + saw_fn_end = true; + break; + default: + if (section < 6) { + if (section < 4) return false; + section = 5; + if (inst.opcode == 19 || inst.opcode == 33 || inst.opcode == kOpTypeInt || inst.opcode == kOpTypeFloat || + inst.opcode == kOpTypeVector || inst.opcode == 28 || inst.opcode == kOpTypePointer) { + if (!record_def(inst.words[1])) return false; + if (inst.opcode == kOpTypeFloat && inst.words[2] == 32) float_ty = inst.words[1]; + if (inst.opcode == kOpTypeVector && inst.words[2] == float_ty) vec_len[inst.words[1]] = inst.words[3]; + if (inst.opcode == kOpTypePointer) ptr_pointee[inst.words[1]] = inst.words[3]; + } else if (inst.opcode == 43 || inst.opcode == 44 || inst.opcode == kOpConstantNull) { + if (!record_def(inst.words[2])) return false; + } else if (inst.opcode == kOpVariable) { + if (!record_def(inst.words[2])) return false; + global_vars.insert(inst.words[2]); + var_info[inst.words[2]] = {inst.words[3], ptr_pointee[inst.words[1]]}; + } else { + return false; + } + } else { + if (inst.opcode == 248) { + if (!record_def(inst.words[1])) return false; + } else if (inst.opcode == kOpAccessChain || inst.opcode == kOpLoad) { + if (!record_def(inst.words[2])) return false; + } else if (inst.opcode == 218) { + ++out.emit_vertices; + } else if (inst.opcode == 219) { + ++out.end_primitives; + } else if (inst.opcode != kOpStore && inst.opcode != kOpReturn) { + return false; + } + } + break; + } + } + if (!saw_fn_end || !out.caps.count(2) || global_vars != ep_iface || + exec_modes != std::set{0, 22, 26, 29}) + return false; + + for (const Inst& inst : mod.insts) { + if (inst.opcode != kOpDecorate || inst.words.size() < 4) continue; + const auto vit = var_info.find(inst.words[1]); + if (vit == var_info.end()) return false; + const std::uint32_t storage = vit->second.first; + const std::uint32_t pt = vit->second.second; + if (inst.words[2] == 11) { // BuiltIn + if (inst.words[3] == 0) { + if (storage == kStorageInput) out.has_in_pos = true; + if (storage == kStorageOutput) out.has_out_pos = true; + } else if (inst.words[3] == 3 || inst.words[3] == 4) { + if (storage == kStorageInput) out.builtin_dist_in = inst.words[3]; + if (storage == kStorageOutput) out.builtin_dist_out = inst.words[3]; + } + } else if (inst.words[2] == kDecorationLocation) { + const std::uint32_t loc = inst.words[3]; + if (storage == kStorageInput) { + if (!out.in_locs.insert(loc).second) return false; + } else if (storage == kStorageOutput) { + const auto vlen = vec_len.find(pt); + if (vlen == vec_len.end()) return false; + if (!out.out_loc_vec_len.emplace(loc, vlen->second).second) return false; + } + } + } + return out.has_in_pos && out.has_out_pos && out.emit_vertices == 3 && out.end_primitives == 1; +} + +void maybe_dump(const std::filesystem::path& dump_dir, const char* name, const std::vector& words) { + if (dump_dir.empty()) return; + std::filesystem::create_directories(dump_dir); + std::ofstream f(dump_dir / (std::string(name) + ".spv"), std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); +} + +} // namespace + +int main(int argc, char** argv) { + using namespace leonida; + std::filesystem::path dump_dir; + if (argc == 3 && std::strcmp(argv[1], "--dump-dir") == 0) dump_dir = argv[2]; + + // 1. Basic VS + PS pair: bary_location = 1, pass-through Location 0 and 2. + { + const auto vs = build_vs({.raw_locs = {0, 2}}); + const auto ps = build_ps({0, 2}, {}, 1); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, &info, &err)); + CHECK(info.clip_count == 0 && info.cull_count == 0); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0, 2})); + CHECK(ins.out_loc_vec_len.size() == 3); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3 && ins.out_loc_vec_len[2] == 4); + maybe_dump(dump_dir, "gs_basic", gs); + } + + // 2. Extra unread VS outputs (including Location 1 == bary_location): left unconsumed on VS->GS. + { + const auto vs = build_vs({.raw_locs = {0, 1, 2, 3}}); + const auto ps = build_ps({0}, {}, 1); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0})); + CHECK(ins.out_loc_vec_len.size() == 2); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3); + maybe_dump(dump_dir, "gs_unread_vs", gs); + } + + // 3. Unexported PS Flat Input Location 2: zero-filled in GS without declaring a dangling GS Input. + { + const auto vs = build_vs({.raw_locs = {0}}); + const auto ps = build_ps({0, 2}, {2}, 1); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0})); + CHECK(ins.out_loc_vec_len.size() == 3); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3 && ins.out_loc_vec_len[2] == 4); + maybe_dump(dump_dir, "gs_zero_fill", gs); + } + + // 4a. ClipDistance[2] forwarding. + { + const auto vs = build_vs({.raw_locs = {0}, .clip_count = 2}); + const auto ps = build_ps({0}, {}, 1); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, &info, &err)); + CHECK(info.clip_count == 2 && info.cull_count == 0); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.caps.count(32) == 1 && !ins.caps.count(33)); + CHECK(ins.builtin_dist_in == 3 && ins.builtin_dist_out == 3); + maybe_dump(dump_dir, "gs_clip2", gs); + } + + // 4b. CullDistance[3] forwarding (dist_count == 3 shares %uint_3 cleanly). + { + const auto vs = build_vs({.raw_locs = {1}, .cull_count = 3}); + const auto ps = build_ps({1}, {}, 0); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 0, gs, &info, &err)); + CHECK(info.clip_count == 0 && info.cull_count == 3); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.caps.count(33) == 1 && !ins.caps.count(32)); + CHECK(ins.builtin_dist_in == 4 && ins.builtin_dist_out == 4); + CHECK(ins.out_loc_vec_len[0] == 3 && ins.out_loc_vec_len[1] == 4); + maybe_dump(dump_dir, "gs_cull3", gs); + } + + // 5. Combined link_f16_halves + build_bary_fallback_gs: + // 16-param VS (raw 0..15) + PS reading raw 0..13, bary_location = 14, f16_halves[7] = [15, 16] (colliding with VS 15). + { + ShaderEntry vs_e, ps_e; + ps_e.f16_halves = {{7, {15, 16}}}; + ps_e.bary_fallback_location = 14; + std::vector vs_raw, ps_raw; + for (std::uint32_t i = 0; i < 16; ++i) vs_raw.push_back(i); + for (std::uint32_t i = 0; i < 14; ++i) ps_raw.push_back(i); + + auto vs = build_vs({.raw_locs = vs_raw}); + auto ps = build_ps(ps_raw, {}, 14, ps_e.f16_halves); + std::string err; + CHECK(link_f16_halves(vs, vs_e, ps, ps_e, &err, 29)); + + std::vector gs; + CHECK(build_bary_fallback_gs(vs, ps, *ps_e.bary_fallback_location, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + // Forwarded: raw 0..13 + relocated f16 halves 28, 29 (16 vec4 inputs); unconsumed VS 14, 15 omitted; bary 14 is vec3. + CHECK(ins.in_locs.size() == 16); + CHECK(!ins.in_locs.count(14) && !ins.in_locs.count(15)); + CHECK(ins.in_locs.count(28) == 1 && ins.in_locs.count(29) == 1); + CHECK(ins.out_loc_vec_len[14] == 3); + CHECK(ins.out_loc_vec_len[28] == 4 && ins.out_loc_vec_len[29] == 4); + maybe_dump(dump_dir, "gs_f16_linked", gs); + } + + // 6. Refusals leave caller's gs_words untouched. + { + const std::vector sentinel = {0xdeadbeefu}; + std::vector gs = sentinel; + std::string err; + + // Mixed ClipDistance + CullDistance. + const auto vs_mixed = build_vs({.raw_locs = {0}, .clip_count = 1, .cull_count = 1}); + const auto ps_ok = build_ps({0}, {}, 1); + CHECK(!build_bary_fallback_gs(vs_mixed, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + + // ShaderLayer (69) and ShaderViewportIndex (70). + const auto vs_layer = build_vs({.raw_locs = {0}, .extra_caps = {69}}); + const auto vs_vp = build_vs({.raw_locs = {0}, .extra_caps = {70}}); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_layer, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_vp, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + + // bary_location colliding with a vec4 PS Input. + const auto vs_ok = build_vs({.raw_locs = {0, 1}}); + const auto ps_collide = build_ps({0, 1}, {}, std::nullopt); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_ok, ps_collide, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + } + + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index fd63fca665..85cb6871e6 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -492,6 +492,8 @@ class Device { enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source + enable.shaderClipDistance = features.features.shaderClipDistance; // d3d12_bary_fallback_test, where available + enable.shaderCullDistance = features.features.shaderCullDistance; // d3d12_bary_fallback_test, where available const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. From 83c0c68130e7b659148aa5644209552a7e3fda30 Mon Sep 17 00:00:00 2001 From: ZroFreaks <42916282+ZroIsHere@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:58:47 +0100 Subject: [PATCH 2/2] runtime: limit bary fallback inputs to used PS values --- runtime/src/spirv_bary_fallback.h | 51 +++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 01194b8b67..8f9f1e6a54 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -9,9 +9,9 @@ // triangle pass-through Geometry SPIR-V module (`tools/bary_fallback_gs.py` equivalent) in memory for the exact // `(VS, PS)` pair: // - copies `BuiltIn Position` across the triangle's 3 vertices (`Triangles` -> `OutputTriangleStrip`, 3 vertices); -// - copies every `vec4` `Location` input the PS reads (other than `bary_location`) that the VS exports, and -// zero-fills any declared PS `Location` input the VS omits without declaring a dangling GS `Input` (preserving -// `VUID-RuntimeSpirv-OpEntryPoint-08743` on both `VS -> GS` and `GS -> PS` interfaces); +// - copies each statically read `vec4` `Location` input the PS reads (other than `bary_location`) that the VS +// exports; declared but unused PS inputs are zero-filled so they keep a matching GS output without consuming GS +// input components. Inputs the VS omits are also zero-filled (preserving the stage interface); // - forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array when present (rejecting // mixed clip+cull and `ShaderLayer` / `ShaderViewportIndex`, which a pass-through helper cannot forward); // - writes `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` so perspective interpolation yields @@ -55,6 +55,9 @@ inline bool build_bary_fallback_gs(std::span vs_words, constexpr std::uint16_t kOpTypeFunction = 33; constexpr std::uint16_t kOpConstant = 43; constexpr std::uint16_t kOpConstantComposite = 44; + constexpr std::uint16_t kOpCopyObject = 83; + constexpr std::uint16_t kOpPtrAccessChain = 67; + constexpr std::uint16_t kOpInBoundsPtrAccessChain = 70; constexpr std::uint16_t kOpEmitVertex = 218; constexpr std::uint16_t kOpEndPrimitive = 219; constexpr std::uint16_t kOpLabel = 248; @@ -192,6 +195,7 @@ inline bool build_bary_fallback_gs(std::span vs_words, std::set ps_v4float_tys; std::map ps_ptr_in_pointee; std::map ps_in_var_pointee; + std::map ps_in_var_by_loc; std::vector> ps_loc_decs; std::set ps_component_targets; @@ -224,6 +228,43 @@ inline bool build_bary_fallback_gs(std::span vs_words, return fail("bary_fallback: Component-decorated PS Input at Location " + std::to_string(loc)); if (!ps_in_loc_pointee.emplace(loc, it->second).second) return fail("bary_fallback: duplicate PS Input Location " + std::to_string(loc)); + ps_in_var_by_loc.emplace(loc, target); + } + + // The translator declares every interpolant in the FSSM table, including inputs the PS never reads. They still + // need matching GS outputs, but making the GS read all of them from the VS exceeds maxGeometryInputComponents on + // devices such as RADV which reports 64. Track pointer chains rooted at PS Input variables and mark only values + // actually loaded by the PS entry point; unused locations are supplied as zero by the GS below. + std::map input_pointer_roots; + for (const auto& [var, _] : ps_in_var_pointee) input_pointer_roots.emplace(var, var); + bool in_ps_function = false; + bool roots_changed = true; + while (roots_changed) { + roots_changed = false; + in_ps_function = false; + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) in_ps_function = true; + if (!in_ps_function) continue; + if ((inst.opcode == kOpAccessChain || inst.opcode == kOpInBoundsAccessChain || + inst.opcode == kOpPtrAccessChain || inst.opcode == kOpInBoundsPtrAccessChain) && + inst.words.size() >= 4) { + const auto root = input_pointer_roots.find(inst.words[3]); + if (root != input_pointer_roots.end()) + roots_changed |= input_pointer_roots.emplace(inst.words[2], root->second).second; + } else if (inst.opcode == kOpCopyObject && inst.words.size() >= 4) { + const auto root = input_pointer_roots.find(inst.words[3]); + if (root != input_pointer_roots.end()) + roots_changed |= input_pointer_roots.emplace(inst.words[2], root->second).second; + } + } + } + std::set statically_read_ps_inputs; + in_ps_function = false; + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) in_ps_function = true; + if (!in_ps_function || inst.opcode != kOpLoad || inst.words.size() < 4) continue; + if (const auto root = input_pointer_roots.find(inst.words[3]); root != input_pointer_roots.end()) + statically_read_ps_inputs.insert(root->second); } if (const auto bary_it = ps_in_loc_pointee.find(bary_location); @@ -240,6 +281,10 @@ inline bool build_bary_fallback_gs(std::span vs_words, if (!ps_v4float_tys.count(pt_ty)) return fail("bary_fallback: PS pass-through Input at Location " + std::to_string(loc) + " is not vec4"); pass_locs.push_back(loc); + if (!statically_read_ps_inputs.count(ps_in_var_by_loc.at(loc))) { + zero_loc_set.insert(loc); + continue; + } const auto vs_it = vs_out_loc_pointee.find(loc); if (vs_it != vs_out_loc_pointee.end()) { if (!vs_v4float_tys.count(vs_it->second))