diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 7cd8c8f0e..d2c459235 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3344,12 +3344,11 @@ or does not check is rebuilt from the generations' names, with young counted ful without the attachment feedback loop (`Gap::Draw`, `AttachmentRead`: an attachment's shadow holds one layer); and, at creation on every device, whatever pass it would draw in, a vertex function whose `[[render_target_array_index]]` the translator cannot show the same at every - vertex of a primitive, an `Error::Translation` naming `LayeredRendering` and `geometryShader`. Vulkan - requires one `Layer` at every vertex of a primitive + vertex of a primitive, an `Error::Translation` naming `LayeredRendering` as not implemented. + Vulkan requires one `Layer` at every vertex of a primitive (`VUID-VkPipelineShaderStageCreateInfo-stage-02596`), so such a function cannot store its index - as written; the translator's other form, a generated geometry stage that selects the layer, - needs `geometryShader`, which device creation does not enable; and Metal documents a differing - index as undefined (the Metal Shading Language specification). The translator shows an index + as written, and Metal documents a differing index as undefined (the Metal Shading Language + specification). The translator shows an index the same where it is computed from constants, `constant` memory, the draw's instance, base vertex and base instance, and attributes fetched per instance, never from `[[vertex_id]]` or another per-vertex input (`StageIo::uniform_outputs`): `constant uint *layers` read at diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index 7691d0989..7cf3113c2 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -428,6 +428,7 @@ fixture unmeasured_speculation: metal: Apple metal version 32023.921 (metalfe-32 fixture unspecialized_stage_functions: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture unv_runtime_levels: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture vector_word_phases: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) +fixture vertex_amplification: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture vertex_fetch_reach: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture vft_tile_caller: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture vft_vertex_caller: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.air.ll index be79554e6..7dc427efe 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.air.ll +++ b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.air.ll @@ -5,32 +5,32 @@ target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3 target triple = "air64_v28-apple-macosx26.0.0" ; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn -define <{ <4 x float>, <4 x float>, <2 x float>, i32 }> @amp_vertex(i32 noundef %0, i16 noundef %1, i16 noundef %2, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %3) local_unnamed_addr #0 { - %5 = shl i32 %0, 1 - %6 = and i32 %5, 2 - %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #4 - %8 = insertelement <2 x float> undef, float %7, i64 0 - %9 = and i32 %0, 2 - %10 = tail call fast float @air.convert.f.f32.u.i32(i32 %9) #4 - %11 = insertelement <2 x float> %8, float %10, i64 1 - %12 = fmul fast <2 x float> %11, - %13 = fadd fast <2 x float> %12, - %14 = shufflevector <2 x float> %13, <2 x float> poison, <4 x i32> - %15 = shufflevector <4 x float> %14, <4 x float> , <4 x i32> - %16 = zext i16 %1 to i64 - %17 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %3, i64 %16 - %18 = load <4 x float>, <4 x float> addrspace(2)* %17, align 16, !tbaa !55, !alias.scope !58 - %19 = fadd fast <4 x float> %15, %18 - %20 = tail call fast float @air.convert.f.f32.u.i16(i16 %1) #4 +define <{ <4 x float>, <4 x float>, <2 x float>, i32 }> @amp_vertex(i32 noundef %0, i32 noundef %1, i16 noundef %2, i16 noundef %3, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %4) local_unnamed_addr #0 { + %6 = shl i32 %0, 1 + %7 = and i32 %6, 2 + %8 = tail call fast float @air.convert.f.f32.u.i32(i32 %7) #4 + %9 = insertelement <2 x float> undef, float %8, i64 0 + %10 = and i32 %0, 2 + %11 = tail call fast float @air.convert.f.f32.u.i32(i32 %10) #4 + %12 = insertelement <2 x float> %9, float %11, i64 1 + %13 = fmul fast <2 x float> %12, + %14 = fadd fast <2 x float> %13, + %15 = shufflevector <2 x float> %14, <2 x float> poison, <4 x i32> + %16 = shufflevector <4 x float> %15, <4 x float> , <4 x i32> + %17 = zext i16 %2 to i64 + %18 = getelementptr inbounds <4 x float>, <4 x float> addrspace(2)* %4, i64 %17 + %19 = load <4 x float>, <4 x float> addrspace(2)* %18, align 16, !tbaa !56, !alias.scope !59 + %20 = fadd fast <4 x float> %16, %19 %21 = tail call fast float @air.convert.f.f32.u.i16(i16 %2) #4 - %22 = insertelement <4 x float> , float %20, i64 0 - %23 = insertelement <4 x float> %22, float %21, i64 1 - %24 = and i32 %0, 1 - %25 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> undef, <4 x float> %19, 0 - %26 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %25, <4 x float> %23, 1 - %27 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %26, <2 x float> %11, 2 - %28 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %27, i32 %24, 3 - ret <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %28 + %22 = tail call fast float @air.convert.f.f32.u.i16(i16 %3) #4 + %23 = insertelement <4 x float> , float %21, i64 0 + %24 = insertelement <4 x float> %23, float %22, i64 1 + %25 = and i32 %1, 1 + %26 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> undef, <4 x float> %20, 0 + %27 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %26, <4 x float> %24, 1 + %28 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %27, <2 x float> %12, 2 + %29 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %28, i32 %25, 3 + ret <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %29 } ; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn @@ -48,23 +48,23 @@ define <4 x float> @amp_vertex_store(i32 noundef %0, i32 noundef %1, i32 noundef %9 = add i32 %8, %1 %10 = zext i32 %9 to i64 %11 = getelementptr inbounds i32, i32 addrspace(1)* %3, i64 %10 - store i32 %7, i32 addrspace(1)* %11, align 4, !tbaa !61, !alias.scope !63 + store i32 %7, i32 addrspace(1)* %11, align 4, !tbaa !62, !alias.scope !64 ret <4 x float> } ; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn -define <{ <4 x float>, i32 }> @amp_vertex_layer(i32 noundef %0, i16 noundef %1, i32 addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %2) local_unnamed_addr #0 { - %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %0) #4 - %5 = tail call fast float @air.convert.f.f32.u.i16(i16 %1) #4 - %6 = insertelement <4 x float> , float %4, i64 0 - %7 = insertelement <4 x float> %6, float %5, i64 1 - %8 = and i32 %0, 1 - %9 = zext i32 %8 to i64 - %10 = getelementptr inbounds i32, i32 addrspace(2)* %2, i64 %9 - %11 = load i32, i32 addrspace(2)* %10, align 4, !tbaa !61, !alias.scope !66 - %12 = insertvalue <{ <4 x float>, i32 }> undef, <4 x float> %7, 0 - %13 = insertvalue <{ <4 x float>, i32 }> %12, i32 %11, 1 - ret <{ <4 x float>, i32 }> %13 +define <{ <4 x float>, i32 }> @amp_vertex_layer(i32 noundef %0, i32 noundef %1, i16 noundef %2, i32 addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %3) local_unnamed_addr #0 { + %5 = tail call fast float @air.convert.f.f32.u.i32(i32 %0) #4 + %6 = tail call fast float @air.convert.f.f32.u.i16(i16 %2) #4 + %7 = insertelement <4 x float> , float %5, i64 0 + %8 = insertelement <4 x float> %7, float %6, i64 1 + %9 = and i32 %1, 1 + %10 = zext i32 %9 to i64 + %11 = getelementptr inbounds i32, i32 addrspace(2)* %3, i64 %10 + %12 = load i32, i32 addrspace(2)* %11, align 4, !tbaa !62, !alias.scope !67 + %13 = insertvalue <{ <4 x float>, i32 }> undef, <4 x float> %8, 0 + %14 = insertvalue <{ <4 x float>, i32 }> %13, i32 %12, 1 + ret <{ <4 x float>, i32 }> %14 } ; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn @@ -112,14 +112,14 @@ attributes #3 = { mustprogress nofree nosync nounwind readnone willreturn "appro attributes #4 = { nounwind readnone willreturn } !llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} -!air.vertex = !{!9, !20, !27, !32} -!air.fragment = !{!38, !46} -!air.compile_options = !{!49, !50, !51} -!llvm.ident = !{!52} -!air.version = !{!53} -!air.language_version = !{!54} +!air.vertex = !{!9, !21, !28, !33} +!air.fragment = !{!41, !47} +!air.compile_options = !{!50, !51, !52} +!llvm.ident = !{!53} +!air.version = !{!54} +!air.language_version = !{!55} -!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 26, i32 5]} +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} !1 = !{i32 1, !"wchar_size", i32 4} !2 = !{i32 7, !"frame-pointer", i32 2} !3 = !{i32 7, !"air.max_device_buffers", i32 31} @@ -128,63 +128,64 @@ attributes #4 = { nounwind readnone willreturn } !6 = !{i32 7, !"air.max_textures", i32 128} !7 = !{i32 7, !"air.max_read_write_textures", i32 8} !8 = !{i32 7, !"air.max_samplers", i32 16} -!9 = !{<{ <4 x float>, <4 x float>, <2 x float>, i32 }> (i32, i16, i16, <4 x float> addrspace(2)*)* @amp_vertex, !10, !15} +!9 = !{<{ <4 x float>, <4 x float>, <2 x float>, i32 }> (i32, i32, i16, i16, <4 x float> addrspace(2)*)* @amp_vertex, !10, !15} !10 = !{!11, !12, !13, !14} !11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} !12 = !{!"air.vertex_output", !"user(locn0)", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} !13 = !{!"air.vertex_output", !"generated(2uvDv2_f)", !"air.shared", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"} !14 = !{!"air.viewport_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} -!15 = !{!16, !17, !18, !19} +!15 = !{!16, !17, !18, !19, !20} !16 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} -!17 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} -!18 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} -!19 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"offsets"} -!20 = !{<4 x float> (i32, i32, i32, i32 addrspace(1)*)* @amp_vertex_store, !21, !23} -!21 = !{!22} -!22 = !{!"air.position", !"air.shared", !"air.arg_type_name", !"float4"} -!23 = !{!16, !24, !25, !26} -!24 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"amp"} -!25 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"uint", !"air.arg_name", !"count"} -!26 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} -!27 = !{<{ <4 x float>, i32 }> (i32, i16, i32 addrspace(2)*)* @amp_vertex_layer, !28, !30} -!28 = !{!11, !29} -!29 = !{!"air.render_target_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} -!30 = !{!16, !17, !31} -!31 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"slices"} -!32 = !{<4 x float> (<3 x float>, i16, i16)* @amp_post_tessellation, !33, !35, !37} -!33 = !{!34} -!34 = !{!"air.position", !"air.arg_type_name", !"float4"} -!35 = !{!36, !17, !18} -!36 = !{i32 0, !"air.position_in_patch", !"air.arg_type_name", !"float3", !"air.arg_name", !"bary"} -!37 = !{!"air.patch", !"triangle", !"air.patch_control_point", i32 3} -!38 = !{<4 x float> (<4 x float>, i32, i16, i16)* @amp_fragment, !39, !41} -!39 = !{!40} -!40 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} -!41 = !{!42, !43, !44, !45} -!42 = !{i32 0, !"air.fragment_input", !"user(locn0)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} -!43 = !{i32 1, !"air.viewport_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} -!44 = !{i32 2, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} -!45 = !{i32 3, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} -!46 = !{<4 x float> (i32, i16)* @amp_fragment_layer, !39, !47} -!47 = !{!48, !17} -!48 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} -!49 = !{!"air.compile.denorms_disable"} -!50 = !{!"air.compile.fast_math_enable"} -!51 = !{!"air.compile.framebuffer_fetch_enable"} -!52 = !{!"Apple metal version 32023.883 (metalfe-32023.883)"} -!53 = !{i32 2, i32 8, i32 0} -!54 = !{!"Metal", i32 4, i32 0, i32 0} -!55 = !{!56, !56, i64 0} -!56 = !{!"omnipotent char", !57, i64 0} -!57 = !{!"Simple C++ TBAA"} -!58 = !{!59} -!59 = distinct !{!59, !60, !"air-alias-scope-arg(3)"} -!60 = distinct !{!60, !"air-alias-scopes(amp_vertex)"} -!61 = !{!62, !62, i64 0} -!62 = !{!"int", !56, i64 0} -!63 = !{!64} -!64 = distinct !{!64, !65, !"air-alias-scope-arg(3)"} -!65 = distinct !{!65, !"air-alias-scopes(amp_vertex_store)"} -!66 = !{!67} -!67 = distinct !{!67, !68, !"air-alias-scope-arg(2)"} -!68 = distinct !{!68, !"air-alias-scopes(amp_vertex_layer)"} +!17 = !{i32 1, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"} +!18 = !{i32 2, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} +!19 = !{i32 3, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} +!20 = !{i32 4, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"offsets"} +!21 = !{<4 x float> (i32, i32, i32, i32 addrspace(1)*)* @amp_vertex_store, !22, !24} +!22 = !{!23} +!23 = !{!"air.position", !"air.shared", !"air.arg_type_name", !"float4"} +!24 = !{!16, !25, !26, !27} +!25 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"amp"} +!26 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"uint", !"air.arg_name", !"count"} +!27 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!28 = !{<{ <4 x float>, i32 }> (i32, i32, i16, i32 addrspace(2)*)* @amp_vertex_layer, !29, !31} +!29 = !{!11, !30} +!30 = !{!"air.render_target_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} +!31 = !{!16, !17, !18, !32} +!32 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"slices"} +!33 = !{<4 x float> (<3 x float>, i16, i16)* @amp_post_tessellation, !34, !36, !40} +!34 = !{!35} +!35 = !{!"air.position", !"air.arg_type_name", !"float4"} +!36 = !{!37, !38, !39} +!37 = !{i32 0, !"air.position_in_patch", !"air.arg_type_name", !"float3", !"air.arg_name", !"bary"} +!38 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} +!39 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} +!40 = !{!"air.patch", !"triangle", !"air.patch_control_point", i32 3} +!41 = !{<4 x float> (<4 x float>, i32, i16, i16)* @amp_fragment, !42, !44} +!42 = !{!43} +!43 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!44 = !{!45, !46, !18, !19} +!45 = !{i32 0, !"air.fragment_input", !"user(locn0)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!46 = !{i32 1, !"air.viewport_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} +!47 = !{<4 x float> (i32, i16)* @amp_fragment_layer, !42, !48} +!48 = !{!49, !38} +!49 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} +!50 = !{!"air.compile.denorms_disable"} +!51 = !{!"air.compile.fast_math_enable"} +!52 = !{!"air.compile.framebuffer_fetch_enable"} +!53 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!54 = !{i32 2, i32 8, i32 0} +!55 = !{!"Metal", i32 4, i32 0, i32 0} +!56 = !{!57, !57, i64 0} +!57 = !{!"omnipotent char", !58, i64 0} +!58 = !{!"Simple C++ TBAA"} +!59 = !{!60} +!60 = distinct !{!60, !61, !"air-alias-scope-arg(4)"} +!61 = distinct !{!61, !"air-alias-scopes(amp_vertex)"} +!62 = !{!63, !63, i64 0} +!63 = !{!"int", !57, i64 0} +!64 = !{!65} +!65 = distinct !{!65, !66, !"air-alias-scope-arg(3)"} +!66 = distinct !{!66, !"air-alias-scopes(amp_vertex_store)"} +!67 = !{!68} +!68 = distinct !{!68, !69, !"air-alias-scope-arg(3)"} +!69 = distinct !{!69, !"air-alias-scopes(amp_vertex_layer)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.ll b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.ll index 37fbc8ab5..7288af7a4 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.ll +++ b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.ll @@ -5,32 +5,32 @@ target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3 target triple = "air64_v28-apple-macosx26.0.0" ; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) -define <{ <4 x float>, <4 x float>, <2 x float>, i32 }> @amp_vertex(i32 noundef %0, i16 noundef %1, i16 noundef %2, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %3) local_unnamed_addr #0 { - %5 = shl i32 %0, 1 - %6 = and i32 %5, 2 - %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #4 - %8 = insertelement <2 x float> undef, float %7, i64 0 - %9 = and i32 %0, 2 - %10 = tail call fast float @air.convert.f.f32.u.i32(i32 %9) #4 - %11 = insertelement <2 x float> %8, float %10, i64 1 - %12 = fmul fast <2 x float> %11, splat (float 2.000000e+00) - %13 = fadd fast <2 x float> %12, splat (float -1.000000e+00) - %14 = shufflevector <2 x float> %13, <2 x float> poison, <4 x i32> - %15 = shufflevector <4 x float> %14, <4 x float> , <4 x i32> - %16 = zext i16 %1 to i64 - %17 = getelementptr inbounds <4 x float>, ptr addrspace(2) %3, i64 %16 - %18 = load <4 x float>, ptr addrspace(2) %17, align 16, !tbaa !55, !alias.scope !58 - %19 = fadd fast <4 x float> %15, %18 - %20 = tail call fast float @air.convert.f.f32.u.i16(i16 %1) #4 +define <{ <4 x float>, <4 x float>, <2 x float>, i32 }> @amp_vertex(i32 noundef %0, i32 noundef %1, i16 noundef %2, i16 noundef %3, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %4) local_unnamed_addr #0 { + %6 = shl i32 %0, 1 + %7 = and i32 %6, 2 + %8 = tail call fast float @air.convert.f.f32.u.i32(i32 %7) #4 + %9 = insertelement <2 x float> undef, float %8, i64 0 + %10 = and i32 %0, 2 + %11 = tail call fast float @air.convert.f.f32.u.i32(i32 %10) #4 + %12 = insertelement <2 x float> %9, float %11, i64 1 + %13 = fmul fast <2 x float> %12, splat (float 2.000000e+00) + %14 = fadd fast <2 x float> %13, splat (float -1.000000e+00) + %15 = shufflevector <2 x float> %14, <2 x float> poison, <4 x i32> + %16 = shufflevector <4 x float> %15, <4 x float> , <4 x i32> + %17 = zext i16 %2 to i64 + %18 = getelementptr inbounds <4 x float>, ptr addrspace(2) %4, i64 %17 + %19 = load <4 x float>, ptr addrspace(2) %18, align 16, !tbaa !56, !alias.scope !59 + %20 = fadd fast <4 x float> %16, %19 %21 = tail call fast float @air.convert.f.f32.u.i16(i16 %2) #4 - %22 = insertelement <4 x float> , float %20, i64 0 - %23 = insertelement <4 x float> %22, float %21, i64 1 - %24 = and i32 %0, 1 - %25 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> undef, <4 x float> %19, 0 - %26 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %25, <4 x float> %23, 1 - %27 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %26, <2 x float> %11, 2 - %28 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %27, i32 %24, 3 - ret <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %28 + %22 = tail call fast float @air.convert.f.f32.u.i16(i16 %3) #4 + %23 = insertelement <4 x float> , float %21, i64 0 + %24 = insertelement <4 x float> %23, float %22, i64 1 + %25 = and i32 %1, 1 + %26 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> undef, <4 x float> %20, 0 + %27 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %26, <4 x float> %24, 1 + %28 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %27, <2 x float> %12, 2 + %29 = insertvalue <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %28, i32 %25, 3 + ret <{ <4 x float>, <4 x float>, <2 x float>, i32 }> %29 } ; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) @@ -48,23 +48,23 @@ define <4 x float> @amp_vertex_store(i32 noundef %0, i32 noundef %1, i32 noundef %9 = add i32 %8, %1 %10 = zext i32 %9 to i64 %11 = getelementptr inbounds i32, ptr addrspace(1) %3, i64 %10 - store i32 %7, ptr addrspace(1) %11, align 4, !tbaa !61, !alias.scope !63 + store i32 %7, ptr addrspace(1) %11, align 4, !tbaa !62, !alias.scope !64 ret <4 x float> } ; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) -define <{ <4 x float>, i32 }> @amp_vertex_layer(i32 noundef %0, i16 noundef %1, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %2) local_unnamed_addr #0 { - %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %0) #4 - %5 = tail call fast float @air.convert.f.f32.u.i16(i16 %1) #4 - %6 = insertelement <4 x float> , float %4, i64 0 - %7 = insertelement <4 x float> %6, float %5, i64 1 - %8 = and i32 %0, 1 - %9 = zext i32 %8 to i64 - %10 = getelementptr inbounds i32, ptr addrspace(2) %2, i64 %9 - %11 = load i32, ptr addrspace(2) %10, align 4, !tbaa !61, !alias.scope !66 - %12 = insertvalue <{ <4 x float>, i32 }> undef, <4 x float> %7, 0 - %13 = insertvalue <{ <4 x float>, i32 }> %12, i32 %11, 1 - ret <{ <4 x float>, i32 }> %13 +define <{ <4 x float>, i32 }> @amp_vertex_layer(i32 noundef %0, i32 noundef %1, i16 noundef %2, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %3) local_unnamed_addr #0 { + %5 = tail call fast float @air.convert.f.f32.u.i32(i32 %0) #4 + %6 = tail call fast float @air.convert.f.f32.u.i16(i16 %2) #4 + %7 = insertelement <4 x float> , float %5, i64 0 + %8 = insertelement <4 x float> %7, float %6, i64 1 + %9 = and i32 %1, 1 + %10 = zext i32 %9 to i64 + %11 = getelementptr inbounds i32, ptr addrspace(2) %3, i64 %10 + %12 = load i32, ptr addrspace(2) %11, align 4, !tbaa !62, !alias.scope !67 + %13 = insertvalue <{ <4 x float>, i32 }> undef, <4 x float> %8, 0 + %14 = insertvalue <{ <4 x float>, i32 }> %13, i32 %12, 1 + ret <{ <4 x float>, i32 }> %14 } ; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) @@ -112,14 +112,14 @@ attributes #3 = { mustprogress nofree nosync nounwind willreturn memory(none) "a attributes #4 = { nounwind willreturn memory(none) } !llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} -!air.vertex = !{!9, !20, !27, !32} -!air.fragment = !{!38, !46} -!air.compile_options = !{!49, !50, !51} -!llvm.ident = !{!52} -!air.version = !{!53} -!air.language_version = !{!54} +!air.vertex = !{!9, !21, !28, !33} +!air.fragment = !{!41, !47} +!air.compile_options = !{!50, !51, !52} +!llvm.ident = !{!53} +!air.version = !{!54} +!air.language_version = !{!55} -!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 26, i32 5]} +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} !1 = !{i32 1, !"wchar_size", i32 4} !2 = !{i32 7, !"frame-pointer", i32 2} !3 = !{i32 7, !"air.max_device_buffers", i32 31} @@ -134,57 +134,58 @@ attributes #4 = { nounwind willreturn memory(none) } !12 = !{!"air.vertex_output", !"user(locn0)", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} !13 = !{!"air.vertex_output", !"generated(2uvDv2_f)", !"air.shared", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"} !14 = !{!"air.viewport_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} -!15 = !{!16, !17, !18, !19} +!15 = !{!16, !17, !18, !19, !20} !16 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} -!17 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} -!18 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} -!19 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"offsets"} -!20 = !{ptr @amp_vertex_store, !21, !23} -!21 = !{!22} -!22 = !{!"air.position", !"air.shared", !"air.arg_type_name", !"float4"} -!23 = !{!16, !24, !25, !26} -!24 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"amp"} -!25 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"uint", !"air.arg_name", !"count"} -!26 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} -!27 = !{ptr @amp_vertex_layer, !28, !30} -!28 = !{!11, !29} -!29 = !{!"air.render_target_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} -!30 = !{!16, !17, !31} -!31 = !{i32 2, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"slices"} -!32 = !{ptr @amp_post_tessellation, !33, !35, !37} -!33 = !{!34} -!34 = !{!"air.position", !"air.arg_type_name", !"float4"} -!35 = !{!36, !17, !18} -!36 = !{i32 0, !"air.position_in_patch", !"air.arg_type_name", !"float3", !"air.arg_name", !"bary"} -!37 = !{!"air.patch", !"triangle", !"air.patch_control_point", i32 3} -!38 = !{ptr @amp_fragment, !39, !41} -!39 = !{!40} -!40 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} -!41 = !{!42, !43, !44, !45} -!42 = !{i32 0, !"air.fragment_input", !"user(locn0)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} -!43 = !{i32 1, !"air.viewport_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} -!44 = !{i32 2, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} -!45 = !{i32 3, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} -!46 = !{ptr @amp_fragment_layer, !39, !47} -!47 = !{!48, !17} -!48 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} -!49 = !{!"air.compile.denorms_disable"} -!50 = !{!"air.compile.fast_math_enable"} -!51 = !{!"air.compile.framebuffer_fetch_enable"} -!52 = !{!"Apple metal version 32023.883 (metalfe-32023.883)"} -!53 = !{i32 2, i32 8, i32 0} -!54 = !{!"Metal", i32 4, i32 0, i32 0} -!55 = !{!56, !56, i64 0} -!56 = !{!"omnipotent char", !57, i64 0} -!57 = !{!"Simple C++ TBAA"} -!58 = !{!59} -!59 = distinct !{!59, !60, !"air-alias-scope-arg(3)"} -!60 = distinct !{!60, !"air-alias-scopes(amp_vertex)"} -!61 = !{!62, !62, i64 0} -!62 = !{!"int", !56, i64 0} -!63 = !{!64} -!64 = distinct !{!64, !65, !"air-alias-scope-arg(3)"} -!65 = distinct !{!65, !"air-alias-scopes(amp_vertex_store)"} -!66 = !{!67} -!67 = distinct !{!67, !68, !"air-alias-scope-arg(2)"} -!68 = distinct !{!68, !"air-alias-scopes(amp_vertex_layer)"} +!17 = !{i32 1, !"air.instance_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"iid"} +!18 = !{i32 2, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} +!19 = !{i32 3, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} +!20 = !{i32 4, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"offsets"} +!21 = !{ptr @amp_vertex_store, !22, !24} +!22 = !{!23} +!23 = !{!"air.position", !"air.shared", !"air.arg_type_name", !"float4"} +!24 = !{!16, !25, !26, !27} +!25 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"amp"} +!26 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"uint", !"air.arg_name", !"count"} +!27 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!28 = !{ptr @amp_vertex_layer, !29, !31} +!29 = !{!11, !30} +!30 = !{!"air.render_target_array_index", !"air.shared", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} +!31 = !{!16, !17, !18, !32} +!32 = !{i32 3, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"slices"} +!33 = !{ptr @amp_post_tessellation, !34, !36, !40} +!34 = !{!35} +!35 = !{!"air.position", !"air.arg_type_name", !"float4"} +!36 = !{!37, !38, !39} +!37 = !{i32 0, !"air.position_in_patch", !"air.arg_type_name", !"float3", !"air.arg_name", !"bary"} +!38 = !{i32 1, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"} +!39 = !{i32 2, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"} +!40 = !{!"air.patch", !"triangle", !"air.patch_control_point", i32 3} +!41 = !{ptr @amp_fragment, !42, !44} +!42 = !{!43} +!43 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!44 = !{!45, !46, !18, !19} +!45 = !{i32 0, !"air.fragment_input", !"user(locn0)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!46 = !{i32 1, !"air.viewport_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"viewport"} +!47 = !{ptr @amp_fragment_layer, !42, !48} +!48 = !{!49, !38} +!49 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"layer"} +!50 = !{!"air.compile.denorms_disable"} +!51 = !{!"air.compile.fast_math_enable"} +!52 = !{!"air.compile.framebuffer_fetch_enable"} +!53 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!54 = !{i32 2, i32 8, i32 0} +!55 = !{!"Metal", i32 4, i32 0, i32 0} +!56 = !{!57, !57, i64 0} +!57 = !{!"omnipotent char", !58, i64 0} +!58 = !{!"Simple C++ TBAA"} +!59 = !{!60} +!60 = distinct !{!60, !61, !"air-alias-scope-arg(4)"} +!61 = distinct !{!61, !"air-alias-scopes(amp_vertex)"} +!62 = !{!63, !63, i64 0} +!63 = !{!"int", !57, i64 0} +!64 = !{!65} +!65 = distinct !{!65, !66, !"air-alias-scope-arg(3)"} +!66 = distinct !{!66, !"air-alias-scopes(amp_vertex_store)"} +!67 = !{!68} +!68 = distinct !{!68, !69, !"air-alias-scope-arg(3)"} +!69 = distinct !{!69, !"air-alias-scopes(amp_vertex_layer)"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.metal b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.metal index edc3ae79c..7a2c03c69 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.metal +++ b/crates/metal2vulkan-validation/fixtures/public/engine/vertex_amplification.metal @@ -14,8 +14,10 @@ struct AmpOut { // Each amplification moves the position by its own offset. `uv` depends only on the vertex, so it // is shared by every amplification; the viewport, a built-in output, is shared by default (MSL -// §5.2.3.3), so it must not depend on the amplification either. +// §5.2.3.3), so it must not depend on the amplification either. It depends on the instance alone, +// the same at every vertex of a primitive, as Metal asks of it. vertex AmpOut amp_vertex(uint vid [[vertex_id]], + uint iid [[instance_id]], ushort amp [[amplification_id]], ushort count [[amplification_count]], constant float4 *offsets [[buffer(0)]]) @@ -25,7 +27,7 @@ vertex AmpOut amp_vertex(uint vid [[vertex_id]], out.position = float4(corner * 2.0f - 1.0f, 0.0f, 1.0f) + offsets[amp]; out.color = float4(float(amp), float(count), 0.25f, 1.0f); out.uv = corner; - out.viewport = vid & 1u; + out.viewport = iid & 1u; return out; } @@ -45,14 +47,16 @@ struct AmpLayerOut { uint layer [[render_target_array_index]]; }; -// Chooses its render target slice itself: the layer output a multiview pipeline cannot declare. +// Chooses its render target slice itself, per instance: the layer output a multiview pipeline +// cannot declare. vertex AmpLayerOut amp_vertex_layer(uint vid [[vertex_id]], + uint iid [[instance_id]], ushort amp [[amplification_id]], constant uint *slices [[buffer(0)]]) { AmpLayerOut out; out.position = float4(float(vid), float(amp), 0.0f, 1.0f); - out.layer = slices[vid & 1u]; + out.layer = slices[iid & 1u]; return out; } diff --git a/crates/metal2vulkan-validation/src/coverage.rs b/crates/metal2vulkan-validation/src/coverage.rs index 4ad6dbcff..556de7536 100644 --- a/crates/metal2vulkan-validation/src/coverage.rs +++ b/crates/metal2vulkan-validation/src/coverage.rs @@ -311,9 +311,8 @@ impl ModuleCensus { /// control stages run none and are left out: the pipeline is tessellated exactly when it has an /// evaluation stage. So are a render pipeline's geometry stages: Metal has no geometry /// function, so every one is a stage link synthesizes between the vertex and fragment - /// functions (`metal2vulkan::pipeline::link::geometry`: the barycentric weights, or the slice - /// and viewport a vertex function selects). `Err` names a module of a stage no Metal function - /// has. + /// functions (`metal2vulkan::pipeline::link::geometry`: the barycentric weights). `Err` names + /// a module of a stage no Metal function has. pub fn of_pipeline_modules( modules: &[StageModule], profile: &DeviceProfile, diff --git a/crates/metal2vulkan-validation/src/coverage/tests.rs b/crates/metal2vulkan-validation/src/coverage/tests.rs index 8dbab2933..6886b1415 100644 --- a/crates/metal2vulkan-validation/src/coverage/tests.rs +++ b/crates/metal2vulkan-validation/src/coverage/tests.rs @@ -239,11 +239,11 @@ fn a_tessellation_pipeline_census_is_its_functions() { } /// A render pipeline's census leaves out its geometry stages, which run no Metal function: a -/// vertex function whose slice and viewport differ among a primitive's vertices -/// (`engine/rt6_first_vertex`) stores them through the synthesized geometry stage of each topology -/// class on a device whose driver does not take Metal's first-vertex indices (the Radeon 780M's -/// committed capture), so the pipeline's modules are its vertex function's, three geometry stages -/// and its fragment function's, and its census is the two functions'. +/// fragment function that reads `[[barycentric_coord]]` (`engine/bary_weights`) reads the weights +/// from the synthesized geometry stage of each topology class on a device without +/// `fragmentShaderBarycentric` (the Radeon 780M's committed capture without it), so the +/// pipeline's modules are its vertex function's, three geometry stages and its fragment +/// function's, and its census is the two functions'. #[test] fn a_render_pipeline_census_leaves_out_its_geometry_stages() { use metal2vulkan::device::{Device, DevicePolicy}; @@ -254,28 +254,28 @@ fn a_render_pipeline_census_leaves_out_its_geometry_stages() { }; use metal2vulkan::Budget; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; - let bitcode = match llvm_assemble(&engine_dir().join("rt6_first_vertex.ll")) { + let bitcode = match llvm_assemble(&engine_dir().join("bary_weights.ll")) { Ok(bytes) => bytes, Err(AssembleError::Missing(why)) => { eprintln!("SKIPPED: {why}"); return; } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected rt6_first_vertex.ll: {why}"), + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected bary_weights.ll: {why}"), }; let path = crate::engine::profiles_dir().join("amd-780m-radv.json"); let text = std::fs::read_to_string(&path).unwrap(); - let device = Device::from_queries( - DeviceDescription::from_khronos_json(&text, None).unwrap(), - DevicePolicy::default(), - ) - .unwrap(); + let mut description = DeviceDescription::from_khronos_json(&text, None).unwrap(); + assert!(description + .features + .remove(&VkFeature::FragmentShaderBarycentric)); + let device = Device::from_queries(description, DevicePolicy::default()).unwrap(); let library = Library::from_air(&bitcode).unwrap(); let stage = |name: &str| { StageSource::Function(FunctionDescriptor::new(library.function(name).unwrap())) }; - let mut d = RenderPipelineDescriptor::new(stage("rt6_first_vertex")); - d.fragment = Some(stage("rt6_first_vertex_read")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Uint)); + let mut d = RenderPipelineDescriptor::new(stage("bw_vertex")); + d.fragment = Some(stage("bw_perspective")); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); let pipeline = device .compile_render_pipeline(&d, &Budget::standard()) .unwrap(); diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index ac2eb28ff..e0bfc223f 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -579,9 +579,8 @@ impl RenderPipeline { /// vertex and control stages run none, and its post-tessellation vertex function is its /// evaluation stage; a mesh render pipeline's object and mesh functions are its task and mesh /// stages; the geometry stages link -/// generates (`link::geometry`: barycentric weights read as varyings, a selected slice or -/// viewport) run none and bind nothing, nor do a band variant's (`banded`) control and evaluation -/// stages (`link::band`). +/// generates (`link::geometry`: barycentric weights read as varyings) run none and bind nothing, +/// nor do a band variant's (`banded`) control and evaluation stages (`link::band`). fn metal_stages( stages: impl ExactSizeIterator, (tessellated, banded): (bool, bool), diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 823b6f8dc..24eb1ad44 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1046,7 +1046,6 @@ codec_enum! { DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve, VariableSampleLocations, SampleLocationSampleCount(f0), ColorAttachmentSampleCount(f0, f1), DeviceSampling, - MetalFirstVertexIndices, ProvokingVertexModePerPipeline, InterpolateAtOffsetFromSevenSixteenths, SubgroupGeometryStage, @@ -1184,7 +1183,7 @@ codec_enum! { Attribute { index }, Varying { user, interpolation }, Color { attachment, index }, ViewportIndex, RenderTargetArrayIndex, PrimitiveVarying { user }, - Barycentric { perspective }, SelectedLayer, SelectedViewport, PrimitiveId, MergedCommand, + Barycentric { perspective }, PrimitiveId, MergedCommand, } IoInterpolation { Flat, Smooth { sampling, perspective } } IoSampling { Center, Centroid, Sample, Interpolant { center, centroid, sample } } @@ -1284,7 +1283,7 @@ codec_enum! { AnisotropicSampler { slot }, StorageTextureIntegerChannels { slot }, MovableStorageWrites { early_variant }, - SynthesizedGeometry { weights, layer, viewport }, + SynthesizedGeometry { weights }, ObjectThreadgroupArena { static_bytes, payload }, MergedDraws, QuadPrimitiveIds, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index aceb09503..affba5de8 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2245; +pub const SEMANTICS_VERSION: u32 = 2246; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2245; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 582; +pub const ARTIFACT_FORMAT_VERSION: u32 = 583; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index efc56c921..1ac13853f 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::air::container::Hash256; use crate::device::requirements::{ApiVersion, FormatUsage, VkExtension, VkFeature, VkProperty}; use crate::device::subgroup::{SimdClass, SubgroupModel, Tier}; -use crate::error::{Capability, DriverDeviation, Unsupported}; +use crate::error::{Capability, Unsupported}; use crate::memory::contain::Check; use crate::pipeline::sym::Stage; use crate::vk; @@ -208,21 +208,6 @@ impl DeviceProfile { crate::memory::contain::device_drops_texel_writes(self, texel_buffer) } - /// Whether the profile takes the driver deviation `deviation` (`device::driver_facts`): its - /// driver is measured with it on the device's GPU, so the translation relies on it. A - /// profile that does not take it compiles the route the deviation's documentation names for a - /// driver without it. A gate lane that checks a deviation on the device asks this before - /// expecting the deviation's answer. - pub fn takes_driver_deviation(&self, deviation: DriverDeviation) -> bool { - let f = &self.fields; - match deviation { - DriverDeviation::MetalFirstVertexIndices => f - .enabled - .properties - .contains(&VkProperty::MetalFirstVertexIndices), - } - } - /// What this profile lacks of `GLSL.std.450`'s interpolation functions (the /// `InterpolationFunction` capability: `InterpolateAtCentroid`, `InterpolateAtSample`, /// `InterpolateAtOffset`): `sampleRateShading`, and on a portability-subset device diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 1b9dcb81e..c340642bc 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -628,15 +628,6 @@ pub enum VkProperty { /// leaves a sample to the device's sampler requires it and records /// [`PrecisionNote::DeviceSampling`](crate::pipeline::PrecisionNote::DeviceSampling). DeviceSampling, - /// The device takes a primitive's `Layer` and `ViewportIndex` from its first vertex, whatever - /// its other vertices store, as Metal takes a primitive's slice and viewport (the driver's - /// measured deviation - /// [`DriverDeviation::MetalFirstVertexIndices`](crate::error::DriverDeviation::MetalFirstVertexIndices)). - /// No Vulkan query reports it: Vulkan takes them only where every vertex of a primitive - /// stores the same. A vertex module that stores an index differing among a primitive's - /// vertices to its builtin requires it; without it, the index goes through the pipeline's - /// synthesized geometry stages. - MetalFirstVertexIndices, /// `provokingVertexModePerPipeline` (`VkPhysicalDeviceProvokingVertexPropertiesEXT`, where /// `VK_EXT_provoking_vertex` is listed): the pipelines bound within one render pass instance /// may have different provoking vertex modes. Without it "all pipelines bound within a render diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 406e05650..006f650e4 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -265,16 +265,8 @@ fn every_fact() -> Vec { RuntimeFact::MovableStorageWrites { early_variant: true, }, - RuntimeFact::SynthesizedGeometry { - weights: true, - layer: false, - viewport: false, - }, - RuntimeFact::SynthesizedGeometry { - weights: false, - layer: true, - viewport: true, - }, + RuntimeFact::SynthesizedGeometry { weights: true }, + RuntimeFact::SynthesizedGeometry { weights: false }, RuntimeFact::ObjectThreadgroupArena { static_bytes: 16, payload: Some(64), diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 844e82468..bcca8b664 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -482,24 +482,6 @@ pub enum Needs { MetalRefuses(&'static [&'static str]), } -/// A driver's measured answer where the specifications leave it to the device, per driver and -/// GPU (`device::driver_facts`): the profile takes it on every release of a driver measured with -/// it. Where the profile takes it a module relies on it (and requires its property) or records no -/// note; elsewhere each variant names the route taken: the device's own answer, recorded as a -/// precision note, or, where the answer decides a capability, its emulation or a refusal. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum DriverDeviation { - /// The device takes a primitive's `Layer` and `ViewportIndex` from its first vertex, whatever - /// its other vertices store, as Metal takes a primitive's slice and viewport - /// (`VkProperty::MetalFirstVertexIndices`). Vulkan takes them only where every vertex of a - /// primitive stores the same. Where the profile takes it, a vertex function whose index differs - /// among a primitive's vertices stores it to its builtin. Unmeasured, it stores it through the - /// pipeline's synthesized geometry stages, which store the first vertex's at every vertex, - /// and is refused on a device without `geometryShader`. - MetalFirstVertexIndices, -} - /// One device capability a refusal can name. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index e83840087..4847facd9 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -82,14 +82,13 @@ //! `uint` varying (`IoRole::ViewportIndex`), which a fragment function compiled under //! `LoweringInputs::viewport_index_varying` reads as its `[[viewport_array_index]]`; any other //! fragment function reads `ViewportIndex` (0 when no stage writes it). -//! - Where the device cannot store `Layer` or `ViewportIndex` from a vertex function -//! (`shaderOutputLayer`, `shaderOutputViewportIndex`), the function stores the value it would -//! store there to a flat `uint` varying instead (`IoRole::SelectedLayer`, -//! `IoRole::SelectedViewport`), and the pipeline's synthesized geometry stages store the builtin -//! from the primitive's first vertex (`link::geometry`), Metal's rule; that needs -//! `geometryShader`, else the function is refused needing either feature. On a device without -//! `multiViewport` a draw has one viewport, so every index selects viewport 0 and no -//! `ViewportIndex` is stored at all: the raw varying alone. A fragment function that reads an +//! - A vertex function stores `Layer` or `ViewportIndex` only where it writes the index the same at +//! every vertex of a primitive, as its structure shows (`StageIo::uniform_outputs`), and the +//! device stores the builtin from a vertex function (`shaderOutputLayer`, +//! `shaderOutputViewportIndex`). One written alike on a device without the output is refused +//! needing it; one not shown alike is refused as not implemented (`plan::index_store`). On a +//! device without `multiViewport` a draw has one viewport, so every index selects viewport 0 and +//! no `ViewportIndex` is stored at all: the raw varying alone. A fragment function that reads an //! index no stage can have written (no varying input names it, and the device declares neither //! builtin) reads 0, Metal's value with no vertex write (`StageIo::zero_indices`). //! @@ -410,9 +409,6 @@ pub struct StageIoPlan { pub zeroed: Vec, /// The shape of the returned value. pub returned: Returned, - /// A vertex function stores every slice and viewport index it stores to its selected index - /// (`IoRole::SelectedLayer`, `IoRole::SelectedViewport`), as it stores one of them there. - pub indices_selected: bool, /// The `PointSize` object a vertex function without a point-size output writes 1.0 to. pub point_size_default: Option, /// The `Position` object of a vertex function, decorated `Invariant`. @@ -463,10 +459,6 @@ pub struct StageIoPlan { /// (`ModuleBuilder::offsets_from_seven_sixteenths`) and requires that property in place of /// `VkProperty::InterpolateAtOffsetCentered`. pub offsets_from_seven_sixteenths: bool, - /// A vertex function stores an index that differs among a primitive's vertices to its - /// builtin, because its device takes the first vertex's as Metal does - /// (`VkProperty::MetalFirstVertexIndices`): the module requires that property. - pub first_vertex_indices_by_device: bool, /// A vertex function compiled in the de-indexed or private list form reads its vertex from /// the draw's indices ([`CapturedIndex`]): planned where the function reads it /// (`[[vertex_id]]`, a per-vertex attribute, `[[base_vertex]]` or the primitive ID). diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 9a202bf08..0cae0638a 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -10,7 +10,7 @@ use crate::air::abi::{ use crate::air::intrinsics::{AirIntrinsic, Fragment as AirFragment, InterpolateAt}; use crate::air::ir::{ArgIdx, Callee, InstKind, Type, TypeId as AirTypeId, Value}; use crate::device::requirements::{VkExtension, VkFeature, VkLimit, VkProperty}; -use crate::error::{Attachment, Capability, DriverDeviation, Error, Feature, Unsupported}; +use crate::error::{Attachment, Capability, Error, Feature, Unsupported}; use crate::lower::arith::legal::{form_on, refuse_bfloat_color, refuse_int64_interface}; use crate::lower::arith::{Form, Held}; use crate::lower::select::SelectCx; @@ -1137,7 +1137,7 @@ fn zeroed_output( /// Plan output `index` of a vertex function compiled under `LoweringInputs::amplification_draws` /// that writes no such index: stored as the amplification's offset below its count push field -/// ([`AmplifiedOutput`]) where [`index_store`] stores it, to its builtin or its selected index. +/// ([`AmplifiedOutput`]) where [`index_store`] stores it, to its builtin. /// Metal renders the amplification through the slice or viewport its offset names, the first at or /// past the count (a Metal probe on the M3 Max and an M4). fn amplified_output(cx: &mut SelectCx<'_>, index: AmplifiedIndex) -> Result<(), Error> { @@ -1167,10 +1167,7 @@ fn amplified_output(cx: &mut SelectCx<'_>, index: AmplifiedIndex) -> Result<(), cx.push.insert(offset); cx.push.insert(below); let sp = &mut cx.families.stage_io; - let object = match store { - IndexStore::Selected => selected_index(sp, raw)?, - _ => builtin(sp, spirv, IoDir::Output, Shape::U32, contract), - }; + let object = builtin(sp, spirv, IoDir::Output, Shape::U32, contract); sp.amplified.push(AmplifiedOutput { link: Link { object, @@ -1439,10 +1436,6 @@ enum RawIndex { enum IndexStore { /// To its builtin, `Layer` or `ViewportIndex`. Builtin, - /// To its selected index (`IoRole::SelectedLayer`, `IoRole::SelectedViewport`), which the - /// pipeline's synthesized geometry stage stores to the builtin from the primitive's first - /// vertex (`pipeline::link::geometry`). - Selected, /// Nowhere: a viewport index on a device without `multiViewport`, whose draws have one /// viewport (the runtime refuses more), so Metal's index selects viewport 0 whatever it is, /// the viewport Vulkan uses where no stage writes `ViewportIndex`. @@ -1450,36 +1443,28 @@ enum IndexStore { } /// Where a vertex function on `cx`'s profile stores index `index`, which it writes the same at -/// every vertex of a primitive where `uniform` ([`uniform_index`]): to its selected index where -/// the function stores another there ([`StageIoPlan::indices_selected`]), and otherwise where -/// [`own_index_store`] puts it. +/// every vertex of a primitive where `uniform` ([`uniform_index`]): to its builtin where the +/// profile enables `shaderOutputLayer` (`shaderOutputViewportIndex` for a viewport index) and +/// the function writes the index alike, and nowhere, a viewport index on a profile without +/// `multiViewport`. Otherwise refused, as `VertexAmplification` for an index the function stores +/// from the amplification's offset alone (`amplification`), else as `LayeredRendering`: one +/// written alike needing the output feature, one not shown alike as not implemented on any +/// device. +/// +/// An index not shown alike is refused because Metal gives it no answer to match: "You must +/// return the same value of [[render_target_array_index]] for every vertex in a primitive. If +/// values differ, the behavior and value passed to the fragment function are undefined." (the +/// Metal Shading Language specification, and the same of `[[viewport_array_index]]`). It is not +/// stored to its builtin as written because Vulkan asks a stage that writes `Layer` to "write the +/// same value to Layer for all vertices of a given primitive" +/// (VUID-VkPipelineShaderStageCreateInfo-stage-02596), and the same of `ViewportIndex` +/// (VUID-VkPipelineShaderStageCreateInfo-stage-02597), which the function's structure does not +/// show of it. fn index_store( cx: &SelectCx<'_>, index: RawIndex, uniform: bool, amplification: bool, -) -> Result { - match own_index_store(cx, index, uniform, amplification)? { - IndexStore::Builtin if cx.families.stage_io.indices_selected => Ok(IndexStore::Selected), - store => Ok(store), - } -} - -/// Where a vertex function on `cx`'s profile stores index `index` taken alone. Vulkan takes a -/// primitive's `Layer` and `ViewportIndex` only where every vertex of it stores the same, Metal -/// the primitive's first vertex's whatever the others store. So: to its builtin where the profile -/// enables `shaderOutputLayer` (`shaderOutputViewportIndex` for a viewport index) and the function -/// writes the index the same at every vertex of a primitive (`uniform`), or the profile takes -/// `DriverDeviation::MetalFirstVertexIndices`; nowhere, a viewport index on a profile without -/// `multiViewport`; else to its selected index where the profile enables `geometryShader`. -/// Otherwise refused, as `VertexAmplification` for an index the function stores from the -/// amplification's offset alone (`amplification`), else as `LayeredRendering`: one written alike -/// needing the output feature or `geometryShader`, one not needing `geometryShader`. -fn own_index_store( - cx: &SelectCx<'_>, - index: RawIndex, - uniform: bool, - amplification: bool, ) -> Result { let f = cx.profile.fields(); let (native, output) = match index { @@ -1489,10 +1474,7 @@ fn own_index_store( VkFeature::ShaderOutputViewportIndex, ), }; - let first_vertex = cx - .profile - .takes_driver_deviation(DriverDeviation::MetalFirstVertexIndices); - if native && (uniform || first_vertex) { + if native && uniform { return Ok(IndexStore::Builtin); } if matches!(index, RawIndex::Viewport) @@ -1500,17 +1482,15 @@ fn own_index_store( { return Ok(IndexStore::Nowhere); } - if f.fragment.geometry_shader { - return Ok(IndexStore::Selected); + // An index stored from the amplification's offset alone is the same at every vertex. + if amplification { + return Err( + Unsupported::needs(Feature::VertexAmplification, Capability::Feature(output)).into(), + ); } - let geometry = vec![Capability::Feature(VkFeature::GeometryShader)]; - let needs = match uniform { - true => vec![vec![Capability::Feature(output)], geometry], - false => vec![geometry], - }; - Err(match amplification { - true => Unsupported::needs_any_of(Feature::VertexAmplification, needs), - false => Unsupported::needs_any_of(Feature::LayeredRendering, needs), + Err(match uniform { + true => Unsupported::needs(Feature::LayeredRendering, Capability::Feature(output)), + false => Unsupported::not_implemented(Feature::LayeredRendering), } .into()) } @@ -1527,74 +1507,6 @@ fn uniform_index(cx: &SelectCx<'_>, index: RawIndex) -> bool { .is_ok() } -/// Whether vertex function `cx`, with outputs `outputs`, drawn under `amplified` (`None` where it -/// returns nothing), stores one of the slice and viewport indices it stores to its selected index -/// ([`own_index_store`]). The pipeline's geometry stage then stores both builtins, and a vertex -/// function's own would not reach the rasterizer past it, so it stores every one there -/// ([`StageIoPlan::indices_selected`]). An index it writes and stores is uniform as written; one -/// it stores from the amplification's offset alone is uniform; a slice it writes in a pass of one -/// layer is stored nowhere. A refusal is left to the output that stores the index. -fn indices_selected( - cx: &SelectCx<'_>, - outputs: &[OutputBinding], - amplified: Option, -) -> bool { - let writes = |role: fn(&OutputRole) -> bool| outputs.iter().any(|o| role(&o.role)); - let layer = writes(|r| matches!(r, OutputRole::RenderTargetArrayIndex)); - let viewport = writes(|r| matches!(r, OutputRole::ViewportArrayIndex)); - let dropped = cx.inputs.dropped_vertex_layer || amplified.is_some_and(|d| !d.layered); - let stored = [ - ( - RawIndex::Layer, - if layer { - !dropped - } else { - amplified.is_some_and(|d| d.layered) - }, - !layer || uniform_index(cx, RawIndex::Layer), - ), - ( - RawIndex::Viewport, - viewport || amplified.is_some_and(|d| d.viewports), - !viewport || uniform_index(cx, RawIndex::Viewport), - ), - ]; - stored.into_iter().any(|(index, stored, uniform)| { - stored - && matches!( - own_index_store(cx, index, uniform, false), - Ok(IndexStore::Selected) - ) - }) -} - -/// The selected index's flat `uint` vertex output (`IoRole::SelectedLayer`, -/// `IoRole::SelectedViewport`), which the pipeline's synthesized geometry stage reads. -fn selected_index(sp: &mut StageIoPlan, index: RawIndex) -> Result { - let (key, role) = match index { - RawIndex::Viewport => (VaryingKey::selected_viewport(), IoRole::SelectedViewport), - RawIndex::Layer => (VaryingKey::selected_layer(), IoRole::SelectedLayer), - }; - let ty = IoType { - numeric: IoNumeric::Uint, - components: 1, - source_bits: 32, - }; - let deco = IoDecor { - packed: true, - ..IoDecor::default() - }; - push_var( - &mut sp.interface.outputs, - IoVariable { - key: key.clone(), - role, - ty, - }, - ); - user(sp, key, IoDir::Output, ty, deco) -} - /// Whether the profile can declare fragment input builtin `b`: one of its enabling /// capabilities' features ([`builtin_enablers`]) is enabled. fn declarable(cx: &SelectCx<'_>, b: crate::spv::BuiltIn) -> bool { @@ -2156,13 +2068,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { }); } let offset = |field| amplified.map(|_| field); - if cx.stage == Stage::Vertex { - cx.families.stage_io.indices_selected = indices_selected( - cx, - &outputs, - amplified.filter(|_| returned != Returned::Void), - ); - } // The pipeline's colors the pass lacks, whose writes plain Metal drops: stated whether or // not the function writes them, so the plan settles on the variant. let dropped = match cx.stage { @@ -3084,17 +2989,7 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result { - // Differing among a primitive's vertices, stored to the builtin only on a - // device that takes the first vertex's as Metal does. - cx.families.stage_io.first_vertex_indices_by_device |= !uniform; - out(cx, spirv, Shape::U32, Place::Whole, f, contract) - } - IndexStore::Selected => Link { - object: selected_index(&mut cx.families.stage_io, index)?, - place: Place::Whole, - form: f, - }, + IndexStore::Builtin => out(cx, spirv, Shape::U32, Place::Whole, f, contract), IndexStore::Nowhere => { return Err(cx.invariant("a viewport index stored nowhere as an output")) } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index b625afd37..f1d999c0e 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -24,14 +24,13 @@ pub struct RenderPipeline { pub key: PipelineKey, /// The fingerprint of the profile it was compiled for: a cache load checks it. pub profile: Hash256, - /// Vertex, then fragment when rasterization is enabled. A post-tessellation vertex - /// function's pipeline has the synthesized vertex and tessellation control stages, then its - /// evaluation stage, then the fragment stage. A pipeline whose fragment function reads - /// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`, or whose vertex - /// function selects its slice or viewport on a device without the output, has three - /// synthesized geometry stages (one set for every such need) before its fragment stage, or - /// last without one, for the point, line and triangle topology classes in that order: a - /// `VkPipeline` runs only the one of its draw's class ([`runs_stage`](Self::runs_stage)). + /// Vertex, then fragment when rasterization is enabled. A post-tessellation vertex function's + /// pipeline has the synthesized vertex and tessellation control stages, then its evaluation + /// stage, then the fragment stage. A pipeline whose fragment function reads + /// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric` has three + /// synthesized geometry stages before its fragment stage, or last without one, for the point, + /// line and triangle topology classes in that order: a `VkPipeline` runs only the one of its + /// draw's class ([`runs_stage`](Self::runs_stage)). pub stages: Vec, pub layout: PipelineLayout, pub vertex_input: VertexInputState, diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 7ef35ebf7..135299c60 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3358,13 +3358,6 @@ fn lower_bounded( .properties .insert(crate::device::requirements::VkProperty::DeviceSampling); } - // An index stored to its builtin although it differs among a primitive's vertices, because - // the device takes the first vertex's as Metal does. - if plan.families.stage_io.first_vertex_indices_by_device { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalFirstVertexIndices); - } // The set-1 heap's binding flags need their features beside the module's. requirements .features diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 321a96b0a..f1ce7dfa8 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -948,10 +948,9 @@ impl Device { all.extend(stages); stages = all; } - // A fragment function that reads `[[barycentric_coord]]` as varyings, or a vertex function - // that selects its slice or viewport through them, or a fan-out variant: the geometry - // stages of the point, line and triangle classes, before the fragment stage, or last - // without one. + // A fragment function that reads `[[barycentric_coord]]` as varyings, or a fan-out variant: + // the geometry stages of the point, line and triangle classes, before the fragment stage, + // or last without one. if let Some(g) = &linked.geometry { let at = stages .iter() @@ -984,8 +983,6 @@ impl Device { if let Some(g) = linked.geometry.as_ref().filter(|g| g.fan_out.is_none()) { let fact = RuntimeFact::SynthesizedGeometry { weights: !g.forms.is_empty(), - layer: g.layer, - viewport: g.viewport, }; dependencies.push(RuntimeDependency { fact, diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index f67edadd3..e945be6f0 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -707,16 +707,10 @@ pub enum RuntimeFact { StorageTextureIntegerChannels { slot: SlotRef }, /// The render pipeline draws through synthesized geometry stages, one per topology class, of /// which a draw runs its class's (`RenderPipeline::runs_stage`): its fragment function reads - /// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric` (`weights`), or its - /// vertex function selects its primitive's render target slice (`layer`) or viewport - /// (`viewport`) on a device that cannot store `Layer` or `ViewportIndex` from a vertex - /// function (`pipeline::link::geometry`). Each draw runs a stage Metal's draw does not, at the - /// stage's cost, with Metal's answer; the consumer announces it. Nothing binds it. - SynthesizedGeometry { - weights: bool, - layer: bool, - viewport: bool, - }, + /// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric` (`weights`) + /// (`pipeline::link::geometry`). Each draw runs a stage Metal's draw does not, at the stage's + /// cost, with Metal's answer; the consumer announces it. Nothing binds it. + SynthesizedGeometry { weights: bool }, /// An object function's `[[threadgroup(n)]]` arguments, whose lengths the render encoder sets /// (`setObjectThreadgroupMemoryLength:atIndex:`, the object stage's /// `StageTable::threadgroup_lengths`), each a `ThreadgroupMemoryLength`: the static part of diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index f6e37a442..90f9eac6d 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -299,8 +299,7 @@ pub struct Linked { /// compile API builds its vertex and control stages from it. pub control: Option, /// The synthesized geometry stages of a render pipeline whose fragment function reads - /// `[[barycentric_coord]]` as varyings, or whose vertex function selects its slice or - /// viewport through them ([`geometry`]): the compile API builds them. + /// `[[barycentric_coord]]` as varyings ([`geometry`]): the compile API builds them. pub geometry: Option, /// The synthesized control and evaluation stages of a render pipeline variant that draws its /// lines as bands ([`band`]), with their push range placed: the compile API builds them. @@ -361,9 +360,8 @@ pub fn link( } _ => None, }; - // A fragment function that reads `[[barycentric_coord]]` as varyings, or a vertex function - // that selects its slice or viewport through them, draws through synthesized geometry stages, - // which write them. + // A fragment function that reads `[[barycentric_coord]]` as varyings draws through + // synthesized geometry stages, which write them. let geometry = match inputs { LinkInputs::Render(r) => geometry::plan( &ifaces, diff --git a/crates/metal2vulkan/src/pipeline/link/geometry.rs b/crates/metal2vulkan/src/pipeline/link/geometry.rs index 410bf573b..cf2197875 100644 --- a/crates/metal2vulkan/src/pipeline/link/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/geometry.rs @@ -1,7 +1,5 @@ //! The synthesized geometry stages of a render pipeline whose fragment function reads -//! `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`, or whose vertex -//! function selects its primitive's render target slice or viewport on a device that cannot store -//! `Layer` or `ViewportIndex` from a vertex function. +//! `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`. //! //! Such a fragment function reads the weights from a `float2` center varying of each form it reads //! (`IoRole::Barycentric`, perspective-correct or not), and a `float3` read computes the third as @@ -12,14 +10,6 @@ //! after a primitive restart; a line's `(1 - t, t)` from its first vertex; a point's `(1, 0)` //! (Metal probes on the Apple M3 Max, macOS 27.0.1). //! -//! Such a vertex function stores the `Layer` or `ViewportIndex` it would store to a flat `uint` -//! varying instead (`IoRole::SelectedLayer`, `IoRole::SelectedViewport`): on a device without -//! `shaderOutputLayer`, or with `multiViewport` but without `shaderOutputViewportIndex`. Metal -//! renders a primitive into the slice and through the viewport of its first vertex, in the same -//! order, whatever its other vertices write, and holds that vertex's index below the pass's length -//! or the draw's viewport count (Metal probes on the Apple M3 Max, macOS 27.0.1: triangle lists in -//! each order of three different indices, strips, lines and points, indices in and past range). -//! //! A geometry stage receives a primitive's vertices in that order (measured on RADV, NVIDIA, ANV //! and lavapipe, every topology), so link adds one between the vertex and fragment stages //! ([`module`](GeometryStages::module)) that emits the primitive's vertices in the order it @@ -35,13 +25,7 @@ //! - each vertex output the fragment stage reads, at its location and component; //! - `PrimitiveId` from its input `PrimitiveId` where the fragment stage reads it: the count //! Vulkan gives the fragment stage without the stage; -//! - the weights, at the locations link gives them after the vertex outputs' (`link::varyings`); -//! - `Layer` and `ViewportIndex`, each the selected index of the primitive's first vertex at every -//! vertex it emits: Metal's index, and the one value per primitive Vulkan requires of a stage -//! that writes either ("it must write the same value to Layer for all output vertices of a given -//! primitive", and to `ViewportIndex` alike: the Vulkan specification's built-in variables). -//! `ViewportIndex` there needs `MultiViewport`, which a device that selects through the stage -//! has. +//! - the weights, at the locations link gives them after the vertex outputs' (`link::varyings`). //! //! The point class writes a point size exactly where the profile enables //! `shaderTessellationAndGeometryPointSize`, under which a geometry stage that writes none draws @@ -53,12 +37,9 @@ //! unspecified class draws every class, and a draw of another class draws as plain Metal does), so //! it carries the three stages, the point class's, the line class's and the triangle class's, in //! that order before its fragment stage (or last, without one): a `VkPipeline` runs the one of its -//! draw's class (`RenderPipeline::runs_stage`). A vertex function's variant for a pass of one layer -//! (`LoweringInputs::dropped_vertex_layer`) selects no slice, so a pipeline of it carries no stage -//! for its slice. +//! draw's class (`RenderPipeline::runs_stage`). //! -//! Refused, as `Unsupported{Barycentrics}` where the fragment stage reads the weights and as -//! `Unsupported{LayeredRendering}` otherwise: +//! Refused, as `Unsupported{Barycentrics}`: //! //! - a post-tessellation vertex function, and a mesh render pipeline that reads the weights: //! not implemented; and a vertex function that writes `[[render_target_array_index]]` or @@ -73,9 +54,8 @@ //! `maxGeometryTotalOutputComponents`, counted in whole locations as link counts the vertex and //! fragment limits. //! -//! Each needs `fragmentShaderBarycentric` instead, or `shaderOutputLayer` and -//! `shaderOutputViewportIndex` for the indices the stage selects. A device without -//! `geometryShader` either is refused at the function (`lower::stage_io`). +//! Each needs `fragmentShaderBarycentric` instead. A device without `geometryShader` either is +//! refused at the function (`lower::stage_io`). //! //! A variant that draws a rate-mapped pass's triangles once (`VariantKey::region_fan_out`) //! carries the stages too, its triangle class's the fan-out stage ([`fan_out`]), @@ -83,10 +63,9 @@ //! function's within `maxClipDistances` and `maxCombinedClipAndCullDistances`, and room in //! `maxGeometryTotalOutputComponents` for one copy's vertices; and, for the probe, //! `vertexPipelineStoresAndAtomics`. Refused as `NotImplemented(RasterizationRateMap)` beside -//! another reason for the stages, for a mesh or post-tessellation vertex function or one that -//! selects its slice or viewport, and a pipeline that amplifies its vertices; as -//! `Unsupported{RasterizationRateMap}` needing what the device -//! lacks otherwise. The consumer draws +//! the weights, for a mesh or post-tessellation vertex function or one that selects its slice or +//! viewport, and a pipeline that amplifies its vertices; as `Unsupported{RasterizationRateMap}` +//! needing what the device lacks otherwise, a limit of the stage included. The consumer draws //! such a pipeline region by region instead. use super::fan_out::{self, FanOutStage}; @@ -127,12 +106,6 @@ pub struct GeometryStages { pub varyings: Vec<(VaryingKey, IoType)>, /// The forms of the weights the fragment stage reads: `true` perspective-correct. pub forms: Vec, - /// The stages store `Layer` from the vertex function's selected slice - /// (`IoRole::SelectedLayer`). - pub layer: bool, - /// The stages store `ViewportIndex` from the vertex function's selected viewport - /// (`IoRole::SelectedViewport`). - pub viewport: bool, /// The elements of the vertex function's `ClipDistance`, 0 for none. pub clip_distances: u32, /// The vertex function declares `PointSize`. @@ -148,53 +121,25 @@ pub struct GeometryStages { pub fan_out: Option, } -/// Why the stages are made: the fragment stage reads the weights, or else the vertex function -/// selects `Layer` or `ViewportIndex` through them. -#[derive(Clone, Copy)] -struct Reason { - weights: bool, - layer: bool, - viewport: bool, +/// The weights' stages refused as not implemented on every device. +fn not_implemented() -> Error { + Unsupported::not_implemented(Feature::Barycentrics).into() } -impl Reason { - /// Refused as not implemented on every device. The refusal names `Barycentrics` where the - /// fragment stage reads the weights, else `LayeredRendering`. - fn not_implemented(self) -> Error { - if self.weights { - Unsupported::not_implemented(Feature::Barycentrics).into() - } else { - Unsupported::not_implemented(Feature::LayeredRendering).into() - } - } - - /// The refusal as needing the features that make the stages needless, or `capability`. - fn refused(self, capability: Capability) -> Error { - let instead = if self.weights { - vec![Capability::Feature(VkFeature::FragmentShaderBarycentric)] - } else { - let mut instead = Vec::new(); - if self.layer { - instead.push(Capability::Feature(VkFeature::ShaderOutputLayer)); - } - if self.viewport { - instead.push(Capability::Feature(VkFeature::ShaderOutputViewportIndex)); - } - instead - }; - let needs = vec![instead, vec![capability]]; - if self.weights { - Unsupported::needs_any_of(Feature::Barycentrics, needs).into() - } else { - Unsupported::needs_any_of(Feature::LayeredRendering, needs).into() - } - } +/// The weights' stages refused as needing `fragmentShaderBarycentric`, which makes them needless, +/// or `capability`. +fn refused(capability: Capability) -> Error { + let needs = vec![ + vec![Capability::Feature(VkFeature::FragmentShaderBarycentric)], + vec![capability], + ]; + Unsupported::needs_any_of(Feature::Barycentrics, needs).into() } /// The geometry stages of the render pipeline of stages `ifaces` (vertex, then fragment when it /// has one), drawn as `class` with vertex amplification up to `amplification`, where its fragment -/// stage reads the weights as varyings or its vertex function selects an index through them, or -/// its variant fans a rate-mapped pass's triangles out (`fan_out`); `None` where none. Refused as +/// stage reads the weights as varyings, or its variant fans a rate-mapped pass's triangles out +/// (`fan_out`); `None` where neither. Refused as /// the module docs state. A mesh pipeline (`mesh`) whose fragment stage reads the weights is not /// implemented. pub fn plan( @@ -217,24 +162,17 @@ pub fn plan( .collect(); forms.sort_unstable(); forms.dedup(); - let selects = - |role: IoRole| !mesh && vertex.is_some_and(|v| v.io.outputs.iter().any(|o| o.role == role)); - let why = Reason { - weights: !forms.is_empty(), - layer: selects(IoRole::SelectedLayer), - viewport: selects(IoRole::SelectedViewport), - }; // A variant that draws its regions' copies from its vertex function synthesizes no stage // for them (`LoweringInputs::region_copies`). if let Some(mode) = fan_out.filter(|&mode| mode != RegionFanOut::RegionCopies) { - return fan_plan(ifaces, (why, mode), (amplification, mesh), p).map(Some); + return fan_plan(ifaces, (!forms.is_empty(), mode), (amplification, mesh), p).map(Some); } - if !why.weights && !why.layer && !why.viewport { + if forms.is_empty() { return Ok(None); } let vertex = match vertex { Some(v) if !mesh && v.tessellation.is_none() => v, - _ => return Err(why.not_implemented()), + _ => return Err(not_implemented()), }; let builtins = &vertex.io.builtins; // A stage after the vertex function stores the indices Vulkan uses: a vertex function's own @@ -243,21 +181,22 @@ pub fn plan( .iter() .any(|b| matches!(b, StageBuiltin::Layer | StageBuiltin::ViewportIndex)) { - return Err(why.not_implemented()); + return Err(not_implemented()); } let f = p.fields(); let enabled = &f.enabled.features; // Drawn as multiview where its views fit the device's, as `compile::api` requires them, unless // a stage declares `Layer`: the binder draws such a pipeline's amplifications one at a time. - let declares_layer = why.layer - || fragment.is_some_and(|f| { - f.io.builtins.contains(&StageBuiltin::Layer) - || f.io.zero_indices.contains(&StageBuiltin::Layer) - }); + let declares_layer = fragment.is_some_and(|f| { + f.io.builtins.contains(&StageBuiltin::Layer) + || f.io.zero_indices.contains(&StageBuiltin::Layer) + }); let multiview = !declares_layer && amplification.min(f.limits.max_multiview_view_count.max(1)) > 1; if multiview && !enabled.contains(&VkFeature::MultiviewGeometryShader) { - return Err(why.refused(Capability::Feature(VkFeature::MultiviewGeometryShader))); + return Err(refused(Capability::Feature( + VkFeature::MultiviewGeometryShader, + ))); } let point_size = builtins .iter() @@ -271,7 +210,7 @@ pub fn plan( PrimitiveTopologyClass::Point | PrimitiveTopologyClass::Unspecified ); if draws_points && written_size && !writes_point_size { - return Err(why.refused(Capability::Feature( + return Err(refused(Capability::Feature( VkFeature::ShaderTessellationAndGeometryPointSize, ))); } @@ -292,8 +231,6 @@ pub fn plan( Ok(Some(GeometryStages { varyings, forms, - layer: why.layer, - viewport: why.viewport, clip_distances, point_size, writes_point_size, @@ -303,11 +240,11 @@ pub fn plan( })) } -/// The stages of a fan-out variant (the module docs): refused beside another reason for them -/// (`why`), and where the pipeline or the device cannot carry the stage, `mode`'s. +/// The stages of a fan-out variant (the module docs): refused beside the weights (`weights`), and +/// where the pipeline or the device cannot carry the stage, `mode`'s. fn fan_plan( ifaces: &[&StageInterface], - (why, mode): (Reason, RegionFanOut), + (weights, mode): (bool, RegionFanOut), (amplification, mesh): (u32, bool), p: &DeviceProfile, ) -> Result { @@ -321,7 +258,7 @@ fn fan_plan( let selects = builtins .iter() .any(|b| matches!(b, StageBuiltin::Layer | StageBuiltin::ViewportIndex)); - if why.weights || why.layer || why.viewport || selects || amplification > 1 { + if weights || selects || amplification > 1 { return Err(not_implemented()); } let f = p.fields(); @@ -378,8 +315,6 @@ fn fan_plan( Ok(GeometryStages { varyings, forms: Vec::new(), - layer: false, - viewport: false, clip_distances, point_size, writes_point_size: enabled.contains(&VkFeature::ShaderTessellationAndGeometryPointSize), @@ -390,24 +325,6 @@ fn fan_plan( } impl GeometryStages { - /// Why the stages are made ([`Reason`]). - fn reason(&self) -> Reason { - Reason { - weights: !self.forms.is_empty(), - layer: self.layer, - viewport: self.viewport, - } - } - - /// The selected indices the stages read, each with its key and the builtin it stores. - fn selected(&self) -> impl Iterator { - let layer = self.layer.then(|| (VaryingKey::selected_layer(), B::Layer)); - let viewport = self - .viewport - .then(|| (VaryingKey::selected_viewport(), B::ViewportIndex)); - layer.into_iter().chain(viewport) - } - /// Refuses stages whose inputs or outputs at `locations` pass the device's geometry limits /// (the module docs); for a fan-out variant, sets the copies its triangle stage emits. pub fn check_limits(&mut self, locations: &Locations, p: &DeviceProfile) -> Result<(), Error> { @@ -430,8 +347,7 @@ impl GeometryStages { .iter() .map(|&p| VaryingKey::barycentric(p)) .collect(); - let selected: Vec = self.selected().map(|(k, _)| k).collect(); - let inputs = end(&mut self.varyings.iter().map(|(k, _)| k).chain(&selected))?; + let inputs = end(&mut self.varyings.iter().map(|(k, _)| k))?; let outputs = end(&mut self.varyings.iter().map(|(k, _)| k).chain(&weights))?; // A copy's vertex: its varyings' locations, its position, its clip distances and its // primitive ID, in components. @@ -486,11 +402,18 @@ impl GeometryStages { ), ] { if required > u64::from(available) { - return Err(self.reason().refused(Capability::Limit { + let limit = Capability::Limit { limit, required, available: u64::from(available), - })); + }; + return Err(match self.fan_out { + Some(_) => { + Unsupported::needs_any_of(Feature::RasterizationRateMap, vec![vec![limit]]) + .into() + } + None => refused(limit), + }); } } Ok(()) @@ -611,15 +534,6 @@ impl GeometryStages { let key = VaryingKey::barycentric(perspective); weights.push(mb.io(key, IoDir::Output, vec2, IoDecor::default())?); } - // Each selected index: its flat per-vertex input, and the builtin it stores. - let mut selected = Vec::new(); - for (key, builtin) in self.selected() { - let ty = per_vertex(&mut mb, u32_)?; - selected.push(( - mb.io(key, IoDir::Input, ty, packed)?, - mb.builtin(builtin, IoDir::Output, u32_)?, - )); - } let primitive = match self.primitive_id { true => Some(( mb.builtin(B::PrimitiveId, IoDir::Input, u32_)?, @@ -628,14 +542,6 @@ impl GeometryStages { false => None, }; let mut fb = mb.function(void)?; - // The indices of the primitive's first vertex, which select its slice and viewport. - let mut first = Vec::with_capacity(selected.len()); - for &(input, output) in &selected { - let at = ku(&mut fb, 0)?; - let base = fb.module().global_value(input)?; - let from = fb.access_chain(base, &[at])?; - first.push((fb.load(from, MemAccess::default())?, output)); - } for k in 0..n { let at = ku(&mut fb, k)?; for &(input, output) in &carried { @@ -671,10 +577,6 @@ impl GeometryStages { let to = fb.module().global_value(output)?; fb.store(to, value, MemAccess::default())?; } - for &(value, output) in &first { - let to = fb.module().global_value(output)?; - fb.store(to, value, MemAccess::default())?; - } fb.emit_vertex()?; } fb.end_primitive()?; diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index f743b320b..e5bedab1e 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -320,13 +320,11 @@ pub fn graphics_state( .into()); } let max_vertex_amplification_count = vertex_amplification(r, vs.stage == Stage::Mesh, p)?; - // A vertex function that selects its slice through the synthesized geometry stage - // (`IoRole::SelectedLayer`) declares `Layer` there, and a fragment function that reads it as 0 - // (`StageIo::zero_indices`) reads it as Metal does only where no amplification moves it. + // A fragment function that reads `Layer` as 0 (`StageIo::zero_indices`) reads it as Metal + // does only where no amplification moves it. let declares_layer = std::iter::once(vs).chain(fs).any(|s| { s.io.builtins.contains(&StageBuiltin::Layer) || s.io.zero_indices.contains(&StageBuiltin::Layer) - || s.io.outputs.iter().any(|o| o.role == IoRole::SelectedLayer) }); let limits = &p.fields().limits; let used = r @@ -756,14 +754,14 @@ pub fn graphics_state( storage_attachments: Vec::new(), shadow_stencil: None, vertex_writes_memory: vs.writes_memory, - // Stored as the builtin, through the synthesized geometry stages, or (on a device with - // one viewport) nowhere: the raw varying is written in every case. + // Stored as the builtin or (on a device with one viewport) nowhere: the raw varying is + // written in both. writes_viewport_index: vs.io.builtins.contains(&StageBuiltin::ViewportIndex) || vs .io .outputs .iter() - .any(|o| matches!(o.role, IoRole::SelectedViewport | IoRole::ViewportIndex)), + .any(|o| o.role == IoRole::ViewportIndex), // A band variant's pipeline states its band (`link`). line_band: None, // A fan-out variant's pipeline states its fan-out (`link`). diff --git a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs index 3be4e9799..1a9fc2c9f 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs @@ -1,7 +1,6 @@ //! The synthesized geometry stages (`link::geometry`) of a fragment function that reads -//! `[[barycentric_coord]]` as varyings and of a vertex function that selects its slice or viewport -//! through them: what they pass through, where the weights live, what they store, each class's -//! module, and the typed refusals. +//! `[[barycentric_coord]]` as varyings: what they pass through, where the weights live, each +//! class's module, and the typed refusals. use super::*; use crate::error::Needs; @@ -237,189 +236,3 @@ fn what_a_geometry_stage_cannot_carry_is_refused() { }, ); } - -/// The flat `uint` vertex output that carries the selected slice (`IoRole::SelectedLayer`) or -/// viewport (`IoRole::SelectedViewport`) to the geometry stages. -fn selected(role: IoRole) -> IoVariable { - let key = match role { - IoRole::SelectedLayer => VaryingKey::selected_layer(), - _ => VaryingKey::selected_viewport(), - }; - IoVariable { - key, - role, - ty: io_ty(IoNumeric::Uint, 1), - } -} - -/// [`pipeline`]'s fragment function without the weights and the primitive ID. -fn plain(f: &FunctionArtifact) -> FunctionArtifact { - let mut plain = f.clone(); - plain.interface.io.inputs.retain(|x| x.key == key("a")); - plain.interface.io.builtins.clear(); - plain -} - -/// The stages [`plan`] makes for `v` and `f`. -fn planned( - v: &FunctionArtifact, - f: &FunctionArtifact, - amplification: u32, - mesh: bool, - p: &DeviceProfile, -) -> Result, Error> { - plan( - &[&v.interface, &f.interface], - Class::Triangle, - amplification, - mesh, - None, - p, - ) -} - -/// Whether `words` decorate a variable as builtin `builtin`. -fn decorates_builtin(words: &[u32], builtin: crate::spv::BuiltIn) -> bool { - let mut i = 5; - while let Some(&w) = words.get(i) { - let len = (w >> 16) as usize; - if w & 0xFFFF == crate::spv::Op::Decorate as u32 - && words.get(i + 2) == Some(&(crate::spv::Decoration::BuiltIn as u32)) - && words.get(i + 3) == Some(&(builtin as u32)) - { - return true; - } - if len == 0 { - break; - } - i += len; - } - false -} - -/// A vertex function's selected slice and viewport take the stages alone, behind a fragment -/// function that reads neither the weights nor the primitive ID: each class's module stores -/// `Layer` and `ViewportIndex` (that one through `MultiViewport`) and is valid on a device without -/// the outputs; the pipeline states both. Behind a fragment function that reads the weights and -/// the primitive ID, one set of stages serves all of them. -#[test] -fn a_selected_slice_and_viewport_take_the_stages() { - let mut p = profile("lavapipe"); - for f in [ - VkFeature::ShaderOutputLayer, - VkFeature::ShaderOutputViewportIndex, - ] { - p.edit(|x| { - x.enabled.features.remove(&f); - }); - } - let (mut v, f) = pipeline(); - v.interface.io.outputs.push(selected(IoRole::SelectedLayer)); - v.interface - .io - .outputs - .push(selected(IoRole::SelectedViewport)); - let linked = link(&[&v, &plain(&f)], &render(), &p).expect("indices alone"); - let b = linked.geometry.as_ref().expect("geometry stages"); - assert!(b.layer && b.viewport); - assert!(b.forms.is_empty() && !b.primitive_id && !b.multiview); - assert_eq!(b.varyings, [(key("a"), io_ty(IoNumeric::Float, 4))]); - let g = linked.graphics.as_ref().expect("graphics"); - assert!(g.declares_layer && g.writes_viewport_index); - let made = b - .stages(&linked, &p, &mut crate::pipeline::testing::meter()) - .expect("stages"); - assert_eq!(made.len(), CLASSES.len()); - let mv = crate::device::SpirvCapability::from_raw(crate::spv::Capability::MultiViewport as u32); - for ((module, requirements), class) in made.iter().zip(CLASSES) { - crate::spirv::testing::check_words_valid(&module.spirv, requirements, &p) - .unwrap_or_else(|e| panic!("{class:?}: {e}")); - for builtin in [ - crate::spv::BuiltIn::Layer, - crate::spv::BuiltIn::ViewportIndex, - ] { - assert!( - decorates_builtin(&module.spirv, builtin), - "{class:?}: {builtin:?}" - ); - } - assert!(requirements.spirv_capabilities.contains(&mv), "{class:?}"); - assert!(requirements.features.contains(&VkFeature::MultiViewport)); - assert!(!requirements - .features - .contains(&VkFeature::ShaderOutputLayer)); - } - let linked = link(&[&v, &f], &render(), &p).expect("with the weights"); - let b = linked.geometry.as_ref().expect("geometry stages"); - assert!(b.layer && b.viewport && b.primitive_id); - assert_eq!(b.forms, [true]); -} - -/// What the stages cannot carry for a selected index is refused typed, naming -/// `LayeredRendering`: a post-tessellation vertex function and a vertex function's own -/// `ViewportIndex` beside a selected slice as not implemented, and a selected viewport drawn as -/// multiview without `multiviewGeometryShader` as needing the output instead. A selected slice is -/// never drawn as multiview. -#[test] -fn what_the_stages_cannot_carry_for_an_index_is_refused() { - let p = profile("lavapipe"); - let (v, f) = pipeline(); - let f = plain(&f); - let layered = |e: Error, needs: Needs| match e { - Error::Unsupported(u) => { - assert_eq!(u.feature, Feature::LayeredRendering); - assert_eq!(u.needs, needs); - } - other => panic!("{other:?}"), - }; - let mut slice = v.clone(); - slice - .interface - .io - .outputs - .push(selected(IoRole::SelectedLayer)); - assert!(planned(&slice, &f, 1, false, &p).unwrap().is_some()); - let mut tess = slice.clone(); - tess.interface.tessellation = Some(crate::pipeline::interface::TessellationStage::new( - crate::pipeline::interface::PatchDomain::Triangle, - 3, - )); - layered( - planned(&tess, &f, 1, false, &p).unwrap_err(), - Needs::NotImplemented, - ); - let mut both = slice.clone(); - both.interface.io.builtins.push(StageBuiltin::ViewportIndex); - layered( - planned(&both, &f, 1, false, &p).unwrap_err(), - Needs::NotImplemented, - ); - assert!(planned(&slice, &f, 1, true, &p).unwrap().is_none()); - let mut lacking = p.clone(); - lacking.edit(|x| { - x.enabled - .features - .remove(&VkFeature::MultiviewGeometryShader); - }); - let b = planned(&slice, &f, 2, false, &lacking).unwrap().unwrap(); - assert!(!b.multiview); - let mut viewport = v.clone(); - viewport - .interface - .io - .outputs - .push(selected(IoRole::SelectedViewport)); - assert!( - planned(&viewport, &f, 2, false, &p) - .unwrap() - .unwrap() - .multiview - ); - layered( - planned(&viewport, &f, 2, false, &lacking).unwrap_err(), - Needs::AnyOf(vec![ - vec![Capability::Feature(VkFeature::ShaderOutputViewportIndex)], - vec![Capability::Feature(VkFeature::MultiviewGeometryShader)], - ]), - ); -} diff --git a/crates/metal2vulkan/src/pipeline/link/varyings.rs b/crates/metal2vulkan/src/pipeline/link/varyings.rs index 9ad95af03..a5a41b63d 100644 --- a/crates/metal2vulkan/src/pipeline/link/varyings.rs +++ b/crates/metal2vulkan/src/pipeline/link/varyings.rs @@ -135,8 +135,6 @@ fn check_roles(stage: Stage, io: &StageIo) -> Result<(), Error> { .. } | IoRole::ViewportIndex | IoRole::RenderTargetArrayIndex - | IoRole::SelectedLayer - | IoRole::SelectedViewport | IoRole::PrimitiveId | IoRole::MergedCommand ) @@ -460,12 +458,9 @@ fn varyings<'a>( ) -> Result>, Error> { let interpolation = |x: &crate::pipeline::stage_io::IoVariable| match &x.role { IoRole::Varying { interpolation, .. } => *interpolation, - // A fragment input: a raw index is read flat. A selected index, which only the - // synthesized geometry stage reads, is a flat integer too. + // A fragment input: a raw index is read flat. IoRole::ViewportIndex | IoRole::RenderTargetArrayIndex - | IoRole::SelectedLayer - | IoRole::SelectedViewport | IoRole::PrimitiveId | IoRole::MergedCommand => Some(Interpolation::Flat), IoRole::Barycentric { perspective } => Some(Interpolation::Smooth { diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index a521814f3..ea11ccd34 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -372,15 +372,13 @@ pub struct LoweringInputs { /// 0 where it is not, only under [`AmplificationDraws::layered`]; it adds the viewport offset /// (`PushField::AmplificationViewportOffset`) to its viewport index and stores `ViewportIndex` /// as that sum below the draw's viewport count and 0 at or past it, where it writes an index of - /// its own or under [`AmplificationDraws::viewports`]. Where the device cannot store either - /// builtin from a vertex function, it stores the value to a flat varying the synthesized - /// geometry stages store the builtin from (`IoRole::SelectedLayer`, - /// `IoRole::SelectedViewport`), and on a device without `multiViewport` it stores no viewport - /// at all. The raw index varyings it writes hold the sums. A fragment function reads its `[[render_target_array_index]]` and - /// `[[viewport_array_index]]` from those varyings where its vertex function writes the index - /// (`render_target_array_index_varying`, `viewport_index_varying`), and otherwise as the - /// offsets themselves, from the push fields. The vertex function states - /// `RuntimeFact::AmplificationDraws`. Any other function compiles as without it. + /// its own or under [`AmplificationDraws::viewports`]. On a device without `multiViewport` it + /// stores no viewport at all. The raw index varyings it writes hold the sums. A fragment + /// function reads its `[[render_target_array_index]]` and `[[viewport_array_index]]` from those + /// varyings where its vertex function writes the index (`render_target_array_index_varying`, + /// `viewport_index_varying`), and otherwise as the offsets themselves, from the push fields. + /// The vertex function states `RuntimeFact::AmplificationDraws`. Any other function compiles as + /// without it. #[cfg_attr(feature = "serde", serde(default))] pub amplification_draws: Option, /// How each color attachment the fragment function writes takes each channel of its float diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index edf1b0782..008a6d671 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -22,12 +22,6 @@ //! `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`, which the pipeline's //! synthesized geometry stage writes. A `float2` varying, perspective-correct or not, one key //! per form ([`VaryingKey::barycentric`]). -//! - [`IoRole::SelectedLayer`] and [`IoRole::SelectedViewport`]: the `Layer` and `ViewportIndex` a -//! vertex function selects its primitive's slice and viewport with on a device that cannot store -//! the builtin from a vertex function, which the pipeline's synthesized geometry stage stores -//! from the primitive's first vertex. A flat `uint` vertex output, one key each -//! ([`VaryingKey::selected_layer`], [`VaryingKey::selected_viewport`]), that no fragment -//! function reads. //! - [`IoRole::PrimitiveId`]: Metal's `[[primitive_id]]` on a device that cannot declare a //! fragment `PrimitiveId`, which the pipeline's vertex function computes for the primitive each //! vertex provokes. A flat `uint` varying for link, one key ([`VaryingKey::primitive_id`]) on @@ -39,8 +33,7 @@ //! The roles live in disjoint key namespaces ([`VaryingKey::user`], [`VaryingKey::attribute`], //! [`VaryingKey::color`], [`VaryingKey::viewport_index`], //! [`VaryingKey::render_target_array_index`], -//! [`VaryingKey::barycentric`], [`VaryingKey::selected_layer`], -//! [`VaryingKey::selected_viewport`], [`VaryingKey::primitive_id`], +//! [`VaryingKey::barycentric`], [`VaryingKey::primitive_id`], //! [`VaryingKey::merged_command`]): the key bytes start with a //! namespace tag, so no AIR user key can collide with another role's key. Keys stay opaque to //! link; it reads the role here, never the bytes. @@ -73,8 +66,6 @@ const COLOR: u8 = 2; const VIEWPORT_INDEX: u8 = 3; const RENDER_TARGET_ARRAY_INDEX: u8 = 4; const BARYCENTRIC: u8 = 6; -const SELECTED_LAYER: u8 = 7; -const SELECTED_VIEWPORT: u8 = 8; const PRIMITIVE_ID: u8 = 9; const MERGED_COMMAND: u8 = 10; @@ -121,18 +112,6 @@ impl VaryingKey { VaryingKey(AirUserKey(vec![BARYCENTRIC, u8::from(perspective)].into())) } - /// The key of the `Layer` a vertex function selects for the pipeline's synthesized geometry - /// stage to store (`IoRole::SelectedLayer`). - pub fn selected_layer() -> VaryingKey { - VaryingKey(AirUserKey(vec![SELECTED_LAYER].into())) - } - - /// The key of the `ViewportIndex` a vertex function selects for the pipeline's synthesized - /// geometry stage to store (`IoRole::SelectedViewport`). - pub fn selected_viewport() -> VaryingKey { - VaryingKey(AirUserKey(vec![SELECTED_VIEWPORT].into())) - } - /// The key of the primitive ID a vertex function writes and a fragment function reads as /// `[[primitive_id]]` (`IoRole::PrimitiveId`). pub fn primitive_id() -> VaryingKey { @@ -315,8 +294,8 @@ pub struct StageIo { /// slice and viewport indices it writes are among them so /// (`VaryingKey::render_target_array_index`, `VaryingKey::viewport_index`): Vulkan takes /// `Layer` and `ViewportIndex` from a vertex function only where every vertex of a primitive - /// stores the same, so it stores an index that is not to its selected index instead - /// (`IoRole::SelectedLayer`, `IoRole::SelectedViewport`). Empty for every other function. + /// stores the same, so an index that is not among them is refused. Empty for every other + /// function. #[cfg_attr(feature = "serde", serde(default))] pub uniform_outputs: Vec, /// The `float` and `half` varyings the fragment function reads flat although it states an @@ -732,19 +711,6 @@ pub enum IoRole { /// a triangle's vertices in their order (`(1, 0)` and `(0, 1)` at a line's, `(1, 0)` at a /// point), and passes the fragment stage's other inputs through. Barycentric { perspective: bool }, - /// The `Layer` a vertex function compiled for a device without `shaderOutputLayer` selects its - /// primitive's render target slice with: the value it would store to `Layer` (the index it - /// writes, plus the amplification's offset when drawn one amplification at a time, held below - /// the render pass's length and 0 at or past it), as a flat `uint` vertex output. No fragment - /// function reads it: the pipeline's synthesized geometry stage stores it to `Layer` at every - /// vertex it emits, from the primitive's first vertex, whose index Metal renders the primitive - /// with. - SelectedLayer, - /// The `ViewportIndex` a vertex function compiled for a device with `multiViewport` but - /// without `shaderOutputViewportIndex` selects its primitive's viewport with, as - /// [`IoRole::SelectedLayer`] is for its slice: held below the draw's viewport count and 0 at - /// or past it. - SelectedViewport, /// Metal's `[[primitive_id]]` carried from a vertex function to its fragment function: the /// flat `uint` output of a vertex function compiled under /// `LoweringInputs::primitive_id_varying`, and the input a fragment function reads as its @@ -767,10 +733,10 @@ pub enum IoRole { } impl IoRole { - /// Whether the role is a varying: a user varying, a raw index a vertex function writes for - /// its fragment function, the barycentric weights a synthesized geometry - /// stage writes, a selected index the geometry stage reads, the primitive ID, or a merged - /// draw's command. Link numbers these, and packs those a vertex function writes. + /// Whether the role is a varying: a user varying, a raw index a vertex function writes for its + /// fragment function, the barycentric weights a synthesized geometry stage writes, the + /// primitive ID, or a merged draw's command. Link numbers these, and packs those a vertex + /// function writes. pub(crate) fn is_varying(&self) -> bool { matches!( self, @@ -778,8 +744,6 @@ impl IoRole { | IoRole::ViewportIndex | IoRole::RenderTargetArrayIndex | IoRole::Barycentric { .. } - | IoRole::SelectedLayer - | IoRole::SelectedViewport | IoRole::PrimitiveId | IoRole::MergedCommand ) diff --git a/crates/metal2vulkan/src/tests/engine_amplification.rs b/crates/metal2vulkan/src/tests/engine_amplification.rs index 76c04c95c..416497983 100644 --- a/crates/metal2vulkan/src/tests/engine_amplification.rs +++ b/crates/metal2vulkan/src/tests/engine_amplification.rs @@ -49,7 +49,7 @@ use crate::pipeline::interface::PushLoc; use crate::pipeline::link::{link, LinkInputs}; use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::relocate::relocate; -use crate::pipeline::stage_io::{IoRole, StageBuiltin}; +use crate::pipeline::stage_io::StageBuiltin; use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SpecKey, Stage, VaryingKey}; use crate::pipeline::testing::{ compile, engine_dir, fixtures_dir, llvm_assemble, moltenvk_msl_compile, profile, typed_module, @@ -114,9 +114,8 @@ fn validate(a: &FunctionArtifact, p: &DeviceProfile) -> Vec<(SpecKey, u64)> { } /// Every amplified entry reads `ViewIndex` for its amplification id and the specialized count, -/// and a shared output stays an output. `amp_vertex`'s viewport index (`vid & 1`) differs among a -/// primitive's vertices: it is stored to the selected viewport the synthesized geometry stage -/// reads. +/// and a shared output stays an output. `amp_vertex`'s viewport index (`iid & 1`) is the same at +/// every vertex of a primitive: it is stored to `ViewportIndex`. #[test] fn amplification_builtins_are_the_view_index_and_a_specialized_count() { let Some(bc) = fixture() else { return }; @@ -158,27 +157,18 @@ fn amplification_builtins_are_the_view_index_and_a_specialized_count() { ); } // `uv` is `[[shared]]`: the second varying, beside the amplified color; the third is - // the viewport index as written, and the fourth, behind the synthesized geometry stage, - // the selected viewport. + // the viewport index as written, beside the `ViewportIndex` it stores. let a = compile(&bc, "amp_vertex", &p).expect("amp_vertex"); assert_eq!( a.interface.io.outputs.len(), - 4, + 3, "{stem}: color, uv, viewport index" ); - assert!( - !a.interface - .io - .builtins - .contains(&StageBuiltin::ViewportIndex), - "{stem}" - ); assert!( a.interface .io - .outputs - .iter() - .any(|o| o.role == IoRole::SelectedViewport), + .builtins + .contains(&StageBuiltin::ViewportIndex), "{stem}" ); } @@ -214,9 +204,8 @@ fn amplification_id_needs_multiview() { /// 0, not `ViewIndex`: SPIRV-Cross gives a vertex function that reads `ViewIndex` a second /// `[[render_target_array_index]]` output, which Metal refuses (authored case 013406ac failed /// MoltenVK pipeline creation so). Without `ViewIndex` it needs neither `MultiView` nor -/// `multiview`. A slice the same at every vertex of a primitive is stored to `Layer`, and its -/// `moltenvk-m3` module compiles as MoltenVK's MSL; one that differs among them goes to the -/// selected slice a synthesized geometry stage reads, which `moltenvk-m3` refuses. +/// `multiview`. Each fixture's slice is the same at every vertex of a primitive, so it is stored +/// to `Layer`, and its `moltenvk-m3` module compiles as MoltenVK's MSL. #[test] fn a_vertex_function_writing_its_slice_reads_amplification_id_zero() { let Some(bc) = fixture() else { return }; @@ -249,26 +238,17 @@ fn a_vertex_function_writing_its_slice_reads_amplification_id_zero() { "{entry}: {:?}", a.interface.io.builtins ); - // `amp_vertex_layer`'s slice (`slices[vid & 1]`) differs among a primitive's - // vertices: stored to the selected slice; `vertex_amplification_id_layer`'s does not, - // and is stored to `Layer`. - let stored = a - .interface - .io - .uniform_outputs - .contains(&VaryingKey::render_target_array_index()); - assert_eq!( - a.interface.io.builtins.contains(&StageBuiltin::Layer), - stored, - "{entry}" - ); - assert_eq!( + // Each slice (`slices[iid & 1]`, and the other's) is the same at every vertex of a + // primitive, and is stored to `Layer`. + assert!( a.interface .io - .outputs - .iter() - .any(|o| o.role == IoRole::SelectedLayer), - !stored, + .uniform_outputs + .contains(&VaryingKey::render_target_array_index()), + "{entry}" + ); + assert!( + a.interface.io.builtins.contains(&StageBuiltin::Layer), "{entry}" ); assert!(!a.requirements.features.contains(&F::Multiview), "{entry}"); @@ -281,20 +261,6 @@ fn a_vertex_function_writing_its_slice_reads_amplification_id_zero() { validate(&a, &p); } let p = prof("moltenvk-m3"); - if entry == "amp_vertex_layer" { - match compile(bc, entry, &p) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::LayeredRendering, "{entry}"); - assert_eq!( - u.needs, - Needs::AnyOf(vec![vec![Capability::Feature(F::GeometryShader)]]), - "{entry}" - ); - } - other => panic!("{entry}: {:?}", other.map(|_| ())), - } - continue; - } let a = compile(bc, entry, &p).expect("moltenvk-m3"); let linked = link(&[&a], &LinkInputs::standalone(), &p).expect("link"); let words = relocate(&a, &linked.table).expect("relocate"); @@ -837,10 +803,9 @@ fn a_variant_draws_each_amplification_with_its_push_fields() { } } -/// The variant's layered `Layer` needs `shaderOutputLayer` or `geometryShader`, which -/// `runtime-floor` without `shaderOutputLayer` (below the runtime's floor) both lacks; and a -/// tessellation pipeline is drawn amplified only as views (`lavapipe` has -/// `multiviewTessellationShader`). +/// The variant's layered `Layer` needs `shaderOutputLayer`, which `runtime-floor` without it (below +/// the runtime's floor) lacks; and a tessellation pipeline is drawn amplified only as views +/// (`lavapipe` has `multiviewTessellationShader`). #[test] fn amplification_draws_refuse_what_the_variant_cannot_be() { let Some(bc) = fixture() else { return }; @@ -853,7 +818,7 @@ fn amplification_draws_refuse_what_the_variant_cannot_be() { match dev.compile_render_variant(&d, &plan.variant, &budget) { Err(Error::Unsupported(u)) => { assert_eq!(u.feature, Feature::VertexAmplification); - assert_eq!(u.needs, output_layer_or_geometry()); + assert_eq!(u.needs, output_layer()); } other => panic!("{:?}", other.map(|_| ())), } @@ -887,12 +852,9 @@ fn below_the_floor() -> Device { } /// What a variant that stores a layered amplification's slice needs on a device without -/// `shaderOutputLayer`: the feature, or the geometry stage that stores the slice instead. -fn output_layer_or_geometry() -> Needs { - Needs::AnyOf(vec![ - vec![Capability::Feature(F::ShaderOutputLayer)], - vec![Capability::Feature(F::GeometryShader)], - ]) +/// `shaderOutputLayer`: the feature. +fn output_layer() -> Needs { + Needs::AnyOf(vec![vec![Capability::Feature(F::ShaderOutputLayer)]]) } /// On a profile without `shaderOutputLayer`, every amplified draw is drawn as Metal or refused @@ -900,10 +862,9 @@ fn output_layer_or_geometry() -> Needs { /// amplification at a time in a pass of one layer or none, whose variant writes no `Layer` and /// carries no geometry stage (every amplification renders the pass's one layer, as Metal's do: /// Metal probe case `amp2_len1` on the M3 Max and an M4); and in a pass of more layers, whose -/// variant must store the amplification's slice as `Layer`, through the synthesized geometry -/// stages where the device has `geometryShader` (`lavapipe` without the output), and otherwise -/// (`runtime-floor` without `shaderOutputLayer`) `Unsupported(VertexAmplification)` needing either -/// feature. +/// variant must store the amplification's slice as `Layer`, `Unsupported(VertexAmplification)` +/// needing the feature, `geometryShader` or not (`runtime-floor` and `lavapipe`, each without +/// `shaderOutputLayer`). #[test] fn a_profile_without_shader_output_layer_draws_or_refuses_every_amplification() { let Some(bc) = fixture() else { return }; @@ -912,17 +873,13 @@ fn a_profile_without_shader_output_layer_draws_or_refuses_every_amplification() assert!(lavapipe.features.remove(&F::ShaderOutputLayer)); assert!(lavapipe.features.contains(&F::GeometryShader)); let lavapipe = Device::from_queries(lavapipe, DevicePolicy::default()).expect("device"); - for (stem, dev, geometry) in [ - ( - "runtime-floor without shaderOutputLayer", - below_the_floor(), - false, - ), - ("lavapipe without shaderOutputLayer", lavapipe, true), + for (stem, dev) in [ + ("runtime-floor without shaderOutputLayer", below_the_floor()), + ("lavapipe without shaderOutputLayer", lavapipe), ] { let d = render(&bc, "amp_vertex_store", None, 2); let p = dev.compile_render_pipeline(&d, &budget).expect("base"); - let (mut views, mut drawn, mut layered, mut refused) = (0, 0, 0, 0); + let (mut views, mut drawn, mut refused) = (0, 0, 0); for length in 0..4 { for mappings in [ vec![(0, 0), (0, 1)], @@ -949,36 +906,29 @@ fn a_profile_without_shader_output_layer_draws_or_refuses_every_amplification() .iter() .filter(|m| m.stage == crate::vk::ShaderStage::GEOMETRY) .count(); - assert_eq!(variant.graphics.declares_layer, draws.layered, "{what}"); - if draws.layered { - assert!(geometry, "{what}: compiled"); - assert_eq!(stages, 3, "{what}"); - layered += 1; - } else { - assert_eq!(stages, 0, "{what}"); - drawn += 1; - } + assert!(!draws.layered, "{what}: compiled"); + assert!(!variant.graphics.declares_layer, "{what}"); + assert_eq!(stages, 0, "{what}"); + drawn += 1; for m in &variant.stages { check_words_valid(&m.spirv, &variant.requirements, dev.profile()) .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); } } Err(Error::Unsupported(u)) => { - assert!(draws.layered && !geometry, "{what}: refused"); + assert!(draws.layered, "{what}: refused"); assert_eq!(u.feature, Feature::VertexAmplification, "{what}"); - assert_eq!(u.needs, output_layer_or_geometry(), "{what}"); + assert_eq!(u.needs, output_layer(), "{what}"); refused += 1; } Err(e) => panic!("{what}: {e}"), } } } - assert!(views > 0 && drawn > 0, "{stem}: {views} {drawn}"); - if geometry { - assert!(layered > 0 && refused == 0, "{stem}: {layered} {refused}"); - } else { - assert!(refused > 0 && layered == 0, "{stem}: {layered} {refused}"); - } + assert!( + views > 0 && drawn > 0 && refused > 0, + "{stem}: {views} {drawn} {refused}" + ); } } diff --git a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs index 57bb8f535..67ad5c24d 100644 --- a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs +++ b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs @@ -15,10 +15,10 @@ //! the other variant is `BindError::NeedsVariant`. //! - Amplified draws are never views on either variant: they draw one amplification at a time. //! -//! Every module that compiles passes L3 (`spirv-val` and requirements within the profile), and -//! the dropped vertex module on MoltenVK, which has no geometry stage to write a slice, converts to -//! MSL and compiles as MoltenVK's does (`spirv-cross` and `xcrun metal`, compile only). `llvm-as` assembles the fixtures; a missing tool skips visibly. -//! No GPU is used. +//! Every module that compiles passes L3 (`spirv-val` and requirements within the profile), and the +//! dropped vertex module on MoltenVK without `shaderOutputLayer` converts to MSL and compiles as +//! MoltenVK's does (`spirv-cross` and `xcrun metal`, compile only). `llvm-as` assembles the +//! fixtures; a missing tool skips visibly. No GPU is used. use std::path::Path; @@ -295,13 +295,10 @@ fn a_fragment_reading_its_slice_alone_asks_for_no_variant() { /// The dropped variant declares no `Layer` output, so a device that cannot write `Layer` from a /// vertex function runs a pass of one layer exactly, where the variant that writes `Layer` is -/// refused typed when the device has no geometry stage to write it either (MoltenVK has none). -/// The device keeps `VK_EXT_shader_viewport_index_layer`: without `shaderOutputLayer` it grants no -/// `Layer` output (the capability a module declares at the 1.2 floor is the feature's), so the -/// refusal names what would store the slice rather than failing as a requirement beyond the -/// profile: `geometryShader`, as `amp_vertex_layer`'s slice (`slices[vid & 1]`) differs among a -/// primitive's vertices, which only the synthesized geometry stage stores. The dropped variant's -/// vertex module converts to MSL that Metal compiles. +/// refused typed. The device keeps `VK_EXT_shader_viewport_index_layer`: without +/// `shaderOutputLayer` it grants no `Layer` output (the capability a module declares at the 1.2 +/// floor is the feature's), so the refusal names the feature rather than failing as a requirement +/// beyond the profile. The dropped variant's vertex module converts to MSL that Metal compiles. #[test] fn the_dropped_variant_needs_no_output_layer() { let Some(bc) = assemble(&engine_dir().join("vertex_amplification.ll")) else { @@ -320,7 +317,7 @@ fn the_dropped_variant_needs_no_output_layer() { assert_eq!(u.feature, Feature::LayeredRendering); assert_eq!( u.needs, - Needs::AnyOf(vec![vec![Capability::Feature(F::GeometryShader)]]) + Needs::AnyOf(vec![vec![Capability::Feature(F::ShaderOutputLayer)]]) ); } other => panic!("{other:?}"), @@ -348,9 +345,9 @@ fn the_dropped_variant_needs_no_output_layer() { /// A vertex function that writes `[[render_target_array_index]]` writes the index as written to a /// flat varying (`IoRole::RenderTargetArrayIndex`) in both variants, and in the one whose pipeline -/// declares `Layer` (on RADV through the synthesized geometry stage, as the slice differs among a -/// primitive's vertices) reads the pass's length from its push data. In its pipeline a fragment function that -/// reads the slice compiles under `render_target_array_index_varying` and reads that varying, as +/// declares `Layer` stores `Layer` and reads the pass's length from its push data. In its pipeline +/// a fragment function that reads the slice compiles under `render_target_array_index_varying` and +/// reads that varying, as /// `render_pipeline_key` names, behind either variant; a fragment function that does not read it /// keeps the key it has without the field. A reading fragment compiled for the other kind of vertex /// function is `NeedsInput(RenderTargetArrayIndex)` either way. Every module passes L3. @@ -387,9 +384,13 @@ fn a_fragment_reads_the_slice_index_its_vertex_function_wrote() { VaryingKey::render_target_array_index(), "{what}" ); - // Its slice differs among a primitive's vertices, so the synthesized geometry stage - // stores it: the vertex function declares no `Layer` in either variant. - assert!(!io.builtins.contains(&StageBuiltin::Layer), "{what}"); + // Its slice is the same at every vertex of a primitive: the variant that writes `Layer` + // stores it, and the dropped one declares none. + assert_eq!( + io.builtins.contains(&StageBuiltin::Layer), + !key.dropped_vertex_layer, + "{what}" + ); let keys = dev .render_variant_key(&d, &key, &budget, &crate::pipeline::StageEntries::new()) diff --git a/crates/metal2vulkan/src/tests/engine_selected_indices.rs b/crates/metal2vulkan/src/tests/engine_selected_indices.rs deleted file mode 100644 index bb7203429..000000000 --- a/crates/metal2vulkan/src/tests/engine_selected_indices.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! The render target slice and viewport a vertex function selects on a device that cannot store -//! `Layer` or `ViewportIndex` from a vertex function, over the owned fixtures `engine/rt6_layered` -//! (a vertex function that chooses its slice per instance, and fragment functions that read it, -//! one with the barycentric weights and the primitive ID) and `engine/rt6_viewports` (a vertex -//! function that selects its viewport per instance, and a fragment function that reads it): -//! -//! - Without `shaderOutputLayer`, on a device with `geometryShader`, the vertex function stores the -//! slice it selects to a flat varying (`IoRole::SelectedLayer`) and declares no `Layer`; its -//! pipeline carries the synthesized geometry stages of the point, line and triangle classes, -//! which store `Layer` from the primitive's first vertex. The variant for a pass of one layer -//! selects nothing and carries no stage. -//! - Without `shaderOutputViewportIndex`, on a device with `multiViewport` and `geometryShader`, -//! the viewport alike (`IoRole::SelectedViewport`), the stages storing `ViewportIndex` through -//! `MultiViewport`. Without `multiViewport` a draw has one viewport, so the vertex function -//! stores no viewport index at all and the pipeline carries no stage. -//! - One set of stages serves the barycentric weights, the primitive ID and the slice together. -//! - A fragment function that reads an index no stage writes, on a device that cannot declare its -//! builtin, reads 0 (`StageIo::zero_indices`). -//! - Without `geometryShader` either, the variant that selects a slice is refused needing either -//! feature, and the one for a pass of one layer compiles. -//! - A vertex function whose slice and viewport index differ among the vertices of a primitive -//! (`engine/rt6_first_vertex`) stores them through the stages behind the device's own outputs -//! too, as Vulkan takes `Layer` and `ViewportIndex` only where every vertex of a primitive -//! stores the same and Metal takes the first vertex's; MoltenVK, which hands them to Metal, -//! stores them itself. Without `geometryShader` elsewhere it is refused needing it. -//! -//! Every module that compiles passes L3 (`spirv-val` and requirements within the profile). `llvm-as` -//! assembles the fixtures; a missing tool skips visibly. No GPU is used. - -use std::path::Path; - -use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::requirements::{VkFeature as F, VkProperty}; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{Capability, Error, Feature, Needs}; -use crate::library::Library; -use crate::metal::PixelFormat; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::stage_io::{IoRole, StageBuiltin}; -use crate::pipeline::sym::VaryingKey; -use crate::pipeline::testing::{compile, engine_dir, llvm_assemble, AssembleError}; -use crate::pipeline::RenderPipeline; -use crate::spirv::testing::check_words_valid; -use crate::spv::Capability as Cap; -use crate::vk; - -fn assemble(name: &str) -> Option> { - let path = engine_dir().join(name); - match llvm_assemble(&path) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {path:?}: {why}"), - } -} - -/// Committed profile `stem`'s description without `withheld`. -fn device(stem: &str, withheld: &[F]) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - for f in withheld { - desc.features.remove(f); - } - Device::from_queries(desc, DevicePolicy::default()).expect("device") -} - -/// A render pipeline of `vertex` and `fragment` from `bc`, drawing into one color of `format`. -fn render( - bc: &[u8], - vertex: &str, - fragment: &str, - format: PixelFormat, -) -> RenderPipelineDescriptor { - let lib = Library::from_air(bc).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(stage(vertex)); - d.fragment = Some(stage(fragment)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format)); - d -} - -/// The geometry stages of `p`, each valid on `dev`, every other stage too. -fn geometry_stages(p: &RenderPipeline, dev: &Device, what: &str) -> usize { - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - p.stages - .iter() - .filter(|m| m.stage == vk::ShaderStage::GEOMETRY) - .count() -} - -/// The roles of the vertex outputs `entry` of `bc` declares on `dev`, and its builtins. -fn vertex_io(bc: &[u8], entry: &str, dev: &Device) -> (Vec, Vec) { - let a = compile(bc, entry, dev.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); - let io = &a.interface.io; - ( - io.outputs.iter().map(|o| o.role.clone()).collect(), - io.builtins.clone(), - ) -} - -fn any_of(alternatives: &[F]) -> Needs { - Needs::AnyOf( - alternatives - .iter() - .map(|&f| vec![Capability::Feature(f)]) - .collect(), - ) -} - -/// Without `shaderOutputLayer` a vertex function selects its slice through the synthesized -/// geometry stages, and its variant for a pass of one layer through none. -#[test] -fn without_the_output_the_slice_goes_through_the_geometry_stage() { - let Some(bc) = assemble("rt6_layered.ll") else { - return; - }; - let dev = device( - "lavapipe", - &[F::ShaderOutputLayer, F::ShaderOutputViewportIndex], - ); - let (outputs, builtins) = vertex_io(&bc, "rt6_layered_vertex", &dev); - assert!(outputs.contains(&IoRole::SelectedLayer), "{outputs:?}"); - assert!( - outputs.contains(&IoRole::RenderTargetArrayIndex), - "{outputs:?}" - ); - assert!(!builtins.contains(&StageBuiltin::Layer), "{builtins:?}"); - let budget = Budget::standard(); - let d = render( - &bc, - "rt6_layered_vertex", - "rt6_layered_fragment", - PixelFormat::R32Uint, - ); - let p = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); - assert_eq!(geometry_stages(&p, &dev, "layered"), 3); - assert!(p.graphics.declares_layer); - assert!(!p.graphics.writes_viewport_index); - assert!(!p.requirements.features.contains(&F::ShaderOutputLayer)); - assert!(p.requirements.features.contains(&F::GeometryShader)); - let mut key = VariantKey::new(); - key.dropped_vertex_layer = true; - let one = dev - .compile_render_variant(&d, &key, &budget) - .expect("dropped variant"); - assert_eq!(geometry_stages(&one, &dev, "one layer"), 0); - assert!(!one.requirements.features.contains(&F::GeometryShader)); - // Behind the device's own `Layer` output, no stage. - let native = device("lavapipe", &[]); - let p = native - .compile_render_pipeline(&d, &budget) - .expect("pipeline"); - assert_eq!(geometry_stages(&p, &native, "native"), 0); - assert!(p.requirements.features.contains(&F::ShaderOutputLayer)); -} - -/// Without `shaderOutputViewportIndex`, a device with `multiViewport` selects the viewport through -/// the synthesized geometry stages, whose `ViewportIndex` needs `MultiViewport`; a device without -/// `multiViewport` draws through one viewport and stores none, its pipeline still stating that the -/// vertex function writes the index. -#[test] -fn without_the_output_the_viewport_goes_through_the_geometry_stage_or_nowhere() { - let Some(bc) = assemble("rt6_viewports.ll") else { - return; - }; - let budget = Budget::standard(); - let d = render( - &bc, - "rt6_select", - "rt6_viewport_read", - PixelFormat::RGBA8Unorm, - ); - let dev = device("lavapipe", &[F::ShaderOutputViewportIndex]); - let (outputs, builtins) = vertex_io(&bc, "rt6_select", &dev); - assert!(outputs.contains(&IoRole::SelectedViewport), "{outputs:?}"); - assert!(outputs.contains(&IoRole::ViewportIndex), "{outputs:?}"); - assert!( - !builtins.contains(&StageBuiltin::ViewportIndex), - "{builtins:?}" - ); - let p = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); - assert_eq!(geometry_stages(&p, &dev, "multiViewport"), 3); - assert!(p.graphics.writes_viewport_index); - assert!(!p.graphics.declares_layer); - assert!(p.requirements.features.contains(&F::MultiViewport)); - assert!(!p - .requirements - .features - .contains(&F::ShaderOutputViewportIndex)); - let mv = crate::device::SpirvCapability::from_raw(Cap::MultiViewport as u32); - assert!(p.requirements.spirv_capabilities.contains(&mv)); - // Without `multiViewport`, on the floor too: the raw index alone. - for dev in [ - device( - "lavapipe", - &[F::ShaderOutputViewportIndex, F::MultiViewport], - ), - device("runtime-floor", &[]), - ] { - let (outputs, builtins) = vertex_io(&bc, "rt6_select", &dev); - assert_eq!(outputs, [IoRole::ViewportIndex], "{builtins:?}"); - assert!(!builtins.contains(&StageBuiltin::ViewportIndex)); - let p = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); - assert_eq!(geometry_stages(&p, &dev, "one viewport"), 0); - // The function still writes the index: the runtime refuses its draw while the encoder - // holds more than one viewport. - assert!(p.graphics.writes_viewport_index); - } -} - -/// One set of synthesized geometry stages carries the barycentric weights, the primitive ID and the -/// selected slice of a pipeline that needs the stages for each. -#[test] -fn one_geometry_stage_serves_the_weights_the_primitive_and_the_slice() { - let Some(bc) = assemble("rt6_layered.ll") else { - return; - }; - let dev = device( - "lavapipe", - &[F::ShaderOutputLayer, F::FragmentShaderBarycentric], - ); - let d = render( - &bc, - "rt6_layered_vertex", - "rt6_layered_weights", - PixelFormat::R32Uint, - ); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - assert_eq!(geometry_stages(&p, &dev, "weights and slice"), 3); - assert!(p.graphics.reads_barycentric_coord); - assert!(p.graphics.declares_layer); - assert!(!p - .requirements - .features - .contains(&F::FragmentShaderBarycentric)); - // With the device's own `Layer` output beside the weights' stage: not implemented. - let mixed = device("lavapipe", &[F::FragmentShaderBarycentric]); - match mixed.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) => assert_eq!(u.feature, Feature::Barycentrics), - other => panic!("{other:?}"), - } -} - -/// A fragment function that reads the slice or viewport no stage writes reads 0 on a device that -/// cannot declare the builtin, which it lists; below the floor (`runtime-floor` without -/// `shaderOutputLayer`, which the floor requires) a vertex function that selects its slice is -/// refused needing either feature, and its variant for a pass of one layer compiles. -#[test] -fn below_the_floor_a_read_is_zero_and_a_selected_slice_needs_either_feature() { - let Some(layered) = assemble("rt6_layered.ll") else { - return; - }; - let Some(amp) = assemble("vertex_amplification.ll") else { - return; - }; - let floor = device("runtime-floor", &[F::ShaderOutputLayer]); - for (entry, zero) in [ - ("amp_fragment_layer", vec![StageBuiltin::Layer]), - ("amp_fragment", vec![StageBuiltin::ViewportIndex]), - ] { - let a = compile(&, entry, floor.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); - assert_eq!(a.interface.io.zero_indices, zero, "{entry}"); - assert!(!a - .interface - .io - .builtins - .iter() - .any(|b| matches!(b, StageBuiltin::Layer | StageBuiltin::ViewportIndex))); - } - let budget = Budget::standard(); - let d = render( - &layered, - "rt6_layered_vertex", - "rt6_layered_fragment", - PixelFormat::R32Uint, - ); - match floor.compile_render_pipeline(&d, &budget) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::LayeredRendering); - assert_eq!(u.needs, any_of(&[F::ShaderOutputLayer, F::GeometryShader])); - } - other => panic!("{other:?}"), - } - let mut key = VariantKey::new(); - key.dropped_vertex_layer = true; - let one = floor - .compile_render_variant(&d, &key, &budget) - .expect("dropped variant"); - assert_eq!( - geometry_stages(&one, &floor, "below the floor, one layer"), - 0 - ); -} - -/// A vertex function whose slice and viewport index differ among the vertices of a primitive -/// (`engine/rt6_first_vertex`) stores them through the synthesized geometry stages behind the -/// device's own outputs too, as Vulkan takes `Layer` and `ViewportIndex` only where every vertex -/// of a primitive stores the same; one whose slice is the same at every vertex -/// (`rt6_layered_vertex`) keeps the builtin. No module requires -/// `VkProperty::MetalFirstVertexIndices`. Without `geometryShader` (MoltenVK's, and lavapipe's with -/// the feature removed), the pipeline is refused needing `geometryShader`. -#[test] -fn indices_that_differ_among_a_primitive_s_vertices_go_through_the_geometry_stage() { - let Some(layered) = assemble("rt6_layered.ll") else { - return; - }; - let Some(bc) = assemble("rt6_first_vertex.ll") else { - return; - }; - let dev = device("lavapipe", &[]); - let uniform = |bc: &[u8], entry: &str, dev: &Device| { - let a = compile(bc, entry, dev.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); - a.interface.io.uniform_outputs.clone() - }; - let alike = uniform(&layered, "rt6_layered_vertex", &dev); - assert!( - alike.contains(&VaryingKey::render_target_array_index()), - "{alike:?}" - ); - let (outputs, builtins) = vertex_io(&layered, "rt6_layered_vertex", &dev); - assert!(builtins.contains(&StageBuiltin::Layer), "{builtins:?}"); - assert!(!outputs.contains(&IoRole::SelectedLayer), "{outputs:?}"); - let per_vertex = uniform(&bc, "rt6_first_vertex", &dev); - for key in [ - VaryingKey::render_target_array_index(), - VaryingKey::viewport_index(), - ] { - assert!(!per_vertex.contains(&key), "{per_vertex:?}"); - } - let (outputs, builtins) = vertex_io(&bc, "rt6_first_vertex", &dev); - assert!(outputs.contains(&IoRole::SelectedLayer), "{outputs:?}"); - assert!(outputs.contains(&IoRole::SelectedViewport), "{outputs:?}"); - assert!( - !builtins - .iter() - .any(|b| matches!(b, StageBuiltin::Layer | StageBuiltin::ViewportIndex)), - "{builtins:?}" - ); - let budget = Budget::standard(); - let d = render( - &bc, - "rt6_first_vertex", - "rt6_first_vertex_read", - PixelFormat::R32Uint, - ); - let p = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); - assert_eq!(geometry_stages(&p, &dev, "per vertex"), 3); - assert!(p.graphics.declares_layer); - assert!(p.graphics.writes_viewport_index); - assert!(p.requirements.features.contains(&F::GeometryShader)); - assert!(!p - .requirements - .properties - .contains(&VkProperty::MetalFirstVertexIndices)); - for without in [ - device("moltenvk-m3", &[]), - device("lavapipe", &[F::GeometryShader]), - ] { - match without.compile_render_pipeline(&d, &budget) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::LayeredRendering); - assert_eq!(u.needs, any_of(&[F::GeometryShader])); - } - other => panic!("{other:?}"), - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_stage_io.rs b/crates/metal2vulkan/src/tests/engine_stage_io.rs index 865046793..a4eed91b9 100644 --- a/crates/metal2vulkan/src/tests/engine_stage_io.rs +++ b/crates/metal2vulkan/src/tests/engine_stage_io.rs @@ -281,27 +281,13 @@ fn feature_dependent_entries_name_their_capability() { Feature::ClipDistance, F::ShaderClipDistance, ); - // A vertex `Layer` takes the output feature or a geometry stage that writes it. + // A vertex `Layer` takes the output feature. compile(&bc, "stage_io_vertex_layer", &floor).expect("the floor's Layer output"); - let below = profile_without( - "runtime-floor", - &[F::ShaderOutputLayer], - DevicePolicy::default(), - ) - .expect("below the runtime's floor"); - match compile(&bc, "stage_io_vertex_layer", &below) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::LayeredRendering); - assert_eq!( - u.needs, - Needs::AnyOf(vec![ - vec![Capability::Feature(F::ShaderOutputLayer)], - vec![Capability::Feature(F::GeometryShader)], - ]) - ); - } - other => panic!("stage_io_vertex_layer: {other:?}"), - } + needs( + "stage_io_vertex_layer", + Feature::LayeredRendering, + F::ShaderOutputLayer, + ); needs( "stage_io_fragment_point", Feature::SampleRateShading, diff --git a/crates/metal2vulkan/src/tests/engine_target_indices.rs b/crates/metal2vulkan/src/tests/engine_target_indices.rs new file mode 100644 index 000000000..26cb97333 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_target_indices.rs @@ -0,0 +1,346 @@ +//! The render target slice and viewport a vertex function selects, over the owned fixtures +//! `engine/rt6_layered` (a vertex function that chooses its slice per instance, and fragment +//! functions that read it, one with the barycentric weights and the primitive ID), +//! `engine/rt6_viewports` (a vertex function that selects its viewport per instance, and a +//! fragment function that reads it) and `engine/rt6_first_vertex` (a vertex function whose slice +//! and viewport differ among the vertices of a primitive): +//! +//! - An index written the same at every vertex of a primitive is stored to `Layer` or +//! `ViewportIndex` where the device stores the builtin from a vertex function; without +//! `shaderOutputLayer` (`shaderOutputViewportIndex`) it is refused needing that feature alone. +//! The variant for a pass of one layer selects no slice and compiles. +//! - Without `multiViewport` a draw has one viewport, so the vertex function stores no viewport +//! index at all. +//! - An index not shown the same at every vertex of a primitive is refused as not implemented on +//! every device: Metal leaves its primitive undefined and Vulkan asks every vertex to write the +//! same. +//! - A fragment function that reads an index no stage writes, on a device that cannot declare its +//! builtin, reads 0 (`StageIo::zero_indices`). +//! - The weights' geometry stage cannot sit beside a vertex function's own `Layer`: refused as not +//! implemented. +//! +//! Every module that compiles passes L3 (`spirv-val` and requirements within the profile). +//! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used. + +use std::path::Path; + +use crate::budget::Budget; +use crate::cache::VariantKey; +use crate::device::requirements::VkFeature as F; +use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::error::{Capability, Error, Feature, Needs}; +use crate::library::Library; +use crate::metal::PixelFormat; +use crate::pipeline::descriptor::{ + ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, +}; +use crate::pipeline::stage_io::{IoRole, StageBuiltin}; +use crate::pipeline::sym::VaryingKey; +use crate::pipeline::testing::{compile, engine_dir, llvm_assemble, AssembleError}; +use crate::pipeline::RenderPipeline; +use crate::spirv::testing::check_words_valid; +use crate::spv::Capability as Cap; +use crate::vk; + +fn assemble(name: &str) -> Option> { + let path = engine_dir().join(name); + match llvm_assemble(&path) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {path:?}: {why}"), + } +} + +/// Committed profile `stem`'s description without `withheld`. +fn device(stem: &str, withheld: &[F]) -> Device { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(path).expect("profile"); + let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + for f in withheld { + desc.features.remove(f); + } + Device::from_queries(desc, DevicePolicy::default()).expect("device") +} + +/// A render pipeline of `vertex` and `fragment` from `bc`, drawing into one color of `format`. +fn render( + bc: &[u8], + vertex: &str, + fragment: &str, + format: PixelFormat, +) -> RenderPipelineDescriptor { + let lib = Library::from_air(bc).expect("library"); + let stage = |name: &str| { + StageSource::Function(FunctionDescriptor::new( + lib.function(name).expect("function"), + )) + }; + let mut d = RenderPipelineDescriptor::new(stage(vertex)); + d.fragment = Some(stage(fragment)); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format)); + d +} + +/// The geometry stages of `p`, each valid on `dev`, every other stage too. +fn geometry_stages(p: &RenderPipeline, dev: &Device, what: &str) -> usize { + for m in &p.stages { + check_words_valid(&m.spirv, &p.requirements, dev.profile()) + .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); + } + p.stages + .iter() + .filter(|m| m.stage == vk::ShaderStage::GEOMETRY) + .count() +} + +/// The roles of the vertex outputs `entry` of `bc` declares on `dev`, and its builtins. +fn vertex_io(bc: &[u8], entry: &str, dev: &Device) -> (Vec, Vec) { + let a = compile(bc, entry, dev.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); + let io = &a.interface.io; + ( + io.outputs.iter().map(|o| o.role.clone()).collect(), + io.builtins.clone(), + ) +} + +/// `result` is the refusal of layered rendering with `needs`. +fn layered(result: Result, needs: Needs, what: &str) { + match result { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::LayeredRendering, "{what}"); + assert_eq!(u.needs, needs, "{what}"); + } + other => panic!("{what}: {:?}", other.map(|_| ())), + } +} + +fn needs(feature: F) -> Needs { + Needs::AnyOf(vec![vec![Capability::Feature(feature)]]) +} + +/// A slice written the same at every vertex of a primitive is stored to `Layer` where the device +/// stores it from a vertex function, and refused needing `shaderOutputLayer` alone without it, +/// `geometryShader` or not; the variant for a pass of one layer compiles either way. +#[test] +fn a_uniform_slice_takes_the_output_and_nothing_else() { + let Some(bc) = assemble("rt6_layered.ll") else { + return; + }; + let budget = Budget::standard(); + let d = render( + &bc, + "rt6_layered_vertex", + "rt6_layered_fragment", + PixelFormat::R32Uint, + ); + let native = device("lavapipe", &[]); + let (outputs, builtins) = vertex_io(&bc, "rt6_layered_vertex", &native); + assert!(builtins.contains(&StageBuiltin::Layer), "{builtins:?}"); + assert!( + outputs.contains(&IoRole::RenderTargetArrayIndex), + "{outputs:?}" + ); + let p = native + .compile_render_pipeline(&d, &budget) + .expect("pipeline"); + assert_eq!(geometry_stages(&p, &native, "native"), 0); + assert!(p.graphics.declares_layer); + assert!(p.requirements.features.contains(&F::ShaderOutputLayer)); + for (stem, without) in [ + ("lavapipe", device("lavapipe", &[F::ShaderOutputLayer])), + ( + "runtime-floor", + device("runtime-floor", &[F::ShaderOutputLayer]), + ), + ] { + layered( + without.compile_render_pipeline(&d, &budget), + needs(F::ShaderOutputLayer), + stem, + ); + let mut key = VariantKey::new(); + key.dropped_vertex_layer = true; + let one = without + .compile_render_variant(&d, &key, &budget) + .unwrap_or_else(|e| panic!("{stem}, one layer: {e}")); + assert_eq!(geometry_stages(&one, &without, stem), 0); + assert!(!one.requirements.features.contains(&F::ShaderOutputLayer)); + } +} + +/// A viewport written the same at every vertex of a primitive is stored to `ViewportIndex` where +/// the device stores it from a vertex function, through `ShaderViewportIndex`; a device with +/// `multiViewport` but without `shaderOutputViewportIndex` refuses it needing that feature alone, +/// and a device without `multiViewport` draws through one viewport and stores none, its pipeline +/// still stating that the vertex function writes the index. +#[test] +fn a_uniform_viewport_takes_the_output_or_goes_nowhere() { + let Some(bc) = assemble("rt6_viewports.ll") else { + return; + }; + let budget = Budget::standard(); + let d = render( + &bc, + "rt6_select", + "rt6_viewport_read", + PixelFormat::RGBA8Unorm, + ); + let native = device("lavapipe", &[]); + let (outputs, builtins) = vertex_io(&bc, "rt6_select", &native); + assert!( + builtins.contains(&StageBuiltin::ViewportIndex), + "{builtins:?}" + ); + assert!(outputs.contains(&IoRole::ViewportIndex), "{outputs:?}"); + let p = native + .compile_render_pipeline(&d, &budget) + .expect("pipeline"); + assert_eq!(geometry_stages(&p, &native, "native"), 0); + assert!(p.graphics.writes_viewport_index); + let index = crate::device::SpirvCapability::from_raw(Cap::ShaderViewportIndex as u32); + assert!(p.requirements.spirv_capabilities.contains(&index)); + layered( + device("lavapipe", &[F::ShaderOutputViewportIndex]).compile_render_pipeline(&d, &budget), + needs(F::ShaderOutputViewportIndex), + "multiViewport without the output", + ); + // Without `multiViewport`, on the floor too: the raw index alone. + for dev in [ + device( + "lavapipe", + &[F::ShaderOutputViewportIndex, F::MultiViewport], + ), + device("runtime-floor", &[]), + ] { + let (outputs, builtins) = vertex_io(&bc, "rt6_select", &dev); + assert_eq!(outputs, [IoRole::ViewportIndex], "{builtins:?}"); + assert!(!builtins.contains(&StageBuiltin::ViewportIndex)); + let p = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); + assert_eq!(geometry_stages(&p, &dev, "one viewport"), 0); + // The function still writes the index: the runtime refuses its draw while the encoder + // holds more than one viewport. + assert!(p.graphics.writes_viewport_index); + } +} + +/// A vertex function whose slice and viewport differ among the vertices of a primitive +/// (`engine/rt6_first_vertex`) writes neither alike, as its structure shows, where one whose slice +/// is the same at every vertex (`rt6_layered_vertex`) writes it alike; the first is refused as not +/// implemented on every device, with the outputs, with `geometryShader` and without it. +#[test] +fn indices_that_differ_among_a_primitive_s_vertices_are_refused() { + let Some(layered_bc) = assemble("rt6_layered.ll") else { + return; + }; + let Some(bc) = assemble("rt6_first_vertex.ll") else { + return; + }; + let dev = device("lavapipe", &[]); + let uniform = |bc: &[u8], entry: &str| { + let a = compile(bc, entry, dev.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); + a.interface.io.uniform_outputs.clone() + }; + let alike = uniform(&layered_bc, "rt6_layered_vertex"); + assert!( + alike.contains(&VaryingKey::render_target_array_index()), + "{alike:?}" + ); + let d = render( + &bc, + "rt6_first_vertex", + "rt6_first_vertex_read", + PixelFormat::R32Uint, + ); + for (stem, dev) in [ + ("lavapipe", device("lavapipe", &[])), + ("moltenvk-m3", device("moltenvk-m3", &[])), + ( + "lavapipe without geometryShader", + device("lavapipe", &[F::GeometryShader]), + ), + ("runtime-floor", device("runtime-floor", &[])), + ] { + for entry in ["rt6_first_vertex", "rt6_first_vertex_point"] { + match compile(&bc, entry, dev.profile()) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::LayeredRendering, "{stem} {entry}"); + assert_eq!(u.needs, Needs::NotImplemented, "{stem} {entry}"); + } + other => panic!("{stem} {entry}: {:?}", other.map(|_| ())), + } + } + layered( + dev.compile_render_pipeline(&d, &Budget::standard()), + Needs::NotImplemented, + stem, + ); + } +} + +/// A fragment function that reads the slice or viewport no stage writes reads 0 on a device that +/// cannot declare the builtin, which it lists: the viewport on the floor, and the slice on the +/// floor without its `shaderOutputLayer`. +#[test] +fn on_the_floor_a_read_of_an_index_no_stage_writes_is_zero() { + let Some(amp) = assemble("vertex_amplification.ll") else { + return; + }; + for (entry, zero, floor) in [ + ( + "amp_fragment_layer", + vec![StageBuiltin::Layer], + device("runtime-floor", &[F::ShaderOutputLayer]), + ), + ( + "amp_fragment", + vec![StageBuiltin::ViewportIndex], + device("runtime-floor", &[]), + ), + ] { + let a = compile(&, entry, floor.profile()).unwrap_or_else(|e| panic!("{entry}: {e}")); + assert_eq!(a.interface.io.zero_indices, zero, "{entry}"); + assert!(!a + .interface + .io + .builtins + .iter() + .any(|b| matches!(b, StageBuiltin::Layer | StageBuiltin::ViewportIndex))); + } +} + +/// The weights' synthesized geometry stages cannot read a vertex function's own `Layer`: a +/// pipeline whose vertex function stores its slice beside a fragment function that reads the +/// weights, on a device without `fragmentShaderBarycentric`, is refused as not implemented, and +/// compiles with no geometry stage where the device reads the weights itself (the 780M's profile, +/// with and without the feature). +#[test] +fn the_weights_stage_beside_a_vertex_layer_is_not_implemented() { + let Some(bc) = assemble("rt6_layered.ll") else { + return; + }; + let d = render( + &bc, + "rt6_layered_vertex", + "rt6_layered_weights", + PixelFormat::R32Uint, + ); + let mixed = device("amd-780m-radv", &[F::FragmentShaderBarycentric]); + match mixed.compile_render_pipeline(&d, &Budget::standard()) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::Barycentrics); + assert_eq!(u.needs, Needs::NotImplemented); + } + other => panic!("{:?}", other.map(|_| ())), + } + let native = device("amd-780m-radv", &[]); + let p = native + .compile_render_pipeline(&d, &Budget::standard()) + .expect("pipeline"); + assert_eq!(geometry_stages(&p, &native, "native weights"), 0); + assert!(p.graphics.declares_layer); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index d4ec45798..051fb2ff6 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -156,7 +156,6 @@ mod engine_sampler; mod engine_sampler_completion; mod engine_sampler_tail; mod engine_sampler_unk; -mod engine_selected_indices; mod engine_separate_samplers; mod engine_seq_cst; mod engine_shared_switch; @@ -185,6 +184,7 @@ mod engine_storage_view_variant; mod engine_swizzled_storage; mod engine_table_copies; mod engine_tables; +mod engine_target_indices; mod engine_tessellation; mod engine_texel_rows; mod engine_texture; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 31f62927d..feb6ee079 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -885,7 +885,6 @@ enum metal2vulkan::error::ComputePipelineProblem #[derive(Clone, Copy, Debug, Pa enum metal2vulkan::error::ConstantRecord #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ConstantRecord enum metal2vulkan::error::ContainerError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ContainerError enum metal2vulkan::error::DescriptorError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum DescriptorError -enum metal2vulkan::error::DriverDeviation #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverDeviation enum metal2vulkan::error::DynamicLibraryProblem #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DynamicLibraryProblem enum metal2vulkan::error::Error #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Error enum metal2vulkan::error::ErrorClass #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ErrorClass @@ -7068,7 +7067,6 @@ method metal2vulkan::device::DeviceProfile::specialized_entry pub fn specialized method metal2vulkan::device::DeviceProfile::spirv_validation pub fn spirv_validation(&self) -> SpirvValidation method metal2vulkan::device::DeviceProfile::subgroups pub fn subgroups(&self) -> &SubgroupModel method metal2vulkan::device::DeviceProfile::supports_format pub fn supports_format(&self, format: vk::Format, usage: FormatUsage) -> bool -method metal2vulkan::device::DeviceProfile::takes_driver_deviation pub fn takes_driver_deviation(&self, deviation: DriverDeviation) -> bool method metal2vulkan::device::DeviceProfile::ulong_atomic_gaps pub fn ulong_atomic_gaps(&self, buffer: bool) -> Vec method metal2vulkan::device::DeviceProfile::union_requirements pub fn union_requirements(&self, a: &Requirements, b: &Requirements) -> Requirements method metal2vulkan::device::DeviceProfile::vertex_entry_inputs pub fn vertex_entry_inputs(&self, d: &EntryDescriptor<'_>, vertex: Option<&VertexDescriptor>, budget: &Budget) -> Result @@ -7347,8 +7345,6 @@ method metal2vulkan::pipeline::VaryingKey::color pub fn color(attachment: u32, i method metal2vulkan::pipeline::VaryingKey::merged_command pub fn merged_command() -> VaryingKey method metal2vulkan::pipeline::VaryingKey::primitive_id pub fn primitive_id() -> VaryingKey method metal2vulkan::pipeline::VaryingKey::render_target_array_index pub fn render_target_array_index() -> VaryingKey -method metal2vulkan::pipeline::VaryingKey::selected_layer pub fn selected_layer() -> VaryingKey -method metal2vulkan::pipeline::VaryingKey::selected_viewport pub fn selected_viewport() -> VaryingKey method metal2vulkan::pipeline::VaryingKey::user pub fn user(k: &[u8]) -> VaryingKey method metal2vulkan::pipeline::VaryingKey::viewport_index pub fn viewport_index() -> VaryingKey method metal2vulkan::pipeline::VertexAttributeDescriptor::new pub fn new(format: metal::VertexFormat, offset: u32, buffer_index: u32) -> Self @@ -10268,7 +10264,6 @@ variant metal2vulkan::device::VkProperty::IndependentResolve IndependentResolve variant metal2vulkan::device::VkProperty::IndependentResolveNone IndependentResolveNone variant metal2vulkan::device::VkProperty::InterpolateAtOffsetCentered InterpolateAtOffsetCentered variant metal2vulkan::device::VkProperty::InterpolateAtOffsetFromSevenSixteenths InterpolateAtOffsetFromSevenSixteenths -variant metal2vulkan::device::VkProperty::MetalFirstVertexIndices MetalFirstVertexIndices variant metal2vulkan::device::VkProperty::ProvokingVertexModePerPipeline ProvokingVertexModePerPipeline variant metal2vulkan::device::VkProperty::RequiredSubgroupSizeStage RequiredSubgroupSizeStage(Stage) variant metal2vulkan::device::VkProperty::Rgba4OpaqueBlackSwizzled Rgba4OpaqueBlackSwizzled @@ -10414,7 +10409,6 @@ variant metal2vulkan::error::DescriptorError::VertexAmplificationCount VertexAmp variant metal2vulkan::error::DescriptorError::VertexAttribute VertexAttribute { attribute: u32 } variant metal2vulkan::error::DescriptorError::VertexLayout VertexLayout { layout: u32 } variant metal2vulkan::error::DescriptorError::VertexStepRate VertexStepRate { step_rate: u32 } -variant metal2vulkan::error::DriverDeviation::MetalFirstVertexIndices MetalFirstVertexIndices variant metal2vulkan::error::DynamicLibraryProblem::FunctionConstants FunctionConstants variant metal2vulkan::error::DynamicLibraryProblem::NoInstallName NoInstallName variant metal2vulkan::error::DynamicLibraryProblem::NotDynamic NotDynamic @@ -11088,7 +11082,7 @@ variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevelViews StorageTex variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevels StorageTextureLevels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTextureNumericType { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureWriteRounding StorageTextureWriteRounding { slot: SlotRef, halves: bool } -variant metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry SynthesizedGeometry { weights: bool, layer: bool, viewport: bool } +variant metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry SynthesizedGeometry { weights: bool } variant metal2vulkan::pipeline::RuntimeFact::TestedStorageWrites TestedStorageWrites { early_tests: bool, early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferParts TexelBufferParts { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 78da1dc16..b21a94c2e 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -189,7 +189,6 @@ surface! { enum Retry N; struct Unsupported N; enum Needs N; - enum DriverDeviation N; enum Capability N; enum Feature N; enum SparseNeed N; diff --git a/docs/API.md b/docs/API.md index ad527fed1..8f2ebb41a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -261,8 +261,7 @@ println!(" Metal properties: {:?}", device.metal_properties()); fields, so two machines that differ only there share artifacts. - `profile().spirv_validation()`: the `spirv-val` environments and relaxations every module for the device is valid under. The command line runs exactly these. -- The profile's facts: `enabled()`, `limits()`, `images()`, `fragment()`, `descriptors()`, the - measured deviations it takes (`driver_deviations()`), +- The profile's facts: `enabled()`, `limits()`, `images()`, `fragment()`, `descriptors()`, its `subgroups()` model and `simd_tier(...)`, the buffer robustness that bounds a buffer-slot access (`robustness()`, `checks_buffers_in_shader()`), and the Function storage a thread holds (`function_storage()`: `FunctionStorage::Measured` bytes for a measured @@ -744,8 +743,7 @@ A `RenderPipeline` holds: - `stages`: vertex, then fragment when rasterization is enabled, with three geometry stages before the fragment stage when the fragment function reads `[[barycentric_coord]]` on a device - without `fragmentShaderBarycentric`, or the vertex function selects its slice or viewport on a - device without the output (below). A `VkPipeline` takes the stages + without `fragmentShaderBarycentric` (below). A `VkPipeline` takes the stages `RenderPipeline::runs_stage(at, topology)` says its topology runs; - `layout`: one pipeline layout for every stage; - `vertex_input`: Vulkan bindings and attributes. An attribute Vulkan cannot fetch as described is @@ -878,29 +876,23 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: without `shaderTessellationAndGeometryPointSize`, more varyings than the geometry limits), the pipeline is refused, naming what it needs. Measured on the Iris Xe (ANV), such a pipeline takes about 2.6 ms longer to create, and a geometry stage's presence costs about 15% of fill rate. -- A primitive renders into the slice and through the viewport its first vertex selects, the range - check applying to that vertex's index, and its fragments read the first vertex's indices as - written, where Vulkan asks every vertex of a primitive to write the same `Layer` and - `ViewportIndex`. A vertex function stores an index to its builtin only where it writes - the same at every vertex of a primitive, decided from its structure (computed from constants, - `constant` memory, the instance, the amplification and per-instance attributes, as - `StageIo::uniform_outputs` lists), or on MoltenVK, which hands the builtins to Metal - (`DriverDeviation::MetalFirstVertexIndices`). Otherwise, and on a device without - `shaderOutputLayer` or `shaderOutputViewportIndex`, the vertex function stores the index it - selects to a flat varying and the same generated geometry stages (one set serving the weights, the - primitive ID and the indices) store `Layer` or `ViewportIndex` from the primitive's first vertex - at every vertex they emit; where it stores one index so, it stores the other so too. The variant - for a pass of one layer selects no slice and carries no stage. A device without `multiViewport` - draws through one viewport, so there the vertex function stores no viewport index at all; a draw - that selects among more than one viewport there is refused at the draw, - `Unsupported(LayeredRendering)` needing `multiViewport`. Without `geometryShader` either, a vertex - function that selects its slice is refused needing either feature (its pass of one layer still - runs), and so is one that selects its viewport on a device with `multiViewport`; one whose index - differs among a primitive's vertices is refused needing `geometryShader`. The stages cannot serve - a post-tessellation vertex function, nor sit beside a vertex function - that writes the builtins itself (a device with the outputs but without - `fragmentShaderBarycentric`): those are refused as not implemented. A fragment function that reads - an index no stage writes, on a device that can declare neither builtin, reads 0, Metal's value +- A vertex function stores `Layer` or `ViewportIndex` only where it writes the index the same at + every vertex of a primitive, decided from its structure (computed from constants, `constant` + memory, the instance, the amplification and per-instance attributes, as + `StageIo::uniform_outputs` lists), on a device with `shaderOutputLayer` or + `shaderOutputViewportIndex`. Metal leaves a primitive whose vertices write different indices + undefined ("If values differ, the behavior and value passed to the fragment function are + undefined.", the Metal Shading Language specification), and Vulkan asks every vertex of a + primitive to write the same `Layer` and `ViewportIndex` + (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597), so a vertex function whose index + is not shown the same is refused, `NotImplemented(LayeredRendering)`. One shown the same on a + device without the output is refused needing it, as `Unsupported(LayeredRendering)`, or as + `Unsupported(VertexAmplification)` for an index the amplification's offset alone sets. The + variant for a pass of one layer selects no slice and runs everywhere. A device without + `multiViewport` draws through one viewport, so there the vertex function stores no viewport + index at all; a draw that selects among more than one viewport there is refused at the draw, + `Unsupported(LayeredRendering)` needing `multiViewport`. A fragment function that reads an + index no stage writes, on a device that can declare neither builtin, reads 0, Metal's value with no vertex write. - `[[primitive_id]]` counts the draw's primitives in each instance from 0; vertex start, base vertex and base instance do not move it. A fragment stage declares `PrimitiveId` through diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f8623fc8f..cafde9ea9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,10 +33,8 @@ metallib | AIR bitcode ── link ────────► bindings, Locations, spec ids, the pipeline pipeline::link layout, pipeline-wide limits, the generated pipeline::link::geometry geometry stages (barycentric weights read as pipeline::link::band - varyings, a selected slice or viewport stored - from the first vertex), the generated - tessellation stages that draw a wide line as a - band + varyings), the generated tessellation stages + that draw a wide line as a band ── relocate ────► the final words of each stage pipeline::relocate = ComputePipeline | RenderPipeline | tile and mesh pipelines diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index b358b395f..3452ad29a 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -113,8 +113,8 @@ Columns: | `FramebufferFetch` | Framebuffer fetch without an ordered form on the device (rasterization-order attachment access, or the pixel interlock's storage form where the... | devices short of a Vulkan property the site names; devices without VkFeature::FragmentShaderPixelInterlock; devices without VkFeature::RasterizationOrderColorAttachmentAccess; devices without VkFeature::SampleRateShading; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/sample_planes.rs (finish)`, `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (packed16)` (+8) | `system`: programmable blending (framebuffer fetch); macOS 26.6.2's login reaches it (two WindowServer and RenderBox pipelines fetch RGB10A8_2P_XR10 attachments, the consumer's boots) | | `PrimitiveId` | `[[primitive_id]]` in a fragment function | devices without a capability the site computes; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` | `rare`: primitive_id on a device without geometry or tessellation shaders, in an indexed draw or behind a mesh function | | `PrivatePrimitives` | One of Metal's private primitive types (a line loop, a triangle fan, quads, a quad strip) drawn in the pulled list form... | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` | `rare`: a private primitive type drawn in the pulled list form (a vertex function that writes memory or the primitive_id varying, a vertex start past 2^31) on a device without device addresses | -| `VertexAmplification` | Vertex amplification | devices without VkFeature::Multiview; devices without VkFeature::MultiviewTessellationShader; devices without VkLimit::MaxMultiviewInstanceIndex; devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (own_index_store)` (+3) | `rare`: vertex amplification | -| `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex; devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (own_index_store)` (+2) | `rare`: layered rendering on a device without its features | +| `VertexAmplification` | Vertex amplification | devices short of a Vulkan feature the site names; devices without VkFeature::Multiview; devices without VkFeature::MultiviewTessellationShader; devices without VkLimit::MaxMultiviewInstanceIndex; every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)` (+3) | `rare`: vertex amplification | +| `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices short of a Vulkan feature the site names; devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` | `rare`: layered rendering on a device without its features | | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | `device` | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | `device` | 3: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)` (+1) | `rare`: dual-source blending on a device without it | | `Barycentrics` | Barycentric coordinates | devices without VkFeature::FragmentShaderBarycentric; devices without VkFeature::GeometryShader; devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` (+2) | `rare`: barycentric coordinates | @@ -135,7 +135,7 @@ Columns: | `Imageblocks` | An imageblock outside the forms implemented | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+6) | `rare`: imageblocks (Apple GPU families) | | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)` (+5) | `rare`: ray tracing (out of scope by ruling) | | `Tensors` | | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`, `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: shader tensors | -| `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; devices without VkLimit::MaxGeometryTotalOutputComponents; devices without a capability the site computes; devices without a capability the site computes (`vec![Capability::Feature(lacks)]`); every device (not implemented) | `ours` | 10: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` (+3) | `rare`: rasterization rate maps | +| `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; devices without VkLimit::MaxGeometryTotalOutputComponents; devices without a capability the site computes; devices without a capability the site computes (`vec![Capability::Feature(lacks)]`); devices without a capability the site computes (`vec![limit]`); every device (not implemented) | `ours` | 11: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` (+3) | `rare`: rasterization rate maps | | `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 20: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`, `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)` (+12) | `rare`: indirect command buffers encoded by a kernel | | `VulkanVersion` | The device's Vulkan version is below the 1.2 floor | devices without ApiVersion::V1_2 | `device` | 2: `crates/metal2vulkan/src/ash_interop/query.rs (query)`, `crates/metal2vulkan/src/device/derive.rs (from_queries)` | `none`: a device below Vulkan 1.2 | | `PushWindow` | The device's `maxPushConstantsSize` is below the 256 bytes of the push window every stage is lowered for | devices without VkLimit::MaxPushConstantsSize | `device` | 1: `crates/metal2vulkan/src/device/derive.rs (from_queries)` | `none`: a device whose maxPushConstantsSize is below 256 bytes | @@ -454,8 +454,8 @@ Each refusal's sites, with the function that builds it. - `feature::FramebufferFetch`: `crates/metal2vulkan/src/bind/sample_planes.rs (finish)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (packed16)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (srgb8)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (unorm8, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/color.rs (unordered)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (unordered_extended_fetch)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs (storage_attachments)` - `feature::PrimitiveId`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` - `feature::PrivatePrimitives`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` -- `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (own_index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` -- `feature::LayeredRendering`: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (own_index_store)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (refused)` +- `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` +- `feature::LayeredRendering`: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` - `feature::DualSourceBlending`: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::Barycentrics`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (refused)` @@ -475,7 +475,7 @@ Each refusal's sites, with the function that builds it. - `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (reach)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (require)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs (fragment_imageblock)` - `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` -- `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (region_box)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (check_limits)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (fan_plan, 3 sites)` +- `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_copy, 3 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (region_box)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (check_limits, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs (fan_plan, 3 sites)` - `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/merged.rs (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/encode.rs (needs, 3 sites)`; `crates/metal2vulkan/src/lower/access/encode.rs (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs (plan_replay, 3 sites)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`; `crates/metal2vulkan/src/lower/select.rs (finish, 2 sites)`; `crates/metal2vulkan/src/lower/simd/divergent.rs (barriers)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/pipeline/compile.rs (analyze_one, 2 sites)` - `feature::VulkanVersion`: `crates/metal2vulkan/src/ash_interop/query.rs (query)`; `crates/metal2vulkan/src/device/derive.rs (from_queries)` - `feature::PushWindow`: `crates/metal2vulkan/src/device/derive.rs (from_queries)`