From 53df7d1aee7c5fc53ee97a9ff320faa2aa7d13b2 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 | 100 +++- 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, 1747 insertions(+), 10 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 10ee582b12..205b374262 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1457,6 +1457,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) @@ -3303,6 +3305,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 1fb36401e3..a05dc3e29a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -63,6 +63,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/console_heap_vsharp_slots.h" @@ -2336,6 +2337,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; @@ -10981,6 +10983,32 @@ 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); } @@ -10988,12 +11016,13 @@ class PipelineState final (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, - &link_error)) { + &link_error, bary_fallback)) { 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(); @@ -11048,8 +11077,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(); } @@ -11082,6 +11111,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; @@ -12102,9 +12165,10 @@ class PipelineState final bool link_f16_halves(std::vector& vs_words, const leonida::ShaderEntry& vs_entry, std::vector& ps_words, const leonida::ShaderEntry& ps_entry, - std::string* error) const { - return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, - device_.f16_half_top_location); + std::string* error, bool bary_fallback = false) const { + const std::uint32_t top_loc = + bary_fallback ? device_.bary_f16_half_top_location : device_.f16_half_top_location; + return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, top_loc); } public: @@ -12137,7 +12201,8 @@ class PipelineState final } if (f16_linked_) { if (vs == SIZE_MAX || ps == SIZE_MAX || - !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) + !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why, + bary_fallback_)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -12150,6 +12215,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 { @@ -12181,7 +12252,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 @@ -12194,8 +12265,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 @@ -13507,6 +13579,14 @@ class Device final ? info.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 (info.f16_half_top_location == 0 && + 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 7699dfbb0d..b6a88e93cf 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; @@ -1301,6 +1304,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 ee49c48ebb..f6a9f60943 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1289,6 +1289,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 eb1be0a2c9..d02fe268d7 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -497,6 +497,8 @@ class Device { enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source enable.depthBounds = features.features.depthBounds; // depth-bounds PSOs (d3d12_mesh_test), where available + 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 79a24375f8e7e84d2e59550e3191f9464e01d493 Mon Sep 17 00:00:00 2001 From: robot00f Date: Wed, 25 Nov 2026 01:09:48 -0300 Subject: [PATCH 2/2] vk_pipeline_check: synthesize --bary-fallback GS stage for PS pipelines When `tools/rdna2spirv.py --bary-fallback` translates a pixel shader (for GPUs without `VK_KHR_fragment_shader_barycentric` or drivers with broken `BaryCoordKHR`), the emitted Fragment SPIR-V reads perspective barycentrics from an ordinary smooth `vec3` `Input` recorded under `"bary_fallback_input": {"location": N}` in `index.json`, while `"inputs"` lists only the `vec4` user `param` locations exported by `stubs/vs_.spv`. Previously `vk_pipeline_check` ignored `"bary_fallback_input"` and built a 2-stage `VS_stub + PS` pipeline, leaving `Location N` unwritten by the preceding stage (`VUID-RuntimeSpirv-OpEntryPoint-08743`), omitting the `geometryShader` / `shaderClipDistance` / `shaderCullDistance` feature gates, and writing a 2-stage entry into `pipeline_cache.bin` that misses the runtime's 3-stage `VS + GS + PS` pipeline key. - Parse `"bary_fallback_input"` in `vk_pipeline_check`'s `JsonParser` into `ShaderMeta::bary_fallback_location` (accepting `null` or an object with an unsigned 32-bit `"location" < 32`, rejecting non-objects, missing `"location"`, and out-of-range locations with exit code 2 before loading Vulkan). - Cache each loaded partner stub's SPIR-V words alongside its `VkShaderModule` in `stub_cache` without re-reading disk per shader. - Skip `--bary-fallback` `ps` entries with `no geometryShader` when the selected device lacks `geometryShader`; otherwise synthesize the triangle pass-through `VK_SHADER_STAGE_GEOMETRY_BIT` module in memory via `leonida::build_bary_fallback_gs` (`runtime/src/spirv_bary_fallback.h`), gate forwarded VS `ClipDistance` / `CullDistance` on `shaderClipDistance` / `shaderCullDistance` before creating the GS module, compile the 3-stage `VS + GS + PS` graphics pipeline, and fail the check (`PIPELINE FAIL`, exit 1) if `build_bary_fallback_gs` rejects an incompatible `VS`/`PS` interface. - Add CTest `vk_pipeline_check_bary_fallback` (`runtime/test/check_vk_pipeline_bary_fallback.py`), index parser cases in `tests/test_vk_pipeline_check_index.py`, and documentation in `docs/pipeline_check.md`. Depends on: #1497 Claim: https://github.com/ubiquitarianism/leonida/issues/14#issuecomment-7152197322 AI-assisted: yes (Antigravity) --- docs/pipeline_check.md | 15 +- runtime/CMakeLists.txt | 6 + .../test/check_vk_pipeline_bary_fallback.py | 524 ++++++++++++++++++ runtime/test/vk_pipeline_check.cpp | 124 ++++- tests/test_vk_pipeline_check_index.py | 15 + 5 files changed, 666 insertions(+), 18 deletions(-) create mode 100644 runtime/test/check_vk_pipeline_bary_fallback.py diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 4d5be5e352..6e028481a7 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -1,10 +1,17 @@ # GPU pipeline corpus check `runtime/test/vk_pipeline_check.cpp` creates a `VkShaderModule` for every entry in the translator's -`index.json` and, for compute shaders, a real compute pipeline with the runtime's descriptor and push -constant contract. It is a driver-level check: it proves the modules and pipelines are accepted by -the Vulkan implementation, not that the shader results are correct. Value-level checks are in -`docs/shader_validation.md`. +`index.json` and builds a Vulkan pipeline with the runtime's descriptor and push-constant contract: +compute pipelines for `cs` entries, and dynamic-rendering graphics pipelines paired with minimal partner +stubs from `/stubs/` (`tools/spirv_stubs.py`) for `vs`, `ps`, `ms` and `gs` entries. When a +pixel shader carries `"bary_fallback_input": {"location": N}` (`tools/rdna2spirv.py --bary-fallback`, for +GPUs without `VK_KHR_fragment_shader_barycentric`), the checker synthesizes the triangle pass-through +geometry shader in memory (`runtime/src/spirv_bary_fallback.h`) and checks the three-stage `VS + GS + PS` +pipeline, skipping with `no geometryShader` (or `no shaderClipDistance` / `no shaderCullDistance` when +the partner VS exports clip or cull distances) if the device lacks the required feature, and counting an +incompatible `VS`/`PS` interface as a pipeline failure. It is a driver-level check: it proves the modules +and pipelines are accepted by the Vulkan implementation, not that the shader results are correct. +Value-level checks are in `docs/shader_validation.md`. Timing and memory figures in this page were measured with `MESA_SHADER_CACHE_DISABLE=true`. Without it, RADV's on-disk shader cache (`~/.cache/mesa_shader_cache`, about 1.1 GB after a full corpus run) turns a repeated module diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 205b374262..45cd345514 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1999,6 +1999,12 @@ if(TARGET Vulkan::Headers) "-DWANT=${LEONIDA_PIPELINE_CHECK_STACK}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") endif() + if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME vk_pipeline_check_bary_fallback COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_bary_fallback.py" + --ctest --exe "$") + set_tests_properties(vk_pipeline_check_bary_fallback PROPERTIES SKIP_RETURN_CODE 77) + endif() add_test(NAME depth24_convert COMMAND depth24_convert_test) set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). diff --git a/runtime/test/check_vk_pipeline_bary_fallback.py b/runtime/test/check_vk_pipeline_bary_fallback.py new file mode 100644 index 0000000000..52af220ce6 --- /dev/null +++ b/runtime/test/check_vk_pipeline_bary_fallback.py @@ -0,0 +1,524 @@ +"""vk_pipeline_check: --bary-fallback pixel shaders ("bary_fallback_input") compile as VS + synthesized GS + PS. + +No game data: tiny synthetic SPIR-V modules are built in pure Python (tools/spirv_asm.py and tools/spirv_stubs.py, +stdlib only, no external llvm-mc or spirv-as required). Checks that vk_pipeline_check: + - validates "bary_fallback_input" in index.json before loading Vulkan (rejecting non-object/non-null values, missing + "location", negative/fractional/overflow values, and location >= 32 with exit code 2); + - synthesizes the triangle pass-through Geometry stage (runtime/src/spirv_bary_fallback.h) for a "ps" entry carrying + "bary_fallback_input": {"location": N} paired with stubs/vs_.spv, compiles the 3-stage VS + GS + PS + graphics pipeline, writes a non-empty pipeline cache, and hits/reports cleanly on a seeded --cache-feedback run + (or skips with "no geometryShader" on a device proven to lack geometryShader, such as MoltenVK); + - handles unexported PS vec4 inputs (zero-filled by the synthesized GS) and VS ClipDistance forwarding; + - fails with exit code 1 (PIPELINE FAIL, never silently skipping or exiting 0) when build_bary_fallback_gs rejects + a broken VS/PS interface (such as a vec4 PS input colliding with bary_fallback_input.location), both directly and + under --isolate. + +Skips GPU tests when vk_pipeline_check is not built or no usable Vulkan device is present (exits 77 with --ctest when +all tests skip). +""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(ROOT / "tools")) +from spirv_asm import assemble # noqa: E402 +from spirv_stubs import build_ps_stub, build_vs_stub, generate_for_index # noqa: E402 + +WINDOWS = os.name == "nt" +EXE_OVERRIDE: str | None = None + +PLAIN_CS_ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +%entry = OpLabel +OpReturn +OpFunctionEnd +""" + +# Minimal --bary-fallback PS: reads vec4 attr0 at Location 0 and vec3 barycentrics at Location 1, writes Location 0. +BARY_PS_ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %in_attr0 %in_bary %out_col +OpExecutionMode %main OriginUpperLeft +OpDecorate %in_attr0 Location 0 +OpDecorate %in_bary Location 1 +OpDecorate %out_col Location 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%float = OpTypeFloat 32 +%v3float = OpTypeVector %float 3 +%v4float = OpTypeVector %float 4 +%ptr_in_v4 = OpTypePointer Input %v4float +%ptr_in_v3 = OpTypePointer Input %v3float +%ptr_out_v4 = OpTypePointer Output %v4float +%f0 = OpConstant %float 0 +%in_attr0 = OpVariable %ptr_in_v4 Input +%in_bary = OpVariable %ptr_in_v3 Input +%out_col = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +%entry = OpLabel +%a = OpLoad %v4float %in_attr0 +%b = OpLoad %v3float %in_bary +%bx = OpCompositeExtract %float %b 0 +%by = OpCompositeExtract %float %b 1 +%bz = OpCompositeExtract %float %b 2 +%b4 = OpCompositeConstruct %v4float %bx %by %bz %f0 +%sum = OpFAdd %v4float %a %b4 +OpStore %out_col %sum +OpReturn +OpFunctionEnd +""" + +# --bary-fallback PS that also declares vec4 at Location 2 (omitted by vs_0.spv so GS zero-fills it) and vec3 at Location 3. +BARY_PS_ZEROFILL_ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %in_attr0 %in_unwritten %in_bary %out_col +OpExecutionMode %main OriginUpperLeft +OpDecorate %in_attr0 Location 0 +OpDecorate %in_unwritten Location 2 +OpDecorate %in_bary Location 3 +OpDecorate %out_col Location 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%float = OpTypeFloat 32 +%v3float = OpTypeVector %float 3 +%v4float = OpTypeVector %float 4 +%ptr_in_v4 = OpTypePointer Input %v4float +%ptr_in_v3 = OpTypePointer Input %v3float +%ptr_out_v4 = OpTypePointer Output %v4float +%f0 = OpConstant %float 0 +%in_attr0 = OpVariable %ptr_in_v4 Input +%in_unwritten = OpVariable %ptr_in_v4 Input +%in_bary = OpVariable %ptr_in_v3 Input +%out_col = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +%entry = OpLabel +%a = OpLoad %v4float %in_attr0 +%u = OpLoad %v4float %in_unwritten +%b = OpLoad %v3float %in_bary +%bx = OpCompositeExtract %float %b 0 +%by = OpCompositeExtract %float %b 1 +%bz = OpCompositeExtract %float %b 2 +%b4 = OpCompositeConstruct %v4float %bx %by %bz %f0 +%s0 = OpFAdd %v4float %a %u +%sum = OpFAdd %v4float %s0 %b4 +OpStore %out_col %sum +OpReturn +OpFunctionEnd +""" + +# Partner VS exporting Position, BuiltIn ClipDistance[2], and Location 0 (exercises GS ClipDistance forwarding). +VS_CLIP2_ASM = """OpCapability Shader +OpCapability ClipDistance +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %main "main" %out_pos %out_clip %out_attr0 +OpDecorate %out_pos BuiltIn Position +OpDecorate %out_clip BuiltIn ClipDistance +OpDecorate %out_attr0 Location 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%u2 = OpConstant %uint 2 +%arr_clip = OpTypeArray %float %u2 +%ptr_out_v4 = OpTypePointer Output %v4float +%ptr_out_clip = OpTypePointer Output %arr_clip +%f0 = OpConstant %float 0 +%f1 = OpConstant %float 1 +%pos_val = OpConstantComposite %v4float %f0 %f0 %f0 %f1 +%zero_v4 = OpConstantComposite %v4float %f0 %f0 %f0 %f0 +%zero_clip = OpConstantComposite %arr_clip %f0 %f0 +%out_pos = OpVariable %ptr_out_v4 Output +%out_clip = OpVariable %ptr_out_clip Output +%out_attr0 = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +%entry = OpLabel +OpStore %out_pos %pos_val +OpStore %out_clip %zero_clip +OpStore %out_attr0 %zero_v4 +OpReturn +OpFunctionEnd +""" + +# Valid standalone Fragment SPIR-V whose Location 1 is vec4 instead of vec3 (collides with bary_fallback_input at 1). +BROKEN_BARY_VEC4_PS_ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %in_attr0 %in_bad_bary %out_col +OpExecutionMode %main OriginUpperLeft +OpDecorate %in_attr0 Location 0 +OpDecorate %in_bad_bary Location 1 +OpDecorate %out_col Location 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%ptr_in_v4 = OpTypePointer Input %v4float +%ptr_out_v4 = OpTypePointer Output %v4float +%in_attr0 = OpVariable %ptr_in_v4 Input +%in_bad_bary = OpVariable %ptr_in_v4 Input +%out_col = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +%entry = OpLabel +%a = OpLoad %v4float %in_attr0 +%b = OpLoad %v4float %in_bad_bary +%sum = OpFAdd %v4float %a %b +OpStore %out_col %sum +OpReturn +OpFunctionEnd +""" + +# Minimal Geometry shader used only as an independent oracle for whether the selected GPU supports geometryShader. +GS_PROBE_ASM = """OpCapability Geometry +OpMemoryModel Logical GLSL450 +OpEntryPoint Geometry %main "main" %in_pos %out_pos +OpExecutionMode %main Triangles +OpExecutionMode %main Invocations 1 +OpExecutionMode %main OutputTriangleStrip +OpExecutionMode %main OutputVertices 3 +OpDecorate %in_pos BuiltIn Position +OpDecorate %out_pos BuiltIn Position +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%int = OpTypeInt 32 1 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%u3 = OpConstant %uint 3 +%arr = OpTypeArray %v4float %u3 +%ptr_in_arr = OpTypePointer Input %arr +%ptr_in_v4 = OpTypePointer Input %v4float +%ptr_out_v4 = OpTypePointer Output %v4float +%i0 = OpConstant %int 0 +%in_pos = OpVariable %ptr_in_arr Input +%out_pos = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +%entry = OpLabel +%p = OpAccessChain %ptr_in_v4 %in_pos %i0 +%v = OpLoad %v4float %p +OpStore %out_pos %v +OpEmitVertex +OpStore %out_pos %v +OpEmitVertex +OpStore %out_pos %v +OpEmitVertex +OpEndPrimitive +OpReturn +OpFunctionEnd +""" + + +def find_binary() -> Path | None: + env = EXE_OVERRIDE or os.environ.get("LEONIDA_VK_PIPELINE_CHECK") + if env: + return Path(env) if Path(env).is_file() else None + build = ROOT / "runtime" / "build" + paths = ( + (build / "vk_pipeline_check.exe", build / "RelWithDebInfo" / "vk_pipeline_check.exe", + build / "Release" / "vk_pipeline_check.exe") + if WINDOWS + else (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check") + ) + for p in paths: + if p.is_file(): + return p + return None + + +def run_checker(exe: Path, spirv_dir: Path, args: list[str] | None = None) -> subprocess.CompletedProcess: + env = dict(os.environ) + env.pop("VK_PIPELINE_CHECK_SIMULATE_CRASH", None) + env.setdefault("VK_LOADER_LAYERS_DISABLE", "~implicit~") + cmd = [str(exe), str(spirv_dir), *(args or [])] + return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120) + + +class BaryFallbackIndexValidationTest(unittest.TestCase): + """Runs without a Vulkan GPU: index.json is validated before Vulkan is loaded.""" + + @classmethod + def setUpClass(cls): + cls.exe = find_binary() + if cls.exe is None: + raise unittest.SkipTest("vk_pipeline_check isn't built (set LEONIDA_VK_PIPELINE_CHECK to its path)") + + def test_invalid_bary_fallback_input_rejected_at_index_parse(self): + invalid_cases = ( + ('"bad"', "expected object for bary_fallback_input"), + ("123", "expected object for bary_fallback_input"), + ("true", "expected object for bary_fallback_input"), + ("[]", "expected object for bary_fallback_input"), + ("{}", "missing bary_fallback_input.location"), + ('{"other": 1}', "missing bary_fallback_input.location"), + ('{"location": 32}', "bary_fallback_input.location must be < 32"), + ('{"location": 99}', "bary_fallback_input.location must be < 32"), + ('{"location": -1}', "expected unsigned 32-bit bary_fallback_input.location"), + ('{"location": 1.5}', "expected unsigned 32-bit bary_fallback_input.location"), + ('{"location": "1"}', "expected unsigned 32-bit bary_fallback_input.location"), + ('{"location": 4294967296}', "expected unsigned 32-bit bary_fallback_input.location"), + ) + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + for raw_value, expected_msg in invalid_cases: + with self.subTest(bary_fallback_input=raw_value): + (d / "index.json").write_text( + f'{{"ps_bad":{{"stage":"ps","bary_fallback_input":{raw_value}}}}}\n', + encoding="utf-8", + newline="\n", + ) + r = run_checker(self.exe, d) + self.assertEqual(r.returncode, 2, r.stdout + r.stderr) + self.assertIn("malformed JSON", r.stderr) + self.assertIn("index.json", r.stderr) + self.assertIn(expected_msg, r.stderr) + + def test_null_and_unknown_keys_in_bary_fallback_input_parse_cleanly(self): + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + # --count 0 exits after parsing index.json + opening/skipping 0 shaders, or fails at Vulkan init if no GPU, + # but never reports a malformed JSON error on index.json. + for raw_value in ("null", '{"extra": [1, 2], "location": 31}'): + with self.subTest(bary_fallback_input=raw_value): + (d / "index.json").write_text( + f'{{"ps_ok":{{"stage":"ps","bary_fallback_input":{raw_value}}}}}\n', + encoding="utf-8", + newline="\n", + ) + r = run_checker(self.exe, d, ["--count", "0"]) + self.assertNotEqual(r.returncode, 2, r.stderr) + self.assertNotIn("malformed JSON", r.stderr) + self.assertIn("1 shaders in index", r.stderr) + + +class BaryFallbackPipelineCheckTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.exe = find_binary() + if cls.exe is None: + raise unittest.SkipTest("vk_pipeline_check isn't built (set LEONIDA_VK_PIPELINE_CHECK to its path)") + cls.tmp = tempfile.TemporaryDirectory() + cls.addClassCleanup(cls.tmp.cleanup) + + probe_dir = Path(cls.tmp.name) / "probe" + probe_dir.mkdir() + (probe_dir / "c_probe.spv").write_bytes(assemble(PLAIN_CS_ASM, target_env="vulkan1.2")) + (probe_dir / "gs_probe.spv").write_bytes(assemble(GS_PROBE_ASM, target_env="vulkan1.2")) + stubs_dir = probe_dir / "stubs" + stubs_dir.mkdir() + (stubs_dir / "vs_empty.spv").write_bytes(build_vs_stub(())) + (stubs_dir / "ps_empty.spv").write_bytes(build_ps_stub(())) + (probe_dir / "index.json").write_text( + json.dumps( + { + "c_probe": {"stage": "cs", "subgroup_size": None, "features": []}, + "gs_probe": { + "stage": "gs", + "features": ["geometryShader"], + "gs_input_locations": [], + "gs_output_locations": [], + "subgroup_size": None, + }, + } + ), + encoding="utf-8", + newline="\n", + ) + probe = cls._exec(probe_dir, ["--compute-only"]) + if probe.returncode != 0 or "cs pipelines: 1 ok, 0 failed" not in probe.stdout: + raise unittest.SkipTest( + f"no usable Vulkan device (exit {probe.returncode}): {probe.stderr.strip()[-300:]}" + ) + gs_probe = cls._exec(probe_dir, ["--graphics-only"]) + cls.has_geometry_shader = "gs pipelines: 1 ok, 0 failed, 0 skipped" in gs_probe.stdout + + @classmethod + def _exec(cls, spirv_dir: Path, args: list[str]) -> subprocess.CompletedProcess: + return run_checker(cls.exe, spirv_dir, ["--jobs", "2", *args]) + + def make_corpus( + self, + name: str, + entries: dict, + files: dict[str, bytes], + stubs: dict[str, bytes] | None = None, + auto_stubs: bool = False, + ) -> Path: + d = Path(self.tmp.name) / name + d.mkdir() + for fname, data in files.items(): + (d / fname).write_bytes(data) + (d / "index.json").write_text(json.dumps(entries, indent=2) + "\n", encoding="utf-8", newline="\n") + if auto_stubs: + generate_for_index(str(d), entries) + if stubs: + sd = d / "stubs" + sd.mkdir(exist_ok=True) + for fname, data in stubs.items(): + (sd / fname).write_bytes(data) + return d + + def test_synthetic_modules_validate_with_spirv_val(self): + spirv_val = shutil.which("spirv-val") + if not spirv_val: + self.skipTest("spirv-val not on PATH") + for label, text in ( + ("bary_ps", BARY_PS_ASM), + ("bary_ps_zerofill", BARY_PS_ZEROFILL_ASM), + ("vs_clip2", VS_CLIP2_ASM), + ("broken_bary_vec4_ps", BROKEN_BARY_VEC4_PS_ASM), + ("gs_probe", GS_PROBE_ASM), + ): + spv = Path(self.tmp.name) / f"{label}.spv" + spv.write_bytes(assemble(text, target_env="vulkan1.2")) + r = subprocess.run([spirv_val, "--target-env", "vulkan1.2", str(spv)], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, f"{label}: {r.stdout}{r.stderr}") + + def test_valid_bary_fallback_ps_compiles_with_synthesized_gs_and_writes_cache(self): + ps_spv = assemble(BARY_PS_ASM, target_env="vulkan1.2") + entries = { + "ps_bary": { + "stage": "ps", + "bindings": [], + "features": [], + "inputs": [0], + "outputs": [0], + "bary_fallback_input": {"location": 1}, + "push_constant_bytes": 144, + "subgroup_size": 32, + "wave64": False, + } + } + # generate_for_index writes stubs/vs_0.spv exporting ONLY BuiltIn Position + Location 0 (NOT Location 1). + corpus = self.make_corpus("valid_bary", entries, {"ps_bary.spv": ps_spv}, auto_stubs=True) + self.assertTrue((corpus / "stubs" / "vs_0.spv").is_file()) + + cache_file = corpus / "pipeline_cache.bin" + r = self._exec(corpus, [str(cache_file), "--cache-feedback"]) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("ps: 1 modules ok, 0 failed", r.stdout) + + if not self.has_geometry_shader: + self.assertIn("SKIPPED ps_bary (no geometryShader)", r.stdout) + self.assertIn("ps pipelines: 0 ok, 0 failed, 1 skipped", r.stdout) + return + + self.assertNotIn("SKIPPED", r.stdout) + self.assertNotIn("PIPELINE FAIL", r.stdout) + self.assertIn("ps pipelines: 1 ok, 0 failed, 0 skipped", r.stdout) + self.assertTrue(cache_file.is_file(), "expected pipeline_cache.bin to be written") + self.assertGreater(cache_file.stat().st_size, 0) + + # Second run seeded with cache_file and --isolate also compiles 1 ok, 0 failed, 0 skipped. + r_seeded = self._exec(corpus, [str(cache_file), "--cache-feedback"]) + self.assertEqual(r_seeded.returncode, 0, r_seeded.stdout + r_seeded.stderr) + self.assertIn("ps pipelines: 1 ok, 0 failed, 0 skipped", r_seeded.stdout) + + r_iso = self._exec(corpus, [str(cache_file), "--isolate", "--isolate-batch", "1"]) + self.assertEqual(r_iso.returncode, 0, r_iso.stdout + r_iso.stderr) + self.assertIn("ps: 1 modules ok, 0 failed", r_iso.stdout) + self.assertIn("ps pipelines: 1 ok, 0 failed, 0 skipped", r_iso.stdout) + + def test_bary_fallback_clip_distance_forwarding_and_unexported_ps_input_zerofill(self): + if not self.has_geometry_shader: + self.skipTest("device has no geometryShader") + ps_spv = assemble(BARY_PS_ZEROFILL_ASM, target_env="vulkan1.2") + vs_clip_spv = assemble(VS_CLIP2_ASM, target_env="vulkan1.2") + entries = { + "ps_bary_clip": { + "stage": "ps", + "bindings": [], + "features": [], + "inputs": [0], + "outputs": [0], + "bary_fallback_input": {"location": 3}, + "push_constant_bytes": 144, + "subgroup_size": 32, + "wave64": False, + } + } + corpus = self.make_corpus( + "clip_and_zerofill", + entries, + {"ps_bary_clip.spv": ps_spv}, + stubs={"vs_0.spv": vs_clip_spv}, + ) + r = self._exec(corpus, []) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("ps: 1 modules ok, 0 failed", r.stdout) + self.assertTrue( + "ps pipelines: 1 ok, 0 failed, 0 skipped" in r.stdout + or "SKIPPED ps_bary_clip (no shaderClipDistance)" in r.stdout, + r.stdout + r.stderr, + ) + + def test_broken_bary_fallback_interface_fails_pipeline_check(self): + if not self.has_geometry_shader: + self.skipTest("device has no geometryShader") + bad_ps_spv = assemble(BROKEN_BARY_VEC4_PS_ASM, target_env="vulkan1.2") + entries = { + "ps_bad_bary": { + "stage": "ps", + "bindings": [], + "features": [], + "inputs": [0], + "outputs": [0], + "bary_fallback_input": {"location": 1}, + "push_constant_bytes": 144, + "subgroup_size": 32, + "wave64": False, + } + } + corpus = self.make_corpus("broken_bary", entries, {"ps_bad_bary.spv": bad_ps_spv}, auto_stubs=True) + + r = self._exec(corpus, []) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("ps: 1 modules ok, 0 failed", r.stdout) + self.assertIn("PIPELINE FAIL ps_bad_bary", r.stdout) + self.assertIn("ps pipelines: 0 ok, 1 failed, 0 skipped", r.stdout) + self.assertIn("bary_fallback: bary_location 1 collides with a non-vec3 PS Input", r.stderr) + + # --isolate must also fail with exit code 1 rather than dropping the GS synthesis failure. + r_iso = self._exec(corpus, ["--isolate", "--isolate-batch", "1"]) + self.assertEqual(r_iso.returncode, 1, r_iso.stdout + r_iso.stderr) + self.assertIn("PIPELINE FAIL ps_bad_bary", r_iso.stdout) + self.assertIn("ps pipelines: 0 ok, 1 failed, 0 skipped", r_iso.stdout) + + +def main(argv=None): + global EXE_OVERRIDE + raw = list(sys.argv) if argv is None else list(argv) + ctest_mode = False + cleaned = [raw[0]] + i = 1 + while i < len(raw): + if raw[i] == "--ctest": + ctest_mode = True + i += 1 + elif raw[i] == "--exe" and i + 1 < len(raw): + EXE_OVERRIDE = raw[i + 1] + i += 2 + else: + cleaned.append(raw[i]) + i += 1 + result = unittest.main(argv=cleaned, exit=False).result + if result.failures or result.errors or result.unexpectedSuccesses: + return 1 + if result.testsRun == 0 and not result.skipped: + return 1 + if ctest_mode and result.testsRun == len(result.skipped): + return 77 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 3ff89524fc..f4ad5cb008 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -6,7 +6,8 @@ // - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for // descriptor-free shaders with the standard push-constant range // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) -// paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py) +// paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py); --bary-fallback +// ps entries (bary_fallback_input) synthesize the pass-through GS stage in memory (VS + GS + PS) // VK_EXT_mesh_shader (with meshShaderQueries), VK_KHR_maintenance8 and VK_EXT_transform_feedback are always enabled // when supported so the saved pipeline cache matches the runtime's device key; other optional device extensions are // enabled only when needed by the selected shaders. Shaders whose required features or partner stubs are unavailable @@ -56,6 +57,7 @@ #include "pipeline_cache_snapshot.h" #include "large_module_gate.h" #include "pipeline_summary.h" +#include "../src/spirv_bary_fallback.h" #include "../src/spirv_words.h" #include "../src/subgroup_size.h" #include "../src/vulkan_bindless.h" @@ -81,6 +83,7 @@ #include #include #include +#include #include #include #include @@ -128,6 +131,7 @@ struct ShaderMeta { bool has_gs_input_locations = false; bool has_gs_output_locations = false; std::vector vertex_inputs; + std::optional bary_fallback_location; }; // Minimal recursive-descent JSON reader for index.json (handles strings, numbers, bools, arrays, objects). @@ -318,6 +322,41 @@ struct JsonParser { if (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E')) { fail(what); return 0u; } return v; } + std::optional parse_bary_fallback_input() { + ws(); + if (s.compare(i, 4, "null") == 0 && + (i + 4 == s.size() || s[i + 4] == ',' || s[i + 4] == '}' || s[i + 4] == ']' || + std::isspace(static_cast(s[i + 4])))) { + i += 4; + return std::nullopt; + } + if (!consume('{')) { fail("expected object for bary_fallback_input"); return std::nullopt; } + uint32_t location = 0; + bool has_location = false; + bool closed = false; + while (!error && i < s.size()) { + if (consume('}')) { closed = true; break; } + const size_t before = i; + std::string k = parse_string(); + if (error) return std::nullopt; + if (!consume(':')) { fail("expected ':' in bary_fallback_input"); return std::nullopt; } + if (k == "location") { + location = parse_strict_u32("expected unsigned 32-bit bary_fallback_input.location"); + if (error) return std::nullopt; + if (location >= 32) { fail("bary_fallback_input.location must be < 32"); return std::nullopt; } + has_location = true; + } else { + skip_value(); + } + if (error) return std::nullopt; + if (consume('}')) { closed = true; break; } + if (!consume(',') || i == before) { fail("expected ',' or '}' in bary_fallback_input"); return std::nullopt; } + } + if (error) return std::nullopt; + if (!closed) { fail("unterminated bary_fallback_input object"); return std::nullopt; } + if (!has_location) { fail("missing bary_fallback_input.location"); return std::nullopt; } + return location; + } uint32_t parse_pc_tail_bytes() { ws(); if (s.compare(i, 4, "null") == 0) { i += 4; return 0u; } @@ -382,6 +421,7 @@ struct JsonParser { else if (k == "features") m.features = parse_str_array(); else if (k == "float_controls") m.float_controls = parse_str_array(); else if (k == "inputs") m.inputs = parse_u32_array(); + else if (k == "bary_fallback_input") m.bary_fallback_location = parse_bary_fallback_input(); else if (k == "outputs") m.outputs = parse_u32_array(); else if (k == "params") m.params = parse_u32_array(); else if (k == "gs_inputs") m.gs_inputs = parse_u32_array(); @@ -1316,6 +1356,8 @@ int main(int argc, char** argv) { if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering"; if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader"; + if (meta.stage == "ps" && meta.bary_fallback_location.has_value() && !f2.features.geometryShader) + return "no geometryShader"; if (meta.needs_maintenance8) { #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (!(ext_m8 && m8.maintenance8)) return "no VK_KHR_maintenance8"; @@ -1493,7 +1535,11 @@ int main(int argc, char** argv) { } std::map modules_ok, modules_bad, big_skipped; std::map stats; - std::map stub_cache; + struct StubEntry { + VkShaderModule mod = VK_NULL_HANDLE; + std::vector words; + }; + std::map stub_cache; std::atomic next{0}, done{0}; std::atomic total_pipes_done{0}; // What each worker is doing in the driver: creating the shader module, then creating its pipeline. @@ -1521,26 +1567,32 @@ int main(int argc, char** argv) { const auto t_start = std::chrono::steady_clock::now(); auto elapsed = [&] { return std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); }; - auto load_stub = [&](const std::string& fname) -> VkShaderModule { + auto load_stub_entry = [&](const std::string& fname) -> const StubEntry& { { std::lock_guard g(mu); auto it = stub_cache.find(fname); if (it != stub_cache.end()) return it->second; } std::ifstream f(dir + "/stubs/" + fname, std::ios::binary | std::ios::ate); - const auto code = leonida::read_spirv_words(f, f.tellg()); + auto words = leonida::read_spirv_words(f, f.tellg()); VkShaderModule mod = VK_NULL_HANDLE; - if (!code.empty()) { + if (!words.empty()) { VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * sizeof(code.front()); - smi.pCode = code.data(); - if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE; + smi.codeSize = words.size() * sizeof(words.front()); + smi.pCode = words.data(); + if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) { + mod = VK_NULL_HANDLE; + words.clear(); + } } std::lock_guard g(mu); - auto [it, inserted] = stub_cache.emplace(fname, mod); + auto [it, inserted] = stub_cache.emplace(fname, StubEntry{mod, std::move(words)}); if (!inserted && mod) vkDestroyShaderModule(dev, mod, nullptr); return it->second; }; + auto load_stub = [&](const std::string& fname) -> VkShaderModule { + return load_stub_entry(fname).mod; + }; auto record_skip = [&](const std::string& name, const std::string& stage, const std::string& reason) { std::lock_guard g(mu); @@ -1766,24 +1818,67 @@ int main(int argc, char** argv) { }; std::string skip_reason; + bool pipe_failed = false; + VkShaderModule gs_mod = VK_NULL_HANDLE; std::vector color_formats; VkFormat depth_format = VK_FORMAT_UNDEFINED; bool use_vertex_input = true; if (stage == "ps") { std::string vs_fn = stub_filename("vs", meta.inputs); - VkShaderModule vs_mod = load_stub(vs_fn); - if (!vs_mod) { + const StubEntry& vs_stub = load_stub_entry(vs_fn); + if (!vs_stub.mod) { skip_reason = "missing stub " + vs_fn; } else { uint32_t n_color = 0; for (uint32_t loc : meta.outputs) n_color = std::max(n_color, loc + 1); if (n_color > props.limits.maxColorAttachments) { skip_reason = "exceeds maxColorAttachments"; + } else if (meta.bary_fallback_location.has_value()) { + const bool ps_sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_FRAGMENT_BIT); + std::vector gs_words; + leonida::BaryFallbackGsInfo bary_info{}; + std::string bary_err; + if (!leonida::build_bary_fallback_gs(vs_stub.words, code, *meta.bary_fallback_location, + gs_words, &bary_info, &bary_err)) { + { + std::lock_guard g(mu); + std::fprintf(stderr, "error: %s: %s\n", name.c_str(), bary_err.c_str()); + } + record_pipe(name, stage, meta.subgroup_size, ps_sg_forced, + VK_ERROR_VALIDATION_FAILED_EXT, 0.0, 0); + pipe_failed = true; + } else if (bary_info.clip_count && !f2.features.shaderClipDistance) { + skip_reason = "no shaderClipDistance"; + } else if (bary_info.cull_count && !f2.features.shaderCullDistance) { + skip_reason = "no shaderCullDistance"; + } else { + VkShaderModuleCreateInfo gsi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + gsi.codeSize = gs_words.size() * sizeof(gs_words.front()); + gsi.pCode = gs_words.data(); + const VkResult gs_r = vkCreateShaderModule(dev, &gsi, nullptr, &gs_mod); + if (gs_r != VK_SUCCESS) { + gs_mod = VK_NULL_HANDLE; + { + std::lock_guard g(mu); + std::fprintf(stderr, + "error: %s: bary_fallback GS vkCreateShaderModule failed (%d)\n", + name.c_str(), gs_r); + } + record_pipe(name, stage, meta.subgroup_size, ps_sg_forced, gs_r, 0.0, 0); + pipe_failed = true; + } else { + color_formats.assign(n_color, VK_FORMAT_R32G32B32A32_SFLOAT); + if (meta.writes_depth) depth_format = VK_FORMAT_D32_SFLOAT; + stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_stub.mod, false)); + stages.push_back(make_stage(VK_SHADER_STAGE_GEOMETRY_BIT, gs_mod, false)); + stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, sm, true)); + } + } } else { color_formats.assign(n_color, VK_FORMAT_R32G32B32A32_SFLOAT); if (meta.writes_depth) depth_format = VK_FORMAT_D32_SFLOAT; - stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false)); + stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_stub.mod, false)); stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, sm, true)); } } @@ -1827,7 +1922,7 @@ int main(int argc, char** argv) { if (!skip_reason.empty()) { record_skip(name, stage, skip_reason); - } else { + } else if (!pipe_failed) { VkVertexInputBindingDescription vbind{0, 16, VK_VERTEX_INPUT_RATE_VERTEX}; std::vector vattrs; if (stage == "vs") { @@ -1918,6 +2013,7 @@ int main(int argc, char** argv) { if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags); } + if (gs_mod) vkDestroyShaderModule(dev, gs_mod, nullptr); } } else if (mod_ok) { record_skip(name, stage, "unsupported stage " + stage); @@ -1972,7 +2068,7 @@ int main(int argc, char** argv) { watch_cv.notify_one(); watch.join(); - for (auto& [_, mod] : stub_cache) if (mod) vkDestroyShaderModule(dev, mod, nullptr); + for (auto& [_, stub] : stub_cache) if (stub.mod) vkDestroyShaderModule(dev, stub.mod, nullptr); const std::set all_stages = leonida::summary_stages(modules_ok, modules_bad, stats, big_skipped); diff --git a/tests/test_vk_pipeline_check_index.py b/tests/test_vk_pipeline_check_index.py index af719e7d0d..44cef17198 100644 --- a/tests/test_vk_pipeline_check_index.py +++ b/tests/test_vk_pipeline_check_index.py @@ -99,6 +99,21 @@ def test_valid_empty_object_is_an_empty_corpus(self): self.assertNotIn("cannot use", r.stderr) self.assertIn("0 shaders in index", r.stderr) + def test_invalid_bary_fallback_input_is_an_error(self): + for bad in ('"bad"', "123", "{}", '{"other":1}', '{"location":32}', '{"location":-1}', '{"location":1.5}'): + with self.subTest(bad=bad): + self.assert_index_error( + self.run_tool(f'{{"ps0":{{"stage":"ps","bary_fallback_input":{bad}}}}}'), + "malformed JSON", + ) + + def test_valid_bary_fallback_input_is_accepted(self): + for ok in ("null", '{"location":0}', '{"extra":true,"location":31}'): + with self.subTest(ok=ok): + r = self.run_tool(f'{{"ps0":{{"stage":"ps","bary_fallback_input":{ok}}}}}') + self.assertNotIn("malformed JSON", r.stderr) + self.assertIn("1 shaders in index", r.stderr) + def main(): """unittest.main(), except that a file whose tests all skipped succeeds: unittest exits 5 for an empty run, and