diff --git a/.github/workflows/anykyty.yml b/.github/workflows/anykyty.yml index bd3b115ba4..dccc548165 100644 --- a/.github/workflows/anykyty.yml +++ b/.github/workflows/anykyty.yml @@ -278,7 +278,7 @@ jobs: sanitizer: address env: GPU_TESTS: >- - ^(kyty_shim_(packed_unorm_blend|compute_execution|wave64_cross_lane|empty_buffer_replay|empty_buffer_replay_off|depth_target_alias|frame_capture_round_trip|buffer_null_range|descriptor_tables_draw|merged_hull_draw|image_write_back_alias|buffer_cache_pages))$ + ^(kyty_shim_(packed_unorm_blend|compute_execution|wave64_cross_lane|empty_buffer_replay|empty_buffer_replay_off|depth_target_alias|frame_capture_round_trip|buffer_null_range|descriptor_tables_draw|merged_hull_draw|mesh_per_primitive_block_draw|image_write_back_alias|buffer_cache_pages))$ CPU_TESTS: ^(kyty_shim_.*|guest_gpu_fault|guest_host_write_filter|agc_kyty_shaders)$ steps: - uses: actions/checkout@v7 diff --git a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h index cff1a9aea5..5e2a24e1d7 100644 --- a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h +++ b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h @@ -240,7 +240,7 @@ struct EmitterState { uint32_t mesh_allocation = 0; uint32_t mesh_primitive_data = 0; uint32_t mesh_primitives = 0; - uint32_t mesh_cull = 0; + uint32_t mesh_per_primitive = 0; uint32_t mesh_payload = 0; uint32_t entry_label = 0; uint32_t current_label = 0; diff --git a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp index 61f437015c..8aed3ca137 100644 --- a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp +++ b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp @@ -40,65 +40,94 @@ uint32_t MeshPrimitiveType(EmitterState& state) { return size == 1u ? TypeU32(state) : TypeU32Vector(state, size); } +uint32_t MeshPerPrimitiveType(EmitterState& state, bool has_layer) { + if (has_layer) { + return state.builder.DecoratedType( + spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationBuiltIn, spv::BuiltInCullPrimitiveEXT}}, + {spv::OpMemberDecorate, {0, spv::DecorationPerPrimitiveEXT}}, + {spv::OpMemberDecorate, {1, spv::DecorationBuiltIn, spv::BuiltInLayer}}, + {spv::OpMemberDecorate, {1, spv::DecorationPerPrimitiveEXT}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + TypeBool(state), TypeU32(state)); + } + return state.builder.DecoratedType( + spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationBuiltIn, spv::BuiltInCullPrimitiveEXT}}, + {spv::OpMemberDecorate, {0, spv::DecorationPerPrimitiveEXT}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + TypeBool(state)); +} + +uint32_t MeshPrimitiveMember(EmitterState& state, uint32_t type, uint32_t index, uint32_t member) { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, type), + pointer, state.mesh_per_primitive, index, ConstantU32(state, member)); + return pointer; +} + } void DefineMeshOutputs(EmitterState& state, uint32_t clip_distance_count, uint32_t cull_distance_count) { - const auto& mesh = state.input_info.vertex->mesh; + const auto& mesh = state.input_info.vertex->mesh; + const bool has_layer = std::ranges::any_of(state.outputs, [](const OutputBinding& output) { + return output.kind == IR::StageOutputKind::Layer; + }); + const auto per_primitive = MeshPerPrimitiveType(state, has_layer); + state.builder.AddName(per_primitive, "gl_MeshPerPrimitiveEXT"); + state.mesh_per_primitive = + MeshArray(state, spv::StorageClassOutput, per_primitive, mesh.max_primitives); + state.builder.AddName(state.mesh_per_primitive, "gl_MeshPrimitivesEXT"); for (auto& output: state.outputs) { - const auto type = MeshOutputType(state, output.kind); - const bool clip = output.kind == IR::StageOutputKind::ClipDistance; - const bool cull = output.kind == IR::StageOutputKind::CullDistance; - auto& variable = clip ? state.clip_distance_variable - : cull ? state.cull_distance_variable : output.variable_id; - if (variable == 0) { - const auto element_type = clip || cull - ? state.builder.Type(spv::OpTypeArray, type, - ConstantU32(state, clip ? clip_distance_count - : cull_distance_count)) - : type; - variable = MeshArray(state, spv::StorageClassOutput, element_type, - output.kind == IR::StageOutputKind::Layer ? mesh.max_primitives - : mesh.max_vertices); - state.interface_variables.push_back(variable); - state.builder.AddName(variable, output.debug_name.c_str()); - if (output.kind == IR::StageOutputKind::Parameter) { - state.builder.AddAnnotation(spv::OpDecorate, variable, - spv::DecorationLocation, output.location); - } else { - const auto builtin = clip ? spv::BuiltInClipDistance - : cull ? spv::BuiltInCullDistance - : output.kind == IR::StageOutputKind::Layer ? spv::BuiltInLayer - : spv::BuiltInPosition; - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, builtin); - } - if (output.kind == IR::StageOutputKind::Layer) { - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationPerPrimitiveEXT); + const auto type = MeshOutputType(state, output.kind); + const bool clip = output.kind == IR::StageOutputKind::ClipDistance; + const bool cull = output.kind == IR::StageOutputKind::CullDistance; + const bool layer = output.kind == IR::StageOutputKind::Layer; + if (layer) { + output.variable_id = state.mesh_per_primitive; + } else { + auto& variable = clip ? state.clip_distance_variable + : cull ? state.cull_distance_variable : output.variable_id; + if (variable == 0) { + const auto element_type = + clip || cull + ? state.builder.Type(spv::OpTypeArray, type, + ConstantU32(state, clip ? clip_distance_count + : cull_distance_count)) + : type; + variable = MeshArray(state, spv::StorageClassOutput, element_type, mesh.max_vertices); + state.interface_variables.push_back(variable); + state.builder.AddName(variable, output.debug_name.c_str()); + if (output.kind == IR::StageOutputKind::Parameter) { + state.builder.AddAnnotation(spv::OpDecorate, variable, + spv::DecorationLocation, output.location); + } else { + const auto builtin = clip ? spv::BuiltInClipDistance + : cull ? spv::BuiltInCullDistance + : spv::BuiltInPosition; + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, + builtin); + } } + output.variable_id = variable; } - output.variable_id = variable; - const bool shared = output.kind == IR::StageOutputKind::Layer; output.mesh_data_variable = - MeshArray(state, shared ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, type, - shared ? mesh.max_vertices : state.lane_count); + MeshArray(state, layer ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, type, + layer ? mesh.max_vertices : state.lane_count); } state.mesh_allocation = MeshArray(state, spv::StorageClassWorkgroup, TypeU32(state), 2); state.mesh_primitive_data = MeshArray(state, spv::StorageClassPrivate, TypeU32(state), state.lane_count); state.mesh_primitives = MeshArray(state, spv::StorageClassOutput, MeshPrimitiveType(state), mesh.max_primitives); - state.mesh_cull = - MeshArray(state, spv::StorageClassOutput, TypeBool(state), mesh.max_primitives); state.interface_variables.push_back(state.mesh_primitives); - state.interface_variables.push_back(state.mesh_cull); + state.interface_variables.push_back(state.mesh_per_primitive); constexpr spv::BuiltIn indices[] = {spv::BuiltInPrimitivePointIndicesEXT, spv::BuiltInPrimitiveLineIndicesEXT, spv::BuiltInPrimitiveTriangleIndicesEXT}; state.builder.AddAnnotation(spv::OpDecorate, state.mesh_primitives, spv::DecorationBuiltIn, indices[mesh.output_primitive_size - 1u]); - state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationBuiltIn, - spv::BuiltInCullPrimitiveEXT); - state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationPerPrimitiveEXT); } uint32_t MeshOutputPointer(EmitterState& state, IR::StageOutputKind kind, uint32_t index) { @@ -211,10 +240,8 @@ void EmitMeshEntryPoint(EmitterState& state) { const auto culled = state.builder.AllocateId(); state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), culled, null_bit, ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpStore, - MeshElement(state, state.mesh_cull, spv::StorageClassOutput, - TypeBool(state), index), - culled); + state.builder.AddFunction( + spv::OpStore, MeshPrimitiveMember(state, TypeBool(state), index, 0), culled); for (const auto& output: state.outputs) { if (output.kind != IR::StageOutputKind::Layer) { continue; @@ -222,9 +249,8 @@ void EmitMeshEntryPoint(EmitterState& state) { const auto layer = MeshLoad(state, output.mesh_data_variable, spv::StorageClassWorkgroup, TypeU32(state), vertex[state.input_info.vertex->mesh.provoking_vertex]); - const auto pointer = MeshElement(state, output.variable_id, spv::StorageClassOutput, - TypeU32(state), index); - state.builder.AddFunction(spv::OpStore, pointer, layer); + state.builder.AddFunction( + spv::OpStore, MeshPrimitiveMember(state, TypeU32(state), index, 1), layer); } }); } diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt index 7948d3399b..ad01a85c71 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt @@ -436,6 +436,21 @@ set_tests_properties(kyty_shim_merged_hull PROPERTIES TIMEOUT 20 PASS_REGULAR_EX add_test(NAME kyty_shim_merged_hull_draw COMMAND kyty_shim_merged_hull_tests draw) set_tests_properties(kyty_shim_merged_hull_draw PROPERTIES TIMEOUT 20 SKIP_RETURN_CODE 77) +add_test_executable(kyty_shim_mesh_per_primitive_block_tests ${CMAKE_CURRENT_SOURCE_DIR}/MeshPerPrimitiveBlock.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../src/Log.cpp) +target_include_directories(kyty_shim_mesh_per_primitive_block_tests PRIVATE ${LIBS_INCLUDE_DIR}) +target_include_directories(kyty_shim_mesh_per_primitive_block_tests SYSTEM PRIVATE ${CMAKE_SOURCE_DIR}/3rdparty/SPIRV-Tools/include) +configure_host_test_executable(kyty_shim_mesh_per_primitive_block_tests) +if(MINGW) + target_link_libraries(kyty_shim_mesh_per_primitive_block_tests PRIVATE stdc++ gcc_eh) +endif() +target_link_libraries(kyty_shim_mesh_per_primitive_block_tests PRIVATE Kyty::gpu libkernel libc) +add_test(NAME kyty_shim_mesh_per_primitive_block COMMAND kyty_shim_mesh_per_primitive_block_tests) +set_tests_properties(kyty_shim_mesh_per_primitive_block PROPERTIES TIMEOUT 20 + PASS_REGULAR_EXPRESSION "kyty_shim_mesh_per_primitive_block: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") +add_test(NAME kyty_shim_mesh_per_primitive_block_draw COMMAND kyty_shim_mesh_per_primitive_block_tests draw) +set_tests_properties(kyty_shim_mesh_per_primitive_block_draw PROPERTIES TIMEOUT 20 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "kyty_shim_mesh_per_primitive_block_draw: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") + if(NOT ANYPS5_KYTY_DLL) add_test_executable(kyty_shim_recompiler_robustness_tests ${CMAKE_CURRENT_SOURCE_DIR}/RecompilerRobustness.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../src/Log.cpp) target_include_directories(kyty_shim_recompiler_robustness_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../fuzz) diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/MeshPerPrimitiveBlock.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/MeshPerPrimitiveBlock.cpp new file mode 100644 index 0000000000..ec36bdb53f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/MeshPerPrimitiveBlock.cpp @@ -0,0 +1,585 @@ +#include "graphics/host_gpu/graphicContext.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace Libs::Graphics; +namespace Recompiler = Libs::Graphics::ShaderRecompiler; + +constexpr const char* Name = "kyty_shim_mesh_per_primitive_block"; + +constexpr std::array MeshWithLayerCode { + 0xbefc03ffu, 0x00002003u, 0xbf900009u, 0x7e0202f3u, 0x7e0402f3u, 0x7e060280u, 0x7e0802f2u, + 0x7e0a02ffu, 0x40400000u, 0x7d840084u, 0x02020b01u, 0x7d840088u, 0x02040b02u, 0x7e0c0280u, + 0x7e0e0281u, 0x7d840084u, 0x020c0f06u, 0x7e1002ffu, 0x80200400u, 0x7e1202ffu, 0x00000801u, + 0x02101308u, 0xf80000cfu, 0x04030201u, 0xf80000d4u, 0x00060000u, 0xf8000941u, 0x00000008u, +}; + +constexpr std::array MeshWithoutLayerCode { + 0xbefc03ffu, 0x00002003u, 0xbf900009u, 0x7e0202f3u, 0x7e0402f3u, 0x7e060280u, 0x7e0802f2u, + 0x7e0a02ffu, 0x40400000u, 0x7d840084u, 0x02020b01u, 0x7d840088u, 0x02040b02u, 0x7d840084u, + 0x7e1002ffu, 0x80200400u, 0x7e1202ffu, 0x00000801u, 0x02101308u, 0xf80000cfu, 0x04030201u, + 0xf8000941u, 0x00000008u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; + +constexpr std::array SolidPixelSpirv { + 0x07230203u, 0x00010300u, 0x0008000bu, 0x0000000cu, 0x00000000u, 0x00020011u, 0x00000001u, + 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x00000000u, 0x00000001u, 0x0006000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, + 0x00000009u, 0x00030010u, 0x00000004u, 0x00000007u, 0x00040047u, 0x00000009u, 0x0000001eu, + 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, + 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u, + 0x00000008u, 0x00000003u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000009u, 0x00000003u, + 0x0004002bu, 0x00000006u, 0x0000000au, 0x3f800000u, 0x0007002cu, 0x00000007u, 0x0000000bu, + 0x0000000au, 0x0000000au, 0x0000000au, 0x0000000au, 0x00050036u, 0x00000002u, 0x00000004u, + 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0003003eu, 0x00000009u, 0x0000000bu, + 0x000100fdu, 0x00010038u, +}; + +void Require(bool condition, const std::string& message) { + if (condition) return; + std::fprintf(stderr, "%s: FAILED: %s\n", Name, message.c_str()); + std::exit(1); +} + +template +T Checked(vk::ResultValue result, const char* what) { + Require(result.result == vk::Result::eSuccess, + std::string(what) + " failed: " + vk::to_string(result.result)); + return std::move(result.value); +} + +void Checked(vk::Result result, const char* what) { + Require(result == vk::Result::eSuccess, std::string(what) + " failed: " + vk::to_string(result)); +} + +int NoDevice(const char* why) { + const char* required = std::getenv("ANYPS5_REQUIRE_VULKAN"); + Require(required == nullptr || std::strcmp(required, "1") != 0, + std::string("ANYPS5_REQUIRE_VULKAN=1 and ") + why); + std::printf("%s_draw: skipped, %s\n", Name, why); + return 77; +} + +std::vector CompileMesh(bool with_layer, uint32_t host_subgroup_size) { + std::vector code; + if (with_layer) { + code.assign(MeshWithLayerCode.begin(), MeshWithLayerCode.end()); + code.push_back(0xbf810000u); + } else { + code.assign(MeshWithoutLayerCode.begin(), MeshWithoutLayerCode.end()); + } + + ShaderVertexInputInfo vertex {}; + vertex.logical_stage = ShaderType::Mesh; + vertex.wave_size = 64u; + vertex.pa_cl_vs_out_cntl = with_layer ? ((1u << 21u) | (1u << 18u)) : 0u; + vertex.mesh.threads_num[0] = 64u; + vertex.mesh.threads_num[1] = 1u; + vertex.mesh.threads_num[2] = 1u; + vertex.mesh.host_subgroup_size = host_subgroup_size; + vertex.mesh.vertices_per_group = 3u; + vertex.mesh.primitives_per_group = 2u; + vertex.mesh.max_vertices = 64u; + vertex.mesh.max_primitives = 2u; + vertex.mesh.input_primitive = static_cast(Prospero::PrimitiveType::kPointList); + vertex.mesh.output_primitive_size = 3u; + vertex.mesh.provoking_vertex = 0u; + vertex.mesh.fast_launch = false; + + Recompiler::Spirv::Profile profile {}; + Recompiler::CompileOptions options {}; + options.stage = ShaderType::Mesh; + options.wave_size = 64u; + options.shader_hash = with_layer ? 0x6d65736800000001ull : 0x6d65736800000002ull; + options.profile = &profile; + options.input_info.vertex = &vertex; + + const auto source = Recompiler::PrepareShaderSource(code, options); + auto translated = Recompiler::TranslateProgram(source.decoded, options); + const auto plan = Recompiler::IR::ExtractResourcePlan(translated.program); + const Recompiler::IR::SrtRuntime runtime {}; + Recompiler::IR::ResourceSnapshot snapshot; + Recompiler::IR::ResourceSpecialization specialization; + Require(Recompiler::IR::MaterializeResources(plan, runtime, snapshot, specialization), + "failed to materialize mesh resources"); + auto compiled = Recompiler::CompileProgram(std::move(translated), options, specialization, 0u); + + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_3); + std::string messages; + tools.SetMessageConsumer( + [&messages](spv_message_level_t, const char*, const spv_position_t&, const char* message) { + messages += message; + messages += '\n'; + }); + spvtools::ValidatorOptions validator; + validator.SetUniformBufferStandardLayout(true); + validator.SetScalarBlockLayout(true); + Require(tools.Validate(compiled.spirv.data(), compiled.spirv.size(), validator), + std::string("SPIR-V validation failed:\n") + messages); + return compiled.spirv; +} + +struct PerPrimitiveLayout { + std::set block_structs; + std::map> struct_members; + std::map, spv::BuiltIn> member_builtins; + std::set> member_per_primitive; + uint32_t standalone_layer = 0; + uint32_t standalone_cull = 0; +}; + +PerPrimitiveLayout Inspect(const std::vector& words) { + PerPrimitiveLayout layout; + for (size_t at = 5; at < words.size();) { + const auto count = words[at] >> 16u; + const auto opcode = static_cast(words[at] & 0xffffu); + if (count == 0 || at + count > words.size()) break; + const auto word = [&](uint32_t index) { return words[at + index]; }; + if (opcode == spv::OpTypeStruct && count >= 3) { + std::vector members; + for (uint32_t i = 2; i < count; i++) members.push_back(word(i)); + layout.struct_members[word(1)] = std::move(members); + } else if (opcode == spv::OpDecorate && count >= 3) { + const auto target = word(1); + const auto deco = static_cast(word(2)); + if (deco == spv::DecorationBlock) { + layout.block_structs.insert(target); + } else if (deco == spv::DecorationBuiltIn && count >= 4) { + const auto builtin = static_cast(word(3)); + if (builtin == spv::BuiltInLayer) layout.standalone_layer++; + if (builtin == spv::BuiltInCullPrimitiveEXT) layout.standalone_cull++; + } + } else if (opcode == spv::OpMemberDecorate && count >= 4) { + const auto target = word(1); + const auto member = word(2); + const auto deco = static_cast(word(3)); + if (deco == spv::DecorationBuiltIn && count >= 5) { + layout.member_builtins[{target, member}] = static_cast(word(4)); + } else if (deco == spv::DecorationPerPrimitiveEXT) { + layout.member_per_primitive.insert({target, member}); + } + } + at += count; + } + return layout; +} + +void VerifyCodegen() { + for (const uint32_t subgroup: {32u, 64u}) { + const auto with_layer = Inspect(CompileMesh(true, subgroup)); + Require(with_layer.standalone_layer == 0u, "BuiltIn Layer must not be a standalone output variable"); + Require(with_layer.standalone_cull == 0u, + "BuiltIn CullPrimitiveEXT must not be a standalone output variable"); + uint32_t block_id = 0; + for (const auto id: with_layer.block_structs) { + const auto cull_it = with_layer.member_builtins.find({id, 0u}); + const auto layer_it = with_layer.member_builtins.find({id, 1u}); + if (cull_it != with_layer.member_builtins.end() && + cull_it->second == spv::BuiltInCullPrimitiveEXT && + layer_it != with_layer.member_builtins.end() && + layer_it->second == spv::BuiltInLayer) { + block_id = id; + break; + } + } + Require(block_id != 0u, "missing Block struct carrying CullPrimitiveEXT and Layer"); + Require(with_layer.member_per_primitive.contains({block_id, 0u}), + "CullPrimitiveEXT member missing PerPrimitiveEXT decoration"); + Require(with_layer.member_per_primitive.contains({block_id, 1u}), + "Layer member missing PerPrimitiveEXT decoration"); + + const auto without_layer = Inspect(CompileMesh(false, subgroup)); + Require(without_layer.standalone_layer == 0u, "unexpected standalone Layer without layer export"); + Require(without_layer.standalone_cull == 0u, + "BuiltIn CullPrimitiveEXT must stay in a Block struct without layer export"); + uint32_t cull_block = 0; + for (const auto id: without_layer.block_structs) { + const auto cull_it = without_layer.member_builtins.find({id, 0u}); + if (cull_it != without_layer.member_builtins.end() && + cull_it->second == spv::BuiltInCullPrimitiveEXT) { + cull_block = id; + break; + } + } + Require(cull_block != 0u, "missing Block struct carrying CullPrimitiveEXT without layer export"); + Require(without_layer.struct_members.at(cull_block).size() == 1u, + "per-primitive Block struct without layer export should have one member"); + Require(without_layer.member_per_primitive.contains({cull_block, 0u}), + "CullPrimitiveEXT member missing PerPrimitiveEXT decoration without layer export"); + } +} + +int DrawMeshPerPrimitiveBlock() { + const vk::detail::DynamicLoader loader; + if (!loader.success()) return NoDevice("the Vulkan loader is missing"); + auto& dispatch = VULKAN_HPP_DEFAULT_DISPATCHER; + dispatch.init(loader.getProcAddress("vkGetInstanceProcAddr")); + vk::ApplicationInfo application; + application.apiVersion = VK_API_VERSION_1_3; + vk::InstanceCreateInfo instance_info; + instance_info.pApplicationInfo = &application; + const auto created = vk::createInstance(instance_info); + if (created.result != vk::Result::eSuccess) return NoDevice("no Vulkan 1.3 instance"); + const auto instance = created.value; + dispatch.init(instance); + + vk::PhysicalDevice physical; + uint32_t family = 0; + uint32_t subgroup = 64u; + bool has_gpl = false; + for (const auto candidate: Checked(instance.enumeratePhysicalDevices(), "device enumeration")) { + const auto extensions = Checked(candidate.enumerateDeviceExtensionProperties(nullptr), + "device extension enumeration"); + const auto has_ext = [&](const char* ext) { + return std::ranges::any_of(extensions, [ext](const auto& props) { + return std::string_view(props.extensionName.data()) == ext; + }); + }; + if (!has_ext(VK_EXT_MESH_SHADER_EXTENSION_NAME)) continue; + const bool candidate_gpl = has_ext(VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME) && + has_ext(VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME); + + vk::PhysicalDeviceMeshShaderFeaturesEXT mesh_features; + vk::PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT gpl_features; + vk::PhysicalDeviceVulkan12Features v12_features; + vk::PhysicalDeviceVulkan13Features v13_features; + vk::PhysicalDeviceFeatures2 features; + v13_features.pNext = &v12_features; + v12_features.pNext = &mesh_features; + mesh_features.pNext = candidate_gpl ? &gpl_features : nullptr; + features.pNext = &v13_features; + candidate.getFeatures2(&features); + + const auto families = candidate.getQueueFamilyProperties(); + const auto graphics = std::ranges::find_if(families, [](const auto& queue) { + return static_cast(queue.queueFlags & vk::QueueFlagBits::eGraphics); + }); + if (!mesh_features.meshShader || !v12_features.shaderOutputLayer || + !v12_features.bufferDeviceAddress || !v12_features.uniformBufferStandardLayout || + !v13_features.dynamicRendering || !features.features.shaderInt64 || + graphics == families.end()) { + continue; + } + vk::PhysicalDeviceSubgroupProperties subgroup_props; + vk::PhysicalDeviceProperties2 props; + props.pNext = &subgroup_props; + candidate.getProperties2(&props); + const bool software = props.properties.deviceType == vk::PhysicalDeviceType::eCpu; + if (physical && software) continue; + physical = candidate; + family = static_cast(graphics - families.begin()); + subgroup = subgroup_props.subgroupSize >= 64u ? 64u : 32u; + has_gpl = candidate_gpl && gpl_features.graphicsPipelineLibrary; + if (!software) break; + } + if (!physical) { + instance.destroy(); + return NoDevice("no device with VK_EXT_mesh_shader, shaderOutputLayer, and dynamic rendering"); + } + + const auto mesh_spirv = CompileMesh(true, subgroup); + + std::vector enabled_extensions {VK_EXT_MESH_SHADER_EXTENSION_NAME}; + if (has_gpl) { + enabled_extensions.push_back(VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME); + enabled_extensions.push_back(VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME); + } + const float priority = 1.0f; + vk::DeviceQueueCreateInfo queue_info; + queue_info.queueFamilyIndex = family; + queue_info.queueCount = 1; + queue_info.pQueuePriorities = &priority; + + vk::PhysicalDeviceMeshShaderFeaturesEXT mesh_features; + mesh_features.meshShader = VK_TRUE; + vk::PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT gpl_features; + gpl_features.graphicsPipelineLibrary = VK_TRUE; + vk::PhysicalDeviceVulkan12Features v12_features; + v12_features.shaderOutputLayer = VK_TRUE; + v12_features.bufferDeviceAddress = VK_TRUE; + v12_features.uniformBufferStandardLayout = VK_TRUE; + vk::PhysicalDeviceVulkan13Features v13_features; + v13_features.dynamicRendering = VK_TRUE; + v13_features.pNext = &v12_features; + v12_features.pNext = &mesh_features; + mesh_features.pNext = has_gpl ? &gpl_features : nullptr; + vk::PhysicalDeviceFeatures2 features; + features.features.shaderInt64 = VK_TRUE; + features.pNext = &v13_features; + + vk::DeviceCreateInfo device_info; + device_info.pNext = &features; + device_info.queueCreateInfoCount = 1; + device_info.pQueueCreateInfos = &queue_info; + device_info.enabledExtensionCount = static_cast(enabled_extensions.size()); + device_info.ppEnabledExtensionNames = enabled_extensions.data(); + const auto device = Checked(physical.createDevice(device_info), "device creation"); + dispatch.init(device); + + vk::PhysicalDeviceDriverProperties driver; + vk::PhysicalDeviceProperties2 properties; + properties.pNext = &driver; + physical.getProperties2(&properties); + const auto gpu_name = std::string(properties.properties.deviceName.data()) + " (" + + driver.driverName.data() + ", " + driver.driverInfo.data() + ")"; + const auto queue = device.getQueue(family, 0); + + vk::ShaderModuleCreateInfo mesh_mod_info; + mesh_mod_info.codeSize = mesh_spirv.size() * sizeof(uint32_t); + mesh_mod_info.pCode = mesh_spirv.data(); + const auto mesh_module = Checked(device.createShaderModule(mesh_mod_info), "mesh shader module"); + + vk::ShaderModuleCreateInfo pixel_mod_info; + pixel_mod_info.codeSize = SolidPixelSpirv.size() * sizeof(uint32_t); + pixel_mod_info.pCode = SolidPixelSpirv.data(); + const auto pixel_module = Checked(device.createShaderModule(pixel_mod_info), "pixel shader module"); + + vk::PushConstantRange push_range; + push_range.stageFlags = vk::ShaderStageFlagBits::eMeshEXT | vk::ShaderStageFlagBits::eFragment; + push_range.offset = 0; + push_range.size = Recompiler::IR::NativePushConstantSize; + vk::PipelineLayoutCreateInfo layout_info; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push_range; + const auto layout = Checked(device.createPipelineLayout(layout_info), "pipeline layout"); + + constexpr uint32_t Side = 4u; + constexpr uint32_t Layers = 2u; + constexpr uint32_t LayerBytes = Side * Side * 4u; + constexpr auto Format = vk::Format::eR8G8B8A8Unorm; + + vk::Viewport viewport {0.0f, 0.0f, static_cast(Side), static_cast(Side), 0.0f, 1.0f}; + vk::Rect2D scissor {{0, 0}, {Side, Side}}; + vk::PipelineViewportStateCreateInfo viewports; + viewports.viewportCount = 1; + viewports.pViewports = &viewport; + viewports.scissorCount = 1; + viewports.pScissors = &scissor; + + vk::PipelineRasterizationStateCreateInfo raster; + raster.polygonMode = vk::PolygonMode::eFill; + raster.cullMode = vk::CullModeFlagBits::eNone; + raster.lineWidth = 1.0f; + + vk::PipelineMultisampleStateCreateInfo multisample; + multisample.rasterizationSamples = vk::SampleCountFlagBits::e1; + + vk::PipelineColorBlendAttachmentState blend_target; + blend_target.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | + vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA; + vk::PipelineColorBlendStateCreateInfo blend; + blend.attachmentCount = 1; + blend.pAttachments = &blend_target; + + vk::PipelineShaderStageCreateInfo mesh_stage; + mesh_stage.stage = vk::ShaderStageFlagBits::eMeshEXT; + mesh_stage.module = mesh_module; + mesh_stage.pName = "main"; + + if (has_gpl) { + vk::PipelineRenderingCreateInfo view_only; + vk::GraphicsPipelineLibraryCreateInfoEXT lib_info; + lib_info.flags = vk::GraphicsPipelineLibraryFlagBitsEXT::ePreRasterizationShaders; + lib_info.pNext = &view_only; + vk::GraphicsPipelineCreateInfo lib_pipe_info; + lib_pipe_info.pNext = &lib_info; + lib_pipe_info.flags = vk::PipelineCreateFlagBits::eLibraryKHR; + lib_pipe_info.stageCount = 1; + lib_pipe_info.pStages = &mesh_stage; + lib_pipe_info.pViewportState = &viewports; + lib_pipe_info.pRasterizationState = &raster; + lib_pipe_info.layout = layout; + const auto library = Checked(device.createGraphicsPipeline(nullptr, lib_pipe_info), + "pre-rasterization mesh pipeline library"); + device.destroyPipeline(library); + } + + std::array stages {}; + stages[0] = mesh_stage; + stages[1].stage = vk::ShaderStageFlagBits::eFragment; + stages[1].module = pixel_module; + stages[1].pName = "main"; + + vk::PipelineRenderingCreateInfo rendering; + rendering.colorAttachmentCount = 1; + rendering.pColorAttachmentFormats = &Format; + + vk::GraphicsPipelineCreateInfo pipeline_info; + pipeline_info.pNext = &rendering; + pipeline_info.stageCount = static_cast(stages.size()); + pipeline_info.pStages = stages.data(); + pipeline_info.pViewportState = &viewports; + pipeline_info.pRasterizationState = &raster; + pipeline_info.pMultisampleState = &multisample; + pipeline_info.pColorBlendState = &blend; + pipeline_info.layout = layout; + const auto pipeline = + Checked(device.createGraphicsPipeline(nullptr, pipeline_info), "whole mesh pipeline"); + + const auto memory_types = physical.getMemoryProperties(); + const auto allocate = [&](const vk::MemoryRequirements& needs, vk::MemoryPropertyFlags flags) { + for (uint32_t type = 0; type < memory_types.memoryTypeCount; type++) { + if (((needs.memoryTypeBits >> type) & 1u) == 0u || + (memory_types.memoryTypes[type].propertyFlags & flags) != flags) { + continue; + } + vk::MemoryAllocateInfo info; + info.allocationSize = needs.size; + info.memoryTypeIndex = type; + return Checked(device.allocateMemory(info), "memory allocation"); + } + Require(false, "no suitable memory type"); + return vk::DeviceMemory {}; + }; + + vk::ImageCreateInfo image_info; + image_info.imageType = vk::ImageType::e2D; + image_info.format = Format; + image_info.extent = vk::Extent3D {Side, Side, 1u}; + image_info.mipLevels = 1u; + image_info.arrayLayers = Layers; + image_info.samples = vk::SampleCountFlagBits::e1; + image_info.tiling = vk::ImageTiling::eOptimal; + image_info.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc; + const auto image = Checked(device.createImage(image_info), "image creation"); + const auto image_memory = allocate(device.getImageMemoryRequirements(image), + vk::MemoryPropertyFlagBits::eDeviceLocal); + Checked(device.bindImageMemory(image, image_memory, 0), "image bind"); + + const vk::ImageSubresourceRange whole {vk::ImageAspectFlagBits::eColor, 0u, 1u, 0u, Layers}; + vk::ImageViewCreateInfo view_info; + view_info.image = image; + view_info.viewType = vk::ImageViewType::e2DArray; + view_info.format = Format; + view_info.subresourceRange = whole; + const auto view = Checked(device.createImageView(view_info), "image view creation"); + + vk::BufferCreateInfo buffer_info; + buffer_info.size = LayerBytes * Layers; + buffer_info.usage = vk::BufferUsageFlagBits::eTransferDst; + const auto buffer = Checked(device.createBuffer(buffer_info), "readback buffer creation"); + const auto buffer_memory = + allocate(device.getBufferMemoryRequirements(buffer), + vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); + Checked(device.bindBufferMemory(buffer, buffer_memory, 0), "buffer bind"); + + vk::CommandPoolCreateInfo pool_info; + pool_info.queueFamilyIndex = family; + const auto pool = Checked(device.createCommandPool(pool_info), "command pool"); + vk::CommandBufferAllocateInfo command_info; + command_info.commandPool = pool; + command_info.commandBufferCount = 1; + const auto command = + Checked(device.allocateCommandBuffers(command_info), "command buffer").front(); + + const auto move = [&](vk::ImageLayout from, vk::ImageLayout to, vk::AccessFlags source, + vk::AccessFlags target, vk::PipelineStageFlags before, + vk::PipelineStageFlags after) { + vk::ImageMemoryBarrier barrier; + barrier.srcAccessMask = source; + barrier.dstAccessMask = target; + barrier.oldLayout = from; + barrier.newLayout = to; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange = whole; + command.pipelineBarrier(before, after, {}, 0, nullptr, 0, nullptr, 1, &barrier); + }; + + Checked(command.begin(vk::CommandBufferBeginInfo {}), "command begin"); + move(vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal, {}, + vk::AccessFlagBits::eColorAttachmentWrite, vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eColorAttachmentOutput); + vk::RenderingAttachmentInfo target; + target.imageView = view; + target.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + target.loadOp = vk::AttachmentLoadOp::eClear; + target.storeOp = vk::AttachmentStoreOp::eStore; + vk::RenderingInfo pass; + pass.renderArea = scissor; + pass.layerCount = Layers; + pass.colorAttachmentCount = 1; + pass.pColorAttachments = ⌖ + command.beginRendering(&pass); + command.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline); + std::array push {}; + push[0] = 3u; + command.pushConstants(layout, push_range.stageFlags, 0, Recompiler::IR::NativePushConstantSize, + push.data()); + command.drawMeshTasksEXT(1u, 1u, 1u); + command.endRendering(); + move(vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eTransferSrcOptimal, + vk::AccessFlagBits::eColorAttachmentWrite, vk::AccessFlagBits::eTransferRead, + vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eTransfer); + vk::BufferImageCopy copy; + copy.imageSubresource = vk::ImageSubresourceLayers {vk::ImageAspectFlagBits::eColor, 0u, 0u, Layers}; + copy.imageExtent = vk::Extent3D {Side, Side, 1u}; + command.copyImageToBuffer(image, vk::ImageLayout::eTransferSrcOptimal, buffer, 1, ©); + Checked(command.end(), "command end"); + + vk::SubmitInfo submit; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &command; + Checked(queue.submit(1, &submit, nullptr), "queue submit"); + Checked(device.waitIdle(), "device waitIdle"); + + const auto* bytes = + static_cast(Checked(device.mapMemory(buffer_memory, 0, LayerBytes * Layers), + "readback map")); + uint32_t layer0_lit = 0; + uint32_t layer1_lit = 0; + for (uint32_t i = 0; i < Side * Side; i++) { + if (bytes[i * 4u] != 0u) layer0_lit++; + if (bytes[LayerBytes + i * 4u] != 0u) layer1_lit++; + } + device.unmapMemory(buffer_memory); + Require(layer0_lit == 0u, + "culled primitive on layer 0 lit " + std::to_string(layer0_lit) + " pixels"); + Require(layer1_lit == Side * Side, + "visible primitive on layer 1 lit " + std::to_string(layer1_lit) + " of " + + std::to_string(Side * Side) + " pixels"); + + device.destroyCommandPool(pool); + device.destroyBuffer(buffer); + device.freeMemory(buffer_memory); + device.destroyImageView(view); + device.destroyImage(image); + device.freeMemory(image_memory); + device.destroyPipeline(pipeline); + device.destroyPipelineLayout(layout); + device.destroyShaderModule(pixel_module); + device.destroyShaderModule(mesh_module); + device.destroy(); + instance.destroy(); + std::printf("%s_draw: ok, layer0=%u layer1=%u/%u on %s\n", Name, layer0_lit, layer1_lit, + Side * Side, gpu_name.c_str()); + return 0; +} + +} + +int main(int argc, char** argv) { + if (argc > 1 && std::strcmp(argv[1], "draw") == 0) return DrawMeshPerPrimitiveBlock(); + VerifyCodegen(); + std::printf("%s: ok\n", Name); + return 0; +}