From 4aee2fa9f1a93afe89c7c78284d2e39c19a00978 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 21:09:09 -0800 Subject: [PATCH] Translator: the ordered fetch form goes; its computed writes are refused on every device The framebuffer fetch had a second form chosen by rasterizationOrderColorAttachmentAccess: over a rasterization-order input attachment, a fragment function computed writes no Vulkan blend, write mask or logic operation gives. No runtime enables that feature, so the form ran on no guest's device. It goes (rule 2: a second form chosen by a query outside the named list; rule 4). What changes: - A fetch reads its input attachment ordered between draws alone on every device, noted UnorderedFetchWithinDraw. Under the identity domains it reads the pushed texture (PushField::FetchedColor). - These states are refused on every device: a padded extended-range attachment's blend; a write of some of the codes one word of an extended-range attachment holds; and a blend no Vulkan state gives on a rotated (ARGB8Unorm) attachment. Each refusal is FramebufferFetch, not implemented (lower::fragment::fetch::computed_write_refused). - A word attachment under a partial mask takes its format's own attachment, and is refused where the device lacks that format. - A private logic operation on a device without logicOp is refused naming PrivateRenderState(LogicOperation) and logicOp. - Deleted: lower/fragment/input_blend.rs, word_input.rs, the shader logic operation in logic.rs, lower/arith/extended_range/blend.rs, pipeline/link/fetch.rs, and the arithmetic only they used (the fma emulation cluster, div_exact, encode_keeping). - Deleted public items: - LoweringInputs.framebuffer_fetch and .logic_operation; - FramebufferFetchInputs, FetchedAttachment, BlendEquation; - GraphicsState.rasterization_order_attachment_access and FragmentCaps.rasterization_order_color_access; - metal::format::extended_range_blend, Feature::ExtendedRangeBlend and the ExtendedRangeBlend enum; - RuntimeInput::FramebufferFetch and ::LogicOperation; - RuntimeFact::ExtendedRangeInputBlend, ::RotatedInputBlend and ::WordInputMerge; - PrecisionNote::ExtendedRangeBlendSource and ::ExtendedRangeFloatBlendSource. - The enable-set facts class VK_EXT_rasterization_order_attachment_access as described and never enabled. Docs, in this commit: - rt README: Known gaps of render encoders gets one line per refused state, each built on the runtime's own fetch form if a guest meets it. The Not-enabled row of rasterizationOrderColorAttachmentAccess goes, and so does logicOp's mention of the shader form. - docs/API.md loses the two blend-source notes from the precision-note catalogue, the rasterization-order form and the word merge. - REFUSALS.md is regenerated (reach row of ExtendedRangeBlend removed), along with api_signatures.tsv and the api_surface table. - The conformance ledger: the 39 rows refused naming rasterization-order access (on llvmpipe and the UHD 630; on other venues the case read as lacks-feature) become 22 every-venue rows, refused, needs NotImplemented. The matrix replay on development confirms the scope. Lines: product sources (crates/metal2vulkan, -air, -runtime src, tests excluded) +238 -4647; product tests +277 -2279; validation and conformance +61 -182; docs +48 -67. Consumer search (reims-vgpu at 71573a84c8, git grep -w over *.rs, *.toml and *.md): - 0 hits: ExtendedRangeBlend, rasterization_order_color_access, BlendEquation, FramebufferFetchInputs, rasterization_order_attachment_access, framebuffer_fetch, extended_range_blend, ExtendedRangeBlendSource, ExtendedRangeFloatBlendSource, ExtendedRangeInputBlend, RotatedInputBlend, WordInputMerge, DualSource. - Hits that are not these items: FetchedAttachment 2 (rt's DrawKind); logic_operation 8 (its own structs and rt's private state). - RuntimeInput: only LinkedFunction is used. - No glob import or re-export of a metal2vulkan module (only `use metal2vulkan_runtime as rt`). Verified: cargo fmt; refusal surface and signatures regenerated locally. The compile job and the host suites follow on the branch. --- .../known-gaps-rt.tsv | 67 +- .../src/cases/extended_range_blends.rs | 5 - .../src/cases/fetch_ordered.rs | 4 +- .../src/cases/padded_blends.rs | 5 +- .../src/cases/padded_fetch.rs | 4 +- .../src/cases/rotated_targets.rs | 8 +- .../src/degradation.rs | 16 - crates/metal2vulkan-conformance/src/replay.rs | 6 - crates/metal2vulkan-runtime/README.md | 38 +- .../src/tests/translator_fields.rs | 4 - .../src/candidate/engine/artifact/tests.rs | 1 - .../src/candidate/engine/graphics/tests.rs | 65 +- .../candidate/platform/graphics_pipeline.rs | 46 +- .../src/candidate/platform/render.rs | 7 +- .../src/candidate/tests/engine_render.rs | 4 +- .../tests/integration/pipeline_selection.rs | 5 +- crates/metal2vulkan/src/cache/codec.rs | 19 +- crates/metal2vulkan/src/device/derive.rs | 1 - crates/metal2vulkan/src/device/enables.rs | 4 +- crates/metal2vulkan/src/device/mechanism.rs | 9 - crates/metal2vulkan/src/device/metal.rs | 4 +- crates/metal2vulkan/src/device/profile.rs | 3 +- .../src/device/tests/description.rs | 15 +- .../metal2vulkan/src/device/tests/enables.rs | 4 + .../src/device/tests/mechanism.rs | 46 +- .../metal2vulkan/src/device/tests/subgroup.rs | 7 +- crates/metal2vulkan/src/error/mod.rs | 38 +- .../src/lower/arith/exact_division.rs | 90 +- .../src/lower/arith/extended_range.rs | 30 - .../src/lower/arith/extended_range/blend.rs | 1556 ----------------- .../src/lower/arith/extended_range/tests.rs | 372 +--- crates/metal2vulkan/src/lower/arith/fma.rs | 206 +-- .../src/lower/arith/output_precision.rs | 54 - crates/metal2vulkan/src/lower/arith/tests.rs | 6 - .../src/lower/arith/tests/blend8.rs | 680 ------- .../src/lower/arith/tests/fused.rs | 71 - .../src/lower/arith/tests/narrow.rs | 26 - .../src/lower/arith/texel_round.rs | 9 +- .../metal2vulkan/src/lower/fragment/color.rs | 100 +- .../metal2vulkan/src/lower/fragment/fetch.rs | 390 +---- .../src/lower/fragment/fetch/tests.rs | 89 - .../src/lower/fragment/input_blend.rs | 501 ------ .../metal2vulkan/src/lower/fragment/logic.rs | 451 +---- .../src/lower/fragment/logic/tests.rs | 24 +- crates/metal2vulkan/src/lower/fragment/mod.rs | 80 +- crates/metal2vulkan/src/lower/fragment/rog.rs | 35 +- .../src/lower/fragment/word_input.rs | 131 -- crates/metal2vulkan/src/lower/select.rs | 3 - .../src/lower/stage_io/extended_color.rs | 31 +- crates/metal2vulkan/src/lower/stage_io/mod.rs | 70 +- .../metal2vulkan/src/lower/stage_io/plan.rs | 22 +- crates/metal2vulkan/src/metal/format/mod.rs | 22 +- crates/metal2vulkan/src/metal/format/word.rs | 17 +- crates/metal2vulkan/src/pipeline/api_tests.rs | 24 - crates/metal2vulkan/src/pipeline/artifact.rs | 61 +- .../metal2vulkan/src/pipeline/color_writes.rs | 83 +- crates/metal2vulkan/src/pipeline/compile.rs | 128 +- .../metal2vulkan/src/pipeline/compile/api.rs | 33 +- .../metal2vulkan/src/pipeline/compile/key.rs | 15 +- .../src/pipeline/compile/tests.rs | 97 +- crates/metal2vulkan/src/pipeline/facts.rs | 47 - crates/metal2vulkan/src/pipeline/graphics.rs | 21 +- crates/metal2vulkan/src/pipeline/link.rs | 19 +- .../metal2vulkan/src/pipeline/link/fetch.rs | 163 -- .../src/pipeline/link/graphics.rs | 113 +- .../src/pipeline/link/tests/render.rs | 11 - .../metal2vulkan/src/pipeline/lower_inputs.rs | 139 +- crates/metal2vulkan/src/pipeline/mod.rs | 5 +- .../src/pipeline/private_state.rs | 156 +- .../src/pipeline/rotated_blend.rs | 16 +- crates/metal2vulkan/src/pipeline/stage_io.rs | 7 - crates/metal2vulkan/src/pipeline/sym.rs | 3 +- crates/metal2vulkan/src/pipeline/testing.rs | 3 +- .../src/tests/engine_coverage_loop.rs | 3 +- .../src/tests/engine_dead_fetch.rs | 9 +- .../src/tests/engine_dead_reads.rs | 23 +- .../blended_pipelines.rs | 91 +- .../tests/engine_extended_range/targets.rs | 40 +- .../src/tests/engine_fetch_blend8.rs | 76 +- .../metal2vulkan/src/tests/engine_fragment.rs | 334 +--- .../engine_function_constant_interface.rs | 5 +- .../src/tests/engine_padded_blends.rs | 177 +- .../src/tests/engine_private_render_state.rs | 123 +- .../src/tests/engine_rotated_colors.rs | 41 +- .../src/tests/engine_word_attachments.rs | 127 +- .../metal2vulkan/src/tests/golden_hashes.rs | 28 +- crates/metal2vulkan/tests/api_signatures.tsv | 35 - crates/metal2vulkan/tests/api_surface.rs | 5 - docs/API.md | 61 +- docs/REFUSALS.md | 16 +- scripts/refusal-surface/reach.tsv | 1 - 91 files changed, 624 insertions(+), 7216 deletions(-) delete mode 100644 crates/metal2vulkan/src/lower/arith/extended_range/blend.rs delete mode 100644 crates/metal2vulkan/src/lower/arith/tests/blend8.rs delete mode 100644 crates/metal2vulkan/src/lower/fragment/fetch/tests.rs delete mode 100644 crates/metal2vulkan/src/lower/fragment/input_blend.rs delete mode 100644 crates/metal2vulkan/src/lower/fragment/word_input.rs delete mode 100644 crates/metal2vulkan/src/pipeline/link/fetch.rs diff --git a/crates/metal2vulkan-conformance/known-gaps-rt.tsv b/crates/metal2vulkan-conformance/known-gaps-rt.tsv index 85181f8cd..bc1aaaec3 100644 --- a/crates/metal2vulkan-conformance/known-gaps-rt.tsv +++ b/crates/metal2vulkan-conformance/known-gaps-rt.tsv @@ -3086,11 +3086,9 @@ half-output-blends-rgba32f NVIDIA divergent case/blended/zero-1msa 4 elements di # # The sampleRateShading cases' states whose fragment function must read its own attachment # (framebuffer fetch): typed refusals until a stream uses them. The computed write over that read -# is not built on any venue (rt README, Known gaps, the fetch bullet). On a device without -# rasterization-order attachment access the case reads lacks-feature, which no row lists: every -# GPU venue of the replays at ce998742d7, the RX 550, the 780M, the RX 7900 XTX, the Iris Xe and -# the NVIDIA cards. -argb8-targets-destination-alpha llvmpipe refused case/pipeline/argb8 Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is a blend that reads destination alpha on an `ARGB8Unorm` attachment, whose image holds its channels rotated, which the translator computes in the fragment function over the rotated texel, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, naming rasterization-order attachment access). The translator builds that computed write only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). +# is not built on any venue (rt README, Known gaps of pipeline states), so each is refused, not +# implemented, on every venue. +argb8-targets-destination-alpha * refused case/pipeline/argb8 Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is a blend that reads destination alpha on an `ARGB8Unorm` attachment, whose image holds its channels rotated, which the translator computes in the fragment function over the rotated texel, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, not implemented). That computed write is not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatASTC_4x4_LDR/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x1/private/size-and-align Err(Error::Unsupported("no texture of ASTC4x4LDR is made on this device for the usage")) The device's own answer (rule 2): this device's format queries offer no image of MTLPixelFormatASTC_4x4_LDR with the usage the case asks, so rt makes no such texture (Gap::TextureFormat, or the creator's NotMade). texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatASTC_4x4_LDR/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x1/private/texture Err(Error::Unsupported("no texture of ASTC4x4LDR is made on this device for the usage")) The device's own answer (rule 2): this device's format queries offer no image of MTLPixelFormatASTC_4x4_LDR with the usage the case asks, so rt makes no such texture (Gap::TextureFormat, or the creator's NotMade). texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatASTC_4x4_LDR/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x11/private/size-and-align Err(Error::Unsupported("no texture of ASTC4x4LDR is made on this device for the usage")) The device's own answer (rule 2): this device's format queries offer no image of MTLPixelFormatASTC_4x4_LDR with the usage the case asks, so rt makes no such texture (Gap::TextureFormat, or the creator's NotMade). @@ -3100,16 +3098,16 @@ texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatASTC_4x4_LDR/Typ texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatBC1_RGBA/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x4/private/size-and-align Err(Error::Unsupported("no texture of BC1RGBA is made on this device for the usage")) The device's own answer (rule 2): this device's format queries offer no image of MTLPixelFormatBC1_RGBA with the usage the case asks, so rt makes no such texture (Gap::TextureFormat, or the creator's NotMade). texture-pairs-usage-crossings RX 550 refused case/MTLPixelFormatBC1_RGBA/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x4/private/texture Err(Error::Unsupported("no texture of BC1RGBA is made on this device for the usage")) The device's own answer (rule 2): this device's format queries offer no image of MTLPixelFormatBC1_RGBA with the usage the case asks, so rt makes no such texture (Gap::TextureFormat, or the creator's NotMade). vertex-fetch-past-4gib-small-buffer * refused case/pipeline:vertex-6 Err(Error::Translation("the translator made no pipeline: unsupported: VertexInputLayout; needs NotImplemented")) refused: no stream uses it yet (states-only play 11-19, m3-max-56371-56373, 56375, player 44668b439f: 32 streams, every render and compute pipeline state made). The translator refuses the state (VertexInputLayout: the vertex layout); rt README, Known gaps of pipeline states. -xr-masked-bgr10xr-blue-green llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, naming rasterization-order attachment access). The translator builds that computed write only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -xr-masked-bgr10xr-red llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, naming rasterization-order attachment access). The translator builds that computed write only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). +xr-masked-bgr10xr-blue-green * refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, not implemented). That computed write is not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +xr-masked-bgr10xr-red * refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, not implemented). That computed write is not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. xr-masked-bgr10xr-red-over llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-red-over RX 7900 XTX refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-red-over 780M refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-red-over NVIDIA refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-red-over Iris(R) Xe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-red-over RX 550 refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. -xr-masked-bgr10xr-srgb-blue-green llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, naming rasterization-order attachment access). The translator builds that computed write only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -xr-masked-bgr10xr-srgb-red llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, naming rasterization-order attachment access). The translator builds that computed write only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). +xr-masked-bgr10xr-srgb-blue-green * refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, not implemented). That computed write is not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +xr-masked-bgr10xr-srgb-red * refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at render pipeline, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The state is an extended-range attachment under a partial write mask, or a mask under a blend, which the translator merges into the attachment's packed word in the fragment function, reading the attachment's texel (the translator's typed `Unsupported` `FramebufferFetch`, not implemented). That computed write is not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. xr-masked-bgr10xr-srgb-red-over llvmpipe refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-srgb-red-over RX 7900 XTX refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. xr-masked-bgr10xr-srgb-red-over 780M refused case/pipeline/second Err(Error::Translation("the translator made no pipeline: unsupported: Format; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: a blend into one of Apple's extended-range formats (Format) is not implemented on any device, as Metal's tile holds such an attachment as half through the render pass, which the codes the attachment stores do not keep. @@ -6012,40 +6010,23 @@ mesh-pipeline-reflection-object-stage * refused case/options-fail-on-binary-arch mesh-pipeline-reflection-object-stage * refused case/options-none Err(Unavailable({call: "mesh_pipeline_bindings"})) refused: no stream uses it yet (full selector census 11-19, m3-max-53207-53208, 53213, 53217-53221: 26 streams, no mesh pipeline, mesh draw or vertex amplification query). The rt side of the suite answers `mesh_pipeline_bindings` Unavailable: rt has no counterpart of the call, and no replay stream makes it. norm-storage-fields-bgr10a2unorm llvmpipe refused case/hsw_write/dispatch Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a BGR10A2Unorm texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatBGR10A2Unorm, so rt binds no such texture to a read_write or write slot. norm-storage-fields-bgr10a2unorm NVIDIA refused case/hsw_write/dispatch Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a BGR10A2Unorm texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatBGR10A2Unorm, so rt binds no such texture to a read_write or write slot. -padded-blend-r10x6-add-float llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-add-float UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-dual-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-dual-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-premul-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-premul-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-add-float llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-add-float UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-dual-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-dual-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-premul-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-r10x6-srgb-premul-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-add-float llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-add-float UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-dual-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-dual-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-premul-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-premul-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-premul-red-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-premul-red-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-add-float llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-add-float UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-dual-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-dual-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-premul-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rg10x12-srgb-premul-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-add-float llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-add-float UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-dual-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-dual-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-premul-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-premul-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-premul-rgb-half llvmpipe refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). -padded-blend-rgb10a2-srgb-premul-rgb-half UHD Graphics 630 refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs AnyOf([[Feature(RasterizationOrderColorAttachmentAccess)]]) at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch), a form built only over rasterization-order access to an input attachment; the runtime enables no rasterization-order access and binds no input attachment, so the form is not built on any device (rt README, Known gaps, the fetch bullet). +padded-blend-r10x6-add-float * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-r10x6-dual-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-r10x6-premul-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-r10x6-srgb-add-float * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-r10x6-srgb-dual-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-r10x6-srgb-premul-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-add-float * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-dual-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-premul-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-premul-red-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-srgb-add-float * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-srgb-dual-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rg10x12-srgb-premul-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rgb10a2-srgb-add-float * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba32float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rgb10a2-srgb-dual-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry xrb_dual_half, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rgb10a2-srgb-premul-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. +padded-blend-rgb10a2-srgb-premul-rgb-half * refused case/pipeline Err(Error::Translation("the translator made no pipeline: unsupported: FramebufferFetch; needs NotImplemented at metadata of entry rt6_fill_rgba16float, color attachment 0")) refused: no stream uses it yet (rt play-report census 11-19: 158 rt reports across the matrix streams, no render pipeline refused for framebuffer fetch). The translator refuses the pipeline: its fragment function computes the blend into a padded extended-range attachment over its own read of the attachment (FramebufferFetch, not implemented), a form not built on any device (rt README, Known gaps of pipeline states); it is built on the runtime's own fetch form when a guest meets it. pass-start-barrier-new-texture-chain Iris(R) Xe refused case/pieces/2-renderCommandEncoder Err(Error::Unsupported("a draw with AttachmentRead is not built")) rt's own gap, not the device's: the pass reads, at its own pixels, its target, a texture over a buffer, and where the device's linear image lies at the buffer's pitch that texture is a linear image on the buffer's memory (rule 3's form), which rt gives no attachment read, neither the feedback usage nor a shadow (texture.rs: only an image a texture's own plan makes takes them), so the draw is Gap::Draw (AttachmentRead). Expected from the code and the venues' pattern, not shown by a counter: the 32-texel targets (128-byte rows) refuse on lavapipe and the Iris Xe and are read on the Radeon 780M, the 896-texel one (3,584-byte rows) refuses on all three, and the RTX 3090 reads both (53452, 53559). pass-start-barrier-new-texture-chain llvmpipe refused case/pieces/2-renderCommandEncoder Err(Error::Unsupported("a draw with AttachmentRead is not built")) rt's own gap, not the device's: the pass reads, at its own pixels, its target, a texture over a buffer, and where the device's linear image lies at the buffer's pitch that texture is a linear image on the buffer's memory (rule 3's form), which rt gives no attachment read, neither the feedback usage nor a shadow (texture.rs: only an image a texture's own plan makes takes them), so the draw is Gap::Draw (AttachmentRead). Expected from the code and the venues' pattern, not shown by a counter: the 32-texel targets (128-byte rows) refuse on lavapipe and the Iris Xe and are read on the Radeon 780M, the 896-texel one (3,584-byte rows) refuses on all three, and the RTX 3090 reads both (53452, 53559). pass-start-barrier-new-texture-chain 780M refused case/pieces/2-renderCommandEncoder Err(Error::Unsupported("a draw with AttachmentRead is not built")) rt's own gap, not the device's: the pass reads, at its own pixels, its target, a texture over a buffer, and where the device's linear image lies at the buffer's pitch that texture is a linear image on the buffer's memory (rule 3's form), which rt gives no attachment read, neither the feedback usage nor a shadow (texture.rs: only an image a texture's own plan makes takes them), so the draw is Gap::Draw (AttachmentRead). Expected from the code and the venues' pattern, not shown by a counter: the 32-texel targets (128-byte rows) refuse on lavapipe and the Iris Xe and are read on the Radeon 780M, the 896-texel one (3,584-byte rows) refuses on all three, and the RTX 3090 reads both (53452, 53559). diff --git a/crates/metal2vulkan-conformance/src/cases/extended_range_blends.rs b/crates/metal2vulkan-conformance/src/cases/extended_range_blends.rs index 2658965ba..573d9ef9c 100644 --- a/crates/metal2vulkan-conformance/src/cases/extended_range_blends.rs +++ b/crates/metal2vulkan-conformance/src/cases/extended_range_blends.rs @@ -240,11 +240,6 @@ impl Case for ExtendedRangeBlend { // device that blends as Metal does shows as announced with nothing differing -- which is // what this M3 Max and lavapipe both show -- and one that does not shows the code. The // allowance fails the case if the notice stops firing, so it cannot outlive its reason. - // - // The function blends the `half4` fill into the extended-range target in the shader, in - // the device's arithmetic, so every row announces `extended-range-blend-source`, a native - // note the suite declares for every case (`crate::replay::NATIVE_NOTES`); the codes still - // compare exactly, and a site the device's arithmetic moves is a known gap. vec![crate::replay::notice_allowance( Degradation::HalfOutputFastMathBlend.code(), )] diff --git a/crates/metal2vulkan-conformance/src/cases/fetch_ordered.rs b/crates/metal2vulkan-conformance/src/cases/fetch_ordered.rs index dda7e5a6f..5b748bb4e 100644 --- a/crates/metal2vulkan-conformance/src/cases/fetch_ordered.rs +++ b/crates/metal2vulkan-conformance/src/cases/fetch_ordered.rs @@ -255,8 +255,8 @@ impl Case for FetchOrdered { // which is the owner's rule for this family: if Metal allows it we must allow it, so a // byte that differs is a bug and a refusal is a bug, and neither gets a tolerance here. // - // A venue with neither ordered fetch form (no rasterization-order attachment access, no - // pixel interlock) reads the input attachment ordered between draws alone and announces + // A venue without the pixel interlock reads the input attachment ordered between draws + // alone and announces // `unordered-fetch-within-draw`, a precision note of what it leaves unordered: overlapping // fragments of one draw. Each draw here is one fullscreen triangle, which overlaps itself // nowhere, so every byte still compares exactly. diff --git a/crates/metal2vulkan-conformance/src/cases/padded_blends.rs b/crates/metal2vulkan-conformance/src/cases/padded_blends.rs index e6e3c1ca3..74931f1ec 100644 --- a/crates/metal2vulkan-conformance/src/cases/padded_blends.rs +++ b/crates/metal2vulkan-conformance/src/cases/padded_blends.rs @@ -287,10 +287,7 @@ impl Case for PaddedBlend { fn allowances(&self) -> Vec { // Every stored word compares exactly. `rt6_samples` is a fast-math module, so a pipeline - // that blends its `half4` fill announces `half-output-fast-math-blend`. The blend in the - // device's arithmetic announces `extended-range-blend-source`, a native note the suite - // declares for every case (`crate::replay::NATIVE_NOTES`); a word the device's arithmetic - // moves is a known gap. + // that blends its `half4` fill announces `half-output-fast-math-blend`. let mut named = Vec::new(); if self.draw == Draw::PremulHalf { named.push(crate::replay::notice_allowance( diff --git a/crates/metal2vulkan-conformance/src/cases/padded_fetch.rs b/crates/metal2vulkan-conformance/src/cases/padded_fetch.rs index 0e8b35870..2e6295afd 100644 --- a/crates/metal2vulkan-conformance/src/cases/padded_fetch.rs +++ b/crates/metal2vulkan-conformance/src/cases/padded_fetch.rs @@ -3,8 +3,8 @@ //! //! `R10Unorm_X6`, `RG10Unorm_X12`, their `_sRGB` twins and `RGB10A2Unorm_sRGB` hold 10-bit //! normalized codes ([`super::padded_blends`]). No Vulkan format holds them, so the runtime renders -//! such a target as its raw unsigned words and a fetch reads the words over an ordered read of the -//! attachment (the pixel interlock or a rasterization-order input attachment), decoding each code +//! such a target as its raw unsigned words and a fetch reads the words over a read of the +//! attachment, decoding each code //! to its value rounded to `half`. Metal's fetch reads so for a loaded code, a `float4` input and a //! `half4` one alike (the M3 Max under macOS 27.0.1, `probes/padded_fetch.m`), and the missing //! lanes of a one- or two-channel format as `(0, 0, 1)`. After a clear, or an earlier draw of the diff --git a/crates/metal2vulkan-conformance/src/cases/rotated_targets.rs b/crates/metal2vulkan-conformance/src/cases/rotated_targets.rs index 64de3780e..2b83e2195 100644 --- a/crates/metal2vulkan-conformance/src/cases/rotated_targets.rs +++ b/crates/metal2vulkan-conformance/src/cases/rotated_targets.rs @@ -566,10 +566,10 @@ impl Case for RotatedTarget { /// /// Our runtime holds the format in an `R8G8B8A8_UNORM` image of the rotated bytes, so the image's /// alpha channel is Metal's blue. A colour factor that reads Metal's destination alpha would have -/// to read the image's *red*, and no Vulkan blend factor does. So the fragment function reads the -/// texel itself (framebuffer fetch, over a rasterization-order input attachment), rotates it into -/// Metal's order and computes Metal's 8-bit unorm blend. The runtime binds no input attachment, so -/// that form is not built and it refuses the pipeline on every device. Metal runs the draw. +/// to read the image's *red*, and no Vulkan blend factor does. So the fragment function would read +/// the texel itself (framebuffer fetch), rotate it into Metal's order and compute Metal's 8-bit +/// unorm blend. That form is not built, so the translator refuses the pipeline on every device. +/// Metal runs the draw. /// /// It is its own case so its route, and anything that route does differently, is one case's rows /// of the ledger rather than folded into the thirteen states. Metal's leg records normally: the diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 0099a05b1..95c3cf7af 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -113,10 +113,6 @@ pub enum Degradation { ArgumentPixelSamplerScaling, /// `metal2vulkan-degrade-half-output-precision`. HalfOutputPrecision, - /// `metal2vulkan-degrade-extended-range-blend-source`. - ExtendedRangeBlendSource, - /// `metal2vulkan-degrade-extended-range-float-blend-source`. - ExtendedRangeFloatBlendSource, /// `metal2vulkan-degrade-anisotropic-filter`. AnisotropicFilter, /// `metal2vulkan-degrade-device-anisotropic-filter`. @@ -235,8 +231,6 @@ impl Degradation { Degradation::LinkedSamplerNumbering, Degradation::ArgumentPixelSamplerScaling, Degradation::HalfOutputPrecision, - Degradation::ExtendedRangeBlendSource, - Degradation::ExtendedRangeFloatBlendSource, Degradation::AnisotropicFilter, Degradation::DeviceAnisotropicFilter, Degradation::DevicePointSize, @@ -348,12 +342,6 @@ impl Degradation { "metal2vulkan-degrade-argument-pixel-sampler-scaling" } Degradation::HalfOutputPrecision => "metal2vulkan-degrade-half-output-precision", - Degradation::ExtendedRangeBlendSource => { - "metal2vulkan-degrade-extended-range-blend-source" - } - Degradation::ExtendedRangeFloatBlendSource => { - "metal2vulkan-degrade-extended-range-float-blend-source" - } Degradation::AnisotropicFilter => "metal2vulkan-degrade-anisotropic-filter", Degradation::DeviceAnisotropicFilter => { "metal2vulkan-degrade-device-anisotropic-filter" @@ -451,10 +439,6 @@ impl Degradation { PrecisionNote::LinkedSamplerNumbering => Degradation::LinkedSamplerNumbering, PrecisionNote::ArgumentPixelSamplerScaling => Degradation::ArgumentPixelSamplerScaling, PrecisionNote::HalfOutputPrecision => Degradation::HalfOutputPrecision, - PrecisionNote::ExtendedRangeBlendSource => Degradation::ExtendedRangeBlendSource, - PrecisionNote::ExtendedRangeFloatBlendSource => { - Degradation::ExtendedRangeFloatBlendSource - } PrecisionNote::AnisotropicFilter => Degradation::AnisotropicFilter, PrecisionNote::DeviceAnisotropicFilter => Degradation::DeviceAnisotropicFilter, PrecisionNote::DevicePointSize => Degradation::DevicePointSize, diff --git a/crates/metal2vulkan-conformance/src/replay.rs b/crates/metal2vulkan-conformance/src/replay.rs index 10fda84ef..4aa780c80 100644 --- a/crates/metal2vulkan-conformance/src/replay.rs +++ b/crates/metal2vulkan-conformance/src/replay.rs @@ -463,10 +463,6 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool { /// - **sampling and filtering**: `device-sampling`, `device-sample-level`, the device's filter of a /// generated mipmap chain (`device-filtered-mipmaps`), and Vulkan's Y′CbCr model filtering a /// two-plane texture's planes read in place (`half-sample-filter`, `float-sample-filter`); -/// - **blending**: the device's arithmetic of the blend a function computes into an extended-range -/// attachment, whose raw codes no blend unit reads (`extended-range-blend-source`, -/// `extended-range-float-blend-source`: `S·Fs op D·Fd` in `float`, where Metal's compiler rounds -/// each step to `half`); /// - **logic operations**: the device's `logicOp` on a 10-bit or signed normalized format's own /// codes (`native-logic-operation`, where Metal operates on 10-bit codes widened to 16 bits, and /// reads and stores a signed lowest code as the code above it); @@ -525,8 +521,6 @@ pub const NATIVE_NOTES: &[crate::degradation::Degradation] = { D::DeviceFilteredMipmaps, D::HalfSampleFilter, D::FloatSampleFilter, - D::ExtendedRangeBlendSource, - D::ExtendedRangeFloatBlendSource, D::NativeLogicOperation, D::DeviceRoundedResolve, D::DeviceAlphaCoverage, diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 636e138f9..18dd69da5 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3794,20 +3794,27 @@ cache is answered compile-required on both. own draw that cover the same pixel, which Metal orders in primitive order: a fragment may read the texel from before an earlier fragment of its draw wrote it (`PrecisionNote::UnorderedFetchWithinDraw`). Exact for a draw whose primitives do not overlap at a - pixel. A write the translator computes over the function's own read of the attachment, where no - Vulkan blend or write mask gives Metal's, is not built: such a state is refused at creation on - every device, an `Error::Translation` naming `FramebufferFetch` and - `RasterizationOrderColorAttachmentAccess`. These are a padded extended-range attachment's blend, - and a write of some of the codes one word of such an attachment holds; a blend no Vulkan state - gives on an attachment whose image holds its channels rotated (`ARGB8Unorm` reading destination - alpha); a word attachment written under a mask of some of its channels; and a logic operation the - device lacks. The translator builds them only over a read ordered after every earlier fragment of - the pixel, rasterization-order access over an input attachment, and the runtime enables no - rasterization-order access and binds no input attachment. The runtime refused these states on - every device before too, worded otherwise (the conformance ledger's 22 such cases). A raster order - group on the colour it reads, or on a colour output of an attachment it reads, takes the same form - on every device, the pixel interlock's included: the interlock cannot order the attachment's own - write, which happens after the function. A fetch of an attachment the draw cannot read through is + pixel. A write the fragment function would compute over its own read of the attachment, where no + Vulkan blend, write mask or logic operation gives Metal's, is not built: the translator refuses + each such state at creation on every device, an `Error::Translation` (the conformance ledger's 22 + such rows). Each is built on the runtime's own fetch form, the attachment's pushed texture + (`PushField::FetchedColor`), if a guest meets it: + - a padded extended-range attachment's blend (`R10Unorm_X6`, `RG10Unorm_X12`, their `_sRGB` + twins and `RGB10A2Unorm_sRGB`), refused naming `FramebufferFetch`, not implemented; + - a write of some of the codes one word of an extended-range attachment holds (`BGR10_XR`, the + two-plane forms' colour word and their `_sRGB` twins, under a mask of some of those codes), + refused naming `FramebufferFetch`, not implemented; + - a blend no Vulkan state gives on an attachment whose image holds its channels rotated + (`ARGB8Unorm` reading destination alpha), refused naming `FramebufferFetch`, not implemented; + - a word attachment written under a mask of some of its channels, which takes its format's own + attachment and is refused where the device lacks that format; + - a logic operation on a device without `logicOp`, refused naming + `PrivateRenderState(LogicOperation)` and `logicOp`. + + A raster order group on the colour it reads, or on a colour output of an attachment it reads, + takes the same form on every device, the pixel interlock's included: the interlock cannot order + the attachment's own write, which happens after the function. A fetch of an attachment the draw + cannot read through is `Gap::Draw` of `FetchedAttachment`: a drawable's texture (its image has no feedback usage and no second element; no boot or replay stream fetched one), a texture made with no index, one that is no 2D texture at its first level and slice, a texture of an image another attachment of the pass @@ -4415,7 +4422,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `robustImageAccess2` | `VkPhysicalDeviceRobustness2FeaturesEXT` | an image read or fetch out of range, past the view's levels included, answering Metal's texel (zero, alpha 1 for a format without alpha), with no check in the shader; a texel buffer's read is still checked in the shader | | `independentBlend` | `VkPhysicalDeviceFeatures` | each color attachment of a render pipeline blended by its own state, as Metal's are | | `fragmentStoresAndAtomics` | `VkPhysicalDeviceFeatures` | a fragment function's writes and atomics on device memory | -| `logicOp` | `VkPhysicalDeviceFeatures` | a render pipeline's logic operation (private render state), the device's own; without it the fragment function would compute it, which is built only over raster-order attachment access, so the state is refused (Known gaps) | +| `logicOp` | `VkPhysicalDeviceFeatures` | a render pipeline's logic operation (private render state), the device's own; without it the state is refused (Known gaps of render encoders) | | `bresenhamLines` | `VkPhysicalDeviceLineRasterizationFeaturesEXT` | a line drawn by Metal's rule, the pixels whose diamond it exits (`VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT`), where Vulkan's default rule is the device's own: the rectangle of the line's width on a device whose `strictLines` is set (lavapipe, NVIDIA's driver); Vulkan 1.4 requires it | | `fullDrawIndexUint32` | `VkPhysicalDeviceFeatures` | an indexed draw's 32-bit indices past `2^24 - 1`; Vulkan 1.4 and Roadmap 2022 require it | | `imageCubeArray` | `VkPhysicalDeviceFeatures` | a cube array texture and a view as one, a cube array image view; Vulkan 1.4 and Roadmap 2022 require it | @@ -4758,7 +4765,6 @@ enables that the translator names. | Feature | Structure | Without it | |---|---|---| -| `rasterizationOrderColorAttachmentAccess` | `VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT` | a blend into an extended-range attachment, which the function would compute over its own read of the attachment, is refused (`FramebufferFetch`) | | `robustBufferAccess` | `VkPhysicalDeviceFeatures` | a buffer is reached by its device address, and an access through a descriptor view is checked in the shader | | `computeDerivativeGroupLinear` | `VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR` | a derivative in a kernel is refused (`ComputeDerivatives`) | | `descriptorBindingStorageBufferUpdateAfterBind` | `VkPhysicalDeviceVulkan12Features` | the translator's function table is a directory and a snapshot, never a heap array of storage buffers; the runtime supplies no function table (Known gaps of pipeline states) | diff --git a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs index 8a68d656b..2e1a354a7 100644 --- a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs +++ b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs @@ -48,10 +48,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[ ("rasterizer_discard", Applied), ("dynamic_states", Applied), ("input_attachments", Refused(SET_0)), - ( - "rasterization_order_attachment_access", - Refused("set only beside input attachments, a set-0 binding draws() refuses"), - ), ( "max_vertex_amplification_count", Refused("refuse() refuses the descriptor's count other than 1"), diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index 136a06aee..c360ead7f 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -142,7 +142,6 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/lower/arith/narrow.rs", packed), ("metal2vulkan/src/lower/arith/ops.rs", "the constant and type emission (`splat`, `ty`, `elem_ty`, `ones`) every compiled pipeline's arithmetic is made through; the runtime's exact division makes its constants with it, so a change to what it emits is a translation change (SEMANTICS_VERSION) that moves the artifact digests"), ("metal2vulkan/src/lower/emit.rs", compile), - ("metal2vulkan/src/lower/fragment/mod.rs", "the fragment lowering's module root: the runtime reaches it only through metal/format's `extended_range_blend`, which answers from the device profile alone whether a render pipeline blends an extended-range attachment, as the compile decides it; what the compile makes of it is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/mesh/mod.rs", "compile-time translation, reached only from the compile-time part of lower/dispatch.rs (plan_kernel's mesh wrapper builtins) and as the parent of its work-buffer layout (lower/mesh/work.rs, an input); what it produces is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/push.rs", "the push window's lowering, reached only from device/derive.rs, which reads `FLOOR_BYTES`, the window's 256 bytes every stage is lowered for, to refuse a description whose maxPushConstantsSize is below it before any pipeline exists; what the lowering makes of the window is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/select.rs", compile), diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs index 5094c0910..abd517912 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs @@ -247,12 +247,10 @@ fn a_stencil_output_case_plans_through_stencil_export() { } /// A fragment case that reads its color attachment maps like any fragment case (its render target -/// is the attachment it reads; no requirement stops the engine's candidate) and plans on -/// lavapipe, whose `rasterizationOrderColorAttachmentAccess` orders the read: the plan reads color -/// attachment 0 through an input-attachment write, and the pipeline states rasterization-order -/// access and requires the feature. On moltenvk-m3, which lacks the feature, it plans the input -/// attachment with no rasterization-order access, which the consumer orders between draws alone -/// (its barriers, `platform::graphics_pipeline::fetch_between_draws`), the fragment stage noting +/// is the attachment it reads; no requirement stops the engine's candidate) and plans, on lavapipe +/// (which has `rasterizationOrderColorAttachmentAccess`) and on moltenvk-m3 alike, color attachment +/// 0 read through an input-attachment write, which the consumer orders between draws alone (its +/// barriers, `platform::graphics_pipeline::fetch_between_draws`), the fragment stage noting /// `PrecisionNote::UnorderedFetchWithinDraw`, and requires no ordered form. #[test] fn a_framebuffer_fetch_case_plans_its_ordered_input_attachment() { @@ -280,8 +278,8 @@ fn a_framebuffer_fetch_case_plans_its_ordered_input_attachment() { }; let (pipeline, plan, _) = planned_draw(&device("lavapipe"), &render, libraries).unwrap(); assert_eq!(pipeline.graphics.input_attachments.len(), 1); - assert!(pipeline.graphics.rasterization_order_attachment_access); - assert!(pipeline + assert!(unordered_within_draw(&pipeline)); + assert!(!pipeline .requirements .features .contains(&VkFeature::RasterizationOrderColorAttachmentAccess)); @@ -298,7 +296,6 @@ fn a_framebuffer_fetch_case_plans_its_ordered_input_attachment() { .map(|input| input.color_index) .collect(); assert_eq!(read, [0]); - assert!(!pipeline.graphics.rasterization_order_attachment_access); assert!(pipeline.graphics.color_attachments[0].is_some()); assert!(!pipeline .requirements @@ -1581,29 +1578,9 @@ fn public_tessellation_cases_plan_their_patch_draws() { ); } -/// The committed profiles whose descriptions lack `rasterizationOrderColorAttachmentAccess`: the -/// devices that order a fetch between draws alone, read from what each states rather than from its -/// name. -fn unordered_profiles() -> Vec { - use metal2vulkan::device::VkFeature; - let stems = crate::engine::committed_profiles().unwrap(); - let stems = stems - .into_iter() - .filter(|stem| { - let description = crate::engine::load_description(stem).unwrap(); - !description.has(VkFeature::RasterizationOrderColorAttachmentAccess) - }) - .collect::>(); - assert!( - !stems.is_empty(), - "a committed profile orders fetch between draws alone" - ); - stems -} - /// Every installed public framebuffer-fetch case maps onto its fullscreen triangle drawn as its /// instances, with each read render target attached, and plans on lavapipe (one input-attachment -/// write per color input, rasterization-order access, the feature required). Every case carries +/// write per color input, ordered between draws alone, noted). Every case carries /// no requirement, at least one of them drawing more than one instance (overlapping fragments). /// The lavapipe pipeline masks every write to a color attachment the function reads but has no /// output for, which at least one case does. A case of a multisampled pass, which at least one @@ -1688,7 +1665,6 @@ fn public_framebuffer_fetch_cases_plan_their_ordered_input_attachments() { assert_eq!(g.rasterization_samples.as_raw(), samples, "{}", case.name); let required = &pipeline.requirements; assert!(required.features.contains(&VkFeature::SampleRateShading)); - assert!(g.rasterization_order_attachment_access); let mut fetched: Vec = g.input_attachments.iter().map(|a| a.color_index).collect(); fetched.sort_unstable(); @@ -1710,15 +1686,7 @@ fn public_framebuffer_fetch_cases_plan_their_ordered_input_attachments() { } let (pipeline, plan, commands) = planned_draw(&device("lavapipe"), &render, libraries) .unwrap_or_else(|error| panic!("lavapipe {}: {error}", case.name)); - assert!( - pipeline.graphics.rasterization_order_attachment_access, - "{}", - case.name - ); - assert!(pipeline - .requirements - .features - .contains(&VkFeature::RasterizationOrderColorAttachmentAccess)); + assert!(unordered_within_draw(&pipeline), "{}", case.name); // A color attachment the fragment function reads but has no output for keeps its // contents, as Metal kept it in case f39cf462: the pipeline the executor builds from // the artifact masks every write to it, and keeps the descriptor's mask on the others. @@ -1785,10 +1753,8 @@ fn public_framebuffer_fetch_cases_plan_their_ordered_input_attachments() { ); } -/// On every committed profile without rasterization-order color attachment access -/// ([`unordered_profiles`]), every installed public framebuffer-fetch case plans its color inputs -/// as input attachments with no -/// rasterization-order access, which the consumer orders between draws alone, and its fragment +/// On every committed profile, every installed public framebuffer-fetch case plans its color +/// inputs as input attachments, which the consumer orders between draws alone, and its fragment /// stage notes `PrecisionNote::UnorderedFetchWithinDraw`; or, a multisampled pass, is refused as on /// every device (the coverage read beside it, or a sample count the attachments lack), or for the /// sample-rate shading each invocation's read of its own sample needs, where the device lacks it. @@ -1798,9 +1764,9 @@ fn public_framebuffer_fetch_cases_plan_input_attachments_without_an_ordered_form let root = metal2vulkan_devtools::validation_dir().join("corpus"); let store = CorpusStore::new(&root); let sources = public_sources().unwrap(); - for stem in unordered_profiles() { + for stem in crate::engine::committed_profiles().unwrap() { let stem = stem.as_str(); - let unordered = device(stem); + let dev = device(stem); let mut fetches = 0; for shard in 0..64 { for case in store.read_case_shard(shard).unwrap() { @@ -1849,7 +1815,7 @@ fn public_framebuffer_fetch_cases_plan_input_attachments_without_an_ordered_form vertex: &companion, fragment: Some(&bitcode), }; - let pipeline = match planned_draw(&unordered, &render, libraries) { + let pipeline = match planned_draw(&dev, &render, libraries) { Ok((pipeline, _, _)) => pipeline, // A multisampled pass's refusals of every device's form (the lavapipe // test's), and its fetch on a device without sample-rate shading, which each @@ -1881,11 +1847,6 @@ fn public_framebuffer_fetch_cases_plan_input_attachments_without_an_ordered_form let mut colors = colors; colors.sort_unstable(); assert_eq!(read, colors, "{stem} {}", case.name); - assert!( - !pipeline.graphics.rasterization_order_attachment_access, - "{stem} {}", - case.name - ); assert!(unordered_within_draw(&pipeline), "{stem} {}", case.name); } } diff --git a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs index c4d2d981a..a997e4c0e 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs @@ -5,10 +5,9 @@ //! Everything comes from the artifact's graphics state and vertex input: the render pass //! ([`create_render_pass`]: every color attachment at its Metal index, each framebuffer-fetch //! input as an input attachment of its color attachment with the by-region self-dependency the -//! contract names, rasterization-order color access where the artifact states it, and the -//! depth/stencil attachment), the vertex input (static strides, and zero for a stride the pipeline -//! makes dynamic state; instance divisors through the divisor state), the multisample, blend -//! (rasterization-order access with the subpass's), and dynamic states. The caller supplies what the artifact leaves to the +//! contract names, and the depth/stencil attachment), the vertex input (static strides, and zero +//! for a stride the pipeline makes dynamic state; instance divisors through the divisor state), +//! the multisample, blend and dynamic states. The caller supplies what the artifact leaves to the //! consumer: each stage's specialization, the draw's topology within the compiled class with the //! primitive restart Metal applies to it, and the depth-stencil state and front face (Metal's //! `MTLDepthStencilState` and front-facing winding, which are encoder state, not pipeline state). @@ -137,11 +136,8 @@ pub(super) fn has_depth(format: vk::Format) -> bool { /// attachment a framebuffer-fetch input also reads, as the input attachment of the same index, /// with the by-region self-dependency of [`FETCH_SELF_DEPENDENCY`]), then the depth/stencil /// attachment ([`depth_stencil_format`]) in `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`. -/// The subpass has rasterization-order color access when the artifact states it -/// (`GraphicsState::rasterization_order_attachment_access`), so each fetch sees the earlier -/// fragments of the draw that cover its pixel, as in Metal; where it does not, each draw records -/// after a barrier of that dependency ([`fetch_between_draws`]). Every attachment is loaded before and -/// stored after the subpass. The framebuffer's views are the present color attachments in index +/// A subpass that reads input attachments records each draw after a barrier of that dependency +/// ([`fetch_between_draws`]). Every attachment is loaded before and stored after the subpass. The framebuffer's views are the present color attachments in index /// order, then the depth/stencil one. pub(super) fn create_render_pass( device: &ash::Device, @@ -252,7 +248,6 @@ pub(super) fn create_render_pass( .layout(vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL) }); let mut subpass = vk::SubpassDescription::default() - .flags(subpass_flags(graphics)) .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) .color_attachments(&colors) .input_attachments(&inputs); @@ -300,15 +295,14 @@ pub(super) const FETCH_SELF_DEPENDENCY: (vk::PipelineStageFlags, vk::AccessFlags ), ); -/// Whether `graphics` reads input attachments ordered between draws alone: on a device without -/// rasterization-order color attachment access, which states none -/// (`GraphicsState::rasterization_order_attachment_access`). The +/// Whether `graphics` reads input attachments, which are ordered between draws alone on every +/// device (`PrecisionNote::UnorderedFetchWithinDraw`). The /// contract has the consumer order each draw of it after the color writes of the draws before, /// and each draw that writes a color after their reads, by a barrier of the subpass's dependency /// on itself; the executor records one before each of its draws ([`fetch_between_draws`]), after /// the load operations too, as the runtime does. pub(super) fn fetches_between_draws(graphics: &GraphicsState) -> bool { - !graphics.input_attachments.is_empty() && !graphics.rasterization_order_attachment_access + !graphics.input_attachments.is_empty() } /// Record, into `command`, inside a render pass of [`create_render_pass`] whose subpass reads @@ -337,26 +331,6 @@ pub(super) unsafe fn fetch_between_draws(device: &ash::Device, command: vk::Comm } } -/// The subpass flags of `graphics`: rasterization-order color access where it states it. -pub(super) fn subpass_flags(graphics: &GraphicsState) -> vk::SubpassDescriptionFlags { - if graphics.rasterization_order_attachment_access { - vk::SubpassDescriptionFlags::RASTERIZATION_ORDER_ATTACHMENT_COLOR_ACCESS_EXT - } else { - vk::SubpassDescriptionFlags::empty() - } -} - -/// The color blend state flags of `graphics`, matching its subpass's ([`subpass_flags`]). -pub(super) fn color_blend_flags( - graphics: &GraphicsState, -) -> vk::PipelineColorBlendStateCreateFlags { - if graphics.rasterization_order_attachment_access { - vk::PipelineColorBlendStateCreateFlags::RASTERIZATION_ORDER_ATTACHMENT_ACCESS_EXT - } else { - vk::PipelineColorBlendStateCreateFlags::empty() - } -} - /// One stage's specialization: its map entries and packed data. pub(super) type Specialization = (Vec, Vec); @@ -586,9 +560,7 @@ pub(super) fn create_graphics_pipeline( } }) .collect(); - let blend = vk::PipelineColorBlendStateCreateInfo::default() - .flags(color_blend_flags(graphics)) - .attachments(&blends); + let blend = vk::PipelineColorBlendStateCreateInfo::default().attachments(&blends); let dynamic_state = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic); // A tessellation pipeline's patches are its control points. let tessellation = graphics.tessellation.map(|t| { diff --git a/crates/metal2vulkan-validation/src/candidate/platform/render.rs b/crates/metal2vulkan-validation/src/candidate/platform/render.rs index 5f6f4d95b..b16268508 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/render.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/render.rs @@ -28,10 +28,9 @@ //! - a color attachment the fragment function reads (framebuffer fetch) is also the input //! attachment of its index: loaded with its authored contents as Metal's `MTLLoadActionLoad` //! loads it, kept in `GENERAL` through the subpass, read through the plan's input-attachment -//! write, with the render pass's by-region self-dependency and, where the artifact states it, -//! rasterization-order color access, so each fetch sees the earlier fragments of the draw that -//! cover its pixel, as in Metal (in a multisampled pass the attachment of the pass's samples, -//! which a function running once per sample reads at its own sample); +//! write, with the render pass's by-region self-dependency and a barrier of it before each draw, +//! so each fetch sees the earlier draws' writes (in a multisampled pass the attachment of the +//! pass's samples, which a function running once per sample reads at its own sample); //! - a patch draw binds its factor buffer where the plan's `WriteSource::TessellationFactors` names //! it, over the draw's range, and draws a patch list: the tessellation pipeline's synthesized //! vertex and control stages bind nothing of Metal's, and its evaluation stage binds the vertex diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs index 4904aa163..61d4cc1da 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs @@ -806,9 +806,7 @@ fn a_back_culled_patch_and_its_mirror_leave_exactly_one_drawn() { /// Framebuffer fetch: `fetch_scalar` writes half of the color it reads, its attachment loaded with /// the authored contents, and the fullscreen triangle drawn as `n` instances covers every pixel `n` -/// times in order, so under rasterization-order access each instance reads what the one before it -/// wrote and the attachment ends at `2^-n` of its contents. A device without that access reads it -/// as an input attachment with no rasterization-order access, after a barrier between draws +/// times. Every device reads it as an input attachment, after a barrier between draws /// (`platform::graphics_pipeline::fetch_between_draws`), and its fragment module notes /// `PrecisionNote::UnorderedFetchWithinDraw`: one instance halves the attachment exactly, and /// three, one draw, leave each texel some order's `2^-k` of its contents, `k` in 1 to 3. diff --git a/crates/metal2vulkan-validation/tests/integration/pipeline_selection.rs b/crates/metal2vulkan-validation/tests/integration/pipeline_selection.rs index b6f1733b6..9a9e3662d 100644 --- a/crates/metal2vulkan-validation/tests/integration/pipeline_selection.rs +++ b/crates/metal2vulkan-validation/tests/integration/pipeline_selection.rs @@ -68,9 +68,8 @@ fn engine_selection_reads_only_the_selected_row_and_names_its_engine() { } } -/// A fragment function that fetches its color attachment compiles on a profile with no ordered -/// form of the fetch (neither rasterization-order attachment access nor the pixel interlock): -/// through input attachments the consumer orders between draws alone, its row naming +/// A fragment function that fetches its color attachment compiles on a profile without the pixel +/// interlock: through input attachments the consumer orders between draws alone, its row naming /// `PrecisionNote::UnorderedFetchWithinDraw`. #[test] fn a_fetch_without_an_ordered_form_compiles_noted() { diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 68a6df323..58cb43680 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -52,9 +52,7 @@ use crate::pipeline::interface::{ use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, }; -use crate::pipeline::lower_inputs::{ - BlendEquation, ChannelWrite, ExtendedRangeColor, FactorLane, VertexFetch, -}; +use crate::pipeline::lower_inputs::{ChannelWrite, ExtendedRangeColor, FactorLane, VertexFetch}; use crate::pipeline::stage_io::{ CoverageLoop, CoverageLoopRefusal, DepthCompares, DepthMode, Interpolation as IoInterpolation, IoNumeric, IoRole, IoType, IoVariable, PulledInput, Sampling as IoSampling, StageBuiltin, @@ -823,13 +821,6 @@ codec_struct! { // ---- Link symbols (`pipeline::sym`) ---- -codec_struct! { - BlendEquation { - source_rgb, destination_rgb, rgb_operation, source_alpha, destination_alpha, - alpha_operation, - } -} - codec_struct! { SlotRef { stage, class, index } ImageHandleClass { dim, arrayed, multisampled, sampled_type, depth_compare, access, format } @@ -1148,7 +1139,6 @@ codec_struct! { texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes, half_blend_colors, half_fast_colors, float_blend_colors, zero_indices, word_colors, alpha_in_red_colors, alpha_test, depth_compares, - logic_operation, } DepthCompares { samplers, clamped } WordField { shift, bits } @@ -1259,8 +1249,6 @@ codec_enum! { CubicSampler { slot }, CubicArgumentSampler { stage }, HeapRawSamples { stage, sampler }, - ExtendedRangeInputBlend { color, blend, kept }, - WordInputMerge { color, kept }, CrossClassReads { slot }, StorageTextureWriteRounding { slot, halves }, HeapWriteRounding { stage, halves }, @@ -1275,7 +1263,6 @@ codec_enum! { PrivateList, YCbCrInPlace { slot, samplers, device }, PartialObjectThreadgroups, - RotatedInputBlend { color, blend, kept }, BorderTexels { slot }, RegionViewports, PartialThreadgroups, @@ -1372,7 +1359,7 @@ codec_struct! { GraphicsState { topology, color_attachments, depth_format, stencil_format, rasterization_samples, alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states, input_attachments, - rasterization_order_attachment_access, max_vertex_amplification_count, declares_layer, + max_vertex_amplification_count, declares_layer, tessellation, vertex_writes_memory, writes_viewport_index, writes_point_size, writes_depth, reads_barycentric_coord, reads_primitive_id, fragment_writes_memory, color_outputs, sample_mask, logic_op, line_band, @@ -1424,8 +1411,6 @@ codec_enum! { LinkedSamplerNumbering, ArgumentPixelSamplerScaling, HalfOutputPrecision, - ExtendedRangeBlendSource, - ExtendedRangeFloatBlendSource, AnisotropicFilter, DeviceAnisotropicFilter, DevicePointSize, diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index df6d32521..493b0b958 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -275,7 +275,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel output_layer: has(VkFeature::ShaderOutputLayer), output_viewport_index: has(VkFeature::ShaderOutputViewportIndex), clip_distance: has(VkFeature::ShaderClipDistance), - rasterization_order_color_access: has(VkFeature::RasterizationOrderColorAttachmentAccess), vertex_attribute_divisor: has(VkFeature::VertexAttributeInstanceRateDivisor), }; diff --git a/crates/metal2vulkan/src/device/enables.rs b/crates/metal2vulkan/src/device/enables.rs index fd6b1f989..66361d6a5 100644 --- a/crates/metal2vulkan/src/device/enables.rs +++ b/crates/metal2vulkan/src/device/enables.rs @@ -338,7 +338,6 @@ fn facts(ext: VkExtension) -> ExtensionFacts { E::ExtRobustness2 | E::ExtShaderStencilExport | E::ExtFragmentShaderInterlock - | E::ExtRasterizationOrderAttachmentAccess | E::KhrShaderMaximalReconvergence | E::KhrShaderSubgroupUniformControlFlow | E::KhrFragmentShaderBarycentric @@ -405,6 +404,9 @@ fn facts(ext: VkExtension) -> ExtensionFacts { E::ExtShaderImageAtomicInt64 => fact(false, None, &[]), // Described, never enabled: the core reads none of its properties. E::ExtSampleLocations => fact(false, None, &[]), + // Described, never enabled: a framebuffer fetch is ordered between draws alone on every + // device (`lower::fragment::fetch`), so the core reads none of its features. + E::ExtRasterizationOrderAttachmentAccess => fact(false, None, &[]), E::KhrDynamicRendering => fact(false, Some(3), &[]), // Object and mesh functions. `VK_KHR_spirv_1_4` is core at the 1.2 floor. E::ExtMeshShader => fact(true, None, &[]), diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 809d0781f..264f3afa9 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -213,15 +213,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The planner refuses a texture a heap holds by its raw texels alone that a plan names // beside the stage; a consumer's own heap announces one. RuntimeFact::HeapRawSamples { .. } => Mechanism::PlanTimeCheck, - // Link gives the attachment no Vulkan blend and its input attachment, which the consumer - // binds as `GraphicsState::input_attachments` states. - RuntimeFact::ExtendedRangeInputBlend { .. } => Mechanism::RenderPassContract, - // Link gives the rotated attachment no Vulkan blend and its input attachment, which the - // consumer binds as `GraphicsState::input_attachments` states. - RuntimeFact::RotatedInputBlend { .. } => Mechanism::RenderPassContract, - // Link writes the whole word and gives the attachment its input attachment, which the - // consumer binds as `GraphicsState::input_attachments` states. - RuntimeFact::WordInputMerge { .. } => Mechanism::RenderPassContract, // Keyed by the slots bound in a format of another numeric class than the declared one, // whose texels the function reads in that class. RuntimeFact::CrossClassReads { .. } => Mechanism::Variant, diff --git a/crates/metal2vulkan/src/device/metal.rs b/crates/metal2vulkan/src/device/metal.rs index 685306726..8db1bffae 100644 --- a/crates/metal2vulkan/src/device/metal.rs +++ b/crates/metal2vulkan/src/device/metal.rs @@ -261,8 +261,8 @@ fn unsupported_features(profile: &DeviceProfile) -> Vec { vec![vec![feature(VkFeature::FragmentShaderPixelInterlock)]], )); } - // Framebuffer fetch refuses on no device: ordered by rasterization-order access, or without - // it through input attachments ordered between draws (`PrecisionNote::UnorderedFetchWithinDraw`). + // Framebuffer fetch refuses on no device: input attachments ordered between draws + // (`PrecisionNote::UnorderedFetchWithinDraw`). // `[[barycentric_coord]]`: the device's builtins. if !f.fragment.barycentric { out.push(Unsupported::needs( diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index bb7f0165c..96608298c 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -562,7 +562,7 @@ pub struct DescriptorCaps { /// Fragment-stage and fixed-function capabilities ([`DeviceProfile::fragment`]). Each field is the /// Vulkan feature or extension of that name (`shaderStencilExport` for `stencil_export`, -/// `rasterizationOrderColorAttachmentAccess` for `rasterization_order_color_access`, ...), enabled. +/// `shaderClipDistance` for `clip_distance`, ...), enabled. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct FragmentCaps { @@ -578,7 +578,6 @@ pub struct FragmentCaps { pub output_layer: bool, pub output_viewport_index: bool, pub clip_distance: bool, - pub rasterization_order_color_access: bool, pub vertex_attribute_divisor: bool, } diff --git a/crates/metal2vulkan/src/device/tests/description.rs b/crates/metal2vulkan/src/device/tests/description.rs index d66c61d42..883cf9df7 100644 --- a/crates/metal2vulkan/src/device/tests/description.rs +++ b/crates/metal2vulkan/src/device/tests/description.rs @@ -219,8 +219,7 @@ fn rgba4_opaque_black_swizzled_follows_exposure() { /// A device that exposes only the ARM spelling of rasterization-order attachment access has the /// same feature as one exposing the EXT spelling: the extension and its feature structure map to -/// one vocabulary entry, so its fragments read their color attachments in rasterization order -/// and the ordered fetch is enabled. +/// one vocabulary entry. #[test] fn the_arm_spelling_of_rasterization_order_access_is_the_ext_one() { use crate::device::requirements::VkExtension; @@ -234,21 +233,11 @@ fn the_arm_spelling_of_rasterization_order_access_is_the_ext_one() { "features": {{{feature}}}}}"# ), ); - let mut d = DeviceDescription::from_khronos_json(&arm, None).unwrap(); + let d = DeviceDescription::from_khronos_json(&arm, None).unwrap(); assert!(d .extensions .contains(&VkExtension::ExtRasterizationOrderAttachmentAccess)); assert!(d.has(VkFeature::RasterizationOrderColorAttachmentAccess)); - // The push window the floor needs, which a Vulkan 1.2 document leaves at 128. - d.limits.max_push_constants_size = 256; - let dev = crate::device::Device::from_queries(d, crate::device::DevicePolicy::RESIDENT_TABLES) - .unwrap(); - assert!( - dev.profile() - .fields() - .fragment - .rasterization_order_color_access - ); // The structure without its extension is not exposed. let bare = doc( "1.2.0", diff --git a/crates/metal2vulkan/src/device/tests/enables.rs b/crates/metal2vulkan/src/device/tests/enables.rs index 92397deb4..940c83b22 100644 --- a/crates/metal2vulkan/src/device/tests/enables.rs +++ b/crates/metal2vulkan/src/device/tests/enables.rs @@ -87,12 +87,16 @@ fn recommendations_are_closed_fixed_points_on_every_committed_profile() { VkFeature::ShaderFmaFloat32, VkFeature::ShaderFloat8, VkFeature::ShaderImageInt64Atomics, + VkFeature::RasterizationOrderColorAttachmentAccess, + VkFeature::RasterizationOrderDepthAttachmentAccess, + VkFeature::RasterizationOrderStencilAttachmentAccess, ]; for e in [ VkExtension::ExtDepthBiasControl, VkExtension::KhrShaderFma, VkExtension::ExtShaderFloat8, VkExtension::ExtShaderImageAtomicInt64, + VkExtension::ExtRasterizationOrderAttachmentAccess, ] { assert!(!rec.extensions.contains(&e), "{stem}: {e:?}"); } diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index d502ad828..73fb3fa99 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -169,33 +169,6 @@ fn every_fact() -> Vec { stage: Stage::Fragment, sampler: Some(1), }, - RuntimeFact::ExtendedRangeInputBlend { - color: 0, - blend: { - let mut c = crate::pipeline::ColorAttachmentDescriptor::new( - crate::metal::PixelFormat::BGRA10XR, - ); - c.blending_enabled = true; - crate::pipeline::lower_inputs::BlendEquation::of(&c).expect("a blend") - }, - kept: crate::vk::ColorComponentFlags::empty(), - }, - RuntimeFact::RotatedInputBlend { - color: 0, - blend: { - let mut c = crate::pipeline::ColorAttachmentDescriptor::new( - crate::metal::PixelFormat::ARGB8Unorm, - ); - c.blending_enabled = true; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::DestinationAlpha; - crate::pipeline::lower_inputs::BlendEquation::of(&c).expect("a blend") - }, - kept: crate::vk::ColorComponentFlags::empty(), - }, - RuntimeFact::WordInputMerge { - color: 1, - kept: crate::vk::ColorComponentFlags::G, - }, RuntimeFact::CrossClassReads { slot }, RuntimeFact::StorageTextureWriteRounding { slot, halves: true }, RuntimeFact::HeapWriteRounding { @@ -315,7 +288,6 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::CubicSampler { .. } => 63, RuntimeFact::CubicArgumentSampler { .. } => 64, RuntimeFact::HeapRawSamples { .. } => 68, - RuntimeFact::ExtendedRangeInputBlend { .. } => 70, RuntimeFact::CrossClassReads { .. } => 71, RuntimeFact::StorageTextureWriteRounding { .. } => 72, RuntimeFact::HeapWriteRounding { .. } => 73, @@ -323,7 +295,6 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::AnisotropicSampler { .. } => 75, RuntimeFact::StorageTextureIntegerChannels { .. } => 76, RuntimeFact::ObjectThreadgroupArena { .. } => 79, - RuntimeFact::WordInputMerge { .. } => 81, RuntimeFact::ReplayBindings => 82, RuntimeFact::MergedDraws => 67, RuntimeFact::QuadPrimitiveIds => 54, @@ -331,22 +302,21 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::PrivateList => 80, RuntimeFact::YCbCrInPlace { .. } => 60, RuntimeFact::PartialObjectThreadgroups => 83, - RuntimeFact::RotatedInputBlend { .. } => 84, RuntimeFact::OpenClMode => 85, RuntimeFact::RowLockstep => 86, RuntimeFact::BorderTexels { .. } => 87, RuntimeFact::HeapResidency { .. } => 88, RuntimeFact::OneRow => 89, RuntimeFact::RegionViewports => 90, - RuntimeFact::CallThreadgroups => 91, - RuntimeFact::PartialThreadgroups => 92, + RuntimeFact::CallThreadgroups => 84, + RuntimeFact::PartialThreadgroups => 81, RuntimeFact::TexelRows { .. } => 78, RuntimeFact::UnitAxes { .. } => 53, RuntimeFact::TexelBufferParts { .. } => 65, RuntimeFact::OpenClLineTexture { .. } => 69, RuntimeFact::AddressAlignment { .. } => 66, RuntimeFact::GridTiles => 51, - RuntimeFact::PrivateArena { .. } => 93, + RuntimeFact::PrivateArena { .. } => 70, } } @@ -354,7 +324,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..94).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..91).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -467,11 +437,9 @@ fn mechanism_is_total_over_every_fact_and_profile() { _ => Mechanism::PlanTimeCheck, } } - RuntimeFact::FramebufferFetch { .. } - | RuntimeFact::TileImageblock { .. } - | RuntimeFact::ExtendedRangeInputBlend { .. } - | RuntimeFact::RotatedInputBlend { .. } - | RuntimeFact::WordInputMerge { .. } => Mechanism::RenderPassContract, + RuntimeFact::FramebufferFetch { .. } | RuntimeFact::TileImageblock { .. } => { + Mechanism::RenderPassContract + } RuntimeFact::ExecutionStatus => match f.buffer_access { crate::device::profile::BufferAccess::Addressed => Mechanism::PushConstant, _ => Mechanism::SyntheticBinding, diff --git a/crates/metal2vulkan/src/device/tests/subgroup.rs b/crates/metal2vulkan/src/device/tests/subgroup.rs index 23e709273..379f0d46c 100644 --- a/crates/metal2vulkan/src/device/tests/subgroup.rs +++ b/crates/metal2vulkan/src/device/tests/subgroup.rs @@ -530,10 +530,9 @@ fn metal_properties_report_d3_d4_values() { assert!(!has(&Feature::Int64Arithmetic)); assert!(!has(&Feature::ArgumentBufferPointers)); assert!(has(&Feature::RasterOrderGroups)); - // Neither rasterization-order access nor the pixel interlock: framebuffer fetch reads input - // attachments ordered between draws, a note, not a refusal. - let fragment = floor.profile().fields().fragment; - assert!(!fragment.rasterization_order_color_access && !fragment.pixel_interlock); + // No pixel interlock: framebuffer fetch reads input attachments ordered between draws, a + // note, not a refusal. + assert!(!floor.profile().fields().fragment.pixel_interlock); assert!(!has(&Feature::FramebufferFetch)); let nv = device("nvidia-rtx50-linux"); let m = nv.metal_properties(); diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 791cc3ba9..89ff6f7db 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -635,8 +635,9 @@ pub enum Feature { // ---- Stages and fragment (lowering B7, B9) ---- /// Raster order groups without fragment shader interlock. RasterOrderGroups, - /// Framebuffer fetch that needs an ordered read the device lacks (rasterization-order - /// attachment access), or in a shape not implemented. + /// Framebuffer fetch in a shape not implemented (a write the function would compute over its + /// own read of the attachment), or that needs a feature the device lacks (sample-rate shading + /// for a multisampled pass's read). FramebufferFetch, /// `[[primitive_id]]` in a fragment function: behind a mesh function on a device without /// geometry or tessellation shaders, whose fragment stage reads it from a varying no mesh @@ -880,10 +881,6 @@ pub enum Feature { /// Metal's) set to a value whose effect the translation has not built: the property it names /// ([`PrivateRenderField`]). Metal's answer for each was measured; building it is open work. PrivateRenderState(PrivateRenderField), - /// A blend the function computes in the shader, into an extended-range attachment - /// (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), of the part it names - /// ([`ExtendedRangeBlend`]). - ExtendedRangeBlend(ExtendedRangeBlend), /// A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p /// [[buffer(n)]];` in Apple's `!air.global_bindings` list, valid AIR this version does not /// implement yet. @@ -908,22 +905,6 @@ pub enum Feature { WideLines, } -/// The part of a blend the shader computes that [`Feature::ExtendedRangeBlend`] refuses. An -/// extended-range attachment's blend, which the shader computes by the device's arithmetic, is -/// built for every factor, operation and write mask, and refuses only [`Output`](Self::Output); -/// Metal's blend the shader computes refuses [`DualSource`](Self::DualSource) under fast math. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum ExtendedRangeBlend { - /// Under fast math, a factor of the second source (`Source1Color`, `Source1Alpha` and their - /// one-minus forms): Metal's blend is not built. (A function that writes no second output to - /// the attachment Metal refuses: [`DescriptorError::ColorAttachment`].) - DualSource, - /// An output other than four `half` or `float` lanes, or a second output other than those the - /// blend reads: not built. - Output, -} - /// A private property of Metal's render pipeline descriptor that /// [`Feature::PrivateRenderState`] refuses at a value other than Metal's default /// (`PrivateRenderState`). @@ -940,7 +921,7 @@ pub enum PrivateRenderField { /// `logicOperationEnabled` with an operation other than copy and no-op: on a device without /// `logicOp` (`Unsupported::needs` naming it), or where Vulkan's operation is not Metal's (an /// sRGB attachment, a float attachment that blends, a format whose operation Metal was not - /// measured with, a fragment function that writes an attachment itself). + /// measured with). LogicOperation, /// `pointSmoothEnabled`. PointSmooth, @@ -1023,12 +1004,6 @@ pub enum RuntimeInput { /// stencil is compiled for the pipeline's kind either way: its shadow is multisampled exactly /// when the pipeline is. Multisampled, - /// A fragment function reads a color attachment (framebuffer fetch) on a device that orders - /// the read only through the pixel interlock, where the read's form depends on the render - /// pipeline's attachments and state (`LoweringInputs::framebuffer_fetch`): compiled without - /// that state, or for a pipeline whose state chose another form, it is compiled for the - /// pipeline again. - FramebufferFetch, /// A fragment function reads `[[viewport_array_index]]`, which it reads from the raw varying /// a vertex function that writes the index adds (`LoweringInputs::viewport_index_varying`), and /// was compiled for the other kind of vertex function: compiled without the field behind such a @@ -1092,11 +1067,6 @@ pub enum RuntimeInput { /// or it runs another comparison. It was compiled for another pipeline, and is compiled for /// this one again. AlphaTest, - /// A fragment function in a render pipeline whose private logic operation it computes itself - /// on a device without Vulkan's `logicOp` (`LoweringInputs::logic_operation`), as Metal - /// operates on its attachments' codes; or it computes another operation, or one its pipeline - /// does not take. It was compiled for another pipeline, and is compiled for this one again. - LogicOperation, /// A fragment function in a render pipeline with a private `fragmentDepthCompareClampMask` /// clamps the references of its depth comparisons through the mask's samplers itself /// (`LoweringInputs::depth_compare_clamp_mask`), as Metal clamps them; or it clamps others. It diff --git a/crates/metal2vulkan/src/lower/arith/exact_division.rs b/crates/metal2vulkan/src/lower/arith/exact_division.rs index f83e698d4..dff82ef75 100644 --- a/crates/metal2vulkan/src/lower/arith/exact_division.rs +++ b/crates/metal2vulkan/src/lower/arith/exact_division.rs @@ -1,17 +1,14 @@ -//! A count over a divisor as an `f32`, correctly rounded with integer operations alone, and the -//! per-lane constants it reads. +//! A constant of a form whose lanes hold bits of their own ([`per_lane`]), which `pack` reads. //! -//! The math intrinsics' normalized-integer conversions, the vertex fetch's normalized formats, -//! and the sRGB decode steps emit it at compile time. It is a file of its own so that it is among -//! the runtime's inputs (validation's `build.rs`) without the math intrinsics, which only the -//! compile emits. +//! It is a file of its own so that it is among the runtime's inputs (validation's `build.rs`) +//! without the math intrinsics, which only the compile emits. -use crate::lower::arith::legal::{FloatFmt, Form, Held}; +use crate::lower::arith::legal::Form; use crate::lower::arith::ops::{elem_ty, ones, splat, ty}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, OperandRule}; use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp}; +use crate::spirv::ir::{ConstBits, Constant}; /// A constant of form `f` whose lane `i` is `bits[i]`: one value for every lane is a splat /// ([`splat`]). @@ -41,80 +38,3 @@ pub(super) fn per_lane(fb: &mut FunctionBuilder<'_>, f: Form, bits: &[u64]) -> B })?; fb.module().const_value(c) } - -/// `k / d` correctly rounded to `f32`, for integers `0 <= k <= d` (`u32` lanes of form `u`) and -/// a divisor `1 <= d < 2^16`, with integer operations only, so it is exact on every device and -/// under every fast-math mode: Metal's normalized-integer conversions (`c / 255`, correctly rounded -/// on every byte of A1's `srgb-decode-of-every-byte`, bcb3682b, where a device division is one ULP -/// off on about half of them) and its sRGB decode steps (`k / 4095`). -/// -/// `k = 0` is `+0`. Otherwise `k` is shifted left until `a = k * 2^e` lies in `[d, 2d)` -/// (`e >= 0`: `k <= d`), so `k / d = (a / d) * 2^-e` with `a / d` in `[1, 2)`. The significand -/// `q = floor(a * 2^23 / d)` (24 bits, its leading one included) is two exact integer divisions -/// (`a * 2^12 < 2^29`, then the remainder times `2^11`), and the last remainder rounds it to -/// nearest even. The biased exponent is `127 - e`, so the bits are `((126 - e) << 23) + q` plus -/// the rounding, which carries into the exponent when `q` is all ones (`k = d` gives exactly -/// `1.0`). -pub fn div_exact(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: u32) -> BResult { - div_exact_lanes(fb, u, k, &[d]) -} - -/// [`div_exact`] with lane `i` of `k` divided by `d[i]` (one divisor for every lane when `d` has -/// one): the sequence is lane-wise, its divisor and the divisor's top bit per-lane constants, so -/// each lane is its own [`div_exact`]. -pub fn div_exact_lanes( - fb: &mut FunctionBuilder<'_>, - u: Form, - k: Value, - d: &[u32], -) -> BResult { - let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let (z, one) = (c(fb, 0)?, c(fb, 1)?); - let dl: Vec = d.iter().map(|d| u64::from(*d)).collect(); - let dk = per_lane(fb, u, &dl)?; - let zero = fb.binary(BinOp::IEqual, k, z)?; - // Any k >= 1 in its place for 0, whose answer is selected below. - let k = fb.glsl(GlslOp::UMax, &[k, one])?; - let m = fb.glsl(GlslOp::FindUMsb, &[k])?; - let top: Vec = d - .iter() - .map(|d| u64::from(31 - d.leading_zeros())) - .collect(); - let top = per_lane(fb, u, &top)?; - let e = fb.binary(BinOp::ISub, top, m)?; - let a = fb.binary(BinOp::ShiftLeftLogical, k, e)?; - let short = fb.binary(BinOp::ULessThan, a, dk)?; - let a2 = fb.binary(BinOp::ShiftLeftLogical, a, one)?; - let a = fb.select(short, a2, a)?; - let e1 = fb.binary(BinOp::IAdd, e, one)?; - let e = fb.select(short, e1, e)?; - let (k11, k12) = (c(fb, 11)?, c(fb, 12)?); - let hi = fb.binary(BinOp::ShiftLeftLogical, a, k12)?; - let q1 = fb.binary(BinOp::UDiv, hi, dk)?; - let t = fb.binary(BinOp::IMul, q1, dk)?; - let r1 = fb.binary(BinOp::ISub, hi, t)?; - let lo = fb.binary(BinOp::ShiftLeftLogical, r1, k11)?; - let q2 = fb.binary(BinOp::UDiv, lo, dk)?; - let t = fb.binary(BinOp::IMul, q2, dk)?; - let r2 = fb.binary(BinOp::ISub, lo, t)?; - let q = fb.binary(BinOp::ShiftLeftLogical, q1, k11)?; - let q = fb.binary(BinOp::BitwiseOr, q, q2)?; - // Round to nearest even on the remainder. - let twice = fb.binary(BinOp::ShiftLeftLogical, r2, one)?; - let above = fb.binary(BinOp::UGreaterThan, twice, dk)?; - let tie = fb.binary(BinOp::IEqual, twice, dk)?; - let lsb = fb.binary(BinOp::BitwiseAnd, q, one)?; - let odd = fb.binary(BinOp::INotEqual, lsb, z)?; - let tie_up = fb.binary(BinOp::LogicalAnd, tie, odd)?; - let up = fb.binary(BinOp::LogicalOr, above, tie_up)?; - let inc = fb.select(up, one, z)?; - let k126 = c(fb, 126)?; - let be = fb.binary(BinOp::ISub, k126, e)?; - let k23 = c(fb, 23)?; - let be = fb.binary(BinOp::ShiftLeftLogical, be, k23)?; - let bits = fb.binary(BinOp::IAdd, be, q)?; - let bits = fb.binary(BinOp::IAdd, bits, inc)?; - let bits = fb.select(zero, z, bits)?; - let ft = ty(fb, u.with(Held::Float(FloatFmt::F32)))?; - fb.convert(ConvOp::Bitcast, bits, ft) -} diff --git a/crates/metal2vulkan/src/lower/arith/extended_range.rs b/crates/metal2vulkan/src/lower/arith/extended_range.rs index 7f54ab3ec..49eac0db3 100644 --- a/crates/metal2vulkan/src/lower/arith/extended_range.rs +++ b/crates/metal2vulkan/src/lower/arith/extended_range.rs @@ -35,9 +35,6 @@ use crate::spirv::error::BResult; use crate::spirv::ids::Value; use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, Type, UnOp}; -pub mod blend; -pub use blend::Blend; - /// An upper estimate of the SPIR-V words of one texel's [`decode`]: the codes, the conversion /// and product, an `_sRGB` form's transfer (its steps and constants) and sign, and the `half` /// narrowing. @@ -492,33 +489,6 @@ pub(crate) fn bfloat_stored( fb.vector_shuffle(code, zero, bfloat_lanes(form)) } -/// [`encode`] of `v` into a texel of a form other than a bfloat one that keeps the channels -/// `kept` (red, green, blue, alpha) of `old`, the raw texel the write overwrites, as Metal's -/// blended write under a write mask keeps them (every masked configuration, each texel): each kept -/// channel's code as [`decode`] reads it (a color code as it is, 1023 too; `BGRA10_XR`'s alpha -/// clamped to `[384, 894]`; a two-plane texel's alpha byte; a padded word's top 10 bits), packed -/// as a write packs it: plane 0's and `BGR10_XR`'s top two bits as the write sets them (zeros and -/// ones), `BGRA10_XR`'s and a padded word's six low bits zero. -pub fn encode_keeping( - fb: &mut FunctionBuilder<'_>, - form: ExtendedRange, - v: Value, - (old, kept): (Value, [bool; 4]), -) -> BResult { - let new = write_codes(fb, form, v)?; - let old = codes(fb, form, old)?; - let lanes: Vec = kept - .iter() - .zip(0..4u32) - .map(|(&kept, k)| match kept { - true => 4 + k, - false => k, - }) - .collect(); - let code = fb.vector_shuffle(new, old, &lanes)?; - pack(fb, form, code) -} - /// The codes a write of `v` (a `vec4` of `f32`, red first) to a slot of a linear or `_sRGB` form /// stores ([`encode`]): the value, a NaN 0, an `_sRGB` color channel's magnitude through the /// transfer, signed, clamped to the linear values of codes 0 and 1023 (alpha to `[0, 1]`), times diff --git a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs deleted file mode 100644 index 526c26e3c..000000000 --- a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs +++ /dev/null @@ -1,1556 +0,0 @@ -//! The blends a fragment function computes in the shader, inside the pixel interlock, where no -//! fixed-function blend applies to the attachment. -//! -//! **An extended-range attachment** ([`NativeBlend`], [`native`]) holds raw codes no device -//! blends: the function reads the texel's tile value ([`super::tile_value`]), blends, and stores -//! the kernel write's encode of the result ([`super::encode`], [`super::encode_keeping`] under a -//! write mask). The blend is a blend unit's arithmetic, the device's own: `S·Fs op D·Fd` in -//! `float`, in the blend equation's order, for the color lanes the write stores and for alpha; -//! `Min` and `Max` read no factor; `SourceAlphaSaturated` is `min(sa, 1 - da)` in color and one in -//! alpha; each `1 - x` is computed in `float`. The source, the second source and the blend color -//! are taken as they are: the attachment is a padded form's, which Metal clamps none of (a blend -//! into one of Apple's extended-range forms is refused, `fragment::fetch::codes_round_the_tile`). -//! Metal's compiler instead fuses, regroups and rounds each step to `half`; -//! the stored value can differ from Metal's in the last bits of the encode, which the artifact -//! records (`PrecisionNote::ExtendedRangeBlendSource`, `ExtendedRangeFloatBlendSource`). -//! -//! **An 8-bit unorm attachment held with its channels rotated** ([`Blend`], [`Blend::unorm8`], -//! the blend `fragment::input_blend` computes over the input attachment) takes the forms Metal's -//! compiler builds. The forms, for the color lanes the write stores (one vector) and alpha (a -//! scalar), each computing `S op D`, `S = s Fs` and `D = d Fd`, each sum and product rounded once -//! to the arithmetic's type, nearest even (`h`): -//! -//! 1. `Min` and `Max`: `min(s, d)` and `max(s, d)`, the factors unread. -//! 2. A zero factor drops its term: `0`, or `h(±S)` or `h(±D)` alone. -//! 3. A factor of one: `h(±S ± D)`, one fused multiply-add. -//! 4. Two products, added, where one's factor is `1 - z` and the other's operands hold `z` -//! (a lerp): `h(y + z · inner)`, `y` the first product's operand and `inner` the other -//! product's other operand minus `y`. -//! 5. Two products sharing an operand `z`: `h(z · inner)`, `inner` the sum of the other two. -//! 6. Otherwise one product is rounded first and the other fused into the sum: the source's -//! under `ReverseSubtract`, the destination's under `Subtract`, and under `Add` by the -//! factors' ranks ([`unorm8_rank`]). -//! -//! An inner sum expands each `1 - z` into `1` and `-z` (but a blend color's, a color lane's of -//! an alpha, and, in alpha, the one-minus-blend-alpha the color factors share once it comes -//! second), merges equal terms, and adds them in a fixed order ([`inner_sum`]), each addition -//! rounded. `SourceAlphaSaturated` is `min(sa, h(1 - da))` in color and one in alpha, and `1 - x` -//! is `h(1 - x)`. -//! -//! **A module without fast math** (`air.compile.fast_math_disable`, [`BlendMath::Rounded`]): -//! Metal's compiler folds the blend into the function without fusing it: each term's product -//! rounded (a factor of one its operand, of zero no term), and the two terms' sum rounded; `min` -//! and `max` as the fast forms. Every `1 - x` is `h(1 - x)` of the value it reads -//! ([`Node::OneMinus`]). - -use super::{floats, per_lane_f}; -use crate::error::{Error, ExtendedRangeBlend, Feature, Unsupported}; -use crate::lower::arith::fma::{float_fma_exact, half_sum}; -use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::narrow; -use crate::lower::arith::ops::{fsplat, splat, ty}; -use crate::lower::arith::texel_round::{f32_to_half, HalfRounding}; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use crate::pipeline::lower_inputs::BlendEquation; -use crate::spirv::builder::{FunctionBuilder, QuantizeForm}; -use crate::spirv::error::{BResult, BuildError, TypeRule}; -use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp}; - -// ---- The device's blend arithmetic ---- - -/// The blend `eq` a write computes in the shader by the device's own arithmetic, where the device -/// cannot blend the attachment's format itself (an extended-range attachment's raw texels: -/// [`native`]). Every factor, operation and write mask is built, the second source's too. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct NativeBlend { - /// The pipeline's blend at the attachment. - pub(crate) eq: BlendEquation, - /// The write stores some color channel. - color: bool, - /// The write stores alpha. - alpha: bool, -} - -/// Whether `f` is one of the second source's factors. -fn second_factor(f: BlendFactor) -> bool { - use BlendFactor as F; - matches!( - f, - F::Source1Color | F::OneMinusSource1Color | F::Source1Alpha | F::OneMinusSource1Alpha - ) -} - -/// Whether `f` reads the blend color. -fn constant_factor(f: BlendFactor) -> bool { - use BlendFactor as F; - matches!( - f, - F::BlendColor | F::OneMinusBlendColor | F::BlendAlpha | F::OneMinusBlendAlpha - ) -} - -impl NativeBlend { - /// The blend `eq` of a write storing the channels `written` of four (a channel the format - /// lacks counts as unwritten): `Err` with the placeholder a factor or operation is - /// (`DescriptorError::PlaceholderEnumValue`). - pub fn of(eq: &BlendEquation, written: ColorWriteMask) -> Result { - for f in [ - eq.source_rgb, - eq.destination_rgb, - eq.source_alpha, - eq.destination_alpha, - ] { - if f == BlendFactor::Unspecialized { - return Err(placeholder(BlendFactor::METAL_NAME, f.as_raw())); - } - } - for op in [eq.rgb_operation, eq.alpha_operation] { - if op == BlendOperation::Unspecialized { - return Err(placeholder(BlendOperation::METAL_NAME, op.as_raw())); - } - } - let color = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ] - .into_iter() - .any(|c| written.contains(c)); - Ok(NativeBlend { - eq: *eq, - color, - alpha: written.contains(ColorWriteMask::ALPHA), - }) - } - - /// The factors the stored classes read: none under `Min` or `Max`. - fn factors(&self) -> Vec { - let minmax = |op: BlendOperation| matches!(op, BlendOperation::Min | BlendOperation::Max); - let mut fs = Vec::with_capacity(4); - if self.color && !minmax(self.eq.rgb_operation) { - fs.extend([self.eq.source_rgb, self.eq.destination_rgb]); - } - if self.alpha && !minmax(self.eq.alpha_operation) { - fs.extend([self.eq.source_alpha, self.eq.destination_alpha]); - } - fs - } - - /// Whether the blend reads the blend color (`PushField::HalfBlendColor`). - pub fn reads_constant(&self) -> bool { - self.factors().into_iter().any(constant_factor) - } - - /// Whether the blend reads the second source (the function's index-1 output). - pub fn reads_second(&self) -> bool { - self.factors().into_iter().any(second_factor) - } -} - -/// The values a native blend's factors read, `vec4`s of `f32`. -struct Operands { - s: Value, - d: Value, - s1: Option, - c: Option, -} - -/// `x`'s alpha in every lane. -fn alpha_splat(fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { - fb.vector_shuffle(x, x, &[3, 3, 3, 3]) -} - -/// Factor `f` of a lane class (alpha's where `alpha`) over `o`, every lane: `None` for a factor -/// of one, whose product is its operand. -fn native_factor( - fb: &mut FunctionBuilder<'_>, - f: BlendFactor, - alpha: bool, - o: &Operands, -) -> BResult> { - use BlendFactor as F; - let v = floats(); - let missing = || BuildError::Type(TypeRule::FunctionSignature); - let one_minus = |fb: &mut FunctionBuilder<'_>, x: Value| -> BResult { - let one = fsplat(fb, v, 1.0)?; - fb.binary(BinOp::FSub, one, x) - }; - let s1 = || o.s1.ok_or_else(missing); - let c = || o.c.ok_or_else(missing); - Ok(Some(match f { - F::Zero => fsplat(fb, v, 0.0)?, - F::One => return Ok(None), - F::SourceAlphaSaturated if alpha => return Ok(None), - F::SourceColor => o.s, - F::OneMinusSourceColor => one_minus(fb, o.s)?, - F::SourceAlpha => alpha_splat(fb, o.s)?, - F::OneMinusSourceAlpha => { - let a = alpha_splat(fb, o.s)?; - one_minus(fb, a)? - } - F::DestinationColor => o.d, - F::OneMinusDestinationColor => one_minus(fb, o.d)?, - F::DestinationAlpha => alpha_splat(fb, o.d)?, - F::OneMinusDestinationAlpha => { - let a = alpha_splat(fb, o.d)?; - one_minus(fb, a)? - } - F::SourceAlphaSaturated => { - let sa = alpha_splat(fb, o.s)?; - let da = alpha_splat(fb, o.d)?; - let m = one_minus(fb, da)?; - fb.glsl(GlslOp::FMin, &[sa, m])? - } - F::BlendColor => c()?, - F::OneMinusBlendColor => one_minus(fb, c()?)?, - F::BlendAlpha => alpha_splat(fb, c()?)?, - F::OneMinusBlendAlpha => { - let a = alpha_splat(fb, c()?)?; - one_minus(fb, a)? - } - F::Source1Color => s1()?, - F::OneMinusSource1Color => one_minus(fb, s1()?)?, - F::Source1Alpha => alpha_splat(fb, s1()?)?, - F::OneMinusSource1Alpha => { - let a = alpha_splat(fb, s1()?)?; - one_minus(fb, a)? - } - F::Unspecialized => return Err(missing()), - })) -} - -/// One lane class of a native blend (alpha's where `alpha`, read from lane 3) over `o`, every -/// lane: `S·Fs op D·Fd` in the equation's order, each product and the sum the device's `OpFMul` -/// and `OpFAdd` or `OpFSub` (a factor of one its operand); `Min` and `Max` the device's `FMin` -/// and `FMax` of the source and the destination, the factors unread. -fn native_class( - fb: &mut FunctionBuilder<'_>, - (fs, fd, op): (BlendFactor, BlendFactor, BlendOperation), - alpha: bool, - o: &Operands, -) -> BResult { - match op { - BlendOperation::Min => return fb.glsl(GlslOp::FMin, &[o.s, o.d]), - BlendOperation::Max => return fb.glsl(GlslOp::FMax, &[o.s, o.d]), - _ => {} - } - let source = match native_factor(fb, fs, alpha, o)? { - Some(f) => fb.binary(BinOp::FMul, o.s, f)?, - None => o.s, - }; - let destination = match native_factor(fb, fd, alpha, o)? { - Some(f) => fb.binary(BinOp::FMul, o.d, f)?, - None => o.d, - }; - match op { - BlendOperation::Subtract => fb.binary(BinOp::FSub, source, destination), - BlendOperation::ReverseSubtract => fb.binary(BinOp::FSub, destination, source), - _ => fb.binary(BinOp::FAdd, source, destination), - } -} - -/// The blend `b` ([`NativeBlend`]) of output `s` (a `vec4` of `f32`: the function's `half4` or -/// `float4` output as it computed it) over `d` (a `vec4` of `f32`, the destination as the write -/// reads it) by the device's arithmetic: a `vec4` of `f32` holding each blended lane, which the -/// caller converts to the attachment. The source, the second source `s1` (the function's index-1 -/// output, where `b` reads it) and the blend color `color` (the encoder's blend color, a `uvec4` -/// of its `f32`s' bits, `PushField::HalfBlendColor`, where `b` reads it) are taken as they are, as -/// Metal takes a padded form's. Each class computes `S·Fs op D·Fd` in `f32`, in the equation's -/// order, each -/// factor (`1 - x`, `SourceAlphaSaturated`'s `min(sa, 1 - da)`), product and sum one device -/// instruction, nothing rounded to `half` between them, the device free to contract a product into -/// its sum as it contracts the module's own arithmetic. A lane the write does not store holds -/// `d`'s. -pub fn native( - fb: &mut FunctionBuilder<'_>, - b: &NativeBlend, - (s, s1, d): (Value, Option, Value), - color: Option, -) -> BResult { - let f = floats(); - let s1 = s1.filter(|_| b.reads_second()); - let c = match color { - Some(words) if b.reads_constant() => { - let ft = ty(fb, f)?; - Some(fb.convert(ConvOp::Bitcast, words, ft)?) - } - _ => None, - }; - let o = Operands { s, d, s1, c }; - let eq = &b.eq; - let rgb = match b.color { - true => native_class( - fb, - (eq.source_rgb, eq.destination_rgb, eq.rgb_operation), - false, - &o, - )?, - false => d, - }; - let alpha = match b.alpha { - true => native_class( - fb, - (eq.source_alpha, eq.destination_alpha, eq.alpha_operation), - true, - &o, - )?, - false => d, - }; - fb.vector_shuffle(rgb, alpha, &[0, 1, 2, 7]) -} - -/// A value a blend lane reads. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Atom { - /// The source's lane: a color lane's own channel, alpha's alpha. - S, - /// The source's alpha. - Sa, - /// The destination's lane (the tile value's). - D, - /// The destination's alpha. - Da, - /// The blend color's lane. - C, - /// The blend color's alpha. - Ca, - /// The second source's lane (the function's index-1 output), rounded and clamped as the - /// source's: a color lane's own channel, alpha's alpha ([`BlendMath::Rounded`] alone). - S1, - /// The second source's alpha. - S1a, -} - -impl Atom { - /// An alpha a color lane reads as a splat of one value. - fn splat(self) -> bool { - matches!(self, Atom::Sa | Atom::Da | Atom::Ca | Atom::S1a) - } - - /// An inner sum's order among its atoms under `scheme`. - fn order(self, scheme: Order) -> u8 { - match (self, scheme) { - (Atom::C | Atom::Ca, _) => 9, - (Atom::S1 | Atom::S1a, _) => 1, - (Atom::S | Atom::Sa, Order::Destination) => 2, - (Atom::D | Atom::Da, Order::Destination) => 0, - (Atom::Da, Order::Scalar) => 0, - (Atom::D, Order::Scalar) => 1, - (Atom::Sa, Order::Scalar) => 2, - (Atom::S, Order::Scalar) => 3, - } - } -} - -/// An inner sum's order among its atoms ([`Atom::order`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Order { - /// The destination's before the source's: an 8-bit unorm attachment's blend. - Destination, - /// The destination's before the source's, and each alpha before its lane: an 8-bit unorm - /// attachment's color channel stored alone. - Scalar, -} - -/// A factor or operand of a blend lane. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Node { - Zero, - One, - Atom(Atom), - /// `h(1 - x)`. - OneMinus(Atom), - /// `min(sa, h(1 - da))`, a color lane's `SourceAlphaSaturated`. - Saturate, -} - -/// An operand and its factor: their product. -pub(crate) type Term = (Atom, Node); - -/// A summand of an inner sum: the constant one (`None`) or a node, with its coefficient. -pub(crate) type Summand = (i8, Option); - -/// The arithmetic of one lane class, in the module docs' forms. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum Arith { - /// `min(s, d)` or `max(s, d)`, `s` the `source` atom. - MinMax { - max: bool, - source: Atom, - }, - Zero, - /// `h(sign · term)`. - Term { - sign: i8, - term: Term, - }, - /// `h(sign · product + sign · addend)`, the addend's factor one: one fused multiply-add. - Fused { - product: (i8, Term), - addend: (i8, Term), - }, - /// `h(y + z · inner)`. - Lerp { - y: Node, - z: Node, - inner: Vec, - }, - /// `h(z · inner)`. - Common { - z: Node, - inner: Vec, - }, - /// `h(sign · h(rounded) + sign · fused)`, the fused product added exactly. - Contracted { - rounded: (i8, Term), - fused: (i8, Term), - }, - /// `h(h(sign · source) + h(sign · destination))`, a term of factor one its operand: a module - /// without fast math's ([`BlendMath::Rounded`]). - Rounded { - source: (i8, Term), - destination: (i8, Term), - }, -} - -/// Metal's blend of one attachment's write, as the shader computes it ([`blend_unorm8`]). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Blend { - /// The color lanes' arithmetic, where the write stores two or three of them. - pub(crate) color: Option, - /// Alpha's, where the write stores it. - pub(crate) alpha: Option, - /// The function's math mode: every one minus is `h(1 - x)` of the `half` it reads under - /// [`BlendMath::Rounded`], the blend color's too. - pub(crate) math: BlendMath, -} - -/// How Metal's compiler computes a blend it folds into the function, by the function's math mode -/// (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BlendMath { - /// Fast math, or a module that names no mode: the fast forms, a product fused into a sum by - /// the factors' structure. - Fast, - /// A module without fast math (`air.compile.fast_math_disable`): each term's product rounded - /// to `half`, then the terms' sum ([`Arith::Rounded`]). - Rounded, -} - -impl BlendMath { - /// The blend math of a module compiled with `fast_math` (`CompileOptions::fast_math`). - pub fn of(fast_math: Option) -> BlendMath { - match fast_math { - Some(false) => BlendMath::Rounded, - Some(true) | None => BlendMath::Fast, - } - } -} - -fn refused(gap: ExtendedRangeBlend) -> Error { - Unsupported::not_implemented(Feature::ExtendedRangeBlend(gap)).into() -} - -fn placeholder(ty: &'static str, value: u32) -> Error { - Error::InvalidDescriptor(crate::error::DescriptorError::PlaceholderEnumValue { ty, value }) -} - -/// Factor `f` of a color lane, or of alpha where `alpha`, under `math`: the second source's -/// factors are refused under fast math. -fn factor(f: BlendFactor, alpha: bool, math: BlendMath) -> Result { - use BlendFactor as F; - let own = |color: Atom, a: Atom| if alpha { a } else { color }; - Ok(match f { - F::Zero => Node::Zero, - F::One => Node::One, - F::SourceColor => Node::Atom(own(Atom::S, Atom::Sa)), - F::OneMinusSourceColor => Node::OneMinus(own(Atom::S, Atom::Sa)), - F::SourceAlpha => Node::Atom(Atom::Sa), - F::OneMinusSourceAlpha => Node::OneMinus(Atom::Sa), - F::DestinationColor => Node::Atom(own(Atom::D, Atom::Da)), - F::OneMinusDestinationColor => Node::OneMinus(own(Atom::D, Atom::Da)), - F::DestinationAlpha => Node::Atom(Atom::Da), - F::OneMinusDestinationAlpha => Node::OneMinus(Atom::Da), - F::SourceAlphaSaturated if alpha => Node::One, - F::SourceAlphaSaturated => Node::Saturate, - F::BlendColor => Node::Atom(own(Atom::C, Atom::Ca)), - F::OneMinusBlendColor => Node::OneMinus(own(Atom::C, Atom::Ca)), - F::BlendAlpha => Node::Atom(Atom::Ca), - F::OneMinusBlendAlpha => Node::OneMinus(Atom::Ca), - F::Source1Color | F::OneMinusSource1Color | F::Source1Alpha | F::OneMinusSource1Alpha - if math == BlendMath::Fast => - { - return Err(refused(ExtendedRangeBlend::DualSource)) - } - F::Source1Color => Node::Atom(own(Atom::S1, Atom::S1a)), - F::OneMinusSource1Color => Node::OneMinus(own(Atom::S1, Atom::S1a)), - F::Source1Alpha => Node::Atom(Atom::S1a), - F::OneMinusSource1Alpha => Node::OneMinus(Atom::S1a), - F::Unspecialized => return Err(placeholder(BlendFactor::METAL_NAME, f.as_raw())), - }) -} - -/// An 8-bit unorm attachment's factor rank, of a color factor or alpha's where `alpha`, in the -/// arithmetic `arith`: of an added pair, the destination's product is rounded first where the -/// source factor's rank is at least the destination factor's, else the source's. -/// -/// In a color lane the one minus the destination alpha ranks as the one minus the source alpha -/// does. Plain Metal on the M3 Max under macOS 27.0.1 blends `DestinationAlpha` over -/// `OneMinusDestinationAlpha` with the source's product rounded first, into `RGBA8Unorm` from a -/// `float4` output under fast math: `f(fma(d, f(1 - da), f(s · da)))` gives Metal's code in every -/// color channel of the 8,192 texels of the `argb8-targets-destination-alpha` recording, and the -/// destination's product rounded first misses 10 of them. The same rank in `half` arithmetic is -/// not measured. -fn unorm8_rank(f: BlendFactor, alpha: bool, arith: BlendArith) -> u8 { - use BlendFactor as F; - let float = arith == BlendArith::Float; - match f { - F::SourceColor - | F::SourceAlpha - | F::DestinationColor - | F::OneMinusDestinationColor - | F::DestinationAlpha => 0, - F::OneMinusDestinationAlpha if alpha => 0, - F::OneMinusSourceColor | F::OneMinusSourceAlpha if alpha && !float => 0, - F::OneMinusSourceColor - | F::OneMinusSourceAlpha - | F::OneMinusDestinationAlpha - | F::SourceAlphaSaturated => 1, - F::BlendColor | F::BlendAlpha if float => 1, - F::BlendColor | F::BlendAlpha => 2, - F::OneMinusBlendColor | F::OneMinusBlendAlpha => 3, - _ => 9, - } -} - -/// The factor `n` of a format without alpha (`BGR10_XR`, `R16Float`, `RG16Float`): its destination -/// alpha is one. -fn opaque(n: Node) -> Node { - match n { - Node::Atom(Atom::Da) => Node::One, - Node::OneMinus(Atom::Da) => Node::Zero, - n => n, - } -} - -/// The one-minus nodes of the color factors that alpha's sums and lerps take apart ([`plan`]): -/// `values` (one value the color lanes compute too: a lerp's one minus is none of them where -/// alpha's model says so, and a sum keeps one whole where added second). -#[derive(Clone, Debug, Default)] -struct Shared { - values: Vec, -} - -/// Whether an inner sum keeps the one-minus node `n`, added with `sign` (from the destination's -/// product where `destination`), whole beyond the nodes that always stay whole ([`inner_sum`]): a -/// shared value added from the destination's product. -fn kept_whole((n, sign, _, destination): (Node, i8, usize, bool), shared: &Shared) -> bool { - shared.values.contains(&n) && sign > 0 && destination -} - -/// The summands of `pairs` (each a node, its sign, and whether it comes from the destination's -/// product, in the IR's order) as Metal's compiler adds them: each `1 - z` expanded into `1` and -/// `-z` but where it stays one value (a blend color's; an alpha's in a color lane of a vector -/// class, `scalar` false; where `keep` says so, [`kept_whole`]), equal terms merged, and the terms -/// ordered: the constant last, but between the two others where they are not both subtracted, -/// after the one of the lower [`Atom::order`] under `order`. -fn inner_sum( - pairs: [(Node, i8, bool); 2], - (scalar, order): (bool, Order), - keep: &dyn Fn((Node, i8, usize, bool)) -> bool, -) -> Vec { - let mut terms: Vec = Vec::with_capacity(4); - for (i, (n, sign, destination)) in pairs.into_iter().enumerate() { - match n { - Node::OneMinus(z) => { - let leaf = matches!(z, Atom::C | Atom::Ca) - || (!scalar && z.splat()) - || keep((n, sign, i, destination)); - if leaf { - terms.push((sign, Some(n))); - } else { - terms.push((sign, None)); - terms.push((-sign, Some(Node::Atom(z)))); - } - } - Node::One => terms.push((sign, None)), - n => terms.push((sign, Some(n))), - } - } - let mut merged: Vec = Vec::with_capacity(terms.len()); - for (c, k) in terms { - match merged.iter_mut().find(|m| m.1 == k) { - Some(m) => m.0 += c, - None => merged.push((c, k)), - } - } - merged.retain(|m| m.0 != 0); - let constant = merged.iter().copied().find(|m| m.1.is_none()); - let rest: Vec = merged.iter().copied().filter(|m| m.1.is_some()).collect(); - match (constant, rest.as_slice()) { - (Some(one), &[a, b]) if a.0 > 0 || b.0 > 0 => { - let rank = |m: Summand| match m.1 { - Some(Node::Atom(x)) => x.order(order), - _ => 9, - }; - match rank(b) < rank(a) { - true => vec![b, one, a], - false => vec![a, one, b], - } - } - _ => rest.into_iter().chain(constant).collect(), - } -} - -/// The arithmetic of a lane class (alpha where `alpha`) of factors `fs` and `fd` under `op`, -/// `shared` the one-minus nodes of the color factors that alpha's sums and lerps take apart, -/// `opaque_` for a format without alpha, in the arithmetic `arith`. `scalar` marks a color class of one channel (an 8-bit unorm attachment's write mask -/// of one color channel), which Metal plans as a scalar: an alpha read there is no splat, but a -/// one minus an alpha that its destination factor is or that alpha's factors compute (`shared`) -/// stays whole in its sums and takes no lerp. -fn plan( - (fs, fd, op): (BlendFactor, BlendFactor, BlendOperation), - (alpha, scalar): (bool, bool), - shared: &Shared, - opaque_: bool, - arith: BlendArith, -) -> Result { - let order = match scalar { - false => Order::Destination, - true => Order::Scalar, - }; - let (s, da) = match alpha { - true => (Atom::Sa, Atom::Da), - false => (Atom::S, Atom::D), - }; - let (ps, pd): (i8, i8) = match op { - BlendOperation::Add => (1, 1), - BlendOperation::Subtract => (1, -1), - BlendOperation::ReverseSubtract => (-1, 1), - BlendOperation::Min => { - return Ok(Arith::MinMax { - max: false, - source: s, - }) - } - BlendOperation::Max => { - return Ok(Arith::MinMax { - max: true, - source: s, - }) - } - BlendOperation::Unspecialized => { - return Err(placeholder(BlendOperation::METAL_NAME, op.as_raw())) - } - }; - let fast = BlendMath::Fast; - let (mut nfs, mut nfd) = (factor(fs, alpha, fast)?, factor(fd, alpha, fast)?); - if opaque_ { - (nfs, nfd) = (opaque(nfs), opaque(nfd)); - } - let st: Term = (s, nfs); - let dt: Term = (da, nfd); - match (nfs == Node::Zero, nfd == Node::Zero) { - (true, true) => return Ok(Arith::Zero), - (true, false) => return Ok(Arith::Term { sign: pd, term: dt }), - (false, true) => return Ok(Arith::Term { sign: ps, term: st }), - (false, false) => {} - } - if nfs == Node::One || nfd == Node::One { - let (product, addend) = match nfs == Node::One && nfd != Node::One { - true => ((pd, dt), (ps, st)), - false => ((ps, st), (pd, dt)), - }; - return Ok(Arith::Fused { product, addend }); - } - // Each product's operand and factor. - let sops = (Node::Atom(s), nfs); - let dops = (Node::Atom(da), nfd); - let both_orders = |p: (Node, Node)| [(p.0, p.1), (p.1, p.0)]; - // A color channel stored alone keeps whole the one minus an alpha its destination factor is - // and those alpha's factors compute. - let mut alone = shared.values.clone(); - if matches!(nfd, Node::OneMinus(z) if z.splat()) { - alone.push(nfd); - } - let alone = &alone; - let keep_in = || { - move |k: (Node, i8, usize, bool)| match scalar { - true => alone.contains(&k.0), - false => kept_whole(k, shared), - } - }; - // The lerp takes the destination's product for `y`'s first. - let sides = [(false, (dops, sops)), (true, (sops, dops))]; - if op == BlendOperation::Add { - for (source_side, (yt, zo)) in sides { - for (y, f) in both_orders(yt) { - let Node::OneMinus(za) = f else { - continue; - }; - // No lerp of a one minus the color factors computed, the destination alpha's - // among them. - if shared.values.contains(&f) && (za == Atom::Ca || za == Atom::Da) { - continue; - } - let both = [sops.0, sops.1].contains(&f) && [dops.0, dops.1].contains(&f); - if !alpha && !scalar && (za.splat() || y == Node::Atom(za) || both) { - continue; - } - if scalar && (alone.contains(&f) || y == Node::Atom(za) || both) { - continue; - } - // Alpha takes no lerp of the destination alpha beside itself or held by both - // products: Metal's alpha there is the common factor's form. - if alpha && za == Atom::Da && (y == Node::Atom(za) || both) { - continue; - } - let z = Node::Atom(za); - if let Some((_, x)) = both_orders(zo).into_iter().find(|&(zj, _)| zj == z) { - let keep = keep_in(); - // `x` comes from the other product than `y`. - let pairs = [(x, 1, source_side), (y, -1, !source_side)]; - let inner = inner_sum(pairs, (alpha || scalar, order), &keep); - return Ok(Arith::Lerp { y, z, inner }); - } - } - } - } - let keep = keep_in(); - for (z, x) in both_orders(sops) { - for (zd, y) in both_orders(dops) { - if z == zd && !matches!(z, Node::Zero | Node::One) { - let pair = match op { - BlendOperation::ReverseSubtract => [(y, pd, true), (x, ps, false)], - _ => [(x, ps, false), (y, pd, true)], - }; - let inner = inner_sum(pair, (alpha || scalar, order), &keep); - return Ok(Arith::Common { z, inner }); - } - } - } - let source_first = Arith::Contracted { - rounded: (ps, st), - fused: (pd, dt), - }; - let destination_first = Arith::Contracted { - rounded: (pd, dt), - fused: (ps, st), - }; - Ok(match op { - BlendOperation::ReverseSubtract => source_first, - BlendOperation::Subtract => destination_first, - _ => { - let rank = |f| unorm8_rank(f, alpha, arith); - match rank(fs) >= rank(fd) { - true => destination_first, - false => source_first, - } - } - }) -} - -/// The arithmetic of a lane class (alpha where `alpha`) of factors `fs` and `fd` under `op` in a -/// module without fast math ([`BlendMath::Rounded`]), `opaque_` for a format without alpha: -/// `min` or `max`; no term, one, or both terms' rounded products added and rounded -/// ([`Arith::Rounded`]). A zero factor leaves its term out. -fn plan_rounded( - (fs, fd, op): (BlendFactor, BlendFactor, BlendOperation), - alpha: bool, - opaque_: bool, -) -> Result { - let (s, d) = match alpha { - true => (Atom::Sa, Atom::Da), - false => (Atom::S, Atom::D), - }; - let (ps, pd): (i8, i8) = match op { - BlendOperation::Add => (1, 1), - BlendOperation::Subtract => (1, -1), - BlendOperation::ReverseSubtract => (-1, 1), - BlendOperation::Min | BlendOperation::Max => { - return Ok(Arith::MinMax { - max: op == BlendOperation::Max, - source: s, - }) - } - BlendOperation::Unspecialized => { - return Err(placeholder(BlendOperation::METAL_NAME, op.as_raw())) - } - }; - let rounded = BlendMath::Rounded; - let (mut nfs, mut nfd) = (factor(fs, alpha, rounded)?, factor(fd, alpha, rounded)?); - if opaque_ { - (nfs, nfd) = (opaque(nfs), opaque(nfd)); - } - let (st, dt): (Term, Term) = ((s, nfs), (d, nfd)); - Ok(match (nfs == Node::Zero, nfd == Node::Zero) { - (true, true) => Arith::Zero, - (true, false) => Arith::Term { sign: pd, term: dt }, - (false, true) => Arith::Term { sign: ps, term: st }, - (false, false) => Arith::Rounded { - source: (ps, st), - destination: (pd, dt), - }, - }) -} - -/// Metal's blend `eq` of a write storing the channels `written` of four into an 8-bit unorm -/// format with an alpha channel where `has_alpha`, in the arithmetic `arith`, in a function of -/// math `math`: a write mask of one color channel Metal plans as a scalar. -fn planned_for( - eq: &BlendEquation, - (has_alpha, arith): (bool, BlendArith), - written: ColorWriteMask, - math: BlendMath, -) -> Result { - let colors = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ] - .into_iter() - .filter(|&c| written.contains(c)) - .count(); - let alpha_written = has_alpha && written.contains(ColorWriteMask::ALPHA); - let opaque_ = !has_alpha; - let color = match colors { - 0 => None, - _ => { - let f = (eq.source_rgb, eq.destination_rgb, eq.rgb_operation); - let scalar = colors == 1; - // A color channel stored alone shares the one minus an alpha that alpha's factors - // compute, stored or not. - let mut computed = Shared::default(); - let alpha_factors = !matches!( - eq.alpha_operation, - BlendOperation::Min | BlendOperation::Max - ); - if scalar && has_alpha && alpha_factors { - use BlendFactor as F; - let uses = |f: [F; 2]| { - f.iter() - .any(|f| [eq.source_alpha, eq.destination_alpha].contains(f)) - }; - for (f, z) in [ - ([F::OneMinusSourceAlpha, F::OneMinusSourceColor], Atom::Sa), - ( - [F::OneMinusDestinationAlpha, F::OneMinusDestinationColor], - Atom::Da, - ), - ([F::OneMinusBlendAlpha, F::OneMinusBlendColor], Atom::Ca), - ] { - if uses(f) { - computed.values.push(Node::OneMinus(z)); - } - } - } - Some(match math { - BlendMath::Fast => plan(f, (false, scalar), &computed, opaque_, arith)?, - BlendMath::Rounded => plan_rounded(f, false, opaque_)?, - }) - } - }; - let alpha = match alpha_written { - false => None, - true => { - let uses = |f: BlendFactor| [eq.source_rgb, eq.destination_rgb].contains(&f); - // Alpha shares what color lanes it stores compute: one minus the blend alpha, the - // source alpha, and the destination alpha (which `SourceAlphaSaturated` computes - // too); with no color channel stored, the one minus an alpha the color channels' - // destination factor is, which Metal computes still. A minimum or maximum computes no - // factor. - use BlendFactor as F; - let mut shared = Shared::default(); - let factors = !matches!(eq.rgb_operation, BlendOperation::Min | BlendOperation::Max); - if colors == 0 && factors { - let z = match eq.destination_rgb { - F::OneMinusBlendAlpha => Some(Atom::Ca), - F::OneMinusSourceAlpha => Some(Atom::Sa), - F::OneMinusDestinationAlpha => Some(Atom::Da), - _ => None, - }; - shared.values = z.map(Node::OneMinus).into_iter().collect(); - } - if colors > 0 && factors { - let minus = [ - (uses(F::OneMinusBlendAlpha), Atom::Ca), - (uses(F::OneMinusSourceAlpha), Atom::Sa), - ( - uses(F::OneMinusDestinationAlpha) || uses(F::SourceAlphaSaturated), - Atom::Da, - ), - ]; - shared.values = minus - .into_iter() - .filter(|&(u, _)| u) - .map(|(_, z)| Node::OneMinus(z)) - .collect(); - } - let f = (eq.source_alpha, eq.destination_alpha, eq.alpha_operation); - Some(match math { - BlendMath::Rounded => plan_rounded(f, true, opaque_)?, - BlendMath::Fast => plan(f, (true, false), &shared, opaque_, arith)?, - }) - } - }; - Ok(Blend { color, alpha, math }) -} - -impl Blend { - /// Metal's blend `eq` of a four-lane output of a module of math `math`, blended in `arith` - /// (the output's type), into an 8-bit unorm attachment of format `pf` (`R8Unorm`, `RG8Unorm`, - /// `RGBA8Unorm`, `BGRA8Unorm`) storing the channels `written` of four (a channel the format - /// lacks counts as written), computed by [`blend_unorm8`] over the output clamped to `[0, 1]` - /// and the destination's code decoded in that type, the result stored by the device's - /// conversion. - /// Without fast math the rounded forms (the module docs). Under fast math the fast forms, as - /// Metal's compiler builds an 8-bit unorm attachment's blend (plain Metal on the M3 Max under - /// macOS 27.0.1): - /// - /// - an inner sum adds the destination's atoms before the source's ([`Atom::order`]); - /// - a lerp takes `y` from the destination's product first, and alpha takes no lerp of the - /// destination alpha beside itself or held by both products; - /// - of an added pair the product rounded first follows [`unorm8_rank`]; - /// - alpha shares the one minus the blend alpha, the source alpha and the destination alpha - /// (`SourceAlphaSaturated`'s too) that stored color lanes compute, and with no color - /// channel stored the one minus an alpha the color channels' destination factor is, where the - /// color channels' operation is no minimum or maximum, which computes no factor: it takes no - /// lerp of a shared blend or destination alpha, and its sums keep a shared one minus whole - /// where they add it from the destination's product; - /// - a write mask of one color channel plans that channel as a scalar: its - /// alpha reads are no splats, but it keeps whole, and takes no lerp of, a one minus an alpha - /// that its destination factor is or that alpha's factors compute, alpha stored or not; its - /// sums add the destination alpha before the destination's lane, then the source alpha - /// before the source's ([`Order::Scalar`]). - /// - /// A factor of the second source is not built (`Feature::FramebufferFetch` `NotImplemented`). - /// Nor, under fast math, is a - /// format without alpha's (`R8Unorm`, `RG8Unorm`) lerp, common factor or contracted pair: Metal - /// sums those in forms of their own, not measured. - pub fn unorm8( - eq: &BlendEquation, - pf: PixelFormat, - written: ColorWriteMask, - (math, arith): (BlendMath, BlendArith), - ) -> Result { - use BlendFactor as F; - let has_alpha = match pf { - PixelFormat::R8Unorm | PixelFormat::RG8Unorm => false, - // `ARGB8Unorm` blends as `RGBA8Unorm`, its channels rotated (`fetch::unorm8_format`). - PixelFormat::RGBA8Unorm | PixelFormat::BGRA8Unorm | PixelFormat::ARGB8Unorm => true, - _ => return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()), - }; - let factors = [ - eq.source_rgb, - eq.destination_rgb, - eq.source_alpha, - eq.destination_alpha, - ]; - let second = |f: &BlendFactor| { - matches!( - f, - F::Source1Color - | F::OneMinusSource1Color - | F::Source1Alpha - | F::OneMinusSource1Alpha - ) - }; - if factors.iter().any(second) { - return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()); - } - let b = planned_for(eq, (has_alpha, arith), written, math)?; - // A format without alpha sums its two products in forms of its own: of - // its fast-math forms only a single or fused product, zero, and a minimum or maximum are - // measured. - let measured = |a: &Arith| { - matches!( - a, - Arith::MinMax { .. } | Arith::Zero | Arith::Term { .. } | Arith::Fused { .. } - ) - }; - if !has_alpha && math == BlendMath::Fast && !b.color.iter().all(measured) { - return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()); - } - Ok(b) - } - - /// Whether the blend reads the blend color (`PushField::HalfBlendColor`). - pub fn reads_constant(&self) -> bool { - [&self.color, &self.alpha] - .into_iter() - .flatten() - .any(|a| nodes(a).into_iter().any(reads_constant)) - } -} - -/// Whether `n` reads the blend color. -fn reads_constant(n: Node) -> bool { - matches!( - n, - Node::Atom(Atom::C | Atom::Ca) | Node::OneMinus(Atom::C | Atom::Ca) - ) -} - -/// Every node `a` reads. -fn nodes(a: &Arith) -> Vec { - let term = |t: &Term| [Node::Atom(t.0), t.1]; - let summands = |s: &[Summand]| s.iter().filter_map(|m| m.1).collect::>(); - match a { - Arith::MinMax { .. } | Arith::Zero => Vec::new(), - Arith::Term { term: t, .. } => term(t).to_vec(), - Arith::Fused { product, addend } => [term(&product.1), term(&addend.1)].concat(), - Arith::Contracted { rounded, fused } => [term(&rounded.1), term(&fused.1)].concat(), - Arith::Rounded { - source, - destination, - } => [term(&source.1), term(&destination.1)].concat(), - Arith::Lerp { y, z, inner } => [vec![*y, *z], summands(inner)].concat(), - Arith::Common { z, inner, .. } => [vec![*z], summands(inner)].concat(), - } -} - -// ---- The shader's arithmetic ---- - -/// How a lane class's values are held: the color lanes in a `vec4` (lane 3 unread), alpha a -/// scalar. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Lanes { - Vector, - Scalar, -} - -impl Lanes { - fn floats(self) -> Form { - Form { - held: Held::Float(FloatFmt::F32), - lanes: match self { - Lanes::Vector => 4, - Lanes::Scalar => 1, - }, - } - } -} - -/// The `vec4`s a blend reads: the source, the destination, and the blend color's reads where the -/// blend reads them; the function's math; and the second source where the blend reads it -/// ([`Atom::S1`]). -struct Inputs { - s: Value, - d: Value, - /// The blend color as alpha's `BlendAlpha` reads it, its one minus as `OneMinusBlendColor` - /// reads it, and the color as the color lanes' `BlendColor` reads it. - constant: Option<(Value, Value, Value)>, - math: BlendMath, - s1: Option, - /// The arithmetic every rounding is to ([`BlendArith`]). - arith: BlendArith, -} - -/// The values of one lane class, each node computed once. -struct Class<'a> { - inputs: &'a Inputs, - lanes: Lanes, - nodes: Vec<(Node, Value)>, - /// The class reads `BlendColor` and `OneMinusBlendColor` both, so its one minus is of - /// `BlendColor`'s read. - one_minus_of_read: bool, -} - -impl<'a> Class<'a> { - /// The class of `lanes` computing `a` over `inputs`. - fn of(inputs: &'a Inputs, lanes: Lanes, a: &Arith) -> Self { - let n = nodes(a); - Class { - inputs, - lanes, - nodes: Vec::new(), - one_minus_of_read: n.contains(&Node::Atom(Atom::C)) - && n.contains(&Node::OneMinus(Atom::C)), - } - } - - /// `v` (a `vec4`) as this class holds it: the vector, or its lane 3. - fn own(&self, fb: &mut FunctionBuilder<'_>, v: Value) -> BResult { - match self.lanes { - Lanes::Vector => Ok(v), - Lanes::Scalar => fb.composite_extract(v, &[3]), - } - } - - /// Lane 3 of `v` (a `vec4`), in every lane of this class. - fn splat(&self, fb: &mut FunctionBuilder<'_>, v: Value) -> BResult { - match self.lanes { - Lanes::Vector => fb.vector_shuffle(v, v, &[3, 3, 3, 3]), - Lanes::Scalar => fb.composite_extract(v, &[3]), - } - } - - fn constant(&self) -> BResult<(Value, Value, Value)> { - self.inputs - .constant - .ok_or(BuildError::Type(TypeRule::FunctionSignature)) - } - - fn atom(&mut self, fb: &mut FunctionBuilder<'_>, a: Atom) -> BResult { - let i = self.inputs; - match a { - Atom::S => self.own(fb, i.s), - Atom::Sa => self.splat(fb, i.s), - Atom::D => self.own(fb, i.d), - Atom::Da => self.splat(fb, i.d), - Atom::C => { - let (_, _, direct) = self.constant()?; - self.own(fb, direct) - } - Atom::Ca => { - let (c, _, _) = self.constant()?; - self.splat(fb, c) - } - Atom::S1 | Atom::S1a => { - let s1 = i.s1.ok_or(BuildError::Type(TypeRule::FunctionSignature))?; - match a { - Atom::S1 => self.own(fb, s1), - _ => self.splat(fb, s1), - } - } - } - } - - /// `h(1 - x)` of `half` `x`: `1 - x` is exact in `f32` but for `|x|` below `2^-13`, where its - /// rounding stays clear of a `half` midpoint, so it rounds once. - fn one_minus(&mut self, fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { - let f = self.lanes.floats(); - let one = fsplat(fb, f, 1.0)?; - if self.inputs.arith == BlendArith::Float { - return fb.binary_no_contraction(BinOp::FSub, one, x); - } - let m = fb.binary(BinOp::FSub, one, x)?; - half_of(fb, f, m) - } - - /// `x · y`: in `float` arithmetic rounded to `float` on its own, never fused into a sum, its - /// zero signed on the bits ([`signed_product`]); a product of two `half`s is exact in `f32`. - fn mul(&self, fb: &mut FunctionBuilder<'_>, x: Value, y: Value) -> BResult { - match self.inputs.arith { - BlendArith::Float => signed_product(fb, self.lanes.floats(), x, y), - BlendArith::Half => fb.binary(BinOp::FMul, x, y), - } - } - - fn node(&mut self, fb: &mut FunctionBuilder<'_>, n: Node) -> BResult { - if let Some(&(_, v)) = self.nodes.iter().find(|(m, _)| *m == n) { - return Ok(v); - } - let f = self.lanes.floats(); - let v = match n { - Node::Zero => fsplat(fb, f, 0.0)?, - Node::One => fsplat(fb, f, 1.0)?, - Node::Atom(a) => self.atom(fb, a)?, - // Under fast math the precomputed one minus, but beside `BlendColor` in its class (a - // 16-bit float attachment's difference, [`constant_difference`]) the one minus of - // `BlendColor`'s read, as below. - Node::OneMinus(Atom::C) - if self.inputs.math == BlendMath::Fast && !self.one_minus_of_read => - { - let (_, m, _) = self.constant()?; - self.own(fb, m)? - } - Node::OneMinus(Atom::Ca) if self.inputs.math == BlendMath::Fast => { - let (_, m, _) = self.constant()?; - self.splat(fb, m)? - } - // The blend color's one minus reads the clamped color, but beside `BlendColor` in its - // class `BlendColor`'s read. - Node::OneMinus(Atom::C) => { - let (c, _, direct) = self.constant()?; - let x = match self.one_minus_of_read { - true => self.own(fb, direct)?, - false => self.own(fb, c)?, - }; - self.one_minus(fb, x)? - } - Node::OneMinus(a) => { - let x = self.atom(fb, a)?; - self.one_minus(fb, x)? - } - Node::Saturate => { - let sa = self.atom(fb, Atom::Sa)?; - let da = self.atom(fb, Atom::Da)?; - let m = self.one_minus(fb, da)?; - metal_min(fb, f, sa, m)? - } - }; - self.nodes.push((n, v)); - Ok(v) - } - - /// `x` times the small integer `c` (exact). - fn scaled(&self, fb: &mut FunctionBuilder<'_>, c: i8, x: Value) -> BResult { - match c { - 1 => Ok(x), - -1 => fb.unary(UnOp::FNegate, x), - c => { - let k = fsplat(fb, self.lanes.floats(), f64::from(c))?; - fb.binary(BinOp::FMul, x, k) - } - } - } - - fn round(&self, fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { - match self.inputs.arith { - // Every `float` operation here is rounded already. - BlendArith::Float => Ok(x), - BlendArith::Half => half_of(fb, self.lanes.floats(), x), - } - } - - /// `h(a · b + c)`: of `half` values exactly ([`half_sum`]); in `float` arithmetic correctly - /// rounded ([`float_fma_exact`]). - fn fma(&self, fb: &mut FunctionBuilder<'_>, [a, b, c]: [Value; 3]) -> BResult { - let f = self.lanes.floats(); - if self.inputs.arith == BlendArith::Float { - return float_fma_exact(fb, f, a, b, c); - } - let s = half_sum(fb, f.with(Held::Float(FloatFmt::Half)), a, b, c)?; - half_of(fb, f, s) - } - - /// `sign · operand`, and the factor, of `(sign, term)`. - fn signed( - &mut self, - fb: &mut FunctionBuilder<'_>, - (sign, t): (i8, Term), - ) -> BResult<[Value; 2]> { - let x = self.atom(fb, t.0)?; - let x = self.scaled(fb, sign, x)?; - let f = self.node(fb, t.1)?; - Ok([x, f]) - } - - /// The value of inner sum `inner`: one summand as it is, more added in order, each addition - /// rounded. - fn inner(&mut self, fb: &mut FunctionBuilder<'_>, inner: &[Summand]) -> BResult { - let f = self.lanes.floats(); - let mut acc: Option = None; - for &(c, k) in inner { - let x = match k { - None => fsplat(fb, f, f64::from(c))?, - Some(n) => { - let v = self.node(fb, n)?; - self.scaled(fb, c, v)? - } - }; - acc = Some(match acc { - None => x, - Some(a) => { - let one = fsplat(fb, f, 1.0)?; - self.fma(fb, [a, one, x])? - } - }); - } - match acc { - Some(v) => Ok(v), - None => fsplat(fb, f, 0.0), - } - } - - fn eval(&mut self, fb: &mut FunctionBuilder<'_>, a: &Arith) -> BResult { - match a { - Arith::MinMax { max, source } => { - let d = match self.lanes { - Lanes::Vector => Atom::D, - Lanes::Scalar => Atom::Da, - }; - let s = self.atom(fb, *source)?; - let d = self.atom(fb, d)?; - let op = match max { - true => GlslOp::FMax, - false => GlslOp::FMin, - }; - fb.glsl(op, &[s, d]) - } - Arith::Zero => fsplat(fb, self.lanes.floats(), 0.0), - Arith::Term { sign, term } => self.product(fb, (*sign, *term)), - Arith::Fused { product, addend } => { - let [x, f] = self.signed(fb, *product)?; - let a = self.atom(fb, addend.1 .0)?; - let a = self.scaled(fb, addend.0, a)?; - self.fma(fb, [x, f, a]) - } - Arith::Lerp { y, z, inner } => { - let i = self.inner(fb, inner)?; - let y = self.node(fb, *y)?; - let z = self.node(fb, *z)?; - self.fma(fb, [z, i, y]) - } - Arith::Common { z, inner } => { - let i = self.inner(fb, inner)?; - let z = self.node(fb, *z)?; - // A product of two `half`s is exact in `f32`. - let p = self.mul(fb, z, i)?; - self.round(fb, p) - } - Arith::Contracted { rounded, fused } => { - let [x, f] = self.signed(fb, *rounded)?; - let p = self.mul(fb, x, f)?; - let r = self.round(fb, p)?; - let [x, f] = self.signed(fb, *fused)?; - self.fma(fb, [x, f, r]) - } - Arith::Rounded { - source, - destination, - } => { - let s = self.product(fb, *source)?; - let d = self.product(fb, *destination)?; - let one = fsplat(fb, self.lanes.floats(), 1.0)?; - self.fma(fb, [s, one, d]) - } - } - } - - /// `h(sign · operand · factor)` of `(sign, term)`: the operand alone where the factor is one; - /// a product of two `half`s is exact in `f32`. - fn product(&mut self, fb: &mut FunctionBuilder<'_>, (sign, t): (i8, Term)) -> BResult { - let [x, f] = self.signed(fb, (sign, t))?; - match t.1 { - Node::One => Ok(x), - _ => { - let p = self.mul(fb, x, f)?; - self.round(fb, p) - } - } - } -} - -/// Metal's `min(x, y)` in `SourceAlphaSaturated` (lanes of form `f`): a NaN operand gives the other, -/// and two zeros `+0` (a 16-bit float attachment's blends, every lane of -/// `min(sa, 1 - da)` where `sa` is `-0` beside the `+0` of a destination alpha of one, or either a -/// NaN, under safe math; under fast math the same rule leaves no lane of `RGBA16Float` but a -/// zero's sign off Metal's, and fewer of those than the device's `FMin` of `-0` first). The -/// device's `FMin` is the minimum of two numbers, its answer for a NaN or a zero's sign the -/// device's own (Vulkan leaves both undefined), so those lanes are decided on the bits and a -/// select. -fn metal_min(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BResult { - let u = crate::lower::arith::narrow::u32_form(f); - let ut = ty(fb, u)?; - let m = fb.glsl(GlslOp::FMin, &[x, y])?; - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let infinity = splat(fb, u, 0x7F80_0000)?; - let zero = splat(fb, u, 0)?; - let either = fb.binary(BinOp::BitwiseOr, xb, yb)?; - let either = fb.binary(BinOp::BitwiseAnd, either, magnitude)?; - let zeros = fb.binary(BinOp::IEqual, either, zero)?; - let plus = fsplat(fb, f, 0.0)?; - let m = fb.select(zeros, plus, m)?; - let xm = fb.binary(BinOp::BitwiseAnd, xb, magnitude)?; - let x_nan = fb.binary(BinOp::UGreaterThan, xm, infinity)?; - let m = fb.select(x_nan, y, m)?; - let ym = fb.binary(BinOp::BitwiseAnd, yb, magnitude)?; - let y_nan = fb.binary(BinOp::UGreaterThan, ym, infinity)?; - fb.select(y_nan, x, m) -} - -/// `x · y` (`float` lanes of form `f`) rounded to `float` on its own (`NoContraction`), a zero -/// product taking the sign IEEE 754 gives it (the factors' signs differing), put on the bits as an -/// integer: SPIRV-Cross renders a `NoContraction` `OpFMul` as `fma(x, y, 0)`, whose zero is `+0` -/// for a `-0` product (MoltenVK; see `fma::half_sum`), and a module without -/// `SignedZeroInfNanPreserve` lets the device ignore the sign of a zero. -fn signed_product(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, y: Value) -> BResult { - let p = fb.binary_no_contraction(BinOp::FMul, x, y)?; - let u = crate::lower::arith::narrow::u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let yb = fb.convert(ConvOp::Bitcast, y, ut)?; - let pb = fb.convert(ConvOp::Bitcast, p, ut)?; - let mag = splat(fb, u, 0x7FFF_FFFF)?; - let sign = splat(fb, u, 0x8000_0000)?; - let z = splat(fb, u, 0)?; - let m = fb.binary(BinOp::BitwiseAnd, pb, mag)?; - let zero = fb.binary(BinOp::IEqual, m, z)?; - let s = fb.binary(BinOp::BitwiseXor, xb, yb)?; - let s = fb.binary(BinOp::BitwiseAnd, s, sign)?; - let w = fb.select(zero, s, pb)?; - fb.convert(ConvOp::Bitcast, w, ft) -} - -/// `s` (a `vec4`) clamped: its color lanes to `(lo, hi)`, alpha to `[0, 1]`, a NaN to the low -/// end. -pub(super) fn clamped( - fb: &mut FunctionBuilder<'_>, - s: Value, - (lo, hi): (f32, f32), -) -> BResult { - let low = per_lane_f(fb, [lo, lo, lo, 0.0])?; - let high = per_lane_f(fb, [hi, hi, hi, 1.0])?; - let nan = fb.unary(UnOp::IsNan, s)?; - let s = fb.select(nan, low, s)?; - fb.glsl(GlslOp::FClamp, &[s, low, high]) -} - -/// The arithmetic Metal blends a 16-bit float attachment in: the type of the function's output -/// (a `half4` output's blend rounds each step to `half`, a `float4` one's to -/// `float`, and the result converts to `half` as Metal's unblended write of a `float` does). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BlendArith { - /// A `half4` output: each rounding is to `half`, nearest even. - Half, - /// A `float4` output: each rounding is to `float`, nearest even, and the result is a `float`, - /// which the caller converts to the format. - Float, -} - -/// Metal's blend `b` ([`Blend::unorm8`]) of a four-lane output `s` (a `vec4` of `f32`: a `half4` -/// output's `half`s, or a `float4` one) over `texel`, the 8-bit unorm attachment's texel as the -/// storage image reads it (a `vec4` of `f32`, each channel its code over 255; a channel the format -/// lacks reads 0, alpha 1), in `arith`: a `vec4` of `f32` holding each blended lane, a `half` -/// (`BlendArith::Half`) or a `float` (`BlendArith::Float`), which the caller stores by the -/// device's conversion (`PrecisionNote::DeviceColorConversion`). Metal clamps the output to `[0, 1]` -/// first, a NaN to 0, every lane ([`clamped`]), and reads the destination as its code over 255 -/// correctly rounded to the arithmetic's type ([`unorm8_tile_value`]), the value a fetch reads. -/// `color`, the encoder's blend color (a `uvec4` of its `f32`s' bits, `PushField::HalfBlendColor`, -/// where `b` reads it, [`Blend::reads_constant`]), is what `BlendColor` reads, clamped to `[0, 1]` -/// and rounded to `half` in `half` arithmetic (blend colors past both ends of every channel), and -/// `OneMinusBlendColor` reads the one minus of that read under either math, `h(1 - h(c))` -/// (`f(1 - c)` in `float`). A NaN blend color, which no probe drew, reads 0. -pub fn blend_unorm8( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - arith: BlendArith, - (s, texel): (Value, Value), - color: Option, -) -> BResult { - let s = clamped(fb, s, (0.0, 1.0))?; - let d = unorm8_tile_value(fb, texel, arith)?; - clamped_blend(fb, b, arith, (s, None, d), color) -} - -/// Blend `b` of the clamped output `s` (and second source `s1`, where `b` reads it) over the -/// destination `d`, `vec4`s of `f32` in `arith`, the blend color `color` clamped to `[0, 1]` (a -/// NaN 0) and rounded to `arith`, and its one minus that of the read: [`blend_unorm8`]'s -/// arithmetic. -fn clamped_blend( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - arith: BlendArith, - (s, s1, d): (Value, Option, Value), - color: Option, -) -> BResult { - let f = floats(); - let constant = match color { - Some(words) => { - let ft = ty(fb, f)?; - let c = fb.convert(ConvOp::Bitcast, words, ft)?; - let zero = fsplat(fb, f, 0.0)?; - let one = fsplat(fb, f, 1.0)?; - let nan = fb.unary(UnOp::IsNan, c)?; - let c = fb.select(nan, zero, c)?; - let c = fb.glsl(GlslOp::FClamp, &[c, zero, one])?; - let c = match arith { - BlendArith::Half => half_of(fb, f, c)?, - BlendArith::Float => c, - }; - let m = fb.binary_no_contraction(BinOp::FSub, one, c)?; - let m = match arith { - BlendArith::Half => half_of(fb, f, m)?, - BlendArith::Float => m, - }; - Some((c, m, c)) - } - None => None, - }; - let inputs = Inputs { - s, - d, - constant, - math: b.math, - s1, - arith, - }; - lanes(fb, b, &inputs) -} - -/// Metal's read of each lane of `texel` (a `vec4` of `f32`, an 8-bit unorm texel as the storage -/// image reads it, `c / 255` for each code `c`, Vulkan's conversion of a normalized fixed-point -/// value) in `arith`: the code `c` (the lane times 255, rounded to the nearest integer, which any -/// decode within half a code of `c / 255` gives) over 255, correctly rounded to `float` -/// ([`div_exact`](crate::lower::arith::exact_division::div_exact)) for `BlendArith::Float`, and to -/// `half` for `BlendArith::Half` (the M3 Max under macOS 27.0.1: a fetch of every -/// code reads `h(c / 255)` as a `half4` and `f(c / 255)` as a `float4`; the blend reads the same). -/// The `half` takes no exact quotient: `c / 255` repeats the byte `c` without end, which keeps it -/// at least `2^-9` of a `half`'s step from a `half` midpoint (at least `2^-20` of the value, every -/// nonzero `c / 255` being a normal `half`), and `c` times the `f32` nearest `1 / 255`, one -/// correctly rounded `OpFMul` (Vulkan's precision table), lies within `2^-23` of `c / 255` -/// relatively (that constant's error and the product's rounding, `2^-24` each), so it rounds to -/// the same `half` ([`half_of`]); every code is checked -/// (`lower::arith::tests::blend8::a_code_s_half_is_its_product_s`). -pub fn unorm8_tile_value( - fb: &mut FunctionBuilder<'_>, - texel: Value, - arith: BlendArith, -) -> BResult { - let f = floats(); - let k255 = fsplat(fb, f, 255.0)?; - let scaled = fb.binary(BinOp::FMul, texel, k255)?; - let rounded = fb.glsl(GlslOp::RoundEven, &[scaled])?; - match arith { - BlendArith::Float => { - let u = crate::lower::arith::narrow::u32_form(f); - let ut = ty(fb, u)?; - let code = fb.convert(ConvOp::ConvertFToU, rounded, ut)?; - crate::lower::arith::exact_division::div_exact(fb, u, code, 255) - } - BlendArith::Half => { - let inverse = fsplat(fb, f, f64::from(1.0f32 / 255.0))?; - let v = fb.binary_no_contraction(BinOp::FMul, rounded, inverse)?; - half_of(fb, f, v) - } - } -} - -/// `x` (`f32` lanes of form `f`) rounded to `half`, nearest even, half denormals kept, an infinity -/// from 65520 up: each rounding of Metal's blend arithmetic. Where the module rounds to `half` by -/// the device's conversion under the 16-bit float controls ([`QuantizeForm::Controlled`]: the -/// profile has `shaderFloat16`, `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` -/// for 16 bits; [`narrow::quantize_form`]), that conversion and -/// its widening ([`narrow::round`]): two instructions, Metal's `half(float)` by the Vulkan spec -/// (conversions are correctly rounded, to nearest even under `RoundingModeRTE`, denormals kept -/// under `DenormPreserve`, zero signs and infinities under `SignedZeroInfNanPreserve`), as the -/// module's own `half` results round on such a profile (exact, no note). Elsewhere the integer -/// sequence ([`f32_to_half`]), about fifty instructions, the same on every device. The two agree on -/// every `x` but a NaN's bits, which the conversion leaves to the device: the blends clamp a NaN -/// source to zero, and a 16-bit float blend stores every NaN as Metal's own. -pub fn half_of(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - match fb.module().quantize_form() { - QuantizeForm::Controlled => narrow::round(fb, f.with(Held::Float(FloatFmt::Half)), x), - _ => f32_to_half(fb, f, x, HalfRounding::NearestEven), - } -} - -/// The `vec4` of blend `b`'s lanes over `inputs`: the color class's three, and alpha's, each -/// lane the write does not store `d`'s. -fn lanes(fb: &mut FunctionBuilder<'_>, b: &Blend, inputs: &Inputs) -> BResult { - let f = floats(); - let d = inputs.d; - let color = match &b.color { - Some(a) => Class::of(inputs, Lanes::Vector, a).eval(fb, a)?, - None => d, - }; - let alpha = match &b.alpha { - Some(a) => Some(Class::of(inputs, Lanes::Scalar, a).eval(fb, a)?), - None => None, - }; - let ft = ty(fb, f)?; - let mut lanes = Vec::with_capacity(4); - for k in 0..3u32 { - lanes.push(fb.composite_extract(color, &[k])?); - } - lanes.push(match alpha { - Some(a) => a, - None => fb.composite_extract(d, &[3])?, - }); - fb.composite_construct(ft, &lanes) -} diff --git a/crates/metal2vulkan/src/lower/arith/extended_range/tests.rs b/crates/metal2vulkan/src/lower/arith/extended_range/tests.rs index 1b6b6a63d..2e11c7a21 100644 --- a/crates/metal2vulkan/src/lower/arith/extended_range/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/extended_range/tests.rs @@ -3,16 +3,14 @@ //! (the device's `Pow`, which the interpreter does not model) checked in the module and against //! Metal's tables. -use super::blend::{native, NativeBlend}; -use super::{decode, encode, encode_keeping, tile_value}; -use crate::error::Error; +use super::{decode, encode, tile_value}; use crate::lower::arith::{FloatFmt, Form, Held}; use crate::lower::stage_io::extended_color::bfloat_output; use crate::metal::format::extended_srgb::{SRGB_DECODE_STEPS, SRGB_ENCODE_FIRST}; use crate::metal::format::padded_srgb::{R10X6_SRGB_ENCODE_FIRST, RG10X12_SRGB_WRITE_CODES}; use crate::metal::format::ExtendedRange; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, TextureWriteRoundingMode}; -use crate::pipeline::lower_inputs::{BlendEquation, ExtendedRangeColor}; +use crate::metal::TextureWriteRoundingMode; +use crate::pipeline::lower_inputs::ExtendedRangeColor; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; @@ -34,30 +32,11 @@ enum Op { Encode, /// The tile value of a raw texel. Tile, - /// The blend under an equation of a write of the channels of a mask (`blend::native`) of a - /// source (words 4 to 7, `f32` bits) over the tile value of a raw texel (words 0 to 3), the - /// blend color words 8 to 11 (`f32` bits, as the encoder set it), the second source words 12 - /// to 15 (`f32` bits). - Blend(BlendEquation, ColorWriteMask), /// A render pass's store of a fragment function's output (`vec4` of `f32` bits, of the /// format, `half` values held as `f32`) to a bfloat attachment of a pipeline at /// `textureWriteRoundingMode` `NearestEven` where the flag is set /// (`stage_io::extended_color::bfloat_output`). Output(bool, FloatFmt), - /// The encode of a `vec4` of `f32` bits (words 4 to 7) over a raw texel (words 0 to 3) that - /// keeps its channels the flags name, red first ([`encode_keeping`]). - Keep([bool; 4]), -} - -impl Op { - /// The words an invocation reads. - fn words(self) -> u32 { - match self { - Op::Blend(..) => 16, - Op::Keep(_) => 8, - _ => 4, - } - } } fn slot(index: u32) -> ResourceSlot { @@ -119,9 +98,9 @@ fn kernel(form: ExtendedRange, op: Op) -> BResult { let gid = f.module().global_value(id)?; let gid = f.load(gid, MemAccess::default())?; let i = f.composite_extract(gid, &[0])?; - let mut lanes = Vec::with_capacity(8); - for k in 0..op.words() { - let at = word(&mut f, input, (i, op.words()), k)?; + let mut lanes = Vec::with_capacity(4); + for k in 0..4 { + let at = word(&mut f, input, (i, 4), k)?; lanes.push(f.load(at, MemAccess::default())?); } let x = f.composite_construct(uvec4, &lanes[..4])?; @@ -155,22 +134,6 @@ fn kernel(form: ExtendedRange, op: Op) -> BResult { }; bfloat_output(&mut f, e, lanes, v)? } - Op::Keep(kept) => { - let v = f.composite_construct(uvec4, &lanes[4..8])?; - let v = f.convert(ConvOp::Bitcast, v, vec4)?; - encode_keeping(&mut f, form, v, (x, kept))? - } - Op::Blend(eq, mask) => { - let b = NativeBlend::of(&eq, mask).expect("a blend"); - let s = f.composite_construct(uvec4, &lanes[4..8])?; - let s = f.convert(ConvOp::Bitcast, s, vec4)?; - let c = f.composite_construct(uvec4, &lanes[8..12])?; - let s1 = f.composite_construct(uvec4, &lanes[12..16])?; - let s1 = f.convert(ConvOp::Bitcast, s1, vec4)?; - let d = tile_value(&mut f, form, x)?; - let v = native(&mut f, &b, (s, Some(s1), d), Some(c))?; - f.convert(ConvOp::Bitcast, v, uvec4)? - } }; for k in 0..4u32 { let c = f.composite_extract(out, &[k])?; @@ -187,8 +150,7 @@ fn kernel(form: ExtendedRange, op: Op) -> BResult { b.finalize() } -fn run(form: ExtendedRange, op: Op, lanes: &[[u32; N]]) -> Vec<[u32; 4]> { - assert_eq!(N as u32, op.words()); +fn run(form: ExtendedRange, op: Op, lanes: &[[u32; 4]]) -> Vec<[u32; 4]> { let m = kernel(form, op).expect("kernel"); let bytes: Vec = lanes .iter() @@ -572,326 +534,6 @@ fn every_code_reads_its_tile_value() { } } -/// A splitmix64 stream. -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - /// A source lane: mostly an `f32` off the `half` grid in `[-1.5, 2.5)`, sometimes a NaN, an - /// infinity or a value far past the format's range. - fn source(&mut self) -> f32 { - match self.next() % 16 { - 0 => f32::NAN, - 1 => f32::INFINITY, - 2 => f32::NEG_INFINITY, - 3 => 1e30, - _ => (self.next() >> 40) as f32 / (1u64 << 24) as f32 * 4.0 - 1.5, - } - } -} - -/// Every blend factor. -const FACTORS: [BlendFactor; 19] = [ - BlendFactor::Zero, - BlendFactor::One, - BlendFactor::SourceColor, - BlendFactor::OneMinusSourceColor, - BlendFactor::SourceAlpha, - BlendFactor::OneMinusSourceAlpha, - BlendFactor::DestinationColor, - BlendFactor::OneMinusDestinationColor, - BlendFactor::DestinationAlpha, - BlendFactor::OneMinusDestinationAlpha, - BlendFactor::SourceAlphaSaturated, - BlendFactor::BlendColor, - BlendFactor::OneMinusBlendColor, - BlendFactor::BlendAlpha, - BlendFactor::OneMinusBlendAlpha, - BlendFactor::Source1Color, - BlendFactor::OneMinusSource1Color, - BlendFactor::Source1Alpha, - BlendFactor::OneMinusSource1Alpha, -]; - -/// Every blend operation. -const OPERATIONS: [BlendOperation; 5] = [ - BlendOperation::Add, - BlendOperation::Subtract, - BlendOperation::ReverseSubtract, - BlendOperation::Min, - BlendOperation::Max, -]; - -/// The device's blend (`blend::native`) of source `s`, second source `s1` and blend color `c` -/// over tile value `d` into a padded form, storing the channels `mask`: each class's `S·Fs op D·Fd` -/// in `f32`, in the equation's order, each factor, product and sum rounded once to `f32`, a factor -/// of one its operand; `Min` and `Max` of the source and the destination; a lane the mask does not -/// store `d`'s. -fn native_model( - eq: &BlendEquation, - mask: ColorWriteMask, - (s, s1, c): ([f32; 4], [f32; 4], [f32; 4]), - d: [f32; 4], -) -> [f32; 4] { - use BlendFactor as F; - let factor = |f: BlendFactor, alpha: bool, k: usize| -> Option { - Some(match f { - F::Zero => 0.0, - F::One => return None, - F::SourceAlphaSaturated if alpha => return None, - F::SourceColor => s[k], - F::OneMinusSourceColor => 1.0 - s[k], - F::SourceAlpha => s[3], - F::OneMinusSourceAlpha => 1.0 - s[3], - F::DestinationColor => d[k], - F::OneMinusDestinationColor => 1.0 - d[k], - F::DestinationAlpha => d[3], - F::OneMinusDestinationAlpha => 1.0 - d[3], - F::SourceAlphaSaturated => s[3].min(1.0 - d[3]), - F::BlendColor => c[k], - F::OneMinusBlendColor => 1.0 - c[k], - F::BlendAlpha => c[3], - F::OneMinusBlendAlpha => 1.0 - c[3], - F::Source1Color => s1[k], - F::OneMinusSource1Color => 1.0 - s1[k], - F::Source1Alpha => s1[3], - F::OneMinusSource1Alpha => 1.0 - s1[3], - F::Unspecialized => unreachable!("no placeholder is drawn"), - }) - }; - let class = - |(fs, fd, op): (BlendFactor, BlendFactor, BlendOperation), alpha: bool, k: usize| { - let source = factor(fs, alpha, k).map_or(s[k], |f| s[k] * f); - let destination = factor(fd, alpha, k).map_or(d[k], |f| d[k] * f); - match op { - BlendOperation::Min => s[k].min(d[k]), - BlendOperation::Max => s[k].max(d[k]), - BlendOperation::Subtract => source - destination, - BlendOperation::ReverseSubtract => destination - source, - _ => source + destination, - } - }; - let color = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ] - .into_iter() - .any(|c| mask.contains(c)); - let rgb = (eq.source_rgb, eq.destination_rgb, eq.rgb_operation); - let a = (eq.source_alpha, eq.destination_alpha, eq.alpha_operation); - std::array::from_fn(|k| match k { - 3 if mask.contains(ColorWriteMask::ALPHA) => class(a, true, 3), - 3 => d[3], - _ if color => class(rgb, false, k), - _ => d[k], - }) -} - -/// A blend into a linear padded attachment is the device's arithmetic (`blend::native`): over -/// sources off the `half` grid, NaNs, infinities and values past the range, random texels, blend -/// colors and second sources, every factor as each of the four factors and every operation for -/// color and for alpha, under every class of write mask, each lane holds the `f32` model's bits -/// ([`native_model`]): `S·Fs op D·Fd` in the equation's order, nothing clamped and nothing rounded -/// to `half` between the steps. Metal's own forms (its lerps and common factors, its fused pairs -/// and a `half` rounding after each step) miss these bits at most lanes. -#[test] -fn every_blend_is_the_devices_arithmetic() { - let masks = [ - ColorWriteMask::ALL, - ColorWriteMask::RED - .union(ColorWriteMask::GREEN) - .union(ColorWriteMask::BLUE), - ColorWriteMask::ALPHA, - ColorWriteMask::GREEN, - ]; - let mut rng = Rng(0x5EED_B1E4D); - let mut checked = 0usize; - for (fi, form) in PADDED.into_iter().enumerate() { - for (i, &f) in FACTORS.iter().enumerate() { - let k = i + fi; - let eq = BlendEquation { - source_rgb: f, - destination_rgb: FACTORS[(k * 7 + 3) % FACTORS.len()], - rgb_operation: OPERATIONS[k % OPERATIONS.len()], - source_alpha: FACTORS[(k * 5 + 1) % FACTORS.len()], - destination_alpha: f, - alpha_operation: OPERATIONS[(k + 2) % OPERATIONS.len()], - }; - let mask = masks[k % masks.len()]; - let lanes: Vec<[u32; 16]> = (0..24) - .map(|_| { - let codes: [u32; 4] = std::array::from_fn(|c| match c { - 3 if !matches!(form, ExtendedRange::Bgra10 { .. }) => { - (rng.next() % 256) as u32 - } - _ => (rng.next() % 1024) as u32, - }); - let texel = raw(form, codes, rng.next() as u32); - let mut w = [0u32; 16]; - w[..4].copy_from_slice(&texel); - for x in w[4..].iter_mut() { - *x = rng.source().to_bits(); - } - w - }) - .collect(); - let tiles = run( - form, - Op::Tile, - &lanes - .iter() - .map(|w| [w[0], w[1], w[2], w[3]]) - .collect::>(), - ); - let got = run(form, Op::Blend(eq, mask), &lanes); - for ((w, tile), got) in lanes.iter().zip(tiles).zip(got) { - let f = |a: &[u32]| -> [f32; 4] { std::array::from_fn(|k| f32::from_bits(a[k])) }; - let d = f(&tile); - let want = native_model(&eq, mask, (f(&w[4..8]), f(&w[12..16]), f(&w[8..12])), d); - let same = (0..4).all(|k| { - want[k].to_bits() == got[k] - || (want[k].is_nan() && f32::from_bits(got[k]).is_nan()) - }); - assert!( - same, - "{form:?} {eq:?} {mask:?}: source {:?}, tile {d:?}: {:?} where the device's \ - arithmetic gives {want:?}", - f(&w[4..8]), - got.map(f32::from_bits) - ); - checked += 1; - } - } - } - assert_eq!(checked, PADDED.len() * FACTORS.len() * 24); -} - -/// The linear padded forms. -const PADDED: [ExtendedRange; 2] = [ExtendedRange::R10X6, ExtendedRange::Rg10X12]; - -/// Every code of a linear padded form reads its tile value, a blend's destination: the device's -/// decode (`float(c)` times the `f32` nearest `1 / 1023`) narrowed to `half`, nearest even, blue 0 -/// and alpha 1, whatever the low 6 bits hold. Code 1023 is one: a padded form's tile holds every -/// code, where an extended-range form's holds none above 1022. -#[test] -fn every_padded_code_reads_its_tile_value() { - let value = |c: u32| c as f32 * reciprocal(1023.0); - for form in PADDED { - let lanes: Vec<[u32; 4]> = (0..1024u32) - .map(|c| raw(form, [c, 1023 - c, 0, 0], c * 13)) - .collect(); - let got = run(form, Op::Tile, &lanes); - for (c, g) in (0..1024u32).zip(&got) { - let green = match form { - ExtendedRange::Rg10X12 => value(1023 - c), - _ => 0.0, - }; - let want = [value(c), green, 0.0, 1.0].map(|v| to_half(f64::from(v), false).to_bits()); - assert_eq!(*g, want, "{form:?} code {c}"); - } - assert_eq!(f32::from_bits(got[1023][0]), 1.0, "{form:?}"); - } -} - -/// A write to a linear padded form under a mask of some of its channels keeps the others' codes -/// ([`encode_keeping`]): each kept word its code in the top 10 bits, each written word the code of -/// the value (`RoundEven(clamp(v, 0, 1) · 1023)`, a NaN 0), and every word's low 6 bits zero, as -/// Metal's pass stores each word of a tile it writes. -#[test] -fn a_masked_padded_write_keeps_the_other_codes() { - let mut rng = Rng(0x000C_0DE5); - let code = |v: f32| { - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - round_even(f64::from(v * 1023.0)) as u32 - }; - for form in PADDED { - for kept in [[true, false, false, false], [false, true, false, false]] { - let lanes: Vec<[u32; 8]> = (0..256) - .map(|_| { - let old = raw( - form, - [(rng.next() % 1024) as u32, (rng.next() % 1024) as u32, 0, 0], - rng.next() as u32, - ); - let mut w = [0u32; 8]; - w[..4].copy_from_slice(&old); - for x in w[4..].iter_mut() { - *x = rng.source().to_bits(); - } - w - }) - .collect(); - let got = run(form, Op::Keep(kept), &lanes); - for (w, g) in lanes.iter().zip(&got) { - let word = |lane: usize| match kept[lane] { - true => w[lane] >> 6 << 6, - false => code(f32::from_bits(w[4 + lane])) << 6, - }; - let green = match form { - ExtendedRange::Rg10X12 => word(1), - _ => 0, - }; - assert_eq!(*g, [word(0), green, 0, 0], "{form:?} {kept:?} words {w:x?}"); - } - } - } -} - -/// A blend's placeholder factor or operation is refused as the placeholder it is; every other -/// factor and operation is built, under every write mask. -#[test] -fn every_blend_is_built_but_a_placeholder() { - use super::blend::NativeBlend; - for &fs in &FACTORS { - for op in OPERATIONS { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: BlendFactor::OneMinusSourceAlpha, - rgb_operation: op, - source_alpha: BlendFactor::One, - destination_alpha: fs, - alpha_operation: op, - }; - for mask in [ - ColorWriteMask::ALL, - ColorWriteMask::RED, - ColorWriteMask::ALPHA, - ] { - assert!(NativeBlend::of(&eq, mask).is_ok(), "{eq:?} {mask:?}"); - } - } - } - let placeholder = BlendEquation { - source_rgb: BlendFactor::Unspecialized, - destination_rgb: BlendFactor::Zero, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::Zero, - alpha_operation: BlendOperation::Add, - }; - assert!(matches!( - NativeBlend::of(&placeholder, ColorWriteMask::ALL), - Err(Error::InvalidDescriptor(_)) - )); - let op = BlendEquation { - rgb_operation: BlendOperation::Unspecialized, - source_rgb: BlendFactor::One, - ..placeholder - }; - assert!(matches!( - NativeBlend::of(&op, ColorWriteMask::ALL), - Err(Error::InvalidDescriptor(_)) - )); -} - /// A padded 10-bit form reads every 16-bit word as `float(c)` of the code `c` in its top 10 bits /// times the `f32` nearest `1 / 1023` (a `half` result that value narrowed to nearest even), blue /// 0 and alpha 1, whatever the low 6 bits hold (every word; `RG10Unorm_X12_sRGB` reads its codes diff --git a/crates/metal2vulkan/src/lower/arith/fma.rs b/crates/metal2vulkan/src/lower/arith/fma.rs index 3296dc7ec..3c1a944f5 100644 --- a/crates/metal2vulkan/src/lower/arith/fma.rs +++ b/crates/metal2vulkan/src/lower/arith/fma.rs @@ -15,18 +15,14 @@ //! `RoundingModeRTE`, where Metal's rounds once: noted `PrecisionNote::NativeFma`, as //! [`Route::Native`] is. Every other `half` one takes [`Route::Native`]: the device's `float` //! `Fma` of the operands held in `float`, whose product is exact there, rounded to `half`. -//! -//! An extended-range blend computes its own correctly rounded multiply-adds ([`half_sum`], -//! [`float_fma_exact`]): the blend the device cannot do, in plain arithmetic. use crate::device::DeviceProfile; -use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::narrow::{self, u32_form}; -use crate::lower::arith::ops::{fsplat, splat, ty}; +use crate::lower::arith::legal::{FloatFmt, Form}; +use crate::lower::arith::narrow; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, TypeRule}; use crate::spirv::ids::Value; -use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, Type}; +use crate::spirv::ir::{ConvOp, GlslOp, Type}; /// How a fused multiply-add computes its result. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -153,199 +149,3 @@ fn f16(fb: &mut FunctionBuilder<'_>, lanes: u8, [a, b, c]: [Value; 3]) -> BResul let r = fb.glsl(GlslOp::Fma, &[a, b, c])?; fb.convert(ConvOp::FConvert, r, w) } - -fn bin(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult { - fb.binary(op, a, b) -} - -/// Float arithmetic decorated `NoContraction`: rounded on its own, never fused or regrouped. -fn exact_op(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult { - fb.binary_with(op, a, b, Contraction::Forbidden) -} - -/// `s = x + y` (floats of form `f`) and its rounding error `e`, exactly ([`sum_error`]), for -/// finite `x` and `y` whose sum does not overflow. -fn two_sum(fb: &mut FunctionBuilder<'_>, x: Value, y: Value) -> BResult<(Value, Value)> { - let s = exact_op(fb, BinOp::FAdd, x, y)?; - let e = sum_error(fb, s, x, y)?; - Ok((s, e)) -} - -/// The rounding error of `s`, the sum of `x` and `y` rounded to nearest, exactly (FastTwoSum on -/// the operands ordered by magnitude: `t = s - big` is exact, and so is `small - t`), for finite -/// `x` and `y` whose sum does not overflow. -fn sum_error(fb: &mut FunctionBuilder<'_>, s: Value, x: Value, y: Value) -> BResult { - let ax = fb.glsl(GlslOp::FAbs, &[x])?; - let ay = fb.glsl(GlslOp::FAbs, &[y])?; - let x_big = bin(fb, BinOp::FOrdGreaterThanEqual, ax, ay)?; - let big = fb.select(x_big, x, y)?; - let small = fb.select(x_big, y, x)?; - let t = exact_op(fb, BinOp::FSub, s, big)?; - exact_op(fb, BinOp::FSub, small, t) -} - -/// `s` (floats of form `f`, bits of integer form `u`) moved to round to odd given its exact -/// rounding error `e`: where `e` is nonzero and `s`'s lowest significand bit is clear, the -/// neighbour on `e`'s side, whose lowest bit is set (consecutive encodings alternate it). `s` -/// is then never zero (an inexact sum is not), so the step stays within its sign. A NaN `e` -/// (from an infinite or NaN `s`) leaves `s`. -fn to_odd(fb: &mut FunctionBuilder<'_>, f: Form, u: Form, s: Value, e: Value) -> BResult { - let ut = ty(fb, u)?; - let ft = ty(fb, f)?; - let sb = fb.convert(ConvOp::Bitcast, s, ut)?; - let (zu, one) = (splat(fb, u, 0)?, splat(fb, u, 1)?); - let low = bin(fb, BinOp::BitwiseAnd, sb, one)?; - let even = bin(fb, BinOp::IEqual, low, zu)?; - let zf = fsplat(fb, f, 0.0)?; - let inexact = bin(fb, BinOp::FOrdNotEqual, e, zf)?; - let s_neg = bin(fb, BinOp::FOrdLessThan, s, zf)?; - let e_neg = bin(fb, BinOp::FOrdLessThan, e, zf)?; - // The exact value lies beyond `s` (away from zero) when `e` has `s`'s sign. - let grow = bin(fb, BinOp::LogicalEqual, s_neg, e_neg)?; - let up = bin(fb, BinOp::IAdd, sb, one)?; - let down = bin(fb, BinOp::ISub, sb, one)?; - let moved = fb.select(grow, up, down)?; - let fix = bin(fb, BinOp::LogicalAnd, inexact, even)?; - let r = fb.select(fix, moved, sb)?; - fb.convert(ConvOp::Bitcast, r, ft) -} - -/// The exact `a * b + c` of `half` values held in `float` (form `f`), rounded to odd in -/// `float`. The product `p` (two 11-bit significands, between `2^-48` and `2^32` in magnitude) -/// is exact in `float`, so the device's `Fma` is the exact sum rounded once, `s`, whether it -/// fuses or not; `s`'s exact error is FastTwoSum's on `p` and `c` ([`sum_error`]), and -/// [`to_odd`] keeps the rounding direction. An infinite or NaN `s` (only from such an operand) -/// is `Fma`'s, unmoved, decided on its bits. Rounded to `half` to nearest even, it is the `half` -/// fused multiply-add correctly rounded (an extended-range blend's). -/// -/// Both choices keep the result off two renderings of SPIRV-Cross, which MoltenVK uses (`f7850ba7` -/// lanes 2, 3, and 7): a `NoContraction` `OpFMul` becomes `fma(l, r, 0)`, which answers `+0` for a -/// `-0` product, so `s`'s signed zeros are `Fma`'s, never `p`'s (a zero `p` leaves the error zero); -/// and `OpFOrdNotEqual` becomes the unordered `!=`, true for the NaN error of an infinite `s`, so -/// [`to_odd`]'s move is not taken there. -pub(crate) fn half_sum( - fb: &mut FunctionBuilder<'_>, - f: Form, - a: Value, - b: Value, - c: Value, -) -> BResult { - let wide = f.with(Held::Float(FloatFmt::F32)); - let s = fb.glsl(GlslOp::Fma, &[a, b, c])?; - let p = exact_op(fb, BinOp::FMul, a, b)?; - let e = sum_error(fb, s, p, c)?; - let odd = to_odd(fb, wide, u32_form(f), s, e)?; - let finite = all_finite(fb, wide, &[s])?; - fb.select(finite, odd, s) -} - -/// `a * b + c` of finite `float`s (lanes of form `f`) rounded once to `float`, nearest even, in -/// plain `float` arithmetic, whatever the device's `Fma` fuses: Dekker's exact product -/// `a * b = ph + pl` (each factor split at 12 bits by Veltkamp's constant, every step -/// `NoContraction`), then Boldo and Melquiond's emulation of a fused multiply-add through rounding -/// to odd (IEEE TC 57(4), 2008): `(th, tl) = TwoSum(c, ph)`, `v = RO(tl + pl)` ([`half_sum`]'s -/// odd sum, its product `tl · 1` exact), and `RN(th + v)`. Exact where no part underflows: an -/// extended-range blend of a `float4` output, whose operands are at most 2 in magnitude and whose -/// result is rounded to `half` next, far above a part that small. An infinite or NaN result (an -/// infinite or NaN operand's: the operands lie far below `float`'s overflow) is the device's -/// `Fma`'s, decided on its bits, as [`half_sum`]'s is: an infinity of the exact sum's sign, or a -/// NaN, whose encoding the caller chooses. -/// -/// A zero result has the sign IEEE 754-2008 (6.3) gives a fused multiply-add's exact zero, put on -/// the bits as an integer ([`zero_sign`]). The emulation's own zero has no defined sign: `th + v` -/// adds a `+0` `v` to a `-0` `th` (`-0 · 1 + -0`), whose sum is `+0` under roundTiesToEven; -/// SPIRV-Cross renders the `NoContraction` product `ph` as `fma(a, b, 0)`, a `+0` for a `-0` -/// product ([`half_sum`]); and a module without `SignedZeroInfNanPreserve` lets the device ignore -/// the sign of a zero in any float instruction (Vulkan's Precision and Operation of SPIR-V -/// Instructions). `OpBitcast` keeps the bits, and the integer instructions are exact. -pub(crate) fn float_fma_exact( - fb: &mut FunctionBuilder<'_>, - f: Form, - a: Value, - b: Value, - c: Value, -) -> BResult { - let (ah, al) = veltkamp(fb, f, a)?; - let (bh, bl) = veltkamp(fb, f, b)?; - let ph = exact_op(fb, BinOp::FMul, a, b)?; - let hh = exact_op(fb, BinOp::FMul, ah, bh)?; - let t = exact_op(fb, BinOp::FSub, hh, ph)?; - let hl = exact_op(fb, BinOp::FMul, ah, bl)?; - let t = exact_op(fb, BinOp::FAdd, t, hl)?; - let lh = exact_op(fb, BinOp::FMul, al, bh)?; - let t = exact_op(fb, BinOp::FAdd, t, lh)?; - let ll = exact_op(fb, BinOp::FMul, al, bl)?; - let pl = exact_op(fb, BinOp::FAdd, t, ll)?; - let (th, tl) = two_sum(fb, c, ph)?; - let one = fsplat(fb, f, 1.0)?; - let v = half_sum(fb, f.with(Held::Float(FloatFmt::Half)), tl, one, pl)?; - let r = exact_op(fb, BinOp::FAdd, th, v)?; - let r = zero_sign(fb, f, [a, b, c], r)?; - // An infinite or NaN result, only from such an operand, is the device's `Fma`'s, which IEEE 754 - // gives exactly: the emulation's own steps subtract an infinity from itself there, a NaN. - let s = fb.glsl(GlslOp::Fma, &[a, b, c])?; - let finite = all_finite(fb, f, &[s])?; - fb.select(finite, r, s) -} - -/// `r`, a multiply-add of `a`, `b`, `c` (`float` lanes of form `f`) rounded once, with a zero -/// result given IEEE 754-2008's sign (6.3): where the exact `a · b + c` is zero, a fused -/// multiply-add's zero is the sign of that sum, the product signed by the rules for -/// multiplication, so under roundTiesToEven `-0` only where the product's sign (`a`'s and `b`'s -/// differing) and `c`'s are both negative, and `+0` otherwise: opposite zeros, or a product that -/// `c` cancels, whose signs differ. The test and the sign are on the bits, as integers -/// (`OpBitcast`, `OpBitwiseAnd`, `OpBitwiseXor`, `OpIEqual`, and `OpSelect` of integers), so the -/// sign is the same whatever the device's float modes. -fn zero_sign( - fb: &mut FunctionBuilder<'_>, - f: Form, - [a, b, c]: [Value; 3], - r: Value, -) -> BResult { - let u = u32_form(f); - let (ut, ft) = (ty(fb, u)?, ty(fb, f)?); - let [ab, bb, cb, rb] = [a, b, c, r].map(|x| fb.convert(ConvOp::Bitcast, x, ut)); - let (ab, bb, cb, rb) = (ab?, bb?, cb?, rb?); - let (mag, sign, z) = ( - splat(fb, u, 0x7FFF_FFFF)?, - splat(fb, u, 0x8000_0000)?, - splat(fb, u, 0)?, - ); - let m = bin(fb, BinOp::BitwiseAnd, rb, mag)?; - let zero = bin(fb, BinOp::IEqual, m, z)?; - let p = bin(fb, BinOp::BitwiseXor, ab, bb)?; - let both = bin(fb, BinOp::BitwiseAnd, p, cb)?; - let signed = bin(fb, BinOp::BitwiseAnd, both, sign)?; - let w = fb.select(zero, signed, rb)?; - fb.convert(ConvOp::Bitcast, w, ft) -} - -/// `x`'s high 12 significand bits and the rest, `x = hi + lo` exactly (Veltkamp's split by -/// `2^12 + 1`), for finite `x` far below `float`'s overflow. -fn veltkamp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<(Value, Value)> { - let k = fsplat(fb, f, 4097.0)?; - let t = exact_op(fb, BinOp::FMul, k, x)?; - let u = exact_op(fb, BinOp::FSub, t, x)?; - let hi = exact_op(fb, BinOp::FSub, t, u)?; - let lo = exact_op(fb, BinOp::FSub, x, hi)?; - Ok((hi, lo)) -} - -/// Whether every lane of `float` values `xs` (form `f`) is finite, from their bits (exact -/// whatever the device does with infinities and NaNs). -fn all_finite(fb: &mut FunctionBuilder<'_>, f: Form, xs: &[Value]) -> BResult { - let u = u32_form(f); - let ut = ty(fb, u)?; - let exp = splat(fb, u, 0x7F80_0000)?; - let mut all: Option = None; - for x in xs { - let b = fb.convert(ConvOp::Bitcast, *x, ut)?; - let e = bin(fb, BinOp::BitwiseAnd, b, exp)?; - let fin = bin(fb, BinOp::INotEqual, e, exp)?; - all = Some(match all { - Some(v) => bin(fb, BinOp::LogicalAnd, v, fin)?, - None => fin, - }); - } - all.ok_or(BuildError::Type(TypeRule::FunctionSignature)) -} diff --git a/crates/metal2vulkan/src/lower/arith/output_precision.rs b/crates/metal2vulkan/src/lower/arith/output_precision.rs index b24806b94..f3264de12 100644 --- a/crates/metal2vulkan/src/lower/arith/output_precision.rs +++ b/crates/metal2vulkan/src/lower/arith/output_precision.rs @@ -22,15 +22,9 @@ //! (`color_writes::stores_output`): one whose write mask stores none holds nothing the output could //! differ by. A module naming no math mode keeps the note at any attachment: what Metal's compiler //! does there was not measured. -//! -//! **A blended extended-range output** ([`note_extended_range_sources`]): the function blends it by -//! the device's arithmetic, where Metal's compiler folds the blend into the function. -use crate::air::ir::Type; -use crate::error::Error; use crate::lower::select::SelectCx; use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::sym::Stage; /// The note a `half` color output records where Metal may hand it to the attachment otherwise /// than the function stores it (the module docs): `PrecisionNote::HalfOutputFastMathBlend` in a @@ -71,51 +65,3 @@ pub(crate) fn note_half_output(cx: &mut SelectCx<'_>, color: u32) { colors.insert(at, color); } } - -/// Record `PrecisionNote::ExtendedRangeBlendSource` (a `half` output) or -/// `PrecisionNote::ExtendedRangeFloatBlendSource` (a `float` one) for each color output the -/// function blends into an extended-range attachment, where the write stores some channel: the -/// function computes that blend by the device's arithmetic (`extended_range::blend::native`), -/// where Metal's compiler folds the blend into the function in forms of its own (each sum and -/// product rounded to `half`, lerps, common factors and fused pairs chosen by the factors and the -/// function's own arithmetic), so a blended channel may store a value apart from Metal's. -pub fn note_extended_range_sources(cx: &mut SelectCx<'_>) -> Result<(), Error> { - use crate::air::abi::{AbiInt, OutputRole}; - if cx.stage != Stage::Fragment { - return Ok(()); - } - let (_, tys) = crate::lower::stage_io::output_types(cx)?; - let types = cx.entry.module.types(); - let mut notes = Vec::new(); - for (o, ty) in cx.entry.ep.outputs.iter().zip(tys) { - let OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } = o.role - else { - continue; - }; - let blended = cx - .inputs - .extended_range_colors - .get(&color) - .is_some_and(|e| e.blended); - // A write of none of the attachment's channels blends nothing. - let stores = crate::lower::fragment::shader_blend(cx, color) - .is_none_or(|(eq, _, nothing)| eq.is_some() || !nothing); - if !blended || !stores { - continue; - } - let elem = match types.get(ty) { - Some(Type::Vector { elem, .. }) => types.get(*elem), - other => other, - }; - notes.push(match elem { - Some(Type::Float) => PrecisionNote::ExtendedRangeFloatBlendSource, - _ => PrecisionNote::ExtendedRangeBlendSource, - }); - } - cx.precision.extend(notes); - Ok(()) -} diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 1bcfaa4f1..ce121ca94 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -390,11 +390,6 @@ fn wide_profile() -> DeviceProfile { .expect("a committed profile with int64, float64, and float16") } -/// The `half` roundings the blends' checks run under (`extended_range::blend::half_of`): the -/// integer sequence, which every form but the controlled one takes, and the device's conversion -/// under the 16-bit float controls, each checked against Metal's arithmetic. -const HALF_FORMS: [QuantizeForm; 2] = [QuantizeForm::Device, QuantizeForm::Controlled]; - /// One case: per operand, per lane, the held bits. type Case = Vec>; @@ -4130,7 +4125,6 @@ fn aggregate_leaf_total_is_capped_before_expansion() { mod atan2; mod bicubic; -mod blend8; mod color_write; mod convert_suffix; mod divide; diff --git a/crates/metal2vulkan/src/lower/arith/tests/blend8.rs b/crates/metal2vulkan/src/lower/arith/tests/blend8.rs deleted file mode 100644 index 8a9f4b2a6..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/blend8.rs +++ /dev/null @@ -1,680 +0,0 @@ -//! A fetched 8-bit unorm attachment's blend on the interpreter -//! (`extended_range::blend::blend_unorm8`), of a `half4` or `float4` output, under fast math and -//! without, against Metal's measured arithmetic. Metal clamps the output to `[0, 1]` (a NaN to 0), -//! reads the destination's code `c` as `h(c / 255)` (`f(c / 255)` for a `float4` output) and the -//! blend color clamped to `[0, 1]` (as `half` in `half` arithmetic), blends in the output's type, -//! and stores the result's code by its unorm write (a NaN 0, clamped, the exact product with 255 -//! rounded to nearest). The function writes the blend's result, which the color attachment's write -//! converts (the device's conversion, `PrecisionNote::DeviceColorConversion`): each lane is checked -//! through Vulkan's conversion of it ([`stored`]: a NaN 0, clamped, the product with 255 rounded to -//! nearest), which gives Metal's code. -//! -//! Premultiplied source-over (one over one minus the source alpha, added, for color and alpha): -//! fast math `h(fma(d, h(1 - a), s))`, without `h(s + h(d · h(1 - a)))`, in `float` likewise. -//! Our probe (plain Metal on the M3 Max under macOS 27.0.1, our own MSL of the guest's shape, -//! a 4096 x 961 target): every `half` alpha in `[0, 1]` against every destination code of each -//! channel, four source draws per pair (half aimed within four units in the last place of a -//! code's midpoint, 2% out of range, infinite or NaN), each of `half4` and `float4`, fast and safe: -//! this arithmetic gives Metal's code in every one of 63 million channels per variant, into -//! `BGRA8Unorm`, and `RGBA8Unorm`, `RG8Unorm` and `R8Unorm` alike. Here every alpha code's `half` -//! (or `float`) meets every destination code in some lane, beside sources aimed at the codes' -//! midpoints, out of range and NaN, and texels read a unit in the last place off `c / 255`. -//! -//! Other factors, operations, write masks and the blend color: a state of each rule -//! `Blend::unorm8` names (the color's contracted pair and alpha's lerp of source alpha over, the -//! blend color's lerps, a lone color channel's lerp, and alpha alone beside the color channels' -//! destination factor), against the arithmetic the probes measured. - -use super::*; -use crate::lower::arith::extended_range::blend::{ - blend_unorm8, half_of, unorm8_tile_value, Blend, BlendArith, BlendMath, -}; -use crate::metal::{BlendFactor as F, BlendOperation as O, ColorWriteMask, PixelFormat}; -use crate::pipeline::lower_inputs::BlendEquation; - -/// `x` rounded to `half`, nearest even. -fn h(x: f64) -> f64 { - f16_to_f64(f64_to_f16(x)) -} - -/// `x` clamped to `[0, 1]`, a NaN to 0. -fn clamp01(x: f64) -> f64 { - if x.is_nan() { - 0.0 - } else { - x.clamp(0.0, 1.0) - } -} - -/// Metal's code of source lane `s` (alpha `a`, both as the output holds them) over destination -/// code `c`, in `arith` under `math` (the module docs). -fn metal_code(arith: BlendArith, math: BlendMath, (s, a): (f64, f64), c: u32) -> u32 { - let (s, a) = (clamp01(s), clamp01(a)); - let v = match arith { - BlendArith::Half => { - let d = h(f64::from(c) / 255.0); - let m = h(1.0 - a); - // Products and sums of these `half`s are exact in `f64`. - match math { - BlendMath::Fast => h(d * m + s), - BlendMath::Rounded => h(s + h(d * m)), - } - } - BlendArith::Float => { - let d = c as f32 / 255.0; - let (s, a) = (s as f32, a as f32); - let m = 1.0 - a; - f64::from(match math { - BlendMath::Fast => d.mul_add(m, s), - BlendMath::Rounded => s + d * m, - }) - } - }; - (clamp01(v) * 255.0 + 0.5).floor() as u32 -} - -/// The `f32` bits of a source lane: a `half` (or a `float` where `float`) aimed within four -/// units in the last place of the midpoint between two codes of the blend of destination code -/// `c` under alpha `a`, a uniform one in `[0, 1]`, or, one time in 16, out of range, an infinity -/// or a NaN. -fn source(rng: &mut Rng, float: bool, (a, c): (f64, u32)) -> u64 { - let w = rng.next(); - const SPECIALS: [f32; 8] = [ - -0.0, - -1.0, - 2.0, - f32::INFINITY, - f32::NEG_INFINITY, - f32::NAN, - 1.5, - -0.25, - ]; - if w.is_multiple_of(16) { - return u64::from(SPECIALS[((w >> 4) % 8) as usize].to_bits()); - } - let x = if (w >> 8) & 1 == 0 { - ((w >> 16) & 0xFFFF) as f64 / 65535.0 - } else { - let k = ((w >> 16) % 255) as f64; - let ulp = if float { - 2f64.powi(-24) - } else { - 2f64.powi(-11) - }; - let step = ((w >> 32) % 9) as f64 - 4.0; - (k + 0.5) / 255.0 - f64::from(c) / 255.0 * (1.0 - a) + step * ulp - }; - let x = x.clamp(0.0, 1.0); - match float { - true => u64::from((x as f32).to_bits()), - false => u64::from((h(x) as f32).to_bits()), - } -} - -/// The `f32` bits of a texel lane of code `c` as a storage image reads it: `c / 255`, a unit in -/// the last place off it one time in four (a decode the function must read as `c` all the same). -fn texel(rng: &mut Rng, c: u32) -> u64 { - let v = c as f32 / 255.0; - let v = match rng.next() % 8 { - 0 if c > 0 => f32::from_bits(v.to_bits() - 1), - 1 if c < 255 => f32::from_bits(v.to_bits() + 1), - _ => v, - }; - u64::from(v.to_bits()) -} - -/// A destination code's `half`, `h(c / 255)`, is the `half` of `c` times the `f32` nearest -/// `1 / 255` (`unorm8_tile_value`'s product): on the host for every code, and through the lowering -/// under each `half` rounding for every code, read as the storage image may decode it (`c / 255`, -/// and a unit in the last place off it either way). -#[test] -fn a_code_s_half_is_its_product_s() { - for c in 0..=255u32 { - let product = c as f32 * (1.0f32 / 255.0); - assert_eq!( - f64_to_f16(f64::from(product)), - f64_to_f16(f64::from(c) / 255.0), - "code {c}" - ); - } - let f4 = vec(float(32), 4); - let mut cases: Vec = Vec::new(); - for step in [-1i64, 0, 1] { - for k in 0..64u32 { - let lanes = (0..4) - .map(|l| { - let c = 4 * k + l; - let v = (c as f32 / 255.0).to_bits(); - let v = match (step, c) { - (-1, 1..) => v - 1, - (1, ..=254) => v + 1, - _ => v, - }; - u64::from(v) - }) - .collect(); - cases.push(vec![lanes]); - } - } - for q in HALF_FORMS { - check( - &format!("a destination code's half, half by {q:?}"), - &[f4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - unorm8_tile_value(fb, x[0], BlendArith::Half) - }, - &cases, - &|c| { - let lanes = c[0].iter().map(|&b| { - let code = (f64::from(f32v(b)) * 255.0).round(); - u64::from((h(code / 255.0) as f32).to_bits()) - }); - Some(lanes.collect()) - }, - false, - ); - } -} - -/// `half_of` rounds to `half` as Metal does under each `half` rounding: to nearest even, half -/// denormals kept, an infinity from 65520 up, the sign of a zero kept. Over every finite `half` of -/// either sign: the `half` itself, the `f32`s beside it, the midpoint to the next `half` up in -/// magnitude and the `f32`s beside that midpoint; and the infinities, `f32` denormals, and the -/// edge of the infinity. -#[test] -fn half_of_rounds_as_metal_under_each_form() { - let f4 = vec(float(32), 4); - let mut inputs: Vec = Vec::new(); - for bits in 0..0x7C00u16 { - for sign in [1.0f64, -1.0] { - let v = sign * f16_to_f64(bits); - let next = sign * f16_to_f64(bits + 1); - let v32 = v as f32; - let mid = ((v + next) / 2.0) as f32; - for x in [v32, mid] { - inputs.push(x); - inputs.push(f32::from_bits(x.to_bits().wrapping_add(1))); - if x.to_bits() & 0x7FFF_FFFF != 0 { - inputs.push(f32::from_bits(x.to_bits() - 1)); - } - } - } - } - let edges = [ - f32::INFINITY, - f32::NEG_INFINITY, - f32::from_bits(1), - f32::from_bits(0x8000_0001), - f32::from_bits(0x007F_FFFF), - f32::from_bits(0x477F_EFFF), - 65520.0, - -65520.0, - 1.0e30, - ]; - inputs.extend(edges); - while !inputs.len().is_multiple_of(4) { - inputs.push(0.0); - } - let cases: Vec = inputs - .chunks(4) - .map(|l| vec![l.iter().map(|x| u64::from(x.to_bits())).collect()]) - .collect(); - for q in HALF_FORMS { - check( - &format!("half_of, half by {q:?}"), - &[f4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - half_of(fb, f4, x[0]) - }, - &cases, - &|c| { - let lanes = c[0].iter().map(|&b| { - let x = f64::from(f32v(b)); - u64::from((f16_to_f64(f64_to_f16(x)) as f32).to_bits()) - }); - Some(lanes.collect()) - }, - false, - ); - } -} - -/// The 8-bit unorm code Vulkan's conversion stores for the `f32` lane `bits` (Fixed-Point Data -/// Conversions: a NaN 0, the value clamped to `[0, 1]`, its product with 255 rounded to nearest). -fn stored(bits: u64) -> u64 { - (clamp01(f64::from(f32v(bits))) * 255.0).round_ties_even() as u64 -} - -/// Whether lane `got`, stored by Vulkan's conversion, gives the code of lane `want`. -fn same_code(got: u64, want: u64) -> bool { - stored(got) == stored(want) -} - -#[test] -fn a_fetched_eight_bit_unorm_blend_stores_metals_code() { - let f4 = vec(float(32), 4); - let over = BlendEquation { - source_rgb: F::One, - destination_rgb: F::OneMinusSourceAlpha, - rgb_operation: O::Add, - source_alpha: F::One, - destination_alpha: F::OneMinusSourceAlpha, - alpha_operation: O::Add, - }; - let one_over = f64::from(1.0f32 / 255.0); - for arith in [BlendArith::Half, BlendArith::Float] { - let float = arith == BlendArith::Float; - let mut rng = Rng(0xB1E8_0C0D ^ u64::from(float)); - // Every alpha code's value against every destination code: alpha code `j`, and each - // case's lanes the codes `4k` to `4k + 3`. - let mut cases: Vec = Vec::new(); - for j in 0..256u32 { - let a = match float { - true => f64::from(j as f32 / 255.0), - false => h(f64::from(j) / 255.0), - }; - let a_bits = u64::from((a as f32).to_bits()); - for k in 0..64u32 { - let codes: Vec = (0..4).map(|l| 4 * k + l).collect(); - let mut s: Vec = codes[..3] - .iter() - .map(|&c| source(&mut rng, float, (a, c))) - .collect(); - s.push(a_bits); - let d = codes.iter().map(|&c| texel(&mut rng, c)).collect(); - cases.push(vec![s, d]); - } - } - for math in [BlendMath::Fast, BlendMath::Rounded] { - for pf in [PixelFormat::BGRA8Unorm, PixelFormat::R8Unorm] { - let what = format!("{arith:?} {math:?} {pf:?}"); - let b = Blend::unorm8(&over, pf, ColorWriteMask::ALL, (math, arith)) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - for q in HALF_FORMS { - check_accept( - &format!("the fetched 8-bit unorm blend, {what}, half by {q:?}"), - &[f4, f4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - blend_unorm8(fb, &b, arith, (x[0], x[1]), None) - }, - &cases, - &|c| { - let a = f64::from(f32v(c[0][3])); - Some( - (0..4) - .map(|l| { - let code = - (f64::from(f32v(c[1][l])) * 255.0).round() as u32; - let s = f64::from(f32v(c[0][l])); - // A format without alpha stores no alpha: the blend - // leaves the lane the texel's. - let got = match (pf, l) { - (PixelFormat::R8Unorm, 3) => code, - _ => metal_code(arith, math, (s, a), code), - }; - u64::from(((got as f32) * one_over as f32).to_bits()) - }) - .collect(), - ) - }, - &same_code, - ); - } - } - } - } -} - -/// A factor of the second source, in any of the four factors, and another format are not built: -/// `Blend::unorm8` refuses each `NotImplemented(FramebufferFetch)`, under either math. -#[test] -fn a_second_source_or_another_format_is_not_built() { - let over = BlendEquation { - source_rgb: F::One, - destination_rgb: F::OneMinusSourceAlpha, - rgb_operation: O::Add, - source_alpha: F::One, - destination_alpha: F::OneMinusSourceAlpha, - alpha_operation: O::Add, - }; - let refused = |r: Result| match r { - Err(crate::error::Error::Unsupported(u)) => { - u.feature == crate::error::Feature::FramebufferFetch - && u.needs == crate::error::Needs::NotImplemented - } - _ => false, - }; - let cases = [ - ( - BlendEquation { - source_rgb: F::Source1Color, - ..over - }, - PixelFormat::BGRA8Unorm, - ), - ( - BlendEquation { - destination_rgb: F::OneMinusSource1Color, - ..over - }, - PixelFormat::RGBA8Unorm, - ), - ( - BlendEquation { - source_alpha: F::Source1Alpha, - ..over - }, - PixelFormat::RG8Unorm, - ), - ( - BlendEquation { - destination_alpha: F::OneMinusSource1Alpha, - ..over - }, - PixelFormat::R8Unorm, - ), - (over, PixelFormat::RGBA8UnormSRGB), - ]; - for (eq, pf) in cases { - for math in [BlendMath::Fast, BlendMath::Rounded] { - assert!( - refused(Blend::unorm8( - &eq, - pf, - ColorWriteMask::ALL, - (math, BlendArith::Half) - )), - "{eq:?} {pf:?} {math:?}" - ); - } - } -} - -/// `x` rounded in `arith`: to `half`, nearest even, or to `float`. -fn rounded(arith: BlendArith, x: f64) -> f64 { - match arith { - BlendArith::Half => h(x), - BlendArith::Float => f64::from(x as f32), - } -} - -/// `a b + c` fused, rounded once in `arith` (a product of `half`s and its sum with one are exact -/// in `f64` over a blend's operands). -fn fused(arith: BlendArith, (a, b, c): (f64, f64, f64)) -> f64 { - match arith { - BlendArith::Half => h(a * b + c), - BlendArith::Float => f64::from((a as f32).mul_add(b as f32, c as f32)), - } -} - -/// One lane's operands as Metal's blend reads them: the source lane `s` and alpha `sa` clamped, -/// the destination lane `d` and alpha `da` decoded, and the blend color's lane `c` and alpha `ca` -/// clamped, each rounded to the arithmetic's type. -#[derive(Clone, Copy)] -struct Lane { - s: f64, - sa: f64, - d: f64, - da: f64, - c: f64, - ca: f64, -} - -#[test] -fn the_factor_set_masks_and_blend_color_store_metals_code() { - let f4 = vec(float(32), 4); - let u4 = vec(int(32), 4); - let one_over = 1.0f32 / 255.0; - let colors: [[f32; 4]; 2] = [[0.3, 0.6, 0.9, 0.45], [-0.25, 1.5, 0.321, 0.8]]; - let eq = |(fs, fd, op): (F, F, O), (sa, da, oa): (F, F, O)| BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: op, - source_alpha: sa, - destination_alpha: da, - alpha_operation: oa, - }; - type Form = fn(BlendArith, BlendMath, Lane) -> f64; - // Each state, its format and mask, and the color and alpha lanes' Metal arithmetic; `None` - // where the lane keeps its texel. - let states: [( - BlendEquation, - PixelFormat, - ColorWriteMask, - Option
, - Option, - ); 5] = [ - // Source alpha over: the color's source product rounded first; alpha a lerp of the - // source alpha from the destination's. - ( - eq( - (F::SourceAlpha, F::OneMinusSourceAlpha, O::Add), - (F::SourceAlpha, F::OneMinusSourceAlpha, O::Add), - ), - PixelFormat::BGRA8Unorm, - ColorWriteMask::ALL, - Some(|ar, math, l| { - let m = rounded(ar, 1.0 - l.sa); - match math { - BlendMath::Fast => fused(ar, (l.d, m, rounded(ar, l.s * l.sa))), - BlendMath::Rounded => { - rounded(ar, rounded(ar, l.s * l.sa) + rounded(ar, l.d * m)) - } - } - }), - Some(|ar, math, l| { - let m = rounded(ar, 1.0 - l.sa); - match math { - BlendMath::Fast => fused(ar, (l.sa, rounded(ar, l.sa - l.da), l.da)), - BlendMath::Rounded => { - rounded(ar, rounded(ar, l.sa * l.sa) + rounded(ar, l.da * m)) - } - } - }), - ), - // The destination alpha and its one minus: the color's source product rounded first, as - // its one minus ranks as the source alpha's does (`argb8-targets-destination-alpha`'s - // `RGBA8Unorm` texels, a `float4` output under fast math: every color channel of 8,192; - // `half` arithmetic takes the same rank, not measured); alpha as source alpha over's. - ( - eq( - (F::DestinationAlpha, F::OneMinusDestinationAlpha, O::Add), - (F::SourceAlpha, F::OneMinusSourceAlpha, O::Add), - ), - PixelFormat::BGRA8Unorm, - ColorWriteMask::ALL, - Some(|ar, math, l| { - let m = rounded(ar, 1.0 - l.da); - match math { - BlendMath::Fast => fused(ar, (l.d, m, rounded(ar, l.s * l.da))), - BlendMath::Rounded => { - rounded(ar, rounded(ar, l.s * l.da) + rounded(ar, l.d * m)) - } - } - }), - Some(|ar, math, l| { - let m = rounded(ar, 1.0 - l.sa); - match math { - BlendMath::Fast => fused(ar, (l.sa, rounded(ar, l.sa - l.da), l.da)), - BlendMath::Rounded => { - rounded(ar, rounded(ar, l.sa * l.sa) + rounded(ar, l.da * m)) - } - } - }), - ), - // The blend color and its one minus: lerps of it under fast math. - ( - eq( - (F::BlendColor, F::OneMinusBlendColor, O::Add), - (F::BlendAlpha, F::OneMinusBlendAlpha, O::Add), - ), - PixelFormat::RGBA8Unorm, - ColorWriteMask::ALL, - Some(|ar, math, l| match math { - BlendMath::Fast => fused(ar, (l.c, rounded(ar, l.s - l.d), l.d)), - BlendMath::Rounded => { - let m = rounded(ar, 1.0 - l.c); - rounded(ar, rounded(ar, l.s * l.c) + rounded(ar, l.d * m)) - } - }), - Some(|ar, math, l| match math { - BlendMath::Fast => fused(ar, (l.ca, rounded(ar, l.sa - l.da), l.da)), - BlendMath::Rounded => { - let m = rounded(ar, 1.0 - l.ca); - rounded(ar, rounded(ar, l.sa * l.ca) + rounded(ar, l.da * m)) - } - }), - ), - // One color channel stored: a lerp of the source alpha a vector does not take. - ( - eq( - (F::OneMinusSourceAlpha, F::SourceAlpha, O::Add), - (F::One, F::Zero, O::Add), - ), - PixelFormat::BGRA8Unorm, - ColorWriteMask::BLUE, - Some(|ar, math, l| match math { - BlendMath::Fast => fused(ar, (l.sa, rounded(ar, l.d - l.s), l.s)), - BlendMath::Rounded => { - let m = rounded(ar, 1.0 - l.sa); - rounded(ar, rounded(ar, l.s * m) + rounded(ar, l.d * l.sa)) - } - }), - None, - ), - // Alpha alone stored: the color channels' destination factor still computes one minus - // the destination alpha, so alpha takes no lerp of it. - ( - eq( - (F::Zero, F::OneMinusDestinationAlpha, O::Add), - (F::OneMinusDestinationColor, F::DestinationColor, O::Add), - ), - PixelFormat::BGRA8Unorm, - ColorWriteMask::ALPHA, - None, - Some(|ar, math, l| { - let m = rounded(ar, 1.0 - l.da); - match math { - BlendMath::Fast => fused(ar, (l.sa, m, rounded(ar, l.da * l.da))), - BlendMath::Rounded => { - rounded(ar, rounded(ar, l.sa * m) + rounded(ar, l.da * l.da)) - } - } - }), - ), - ]; - for arith in [BlendArith::Half, BlendArith::Float] { - let float = arith == BlendArith::Float; - let mut rng = Rng(0xFAC7_0B1E ^ u64::from(float)); - let mut cases: Vec = Vec::new(); - for bc in colors { - let color: Vec = bc.iter().map(|c| u64::from(c.to_bits())).collect(); - for _ in 0..1500 { - let codes: Vec = (0..4).map(|_| (rng.next() % 256) as u32).collect(); - let a = h(f64::from((rng.next() % 256) as u32) / 255.0); - let s = codes - .iter() - .map(|&c| source(&mut rng, float, (a, c))) - .collect(); - let d = codes.iter().map(|&c| texel(&mut rng, c)).collect(); - cases.push(vec![s, d, color.clone()]); - } - } - for (e, pf, mask, color_form, alpha_form) in states { - for math in [BlendMath::Fast, BlendMath::Rounded] { - let what = format!("{arith:?} {math:?} {pf:?} {mask:?} {e:?}"); - let b = Blend::unorm8(&e, pf, mask, (math, arith)) - .unwrap_or_else(|err| panic!("{what}: {err:?}")); - assert_eq!(b.reads_constant(), pf == PixelFormat::RGBA8Unorm, "{what}"); - for q in HALF_FORMS { - check_accept( - &format!("the fetched 8-bit unorm blend, {what}, half by {q:?}"), - &[f4, f4, u4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - let color = b.reads_constant().then_some(x[2]); - blend_unorm8(fb, &b, arith, (x[0], x[1]), color) - }, - &cases, - &|c| { - let code = |l: usize| (f64::from(f32v(c[1][l])) * 255.0).round() as u32; - let read = |x: f64| rounded(arith, clamp01(x)); - let lane = |l: usize| Lane { - s: read(f64::from(f32v(c[0][l]))), - sa: read(f64::from(f32v(c[0][3]))), - d: rounded(arith, f64::from(code(l)) / 255.0), - da: rounded(arith, f64::from(code(3)) / 255.0), - c: read(f64::from(f32v(c[2][l]))), - ca: read(f64::from(f32v(c[2][3]))), - }; - Some( - (0..4) - .map(|l| { - let form = if l < 3 { color_form } else { alpha_form }; - let got = match form { - Some(form) => { - let v = form(arith, math, lane(l)); - (clamp01(v) * 255.0 + 0.5).floor() as u32 - } - None => code(l), - }; - u64::from(((got as f32) * one_over).to_bits()) - }) - .collect(), - ) - }, - &same_code, - ); - } - } - } - } -} - -/// A format without alpha (`R8Unorm`, `RG8Unorm`) sums its products under fast math in forms of -/// its own: a lerp, common factor or contracted pair is refused `NotImplemented(FramebufferFetch)` -/// there, a fused or single product built, and without fast math every blend is built. -#[test] -fn a_format_without_alpha_builds_only_its_measured_fast_forms() { - let eq = |fs, fd| BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: O::Add, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: O::Add, - }; - // Each blend and whether fast math builds it. - let cases = [ - (eq(F::SourceAlpha, F::OneMinusSourceAlpha), false), - (eq(F::OneMinusSourceAlpha, F::SourceAlpha), false), - (eq(F::DestinationColor, F::OneMinusSourceAlpha), false), - (eq(F::One, F::OneMinusSourceAlpha), true), - (eq(F::Zero, F::SourceColor), true), - (eq(F::BlendColor, F::One), true), - ]; - for pf in [PixelFormat::R8Unorm, PixelFormat::RG8Unorm] { - for (e, fast) in cases { - for math in [BlendMath::Fast, BlendMath::Rounded] { - let built = Blend::unorm8(&e, pf, ColorWriteMask::ALL, (math, BlendArith::Half)); - let what = format!("{pf:?} {math:?} {e:?}"); - match built { - Ok(_) => assert!(fast || math == BlendMath::Rounded, "{what}"), - Err(crate::error::Error::Unsupported(u)) => { - assert!(!fast && math == BlendMath::Fast, "{what}"); - assert_eq!(u.feature, crate::error::Feature::FramebufferFetch, "{what}"); - assert_eq!(u.needs, crate::error::Needs::NotImplemented, "{what}"); - } - Err(e) => panic!("{what}: {e:?}"), - } - } - } - } -} diff --git a/crates/metal2vulkan/src/lower/arith/tests/fused.rs b/crates/metal2vulkan/src/lower/arith/tests/fused.rs index f0917eb02..a777a1549 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/fused.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/fused.rs @@ -283,77 +283,6 @@ fn float_fused_multiply_add_is_the_device_s_instruction() { } } -/// The blends' exact `float` multiply-add (`fma::float_fma_exact`, of a `float` output's blend into -/// an extended-range or 16-bit float attachment) rounds the exact `a * b + c` once on operands below -/// 2 in magnitude whose parts do not underflow, on one lane and four, and its zero is IEEE's: `-0` -/// for a negative zero product and a `-0` addend (`-0 · 1 + -0`, the zero alpha Metal stores for a -/// `float4` output's blend over a `-0` texel), `+0` for opposite zeros and for a product the addend -/// cancels. The emulation's own sum loses the first (`th + v` adds a `+0` to a `-0`). An infinite -/// operand's infinite result is that infinity, where the emulation's own steps give a NaN (a -/// `float4` output's infinity over a texel, which Metal stores as the `half` infinity). -#[test] -fn the_blends_float_multiply_add_rounds_once_and_signs_its_zeros() { - fn operand(rng: &mut Rng) -> u64 { - let r = rng.next(); - mk32(r & 1, ((r >> 1) % 15) as i32 - 14, (r >> 8) & 0x7F_FFFF) - } - let edges: [u64; 8] = [ - 0, - 0x8000_0000, - 0x3F80_0000, - 0xBF80_0000, - 0x3F00_0000, - 0xBF00_0000, - 0x3FFF_FFFF, - 0xBFFF_FFFF, - ]; - let mut triples = Vec::new(); - for a in edges { - for b in edges { - for c in edges { - triples.push([a, b, c]); - } - } - } - // Infinite operands whose results are infinite. - triples.extend([ - [0x7F80_0000, 0x3F80_0000, 0x3F00_0000], - [0xFF80_0000, 0x3F00_0000, 0xBF80_0000], - [0x3F80_0000, 0x3F00_0000, 0x7F80_0000], - [0xBFFF_FFFF, 0x3F80_0000, 0xFF80_0000], - [0x7F80_0000, 0x3F80_0000, 0x7F80_0000], - ]); - let mut rng = Rng(0xB1E0_F32A); - for _ in 0..2000 { - triples.push([operand(&mut rng), operand(&mut rng), operand(&mut rng)]); - } - // Products the addend cancels: factors of 12 significand bits, whose product is a `float`. - for _ in 0..300 { - let (a, b) = (operand(&mut rng) & !0xFFF, operand(&mut rng) & !0xFFF); - let p = f32v(a) * f32v(b); - triples.push([a, b, u64::from((-p).to_bits())]); - } - assert!(triples.contains(&[0x8000_0000, 0x3F80_0000, 0x8000_0000])); - for lanes in [1u8, 4] { - let f = floats(lanes); - check( - &format!("the blends' float fma x{lanes}"), - &[f, f, f], - f, - &|fb, x| fma::float_fma_exact(fb, f, x[0], x[1], x[2]), - &lane_cases(&triples, lanes), - &|c| { - Some( - (0..c[0].len()) - .map(|l| fma32(c[0][l], c[1][l], c[2][l])) - .collect(), - ) - }, - false, - ); - } -} - /// The triples reach the hazards a shortcut gets wrong: the hazard families hold triples a /// `double` sum rounded to `float` gets wrong, and the cancellations triples where the unfused /// result differs from the fused one. diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index cef35cca2..51581b0f1 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -1944,32 +1944,6 @@ fn fp8_to_integer_converts_every_pattern_as_its_value() { } } -/// `k / d` is correctly rounded (the host's IEEE `f32` division) for every `k` in `[0, d]` of every -/// normalized scale and the sRGB step scale 4095, and for every 97th `k` and both ends of the -/// 16-bit scales. -#[test] -fn normalized_division_is_correctly_rounded() { - let u = int(32); - let s = float(32); - for d in [1u32, 3, 31, 63, 127, 255, 1023, 4095, 32767, 65535] { - let step = if d > 4095 { 97 } else { 1 }; - let cases: Vec = (0..=u64::from(d)) - .step_by(step) - .chain([u64::from(d) - 1, u64::from(d)]) - .map(|k| vec![vec![k]]) - .collect(); - check( - &format!("k / {d}"), - &[u], - s, - &|fb, k| crate::lower::arith::exact_division::div_exact(fb, u, k[0], d), - &cases, - &|c| Some(vec![u64::from((arg(c, 0) as f32 / d as f32).to_bits())]), - false, - ); - } -} - /// The value of a packed small-float field with a 5-bit exponent (bias 15) above `man` bits. fn small_float(field: u64, man: u32) -> f64 { let e = (field >> man) & 0x1F; diff --git a/crates/metal2vulkan/src/lower/arith/texel_round.rs b/crates/metal2vulkan/src/lower/arith/texel_round.rs index 9bb1dabda..19b8c1eb4 100644 --- a/crates/metal2vulkan/src/lower/arith/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/texel_round.rs @@ -16,7 +16,7 @@ //! //! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as its //! `air.unpack` does: the step `k` of [`srgb`](crate::lower::arith::srgb), then `k / 4095` -//! ([`div_exact`](crate::lower::arith::exact_division::div_exact); every code of the authored case +//! correctly rounded (every code of the authored case //! `half-conversion-of-wider-texels-by-read-and-sample`, and every bicubic sum of //! `bicubic-rounding-of-random-float-and-srgb-texels`, read those steps). //! @@ -220,9 +220,10 @@ fn round_up(fb: &mut FunctionBuilder<'_>, u: Form, q: Value, r: Value, d: Value) } /// `k / d` correctly rounded to `f32` (nearest even), for `u32` lanes (form `u`) with -/// `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value: -/// [`div_exact`](crate::lower::arith::exact_division::div_exact)'s sequence, the divisor's -/// leading bit found at run time. `k = 0` is `+0`. +/// `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value, with integer operations only: +/// `k` shifted into `[d, 2d)`, two exact integer divisions for the significand and the last +/// remainder's rounding to nearest even, the divisor's leading bit found at run time. `k = 0` is +/// `+0`. pub fn ratio_to_f32(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult { let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); let (z, one) = (c(fb, 0)?, c(fb, 1)?); diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index 52f22442f..d5742cc4c 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -11,19 +11,12 @@ //! declared one. //! //! **Ordering**: Metal orders a fetch after every earlier fragment of the pixel, of the draw and -//! of earlier draws. Vulkan orders an input-attachment read so only with rasterization-order color -//! attachment access. Without it, a device with `fragmentShaderPixelInterlock` reads (and writes) -//! the attachment as a storage image inside the ordered interlock where the pipeline's state lets -//! that be exact (`fetch`), and refuses the function where that state blocks it. A device with -//! neither ([`fetch::fetch_unordered`](super::fetch::fetch_unordered)) reads the input attachment -//! all the same: Vulkan orders an earlier draw's color write before a later draw's input -//! attachment read of the subpass by a barrier of the subpass's dependency on itself, by region, -//! which the consumer records between them (`GraphicsState::rasterization_order_attachment_access` -//! false), but nothing orders the overlapping fragments of one draw. The function records -//! `PrecisionNote::UnorderedFetchWithinDraw` there. The function states -//! `RuntimeFact::FramebufferFetch{color}` for every index it reads as an input attachment, so -//! link can set the pipeline's rasterization-order flags where the device has them and the render -//! pass can provide the self-dependency. +//! of earlier draws. Vulkan orders an earlier draw's color write before +//! a later draw's input attachment read of the subpass by a barrier of the subpass's dependency on +//! itself, by region, which the consumer records between them, but nothing orders the overlapping +//! fragments of one draw. The function records `PrecisionNote::UnorderedFetchWithinDraw`. It +//! states `RuntimeFact::FramebufferFetch{color}` for every index it reads, so the render pass can +//! provide the self-dependency. //! //! **Per sample**. Metal runs a function that reads a color attachment of a multisampled pass once //! per covered sample, reading its own sample (measured). Compiled for such a pipeline @@ -31,8 +24,7 @@ //! (`MS` 1, as Vulkan requires for an attachment of more than one sample), read at the invocation's //! `SampleId` (`fetch::plan_sample`), which runs the function once per covered sample under sample //! shading; the function's color outputs then write only that sample, and a returned sample mask -//! and alpha to coverage stay the fixed function's, as at one sample. Rasterization-order -//! attachment access orders each sample's reads and writes in primitive order. Link's sample +//! and alpha to coverage stay the fixed function's, as at one sample. Link's sample //! invocations read the function's pixel inputs where Metal does or refuse them, and refuse a stage //! compiled for another sample count. //! @@ -44,9 +36,7 @@ //! Metal's tile holds such an attachment as `half` through the pass, which the codes an earlier //! draw stored do not keep (`fetch::codes_round_the_tile`); a padded one's is built. The //! interface records the attachment (`StageIo::extended_range_colors`), so link holds a stage -//! compiled for it to the pipeline's attachments. Where the pipeline blends such an attachment the -//! function writes, the write blends over the same input attachment (`input_blend`), which a -//! `[[color(n)]]` read of the attachment shares ([`input_texel`]). +//! compiled for it to the pipeline's attachments. //! //! **An 8-bit sRGB attachment** (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB` and the rest) reads through //! its input attachment the device's decode of its bytes, Vulkan's sRGB EOTF within the device's @@ -149,7 +139,6 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result, b: &ParamBinding) -> Result, b: &ParamBinding) -> Result { let class = texture_class(cx, color, form); @@ -344,21 +315,11 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl { } /// Declare one input attachment per color index the plan reads, multisampled for a per-sample -/// function (`multisampled`); the input attachment of every extended-range attachment whose -/// blend the function computes over it (`input_blend`) and that of every word attachment whose -/// word the function merges into the texel's (`word_input`), of `uint` texels; and that of every -/// attachment held with its channels rotated whose blend the function computes over it -/// (`rotated`, `input_blend`), of `float` texels; and that of every attachment whose private logic -/// operation the function computes over it (`logic`). A color read through a pushed texture -/// (`textured`) declares nothing here. +/// function (`multisampled`). A color read through a pushed texture (`textured`) declares nothing +/// here. pub(super) fn declare( mb: &mut ModuleBuilder, colors: &[ColorInput], - (blends, merges): (&BTreeMap, &BTreeMap), - (rotated, logic): ( - &BTreeMap, - &BTreeMap, - ), multisampled: bool, textured: &BTreeMap, ) -> BResult> { @@ -373,27 +334,6 @@ pub(super) fn declare( let float = c.form.is_float() && c.extended.is_none(); out.insert(c.color, input_attachment(mb, c.color, float, multisampled)?); } - let blended = blends.iter().filter(|(_, ib)| ib.reads()).map(|(&c, _)| c); - for color in blended.chain(merges.keys().copied()) { - if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { - e.insert(input_attachment(mb, color, false, multisampled)?); - } - } - // An attachment held with its channels rotated, whose 8-bit unorm texels its blend reads as - // `float`s. - for (&color, _) in rotated.iter().filter(|(_, rb)| rb.reads()) { - if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { - e.insert(input_attachment(mb, color, true, multisampled)?); - } - } - // An attachment whose logic operation the function computes over it, of `float` texels for a - // normalized format and `uint` ones (a signed integer's bits) for an integer one. - for (&color, li) in logic { - if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { - let float = super::logic::reads_float(li.channels); - e.insert(input_attachment(mb, color, float, multisampled)?); - } - } Ok(out) } diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index 95d4683cd..b55b69c3c 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -1,26 +1,21 @@ -//! Framebuffer fetch: what orders it, and the writes a fragment function computes over the texel -//! it reads. +//! Framebuffer fetch: what orders it, and the writes no form computes over the texel it reads. //! //! **Where.** Metal orders a fetch after every earlier fragment of the pixel, across draws. A color //! input reads the attachment's input attachment (`color`), which Vulkan orders so only under -//! rasterization-order color attachment access ([`inputs_order`]). A device without that access -//! reads the input attachment ordered between draws alone, by the consumer's barrier of the -//! subpass's dependency on itself, and the read notes `PrecisionNote::UnorderedFetchWithinDraw` -//! ([`fetch_unordered`]); under the identity domains it reads the attachment's pushed texture at -//! the invocation's pixel instead (`PushField::FetchedColor`, [`pixel`]). The pixel interlock -//! orders no fetch: it serves raster order groups on memory the function itself reads and writes -//! (`fragment::rog`). +//! rasterization-order color attachment access, which no form here takes: the read is ordered +//! between draws alone, by the consumer's barrier of the subpass's dependency on itself, and notes +//! `PrecisionNote::UnorderedFetchWithinDraw`; under the identity domains it reads the attachment's +//! pushed texture at the invocation's pixel instead (`PushField::FetchedColor`, [`pixel`]). The +//! pixel interlock orders no fetch: it serves raster order groups on memory the function itself +//! reads and writes (`fragment::rog`). //! -//! **Writes computed over the input attachment.** On a device that orders fetch through -//! rasterization-order input attachments, the function computes over the texel it reads the writes -//! no Vulkan blend or write mask gives, from the pipeline's state (`LoweringInputs::framebuffer_fetch`, -//! which the render pipeline compile sets, `compile::fetch_inputs`): a padded extended-range -//! attachment's blend, and a write of some of the codes one word of such an attachment holds -//! (`input_blend`, [`extended_range_blend`]); an attachment held with its channels rotated whose -//! blend no Vulkan state on its image gives (`input_blend`'s `RotatedInputBlend`); a word -//! attachment written under a mask of some of the word's channels (`word_input`); and a private -//! logic operation the device lacks (`logic`). On a device that does not order fetch so, each is -//! refused naming rasterization-order access ([`unordered_extended_fetch`]). +//! **Writes over the texel.** A write no Vulkan blend or write mask gives would be computed by the +//! function over an ordered read of the attachment, which is not built: a padded extended-range +//! attachment's blend, a write of some of the codes one word of such an attachment holds +//! (`color_writes::merged_extended`), and a blend no Vulkan state gives on an attachment held with +//! its channels rotated (`color_writes::rotated_blend_in_shader`) are refused on every device +//! ([`computed_write_refused`]); so is a private logic operation the device lacks +//! (`pipeline::private_state`). //! //! **Per sample**. Metal runs a function that reads a color attachment of a multisampled pass once //! per covered sample, reading its own sample, in draw order per sample, with `[[position]]`'s x @@ -29,63 +24,26 @@ //! ([`plan_sample`]), which runs it once per covered sample under Vulkan's sample shading, and needs //! `sampleRateShading`. //! -//! **A write mask** short of the format's channels: Metal keeps the channels the mask leaves out. -//! A write the function computes over its input attachment keeps them from the texel it read -//! ([`kept_channels`]); a mask that covers none of the format's channels writes nothing. The -//! function compiles a format's mask by its class ([`compiled_write_mask`]: none, every channel, or -//! some), but an extended-range or an sRGB format's mask as the descriptor sets it -//! ([`kept_at_draw`]); link holds the channels the stage keeps to the pipeline's own mask. -//! //! **Apple's extended-range forms** (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their //! `_sRGB` twins, [`codes_round_the_tile`]): Metal's tile memory holds such an attachment as `half` //! through a render pass and rounds it to the codes only at the store, so a fetch or a blend onto //! what an earlier draw of the pass wrote sees that draw's `half`, which the codes the attachment //! holds do not keep. A fetch of one, and a blend into one the function writes, are not //! implemented: refused on every device (`Feature::Format`, at the attachment; here, in -//! `color::select_param`, and in `stage_io::extended_color` where the device does not order -//! fetch). An unblended write, a masked one included, is built: a kept channel's code is the -//! encode of the `half` the tile keeps there. `metal2vulkan-runtime` makes no extended-range -//! texture (`Gap::TextureFormat`). -//! -//! A blocked attachment is refused with the blocker's reason (what the device lacks, or -//! `NotImplemented`): no ordered path exists there. +//! `color::select_param`, and in `stage_io::extended_color`). An unblended write, a masked one +//! included, is built: a kept channel's code is the encode of the `half` the tile keeps there. +//! `metal2vulkan-runtime` makes no extended-range texture (`Gap::TextureFormat`). -use std::collections::BTreeSet; - -use crate::air::abi::{AbiInt, OutputRole}; -use crate::air::ir::TypeId as AirTypeId; -use crate::device::requirements::{FormatUsage, VkFeature}; -use crate::device::DeviceProfile; -use crate::error::{Attachment, Capability, Error, ExtendedRangeBlend, Feature, Unsupported}; -use crate::lower::arith::{extended_range, FloatFmt, Form}; +use crate::device::requirements::VkFeature; +use crate::error::{Capability, Error, Feature, Unsupported}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::lower::stage_io; -use crate::metal::format::{color_output_components, ExtendedRange, WordAttachment}; -use crate::metal::ColorWriteMask; -use crate::pipeline::lower_inputs::BlendEquation; -use crate::pipeline::sym::PushField; +use crate::metal::format::ExtendedRange; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::Value as SValue; use crate::spirv::ir::{ConvOp, ImageOperands, MemAccess, Type as SType}; -use crate::vk; - -/// Whether `p` orders framebuffer fetch through rasterization-order input attachments (lavapipe): -/// rasterization-order color attachment access. -pub(crate) fn inputs_order(p: &DeviceProfile) -> bool { - p.fields().fragment.rasterization_order_color_access -} - -/// Whether `p` orders framebuffer fetch in no form: no rasterization-order color attachment -/// access. A fetch there reads the input attachment, which -/// the consumer's barrier of the subpass's dependency on itself orders after the earlier draws' -/// writes but not after an overlapping earlier fragment of the same draw -/// (`PrecisionNote::UnorderedFetchWithinDraw`, `color`); a blend or a merge the function computes -/// over its own read ([`unordered_extended_fetch`]) is refused. -pub(crate) fn fetch_unordered(p: &DeviceProfile) -> bool { - !inputs_order(p) -} /// Whether Metal's tile memory holds an attachment of `form` as `half` through a render pass and /// rounds it to the codes only at the store, where the attachment holds the codes: Apple's @@ -96,221 +54,22 @@ pub(crate) fn codes_round_the_tile(form: ExtendedRange) -> bool { !form.padded() && !form.bfloat() } -/// The refusal of a blend into an extended-range attachment, or of a write of some of the codes -/// one of its words holds (`color_writes::merged_extended`), on a device that does not order -/// framebuffer fetch ([`fetch_unordered`]): the function computes the blend, or merges the codes, -/// over its own read of the attachment's codes, which no device's blend unit or write mask does, -/// and that read must be ordered after every earlier fragment's write of the pixel, through -/// rasterization-order color attachment access (over the input attachment). -pub(crate) fn unordered_extended_fetch() -> Unsupported { - Unsupported::needs( - Feature::FramebufferFetch, - Capability::Feature(VkFeature::RasterizationOrderColorAttachmentAccess), - ) +/// The refusal of a write the fragment function would compute over its own ordered read of the +/// attachment, on every device (module docs): a padded extended-range attachment's blend, a write +/// of some of the codes one word of such an attachment holds, and a blend no Vulkan state gives on +/// an attachment held with its channels rotated. No device's blend unit or write mask gives them, +/// and their form over the read is not built. +pub(crate) fn computed_write_refused() -> Unsupported { + Unsupported::not_implemented(Feature::FramebufferFetch) } /// Whether `pf` is a 16-bit float color format, whose blend of a `half` output of a module -/// without fast math Metal computes in `half` arithmetic, and of one with fast math in the fast -/// forms it folds into the function ([`extended_range::blend::BlendMath`]). +/// without fast math Metal computes in `half` arithmetic. pub(crate) fn half_float_format(pf: crate::metal::PixelFormat) -> bool { use crate::metal::PixelFormat as P; matches!(pf, P::R16Float | P::RG16Float | P::RGBA16Float) } -/// Whether `pf` is an 8-bit unorm color format, whose blend Metal computes in the arithmetic of -/// the output's type over the clamped output ([`extended_range::Blend::unorm8`]): one held -/// directly, or `ARGB8Unorm`, which Metal blends as `RGBA8Unorm` with its channels rotated. -pub(crate) fn unorm8_format(pf: crate::metal::PixelFormat) -> bool { - use crate::metal::PixelFormat as P; - matches!( - pf, - P::R8Unorm | P::RG8Unorm | P::RGBA8Unorm | P::BGRA8Unorm | P::ARGB8Unorm - ) -} - -/// Whether `pf` is a packed 16-bit unorm format (`metal::format::WordAttachment::Packed16`), whose -/// blend Metal computes in `half` over its decoded codes. -pub(crate) fn packed16_format(pf: crate::metal::PixelFormat) -> bool { - matches!( - WordAttachment::layout(pf), - Some(WordAttachment::Packed16 { .. }) - ) -} - -/// The channels of `mask` a write of every channel of a color attachment of `pf` must keep: its -/// first `color_output_components(pf)` of red, green, blue, and alpha (all four for a format of -/// none). -fn channels(pf: crate::metal::PixelFormat) -> ColorWriteMask { - let n = color_output_components(pf).unwrap_or(4); - let order = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ColorWriteMask::ALPHA, - ]; - order - .iter() - .take(usize::from(n)) - .fold(ColorWriteMask::NONE, |m, &c| m.union(c)) -} - -/// Whether the write masks of a class compile alike for an attachment of `pf` -/// ([`compiled_write_mask`]): every format but an extended-range one, whose kept channels Metal's -/// blend model and encode read (`extended_range::Blend`, `encode_keeping`), and an sRGB one. -pub(crate) fn kept_at_draw(pf: crate::metal::PixelFormat) -> bool { - let srgb = crate::metal::format::direct_format(pf) - .and_then(|f| f.block()) - .is_some_and(|b| b.color == Some(vk::NumericFormat::Srgb)); - ExtendedRange::of(pf).is_none() && !srgb -} - -/// The channels a write of the attachment of `pf` under write mask `mask` keeps from its texel: -/// none where the function does not write it (`writes` false) or the mask covers every channel of -/// the format, all four (`R`, `G`, `B` and `A`) where it covers none of them (the write stores -/// nothing), else those of the format the mask leaves out. -pub(crate) fn kept_channels( - pf: crate::metal::PixelFormat, - mask: ColorWriteMask, - writes: bool, -) -> ColorWriteMask { - let all = channels(pf); - if !writes { - ColorWriteMask::NONE - } else if all.intersection(mask).is_empty() { - ColorWriteMask::ALL - } else { - all.difference(mask) - } -} - -/// The write mask a fragment function compiles its computed write of an attachment of `pf` under, -/// for the descriptor's `mask` (`FramebufferFetchInputs::of`), blended where `blended`: where the -/// masks of a class compile alike ([`kept_at_draw`]), the class of `mask` alone (none -/// where it covers none of the format's channels, all where it covers every one, and for a mask -/// covering some, every channel of the format but the first, the one mask that stands for them -/// all), so the write masks of a class share one key and one module; any other format's `mask` as -/// it is. A blended 8-bit unorm attachment with alpha, or a blended packed 16-bit one, splits the -/// partial class in three, as Metal's blend forms do (`extended_range::Blend::unorm8`, -/// `extended_range::Blend::packed16`): alpha alone (`ALPHA`), one color channel with or without -/// alpha (`RED` and `ALPHA`), and two or more color channels. -pub(crate) fn compiled_write_mask( - pf: crate::metal::PixelFormat, - mask: ColorWriteMask, - blended: bool, -) -> ColorWriteMask { - if !kept_at_draw(pf) || mask.contains(ColorWriteMask::UNSPECIALIZED) { - return mask; - } - let all = channels(pf); - let written = all.intersection(mask); - let colors = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ] - .into_iter() - .filter(|&c| written.contains(c)) - .count(); - // Metal's blend forms differ by the class (`extended_range::Blend::unorm8`, `packed16`). - let unorm8 = blended - && ((unorm8_format(pf) && all.contains(ColorWriteMask::ALPHA)) || packed16_format(pf)); - if written.is_empty() { - ColorWriteMask::NONE - } else if written == all { - ColorWriteMask::ALL - } else if unorm8 && colors == 0 { - ColorWriteMask::ALPHA - } else if unorm8 && colors == 1 { - ColorWriteMask::RED.union(ColorWriteMask::ALPHA) - } else { - all.difference(ColorWriteMask::RED) - } -} - -/// Whether a render pipeline on `p` blends into a color attachment of `pf`, one of Apple's -/// extended-range formats (`metal::format::extended_range_blend`, its public door): the decision -/// `input_blend` makes for such an attachment, written whole by the function's -/// first output under a blend Metal's model holds (premultiplied source-over, one), in a pipeline -/// of one sample with no depth or stencil attachment. One of Apple's extended-range forms -/// ([`codes_round_the_tile`]) answers `NotImplemented(Format)` on every device. Another's: `Ok` -/// where the device orders fetch through rasterization-order input attachments and the function's -/// blend over the attachment's input attachment holds (`input_blend`); else what blocks it -/// ([`unordered_extended_fetch`]). A bfloat format, which -/// Metal blends nowhere (its pipeline validation asserts; link refuses such a blend -/// `InvalidDescriptor(ColorAttachment)`), answers `NotRepresentable(Format)`, as the runtime's -/// formats answer what Metal refuses. -pub(crate) fn extended_range_blend( - pf: crate::metal::PixelFormat, - p: &DeviceProfile, -) -> Result<(), Unsupported> { - use crate::metal::{BlendFactor as F, BlendOperation as O}; - let Some(form) = ExtendedRange::of(pf) else { - return Err(Unsupported::not_implemented(Feature::Format)); - }; - if form.bfloat() { - return Err(Unsupported::not_representable(Feature::Format)); - } - if codes_round_the_tile(form) { - return Err(Unsupported::not_implemented(Feature::Format)); - } - let equation = BlendEquation { - source_rgb: F::One, - destination_rgb: F::OneMinusSourceAlpha, - rgb_operation: O::Add, - source_alpha: F::One, - destination_alpha: F::OneMinusSourceAlpha, - alpha_operation: O::Add, - }; - if fetch_unordered(p) { - return Err(unordered_extended_fetch()); - } - // The blend over the input attachment: the attachment's raw format a color attachment, and - // the blend Metal's model's. - let usages = BTreeSet::from([FormatUsage::ColorAttachment]); - match crate::metal::format::vk_format(pf, &usages, p) { - Ok(_) => {} - Err(Error::Unsupported(gap)) => return Err(gap), - Err(_) => return Err(Unsupported::not_representable(Feature::Format)), - } - match extended_range::blend::NativeBlend::of(&equation, channels(pf)) { - Ok(_) => Ok(()), - Err(Error::Unsupported(gap)) => Err(gap), - Err(_) => Err(Unsupported::not_representable(Feature::Format)), - } -} - -/// The extended-range attachments the function writes through a first output where the -/// pipeline blends them (`LoweringInputs::extended_range_colors`), whose blend the function -/// computes over the input attachment (`input_blend`), and the AIR type of each output. A blend into one of Apple's extended-range forms -/// ([`codes_round_the_tile`]) is refused (`Feature::Format`, at the attachment). -pub(super) fn blended_extended_range(cx: &SelectCx<'_>) -> Result, Error> { - let mut out = Vec::new(); - for (o, ty) in cx - .entry - .ep - .outputs - .iter() - .zip(stage_io::output_types(cx)?.1) - { - if let OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } = o.role - { - match cx.inputs.extended_range_colors.get(&color) { - Some(e) if e.blended && codes_round_the_tile(e.form) => { - let refused = Unsupported::not_implemented(Feature::Format); - return Err(refused.at_attachment(Attachment::Color(color)).into()); - } - Some(e) if e.blended => out.push((color, ty)), - _ => {} - } - } - } - Ok(out) -} - /// Plan the invocation's sample for a function compiled for a multisampled pipeline /// (`LoweringInputs::multisampled`), which reads each color it fetches, in either form, at its /// `SampleId`: Metal runs a function that reads a color attachment once per covered sample, reading @@ -331,38 +90,6 @@ pub(super) fn plan_sample(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } -/// The function's second (index-1) output to attachment `color`: `None` where it writes none, -/// `Some(Some(fmt))` where it is four lanes of `fmt`, a `half` or a `float`, and `Some(None)` for -/// another. -pub(super) fn second_output4( - cx: &SelectCx<'_>, - color: u32, -) -> Result>, Error> { - for (o, ty) in cx - .entry - .ep - .outputs - .iter() - .zip(stage_io::output_types(cx)?.1) - { - if let OutputRole::RenderTarget { - attachment: AbiInt::Const(c), - index: 1, - .. - } = o.role - { - if c == color { - let f = super::color::form(cx, ty)?; - let fmt = f.float_fmt().filter(|_| f.lanes == 4); - return Ok(Some( - fmt.filter(|f| matches!(f, FloatFmt::Half | FloatFmt::F32)), - )); - } - } - } - Ok(None) -} - /// The image operands of a fetched color's read or write in a multisampled image (an input /// attachment, or a pushed texture's fetch): the invocation's `SampleId` for a per-sample /// function (`FragmentPlan::fetch_sample`), none for one sample. @@ -409,64 +136,3 @@ pub(super) fn pixel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResul let y = fb.convert(ConvOp::ConvertFToU, fy, u32_)?; fb.composite_construct(uvec2, &[x, y]) } - -/// The second source the blend `b` of an extended-range attachment reads, where it reads one: -/// the function's second (index-1) output `second`, as it computed it. -pub(super) fn blend_second( - cx: &mut EmitCx<'_>, - b: &extended_range::blend::NativeBlend, - second: Option<(Form, SValue)>, -) -> BResult> { - match (b.reads_second(), second) { - (true, Some((_, s1))) => Ok(Some(s1)), - (true, None) => Err(cx.fail("a blend of the second source without its output")), - (false, _) => Ok(None), - } -} - -/// The blend color words the blend `b` reads (`PushField::HalfBlendColor`, the encoder's color's -/// `f32` bits), where it reads the blend color. -pub(super) fn blend_constant( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - b: &extended_range::blend::NativeBlend, -) -> BResult> { - if !b.reads_constant() { - return Ok(None); - } - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Ok(Some(fb.composite_extract(field, &[0])?)) -} - -/// `Ok` for an output of four `half` or `float` lanes (`output`, `None` for another), the outputs -/// an extended-range blend takes; else `Feature::ExtendedRangeBlend` `Output`. -pub(super) fn extended_range_output(output: Option) -> Result<(), Error> { - match output { - Some(FloatFmt::Half | FloatFmt::F32) => Ok(()), - _ => Err(Unsupported::not_implemented(Feature::ExtendedRangeBlend( - ExtendedRangeBlend::Output, - )) - .into()), - } -} - -/// The blend math of the function `cx` selects ([`extended_range::blend::BlendMath`]). -pub(super) fn blend_math(cx: &SelectCx<'_>) -> extended_range::blend::BlendMath { - extended_range::blend::BlendMath::of(cx.entry.compile.fast_math) -} - -/// The channels a write that keeps `kept` stores. -pub(super) fn written(kept: vk::ColorComponentFlags) -> ColorWriteMask { - [ - (vk::ColorComponentFlags::R, ColorWriteMask::RED), - (vk::ColorComponentFlags::G, ColorWriteMask::GREEN), - (vk::ColorComponentFlags::B, ColorWriteMask::BLUE), - (vk::ColorComponentFlags::A, ColorWriteMask::ALPHA), - ] - .into_iter() - .filter(|(k, _)| !kept.contains(*k)) - .fold(ColorWriteMask::NONE, |m, (_, c)| m.union(c)) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs b/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs deleted file mode 100644 index 553884ba4..000000000 --- a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! The extended-range blend's answer by the device's fetch ordering. - -use super::*; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::metal::PixelFormat; - -/// Committed profile `stem`. -fn profile(stem: &str) -> DeviceProfile { - let path = std::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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) - .expect("device") - .profile() - .clone() -} - -/// An extended-range format's blend (`extended_range_blend`): a padded form's taken where the device -/// orders fetch through rasterization-order input attachments, over which the function blends, and -/// refused naming that ordering elsewhere, the pixel interlock's devices included; one of Apple's -/// extended-range forms not implemented on every device (`codes_round_the_tile`); a bfloat form, -/// which Metal blends nowhere, Metal's refusal; any other format refused. -#[test] -fn an_extended_range_blend_needs_rasterization_order_fetch() { - let xr = [ - PixelFormat::BGR10XR, - PixelFormat::BGR10XRSRGB, - PixelFormat::BGRA10XR, - PixelFormat::BGRA10XRSRGB, - PixelFormat::RGB10A82PXR10, - PixelFormat::RGB10A82PXR10SRGB, - ]; - let not_implemented = Err(Unsupported::not_implemented(Feature::Format)); - let blended = [ - PixelFormat::R10UnormX6, - PixelFormat::R10UnormX6SRGB, - PixelFormat::RG10UnormX12, - PixelFormat::RG10UnormX12SRGB, - PixelFormat::RGB10A2UnormSRGB, - ]; - let bfloat = [ - PixelFormat::R16Bfloat, - PixelFormat::RG16Bfloat, - PixelFormat::RGBA16Bfloat, - ]; - let unordered = Err(Unsupported::needs( - Feature::FramebufferFetch, - Capability::Feature(VkFeature::RasterizationOrderColorAttachmentAccess), - )); - for (stem, ordered) in [ - ("lavapipe", true), - ("gate-lavapipe-x86_64", true), - ("moltenvk-m3", false), - ("amd-780m-radv", false), - ("intel-arl-anv", false), - ("intel-irisxe-anv", false), - ("nvidia-rtx5080-laptop", false), - ("nvidia-pascal-linux", false), - ("runtime-floor", false), - ] { - let p = profile(stem); - assert_eq!(inputs_order(&p), ordered, "{stem}"); - for pf in blended { - let want = if ordered { Ok(()) } else { unordered.clone() }; - assert_eq!(extended_range_blend(pf, &p), want, "{stem}: {pf:?}"); - } - for pf in xr { - assert_eq!( - extended_range_blend(pf, &p), - not_implemented, - "{stem}: {pf:?}" - ); - } - for pf in bfloat { - assert_eq!( - extended_range_blend(pf, &p), - Err(Unsupported::not_representable(Feature::Format)), - "{stem}: {pf:?}" - ); - } - assert_eq!( - extended_range_blend(PixelFormat::RGBA16Float, &p), - not_implemented, - "{stem}" - ); - } -} diff --git a/crates/metal2vulkan/src/lower/fragment/input_blend.rs b/crates/metal2vulkan/src/lower/fragment/input_blend.rs deleted file mode 100644 index 22ac4b6c3..000000000 --- a/crates/metal2vulkan/src/lower/fragment/input_blend.rs +++ /dev/null @@ -1,501 +0,0 @@ -//! The blend into an extended-range attachment on a device that orders framebuffer fetch through -//! rasterization-order input attachments: a padded one's (a blend into one of Apple's -//! extended-range forms is refused, `fetch::codes_round_the_tile`). -//! -//! Such an attachment holds Metal's raw texels in its raw unsigned format, which no device blends. -//! On a device that fetches through input attachments with rasterization-order access (lavapipe) -//! the function computes the blend over the attachment's input attachment: its first -//! output's write reads the pixel's raw texel there (at the invocation's sample in a multisampled -//! pipeline), decodes it to Metal's tile value (`extended_range::tile_value`, as a fetch reads it), -//! blends the output over that by the device's arithmetic (`extended_range::blend::native`, the -//! second source the function's index-1 output and the blend color push data, -//! `fetch::blend_second`, `fetch::blend_constant`), -//! and writes the kernel write's encode of the result as the raw texel through the output variable -//! (`extended_range::encode`), the channels a write mask keeps taken from the texel read -//! (`extended_range::encode_keeping`). The attachment then takes no Vulkan blend and every raw -//! component is written (link, from `RuntimeFact::ExtendedRangeInputBlend`). Rasterization-order -//! attachment access orders each fragment's read after every earlier fragment's write of the pixel, -//! so each blend reads the codes the one before stored (the announcement, -//! `extended-range-blends-stored-codes`, stays the runtime's there). On a device that does not -//! order fetch so, the blend is refused (`fetch::unordered_extended_fetch`). -//! -//! There too an unblended write of some of the codes one word holds (`BGR10_XR`'s word, the -//! two-plane forms' color word, `color_writes::merged_extended`), which no mask of the raw -//! components gives, reads the texel's raw codes through the input attachment and writes the -//! kernel write's encode of its output with the codes the mask keeps taken from them -//! (`extended_range::encode_keeping`), as Metal's tile keeps a masked channel's code; it states -//! `RuntimeFact::WordInputMerge`, and link writes every raw component. -//! -//! An attachment held with its channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`) whose blend no -//! Vulkan state on its image gives (`color_writes::shader_rotated_blend`) takes Metal's blend there -//! too ([`RotatedInputBlend`]): Metal blends the format as `RGBA8Unorm` with its channels rotated, so -//! the first output's write reads the pixel's texel through the input attachment, rotates it into -//! Metal's order, computes Metal's 8-bit unorm blend of the clamped output over it -//! (`extended_range::Blend::unorm8`, `extended_range::blend::blend_unorm8`), and writes the result through the output variable, which the stage interface -//! rotates into the image's order as every output to such an attachment -//! (`stage_io::output_part`); the device's conversion stores its code -//! (`PrecisionNote::DeviceColorConversion`), and the descriptor's write mask, rotated, keeps the -//! channels it leaves out. It states `RuntimeFact::RotatedInputBlend`, and link gives the -//! attachment no Vulkan blend. -//! -//! The blend takes a `half4` or `float4` output under every factor, operation and write mask -//! (another output is refused, `Feature::ExtendedRangeBlend` `Output`); its -//! second source is the function's index-1 output, read from the returned value and stored nowhere -//! else ([`select_second_output`]). A write of none of the format's channels stores nothing and -//! blends nothing. A padded attachment's blend is built so too; a bfloat attachment's is Metal's -//! pipeline error (`InvalidDescriptor(ColorAttachment)`, `stage_io::extended_color`). - -use std::collections::BTreeMap; - -use crate::air::abi::{AbiInt, OutputRole}; -use crate::air::ir::TypeId as AirTypeId; -use crate::error::{ - Attachment, DescriptorError, Error, ExtendedRangeBlend, Feature, MetalAnswer, RuntimeInput, - Unsupported, -}; -use crate::lower::arith::{extended_range, FloatFmt, Form}; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::metal::format::ExtendedRange; -use crate::metal::{ColorWriteMask, PixelFormat}; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::lower_inputs::BlendEquation; -use crate::pipeline::sym::{PushField, Stage}; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value as SValue; -use crate::vk; - -use super::fetch; - -/// An extended-range attachment whose blend the function computes over its input attachment. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct InputBlend { - /// The attachment's form. - pub form: ExtendedRange, - /// The pipeline's blend at the attachment; `None` for an unblended write of some of the codes - /// one word holds, which the function merges into the texel (see the module docs). - pub equation: Option, - /// The blend of the write, as the shader computes it; `None` where the write stores none of - /// the format's channels, and blends nothing. - pub blend: Option, - /// The format's channels the write keeps from the texel (those the descriptor's write mask - /// leaves out); empty where it stores every one, all four where it stores none. - pub kept: vk::ColorComponentFlags, - /// The returned value's field holding the function's second (index-1) output to the - /// attachment and its form, once the stage interface planned it, where the blend reads the - /// second source ([`select_second_output`]). - pub second: Option<(u32, Form)>, -} - -impl InputBlend { - /// Whether the write is unblended and keeps some of the format's codes from the texel it reads - /// (`color_writes::merged_extended`). - pub fn merges(&self) -> bool { - self.equation.is_none() - } - - /// Whether the write reads the attachment's input attachment: a blend, or a merge. - pub fn reads(&self) -> bool { - self.blend.is_some() || self.merges() - } -} - -/// An attachment held with its channels rotated (`ARGB8Unorm`) whose blend the function computes -/// over its input attachment (see the module docs). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct RotatedInputBlend { - /// The pipeline's blend at the attachment. - pub equation: BlendEquation, - /// Metal's channels the write stores: those the descriptor's write mask covers, none where it - /// covers none (the write then reads and blends nothing). - pub written: ColorWriteMask, -} - -impl RotatedInputBlend { - /// Whether the write reads the attachment's input attachment: it stores some channel. - pub fn reads(&self) -> bool { - !self.written.is_empty() - } -} - -/// Whether the device orders framebuffer fetch through rasterization-order input attachments, -/// where this module computes an extended-range blend (on another it is refused, -/// `fetch::unordered_extended_fetch`). -fn through_inputs(cx: &SelectCx<'_>) -> bool { - fetch::inputs_order(cx.profile) -} - -/// Plan the extended-range attachments the function writes through a first output where the -/// pipeline blends them (`LoweringInputs::extended_range_colors`), on a device that fetches -/// through input attachments, before the stage interface: each one whose write stores some of -/// its format's channels reads its input attachment, blends there, and states -/// `RuntimeFact::ExtendedRangeInputBlend` (see the module docs). -pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { - if cx.stage != Stage::Fragment || !through_inputs(cx) { - return Ok(()); - } - let blended = fetch::blended_extended_range(cx)?; - let Some(inputs) = cx.inputs.framebuffer_fetch.clone() else { - return match blended.is_empty() { - true => Ok(()), - false => Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)), - }; - }; - let mut planned = BTreeMap::new(); - for (color, ty) in blended { - let tied = |e: Error| e.at_attachment(Attachment::Color(color)); - let Some(form) = cx - .inputs - .extended_range_colors - .get(&color) - .map(|e| e.form) - .filter(|f| !f.bfloat()) - else { - // A bfloat attachment's blend is refused (`fetch::plan`). - continue; - }; - // Compiled under the state of a pipeline for another function. - let Some((attachment, eq)) = inputs - .attachments - .get(&color) - .copied() - .flatten() - .and_then(|a| a.equation.map(|eq| (a, eq))) - else { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - }; - let kept = fetch::kept_channels(attachment.pixel_format, attachment.write_mask, true); - let stores = kept != ColorWriteMask::ALL; - let kept = crate::metal::state::color_write_mask(kept).map_err(tied)?; - cx.facts.insert(RuntimeFact::ExtendedRangeInputBlend { - color, - blend: eq, - kept, - }); - cx.families.arith.converts(form); - // A write of none of the format's channels stores nothing: link gives it no channel. - if !stores { - let ib = InputBlend { - form, - equation: Some(eq), - blend: None, - kept, - second: None, - }; - planned.insert(color, ib); - continue; - } - let f = super::color::form(cx, ty).map_err(tied)?; - let output = (f.lanes == 4).then(|| f.float_fmt()).flatten(); - fetch::extended_range_output(output).map_err(tied)?; - let blend = - extended_range::blend::NativeBlend::of(&eq, fetch::written(kept)).map_err(tied)?; - // A blend of the second source reads the function's index-1 output, four `half` or - // `float` lanes as the first's. Without one, Metal refuses the pipeline ("Fragment shader - // does not write to render target color(0), index(1) that is required for blending"). - if blend.reads_second() { - match fetch::second_output4(cx, color).map_err(tied)? { - Some(Some(_)) => {} - Some(None) => { - let gap = Feature::ExtendedRangeBlend(ExtendedRangeBlend::Output); - return Err(tied(Unsupported::not_implemented(gap).into())); - } - None => { - let invalid = DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::NilWithError, - }; - return Err(Error::InvalidDescriptor(invalid)); - } - } - } - if blend.reads_constant() { - cx.push.insert(PushField::HalfBlendColor); - } - // The attachment's input attachment, which a `[[color(n)]]` read of it shares (`color`). - cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); - cx.facts.insert(RuntimeFact::FramebufferFetch { color }); - planned.insert( - color, - InputBlend { - form, - equation: Some(eq), - blend: Some(blend), - kept, - second: None, - }, - ); - } - merged(cx, &inputs, &mut planned)?; - let rotated = rotated(cx, &inputs)?; - let reads = - planned.values().any(InputBlend::reads) || rotated.values().any(RotatedInputBlend::reads); - cx.families.fragment.input_blends = planned; - cx.families.fragment.rotated_blends = rotated; - match reads { - true => fetch::plan_sample(cx), - false => Ok(()), - } -} - -/// Plan, into `planned`, the extended-range attachments the function writes through a first output -/// unblended under a mask of some of the codes one word holds, as the pipeline's state `inputs` -/// names them (`color_writes::merged_extended`): each reads its input attachment, merges the -/// written codes into the texel it reads, and states `RuntimeFact::WordInputMerge` with the -/// channels it keeps (see the module docs). -fn merged( - cx: &mut SelectCx<'_>, - inputs: &crate::pipeline::lower_inputs::FramebufferFetchInputs, - planned: &mut BTreeMap, -) -> Result<(), Error> { - let written: Vec = cx - .entry - .ep - .outputs - .iter() - .filter_map(|o| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } => Some(color), - _ => None, - }) - .collect(); - for color in written { - let Some(a) = inputs.attachments.get(&color).copied().flatten() else { - continue; - }; - let Some(form) = cx - .inputs - .extended_range_colors - .get(&color) - .filter(|e| !e.blended) - .map(|e| e.form) - else { - continue; - }; - let merges = crate::pipeline::color_writes::merges_extended; - if !merges(a.pixel_format, a.write_mask, a.blending_enabled) { - continue; - } - let tied = |e: Error| e.at_attachment(Attachment::Color(color)); - let kept = fetch::kept_channels(a.pixel_format, a.write_mask, true); - let kept = crate::metal::state::color_write_mask(kept).map_err(tied)?; - cx.facts.insert(RuntimeFact::WordInputMerge { color, kept }); - cx.facts.insert(RuntimeFact::FramebufferFetch { color }); - cx.families.arith.converts(form); - cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); - planned.insert( - color, - InputBlend { - form, - equation: None, - blend: None, - kept, - second: None, - }, - ); - } - Ok(()) -} - -/// Plan the attachments held with their channels rotated that the function writes through a first -/// output and the pipeline's state `inputs` names (`color_writes::shader_rotated_blend`, the only -/// reason such an attachment is named on this device): each one whose write stores some of its -/// channels reads its input attachment and computes Metal's 8-bit unorm blend there, and each -/// states `RuntimeFact::RotatedInputBlend` (see the module docs). -fn rotated( - cx: &mut SelectCx<'_>, - inputs: &crate::pipeline::lower_inputs::FramebufferFetchInputs, -) -> Result, Error> { - let mut planned = BTreeMap::new(); - let outputs: Vec<(u32, AirTypeId)> = cx - .entry - .ep - .outputs - .iter() - .zip(crate::lower::stage_io::output_types(cx)?.1) - .filter_map(|(o, ty)| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } => Some((color, ty)), - _ => None, - }) - .collect(); - for (color, ty) in outputs { - let Some(a) = inputs.attachments.get(&color).copied().flatten() else { - continue; - }; - if !crate::metal::format::rotated_channels(a.pixel_format) - || !cx.inputs.rotated_colors.contains(&color) - { - continue; - } - let tied = |e: Error| e.at_attachment(Attachment::Color(color)); - let Some(eq) = a.equation.filter(|_| a.blending_enabled) else { - // Compiled under the state of a pipeline for another function. - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - }; - let kept = fetch::kept_channels(a.pixel_format, a.write_mask, true); - let written = ColorWriteMask::ALL.difference(kept); - let kept = crate::metal::state::color_write_mask(kept).map_err(tied)?; - cx.facts.insert(RuntimeFact::RotatedInputBlend { - color, - blend: eq, - kept, - }); - let rb = RotatedInputBlend { - equation: eq, - written: match kept == vk::ColorComponentFlags::known_bits() { - true => ColorWriteMask::NONE, - false => written, - }, - }; - if rb.reads() { - let f = super::color::form(cx, ty).map_err(tied)?; - let arith = match (f.lanes, f.float_fmt()) { - (4, Some(FloatFmt::Half)) => extended_range::blend::BlendArith::Half, - (4, Some(FloatFmt::F32)) => extended_range::blend::BlendArith::Float, - // An output of fewer lanes to a rotated attachment (`stage_io`). - _ => { - let refused = Unsupported::not_implemented(Feature::Format); - return Err(tied(refused.into())); - } - }; - let math = fetch::blend_math(cx); - let b = extended_range::Blend::unorm8( - &eq, - PixelFormat::ARGB8Unorm, - rb.written, - (math, arith), - ) - .map_err(tied)?; - if b.reads_constant() { - cx.push.insert(PushField::HalfBlendColor); - } - // The attachment's input attachment. - cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); - cx.facts.insert(RuntimeFact::FramebufferFetch { color }); - // The result is the device's to convert to its code; the blend is Metal's where the - // module states its math (Metal clamps the output first, so none of the output's - // arithmetic folds into it). - cx.precision.insert(PrecisionNote::DeviceColorConversion); - if cx.entry.compile.fast_math.is_none() { - let note = crate::lower::arith::output_precision::half_output_note(cx); - cx.precision.insert(note); - } - } - planned.insert(color, rb); - } - Ok(planned) -} - -/// Whether the function's second (index-1) output to `color` is the second source of the blend -/// the function computes over the attachment's input attachment ([`select_second_output`]). -pub(super) fn blends_second(cx: &SelectCx<'_>, color: u32) -> bool { - cx.families - .fragment - .input_blends - .get(&color) - .and_then(|ib| ib.blend.as_ref()) - .is_some_and(extended_range::blend::NativeBlend::reads_second) -} - -/// Plan the second (index-1) output of AIR type `ty` held in field `field` of the returned value -/// to attachment `color`, whose blend the function computes over its input attachment and reads -/// the second source ([`blends_second`]): the blend reads it, clamped as the first output; no -/// interface variable holds it. -pub fn select_second_output( - cx: &mut SelectCx<'_>, - field: u32, - color: u32, - ty: AirTypeId, -) -> Result<(), Error> { - let form = super::color::form(cx, ty)?; - let Some(ib) = cx.families.fragment.input_blends.get_mut(&color) else { - return Err(cx.invariant("a second output of an attachment no input blend writes")); - }; - ib.second = Some((field, form)); - Ok(()) -} - -/// The raw texel, as a `uvec4`, a write of output `part` (of `form`; the second source `second` -/// where the blend reads it) to attachment `color` stores, whose blend the function computes over -/// its input attachment (`ib`; see the module docs). For a write that stores none of the -/// format's channels, the unblended output's, which link stores nowhere. -pub(crate) fn texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (color, ib): (u32, &InputBlend), - (form, part): (Form, SValue), - second: Option<(Form, SValue)>, -) -> BResult { - let kept = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ] - .map(|c| ib.kept.contains(c)); - let Some(b) = &ib.blend else { - if !ib.merges() { - return crate::lower::stage_io::extended_color::texel(fb, ib.form, form, part); - } - // The unblended write's `half`, encoded, the codes the mask keeps taken from the texel. - let codes = super::color::input_texel(cx, fb, color)?; - let v = crate::lower::stage_io::extended_color::held(fb, ib.form, form, part)?; - return extended_range::encode_keeping(fb, ib.form, v, (codes, kept)); - }; - let s1 = fetch::blend_second(cx, b, second)?; - let codes = super::color::input_texel(cx, fb, color)?; - let d = extended_range::tile_value(fb, ib.form, codes)?; - let constant = fetch::blend_constant(cx, fb, b)?; - let v = extended_range::blend::native(fb, b, (part, s1, d), constant)?; - if ib.kept.is_empty() { - return extended_range::encode(fb, ib.form, v); - } - extended_range::encode_keeping(fb, ib.form, v, (codes, kept)) -} - -/// The Metal-ordered value a write of first output `part` (of `form`: four `half` or `float` -/// lanes held as `f32`s) to attachment `color`, held with its channels rotated, stores, whose blend -/// the function computes over its input attachment (`rb`; see the module docs): the texel read -/// there, rotated into Metal's order, and Metal's 8-bit unorm blend of the output over it -/// (`extended_range::blend::blend_unorm8`), the blend color from `PushField::HalfBlendColor` where -/// the blend reads it. For a write that stores none of the format's channels, the output. -pub(crate) fn rotated_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (color, rb): (u32, &RotatedInputBlend), - (form, part): (Form, SValue), -) -> BResult { - if !rb.reads() { - return Ok(part); - } - let arith = match (form.lanes, form.float_fmt()) { - (4, Some(FloatFmt::Half)) => extended_range::blend::BlendArith::Half, - (4, Some(FloatFmt::F32)) => extended_range::blend::BlendArith::Float, - _ => return Err(cx.fail("an 8-bit unorm blend of another output")), - }; - let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); - let pf = PixelFormat::ARGB8Unorm; - let Ok(b) = extended_range::Blend::unorm8(&rb.equation, pf, rb.written, (math, arith)) else { - return Err(cx.fail("an 8-bit unorm blend outside Metal's model")); - }; - let texel = super::color::input_texel(cx, fb, color)?; - // The image's red, green, blue and alpha hold Metal's alpha, red, green and blue. - let texel = fb.vector_shuffle(texel, texel, &[1, 2, 3, 0])?; - let constant = match b.reads_constant() { - true => { - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Some(fb.composite_extract(field, &[0])?) - } - false => None, - }; - extended_range::blend::blend_unorm8(fb, &b, arith, (part, texel), constant) -} diff --git a/crates/metal2vulkan/src/lower/fragment/logic.rs b/crates/metal2vulkan/src/lower/fragment/logic.rs index b2fd61b8e..649c4f324 100644 --- a/crates/metal2vulkan/src/lower/fragment/logic.rs +++ b/crates/metal2vulkan/src/lower/fragment/logic.rs @@ -1,78 +1,28 @@ -//! The private logic operation of a render pipeline (`LoweringInputs::logic_operation`), computed -//! by the fragment function on a device without Vulkan's `logicOp`. +//! The formats of a render pipeline's private logic operation (`pipeline::private_state`): those +//! whose channels Metal's operation takes per channel ([`channels`]), and where Vulkan's `logicOp` +//! may store another code than Metal's ([`vulkan_differs`]). //! //! Metal applies the operation to the code of each channel of a normalized or integer attachment //! the function writes, the fragment's code against the stored one, blending ignored and the write -//! mask kept after it (`pipeline::private_state`'s module docs). On a device that orders -//! framebuffer fetch through rasterization-order input attachments, the function's first output's -//! write to such an attachment reads the pixel's texel through the attachment's input attachment, -//! and stores the operation's result itself ([`operated`]): +//! mask kept after it (`pipeline::private_state`'s module docs). A signed normalized channel reads +//! its lowest code, `-2^(n-1)`, as -1, as it reads the code above it, and stores a result of the +//! lowest code as -1, the code above (probe `logic_operation`, an Apple M3 Max under macOS +//! 27.0.1); Vulkan's `logicOp` takes and stores the lowest code itself. A 10-bit unorm format +//! (`RGB10A2Unorm`, `BGR10A2Unorm`) operates on 16-bit codes: Metal widens each stored code to 16 +//! bits (`round(d * 65535 / max)`), operates on it and the output's 16-bit code, and stores the +//! result narrowed back to the channel's code, rounded to nearest (the same probe), where Vulkan's +//! operation takes the channel's own code. //! -//! - the stored codes from the texel the read gives: a normalized channel's value times its -//! largest code, rounded to nearest even (exact: the read's value is a code over that largest -//! code), an integer channel's bits; -//! - the fragment's codes from its output by the device's own arithmetic: a normalized channel's -//! value clamped (`NClamp`: a NaN the low end, 0, or -1 for a signed channel, as Metal's logic -//! operation takes it) times its largest code in `float`, rounded to nearest even -//! (`RoundEven`), where Metal rounds the exact product to nearest; the two differ only where -//! the `float` product rounds onto or across a half-code tie -//! (`PrecisionNote::DeviceColorConversion`); an integer channel's value saturated to the -//! channel's range, as Metal saturates it; -//! - the operation of the two, by bits, in the channel's width; -//! - the result written as the value the device's write stores as that code: a normalized code -//! over the largest code, an integer's bits. -//! -//! A signed normalized channel reads its lowest code, `-2^(n-1)`, as -1, as it reads the code -//! above it, and stores a result of the lowest code as -1, the code above: so does Metal's logic -//! operation (probe `logic_operation`, an Apple M3 Max under macOS 27.0.1). Vulkan's `logicOp` -//! takes and stores the lowest code itself ([`vulkan_differs`]). A channel the write does not -//! store (outside the write mask, and every channel under no-op, which draws unwritten) keeps -//! its lowest code over an input attachment, where Metal's pass stores the code above: -//! `PrecisionNote::SnormMinimumKept`, as for any draw into such an attachment. -//! -//! A 10-bit unorm format (`RGB10A2Unorm`, `BGR10A2Unorm`) operates on 16-bit codes: Metal widens -//! each stored code to 16 bits (`round(d * 65535 / max)`), operates on it and the output's 16-bit -//! code, and stores the result narrowed back to the channel's code, rounded to nearest (the same -//! probe: every texel of every operation into both formats, written whole and under masks). The -//! function computes it as a 16-bit channel's: the read's value times 65535, the output's code at -//! 16 bits, and the result over 65535, which the device's write narrows (the device's conversion -//! again, `PrecisionNote::DeviceColorConversion`). -//! -//! The formats this serves ([`channels`]): every channel an 8-, 10- or 16-bit unorm one, an 8- or -//! 16-bit snorm one, or an 8-, 16- or 32-bit integer one. Metal's operation into a packed 16-bit -//! format is not a per-channel rule of either width (the same probe: a `B5G6R5Unorm` copy stores a -//! code past the rounded product), nor is `RGB10A2Uint`'s (it saturates the operation's 32-bit -//! result), and is refused there (`pipeline::private_state::logic_operation`). So is a write the -//! operation would read otherwise than as the format's codes: a narrower integer output than 32 -//! bits ([`takes`]), an attachment held through a word view, and one held with its channels -//! rotated or with Metal's alpha in red. -//! -//! The write mask applies after the operation: the device's write mask keeps the channels it leaves -//! out. Each read is ordered after every earlier fragment's write of the pixel (rasterization-order -//! attachment access), so overlapping fragments operate in primitive order, as -//! Metal's do; a multisampled pipeline's function runs per sample and operates on its own sample's -//! codes. +//! The formats Metal's operation takes per channel ([`channels`]): every channel an 8-, 10- or +//! 16-bit unorm one, an 8- or 16-bit snorm one, or an 8-, 16- or 32-bit integer one. A device +//! without `logicOp` would have the function compute the operation over an ordered read of the +//! attachment, which is not built: `pipeline::private_state` refuses the pipeline there naming +//! `logicOp`. -use std::collections::BTreeMap; - -use crate::air::abi::{AbiInt, OutputRole}; -use crate::air::ir::TypeId as AirTypeId; -use crate::error::{Attachment, Error, Feature, PrivateRenderField, Unsupported}; -use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::ops; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; use crate::metal::format::{write_conversion, WriteConversion}; use crate::metal::PixelFormat; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::ChannelWrite; -use crate::pipeline::sym::{SampledType, Stage}; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value as SValue; -use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type as SType, UnOp}; -use crate::vk; +use crate::pipeline::sym::SampledType; /// How an attachment's channels hold their codes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -83,7 +33,7 @@ pub enum LogicNumeric { Sint, } -/// The channels of an attachment the function computes the logic operation of ([`channels`]). +/// The channels of an attachment Metal's logic operation takes per channel ([`channels`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LogicChannels { pub numeric: LogicNumeric, @@ -93,8 +43,8 @@ pub struct LogicChannels { pub bits: [Option; 4], } -/// The channels of a color attachment of `pf` whose logic operation the function computes (see -/// the module docs): every channel an 8-, 10- or 16-bit unorm one (a 10-bit format's alpha 2-bit), +/// The channels of a color attachment of `pf` Metal's logic operation takes per channel (see the +/// module docs): every channel an 8-, 10- or 16-bit unorm one (a 10-bit format's alpha 2-bit), /// an 8- or 16-bit snorm one, or an 8-, 16- or 32-bit integer one; `None` for another format. pub(crate) fn channels(pf: PixelFormat) -> Option { match write_conversion(pf)? { @@ -167,366 +117,5 @@ fn widens(pf: PixelFormat) -> bool { }) } -/// The read class of an attachment of `channels`: `float` texels for a normalized format, `uint` -/// ones for an integer format (a signed one's bits). -pub(crate) fn reads_float(channels: LogicChannels) -> bool { - matches!(channels.numeric, LogicNumeric::Unorm | LogicNumeric::Snorm) -} - -fn u32_ty(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Int { - width: 32, - signed: false, - }) -} - -fn i32_ty(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Int { - width: 32, - signed: true, - }) -} - -fn f32_ty(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Float { width: 32 }) -} - -fn u32_value(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = fb.u32_const(v)?; - fb.module().const_value(c) -} - -fn f32_value(fb: &mut FunctionBuilder<'_>, v: f32) -> BResult { - let one = Form { - held: Held::Float(FloatFmt::F32), - lanes: 1, - }; - ops::fsplat(fb, one, f64::from(v)) -} - -fn i32_value(fb: &mut FunctionBuilder<'_>, v: i32) -> BResult { - let one = Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 1, - }; - let bits = ops::splat(fb, one, u64::from(v as u32))?; - let i32_ = i32_ty(fb)?; - fb.convert(ConvOp::Bitcast, bits, i32_) -} - -/// `op` of the source code `s` and the stored code `d` (`u32`s), by bits, unmasked. -fn operate(fb: &mut FunctionBuilder<'_>, op: vk::LogicOp, s: SValue, d: SValue) -> BResult { - use vk::LogicOp as L; - let not = |fb: &mut FunctionBuilder<'_>, x| fb.unary(UnOp::Not, x); - Ok(match op { - L::CLEAR => u32_value(fb, 0)?, - L::SET => u32_value(fb, u32::MAX)?, - L::COPY => s, - L::COPY_INVERTED => not(fb, s)?, - L::NO_OP => d, - L::INVERT => not(fb, d)?, - L::AND => fb.binary(BinOp::BitwiseAnd, s, d)?, - L::NAND => { - let x = fb.binary(BinOp::BitwiseAnd, s, d)?; - not(fb, x)? - } - L::OR => fb.binary(BinOp::BitwiseOr, s, d)?, - L::NOR => { - let x = fb.binary(BinOp::BitwiseOr, s, d)?; - not(fb, x)? - } - L::XOR => fb.binary(BinOp::BitwiseXor, s, d)?, - L::EQUIVALENT => { - let x = fb.binary(BinOp::BitwiseXor, s, d)?; - not(fb, x)? - } - L::AND_REVERSE => { - let nd = not(fb, d)?; - fb.binary(BinOp::BitwiseAnd, s, nd)? - } - L::AND_INVERTED => { - let ns = not(fb, s)?; - fb.binary(BinOp::BitwiseAnd, ns, d)? - } - L::OR_REVERSE => { - let nd = not(fb, d)?; - fb.binary(BinOp::BitwiseOr, s, nd)? - } - // `OR_INVERTED`, the last of Metal's sixteen. - _ => { - let ns = not(fb, s)?; - fb.binary(BinOp::BitwiseOr, ns, d)? - } - }) -} - -/// The largest code of a channel of `bits` of `numeric` (a normalized one's). -fn largest(numeric: LogicNumeric, bits: u32) -> f32 { - match numeric { - LogicNumeric::Snorm => ((1u32 << (bits - 1)) - 1) as f32, - _ => ((1u64 << bits) - 1) as f32, - } -} - -/// The mask of a channel of `bits`. -fn mask_of(bits: u32) -> u32 { - match bits { - 32 => u32::MAX, - b => (1u32 << b) - 1, - } -} - -/// One channel: the operation `op` of the output lane `x` (an `f32` for a normalized channel, the -/// `u32` bits of an integer one) over the stored lane `stored` (the read's `f32`, or `u32` bits), -/// in a channel of `bits` of `numeric`, as the lane written (see the module docs). -fn channel( - fb: &mut FunctionBuilder<'_>, - op: vk::LogicOp, - (numeric, bits): (LogicNumeric, u32), - x: SValue, - stored: SValue, -) -> BResult { - let u32_ = u32_ty(fb)?; - let i32_ = i32_ty(fb)?; - let mask = u32_value(fb, mask_of(bits))?; - let (s, d) = match numeric { - LogicNumeric::Unorm | LogicNumeric::Snorm => { - let max = f32_value(fb, largest(numeric, bits))?; - let lo = f32_value( - fb, - if numeric == LogicNumeric::Snorm { - -1.0 - } else { - 0.0 - }, - )?; - let one = f32_value(fb, 1.0)?; - let clamped = fb.glsl(GlslOp::NClamp, &[x, lo, one])?; - let scaled = fb.binary(BinOp::FMul, clamped, max)?; - let s = fb.glsl(GlslOp::RoundEven, &[scaled])?; - let read = fb.binary(BinOp::FMul, stored, max)?; - let d = fb.glsl(GlslOp::RoundEven, &[read])?; - match numeric { - LogicNumeric::Unorm => ( - fb.convert(ConvOp::ConvertFToU, s, u32_)?, - fb.convert(ConvOp::ConvertFToU, d, u32_)?, - ), - _ => { - let s = fb.convert(ConvOp::ConvertFToS, s, i32_)?; - let d = fb.convert(ConvOp::ConvertFToS, d, i32_)?; - ( - fb.convert(ConvOp::Bitcast, s, u32_)?, - fb.convert(ConvOp::Bitcast, d, u32_)?, - ) - } - } - } - // Saturated to the channel's range, as Metal saturates an integer write. - LogicNumeric::Uint => { - let s = match bits { - 32 => x, - _ => fb.glsl(GlslOp::UMin, &[x, mask])?, - }; - (s, stored) - } - LogicNumeric::Sint => { - let s = match bits { - 32 => x, - _ => { - let signed = fb.convert(ConvOp::Bitcast, x, i32_)?; - let lo = i32_value(fb, -(1i32 << (bits - 1)))?; - let hi = i32_value(fb, (1i32 << (bits - 1)) - 1)?; - let c = fb.glsl(GlslOp::SClamp, &[signed, lo, hi])?; - fb.convert(ConvOp::Bitcast, c, u32_)? - } - }; - (s, stored) - } - }; - let d = fb.binary(BinOp::BitwiseAnd, d, mask)?; - let r = operate(fb, op, s, d)?; - let r = fb.binary(BinOp::BitwiseAnd, r, mask)?; - // The value the device's write stores as the code: a signed code's bits sign-extended. - let signed = |fb: &mut FunctionBuilder<'_>, r: SValue| -> BResult { - if bits == 32 { - return fb.convert(ConvOp::Bitcast, r, i32_); - } - let shift = u32_value(fb, 32 - bits)?; - let up = fb.binary(BinOp::ShiftLeftLogical, r, shift)?; - let up = fb.convert(ConvOp::Bitcast, up, i32_)?; - fb.binary(BinOp::ShiftRightArithmetic, up, shift) - }; - match numeric { - LogicNumeric::Unorm => { - let f32_ = f32_ty(fb)?; - let v = fb.convert(ConvOp::ConvertUToF, r, f32_)?; - let max = f32_value(fb, largest(numeric, bits))?; - fb.binary(BinOp::FDiv, v, max) - } - LogicNumeric::Snorm => { - let f32_ = f32_ty(fb)?; - let r = signed(fb, r)?; - let v = fb.convert(ConvOp::ConvertSToF, r, f32_)?; - let max = f32_value(fb, largest(numeric, bits))?; - fb.binary(BinOp::FDiv, v, max) - } - LogicNumeric::Uint => Ok(r), - LogicNumeric::Sint => { - let r = signed(fb, r)?; - fb.convert(ConvOp::Bitcast, r, u32_) - } - } -} - -/// The value a write of output `part` (of `form`: one to four `f32` lanes of a `half` or `float` -/// output, or `u32` lanes of an integer one) stores in an attachment of `channels` under Metal's -/// logic operation `op`, over the attachment's texel `texel` in Metal's channel order (four `f32` -/// lanes for a normalized format, four `u32` lanes of an integer one's bits), in the output's form -/// (see the module docs). A lane the format lacks is the output's. -pub(crate) fn operated( - fb: &mut FunctionBuilder<'_>, - op: vk::LogicOp, - channels: LogicChannels, - (form, part): (Form, SValue), - texel: SValue, -) -> BResult { - let mut lanes = Vec::with_capacity(usize::from(form.lanes)); - for (lane, bits) in (0..u32::from(form.lanes)).zip(channels.bits) { - let x = match form.lanes { - 1 => part, - _ => fb.composite_extract(part, &[lane])?, - }; - let Some(bits) = bits else { - lanes.push(x); - continue; - }; - let stored = fb.composite_extract(texel, &[lane])?; - lanes.push(channel(fb, op, (channels.numeric, bits), x, stored)?); - } - match lanes.as_slice() { - [one] => Ok(*one), - _ => { - let ty = ops::ty(fb, form)?; - fb.composite_construct(ty, &lanes) - } - } -} - -/// Whether the operation takes an output of `form` to an attachment of `channels`: a `float` or -/// `half` output for a normalized format, a 32-bit integer one for an integer format (a narrower -/// integer output's operation is not built). -pub(crate) fn takes(channels: LogicChannels, form: Form) -> bool { - match reads_float(channels) { - true => form.is_float(), - false => matches!(form.held, Held::Int { bits: 32, .. }), - } -} - -/// The refusal of the operation at attachment `color` where the function's write there is outside -/// what this module computes. -pub(crate) fn refused(color: u32) -> Error { - let gap = Feature::PrivateRenderState(PrivateRenderField::LogicOperation); - Unsupported::not_implemented(gap) - .at_attachment(Attachment::Color(color)) - .into() -} - -/// An attachment whose logic operation the function computes over its input attachment, on a -/// device that orders framebuffer fetch through rasterization-order input attachments (see the -/// module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct LogicInput { - /// The pipeline's operation. - pub op: vk::LogicOp, - /// The attachment's channels. - pub channels: LogicChannels, -} - -/// Plan the attachments the function writes through a first output under the pipeline's private -/// logic operation (`LoweringInputs::logic_operation`) on a device that orders framebuffer fetch -/// through input attachments, before the stage interface: each one whose format the operation -/// serves ([`channels`]) and that the pipeline's state names (`FramebufferFetchInputs`) reads its -/// input attachment, and states `RuntimeFact::FramebufferFetch`; a normalized one's codes are the -/// device's conversion (`PrecisionNote::DeviceColorConversion`). An attachment held through a -/// word, with its channels rotated, or with Metal's alpha in red, and an output the operation does -/// not take ([`takes`]), are refused naming the operation. -pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { - let Some(op) = cx.inputs.logic_operation else { - return Ok(()); - }; - if cx.stage != Stage::Fragment || !super::fetch::inputs_order(cx.profile) { - return Ok(()); - } - let outputs: Vec<(u32, AirTypeId)> = cx - .entry - .ep - .outputs - .iter() - .zip(crate::lower::stage_io::output_types(cx)?.1) - .filter_map(|(o, ty)| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } => Some((color, ty)), - _ => None, - }) - .collect(); - let mut planned = BTreeMap::new(); - for (color, ty) in outputs { - let Some(pf) = cx - .inputs - .framebuffer_fetch - .as_ref() - .and_then(|i| i.attachments.get(&color).copied().flatten()) - .map(|a| a.pixel_format) - else { - continue; - }; - let Some(channels) = channels(pf) else { - continue; - }; - let held_otherwise = cx.inputs.word_colors.contains_key(&color) - || cx.inputs.rotated_colors.contains(&color) - || cx.inputs.alpha_in_red_colors.contains(&color); - let form = - super::color::form(cx, ty).map_err(|e| e.at_attachment(Attachment::Color(color)))?; - if held_otherwise || !takes(channels, form) { - return Err(refused(color)); - } - cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); - cx.facts.insert(RuntimeFact::FramebufferFetch { color }); - if reads_float(channels) { - cx.precision.insert(PrecisionNote::DeviceColorConversion); - } - planned.insert(color, LogicInput { op, channels }); - } - let reads = !planned.is_empty(); - cx.families.fragment.logic_inputs = planned; - match reads { - true => super::fetch::plan_sample(cx), - false => Ok(()), - } -} - -/// The value a write of first output `part` (of `form`) to attachment `color` stores, whose logic -/// operation the function computes over its input attachment ([`plan`]): the operation of the -/// output's codes over those of the texel read there ([`operated`]). -pub(crate) fn input_operated( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - (form, part): (Form, SValue), -) -> BResult { - let Some(li) = cx.plan.families.fragment.logic_inputs.get(&color).copied() else { - return Err(cx.fail("a logic operation of an attachment the plan does not name")); - }; - let texel = super::color::input_texel(cx, fb, color)?; - operated(fb, li.op, li.channels, (form, part), texel) -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/lower/fragment/logic/tests.rs b/crates/metal2vulkan/src/lower/fragment/logic/tests.rs index 624329154..79083fc31 100644 --- a/crates/metal2vulkan/src/lower/fragment/logic/tests.rs +++ b/crates/metal2vulkan/src/lower/fragment/logic/tests.rs @@ -1,4 +1,4 @@ -//! The formats the function's logic operation serves, and the outputs it takes. +//! The formats Metal's logic operation takes per channel, and where Vulkan's differs. use super::*; @@ -86,25 +86,3 @@ fn vulkan_s_operation_differs_on_10_bit_and_signed_codes_alone() { assert!(!vulkan_differs(pf), "{pf:?}"); } } - -/// A normalized format takes a `float` or `half` output, an integer one a 32-bit integer output. -#[test] -fn the_operation_takes_its_class_s_outputs() { - let unorm = channels(PixelFormat::RGBA8Unorm).expect("served"); - let uint = channels(PixelFormat::RGBA8Uint).expect("served"); - let form = |held| Form { held, lanes: 4 }; - let float = form(Held::Float(FloatFmt::F32)); - let half = form(Held::Float(FloatFmt::Half)); - let int32 = form(Held::Int { - bits: 32, - container: 32, - }); - let int16 = form(Held::Int { - bits: 16, - container: 32, - }); - assert!(takes(unorm, float) && takes(unorm, half)); - assert!(!takes(unorm, int32)); - assert!(takes(uint, int32)); - assert!(!takes(uint, int16) && !takes(uint, float)); -} diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index ada0bb5fb..0abb88995 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -6,9 +6,7 @@ //! family declares, and [`emit_return`] kills a discarded invocation before `OpReturn`. //! - **Framebuffer fetch** (`[[color(n)]]` inputs): each color index is one input attachment //! (`color`), read at every use. Compiled for a multisampled pipeline, it reads the invocation's -//! own sample at `SampleId`, which runs the function once per covered sample, as Metal does. On a device that orders the read through -//! rasterization-order input attachments, a blend into an extended-range attachment is computed -//! over its input attachment (`input_blend`). +//! own sample at `SampleId`, which runs the function once per covered sample, as Metal does. //! - **Raster order groups** (`rog`): a function that names a group runs its body as a function //! called from `main` between `Begin/EndInvocationInterlockEXT` ([`wrap_entry`], the //! entry-wrapper hook of `lower::emit`); inside it a discard only records `discarded`, and `main` @@ -41,11 +39,9 @@ mod color; mod coverage; mod discard; pub(crate) mod fetch; -mod input_blend; mod interpolate; mod logic; mod rog; -mod word_input; pub(crate) use color::texture_decl; @@ -79,19 +75,8 @@ use crate::spirv::ir::{ pub use color::ColorInput; pub use coverage::CoveragePlan; pub use discard::DiscardForm; -pub(crate) use fetch::{ - compiled_write_mask, extended_range_blend, half_float_format, inputs_order, kept_channels, -}; -pub(crate) use input_blend::{rotated_texel as rotated_input_texel, texel as input_blend_texel}; -pub use input_blend::{ - select_second_output as select_input_second_output, InputBlend, RotatedInputBlend, -}; -pub use logic::LogicInput; -pub(crate) use logic::{ - channels as logic_channels, input_operated as logic_input_operated, - vulkan_differs as logic_vulkan_differs, -}; -pub(crate) use word_input::merge as word_input_merge; +pub(crate) use fetch::half_float_format; +pub(crate) use logic::vulkan_differs as logic_vulkan_differs; fn not_lowered() -> Error { Unsupported::not_implemented(Feature::Lowering(LowerFamily::Fragment)).into() @@ -158,27 +143,13 @@ pub struct FragmentPlan { /// Every used color input (framebuffer fetch), in parameter order. pub colors: Vec, /// The color attachments the function reads through the set-1 sampled-texture array's element - /// the consumer pushes for each (`PushField::FetchedColor`), under the identity domains on a - /// device that orders fetch in neither form (`color`), by index: the class of the element's + /// the consumer pushes for each (`PushField::FetchedColor`), under the identity domains + /// (`color`), by index: the class of the element's /// image, whose array the texture family declares (`texture::declare`). pub texture_fetches: BTreeMap, /// The function is in a raster order group: its body runs inside this interlock mode's /// critical section, called from the entry [`wrap_entry`] builds. pub interlock: Option, - /// The extended-range attachments whose blend the function computes over their input - /// attachments, on a device that orders fetch through them (`input_blend`), by index. - pub input_blends: BTreeMap, - /// The attachments held with their channels rotated whose blend the function computes over - /// their input attachments, on a device that orders fetch through them (`input_blend`), by - /// index. - pub rotated_blends: BTreeMap, - /// The word attachments whose word the function merges into the texel's over their input - /// attachments, on a device that orders fetch through them (`word_input`), by index: the bits - /// of the fields each write keeps from the texel. - pub word_merges: BTreeMap, - /// The attachments whose private logic operation the function computes over their input - /// attachments, on a device that orders fetch through them (`logic`), by index. - pub logic_inputs: BTreeMap, /// The stage interface's `FragCoord` object, which gives the pixel a color read through a /// pushed texture fetches (`texture_fetches`). pub fetch_coord: Option, @@ -345,8 +316,6 @@ pub fn declare( d.attachments = color::declare( mb, &fp.colors, - (&fp.input_blends, &fp.word_merges), - (&fp.rotated_blends, &fp.logic_inputs), fp.fetch_sample.is_some(), &fp.texture_fetches, )?; @@ -445,13 +414,9 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error Ok(()) } -/// Plan the entry's framebuffer-fetch forms before its stage interface. Then the loop over the -/// covered samples, which decides how the stage interface reads `[[sample_id]]` and the -/// sample-qualified varyings. +/// Plan the entry's loop over the covered samples before its stage interface, which decides how +/// the stage interface reads `[[sample_id]]` and the sample-qualified varyings. pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { - input_blend::plan(cx)?; - word_input::plan(cx)?; - logic::plan(cx)?; coverage::plan(cx) } @@ -461,37 +426,6 @@ pub fn loops_samples(cx: &SelectCx<'_>) -> bool { cx.families.fragment.coverage.is_some_and(|c| c.looped) } -/// The extended-range write of attachment `color` the shader computes over the input attachment -/// (`input_blend`): the pipeline's blend there (`None` -/// for an unblended write and for a write that stores none of the format's channels), the -/// attachment's form, and whether the write stores none of its channels. `None` where the -/// function writes the attachment otherwise (or not at all). -pub(crate) fn shader_blend( - cx: &SelectCx<'_>, - color: u32, -) -> Option<( - Option, - crate::metal::format::ExtendedRange, - bool, -)> { - let fp = &cx.families.fragment; - fp.input_blends.get(&color).map(|ib| { - let blends = ib.blend.is_some(); - ( - blends.then_some(ib.equation).flatten(), - ib.form, - !blends && !ib.merges(), - ) - }) -} - -/// Whether the function's second (index-1) output to `color` is the second source of the -/// extended-range blend it computes over the attachment's input attachment, outside the stage -/// interface. -pub fn blends_second_through_inputs(cx: &SelectCx<'_>, color: u32) -> bool { - input_blend::blends_second(cx, color) -} - /// The work before the body, in the function's first block: place the fragment's tile in the /// pass's tile memory. pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { diff --git a/crates/metal2vulkan/src/lower/fragment/rog.rs b/crates/metal2vulkan/src/lower/fragment/rog.rs index 2bc566a6a..46b99ea95 100644 --- a/crates/metal2vulkan/src/lower/fragment/rog.rs +++ b/crates/metal2vulkan/src/lower/fragment/rog.rs @@ -27,10 +27,8 @@ //! output alone does not interlock the function, so a function whose groups hold nothing else //! compiles on every device, the ones without an interlock included. //! -//! **Color inputs without an ordered fetch**. On a device without rasterization-order color -//! attachment access (`fetch::fetch_unordered`), a color input reads its input attachment ordered -//! between draws alone, by the consumer's barriers (under the identity domains, the attachment's -//! pushed texture). A group on such an input, or on a color output of an attachment the +//! **Color inputs**. A color input reads its input attachment ordered between draws alone, by the +//! consumer's barriers (under the identity domains, the attachment's pushed texture; `fetch`). A group on such an input, or on a color output of an attachment the //! function reads, asks for the order of that read, which is the read's own there: it does not //! interlock the function, since the interlock cannot order the attachment's own write, which //! happens after the function, and the read's fragments of one draw stay unordered @@ -89,33 +87,16 @@ fn role_layouts(role: &ParamRole) -> [Option; 2] { /// attachment), or an argument-buffer or imageblock member of a layout its used parameters and its /// outputs reach. `e.structs` holds every layout of the module, so a layout only another function /// names does not count. A group's color output the function does not read needs none, and neither -/// does a group on a parameter the body never uses, nor, on a device with neither ordered fetch -/// form, a group on a color input or on a color output of an attachment the function reads -/// ([module docs](self)). +/// does a group on a parameter the body never uses, nor a group on a color input or on a color +/// output of an attachment the function reads ([module docs](self)). pub(super) fn declared(cx: &SelectCx<'_>) -> bool { let e = cx.entry; let used = &crate::lower::users::params_used(cx.body); let params = || e.ep.params.iter().filter(move |b| used.contains(&b.param)); - let read = |attachment| { - params() - .any(|b| matches!(b.role, ParamRole::ColorInput { index, .. } if index == attachment)) - }; - // Whether a group on a color read interlocks: not where the read is ordered between draws - // alone. - let colors = !super::fetch::fetch_unordered(cx.profile); - let named = params().any(|b| { - role_group(&b.role).is_some() && (colors || !matches!(b.role, ParamRole::ColorInput { .. })) - }); - let outputs = colors - && e.ep.outputs.iter().any(|o| match o.role { - OutputRole::RenderTarget { - attachment, - raster_order_group: Some(_), - .. - } => read(attachment), - _ => false, - }); - if named || outputs { + // A group on a color read does not interlock: the read is ordered between draws alone. + let named = params() + .any(|b| role_group(&b.role).is_some() && !matches!(b.role, ParamRole::ColorInput { .. })); + if named { return true; } let mut stack: Vec = params() diff --git a/crates/metal2vulkan/src/lower/fragment/word_input.rs b/crates/metal2vulkan/src/lower/fragment/word_input.rs deleted file mode 100644 index 308642442..000000000 --- a/crates/metal2vulkan/src/lower/fragment/word_input.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Metal's write of some of a word attachment's channels on a device that orders framebuffer fetch -//! through rasterization-order input attachments. -//! -//! An attachment the device renders through a view of its word (`metal::format::WordAttachment`) -//! has one component, which the device writes whole, so the device's write mask cannot keep a -//! field of it. On a device that orders fetch through input attachments with rasterization-order -//! access (lavapipe) the function reads the texel's word through the attachment's input attachment -//! at its first output's write (at the invocation's sample in a multisampled pipeline) and stores -//! Metal's word of the output (`stage_io::word_color::encode`) with the fields of the channels the -//! descriptor's write mask leaves out taken from the word read, as Metal's tile keeps them. Link -//! writes the whole word (`RuntimeFact::WordInputMerge`). Rasterization-order attachment access -//! orders each fragment's read after every earlier fragment's write of the pixel, so each merge -//! keeps what the fragments before it stored. -//! -//! The function compiles under the descriptor's mask (`LoweringInputs::framebuffer_fetch`), which -//! is the descriptor's own for the formats this merges, the 8-bit sRGB words -//! (`color_writes::merged_word`); a stage linked into a pipeline of another mask there was -//! compiled for another pipeline, `NeedsInput(FramebufferFetch)` (`link::fetch::word_merges`). - -use std::collections::BTreeMap; - -use crate::air::abi::{AbiInt, OutputRole}; -use crate::error::{Attachment, Error}; -use crate::lower::arith::{ops, Form, Held}; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::metal::format::WordAttachment; -use crate::metal::ColorWriteMask; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::Stage; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value as SValue; -use crate::spirv::ir::BinOp; - -use super::fetch; - -/// The bits of `word`'s fields of the channels `kept`. -fn kept_bits(word: WordAttachment, kept: ColorWriteMask) -> u32 { - [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ColorWriteMask::ALPHA, - ] - .into_iter() - .zip(word.fields()) - .filter_map(|(channel, field)| field.filter(|_| kept.contains(channel))) - .fold(0, |bits, f| bits | ((1u32 << f.bits) - 1) << f.shift) -} - -/// Plan the word attachments the function writes through a first output under a write mask of -/// some of their channels, on a device that fetches through input attachments, before the stage -/// interface: each one the pipeline's state names (`FramebufferFetchInputs`) reads its input -/// attachment and keeps the fields of the channels the mask leaves out, and states -/// `RuntimeFact::WordInputMerge` (see the module docs). -pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { - if cx.stage != Stage::Fragment || !fetch::inputs_order(cx.profile) { - return Ok(()); - } - let Some(inputs) = cx.inputs.framebuffer_fetch.clone() else { - return Ok(()); - }; - let written: Vec = cx - .entry - .ep - .outputs - .iter() - .filter_map(|o| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } => Some(color), - _ => None, - }) - .collect(); - let mut planned = BTreeMap::new(); - for color in written { - let Some(word) = cx.inputs.word_colors.get(&color).copied() else { - continue; - }; - let Some(a) = inputs.attachments.get(&color).copied().flatten() else { - continue; - }; - // A mask of every channel or none writes the word whole (`color_writes::word_color`). - let kept = fetch::kept_channels(a.pixel_format, a.write_mask, true); - if kept.is_empty() || kept == ColorWriteMask::ALL { - continue; - } - let flags = crate::metal::state::color_write_mask(kept) - .map_err(|e| e.at_attachment(Attachment::Color(color)))?; - cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); - cx.facts.insert(RuntimeFact::FramebufferFetch { color }); - cx.facts - .insert(RuntimeFact::WordInputMerge { color, kept: flags }); - planned.insert(color, kept_bits(word, kept)); - } - let merges = !planned.is_empty(); - cx.families.fragment.word_merges = planned; - match merges { - true => fetch::plan_sample(cx), - false => Ok(()), - } -} - -/// The word a write stores to attachment `color`, whose fields `kept` (bits) it takes from the -/// texel's word read through the attachment's input attachment, and the rest from `word`, Metal's -/// word of the output (see the module docs). -pub(crate) fn merge( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - kept: u32, - word: SValue, -) -> BResult { - let u = Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 1, - }; - let texel = super::color::input_texel(cx, fb, color)?; - let read = fb.composite_extract(texel, &[0])?; - let keep = ops::splat(fb, u, u64::from(kept))?; - let take = ops::splat(fb, u, u64::from(!kept))?; - let read = fb.binary(BinOp::BitwiseAnd, read, keep)?; - let word = fb.binary(BinOp::BitwiseAnd, word, take)?; - fb.binary(BinOp::BitwiseOr, read, word) -} diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 36f1405cf..8ecbceed3 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1418,9 +1418,6 @@ fn select_body( select_params(cx, &used)?; // The member-wise phis' representations, before any use of one is selected. arith::aggregate::plan_phis(cx, m)?; - // A blended extended-range output, whose blend the function computes by the device's - // arithmetic. - arith::output_precision::note_extended_range_sources(cx)?; // The `half` chains' operations held at `float` precision, before any of them is selected. cx.families.arith.held_at_float = arith::half_chain::plan(cx, m)?; diff --git a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs index 02057baa6..ae7519382 100644 --- a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs +++ b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs @@ -25,19 +25,12 @@ //! refuses it (`ColorAttachment`). So is a blend into a bfloat attachment, whatever the function //! writes there (`InvalidDescriptor(ColorAttachment)`: Metal's pipeline validation asserts that //! the format is not blendable). A `bfloat` output is refused before, as Metal's compiler rejects -//! it. The blend of another form, a padded one's included, is the function's own, over an ordered -//! read of the attachment (below), and a dual-source second output to such an attachment is that -//! blend's second source: on a device that does not order fetch the blend is refused naming what -//! it needs (`fetch::unordered_extended_fetch`: `rasterizationOrderColorAttachmentAccess`). A blend -//! into one -//! of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` -//! twins) is not implemented on any device (`Feature::Format`, `fetch::codes_round_the_tile`): -//! only a padded form's blend is built. -//! -//! On a device that orders framebuffer fetch through rasterization-order input attachments, a blend -//! the function computes over the attachment's input attachment (`lower::fragment`'s `input_blend`) -//! is built: the output's write stores the raw texel of Metal's blend over the texel the input -//! attachment reads, which `stage_io` writes through the output variable as it writes [`encode`]'s. +//! it. A blend into one of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, +//! `RGB10A8_2P_XR10` and their `_sRGB` twins) is not implemented on any device (`Feature::Format`, +//! `fetch::codes_round_the_tile`). A padded form's blend would be the function's own, over an +//! ordered read of the attachment, which is not built: it is refused on every device +//! (`fetch::computed_write_refused`). A dual-source second output to such an attachment is stored +//! nowhere, as an unblended write reads none. use crate::error::{DescriptorError, Error, Feature, MetalAnswer, Unsupported}; use crate::lower::arith::extended_range; @@ -92,14 +85,12 @@ pub(super) fn plan( if e.blended && crate::lower::fragment::fetch::codes_round_the_tile(e.form) { return Err(Unsupported::not_implemented(Feature::Format).into()); } - let blended = e.blended && !cx.families.fragment.input_blends.contains_key(&color); - // A blend the function computes over an ordered read of the attachment (over the input - // attachment, `lower::fragment`), on a device that does not order fetch: refused naming the - // ordering. - if blended && crate::lower::fragment::fetch::fetch_unordered(cx.profile) { - return Err(crate::lower::fragment::fetch::unordered_extended_fetch().into()); + // A padded form's blend, which the function would compute over an ordered read of the + // attachment. + if e.blended { + return Err(crate::lower::fragment::fetch::computed_write_refused().into()); } - if blended || !matches!(fmt, FloatFmt::F32 | FloatFmt::Half) { + if !matches!(fmt, FloatFmt::F32 | FloatFmt::Half) { return Err(Unsupported::not_implemented(Feature::Format).into()); } cx.families diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index fde3f11c0..3ee5a1e46 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -2153,54 +2153,11 @@ fn output_part( None => part, }; let part = match o.color { - // An extended-range attachment's blend the function computes over its input attachment. - Some(color) if cx.plan.families.fragment.input_blends.contains_key(&color) => { - input_blended(cx, fb, (x, returned), color, (o.link.form, part))? - } - // An attachment held with its channels rotated whose blend the function computes over its - // input attachment, in Metal's order: the rotation below takes it into the image's. - Some(color) - if cx - .plan - .families - .fragment - .rotated_blends - .contains_key(&color) => - { - let plan = cx.plan; - let Some(rb) = plan.families.fragment.rotated_blends.get(&color) else { - return Err( - cx.fail("a rotated input blend of an attachment the plan does not name") - ); - }; - let v = crate::lower::fragment::rotated_input_texel( - cx, - fb, - (color, rb), - (o.link.form, part), - )?; - color_write::round(cx, fb, color, o.link.form, v)? - } - // The pipeline's private logic operation over the attachment's input attachment. - Some(color) if cx.plan.families.fragment.logic_inputs.contains_key(&color) => { - let v = - crate::lower::fragment::logic_input_operated(cx, fb, color, (o.link.form, part))?; - color_write::round(cx, fb, color, o.link.form, v)? - } Some(color) => match ( cx.plan.families.stage_io.words_written.get(&color).copied(), cx.plan.families.stage_io.extended.get(&color).copied(), ) { - (Some(w), _) => { - let word = word_color::encode(fb, w, (o.link.form, part))?; - // A write of some of the word's channels over the attachment's input attachment. - match cx.plan.families.fragment.word_merges.get(&color).copied() { - Some(kept) => { - crate::lower::fragment::word_input_merge(cx, fb, color, kept, word)? - } - None => word, - } - } + (Some(w), _) => word_color::encode(fb, w, (o.link.form, part))?, (None, Some(e)) => extended_color::encode(fb, e, o.link.form, part)?, (None, None) => color_write::round(cx, fb, color, o.link.form, part)?, }, @@ -2216,31 +2173,6 @@ fn output_part( Ok(part) } -/// The raw components a write of first output `part` (of `form`) to extended-range attachment -/// `color` stores, whose blend the function computes over the attachment's input attachment -/// (`lower::fragment`'s `input_blend`), the second source read from the returned value `x` (of -/// shape `returned`) where the blend reads it. -fn input_blended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (x, returned): (SValue, Returned), - color: u32, - (form, part): (Form, SValue), -) -> BResult { - let plan = cx.plan; - let Some(ib) = plan.families.fragment.input_blends.get(&color) else { - return Err(cx.fail("an input blend of an attachment the plan does not name")); - }; - let second = match (ib.second, returned) { - (Some((field, form)), Returned::Struct) => Some((form, fb.composite_extract(x, &[field])?)), - (Some(_), _) => return Err(cx.fail("a second output outside a returned structure")), - (None, _) => None, - }; - let texel = - crate::lower::fragment::input_blend_texel(cx, fb, (color, ib), (form, part), second)?; - extended_color::raw_components(fb, ib.form, texel) -} - /// The second output `s` holds beside the first output `first`, as the function returns it /// (`LoweringInputs::rotated_factors`): each channel of the image a copy of one of `first`'s /// channels, or `0` or `1`, so the blend's `SRC1` factors read the values Metal's factors read. diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 8bdbeeb03..df9c05f2b 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2153,19 +2153,9 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { if cx.stage == Stage::Fragment && cx.inputs.rotated_factors.contains_key(&color) { continue; } - // The second source of an extended-range blend the function computes over the - // attachment's input attachment, which the blend reads from the returned value. - if cx.stage == Stage::Fragment - && crate::lower::fragment::blends_second_through_inputs(cx, color) - { - crate::lower::fragment::select_input_second_output(cx, o.field, color, ty) - .map_err(|e| e.at_attachment(Attachment::Color(color)))?; - continue; - } - // Every other write of an extended-range attachment (the raw texel's through the - // interface, or over the input attachment unblended) reads no second - // output, as Metal's write there reads none: it is stored nowhere, where the - // interface's raw texel refused it `Format`. + // A write of an extended-range attachment (the raw texel's through the interface) + // reads no second output, as Metal's unblended write there reads none: it is stored + // nowhere, where the interface's raw texel refused it `Format`. if cx.stage == Stage::Fragment && cx.inputs.extended_range_colors.contains_key(&color) { continue; } @@ -2990,12 +2980,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { } cx.families.stage_io.interface.alpha_test = Some(function); } - // The render pipeline's private logic operation, which the function's writes compute - // (`lower::fragment`'s `logic`): recorded for link, whether or not the function writes an - // attachment the operation serves. - if cx.stage == Stage::Fragment { - cx.families.stage_io.interface.logic_operation = cx.inputs.logic_operation; - } // The render pipeline's private masks a fragment function applies itself: its `SampleMask` // output, the function's own where it writes one, which each return ANDs the pixel's mask // into or stores it as; and the `FragCoord` input whose pixel picks the mask, where the masks diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 3a51bf6c2..0b5fea409 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -154,8 +154,7 @@ pub enum FormatEmulation { /// rotates too; Metal stores, clears, masks, resolves and blends the format as `RGBA8Unorm` /// with its channels rotated. Admitted for those usages, and for blending /// through the factors `pipeline::rotated_blend` finds Metal's blend in; a blend no such - /// factor gives the fragment function computes over the texel where the device orders - /// framebuffer fetch (`pipeline::color_writes::shader_rotated_blend`). + /// factor gives is refused (`pipeline::color_writes::rotated_blend_in_shader`). RotatedView, /// A render pass's color attachment of a two-plane YCbCr format Metal renders into /// ([`ycbcr_renders`]): `R32G32B32A32_SFLOAT` of the values the pass leaves in each texel (the @@ -1029,25 +1028,6 @@ fn copies_only_repr(pf: PixelFormat) -> Repr { color(vec![combined(format, FormatEmulation::CopiesOnly)]) } -/// Whether a render pipeline on `profile` blends into a color attachment of `pf`, one of Apple's -/// extended-range formats ([`ExtendedRange::of`]). No device blends such an attachment's raw -/// texels: the fragment function computes Metal's blend in the shader from the texel it reads -/// through the attachment's input attachment. `Ok` where the device orders fetch through -/// rasterization-order input attachments and that blend holds for an attachment of `pf` written -/// whole under a blend Metal's model holds (a padded 10-bit form's); else what blocks it (on a -/// device without rasterization-order color attachment access, `Feature::FramebufferFetch` naming -/// that feature). `BGR10_XR`, `BGRA10_XR`, -/// `RGB10A8_2P_XR10` and their `_sRGB` twins answer `NotImplemented(Format)` on every device: Metal's -/// tile holds such an attachment as `half` through the render pass, which the codes the attachment -/// holds do not keep, so its blend over an earlier draw's write is not built. A pipeline's own -/// blend, write mask or output may still be refused by name (`Feature::ExtendedRangeBlend`), as -/// [`rotated_channels`]' blends are per pipeline. A bfloat format answers `NotRepresentable(Format)`: -/// Metal blends none (`compile_render_pipeline` refuses such a blend -/// `InvalidDescriptor(ColorAttachment)`). Another format answers `NotImplemented(Format)`. -pub fn extended_range_blend(pf: PixelFormat, profile: &DeviceProfile) -> Result<(), Unsupported> { - crate::lower::fragment::extended_range_blend(pf, profile) -} - /// The texel extent of one block of the compressed format `pf`, `None` for an uncompressed one. /// /// Metal states this nowhere: `MTLPixelFormat` has no block-extent getter, and a program that diff --git a/crates/metal2vulkan/src/metal/format/word.rs b/crates/metal2vulkan/src/metal/format/word.rs index 89c24efb0..5edb04a4f 100644 --- a/crates/metal2vulkan/src/metal/format/word.rs +++ b/crates/metal2vulkan/src/metal/format/word.rs @@ -25,10 +25,9 @@ //! by Metal's twelve-bit table, as `pack_float_to_srgb_unorm4x8` encodes a color channel. The //! fragment function encodes the channel by the MSL transfer through the device's `Pow`, as its //! `pack_float_to_srgb_unorm4x8` does (`lower::arith::pack`, `PrecisionNote::DevicePackConversion`). A write -//! of some of its channels merges the word into the texel's over the attachment's input attachment -//! on a device that orders fetch through rasterization-order input attachments -//! (`color_writes::merged_word`), and is refused as the device lacking the format elsewhere. A -//! blend of such an attachment, other than one and zero, is not built. +//! of some of its channels takes the format's own attachment, refused as the device lacking the +//! format: its merge into the texel over an ordered read of the attachment is not built. A blend +//! of such an attachment, other than one and zero, is not built. //! //! Metal's store of a `float` output into `RGB9E5Float` (measured on the M3 Max: 65,536 draws and //! clears, and the format scout's draws): each of red, green and blue clamped to `[0, 65408]` (a @@ -38,13 +37,9 @@ //! folds the conversion into the store): that store is not built. //! //! A blend of factors one and zero, added, stores the same (Metal's draws through it matched too). -//! A write mask of some of the format's channels keeps the other fields: on a device that orders -//! fetch through rasterization-order input attachments, the fragment function merges an 8-bit -//! sRGB word into the word its input attachment holds (`lower::fragment`'s `word_input`). The -//! device blends no such view, resolves none, and reads none as the format's input attachment: a -//! pipeline that blends a word attachment, covers by its alpha, or writes some of a packed 16-bit -//! or `RGB9E5Float` word's channels is refused as the device lacking the format's attachment, as -//! without the view. A fragment function's color input of a word attachment is +//! The device blends no such view, resolves none, and reads none as the format's input attachment: +//! a pipeline that blends a word attachment, covers by its alpha, or writes some of a word's +//! channels is refused as the device lacking the format's attachment, as without the view. A fragment function's color input of a word attachment is //! `NotImplemented(Format)`. //! //! A multisampled texture of such a format is held in the word's format where the device renders diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 65412eeb4..0a28b9458 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -315,28 +315,6 @@ mod serde_round_trips { multisampled: true, replay_bindings: true, merged_draws: true, - framebuffer_fetch: Some(FramebufferFetchInputs { - attachments: BTreeMap::from([ - ( - 0, - Some(FetchedAttachment { - pixel_format: metal::PixelFormat::RGBA32Float, - blending_enabled: true, - write_mask: metal::ColorWriteMask::RED, - replaces: true, - equation: Some(crate::pipeline::BlendEquation { - source_rgb: metal::BlendFactor::One, - destination_rgb: metal::BlendFactor::Zero, - rgb_operation: metal::BlendOperation::Add, - source_alpha: metal::BlendFactor::One, - destination_alpha: metal::BlendFactor::Zero, - alpha_operation: metal::BlendOperation::Add, - }), - }), - ), - (2, None), - ]), - }), srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]), ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]), ycbcr_planes_sampled: BTreeMap::from([( @@ -423,7 +401,6 @@ mod serde_round_trips { unattached_colors: BTreeSet::from([5, 7]), sample_mask: Some([0b1010, 0b0010, 0b1000, 0]), alpha_test: Some(metal::CompareFunction::GreaterEqual), - logic_operation: Some(crate::vk::LogicOp::XOR), depth_compare_clamp_mask: 0x8000_0005, rotated_colors: BTreeSet::from([4]), alpha_in_red_colors: BTreeSet::from([4]), @@ -561,7 +538,6 @@ mod serde_round_trips { input_attachment_index: 0, format_class: SampledType::Float, }], - rasterization_order_attachment_access: true, max_vertex_amplification_count: 2, declares_layer: true, tessellation: Some(TessellationState { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 06ee841b9..4135c39f6 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1026,18 +1026,6 @@ pub enum PrecisionNote { /// than Metal (3,527 of 94,732,288 channels measured a code apart, none further). `RGBA8Unorm` /// and `RGB10A2Unorm` hold their codes there, as the device does. /// - /// Also: a blend the function computes over the input attachment of an attachment held with - /// its channels rotated (`ARGB8Unorm`), whose result the device's color write converts to its - /// code, where Metal rounds the exact product with 255 (a NaN 0); the write may take the other - /// code near a tie. - /// - /// Also: a render pipeline's private logic operation the fragment function computes on a - /// device without Vulkan's `logicOp` (`LoweringInputs::logic_operation`), into an 8- or 16-bit - /// unorm or snorm attachment: the function converts its output to the codes it operates on by - /// the device's arithmetic, the `float` product with the channel's largest code rounded to - /// nearest even, where Metal rounds the exact product to nearest; the two take different codes - /// only where the `float` product rounds onto or across a half-code tie. - /// /// Also (the runtime announces it): a render pass clears a normalized, sRGB, packed 16-bit, /// half or small-float color attachment to a color whose conversion is in question. The device /// converts the clear color, which Vulkan lets store either of the two codes closest to a @@ -1214,39 +1202,6 @@ pub enum PrecisionNote { /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review, deferred in C3 until an exact path exists. HalfOutputPrecision, - /// A fragment function's `half` color output (a scalar or vector of AIR's `half`) is blended - /// into a padded 10-bit attachment (`R10Unorm_X6`, `RG10Unorm_X12`, their `_sRGB` twins, - /// `RGB10A2Unorm_sRGB`), whose raw codes no device's blend unit reads, so the function blends - /// in the shader (`lower::arith::extended_range::blend::native`), in the device's arithmetic: a - /// blend unit's `S·Fs op D·Fd` in `float`, in the blend equation's order, the source, the - /// second source and the blend color unclamped, as Metal takes them there (a blend into one of - /// Apple's extended-range forms, `BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` - /// twins, is refused). The device's compiler may contract a product into - /// its sum and may regroup the blend: MoltenVK on the M3 Max and NVIDIA's driver on an RTX 5080 - /// compute a second source's blend `S·F + D·(1 - F)` as `D + F·(S - D)`. Metal's compiler - /// folds the blend into the function and fuses, regroups and rounds each step to `half` - /// instead, so a blended channel may store another code than Metal's: within two codes on a - /// linear format and within six on an sRGB twin near zero, where its transfer is steepest, in - /// the conformance suite's extended-range and padded blend cases (its known gaps' rows); and - /// where the device's compiler regroups a padded format's blend, an infinite second source - /// stores the end code its sign picks where Metal's sum is NaN, stored as code 0. Recorded - /// for every blended output that stores a channel, under either math. A `float` output - /// records [`PrecisionNote::ExtendedRangeFloatBlendSource`] instead, so a function of both - /// records both. - /// - /// Validation derives no tolerance and no explanation from it: a difference stays a - /// mismatch for review. - ExtendedRangeBlendSource, - /// [`PrecisionNote::ExtendedRangeBlendSource`] for a `float` color output (a scalar or vector - /// of AIR's `float`): blended into a padded 10-bit attachment in the shader - /// in the device's arithmetic, which the device's compiler may contract and regroup, where - /// Metal's compiler rounds the output and each step of the blend to `half`. A blended channel - /// may store another code than Metal's, within `ExtendedRangeBlendSource`'s bound. Its own - /// note, apart from the `half` output's, so a consumer can tell the two apart. - /// - /// Validation derives no tolerance and no explanation from it: a difference stays a - /// mismatch for review. - ExtendedRangeFloatBlendSource, /// The module samples a texture through an anisotropic sampler with Metal's anisotropic /// filter emulated by the device's samples at explicit levels (`lower::sampler::anisotropic`), /// on a device without `samplerAnisotropy`, every Vulkan sampler being isotropic there, each @@ -1877,19 +1832,17 @@ pub enum PrecisionNote { /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review. ExtrapolatedInterpolation, - /// A fragment function reads a color attachment (framebuffer fetch) on a device without - /// rasterization-order color attachment access. It reads - /// the attachment as an input attachment, and the consumer records a barrier of the subpass's + /// A fragment function reads a color attachment (framebuffer fetch), on every device. It + /// reads the attachment as an input attachment, and the consumer records a barrier of the subpass's /// dependency on itself, by region, from the color writes of the draws before to the input /// attachment reads of a draw that fetches (and from those reads to the color writes of the /// draws after): a fetch reads what every earlier draw stored at its pixel, Metal's answer. /// Under the identity domains it reads the attachment's texture at its own pixel instead /// ([`PushField::FetchedColor`](crate::pipeline::PushField::FetchedColor)), and the /// consumer orders each fetching draw after the earlier draws of its pass by a barrier between - /// them. Vulkan orders nothing between the overlapping fragments of one draw - /// (`GraphicsState::rasterization_order_attachment_access` false), where Metal orders them in - /// primitive order: a fragment that covers a pixel an earlier fragment of its own draw - /// covered may read the texel from before that fragment's write, and its own write may land + /// them. Vulkan orders nothing between the overlapping fragments of one draw, where Metal + /// orders them in primitive order: a fragment that covers a pixel an earlier fragment of its + /// own draw covered may read the texel from before that fragment's write, and its own write may land /// before that one. Exact for a draw whose primitives do not overlap at a pixel (one /// fullscreen triangle, a rectangle of two triangles, disjoint quads); otherwise each such /// pixel holds the result of some order of the draw's fragments there, not necessarily @@ -1913,8 +1866,8 @@ pub enum PrecisionNote { /// green 938 where Metal's rule gives 937, and its xor of `0xe0` over an `RGBA8Snorm` /// channel's `0x80` stored `0x60` where Metal's gives `0x61`. The distance is not bounded, /// since the operation's result follows the codes' bits, not their values. A device without - /// `logicOp` computes Metal's rule in the fragment function and records none. The fragment - /// stage records it whatever the specialization. + /// `logicOp` refuses the operation. The fragment stage records it whatever the + /// specialization. /// /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review. diff --git a/crates/metal2vulkan/src/pipeline/color_writes.rs b/crates/metal2vulkan/src/pipeline/color_writes.rs index 70d77ee22..a8674d4b5 100644 --- a/crates/metal2vulkan/src/pipeline/color_writes.rs +++ b/crates/metal2vulkan/src/pipeline/color_writes.rs @@ -328,11 +328,9 @@ pub(crate) fn extended_range_colors( /// Whether color attachment `c`, of an extended-range form that holds its three color codes in /// one raw component (`BGR10_XR`, the two-plane forms' color word, and their `_sRGB` twins), is /// written unblended under a mask of some of those codes ([`merges_extended`]): no mask of the -/// raw components keeps one code of a word and writes another, so the fragment function merges its -/// codes into the word it reads first, over the attachment's input attachment -/// (`lower::fragment`'s `input_blend`, `RuntimeFact::WordInputMerge`) where the device orders -/// fetch through rasterization-order input attachments. On a device that does not order fetch so, -/// link names the ordering the merge needs (`lower::fragment::fetch::unordered_extended_fetch`). +/// raw components keeps one code of a word and writes another, and the fragment function's merge +/// of its codes into the word over an ordered read of the attachment is not built, so link refuses +/// it (`lower::fragment::fetch::computed_write_refused`). pub(crate) fn merged_extended(c: &ColorAttachmentDescriptor) -> bool { merges_extended(c.pixel_format, c.write_mask, c.blending_enabled) } @@ -355,11 +353,10 @@ pub(crate) fn merges_extended( /// render pipeline, described by `c`, that covers by alpha where `alpha_to_coverage` /// (`LoweringInputs::word_colors`): `metal::format::WordAttachment::of` the attachment's format, /// where the pipeline writes it unblended (or blended with factors one and zero, added, which -/// Metal stores alike), under a write mask of all of the format's channels or none, or of some of -/// them where the function merges the word into the texel over its input attachment -/// ([`merged_word`]), and it is not attachment 0 under alpha-to-coverage (whose coverage reads the -/// output's alpha as computed). `None` for every other attachment: one that takes its format's own -/// attachment, as the device has it or not. +/// Metal stores alike), under a write mask of all of the format's channels or none, and it is not +/// attachment 0 under alpha-to-coverage (whose coverage reads the output's alpha as computed). +/// `None` for every other attachment: one that takes its format's own attachment, as the device +/// has it or not. pub(crate) fn word_color( index: u32, c: &ColorAttachmentDescriptor, @@ -369,9 +366,8 @@ pub(crate) fn word_color( let word = metal::format::WordAttachment::of(c.pixel_format, p)?; let kept = c.write_mask & word_channels(word); let whole = kept.is_empty() || kept == word_channels(word); - let merged = merges_over_input(c, word, p); let unblended = !c.blending_enabled || replaces(c); - (unblended && (whole || merged) && !(index == 0 && alpha_to_coverage)).then_some(word) + (unblended && whole && !(index == 0 && alpha_to_coverage)).then_some(word) } /// The channels of `word`'s fields: Metal's red, green, blue and alpha, in its field order. @@ -384,40 +380,6 @@ fn word_channels(word: metal::format::WordAttachment) -> metal::ColorWriteMask { .fold(M::NONE, |m, (bit, _)| m | bit) } -/// Whether the fragment function merges its word of attachment `c` (a `word` attachment) into the -/// texel over the attachment's input attachment: a write mask of some of the word's channels, on a -/// device that orders framebuffer fetch through rasterization-order input attachments -/// (`lower::fragment`'s `word_input`), for a format whose mask the function compiles as the -/// descriptor sets it (`lower::fragment::fetch::kept_at_draw` false: the 8-bit sRGB words, where a -/// packed 16-bit or `RGB9E5Float` word's mask stands for its class). -fn merges_over_input( - c: &ColorAttachmentDescriptor, - word: metal::format::WordAttachment, - p: &DeviceProfile, -) -> bool { - let channels = word_channels(word); - let kept = c.write_mask & channels; - let partial = !kept.is_empty() && kept != channels; - partial - && !crate::lower::fragment::fetch::kept_at_draw(c.pixel_format) - && crate::lower::fragment::inputs_order(p) -} - -/// The channels the fragment function keeps from the texel of color attachment `index` of a -/// render pipeline, described by `c`, that covers by alpha where `alpha_to_coverage`, where it -/// merges its word into the texel over the attachment's input attachment ([`word_color`], -/// `lower::fragment`'s `word_input`): those of the word's channels the write mask leaves out. -/// `None` for every other attachment. -pub(crate) fn merged_word( - index: u32, - c: &ColorAttachmentDescriptor, - alpha_to_coverage: bool, - p: &DeviceProfile, -) -> Option { - let word = word_color(index, c, alpha_to_coverage, p)?; - merges_over_input(c, word, p).then(|| word_channels(word).difference(c.write_mask)) -} - /// The word attachments of a render pipeline whose color attachments are `colors` (covering by /// alpha where `alpha_to_coverage`) on `p`, by color index ([`word_color`]). pub(crate) fn word_colors( @@ -555,26 +517,15 @@ pub(crate) fn wanted_alpha_in_red( out } -/// Whether the fragment function computes Metal's blend into color attachment `c` of a render -/// pipeline on `p` itself, over the texel it reads: an attachment held with its channels rotated -/// (`ARGB8Unorm` in `R8G8B8A8_UNORM`, `metal::format::rotated_channels`) whose blend no Vulkan -/// state on the rotated image gives (`rotated_blend` refuses it `NotImplemented(Format)`: Metal's -/// destination alpha in a color factor, the saturated source alpha, the blend color's red, green -/// or blue, different color and alpha operations), whose factors read no second source, on a -/// device that orders framebuffer fetch (`lower::fragment::fetch`). Metal blends the format as -/// `RGBA8Unorm` with its channels rotated, so the function computes Metal's 8-bit unorm blend -/// (`extended_range::Blend::unorm8`, which takes every factor and operation but the second -/// source's) over the texel rotated into Metal's order, over the attachment's input attachment -/// where the device orders fetch through rasterization-order input attachments -/// (`lower::fragment`'s `input_blend`). A device that does not order fetch so refuses the pipeline -/// (`fetch::unordered_extended_fetch`, at link). -pub(crate) fn shader_rotated_blend(c: &ColorAttachmentDescriptor, p: &DeviceProfile) -> bool { - rotated_blend_in_shader(c, p) && !crate::lower::fragment::fetch::fetch_unordered(p) -} - -/// Whether the blend of color attachment `c` of a render pipeline on `p` is one the fragment -/// function computes over the texel where the device orders framebuffer fetch -/// ([`shader_rotated_blend`]'s, whatever the device's orderings). +/// Whether the blend into color attachment `c` of a render pipeline on `p` is one the fragment +/// function would compute itself over an ordered read of the attachment, which is not built (link +/// refuses it, `lower::fragment::fetch::computed_write_refused`): an attachment held with its +/// channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`, `metal::format::rotated_channels`) whose +/// blend no Vulkan state on the rotated image gives (`rotated_blend` refuses it +/// `NotImplemented(Format)`: Metal's destination alpha in a color factor, the saturated source +/// alpha, the blend color's red, green or blue, different color and alpha operations), whose +/// factors read no second source. One whose factors read a second source stays +/// `NotImplemented(Format)`. pub(crate) fn rotated_blend_in_shader(c: &ColorAttachmentDescriptor, p: &DeviceProfile) -> bool { use metal::BlendFactor as F; if !metal::format::rotated_channels(c.pixel_format) || !c.blending_enabled { diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 177a529a5..f7acf29ed 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -104,10 +104,7 @@ pub enum InputsFrom<'a> { /// inputs, the attachments among the pipeline's color attachments that the specialized entry /// writes and whose pixel format is a signed integer /// (`LoweringInputs::signed_color_attachments`), whether the pipeline rasterizes more than one - /// sample (`LoweringInputs::multisampled`), on a device that orders framebuffer fetch through - /// rasterization-order input attachments the state of the attachments whose writes the entry - /// computes over them (`LoweringInputs::framebuffer_fetch`), and, for each index the pipeline's - /// vertex function + /// sample (`LoweringInputs::multisampled`), and, for each index the pipeline's vertex function /// writes (the [`RawIndices`]), whether the entry reads it /// (`LoweringInputs::viewport_index_varying`; /// `LoweringInputs::render_target_array_index_varying`). The pipeline's @@ -153,10 +150,6 @@ pub struct FragmentPass<'a> { pub(crate) sample_mask: Option<[u32; 4]>, /// The pipeline's private alpha test (`LoweringInputs::alpha_test`). pub(crate) alpha_test: Option, - /// The pipeline's private logic operation the function computes itself - /// (`LoweringInputs::logic_operation`); `None` from a descriptor, set by the compile layer on - /// a device without Vulkan's `logicOp` (`private_state::logic_operation`). - pub(crate) logic_operation: Option, /// The pipeline's private `fragmentDepthCompareClampMask` /// (`LoweringInputs::depth_compare_clamp_mask`). pub(crate) depth_compare_clamp_mask: u32, @@ -180,7 +173,6 @@ impl<'a> From<&'a RenderPipelineDescriptor> for FragmentPass<'a> { alpha_test: crate::pipeline::private_state::alpha_test(&d.private) .ok() .flatten(), - logic_operation: None, depth_compare_clamp_mask: d.private.fragment_depth_compare_clamp_mask, push_base: 0, } @@ -198,7 +190,6 @@ impl<'a> From<&'a MeshPipelineDescriptor> for FragmentPass<'a> { texture_write_rounding_mode: d.texture_write_rounding_mode, sample_mask: None, alpha_test: None, - logic_operation: None, depth_compare_clamp_mask: 0, push_base: crate::lower::push::window(crate::pipeline::sym::Stage::Mesh, 0).1, } @@ -2428,19 +2419,16 @@ pub(crate) fn signed_colors_written( /// The colors the specialized fragment entry `spec` reads (`[[color(n)]]`) that a render pipeline /// whose color attachments are `colors` gives a signed-integer pixel format, under the identity -/// domains on a device that orders framebuffer fetch in neither form, where an integer read -/// fetches the attachment's own view through an `int` image (`lower::fragment::color`'s -/// `texture_class`); none elsewhere, where it reads the attachment's bits through a `uint` input -/// attachment. +/// domains, where an integer read fetches the attachment's own view through an `int` image +/// (`lower::fragment::color`'s `texture_class`); none elsewhere, where it reads the attachment's +/// bits through a `uint` input attachment. fn signed_colors_fetched( spec: &air::Entry, colors: &[Option], p: &DeviceProfile, ) -> BTreeSet { use crate::pipeline::sym::SampledType; - let textured = - crate::lower::access::identity(p) && crate::lower::fragment::fetch::fetch_unordered(p); - if !textured || !matches!(spec.ep.stage, AbiStage::Fragment { .. }) { + if !crate::lower::access::identity(p) || !matches!(spec.ep.stage, AbiStage::Fragment { .. }) { return BTreeSet::new(); } spec.ep @@ -2491,110 +2479,6 @@ pub(crate) fn unattached_colors_written( .collect() } -/// The framebuffer-fetch state of pass `d` for the specialized fragment entry `spec` on `p` -/// (`LoweringInputs::framebuffer_fetch`): on a device that orders fetch through -/// rasterization-order input attachments, the state of every extended-range attachment the entry -/// writes that the pass blends (whose blend the function computes over its input attachment, -/// `lower::fragment`'s `input_blend`), of every attachment held with its channels rotated whose -/// blend the function computes (`color_writes::shader_rotated_blend`), of every word attachment -/// it writes under a mask of some of the word's channels (whose word the function merges into its -/// input attachment's, `color_writes::merged_word`), of every extended-range attachment it writes -/// unblended under a mask of some of the codes one word holds (merged so, -/// `color_writes::merged_extended`), and, under a private logic operation the function computes -/// (`FragmentPass::logic_operation`), of every attachment whose format the operation serves that -/// the entry writes through its first output (`lower::fragment`'s `logic`); `None` on another -/// device or for an entry that writes none of them. -pub(crate) fn fetch_inputs( - spec: &air::Entry, - d: FragmentPass<'_>, - p: &DeviceProfile, -) -> Option { - if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) - || !crate::lower::fragment::inputs_order(p) - { - return None; - } - let blended = |color: u32| { - d.color_attachments - .get(color as usize) - .copied() - .flatten() - .is_some_and(|c| { - c.blending_enabled - && crate::metal::format::ExtendedRange::of(c.pixel_format).is_some() - }) - }; - // An extended-range attachment whose word's codes an unblended write of some of them merges - // into the word it reads. - let merged_extended = |color: u32| { - d.color_attachments - .get(color as usize) - .copied() - .flatten() - .is_some_and(|c| crate::pipeline::color_writes::merged_extended(&c)) - }; - // A word attachment whose writes the function merges into the word its input attachment - // holds. - let merged_word = |color: u32| { - d.color_attachments - .get(color as usize) - .copied() - .flatten() - .and_then(|c| { - crate::pipeline::color_writes::merged_word(color, &c, d.alpha_to_coverage, p) - }) - .is_some() - }; - // An attachment held with its channels rotated whose blend the function computes over the - // texel it reads, in either form (`color_writes::shader_rotated_blend`). - let rotated_blend = |color: u32| { - d.color_attachments - .get(color as usize) - .copied() - .flatten() - .is_some_and(|c| crate::pipeline::color_writes::shader_rotated_blend(&c, p)) - }; - // An attachment whose codes the function's write operates on under the pipeline's private - // logic operation, over the texel it reads (`lower::fragment`'s `logic`), in either form. - let logic = |color: u32| { - d.logic_operation.is_some() - && d.color_attachments - .get(color as usize) - .copied() - .flatten() - .is_some_and(|c| crate::lower::fragment::logic_channels(c.pixel_format).is_some()) - }; - let read: BTreeSet = spec - .ep - .outputs - .iter() - .filter_map(|o| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } if blended(color) - || rotated_blend(color) - || logic(color) - || merged_word(color) - || merged_extended(color) => - { - Some(color) - } - _ => None, - }) - .collect(); - if read.is_empty() { - return None; - } - // The blend over an input attachment depends on the attachments' state alone: its write is - // the fixed function's, which the tests, coverage and views take as any other's. - Some(crate::pipeline::lower_inputs::FramebufferFetchInputs::of( - read, - d.color_attachments, - )) -} - /// A fragment stage's lowering inputs under variant `v` on `p` that need no decoded entry: the /// key's, whether pass `d` rasterizes more than one sample (`LoweringInputs::multisampled`), and /// how its color attachments take float outputs (`LoweringInputs::color_writes`). @@ -2627,7 +2511,6 @@ pub(crate) fn fragment_inputs( out.rotated_blends = crate::pipeline::color_writes::rotated_blends(d.color_attachments, p); out.sample_mask = d.sample_mask; out.alpha_test = d.alpha_test; - out.logic_operation = d.logic_operation; out.depth_compare_clamp_mask = d.depth_compare_clamp_mask; out.texture_write_rounding = d.texture_write_rounding_mode; // The floor's one render range moves the fragment function's fields. @@ -2773,7 +2656,6 @@ fn lower_inputs( )); out.unattached_colors = unattached_colors_written(spec, d.color_attachments, d.alpha_to_coverage); - out.framebuffer_fetch = fetch_inputs(spec, d, p); let read = raw_indices_read(spec); out.viewport_index_varying = written.viewport && read.viewport; out.render_target_array_index_varying = written.layer && read.layer; diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index d183a5bac..6bb76d1ed 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -100,10 +100,8 @@ pub struct RenderPipelineKeys { /// `Compiled` vertex stage. pub vertex_inputs: Option, /// The inputs a `Function` fragment stage compiles under (`VariantKey::lowering_inputs` of - /// the fragment stage, the signed-integer color attachments it writes, whether the pipeline is - /// multisampled, and the state of the attachments whose writes it computes over their input - /// attachments where the device orders framebuffer fetch through rasterization-order input - /// attachments). `None` for a `Compiled` fragment stage or none. + /// the fragment stage, the signed-integer color attachments it writes, and whether the + /// pipeline is multisampled). `None` for a `Compiled` fragment stage or none. pub fragment_inputs: Option, } @@ -401,8 +399,7 @@ impl Device { crate::pipeline::private_state::check_render(d)?; let p = self.profile(); // The attachments as the private logic operation draws them (`render_pipeline`). - let (operated, logic) = crate::pipeline::private_state::logic_operation(d, p)?; - let logic = crate::pipeline::private_state::LogicDraw::shader(logic); + let (operated, _) = crate::pipeline::private_state::logic_operation(d, p)?; let d = operated.as_ref(); let zeroed = with_zeroed_colors(d, v)?; let d = zeroed.as_ref(); @@ -454,7 +451,6 @@ impl Device { // Whether the function applies the private masks itself shows only in its // module, so a pipeline whose masks drop a sample lowers it once. let mut pass: FragmentPass<'_> = d.into(); - pass.logic_operation = logic; pass.push_base = push_end; if crate::pipeline::private_state::applied_masks(d).is_some() { let inputs = InputsFrom::Fragment( @@ -826,17 +822,13 @@ impl Device { crate::pipeline::private_state::check_render(d)?; let p = self.profile(); // The attachments as the private logic operation draws them: its normalized and integer - // attachments unblended (unwritten under a no-op), and Vulkan's operation, or the fragment - // function's, where one is needed. + // attachments unblended (unwritten under a no-op), and Vulkan's operation where one is + // needed. let (operated, logic) = crate::pipeline::private_state::logic_operation(d, p)?; let d = operated.as_ref(); let zeroed = with_zeroed_colors(d, v)?; let d = zeroed.as_ref(); - let pass = || { - let mut pass = FragmentPass::from(d); - pass.logic_operation = crate::pipeline::private_state::LogicDraw::shader(logic); - pass - }; + let pass = || FragmentPass::from(d); // On a device without a fragment `PrimitiveId`, whether the vertex function writes the // primitive ID's varying: the fragment entry specialized for that is the one its compile // reads. @@ -969,12 +961,7 @@ impl Device { d, fragment.as_ref().map(|f| f.artifact()), )?; - crate::pipeline::private_state::logic_operated( - logic, - fragment.as_ref().map(|f| f.artifact()), - )?; - let logic_op = crate::pipeline::private_state::LogicDraw::vulkan(logic); - graphics.logic_op = logic_op; + graphics.logic_op = logic; crate::pipeline::private_state::note_vulkan_codes(d, &graphics, &mut stages); crate::pipeline::private_state::note_tile_store(d, &mut stages); let mut requirements = requirements; @@ -1125,12 +1112,6 @@ fn graphics_requirements( .features .insert(VkFeature::VertexAttributeAccessBeyondStride); } - // Ordered framebuffer fetch: the subpass and pipeline flags need the feature. - if graphics.rasterization_order_attachment_access { - requirements - .features - .insert(VkFeature::RasterizationOrderColorAttachmentAccess); - } // A multiview pipeline needs `multiview` and its view count whether or not a stage reads the // view index; the binder draws more amplifications than the device has views one at a time, so // the views it needs are at most those. diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 08750c906..ea6027dfb 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -11,8 +11,8 @@ //! hash, and constant values. A stage without linked functions keeps the key it had before //! linking existed, and one //! compiled without `emulated_simdgroups`, `one_row`, `storage_view_slots`, -//! `signed_color_attachments`, `multisampled`, `replay_bindings`, or `framebuffer_fetch` the key -//! it had before those inputs existed. A stage that links dynamic libraries records each library +//! `signed_color_attachments`, `multisampled` or `replay_bindings` the key it had before those +//! inputs existed. A stage that links dynamic libraries records each library //! its imports are searched in, in order (install name and content hash), and the install name //! not loaded; one that links none keeps its key. //! - [`pipeline_key`] (`PipelineKey`): the profile fingerprint, each stage's `FunctionCompileKey` @@ -228,12 +228,6 @@ pub fn function_key( if inputs.merged_draws { h.bytes(b"merged-draws"); } - // Appended only when set, in its derived `Debug` form (ordered maps of plain enums, flags, and - // booleans, a total encoding as `inputs_encoding`'s). - if let Some(f) = &inputs.framebuffer_fetch { - h.bytes(b"framebuffer-fetch") - .bytes(format!("{f:?}").as_bytes()); - } // Appended only when set, as `storage_view_slots`. if !inputs.srgb_textures.is_empty() { h.bytes(b"srgb-textures") @@ -425,11 +419,6 @@ pub fn function_key( .bytes(&function.as_raw().to_le_bytes()); } // Appended only when set. - if let Some(op) = inputs.logic_operation { - h.bytes(b"logic-operation") - .bytes(&op.as_raw().to_le_bytes()); - } - // Appended only when set. if inputs.depth_compare_clamp_mask != 0 { h.bytes(b"depth-compare-clamp") .bytes(&inputs.depth_compare_clamp_mask.to_le_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 9bfebcdc9..c76fb306e 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -524,19 +524,6 @@ fn function_keys_cover_their_inputs() { let cl = a.function_compile_key(&fd, &cl); assert_ne!(with_true, cl); assert_ne!(replay, cl); - // So is the framebuffer-fetch pipeline state, by its attachments' state. - let fetch = |format| { - let mut i = LoweringInputs::new(); - let colors = [Some( - crate::pipeline::descriptor::ColorAttachmentDescriptor::new(format), - )]; - i.framebuffer_fetch = Some(crate::pipeline::FramebufferFetchInputs::of([0], &colors)); - a.function_compile_key(&fd, &i) - }; - let r32 = fetch(metal::PixelFormat::R32Float); - assert_ne!(with_true, r32); - assert_ne!(replay, r32); - assert_ne!(r32, fetch(metal::PixelFormat::RGBA8Unorm)); // So is the raw viewport index's varying. let mut viewport = LoweringInputs::new(); viewport.viewport_index_varying = true; @@ -662,7 +649,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", multisampled: false", "") .replace(", replay_bindings: false", "") .replace(", merged_draws: false", "") - .replace(", framebuffer_fetch: None", "") .replace(", srgb_textures: {}", "") .replace(", ycbcr_in_place: {}", "") .replace(", ycbcr_planes_sampled: {}", "") @@ -698,7 +684,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", unattached_colors: {}", "") .replace(", sample_mask: None", "") .replace(", alpha_test: None", "") - .replace(", logic_operation: None", "") .replace(", depth_compare_clamp_mask: 0", "") .replace(", read_only_tests: false", "") .replace(", rotated_colors: {}", "") @@ -1781,17 +1766,16 @@ fn a_vertex_pipeline_makes_its_input_assembly_dynamic_exactly_with_both_extended } } -/// A render pipeline whose fragment function reads its color attachment orders the read exactly -/// where the device can. With rasterization-order attachment access it states that access and -/// requires `rasterizationOrderColorAttachmentAccess` (enabled with its extension). Without it, -/// with the ordered pixel interlock or not, it reads the input attachment without -/// rasterization-order access, which the consumer's barriers order between draws alone, a blend -/// the device's, and its fragment stage records `PrecisionNote::UnorderedFetchWithinDraw`, which -/// the ordered form does not record. A raster order group on the color input (`fetch_ordered`) -/// orders that read alone there: no interlock, noted. +/// A render pipeline whose fragment function reads its color attachment reads the input +/// attachment without rasterization-order access on every device, lavapipe (which has +/// `rasterizationOrderColorAttachmentAccess`) included, with the ordered pixel interlock or not: +/// the consumer's barriers order it between draws alone, a blend is the device's, and its fragment +/// stage records `PrecisionNote::UnorderedFetchWithinDraw`. A raster order group on the color +/// input (`fetch_ordered`) orders that read alone: no interlock, noted. No requirement names +/// either feature. #[test] -fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it() { - use crate::device::requirements::{VkExtension, VkFeature}; +fn a_framebuffer_fetch_pipeline_is_ordered_between_draws_on_every_device() { + use crate::device::requirements::VkFeature; use crate::pipeline::{PrecisionNote, RenderPipeline}; const ORDERED: VkFeature = VkFeature::RasterizationOrderColorAttachmentAccess; const INTERLOCK: VkFeature = VkFeature::FragmentShaderPixelInterlock; @@ -1843,33 +1827,14 @@ fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it() }) }; let lavapipe = description("lavapipe"); - assert!(lavapipe.has(ORDERED)); - { - let pipe = compile(&lavapipe, DevicePolicy::RESIDENT_TABLES, &d).expect("lavapipe"); - assert!(!unordered(&pipe)); - assert_eq!(pipe.graphics.input_attachments.len(), 1); - assert!(pipe.graphics.rasterization_order_attachment_access); - assert!(pipe.requirements.features.contains(&ORDERED)); - let enables = lavapipe - .required_enables(&pipe.requirements) - .expect("enables"); - assert!(enables.features.contains(&ORDERED)); - assert!(enables - .extensions - .contains(&VkExtension::ExtRasterizationOrderAttachmentAccess)); - } - - let mut interlocked = lavapipe.clone(); - interlocked.features.remove(&ORDERED); - assert!(interlocked.has(INTERLOCK)); - let mut without = interlocked.clone(); + assert!(lavapipe.has(ORDERED) && lavapipe.has(INTERLOCK)); + let mut without = lavapipe.clone(); without.features.remove(&INTERLOCK); - for desc in [&interlocked, &without] { + for desc in [&lavapipe, &without] { for pd in [&d, &blended, &grouped] { let pipe = compile(desc, DevicePolicy::RESIDENT_TABLES, pd).expect("unordered"); assert!(unordered(&pipe)); assert_eq!(pipe.graphics.input_attachments.len(), 1); - assert!(!pipe.graphics.rasterization_order_attachment_access); for f in [ORDERED, INTERLOCK] { assert!(!pipe.requirements.features.contains(&f), "{f:?}"); } @@ -1877,8 +1842,8 @@ fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it() } } -/// Under the identity domains on a device that orders framebuffer fetch in neither form (rt's -/// profile), a color read takes no input attachment and no descriptor: the fragment fetches the +/// Under the identity domains (rt's, on a device without the pixel interlock), a color read takes +/// no input attachment and no descriptor: the fragment fetches the /// sampled-texture array's element pushed for the attachment (`PushField::FetchedColor`), in the /// attachment's own numeric class (an unsigned read of a signed-integer attachment as `int`, which /// the element's view takes), noted `UnorderedFetchWithinDraw`. A read of another class than the @@ -1909,12 +1874,9 @@ fn an_identity_fetch_reads_its_attachments_pushed_texture_in_the_attachments_cla d }; let mut without = description("lavapipe"); - for f in [ - VkFeature::RasterizationOrderColorAttachmentAccess, - VkFeature::FragmentShaderPixelInterlock, - ] { - without.features.remove(&f); - } + without + .features + .remove(&VkFeature::FragmentShaderPixelInterlock); let policy = DevicePolicy { pointer_domain: PointerDomain::Identity, handle_domain: HandleDomain::Identity, @@ -1962,7 +1924,6 @@ fn an_identity_fetch_reads_its_attachments_pushed_texture_in_the_attachments_cla pipe.graphics.input_attachments.is_empty(), "{fragment} {format:?}" ); - assert!(!pipe.graphics.rasterization_order_attachment_access); assert!( (pipe.layout.sets.iter()) .filter(|s| s.set == 0) @@ -2022,8 +1983,8 @@ fn images_and_sample_id(words: &[u32]) -> (Vec<(u32, u32, u32)>, bool) { /// Metal runs a function that reads a color attachment of a multisampled pass once per covered /// sample, reading its own sample. Compiled for a pipeline of 4 samples, the fragment reads each /// color at its `SampleId` (which runs it once per covered sample under sample shading) through a -/// multisampled `SubpassData` image: on lavapipe under rasterization-order access, and on a device -/// without it unordered within a draw (noted). Where the device lacks sample-rate shading, the +/// multisampled `SubpassData` image, unordered within a draw (noted). Where the device lacks +/// sample-rate shading, the /// refusal names it; `[[sample_mask]]` in is the pixel's coverage, which no device gives a /// per-sample invocation. One sample compiles as before: no `SampleId`, a single-sample image. #[test] @@ -2031,7 +1992,6 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { use crate::device::requirements::VkFeature; use crate::error::Capability; use crate::pipeline::{PrecisionNote, RenderPipeline}; - const ORDERED: VkFeature = VkFeature::RasterizationOrderColorAttachmentAccess; const SUBPASS_DATA: u32 = 6; let (Some(io), Some(blend), Some(ms)) = ( fixture("stage_io"), @@ -2081,15 +2041,13 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { .contains(&PrecisionNote::UnorderedFetchWithinDraw) }; - // The input attachment's own sample, ordered where the device orders it. + // The input attachment's own sample, ordered between draws alone. let lavapipe = description("lavapipe"); - let mut unordered_device = lavapipe.clone(); - unordered_device.features.remove(&ORDERED); - for (desc, ordered) in [(&lavapipe, true), (&unordered_device, false)] { + { + let desc = &lavapipe; let pipe = compile(desc, &descriptor(&blend, "exf_fetch_blend", 4)).expect("four"); assert_eq!(pipe.graphics.input_attachments.len(), 1); - assert_eq!(pipe.graphics.rasterization_order_attachment_access, ordered); - assert_eq!(unordered(&pipe), !ordered); + assert!(unordered(&pipe)); assert_eq!( pipe.graphics.rasterization_samples, vk::SampleCountFlags::COUNT_4 @@ -2098,7 +2056,6 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { .requirements .features .contains(&VkFeature::SampleRateShading)); - assert_eq!(pipe.requirements.features.contains(&ORDERED), ordered); assert_eq!( images_and_sample_id(&fragment_words(&pipe)), (vec![(SUBPASS_DATA, 0, 1)], true) @@ -2112,8 +2069,8 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { compile(desc, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out"); } // Without sample-rate shading no form reads a sample. - for desc in [&lavapipe, &unordered_device] { - let mut no_rate = desc.clone(); + { + let mut no_rate = lavapipe.clone(); no_rate.features.remove(&VkFeature::SampleRateShading); let (feature, needs) = refusal(compile(&no_rate, &descriptor(&blend, "exf_fetch_blend", 4))); @@ -2127,9 +2084,9 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { .any(|c| *c == Capability::Feature(VkFeature::SampleRateShading))); } // `[[sample_mask]]` in beside a fetch reads the pixel's coverage (measured): no device. - for desc in [&lavapipe, &unordered_device] { + { assert_eq!( - refusal(compile(desc, &descriptor(&ms, "msf_fetch_mask_in", 4))), + refusal(compile(&lavapipe, &descriptor(&ms, "msf_fetch_mask_in", 4))), (Feature::PixelCoverageAtSampleRate, Needs::NotRepresentable) ); } diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 24070cc19..13e2213fe 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -467,50 +467,6 @@ pub enum RuntimeFact { /// with `None`, or naming a slot whose bound sampler states what the emulation does not /// answer (`Unsupported(ArgumentBufferTextures)`). HeapRawSamples { stage: Stage, sampler: Option }, - /// On a device that orders framebuffer fetch through rasterization-order input attachments, - /// the function computes Metal's blend `blend` into extended-range color attachment `color` - /// in the shader: it reads the attachment's raw texel through its input attachment - /// (`RuntimeFact::FramebufferFetch`), blends its output over the texel's tile value, and - /// writes the encode of the result through its first output, the channels `kept` (the - /// format's channels the descriptor's write mask leaves out) taken from the texel. Link - /// gives the attachment no Vulkan blend and writes every raw component, and a pipeline of - /// another blend or write mask there is `NeedsInput(FramebufferFetch)`. - ExtendedRangeInputBlend { - color: u32, - blend: crate::pipeline::lower_inputs::BlendEquation, - kept: crate::vk::ColorComponentFlags, - }, - /// On a device that orders framebuffer fetch through rasterization-order input attachments, - /// the function computes Metal's blend `blend` into color attachment `color`, held with its - /// channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`), where no Vulkan state on that image - /// gives it (`color_writes::shader_rotated_blend`): it reads the texel through the - /// attachment's input attachment (`RuntimeFact::FramebufferFetch`), blends its output over it - /// in Metal's channel order by Metal's 8-bit unorm blend, and writes the result through its - /// first output, rotated as every output there is. `kept` is the format's channels the - /// descriptor's write mask leaves out, which the attachment's write mask keeps. Link gives the - /// attachment no Vulkan blend, and a pipeline of another blend or write mask there is - /// `NeedsInput(FramebufferFetch)`. - RotatedInputBlend { - color: u32, - blend: crate::pipeline::lower_inputs::BlendEquation, - kept: crate::vk::ColorComponentFlags, - }, - /// On a device that orders framebuffer fetch through rasterization-order input attachments, - /// the function writes color attachment `color`, which renders through a view of its word - /// (`metal::format::WordAttachment`, an 8-bit sRGB one), under a write mask of some of the - /// word's channels: it reads the texel's word through the attachment's input attachment - /// (`RuntimeFact::FramebufferFetch`) and writes Metal's word of its output with the fields of - /// the channels `kept` (those of the word the descriptor's write mask leaves out) taken from - /// the word read. Likewise an extended-range attachment whose one raw component holds three - /// codes (`BGR10_XR`, the two-plane forms' color word, their `_sRGB` twins) written unblended - /// under a mask of some of them: the function writes the kernel write's encode of its output - /// with the codes of the channels `kept` taken from the texel read. Link writes the whole word - /// (every raw component), and a pipeline of another write mask there is - /// `NeedsInput(FramebufferFetch)`. - WordInputMerge { - color: u32, - kept: crate::vk::ColorComponentFlags, - }, /// The function reads, samples or gathers the sampled color texture (not a texture buffer, /// a multisampled or a depth texture) bound to the slot only with `float`, `half` or 32-bit /// integer results: bound to a texture of a color format whose numeric class is not the @@ -789,9 +745,6 @@ impl RuntimeFact { RuntimeFact::CubicSampler { .. } => "CubicSampler", RuntimeFact::CubicArgumentSampler { .. } => "CubicArgumentSampler", RuntimeFact::HeapRawSamples { .. } => "HeapRawSamples", - RuntimeFact::ExtendedRangeInputBlend { .. } => "ExtendedRangeInputBlend", - RuntimeFact::RotatedInputBlend { .. } => "RotatedInputBlend", - RuntimeFact::WordInputMerge { .. } => "WordInputMerge", RuntimeFact::CrossClassReads { .. } => "CrossClassReads", RuntimeFact::StorageTextureWriteRounding { .. } => "StorageTextureWriteRounding", RuntimeFact::HeapWriteRounding { .. } => "HeapWriteRounding", diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index c7da0d89c..9b6d3aa8d 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -53,21 +53,6 @@ pub struct GraphicsState { /// Framebuffer-fetch inputs. In a pipeline of more than one sample the fragment function runs /// once per covered sample and reads its own sample of each. pub input_attachments: Vec, - /// The pipeline and its subpass use rasterization-order attachment access: set when the - /// pipeline has input attachments and the device has `rasterizationOrderColorAttachmentAccess`, - /// so each fetch is ordered after the earlier fragments of the draw that cover its pixel, as - /// Metal orders it. The consumer creates the subpass with - /// `VK_SUBPASS_DESCRIPTION_RASTERIZATION_ORDER_ATTACHMENT_COLOR_ACCESS_BIT_EXT` and the - /// pipeline's color blend state with - /// `VK_PIPELINE_COLOR_BLEND_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_BIT_EXT`, and - /// the pipeline's requirements name the feature. A device without it reads them without this - /// flag: the consumer - /// then orders each draw that reads them after the color writes of the earlier draws of its - /// subpass, and each draw that writes a color after the input attachment reads of the earlier - /// ones, by a barrier of the subpass's dependency on itself (by region) between the two, which - /// orders draws but not the overlapping fragments of one draw - /// (`PrecisionNote::UnorderedFetchWithinDraw`, which the fragment stage records). - pub rasterization_order_attachment_access: bool, /// Metal's `maxVertexAmplificationCount` (1 without vertex amplification): a draw with this /// pipeline amplifies each vertex by a count in `[1, max_vertex_amplification_count]`, or, /// above 1, by a larger count too, as plain Metal draws one. Above 1 the pipeline is a @@ -322,7 +307,6 @@ impl GraphicsState { rasterizer_discard: false, dynamic_states: Vec::new(), input_attachments: Vec::new(), - rasterization_order_attachment_access: false, max_vertex_amplification_count: 1, declares_layer: false, tessellation: None, @@ -622,9 +606,8 @@ impl BlendState { /// A framebuffer-fetch input: color attachment `color_index` read as input attachment /// `input_attachment_index`. The consumer's render pass provides the self-dependency (or -/// `dynamicRenderingLocalRead` mapping) that the contract names, and, without -/// [`rasterization_order_attachment_access`](GraphicsState::rasterization_order_attachment_access), -/// the barriers between draws it states. In a pipeline of more than one +/// `dynamicRenderingLocalRead` mapping) that the contract names, and the barriers between draws +/// it states (`PrecisionNote::UnorderedFetchWithinDraw`). In a pipeline of more than one /// sample the attachment is the pass's multisampled one, of `GraphicsState::rasterization_samples` /// samples, which the function reads at each invocation's own sample. #[non_exhaustive] diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index e9ea950ab..47493dff5 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -48,7 +48,6 @@ pub mod band; pub mod contract; -pub mod fetch; pub mod graphics; pub mod mesh; pub mod tessellation; @@ -74,7 +73,6 @@ use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, MeshPipelineDescriptor, RenderPipelineDescriptor, TessellationDescriptor, VertexDescriptor, }; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::graphics::GraphicsState; use crate::pipeline::interface::{PipelineInterface, StageDescriptor, StageInterface}; use crate::pipeline::layout::{ @@ -513,23 +511,8 @@ fn render_state( ts: Option, p: &DeviceProfile, ) -> Result { - // The extended-range blends the fragment computes over input attachments, against this - // pipeline's attachments. - let input_blends = fetch::input_blends(r, fragment, p)?; - // Those of them held with their channels rotated, whose input attachments link admits for - // that blend alone. - let rotated_inputs: BTreeSet = (fragment.into_iter().flat_map(|f| &f.facts)) - .filter_map(|fact| match *fact { - RuntimeFact::RotatedInputBlend { color, .. } => Some(color), - _ => None, - }) - .collect(); - // The word merges the fragment computes over input attachments, against this pipeline's - // write masks. - fetch::word_merges(r, fragment, p)?; let fs = fragment.map(|f| &f.interface); - let blends = (&input_blends, &rotated_inputs); - let mut gs = graphics::graphics_state(r, (geometry, fs), vi, ts, blends, p)?; + let mut gs = graphics::graphics_state(r, (geometry, fs), vi, ts, p)?; // The color writes the fragment rounds against this pipeline's attachments, once the // descriptor's checks of its outputs passed. crate::pipeline::color_writes::check( diff --git a/crates/metal2vulkan/src/pipeline/link/fetch.rs b/crates/metal2vulkan/src/pipeline/link/fetch.rs deleted file mode 100644 index df6fcc63d..000000000 --- a/crates/metal2vulkan/src/pipeline/link/fetch.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! A render pipeline's framebuffer fetch computed over input attachments. -//! -//! On a device that orders framebuffer fetch through rasterization-order input attachments, the -//! function computes an extended-range attachment's blend over its input attachment -//! (`RuntimeFact::ExtendedRangeInputBlend`, [`input_blends`]): the attachment stays a color -//! attachment of the subpass, which `graphics_state` gives no Vulkan blend and a write of every raw -//! component, the function merging the channels the descriptor's mask keeps; a stage compiled under -//! another blend or mask there was compiled for another pipeline, `NeedsInput(FramebufferFetch)`. -//! There too the function computes the blend of an attachment held with its channels rotated that -//! no Vulkan state on its image gives (`RuntimeFact::RotatedInputBlend`, [`input_blends`]), which -//! `graphics_state` gives no Vulkan blend and the descriptor's write mask, rotated. -//! There too the function merges its word of a word attachment written under a mask of some of -//! the word's channels into the word its input attachment holds (`RuntimeFact::WordInputMerge`, -//! [`word_merges`]); `graphics_state` writes the whole word, and a stage compiled under another -//! mask there, or without the merge, was compiled for another pipeline. So does it merge the codes -//! of an extended-range attachment written unblended under a mask of some of the codes one word -//! holds (`color_writes::merged_extended`, the same fact): [`input_blends`] names it beside the -//! blended ones, so that `graphics_state` gives it no blend and a write of every raw component. - -use std::collections::BTreeMap; - -use crate::device::DeviceProfile; -use crate::error::{Error, InternalError, InternalKind, RuntimeInput}; -use crate::library::FunctionArtifact; -use crate::lower::fragment::{inputs_order, kept_channels}; -use crate::metal::format::ExtendedRange; -use crate::metal::state::color_write_mask; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::lower_inputs::BlendEquation; -use crate::pipeline::stage_io::IoRole; - -/// The extended-range attachments whose blend fragment stage `fragment` computes over their -/// input attachments (`RuntimeFact::ExtendedRangeInputBlend`), or whose codes it merges there -/// (`RuntimeFact::WordInputMerge` of such an attachment), and the attachments held with their -/// channels rotated whose blend it computes there (`RuntimeFact::RotatedInputBlend`, which link -/// gives no Vulkan blend and the descriptor's write mask, rotated), on a device that orders fetch through -/// rasterization-order input attachments, against the attachments of render inputs `r`: by color -/// index, the channels each write keeps from its texel, where the pipeline's blend and write mask -/// there are those the function compiled under; `NeedsInput(FramebufferFetch)` where they are -/// another pipeline's (a merge's mask, [`word_merges`]). -pub fn input_blends( - r: &RenderLinkInputs, - fragment: Option<&FunctionArtifact>, - p: &DeviceProfile, -) -> Result, Error> { - let mut out = BTreeMap::new(); - for fact in fragment.into_iter().flat_map(|f| &f.facts) { - // An extended-range attachment's merge, which [`word_merges`] holds to the pipeline's - // state, writes every raw component as a blend over the input attachment does. - if let RuntimeFact::WordInputMerge { color, kept } = *fact { - let extended = r - .color_attachments - .get(color as usize) - .copied() - .flatten() - .is_some_and(|a| ExtendedRange::of(a.pixel_format).is_some()); - if extended { - out.insert(color, kept); - } - continue; - } - // An attachment held with its channels rotated whose blend the function computes over its - // input attachment (`color_writes::shader_rotated_blend`): its write keeps the channels the - // descriptor's mask leaves out through the attachment's write mask. - if let RuntimeFact::RotatedInputBlend { color, blend, kept } = *fact { - if !inputs_order(p) { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - "a rotated blend over an input attachment on a device that fetches otherwise", - ))); - } - let Some(a) = r.color_attachments.get(color as usize).copied().flatten() else { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - }; - let pipeline_kept = - color_write_mask(kept_channels(a.pixel_format, a.write_mask, true))?; - if !crate::pipeline::color_writes::shader_rotated_blend(&a, p) - || BlendEquation::of(&a) != Some(blend) - || pipeline_kept != kept - { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - } - out.insert(color, kept); - continue; - } - let RuntimeFact::ExtendedRangeInputBlend { color, blend, kept } = *fact else { - continue; - }; - if !inputs_order(p) { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - "an extended-range blend over an input attachment on a device that fetches \ - otherwise", - ))); - } - let Some(a) = r.color_attachments.get(color as usize).copied().flatten() else { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - }; - let pipeline_kept = color_write_mask(kept_channels(a.pixel_format, a.write_mask, true))?; - if BlendEquation::of(&a) != Some(blend) || pipeline_kept != kept { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - } - out.insert(color, kept); - } - Ok(out) -} - -/// The word merges the fragment stage `fragment` computes over input attachments -/// (`RuntimeFact::WordInputMerge`), against the attachments of render inputs `r` on `p`: each -/// attachment the stage writes through a first output whose word the pipeline's state merges -/// (`color_writes::merged_word`, and an extended-range one's codes, `color_writes::merged_extended`) -/// needs the stage's merge keeping the channels the mask leaves out, -/// and each merge the stage states needs that state. A stage compiled under another mask there, -/// or without the merge, is `NeedsInput(FramebufferFetch)`. -pub fn word_merges( - r: &RenderLinkInputs, - fragment: Option<&FunctionArtifact>, - p: &DeviceProfile, -) -> Result<(), Error> { - let Some(f) = fragment else { - return Ok(()); - }; - let stated: BTreeMap = f - .facts - .iter() - .filter_map(|fact| match *fact { - RuntimeFact::WordInputMerge { color, kept } => Some((color, kept)), - _ => None, - }) - .collect(); - if !stated.is_empty() && !inputs_order(p) { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - "a word merge over an input attachment on a device that fetches otherwise", - ))); - } - let mut wanted = BTreeMap::new(); - for o in &f.interface.io.outputs { - let IoRole::Color { - attachment: color, - index: 0, - } = o.role - else { - continue; - }; - let Some(a) = r.color_attachments.get(color as usize).copied().flatten() else { - continue; - }; - if let Some(kept) = - crate::pipeline::color_writes::merged_word(color, &a, r.alpha_to_coverage, p) - { - wanted.insert(color, color_write_mask(kept)?); - } else if crate::pipeline::color_writes::merged_extended(&a) && inputs_order(p) { - let kept = kept_channels(a.pixel_format, a.write_mask, true); - wanted.insert(color, color_write_mask(kept)?); - } - } - match stated == wanted { - true => Ok(()), - false => Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)), - } -} diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index c81b67b17..af57b35a7 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -52,13 +52,9 @@ //! dynamic state also cull mode, front face, topology, the depth/stencil test state, and the //! vertex strides of `PerBind` layouts. //! - **Input attachments**: one per framebuffer-fetch binding of the fragment stage. Metal orders -//! each fetch after the earlier fragments of the draw that cover the pixel; Vulkan does only -//! under rasterization-order attachment access, so a pipeline with input attachments on a profile -//! with `rasterizationOrderColorAttachmentAccess` states `rasterization_order_attachment_access` -//! (and the compiled pipeline requires the feature). Without the feature a fragment stage reads +//! each fetch after the earlier fragments of the draw that cover the pixel; a fragment stage reads //! an input attachment ordered between draws alone (`lower::fragment::color`), whose consumer -//! orders the draws by barriers. In a -//! multisampled pipeline +//! orders the draws by barriers. In a multisampled pipeline //! (`rasterSampleCount` above 1) Metal runs a function that reads a color attachment once per //! covered sample, each invocation reading its own sample (measured), so the stage, compiled for //! the pipeline (`LoweringInputs::multisampled`), reads a multisampled `SubpassData` image at @@ -171,7 +167,7 @@ //! ordinary layered rendering. A mesh pipeline keeps its count and needs no `multiview`: its //! draws of more than one amplification are refused at the draw (`bind::graphics`). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use crate::device::requirements::{FormatUsage, VkFeature, VkLimit, VkProperty}; use crate::device::DeviceProfile; @@ -203,7 +199,7 @@ use crate::vk; /// Whether the fragment stage `fs` reads a color attachment of render inputs `r` through the /// sampled-texture array's element the consumer pushes for it (`PushField::FetchedColor`, the -/// identity domains' form on a device that orders fetch in neither form), each such attachment +/// identity domains' form), each such attachment /// checked as an input attachment of it is: the pipeline has it, its view holds Metal's channels /// (no rotated, two-plane YCbCr or extended-range format, whose texels the view does not hold as /// Metal's), and its format's numeric class is the one the stage reads, else Metal's pipeline @@ -297,16 +293,11 @@ fn vertex_amplification(r: &RenderLinkInputs, mesh: bool, p: &DeviceProfile) -> /// The graphics state of render inputs `r` with vertex stage `vs`, fragment stage `fs`, vertex /// input `vi`, and, for a tessellation pipeline, its tessellation state `tessellation`: its /// topology is `PATCH_LIST` and never dynamic state, as its draws draw patches only. -/// `input_blends`: the extended-range attachments whose blend the fragment function computes over -/// their input attachments, and the channels each write keeps (`link::fetch::input_blends`); -/// `rotated_inputs`: those of them held with their channels rotated, whose blend the function -/// states as `RuntimeFact::RotatedInputBlend`. pub fn graphics_state( r: &RenderLinkInputs, (vs, fs): (&StageInterface, Option<&StageInterface>), vi: &VertexInputState, tessellation: Option, - (input_blends, rotated_inputs): (&BTreeMap, &BTreeSet), p: &DeviceProfile, ) -> Result { if r.alpha_to_one && !p.fields().enabled.features.contains(&VkFeature::AlphaToOne) { @@ -379,8 +370,7 @@ pub fn graphics_state( // A word attachment renders through the view of its word, which the function // writes whole and unblended (`color_writes::word_color`): its one component, // where the function writes the attachment and the mask keeps some of the - // format's channels (all of them, or some where the function merges the word - // into its input attachment's, `fetch::word_merges`). + // format's channels (all of them). if let Some(word) = color_writes::word_color(index as u32, a, r.alpha_to_coverage, p) { @@ -429,10 +419,6 @@ pub fn graphics_state( let keeps_zero = fs.is_some_and(|f| color_writes::keeps_zero(&f.io, index as u32, a)); let replaced = stored && color_writes::replaces(a) && !keeps_zero; - // An extended-range attachment whose blend the function computes over its - // input attachment takes no Vulkan blend, and the function's write stores - // every raw component (none where it keeps every channel). - let input_blend = input_blends.get(&(index as u32)).copied(); // An extended-range attachment no first output writes (every attachment of a // pipeline without a fragment function) is left as it is, as Metal leaves an // unwritten attachment (the module docs), so its blend changes nothing: it @@ -448,10 +434,7 @@ pub fn graphics_state( // alpha, the mask's alpha bit in red, and Metal's alpha blend in red. let alpha_red = metal::format::alpha_in_red(a.pixel_format, p); let rotated = metal::format::rotated_channels(a.pixel_format) || alpha_red; - let blended = a.blending_enabled - && !replaced - && input_blend.is_none() - && !unwritten_extended; + let blended = a.blending_enabled && !replaced && !unwritten_extended; // A blend into a two-plane YCbCr `_sRGB` twin a pass renders is not measured // (`metal::format::ycbcr_renders`): whether Metal's tile blends the texels' // linear values or their encoding. @@ -474,59 +457,29 @@ pub fn graphics_state( // An extended-range attachment holds its raw texels, whose components the // function writes whole (`extended_write_mask`). An unwritten attachment's mask // is empty whatever the descriptor's. - let write_mask = match (extended, input_blend) { + let write_mask = match extended { _ if !written_here => vk::ColorComponentFlags::empty(), - (Some(form), Some(kept)) => { - let stored = match kept == vk::ColorComponentFlags::known_bits() { - true => vk::ColorComponentFlags::empty(), - false => vk::ColorComponentFlags::known_bits(), - }; - extended_write_mask(form, stored)? - } - // A mask of some of the codes one word holds, which a stage compiled for - // this pipeline merges where the device orders fetch (one that reaches here - // was compiled for another): on a device that does not, the ordering the - // merge needs. - (Some(form), None) => { - extended_write_mask(form, descriptor_mask).map_err(|e| { - let unordered = crate::lower::fragment::fetch::fetch_unordered(p); - match (color_writes::merged_extended(a), unordered) { - (true, true) => { - crate::lower::fragment::fetch::unordered_extended_fetch() - .into() - } - (true, false) => { - Error::NeedsInput(RuntimeInput::FramebufferFetch) - } - (false, _) => e, + // A mask of some of the codes one word holds, which the function would + // merge into the word over an ordered read of the attachment: not built. + Some(form) => extended_write_mask(form, descriptor_mask).map_err(|e| { + match color_writes::merged_extended(a) { + true => { + crate::lower::fragment::fetch::computed_write_refused().into() } - })? - } - (None, _) => descriptor_mask, + false => e, + } + })?, + None => descriptor_mask, }; - let blend = match ( - replaced || input_blend.is_some() || unwritten_extended, - rotated, - ) { + let blend = match (replaced || unwritten_extended, rotated) { (true, _) => None, (false, false) => blend_factors(a, p)?, (false, true) if alpha_red => alpha_in_red_blend(a, p)?, - // A blend no Vulkan state on the rotated image gives, which a stage - // compiled for this pipeline computes itself over the input attachment - // (above): one that does not was compiled for another pipeline. Unwritten, - // it writes nothing. - (false, true) if color_writes::shader_rotated_blend(a, p) => { - match written_here { - true => { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)) - } - false => None, - } - } - // Where the device does not order fetch, the ordering that blend needs. + // A blend no Vulkan state on the rotated image gives, which the function + // would compute over an ordered read of the attachment: not built. (false, true) if color_writes::rotated_blend_in_shader(a, p) => { return Err( - crate::lower::fragment::fetch::unordered_extended_fetch().into() + crate::lower::fragment::fetch::computed_write_refused().into() ); } // The second output the rotation needs is the function's only beside @@ -609,16 +562,12 @@ pub fn graphics_state( }))?; // An input attachment of an image holding Metal's channels rotated reads them so: a // color input of one is not modelled, which a stage compiled for the attachment refuses - // (`lower::fragment::color`), so the one input attachment such a stage reads of it is - // the one its own blend there rotates into Metal's order - // (`RuntimeFact::RotatedInputBlend`, which `fetch::input_blends` held to the pipeline's - // state above); any other is a stage's compiled for another pipeline. (One holding - // Metal's alpha in red is read as Metal's alpha by a stage compiled for it, + // (`lower::fragment::color`), so one is a stage's compiled for another pipeline. (One + // holding Metal's alpha in red is read as Metal's alpha by a stage compiled for it, // `StageIo::alpha_in_red_colors`, which `color_writes::check` holds to the pipeline's.) // Nor is a two-plane YCbCr attachment's, whose texels Metal holds as halves and the // attachment as the function's floats. - if (metal::format::rotated_channels(attachment.pixel_format) - && !rotated_inputs.contains(&color)) + if metal::format::rotated_channels(attachment.pixel_format) || metal::format::ycbcr_renders(attachment.pixel_format) || metal::format::ycbcr_pass_refused(attachment.pixel_format) { @@ -627,7 +576,7 @@ pub fn graphics_state( } // An extended-range attachment's input reads its raw texels, the raw format's // `uint`s, which a stage compiled for the attachment decodes (`color_writes::check`); - // a word attachment's reads its word, which a stage merges (`fetch::word_merges`). + // a word attachment's reads its word (`color_writes::word_color`). let word = color_writes::word_color(color, &attachment, r.alpha_to_coverage, p).is_some(); let format_class = match ExtendedRange::of(attachment.pixel_format) { @@ -717,9 +666,6 @@ pub fn graphics_state( alpha_to_one: r.alpha_to_one, rasterizer_discard: !r.rasterization_enabled, dynamic_states, - // Ordered wherever the device can order the reads. - rasterization_order_attachment_access: !input_attachments.is_empty() - && p.fields().fragment.rasterization_order_color_access, input_attachments, max_vertex_amplification_count, declares_layer, @@ -1041,12 +987,9 @@ fn uniform_blend( /// Max and an M4, byte-identical). A mask of some of the channels one component holds /// (`BGR10_XR`'s word, `RGB10A2Unorm_sRGB`'s, the two-plane forms' color word) is /// `NotImplemented(Format)` here: no mask of the raw components keeps one code of a word and -/// writes another. A stage that writes `BGR10_XR` or a two-plane form so merges the codes -/// (`color_writes::merged_extended`) over the input attachment, whose write the caller makes of -/// every raw component, where the device orders fetch through rasterization-order input -/// attachments, so a stage that reaches here so was compiled for another pipeline (the caller -/// answers `NeedsInput(FramebufferFetch)`); on a device that does not order it so, the caller names -/// the ordering the merge needs. A bfloat form's channels +/// writes another. The merge of such a mask's codes into the word over an ordered read of the +/// attachment (`color_writes::merged_extended`) is not built: the caller refuses it +/// (`fetch::computed_write_refused`). A bfloat form's channels /// are its own (red; red and green; all four), each a raw component; a mask of some of them is /// unmeasured and refused as above. fn extended_write_mask( diff --git a/crates/metal2vulkan/src/pipeline/link/tests/render.rs b/crates/metal2vulkan/src/pipeline/link/tests/render.rs index fd7cab6b2..9c6c55eeb 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests/render.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests/render.rs @@ -1028,17 +1028,6 @@ fn graphics_state_maps_the_descriptor() { assert_eq!(g.input_attachments.len(), 1); assert_eq!(g.input_attachments[0].color_index, 2); assert_eq!(g.input_attachments[0].format_class, SampledType::Float); - // The fetch is ordered wherever the device can order it. - assert_eq!( - g.rasterization_order_attachment_access, - p.fields().fragment.rasterization_order_color_access, - "{stem}" - ); - assert_eq!( - g.rasterization_order_attachment_access, - stem == "lavapipe", - "{stem}: lavapipe alone of these orders attachment reads" - ); // Extended dynamic state makes the cull mode dynamic; the topology and its restart // follow with `extendedDynamicState2` too, together. assert_eq!( diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 69d60a0e3..a551c2670 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -67,8 +67,8 @@ pub struct LoweringInputs { /// signed-integer pixel format (`MTLRenderPipelineColorAttachmentDescriptor.pixelFormat`). A /// 32-bit integer color output to one is declared `int`, because Vulkan writes a signed-integer /// attachment only from a signed output; every other integer output is declared `uint`. Under - /// the identity domains on a device that orders framebuffer fetch in neither form it also - /// holds the signed-integer attachments the function reads (`[[color(n)]]`), whose integer + /// the identity domains it also holds the signed-integer attachments the function reads + /// (`[[color(n)]]`), whose integer /// read fetches the attachment's own view through an `int` image (`PushField::FetchedColor`). /// `Device::compile_render_pipeline` sets it for a `Function` fragment stage, and a fragment /// compiled on its own for such a pipeline compiles under the same set; any other function @@ -90,8 +90,8 @@ pub struct LoweringInputs { /// `InterpolateAtOffset` at offset 0 on a device with interpolation functions whose offset /// reads from the center (`VkProperty::InterpolateAtOffsetCentered`): the pixel center whatever /// samples its invocation shades (`StageIo::{multisampled, varyings_at_pixel}`). A function - /// that reads its color attachments (`framebuffer_fetch`) reads each one's multisampled image - /// at its `SampleId`, running once per covered sample, as + /// that reads its color attachments reads each one's multisampled image at its `SampleId`, + /// running once per covered sample, as /// Metal does. `Device::compile_render_pipeline` sets it for a `Function` fragment stage, and a /// fragment compiled on its own for such a pipeline compiles under it: link refuses one /// compiled without it whose sample-rate invocations would read either elsewhere, or that reads @@ -131,18 +131,6 @@ pub struct LoweringInputs { /// states `RuntimeFact::MergedDraws`. Any other stage compiles as without it. #[cfg_attr(feature = "serde", serde(default))] pub merged_draws: bool, - /// The render pipeline state of the attachments whose writes a fragment function computes - /// over their input attachments, on a device that orders fetch through rasterization-order - /// input attachments: an extended-range attachment the pipeline blends, one held with its - /// channels rotated whose blend no Vulkan state gives, a word or extended-range attachment - /// written under a mask of some of a word's channels, and an attachment a private logic - /// operation the function computes serves. `Device::compile_render_pipeline` sets it for a - /// `Function` fragment stage on such a device, and a fragment compiled on its own for such a - /// pipeline compiles under the same state; without it such a function is - /// `NeedsInput(FramebufferFetch)`. `None` on every other device and for every other - /// function. - #[cfg_attr(feature = "serde", serde(default))] - pub framebuffer_fetch: Option, /// Texture slots bound to an 8-bit sRGB texture the device cannot sample, which the runtime /// holds as the format's UNORM twin, whose views read the codes (`VariantKey::srgb_textures`, /// `RuntimeFact::SrgbTexture`): each `half` or `float` access of such a slot decodes what its @@ -473,8 +461,7 @@ pub struct LoweringInputs { /// unblended (or blended with factors one and zero, added), under a write mask of all of the /// format's channels or none, and that is not attachment 0 under alpha-to-coverage, of a format /// the device samples but does not render (one written under a mask of some of its channels - /// is merged over the input attachment where the device orders fetch so, named in - /// [`framebuffer_fetch`](Self::framebuffer_fetch)). The function writes such an attachment + /// takes the format's own attachment). The function writes such an attachment /// through an output variable of the word's unsigned integer, the word Metal stores for its /// `float` or `half` output (`ChannelWrite::HalfUnorm`'s rule per channel); a dual-source /// second output there is stored nowhere, as Metal's unblended write reads none, and a color @@ -593,16 +580,6 @@ pub struct LoweringInputs { /// tests nothing. Any other function compiles as without it. #[cfg_attr(feature = "serde", serde(default))] pub alpha_test: Option, - /// The render pipeline's private logic operation (`logicOperationEnabled`, `logicOperation`), - /// which the fragment function computes itself on a device without Vulkan's `logicOp` that - /// orders framebuffer fetch: its first output's write to each normalized or integer attachment - /// the operation serves reads the pixel's texel, operates on the codes, and stores the result - /// (`StageIo::logic_operation`; `lower::fragment`'s `logic`). `Device::compile_render_pipeline` - /// sets it for a `Function` fragment stage of such a pipeline on such a device, for every - /// operation but copy and no-op, which the attachments' blends and masks draw. Any other - /// function compiles as without it. - #[cfg_attr(feature = "serde", serde(default))] - pub logic_operation: Option, /// The render pipeline's private `fragmentDepthCompareClampMask`: a fragment function's depth /// comparison through `[[sampler(s)]]` where bit `s` is set, or through a constexpr sampler /// where bit 31 is, clamps its reference to `[0, 1]`, a NaN taken as 0, before comparing, as @@ -993,112 +970,6 @@ impl AmplificationDraws { } } -/// The render pipeline state a fragment function's computed writes over its input attachments -/// depend on (`LoweringInputs::framebuffer_fetch`): the attachments whose blend, merge or logic -/// operation the function computes over the texel it reads. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct FramebufferFetchInputs { - /// Each color attachment index the function declares a `[[color(n)]]` input for: the - /// descriptor's attachment there, `None` where the descriptor sets none. - pub attachments: BTreeMap>, -} - -impl FramebufferFetchInputs { - /// The state of a pipeline whose color attachments are `colors` (by Metal index), for a - /// function whose writes at `read` the function computes over its input attachments. - pub fn of( - read: impl IntoIterator, - colors: &[Option], - ) -> FramebufferFetchInputs { - FramebufferFetchInputs { - attachments: read - .into_iter() - .map(|color| { - let attachment = - colors - .get(color as usize) - .copied() - .flatten() - .map(|a| FetchedAttachment { - pixel_format: a.pixel_format, - blending_enabled: a.blending_enabled, - write_mask: crate::lower::fragment::compiled_write_mask( - a.pixel_format, - a.write_mask, - a.blending_enabled, - ), - replaces: crate::pipeline::color_writes::replaces(&a), - equation: BlendEquation::of(&a), - }); - (color, attachment) - }) - .collect(), - } - } -} - -/// What a function's computed write over its input attachment reads of one color attachment's -/// descriptor. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct FetchedAttachment { - pub pixel_format: metal::PixelFormat, - pub blending_enabled: bool, - /// The descriptor's write mask, as the function compiles it: for a format whose kept - /// channels a draw names (every format but an extended-range or an sRGB one), the mask's class - /// (none where it covers none of the format's channels, all where it covers every one, and for - /// a mask covering some, every channel of the format but its first), so that the masks of a - /// class share one key; any other format's mask as the descriptor sets it. - pub write_mask: metal::ColorWriteMask, - /// The descriptor's blend factors are one and zero, added, for color and alpha: where - /// blending is enabled, Metal stores the source as blending disabled does (but a signed - /// normalized NaN, and a 16-bit float attachment's blend without fast math, which keeps the - /// destination's product by zero). - #[cfg_attr(feature = "serde", serde(default))] - pub replaces: bool, - /// The descriptor's blend where it enables blending, which the function computes in the - /// shader for an extended-range attachment (`metal::format::ExtendedRange`) it writes. - #[cfg_attr(feature = "serde", serde(default))] - pub equation: Option, -} - -/// A color attachment's blend as its descriptor states it: the factors and operation of the color -/// channels and of alpha. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BlendEquation { - /// `sourceRGBBlendFactor`. - pub source_rgb: metal::BlendFactor, - /// `destinationRGBBlendFactor`. - pub destination_rgb: metal::BlendFactor, - /// `rgbBlendOperation`. - pub rgb_operation: metal::BlendOperation, - /// `sourceAlphaBlendFactor`. - pub source_alpha: metal::BlendFactor, - /// `destinationAlphaBlendFactor`. - pub destination_alpha: metal::BlendFactor, - /// `alphaBlendOperation`. - pub alpha_operation: metal::BlendOperation, -} - -impl BlendEquation { - /// The blend of attachment `c`, where it enables blending. - pub fn of(c: &crate::pipeline::descriptor::ColorAttachmentDescriptor) -> Option { - c.blending_enabled.then_some(BlendEquation { - source_rgb: c.source_rgb_blend_factor, - destination_rgb: c.destination_rgb_blend_factor, - rgb_operation: c.rgb_blend_operation, - source_alpha: c.source_alpha_blend_factor, - destination_alpha: c.destination_alpha_blend_factor, - alpha_operation: c.alpha_blend_operation, - }) - } -} - impl LoweringInputs { /// No inputs: fixed-function vertex fetch, no variants. pub fn new() -> LoweringInputs { diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 87d6ff6c6..04ffce632 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -133,9 +133,8 @@ pub use layout::{ }; pub use link::{heap_sampler_capacity, heap_unused_while_pending}; pub use lower_inputs::{ - AliasView, AmplificationDraws, BlendEquation, ChannelWrite, ExtendedRangeColor, FactorLane, - FetchedAttachment, FramebufferFetchInputs, KernelVariant, LoweringInputs, StorageImageChoice, - StorageImageClass, VertexFetch, VertexFetchProjection, + AliasView, AmplificationDraws, ChannelWrite, ExtendedRangeColor, FactorLane, KernelVariant, + LoweringInputs, StorageImageChoice, StorageImageClass, VertexFetch, VertexFetchProjection, }; pub use own::{own_kernel, ExecutionCounts, OwnKernel}; pub use table::FunctionHandle; diff --git a/crates/metal2vulkan/src/pipeline/private_state.rs b/crates/metal2vulkan/src/pipeline/private_state.rs index 86d29ae2b..e3b761759 100644 --- a/crates/metal2vulkan/src/pipeline/private_state.rs +++ b/crates/metal2vulkan/src/pipeline/private_state.rs @@ -62,28 +62,12 @@ //! code above it: Vulkan's operation is the device's native form there, recorded //! (`PrecisionNote::NativeLogicOperation`, [`note_vulkan_codes`]). An integer output past the //! channel's range, which Metal saturates first, Vulkan's conversion leaves undefined -//! (lavapipe and an RTX 3090 saturate it, as Metal does). A device without it that -//! orders framebuffer fetch through rasterization-order input attachments has the fragment -//! function compute -//! the operation itself, over the texel its first output's write reads (`lower::fragment`'s -//! `logic`; probe `logic_operation` on an Apple M3 Max, macOS 27.0.1: every operation into -//! `R8Unorm`, `A8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`, `R16Unorm`, `RGBA16Unorm`, `RGB10A2Unorm`, -//! `BGR10A2Unorm`, `RG8Snorm`, -//! `RGBA8Snorm`, `RG16Snorm`, `RGBA16Snorm`, `RGBA8Uint`, `R16Uint`, `R32Uint`, `RGBA8Sint`, -//! `RG16Sint` and `R32Sint`, some under write masks, at 4 samples and over overlapping -//! fragments): a NaN takes the channel's low end (0, or -1 signed), a signed -//! normalized channel's lowest code reads and stores as the code above it, and an integer output -//! saturates to the channel's range before the operation; `RGB10A2Unorm` and `BGR10A2Unorm` -//! operate on their codes widened to 16 bits, the result narrowed back. It refuses formats -//! outside that rule (`RGB10A2Uint` and the packed 16-bit formats, whose operation Metal -//! computes otherwise), color 0 under alpha to coverage, and a function that writes the attachment -//! through a merged word ([`logic_operated`]). A device that does not order fetch refuses the -//! operation naming Vulkan's operation and rasterization-order access. So is an operation -//! other than copy and no-op refused where Vulkan's form is not Metal's: an sRGB attachment -//! (Vulkan applies none there), a float attachment that blends under Vulkan's operation (which -//! turns every blend off), a format whose operation Metal was not measured with -//! (extended-range, packed small-float, YCbCr), or a function that writes an attachment itself -//! ([`logic_operated`]). +//! (lavapipe and an RTX 3090 saturate it, as Metal does). A device without `logicOp` refuses +//! the operation naming it: the fragment function's own operation over an ordered read of the +//! attachment is not built. So is an operation other than copy and no-op refused where +//! Vulkan's form is not Metal's: an sRGB attachment (Vulkan applies none there), a float +//! attachment that blends under Vulkan's operation (which turns every blend off), and a format +//! whose operation Metal was not measured with (extended-range, packed small-float, YCbCr). //! - `sampleCoverage` keeps a fraction of the samples, dithered over each 2x2 quad of window //! pixels, and is applied as `sampleMask` is, after the function runs: the value clamped to //! `[0, 1]` (a NaN taken as 0) and converted to an 8-bit unorm code `c`; at one sample a pixel @@ -424,67 +408,27 @@ fn logic_class(pf: PixelFormat) -> LogicClass { } } -/// How a pipeline draws its private logic operation other than copy and no-op -/// ([`logic_operation`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum LogicDraw { - /// Through Vulkan's `logicOp` ([`GraphicsState::logic_op`]). - Vulkan(vk::LogicOp), - /// By the fragment function, over the texel its write reads through framebuffer fetch - /// (`LoweringInputs::logic_operation`, `lower::fragment`'s `logic`), on a device without - /// Vulkan's `logicOp` that orders the fetch. - Shader(vk::LogicOp), -} - -impl LogicDraw { - /// The Vulkan logic operation the pipeline draws with, if any. - pub(crate) fn vulkan(draw: Option) -> Option { - match draw { - Some(LogicDraw::Vulkan(op)) => Some(op), - _ => None, - } - } - - /// The logic operation the fragment function computes, if any. - pub(crate) fn shader(draw: Option) -> Option { - match draw { - Some(LogicDraw::Shader(op)) => Some(op), - _ => None, - } - } -} - -/// The pipeline `d` draws as on `p` under its private logic operation (the module docs), and how -/// it draws the operation: each normalized, sRGB and integer attachment unblended, under a no-op -/// also unwritten, a float attachment as it is. Copy and no-op are then Metal's on every device -/// and need no operation. Every other operation takes Vulkan's `logicOp` -/// ([`LogicDraw::Vulkan`]); on a device without it that orders framebuffer fetch, the fragment -/// function computes it ([`LogicDraw::Shader`]), refused `NotImplemented` -/// (`PrivateRenderField::LogicOperation`) at a normalized or integer attachment whose format it -/// does not serve (`lower::fragment`'s `logic`); on a device that has neither, it is refused naming -/// them. Every operation but copy and no-op is refused `NotImplemented` where an attachment is -/// sRGB, where a float attachment blends under Vulkan's operation, and where an attachment's -/// format was not measured. A pipeline without a fragment function writes no color, and takes no -/// operation. +/// The pipeline `d` draws as on `p` under its private logic operation (the module docs), and the +/// Vulkan `logicOp` it draws the operation with ([`GraphicsState::logic_op`]): each normalized, +/// sRGB and integer attachment unblended, under a no-op also unwritten, a float attachment as it +/// is. Copy and no-op are then Metal's on every device and need no operation. Every other +/// operation takes Vulkan's `logicOp`, refused naming it on a device without it, and refused +/// `NotImplemented` where an attachment is sRGB, where a float attachment blends under Vulkan's +/// operation, and where an attachment's format was not measured. A pipeline without a fragment +/// function writes no color, and takes no operation. pub(crate) fn logic_operation<'a>( d: &'a RenderPipelineDescriptor, p: &DeviceProfile, -) -> Result<(Cow<'a, RenderPipelineDescriptor>, Option), Error> { +) -> Result<(Cow<'a, RenderPipelineDescriptor>, Option), Error> { if !d.private.logic_operation_enabled || d.fragment.is_none() { return Ok((Cow::Borrowed(d), None)); } let op = LOGIC_OPS[(d.private.logic_operation & 15) as usize]; let blendless = matches!(op, vk::LogicOp::COPY | vk::LogicOp::NO_OP); - let shader = !blendless && !p.fields().enabled.features.contains(&VkFeature::LogicOp); - if shader && !crate::lower::fragment::inputs_order(p) { - return Err(Unsupported::needs_any_of( + if !blendless && !p.fields().enabled.features.contains(&VkFeature::LogicOp) { + return Err(Unsupported::needs( Feature::PrivateRenderState(PrivateRenderField::LogicOperation), - vec![ - vec![Capability::Feature(VkFeature::LogicOp)], - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess, - )], - ], + Capability::Feature(VkFeature::LogicOp), ) .into()); } @@ -503,19 +447,10 @@ pub(crate) fn logic_operation<'a>( match (logic_class(a.pixel_format), blendless) { (LogicClass::Unmeasured, _) => return Err(refused()), (LogicClass::Float, true) => {} - // The function leaves a float attachment to the device's blend. - (LogicClass::Float, false) if a.blending_enabled && !shader => return Err(refused()), + // Vulkan's operation turns every blend off. + (LogicClass::Float, false) if a.blending_enabled => return Err(refused()), (LogicClass::Float, false) => {} (LogicClass::Srgb, false) => return Err(refused()), - // A format the function's operation does not serve, and color 0 under alpha to - // coverage, whose alpha the coverage reads before Metal's operation. - (LogicClass::Codes, false) - if shader - && (crate::lower::fragment::logic_channels(a.pixel_format).is_none() - || (index == 0 && d.alpha_to_coverage)) => - { - return Err(refused()); - } (LogicClass::Codes, _) | (LogicClass::Srgb, true) => { a.blending_enabled = false; if op == vk::LogicOp::NO_OP { @@ -524,56 +459,13 @@ pub(crate) fn logic_operation<'a>( } } } - let draw = match (blendless, shader) { - (true, _) => None, - (false, true) => Some(LogicDraw::Shader(op)), - (false, false) => Some(LogicDraw::Vulkan(op)), - }; - Ok((Cow::Owned(out), draw)) -} - -/// `Ok` where the linked pipeline `g` draws its logic operation `draw` ([`logic_operation`]) as -/// Metal's. Vulkan's operation applies to the color attachments of the subpass alone, so a -/// pipeline whose fragment function merges a word with its input attachment's is refused -/// (`PrivateRenderField::LogicOperation`), Metal's answer there unmeasured. The operation the -/// fragment function computes must be the one it compiled under (`StageIo::logic_operation`, -/// else `NeedsInput(LogicOperation)`). -pub(crate) fn logic_operated( - draw: Option, - fragment: Option<&FunctionArtifact>, -) -> Result<(), Error> { - let compiled = fragment.and_then(|f| f.interface.io.logic_operation); - let Some(draw) = draw else { - return match compiled { - Some(_) => Err(Error::NeedsInput(RuntimeInput::LogicOperation)), - None => Ok(()), - }; - }; - let merges = fragment.is_some_and(|f| { - f.facts.iter().any(|fact| { - matches!( - fact, - crate::pipeline::facts::RuntimeFact::WordInputMerge { .. } - ) - }) - }); - match draw { - LogicDraw::Vulkan(_) if merges => Err(refused(PrivateRenderField::LogicOperation)), - LogicDraw::Vulkan(_) => match compiled { - Some(_) => Err(Error::NeedsInput(RuntimeInput::LogicOperation)), - None => Ok(()), - }, - LogicDraw::Shader(op) => match compiled == Some(op) { - true => Ok(()), - false => Err(Error::NeedsInput(RuntimeInput::LogicOperation)), - }, - } + Ok((Cow::Owned(out), (!blendless).then_some(op))) } /// Note Vulkan's operation (`PrecisionNote::NativeLogicOperation`) on the fragment stage among /// `modules` of the linked pipeline `g`, of descriptor `d` as it draws its logic operation /// ([`logic_operation`]), where Vulkan's `logicOp` ([`GraphicsState::logic_op`]) operates on an -/// attachment whose codes Metal's operation takes otherwise (`lower::fragment`'s `logic`): +/// attachment whose codes Metal's operation takes otherwise (`lower::fragment::logic_vulkan_differs`): /// `RGB10A2Unorm` and `BGR10A2Unorm`, whose codes Metal widens to 16 bits, and a signed normalized /// format, whose lowest code Metal reads and stores as the code above it; one a first output /// writes (`GraphicsState::color_outputs`) with a channel its write mask keeps. Vulkan's @@ -657,8 +549,8 @@ pub(crate) fn note_tile_store(d: &RenderPipelineDescriptor, modules: &mut [Stage /// The text the key of the render pipeline `d` appends for its private state: empty at Metal's /// defaults and wherever only properties that change nothing differ, so every other pipeline /// keeps its key. A logic operation's attachments are already in `d` as it draws them -/// ([`logic_operation`]), so only the operation is added, Vulkan's or the fragment function's: -/// copy and no-op key as the pipeline of those attachments. +/// ([`logic_operation`]), so only Vulkan's operation is added: copy and no-op key as the pipeline +/// of those attachments. pub(crate) fn render_key_fields(d: &RenderPipelineDescriptor) -> String { let mut fields = match applied_masks(d) { Some(m) if uniform(&m) => format!(" sample_mask {:#x}", m[0]), diff --git a/crates/metal2vulkan/src/pipeline/rotated_blend.rs b/crates/metal2vulkan/src/pipeline/rotated_blend.rs index 8909c9c82..450c938a8 100644 --- a/crates/metal2vulkan/src/pipeline/rotated_blend.rs +++ b/crates/metal2vulkan/src/pipeline/rotated_blend.rs @@ -23,15 +23,13 @@ //! the very value Metal's blend reads, and computes one minus it itself, as Metal's does. This //! needs `dualSrcBlend`. A blend of Metal's own second output (`Source1` factors) reads that //! output, which the function stores rotated as the image's channels are. -//! - **What no such factor gives, the fragment function computes:** Metal's destination alpha in -//! a color factor, the saturated source alpha, the blend color's red, green or blue, and -//! different color and alpha operations (`rotated_blend` refuses them `NotImplemented(Format)`). -//! Where the device orders framebuffer fetch, the function reads the texel, rotates it into -//! Metal's order, and computes Metal's 8-bit unorm blend over it -//! (`color_writes::shader_rotated_blend`, over the input attachment); a device that does not -//! order fetch so refuses the pipeline naming rasterization-order access. A factor of the second source (Metal's own second output beside one the rotation -//! needs, or any `Source1` factor where no Vulkan state gives the blend) stays -//! `NotImplemented(Format)`. A one minus a value the function would compute is not offered +//! - **What no such factor gives is refused:** Metal's destination alpha in a color factor, the +//! saturated source alpha, the blend color's red, green or blue, and different color and alpha +//! operations (`rotated_blend` refuses them `NotImplemented(Format)`). The fragment function's +//! own blend over an ordered read of the texel is not built: link refuses the pipeline +//! (`color_writes::rotated_blend_in_shader`, `NotImplemented(FramebufferFetch)`). A factor of +//! the second source (Metal's own second output beside one the rotation needs, or any `Source1` +//! factor where no Vulkan state gives the blend) stays `NotImplemented(Format)`. A one minus a value the function would compute is not offered //! among Vulkan's factors: it would round apart from the blend's own. //! //! **Rounding.** Apple's blend does not compute every factor pair alike in its color and alpha diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index 86b03cd7c..1572e293b 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -252,13 +252,6 @@ pub struct StageIo { /// the comparison against `PushField::AlphaTestReference`. `None` for every other function. #[cfg_attr(feature = "serde", serde(default))] pub alpha_test: Option, - /// The render pipeline's private logic operation the fragment function computes itself - /// (`LoweringInputs::logic_operation`): its first output's writes to the attachments the - /// operation serves store the operation of their codes over the texels they read. Link - /// refuses the function in a pipeline that draws another operation, or none - /// (`NeedsInput(LogicOperation)`). `None` for every other function. - #[cfg_attr(feature = "serde", serde(default))] - pub logic_operation: Option, /// The samplers a fragment function makes depth comparisons through, and those whose /// references it clamps (`LoweringInputs::depth_compare_clamp_mask`). Link refuses a function /// whose clamped samplers are not the pipeline's mask over its samplers diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index c10fb9103..7f7fc2484 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -872,8 +872,7 @@ pub enum PushField { /// Residual bind offset of a descriptor-form slot: the bind offset minus the descriptor base, /// modulo 2^32. SlotBindOffset(SlotRef), - /// Under the identity domains, on a device that orders framebuffer fetch in neither form - /// (`lower::fragment::fetch::fetch_unordered`), the element of the set-1 sampled-texture array + /// Under the identity domains, the element of the set-1 sampled-texture array /// through which a fragment function reads color attachment `color` (`[[color(n)]]`): one /// `u32`, the index of an element holding a 2D view of the attachment's level and slice /// (multisampled in a multisampled pipeline), which the function fetches as `texels` at the diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 5675d9b99..06062394e 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -264,8 +264,7 @@ pub fn fragment_inputs( inputs } -/// [`compile`] under lowering inputs `inputs` (a pipeline's state, such as its framebuffer -/// fetch's). +/// [`compile`] under lowering inputs `inputs` (a pipeline's state, such as its color writes'). pub fn compile_with( bitcode: &[u8], entry: &str, diff --git a/crates/metal2vulkan/src/tests/engine_coverage_loop.rs b/crates/metal2vulkan/src/tests/engine_coverage_loop.rs index 9540d8c9c..8edaf6206 100644 --- a/crates/metal2vulkan/src/tests/engine_coverage_loop.rs +++ b/crates/metal2vulkan/src/tests/engine_coverage_loop.rs @@ -501,8 +501,7 @@ fn l3(dev: &Device, p: &RenderPipeline, what: &str) { /// Over `coverage_loop` on every committed profile at four samples: where the device makes the /// memory writers, they loop without sample shading, each function holding one thing the loop -/// does not fit is refused for that thing (or first for a feature the device lacks, as the color -/// attachment read where neither rasterization-order access nor pixel interlock exists, but never +/// does not fit is refused for that thing (or first for a feature the device lacks, but never /// made), and the sample-qualified varying loops, read at each /// pass's sample through `InterpolateAtSample` with no `Sample` decoration, or is refused as /// needing the interpolation functions on a device that withholds them. A device that does not diff --git a/crates/metal2vulkan/src/tests/engine_dead_fetch.rs b/crates/metal2vulkan/src/tests/engine_dead_fetch.rs index b7c33a264..34c710202 100644 --- a/crates/metal2vulkan/src/tests/engine_dead_fetch.rs +++ b/crates/metal2vulkan/src/tests/engine_dead_fetch.rs @@ -11,8 +11,7 @@ //! nothing of the attachment, so on every committed profile its pipeline is the one of a function //! that declares no color input: color 0 an ordinary color attachment that the device blends //! where the pipeline blends, and no input attachment, its stages passing L3. Specialized with the -//! read live, each reads color 0 through an input attachment: ordered where the device orders it -//! through rasterization-order input attachments, and ordered between draws alone elsewhere, its +//! read live, each reads color 0 through an input attachment, ordered between draws alone, its //! fragment stage noting `UnorderedFetchWithinDraw`. //! No GPU is used. @@ -22,7 +21,6 @@ use crate::budget::Budget; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::Error; use crate::library::{FunctionConstantValue, FunctionConstantValues, Library}; -use crate::lower::fragment::inputs_order; use crate::metal::{BlendFactor, BlendOperation, DataType, PixelFormat}; use crate::pipeline::artifact::{PrecisionNote, RenderPipeline}; use crate::pipeline::descriptor::{ @@ -140,8 +138,7 @@ fn a_framebuffer_read_dead_after_specialization_takes_no_fetch_form() { .unwrap_or_else(|e| panic!("{what}, dead: L3: {e}")); } dead += 1; - // Rasterization-order input attachments, or input attachments ordered between - // draws alone, noted. + // An input attachment ordered between draws alone, noted. let pipe = pipeline(&dev, &library, entry, true, blended) .unwrap_or_else(|e| panic!("{what}, live: {e}")); let read: Vec = (pipe.graphics.input_attachments.iter()) @@ -151,7 +148,7 @@ fn a_framebuffer_read_dead_after_specialization_takes_no_fetch_form() { let noted = (pipe.stages.iter()).any(|s| { (s.precision_notes).contains(&PrecisionNote::UnorderedFetchWithinDraw) }); - assert_eq!(noted, !inputs_order(&p), "{what}, live"); + assert!(noted, "{what}, live"); } } } diff --git a/crates/metal2vulkan/src/tests/engine_dead_reads.rs b/crates/metal2vulkan/src/tests/engine_dead_reads.rs index 19dd77282..93ba053a7 100644 --- a/crates/metal2vulkan/src/tests/engine_dead_reads.rs +++ b/crates/metal2vulkan/src/tests/engine_dead_reads.rs @@ -9,11 +9,9 @@ //! five colors, and `dfr_output` (a color 0 input of a color 0 output in group 0) over one, with //! the read dead as with it live. Specialized dead, each compiles on every profile here without //! an interlock, including a device without one, passing L3. Specialized live, `dfr_buffer` -//! takes the pixel interlock where the device has it and is refused where it has none; -//! `dfr_color` and `dfr_output` take it where the device orders fetch through -//! rasterization-order input attachments (`lavapipe`). Elsewhere (`moltenvk-m3` with and -//! without the interlock, `runtime-floor`) the group on their color orders only what the read -//! orders there: the input attachment, between draws, compiled without an interlock and noted +//! takes the pixel interlock where the device has it and is refused where it has none. On +//! every device the group on the color of `dfr_color` and `dfr_output` orders only what the read +//! orders: the input attachment, between draws, compiled without an interlock and noted //! (`PrecisionNote::UnorderedFetchWithinDraw`). //! - **A color input without an attachment** is Metal's pipeline error whether or not the body //! reads it ("Shaders reads from a color attachment whose pixel format is @@ -129,12 +127,6 @@ fn interlocks(words: &[u32]) -> bool { false } -/// Whether `dev` orders framebuffer fetch between draws alone: no rasterization-order color -/// attachment access. -fn unordered(dev: &Device) -> bool { - !dev.profile().fragment().rasterization_order_color_access -} - fn fragment(p: &RenderPipeline) -> &[u32] { let m = p .stages @@ -155,9 +147,8 @@ fn validate(p: &RenderPipeline, dev: &Device, what: &str) { /// interlock on `lavapipe`, `moltenvk-m3` and `moltenvk-m3` without either interlock, and /// `dfr_output` on `runtime-floor` (no interlock). Live, `dfr_buffer` interlocks where the device /// has the pixel interlock and is refused on `moltenvk-m3` without either interlock; `dfr_color` -/// and `dfr_output` interlock on `lavapipe`, and on the devices without rasterization-order -/// access read their color as the input attachment without an interlock, the fragment stage -/// noting `UnorderedFetchWithinDraw`. +/// and `dfr_output` read their color as the input attachment without an interlock on every device, +/// the fragment stage noting `UnorderedFetchWithinDraw`. #[test] fn a_raster_order_group_on_an_input_dead_after_specialization_takes_no_interlock() { let (Some(vs), Some(fs)) = (fixture("color_groups"), fixture("dfk_dead_rog")) else { @@ -211,8 +202,8 @@ fn a_raster_order_group_on_an_input_dead_after_specialization_takes_no_interlock dev.compile_render_pipeline(&specialized(&vs, &fs, entry, colors, true), &budget); match (interlock, live) { // Fetch ordered between draws alone: a group on a color read orders that read alone, - // which is ordered between draws there. - (_, Ok(p)) if unordered(dev) && *entry != "dfr_buffer" => { + // which is ordered between draws. + (_, Ok(p)) if *entry != "dfr_buffer" => { assert!(!interlocks(fragment(&p)), "{what}: interlocked"); assert_eq!(p.graphics.input_attachments.len(), 1, "{what}"); let noted = (p.stages.iter()).any(|m| { diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs b/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs index efbc61343..9e0f286b4 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs @@ -15,9 +15,9 @@ //! states no multisampled color attachment of the raw format (`R16G16B16A16_UINT`: its //! `framebufferIntegerColorSampleCounts` is one sample, and it records no count of that format's //! own), so a pipeline of four samples is refused there naming the properties it needs. An -//! unblended mask of some of the codes one word holds (`BGR10_XR`'s, the two-plane forms') merges -//! them over the input attachment where the device orders fetch through rasterization-order input -//! attachments. No GPU is used. +//! unblended mask of some of the codes one word holds (`BGR10_XR`'s, the two-plane forms') is +//! refused `NotImplemented(FramebufferFetch)` on every device: their merge over an ordered read of +//! the attachment is not built. No GPU is used. //! //! `llvm-as` assembles the fixture `rt6_samples`; without it the tests skip visibly. @@ -26,7 +26,6 @@ use crate::error::{Error, Needs, Unsupported}; use crate::metal::{BlendFactor, ColorWriteMask}; use crate::pipeline::descriptor::{ColorAttachmentDescriptor, RenderPipelineDescriptor}; use crate::pipeline::RenderPipeline; -use crate::spirv::testing::check_words_valid; use crate::vk; /// The profiles: the reported device's family, MoltenVK's and lavapipe's. @@ -283,13 +282,11 @@ fn unwritten_and_masked_extended_range_attachments_are_made() { assert_eq!(made_count, 3 * shapes * 2 + shapes); } -/// On a device that orders framebuffer fetch in neither form (no `fragmentShaderPixelInterlock`, -/// no `rasterizationOrderColorAttachmentAccess`: the runtime's floor), a written blended -/// attachment of either format is refused `NotImplemented(Format)`, as on a device that orders it, -/// the refusal the public door (`metal::format::extended_range_blend`) gives: no device would make -/// it. The unwritten attachment, which takes no blend, is still made there. +/// On the runtime's floor (no `fragmentShaderPixelInterlock`), a written blended attachment of +/// either format is refused `NotImplemented(Format)`, as on every device: no device would make it. +/// The unwritten attachment, which takes no blend, is still made there. #[test] -fn an_unordered_device_refuses_an_extended_range_blend_as_every_device_does() { +fn the_floor_refuses_an_extended_range_blend_as_every_device_does() { let Some(library) = library() else { return; }; @@ -308,10 +305,6 @@ fn an_unordered_device_refuses_an_extended_range_blend_as_every_device_does() { let wanted = Unsupported::not_implemented(Feature::Format); for stem in ["runtime-floor"] { let dev = device(stem); - assert!( - crate::lower::fragment::fetch::fetch_unordered(dev.profile()), - "{stem}" - ); for pf in FORMATS { for fill in ["rt6_fill_rgba16float", "rt6_fill_rgba32float"] { let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); @@ -342,14 +335,12 @@ fn an_unordered_device_refuses_an_extended_range_blend_as_every_device_does() { /// An unblended write of some of the codes one word holds (`BGR10_XR`'s and its twin's word, the /// two-plane forms' color word: `color_writes::merged_extended`), which no mask of the raw -/// components gives: on lavapipe, which orders fetch through rasterization-order input -/// attachments, the function merges them over the input attachment, from a `half4` output and a -/// `float4` one: color 0 stays a color attachment of the raw format with no blend and a write of -/// every raw component, the stage states `RuntimeFact::WordInputMerge` with the channels the mask -/// keeps, and it passes L3 (four samples are its profile's gap). On a device that does not order -/// fetch so, the pixel interlock's included, the refusal names the ordering the merge needs. +/// components gives, from a `half4` output and a `float4` one, is refused +/// `NotImplemented(FramebufferFetch)` on every device here, lavapipe and the floor included: the +/// merge over an ordered read of the attachment is not built. At four samples a device that lacks +/// the raw format's samples may name that instead. #[test] -fn a_mask_of_some_codes_of_a_word_merges_them_over_the_input_attachment() { +fn a_mask_of_some_codes_of_a_word_is_refused_on_every_device() { let Some(library) = library() else { return; }; @@ -369,18 +360,17 @@ fn a_mask_of_some_codes_of_a_word_merges_them_over_the_input_attachment() { ColorWriteMask::BLUE.union(ColorWriteMask::GREEN), ColorWriteMask::RED.union(ColorWriteMask::ALPHA), ]; - let unordered = crate::lower::fragment::fetch::unordered_extended_fetch(); - let mut merged = 0; - for stem in [ + let stems = [ "nvidia-rtx50-linux", "nvidia-rtx5080-laptop", "moltenvk-m3", "intel-uhd770-rpls-anv", "lavapipe", "runtime-floor", - ] { + ]; + let mut refused = 0; + for stem in stems { let dev = device(stem); - let inputs = crate::lower::fragment::inputs_order(dev.profile()); for pf in formats { for mask in masks { for fill in ["rt6_fill_rgba16float", "rt6_fill_rgba32float"] { @@ -392,52 +382,19 @@ fn a_mask_of_some_codes_of_a_word_merges_them_over_the_input_attachment() { let what = format!("{stem} {pf:?} mask {} {fill} x{samples}", mask.as_raw()); match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(pipe) => { - assert!(inputs, "{what}"); - if inputs { - let a = pipe.graphics.color_attachments[0].expect("attachment"); - let form = ExtendedRange::of(pf).expect("a form"); - assert_eq!(a.format, form.raw_format(), "{what}"); - let whole = match form.raw_components() { - 1 => vk::ColorComponentFlags::R, - _ => { - vk::ColorComponentFlags::R | vk::ColorComponentFlags::G - } - }; - assert_eq!(a.write_mask, whole, "{what}"); - assert!(a.blend.is_none(), "{what}"); - let kept = crate::metal::state::color_write_mask( - crate::lower::fragment::kept_channels(pf, mask, true), - ) - .expect("mask"); - let fact = crate::pipeline::RuntimeFact::WordInputMerge { - color: 0, - kept, - }; - assert!( - pipe.dependencies.iter().any(|d| d.fact == fact), - "{what}: {:?}", - pipe.dependencies - ); - } - for m in &pipe.stages { - check_words_valid(&m.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - merged += 1; + Err(Error::Unsupported(u)) + if (u.feature, &u.needs) + == (Feature::FramebufferFetch, &Needs::NotImplemented) => + { + refused += 1; } - Err(Error::Unsupported(u)) if !inputs => { - assert_eq!(u.feature, unordered.feature, "{what}: {u:?}"); - assert_eq!(u.needs, unordered.needs, "{what}: {u:?}"); - } - Err(e) if inputs && samples > 1 && lacks_samples(&e) => {} - Err(e) => panic!("{what}: {e:?}"), + Err(e) if samples > 1 && lacks_samples(&e) => {} + other => panic!("{what}: {:?}", other.map(|_| ())), } } } } } } - // Lavapipe at one sample. - assert_eq!(merged, formats.len() * masks.len() * 2); + assert!(refused >= stems.len() * formats.len() * masks.len() * 2); } diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs b/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs index 1376d7f73..3f5bb035f 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs @@ -18,10 +18,9 @@ //! alpha byte's. A blended attachment no first output writes links so whatever its form, a padded //! or bfloat one's too. //! - Refused, typed: a blended attachment the function writes, a fetch of the attachment -//! (`NotImplemented(Format)`, on every device), a mask of some of the codes one word -//! holds from a stage compiled without the pipeline's fetch state -//! (`NeedsInput(FramebufferFetch)`; a stage compiled for the pipeline merges them in the storage -//! form or over the input attachment, `blended_pipelines`), an +//! (`NotImplemented(Format)`, on every device), a mask of some of the codes one word holds +//! (`NotImplemented(FramebufferFetch)`, on every device: their merge over an ordered read of the +//! attachment is not built, `blended_pipelines`), an //! integer or a `float` output (Metal's pipeline errors, `ColorAttachment`), a fragment compiled //! without the pipeline's attachments (`NeedsInput(ColorWrites)`). @@ -111,20 +110,6 @@ fn is_format_refusal(e: &Error) -> bool { matches!(e, Error::Unsupported(u) if u.feature == Feature::Format && u.needs == Needs::NotImplemented) } -/// [`fragment_inputs`] with the framebuffer-fetch state the pipeline compile gives a function -/// that writes color 0 where it blends an extended-range attachment there, on a device that -/// orders fetch through rasterization-order input attachments (`compile::fetch_inputs`). -fn blended_inputs(r: &RenderLinkInputs, p: &crate::device::profile::DeviceProfile) -> LowerInputs { - let mut inputs = fragment_inputs(r, p); - if crate::lower::fragment::inputs_order(p) { - inputs.framebuffer_fetch = Some(crate::pipeline::FramebufferFetchInputs::of( - [0], - &r.color_attachments, - )); - } - inputs -} - /// The fixture's `float4` and `half4` fills compile for each format's attachment on every venue, /// write its raw texel through an unsigned output variable, and link with the raw format (the /// module docs). @@ -329,7 +314,7 @@ fn fragment_outputs_to_bfloat_targets_write_raw_codes() { }); let r = pipeline_of(pf, ColorWriteMask::ALL, true); for entry in ["rt6_fill_rgba32float", "rt6_fill_rgba16float"] { - let e = compile_with(&bc, entry, &p, &blended_inputs(&r, &p)).expect_err(&what); + let e = compile_with(&bc, entry, &p, &fragment_inputs(&r, &p)).expect_err(&what); assert_eq!(e, invalid, "{what} {entry}"); } let e = link(&[&v], &render(&r), &p).expect_err(&what); @@ -429,7 +414,7 @@ fn unmodelled_extended_range_targets_are_refused() { let what = format!("{stem} {pf:?}"); // Blended: refused on every device, whichever form it fetches in. let r = pipeline_of(pf, ColorWriteMask::ALL, true); - match compile_with(&bc, "rt6_fill_rgba32float", &p, &blended_inputs(&r, &p)) { + match compile_with(&bc, "rt6_fill_rgba32float", &p, &fragment_inputs(&r, &p)) { Err(e) => assert!(is_format_refusal(&e), "{what} blended: {e}"), Ok(a) => panic!("{what} blended: made, {:?}", a.precision), } @@ -474,19 +459,14 @@ fn unmodelled_extended_range_targets_are_refused() { ); } form => { - // Merged by a stage compiled with the pipeline's fetch state where the device - // orders fetch through rasterization-order input attachments, which this one - // was not (`blended_pipelines`); elsewhere the ordering the merge needs. - let e = linked.expect_err(&what); - let unordered = crate::lower::fragment::fetch::unordered_extended_fetch(); - match (crate::lower::fragment::fetch::fetch_unordered(&p), e) { - (true, Error::Unsupported(u)) => assert_eq!( + // Their merge over an ordered read of the attachment is not built. + match linked.expect_err(&what) { + Error::Unsupported(u) => assert_eq!( (u.feature, u.needs), - (unordered.feature, unordered.needs), + (Feature::FramebufferFetch, Needs::NotImplemented), "{what} red mask" ), - (false, Error::NeedsInput(RuntimeInput::FramebufferFetch)) => {} - (_, e) => panic!("{what} red mask: {e}"), + e => panic!("{what} red mask: {e}"), } // The two-plane forms' three color codes alone are the color word, the // first raw component. diff --git a/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs b/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs index cedb72162..d032fbb50 100644 --- a/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs +++ b/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs @@ -1,19 +1,16 @@ //! A fragment function that fetches a blended 8-bit unorm attachment, in the shape of a //! CoreAnimation composite of the x86 macOS guest (the owned fixture `engine/fbl_fetch_blend8`, //! under fast math): color 0 blended with one over one minus the source alpha for color and alpha, -//! color 1 `RGBA16Float` of mask none, the function reading color 0. On a profile that orders -//! fetch through rasterization-order input attachments, a color input of an `ARGB8Unorm` -//! attachment, whose input attachment would read its image's rotated channels, is refused -//! `NotImplemented(Format)` at color 0. No GPU is used. +//! color 1 `RGBA16Float` of mask none, the function reading color 0. On every profile, a color +//! input of an `ARGB8Unorm` attachment, whose input attachment would read its image's rotated +//! channels, is refused `NotImplemented(Format)` at color 0. No GPU is used. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. -use crate::device::DeviceProfile; use crate::error::{Attachment, Error, Feature, Needs}; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; +use crate::metal::{BlendFactor, ColorWriteMask, PixelFormat}; use crate::pipeline::descriptor::ColorAttachmentDescriptor; use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs, LoweringInputs}; use crate::pipeline::testing::{compile_with, engine_dir, fragment_inputs, AssembleError}; use crate::spirv::testing::committed_profiles; @@ -31,28 +28,15 @@ fn assembled(stem: &str) -> Option> { } } -/// The guest's blend: one over one minus the source alpha, added, for color and alpha. -const OVER: BlendEquation = BlendEquation { - source_rgb: BlendFactor::One, - destination_rgb: BlendFactor::OneMinusSourceAlpha, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::OneMinusSourceAlpha, - alpha_operation: BlendOperation::Add, -}; - -/// The attachments: color 0 of `pf` blended by `eq` under write mask `mask`, color 1 of mask none. -fn attachments(pf: PixelFormat, eq: BlendEquation, mask: ColorWriteMask) -> RenderLinkInputs { +/// The attachments: color 0 of `pf` blended one over one minus the source alpha, added, for +/// color and alpha (the guest's blend), color 1 of mask none. +fn attachments(pf: PixelFormat) -> RenderLinkInputs { let mut blended = ColorAttachmentDescriptor::new(pf); blended.blending_enabled = true; - blended.source_rgb_blend_factor = eq.source_rgb; - blended.destination_rgb_blend_factor = eq.destination_rgb; - blended.rgb_blend_operation = eq.rgb_operation; - blended.source_alpha_blend_factor = eq.source_alpha; - blended.destination_alpha_blend_factor = eq.destination_alpha; - blended.alpha_blend_operation = eq.alpha_operation; - blended.write_mask = mask; - assert_eq!(BlendEquation::of(&blended), Some(eq)); + blended.source_rgb_blend_factor = BlendFactor::One; + blended.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; + blended.source_alpha_blend_factor = BlendFactor::One; + blended.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); unwritten.write_mask = ColorWriteMask::NONE; let mut r = RenderLinkInputs::new(); @@ -61,36 +45,18 @@ fn attachments(pf: PixelFormat, eq: BlendEquation, mask: ColorWriteMask) -> Rend r } -/// The lowering inputs of a function that reads color 0 in [`attachments`] on `p`. -fn state( - p: &DeviceProfile, - pf: PixelFormat, - eq: BlendEquation, - mask: ColorWriteMask, -) -> LoweringInputs { - let r = attachments(pf, eq, mask); - let mut inputs = fragment_inputs(&r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); - inputs -} - /// A color input of an `ARGB8Unorm` attachment, whose image holds Metal's channels rotated, on -/// every committed profile that orders fetch through rasterization-order input attachments: the -/// input attachment would read the image's order, so the function's lowering refuses it -/// `NotImplemented(Format)` at the attachment (link admits such an attachment's input attachment -/// only for the function's own blend over it, `RuntimeFact::RotatedInputBlend`). +/// every committed profile: the input attachment would read the image's order, so the function's +/// lowering refuses it `NotImplemented(Format)` at the attachment. #[test] -fn a_color_input_of_a_rotated_attachment_is_refused_over_its_input_attachment() { +fn a_color_input_of_a_rotated_attachment_is_refused() { let Some(fast) = assembled("fbl_fetch_blend8") else { return; }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::inputs_order(&p) { - continue; - } - let inputs = state(&p, PixelFormat::ARGB8Unorm, OVER, ColorWriteMask::ALL); - match compile_with(&fast, "fbl8_over_loaded", &p, &inputs) { + let profiles = committed_profiles().expect("profiles"); + for (stem, p) in &profiles { + let inputs = fragment_inputs(&attachments(PixelFormat::ARGB8Unorm), p); + match compile_with(&fast, "fbl8_over_loaded", p, &inputs) { Err(Error::Unsupported(u)) => { assert_eq!( (u.feature, u.needs), @@ -102,10 +68,6 @@ fn a_color_input_of_a_rotated_attachment_is_refused_over_its_input_attachment() } other => panic!("{stem}: {:?}", other.map(|_| ())), } - checked += 1; } - assert!( - checked > 0, - "no profile orders fetch through input attachments" - ); + assert!(!profiles.is_empty()); } diff --git a/crates/metal2vulkan/src/tests/engine_fragment.rs b/crates/metal2vulkan/src/tests/engine_fragment.rs index c1f178a64..40f8ec6b3 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment.rs @@ -7,8 +7,7 @@ //! fixtures `engine/fragment_rog` and `fragment_rog_msl22` cover raster order groups: the body //! runs as a function called between `Begin/EndInvocationInterlockEXT`, only the entry kills, and //! the body's loops stay in it. `engine/fragment_fetch` covers framebuffer fetch: input -//! attachments, ordered where the device has rasterization-order color attachment access. No GPU -//! is used. +//! attachments, ordered between draws. No GPU is used. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. @@ -28,7 +27,7 @@ use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, }; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::lower_inputs::{FramebufferFetchInputs, LoweringInputs}; +use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::sym::ResourceKind; use crate::pipeline::testing::{ compile, compile_with, engine_dir, interlocked_coherence, link_and_validate, llvm_assemble, @@ -434,84 +433,46 @@ fn attachments(a: &crate::library::FunctionArtifact) -> Vec { .collect() } -/// The framebuffer-fetch state of a pipeline whose color attachments are `formats` (by index), -/// read at `read`. -fn fetch_state(read: &[u32], formats: &[PixelFormat]) -> LoweringInputs { - let colors: Vec> = formats - .iter() - .map(|&f| Some(ColorAttachmentDescriptor::new(f))) - .collect(); - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of(read.iter().copied(), &colors)); - inputs -} /// Each color index a function reads is one input attachment with a `FramebufferFetch` fact, -/// standalone and under its pipeline's fetch state alike: ordered where the device has -/// rasterization-order color attachment access, and elsewhere ordered between draws alone and -/// noted `UnorderedFetchWithinDraw`, a raster order group on it (`fetch_ordered`) taking no -/// interlock there. Every compiled module passes L3. +/// ordered between draws alone and noted `UnorderedFetchWithinDraw` on every committed profile, a +/// raster order group on it (`fetch_ordered`) taking no interlock. Every compiled module passes +/// L3. #[test] -fn framebuffer_fetch_reads_an_input_attachment_ordered_where_the_device_orders_it() { +fn framebuffer_fetch_reads_an_input_attachment_ordered_between_draws() { let Some(bc) = fixture("fragment_fetch") else { return; }; - // (entry, colors read, the pipeline's attachment formats): `fetch_blend` reads three colors - // of distinct classes and writes the first two; the others read and write color 0. - let entries: [(&str, &[u32], &[PixelFormat]); 3] = [ - ( - "fetch_blend", - &[0, 1, 2], - &[ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA32Uint, - PixelFormat::RG16Float, - ], - ), - ("fetch_scalar", &[0], &[PixelFormat::R32Float]), - ("fetch_ordered", &[0], &[PixelFormat::RGBA16Float]), + // (entry, colors read): `fetch_blend` reads three colors of distinct classes and writes the + // first two; the others read and write color 0. + let entries: [(&str, &[u32]); 3] = [ + ("fetch_blend", &[0, 1, 2]), + ("fetch_scalar", &[0]), + ("fetch_ordered", &[0]), ]; - // [unordered, ordered] - let mut forms = [0usize; 2]; + let mut checked = 0; for (stem, strict) in committed_profiles().expect("profiles") { - let frag = strict.fields().fragment; - let ordered = frag.rasterization_order_color_access; - for (entry, colors, formats) in entries { - // A color input in a raster order group needs the interlock where rasterization-order - // access orders the read; where the read is unordered the group orders it alone. - if entry == "fetch_ordered" && !frag.pixel_interlock && ordered { - assert_eq!( - refusal(&bc, entry, &strict), - (Feature::RasterOrderGroups, pixel_interlock()), - "{stem}" - ); - continue; - } - forms[usize::from(ordered)] += 1; - for inputs in [LoweringInputs::new(), fetch_state(colors, formats)] { - let a = compile_with(&bc, entry, &strict, &inputs) - .unwrap_or_else(|e| panic!("{entry} on {stem}: {e}")); - link_and_validate(&a, &strict) - .unwrap_or_else(|e| panic!("{entry} on {stem}: L3: {e}")); - assert_eq!(attachments(&a), colors, "{entry} on {stem}"); - for &color in colors { - assert!( - a.facts.contains(&RuntimeFact::FramebufferFetch { color }), - "{entry} on {stem}: {:?}", - a.facts - ); - } - assert_eq!( - a.precision - .contains(&PrecisionNote::UnorderedFetchWithinDraw), - !ordered, + for (entry, colors) in entries { + let a = compile_with(&bc, entry, &strict, &LoweringInputs::new()) + .unwrap_or_else(|e| panic!("{entry} on {stem}: {e}")); + link_and_validate(&a, &strict).unwrap_or_else(|e| panic!("{entry} on {stem}: L3: {e}")); + assert_eq!(attachments(&a), colors, "{entry} on {stem}"); + for &color in colors { + assert!( + a.facts.contains(&RuntimeFact::FramebufferFetch { color }), "{entry} on {stem}: {:?}", - a.precision + a.facts ); } + assert!( + a.precision + .contains(&PrecisionNote::UnorderedFetchWithinDraw), + "{entry} on {stem}: {:?}", + a.precision + ); + checked += 1; } } - // The committed profiles cover each kind of device. - assert!(forms.iter().all(|&n| n > 0), "{forms:?}"); + assert!(checked > 0, "no committed profile"); } /// Whether module `words` holds a constant composite of 256 or more constituents: Metal's sRGB /// table (`lower::arith::srgb::declare`), which no other initializer of these fixtures reaches. @@ -528,9 +489,8 @@ pub(super) fn holds_srgb_table(words: &[u32]) -> bool { false } -/// On a device that reads a fetched color through an input attachment (both lavapipes), an -/// `RGBA8Unorm_sRGB` or `BGRA8Unorm_sRGB` color reads the device's own decode through its input -/// attachment: the render pipeline's fragment module is the one an `RGBA8Unorm` attachment's +/// On both lavapipes, an `RGBA8Unorm_sRGB` or `BGRA8Unorm_sRGB` color reads the device's own +/// decode through its input attachment: the render pipeline's fragment module is the one an `RGBA8Unorm` attachment's /// pipeline takes, word for word, holding no Metal sRGB table; the interface records the `float` /// colors the device decodes (`StageIo::decoded_fetches`), and the pipeline notes /// `PrecisionNote::SrgbTexelDecode` for the sRGB attachment alone. A fragment compiled alone links @@ -542,7 +502,7 @@ fn an_srgb_input_attachment_reads_the_devices_decode() { }; let mut checked = 0; for (stem, p) in committed_profiles().expect("profiles") { - if !p.fields().fragment.rasterization_order_color_access { + if !stem.contains("lavapipe") { continue; } let plain = compile_with(&bc, "fetch_blend", &p, &LoweringInputs::new()) @@ -645,7 +605,7 @@ fn a_fetched_extended_range_attachment_is_refused() { unwritten.write_mask = ColorWriteMask::NONE; vec![Some(fetched), Some(read), Some(unwritten)] }; - let state = |read: &[u32], colors: &[Option], p: &DeviceProfile| { + let state = |colors: &[Option], p: &DeviceProfile| { let mut inputs = LoweringInputs::new(); inputs.color_writes = crate::pipeline::color_writes::color_writes( 0..colors.len() as u32, @@ -655,7 +615,6 @@ fn a_fetched_extended_range_attachment_is_refused() { ); inputs.extended_range_colors = crate::pipeline::color_writes::extended_range_colors(colors, Default::default()); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of(read.iter().copied(), colors)); inputs }; let refused = |r: Result, Error>, @@ -683,14 +642,14 @@ fn a_fetched_extended_range_attachment_is_refused() { let mut checked = 0; for (stem, p) in committed_profiles().expect("profiles") { for pf in xr { - let r = compile_with(&blend, "exf_fetch_blend", &p, &state(&[0], &colors(pf), &p)); + let r = compile_with(&blend, "exf_fetch_blend", &p, &state(&colors(pf), &p)); refused(r, &format!("{stem}: {pf:?}")); checked += 1; } let mut both = colors(PixelFormat::RGB10A82PXR10SRGB); both[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Uint)); both[2] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGB10A82PXR10)); - let r = compile_with(&three, "exf_fetch_three", &p, &state(&[0, 1, 2], &both, &p)); + let r = compile_with(&three, "exf_fetch_three", &p, &state(&both, &p)); refused(r, &format!("{stem}: three")); } assert!(checked > 0, "no committed profile"); @@ -1105,8 +1064,8 @@ fn raster_order_groups_run_the_body_inside_the_interlock() { /// needs no interlock: Vulkan already orders a fragment's color writes and blending per sample in /// rasterization order, as Metal does. It compiles without an interlock mode or instruction on /// every committed profile, and on a device with neither interlock, and passes L3. (A group on a -/// color input still needs the interlock: -/// `framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one`.) +/// color input orders only the input attachment's read, between draws: +/// `framebuffer_fetch_reads_an_input_attachment_ordered_between_draws`.) #[test] fn a_group_of_color_outputs_alone_needs_no_interlock() { let Some(bc) = fixture("fragment_rog") else { @@ -1438,223 +1397,6 @@ fn a_varying_the_device_interpolates_records_the_device_interpolation_note() { } } -/// A fragment function blended into an `RG10Unorm_X12` attachment (premultiplied over, and a -/// blend of source alpha into the color channels) records its output's blend note on every -/// profile that orders fetch through rasterization-order input attachments, whatever the module's -/// math and however it computes the output: the shader blends it over the input attachment by the -/// device's arithmetic, where Metal's compiler -/// folds the blend into the function in forms of its own. A `half4` output records -/// `PrecisionNote::ExtendedRangeBlendSource` and a `float4` one -/// `PrecisionNote::ExtendedRangeFloatBlendSource`, never the other's: the fills loaded from a -/// buffer, `rt6_resolve_white`'s constant, a computed `half4`, a `float4` computed by whole-vector -/// arithmetic or with a lane moved alone, under fast math, without it (into the `_sRGB` form too) -/// and naming no math mode. Unblended, the constant output records none. -#[test] -fn a_blended_padded_output_records_its_blend_note() { - use crate::metal::BlendFactor; - let (Some(fills), Some(resolves)) = (fixture("rt6_samples"), fixture("rt6_resolves")) else { - return; - }; - let text = std::fs::read_to_string(engine_dir().join("rt6_samples.ll")).expect("text"); - assert_eq!(text.matches("air.compile.fast_math_enable").count(), 1); - let assemble = |text: &str, what: &str| match metal2vulkan_devtools::llvm_assemble_text(text) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {what}: {why}"), - }; - let disable = |text: &str| { - text.replace( - "air.compile.fast_math_enable", - "air.compile.fast_math_disable", - ) - }; - let Some(safe) = assemble(&disable(&text), "the safe fills") else { - return; - }; - // The module's options without its math mode. - let options = "!air.compile_options = !{!106, !107, !108}"; - assert_eq!(text.matches(options).count(), 1); - assert_eq!( - text.matches("!107 = !{!\"air.compile.fast_math_enable\"}") - .count(), - 1 - ); - let unnamed = text.replace(options, "!air.compile_options = !{!106, !108}"); - let Some(unnamed) = assemble(&unnamed, "the fills without a math mode") else { - return; - }; - let load = " ret <4 x half> %19\n"; - assert_eq!(text.matches(load).count(), 1); - let computed = text.replace( - load, - " %computed = fmul fast <4 x half> %19, \n ret <4 x half> %computed\n", - ); - let Some(safe_computed) = assemble(&disable(&computed), "the safe computed fill") else { - return; - }; - let Some(computed) = assemble(&computed, "the computed fill") else { - return; - }; - // The `float4` fill computed by whole-vector arithmetic (its load times ones), and computed - // with its alpha the load's (a lane moved alone). - let float_load = " ret <4 x float> %19\n"; - assert_eq!(text.matches(float_load).count(), 1); - let ones = ""; - let float_computed = text.replace( - float_load, - &format!(" %cf = fmul fast <4 x float> %19, {ones}\n ret <4 x float> %cf\n"), - ); - let Some(float_computed) = assemble(&float_computed, "the computed float4 fill") else { - return; - }; - let float_mixed = text.replace( - float_load, - &format!( - " %cf = fmul fast <4 x float> %19, {ones}\n %mixed = shufflevector <4 x float> %cf, \ - <4 x float> %19, <4 x i32> \n ret <4 x float> %mixed\n" - ), - ); - let Some(float_mixed) = assemble(&float_mixed, "the lane-mixed float4 fill") else { - return; - }; - let colors_of = |format: PixelFormat, blended: bool| { - let mut c = ColorAttachmentDescriptor::new(format); - c.blending_enabled = blended; - c.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - c.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - vec![Some(c)] - }; - let colors = |blended: bool| colors_of(PixelFormat::RG10UnormX12, blended); - let state = |colors: &[Option], p: &DeviceProfile| { - let mut inputs = LoweringInputs::new(); - inputs.color_writes = crate::pipeline::color_writes::color_writes( - 0..colors.len() as u32, - colors, - (false, Default::default()), - p, - ); - inputs.extended_range_colors = - crate::pipeline::color_writes::extended_range_colors(colors, Default::default()); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0u32], colors)); - inputs - }; - let notes = [ - PrecisionNote::ExtendedRangeBlendSource, - PrecisionNote::ExtendedRangeFloatBlendSource, - ]; - let (half, float) = (Some(notes[0]), Some(notes[1])); - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::inputs_order(&p) { - continue; - } - let blended = state(&colors(true), &p); - // The one of the two notes the function records, if it records one. - let recorded = |a: &crate::library::FunctionArtifact| { - let found: Vec = notes - .into_iter() - .filter(|n| a.precision.contains(n)) - .collect(); - assert!(found.len() <= 1, "{stem}: {found:?}"); - found.first().copied() - }; - let noted = |bitcode: &[u8], name: &str, inputs: &LoweringInputs| { - compile_with(bitcode, name, &p, inputs) - .map(|a| recorded(&a)) - .map_err(|e| format!("{stem}: {name}: {e}")) - }; - let float_fill = match compile_with(&fills, "rt6_fill_rgba32float", &p, &blended) { - Ok(a) => recorded(&a), - // A device without the raw format's color attachment refuses the blend whatever the - // source. - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => continue, - Err(e) => panic!("{stem}: {e}"), - }; - checked += 1; - assert_eq!(float_fill, float, "{stem}: a loaded float4 under fast math"); - assert_eq!( - noted(&fills, "rt6_fill_rgba16float", &blended), - Ok(half), - "{stem}: a loaded half4 under fast math" - ); - assert_eq!( - noted(&resolves, "rt6_resolve_white", &blended), - Ok(float), - "{stem}: a constant float4" - ); - assert_eq!( - noted(&computed, "rt6_fill_rgba16float", &blended), - Ok(half), - "{stem}: a computed half4 under fast math" - ); - let fill = "rt6_fill_rgba32float"; - assert_eq!( - noted(&float_computed, fill, &blended), - Ok(float), - "{stem}: a computed float4 under fast math" - ); - let keyed = { - let mut c = ColorAttachmentDescriptor::new(PixelFormat::RG10UnormX12); - c.blending_enabled = true; - c.destination_rgb_blend_factor = BlendFactor::SourceAlpha; - c.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - state(&[Some(c)], &p) - }; - assert_eq!( - noted(&fills, fill, &keyed), - Ok(float), - "{stem}: keyed, loaded" - ); - assert_eq!( - noted(&float_computed, fill, &keyed), - Ok(float), - "{stem}: keyed, computed" - ); - assert_eq!( - noted(&float_mixed, fill, &blended), - Ok(float), - "{stem}: a float4 with a lane moved alone" - ); - let unblended = state(&colors(false), &p); - assert_eq!( - noted(&resolves, "rt6_resolve_white", &unblended), - Ok(None), - "{stem}: a constant float4 unblended" - ); - let srgb = state(&colors_of(PixelFormat::RG10UnormX12SRGB, true), &p); - for (name, note) in [ - ("rt6_fill_rgba32float", float), - ("rt6_fill_rgba16float", half), - ] { - assert_eq!( - noted(&safe, name, &blended), - Ok(note), - "{stem}: {name} without fast math" - ); - assert_eq!( - noted(&unnamed, name, &blended), - Ok(note), - "{stem}: {name} of no math mode" - ); - assert_eq!( - noted(&safe, name, &srgb), - Ok(note), - "{stem}: {name} without fast math into the sRGB form" - ); - } - assert_eq!( - noted(&safe_computed, "rt6_fill_rgba16float", &blended), - Ok(half), - "{stem}: a computed half4 without fast math" - ); - } - assert!(checked > 0, "no profile blended over the input attachment"); -} - /// The opcodes of every instruction in `words`, and the capabilities it declares. fn opcodes_and_capabilities(words: &[u32]) -> (Vec, Vec) { let (mut ops, mut caps) = (Vec::new(), Vec::new()); diff --git a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs index 68f1c4c89..4a871d9fd 100644 --- a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs +++ b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs @@ -208,9 +208,8 @@ fn an_unobserved_gated_off_input_compiles() { assert!(off.facts.is_empty(), "{stem}: {:?}", off.facts); validate(&off, &p); } - // Defined (and so declared), the color input is read: a framebuffer fetch. Neither profile - // has rasterization-order access, so each reads color 0's input attachment, ordered between - // draws alone and noted. + // Defined (and so declared), the color input is read: a framebuffer fetch. Each profile reads + // color 0's input attachment, ordered between draws alone and noted. for stem in ["runtime-floor", "moltenvk-m3"] { let r = compile_bitcode( &bc, diff --git a/crates/metal2vulkan/src/tests/engine_padded_blends.rs b/crates/metal2vulkan/src/tests/engine_padded_blends.rs index 3019aa46b..ea1b2e221 100644 --- a/crates/metal2vulkan/src/tests/engine_padded_blends.rs +++ b/crates/metal2vulkan/src/tests/engine_padded_blends.rs @@ -3,16 +3,11 @@ //! `probes/padded_and_bfloat_blends.m` of the conformance crate), and which no device blends: the //! attachment holds the raw words in an unsigned integer format. //! -//! The function computes the blend over an ordered read of the attachment -//! (`lower::fragment::input_blend`); a blend into one of Apple's extended-range forms, which -//! Metal's tile holds as `half`, is refused (`blended_pipelines`). On every committed profile that -//! orders fetch through rasterization-order input attachments, `rt6_samples`' `half4` and `float4` -//! fills under premultiplied source-over and one plus one, `xrb_dual`'s second-source blends, -//! whose index-1 output the blend reads, and a write mask of some of the channels make the whole -//! pipeline with color 0's blend computed over its input attachment -//! (`RuntimeFact::ExtendedRangeInputBlend`), the attachment a color attachment of the raw format -//! with no Vulkan blend. On one that does not order it the pipeline is refused naming the ordering. -//! No GPU is used. +//! The function's own blend over an ordered read of the attachment is not built, so on every +//! committed profile `rt6_samples`' `half4` and `float4` fills under premultiplied source-over and +//! one plus one, `xrb_dual`'s second-source blends and a write mask of some of the channels are +//! refused `NotImplemented(FramebufferFetch)`; a blend into one of Apple's extended-range forms, +//! which Metal's tile holds as `half`, is refused (`blended_pipelines`). No GPU is used. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. @@ -20,19 +15,17 @@ use std::path::Path; use crate::budget::Budget; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{DescriptorError, Error, MetalAnswer, Needs}; +use crate::error::{DescriptorError, Error, Feature, MetalAnswer, Needs}; use crate::library::Library; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; +use crate::metal::{BlendFactor, ColorWriteMask, PixelFormat}; use crate::pipeline::artifact::{PrecisionNote, RenderPipeline}; use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, }; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs, LoweringInputs}; +use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::testing::{compile_with, engine_dir, fragment_inputs, AssembleError}; use crate::spirv::testing::committed_profiles; -use crate::vk; /// Fixture `stem` assembled; `None` (skipped) without `llvm-as`. fn assembled(stem: &str) -> Option> { @@ -64,68 +57,55 @@ const BFLOAT: [PixelFormat; 3] = [ PixelFormat::RGBA16Bfloat, ]; -/// Premultiplied source-over: one over one minus the source alpha, added, for color and alpha. -const OVER: BlendEquation = BlendEquation { - source_rgb: BlendFactor::One, - destination_rgb: BlendFactor::OneMinusSourceAlpha, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::OneMinusSourceAlpha, - alpha_operation: BlendOperation::Add, -}; +/// A blend's source and destination factors for color and for alpha, each added. +type Factors = [BlendFactor; 4]; -/// One plus one, added, for color and alpha. -const ADD: BlendEquation = BlendEquation { - source_rgb: BlendFactor::One, - destination_rgb: BlendFactor::One, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::One, - alpha_operation: BlendOperation::Add, -}; +/// Premultiplied source-over: one over one minus the source alpha, for color and alpha. +const OVER: Factors = [ + BlendFactor::One, + BlendFactor::OneMinusSourceAlpha, + BlendFactor::One, + BlendFactor::OneMinusSourceAlpha, +]; + +/// One plus one, for color and alpha. +const ADD: Factors = [BlendFactor::One; 4]; /// The second source's blend: its color and one minus it, its alpha and one minus it. -const SECOND: BlendEquation = BlendEquation { - source_rgb: BlendFactor::Source1Color, - destination_rgb: BlendFactor::OneMinusSource1Color, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::Source1Alpha, - destination_alpha: BlendFactor::OneMinusSource1Alpha, - alpha_operation: BlendOperation::Add, -}; +const SECOND: Factors = [ + BlendFactor::Source1Color, + BlendFactor::OneMinusSource1Color, + BlendFactor::Source1Alpha, + BlendFactor::OneMinusSource1Alpha, +]; -/// Color 0 of `pf` blended by `eq` under write mask `mask`. +/// Color 0 of `pf` blended by `factors`, added, under write mask `mask`. fn attachment( pf: PixelFormat, - eq: BlendEquation, + factors: Factors, mask: ColorWriteMask, ) -> ColorAttachmentDescriptor { let mut c = ColorAttachmentDescriptor::new(pf); c.blending_enabled = true; - c.source_rgb_blend_factor = eq.source_rgb; - c.destination_rgb_blend_factor = eq.destination_rgb; - c.rgb_blend_operation = eq.rgb_operation; - c.source_alpha_blend_factor = eq.source_alpha; - c.destination_alpha_blend_factor = eq.destination_alpha; - c.alpha_blend_operation = eq.alpha_operation; + c.source_rgb_blend_factor = factors[0]; + c.destination_rgb_blend_factor = factors[1]; + c.source_alpha_blend_factor = factors[2]; + c.destination_alpha_blend_factor = factors[3]; c.write_mask = mask; - assert_eq!(BlendEquation::of(&c), Some(eq)); c } -/// The lowering inputs of a fragment function writing color 0 of `pf` blended by `eq` under +/// The lowering inputs of a fragment function writing color 0 of `pf` blended by `factors` under /// `mask` on `p`, as the render pipeline compile sets them. fn state( p: &DeviceProfile, pf: PixelFormat, - eq: BlendEquation, + factors: Factors, mask: ColorWriteMask, ) -> LoweringInputs { let mut r = RenderLinkInputs::new(); - r.color_attachments[0] = Some(attachment(pf, eq, mask)); - let mut inputs = fragment_inputs(&r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); - inputs + r.color_attachments[0] = Some(attachment(pf, factors, mask)); + fragment_inputs(&r, p) } /// The device of committed profile `stem`. @@ -163,28 +143,15 @@ fn pipeline( dev.compile_render_pipeline(&d, &Budget::standard()) } -/// The blends a pipeline computes over color 0's input attachment, with the channels each keeps. -fn input_blends(a: &RenderPipeline) -> Vec<(BlendEquation, vk::ColorComponentFlags)> { - a.dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::ExtendedRangeInputBlend { - color: 0, - blend, - kept, - } => Some((blend, kept)), - _ => None, - }) - .collect() -} - +/// A blend into a padded attachment is refused `NotImplemented(FramebufferFetch)` on every +/// committed profile, under every blend and mask here (the module docs). #[test] -fn a_blend_into_a_padded_attachment_is_computed_in_the_shader() { +fn a_blend_into_a_padded_attachment_is_refused_on_every_device() { let (Some(fills), Some(dual)) = (assembled("rt6_samples"), assembled("xrb_dual")) else { return; }; // Each function, its vertex function, and the blends it takes. - let entries: [(&[u8], &str, &str, &[BlendEquation]); 4] = [ + let entries: [(&[u8], &str, &str, &[Factors]); 4] = [ ( &fills, "rt6_fill_vertex", @@ -204,41 +171,31 @@ fn a_blend_into_a_padded_attachment_is_computed_in_the_shader() { let rgb = ColorWriteMask::RED .union(ColorWriteMask::GREEN) .union(ColorWriteMask::BLUE); - let (mut inputs, mut unordered) = (0, 0); - for (stem, p) in committed_profiles().expect("profiles") { + let mut refused = 0; + for (stem, _) in committed_profiles().expect("profiles") { let dev = device(&stem); for pf in PADDED { for &(bc, vertex, fragment, blends) in &entries { - for &eq in blends { + for &factors in blends { for mask in [ColorWriteMask::ALL, ColorWriteMask::RED, rgb] { - let what = format!("{stem} {pf:?} {fragment} {eq:?} {mask:?}"); - let made = pipeline(&dev, (bc, vertex, fragment), attachment(pf, eq, mask)); - if crate::lower::fragment::inputs_order(&p) { - let a = made.unwrap_or_else(|e| panic!("{what}: {e}")); - let blends = input_blends(&a); - assert_eq!(blends.len(), 1, "{what}: {blends:?}"); - assert_eq!(blends[0].0, eq, "{what}"); - let state0 = a.graphics.color_attachments[0].expect("color 0"); - let form = crate::metal::format::ExtendedRange::of(pf).expect("padded"); - assert_eq!(state0.format, form.raw_format(), "{what}"); - assert!(state0.blend.is_none(), "{what}"); - inputs += 1; - } else { - let e = made.map(|_| ()).expect_err(&what); - let named = crate::lower::fragment::fetch::unordered_extended_fetch(); - assert!( - matches!(&e, Error::Unsupported(u) if u.needs == named.needs), - "{what}: {e}" - ); - unordered += 1; + let what = format!("{stem} {pf:?} {fragment} {factors:?} {mask:?}"); + let made = + pipeline(&dev, (bc, vertex, fragment), attachment(pf, factors, mask)); + match made.map(drop) { + Err(Error::Unsupported(u)) => assert_eq!( + (u.feature, u.needs), + (Feature::FramebufferFetch, Needs::NotImplemented), + "{what}" + ), + other => panic!("{what}: {other:?}"), } + refused += 1; } } } } } - assert!(inputs > 0, "no profile blends over the input attachment"); - assert!(unordered > 0, "no profile leaves fetch unordered"); + assert!(refused > 0); } /// A blend into a bfloat attachment (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) is Metal's @@ -298,15 +255,12 @@ fn a_blend_into_a_bfloat_attachment_is_metals_pipeline_error() { /// `half`, a `float4` input's too (the M3 Max under macOS 27.0.1, `probes/padded_fetch.m` of the /// conformance crate). `pfx_fetch`'s `float4` and `half4` reads of color 0 (mask none), stored into /// an `RGBA32Float` color 1, make the whole pipeline on every committed profile, color 0 an -/// attachment of the raw format read as an unsigned input attachment: ordered where the profile -/// orders fetch through rasterization-order input attachments, elsewhere ordered between draws -/// alone, its fragment stage noting `UnorderedFetchWithinDraw`. The negative control: a fetch of a +/// attachment of the raw format read as an unsigned input attachment, ordered between draws alone, +/// its fragment stage noting `UnorderedFetchWithinDraw`. The negative control: a fetch of a /// bfloat attachment, whose read Metal answers unmeasured, stays `NotImplemented(Format)` on every /// profile. #[test] fn a_fetch_of_a_padded_attachment_reads_the_tile_value_of_its_codes() { - use crate::error::Feature; - use crate::lower::fragment::inputs_order; use crate::metal::format::ExtendedRange; let Some(bc) = assembled("pfx_fetch") else { return; @@ -329,15 +283,14 @@ fn a_fetch_of_a_padded_attachment_reads_the_tile_value_of_its_codes() { d.color_attachments[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); dev.compile_render_pipeline(&d, &Budget::standard()) }; - let (mut inputs, mut unordered, mut bfloat) = (0, 0, 0); - for (stem, p) in committed_profiles().expect("profiles") { + let (mut read_padded, mut bfloat) = (0, 0); + for (stem, _) in committed_profiles().expect("profiles") { let dev = device(&stem); for fragment in ["pfx_fetch_read", "pfx_fetch_read_half"] { for pf in PADDED { let what = format!("{stem} {pf:?} {fragment}"); let raw = ExtendedRange::of(pf).expect("padded").raw_format(); - // Rasterization-order input attachments, or input attachments ordered between - // draws alone, noted. + // Input attachments ordered between draws alone, noted. let a = made(&dev, fragment, pf).unwrap_or_else(|e| panic!("{what}: {e}")); let state0 = a.graphics.color_attachments[0].expect("color 0"); assert_eq!(state0.format, raw, "{what}"); @@ -351,11 +304,8 @@ fn a_fetch_of_a_padded_attachment_reads_the_tile_value_of_its_codes() { let noted = (a.stages.iter()).any(|s| { (s.precision_notes).contains(&PrecisionNote::UnorderedFetchWithinDraw) }); - assert_eq!(noted, !inputs_order(&p), "{what}"); - match inputs_order(&p) { - true => inputs += 1, - false => unordered += 1, - } + assert!(noted, "{what}"); + read_padded += 1; } for pf in BFLOAT { let what = format!("{stem} {pf:?} {fragment}"); @@ -371,7 +321,6 @@ fn a_fetch_of_a_padded_attachment_reads_the_tile_value_of_its_codes() { } } } - assert!(inputs > 0, "no profile reads through the input attachment"); - assert!(unordered > 0, "no profile leaves fetch unordered"); + assert!(read_padded > 0, "no padded fetch was made"); assert!(bfloat > 0, "no bfloat fetch was refused"); } diff --git a/crates/metal2vulkan/src/tests/engine_private_render_state.rs b/crates/metal2vulkan/src/tests/engine_private_render_state.rs index 265342c26..589d18910 100644 --- a/crates/metal2vulkan/src/tests/engine_private_render_state.rs +++ b/crates/metal2vulkan/src/tests/engine_private_render_state.rs @@ -15,9 +15,8 @@ //! field; `Always` keeps the pipeline. //! - The logic operation leaves the normalized, sRGB and integer attachments unblended (unwritten //! under a no-op), so copy and no-op draw on every device; the others take Vulkan's `logicOp` -//! where the device has it (lavapipe), are computed by the fragment function where it does not -//! and the device orders fetch (lavapipe with the feature off), and are refused where neither -//! holds (MoltenVK) and where Metal's operation is not built. +//! where the device has it (lavapipe), and are refused where it does not (MoltenVK, lavapipe +//! with the feature off) and where Metal's operation is not built. //! - The sample coverage is Metal's masks by the window pixel's place in its quad, ANDed with the //! sample mask: alike at every place the Vulkan mask, else applied by the fragment function from //! its pixel. @@ -627,15 +626,12 @@ fn a_shared_exponent_attachment_notes_the_words_metal_s_pass_normalizes() { /// another operation (xor, raw 10, and raw 26, whose low four bits are xor's) is Vulkan's /// `logicOp` on lavapipe, its requirements naming the feature, its fragment stage noting /// `PrecisionNote::NativeLogicOperation` exactly where the operation reaches a written channel of -/// `RGB10A2Unorm` or `BGR10A2Unorm` (whose codes Metal widens). On lavapipe without it the -/// fragment function computes it over the attachment's input attachment, noting the device's -/// conversion of the codes (`RGB10A2Unorm`'s on 16-bit codes, as Metal's); `B5G6R5Unorm`, whose -/// operation is not a per-channel rule, is refused there, and on a device that lacks it and does -/// not order fetch (MoltenVK) the operation is refused naming Vulkan's operation and -/// rasterization-order access. A float attachment keeps its blend under copy and no-op and takes -/// Vulkan's operation unblended, or keeps its blend beside the function's; an sRGB attachment -/// under xor, a blended float attachment under Vulkan's xor and a format whose operation Metal -/// was not measured with are refused `NotImplemented`. +/// `RGB10A2Unorm` or `BGR10A2Unorm` (whose codes Metal widens). A device without it (MoltenVK, +/// lavapipe with the feature off) refuses the operation naming Vulkan's operation, and draws copy +/// as every device does. A float attachment keeps its blend under copy and no-op and takes +/// Vulkan's operation unblended; an sRGB attachment under xor, a blended float attachment under +/// Vulkan's xor and a format whose operation Metal was not measured with are refused +/// `NotImplemented`. #[test] fn the_logic_operation_draws_as_metal_s_or_is_refused() { use crate::device::requirements::VkFeature; @@ -666,15 +662,10 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { ))) .at_attachment(Attachment::Color(index)) }; - let unordered = || { - use crate::device::requirements::VkFeature as V; - use crate::error::Capability as C; - Error::Unsupported(Unsupported::needs_any_of( + let lacking = || { + Error::Unsupported(Unsupported::needs( Feature::PrivateRenderState(PrivateRenderField::LogicOperation), - vec![ - vec![C::Feature(V::LogicOp)], - vec![C::Feature(V::RasterizationOrderColorAttachmentAccess)], - ], + Capability::Feature(VkFeature::LogicOp), )) }; for stem in STEMS { @@ -721,20 +712,19 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { matches!(pf, PixelFormat::RGB10A2Unorm | PixelFormat::RGBA8Snorm); assert_eq!(native_logic(&p), differs, "{stem} {pf:?} xor"); } - // MoltenVK lacks Vulkan's operation and does not order fetch. - (false, Err(e)) => assert_eq!(e, unordered(), "{stem} {pf:?} xor"), + // MoltenVK lacks Vulkan's operation. + (false, Err(e)) => assert_eq!(e, lacking(), "{stem} {pf:?} xor"), (_, other) => panic!("{stem} {pf:?} xor: {other:?}"), } } } - // Where Vulkan's operation is not Metal's, on either device; the function's own leaves a - // blended float attachment to the device's blend. + // Where Vulkan's operation is not Metal's, on the device that has it. for (pf, blended) in [ (PixelFormat::RGBA8UnormSRGB, false), (PixelFormat::RGBA16Float, true), (PixelFormat::RG11B10Float, false), ] { - let want = if has { not_built(0) } else { unordered() }; + let want = if has { not_built(0) } else { lacking() }; match dev.compile_render_pipeline(&with(pf, blended, Some(10)), &Budget::standard()) { Err(e) => assert_eq!(e, want, "{stem} {pf:?}"), other => panic!("{stem} {pf:?} xor: {:?}", other.map(|_| ())), @@ -789,59 +779,17 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { unwritten.color_attachments[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGB10A2Unorm)); assert!(!noted(&unwritten, "RGB10A2Unorm unwritten beside xor")); - // lavapipe without `logicOp` orders fetch through rasterization-order input attachments: the - // function computes the operation over each served attachment's input attachment, which the - // device's write mask then keeps channels of; without either ordered form it is refused naming - // the three features. - let inputs = device_without("lavapipe", &["logicOp"]); - for pf in [ - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA8Snorm, - PixelFormat::RGB10A2Unorm, - PixelFormat::R16Unorm, - PixelFormat::RGBA16Float, - ] { - let what = format!("lavapipe without logicOp {pf:?}"); - let p = compile(&inputs, &with(pf, false, Some(10)), &what); - let operated = pf != PixelFormat::RGBA16Float; - shader_operated(&p, operated, &what); - assert!(!native_logic(&p), "{what}"); - let read = p - .graphics - .input_attachments - .iter() - .any(|i| i.color_index == 0); - assert_eq!(read, operated, "{what}"); - } - // A packed 16-bit format's operation is not a per-channel rule: refused at the attachment. - let packed = with(PixelFormat::B5G6R5Unorm, false, Some(10)); - match inputs.compile_render_pipeline(&packed, &Budget::standard()) { - Err(e) => assert_eq!(e, not_built(0), "lavapipe without logicOp B5G6R5Unorm"), - Ok(_) => panic!("lavapipe without logicOp B5G6R5Unorm xor compiled"), - } - let unordered = device_without( - "lavapipe", - &["logicOp", "rasterizationOrderColorAttachmentAccess"], - ); - let wanted = Error::Unsupported(Unsupported::needs_any_of( - Feature::PrivateRenderState(PrivateRenderField::LogicOperation), - vec![ - vec![Capability::Feature(VkFeature::LogicOp)], - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess, - )], - ], - )); + // Without `logicOp` the operation is refused naming it; copy needs no operation there. + let without = device_without("lavapipe", &["logicOp"]); let d = with(PixelFormat::RGBA8Unorm, false, Some(10)); - match unordered.compile_render_pipeline(&d, &Budget::standard()) { - Err(e) => assert_eq!(e, wanted), - Ok(_) => panic!("xor compiled without an ordered fetch"), + match without.compile_render_pipeline(&d, &Budget::standard()) { + Err(e) => assert_eq!(e, lacking(), "lavapipe without logicOp"), + Ok(_) => panic!("xor compiled without logicOp"), } - // Copy needs no operation there either. compile( - &unordered, + &without, &with(PixelFormat::RGBA8Unorm, false, Some(2)), - "unordered copy", + "copy without logicOp", ); } @@ -860,33 +808,6 @@ fn device_without(stem: &str, features: &[&str]) -> Device { Device::from_queries(description, DevicePolicy::RESIDENT_TABLES).expect("device") } -/// Assert that pipeline `p` draws its logic operation in its fragment function: no Vulkan -/// operation or requirement of it; where `operated`, attachment 0 is unblended and the function -/// notes the device's conversion of its codes. -fn shader_operated(p: &RenderPipeline, operated: bool, what: &str) { - use crate::device::requirements::VkFeature; - use crate::pipeline::artifact::PrecisionNote; - assert_eq!(p.graphics.logic_op, None, "{what}"); - assert!( - !p.requirements.features.contains(&VkFeature::LogicOp), - "{what}" - ); - let fragment = p - .stages - .iter() - .find(|s| s.stage == crate::vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - if operated { - let noted = fragment - .precision_notes - .contains(&PrecisionNote::DeviceColorConversion); - assert!(noted, "{what}"); - // Attachment 0 is a color attachment of the subpass over an input attachment. - let a = p.graphics.color_attachments[0]; - assert!(a.is_none_or(|a| a.blend.is_none()), "{what} blends"); - } -} - /// Whether pipeline `p`'s fragment stage records Vulkan's operation on a 10-bit or signed /// normalized format's own codes (`PrecisionNote::NativeLogicOperation`). fn native_logic(p: &RenderPipeline) -> bool { diff --git a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs index ce1c7dfbf..75141076d 100644 --- a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs +++ b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs @@ -11,11 +11,10 @@ //! output of copies of it (`StageIo::rotated_factors`, an output of index 1 the function's //! last shuffle fills) through Vulkan's `SRC1` factors where the device blends dual-source and //! the function writes no more attachments than its dual-source limit, else names the feature -//! or the limit; one no Vulkan factor gives the function computes over the texel where the -//! device orders framebuffer fetch (over the input attachment, `RotatedInputBlend`), noting the -//! device's conversion, and a device that does not order it refuses naming the ordering; alpha -//! to coverage over the image is refused -//! `NotImplemented(Format)` at the attachment; +//! or the limit; one no Vulkan factor gives is refused on every device +//! (`NotImplemented(FramebufferFetch)`: the function's own blend over an ordered read of the +//! texel is not built); alpha to coverage over the image is refused `NotImplemented(Format)` at +//! the attachment; //! - a blend not exact by construction records `PrecisionNote::RotatedBlendRounding`. //! //! No GPU is used. `llvm-as` assembles the fixture; a missing tool skips visibly. @@ -286,11 +285,8 @@ fn argb8_attachments_take_the_output_mask_and_blend_rotated() { Err(e) => panic!("{stem}: {c:?} beside color 2: {e}"), } } - // Blends no Vulkan factor gives on the image: the function computes Metal's 8-bit unorm - // blend over the texel where the device orders framebuffer fetch, over the attachment's - // input attachment (`RotatedInputBlend`, no Vulkan blend there), and a device that does - // not order it names the ordering. - let inputs = crate::lower::fragment::inputs_order(dev.profile()); + // Blends no Vulkan factor gives on the image: the function's own blend over an ordered read + // of the texel is not built, refused on every device. for c in [ blended(F::DestinationAlpha, F::Zero, O::Add, O::Add), blended(F::BlendColor, F::Zero, O::Add, O::Add), @@ -299,34 +295,15 @@ fn argb8_attachments_take_the_output_mask_and_blend_rotated() { ] { let d = descriptor(&bc, c, true); match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(p) if inputs => { - let state = p.graphics.color_attachments[0].expect("color 0"); - assert_eq!(state.blend, None, "{stem}: {c:?}"); - assert_eq!(state.format, vk::Format::R8G8B8A8_UNORM, "{stem}"); - let fact = p.dependencies.iter().any(|d| { - matches!( - d.fact, - crate::pipeline::RuntimeFact::RotatedInputBlend { color: 0, .. } - ) - }); - assert!(fact, "{stem}: {c:?}"); - assert!(notes(&p, PrecisionNote::DeviceColorConversion), "{stem}"); - } - Ok(_) => panic!("{stem}: {c:?}: made on a device that orders no fetch"), - Err(Error::Unsupported(u)) if !inputs => { - assert_eq!(u.feature, Feature::FramebufferFetch, "{stem}: {c:?}"); + Err(Error::Unsupported(u)) => { assert_eq!( - u.needs, - Needs::AnyOf(vec![vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess - )]]), + (u.feature, &u.needs), + (Feature::FramebufferFetch, &Needs::NotImplemented), "{stem}: {c:?}" ); let at = u.location.as_ref().and_then(|l| l.attachment()); assert_eq!(at, Some(Attachment::Color(0)), "{stem}: {c:?}"); } - // A device that orders fetch but lacks what the form needs names it. - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => {} other => panic!("{stem}: {c:?}: {:?}", other.map(|_| ())), } } diff --git a/crates/metal2vulkan/src/tests/engine_word_attachments.rs b/crates/metal2vulkan/src/tests/engine_word_attachments.rs index 19e1c73d2..9eafb7366 100644 --- a/crates/metal2vulkan/src/tests/engine_word_attachments.rs +++ b/crates/metal2vulkan/src/tests/engine_word_attachments.rs @@ -9,17 +9,12 @@ //! attachment takes `R16_UINT`, a write of its one component under a full mask and of none under //! an empty one, no blend, and both modules pass L3. //! - Where the device renders the format (lavapipe), the attachment takes the format itself. -//! - A mask of some of the format's channels, or a blend, on the 5080, which does not order -//! fetch: the whole render pipeline is the device's lack of the format. +//! - A mask of some of the format's channels, or a blend, on the 5080: the whole render pipeline +//! is the device's lack of the format. //! - The 8-bit sRGB formats the 5080 renders through their words (`R8Unorm_sRGB`, //! `RG8Unorm_sRGB`) write the word too; a partial mask or a blend of one is the device's lack of -//! the format there. -//! - On lavapipe, which renders neither `R8_SRGB` nor `R8G8_SRGB` and orders fetch through -//! rasterization-order input attachments, an `RG8Unorm_sRGB` attachment written under a mask of -//! some of its channels keeps its `R16_UINT` color attachment, written whole, and its fragment -//! merges the word into its input attachment's (`lower::fragment`'s `word_input`), stating the -//! channels it keeps (`RuntimeFact::WordInputMerge`); a fragment compiled under another mask, or -//! under a full one, does not link there (`NeedsInput(FramebufferFetch)`). +//! the format there, and on lavapipe, which renders neither `R8_SRGB` nor `R8G8_SRGB`: the +//! merge of the word into the texel over an ordered read of the attachment is not built. //! - `RGB9E5Float`, which the 5080 samples and does not render, takes a `float` output's word //! through `R32_UINT`; a `half` output is `NotImplemented(Format)`, and a partial mask or a //! blend the device's lack of the format. @@ -255,28 +250,37 @@ fn masked_and_blended_word_attachments_are_the_devices_lack_of_the_format() { } /// An 8-bit sRGB word attachment written under a mask of some of its channels, or blended, is the -/// device's lack of the format on the 5080's device, which does not order fetch (Metal's sRGB -/// blend over the word is not built anywhere). +/// device's lack of the format on the 5080's device and on lavapipe's, which render neither +/// format (the merge over the word and Metal's sRGB blend over it are not built). #[test] -fn srgb_word_attachments_neither_merge_nor_blend_without_an_ordered_fetch() { +fn srgb_word_attachments_neither_merge_nor_blend() { let Some(bc) = fixture() else { return; }; - let dev = device("nvidia-rtx5080-laptop"); let library = Library::from_air(&bc).expect("library"); let function = |name: &str| { StageSource::Function(FunctionDescriptor::new( library.function(name).expect("function"), )) }; - for entry in ENTRIES { + for (stem, entry) in ["nvidia-rtx5080-laptop", "lavapipe"] + .into_iter() + .flat_map(|s| ENTRIES.map(|e| (s, e))) + { + let dev = device(stem); + assert!(WordAttachment::of(PixelFormat::RG8UnormSRGB, dev.profile()).is_some()); for (pf, mask, blended) in [ (PixelFormat::RG8UnormSRGB, ColorWriteMask::RED, false), (PixelFormat::RG8UnormSRGB, ColorWriteMask::GREEN, false), + ( + PixelFormat::RG8UnormSRGB, + ColorWriteMask::GREEN | ColorWriteMask::ALPHA, + false, + ), (PixelFormat::RG8UnormSRGB, ColorWriteMask::ALL, true), (PixelFormat::R8UnormSRGB, ColorWriteMask::ALL, true), ] { - let what = format!("{entry} {pf:?} {mask:?} blended {blended}"); + let what = format!("{stem} {entry} {pf:?} {mask:?} blended {blended}"); let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); d.fragment = Some(function(entry)); d.color_attachments[0] = pipeline_of(pf, mask, blended).color_attachments[0]; @@ -289,99 +293,6 @@ fn srgb_word_attachments_neither_merge_nor_blend_without_an_ordered_fetch() { } } -/// On lavapipe's device an `RG8Unorm_sRGB` attachment written under a mask of some of its channels -/// keeps its color attachment of `R16_UINT`, written whole and unblended, and reads its input -/// attachment as `uint`s; its fragment, compiled under the pipeline's fetch state, states the merge -/// of the channels the mask leaves out and passes L3. Under a full mask the pipeline reads no input -/// attachment. A fragment compiled under another partial mask, or under the full one, does not -/// link into a pipeline of a partial mask (the module docs). -#[test] -fn srgb_word_attachments_merge_over_input_attachments() { - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::lower_inputs::FramebufferFetchInputs; - use crate::pipeline::sym::SampledType; - let Some(bc) = fixture() else { - return; - }; - let dev = device("lavapipe"); - let pf = PixelFormat::RG8UnormSRGB; - assert!(WordAttachment::of(pf, dev.profile()).is_some()); - let library = Library::from_air(&bc).expect("library"); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - library.function(name).expect("function"), - )) - }; - let p = dev.profile(); - let v = compile(&bc, "rt6_fill_vertex", p).expect("vertex"); - // The fragment compiled for pipeline `r`, as the pipeline compile hands it the fetch state. - let fragment = |entry: &str, r: &RenderLinkInputs| { - let mut inputs = fragment_inputs(r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); - compile_with(&bc, entry, p, &inputs).expect("fragment") - }; - for entry in ENTRIES { - for (mask, kept) in [ - (ColorWriteMask::RED, vk::ColorComponentFlags::G), - (ColorWriteMask::GREEN, vk::ColorComponentFlags::R), - ( - ColorWriteMask::GREEN | ColorWriteMask::ALPHA, - vk::ColorComponentFlags::R, - ), - (ColorWriteMask::ALL, vk::ColorComponentFlags::empty()), - ] { - let what = format!("{entry} {mask:?}"); - let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); - d.fragment = Some(function(entry)); - d.color_attachments[0] = pipeline_of(pf, mask, false).color_attachments[0]; - let pipe = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = pipe.graphics.color_attachments[0].expect("a color attachment"); - assert_eq!( - (a.format, a.write_mask, a.blend), - (vk::Format::R16_UINT, vk::ColorComponentFlags::R, None), - "{what}" - ); - let inputs: Vec<_> = (pipe.graphics.input_attachments.iter()) - .map(|u| (u.color_index, u.input_attachment_index, u.format_class)) - .collect(); - let merged = !kept.is_empty(); - let want = match merged { - true => vec![(0, 0, SampledType::Uint)], - false => Vec::new(), - }; - assert_eq!(inputs, want, "{what}"); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, p) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - let r = pipeline_of(pf, mask, false); - let f = fragment(entry, &r); - let stated: Vec<_> = (f.facts.iter()) - .filter(|f| matches!(f, RuntimeFact::WordInputMerge { .. })) - .copied() - .collect(); - let want = match merged { - true => vec![RuntimeFact::WordInputMerge { color: 0, kept }], - false => Vec::new(), - }; - assert_eq!(stated, want, "{what}"); - link(&[&v, &f], &render(&r), p).unwrap_or_else(|e| panic!("{what}: link: {e}")); - } - // Compiled under another mask, or the full one, for a pipeline of a partial mask. - let red = pipeline_of(pf, ColorWriteMask::RED, false); - for other in [ColorWriteMask::GREEN, ColorWriteMask::ALL] { - let f = fragment(entry, &pipeline_of(pf, other, false)); - let e = link(&[&v, &f], &render(&red), p).expect_err(entry); - assert!( - matches!(e, Error::NeedsInput(RuntimeInput::FramebufferFetch)), - "{entry} compiled under {other:?}: {e}" - ); - } - } -} - /// An `RGB9E5Float` attachment on the 5080's device renders a `float` output through an /// `R32_UINT` view and no conversion note; a `half` output is `NotImplemented(Format)`, and /// a mask of some of its channels, or a blend, the device's lack of the format (the module docs). diff --git a/crates/metal2vulkan/src/tests/golden_hashes.rs b/crates/metal2vulkan/src/tests/golden_hashes.rs index 1440c3eb9..6d05d4bf0 100644 --- a/crates/metal2vulkan/src/tests/golden_hashes.rs +++ b/crates/metal2vulkan/src/tests/golden_hashes.rs @@ -57,10 +57,10 @@ use crate::pipeline::testing::{ engine_dir, fixtures_dir, link_standalone, llvm_assemble, metal_assemble, AssembleError, }; use crate::pipeline::{ - ColorAttachmentDescriptor, ComputePipelineDescriptor, FramebufferFetchInputs, - FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, SlotClass, SlotRef, Stage, - StageSource, StorageImageClass, TileRenderPipelineDescriptor, VertexAttributeDescriptor, - VertexBufferLayoutDescriptor, VertexDescriptor, + ColorAttachmentDescriptor, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, + RenderPipelineDescriptor, SlotClass, SlotRef, Stage, StageSource, StorageImageClass, + TileRenderPipelineDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, + VertexDescriptor, }; use crate::Budget; @@ -124,11 +124,9 @@ enum Subject { vertex: &'static str, fragment: &'static str, }, - /// Fragment `entry` compiled under the framebuffer-fetch state of a pipeline whose color - /// attachments are `formats` (by index, each read), linked alone: the state a write the - /// function computes over its input attachment needs on a device that orders fetch through - /// rasterization-order input attachments. Above one sample, compiled under `multisampled`: the - /// per-sample form. + /// Fragment `entry`, which reads the color attachments of a pipeline whose attachments are + /// `formats` (by index; they name the row, and the function compiles alike for any), linked + /// alone. Above one sample, compiled under `multisampled`: the per-sample form. Fetch { entry: &'static str, formats: &'static [PixelFormat], @@ -580,18 +578,8 @@ fn compiled(lib: &Library, subject: &Subject, dev: &Device) -> Result { - let colors: Vec> = formats - .iter() - .map(|&f| Some(ColorAttachmentDescriptor::new(f))) - .collect(); + Subject::Fetch { entry, samples, .. } => { let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = - Some(FramebufferFetchInputs::of(0..formats.len() as u32, &colors)); inputs.multisampled = *samples > 1; let f = FunctionDescriptor::new(lib.function(entry)?); let c = dev.compile_function(&f, &inputs, &b)?; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index cdeb70574..f06d9f235 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -897,7 +897,6 @@ enum metal2vulkan::error::DescriptorError #[derive(Clone, Debug, PartialEq, Eq)] 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 -enum metal2vulkan::error::ExtendedRangeBlend #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ExtendedRangeBlend enum metal2vulkan::error::Feature #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum Feature enum metal2vulkan::error::GenericPointer #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum GenericPointer enum metal2vulkan::error::InputErrorKind #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum InputErrorKind @@ -2583,7 +2582,6 @@ field metal2vulkan::device::FragmentCaps.independent_blend pub independent_blend field metal2vulkan::device::FragmentCaps.output_layer pub output_layer: bool field metal2vulkan::device::FragmentCaps.output_viewport_index pub output_viewport_index: bool field metal2vulkan::device::FragmentCaps.pixel_interlock pub pixel_interlock: bool -field metal2vulkan::device::FragmentCaps.rasterization_order_color_access pub rasterization_order_color_access: bool field metal2vulkan::device::FragmentCaps.sample_rate_shading pub sample_rate_shading: bool field metal2vulkan::device::FragmentCaps.stencil_export pub stencil_export: bool field metal2vulkan::device::FragmentCaps.terminate_invocation pub terminate_invocation: bool @@ -2849,12 +2847,6 @@ field metal2vulkan::pipeline::AccessSet.write pub write: bool field metal2vulkan::pipeline::AliasView.image_format pub image_format: vk::Format field metal2vulkan::pipeline::AmplificationDraws.layered pub layered: bool field metal2vulkan::pipeline::AmplificationDraws.viewports pub viewports: bool -field metal2vulkan::pipeline::BlendEquation.alpha_operation pub alpha_operation: metal::BlendOperation -field metal2vulkan::pipeline::BlendEquation.destination_alpha pub destination_alpha: metal::BlendFactor -field metal2vulkan::pipeline::BlendEquation.destination_rgb pub destination_rgb: metal::BlendFactor -field metal2vulkan::pipeline::BlendEquation.rgb_operation pub rgb_operation: metal::BlendOperation -field metal2vulkan::pipeline::BlendEquation.source_alpha pub source_alpha: metal::BlendFactor -field metal2vulkan::pipeline::BlendEquation.source_rgb pub source_rgb: metal::BlendFactor field metal2vulkan::pipeline::BlendState.alpha_op pub alpha_op: vk::BlendOp field metal2vulkan::pipeline::BlendState.color_op pub color_op: vk::BlendOp field metal2vulkan::pipeline::BlendState.dst_alpha pub dst_alpha: vk::BlendFactor @@ -2934,12 +2926,6 @@ field metal2vulkan::pipeline::EntryPlan.strategies pub strategies: BTreeMap -field metal2vulkan::pipeline::FetchedAttachment.pixel_format pub pixel_format: metal::PixelFormat -field metal2vulkan::pipeline::FetchedAttachment.replaces pub replaces: bool -field metal2vulkan::pipeline::FetchedAttachment.write_mask pub write_mask: metal::ColorWriteMask -field metal2vulkan::pipeline::FramebufferFetchInputs.attachments pub attachments: BTreeMap> field metal2vulkan::pipeline::FunctionDescriptor.constants pub constants: FunctionConstantValues field metal2vulkan::pipeline::FunctionDescriptor.function pub function: Function field metal2vulkan::pipeline::FunctionDescriptor.libraries pub libraries: DynamicLibraries @@ -2957,7 +2943,6 @@ field metal2vulkan::pipeline::GraphicsState.input_attachments pub input_attachme field metal2vulkan::pipeline::GraphicsState.line_band pub line_band: Option field metal2vulkan::pipeline::GraphicsState.logic_op pub logic_op: Option field metal2vulkan::pipeline::GraphicsState.max_vertex_amplification_count pub max_vertex_amplification_count: u32 -field metal2vulkan::pipeline::GraphicsState.rasterization_order_attachment_access pub rasterization_order_attachment_access: bool field metal2vulkan::pipeline::GraphicsState.rasterization_samples pub rasterization_samples: vk::SampleCountFlags field metal2vulkan::pipeline::GraphicsState.rasterizer_discard pub rasterizer_discard: bool field metal2vulkan::pipeline::GraphicsState.reads_barycentric_coord pub reads_barycentric_coord: bool @@ -3015,11 +3000,9 @@ field metal2vulkan::pipeline::LoweringInputs.extended_range pub extended_range: field metal2vulkan::pipeline::LoweringInputs.extended_range_colors pub extended_range_colors: BTreeMap field metal2vulkan::pipeline::LoweringInputs.flat_grid pub flat_grid: bool field metal2vulkan::pipeline::LoweringInputs.folded_groups pub folded_groups: bool -field metal2vulkan::pipeline::LoweringInputs.framebuffer_fetch pub framebuffer_fetch: Option field metal2vulkan::pipeline::LoweringInputs.indirect_range pub indirect_range: bool field metal2vulkan::pipeline::LoweringInputs.instanced_attributes pub instanced_attributes: BTreeSet field metal2vulkan::pipeline::LoweringInputs.kept_imageblock_bytes pub kept_imageblock_bytes: Option -field metal2vulkan::pipeline::LoweringInputs.logic_operation pub logic_operation: Option field metal2vulkan::pipeline::LoweringInputs.max_call_stack_depth pub max_call_stack_depth: Option field metal2vulkan::pipeline::LoweringInputs.merged_draws pub merged_draws: bool field metal2vulkan::pipeline::LoweringInputs.multisampled pub multisampled: bool @@ -3434,7 +3417,6 @@ fn metal2vulkan::metal::format::byte_format pub fn byte_format(pf: PixelFormat) fn metal2vulkan::metal::format::color_record pub fn color_record(formats: &[Option]) -> Option>> fn metal2vulkan::metal::format::copies_only pub fn copies_only(pf: PixelFormat) -> bool fn metal2vulkan::metal::format::direct_format pub fn direct_format(pf: PixelFormat) -> Option -fn metal2vulkan::metal::format::extended_range_blend pub fn extended_range_blend(pf: PixelFormat, profile: &DeviceProfile) -> Result<(), Unsupported> fn metal2vulkan::metal::format::footprint pub fn footprint(pf: PixelFormat) -> Option fn metal2vulkan::metal::format::image_type pub fn image_type(ty: TextureType) -> Option<(vk::ImageType, vk::ImageCreateFlags)> fn metal2vulkan::metal::format::image_view_type pub fn image_view_type(ty: TextureType) -> Option @@ -7247,7 +7229,6 @@ method metal2vulkan::metal::sampler::SamplerWord::of pub fn of(desc: &SamplerDes method metal2vulkan::pipeline::AliasView::new pub fn new(image_format: vk::Format) -> AliasView method metal2vulkan::pipeline::AmplificationDraws::new pub fn new(layered: bool, viewports: bool) -> AmplificationDraws method metal2vulkan::pipeline::BandPrimitive::patch_control_points pub fn patch_control_points(self) -> u32 -method metal2vulkan::pipeline::BlendEquation::of pub fn of(c: &crate::pipeline::descriptor::ColorAttachmentDescriptor) -> Option method metal2vulkan::pipeline::BlendState::reads_second_output pub fn reads_second_output(&self) -> bool method metal2vulkan::pipeline::BufferForm::uniform_view pub fn uniform_view(self) -> bool method metal2vulkan::pipeline::ColorAttachmentDescriptor::new pub fn new(pixel_format: metal::PixelFormat) -> ColorAttachmentDescriptor @@ -7277,7 +7258,6 @@ method metal2vulkan::pipeline::DynamicLibraries::with_preloaded pub fn with_prel method metal2vulkan::pipeline::EntryDescriptor::new pub fn new(bitcode: &'a [u8], entry: EntryRef<'a>) -> EntryDescriptor<'a> method metal2vulkan::pipeline::ExtendedRangeColor::new pub fn new(form: metal::format::ExtendedRange, blended: bool) -> ExtendedRangeColor method metal2vulkan::pipeline::ExtendedRangeColor::with_rounding pub fn with_rounding(self, rounding: metal::TextureWriteRoundingMode) -> ExtendedRangeColor -method metal2vulkan::pipeline::FramebufferFetchInputs::of pub fn of(read: impl IntoIterator, colors: &[Option]) -> FramebufferFetchInputs method metal2vulkan::pipeline::FunctionDescriptor::needs_specialization pub fn needs_specialization(&self, budget: &Budget, entries: &StageEntries) -> Result method metal2vulkan::pipeline::FunctionDescriptor::new pub fn new(function: Function) -> FunctionDescriptor method metal2vulkan::pipeline::FunctionDescriptor::with_libraries pub fn with_libraries(mut self, libraries: DynamicLibraries) -> FunctionDescriptor @@ -7869,7 +7849,6 @@ struct metal2vulkan::pipeline::AccessSet #[cfg_attr(feature = "serde", derive(se struct metal2vulkan::pipeline::AirUserKey #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct AirUserKey(pub Box<[u8]>) struct metal2vulkan::pipeline::AliasView #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct AliasView struct metal2vulkan::pipeline::AmplificationDraws #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct AmplificationDraws -struct metal2vulkan::pipeline::BlendEquation #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct BlendEquation struct metal2vulkan::pipeline::BlendState #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BlendState struct metal2vulkan::pipeline::BufferSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferSlot struct metal2vulkan::pipeline::ColorAttachmentDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ColorAttachmentDescriptor @@ -7887,8 +7866,6 @@ struct metal2vulkan::pipeline::EntryDescriptor #[derive(Clone, Debug)] #[non_exh struct metal2vulkan::pipeline::EntryPlan #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct EntryPlan struct metal2vulkan::pipeline::ExecutionCounts #[derive(Clone, Copy, Debug)] pub struct ExecutionCounts struct metal2vulkan::pipeline::ExtendedRangeColor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ExtendedRangeColor -struct metal2vulkan::pipeline::FetchedAttachment #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct FetchedAttachment -struct metal2vulkan::pipeline::FramebufferFetchInputs #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct FramebufferFetchInputs struct metal2vulkan::pipeline::FunctionDescriptor #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FunctionDescriptor struct metal2vulkan::pipeline::FunctionHandle #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FunctionHandle(u32) struct metal2vulkan::pipeline::GraphicsState #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct GraphicsState @@ -9399,8 +9376,6 @@ variant metal2vulkan-runtime::PrecisionNote::DeviceSignedZeroInfNan DeviceSigned variant metal2vulkan-runtime::PrecisionNote::DeviceTexelConversion DeviceTexelConversion variant metal2vulkan-runtime::PrecisionNote::DeviceTranscendentals DeviceTranscendentals variant metal2vulkan-runtime::PrecisionNote::DeviceVertexConversion DeviceVertexConversion -variant metal2vulkan-runtime::PrecisionNote::ExtendedRangeBlendSource ExtendedRangeBlendSource -variant metal2vulkan-runtime::PrecisionNote::ExtendedRangeFloatBlendSource ExtendedRangeFloatBlendSource variant metal2vulkan-runtime::PrecisionNote::ExtrapolatedInterpolation ExtrapolatedInterpolation variant metal2vulkan-runtime::PrecisionNote::F16FmaDoubleRounding F16FmaDoubleRounding variant metal2vulkan-runtime::PrecisionNote::F16IntConvDoubleRounding F16IntConvDoubleRounding @@ -10506,8 +10481,6 @@ variant metal2vulkan::error::ErrorClass::InvalidRequest InvalidRequest variant metal2vulkan::error::ErrorClass::LimitExceeded LimitExceeded variant metal2vulkan::error::ErrorClass::Malformed Malformed variant metal2vulkan::error::ErrorClass::Unsupported Unsupported -variant metal2vulkan::error::ExtendedRangeBlend::DualSource DualSource -variant metal2vulkan::error::ExtendedRangeBlend::Output Output variant metal2vulkan::error::Feature::AddressSpace AddressSpace(u32) variant metal2vulkan::error::Feature::AgxUnmodeled AgxUnmodeled variant metal2vulkan::error::Feature::AlphaToOne AlphaToOne @@ -10536,7 +10509,6 @@ variant metal2vulkan::error::Feature::DivergentImplicitLod DivergentImplicitLod variant metal2vulkan::error::Feature::DivergentInterpolation DivergentInterpolation variant metal2vulkan::error::Feature::DualSourceBlending DualSourceBlending variant metal2vulkan::error::Feature::DynamicCall DynamicCall -variant metal2vulkan::error::Feature::ExtendedRangeBlend ExtendedRangeBlend(ExtendedRangeBlend) variant metal2vulkan::error::Feature::Float64Arithmetic Float64Arithmetic variant metal2vulkan::error::Feature::Format Format variant metal2vulkan::error::Feature::FramebufferFetch FramebufferFetch @@ -10713,9 +10685,7 @@ variant metal2vulkan::error::RuntimeInput::ColorWrites ColorWrites variant metal2vulkan::error::RuntimeInput::DepthCompareClamp DepthCompareClamp variant metal2vulkan::error::RuntimeInput::DynamicLibrary DynamicLibrary { install_name: DiagName } variant metal2vulkan::error::RuntimeInput::DynamicSymbol DynamicSymbol { symbol: DiagName } -variant metal2vulkan::error::RuntimeInput::FramebufferFetch FramebufferFetch variant metal2vulkan::error::RuntimeInput::LinkedFunction LinkedFunction { symbol: DiagName } -variant metal2vulkan::error::RuntimeInput::LogicOperation LogicOperation variant metal2vulkan::error::RuntimeInput::Multisampled Multisampled variant metal2vulkan::error::RuntimeInput::ObjectPayload ObjectPayload variant metal2vulkan::error::RuntimeInput::PrimitiveId PrimitiveId @@ -10928,8 +10898,6 @@ variant metal2vulkan::pipeline::PrecisionNote::DeviceSignedZeroInfNan DeviceSign variant metal2vulkan::pipeline::PrecisionNote::DeviceTexelConversion DeviceTexelConversion variant metal2vulkan::pipeline::PrecisionNote::DeviceTranscendentals DeviceTranscendentals variant metal2vulkan::pipeline::PrecisionNote::DeviceVertexConversion DeviceVertexConversion -variant metal2vulkan::pipeline::PrecisionNote::ExtendedRangeBlendSource ExtendedRangeBlendSource -variant metal2vulkan::pipeline::PrecisionNote::ExtendedRangeFloatBlendSource ExtendedRangeFloatBlendSource variant metal2vulkan::pipeline::PrecisionNote::ExtrapolatedInterpolation ExtrapolatedInterpolation variant metal2vulkan::pipeline::PrecisionNote::F16FmaDoubleRounding F16FmaDoubleRounding variant metal2vulkan::pipeline::PrecisionNote::F16IntConvDoubleRounding F16IntConvDoubleRounding @@ -11068,7 +11036,6 @@ variant metal2vulkan::pipeline::RuntimeFact::DispatchGrid DispatchGrid variant metal2vulkan::pipeline::RuntimeFact::DroppedColor DroppedColor { color: u32 } variant metal2vulkan::pipeline::RuntimeFact::EmulatedSimdgroups EmulatedSimdgroups variant metal2vulkan::pipeline::RuntimeFact::ExecutionStatus ExecutionStatus -variant metal2vulkan::pipeline::RuntimeFact::ExtendedRangeInputBlend ExtendedRangeInputBlend { color: u32, blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::FlatGrid FlatGrid variant metal2vulkan::pipeline::RuntimeFact::FoldedGroups FoldedGroups variant metal2vulkan::pipeline::RuntimeFact::FramebufferFetch FramebufferFetch { color: u32 } @@ -11101,7 +11068,6 @@ variant metal2vulkan::pipeline::RuntimeFact::RegionViewports RegionViewports variant metal2vulkan::pipeline::RuntimeFact::RenderTargetArrayLength RenderTargetArrayLength { layer_dropped: bool } variant metal2vulkan::pipeline::RuntimeFact::ReplayBindings ReplayBindings variant metal2vulkan::pipeline::RuntimeFact::ResourcePresence ResourcePresence { slot: SlotRef } -variant metal2vulkan::pipeline::RuntimeFact::RotatedInputBlend RotatedInputBlend { color: u32, blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::RotatedWeights RotatedWeights variant metal2vulkan::pipeline::RuntimeFact::RowLockstep RowLockstep variant metal2vulkan::pipeline::RuntimeFact::SampleCount SampleCount @@ -11136,7 +11102,6 @@ variant metal2vulkan::pipeline::RuntimeFact::UnitAxes UnitAxes { axes: u8, relie variant metal2vulkan::pipeline::RuntimeFact::VertexBufferStride VertexBufferStride { layout: u32 } variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32 } variant metal2vulkan::pipeline::RuntimeFact::ViewportCount ViewportCount -variant metal2vulkan::pipeline::RuntimeFact::WordInputMerge WordInputMerge { color: u32, kept: crate::vk::ColorComponentFlags } variant metal2vulkan::pipeline::RuntimeFact::YCbCrInPlace YCbCrInPlace { slot: SlotRef, samplers: u32, device: bool } variant metal2vulkan::pipeline::RuntimeFact::ZeroedColor ZeroedColor { color: u32, format: crate::metal::PixelFormat } variant metal2vulkan::pipeline::SampledType::Float Float diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 3482bd9f4..49d10e619 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -194,7 +194,6 @@ surface! { enum Feature N; enum LowerFamily N; enum PrivateRenderField N; - enum ExtendedRangeBlend N; enum RuntimeInput N; enum DescriptorError N; enum MetalAnswer N; @@ -392,12 +391,9 @@ surface! { struct PushConstantRange N; struct AliasView N; struct AmplificationDraws N; - struct BlendEquation N; enum ChannelWrite N; struct ExtendedRangeColor N; enum FactorLane N; - struct FetchedAttachment N; - struct FramebufferFetchInputs N; enum KernelVariant N; struct LoweringInputs N; struct StorageImageChoice N; @@ -766,7 +762,6 @@ surface! { fn writes_dropped; fn ycbcr_renders; fn ycbcr_pass_refused; - fn extended_range_blend; fn x_channel; fn bound_texel_format; fn integer_channels_word; diff --git a/docs/API.md b/docs/API.md index 9f74417ae..62babde47 100644 --- a/docs/API.md +++ b/docs/API.md @@ -849,12 +849,9 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: does not render (the RTX 5080: it renders neither `R8_SRGB` nor `R8G8_SRGB`, and holds the latter in its UNORM twin) renders through an `R8_UINT` or `R16_UINT` view of its texture the same way: the fragment function writes the bytes of the device's sRGB encode - (`DevicePackConversion`), a pass clears it to the bytes of Metal's clear, and a partial mask - merges the word over the attachment's input attachment on a device that orders fetch through - rasterization-order input attachments (lavapipe; `RuntimeFact::WordInputMerge`), and is refused - as the device lacking the format elsewhere. A blend of one - other than one and zero is refused as the device lacking the format; a color input of one is - `NotImplemented(Format)`. + (`DevicePackConversion`), and a pass clears it to the bytes of Metal's clear. A partial mask, and + a blend of one other than one and zero, are refused as the device lacking the format; a color + input of one is `NotImplemented(Format)`. - An `RGB9E5Float` attachment the device does not render (the RTX 5080) renders through an `R32_UINT` view of its texture: the fragment function writes Metal's word of a `float` output (each channel clamped to `[0, 65408]`, a NaN 0, the exponent of the largest, every mantissa @@ -874,13 +871,11 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: tile's finer values. A device whose word's format renders one sample at that count refuses the texture (the runtime's `Limit::TextureSamples`). - A fragment function that reads a color attachment (framebuffer fetch) reads it as an input - attachment, ordered by rasterization-order attachment access wherever the device has it. On a - device without it the input attachment has no rasterization-order access - (`GraphicsState::rasterization_order_attachment_access` false), and the consumer records a - barrier of the subpass's dependency on itself, by region, before each draw that reads input - attachments after an earlier draw of the subpass, or its load operations, wrote a color, and - before each draw that writes a color after an earlier one read them: a fetch reads what every earlier draw stored, Metal's - answer, but the overlapping fragments of one draw are not ordered, which the fragment stage + attachment without rasterization-order attachment access, on every device, and the consumer + records a barrier of the subpass's dependency on itself, by region, before each draw that reads + input attachments after an earlier draw of the subpass, or its load operations, wrote a color, + and before each draw that writes a color after an earlier one read them: a fetch reads what every + earlier draw stored, Metal's answer, but the overlapping fragments of one draw are not ordered, which the fragment stage records (`PrecisionNote::UnorderedFetchWithinDraw`; the runtime does all of this itself). Under the identity domains the read is the pushed texture of section 1 instead, at the fragment's own pixel, with the same note: the consumer reads the attachment's texture there and orders each @@ -892,10 +887,14 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: every device (`Unsupported{Format}` at the color attachment): Metal's tile holds such an attachment as `half` through the render pass and rounds it to the codes only at the store, so a read or a blend after an earlier draw's write sees that draw's `half`, which the - stored codes do not keep. An unblended write, under any write mask, is built. On a device - without rasterization-order access, a raster order group on a color input, or on a color output - of an attachment the function reads, orders that read alone there and takes no interlock; a group on anything else still - needs the pixel interlock (`Unsupported{RasterOrderGroups}`). A `[[stencil]]` output uses + stored codes do not keep. An unblended write, under any write mask, is built. A write the + function would compute over its own read of the attachment, where no Vulkan blend or write mask + gives Metal's, is not built (`Unsupported{FramebufferFetch}`, not implemented, on every device): + a padded extended-range attachment's blend, a write of some of the codes one word of an + extended-range attachment holds, and a blend no Vulkan state gives on an attachment held with + its channels rotated. A raster order group on a color input, or on a color output of an + attachment the function reads, orders that read alone and takes no interlock; a group on + anything else needs the pixel interlock (`Unsupported{RasterOrderGroups}`). A `[[stencil]]` output uses `VK_EXT_shader_stencil_export`; a device without it refuses the function (`Unsupported{StencilExport}` naming the extension). - `[[barycentric_coord]]` reads `BaryCoordKHR` or `BaryCoordNoPerspKHR`, whose vertex order is @@ -1993,8 +1992,7 @@ bound. measured. The sample may read another level or filter than Metal's near a boundary. - `metal2vulkan-degrade-unordered-fetch-within-draw` (precision). `PrecisionNote::UnorderedFetchWithinDraw`: A fragment function reads a color attachment - (framebuffer fetch) on a device without rasterization-order color attachment access (among - the committed profiles, every one but the lavapipe ones). It reads the attachment as an input + (framebuffer fetch), on every device. It reads the attachment as an input attachment, and the runtime records a barrier of the draws' subpass's dependency on itself, by region, before each draw that reads input attachments after an earlier draw of its render pass instance, or its load operations, wrote a @@ -2280,27 +2278,6 @@ bound. some channel written (`StageIo::half_blend_colors`, which the pipeline's stage reads), or its module names no math mode (under fast math the pipeline's stage records `PrecisionNote::HalfOutputFastMathBlend` instead). -- `metal2vulkan-degrade-extended-range-blend-source` (precision). - `PrecisionNote::ExtendedRangeBlendSource`: A fragment function's `half` color output (a scalar or - vector of AIR's `half`) is blended into a padded 10-bit attachment (`R10Unorm_X6`, - `RG10Unorm_X12`, their `_sRGB` twins, `RGB10A2Unorm_sRGB`), whose raw codes no device's blend - unit reads, so the function blends in the shader in the device's arithmetic: `S·Fs op D·Fd` in - `float`, in the blend equation's order, the source, second source and blend color unclamped, as - Metal takes them there (a blend into one of Apple's extended-range formats is refused, section - 4). The device's compiler may contract a - product into its sum and may regroup the blend: MoltenVK on the M3 Max and NVIDIA's driver on an - RTX 5080 compute a second source's blend `S·F + D·(1 - F)` as `D + F·(S - D)`. Metal's compiler - rounds each step to `half`, so a blended channel may store another code than Metal's: within two - codes on a linear format and within six on an sRGB twin near zero, where its transfer is - steepest, in the conformance suite's extended-range and padded blend cases; and where the - device's compiler regroups a padded format's blend, an infinite second source stores the end code - its sign picks where Metal's sum is NaN, stored as code 0. -- `metal2vulkan-degrade-extended-range-float-blend-source` (precision). - `PrecisionNote::ExtendedRangeFloatBlendSource`: `PrecisionNote::ExtendedRangeBlendSource` for a - `float` color output (a scalar or vector of AIR's `float`): blended into a padded 10-bit - attachment in the shader in the device's arithmetic, which the device's compiler - may contract and regroup, where Metal's compiler rounds the output and each step of the blend to - `half`; a blended channel within `ExtendedRangeBlendSource`'s bound of Metal's. - `metal2vulkan-degrade-anisotropic-filter` (precision). `PrecisionNote::AnisotropicFilter`: The module samples a texture through an anisotropic sampler with Metal's anisotropic filter emulated by the device's samples at explicit levels (`lower::sampler::anisotropic`), on a device without @@ -2509,8 +2486,8 @@ bound. `RGB10A2Unorm` stored green 938 where Metal's rule gives 937, and its xor of `0xe0` over an `RGBA8Snorm` channel's `0x80` stored `0x60` where Metal's gives `0x61`), by a distance the note does not bound: the result follows the codes' bits. The device's `logicOp` is its native form - there, and no other form is built for it; a device without `logicOp` computes Metal's rule in - the fragment function and records none. A signed channel the draw does not write (outside the + there, and no other form is built for it; a device without `logicOp` refuses the operation + (`Unsupported{PrivateRenderState(LogicOperation)}` naming `logicOp`). A signed channel the draw does not write (outside the write mask, or every channel under no-op) keeps its lowest code where any draw's unwritten texel does (`snorm-minimum-kept`). - `metal2vulkan-degrade-device-depth-bias` (precision). `PrecisionNote::DeviceDepthBias`: A draw diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 575db8a32..eb1b03bb8 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -26,7 +26,7 @@ Columns: | Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed | |---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 119 | 119 | 7 | 26 | 66 | 20 | 0 | +| Translator and front-end refusals | 118 | 118 | 6 | 26 | 66 | 20 | 0 | | Binder refusals at a device limit | 9 | 9 | 0 | 1 | 7 | 1 | 0 | | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | @@ -40,7 +40,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 48 | 71 | 0 | 0 | 0 | +| Translator and front-end refusals | 0 | 0 | 0 | 48 | 70 | 0 | 0 | 0 | | Binder refusals at a device limit | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 0 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | @@ -93,7 +93,7 @@ Columns: | `BufferRange` | A buffer window beyond the descriptor range limits | devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 6: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)`, `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)` (+2) | `app`: a buffer window past a device's descriptor range | | `Int64Arithmetic` | 64-bit integer arithmetic | devices without VkFeature::ShaderInt64 | `device` | 2: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`, `crates/metal2vulkan/src/lower/select.rs (selector_form)` | `rare`: 64-bit integers on a device without shaderInt64 | | `Float64Arithmetic` | 64-bit float arithmetic | devices without VkFeature::ShaderFloat64 | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` | `rare`: doubles (MSL has none outside Apple's own code) | -| `Format` | A pixel or vertex format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 64: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)` (+35) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) | +| `Format` | A pixel or vertex format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 57: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)` (+32) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) | | `DivergentImplicitLod` | Divergent implicit-LOD sampling or LOD query through a multi-candidate handle | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` | `app`: implicit-LOD sampling through a dynamically chosen texture | | `ImplicitLodOutsideFragment` | Implicit-LOD sampling outside fragment | every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`, `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)` (+1) | `rare`: implicit-LOD sampling outside fragment functions | | `MinLodClamp` | `min_lod_clamp` without `shaderResourceMinLod` | devices without VkFeature::ShaderResourceMinLod; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`, `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` | `rare`: min_lod_clamp on a device without shaderResourceMinLod | @@ -109,7 +109,7 @@ Columns: | `PixelSamplerCompare` | A constexpr sampler with pixel coordinates and a compare function, which Apple's compiler rejects ("invalid values combination in sampler... | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (lowered)` | `none`: Apple's compiler rejects it | | `TexelBuffer` | Texture buffers beyond the device's texel-buffer limits | devices without a format's usage; every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges, 2 sites)`, `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)` | `app`: texture buffers past a device's texel-buffer limits | | `RasterOrderGroups` | Raster order groups without fragment shader interlock | devices without VkFeature::FragmentShaderPixelInterlock; every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/fragment/rog.rs (mode, 2 sites)` | `rare`: raster order groups | -| `FramebufferFetch` | Framebuffer fetch that needs an ordered read the device lacks (rasterization-order attachment access), or in a shape not implemented | devices without VkFeature::RasterizationOrderColorAttachmentAccess; devices without VkFeature::SampleRateShading; every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (unorm8, 3 sites)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)` (+1) | `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) | +| `FramebufferFetch` | Framebuffer fetch in a shape not implemented (a write the function would compute over its own read of the attachment), or that needs a feature the... | devices without VkFeature::SampleRateShading; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/fragment/fetch.rs (computed_write_refused)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)` | `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... | devices without buffer device addresses (`addressed_needs`); every device (not implemented) | `ours` | 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 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 | @@ -166,8 +166,7 @@ Columns: | `Reflection` | Reflection of an argument whose answer Metal's has not been measured for (`reflection`) | every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`, `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)` (+6) | `rare`: reflection of argument kinds Metal's answer is unmeasured for | | `IndirectRenderState` | A `depth_stencil_state` a function reads from an argument buffer or takes as a parameter, the state of an indirect render command, which no record... | every device (not implemented) | `ours` | via a helper: 2: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`, `crates/metal2vulkan/src/lower/select.rs (param_family)` | `rare`: render state set by a kernel on an indirect command | | `GlobalBuiltinInFragment` | A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does not lower there | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: Metal 3.1 global built-ins in fragment functions | -| `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | devices without VkFeature::LogicOp; devices without VkFeature::RasterizationOrderColorAttachmentAccess; every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)` (+5) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | -| `ExtendedRangeBlend` | A blend the function computes in the shader, into an extended-range attachment (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB`... | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (refused)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_output)` | `system`: an extended-range (XR10) attachment blended from an output other than four half or float lanes; a 16-bit float attachment's storage-form blend of a second-source factor or a one-color-channel mask under fast math; the consumer's guests blend RGB10A8_2P_XR10 attachments | +| `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | devices without VkFeature::LogicOp; every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)` (+5) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | | `ProgramScopeBinding` | A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p [[buffer(n)]];` in Apple's `!air.global_bindings` list,... | every device (not implemented) | `ours` | via a helper: 2: `crates/metal2vulkan-air/src/abi/module.rs (decode)`, `crates/metal2vulkan/src/error/mod.rs (from)` | `app`: MSL 3.2 program-scope buffer bindings (macOS 15 and later) | | `GenericPointer` | A generic pointer (MSL 4.1's `addrspace(8)`) that canonicalization cannot make a pointer of one address space, by how it comes to hold a space... | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/generic.rs (refuse)`, `crates/metal2vulkan-air/src/canon/generic.rs (refused)` | `system`: MSL 4.1 generic pointers held in memory or of two spaces (macOS 27 and later) | | `SeqCstFence` | A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`, or a `seq_cst` barrier ordering device memory), whose... | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/lower/sync/barrier.rs (require_seq_cst)` | `rare`: a seq_cst fence in a vertex or fragment stage without its stores and atomics | @@ -426,7 +425,7 @@ Each refusal's sites, with the function that builds it. - `feature::BufferRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)`; `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs (select)`; `crates/metal2vulkan/src/lower/access/mod.rs (place_slots)` - `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs (selector_form)` - `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` -- `feature::Format`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (require_filter_features)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (finish)`; `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (blended_extended_range)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_blend, 5 sites)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs (rotated)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format, 5 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (ulong_format, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs (held_storage_choice, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs (vk_format, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as, 2 sites)`; `crates/metal2vulkan/src/pipeline/color_writes.rs (rotated_blend_in_shader)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (extended_write_mask, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state, 3 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (reads_alpha_to_coverage, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (textured_fetches)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (alpha_in_red_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` +- `feature::Format`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (require_filter_features)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (finish)`; `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format, 5 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (ulong_format, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs (held_storage_choice, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs (vk_format, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as, 2 sites)`; `crates/metal2vulkan/src/pipeline/color_writes.rs (rotated_blend_in_shader)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (extended_write_mask, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state, 3 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (reads_alpha_to_coverage, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (textured_fetches)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (alpha_in_red_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::DivergentImplicitLod`: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` - `feature::ImplicitLodOutsideFragment`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_min_level)` - `feature::MinLodClamp`: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` @@ -442,7 +441,7 @@ Each refusal's sites, with the function that builds it. - `feature::PixelSamplerCompare`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (lowered)` - `feature::TexelBuffer`: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)` - `feature::RasterOrderGroups`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/rog.rs (mode, 2 sites)` -- `feature::FramebufferFetch`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (unorm8, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (unordered_extended_fetch)` +- `feature::FramebufferFetch`: `crates/metal2vulkan/src/lower/fragment/fetch.rs (computed_write_refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)` - `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 (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)` @@ -500,7 +499,6 @@ Each refusal's sites, with the function that builds it. - `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`; `crates/metal2vulkan/src/lower/select.rs (param_family)` - `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::PrivateRenderState`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)`; `crates/metal2vulkan/src/lower/sampler/select.rs (clamps_reference)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (alpha_test_refused)`; `crates/metal2vulkan/src/lower/texture/mod.rs (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs (logic_operation)`; `crates/metal2vulkan/src/pipeline/private_state.rs (refused)` -- `feature::ExtendedRangeBlend`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_output)` - `feature::ProgramScopeBinding`: `crates/metal2vulkan-air/src/abi/module.rs (decode)`; `crates/metal2vulkan/src/error/mod.rs (from)` - `feature::GenericPointer`: `crates/metal2vulkan-air/src/canon/generic.rs (refuse)`; `crates/metal2vulkan-air/src/canon/generic.rs (refused)` - `feature::SeqCstFence`: `crates/metal2vulkan/src/lower/sync/barrier.rs (require_seq_cst)` diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index 8b5c6a761..5d21e22be 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -147,7 +147,6 @@ ratemap SampleOutOfRange rare a rate map quality sample outside [0, 1] among oth ratemap SampleCount rare a rate map axis of more distinct samples than measured (9 on one layer, 4 on two) budget Time none a translation past its deadline: a defect of ours to fix on any supported input (AGENTS.md: 20 seconds) feature PrivateRenderState none Apple-private pipeline fields of OpenGL on Metal (no public header) -feature ExtendedRangeBlend system an extended-range (XR10) attachment blended from an output other than four half or float lanes; a 16-bit float attachment's storage-form blend of a second-source factor or a one-color-channel mask under fast math; the consumer's guests blend RGB10A8_2P_XR10 attachments feature CommandPredication none Apple-private command predication on a device without buffer device addresses feature ProgramScopeBinding app MSL 3.2 program-scope buffer bindings (macOS 15 and later) feature GenericPointer system MSL 4.1 generic pointers held in memory or of two spaces (macOS 27 and later)