diff --git a/crates/metal2vulkan-conformance/probes/packed16_word_fetch.m b/crates/metal2vulkan-conformance/probes/packed16_word_fetch.m index 1ca5a5026..9d662edd2 100644 --- a/crates/metal2vulkan-conformance/probes/packed16_word_fetch.m +++ b/crates/metal2vulkan-conformance/probes/packed16_word_fetch.m @@ -83,11 +83,9 @@ // formats' blends are each other's through the measured field orders and share no word, so no // reading here is a constant and the orders are confirmed. // -// So the word view's refusal of a packed 16-bit color input was ours, and the fetch is built on -// the decode the blend already uses (`lower::fragment::fetch`, `stage_io::word_color::decode`). -// The tile answers are the storage form's near-equivalence, not the word view's: our form reads -// the attachment's memory for every format, so a packed 16-bit attachment the device renders -// directly reads the codes too. +// So Metal's fetch of a packed 16-bit attachment reads the value of its codes, by the decode the +// blend already uses (`stage_io::word_color::decode`): the product's refusal of such a color input +// (`NotImplemented(Format)`) is its own gap, not Metal's. // // clang -O2 -fobjc-arc -framework Metal -framework Foundation -o packed16_word_fetch \ // packed16_word_fetch.m diff --git a/crates/metal2vulkan-conformance/src/cases/pass_start_reads.rs b/crates/metal2vulkan-conformance/src/cases/pass_start_reads.rs index 9603d4bbc..45f70b484 100644 --- a/crates/metal2vulkan-conformance/src/cases/pass_start_reads.rs +++ b/crates/metal2vulkan-conformance/src/cases/pass_start_reads.rs @@ -736,8 +736,8 @@ impl Row { } /// What the runtime answers for a row that reads or samples with no barrier, where it takes - /// the read through a copy cleared to the clear or through a snapshot (the module docs): the - /// clear, as the barrier's rows answer. `None` for every other row. + /// the read through a copy cleared to the clear (the module docs): the clear, as the barrier's + /// rows answer. `None` for every other row. fn drawn(&self) -> Option> { match self.shape { Shape::Small { @@ -831,7 +831,7 @@ impl Case for PassStartRead { }) .collect(); // A read with no barrier may answer the clear where the runtime reads it through a copy - // cleared to it or a snapshot (the module docs). + // cleared to it (the module docs). if let Some(bytes) = self.row.drawn() { allowances.push(Allowance::new( format!("case/{}", texels_site(0)), diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index e1b8526cd..11cb0463e 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -165,8 +165,6 @@ pub enum Degradation { CoverageReadsRoundedAlpha, /// `metal2vulkan-degrade-device-alpha-coverage`. DeviceAlphaCoverage, - /// `metal2vulkan-degrade-unmeasured-fetch-blend`. - UnmeasuredFetchBlend, /// `metal2vulkan-degrade-unordered-fetch-within-draw`. UnorderedFetchWithinDraw, /// `metal2vulkan-degrade-native-logic-operation`. @@ -263,7 +261,6 @@ impl Degradation { Degradation::DeviceSampleLevel, Degradation::CoverageReadsRoundedAlpha, Degradation::DeviceAlphaCoverage, - Degradation::UnmeasuredFetchBlend, Degradation::UnorderedFetchWithinDraw, Degradation::NativeLogicOperation, Degradation::NativeFloat8, @@ -391,7 +388,6 @@ impl Degradation { "metal2vulkan-degrade-coverage-reads-rounded-alpha" } Degradation::DeviceAlphaCoverage => "metal2vulkan-degrade-device-alpha-coverage", - Degradation::UnmeasuredFetchBlend => "metal2vulkan-degrade-unmeasured-fetch-blend", Degradation::UnorderedFetchWithinDraw => { "metal2vulkan-degrade-unordered-fetch-within-draw" } @@ -483,7 +479,6 @@ impl Degradation { PrecisionNote::DeviceSampleLevel => Degradation::DeviceSampleLevel, PrecisionNote::CoverageReadsRoundedAlpha => Degradation::CoverageReadsRoundedAlpha, PrecisionNote::DeviceAlphaCoverage => Degradation::DeviceAlphaCoverage, - PrecisionNote::UnmeasuredFetchBlend => Degradation::UnmeasuredFetchBlend, PrecisionNote::UnorderedFetchWithinDraw => Degradation::UnorderedFetchWithinDraw, PrecisionNote::NativeLogicOperation => Degradation::NativeLogicOperation, PrecisionNote::NativeFloat8 => Degradation::NativeFloat8, diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 566524ebf..e3b6c728e 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2966,9 +2966,8 @@ or does not check is rebuilt from the generations' names, with young counted ful count bits), vertex amplification, a post-tessellation vertex function's per-instance factor step function or enabled factor scale (`Tessellation`; a descriptor's tessellation state with any other vertex function is ignored, as Metal ignores it), - stages the translator synthesizes beside the functions' and a tessellation's, an imageblock, a - fragment function's stencil output applied by the function itself (`ShaderStencil`, a form the - translator does not choose under the identity domains), a specialization other than the sample and + stages the translator synthesizes beside the functions' and a tessellation's, a specialization + other than the sample and amplification counts, dynamic state beyond Vulkan 1.3's (a vertex buffer layout whose stride is set per bind among it), a feature or extension device creation does not enable, and a function that reads what a draw does not supply (`DrawInput`: a function table, a table the binder builds, @@ -2976,9 +2975,19 @@ or does not check is rebuilt from the generations' names, with young counted ful an unnormalized constexpr sampler). Of the replay streams' contents that translate, every one reads only its slots' addresses, resource IDs and constexpr sampler indices. The `completionHandler:` forms are not built. +- A fragment function with imageblock data, an input or an output declared `[[imageblock_data]]`, + is refused at creation on every device, an `Error::Translation` naming `Imageblocks` + (`NotImplemented`): the translator has no form for it. The runtime has refused such a function on + every device all along, worded otherwise before: the only form the translator had bound a storage + image through a descriptor, which the identity domains the runtime compiles under hold none of. + The states-only plays of the 35 replay streams on lavapipe refuse none of their render or compute + states (jobs m3-max-63105 to 63108, and m3-max-63132 and m3-max-63156 for the two streams that + ran past those jobs' 300-second limit). - On a device that does not list `VK_EXT_shader_stencil_export`, a fragment function's `[[stencil]]` - output is refused at creation, an `Error::Translation` naming `StencilExport`: under the identity - domains the pixel interlock chooses no other form. Metal's feature set tables give stencil + output is refused at creation, an `Error::Translation` naming `StencilExport`: the translator has + no other form. The runtime has refused it on such a device all along, worded otherwise before: + the translator's other form bound a storage image through a descriptor, which the identity + domains hold none of. Metal's feature set tables give stencil feedback to the Apple5 family and later and to Metal 3 and Metal 4. NVIDIA's 615 and 620 drivers on the RTX 2080, RTX 3090 and RTX 5080 Laptop list none (`vulkaninfo`, jobs m3-max-48727, 48729 and 48731); RADV on the RX 7900 XTX, the 780Ms and the RX 550, ANV on the Iris Xe, lavapipe, diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index d761072ed..34bf6ba68 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1410,10 +1410,6 @@ pub enum RenderPipelineKind { /// Stages the translator synthesizes beside the functions' but a tessellation's: lines drawn as /// bands of triangles. SynthesizedStages, - /// A fragment function that reaches the render pass's imageblock. - Imageblock, - /// A fragment function's stencil output applied by the shader. - ShaderStencil, /// A specialization the draw would set, beside the sample and amplification counts. Specialization, /// Dynamic state the translator asks for beyond what Vulkan 1.3 leaves dynamic. diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 347d29739..a2b5b28dc 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -531,8 +531,6 @@ fn draws( // the `SpecKey::SampleCount` constant, which the state's creation sets to its // `rasterSampleCount`, the count of every pass it draws in (`renders_into`). RuntimeFact::SampleCount => {} - // A colour moved into a storage form, which the runtime never moves. - RuntimeFact::MovableStorageWrites { .. } => {} // The pulled attributes and their layouts' strides of a post-tessellation function and // of a state made for indirect command buffers, which pulls every attribute: the // content's own descriptor, whose projection link checked. A stride set per bind is @@ -815,10 +813,6 @@ fn unbuilt(pipeline: &RenderPipeline, enabled: &EnabledCaps) -> Option, - /// What the two stages need from the device: `sampleRateShading`; for the shadow, - /// multisampled storage images of an extended format; for the export, the extension. + /// What the two stages need from the device: `sampleRateShading`; for the export, the + /// extension. pub requirements: Requirements, } impl DepthStencilCopyModules { /// Descriptor set of the binding. pub const SET: u32 = 0; - /// The source: a sampled image ([`CopySource::Aspect`]) or a storage image - /// ([`CopySource::Shadow`]). + /// The source, a sampled image. pub const SOURCE_BINDING: u32 = 0; } -/// The crate-owned stencil split of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct StencilSplitModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device: multisampled storage images - /// (`shaderStorageImageMultisample`) of an extended format - /// (`shaderStorageImageExtendedFormats`). - pub requirements: Requirements, -} - -impl StencilSplitModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The source, a sampled image of the stencil aspect. - pub const SOURCE_BINDING: u32 = 0; - /// The destination, a multisampled `R8_UINT` storage image. - pub const DESTINATION_BINDING: u32 = 1; - /// Invocations of one workgroup along x, and along y. - pub const LOCAL_SIZE: u32 = 8; -} - /// The binding symbol of a draw's source ([`DepthStencilCopyModules::SOURCE_BINDING`]). const DRAW_SOURCE: ResourceSlot = ResourceSlot { stage: Stage::Fragment, kind: ResourceKind::Texture, index: 0, }; -/// The binding symbol of the split's source ([`StencilSplitModule::SOURCE_BINDING`]). -const SPLIT_SOURCE: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Texture, - index: 0, -}; -/// The binding symbol of the split's destination ([`StencilSplitModule::DESTINATION_BINDING`]). -const SPLIT_DESTINATION: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Texture, - index: 1, -}; - /// The unsigned 32-bit scalar type. pub(super) fn u32_ty(b: &mut ModuleBuilder) -> BResult { b.ty(Type::Int { @@ -255,38 +199,21 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult { let f32_ = b.ty(Type::Float { width: 32 })?; let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?; let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; - let source = match copy { - DepthStencilCopy::StencilPlane { source, .. } - | DepthStencilCopy::StencilExport { source } => source, - DepthStencilCopy::Depth - | DepthStencilCopy::DepthBits + let texel_type = match copy { + DepthStencilCopy::Depth | DepthStencilCopy::DepthBits | DepthStencilCopy::Depth16Bits => { + f32_ + } + DepthStencilCopy::StencilPlane { .. } + | DepthStencilCopy::StencilExport | DepthStencilCopy::StencilBits - | DepthStencilCopy::Depth16Code - | DepthStencilCopy::Depth16Bits => CopySource::Aspect, - }; - let source_ty = match (copy, source) { - ( - DepthStencilCopy::Depth | DepthStencilCopy::DepthBits | DepthStencilCopy::Depth16Bits, - _, - ) => multisampled_image( - &mut b, - f32_, - ImageUsage::Sampled, - crate::spv::ImageFormat::Unknown, - )?, - (_, CopySource::Aspect) => multisampled_image( - &mut b, - u32_, - ImageUsage::Sampled, - crate::spv::ImageFormat::Unknown, - )?, - (_, CopySource::Shadow) => multisampled_image( - &mut b, - u32_, - ImageUsage::Storage, - crate::spv::ImageFormat::R8ui, - )?, + | DepthStencilCopy::Depth16Code => u32_, }; + let source_ty = multisampled_image( + &mut b, + texel_type, + ImageUsage::Sampled, + crate::spv::ImageFormat::Unknown, + )?; let image = b.resource(DRAW_SOURCE, StorageClass::UniformConstant, source_ty)?; let coord = b.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)?; let sample = b.builtin(crate::spv::BuiltIn::SampleId, IoDir::Input, i32_)?; @@ -307,13 +234,10 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult { sample: Some(sample), ..ImageOperands::default() }; - let texel = match source { - CopySource::Aspect => f.fetch(image, pixel, &ops)?, - CopySource::Shadow => f.read(image, pixel, &ops, TexelMemory::default())?, - }; + let texel = f.fetch(image, pixel, &ops)?; let value = f.composite_extract(texel, &[0])?; match copy { - DepthStencilCopy::StencilPlane { bit, .. } => { + DepthStencilCopy::StencilPlane { bit } => { let mask = uint(&mut f, bit.mask())?; let set = f.binary(BinOp::BitwiseAnd, value, mask)?; let zero = uint(&mut f, 0)?; @@ -325,7 +249,7 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult { }); f.if_(&mut (), clear, kill, None)?; } - DepthStencilCopy::StencilExport { .. } => { + DepthStencilCopy::StencilExport => { let reference = f.convert(ConvOp::Bitcast, value, i32_)?; let output = f.module() @@ -382,7 +306,7 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult { let mut modes = vec![ExecMode::OriginUpperLeft]; match copy { DepthStencilCopy::StencilPlane { .. } => {} - DepthStencilCopy::StencilExport { .. } => modes.push(ExecMode::StencilRefReplacing), + DepthStencilCopy::StencilExport => modes.push(ExecMode::StencilRefReplacing), DepthStencilCopy::Depth | DepthStencilCopy::Depth16Code => { modes.push(ExecMode::DepthReplacing) } @@ -394,96 +318,11 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult { b.finalize() } -/// The stencil split as a typed module, before serialization: the module -/// [`stencil_split_module`] serializes. Its bindings are the symbols [`SPLIT_SOURCE`] and -/// [`SPLIT_DESTINATION`]. -pub fn split_typed_module() -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = u32_ty(&mut b)?; - let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let source_ty = multisampled_image( - &mut b, - u32_, - ImageUsage::Sampled, - crate::spv::ImageFormat::Unknown, - )?; - let destination_ty = multisampled_image( - &mut b, - u32_, - ImageUsage::Storage, - crate::spv::ImageFormat::R8ui, - )?; - let source = b.resource(SPLIT_SOURCE, StorageClass::UniformConstant, source_ty)?; - let destination = b.resource( - SPLIT_DESTINATION, - StorageClass::UniformConstant, - destination_ty, - )?; - let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let invocation = f.module().global_value(invocation)?; - let invocation = f.load(invocation, MemAccess::default())?; - let destination = f.module().global_value(destination)?; - let destination = f.load(destination, MemAccess::default())?; - let size = f.query(ImageQuery::Size, destination)?; - let samples = f.query(ImageQuery::Samples, destination)?; - let mut inside = None; - for axis in 0..3 { - let at = f.composite_extract(invocation, &[axis])?; - let end = if axis < 2 { - f.composite_extract(size, &[axis])? - } else { - samples - }; - let below = f.binary(BinOp::ULessThan, at, end)?; - inside = Some(match inside { - None => below, - Some(all) => f.binary(BinOp::LogicalAnd, all, below)?, - }); - } - let inside = inside.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?; - let source = f.module().global_value(source)?; - // Invocation `(x, y, s)` inside the destination copies sample `s` of pixel `(x, y)`. - let copy_sample: ArmFn<'_, ()> = Box::new(move |f, _| { - let source = f.load(source, MemAccess::default())?; - let x = f.composite_extract(invocation, &[0])?; - let y = f.composite_extract(invocation, &[1])?; - let s = f.composite_extract(invocation, &[2])?; - let pixel = f.composite_construct(uvec2, &[x, y])?; - let ops = ImageOperands { - sample: Some(s), - ..ImageOperands::default() - }; - let texel = f.fetch(source, pixel, &ops)?; - f.write(destination, pixel, texel, &ops, TexelMemory::default())?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), inside, copy_sample, None)?; - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: StencilSplitModule::LOCAL_SIZE, - y: StencilSplitModule::LOCAL_SIZE, - z: 1, - }], - )?; - b.finalize() -} - /// The fixed binding numbers of the modules' symbols. fn binding_of(sym: &Symbol) -> Option { match sym { Symbol::DescriptorSet(_) => Some(0), Symbol::Binding(s) if *s == DRAW_SOURCE => Some(DepthStencilCopyModules::SOURCE_BINDING), - Symbol::Binding(s) if *s == SPLIT_SOURCE => Some(StencilSplitModule::SOURCE_BINDING), - Symbol::Binding(s) if *s == SPLIT_DESTINATION => { - Some(StencilSplitModule::DESTINATION_BINDING) - } _ => None, } } @@ -516,7 +355,7 @@ pub(super) fn finish( } /// The modules of the copy draw `copy` on `device`: built with the typed builder (the vertex -/// stage is the sample planes merge's, `bind::sample_planes`), checked by the owned verifier +/// stage is the interleave merge's, `bind::sample_interleave`), checked by the owned verifier /// against the device's profile (requirements included), serialized, and numbered with the fixed /// binding of [`DepthStencilCopyModules`]. Refused, `Unsupported` naming `feature` (what the /// consumer copies for) and what the device lacks, where it lacks what the draw needs. @@ -527,7 +366,7 @@ pub fn depth_stencil_copy_modules( ) -> Result { let (vertex, vertex_needs) = finish( device, - super::sample_planes::merge_vertex_typed_module()?, + super::sample_interleave::merge_vertex_typed_module()?, &feature, "depth/stencil copy's vertex stage", )?; @@ -547,18 +386,5 @@ pub fn depth_stencil_copy_modules( }) } -/// The stencil split on `device`, built and checked as [`depth_stencil_copy_modules`] is; -/// refused likewise where the device lacks multisampled storage images of `R8_UINT`. -pub fn stencil_split_module( - device: &Device, - feature: Feature, -) -> Result { - let (spirv, requirements) = finish(device, split_typed_module()?, &feature, "stencil split")?; - Ok(StencilSplitModule { - spirv, - requirements, - }) -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/bind/depth_stencil_copy/tests.rs b/crates/metal2vulkan/src/bind/depth_stencil_copy/tests.rs index dc5ffbf3b..e212398be 100644 --- a/crates/metal2vulkan/src/bind/depth_stencil_copy/tests.rs +++ b/crates/metal2vulkan/src/bind/depth_stencil_copy/tests.rs @@ -7,17 +7,15 @@ use crate::device::{DeviceDescription, DevicePolicy}; use crate::spirv::testing::assert_valid; use std::path::PathBuf; -/// Every copy draw: each plane of each source, the export of each source, the depth, the +/// Every copy draw: each plane, the export, the depth, the /// depth's and the stencil's bits into colour, a depth's magnitude as a depth and as bits, and a /// 16-bit depth's code both ways. fn every_copy() -> Vec { let mut copies = Vec::new(); - for source in [CopySource::Aspect, CopySource::Shadow] { - for bit in StencilBit::ALL { - copies.push(DepthStencilCopy::StencilPlane { source, bit }); - } - copies.push(DepthStencilCopy::StencilExport { source }); + for bit in StencilBit::ALL { + copies.push(DepthStencilCopy::StencilPlane { bit }); } + copies.push(DepthStencilCopy::StencilExport); copies.push(DepthStencilCopy::Depth); copies.push(DepthStencilCopy::DepthBits); copies.push(DepthStencilCopy::StencilBits); @@ -41,8 +39,7 @@ fn each_bit_masks_its_plane() { } /// Each module needs exactly what the module docs say: every fragment stage `sampleRateShading`, -/// a read of the shadow multisampled storage images, the export the extension, the split -/// multisampled storage images of an extended format and no sample-rate shading. +/// the export the extension, and none multisampled storage images. #[test] fn each_module_needs_what_its_docs_say() { for copy in every_copy() { @@ -51,36 +48,18 @@ fn each_module_needs_what_its_docs_say() { r.features.contains(&VkFeature::SampleRateShading), "{copy:?}: {r:?}" ); - let export = matches!(copy, DepthStencilCopy::StencilExport { .. }); + let export = matches!(copy, DepthStencilCopy::StencilExport); assert_eq!( r.extensions.contains(&VkExtension::ExtShaderStencilExport), export, "{copy:?}: {r:?}" ); - let shadow = matches!( - copy, - DepthStencilCopy::StencilPlane { - source: CopySource::Shadow, - .. - } | DepthStencilCopy::StencilExport { - source: CopySource::Shadow - } - ); - assert_eq!( - r.features + assert!( + !r.features .contains(&VkFeature::ShaderStorageImageMultisample), - shadow, "{copy:?}: {r:?}" ); } - let r = needs(split_typed_module().expect("split")); - for feature in [ - VkFeature::ShaderStorageImageMultisample, - VkFeature::ShaderStorageImageExtendedFormats, - ] { - assert!(r.features.contains(&feature), "{feature:?}: {r:?}"); - } - assert!(!r.features.contains(&VkFeature::SampleRateShading), "{r:?}"); } /// Every committed device (`validation/profiles/*.json`), derived with the resident-table domains, @@ -112,7 +91,7 @@ fn committed_devices() -> Vec<(String, Device)> { #[test] fn the_modules_are_valid_where_the_device_has_what_they_need() { let feature = Feature::SeparateMultisampledDepthStencil; - let (mut draws, mut splits) = (0, 0); + let mut draws = 0; for (name, device) in committed_devices() { let profile = device.profile(); let fits = |m: TypedModule| profile.check(&needs(m)).is_ok(); @@ -132,22 +111,8 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { Err(other) => panic!("{name} {copy:?}: {other}"), } } - let fit = fits(split_typed_module().expect("split")); - match stencil_split_module(&device, feature.clone()) { - Ok(module) => { - assert!(fit, "{name}"); - assert_valid(split_typed_module().expect("split"), profile); - assert!(!module.spirv.is_empty()); - splits += 1; - } - Err(Error::Unsupported(u)) => { - assert!(!fit, "{name}"); - assert_eq!(u.feature, feature, "{name}"); - } - Err(other) => panic!("{name}: {other}"), - } } - assert!(draws > 0 && splits > 0, "{draws} {splits}"); + assert!(draws > 0); } /// The 16-bit depth pair's arithmetic is exact for **every** code: of all 65536 codes, each one diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 4d5842dcb..db01d25f7 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -10,12 +10,7 @@ //! stage's handle table and the set-1 heap arrays through the heap planner (`bind::heap`): the //! heap's members are shared by both stages, and each stage's table enters the members that reach //! it (a used texture's render stages, a bound texture's own stage). A fragment function's -//! imageblock storage binding is `WriteSource::Imageblock`; the pass's imageblock is one plane of -//! cells, so a pass of more than one layer or an amplified draw is not implemented. An attachment -//! the fragment function reads in the interlocked storage form -//! (`GraphicsState::storage_attachments`) is `WriteSource::TileAttachment` in the attachment's -//! own format, likewise one 2D view, so such a pass or draw is not implemented either. A fragment -//! function's threadgroup arguments (`RuntimeFact::TileThreadgroupMemory`) are the pass's tile +//! threadgroup arguments (`RuntimeFact::TileThreadgroupMemory`) are the pass's tile //! memory, `WriteSource::TileMemory` as a tile function's (`plan::compute`): the shape's //! `tile_threadgroup` places each argument, and its `render_area` and `imageblock_size` (the //! pass's tile) the tiles; a layered pass or an amplified draw is not implemented. @@ -93,29 +88,6 @@ //! has no attachment for (`BindShape::dropped_colors`), whose writes plain Metal drops: the //! variant whose fragment function keeps no output there (`VariantKey::dropped_colors`). A mesh //! pipeline's is not implemented. -//! - **Interlocked colors**. A draw into a render pass instance that leaves color attachments out -//! of its subpass for other draws' interlocked storage form (`BindShape::interlocked_colors`) -//! runs the variant whose fragment function writes those it writes through that form too -//! (`VariantKey::interlocked_colors`), so the draw records in the instance. That variant stores -//! them before the depth and stencil tests (tested storage writes, below): the plan of the -//! pipeline as compiled selects such a moved writer's tests from -//! `RuntimeFact::MovableStorageWrites`. A mesh pipeline's is not implemented, nor a -//! multisampled, layered or amplified draw's. -//! - **Snapshot reads**. A draw the consumer reads a texture of its own subpass for through a -//! snapshot (`BindShape::snapshot_textures`) runs the variant whose fragment function reads it so -//! (`VariantKey::snapshot_textures`, `lower::fragment`'s `snapshot`), for each slot of the -//! fragment stage's `StageInterface::snapshot_textures`, where the pipeline's two draws are -//! Metal's one: a device with `fragmentShaderPixelInterlock`, `fragmentStoresAndAtomics`, -//! `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask` (the variant's -//! pipeline requires the last two: its feedback loop flag and dynamic write masks), one -//! sample, no depth or stencil attachment, no rasterizer discard, no memory the vertex or -//! fragment function writes, no attachment in the storage form or input attachment, no -//! imageblock, tile memory, shader-side stencil or tests, no interlocked or shadowed colors, no -//! tessellation or mesh stages, and no amplified or layered draw. Every other -//! slot the shape names is left out, and the plan's `variant.snapshot_textures` says which it -//! kept. Its plan binds each slot's snapshot (`WriteSource::SnapshotTexels`) and leaves which of -//! the two draws runs to the consumer (`PushHole::SnapshotPhase`, zero in the plan's bytes); -//! `GraphicsState::snapshot_reads` states the consumer's part. //! - **Depth clamp range**. A draw in depth clamp mode through a range above 0 whose Vulkan depth //! clamp holds 0 (`BindShape::depth_clamp_range`) runs the variant whose fragment function, where //! it writes its depth, clamps that depth to the draw's range itself @@ -125,25 +97,6 @@ //! (`BindShape::rotated_weights`) of a pipeline whose fragment function reads //! `[[barycentric_coord]]` runs the variant that takes Metal's weights back from the drawn //! triangle's (`VariantKey::rotated_weights`, `LoweringInputs::rotated_weights`). -//! - **Tested storage writes**. A fragment function that stores a color through the interlocked -//! storage form and declares no early tests only because it discards -//! (`RuntimeFact::TestedStorageWrites`), in a pipeline with a depth or stencil attachment, stores -//! before Vulkan's tests where Metal stores after its own: a draw whose tests drop no fragment -//! (`BindShape::fragment_tests`, `FragmentTests::Pass`) runs it as compiled; one whose tests may -//! drop fragments but write neither attachment and count nothing (`Drop`) runs the variant whose -//! function declares early tests (`VariantKey::read_only_tests`); any other is -//! `NotImplemented(FramebufferFetch)`. A function that also writes other memory, or returns -//! depth, stencil, or a sample mask, states the fact without that variant (`early_variant`): a -//! draw whose tests drop no fragment runs it as compiled, and any other is -//! `NotImplemented(FramebufferFetch)` at the depth attachment (the stencil one where the pipeline -//! has no depth attachment). A draw that moves a color the function writes as an ordinary output -//! into the storage form (interlocked colors, above) takes its tests alike from -//! `RuntimeFact::MovableStorageWrites`, which states the `early_variant` the moved writer's -//! variant states, where the pipeline as compiled states no `TestedStorageWrites`; a moved write -//! whose mask names none of the attachment's components stores nothing, and takes no tests. (A -//! draw whose depth test alone acts, `Depth`, is `NotImplemented(FramebufferFetch)` at the depth -//! attachment, unless it writes nothing and the early-tests variant serves it; one whose stencil -//! test acts and whose tests write, `Stencil`, is so at the stencil attachment.) //! - **Draws.** A Metal draw maps to the Vulkan draw of the same arguments; an indirect draw is //! GPU-side unless a stage reads `BaseVertexInstance` from push constants or the plan is //! multiview, in which case `indirect_needs_arguments` asks for the CPU read. @@ -268,26 +221,25 @@ use crate::bind::plan::resources::{separate_samplers, ResourcePlanner}; use crate::bind::plan::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, check_sparse_textures, cross_variant, cubic_variant, heap_raw, large_view_candidates, - mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, snapshot_forms, - srgb_variant, storage_view_variant, texel_buffer_parts_variant, used_uses, - ycbcr_in_place_variant, ycbcr_planes_sampled_variant, + mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, srgb_variant, + storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, + ycbcr_planes_sampled_variant, }; use crate::bind::plan::{ AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorTemplate, FieldLocation, GraphicsTemplate, GroupLimits, GroupStage, MeshTemplate, PlannedVertexBuffer, - PushFieldPlacement, PushTemplate, ResourceUse, ShadowTemplate, StageTemplate, StrideRules, - UseTarget, VertexBufferBind, ViewSetup, WriteSource, + PushFieldPlacement, PushTemplate, ResourceUse, StageTemplate, StrideRules, UseTarget, + VertexBufferBind, ViewSetup, WriteSource, }; use crate::bind::resident::{stage_root_table, table_entries}; use crate::bind::state::{ - offset_alignment, BindShape, BindState, BoundBuffer, BufferShape, FragmentTests, - VertexAmplification, + offset_alignment, BindShape, BindState, BoundBuffer, BufferShape, VertexAmplification, }; use crate::cache::{SpecializationKey, VariantKey}; use crate::device::profile::portable_vertex_stride; use crate::device::requirements::{VkFeature, VkLimit}; use crate::device::{vk_stage, Device}; -use crate::error::{Attachment, BindError, Capability, Feature, LowerFamily, Unsupported}; +use crate::error::{BindError, Capability, Feature, LowerFamily, Unsupported}; use crate::float16::{f16_bits_to_f32, f32_to_f16_bits}; use crate::lower::dispatch::region_bytes; use crate::metal; @@ -719,16 +671,6 @@ fn vertex_layer(p: &RenderPipeline) -> Option { }) } -/// Whether a draw's write to the ordinary color attachment of state `a` stores something: its -/// mask names some of the format's color components (Vulkan writes nothing to a component the -/// mask leaves out, nor to one the format lacks), as the storage form's write stores something -/// where its mask covers some of the format's channels (`StorageView::stores_nothing`). -fn stores(a: crate::pipeline::graphics::ColorAttachmentState) -> bool { - a.format - .block() - .is_some_and(|b| a.write_mask.intersects(b.color_components)) -} - fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { check_slots(shape)?; let tessellation = p.graphics.tessellation.is_some(); @@ -830,28 +772,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result None, }); - // The fragment imageblock is one plane per render pass instance. What Metal gives each layer of - // a layered pass, or each view of an amplified draw, is not read yet: such a pass is not - // implemented. - if p.graphics.fragment_imageblock.is_some() - && (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1) - { - return Err(not_implemented(Feature::Imageblocks)); - } - // An attachment read in the interlocked storage form is one 2D view: what a layered pass, or an - // amplified draw, reads and writes of each layer or view is not modelled. - if !p.graphics.storage_attachments.is_empty() - && (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1) - { - return Err(not_implemented(Feature::FramebufferFetch)); - } - // The shader-side stencil's shadow is one 2D image: the same holds. - let shadow = shadow_template(p); - if shadow.is_some() - && (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1) - { - return Err(not_implemented(Feature::StencilExport)); - } // A fragment function's tile threadgroup memory is the pass's, every tile's in one buffer: // what Metal gives each layer of a layered pass, or each view of an amplified draw, is not // read yet, as for a tile dispatch. @@ -904,101 +824,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result None, }) .collect(); - // The colors the draw's instance keeps out of its subpass that the fragment function writes - // through its first output: the variant that writes them through the interlocked storage - // form, as a fetching function does. A pipeline that writes them so is that variant. A mesh - // pipeline's is not built. - let interlocked_colors: std::collections::BTreeSet = shape - .interlocked_colors - .iter() - .copied() - .filter(|&c| { - 1u32.checked_shl(c) - .is_some_and(|bit| p.graphics.color_outputs & bit != 0) - }) - .collect(); - if !interlocked_colors.is_empty() && mesh { - return Err(not_implemented(Feature::MeshShading)); - } - // Nor a multisampled draw's, whose storage form reads and writes the attachment per sample, - // which runs the function per sample where a plain writer runs it per pixel; nor a layered - // pass's or an amplified draw's, whose storage form is one 2D view (above). - if !interlocked_colors.is_empty() - && (p.graphics.rasterization_samples.as_raw() > 1 - || shape.render_target_array_length > 1 - || shape.vertex_amplification.count > 1) - { - return Err(not_implemented(Feature::FramebufferFetch)); - } - let compiled_interlocked: std::collections::BTreeSet = p - .graphics - .storage_attachments - .iter() - .filter(|a| a.writes && shape.interlocked_colors.contains(&a.color_index)) - .map(|a| a.color_index) - .collect(); - // The fragment texture slots the draw reads through a snapshot: those the shape names that - // the fragment function can read so, where the pipeline's two draws are Metal's one. The two - // run the same fragments (the pipeline differs only in its dynamic write masks), the first - // with every mask 0 running none of the function past its copy, so the pipeline may hold - // nothing else either draw writes, tests, or orders: one sample, no depth or stencil, no - // memory either function writes, no attachment, imageblock, tile memory or stencil shadow of - // the storage form or an input attachment, and no other interlock. A tessellation - // or mesh pipeline's, and an amplified or layered draw's are not built. - // The device makes the variant's pipeline: its feedback loop flag and dynamic write masks - // need `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`. - // Every other slot the shape names is left out, and the consumer reads it as it would without - // a snapshot. - let enabled = &profile.fields().enabled.features; - let snapshot_able = crate::lower::fragment::interlock_forms(profile) - && enabled.contains(&VkFeature::FragmentStoresAndAtomics) - && enabled.contains(&VkFeature::AttachmentFeedbackLoopLayout) - && enabled.contains(&VkFeature::ExtendedDynamicState3ColorWriteMask) - && p.graphics.rasterization_samples.as_raw() <= 1 - && p.graphics.depth_format.is_none() - && p.graphics.stencil_format.is_none() - && !p.graphics.rasterizer_discard - && !p.graphics.vertex_writes_memory - && !p.graphics.fragment_writes_memory - && p.graphics.storage_attachments.is_empty() - && p.graphics.input_attachments.is_empty() - && p.graphics.fragment_imageblock.is_none() - && p.graphics.tessellation.is_none() - && shadow.is_none() - && tile_memory.is_none() - && !mesh - && interlocked_colors.is_empty() - && shape.vertex_amplification.count <= 1 - && shape.render_target_array_length <= 1; - let snapshot_textures: std::collections::BTreeSet = match snapshot_able { - true => p - .stages - .iter() - .filter(|m| m.stage == vk::ShaderStage::FRAGMENT) - .flat_map(|m| &m.snapshot_textures) - .filter(|index| shape.snapshot_textures.contains(index)) - .map(|&index| SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index, - }) - .collect(), - false => std::collections::BTreeSet::new(), - }; - let compiled_snapshots: std::collections::BTreeSet = p - .layout - .sets - .iter() - .flat_map(|set| &set.bindings) - .filter_map(|b| match b.source { - BindingSource::SnapshotTexels(index) => Some(SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index, - }), - _ => None, - }) - .collect(); // A draw in depth clamp mode through a range above 0 whose Vulkan depth clamp holds 0: the // variant whose fragment function clamps the depth it writes to the draw's range. A pipeline // whose fragment function writes no depth has none to clamp. @@ -1019,93 +844,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Some((early_tests, early_variant)), - _ => None, - }) - .or_else(|| { - let movable = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::MovableStorageWrites { early_variant } => Some((false, early_variant)), - _ => None, - }); - movable.filter(|_| moves) - }); - let tested_attachments = - p.graphics.depth_format.is_some() || p.graphics.stencil_format.is_some(); - // What stores before the tests: the storage form's colors, or else the imageblock. - let tested_feature = match p.graphics.fragment_imageblock { - Some(_) if p.graphics.storage_attachments.is_empty() => Feature::Imageblocks, - _ => Feature::FramebufferFetch, - }; - // A draw whose tests drop some fragments but write and count nothing runs the early-tests - // variant where the function has one; a draw whose tests may drop a fragment and write, or - // count, is not implemented, as the function stores before Vulkan's tests. The refusal is - // placed at the tested attachment: the depth one where the pipeline has one, else the - // stencil. - let depth = p.graphics.depth_format.is_some(); - let stencil = p.graphics.stencil_format.is_some(); - let at = |attachment: Attachment| { - Err(BindError::Unsupported( - Unsupported::not_implemented(tested_feature.clone()).at_attachment(attachment), - )) - }; - let read_only_tests = match (tested, shape.fragment_tests) { - (Some((_, true)), FragmentTests::Drop | FragmentTests::Depth { writes: false }) - if tested_attachments => - { - true - } - // A function that writes other memory or returns depth, stencil, or a sample mask: its - // stores are Metal's only where no test can drop a fragment. - ( - Some((_, false)), - FragmentTests::Drop - | FragmentTests::Depth { .. } - | FragmentTests::Any - | FragmentTests::Stencil, - ) if tested_attachments => { - return at(match depth { - true => Attachment::Depth, - false => Attachment::Stencil, - }); - } - (Some(_), FragmentTests::Depth { .. }) if depth => return at(Attachment::Depth), - (Some(_), FragmentTests::Stencil) if stencil => return at(Attachment::Stencil), - (Some(_), FragmentTests::Any | FragmentTests::Stencil) if tested_attachments => { - return Err(not_implemented(tested_feature.clone())); - } - _ => false, - }; - let compiled_tests = tested.is_some_and(|(early, _)| early); // A mesh entry's `Layer` at or past `maxMeshOutputLayers` is undefined: a pass of more layers // than that, which a mesh function choosing its slice could render into, is past the device. let mesh_layers = limits.mesh.max_mesh_output_layers; @@ -1201,7 +939,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result {} - // Which of a snapshot variant's draws runs: the consumer's hole. - PushField::SnapshotPhase if stage == Stage::Fragment => {} PushField::SlotBindOffset(slot) if planned(slot).is_some_and(|b| b.binding.is_some()) => {} // The bound buffer's Metal address; a `set*Bytes` binding has none. @@ -1266,8 +1001,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result {} - // The encoder's stencil state, which instantiation reads from the state. - PushField::ShadowStencilState if stage == Stage::Fragment => {} // The encoder's viewport count, which instantiation reads from the state, in the // stage that chooses a viewport (a mesh function per primitive). PushField::ViewportCount if matches!(stage, Stage::Vertex | Stage::Mesh) => {} @@ -1286,8 +1019,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result {} // The encoder's blend color, which instantiation reads from the state. PushField::HalfBlendColor if stage == Stage::Fragment => {} - // The storage form's kept channels, which instantiation reads from the template. - PushField::StorageKeptChannels if stage == Stage::Fragment => {} // A draw of one amplification's id and offsets, which instantiation writes before // each draw; the placement order puts them right after the addresses, so the window // holds them. @@ -1546,12 +1277,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { planner(&mut heap)?.snapshot(stage, set.set, b.binding)? } - // The pass's imageblock storage. - SyntheticBinding::Imageblock - if stage == Stage::Fragment && p.graphics.fragment_imageblock.is_some() => - { - WriteSource::Imageblock - } // The pass's tile threadgroup memory. SyntheticBinding::TileMemory if stage == Stage::Fragment => { match &tile_memory { @@ -1563,21 +1288,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { - match &p.graphics.shadow_stencil { - Some(_) => WriteSource::ShadowStencil, - None => WriteSource::Neutral(NeutralResource::Image { - view_type: vk::ImageViewType::TYPE_2D, - sampled_type: crate::pipeline::sym::SampledType::Uint, - depth_compare: false, - samples: p.graphics.rasterization_samples.as_raw().max(1), - storage_format: Some(crate::lower::fragment::SHADOW_FORMAT), - }), - } - } // The command buffer's status, on a device that does not address buffers. SyntheticBinding::ExecutionStatus => WriteSource::ExecutionStatus, other => return Err(internal(format!("a render binding {other:?}"))), @@ -1598,31 +1308,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { WriteSource::AccelerationStructure { slot, level } } - // An attachment the fragment function reads in the interlocked storage form, a - // storage view of the attachment, or of its sample planes, in its own format. - BindingSource::TileAttachment(color_index) => { - let a = p - .graphics - .storage_attachments - .iter() - .find(|a| a.color_index == color_index) - .ok_or_else(|| { - internal(format!( - "a storage binding of color attachment {color_index}, which the \ - pipeline does not read in the storage form" - )) - })?; - WriteSource::TileAttachment { - color_index, - format: a.format, - view: a.view, - view_alias: a.view_alias, - } + // A tile function's attachment, which no render pipeline binds. + BindingSource::TileAttachment(_) => { + return Err(internal("a tile attachment binding in a render pipeline")) } // A sparse texture's tile map. BindingSource::TileMap(slot) => resources.tile_map(slot), - // A texture's snapshot, which the draw reads the texture through. - BindingSource::SnapshotTexels(slot) => WriteSource::SnapshotTexels { slot }, // A two-plane YCbCr texture's planes image, through the device's conversion. BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?, }; @@ -1969,28 +1660,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result Result Result { - p.graphics - .storage_attachments - .iter() - .try_fold(0u32, |word, s| match s.color_index { - c @ 0..8 => Ok(word | ((s.kept.as_raw() & 0xF) << (4 * c))), - _ => Err(internal("a storage-form color attachment past the eighth")), - }) -} - -/// The shader-side stencil of `p`'s fragment function, when it has one. -fn shadow_template(p: &RenderPipeline) -> Option { - let has = p.interface.push.iter().any(|pl| { - pl.fields - .iter() - .any(|f| f.field == PushField::ShadowStencilState) - }); - has.then(|| ShadowTemplate { - attached: p.graphics.shadow_stencil.is_some(), - depth_attachment: p.graphics.depth_format.is_some(), - }) -} - -/// The `PushField::ShadowStencilState` words of a draw under encoder state `state`: the front -/// face's, then the back face's (`lower::fragment::face_word`). A state whose stencil write could -/// depend on the depth test is refused as needing stencil export: the pass has a depth attachment, -/// the depth comparison is not `Always`, and a face's depth-failure operation differs from its pass -/// operation (the depth test runs after the function). -fn shadow_stencil_words(t: &ShadowTemplate, state: &BindState) -> Result { - let ds = &state.depth_stencil; - let faces = [&ds.front_face_stencil, &ds.back_face_stencil]; - if t.attached - && t.depth_attachment - && ds.depth_compare_function != metal::CompareFunction::Always - && faces - .iter() - .any(|f| f.depth_failure_operation != f.depth_stencil_pass_operation) - { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::StencilExport, - Capability::Extension(crate::device::requirements::VkExtension::ExtShaderStencilExport), - ))); - } - Ok(FieldBytes::words(faces.map(|f| { - crate::lower::fragment::face_word( - f.stencil_compare_function.as_raw(), - f.stencil_failure_operation.as_raw(), - f.depth_stencil_pass_operation.as_raw(), - f.read_mask, - f.write_mask, - t.attached, - ) - }))) -} - /// The 8-bit unorm code Metal's private alpha test compares the reference `reference` as /// (`setAlphaTestReferenceValue:`, Apple SPI; `PushField::AlphaTestReference`, probes on an Apple /// M3 Max): NaN is 0, the value is clamped to `[0, 1]`, and the code is the exact product with @@ -3431,7 +3045,6 @@ fn instantiate( | PushField::ExecutionStatusAddress | PushField::CaptureIndexAddress | PushField::MergedDrawAddress - | PushField::SnapshotPhase | PushField::ReplayRegionAddress => { let PushLoc::Push { offset } = f.loc else { return Err(not_implemented(Feature::Lowering(LowerFamily::StageIo))); @@ -3444,7 +3057,6 @@ fn instantiate( PushField::ExecutionStatusAddress => { PushHole::ExecutionStatusAddress { stages, offset } } - PushField::SnapshotPhase => PushHole::SnapshotPhase { stages, offset }, PushField::MergedDrawAddress => { PushHole::MergedDrawAddress { stages, offset } } @@ -3459,12 +3071,6 @@ fn instantiate( Some(d) => FieldBytes::words(d.layout.iter().copied()), None => return Err(internal("a draw layout without its de-indexed form")), }, - PushField::ShadowStencilState => { - let Some(shadow) = &t.shadow_stencil else { - return Err(internal("a stencil state without its shader-side stencil")); - }; - shadow_stencil_words(shadow, state)? - } PushField::DispatchRegion => match mesh.as_ref().and_then(|m| m.region(st.stage)) { Some(region) => FieldBytes::of(®ion), None => return Err(internal("a dispatch region outside a mesh draw")), @@ -3482,7 +3088,6 @@ fn instantiate( .iter() .flat_map(|v| v.to_le_bytes()) .collect(), - PushField::StorageKeptChannels => FieldBytes::of(&t.storage_kept.to_le_bytes()), // The alpha test reference's code, Metal's 1 where the encoder never set it. PushField::AlphaTestReference => FieldBytes::of( &alpha_test_code(state.alpha_test_reference.unwrap_or(1.0)).to_le_bytes(), diff --git a/crates/metal2vulkan/src/bind/graphics/tests.rs b/crates/metal2vulkan/src/bind/graphics/tests.rs index 8ac3daa8b..af99aefd9 100644 --- a/crates/metal2vulkan/src/bind/graphics/tests.rs +++ b/crates/metal2vulkan/src/bind/graphics/tests.rs @@ -599,11 +599,9 @@ fn instantiation_bounds_a_draw_by_its_index_buffer() { tessellation: None, indirect_first_instance_missing: false, robust_index_fetch, - shadow_stencil: None, mesh: None, deindexed: None, private_list: false, - storage_kept: 0, line_band: None, }; let state = BindState::default(); @@ -647,11 +645,9 @@ fn a_draw_of_no_index_binds_inside_the_buffer() { tessellation: None, indirect_first_instance_missing: false, robust_index_fetch, - shadow_stencil: None, mesh: None, deindexed: None, private_list: false, - storage_kept: 0, line_band: None, }; let state = BindState::default(); @@ -730,11 +726,9 @@ fn an_unbounded_indexed_indirect_draw_reads_its_arguments() { tessellation: None, indirect_first_instance_missing, robust_index_fetch, - shadow_stencil: None, mesh: None, deindexed: None, private_list: false, - storage_kept: 0, line_band: None, }; let state = BindState::default(); @@ -785,11 +779,9 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() { tessellation: None, indirect_first_instance_missing: false, robust_index_fetch: false, - shadow_stencil: None, mesh: None, deindexed: None, private_list: false, - storage_kept: 0, line_band: None, }; let state = |offsets: (u64, u64), stride| { @@ -875,11 +867,9 @@ fn inline_vertex_bytes_bind_the_strides_a_dynamic_layout_reads() { tessellation: None, indirect_first_instance_missing: false, robust_index_fetch: false, - shadow_stencil: None, mesh: None, deindexed: None, private_list: false, - storage_kept: 0, line_band: None, }; let state = |attribute_stride| { @@ -1463,7 +1453,6 @@ fn mesh_template(flat: bool, multiples: Vec) -> GraphicsTemplate { tessellation: None, indirect_first_instance_missing: false, robust_index_fetch: true, - shadow_stencil: None, mesh: Some(MeshTemplate { spec: layout, fixed: vec![(SpecKey::Presence(fragment_buffer), 1)], @@ -1481,7 +1470,6 @@ fn mesh_template(flat: bool, multiples: Vec) -> GraphicsTemplate { }), deindexed: None, private_list: false, - storage_kept: 0, line_band: None, } } diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index e3363b12c..94dbc823e 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -101,14 +101,6 @@ pub enum PushHole { stages: vk::ShaderStageFlags, offset: u32, }, - /// Which draw of a snapshot variant (`VariantKey::snapshot_textures`, - /// `PushField::SnapshotPhase`) runs, as a `u32` at `offset` of the variant's fragment push - /// bytes: 1 in the draw that takes the snapshot (every color write mask 0), 0 in the draw that - /// reads it (the pipeline's masks). - SnapshotPhase { - stages: vk::ShaderStageFlags, - offset: u32, - }, } /// A consumer-owned indirect-argument buffer and the byte offset of the arguments. diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 89c9eedc6..d0b7e969e 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -36,13 +36,9 @@ //! through the binding [`WriteSource::ExecutionStatus`] names where it does not. An indirect //! dispatch reads its group counts from Metal's buffer itself ([`IndirectArgs::Buffer`]). //! A pass's visibility results are its queries' results copied to their -//! offsets, a `Boolean` one the device's own nonzero value where a sample passed. A pass whose -//! fetching draws -//! read a multisampled attachment's sample planes (`StorageAttachmentView::SamplePlanes`) splits -//! the attachment into them with [`planes_split_module`] and merges them back with -//! [`planes_merge_modules`], through the [`PlanesCopy`] view of its texel size. A multisampled +//! offsets, a `Boolean` one the device's own nonzero value where a sample passed. A multisampled //! depth or stencil aspect moves between images without colour copies through the draws of -//! [`depth_stencil_copy_modules`] and the kernel of [`stencil_split_module`]. Compute commands +//! [`depth_stencil_copy_modules`]. Compute commands //! a kernel encodes into an indirect command buffer replay on the device where it has device //! addresses: the [`replay_preprocess`] of an execution ([`ReplayExecution`]) over registered //! [`ReplayVariant`]s, recorded with [`replay_preprocess_module`], writes each command's arguments @@ -97,7 +93,6 @@ pub(crate) mod rate_map; pub(crate) mod replay; pub(crate) mod resident; pub(crate) mod sample_interleave; -pub(crate) mod sample_planes; pub(crate) mod state; pub(crate) mod status; pub(crate) mod table; @@ -119,8 +114,7 @@ pub use astc_decode::{AstcDecode, AstcTexels}; pub use chroma_decode::ChromaDecode; pub use depth_clamp::clamped_depth; pub use depth_stencil_copy::{ - depth_stencil_copy_modules, stencil_split_module, CopySource, DepthStencilCopy, - DepthStencilCopyModules, StencilBit, StencilSplitModule, + depth_stencil_copy_modules, DepthStencilCopy, DepthStencilCopyModules, StencilBit, }; pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs}; pub use etc_decode::{EtcDecode, EtcTexels}; @@ -172,8 +166,8 @@ pub use replay::{ pub use state::{ ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState, BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture, - BufferRanges, BufferShape, FragmentTests, FunctionTablesShape, HeapPlacement, ImageblockSize, - ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable, + BufferRanges, BufferShape, FunctionTablesShape, HeapPlacement, ImageblockSize, ResourceClass, + SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape, TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape, VertexAmplification, ViewMapping, @@ -183,10 +177,7 @@ pub use state::{ pub use pvrtc_decode::PvrtcDecode; pub use sample_interleave::{ interleave_merge_modules, interleave_split_module, InterleaveMergeModules, - InterleaveSplitModule, -}; -pub use sample_planes::{ - planes_merge_modules, planes_split_module, PlanesCopy, PlanesMergeModules, PlanesSplitModule, + InterleaveSplitModule, PlanesCopy, }; pub use status::{ExecutionStatus, ReplayFaults, StatusBits, StatusReport, StatusWord}; pub use table::{FunctionTableSnapshot, FunctionTableWords}; diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 2a3cb3cc8..21f2ce830 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -14,7 +14,6 @@ use crate::bind::neutral::NeutralResource; use crate::cache::{SpecializationKey, VariantKey}; use crate::metal::sampler::OpaqueBlackBorder; use crate::pipeline::artifact::SpecConstant; -use crate::pipeline::graphics::StorageAttachmentView; use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window}; use crate::pipeline::sym::{ @@ -207,10 +206,6 @@ pub struct GraphicsTemplate { /// only without it): a direct indexed draw past its index buffer is drawn, not clamped. #[cfg_attr(feature = "serde", serde(default))] pub(crate) robust_index_fetch: bool, - /// A fragment function's shader-side stencil: its draws write the encoder's stencil state as - /// `PushField::ShadowStencilState`. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) shadow_stencil: Option, /// A mesh render pipeline's mesh stage: its draws are mesh draws, each of its own /// specialization. #[cfg_attr(feature = "serde", serde(default))] @@ -225,11 +220,6 @@ pub struct GraphicsTemplate { /// draw call. #[cfg_attr(feature = "serde", serde(default))] pub(crate) private_list: bool, - /// `PushField::StorageKeptChannels`: each storage-form color attachment's kept channels - /// (`StorageAttachmentUse::kept`), bits `4c` to `4c + 3` for color `c`, which its draws - /// write. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) storage_kept: u32, /// A band variant's (`GraphicsState::line_band`): the byte offset of its evaluation stage's /// push range, where its draws push `BindState::line_band` (`PushField::LineBand`). #[cfg_attr(feature = "serde", serde(default))] @@ -291,17 +281,6 @@ pub(crate) enum GroupStage { Mesh, } -/// What a draw of a pipeline with a shader-side stencil instantiates. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct ShadowTemplate { - /// The pass has a stencil attachment, so the plan binds the shadow - /// (`GraphicsState::shadow_stencil`); otherwise a neutral stands in and nothing is tested. - pub attached: bool, - /// The pass has a depth attachment, whose test could decide the stencil write. - pub depth_attachment: bool, -} - /// What a patch draw of a tessellation pipeline instantiates: the control stage's push range, the /// patch and control-point index buffers' descriptor ranges, and the factor buffer's range. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -668,41 +647,22 @@ pub enum WriteSource { slot: SlotRef, level: AccelerationStructureLevel, }, - /// The render pass's fragment imageblock storage (`GraphicsState::fragment_imageblock`): the - /// one storage image the consumer creates for the pass instance, in `GENERAL` layout, bound to - /// every draw of the pass, and to every tile dispatch whose function's explicit imageblock - /// stands alone, which stages its tile's cells from it and back. + /// The render pass's imageblock storage: the one storage image the consumer creates for the + /// pass instance, in `GENERAL` layout, bound to every tile dispatch whose function's explicit + /// imageblock stands alone, which stages its tile's cells from it and back. Imageblock, - /// A render pass's color attachment `color_index` as a storage image: the view `view` names, - /// in `format`, with the identity component mapping, in `GENERAL` layout. For - /// [`StorageAttachmentView::Attachment`] that is a 2D view of the attachment's own image, of - /// the pass's layer and level; for [`StorageAttachmentView::SamplePlanes`] `{ layers }` a - /// 2D-array view of all `layers` layers of the attachment's sample planes, the single-sample - /// image the consumer keeps beside a multisampled attachment, never a 2D view. - /// - /// - A tile dispatch's: the image's format is the tile pipeline descriptor's - /// (`TileRenderPipelineDescriptor::color_attachment_formats`), as Metal requires of the - /// pass, and its extent at least the render area (`BindState::render_area`). `format` is - /// the image's own for an integer format, and for a float format the unsigned-integer - /// format of the same channels and widths (`R16_UINT` for `R16_SFLOAT`), so the dispatch - /// moves the texels' bits: the consumer creates such an image with `MUTABLE_FORMAT` (and - /// `EXTENDED_USAGE` when its own format is not storage-capable). - /// `view` is always `Attachment`. - /// - A draw's whose fragment function reads the attachment in the interlocked storage form - /// (`GraphicsState::storage_attachments`): `format` and `view` are the pipeline's - /// [`StorageAttachmentUse`](crate::pipeline::StorageAttachmentUse)'s, and the image has - /// `STORAGE` usage and is no color attachment of the subpass. + /// A render pass's color attachment `color_index` as a storage image of a tile dispatch: a 2D + /// view of the attachment's own image, of the pass's layer and level, in `format`, with the + /// identity component mapping, in `GENERAL` layout. The image's format is the tile pipeline + /// descriptor's (`TileRenderPipelineDescriptor::color_attachment_formats`), as Metal requires + /// of the pass, and its extent at least the render area (`BindState::render_area`). `format` + /// is the image's own for an integer format, and for a float format the unsigned-integer + /// format of the same channels and widths (`R16_UINT` for `R16_SFLOAT`), so the dispatch moves + /// the texels' bits: the consumer creates such an image with `MUTABLE_FORMAT` (and + /// `EXTENDED_USAGE` when its own format is not storage-capable). TileAttachment { color_index: u32, format: vk::Format, - view: StorageAttachmentView, - /// A draw's: the pipeline's `StorageAttachmentUse::view_alias`, where the view is in that - /// format, of an image the consumer made mutable to it (an sRGB attachment's - /// unsigned-integer format of its texel size, a BGRA-order one's RGBA-order twin on a - /// device that accesses its format without one in neither direction); `None` elsewhere, - /// and for a tile dispatch's, whose view is `format`. - #[cfg_attr(feature = "serde", serde(alias = "uint_view"))] - view_alias: Option, }, /// The tile map of the sparse texture bound at texture slot `slot` (`bind::SparseTileMap`), /// a read-only storage buffer of [`SparseTileMap::byte_len`](crate::bind::SparseTileMap) @@ -723,11 +683,6 @@ pub enum WriteSource { compare: bool, integer: bool, }, - /// The shadow of the render pass's stencil attachment that a fragment function's - /// shader-side stencil tests and writes (`GraphicsState::shadow_stencil`): the consumer's - /// `R8_UINT` 2D storage image of the attachment's extent, in `GENERAL` layout - /// ([`ShadowStencilUse`](crate::pipeline::ShadowStencilUse)). - ShadowStencil, /// Element `index + 1` of the set-1 function-table array: the words of /// `BindState::function_tables[index]` (`pipeline::table`'s layout, as /// [`FunctionTableWords`](crate::bind::FunctionTableWords) encodes them), a read-only @@ -769,12 +724,6 @@ pub enum WriteSource { /// zero ([`ExecutionStatus::initial`](crate::bind::ExecutionStatus::initial)). The consumer /// reads it once the command buffer completes. ExecutionStatus, - /// The snapshot of the texture the draw binds at fragment texture slot `slot` - /// (`BindingSource::SnapshotTexels`, `VariantKey::snapshot_textures`): the consumer's - /// single-sample 2D `R32G32B32A32_UINT` storage image covering the draw's render area, in - /// `GENERAL` layout, which the draw's fragments write at their pixels in the draw that takes - /// the snapshot and read in the draw that reads it (`PushHole::SnapshotPhase`). - SnapshotTexels { slot: u32 }, } /// The image of a combined image-sampler write. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 2bf850d3a..809ae8fc7 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -84,7 +84,6 @@ use crate::lower::simd::divergent::VOTE_BYTES; use crate::lower::simd::workgroup::arena_bytes; use crate::pipeline::artifact::{ComputePipeline, RuntimeDependency, SpecConstant}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::graphics::StorageAttachmentView; use crate::pipeline::interface::{BufferForm, PushLoc, SlotInterface}; use crate::pipeline::layout::BindingSource; use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding}; @@ -684,8 +683,6 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result WriteSource::TileAttachment { color_index, format: tile_view_format(p, color_index)?, - view: StorageAttachmentView::Attachment, - view_alias: None, }, other => return Err(internal(format!("a compute binding {other:?}"))), }; diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index dc39c7fff..5594193fe 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -18,7 +18,7 @@ use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice}; use crate::pipeline::interface::SlotInterface; use crate::pipeline::interface::{AccessSet, BufferForm, BufferSlot, Window}; use crate::pipeline::layout::{BindingSource, PipelineLayout}; -use crate::pipeline::sym::{SampledType, SlotClass, SlotRef, SnapshotForm, SpecKey, Stage}; +use crate::pipeline::sym::{SampledType, SlotClass, SlotRef, SpecKey, Stage}; use crate::vk; use super::compute::internal; @@ -400,39 +400,6 @@ pub(crate) fn srgb_variant( .collect() } -/// The form each of the snapshot slots `slots` keeps its texels in (`VariantKey::snapshot_textures`, -/// `SnapshotForm::of`): by the bound texture's sampled view, which the snapshot's copy fetches -/// through, and the slot's declared sampled type. [`SnapshotForm::Bits`] at a slot the variant -/// reads in another class (`cross`), or one whose sampled view the device has no format for (an -/// 8-bit sRGB format held as its UNORM twin among them). The variant's compile reads the same -/// key, so its plan for the same shape states the same forms. -pub(crate) fn snapshot_forms( - profile: &DeviceProfile, - slots: &std::collections::BTreeSet, - interface: &BTreeMap, - shape: &BindShape, - cross: &BTreeMap, -) -> BTreeMap { - let form = |slot: SlotRef| { - let Some(SlotInterface::Texture(t)) = interface.get(&slot) else { - return SnapshotForm::Bits; - }; - let Some(TextureShape::Texture { pixel_format, .. }) = bound_texture(shape, slot) else { - return SnapshotForm::Bits; - }; - if cross.contains_key(&slot) { - return SnapshotForm::Bits; - } - let usages: std::collections::BTreeSet<_> = - [crate::device::requirements::FormatUsage::SampledImage].into(); - let Ok(m) = metal::format::vk_format(*pixel_format, &usages, profile) else { - return SnapshotForm::Bits; - }; - SnapshotForm::of(m.format, t.sampled_type) - }; - slots.iter().map(|&slot| (slot, form(slot))).collect() -} - /// The sampled texture slots whose function reads their texels in any numeric class /// (`RuntimeFact::CrossClassReads`) at which `shape` binds a texture whose format's class is not /// the slot's declared one and which the variant reads in that class diff --git a/crates/metal2vulkan/src/bind/replay/rules.rs b/crates/metal2vulkan/src/bind/replay/rules.rs index bdef8a73c..e1ff83a83 100644 --- a/crates/metal2vulkan/src/bind/replay/rules.rs +++ b/crates/metal2vulkan/src/bind/replay/rules.rs @@ -44,10 +44,6 @@ pub enum DrawReplayRule { VertexWritesMemory, /// The state's fragment function writes memory. FragmentWritesMemory, - /// The state has a fragment imageblock. - FragmentImageblock, - /// The state tests stencil in its shaders. - ShaderStencil, /// The state reads its attachments. InputAttachments, /// The state's indirect draw needs its arguments on the CPU. @@ -102,8 +98,6 @@ impl fmt::Display for DrawReplayRule { DrawReplayRule::FragmentWritesMemory => { "the inherited state's fragment function writes memory" } - DrawReplayRule::FragmentImageblock => "the inherited state has a fragment imageblock", - DrawReplayRule::ShaderStencil => "the inherited state tests stencil in its shaders", DrawReplayRule::InputAttachments => "the inherited state reads its attachments", DrawReplayRule::ArgumentsOnCpu => { "the inherited state's indirect draw needs its arguments on the CPU" @@ -193,8 +187,8 @@ pub fn draw_replay_merges(primitive_type: PrimitiveType) -> bool { /// The inherited state's rules (its `graphics` facts) for a draw replay, `merged` into one draw or /// not: its functions write no memory (but a vertex function where nothing rasterizes, unless the /// draws merge: a merged draw runs a vertex for each corner of a whole primitive, which only a -/// vertex function that writes no memory cannot tell from Metal's), and it has no fragment -/// imageblock, shader-side stencil or depth test or attachment read. +/// vertex function that writes no memory cannot tell from Metal's), and it has no depth test or +/// attachment read. pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), DrawReplayRule> { let rules = [ ( @@ -205,14 +199,6 @@ pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), D graphics.fragment_writes_memory, DrawReplayRule::FragmentWritesMemory, ), - ( - graphics.fragment_imageblock.is_some(), - DrawReplayRule::FragmentImageblock, - ), - ( - graphics.shadow_stencil.is_some(), - DrawReplayRule::ShaderStencil, - ), ( !graphics.input_attachments.is_empty(), DrawReplayRule::InputAttachments, diff --git a/crates/metal2vulkan/src/bind/replay/tests.rs b/crates/metal2vulkan/src/bind/replay/tests.rs index 6f4f19a56..0b7cdafa3 100644 --- a/crates/metal2vulkan/src/bind/replay/tests.rs +++ b/crates/metal2vulkan/src/bind/replay/tests.rs @@ -340,7 +340,6 @@ fn run_preprocess_counted( PushHole::CommandRecordsAddress { offset, .. } => (offset, RECORDS), PushHole::ReplayRegionAddress { .. } => panic!("the preprocess reads no region"), PushHole::CaptureIndexAddress { .. } => panic!("the preprocess reads no index"), - PushHole::SnapshotPhase { .. } => panic!("the preprocess draws no snapshot"), PushHole::MergedDrawAddress { .. } => panic!("the preprocess draws no merged draw"), }; push[offset as usize..offset as usize + 8].copy_from_slice(&address.to_le_bytes()); diff --git a/crates/metal2vulkan/src/bind/sample_interleave.rs b/crates/metal2vulkan/src/bind/sample_interleave.rs index c41798714..fb46daaac 100644 --- a/crates/metal2vulkan/src/bind/sample_interleave.rs +++ b/crates/metal2vulkan/src/bind/sample_interleave.rs @@ -10,7 +10,7 @@ //! `x`; the runtime copies the buffer to and from that wide image with ordinary buffer-image //! copies (one per row, so any `bytesPerRow`, overlapping rows included, is exact) and moves the //! samples between it and the multisampled texture with these two crate-owned modules, each -//! through an unsigned-integer view of the texel size ([`PlanesCopy`], reused), so every texel's +//! through an unsigned-integer view of the texel size ([`PlanesCopy`]), so every texel's //! bits cross unchanged whatever the format. `n` is baked into each module, so the split is one //! per [`PlanesCopy`] and sample count, and the merge (whose fragment stage writes an unsigned //! `uvec4` whatever the attachment's format) one per sample count. @@ -29,7 +29,7 @@ //! wide image. Dispatch `ceil((width / n) / LOCAL_SIZE)`, `ceil(height / LOCAL_SIZE)`, `n` //! workgroups. //! - **The merge** ([`interleave_merge_modules`], buffer to texture): the fullscreen-triangle -//! vertex entry ([`super::sample_planes::merge_vertex_typed_module`], shared) and a `Fragment` +//! vertex entry ([`merge_vertex_typed_module`], which the depth/stencil copies share) and a `Fragment` //! entry `main` with one sampled 2D image, the wide image in [`PlanesCopy::format`], at //! [`InterleaveMergeModules::WIDE_BINDING`] of set 0. Each invocation at texel `(x, y)` sample //! `s` fetches wide texel `(x * n + s, y)` and writes it, an unsigned `uvec4`, to the color @@ -45,7 +45,6 @@ use std::sync::Arc; -use super::sample_planes::PlanesCopy; use crate::budget::{Budget, Meter}; use crate::device::requirements::Requirements; use crate::device::Device; @@ -56,9 +55,61 @@ use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; use crate::spirv::ids::{TypeId, Value}; use crate::spirv::ir::{ - BinOp, ExecMode, ExecModel, ImageOperands, ImageQuery, ImageType, ImageUsage, IoDir, MemAccess, - StorageClass, TexelMemory, Type, TypedModule, + BinOp, ConstBits, Constant, ConvOp, ExecMode, ExecModel, ImageOperands, ImageQuery, ImageType, + ImageUsage, IoDir, MemAccess, StorageClass, TexelMemory, Type, TypedModule, }; +use crate::vk::Format; + +/// The unsigned-integer format of a color format's texel size, through which the split and the +/// merge move a texel's bits unchanged (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PlanesCopy { + /// One byte: `R8_UINT`. + R8, + /// Two bytes: `R16_UINT`. + R16, + /// Four bytes: `R32_UINT`. + R32, + /// Eight bytes: `R32G32_UINT`. + Rg32, + /// Sixteen bytes: `R32G32B32A32_UINT`. + Rgba32, +} + +impl PlanesCopy { + /// Every copy format, by texel size. + pub const ALL: [PlanesCopy; 5] = [ + PlanesCopy::R8, + PlanesCopy::R16, + PlanesCopy::R32, + PlanesCopy::Rg32, + PlanesCopy::Rgba32, + ]; + + /// The Vulkan format of the copy's views, an unsigned-integer one. + pub fn format(self) -> Format { + match self { + PlanesCopy::R8 => Format::R8_UINT, + PlanesCopy::R16 => Format::R16_UINT, + PlanesCopy::R32 => Format::R32_UINT, + PlanesCopy::Rg32 => Format::R32G32_UINT, + PlanesCopy::Rgba32 => Format::R32G32B32A32_UINT, + } + } + + /// The SPIR-V image format of a storage view in [`PlanesCopy::format`]. + pub(crate) fn spirv_format(self) -> crate::spv::ImageFormat { + match self { + PlanesCopy::R8 => crate::spv::ImageFormat::R8ui, + PlanesCopy::R16 => crate::spv::ImageFormat::R16ui, + PlanesCopy::R32 => crate::spv::ImageFormat::R32ui, + PlanesCopy::Rg32 => crate::spv::ImageFormat::Rg32ui, + PlanesCopy::Rgba32 => crate::spv::ImageFormat::Rgba32ui, + } + } +} /// The crate-owned split module of one copy format and sample count on one device. #[non_exhaustive] @@ -317,18 +368,12 @@ fn finish( /// The split module of `copy` at `samples` on `device`, built, verified, serialized and /// numbered. Refused, `Unsupported` (feature `Format`) naming what the device lacks: an extended -/// copy format's storage without `shaderStorageImageExtendedFormats`; and `NotImplemented` for a -/// copy that moves no bits ([`PlanesCopy::Alpha8`], the sample planes' alone). +/// copy format's storage without `shaderStorageImageExtendedFormats`. pub fn interleave_split_module( device: &Device, copy: PlanesCopy, samples: u32, ) -> Result { - if !copy.moves_bits() { - return Err(Error::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))); - } let (spirv, requirements) = finish( device, split_typed_module(copy, samples)?, @@ -348,7 +393,7 @@ pub fn interleave_merge_modules( ) -> Result { let (vertex, vertex_needs) = finish( device, - super::sample_planes::merge_vertex_typed_module()?, + merge_vertex_typed_module()?, "interleave merge's vertex stage", )?; let (fragment, fragment_needs) = finish( @@ -366,5 +411,59 @@ pub fn interleave_merge_modules( }) } +/// The merge's vertex stage as a typed module: one triangle over the viewport, `VertexIndex` +/// 0, 1, 2 at clip positions (-1, -1), (3, -1), (-1, 3). +pub(super) fn merge_vertex_typed_module() -> BResult { + let mut b = ModuleBuilder::new(); + let i32_ = b.ty(Type::Int { + width: 32, + signed: true, + })?; + let f32_ = b.ty(Type::Float { width: 32 })?; + let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?; + let index = b.builtin(crate::spv::BuiltIn::VertexIndex, IoDir::Input, i32_)?; + let position = b.builtin(crate::spv::BuiltIn::Position, IoDir::Output, vec4)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let int = |f: &mut FunctionBuilder<'_>, v: i32| -> BResult { + let c = f.module().constant(Constant::Scalar { + ty: i32_, + bits: ConstBits(u64::from(v as u32)), + })?; + f.module().const_value(c) + }; + let float = |f: &mut FunctionBuilder<'_>, v: f32| -> BResult { + let c = f.module().constant(Constant::Scalar { + ty: f32_, + bits: ConstBits(u64::from(v.to_bits())), + })?; + f.module().const_value(c) + }; + let index = f.module().global_value(index)?; + let index = f.load(index, MemAccess::default())?; + let one = int(&mut f, 1)?; + let two = int(&mut f, 2)?; + // x = (i << 1) & 2, y = i & 2: (0, 0), (2, 0), (0, 2); the position is twice that, less 1. + let shifted = f.binary(BinOp::ShiftLeftLogical, index, one)?; + let x = f.binary(BinOp::BitwiseAnd, shifted, two)?; + let y = f.binary(BinOp::BitwiseAnd, index, two)?; + let x = f.convert(ConvOp::ConvertSToF, x, f32_)?; + let y = f.convert(ConvOp::ConvertSToF, y, f32_)?; + let twice = float(&mut f, 2.0)?; + let less = float(&mut f, 1.0)?; + let x = f.binary(BinOp::FMul, x, twice)?; + let x = f.binary(BinOp::FSub, x, less)?; + let y = f.binary(BinOp::FMul, y, twice)?; + let y = f.binary(BinOp::FSub, y, less)?; + let zero = float(&mut f, 0.0)?; + let at = f.composite_construct(vec4, &[x, y, zero, less])?; + let position = f.module().global_value(position)?; + f.store(position, at, MemAccess::default())?; + f.ret(None)?; + let id = f.finish()?; + b.entry(ExecModel::Vertex, id, Vec::new())?; + b.finalize() +} + #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/bind/sample_interleave/tests.rs b/crates/metal2vulkan/src/bind/sample_interleave/tests.rs index ea89eb0b4..6b4a6ae08 100644 --- a/crates/metal2vulkan/src/bind/sample_interleave/tests.rs +++ b/crates/metal2vulkan/src/bind/sample_interleave/tests.rs @@ -21,7 +21,7 @@ fn needs(m: TypedModule) -> Requirements { /// `shaderStorageImageExtendedFormats`, the merge's fragment stage `sampleRateShading`. #[test] fn each_module_needs_what_its_docs_say() { - for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) { + for copy in PlanesCopy::ALL { for samples in SAMPLES { let r = needs(split_typed_module(copy, samples).expect("split")); let extended = !matches!(copy, PlanesCopy::R32 | PlanesCopy::Rgba32); @@ -99,7 +99,7 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { let mut built = 0; for (name, device) in committed_devices() { let profile = device.profile(); - for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) { + for copy in PlanesCopy::ALL { for samples in SAMPLES { let fits = profile .check(&needs(split_typed_module(copy, samples).expect("split"))) @@ -116,14 +116,6 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() { } } } - // The sample planes' copy of floats moves no bits: no interleave takes it. - assert_eq!( - interleave_split_module(&device, PlanesCopy::Alpha8, 4).err(), - Some(Error::Unsupported(Unsupported::not_implemented( - Feature::Format - ))), - "{name}" - ); for samples in SAMPLES { let fits = profile .check(&needs( diff --git a/crates/metal2vulkan/src/bind/sample_planes.rs b/crates/metal2vulkan/src/bind/sample_planes.rs deleted file mode 100644 index 4ac6731f2..000000000 --- a/crates/metal2vulkan/src/bind/sample_planes.rs +++ /dev/null @@ -1,493 +0,0 @@ -//! The copies between a multisampled color attachment and its sample planes. -//! -//! On a device without multisampled storage images, the storage form of framebuffer fetch reads -//! and writes a multisampled pass's fetched attachment as sample planes -//! (`StorageAttachmentView::SamplePlanes`): a single-sample 2D-array image of one layer per sample, -//! addressed `(x, y, SampleId)`. The consumer keeps the planes and moves the samples between -//! them and the attachment around the fetching draws. These crate-owned modules are the two -//! moves, each through an unsigned-integer view of the attachment format's texel size -//! ([`PlanesCopy`]), so every texel's bits cross unchanged whatever the format; `A8_UNORM`, whose -//! class no unsigned format shares, moves through its own format's `float`s -//! ([`PlanesCopy::Alpha8`]), which keep each 8-bit code: -//! -//! - **The split** ([`planes_split_module`], one per [`PlanesCopy`]): one `GLCompute` entry `main` -//! with local size ([`PlanesSplitModule::LOCAL_SIZE`], [`PlanesSplitModule::LOCAL_SIZE`], 1) -//! and two images in set 0: -//! -//! | Binding | Image | View | -//! |---|---|---| -//! | [`PlanesSplitModule::SOURCE_BINDING`] | the multisampled attachment | a sampled 2D view of its level and layer, in [`PlanesCopy::format`] | -//! | [`PlanesSplitModule::PLANES_BINDING`] | the planes | a storage 2D-array view of every layer, in [`PlanesCopy::format`] (declared without a format for [`PlanesCopy::Alpha8`]) | -//! -//! Invocation `(x, y, s)` inside the planes' size fetches sample `s` of pixel `(x, y)` and -//! writes it to texel `(x, y)` of layer `s`. Dispatch `ceil(width / LOCAL_SIZE)`, -//! `ceil(height / LOCAL_SIZE)`, `samples` workgroups over planes of the render area's size. -//! - **The merge** ([`planes_merge_modules`]): a `Vertex` entry `main` that draws one triangle over -//! the whole viewport from `VertexIndex` 0 to 2 (no vertex input), and a `Fragment` entry `main` -//! with one sampled 2D-array image, the planes in [`PlanesCopy::format`], at -//! [`PlanesMergeModules::PLANES_BINDING`] of set 0. Each invocation fetches texel -//! `(FragCoord.xy, SampleId)` and writes it, an unsigned `uvec4` (a `vec4` for -//! [`PlanesCopy::Alpha8`]), to the color output at `Location` 0. Run at sample rate (`sampleShadingEnable`, `minSampleShading` 1) into a -//! render pass whose one color attachment is the multisampled attachment's view in -//! [`PlanesCopy::format`], over the render area, without blending: each invocation writes its -//! own sample. The fragment module reads `SampleId`, so it needs `sampleRateShading`. -//! -//! **Synchronization** (consumer): the attachment's writes before the split's sampled reads, and -//! the planes' earlier accesses before its storage writes; the planes' storage writes before -//! the fetching draws; their writes before the merge's sampled reads, and the attachment's -//! earlier accesses before the merge's color writes. - -use std::sync::Arc; - -use crate::budget::{Budget, Meter}; -use crate::device::requirements::Requirements; -use crate::device::Device; -use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported}; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{TypeId, Value}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, ExecModel, ImageOperands, ImageQuery, - ImageType, ImageUsage, IoDir, MemAccess, StorageClass, TexelMemory, Type, TypedModule, -}; -use crate::vk::Format; - -/// The unsigned-integer format of a color format's texel size, through which the split and the -/// merge move a texel's bits unchanged (the module docs). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum PlanesCopy { - /// One byte: `R8_UINT`. - R8, - /// Two bytes: `R16_UINT`. - R16, - /// Four bytes: `R32_UINT`. - R32, - /// Eight bytes: `R32G32_UINT`. - Rg32, - /// Sixteen bytes: `R32G32B32A32_UINT`. - Rgba32, - /// One byte of `A8_UNORM`'s own compatibility class ("8-bit alpha"), which no view of another - /// format reads: moved through `A8_UNORM` views as the `float` each reads, `code / 255` in - /// alpha, which its store keeps as the code. Not a bits copy ([`PlanesCopy::moves_bits`]): - /// the sample planes' copies alone take it. - Alpha8, -} - -impl PlanesCopy { - /// Every copy format, by texel size, then [`PlanesCopy::Alpha8`]. - pub const ALL: [PlanesCopy; 6] = [ - PlanesCopy::R8, - PlanesCopy::R16, - PlanesCopy::R32, - PlanesCopy::Rg32, - PlanesCopy::Rgba32, - PlanesCopy::Alpha8, - ]; - - /// The Vulkan format of the copy's views: an unsigned-integer one, or `A8_UNORM` for - /// [`PlanesCopy::Alpha8`]. - pub fn format(self) -> Format { - match self { - PlanesCopy::R8 => Format::R8_UINT, - PlanesCopy::R16 => Format::R16_UINT, - PlanesCopy::R32 => Format::R32_UINT, - PlanesCopy::Rg32 => Format::R32G32_UINT, - PlanesCopy::Rgba32 => Format::R32G32B32A32_UINT, - PlanesCopy::Alpha8 => Format::A8_UNORM, - } - } - - /// Whether the copy moves texels as their bits, through an unsigned-integer format; else as - /// the `float`s of their own format ([`PlanesCopy::Alpha8`]). - pub fn moves_bits(self) -> bool { - self != PlanesCopy::Alpha8 - } - - /// The SPIR-V image format of a storage view in [`PlanesCopy::format`]: `Unknown` for - /// [`PlanesCopy::Alpha8`], whose format no SPIR-V format names. - pub(crate) fn spirv_format(self) -> crate::spv::ImageFormat { - match self { - PlanesCopy::R8 => crate::spv::ImageFormat::R8ui, - PlanesCopy::R16 => crate::spv::ImageFormat::R16ui, - PlanesCopy::R32 => crate::spv::ImageFormat::R32ui, - PlanesCopy::Rg32 => crate::spv::ImageFormat::Rg32ui, - PlanesCopy::Rgba32 => crate::spv::ImageFormat::Rgba32ui, - PlanesCopy::Alpha8 => crate::spv::ImageFormat::Unknown, - } - } -} - -/// The crate-owned split module of one copy format on one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PlanesSplitModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device: a storage image of an extended format - /// (`shaderStorageImageExtendedFormats`) for [`PlanesCopy::R8`], [`PlanesCopy::R16`] and - /// [`PlanesCopy::Rg32`], and a storage write without a format (the SPIR-V capability - /// `StorageImageWriteWithoutFormat`, which the device resolves, `Requirements`) for - /// [`PlanesCopy::Alpha8`]. - pub requirements: Requirements, -} - -impl PlanesSplitModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The multisampled attachment, a sampled image. - pub const SOURCE_BINDING: u32 = 0; - /// The planes, a storage image. - pub const PLANES_BINDING: u32 = 1; - /// Invocations of one workgroup along x, and along y. - pub const LOCAL_SIZE: u32 = 8; -} - -/// The crate-owned merge modules of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PlanesMergeModules { - /// The vertex stage: SPIR-V 1.5 words, entry point `main`, no resources. - pub vertex: Arc<[u32]>, - /// The fragment stage: SPIR-V 1.5 words, entry point `main`, the planes at - /// [`PlanesMergeModules::PLANES_BINDING`] of set 0, the output at `Location` 0: a `uvec4`, or - /// a `vec4` for [`PlanesCopy::Alpha8`]. - pub fragment: Arc<[u32]>, - /// What the two stages need from the device: `sampleRateShading`. - pub requirements: Requirements, -} - -impl PlanesMergeModules { - /// Descriptor set of the binding. - pub const SET: u32 = 0; - /// The planes, a sampled image. - pub const PLANES_BINDING: u32 = 0; -} - -/// The binding symbol of the split's multisampled attachment in its typed module -/// ([`PlanesSplitModule::SOURCE_BINDING`]). -const SPLIT_SOURCE: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Texture, - index: 0, -}; -/// The binding symbol of the split's planes in its typed module -/// ([`PlanesSplitModule::PLANES_BINDING`]). -const SPLIT_PLANES: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Texture, - index: 1, -}; -/// The binding symbol of the merge's planes in its typed fragment module -/// ([`PlanesMergeModules::PLANES_BINDING`]). -const MERGE_PLANES: ResourceSlot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Texture, - index: 0, -}; - -/// The unsigned 32-bit scalar type. -fn u32_ty(b: &mut ModuleBuilder) -> BResult { - b.ty(Type::Int { - width: 32, - signed: false, - }) -} - -/// The scalar type of `copy`'s texels: unsigned 32-bit, or 32-bit float for a copy that does not -/// move bits ([`PlanesCopy::moves_bits`]). -fn texel_scalar(b: &mut ModuleBuilder, copy: PlanesCopy) -> BResult { - match copy.moves_bits() { - true => u32_ty(b), - false => b.ty(Type::Float { width: 32 }), - } -} - -/// A 2D image type of `copy`'s texels ([`texel_scalar`]), of `usage` and `format`, arrayed or -/// multisampled as asked. -fn copy_image( - b: &mut ModuleBuilder, - copy: PlanesCopy, - usage: ImageUsage, - format: crate::spv::ImageFormat, - arrayed: bool, - multisampled: bool, -) -> BResult { - let sampled_type = texel_scalar(b, copy)?; - b.ty(Type::Image(ImageType { - sampled_type, - dim: Dim::D2, - depth: false, - arrayed, - multisampled, - usage, - format, - })) -} - -/// The unsigned 32-bit constant `v` as a value. -fn uint(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = f.u32_const(v)?; - f.module().const_value(c) -} - -/// The split module of `copy` as a typed module, before serialization: the module -/// [`planes_split_module`] serializes. Its bindings are the symbols [`SPLIT_SOURCE`] and -/// [`SPLIT_PLANES`]. -pub fn split_typed_module(copy: PlanesCopy) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = u32_ty(&mut b)?; - let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let unknown = crate::spv::ImageFormat::Unknown; - let source_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, false, true)?; - let planes_ty = copy_image( - &mut b, - copy, - ImageUsage::Storage, - copy.spirv_format(), - true, - false, - )?; - let source = b.resource(SPLIT_SOURCE, StorageClass::UniformConstant, source_ty)?; - let planes = b.resource(SPLIT_PLANES, StorageClass::UniformConstant, planes_ty)?; - let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let invocation = f.module().global_value(invocation)?; - let invocation = f.load(invocation, MemAccess::default())?; - let planes = f.module().global_value(planes)?; - let planes = f.load(planes, MemAccess::default())?; - let size = f.query(ImageQuery::Size, planes)?; - let mut inside = None; - for axis in 0..3 { - let at = f.composite_extract(invocation, &[axis])?; - let end = f.composite_extract(size, &[axis])?; - let below = f.binary(BinOp::ULessThan, at, end)?; - inside = Some(match inside { - None => below, - Some(all) => f.binary(BinOp::LogicalAnd, all, below)?, - }); - } - let inside = inside.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?; - let source = f.module().global_value(source)?; - // Invocation `(x, y, s)` inside the planes copies sample `s` of pixel `(x, y)` into layer `s`. - let copy_sample: ArmFn<'_, ()> = Box::new(move |f, _| { - let source = f.load(source, MemAccess::default())?; - let x = f.composite_extract(invocation, &[0])?; - let y = f.composite_extract(invocation, &[1])?; - let s = f.composite_extract(invocation, &[2])?; - let pixel = f.composite_construct(uvec2, &[x, y])?; - let ops = ImageOperands { - sample: Some(s), - ..ImageOperands::default() - }; - let texel = f.fetch(source, pixel, &ops)?; - f.write( - planes, - invocation, - texel, - &ImageOperands::default(), - TexelMemory::default(), - )?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), inside, copy_sample, None)?; - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: PlanesSplitModule::LOCAL_SIZE, - y: PlanesSplitModule::LOCAL_SIZE, - z: 1, - }], - )?; - b.finalize() -} - -/// The merge's vertex stage as a typed module: one triangle over the viewport, `VertexIndex` -/// 0, 1, 2 at clip positions (-1, -1), (3, -1), (-1, 3). -pub fn merge_vertex_typed_module() -> BResult { - let mut b = ModuleBuilder::new(); - let i32_ = b.ty(Type::Int { - width: 32, - signed: true, - })?; - let f32_ = b.ty(Type::Float { width: 32 })?; - let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?; - let index = b.builtin(crate::spv::BuiltIn::VertexIndex, IoDir::Input, i32_)?; - let position = b.builtin(crate::spv::BuiltIn::Position, IoDir::Output, vec4)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let int = |f: &mut FunctionBuilder<'_>, v: i32| -> BResult { - let c = f.module().constant(Constant::Scalar { - ty: i32_, - bits: ConstBits(u64::from(v as u32)), - })?; - f.module().const_value(c) - }; - let float = |f: &mut FunctionBuilder<'_>, v: f32| -> BResult { - let c = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(u64::from(v.to_bits())), - })?; - f.module().const_value(c) - }; - let index = f.module().global_value(index)?; - let index = f.load(index, MemAccess::default())?; - let one = int(&mut f, 1)?; - let two = int(&mut f, 2)?; - // x = (i << 1) & 2, y = i & 2: (0, 0), (2, 0), (0, 2); the position is twice that, less 1. - let shifted = f.binary(BinOp::ShiftLeftLogical, index, one)?; - let x = f.binary(BinOp::BitwiseAnd, shifted, two)?; - let y = f.binary(BinOp::BitwiseAnd, index, two)?; - let x = f.convert(ConvOp::ConvertSToF, x, f32_)?; - let y = f.convert(ConvOp::ConvertSToF, y, f32_)?; - let twice = float(&mut f, 2.0)?; - let less = float(&mut f, 1.0)?; - let x = f.binary(BinOp::FMul, x, twice)?; - let x = f.binary(BinOp::FSub, x, less)?; - let y = f.binary(BinOp::FMul, y, twice)?; - let y = f.binary(BinOp::FSub, y, less)?; - let zero = float(&mut f, 0.0)?; - let at = f.composite_construct(vec4, &[x, y, zero, less])?; - let position = f.module().global_value(position)?; - f.store(position, at, MemAccess::default())?; - f.ret(None)?; - let id = f.finish()?; - b.entry(ExecModel::Vertex, id, Vec::new())?; - b.finalize() -} - -/// The merge's fragment stage of `copy` as a typed module. Its binding is the symbol -/// [`MERGE_PLANES`]. -pub fn merge_fragment_typed_module(copy: PlanesCopy) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = u32_ty(&mut b)?; - let scalar = texel_scalar(&mut b, copy)?; - let i32_ = b.ty(Type::Int { - width: 32, - signed: true, - })?; - let f32_ = b.ty(Type::Float { width: 32 })?; - let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let texel4 = b.ty(Type::Vector { - elem: scalar, - len: 4, - })?; - let unknown = crate::spv::ImageFormat::Unknown; - let planes_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, true, false)?; - let planes = b.resource(MERGE_PLANES, StorageClass::UniformConstant, planes_ty)?; - let coord = b.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)?; - let sample = b.builtin(crate::spv::BuiltIn::SampleId, IoDir::Input, i32_)?; - let output = b.fixed_io(0, IoDir::Output, texel4, false)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let coord = f.module().global_value(coord)?; - let coord = f.load(coord, MemAccess::default())?; - let sample = f.module().global_value(sample)?; - let sample = f.load(sample, MemAccess::default())?; - let layer = f.convert(ConvOp::Bitcast, sample, u32_)?; - // A pixel's center is at `(x + 0.5, y + 0.5)`: the conversion truncates to its integer. - let x = f.composite_extract(coord, &[0])?; - let y = f.composite_extract(coord, &[1])?; - let x = f.convert(ConvOp::ConvertFToU, x, u32_)?; - let y = f.convert(ConvOp::ConvertFToU, y, u32_)?; - let at = f.composite_construct(uvec3, &[x, y, layer])?; - let planes = f.module().global_value(planes)?; - let planes = f.load(planes, MemAccess::default())?; - let level = uint(&mut f, 0)?; - let ops = ImageOperands { - lod: Some(level), - ..ImageOperands::default() - }; - let texel = f.fetch(planes, at, &ops)?; - let output = f.module().global_value(output)?; - f.store(output, texel, MemAccess::default())?; - f.ret(None)?; - let id = f.finish()?; - b.entry(ExecModel::Fragment, id, vec![ExecMode::OriginUpperLeft])?; - b.finalize() -} - -/// The fixed binding numbers of the modules' symbols. -fn binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(0), - Symbol::Binding(s) if *s == SPLIT_SOURCE => Some(PlanesSplitModule::SOURCE_BINDING), - Symbol::Binding(s) if *s == SPLIT_PLANES => Some(PlanesSplitModule::PLANES_BINDING), - Symbol::Binding(s) if *s == MERGE_PLANES => Some(PlanesMergeModules::PLANES_BINDING), - _ => None, - } -} - -/// `m` verified against `device`'s profile (requirements included), serialized, and numbered -/// with the fixed bindings; `what` names it in an internal error. Refused, `Unsupported` naming -/// the first capability, where the device lacks what `m` needs. -fn finish( - device: &Device, - m: TypedModule, - what: &str, -) -> Result<(Arc<[u32]>, Requirements), Error> { - let profile = device.profile(); - profile - .check(m.requirements()) - .map_err(|c| Error::Unsupported(Unsupported::needs(Feature::FramebufferFetch, c)))?; - let mut meter = Meter::new(&Budget::default()); - crate::spirv::verify::verify(&m, profile, &mut meter)?; - let r = crate::spirv::serialize::serialize(m)?; - profile.check(&r.requirements).map_err(|c| { - Error::Internal(InternalError::new( - InternalKind::RequirementsExceedProfile, - format!("the {what} needs {c:?}"), - )) - })?; - let words = crate::spirv::serialize::relocate(&r, &binding_of)?; - Ok((words.into(), r.requirements)) -} - -/// The split module of `copy` on `device`: built with the typed builder, checked by the owned -/// verifier against the device's profile (requirements included), serialized, and numbered with -/// the fixed bindings of [`PlanesSplitModule`]. Refused, `Unsupported` (feature -/// `FramebufferFetch`) naming what the device lacks, where it lacks what the split needs: an -/// extended copy format's storage without `shaderStorageImageExtendedFormats`. -pub fn planes_split_module(device: &Device, copy: PlanesCopy) -> Result { - let (spirv, requirements) = finish(device, split_typed_module(copy)?, "planes split")?; - Ok(PlanesSplitModule { - spirv, - requirements, - }) -} - -/// The merge modules of `copy` on `device`, built and checked as [`planes_split_module`] is; -/// refused likewise where the device lacks `sampleRateShading`. Every bits copy -/// ([`PlanesCopy::moves_bits`]) takes the same modules. -pub fn planes_merge_modules( - device: &Device, - copy: PlanesCopy, -) -> Result { - let (vertex, vertex_needs) = finish( - device, - merge_vertex_typed_module()?, - "planes merge's vertex stage", - )?; - let (fragment, fragment_needs) = - finish(device, merge_fragment_typed_module(copy)?, "planes merge")?; - let requirements = device - .profile() - .union_requirements(&vertex_needs, &fragment_needs); - Ok(PlanesMergeModules { - vertex, - fragment, - requirements, - }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/sample_planes/tests.rs b/crates/metal2vulkan/src/bind/sample_planes/tests.rs deleted file mode 100644 index c2322a0ed..000000000 --- a/crates/metal2vulkan/src/bind/sample_planes/tests.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! The sample planes' copy modules: what each needs, valid on every committed profile that has -//! it (L3, `G-val`), refused on a device that does not. - -use super::*; -use crate::device::requirements::VkFeature; -use crate::device::{DeviceDescription, DevicePolicy}; -use crate::spirv::testing::assert_valid; -use std::path::PathBuf; - -/// The requirements of `m` as serialized. -fn needs(m: TypedModule) -> Requirements { - crate::spirv::serialize::serialize(m) - .expect("serialize") - .requirements -} - -/// Each module needs exactly what the module docs say: the split of an extended storage format -/// `shaderStorageImageExtendedFormats`, the split of `A8_UNORM`'s planes a storage write without a -/// format (the capability, which the device resolves), the merge's fragment stage -/// `sampleRateShading`, and nothing else of the device. -#[test] -fn each_module_needs_what_its_docs_say() { - let write_without = crate::device::requirements::SpirvCapability::of( - crate::spv::Capability::StorageImageWriteWithoutFormat, - ); - for copy in PlanesCopy::ALL { - let r = needs(split_typed_module(copy).expect("split")); - let extended = matches!(copy, PlanesCopy::R8 | PlanesCopy::R16 | PlanesCopy::Rg32); - assert_eq!( - r.features - .contains(&VkFeature::ShaderStorageImageExtendedFormats), - extended, - "{copy:?}: {r:?}" - ); - assert_eq!( - r.spirv_capabilities.contains(&write_without), - !copy.moves_bits(), - "{copy:?}: {r:?}" - ); - assert!( - !r.features.contains(&VkFeature::SampleRateShading), - "{copy:?}" - ); - let r = needs(merge_fragment_typed_module(copy).expect("fragment")); - assert!(r.features.contains(&VkFeature::SampleRateShading), "{r:?}"); - } - let r = needs(merge_vertex_typed_module().expect("vertex")); - assert!(r.features.is_empty(), "{r:?}"); -} - -/// Every committed device (`validation/profiles/*.json`), derived with the resident-table domains, -/// by file stem. -fn committed_devices() -> Vec<(String, Device)> { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); - let mut out = Vec::new(); - for entry in std::fs::read_dir(&dir).expect("profiles") { - let path = entry.expect("entry").path(); - if path.extension().is_none_or(|x| x != "json") { - continue; - } - let stem = path - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - let text = std::fs::read_to_string(&path).expect("read"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let device = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - out.push((stem, device)); - } - out.sort_by(|a, b| a.0.cmp(&b.0)); - out -} - -/// On every committed device each module is valid where the device has what it needs, numbered -/// with the fixed bindings, and refused (`Unsupported`) where it does not, never given as words -/// it cannot run. -#[test] -fn the_modules_are_valid_where_the_device_has_what_they_need() { - let mut built = 0; - for (name, device) in committed_devices() { - let profile = device.profile(); - for copy in PlanesCopy::ALL { - let fits = profile - .check(&needs(split_typed_module(copy).expect("split"))) - .is_ok(); - match planes_split_module(&device, copy) { - Ok(module) => { - assert!(fits, "{name} {copy:?}"); - assert_valid(split_typed_module(copy).expect("split"), profile); - assert!(!module.spirv.is_empty()); - built += 1; - } - Err(Error::Unsupported(_)) => assert!(!fits, "{name} {copy:?}"), - Err(other) => panic!("{name} {copy:?}: {other}"), - } - } - for copy in [PlanesCopy::R32, PlanesCopy::Alpha8] { - let fragment = || merge_fragment_typed_module(copy).expect("fragment"); - let fits = profile.check(&needs(fragment())).is_ok(); - match planes_merge_modules(&device, copy) { - Ok(modules) => { - assert!(fits, "{name} {copy:?}"); - assert_valid(merge_vertex_typed_module().expect("vertex"), profile); - assert_valid(fragment(), profile); - assert!(!modules.vertex.is_empty() && !modules.fragment.is_empty()); - } - Err(Error::Unsupported(_)) => assert!(!fits, "{name} {copy:?}"), - Err(other) => panic!("{name} {copy:?}: {other}"), - } - } - } - assert!(built > 0); -} diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index a7aab9ee6..273e2ad99 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -263,33 +263,6 @@ pub struct BindState { /// the whole set. #[cfg_attr(feature = "serde", serde(default))] pub resident_apart: bool, - /// The color attachments the draw's render pass instance leaves out of its subpass, read and - /// written as storage images in the pixel interlock by its other draws, that the draw's - /// render pipeline does not itself read or write so: a fragment function that writes one of - /// them through its first output runs the variant that writes it through the interlocked - /// storage form, so the draw records in that instance. Its variant is part of the shape - /// (`BindShape::interlocked_colors`); empty for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub interlocked_colors: BTreeSet, - /// The fragment texture slots the consumer reads through a snapshot, by Metal index: a draw - /// that reads a texture its render pass renders, where the consumer draws it twice, first - /// taking each fragment's texel into the slot's snapshot with every color write mask zero, - /// then with the pipeline's masks reading the snapshot. The plan keeps a slot only where the - /// draw's pipeline can (the module docs of `bind::graphics`) and runs the variant that reads - /// it so (`VariantKey::snapshot_textures`); `BindingPlan::variant`'s `snapshot_textures` says - /// which it kept, and the consumer serves every other read as it would without it. Part of the - /// shape (`BindShape::snapshot_textures`); empty for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub snapshot_textures: BTreeSet, - /// What the draw's depth and stencil tests can do to its fragments ([`FragmentTests::of`]), - /// which decides whether a fragment function that stores a color through the interlocked - /// storage form before the tests (`RuntimeFact::TestedStorageWrites`) stores what Metal - /// stores: its plan runs it as compiled, asks for the variant that declares early tests, or - /// refuses the draw. Its default, [`FragmentTests::Any`], refuses such a draw; the consumer - /// states it for a draw of such a pipeline, and may leave it for every other, whose plan does - /// not read it. Part of the shape (`BindShape::fragment_tests`). - #[cfg_attr(feature = "serde", serde(default))] - pub fragment_tests: FragmentTests, /// The render encoder's blend color (`setBlendColorRed:green:blue:alpha:`; Metal's default /// `[0, 0, 0, 0]` where the encoder never set it), red first: a fragment function that /// computes a blend in the shader under a blend that reads it takes it as push data @@ -307,104 +280,6 @@ pub struct BindState { pub alpha_test_reference: Option, } -/// What a draw's depth and stencil tests can do to its fragments (`BindState::fragment_tests`). -/// Metal tests a fragment after its function runs, unless the function declares -/// `[[early_fragment_tests]]`: a function that writes a color attachment through the interlocked -/// storage form stores inside the shader, so where it discards, and so cannot be tested early -/// whatever the draw's state, whether its store is Metal's is the draw's tests' to decide. -/// -/// Where the tests drop fragments and write, such a draw is refused: [`FragmentTests::Depth`] and -/// [`FragmentTests::Stencil`] name the test that acts, and so the attachment the refusal names. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum FragmentTests { - /// The tests may drop a fragment and the encoder counts the fragments that pass them (a - /// visibility result mode is set); or the draw does not state them. Such a draw of a function - /// that stores before the tests is refused `NotImplemented(FramebufferFetch)`: a store before - /// them would keep what they drop, and early tests would count what the function then - /// discards. (A draw whose tests write but count nothing is [`FragmentTests::Depth`] or - /// [`FragmentTests::Stencil`].) - #[default] - Any, - /// The tests may drop a fragment, but write neither the depth nor the stencil attachment, and - /// the encoder counts nothing: early tests drop the fragments Metal's later tests drop and - /// leave the attachments as Metal's do, so such a draw runs the variant that declares them - /// (`VariantKey::read_only_tests`). (A function that may not declare them, since it writes - /// other memory or returns depth, is refused at the tested attachment.) - Drop, - /// No test can drop a fragment: a store before the tests is the store Metal makes after - /// them, so such a draw runs the pipeline as compiled. - Pass, - /// Only the depth test can drop a fragment, and it writes the depth attachment where - /// `writes`; the stencil test can neither drop nor write, and the encoder counts nothing. - /// Such a draw of a function that stores before the tests is refused - /// `NotImplemented(FramebufferFetch)` at the depth attachment, unless it writes nothing and - /// the function has the variant that declares early tests, which it runs, as - /// [`FragmentTests::Drop`]. - Depth { writes: bool }, - /// The stencil test can drop a fragment or write the stencil attachment, and some test - /// writes its attachment (the stencil test's operations, or the depth test's writes; where - /// none does, the tests are [`FragmentTests::Drop`]); the encoder counts nothing. Such a draw - /// of a function that stores before the tests is refused `NotImplemented(FramebufferFetch)` - /// at the stencil attachment. - Stencil, -} - -impl FragmentTests { - /// The tests of `depth_stencil` in a pass with a depth attachment where `depth` and a - /// stencil attachment where `stencil`, the encoder counting the fragments that pass them - /// where `counted`: a test of an attachment the pass lacks does nothing. Depth drops a - /// fragment unless it compares `Always`, and writes where its writes are enabled; a stencil - /// face drops one unless it compares `Always`, and writes where its write mask has a bit set - /// and an operation that can apply is not `Keep` (the stencil failure operation where it - /// can fail, the depth failure operation where depth can, and the pass operation). - pub fn of( - depth_stencil: &metal::state::DepthStencilDescriptor, - depth: bool, - stencil: bool, - counted: bool, - ) -> FragmentTests { - use metal::{CompareFunction, StencilOperation}; - let depth_drops = depth && depth_stencil.depth_compare_function != CompareFunction::Always; - let faces = [ - &depth_stencil.front_face_stencil, - &depth_stencil.back_face_stencil, - ]; - let stencil_drops = stencil - && faces - .iter() - .any(|f| f.stencil_compare_function != CompareFunction::Always); - if !depth_drops && !stencil_drops { - return FragmentTests::Pass; - } - let depth_writes = depth && depth_stencil.depth_write_enabled; - let stencil_writes = stencil - && faces.iter().any(|f| { - let fails = f.stencil_compare_function != CompareFunction::Always; - let applies = [ - (fails, f.stencil_failure_operation), - (depth_drops, f.depth_failure_operation), - (true, f.depth_stencil_pass_operation), - ]; - f.write_mask != 0 - && applies - .iter() - .any(|&(can, op)| can && op != StencilOperation::Keep) - }); - if !stencil_drops && !stencil_writes && !counted { - return FragmentTests::Depth { - writes: depth_writes, - }; - } - match (counted, depth_writes || stencil_writes) { - (true, _) => FragmentTests::Any, - (false, true) => FragmentTests::Stencil, - (false, false) => FragmentTests::Drop, - } - } -} - /// Where a command's heap arrays (set 1) hold its heap members and its argument samplers. A plan /// writes member `i` of every image array, and listed argument sampler `i` of every sampler array, /// at its planned element `i + 1` (element 0 is each array's neutral); the command's handle and @@ -587,9 +462,6 @@ impl BindState { depth_clamp_range: self.depth_clamp_range.is_some(), rotated_weights: self.rotated_weights, line_band: self.line_band.map(|(primitive, _)| primitive), - interlocked_colors: self.interlocked_colors.clone(), - fragment_tests: self.fragment_tests, - snapshot_textures: self.snapshot_textures.clone(), primitive_id_indices: self.primitive_id_indices, quad_primitive_ids: self.quad_primitive_ids, private_list: self.private_list, @@ -672,9 +544,6 @@ impl BindState { depth_clamp_range, rotated_weights, line_band, - interlocked_colors, - fragment_tests, - snapshot_textures, primitive_id_indices, quad_primitive_ids, private_list, @@ -700,9 +569,6 @@ impl BindState { && self.depth_clamp_range.is_some() == *depth_clamp_range && self.rotated_weights == *rotated_weights && self.line_band.map(|(primitive, _)| primitive) == *line_band - && self.interlocked_colors == *interlocked_colors - && self.fragment_tests == *fragment_tests - && self.snapshot_textures == *snapshot_textures && self.primitive_id_indices == *primitive_id_indices && self.quad_primitive_ids == *quad_primitive_ids && self.private_list == *private_list @@ -1666,19 +1532,6 @@ pub struct BindShape { /// triangles' edges, so (`VariantKey::line_band`). #[cfg_attr(feature = "serde", serde(default))] pub line_band: Option, - /// `BindState.interlocked_colors`: the variant whose fragment function writes those it writes - /// through the interlocked storage form (`VariantKey::interlocked_colors`). - #[cfg_attr(feature = "serde", serde(default))] - pub interlocked_colors: BTreeSet, - /// `BindState.fragment_tests`: whether a fragment function that stores before the tests runs - /// as compiled, runs the variant that declares early tests (`VariantKey::read_only_tests`), - /// or is refused. - #[cfg_attr(feature = "serde", serde(default))] - pub fragment_tests: FragmentTests, - /// `BindState.snapshot_textures`: the variant whose fragment function reads those of them - /// the pipeline can read through a snapshot so (`VariantKey::snapshot_textures`). - #[cfg_attr(feature = "serde", serde(default))] - pub snapshot_textures: BTreeSet, /// `BindState.primitive_id_indices`: the primitive ID's de-indexed variant of an indexed /// draw's index type (`VariantKey::primitive_id_indices`), where the pipeline writes the ID. #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 5e9dc8aa9..16b956f04 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -40,16 +40,14 @@ use crate::pipeline::artifact::{ use crate::pipeline::descriptor::TessellationDescriptor; use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice}; use crate::pipeline::graphics::{ - BandPrimitive, BlendState, ColorAttachmentState, FragmentImageblock, GraphicsState, - ImageblockMechanism, InputAttachmentUse, LineBandState, ShadowStencilUse, StorageAttachmentUse, - StorageAttachmentView, TessellationState, + BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse, + LineBandState, TessellationState, }; use crate::pipeline::interface::{ AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, - SampledLevels, SamplerArray, SamplerSlot, SlotInterface, SnapshotRefusal, StageDescriptor, - StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, - Window, + SampledLevels, SamplerArray, SamplerSlot, SlotInterface, StageDescriptor, StageInterface, + StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, Window, }; use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -849,7 +847,6 @@ codec_enum! { SyntheticBinding { ArgumentTable, ExecutionStatus, RootTable, HandleTable, ConstantBlob, TessellationFactors, Imageblock, SamplerTable, - ShadowStencil, FunctionTableDirectory, PatchIndices, ControlPointIndices, @@ -860,7 +857,6 @@ codec_enum! { Buffer, Texture, Sampler, Heap(f0), Synthetic(f0), InputAttachment(f0), CombinedTextureSampler(f0), HeapSampler(f0), AccelerationStructure(f0), TileAttachment(f0), TileMap, SeparateTexture(f0), SeparateSampler(f0), - SnapshotTexels(f0), YCbCrPlanes(f0), SamplerArray { compare, integer }, } @@ -882,17 +878,15 @@ codec_enum! { SlotBindOffset(f0), SlotGuestBase(f0), VertexBufferStride(f0), StageInRegion, TessellationFactorOffset, TessellationFactorInstanceStride, TessellationFactorScale, TextureLevels(f0), InstanceCount(f0), CommandRecordsAddress, ReplayRegionAddress, - ShadowStencilState, IndexCapacity, ViewportCount, RenderTargetArrayLength, + IndexCapacity, ViewportCount, RenderTargetArrayLength, PatchIndexOffset, PatchIndexBound, ControlPointIndexOffset, StageInStride(f0), AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset, DepthClampRange, CaptureLayout, CaptureIndexAddress, - StorageKeptChannels, TextureIntegerChannels(f0), BicubicTexels(f0), HalfBlendColor, - SnapshotPhase, VerticesPerPrimitive, MergedDrawAddress, AlphaTestReference, @@ -1122,7 +1116,7 @@ codec_struct! { stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation, needs_handle_translation, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures, reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, - numbered_samplers, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads, + numbered_samplers, own_pixel_textures, level_reads, private_bytes, sampler_arrays, } SamplerArray { slot, samplers } @@ -1168,10 +1162,6 @@ codec_enum! { TypeDetail { Plain, Struct(f0), Array(f0), TextureReference(f0), Pointer(f0) } SlotInterface { Buffer(f0), Texture(f0), Sampler(f0) } NumberedSampler { Constexpr(f0), Read, Write } - SnapshotRefusal { - Branch, Derivative, Sample, GroupOperation, Store, Atomic, ImageWrite, UndefinedOperand, - WritesMemory, Interlock, Coherent, Other, - } PatchDomain { Triangle, Quad } Window { Bounded { start, len }, Whole } BufferForm { Descriptor(f0), Psb } @@ -1230,7 +1220,6 @@ codec_enum! { RenderTargetArrayLength { layer_dropped }, StageInRegion, StageInStride { layout }, UniformViewRange { slot, choice }, UniformViewAliasing { slot }, - FragmentImageblock { words, writes, master, data_size, alignment }, TileFunction, TileAttachmentFormat { color, format }, StorageTextureNumericType { slot }, OutOfBoundsAlpha { slot }, @@ -1239,8 +1228,6 @@ codec_enum! { StorageTextureLevelViews { slot }, SparseTexture { slot, sparse_arm, tile_map }, AccelerationStructureInstanceCount { slot }, - InterlockedFramebufferFetch { color, format, writes, early_tests, kept, blend, rounded }, - ShadowStencil { formatless, multisampled }, PredicationVote, SrgbTexture { slot }, UlongAtomicView { slot }, ViewportCount, @@ -1265,7 +1252,6 @@ codec_enum! { RotatedWeights, ConstantLanes { slot }, FunctionTableRange { addressed }, - TestedStorageWrites { early_tests, early_variant }, TileThreadgroup { tile_sized }, ConstexprSampled { slot, modes }, CubicSampler { slot }, @@ -1281,7 +1267,6 @@ codec_enum! { HeapStorageReads { stage, class }, AnisotropicSampler { slot }, StorageTextureIntegerChannels { slot }, - MovableStorageWrites { early_variant }, ObjectThreadgroupArena { static_bytes, payload }, MergedDraws, QuadPrimitiveIds, @@ -1351,7 +1336,7 @@ codec_struct! { StageModule { stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags, reconvergence, precision_notes, strategies, constant_blob, rounded_colors, - specialized_notes, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads, + specialized_notes, own_pixel_textures, level_reads, private_bytes, stats, } SpecializedNote { note, when } @@ -1386,22 +1371,18 @@ codec_struct! { 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, - tessellation, fragment_imageblock, vertex_writes_memory, writes_viewport_index, - storage_attachments, shadow_stencil, writes_point_size, writes_depth, + 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, snapshot_reads, logic_op, line_band, + sample_mask, logic_op, line_band, } TessellationState { patch_control_points, domain, control_points, factor_step_function, push_offset, control_point_index_type, } LineBandState { push_offset, primitive } - FragmentImageblock { mechanism, words, master, data_size, alignment } ColorAttachmentState { format, write_mask, blend } BlendState { src_color, dst_color, color_op, src_alpha, dst_alpha, alpha_op } InputAttachmentUse { color_index, input_attachment_index, format_class } - StorageAttachmentUse { color_index, format, writes, formatless, view, view_alias, kept } - ShadowStencilUse { format, formatless, samples } } codec_enum! { @@ -1409,8 +1390,6 @@ codec_enum! { LinkedUseGap { EndlessLoop, StackMemory, GatedOffMeshBuiltin, UnmeasuredColorWrite } SlotWritability { Never, Maybe, Unknown(f0) } SlotWriteGap { UnresolvedIndex, UnmeasuredPayloadStage, MemberRole } - ImageblockMechanism { StorageImageInterlock } - StorageAttachmentView { Attachment, SamplePlanes { layers } } BandPrimitive { Lines, Triangles } PrecisionNote { F16FmaDoubleRounding, F16IntConvDoubleRounding, GradFromBias, @@ -1467,7 +1446,6 @@ codec_enum! { UnmeasuredGroupSpeculation, DeviceSampleLevel, CoverageReadsRoundedAlpha, - UnmeasuredFetchBlend, DeviceVertexConversion, DeviceAlphaCoverage, DeviceInterpolationOffset, @@ -1495,7 +1473,6 @@ codec_enum! { Synthetic { stage, binding }, Heap(f0), InputAttachment(f0), HeapSampler { stage, sampler }, AccelerationStructure { slot, level }, TileAttachment(f0), TileMap(f0), SeparateTexture { texture, sampler }, SeparateSampler { stage, sampler }, - SnapshotTexels(f0), YCbCrPlanes(f0), SamplerArray { stage, compare, integer }, IdentityArray, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index e0643bd7f..154bcc7a2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -36,7 +36,7 @@ use std::fmt; pub use crate::air::container::Hash256; use crate::device::Device; use crate::pipeline::lower_inputs::StorageImageChoice; -use crate::pipeline::sym::{SlotRef, SnapshotForm}; +use crate::pipeline::sym::SlotRef; use crate::vk; mod artifacts; @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2254; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 586; +pub const ARTIFACT_FORMAT_VERSION: u32 = 587; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle @@ -196,19 +196,6 @@ pub struct VariantKey { /// states it. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, - /// Fragment texture slots the draw reads through a snapshot an earlier draw of the same - /// primitives took (`LoweringInputs::snapshot_textures`), each with the form the snapshot - /// keeps its texels in (`SnapshotForm::of` the slot's bound view): the slots - /// `BindShape::snapshot_textures` names, each one of the fragment stage's - /// `StageInterface::snapshot_textures`. The plan of a pipeline compiled under it states it, - /// and binds each slot's snapshot (`WriteSource::SnapshotTexels`, an image of the form's - /// `SnapshotForm::format`) and leaves which of its draws runs to the consumer - /// (`PushHole::SnapshotPhase`). - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub snapshot_textures: BTreeMap, /// Texture slots whose function reads the two-plane YCbCr texture the shape binds there in /// place: every slot of a `RuntimeFact::YCbCrInPlace` the shape binds a texture whose planes /// are read so (`TextureShape::Texture::ycbcr_in_place`). Each such slot binds the planes' @@ -376,24 +363,6 @@ pub struct VariantKey { /// (`FunctionTablesShape::bytes_class`). The plan of a pipeline compiled under it states it. #[cfg_attr(feature = "serde", serde(default))] pub addressed_function_tables: bool, - /// Color attachments the draw's render pass instance leaves out of its subpass, which its - /// draws read and write as storage images in the pixel interlock, that the fragment function - /// writes through its first output (`BindShape::interlocked_colors`): the variant's function - /// writes each through the interlocked storage form, as a function that fetches the color - /// writes it, so the draw records in that instance. Not a lowering input of its own: the render - /// pipeline's compile adds the colors to the fragment function's - /// `LoweringInputs::framebuffer_fetch`, whose exactness conditions refuse what the form does - /// not keep Metal's (a blend, among others). - #[cfg_attr(feature = "serde", serde(default))] - pub interlocked_colors: BTreeSet, - /// The draw's depth and stencil tests may drop fragments but write neither attachment and - /// count no visibility result (`BindShape::fragment_tests`), and the fragment function stores - /// a color through the interlocked storage form before the tests - /// (`RuntimeFact::TestedStorageWrites`): the variant whose function declares early fragment - /// tests (`LoweringInputs::read_only_tests`). The plan of a pipeline compiled under it states - /// it. - #[cfg_attr(feature = "serde", serde(default))] - pub read_only_tests: bool, /// The runtime sampler slots of a `RuntimeFact::CubicSampler` that the shape binds to a /// sampler whose min or mag filter is `Cubic`, each with the bound word masked by /// `SamplerWord::CUBIC_STATE` (`LoweringInputs::cubic_samplers`): the variant whose function @@ -535,7 +504,6 @@ impl VariantKey { && self.unit_axes == 0 && self.storage_view_slots.is_empty() && self.srgb_textures.is_empty() - && self.snapshot_textures.is_empty() && self.ycbcr_in_place.is_empty() && self.ycbcr_planes_sampled.is_empty() && self.texel_rows.is_empty() @@ -557,8 +525,6 @@ impl VariantKey { && self.line_band.is_none() && self.swizzled_storage.is_empty() && !self.addressed_function_tables - && self.interlocked_colors.is_empty() - && !self.read_only_tests && self.cubic_samplers.is_empty() && self.primitive_id_indices.is_none() && !self.quad_primitive_ids @@ -643,12 +609,6 @@ impl VariantKey { .filter(|s| s.stage == stage) .copied() .collect(); - out.snapshot_textures = self - .snapshot_textures - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, form)| (*s, *form)) - .collect(); out.ycbcr_in_place = self .ycbcr_in_place .iter() @@ -720,7 +680,6 @@ impl VariantKey { out.dropped_colors = self.dropped_colors.clone(); out.depth_clamp_range = self.depth_clamp_range; out.rotated_weights = self.rotated_weights; - out.read_only_tests = self.read_only_tests; } out.primitive_id_indices = self .primitive_id_indices diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index 38e28a5f6..e9774d597 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -537,31 +537,6 @@ fn the_version_190_members_round_trip() { assert_eq!(decode::(&encode(&fact)), Ok(fact)); } -/// The fields format version 193 adds encode and decode with the fact and the pipeline state that -/// carry them: `RuntimeFact::FragmentImageblock`'s and `FragmentImageblock`'s `data_size` and -/// `alignment`. -#[test] -fn the_version_193_fields_round_trip() { - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::{FragmentImageblock, ImageblockMechanism}; - let fact = RuntimeFact::FragmentImageblock { - words: 3, - writes: true, - master: [5; 32], - data_size: 11, - alignment: 2, - }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); - let state = FragmentImageblock { - mechanism: ImageblockMechanism::StorageImageInterlock, - words: 8, - master: [6; 32], - data_size: 32, - alignment: 16, - }; - assert_eq!(decode::(&encode(&state)), Ok(state)); -} - /// The members format version 187 appends encode and decode, and each decodes as itself: /// `PushField::ViewportCount`, `RuntimeFact::ViewportCount`, and `IoRole::ViewportIndex`. #[test] @@ -786,8 +761,7 @@ fn the_version_535_member_round_trips() { /// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and /// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and -/// `CombinedSampler`, `RuntimeFact::InterlockedFramebufferFetch` and -/// `GraphicsState::storage_attachments`, `RuntimeFact::SrgbTexture` and +/// `CombinedSampler`, `RuntimeFact::SrgbTexture` and /// `SrgbTexture`, and `PrecisionNote::HalfTexelConversion`, /// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`, /// `HandleClass::Sampler { compare, integer }` and @@ -797,7 +771,6 @@ fn the_version_535_member_round_trips() { fn the_merged_members_round_trip_in_one_render_pipeline() { use crate::pipeline::artifact::{PrecisionNote, RuntimeDependency, SpecConstant}; use crate::pipeline::facts::{Mechanism, RuntimeFact}; - use crate::pipeline::graphics::StorageAttachmentUse; use crate::pipeline::layout::{BindingSource, DescriptorBinding, DescriptorSetLayout}; use crate::pipeline::sym::{ CombinedSampler, HandleClass, ResourceKind, SamplerRef, SpecKey, SyntheticBinding, @@ -904,34 +877,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { if let Some(last) = p.layout.sets.last_mut() { last.bindings.extend(argument_samplers); } - p.graphics.storage_attachments.push(StorageAttachmentUse { - color_index: 0, - format: vk::Format::R8G8B8A8_UNORM, - writes: true, - formatless: false, - view: crate::pipeline::StorageAttachmentView::SamplePlanes { layers: 4 }, - view_alias: Some(vk::Format::R32_UINT), - kept: vk::ColorComponentFlags::B, - }); - p.dependencies.push(RuntimeDependency { - fact: RuntimeFact::InterlockedFramebufferFetch { - color: 0, - format: vk::Format::R8G8B8A8_UNORM, - writes: true, - early_tests: true, - kept: vk::ColorComponentFlags::A, - blend: Some(crate::pipeline::lower_inputs::BlendEquation { - source_rgb: crate::metal::BlendFactor::One, - destination_rgb: crate::metal::BlendFactor::OneMinusSourceAlpha, - rgb_operation: crate::metal::BlendOperation::Add, - source_alpha: crate::metal::BlendFactor::One, - destination_alpha: crate::metal::BlendFactor::Zero, - alpha_operation: crate::metal::BlendOperation::Add, - }), - rounded: true, - }, - mechanism: Mechanism::RenderPassContract, - }); p.dependencies.push(RuntimeDependency { fact: RuntimeFact::SrgbTexture { slot: texture }, mechanism: Mechanism::Variant, @@ -984,14 +929,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { sealed.dependencies.iter().any(|d| d.fact == fact), "{fact:?}" ); - assert_eq!(sealed.graphics.storage_attachments.len(), 1); - assert!(sealed.dependencies.iter().any(|d| matches!( - d.fact, - RuntimeFact::InterlockedFramebufferFetch { - early_tests: true, - .. - } - ))); assert!(sealed.dependencies.iter().any(|d| d.fact == ulong_view)); } diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index cb3320fff..249e69204 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -86,8 +86,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::UniformViewRange { .. } => Mechanism::Variant, // Instantiation compares the bound Metal addresses. RuntimeFact::UniformViewAliasing { .. } => Mechanism::PlanTimeCheck, - // The pass's imageblock storage image, bound to every draw of the pass. - RuntimeFact::FragmentImageblock { .. } => Mechanism::RenderPassContract, // The render area is specialized; the planner refuses a layered pass. RuntimeFact::TileFunction => Mechanism::Specialization, // Compiled in under the function's key; the tile pipeline checks its descriptor. @@ -117,12 +115,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { } => Mechanism::PlanTimeCheck, // The binder writes the bound structure's instance count per dispatch or draw. RuntimeFact::AccelerationStructureInstanceCount { .. } => Mechanism::PushConstant, - // The consumer binds the attachment as a storage image outside the subpass's color - // attachments (`GraphicsState::storage_attachments`). - RuntimeFact::InterlockedFramebufferFetch { .. } => Mechanism::RenderPassContract, - // The consumer keeps the stencil's shadow and binds it, with the encoder's stencil state - // as push data (`GraphicsState::shadow_stencil`). - RuntimeFact::ShadowStencil { .. } => Mechanism::RenderPassContract, // The vote word is fixed in the module; the planner counts it against the limit. RuntimeFact::PredicationVote => Mechanism::PlanTimeCheck, // The binder pushes the bound format's class, which selects its conversion. @@ -209,13 +201,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { BufferAccess::Addressed => Mechanism::Variant, BufferAccess::Floor => Mechanism::PlanTimeCheck, }, - // A separate compile that declares early tests, which a draw whose tests drop fragments - // but write and count nothing asks for; the planner refuses a draw whose tests may write - // or count. - RuntimeFact::TestedStorageWrites { .. } => Mechanism::Variant, - // The tests a draw that moves the function's color into the interlocked storage form - // selects: that variant's. - RuntimeFact::MovableStorageWrites { .. } => Mechanism::Variant, // The binder's regions carry the tile as Metal's threadgroup; the tile pipeline checks its // descriptor's flag. RuntimeFact::TileThreadgroup { .. } => Mechanism::RegionSelected, diff --git a/crates/metal2vulkan/src/device/metal.rs b/crates/metal2vulkan/src/device/metal.rs index 5851eaf60..2d6fb1a5e 100644 --- a/crates/metal2vulkan/src/device/metal.rs +++ b/crates/metal2vulkan/src/device/metal.rs @@ -264,9 +264,8 @@ fn unsupported_features(profile: &DeviceProfile) -> Vec { ], )); } - // Framebuffer fetch refuses on no device: ordered by rasterization-order access, by the pixel - // interlock's storage form, or, with neither, through input attachments ordered between draws - // (`PrecisionNote::UnorderedFetchWithinDraw`). + // Framebuffer fetch refuses on no device: ordered by rasterization-order access, or without + // it through 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/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index df2ae3db3..b5b0841d2 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -313,8 +313,7 @@ pub enum VkFeature { /// `VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`, the image usage /// `VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT` and the pipeline flag /// `VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`, under which a draw samples a - /// color attachment of its own subpass (a feedback loop). A render pipeline that reads a - /// texture its pass renders through a snapshot requires it. + /// color attachment of its own subpass (a feedback loop). AttachmentFeedbackLoopLayout, /// `VK_EXT_extended_dynamic_state3`'s `extendedDynamicState3ColorWriteMask`: the dynamic /// state `VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`, set by `vkCmdSetColorWriteMaskEXT`. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 1606477f9..1ecfe05d4 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -75,13 +75,6 @@ fn every_fact() -> Vec { choice: UniformViewChoice::Kept, }, RuntimeFact::UniformViewAliasing { slot }, - RuntimeFact::FragmentImageblock { - words: 4, - writes: true, - master: [7; 32], - data_size: 16, - alignment: 16, - }, RuntimeFact::TileFunction, RuntimeFact::TileAttachmentFormat { color: 1, @@ -109,19 +102,6 @@ fn every_fact() -> Vec { tile_map: false, }, RuntimeFact::AccelerationStructureInstanceCount { slot }, - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - format: crate::vk::Format::R32G32B32A32_SFLOAT, - writes: true, - early_tests: true, - kept: crate::vk::ColorComponentFlags::empty(), - blend: None, - rounded: false, - }, - RuntimeFact::ShadowStencil { - formatless: false, - multisampled: false, - }, RuntimeFact::PredicationVote, RuntimeFact::SrgbTexture { slot }, RuntimeFact::UlongAtomicView { slot }, @@ -176,10 +156,6 @@ fn every_fact() -> Vec { RuntimeFact::DepthClampRange, RuntimeFact::ConstantLanes { slot }, RuntimeFact::FunctionTableRange { addressed: false }, - RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant: true, - }, RuntimeFact::TileThreadgroup { tile_sized: true }, RuntimeFact::ConstexprSampled { slot, @@ -262,9 +238,6 @@ fn every_fact() -> Vec { index: 0, }, }, - RuntimeFact::MovableStorageWrites { - early_variant: true, - }, RuntimeFact::ObjectThreadgroupArena { static_bytes: 16, payload: Some(64), @@ -311,76 +284,71 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::StageInStride { .. } => 27, RuntimeFact::UniformViewRange { .. } => 28, RuntimeFact::UniformViewAliasing { .. } => 29, - RuntimeFact::FragmentImageblock { .. } => 30, - RuntimeFact::TileFunction => 31, - RuntimeFact::TileAttachmentFormat { .. } => 32, - RuntimeFact::StorageTextureNumericType { .. } => 33, - RuntimeFact::OutOfBoundsAlpha { .. } => 34, - RuntimeFact::BicubicTexels { .. } => 35, - RuntimeFact::StorageTextureLevels { .. } => 36, - RuntimeFact::StorageTextureLevelViews { .. } => 37, - RuntimeFact::SparseTexture { .. } => 38, - RuntimeFact::AccelerationStructureInstanceCount { .. } => 39, - RuntimeFact::InterlockedFramebufferFetch { .. } => 40, - RuntimeFact::ShadowStencil { .. } => 41, - RuntimeFact::PredicationVote => 42, - RuntimeFact::HeapStorageReads { .. } => 43, - RuntimeFact::SrgbTexture { .. } => 44, - RuntimeFact::UlongAtomicView { .. } => 45, - RuntimeFact::ViewportCount => 46, - RuntimeFact::AliasedImageblock { .. } => 47, - RuntimeFact::CallStackDepth { .. } => 48, - RuntimeFact::FlatGrid => 49, - RuntimeFact::SparseTextureWrites { .. } => 50, - RuntimeFact::TileThreadgroupMemory { .. } => 51, - RuntimeFact::TextureSwizzle { .. } => 52, - RuntimeFact::TileImageblock { .. } => 53, - RuntimeFact::AmplificationDraws { .. } => 54, - RuntimeFact::FoldedGroups => 56, - RuntimeFact::ZeroedColor { .. } => 59, - RuntimeFact::DroppedColor { .. } => 60, - RuntimeFact::DepthClampRange => 61, - RuntimeFact::ConstantLanes { .. } => 62, - RuntimeFact::FunctionTableRange { .. } => 63, - RuntimeFact::TestedStorageWrites { .. } => 64, - RuntimeFact::TileThreadgroup { .. } => 66, - RuntimeFact::ConstexprSampled { .. } => 67, - RuntimeFact::CubicSampler { .. } => 68, - RuntimeFact::CubicArgumentSampler { .. } => 69, - RuntimeFact::HeapRawSamples { .. } => 73, - RuntimeFact::ExtendedRangeInputBlend { .. } => 75, - RuntimeFact::CrossClassReads { .. } => 76, - RuntimeFact::StorageTextureWriteRounding { .. } => 77, - RuntimeFact::HeapWriteRounding { .. } => 78, - RuntimeFact::HeapCrossClassNeutral { .. } => 79, - RuntimeFact::AnisotropicSampler { .. } => 80, - RuntimeFact::StorageTextureIntegerChannels { .. } => 81, - RuntimeFact::MovableStorageWrites { .. } => 83, - RuntimeFact::ObjectThreadgroupArena { .. } => 85, - RuntimeFact::WordInputMerge { .. } => 87, - RuntimeFact::ReplayBindings => 88, - RuntimeFact::MergedDraws => 72, - RuntimeFact::QuadPrimitiveIds => 58, - RuntimeFact::RotatedWeights => 82, - RuntimeFact::PrivateList => 86, - RuntimeFact::YCbCrInPlace { .. } => 65, - RuntimeFact::PartialObjectThreadgroups => 89, - RuntimeFact::RotatedInputBlend { .. } => 90, - RuntimeFact::OpenClMode => 91, - RuntimeFact::RowLockstep => 92, - RuntimeFact::BorderTexels { .. } => 93, - RuntimeFact::HeapResidency { .. } => 94, - RuntimeFact::OneRow => 95, - RuntimeFact::RegionViewports => 96, - RuntimeFact::CallThreadgroups => 97, - RuntimeFact::PartialThreadgroups => 98, - RuntimeFact::TexelRows { .. } => 84, - RuntimeFact::UnitAxes { .. } => 57, - RuntimeFact::TexelBufferParts { .. } => 70, - RuntimeFact::OpenClLineTexture { .. } => 74, - RuntimeFact::AddressAlignment { .. } => 71, - RuntimeFact::GridTiles => 55, - RuntimeFact::PrivateArena { .. } => 99, + RuntimeFact::TileFunction => 30, + RuntimeFact::TileAttachmentFormat { .. } => 31, + RuntimeFact::StorageTextureNumericType { .. } => 32, + RuntimeFact::OutOfBoundsAlpha { .. } => 33, + RuntimeFact::BicubicTexels { .. } => 34, + RuntimeFact::StorageTextureLevels { .. } => 35, + RuntimeFact::StorageTextureLevelViews { .. } => 36, + RuntimeFact::SparseTexture { .. } => 37, + RuntimeFact::AccelerationStructureInstanceCount { .. } => 38, + RuntimeFact::PredicationVote => 39, + RuntimeFact::HeapStorageReads { .. } => 40, + RuntimeFact::SrgbTexture { .. } => 41, + RuntimeFact::UlongAtomicView { .. } => 42, + RuntimeFact::ViewportCount => 43, + RuntimeFact::AliasedImageblock { .. } => 44, + RuntimeFact::CallStackDepth { .. } => 45, + RuntimeFact::FlatGrid => 46, + RuntimeFact::SparseTextureWrites { .. } => 47, + RuntimeFact::TileThreadgroupMemory { .. } => 48, + RuntimeFact::TextureSwizzle { .. } => 49, + RuntimeFact::TileImageblock { .. } => 50, + RuntimeFact::AmplificationDraws { .. } => 51, + RuntimeFact::FoldedGroups => 53, + RuntimeFact::ZeroedColor { .. } => 56, + RuntimeFact::DroppedColor { .. } => 57, + RuntimeFact::DepthClampRange => 58, + RuntimeFact::ConstantLanes { .. } => 59, + RuntimeFact::FunctionTableRange { .. } => 60, + RuntimeFact::TileThreadgroup { .. } => 62, + RuntimeFact::ConstexprSampled { .. } => 63, + RuntimeFact::CubicSampler { .. } => 64, + RuntimeFact::CubicArgumentSampler { .. } => 65, + RuntimeFact::HeapRawSamples { .. } => 69, + RuntimeFact::ExtendedRangeInputBlend { .. } => 71, + RuntimeFact::CrossClassReads { .. } => 72, + RuntimeFact::StorageTextureWriteRounding { .. } => 73, + RuntimeFact::HeapWriteRounding { .. } => 74, + RuntimeFact::HeapCrossClassNeutral { .. } => 75, + RuntimeFact::AnisotropicSampler { .. } => 76, + RuntimeFact::StorageTextureIntegerChannels { .. } => 77, + RuntimeFact::ObjectThreadgroupArena { .. } => 80, + RuntimeFact::WordInputMerge { .. } => 82, + RuntimeFact::ReplayBindings => 83, + RuntimeFact::MergedDraws => 68, + RuntimeFact::QuadPrimitiveIds => 55, + RuntimeFact::RotatedWeights => 78, + RuntimeFact::PrivateList => 81, + RuntimeFact::YCbCrInPlace { .. } => 61, + RuntimeFact::PartialObjectThreadgroups => 84, + RuntimeFact::RotatedInputBlend { .. } => 85, + RuntimeFact::OpenClMode => 86, + RuntimeFact::RowLockstep => 87, + RuntimeFact::BorderTexels { .. } => 88, + RuntimeFact::HeapResidency { .. } => 89, + RuntimeFact::OneRow => 90, + RuntimeFact::RegionViewports => 91, + RuntimeFact::CallThreadgroups => 92, + RuntimeFact::PartialThreadgroups => 93, + RuntimeFact::TexelRows { .. } => 79, + RuntimeFact::UnitAxes { .. } => 54, + RuntimeFact::TexelBufferParts { .. } => 66, + RuntimeFact::OpenClLineTexture { .. } => 70, + RuntimeFact::AddressAlignment { .. } => 67, + RuntimeFact::GridTiles => 52, + RuntimeFact::PrivateArena { .. } => 94, } } @@ -388,7 +356,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..100).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..95).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -473,8 +441,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::DroppedColor { .. } | RuntimeFact::DepthClampRange | RuntimeFact::RotatedWeights - | RuntimeFact::TestedStorageWrites { .. } - | RuntimeFact::MovableStorageWrites { .. } | RuntimeFact::ConstexprSampled { .. } | RuntimeFact::CubicSampler { .. } | RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant, @@ -505,9 +471,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { } } RuntimeFact::FramebufferFetch { .. } - | RuntimeFact::FragmentImageblock { .. } - | RuntimeFact::InterlockedFramebufferFetch { .. } - | RuntimeFact::ShadowStencil { .. } | RuntimeFact::TileImageblock { .. } | RuntimeFact::ExtendedRangeInputBlend { .. } | RuntimeFact::RotatedInputBlend { .. } diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 692af94f8..9f5203114 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -657,9 +657,8 @@ pub enum Feature { // ---- Stages and fragment (lowering B7, B9) ---- /// Raster order groups without fragment shader interlock. RasterOrderGroups, - /// Framebuffer fetch without an ordered form on the device (rasterization-order attachment - /// access, or the pixel interlock's storage form where the pipeline's state lets it be - /// exact), or in a shape not implemented. + /// Framebuffer fetch that needs an ordered read the device lacks (rasterization-order + /// attachment access), or in a shape not implemented. 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 @@ -974,8 +973,7 @@ pub enum Feature { /// ([`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) or into a 16-bit - /// float attachment in the interlocked storage form, of the part it names + /// (`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 @@ -1004,20 +1002,14 @@ pub enum Feature { /// 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); -/// a 16-bit float attachment's blend in the interlocked storage form refuses the other two, the -/// generic blend taking their place where the function reads the attachment. +/// 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 { - /// Into a 16-bit float attachment in the storage form, 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`].) + /// 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, - /// Into a 16-bit float attachment in the storage form under fast math, a write mask of exactly - /// one color channel: Metal blends that channel otherwise than the two or three it blends as - /// one vector, by a rule not known. (Without fast math it is built.) - OneColorChannel, /// An output other than four `half` or `float` lanes, or a second output other than those the /// blend reads: not built. Output, @@ -1029,13 +1021,7 @@ pub enum ExtendedRangeBlend { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PrivateRenderField { - /// `sampleMask` dropping a sample, in a pipeline whose fragment function writes an - /// attachment itself (a storage attachment, a shadow stencil or an imageblock), whose writes - /// were not measured under the mask. - SampleMask, - /// `sampleCoverage` other than 1 at a sample count past 4, where Metal was not measured, or - /// in a pipeline whose fragment function writes an attachment itself (a storage attachment, - /// a shadow stencil or an imageblock), whose writes were not measured under it. + /// `sampleCoverage` other than 1 at a sample count past 4, where Metal was not measured. SampleCoverage, /// `alphaTestEnabled` with a test the translation has not built: an `alphaTestFunction` past /// `MTLCompareFunctionAlways`, a pipeline without a fragment function, a fragment function diff --git a/crates/metal2vulkan/src/lower/access/tile.rs b/crates/metal2vulkan/src/lower/access/tile.rs index 31723b600..8c3989e81 100644 --- a/crates/metal2vulkan/src/lower/access/tile.rs +++ b/crates/metal2vulkan/src/lower/access/tile.rs @@ -89,9 +89,8 @@ //! is not aliased onto one. Metal keeps it in the tile memory a fragment function's //! `[[imageblock_data]]` is in, each pixel's same bytes, for the whole pass (measured on an M4, //! `runtime::fragment_imageblock`). Its cells are the pass's imageblock storage -//! (`SyntheticBinding::Imageblock`, a fragment imageblock's `R32Uint` 2D-array storage image, -//! layer `w` word `w` of pixel `(x, y)`'s cell at texel `(x, y)`, which covers every pixel of -//! every tile): the entry stages each word of every cell of its tile from the storage into the +//! (`SyntheticBinding::Imageblock`, an `R32Uint` 2D-array storage image, layer `w` word `w` of +//! pixel `(x, y)`'s cell at texel `(x, y)`, which covers every pixel of every tile): the entry stages each word of every cell of its tile from the storage into the //! threadgroup cells before the function runs, and back after it where the function may write //! them, as it stages attachments, a cell past the render area too. The function records //! `RuntimeFact::TileImageblock`, its size and alignment, which the consumer matches against the @@ -327,8 +326,8 @@ pub struct TilePlan { } /// A tile function's explicit imageblock that stands alone (`TilePlan::pass_cells`): the pass's -/// imageblock storage, `SyntheticBinding::Imageblock`, which the pass's fragment functions' -/// imageblocks are in, each cell's words staged into the tile's cells and back. +/// imageblock storage, `SyntheticBinding::Imageblock`, each cell's words staged into the tile's +/// cells and back. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PassCells { /// The function reaches its cells: the staging loads them. @@ -1072,8 +1071,8 @@ pub fn declare(mb: &mut ModuleBuilder, access: &super::AccessPlan) -> BResult 9, (Atom::S1 | Atom::S1a, _) => 1, - (Atom::S | Atom::Sa, Order::Source) => 0, - (Atom::D | Atom::Da, Order::Source) => 2, (Atom::S | Atom::Sa, Order::Destination) => 2, (Atom::D | Atom::Da, Order::Destination) => 0, (Atom::Da, Order::Scalar) => 0, @@ -350,8 +346,6 @@ impl Atom { /// An inner sum's order among its atoms ([`Atom::order`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Order { - /// The source's before the destination's. - Source, /// 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 @@ -420,27 +414,16 @@ pub(crate) enum Arith { }, } -/// Metal's blend of one attachment's write, as the shader computes it ([`blend_half_float`], -/// [`blend_unorm8`], [`blend_srgb8`], [`blend_packed16`], [`blend_generic`]). +/// 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 write keeps a channel of the format. - masked: bool, /// 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, - /// A 16-bit float attachment of two or more channels under fast math, whose destination - /// product subtracted alone by one minus a source value Metal computes with the factor negated - /// ([`Blend::half_float`]). - negates_one_minus: bool, - /// A blend of a state measured word for word against Metal's own stored codes - /// ([`MEASURED_SIXTEEN`]), whose forms are Metal's whether or not the sweeps fit them in every - /// state ([`Blend::fitted`]). - measured: bool, } /// How Metal's compiler computes a blend it folds into the function, by the function's math mode @@ -465,43 +448,6 @@ impl BlendMath { } } -/// The blend states a 16-bit float attachment's fast-math blend was measured in word for word -/// against Metal's own stored codes, color and alpha factors alike, whose forms [`Blend::fitted`] -/// holds although the state sweeps do not fit a contracted pair or a common factor in every state: -/// the source and destination factors, under `Add`. -/// -/// Measured against the committed recordings of plain Metal on an Apple M3 Max (macOS 27.0.1) of -/// `half-output-blends-r16f`, `-rg16f` and `-rgba16f` ("conformance"): every word of each state's -/// site in each of the three formats, 1,792 a state, the destinations each case's own generator -/// draws and the sources its sweep. `half-output-blends-rgba16f`'s `da-1mda` needs the alpha -/// class's common factor ([`plan`]) to hold at its alpha. -/// -/// A state is here only where no word of any of the three formats differs, which is what says the -/// form is Metal's and not one width's coincidence. Two states the sites measure are out: -/// `SourceAlpha` over `OneMinusSourceAlpha`, whose contracted pair holds at every word of -/// `-rg16f` and differs at 5 of `-r16f` and 13 of `-rgba16f`; and `SourceAlphaSaturated` over -/// `OneMinusSourceAlpha`, where Metal rounds the destination's product first at one and at four -/// channels (every word of `-r16f` and `-rgba16f`) and the source's at two (every word of -/// `-rg16f`, the other order differing at 47): no form the state decides is Metal's at every -/// width, so the device blends it and the pipeline announces -/// `PrecisionNote::HalfOutputFastMathBlend`. -const MEASURED_SIXTEEN: [(BlendFactor, BlendFactor); 2] = [ - (BlendFactor::SourceColor, BlendFactor::DestinationColor), - ( - BlendFactor::DestinationAlpha, - BlendFactor::OneMinusDestinationAlpha, - ), -]; - -/// Whether the blend `eq` is one of the measured states `states` ([`MEASURED_SIXTEEN`]): its color and its alpha factors the one pair, added, as each measured -/// state's are. -fn measured_state(eq: &BlendEquation, states: &[(BlendFactor, BlendFactor)]) -> bool { - let added = eq.rgb_operation == BlendOperation::Add - && eq.alpha_operation == BlendOperation::Add - && (eq.source_rgb, eq.destination_rgb) == (eq.source_alpha, eq.destination_alpha); - added && states.contains(&(eq.source_rgb, eq.destination_rgb)) -} - fn refused(gap: ExtendedRangeBlend) -> Error { Unsupported::not_implemented(Feature::ExtendedRangeBlend(gap)).into() } @@ -545,40 +491,6 @@ fn factor(f: BlendFactor, alpha: bool, math: BlendMath) -> Result { }) } -/// A color factor's rank, which picks the contracted form of an added pair (the module docs' -/// form 6): the source's product is rounded first where its rank is at most the destination's, -/// but the destination's at equal ranks 4 and 5. -fn color_rank(f: BlendFactor) -> u8 { - use BlendFactor as F; - match f { - F::SourceColor | F::OneMinusSourceColor => 0, - F::SourceAlpha | F::OneMinusSourceAlpha | F::DestinationAlpha => 1, - F::DestinationColor => 2, - F::OneMinusDestinationColor | F::OneMinusDestinationAlpha => 3, - F::SourceAlphaSaturated | F::BlendAlpha => 4, - F::BlendColor | F::OneMinusBlendAlpha => 5, - F::OneMinusBlendColor => 6, - _ => 9, - } -} - -/// Alpha's factor rank ([`color_rank`]'s): the source's product is rounded first where its rank -/// is at most the destination's. -fn alpha_rank(f: BlendFactor) -> u8 { - use BlendFactor as F; - match f { - F::SourceAlphaSaturated => 0, - F::SourceColor | F::OneMinusSourceColor | F::SourceAlpha | F::OneMinusSourceAlpha => 1, - F::DestinationColor - | F::OneMinusDestinationColor - | F::DestinationAlpha - | F::OneMinusDestinationAlpha => 3, - F::BlendColor | F::BlendAlpha => 4, - F::OneMinusBlendColor | F::OneMinusBlendAlpha => 5, - _ => 9, - } -} - /// 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. @@ -630,20 +542,11 @@ struct Shared { values: Vec, } -/// Whether an inner sum keeps the one-minus node `n`, added with `sign` as its `i`th pair (from -/// the destination's product where `destination`), whole beyond the nodes that always stay whole -/// ([`inner_sum`]): a shared value added second. An 8-bit unorm attachment's blend (`unorm8`) -/// keeps a shared value added from the destination's product. -fn kept_whole( - (n, sign, i, destination): (Node, i8, usize, bool), - shared: &Shared, - unorm8: bool, -) -> bool { - let added = sign > 0; - match unorm8 { - true => shared.values.contains(&n) && added && destination, - false => shared.values.contains(&n) && added && i > 0, - } +/// 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 @@ -702,7 +605,7 @@ fn inner_sum( /// 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 rules of `family`. `scalar` marks a color class of one channel (an 8-bit unorm attachment's write mask +/// `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. @@ -711,13 +614,11 @@ fn plan( (alpha, scalar): (bool, bool), shared: &Shared, opaque_: bool, - family: Family, + arith: BlendArith, ) -> Result { - let unorm8 = matches!(family, Family::Unorm8(_)); - let order = match (unorm8, scalar) { - (false, _) => Order::Source, - (true, false) => Order::Destination, - (true, true) => Order::Scalar, + let order = match scalar { + false => Order::Destination, + true => Order::Scalar, }; let (s, da) = match alpha { true => (Atom::Sa, Atom::Da), @@ -777,23 +678,20 @@ fn plan( let keep_in = || { move |k: (Node, i8, usize, bool)| match scalar { true => alone.contains(&k.0), - false => kept_whole(k, shared, unorm8), + false => kept_whole(k, shared), } }; - // An 8-bit unorm attachment's lerp takes the destination's product for `y`'s first. - let mut sides = [(true, (sops, dops)), (false, (dops, sops))]; - if unorm8 { - sides.reverse(); - } + // 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 (8-bit unorm: the destination - // alpha's too). - if shared.values.contains(&f) && (za == Atom::Ca || (unorm8 && za == Atom::Da)) { + // 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); @@ -803,14 +701,9 @@ fn plan( if scalar && (alone.contains(&f) || y == Node::Atom(za) || both) { continue; } - // An 8-bit unorm attachment's alpha takes no lerp of the destination alpha beside - // itself or held by both products, and nor does a 16-bit float one's: Metal's - // alpha there is the common factor's form, `h(da · h(h(1 + sa) - da))` - // (`half-output-blends-rgba16f`'s `da-1mda` and `dc-1mdc`, whose alpha factors are - // both the destination alpha and its one minus: every one of the 512 words of the - // two sites, against the committed Metal recordings, where the lerp holds 480). - let no_destination_lerp = unorm8 || family == Family::HalfFloat; - if no_destination_lerp && alpha && za == Atom::Da && (y == Node::Atom(za) || both) { + // 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); @@ -845,22 +738,12 @@ fn plan( rounded: (pd, dt), fused: (ps, st), }; - if let (Family::Unorm8(arith), BlendOperation::Add) = (family, op) { - let rank = |f| unorm8_rank(f, alpha, arith); - return Ok(match rank(fs) >= rank(fd) { - true => destination_first, - false => source_first, - }); - } Ok(match op { BlendOperation::ReverseSubtract => source_first, BlendOperation::Subtract => destination_first, _ => { - let (rs, rd) = match alpha { - true => (alpha_rank(fs), alpha_rank(fd)), - false => (color_rank(fs), color_rank(fd)), - }; - match rs > rd || (!alpha && rs == rd && matches!(rs, 4 | 5)) { + let rank = |f| unorm8_rank(f, alpha, arith); + match rank(fs) >= rank(fd) { true => destination_first, false => source_first, } @@ -871,13 +754,11 @@ fn plan( /// 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`]). Where `keep_zero` (a 16-bit float attachment's blend) a zero factor keeps -/// its product, `x · 0`, in the sum ([`Class::zero_kept`]); elsewhere it leaves its term out, -/// which an extended-range form's clamped operands and encode cannot tell apart. +/// ([`Arith::Rounded`]). A zero factor leaves its term out. fn plan_rounded( (fs, fd, op): (BlendFactor, BlendFactor, BlendOperation), alpha: bool, - (opaque_, keep_zero): (bool, bool), + opaque_: bool, ) -> Result { let (s, d) = match alpha { true => (Atom::Sa, Atom::Da), @@ -904,37 +785,25 @@ fn plan_rounded( } let (st, dt): (Term, Term) = ((s, nfs), (d, nfd)); Ok(match (nfs == Node::Zero, nfd == Node::Zero) { - (true, true) if !keep_zero => Arith::Zero, - (true, false) if !keep_zero => Arith::Term { sign: pd, term: dt }, - (false, true) if !keep_zero => Arith::Term { sign: ps, term: st }, - _ => Arith::Rounded { + (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), }, }) } -/// The attachment whose blend Metal's compiler builds, whose forms differ: a 16-bit float -/// attachment's ([`Blend::half_float`]), or an 8-bit unorm one's in the arithmetic of the output's -/// type ([`Blend::unorm8`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Family { - HalfFloat, - Unorm8(BlendArith), -} - -/// Metal's blend `eq` of a write storing the channels `written` of four into a format with an -/// alpha channel where `has_alpha`, of `family`, in a function of math `math`: an 8-bit unorm -/// attachment's blend takes a write mask of one color channel, which Metal plans as a scalar. +/// 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, family): (bool, Family), + (has_alpha, arith): (bool, BlendArith), written: ColorWriteMask, math: BlendMath, ) -> Result { - let unorm8 = matches!(family, Family::Unorm8(_)); - // A zero factor keeps its product without fast math in a 16-bit float attachment's blend. - let keep_zero = family == Family::HalfFloat; let colors = [ ColorWriteMask::RED, ColorWriteMask::GREEN, @@ -944,16 +813,12 @@ fn planned_for( .filter(|&c| written.contains(c)) .count(); let alpha_written = has_alpha && written.contains(ColorWriteMask::ALPHA); - let masked = colors < 3 || (has_alpha && !alpha_written); - // The rounded model holds for a mask of one color channel. - let fast = math == BlendMath::Fast; let opaque_ = !has_alpha; let color = match colors { 0 => None, - 1 if fast && !unorm8 => return Err(refused(ExtendedRangeBlend::OneColorChannel)), _ => { let f = (eq.source_rgb, eq.destination_rgb, eq.rgb_operation); - let scalar = unorm8 && colors == 1; + 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(); @@ -981,167 +846,67 @@ fn planned_for( } } Some(match math { - BlendMath::Fast => plan(f, (false, scalar), &computed, opaque_, family)?, - BlendMath::Rounded => plan_rounded(f, false, (opaque_, keep_zero))?, + BlendMath::Fast => plan(f, (false, scalar), &computed, opaque_, arith)?, + BlendMath::Rounded => plan_rounded(f, false, opaque_)?, }) } }; let alpha = match alpha_written { false => None, true => { - // The one-minus-blend-alpha the color factors use, which alpha's sums keep whole once - // it comes second. 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(); - if uses(BlendFactor::OneMinusBlendAlpha) { - shared.values.push(Node::OneMinus(Atom::Ca)); + 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(); } - // An 8-bit unorm attachment's 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. - if unorm8 { - use BlendFactor as F; - 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(); - } + 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_, keep_zero))?, - BlendMath::Fast => plan(f, (true, false), &shared, opaque_, family)?, + BlendMath::Rounded => plan_rounded(f, true, opaque_)?, + BlendMath::Fast => plan(f, (true, false), &shared, opaque_, arith)?, }) } }; - Ok(Blend { - color, - alpha, - masked, - math, - negates_one_minus: false, - measured: false, - }) + Ok(Blend { color, alpha, math }) } impl Blend { - /// Metal's blend `eq` of a `half` or `float` output of a module of math `math` into a 16-bit - /// float attachment of format `pf` (`R16Float`, `RG16Float`, `RGBA16Float`) storing the - /// channels `written` of four (a channel the format lacks counts as written: the store drops - /// it), in the arithmetic of the output's type ([`BlendArith`]), computed by - /// [`blend_half_float`]. `R16Float` and `RG16Float` have no alpha: their destination alpha is - /// one, so `DestinationAlpha` is a factor of one and `OneMinusDestinationAlpha` of zero, which - /// under fast math drops its term (a lone term `h(±S)` or `h(±D)`, both dropped `+0`). Under - /// fast math into `RG16Float` or `RGBA16Float`, a destination's product subtracted alone - /// (`Subtract` of a zero source factor) by one minus the source's color or alpha is - /// `h(d · h(z - 1))`, the factor negated, whose zero has `d`'s sign where `z` is one; so is any - /// one minus in alpha of a `float4` output; every other lone term is `h(±S)` or `h(±D)`, the - /// operand negated, `R16Float`'s too (our probes `rb16b`, `rb16c` and `rb16e`, the M3 Max under - /// macOS 27.0.1: `half4` and `float4` outputs, sources and texels of `±0`, `±1`, `2.5`, - /// `-0.75`, `±inf` and NaN in each of color and alpha, every lane of 20 states with a zero - /// factor into each format, and the blend color one). Without fast math - /// the model's rounded forms ([`BlendMath::Rounded`], the module docs): each factor, each - /// product and the sum rounded to the arithmetic's type, nearest even, the blend color rounded - /// to `half` (a `half4` output) before its one minus (and our probes, plain Metal on the M3 Max - /// under macOS 27.0.1: every one of 677 blend states of one key for color and alpha and 1,350 - /// of a key beside one minus the source alpha's, over 16,384 pixels of loaded `half4` and - /// `float4` outputs, every channel of each 16-bit float format, and the 677 under four write - /// masks that keep some channels of `RGBA16Float`). There a factor of zero keeps its product - /// `x · 0` in the sum, as IEEE 754 adds: a NaN where `x` is an infinity or a NaN, else the - /// other term, a zero sum `-0` only where both terms are `-0` (two zero factors alike), every - /// NaN the one Metal stores, `0x7e00` (plain Metal on the M3 Max under macOS 27.0.1, each - /// operation with a zero factor beside each factor, color and alpha, into `RGBA16Float` and - /// `RG16Float` from `half4` and `float4` outputs, three seeds of 16,384 pixels whose sources - /// and texels hold signed zeros, infinities and NaNs among them: every lane). - /// `SourceAlphaSaturated` takes Metal's minimum under either math, a NaN operand giving the - /// other and two zeros `+0` ([`metal_min`]). Under fast math the fast forms of the module docs, - /// with nothing clamped: the blend color's one minus `h(1 - c)` of a color channel and - /// `h(1 - h(a))` of alpha in `half`, `1 - c` in `float` (the same sweeps built under - /// `MTLMathModeFast`: every class of the forms [`Blend::fitted`] names, each channel of every - /// state; the sum and lerp forms fit most states but not all). A blend constant's difference - /// (`BlendColor` with `OneMinusBlendColor`, `BlendAlpha` with `OneMinusBlendAlpha`, under - /// `Subtract` or `ReverseSubtract`) fuses the minuend's product and rounds the subtrahend's - /// first, the color channels' one minus beside `BlendColor` being of its read, `h(1 - h(c))` in - /// `half` (each such state of both sweeps, every channel of `half4` and `float4` outputs, - /// signed zeros included; and our probe through narrower outputs). A factor of the second - /// source is no form here (`Feature::ExtendedRangeBlend` `DualSource`): its output is not - /// planned beside the storage form's write. - pub fn half_float( - eq: &BlendEquation, - pf: PixelFormat, - written: ColorWriteMask, - math: BlendMath, - ) -> Result { - let channels = match pf { - PixelFormat::R16Float => 1, - PixelFormat::RG16Float => 2, - _ => 4, - }; - let b = planned_for(eq, (channels == 4, Family::HalfFloat), written, math)?; - let b = Blend { - negates_one_minus: channels > 1 && math == BlendMath::Fast, - measured: math == BlendMath::Fast && !b.masked && measured_state(eq, &MEASURED_SIXTEEN), - ..b - }; - match b.reads_second() { - true => Err(refused(ExtendedRangeBlend::DualSource)), - false => Ok(b), - } - } - - /// The generic blend `eq` into a format whose Metal blend is not built (see - /// `lower::fragment::fetch`'s module docs), of a format with an alpha channel where - /// `has_alpha` (else the destination alpha is one), storing the channels `written` of four (a - /// channel the format lacks counts as written), computed by [`blend_generic`]: in `float`, each - /// factor, product and sum rounded to `float`, nearest even, a factor of zero keeping its - /// product as IEEE 754 adds, the forms of [`BlendMath::Rounded`] whatever the module's math. A - /// factor of the second source reads the function's second (index 1) output. - pub fn generic( - eq: &BlendEquation, - has_alpha: bool, - written: ColorWriteMask, - ) -> Result { - planned_for( - eq, - (has_alpha, Family::HalfFloat), - written, - BlendMath::Rounded, - ) - } - /// 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 16-bit float - /// blend's forms, but as Metal's compiler builds an 8-bit unorm attachment's blend (plain Metal - /// on the M3 Max under macOS 27.0.1, `lower::fragment::fetch`'s module docs): + /// 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 @@ -1159,8 +924,8 @@ impl Blend { /// 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`): - /// its output is not planned beside the storage form's write. Nor, under fast math, is a + /// 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( @@ -1194,8 +959,7 @@ impl Blend { if factors.iter().any(second) { return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()); } - let family = Family::Unorm8(arith); - let b = planned_for(eq, (has_alpha, family), written, math)?; + 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. @@ -1211,116 +975,6 @@ impl Blend { Ok(b) } - /// 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 sRGB attachment of format `pf` (`R8Unorm_sRGB`, - /// `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`) storing the channels `written` of - /// four, computed by [`blend_srgb8`]: the 8-bit unorm blend of the format's unorm twin - /// ([`Blend::unorm8`]) over the destination as a fetch reads it, Metal's twelve-bit decode of - /// each color byte and alpha's byte over 255, the result stored by Metal's sRGB encode. Plain - /// Metal on the M3 Max under macOS 27.0.1 (our own MSL, random sources and texel bytes, `half4` - /// and `float4` outputs, fast and safe math, each of the four formats): every channel of - /// premultiplied and source-alpha over, the blend color's lerps, a blue-only and an - /// alpha-only write mask, a sum, and a minimum and maximum is that arithmetic's. Where the - /// 8-bit unorm blend is not built (a factor of the second source; under fast math, a format - /// without alpha's lerp, common factor or contracted pair), the rounded forms - /// ([`BlendMath::Rounded`]): Metal's without fast math (a second source's and the formats - /// without alpha's measured so), a near-equivalent under it. The flag is whether the blend is - /// Metal's: the 8-bit unorm blend, or the rounded forms without fast math. - pub fn srgb8( - eq: &BlendEquation, - pf: PixelFormat, - written: ColorWriteMask, - (math, arith): (BlendMath, BlendArith), - ) -> Result<(Blend, bool), Error> { - let (twin, has_alpha) = match pf { - PixelFormat::R8UnormSRGB => (PixelFormat::R8Unorm, false), - PixelFormat::RG8UnormSRGB => (PixelFormat::RG8Unorm, false), - PixelFormat::RGBA8UnormSRGB => (PixelFormat::RGBA8Unorm, true), - PixelFormat::BGRA8UnormSRGB => (PixelFormat::BGRA8Unorm, true), - _ => return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()), - }; - if let Ok(b) = Blend::unorm8(eq, twin, written, (math, arith)) { - return Ok((b, true)); - } - let family = Family::Unorm8(arith); - let rounded = BlendMath::Rounded; - let b = planned_for(eq, (has_alpha, family), written, rounded)?; - Ok((b, math == rounded)) - } - - /// Metal's blend `eq` of a four-lane output of a module of math `math` into a packed 16-bit - /// unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm`, `BGR5A1Unorm`) storing the - /// channels `written` of four, computed by [`blend_packed16`] in `half` arithmetic whatever the - /// output's type, over the output clamped to `[0, 1]` and rounded to `half`, and the - /// destination's code decoded to `half` (alpha one in a format without it), the result stored - /// by Metal's write of the format's codes. Without fast math the 8-bit unorm blend's rounded - /// forms in `half` ([`Blend::unorm8`]); under fast math the 16-bit float blend's forms of four - /// channels ([`Blend::half_float`]), and a write mask of one color channel the 8-bit unorm - /// blend's scalar plan. Measured on plain Metal on the M3 Max under macOS 27.0.1, our own MSL: - /// 2,891 states (every factor and operation pair for color beside source-over alpha, the same - /// pair for both, and random states under random write masks, one blend color) over 8,192 - /// random pixels of `half4` and `float4` outputs into each of the four formats, under fast and - /// safe math. Without fast math every channel holds Metal's code; under fast math every channel - /// lies within one code of Metal's, and 3,527 of 94,732,288 channels miss it (`B5G6R5Unorm`; - /// at most 1,232 in each other format): Metal regroups some sums otherwise than either form. - /// A factor of the second source is not built (`Feature::FramebufferFetch` `NotImplemented`). - pub fn packed16( - eq: &BlendEquation, - written: ColorWriteMask, - math: BlendMath, - ) -> Result { - use BlendFactor as F; - 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 unorm8 = (true, Family::Unorm8(BlendArith::Half)); - match math { - BlendMath::Rounded => planned_for(eq, unorm8, written, math), - BlendMath::Fast => planned_for(eq, (true, Family::HalfFloat), written, math) - .or_else(|_| planned_for(eq, unorm8, written, math)), - } - } - - /// Whether every class the blend stores takes a form the 16-bit float sweeps fit in every state - /// ([`Blend::half_float`]): the rounded forms without fast math; under fast math no term, one - /// term, one fused multiply-add, a minimum or maximum, or a blend constant's difference - /// ([`constant_difference`], a 16-bit float attachment's alone), and every form of a state - /// measured word for word against Metal's stored codes ([`MEASURED_SIXTEEN`]). A fast-math blend of another form (a sum regrouped by a lerp or a - /// common factor, or another product rounded beside a fused one) fits most states but not every - /// one, so it is a near-equivalent. - pub fn fitted(&self) -> bool { - let fits = |a: &Arith| match self.math { - BlendMath::Rounded => true, - BlendMath::Fast => { - self.measured - || matches!( - a, - Arith::Zero - | Arith::Term { .. } - | Arith::Fused { .. } - | Arith::MinMax { .. } - ) - || constant_difference(a) - } - }; - [&self.color, &self.alpha].into_iter().flatten().all(fits) - } - /// Whether the blend reads the blend color (`PushField::HalfBlendColor`). pub fn reads_constant(&self) -> bool { [&self.color, &self.alpha] @@ -1329,17 +983,6 @@ impl Blend { .any(|a| nodes(a).into_iter().any(reads_constant)) } - /// Whether the color channels' arithmetic reads the source alpha as a factor (`SourceAlpha` or - /// `OneMinusSourceAlpha`; `SourceAlphaSaturated` reads it beside one minus the destination - /// alpha). - pub fn color_reads_source_alpha(&self) -> bool { - self.color.as_ref().is_some_and(|a| { - nodes(a) - .into_iter() - .any(|n| matches!(n, Node::Atom(Atom::Sa) | Node::OneMinus(Atom::Sa))) - }) - } - /// Whether the blend reads the second source (the function's index-1 output). pub fn reads_second(&self) -> bool { let second = |n: Node| { @@ -1355,22 +998,6 @@ impl Blend { } } -/// Whether `a` is a difference of a blend constant's product and its one minus's (`BlendColor` with -/// `OneMinusBlendColor`, `BlendAlpha` with `OneMinusBlendAlpha`, subtracted either way): the -/// minuend's product fused, the subtrahend's rounded first ([`Arith::Contracted`] of terms of -/// opposite signs), which a 16-bit float attachment's fast-math sweeps fit in every state -/// ([`Blend::fitted`]; added, the same products are no such form). -fn constant_difference(a: &Arith) -> bool { - let Arith::Contracted { rounded, fused } = a else { - return false; - }; - let factors = [rounded.1 .1, fused.1 .1]; - rounded.0 != fused.0 - && [Atom::C, Atom::Ca] - .into_iter() - .any(|x| factors.contains(&Node::Atom(x)) && factors.contains(&Node::OneMinus(x))) -} - /// Whether `n` reads the blend color. fn reads_constant(n: Node) -> bool { matches!( @@ -1430,11 +1057,8 @@ struct Inputs { constant: Option<(Value, Value, Value)>, math: BlendMath, s1: Option, - /// The arithmetic every rounding is to: `half` but a 16-bit float attachment's blend of a - /// `float4` output ([`BlendArith`]). + /// The arithmetic every rounding is to ([`BlendArith`]). arith: BlendArith, - /// [`Blend`]'s `negates_one_minus`. - negates_one_minus: bool, } /// The values of one lane class, each node computed once. @@ -1507,25 +1131,6 @@ impl<'a> Class<'a> { } } - /// Whether Metal computes a destination's product subtracted alone by `1 - z` as `d · (z - 1)` - /// ([`Blend::half_float`]): into a 16-bit float attachment of two or more channels under fast - /// math, where `z` is a source value; in alpha of a `float4` output, any `z`. - fn negates_one_minus(&self, z: Atom) -> bool { - let float_alpha = self.lanes == Lanes::Scalar && self.inputs.arith == BlendArith::Float; - self.inputs.negates_one_minus && (matches!(z, Atom::S | Atom::Sa) || float_alpha) - } - - /// `x - 1`, rounded as [`one_minus`](Self::one_minus) rounds `1 - x`: `+0` where `x` is one. - fn minus_one(&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, x, one); - } - let m = fb.binary(BinOp::FSub, x, one)?; - half_of(fb, f, m) - } - /// `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 { @@ -1680,17 +1285,6 @@ impl<'a> Class<'a> { fb.glsl(op, &[s, d]) } Arith::Zero => fsplat(fb, self.lanes.floats(), 0.0), - Arith::Term { - sign: -1, - term: (operand @ (Atom::D | Atom::Da), Node::OneMinus(z)), - } if self.negates_one_minus(*z) => { - // `h(d · h(z - 1))`: where `z` is one, the zero of `d`'s sign. - let x = self.atom(fb, *operand)?; - let z = self.atom(fb, *z)?; - let f = self.minus_one(fb, z)?; - let p = self.mul(fb, x, f)?; - self.round(fb, p) - } Arith::Term { sign, term } => self.product(fb, (*sign, *term)), Arith::Fused { product, addend } => { let [x, f] = self.signed(fb, *product)?; @@ -1718,12 +1312,6 @@ impl<'a> Class<'a> { let [x, f] = self.signed(fb, *fused)?; self.fma(fb, [x, f, r]) } - Arith::Rounded { - source, - destination, - } if source.1 .1 == Node::Zero || destination.1 .1 == Node::Zero => { - self.zero_kept(fb, *source, *destination) - } Arith::Rounded { source, destination, @@ -1748,102 +1336,6 @@ impl<'a> Class<'a> { } } } - - /// The bits of `sign · operand · 0` of `(sign, term)`, a term of factor zero, and whether it is - /// a NaN: the operand an infinity or a NaN, whose product with zero is a NaN; else the zero of - /// the signed operand's sign. Decided on the bits: a device may fold a product by a constant - /// zero to `+0` (a module without `SignedZeroInfNanPreserve`, MoltenVK's fast math), which - /// keeps neither the NaN nor the sign. - fn zero_product( - &mut self, - fb: &mut FunctionBuilder<'_>, - (sign, t): (i8, Term), - ) -> BResult<(Value, Value)> { - let f = self.lanes.floats(); - let u = crate::lower::arith::narrow::u32_form(f); - let ut = ty(fb, u)?; - let x = self.atom(fb, t.0)?; - let xb = fb.convert(ConvOp::Bitcast, x, ut)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let infinity = splat(fb, u, 0x7F80_0000)?; - let sign_bit = splat(fb, u, 0x8000_0000)?; - let m = fb.binary(BinOp::BitwiseAnd, xb, magnitude)?; - let nan = fb.binary(BinOp::UGreaterThanEqual, m, infinity)?; - let z = fb.binary(BinOp::BitwiseAnd, xb, sign_bit)?; - let z = match sign < 0 { - true => fb.binary(BinOp::BitwiseXor, z, sign_bit)?, - false => z, - }; - Ok((z, nan)) - } - - /// The bits of term `t`: a zero factor's product and whether it is a NaN - /// ([`zero_product`](Self::zero_product)), or the term rounded as - /// [`product`](Self::product) rounds it and `None`. - fn zero_or_product( - &mut self, - fb: &mut FunctionBuilder<'_>, - t: (i8, Term), - ) -> BResult<(Value, Option)> { - if t.1 .1 == Node::Zero { - let (z, nan) = self.zero_product(fb, t)?; - return Ok((z, Some(nan))); - } - let u = crate::lower::arith::narrow::u32_form(self.lanes.floats()); - let ut = ty(fb, u)?; - let p = self.product(fb, t)?; - Ok((fb.convert(ConvOp::Bitcast, p, ut)?, None)) - } - - /// The sum of `a` and `b` where a factor of either is zero ([`Arith::Rounded`] of a 16-bit - /// float attachment's blend, [`plan_rounded`]'s `keep_zero`): a NaN where a zero factor's - /// product is one (its operand an infinity or a NaN) or the other term is one, the quiet NaN - /// of positive sign Metal stores (`0x7e00`) whatever the NaN's sign and payload; else the - /// other term, rounded as [`product`](Self::product) rounds it, but where that is a zero, the - /// zero IEEE 754 gives the sum: `-0` only where both are `-0`. Two zero factors sum their - /// zeros alike. The sum of a zero and a number is the number, so nothing rounds again. On the - /// bits, as [`zero_product`](Self::zero_product), and the NaN on a select, which no float mode - /// changes. - fn zero_kept( - &mut self, - fb: &mut FunctionBuilder<'_>, - a: (i8, Term), - b: (i8, Term), - ) -> BResult { - let f = self.lanes.floats(); - let u = crate::lower::arith::narrow::u32_form(f); - let ft = ty(fb, f)?; - let magnitude = splat(fb, u, 0x7FFF_FFFF)?; - let zero = splat(fb, u, 0)?; - let (za, na) = self.zero_or_product(fb, a)?; - let (zb, nb) = self.zero_or_product(fb, b)?; - // Each zero factor's product is a signed zero (its magnitude bits clear): `x & z` is the - // zero both signs share where `x` is a zero too, so a zero other takes it and a number - // stays itself. - let (sum, nan) = match (na, nb) { - (Some(na), Some(nb)) => ( - fb.binary(BinOp::BitwiseAnd, za, zb)?, - fb.binary(BinOp::LogicalOr, na, nb)?, - ), - (Some(n), None) | (None, Some(n)) => { - let (z, other) = match na.is_some() { - true => (za, zb), - false => (zb, za), - }; - let shared = fb.binary(BinOp::BitwiseAnd, other, z)?; - let m = fb.binary(BinOp::BitwiseAnd, other, magnitude)?; - let is_zero = fb.binary(BinOp::IEqual, m, zero)?; - let infinity = splat(fb, u, 0x7F80_0000)?; - let other_nan = fb.binary(BinOp::UGreaterThan, m, infinity)?; - let nan = fb.binary(BinOp::LogicalOr, n, other_nan)?; - (fb.select(is_zero, shared, other)?, nan) - } - (None, None) => return Err(BuildError::Type(TypeRule::FunctionSignature)), - }; - let quiet = splat(fb, u, 0x7FC0_0000)?; - let w = fb.select(nan, quiet, sum)?; - fb.convert(ConvOp::Bitcast, w, ft) - } } /// Metal's `min(x, y)` in `SourceAlphaSaturated` (lanes of form `f`): a NaN operand gives the other, @@ -1925,65 +1417,6 @@ pub enum BlendArith { Float, } -/// Metal's blend `b` ([`Blend::half_float`]) of a four-lane output `s` (a `vec4` of `f32`: a -/// `half4` output's `half`s, or a `float4` one) over `d`, the 16-bit float attachment's texel as -/// the storage image reads it (a `vec4` of `f32`; 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 converts to `half` by Metal's write). Nothing is clamped: -/// the source is the value the function returns, and `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, rounded to `half`, nearest even, in -/// `half` arithmetic (the one fit of `RGBA16Float`'s blue lane under a blend color of 0.9), and -/// `OneMinusBlendColor` its one minus: without fast math of that read, under fast math `h(1 - c)` -/// of a color channel's `f32` and `h(1 - h(a))` of alpha, but of that read beside `BlendColor` in a -/// color class. The `Min` and `Max` operations are the device's `FMin` and `FMax`, whose answer at -/// a NaN is not Metal's measured one; `SourceAlphaSaturated`'s minimum is Metal's ([`metal_min`]). -/// A `float` multiply-add is correctly rounded where no part of it underflows -/// (`fma::float_fma_exact`). -pub fn blend_half_float( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - arith: BlendArith, - (s, d): (Value, 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 one = fsplat(fb, f, 1.0)?; - match arith { - BlendArith::Half => { - let h = half_of(fb, f, c)?; - // Under fast math the color channels' one minus reads the `f32`, alpha's - // its `half` (a color class beside `BlendColor` computes its own of the - // `half`). - let minus_of = fb.vector_shuffle(c, h, &[0, 1, 2, 7])?; - let m = fb.binary(BinOp::FSub, one, minus_of)?; - let m = half_of(fb, f, m)?; - Some((h, m, h)) - } - BlendArith::Float => { - let m = fb.binary_no_contraction(BinOp::FSub, one, c)?; - Some((c, m, c)) - } - } - } - None => None, - }; - let inputs = Inputs { - s, - d, - constant, - math: b.math, - s1: None, - arith, - negates_one_minus: b.negates_one_minus, - }; - lanes(fb, b, &inputs) -} - /// 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 @@ -2009,99 +1442,10 @@ pub fn blend_unorm8( clamped_blend(fb, b, arith, (s, None, d), color) } -/// Metal's blend `b` ([`Blend::srgb8`]) of a four-lane output `s` (a `vec4` of `f32`: a `half4` -/// output's `half`s, or a `float4` one) over `decoded`, the 8-bit sRGB attachment's texel as a -/// fetch reads it (a `vec4` of `f32`: each color byte's twelve-bit step over 4095 and the alpha -/// byte over 255, correctly rounded; a channel the format lacks 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 Metal's -/// sRGB encode. The output, and `s1`, the second source (the function's second output, where `b` -/// reads it, [`Blend::reads_second`]), are clamped to `[0, 1]` first, a NaN to 0, and the -/// destination read rounded to the arithmetic's type: each `f32` the decode gives rounds to the -/// `half` its exact quotient does (no step over 4095 and no byte over 255 lies within an `f32` -/// rounding of a `half` midpoint; every one is checked, -/// `lower::arith::tests::blend8::an_srgb_step_s_half_is_its_quotient_s`). `color`, the blend -/// color, reads as [`blend_unorm8`]'s. -pub fn blend_srgb8( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - arith: BlendArith, - (s, s1, decoded): (Value, Option, Value), - color: Option, -) -> BResult { - let f = floats(); - let s = clamped(fb, s, (0.0, 1.0))?; - let s1 = match s1 { - Some(v) => Some(clamped(fb, v, (0.0, 1.0))?), - None => None, - }; - let d = match arith { - BlendArith::Half => half_of(fb, f, decoded)?, - BlendArith::Float => decoded, - }; - clamped_blend(fb, b, arith, (s, s1, d), color) -} - -/// The generic blend `b` ([`Blend::generic`]) of a four-lane output `s` (a `vec4` of `f32`) over -/// `d`, the attachment's texel as the storage image reads it (a `vec4` of `f32`; a channel the -/// format lacks reads 0, alpha 1), in `float`: a `vec4` of `f32` holding each blended lane, which -/// the caller stores through the device's conversion. Where the format is normalized, the source -/// and the blend color are clamped to its `range` first (`[0, 1]` unorm, `[-1, 1]` snorm, every -/// lane, a NaN to the low end), as a fixed-function blend clamps them; `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, and `OneMinusBlendColor` reads one minus -/// it; `s1`, the second source (a `vec4` of `f32`, the function's second output, where `b` reads -/// it, [`Blend::reads_second`]), is clamped as `s`. Not Metal's arithmetic for the format, which is -/// not built: a near-equivalent. -pub fn blend_generic( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - range: Option<(f32, f32)>, - (s, s1, d): (Value, Option, Value), - color: Option, -) -> BResult { - let f = floats(); - let clamp = |fb: &mut FunctionBuilder<'_>, v: Value| -> BResult { - let Some((lo, hi)) = range else { - return Ok(v); - }; - let low = per_lane_f(fb, [lo; 4])?; - let high = per_lane_f(fb, [hi; 4])?; - let nan = fb.unary(UnOp::IsNan, v)?; - let v = fb.select(nan, low, v)?; - fb.glsl(GlslOp::FClamp, &[v, low, high]) - }; - let s = clamp(fb, s)?; - let s1 = match s1 { - Some(v) => Some(clamp(fb, v)?), - None => None, - }; - let constant = match color { - Some(words) => { - let ft = ty(fb, f)?; - let c = fb.convert(ConvOp::Bitcast, words, ft)?; - let c = clamp(fb, c)?; - let one = fsplat(fb, f, 1.0)?; - let m = fb.binary_no_contraction(BinOp::FSub, one, c)?; - Some((c, m, c)) - } - None => None, - }; - let inputs = Inputs { - s, - d, - constant, - math: BlendMath::Rounded, - s1, - arith: BlendArith::Float, - negates_one_minus: false, - }; - lanes(fb, b, &inputs) -} - /// 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, -/// [`blend_srgb8`]'s and [`blend_packed16`]'s arithmetic. +/// 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, @@ -2139,30 +1483,10 @@ fn clamped_blend( math: b.math, s1, arith, - negates_one_minus: false, }; lanes(fb, b, &inputs) } -/// Metal's blend `b` ([`Blend::packed16`]) of a four-lane output `s` (a `vec4` of `f32`: a -/// `half4` output's `half`s, or a `float4` one) over `d`, a packed 16-bit attachment's texel as -/// Metal's blend reads it (a `vec4` of `f32`, each channel its code over its maximum rounded to -/// `half`, a channel the format lacks 0, alpha 1), in `half` arithmetic: a `vec4` of `f32` holding -/// each blended lane, a `half`, which the caller stores as the format's codes. Metal clamps the -/// output to `[0, 1]` first, a NaN to 0, and rounds it to `half`, nearest even, a `float4` one too; -/// `color`, the blend color, reads as [`blend_unorm8`]'s in `half`. -pub fn blend_packed16( - fb: &mut FunctionBuilder<'_>, - b: &Blend, - (s, d): (Value, Value), - color: Option, -) -> BResult { - let f = floats(); - let s = clamped(fb, s, (0.0, 1.0))?; - let s = half_of(fb, f, s)?; - clamped_blend(fb, b, BlendArith::Half, (s, None, d), color) -} - /// 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 diff --git a/crates/metal2vulkan/src/lower/arith/output_precision.rs b/crates/metal2vulkan/src/lower/arith/output_precision.rs index cbe868b19..b24806b94 100644 --- a/crates/metal2vulkan/src/lower/arith/output_precision.rs +++ b/crates/metal2vulkan/src/lower/arith/output_precision.rs @@ -53,23 +53,11 @@ pub(crate) fn half_output_note(cx: &SelectCx<'_>) -> PrecisionNote { /// under every blend and format); in a module compiled with fast math the attachment too /// (`StageIo::half_fast_colors`), whose note the pipeline decides by whether the attachment stores /// some channel, since one that stores none (its write mask none, or absent from the pipeline) -/// holds nothing the output could differ by, but [`half_output_note`] itself for an attachment -/// the function writes in the storage form, which the pipeline's color attachments do not show; -/// in a module naming no math mode [`half_output_note`] itself. Nothing where the function -/// computes Metal's 16-bit float blend there itself (a fetched attachment's blend), which stores -/// Metal's value, nor where it writes the attachment in the -/// storage form under a write mask that names none of the format's channels, which stores nothing. +/// holds nothing the output could differ by; in a module naming no math mode +/// [`half_output_note`] itself. pub(crate) fn note_half_output(cx: &mut SelectCx<'_>, color: u32) { - // Metal's 16-bit float blend, computed by the function: the attachment stores Metal's value. - // A storage write of no channel stores nothing. - if crate::lower::fragment::blends_half_in_storage(cx, color) - || crate::lower::fragment::stores_nothing_in_storage(cx, color) - { - return; - } let math = cx.entry.compile.fast_math; - let in_storage = crate::lower::fragment::written_in_storage(cx, color); - if math.is_none() || (math == Some(true) && in_storage) { + if math.is_none() { let note = half_output_note(cx); cx.precision.insert(note); return; diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 53179338c..c2c6f7645 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -4083,9 +4083,7 @@ fn aggregate_leaf_total_is_capped_before_expansion() { mod atan2; mod bicubic; -mod blend16; mod blend8; -mod blend_packed; mod color_write; mod convert_suffix; mod divide; @@ -4095,7 +4093,6 @@ mod libm; mod narrow; mod pack; mod round_texel; -mod snapshot_codes; mod specials; mod texel_round; mod wide; diff --git a/crates/metal2vulkan/src/lower/arith/tests/blend16.rs b/crates/metal2vulkan/src/lower/arith/tests/blend16.rs deleted file mode 100644 index 73c1fe295..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/blend16.rs +++ /dev/null @@ -1,711 +0,0 @@ -//! A fetched 16-bit float attachment's blend constant differences under fast math, on the -//! interpreter (`extended_range::blend::blend_half_float`): `BlendColor` with `OneMinusBlendColor` -//! and `BlendAlpha` with `OneMinusBlendAlpha`, either as the source factor, under `Subtract` and -//! `ReverseSubtract`, for the color channels and alpha alike, against Metal's measured form. The -//! minuend's product is fused into the difference, the subtrahend's rounded first, in the -//! arithmetic of the output's type: in `half` (a `half4` output) the blend color reads `h(c)` and -//! its one minus `h(1 - h(c))`, each sum and product rounded to `half`; in `float` (a `float4` -//! output) they read `c` and `f(1 - c)`, the result the `float` the caller converts. -//! -//! Plain Metal on the M3 Max under macOS 27.0.1, our own MSL, every channel of 16,384 random pixels -//! of each such state of the 677 and 1,350 state sweeps, `half4` and `float4` outputs, under the -//! blend color (0.3, 0.6, 0.9, 0.45), where blue's `h(1 - h(c))` and `h(1 - c)` differ: this form -//! holds Metal's bits in every channel, signed zeros included (through narrower outputs too). The -//! second blend color puts every color channel where the two differ. Before the form was built, the -//! color channels' blend color difference took the rounded form (both products rounded, one minus -//! of the color's `f32`), which differs from Metal's in some channels, and neither difference -//! counted as fitted. -//! -//! Without fast math a zero factor keeps its product (`a_safe_blend_keeps_a_zero_factors_product`): -//! each product rounded, `x · 0` a NaN where `x` is an infinity or a NaN and else a zero of the -//! signed operand's sign, their IEEE 754 sum rounded (`-0` only where both terms are `-0`), every -//! NaN the quiet `0x7FC00000`, and `SourceAlphaSaturated`'s minimum Metal's: a NaN operand gives -//! the other, two zeros `+0` (plain Metal on the M3 Max under macOS 27.0.1, each -//! operation with a zero factor beside each factor, color and alpha, into `RGBA16Float` and -//! `RG16Float` from `half4` and `float4` outputs, sources and texels holding signed zeros, -//! infinities and NaNs: every lane). Before the form was built, a zero factor dropped its term, -//! which kept neither the NaN of an infinite or NaN operand nor the zero sum's sign. -//! -//! Under fast math a zero factor drops its term, and a lone term's zero takes Metal's sign -//! (`a_fast_blend_s_lone_term_takes_metal_s_zero`): `R16Float` and `RG16Float` have no alpha, so -//! one minus the destination alpha is a zero factor; and into `RG16Float` or `RGBA16Float` a -//! destination's product subtracted alone by one minus the source's color or alpha negates the -//! factor, `h(d · h(z - 1))`, as does any one minus in alpha of a `float4` output (our probes -//! `rb16b`, `rb16c` and `rb16e`, the M3 Max under macOS 27.0.1, every lane). Before, the destination -//! alpha of those formats was the texel's one, whose `1 - 1` kept the product `d · 0` in the sum, -//! and every lone term negated its operand: the zero's sign was off Metal's. - -use super::*; -use crate::lower::arith::extended_range::blend::{blend_half_float, 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)) -} - -/// The `f32` bits of a random `half` of magnitude in `[2^-8, 2^4)`, or a signed zero one time in -/// 16; a random `float` of that range where `float`. -fn operand(rng: &mut Rng, float: bool) -> u64 { - let w = rng.next(); - let sign = if w & 1 == 1 { -1.0f64 } else { 1.0 }; - if (w >> 1) & 15 == 0 { - return u64::from((0.0 * sign as f32).to_bits()); - } - let exponent = ((w >> 5) % 12) as i32 - 8; - let v = match float { - true => 1.0 + ((w >> 16) & 0x7F_FFFF) as f64 / 8_388_608.0, - false => 1.0 + ((w >> 16) & 0x3FF) as f64 / 1024.0, - }; - u64::from(((sign * v * 2f64.powi(exponent)) as f32).to_bits()) -} - -/// Metal's difference in lane `l` (alpha the last) of source `s` over destination -/// `d`, factors `fs` and `fd` under `op`, blend color `bc`, in `arith`: the `f32` bits of the -/// `half` (`BlendArith::Half`) or the `float`. -fn metal( - arith: BlendArith, - (fs, fd, op): (F, F, O), - bc: [f32; 4], - l: usize, - (s, d): (f32, f32), -) -> u64 { - let factor = |f: F| { - let alpha = l == 3 || matches!(f, F::BlendAlpha | F::OneMinusBlendAlpha); - let c = bc[if alpha { 3 } else { l }]; - let one_minus = matches!(f, F::OneMinusBlendColor | F::OneMinusBlendAlpha); - match (arith, one_minus) { - (BlendArith::Half, false) => h(f64::from(c)), - (BlendArith::Half, true) => h(1.0 - h(f64::from(c))), - (BlendArith::Float, false) => f64::from(c), - (BlendArith::Float, true) => f64::from(1.0f32 - c), - } - }; - let (ks, kd) = (factor(fs), factor(fd)); - // The minuend's product fused, the subtrahend's rounded first. - let ((x, kx), (y, ky)) = match op { - O::Subtract => ((s, ks), (d, kd)), - _ => ((d, kd), (s, ks)), - }; - match arith { - // Products and sums of these `half`s are exact in `f64`. - BlendArith::Half => { - let r = f64::from(x).mul_add(kx, -h(f64::from(y) * ky)); - u64::from((h(r) as f32).to_bits()) - } - BlendArith::Float => { - let (kx, ky) = (kx as f32, ky as f32); - u64::from(x.mul_add(kx, -(y * ky)).to_bits()) - } - } -} - -#[test] -fn a_fetched_blend_constant_difference_is_metals() { - let f4 = vec(float(32), 4); - let u4 = vec(int(32), 4); - let colors: [[f32; 4]; 2] = [[0.3, 0.6, 0.9, 0.45], [0.7, 0.55, 0.321, 0.8]]; - let pairs = [ - (F::BlendColor, F::OneMinusBlendColor), - (F::OneMinusBlendColor, F::BlendColor), - (F::BlendAlpha, F::OneMinusBlendAlpha), - (F::OneMinusBlendAlpha, F::BlendAlpha), - ]; - for arith in [BlendArith::Half, BlendArith::Float] { - let float = arith == BlendArith::Float; - let mut rng = Rng(0xD1FF_B1E0 ^ 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..300 { - let s = (0..4).map(|_| operand(&mut rng, float)).collect(); - let d = (0..4).map(|_| operand(&mut rng, false)).collect(); - cases.push(vec![s, d, color.clone()]); - } - } - for (fs, fd) in pairs { - for op in [O::Subtract, O::ReverseSubtract] { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: op, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: op, - }; - let what = format!("{arith:?} {fs:?} {fd:?} {op:?}"); - let b = Blend::half_float( - &eq, - PixelFormat::RGBA16Float, - ColorWriteMask::ALL, - BlendMath::Fast, - ) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(b.fitted(), "{what}: {b:?}"); - for q in HALF_FORMS { - check( - &format!("the fetched blend's {what}, half by {q:?}"), - &[f4, f4, u4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2])) - }, - &cases, - &|c| { - let bc: [f32; 4] = std::array::from_fn(|l| f32v(c[2][l])); - Some( - (0..4) - .map(|l| { - let sd = (f32v(c[0][l]), f32v(c[1][l])); - metal(arith, (fs, fd, op), bc, l, sd) - }) - .collect(), - ) - }, - false, - ); - } - } - } - } -} - -/// The `f32` bits of a special `half` (a signed zero, an infinity, a NaN of either sign, one, the -/// smallest subnormal and normal, the largest finite) one time in three, else a random `half` (or -/// `float` where `float`) of [`operand`]. -fn special(rng: &mut Rng, float: bool) -> u64 { - const SPECIALS: [u32; 12] = [ - 0x0000_0000, - 0x8000_0000, - 0x7F80_0000, - 0xFF80_0000, - 0x7FC0_0000, - 0xFFC0_0000, - 0x3F80_0000, - 0xBF80_0000, - 0x3380_0000, - 0x3880_0000, - 0x477F_E000, - 0xC77F_E000, - ]; - let w = rng.next(); - match w % 3 { - 0 => u64::from(SPECIALS[((w >> 2) % 12) as usize]), - _ => operand(rng, float), - } -} - -/// `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), - } -} - -/// Metal's `min` in `SourceAlphaSaturated`: a NaN operand gives the other, two -/// zeros `+0`. -fn metal_min(x: f64, y: f64) -> f64 { - match (x.is_nan(), y.is_nan()) { - (true, _) => y, - (_, true) => x, - _ if x == 0.0 && y == 0.0 => 0.0, - _ => x.min(y), - } -} - -/// Metal's blend without fast math in lane `l` (alpha the last) of source `s` over -/// destination `d`, factors `fs` and `fd` under `op`, blend color `bc`, in `arith`: each product -/// rounded, a zero factor's kept, the IEEE 754 sum rounded; the `f32` bits of the `half` or the -/// `float`, every NaN `0x7FC00000`. -fn metal_safe( - arith: BlendArith, - (fs, fd, op): (F, F, O), - bc: [f32; 4], - l: usize, - (s, d): ([f32; 4], [f32; 4]), -) -> u64 { - let alpha = l == 3; - let r = |x: f64| rounded(arith, x); - let (sl, dl) = (f64::from(s[l]), f64::from(d[l])); - let (sa, da) = (f64::from(s[3]), f64::from(d[3])); - let factor = |f: F| match f { - F::Zero => 0.0, - F::One => 1.0, - F::SourceColor => sl, - F::OneMinusSourceAlpha => r(1.0 - sa), - F::DestinationColor => dl, - F::OneMinusDestinationAlpha => r(1.0 - da), - F::SourceAlphaSaturated if alpha => 1.0, - F::SourceAlphaSaturated => metal_min(sa, r(1.0 - da)), - F::BlendColor => r(f64::from(bc[l])), - _ => panic!("no factor {f:?} here"), - }; - // Every product of two `half`s or two `float`s is exact in `f64`. - let (ps, pd) = (r(sl * factor(fs)), r(dl * factor(fd))); - let v = r(match op { - O::Add => ps + pd, - O::Subtract => ps - pd, - O::ReverseSubtract => pd - ps, - _ => panic!("no operation {op:?} here"), - }); - match v.is_nan() { - true => 0x7FC0_0000, - false => u64::from((v as f32).to_bits()), - } -} - -#[test] -fn a_safe_blend_keeps_a_zero_factors_product() { - let f4 = vec(float(32), 4); - let u4 = vec(int(32), 4); - let bc: [f32; 4] = [0.3, 0.6, 0.9, 0.45]; - let others = [ - F::One, - F::SourceColor, - F::OneMinusSourceAlpha, - F::DestinationColor, - F::OneMinusDestinationAlpha, - F::SourceAlphaSaturated, - F::BlendColor, - ]; - let pairs: Vec<(F, F)> = (others.iter()) - .flat_map(|&o| [(F::Zero, o), (o, F::Zero)]) - .chain([(F::Zero, F::Zero)]) - .collect(); - for arith in [BlendArith::Half, BlendArith::Float] { - let float = arith == BlendArith::Float; - let mut rng = Rng(0x2E80_FAC7 ^ u64::from(float)); - let color: Vec = bc.iter().map(|c| u64::from(c.to_bits())).collect(); - let mut cases: Vec = Vec::new(); - // The saturated factor's zeros: a source alpha of `-0` beside a destination alpha of one. - for z in [0x8000_0000u64, 0] { - let s = vec![0xBF80_0000, 0x3F80_0000, 0x8000_0000, z]; - let d = vec![0x3F80_0000, 0x8000_0000, 0xBF80_0000, 0x3F80_0000]; - cases.push(vec![s, d, color.clone()]); - } - for _ in 0..400 { - let s = (0..4).map(|_| special(&mut rng, float)).collect(); - let d = (0..4).map(|_| special(&mut rng, false)).collect(); - cases.push(vec![s, d, color.clone()]); - } - for &(fs, fd) in &pairs { - for op in [O::Add, O::Subtract, O::ReverseSubtract] { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: op, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: op, - }; - let what = format!("{arith:?} {fs:?} {fd:?} {op:?}"); - let b = Blend::half_float( - &eq, - PixelFormat::RGBA16Float, - ColorWriteMask::ALL, - BlendMath::Rounded, - ) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - for q in HALF_FORMS { - check_accept( - &format!("the safe blend's {what}, half by {q:?}"), - &[f4, f4, u4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2])) - }, - &cases, - &|c| { - let s: [f32; 4] = std::array::from_fn(|l| f32v(c[0][l])); - let d: [f32; 4] = std::array::from_fn(|l| f32v(c[1][l])); - Some( - (0..4) - .map(|l| metal_safe(arith, (fs, fd, op), bc, l, (s, d))) - .collect(), - ) - }, - &|got, want| { - let nan = |w: u64| f32v(w).is_nan(); - got == want || (q == QuantizeForm::Controlled && nan(got) && nan(want)) - }, - ); - } - } - } - } -} - -/// The values of [`a_fast_blend_s_lone_term_takes_metal_s_zero`]'s grid: the signed zeros, one, -/// -1, 2.5, -0.75, the infinities and a NaN, each exact in `half` and every product and `1 - x` of -/// them too. -const GRID: [f32; 9] = [ - 0.0, - -0.0, - 1.0, - -1.0, - 2.5, - -0.75, - f32::INFINITY, - -f32::INFINITY, - f32::NAN, -]; - -/// Metal's blend under fast math (our probes `rb16b`, `rb16c`, `rb16e`) in lane `l` (alpha the -/// last) of an attachment of `channels` channels, of source `s` over destination `d`, factors `fs` -/// and `fd` under `op`, blend color one, one of whose terms is dropped by a zero factor (`None` -/// where neither is), in `arith`: the remaining term, its operand negated or, a destination's -/// product subtracted by one minus a source value into two or more channels (any one minus in -/// alpha in `float`), its factor; both dropped `+0`. -fn metal_fast_term( - arith: BlendArith, - (fs, fd, op): (F, F, O), - channels: u32, - l: usize, - (s, d): ([f32; 4], [f32; 4]), -) -> Option { - let alpha = l == 3; - let (sl, dl) = (f64::from(s[l]), f64::from(d[l])); - let sa = f64::from(s[3]); - let da = if channels == 4 { f64::from(d[3]) } else { 1.0 }; - // Each factor: `None` where it is zero by the state, else its `1 - z` (`Some(z)`) or value; - // the blend color one. - let factor = |f: F| -> Option<(Option, f64)> { - let z = match f { - F::Zero => return None, - F::OneMinusDestinationAlpha if channels < 4 => return None, - F::One | F::BlendColor => return Some((None, 1.0)), - F::SourceColor => return Some((None, sl)), - F::SourceAlpha => return Some((None, sa)), - F::DestinationColor => return Some((None, dl)), - F::DestinationAlpha => return Some((None, da)), - F::SourceAlphaSaturated if alpha => return Some((None, 1.0)), - F::SourceAlphaSaturated => return Some((None, metal_min(sa, 1.0 - da))), - F::OneMinusBlendColor | F::OneMinusBlendAlpha => 1.0, - F::OneMinusSourceAlpha => sa, - F::OneMinusSourceColor if alpha => sa, - F::OneMinusSourceColor => sl, - F::OneMinusDestinationAlpha => da, - F::OneMinusDestinationColor if alpha => da, - F::OneMinusDestinationColor => dl, - _ => panic!("no factor {f:?} here"), - }; - Some((Some(z), 1.0 - z)) - }; - let source_value = |f: F| matches!(f, F::OneMinusSourceAlpha | F::OneMinusSourceColor); - let (ks, kd) = (factor(fs), factor(fd)); - let (x, k, f, sign) = match (ks, kd) { - (None, None) => return Some(0.0), - (Some(_), Some(_)) => return None, - (Some(k), None) => (sl, k, fs, if op == O::ReverseSubtract { -1.0 } else { 1.0 }), - (None, Some(k)) => (dl, k, fd, if op == O::Subtract { -1.0 } else { 1.0 }), - }; - let destination = kd.is_some(); - let into = destination - && sign < 0.0 - && channels > 1 - && k.0.is_some() - && (source_value(f) || (alpha && arith == BlendArith::Float)); - Some(match (into, k.0) { - (true, Some(z)) => x * (z - 1.0), - _ => sign * (x * k.1), - }) -} - -#[test] -fn a_fast_blend_s_lone_term_takes_metal_s_zero() { - let f4 = vec(float(32), 4); - let u4 = vec(int(32), 4); - // The probes' states with a zero factor. - let states = [ - (F::One, F::OneMinusDestinationAlpha, O::Add), - (F::One, F::OneMinusDestinationAlpha, O::Subtract), - (F::One, F::OneMinusDestinationAlpha, O::ReverseSubtract), - (F::SourceAlpha, F::OneMinusDestinationAlpha, O::Add), - (F::SourceAlpha, F::OneMinusDestinationAlpha, O::Subtract), - (F::OneMinusDestinationAlpha, F::One, O::Subtract), - ( - F::OneMinusDestinationAlpha, - F::SourceAlpha, - O::ReverseSubtract, - ), - ( - F::OneMinusDestinationAlpha, - F::OneMinusDestinationAlpha, - O::Subtract, - ), - (F::Zero, F::OneMinusSourceAlpha, O::Add), - (F::Zero, F::OneMinusSourceAlpha, O::Subtract), - (F::Zero, F::OneMinusSourceColor, O::Subtract), - (F::Zero, F::OneMinusDestinationAlpha, O::Subtract), - (F::Zero, F::OneMinusDestinationColor, O::Subtract), - (F::Zero, F::OneMinusBlendColor, O::Subtract), - (F::Zero, F::OneMinusBlendAlpha, O::Subtract), - (F::Zero, F::BlendColor, O::Subtract), - (F::Zero, F::SourceColor, O::Subtract), - (F::Zero, F::SourceAlpha, O::Subtract), - (F::Zero, F::SourceAlphaSaturated, O::Subtract), - (F::Zero, F::One, O::Subtract), - (F::Zero, F::DestinationAlpha, O::Add), - (F::Zero, F::DestinationAlpha, O::Subtract), - (F::Zero, F::DestinationColor, O::Subtract), - (F::OneMinusSourceAlpha, F::Zero, O::Subtract), - (F::OneMinusSourceAlpha, F::Zero, O::ReverseSubtract), - (F::OneMinusSourceColor, F::Zero, O::ReverseSubtract), - (F::OneMinusDestinationAlpha, F::Zero, O::ReverseSubtract), - (F::OneMinusDestinationColor, F::Zero, O::ReverseSubtract), - (F::OneMinusBlendColor, F::Zero, O::ReverseSubtract), - (F::SourceAlpha, F::Zero, O::Subtract), - (F::SourceAlpha, F::Zero, O::ReverseSubtract), - (F::SourceAlphaSaturated, F::Zero, O::ReverseSubtract), - (F::DestinationColor, F::Zero, O::ReverseSubtract), - (F::DestinationAlpha, F::Zero, O::ReverseSubtract), - (F::One, F::Zero, O::ReverseSubtract), - (F::Zero, F::Zero, O::Add), - (F::Zero, F::Zero, O::Subtract), - ]; - let formats = [ - (PixelFormat::R16Float, 1), - (PixelFormat::RG16Float, 2), - (PixelFormat::RGBA16Float, 4), - ]; - let bits = |x: f32| u64::from(x.to_bits()); - for arith in [BlendArith::Half, BlendArith::Float] { - for (pf, channels) in formats { - // Each source of color `GRID[a]` and alpha `GRID[b]` over a texel of color `GRID[c]` - // and alpha `GRID[e]`, or one, the texel's, where the format has no alpha. - let n = GRID.len(); - let alphas = if channels == 4 { n } else { 1 }; - let mut cases: Vec = Vec::new(); - for i in 0..n * n * n * alphas { - let (a, b, c, e) = ( - i / (n * n * alphas), - (i / (n * alphas)) % n, - (i / alphas) % n, - i % alphas, - ); - let da = if channels == 4 { GRID[e] } else { 1.0 }; - let s = [GRID[a], GRID[a], GRID[a], GRID[b]].map(bits).to_vec(); - let d = [GRID[c], GRID[c], GRID[c], da].map(bits).to_vec(); - cases.push(vec![s, d, vec![bits(1.0); 4]]); - } - // A zero factor of the state or the format's, which drops its term. - let dropped = |f: F| f == F::Zero || (f == F::OneMinusDestinationAlpha && channels < 4); - for (fs, fd, op) in states - .into_iter() - .filter(|&(fs, fd, _)| dropped(fs) || dropped(fd)) - { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: op, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: op, - }; - let what = format!("{arith:?} {pf:?} {fs:?} {fd:?} {op:?}"); - let b = Blend::half_float(&eq, pf, ColorWriteMask::ALL, BlendMath::Fast) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(b.fitted(), "{what}: {b:?}"); - // The channels the format stores: the store drops the others. - let stored = channels as usize; - for q in HALF_FORMS { - check_accept( - &format!("the fast blend's {what}, half by {q:?}"), - &[f4, f4, u4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2])) - }, - &cases, - &|c| { - let s: [f32; 4] = std::array::from_fn(|l| f32v(c[0][l])); - let d: [f32; 4] = std::array::from_fn(|l| f32v(c[1][l])); - let lanes = (0..4).map(|l| match l < stored { - true => metal_fast_term(arith, (fs, fd, op), channels, l, (s, d)) - .map(|v| bits(v as f32)), - // A lane the store drops: any answer. - false => Some(u64::MAX), - }); - lanes.collect() - }, - &|got, want| { - let nan = |w: u64| f32v(w).is_nan(); - want == u64::MAX || got == want || (nan(got) && nan(want)) - }, - ); - } - } - } - } -} - -/// The source values `half-output-blends-*` sweeps: `k / 16 - 2` for `k` in 0 to 63, every -/// sixteenth between -2 and 2, each exact in `half`. -fn blend_source(index: usize) -> f64 { - index as f64 / 16.0 - 2.0 -} - -/// The destination codes `half-output-blends-*` draws for a 16-bit float format: xorshift64\* -/// seeded from the format's Metal value, a multiple of 2^-10 in [0, 1] per channel per pixel, -/// each exact in `half`. Restated here so this test owns its inputs; the words are the words of -/// that family's recordings. -struct BlendRng(u64); - -impl BlendRng { - fn new(seed: u64) -> Self { - let mut state = seed - .wrapping_mul(0x9e37_79b9_7f4a_7c15) - .wrapping_add(0x632b_e59b_d9b4_e019); - if state == 0 { - state = 1; - } - let mut generator = Self(state); - for _ in 0..8 { - generator.next(); - } - generator - } - - fn next(&mut self) -> u64 { - self.0 ^= self.0 >> 12; - self.0 ^= self.0 << 25; - self.0 ^= self.0 >> 27; - self.0.wrapping_mul(2_685_821_657_736_338_717) - } -} - -/// Metal's rounding in a fast-math `half` output's blend into a 16-bit float attachment at the -/// states [`Blend::fitted`] holds by measurement (`blend::MEASURED_SIXTEEN`), on the interpreter, -/// over the very sources and destinations `half-output-blends-r16f`, `-rg16f` and `-rgba16f` -/// compare against plain Metal. -/// -/// **The rule, off those sites' recordings:** Metal rounds the **source** product to the -/// attachment's precision and carries the **destination** product into the sum unrounded, -/// `h(h(Sf · S) + Df · D)` -- one fused multiply-add on the destination term -- where the device's -/// own blend is the mirror image, `h(Sf · S + h(Df · D))`. `SourceColor` over `DestinationColor` -/// is the state that shows it: the source product `S · S` is exact in the attachment, so only the -/// destination product's rounding is left, and the two orders part by a code. -/// -/// `DestinationAlpha` over `OneMinusDestinationAlpha` adds the alpha class, which is neither -/// order: `h(da · h(h(1 + sa) - da))`, the common factor's form ([`plan`]). -/// -/// 2,560 words: 256 of `R16Float`, 512 of `RG16Float` and 1,024 of `RGBA16Float` at -/// `SourceColor`/`DestinationColor`, and 768 color words of `RGBA16Float` at -/// `DestinationAlpha`/`OneMinusDestinationAlpha`, whose 256 alpha words this test holds too. -#[test] -fn a_measured_fast_blend_rounds_the_source_product_first() { - let f4 = vec(float(32), 4); - // The sweep's stride: how far apart two channels of one pixel are, so each source value lands - // at every channel position across the pixels. - const STRIDE: usize = 7; - const SOURCES: usize = 64; - const PIXELS: usize = 256; - let states = [ - (F::SourceColor, F::DestinationColor), - (F::DestinationAlpha, F::OneMinusDestinationAlpha), - ]; - let formats = [ - (PixelFormat::R16Float, 1u32, 25u64), - (PixelFormat::RG16Float, 2, 65), - (PixelFormat::RGBA16Float, 4, 115), - ]; - let mut words = 0usize; - for (pf, channels, raw) in formats { - // The case's destination codes, one row a pixel, and a missing alpha channel's one, as - // Metal's blend and Vulkan's both read it. - let mut rng = BlendRng::new(raw); - let destinations: Vec<[f64; 4]> = (0..PIXELS) - .map(|_| { - std::array::from_fn(|c| match c < channels as usize { - true => (rng.next() % 1025) as f64 / 1024.0, - false => 1.0, - }) - }) - .collect(); - let cases: Vec = (0..PIXELS) - .map(|pixel| { - let s: Vec = (0..4) - .map(|c| { - let v = blend_source((pixel + STRIDE * c as usize) % SOURCES); - u64::from((v as f32).to_bits()) - }) - .collect(); - let d: Vec = destinations[pixel] - .iter() - .map(|&v| u64::from((v as f32).to_bits())) - .collect(); - vec![s, d] - }) - .collect(); - for (fs, fd) in states { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: O::Add, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: O::Add, - }; - let what = format!("{pf:?} {fs:?} {fd:?}"); - let b = Blend::half_float(&eq, pf, ColorWriteMask::ALL, BlendMath::Fast) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(b.fitted(), "{what}: {b:?}"); - // Metal's value in lane `l` of the blend: the color class in the three color lanes, - // and in alpha the attachment's own class, where it holds one. - let metal = |s: [f64; 4], d: [f64; 4], l: usize| -> u64 { - let alpha = l == 3; - let has_alpha = channels == 4; - let (sl, dl) = (s[l], d[l]); - let (sa, da) = (s[3], d[3]); - if alpha && !has_alpha { - // The lane the attachment does not hold keeps the texel's. - return u64::from((dl as f32).to_bits()); - } - let value = match (fs, alpha) { - // The alpha of the destination alpha over its one minus: the common factor's - // form, `h(da · h(h(1 + sa) - da))`. - (F::DestinationAlpha, true) => h(da * h(h(1.0 + sa) - da)), - _ => { - let (ks, kd) = match fs { - F::SourceColor => (sl, dl), - F::DestinationAlpha => (da, h(1.0 - da)), - other => panic!("no factor {other:?} here"), - }; - // Every product of two of these `half`s is exact in `f64`: the source's - // rounded to the attachment, the destination's fused into the sum. - h(h(sl * ks) + dl * kd) - } - }; - u64::from((value as f32).to_bits()) - }; - for q in HALF_FORMS { - check( - &format!("the measured blend's {what}, by {q:?}"), - &[f4, f4], - f4, - &|fb, x| { - fb.module().set_quantize_form(q); - blend_half_float(fb, &b, BlendArith::Half, (x[0], x[1]), None) - }, - &cases, - &|c| { - let s: [f64; 4] = std::array::from_fn(|l| f64::from(f32v(c[0][l]))); - let d: [f64; 4] = std::array::from_fn(|l| f64::from(f32v(c[1][l]))); - Some((0..4).map(|l| metal(s, d, l)).collect()) - }, - false, - ); - } - // The words of the site: one pixel a row, the channels the format holds. - words += PIXELS * channels as usize; - } - } - // The states' sites in the three formats: 1,792 a state, the 2,560 of the five sites the - // family's recordings measure among them. - assert_eq!(words, 3_584, "every word of the measured states' sites"); -} diff --git a/crates/metal2vulkan/src/lower/arith/tests/blend8.rs b/crates/metal2vulkan/src/lower/arith/tests/blend8.rs index 7a65b8016..8a9f4b2a6 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/blend8.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/blend8.rs @@ -4,7 +4,7 @@ //! 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 storage image's store +//! 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. @@ -178,41 +178,6 @@ fn a_code_s_half_is_its_product_s() { } } -/// The `half` nearest `n / d` (a quotient in `[2^-14, 1]`, or zero), from the exact quotient: -/// `n` scaled to eleven significant bits over `d`, rounded to nearest even by the remainder. -fn exact_half(n: u64, d: u64) -> f64 { - if n == 0 { - return 0.0; - } - // No quotient but 1 lies near a power of two, so the `f64`'s exponent is the quotient's. - let e = (n as f64 / d as f64).log2().floor() as i32; - assert!(e >= -14, "{n} / {d} is no normal half"); - let scaled = n << (10 - e); - let (mut q, r) = (scaled / d, scaled % d); - if 2 * r > d || (2 * r == d && q % 2 == 1) { - q += 1; - } - q as f64 * 2f64.powi(e - 10) -} - -/// An 8-bit sRGB destination read in `half` (`blend_srgb8`): the `half` of the `f32` nearest each -/// twelve-bit step over 4095 (the decode of a color byte) and each byte over 255 (alpha's), as the -/// decode gives it correctly rounded, is the `half` nearest the exact quotient: for every step and -/// byte, so the read rounds once, as Metal's. -#[test] -fn an_srgb_step_s_half_is_its_quotient_s() { - for d in [4095u64, 255] { - for n in 0..=d { - let near = n as f32 / d as f32; - assert_eq!( - f64_to_f16(f64::from(near)), - f64_to_f16(exact_half(n, d)), - "{n} / {d}" - ); - } - } -} - /// `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 diff --git a/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs b/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs deleted file mode 100644 index e0172e82b..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs +++ /dev/null @@ -1,330 +0,0 @@ -//! A packed 16-bit word attachment's blend on the interpreter: the word read as Metal's blend -//! reads it (`stage_io::word_color::decode`), blended (`extended_range::blend::blend_packed16`), -//! encoded as Metal's word (`stage_io::word_color::encode`), and the fields of the channels the -//! write mask keeps taken from the word read, against words Metal stored. The words are the M3 -//! Max's under macOS 27.0.1 (plain Metal, our own MSL, a target loaded with the destination's -//! words): nine states of the packed 16-bit blend sweep (`Blend::packed16`) of every form the -//! planner names (a fused product, a contracted pair, a common factor, a lerp of the blend color, -//! minimum and maximum, write masks of one color channel, of red and alpha, and of all but red), -//! each into every packed 16-bit format from `half4` and `float4` outputs under fast and safe math, -//! over six pixels of the sweep: one with an infinite lane, one past both ends of `[0, 1]`, four -//! inside it. - -use super::*; -use crate::lower::arith::extended_range::blend::{blend_packed16, Blend, BlendMath}; -use crate::metal::format::WordAttachment; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat as P}; -use crate::pipeline::lower_inputs::BlendEquation; - -/// The pixels: the output's four lanes (as `f32` bits) and the destination's word. -const PIXELS: [([u32; 4], u16); 6] = [ - ([0x3f2dcb14, 0x3d46318c, 0x3df3cf3d, 0xff800000], 0x4955), - ([0x3f2cee30, 0xbe679b5a, 0x3eefbefc, 0x3ff7099d], 0xcae6), - ([0x3f1b0000, 0x3df42000, 0x3f54c000, 0x3f362000], 0x68b4), - ([0x3eb7870d, 0x3ebb68d0, 0x3ebcc000, 0x3f2b2000], 0x06ad), - ([0x3e082000, 0x3f665d72, 0x3f5fa000, 0x3f7aa000], 0x844b), - ([0x3d088889, 0x3f154000, 0x3e972000, 0x3f02c000], 0x3165), -]; - -/// The states: source and destination factors and operation of color, then alpha (Metal's -/// enumerations), the write mask, and the blend color (as `f32` bits). -const STATES: [([u32; 7], [u32; 4]); 9] = [ - ( - [1, 5, 0, 1, 5, 0, 15], - [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], - ), - ( - [4, 5, 0, 1, 5, 0, 15], - [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], - ), - ( - [14, 14, 0, 14, 1, 3, 4], - [0x3f76ceb7, 0x3e9e8f0f, 0x3ec3fe9a, 0x3da46ba8], - ), - ( - [11, 3, 0, 7, 14, 4, 15], - [0x3ee6c29e, 0x3f92f0c0, 0x3f3abf47, 0x3e9e5b86], - ), - ( - [5, 6, 2, 14, 7, 1, 15], - [0x3ec91e09, 0x3f2e55d9, 0xbe263f9d, 0x3f9d77bb], - ), - ( - [11, 2, 2, 11, 13, 1, 15], - [0x3e9b4ea9, 0x3f017c31, 0x3e62035b, 0x3df4d713], - ), - ( - [1, 1, 4, 1, 1, 4, 15], - [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], - ), - ( - [13, 12, 4, 14, 13, 0, 9], - [0x3e9b462a, 0xbdd04230, 0x3f403c27, 0x3eb75716], - ), - ( - [11, 11, 2, 9, 2, 1, 7], - [0x3f10cf42, 0x3e591def, 0xbe1e5284, 0x3f7b28e6], - ), -]; - -/// Metal's words, one row each: the state, the format, the output (`half4` or `float4`), the math -/// (fast or safe), and the word each pixel stored, in hex. -const WORDS: &str = "\ -0 B5G6R5 half fast f1b9 a80f b93f 5d30 273b 254c -0 B5G6R5 half safe f1b9 a80f b93f 5d30 273b 254c -0 B5G6R5 float fast f1b9 a80f b93f 5d30 273b 254c -0 B5G6R5 float safe f1b9 a80f b93f 5d30 273b 254c -0 A1BGR5 half fast f1dd a81f b93f 5d27 2737 2565 -0 A1BGR5 half safe f1dd a81f b93f 5d27 2737 2565 -0 A1BGR5 float fast f1dd a81f b93f 5d27 2737 2565 -0 A1BGR5 float safe f1dd a81f b93f 5d27 2737 2565 -0 ABGR4 half fast ea75 a07f b4fc 579e 2edf 297a -0 ABGR4 half safe ea75 a07f b4fc 579e 2edf 297a -0 ABGR4 float fast ea75 a07f b4fc 579e 2edf 297a -0 ABGR4 float safe ea75 a07f b4fc 579e 2edf 297a -0 BGR5A1 half fast 7d79 d40f e8bf ae50 939b 9eec -0 BGR5A1 half safe 7d79 d40f e8bf ae50 939b 9eec -0 BGR5A1 float fast 7d79 d40f e8bf ae50 939b 9eec -0 BGR5A1 float safe 7d79 d40f e8bf ae50 939b 9eec -1 B5G6R5 half fast 4955 a80f 88f8 3c2c 271b 1b07 -1 B5G6R5 half safe 4955 a80f 88f8 3c2c 271b 1b07 -1 B5G6R5 float fast 4955 a80f 88f8 3c2c 271b 1b07 -1 B5G6R5 float safe 4955 a80f 88f8 3c2c 271b 1b07 -1 A1BGR5 half fast 4955 a81f 88f5 3c1f 2737 1b1b -1 A1BGR5 half safe 4955 a81f 88f5 3c1f 2737 1b1b -1 A1BGR5 float fast 4955 a81f 88f5 3c1f 2737 1b1b -1 A1BGR5 float safe 4955 a81f 88f5 3c1f 2737 1b1b -1 ABGR4 half fast 4955 a07f 84cc 467e 2ddf 255a -1 ABGR4 half safe 4955 a07f 84cc 467e 2ddf 255a -1 ABGR4 float fast 4955 a07f 84cc 467e 2ddf 255a -1 ABGR4 float safe 4955 a07f 84cc 467e 2ddf 255a -1 BGR5A1 half fast 4955 d40f d498 a1ec 937b 99e7 -1 BGR5A1 half safe 4955 d40f d498 a1ec 937b 99e7 -1 BGR5A1 float fast 4955 d40f d498 a1ec 937b 99e7 -1 BGR5A1 float safe 4955 d40f d498 a1ec 937b 99e7 -2 B5G6R5 half fast 4995 caa6 6994 07ed 87eb 3585 -2 B5G6R5 half safe 4995 caa6 6994 07ed 87eb 3585 -2 B5G6R5 float fast 4995 caa6 6994 07ed 87eb 3585 -2 B5G6R5 float safe 4995 caa6 6994 07ed 87eb 3585 -2 A1BGR5 half fast 4995 caa6 6974 07ed 87cb 3565 -2 A1BGR5 half safe 4995 caa6 6974 07ed 87cb 3565 -2 A1BGR5 float fast 4995 caa6 6974 07ed 87cb 3565 -2 A1BGR5 float safe 4995 caa6 6974 07ed 87cb 3565 -2 ABGR4 half fast 4955 c9e6 69b4 0bad 8f4b 3965 -2 ABGR4 half safe 4955 c9e6 69b4 0bad 8f4b 3965 -2 ABGR4 float fast 4955 c9e6 69b4 0bad 8f4b 3965 -2 ABGR4 float safe 4955 c9e6 69b4 0bad 8f4b 3965 -2 BGR5A1 half fast 4975 caa6 6914 07cd 878b 3365 -2 BGR5A1 half safe 4975 caa6 6914 07cd 878b 3365 -2 BGR5A1 float fast 4975 caa6 6914 07cd 878b 3365 -2 BGR5A1 float safe 4975 caa6 6914 07cd 878b 3365 -3 B5G6R5 half fast 61b5 92ee 7196 2f31 8795 352a -3 B5G6R5 half safe 61b5 92ee 7196 2f31 8795 352a -3 B5G6R5 float fast 61b5 92ee 7196 2f31 8795 352a -3 B5G6R5 float safe 61b5 92ee 7196 2f31 8795 352a -3 A1BGR5 half fast 6197 92eb 716f 2f2d 87a9 3527 -3 A1BGR5 half safe 6199 92eb 716f 2f2d 87a9 3527 -3 A1BGR5 float fast 6197 92eb 716f 2f2d 87a9 3527 -3 A1BGR5 float safe 6199 92eb 716f 2f2d 87a9 3527 -3 ABGR4 half fast 6965 8adf 69bb 29ad 8eaf 3978 -3 ABGR4 half safe 6965 8adf 69bb 29ad 8eaf 3978 -3 ABGR4 float fast 6965 8adf 69bb 29ad 8eaf 3978 -3 ABGR4 float safe 6965 8adf 69bb 29ad 8eaf 3978 -3 BGR5A1 half fast 3d75 beee cd16 9b31 8f95 b2ea -3 BGR5A1 half safe 3d75 beee cd16 9b31 8f95 b2ea -3 BGR5A1 float fast 3d75 beee cd16 9b31 8f95 b2ea -3 BGR5A1 float safe 3d75 beee cd16 9b31 8f95 b2ea -4 B5G6R5 half fast 000b a101 0005 04a2 4223 0800 -4 B5G6R5 half safe 000b a101 0005 04a2 4223 0800 -4 B5G6R5 float fast 000b a101 0005 04a2 4223 0800 -4 B5G6R5 float safe 000b a101 0005 04a2 4223 0800 -4 A1BGR5 half fast 0000 a118 001c 0498 4240 080c -4 A1BGR5 half safe 0000 a118 001c 0498 4240 080c -4 A1BGR5 float fast 0000 a118 001c 0498 4240 080c -4 A1BGR5 float safe 0000 a118 001c 0498 4240 080c -4 ABGR4 half fast 0500 a7d0 0440 0150 4110 0000 -4 ABGR4 half safe 0500 a7d0 0440 0150 4110 0000 -4 ABGR4 float fast 0500 a7d0 0440 0150 4110 0000 -4 ABGR4 float safe 0500 a7d0 0440 0150 4110 0000 -4 BGR5A1 half fast 004b 2a21 4005 0142 0003 1000 -4 BGR5A1 half safe 004b 2a21 4005 0142 0003 1000 -4 BGR5A1 float fast 004b 2a21 4005 0142 0003 1000 -4 BGR5A1 float safe 004b 2a21 4005 0142 0003 1000 -5 B5G6R5 half fast 0002 5800 100b 0102 0844 0000 -5 B5G6R5 half safe 0002 5800 100b 0102 0844 0000 -5 B5G6R5 float fast 0002 5800 100b 0102 0844 0000 -5 B5G6R5 float safe 0002 5800 100b 0102 0844 0000 -5 A1BGR5 half fast 0000 580c 1020 010c 0840 0006 -5 A1BGR5 half safe 0000 580c 1020 010c 0840 0006 -5 A1BGR5 float fast 0000 580c 1020 010c 0840 0006 -5 A1BGR5 float safe 0000 580c 1020 010c 0840 0006 -5 ABGR4 half fast 0000 5051 1061 0020 0010 0010 -5 ABGR4 half safe 0000 5051 1061 0020 0010 0010 -5 ABGR4 float fast 0000 5051 1061 0020 0010 0010 -5 ABGR4 float safe 0000 5051 1061 0020 0010 0010 -5 BGR5A1 half fast 1802 1800 280b 0042 0004 0000 -5 BGR5A1 half safe 1802 1800 280b 0042 0004 0000 -5 BGR5A1 float fast 1802 1800 280b 0042 0004 0000 -5 BGR5A1 float safe 1802 1800 280b 0042 0004 0000 -6 B5G6R5 half fast a955 caef 991a 5ead 873b 34a9 -6 B5G6R5 half safe a955 caef 991a 5ead 873b 34a9 -6 B5G6R5 float fast a955 caef 991a 5ead 873b 34a9 -6 B5G6R5 float safe a955 caef 991a 5ead 873b 34a9 -6 A1BGR5 half fast a955 cae7 9935 5ead 8737 34a5 -6 A1BGR5 half safe a955 cae7 9935 5ead 8737 34a5 -6 A1BGR5 float fast a955 cae7 9935 5ead 8737 34a5 -6 A1BGR5 float safe a955 cae7 9935 5ead 8737 34a5 -6 ABGR4 half fast a955 caef 98cb 56ad 8ddf 3968 -6 ABGR4 half safe a955 caef 98cb 56ad 8ddf 3968 -6 ABGR4 float fast a955 caef 98cb 56ad 8ddf 3968 -6 ABGR4 float safe a955 caef 98cb 56ad 8ddf 3968 -6 BGR5A1 half fast 5555 d6ef e8ba aead 939b b249 -6 BGR5A1 half safe 5555 d6ef e8ba aead 939b b249 -6 BGR5A1 float fast 5555 d6ef e8ba aead 939b b249 -6 BGR5A1 float safe 5555 d6ef e8ba aead 939b b249 -7 B5G6R5 half fast a955 cae6 98b4 5ead 844b 3165 -7 B5G6R5 half safe a955 cae6 98b4 5ead 844b 3165 -7 B5G6R5 float fast a955 cae6 98b4 5ead 844b 3165 -7 B5G6R5 float safe a955 cae6 98b4 5ead 844b 3165 -7 A1BGR5 half fast a954 cae7 98b4 5ead 844b 3165 -7 A1BGR5 half safe a954 cae7 98b4 5ead 844b 3165 -7 A1BGR5 float fast a954 cae7 98b4 5ead 844b 3165 -7 A1BGR5 float safe a954 cae7 98b4 5ead 844b 3165 -7 ABGR4 half fast a952 caec 98b8 56ab 844d 3167 -7 ABGR4 half safe a952 caec 98b8 56ab 844d 3167 -7 ABGR4 float fast a952 caec 98b8 56ab 844d 3167 -7 ABGR4 float safe a952 caec 98b8 56ab 844d 3167 -7 BGR5A1 half fast 5555 d6e6 68b4 2ead 904b 3165 -7 BGR5A1 half safe 5555 d6e6 68b4 2ead 904b 3165 -7 BGR5A1 float fast 5555 d6e6 68b4 2ead 904b 3165 -7 BGR5A1 float safe 5555 d6e6 68b4 2ead 904b 3165 -8 B5G6R5 half fast 4820 c8a0 6800 00c0 8000 3000 -8 B5G6R5 half safe 4820 c8a0 6800 00c0 8000 3000 -8 B5G6R5 float fast 4820 c8a0 6800 00c0 8000 3000 -8 B5G6R5 float safe 4820 c8a0 6800 00c0 8000 3000 -8 A1BGR5 half fast 4840 c881 6801 00c0 8000 3000 -8 A1BGR5 half safe 4840 c881 6801 00c0 8000 3000 -8 A1BGR5 float fast 4840 c881 6801 00c0 8000 3000 -8 A1BGR5 float safe 4840 c881 6801 00c0 8000 3000 -8 ABGR4 half fast 4200 c203 6105 0000 8000 3003 -8 ABGR4 half safe 4200 c203 6105 0000 8000 3003 -8 ABGR4 float fast 4200 c203 6105 0000 8000 3003 -8 ABGR4 float safe 4200 c203 6105 0000 8000 3003 -8 BGR5A1 half fast 4840 48a0 e800 8440 0400 b000 -8 BGR5A1 half safe 4840 48a0 e800 8440 0400 b000 -8 BGR5A1 float fast 4840 48a0 e800 8440 0400 b000 -8 BGR5A1 float safe 4840 48a0 e800 8440 0400 b000 -"; - -#[test] -fn a_packed_word_attachment_blend_stores_metals_words() { - let f4 = vec(float(32), 4); - let u4 = vec(int(32), 4); - let factor = |x: u32| BlendFactor::try_from(x).expect("a factor"); - let operation = |x: u32| BlendOperation::try_from(x).expect("an operation"); - for row in WORDS.lines() { - let cols: Vec<&str> = row.split_whitespace().collect(); - let state: usize = cols[0].parse().expect("a state"); - let pf = match cols[1] { - "B5G6R5" => P::B5G6R5Unorm, - "A1BGR5" => P::A1BGR5Unorm, - "ABGR4" => P::ABGR4Unorm, - _ => P::BGR5A1Unorm, - }; - let (half, fast) = (cols[2] == "half", cols[3] == "fast"); - let words: Vec = (cols[4..].iter()) - .map(|w| u16::from_str_radix(w, 16).expect("a word")) - .collect(); - assert_eq!(words.len(), PIXELS.len(), "{row}"); - let (st, color) = STATES[state]; - let eq = BlendEquation { - source_rgb: factor(st[0]), - destination_rgb: factor(st[1]), - rgb_operation: operation(st[2]), - source_alpha: factor(st[3]), - destination_alpha: factor(st[4]), - alpha_operation: operation(st[5]), - }; - let mask = ColorWriteMask::try_from(st[6]).expect("a mask"); - let word = WordAttachment::layout(pf).expect("a word layout"); - // A channel the format lacks counts as written, as the storage form plans it. - let written = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ColorWriteMask::ALPHA, - ] - .into_iter() - .zip(word.fields()) - .filter(|&(c, f)| mask.contains(c) || f.is_none()) - .fold(ColorWriteMask::NONE, |m, (c, _)| m.union(c)); - let kept: u32 = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ColorWriteMask::ALPHA, - ] - .into_iter() - .zip(word.fields()) - .filter_map(|(c, f)| f.filter(|_| !mask.contains(c))) - .fold(0, |m, f| m | (((1u32 << f.bits) - 1) << f.shift)); - let math = match fast { - true => BlendMath::Fast, - false => BlendMath::Rounded, - }; - let what = format!("state {state} {pf:?} half {half} fast {fast}"); - let b = Blend::packed16(&eq, written, math).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let cases: Vec = PIXELS - .iter() - .map(|(s, d)| { - let s = - s.iter() - .map(|&x| match half { - true => (f16_to_f64(f64_to_f16(f64::from(f32::from_bits(x)))) as f32) - .to_bits(), - false => x, - }) - .map(u64::from) - .collect(); - let c = color.iter().map(|&x| u64::from(x)).collect(); - vec![s, vec![u64::from(*d)], c] - }) - .collect(); - let expected = words; - for q in HALF_FORMS { - check_accept( - &format!("the packed word blend, {what}, half by {q:?}"), - &[f4, int(32), u4], - int(32), - &|fb, x| { - fb.module().set_quantize_form(q); - let d = crate::lower::stage_io::word_color::decode(fb, word, x[1])?; - let color = b.reads_constant().then_some(x[2]); - let v = blend_packed16(fb, &b, (x[0], d), color)?; - let w = crate::lower::stage_io::word_color::encode(fb, word, (f4, v))?; - let u = Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 1, - }; - let keep = crate::lower::arith::ops::splat(fb, u, u64::from(kept))?; - let write = crate::lower::arith::ops::splat(fb, u, u64::from(!kept))?; - let old = fb.binary(crate::spirv::ir::BinOp::BitwiseAnd, x[1], keep)?; - let new = fb.binary(crate::spirv::ir::BinOp::BitwiseAnd, w, write)?; - fb.binary(crate::spirv::ir::BinOp::BitwiseOr, old, new) - }, - &cases, - &|c| { - let i = PIXELS - .iter() - .position(|(_, d)| u64::from(*d) == c[1][0]) - .expect("a pixel"); - Some(vec![u64::from(expected[i])]) - }, - &|g, w| g == w, - ); - } - } -} diff --git a/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs b/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs deleted file mode 100644 index 8c18ba428..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Interpreter tests of a snapshot's codes (`lower::fragment`'s `snapshot`, `SnapshotForm`): the -//! copy's encode of a fetched texel and a read's decode give back every value a fetch of a texel -//! of the form's formats returns: bit for bit but a normalized code's, which a read decodes by the -//! device's arithmetic (`c` times the `f32` nearest `1 / D`, `PrecisionNote::DevicePackConversion`), -//! from the fetch's exact value and from a device's decode an ulp off. - -use super::*; -use crate::lower::fragment::{snapshot_decode, snapshot_encode}; -use crate::pipeline::sym::SnapshotForm; - -fn v4f() -> Form { - vec(float(32), 4) -} - -fn v4u() -> Form { - vec(int(32), 4) -} - -/// The copy's encode and a read's decode of `form`, back to the input's type. -fn round_trip(form: SnapshotForm) -> impl Fn(&mut FunctionBuilder<'_>, &[Value]) -> BResult { - move |fb, x| { - let texel = fb.value_ty(x[0])?; - let codes = snapshot_encode(fb, form, x[0])?; - snapshot_decode(fb, form, codes, texel) - } -} - -/// `c / d` correctly rounded to `f32`: IEEE division of two integers `f32` holds exactly. -fn exact(c: u32, d: u32) -> u32 { - (c as f32 / d as f32).to_bits() -} - -/// A read's decode of code `c` of scale `d`: `c` times the `f32` nearest `1 / d`, at least `-1`. -fn native(c: i64, d: u32) -> u64 { - u64::from((c as f32 * (1.0 / d as f32)).max(-1.0).to_bits()) -} - -/// Every lane value in `values`, four to a case, the last case padded with the first values. -fn cases(values: &[u64]) -> Vec { - values - .chunks(4) - .map(|c| { - let mut lanes = c.to_vec(); - lanes.extend(values.iter().take(4 - c.len())); - vec![lanes] - }) - .collect() -} - -/// Bit-for-bit agreement, NaNs included. -fn same(g: u64, w: u64) -> bool { - g == w -} - -/// An unsigned normalized code's value, exact or a device's an ulp off its code's (lavapipe's -/// reciprocal), comes back as the device's product `c · fl(1 / (2^b - 1))`, which is not Metal's -/// correctly rounded quotient at some codes. -#[test] -fn unsigned_normalized_codes_come_back() { - for (form, d) in [ - (SnapshotForm::Unorm8, 255u32), - (SnapshotForm::Unorm16, 65535), - ] { - let step = if d > 255 { 7 } else { 1 }; - let codes: Vec = (0..=d).step_by(step).chain([d - 1, d]).collect(); - let values: Vec = codes.iter().map(|&c| u64::from(exact(c, d))).collect(); - let wanted: Vec = codes.iter().map(|&c| native(i64::from(c), d)).collect(); - assert_ne!( - values, wanted, - "{form:?}: the product is the quotient at every code" - ); - let body = round_trip(form); - let exact_cases = cases(&values); - let wanted_cases = cases(&wanted); - check_accept( - &format!("{form:?}"), - &[v4f()], - v4f(), - &body, - &exact_cases, - &|c| { - let i = exact_cases.iter().position(|o| o == c)?; - Some(wanted_cases[i][0].clone()) - }, - &same, - ); - // The reciprocal's product, an ulp off on some codes. - let recip = (1.0f32 / d as f32).to_bits(); - let off: Vec = codes - .iter() - .map(|&c| u64::from((c as f32 * f32::from_bits(recip)).to_bits())) - .collect(); - let off_cases = cases(&off); - check_accept( - &format!("{form:?} off an ulp"), - &[v4f()], - v4f(), - &body, - &off_cases, - &|c| { - let i = off_cases.iter().position(|o| o == c)?; - Some(wanted_cases[i][0].clone()) - }, - &same, - ); - } -} - -/// A signed normalized code's value comes back as the device's product: `max(c · fl(1 / -/// (2^(b-1) - 1)), -1)` for every code, the lowest `-1`. -#[test] -fn signed_normalized_codes_come_back() { - for (form, d) in [ - (SnapshotForm::Snorm8, 127u32), - (SnapshotForm::Snorm16, 32767), - ] { - let step = if d > 127 { 7 } else { 1 }; - let lowest = -(d as i64) - 1; - let codes: Vec = (lowest..=i64::from(d)) - .step_by(step) - .chain([lowest, lowest + 1, -1, 0, 1, i64::from(d)]) - .collect(); - let values: Vec = codes - .iter() - .map(|&c| { - let m = exact(c.unsigned_abs().min(u64::from(d)) as u32, d); - let v = if c < 0 { m | 0x8000_0000 } else { m }; - u64::from(v) - }) - .collect(); - let wanted: Vec = codes - .iter() - .map(|&c| native(c.max(-i64::from(d)), d)) - .collect(); - let body = round_trip(form); - let value_cases = cases(&values); - let wanted_cases = cases(&wanted); - check_accept( - &format!("{form:?}"), - &[v4f()], - v4f(), - &body, - &value_cases, - &|c| { - let i = value_cases.iter().position(|o| o == c)?; - Some(wanted_cases[i][0].clone()) - }, - &same, - ); - } -} - -/// Every half value widened comes back bit for bit, zeros, denormals and infinities, and each NaN a -/// NaN: a read's widening of the code is the device's, whose NaN bits it records -/// (`PrecisionNote::NativeNanEncoding`). -#[test] -fn half_codes_come_back() { - let values: Vec = (0..=u16::MAX) - .map(|h| { - let b = crate::lower::arith::narrow::f32_of_half_bits(u32::from(h)); - u64::from(b) - }) - .collect(); - let body = round_trip(SnapshotForm::Half); - check_accept( - "Half", - &[v4f()], - v4f(), - &body, - &cases(&values), - &|c| Some(c[0].clone()), - &|g, w| same(g, w) || (is_nan(float(32), g) && is_nan(float(32), w)), - ); -} - -/// Every integer code comes back: an unsigned one as it is, a signed one sign-extended. -#[test] -fn integer_codes_come_back() { - for (form, bits, signed) in [ - (SnapshotForm::Uint8, 8u32, false), - (SnapshotForm::Sint8, 8, true), - (SnapshotForm::Uint16, 16, false), - (SnapshotForm::Sint16, 16, true), - ] { - let step = if bits > 8 { 3 } else { 1 }; - let values: Vec = (0..1u64 << bits) - .step_by(step) - .map(|c| match signed { - // Sign-extended into the 32-bit lane. - true => u64::from((((c as u32) << (32 - bits)) as i32 >> (32 - bits)) as u32), - false => c, - }) - .collect(); - let body = round_trip(form); - check_accept( - &format!("{form:?}"), - &[v4u()], - v4u(), - &body, - &cases(&values), - &|c| Some(c[0].clone()), - &same, - ); - } -} - -/// The bits form keeps any lanes, NaNs included. -#[test] -fn bits_come_back() { - let values: Vec = [ - 0u32, - 1, - 0x7FC0_0000, - 0xFFFF_FFFF, - 0x8000_0000, - 0x3F80_0000, - 0x7F80_0001, - ] - .iter() - .map(|&b| u64::from(b)) - .collect(); - let body = round_trip(SnapshotForm::Bits); - check_accept( - "Bits", - &[v4f()], - v4f(), - &body, - &cases(&values), - &|c| Some(c[0].clone()), - &same, - ); -} - -/// What the copy's fetch of the slot's own image loses on a device whose `f32` decode -/// canonicalizes a NaN: every NaN code's texel arrives as `0x7fc00000`, which `encode` stores as -/// the one code `0x7e00`, so the read hands back that one quiet positive NaN for all 2,046 of -/// them: the bound `PrecisionNote::DeviceNanEncoding` states for a 16-bit float texel's read. -#[test] -fn a_canonicalized_nan_loses_its_code() { - let canonical = u64::from(f32::NAN.to_bits()); - assert_eq!(canonical, 0x7FC0_0000); - let body = round_trip(SnapshotForm::Half); - let widened = crate::lower::arith::narrow::f32_of_half_bits(0x7E00); - check_accept( - "a canonicalized NaN", - &[v4f()], - v4f(), - &body, - &[vec![vec![canonical; 4]]], - &|_| Some(vec![u64::from(widened); 4]), - &same, - ); - // No NaN code's own widening is that value, so the code is gone, not merely requantized. - let kept = (0..=u16::MAX) - .filter(|h| h & 0x7C00 == 0x7C00 && h & 0x3FF != 0) - .filter(|h| crate::lower::arith::narrow::f32_of_half_bits(u32::from(*h)) == widened) - .count(); - assert_eq!(kept, 1, "only `0x7e00` widens to the canonical NaN"); -} diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 73ad31182..96542acf9 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -219,11 +219,6 @@ pub struct EmitCx<'a> { /// `stage_io::emit_draw_entry` finds before the body and before any other hook reads it /// (`stage_io::StageIoPlan::merged_fragment`), defined in the function's straight-line entry. pub(crate) merged_fragment_table: Option, - /// The texel of each storage-form color attachment a fragment function reads, by Metal - /// color index, at the invocation's pixel (and sample), which `fragment::emit_entry` reads - /// before the body: defined in the function's straight-line entry, inside the interlock, so - /// every use of the color in a later block takes the one texel (`fragment::fetch::value`). - pub(crate) fetched: Vec<(u32, SValue)>, } /// A value that is the same wherever an invocation computes it, so a block computes it once, and @@ -286,7 +281,6 @@ impl<'a> EmitCx<'a> { sampling: Default::default(), merged_draw: None, merged_fragment_table: None, - fetched: Vec::new(), } } @@ -864,7 +858,6 @@ impl<'a> Emitter<'a> { sampling: Default::default(), merged_draw: None, merged_fragment_table: None, - fetched: Vec::new(), }, vars: None, phis, @@ -1471,7 +1464,7 @@ impl CodeEmitter for Emitter<'_> { fn on_return(&mut self, v: Option, fb: &mut FunctionBuilder<'_>) -> BResult<()> { stage_io::emit_return(&mut self.cx, fb, v)?; - fragment::emit_return(&mut self.cx, fb, v) + fragment::emit_return(&mut self.cx, fb) } } diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index 836434249..52f22442f 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -38,9 +38,9 @@ //! //! **An extended-range attachment** (`metal::format::ExtendedRange`) holds Metal's raw texels in //! its raw unsigned format: its input attachment is of `uint` texels, and a read decodes the texel -//! to Metal's tile value (`arith::extended_range::tile_value`), as the storage form's does. A read +//! to Metal's tile value (`arith::extended_range::tile_value`). A read //! of one of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their -//! `_sRGB` twins) is not implemented, on either device (`Feature::Format`, at the attachment): +//! `_sRGB` twins) is not implemented, on every device (`Feature::Format`, at the attachment): //! 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 @@ -53,8 +53,7 @@ //! precision, where Metal decodes a color byte to its twelve-bit step over 4095. The interface //! records each `float` color it reads so (`StageIo::decoded_fetches`), and a render pipeline whose //! attachment there has such a format records `PrecisionNote::SrgbTexelDecode` -//! (`color_writes::pipeline_writes`). The interlocked storage form reads the attachment's bytes, no -//! sRGB view of them, and decodes them by Metal's table itself (`fetch`). +//! (`color_writes::pipeline_writes`). //! //! **An `A8Unorm` attachment whose image holds Metal's alpha in red** (`R8_UNORM` on a device //! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) reads `(r, 0, 0, 1)` through its @@ -71,13 +70,10 @@ use std::collections::BTreeMap; -use crate::air::abi::{AbiInt, OutputRole, ParamBinding, ParamRole}; +use crate::air::abi::{AbiInt, ParamBinding, ParamRole}; use crate::air::ir::{ArgIdx, TypeId as AirTypeId, Value}; -use crate::device::requirements::VkFeature; -use crate::error::{ - Attachment, Capability, DescriptorError, Error, Feature, MetalAnswer, Unsupported, -}; +use crate::error::{Attachment, DescriptorError, Error, Feature, MetalAnswer, Unsupported}; use crate::lower::arith::legal::{form_on, refuse_int64_interface}; use crate::lower::arith::{extended_range, narrow, ops, Form, Held}; use crate::lower::emit::EmitCx; @@ -159,11 +155,9 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result, b: &ParamBinding) -> Result, b: &ParamBinding) -> Result, color: u32) -> Error { - let f = cx.profile.fields(); - let writes = cx.entry.ep.outputs.iter().any(|o| { - matches!( - o.role, - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: 0, - .. - } if a == color - ) - }); - let mut interlock = Vec::new(); - if !super::fetch::interlock_forms(cx.profile) { - interlock.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock)); - } - if writes && !f.leaf.fragment_stores_and_atomics { - interlock.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics)); - } - Unsupported::needs_any_of( - Feature::FramebufferFetch, - vec![ - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess, - )], - interlock, - ], - ) - .into() -} - /// The set-1 class of the element a color input of `form` reads attachment `color` through under /// the identity domains (`PushField::FetchedColor`): a sampled 2D image, multisampled in a /// multisampled pipeline, of `float` texels for a float read and of the attachment's own integer @@ -393,9 +344,7 @@ 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`), or its storage image in the interlocked storage form (`fetch`), which -/// holds the samples as its view states; the storage image of every other attachment in that form -/// (one the function only writes); the input attachment of every extended-range attachment whose +/// 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 @@ -405,11 +354,7 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl { pub(super) fn declare( mb: &mut ModuleBuilder, colors: &[ColorInput], - (storage, blends, merges): ( - &BTreeMap, - &BTreeMap, - &BTreeMap, - ), + (blends, merges): (&BTreeMap, &BTreeMap), (rotated, logic): ( &BTreeMap, &BTreeMap, @@ -424,21 +369,10 @@ pub(super) fn declare( if out.contains_key(&c.color) || textured.contains_key(&c.color) { continue; } - if let Some(sc) = storage.get(&c.color) { - out.insert(c.color, super::fetch::declare(mb, c.color, sc)?); - continue; - } // An extended-range attachment's image holds the raw format's `uint` texels. let float = c.form.is_float() && c.extended.is_none(); out.insert(c.color, input_attachment(mb, c.color, float, multisampled)?); } - // A storage-form attachment the function writes without reading it: an extended-range - // attachment whose blend the shader computes from the texel. - for (&color, sc) in storage { - if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { - e.insert(super::fetch::declare(mb, color, sc)?); - } - } 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) { @@ -497,16 +431,12 @@ fn input_attachment( /// The value of color input `c` in its lowered representation, at the invocation's sample for a /// per-sample function: an input attachment's read at each use (the use may sit in a construct -/// whose values do not dominate the rest of the block), a storage-form attachment's from the -/// texel the function read before its body (`fetch::value`). +/// whose values do not dominate the rest of the block). pub(super) fn value( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, c: ColorInput, ) -> BResult { - if cx.plan.families.fragment.fetch.contains_key(&c.color) { - return super::fetch::value(cx, fb, c); - } let texel = match c.extended { Some(form) => { let texel = input_texel(cx, fb, c.color)?; diff --git a/crates/metal2vulkan/src/lower/fragment/discard.rs b/crates/metal2vulkan/src/lower/fragment/discard.rs index 6f3f85a6a..5c89da410 100644 --- a/crates/metal2vulkan/src/lower/fragment/discard.rs +++ b/crates/metal2vulkan/src/lower/fragment/discard.rs @@ -172,13 +172,6 @@ fn contribution(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Reach { Reach(r) } -/// Whether instruction `id` writes memory another invocation or a later command can read: a -/// store, atomic, image write, or copy outside `Thread` memory, or a call the walk cannot see -/// into (the interlocked framebuffer fetch's early-test rule). -pub(super) fn side_effect(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> bool { - contribution(cx, id, inst).has(Reach::SIDE_EFFECT) -} - /// Whether instruction `id` is tangled (a derivative, an implicit-LOD sample, a quad or subgroup /// operation, a barrier) or a non-quad subgroup operation: what tells the invocations of a quad /// apart from each other (the loop over the covered samples). Valid once every instruction is diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index 54371b25e..860126ede 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -1,176 +1,40 @@ -//! Framebuffer fetch through the ordered pixel interlock. +//! Framebuffer fetch: what orders it, and the writes a fragment function computes over the texel +//! it reads. //! -//! **Where.** Metal orders a fetch after every earlier fragment of the pixel, across draws. -//! Vulkan orders an input-attachment read so only under rasterization-order attachment access -//! (`color`; a device with neither form reads the input attachment ordered between draws alone, -//! [`fetch_unordered`]). A device without that access but with `fragmentShaderPixelInterlock` -//! outside the identity domains ([`interlock_orders`], [`interlock_forms`]: RADV, ANV, and -//! MoltenVK where measured) orders a fetch instead through the ordered pixel interlock, the -//! mechanism of raster order groups and imageblocks: each color attachment the function reads -//! becomes a storage image of the attachment -//! (`ResourceKind::TileAttachment(n)`), read once at the fragment's pixel (the integer part of -//! `FragCoord.xy`) before the body, the texel every use takes, and, when the function writes that -//! attachment through its first -//! (index 0) output, written there at the return in place of the output -//! (`GraphicsState::storage_attachments`; colors it writes but does not read stay ordinary outputs, -//! but those the pipeline's state names: an extended-range attachment it blends, below, and a color -//! its draw's render pass instance keeps out of its subpass for other draws' storage form, -//! `VariantKey::interlocked_colors`). The whole body runs inside the critical section -//! (`fragment::wrap_entry`), so the read, the body, and the write of every fragment of a pixel are -//! one step in primitive order, across the draws and instances of a subpass, and the device-scope -//! coherence of every access inside the critical section (`sync::memory_model`, the image is -//! `Coherent` under `GLSL450`, each access carries `MakeTexel*` under the Vulkan model, as the -//! body's other accesses do) makes each step's write visible to the next: Metal's order. A -//! discarded fragment writes nothing: a demoted invocation's image writes have no effect, a -//! terminate-form discard returns before the write (the entry kills after the critical section), -//! and a predicated one skips it. +//! **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`). //! -//! **Exactness, from the pipeline's state** (`LoweringInputs::framebuffer_fetch`, which the -//! render pipeline compile sets on such a device; without it the function is -//! `NeedsInput(FramebufferFetch)`). The storage write happens inside the shader, so it is exact -//! only where nothing after the shader would drop or change Metal's color write ([`storage_form`], -//! which link applies again to the pipeline it links into): -//! -//! - one view and one layer: no vertex amplification (the binder also refuses a pass of more -//! than one layer); -//! - for a written attachment whose write mask covers some of its format's channels (one that -//! covers none stores nothing, so none of this bears on it): no blending but one and zero, added, -//! for color and alpha, which stores the source as no blending does (a signed normalized format's -//! aside: its NaN stores another code under it), or a blend the shader computes as Metal does, -//! an extended-range, a 16-bit float or an 8-bit unorm attachment's (all below), or the generic -//! blend of another format the function reads (a near-equivalent, below), no alpha to coverage -//! (it can drop the -//! fragment's samples), no signed normalized format under a write mask that keeps some of its -//! channels (its two codes of -1 read alike, so a channel written back would lose the texel's -//! bits), and, with a depth or stencil attachment, early fragment tests: the module declares them -//! there when they keep the function's writes Metal's (Metal's function declares them, or it runs -//! no discard, exports no depth, stencil, or coverage, and writes no other memory), so a fragment -//! the tests fail never runs. Without a depth or stencil attachment no test can fail, and the -//! module declares none (unless Metal's function does). A function that only its discard keeps -//! from them stores before the tests, which each draw's plan checks -//! (`RuntimeFact::TestedStorageWrites`): a draw whose tests drop no fragment runs it, one whose -//! tests write neither attachment and count nothing runs the variant that declares them -//! (`LoweringInputs::read_only_tests`), and any other is refused. A function that writes other -//! memory, or returns depth, stencil, or a sample mask, stores before the tests too, and states -//! the fact without that variant: Metal runs its memory writes for the fragments its tests then -//! drop and tests what it returns, which early tests would not, so only a draw -//! whose tests drop no fragment runs it, and any other is refused at the depth (or stencil) -//! attachment; -//! - a direct format, declared without a format where the device grants the format's storage -//! access without one, so that one module serves every format the function reads alike, else with -//! its SPIR-V image format where it has one (no format feature beyond storage, -//! `shaderStorageImageExtendedFormats` for an extended one); a BGRA-order format (`BGRA8Unorm`, -//! `BGR10A2Unorm`), which has no SPIR-V image format, on a device that accesses it without one -//! in neither direction (ANV), through a view of the attachment in its RGBA-order twin -//! (`R8G8B8A8_UNORM`, `A2B10G10R10_UNORM_PACK32`; `StorageView::rgba_view`, -//! `StorageAttachmentUse::view_alias_of`), declared as the twin is, every texel read from the -//! image or written to it with red and blue exchanged ([`metal_order`]): the device converts -//! each channel as it converts the attachment's own, so a read, a write, the channels a write -//! mask keeps and the per-sample forms hold the values the attachment's own view would; an -//! `A8Unorm` attachment whose image holds Metal's alpha in red (`R8_UNORM` on a device without -//! `A8_UNORM`, `StorageView::alpha_in_red`) through that image, every texel read from it taken -//! to Metal's `(0, 0, 0, r)` and every one written to it holding Metal's alpha in red -//! ([`metal_order`], [`image_order`]), so a read, a merge of the channels a write mask keeps -//! (in Metal's channels, of which only alpha is stored) and the per-sample forms are Metal's -//! (probe `a8`'s uses on an M3 Max under macOS 27.0.1); an `ARGB8Unorm` attachment through its -//! `R8G8B8A8_UNORM` image, whose red, green, blue and alpha hold Metal's alpha, red, green and -//! blue (`StorageView::rotated`), every texel read from it rotated into Metal's order and every -//! one written to it out of it ([`metal_order`], [`image_order`]), blended as `RGBA8Unorm` -//! (below; Metal stores the format as `RGBA8Unorm` with its channels rotated); an -//! 8-bit sRGB format the device renders (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, -//! `BGRA8Unorm_sRGB`) through a view of the attachment in the unsigned integer format of its -//! texel (`R8_UINT`, `R16_UINT`, `R32_UINT`; `StorageView::uint_view`), whose bytes the function -//! converts itself by the device's conversion (`arith::pack`'s `unpack` and `pack` of -//! `unorm4x8_srgb`: the 8-bit instruction and the sRGB transfer by the device's `Pow`, -//! `PrecisionNote::DevicePackConversion`): a read decodes each byte, a channel the format lacks -//! 0 and alpha 1, a write encodes and keeps the format's bytes; a blended write encodes Metal's blend, its -//! 8-bit unorm blend of the format's unorm twin over the texel as a fetch decodes it -//! (`extended_range::Blend::srgb8`, [`srgb_texel`]: on the M3 Max every channel of the blends -//! measured, both maths, `half4` and `float4`, each format), and where that blend is not built -//! (a blend of the second source; under fast math a format without alpha's lerps, which Metal -//! computes in forms of its own) or the output is fewer than four lanes (blended as four whose -//! missing lanes are zero), the rounded forms: Metal's without fast math for four lanes, else a -//! near-equivalent the function notes (`PrecisionNote::UnmeasuredFetchBlend`); a packed 16-bit -//! format the device samples but does not render -//! (`metal::format::WordAttachment`: `A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080) through a view -//! of the attachment in its word's unsigned integer format (`R16_UINT`, `StorageView::word`): a -//! write stores Metal's word of the output (`stage_io::word_color::encode`), the fields of the -//! channels its write mask keeps taken from the word it reads first, so they keep their codes as -//! Metal's tile keeps them ([`word_texel`]). The pipeline sends such an attachment here where it -//! writes it unblended (or blended one and zero) under a mask of some of its channels, or -//! blended otherwise (`color_writes::stored_word`). A blended write computes Metal's packed -//! 16-bit blend of a `half4` or `float4` output over the word it reads -//! (`extended_range::Blend::packed16`, `stage_io::word_color::decode`): exact without fast math -//! over an attachment holding the codes Metal's tile does, within one code of Metal's under fast -//! math (Metal regroups some sums otherwise, 3,527 of 94,732,288 channels measured off by one), -//! and over a clear's or an earlier blend's result in the same pass, which Metal's tile holds as -//! a `half` finer than the codes the attachment holds (`PrecisionNote::DeviceColorConversion`, -//! noted for every such blend). An output of fewer lanes and a factor of the second source are -//! not built. A read of one decodes the word's channels as Metal's programmable blending hands -//! them to the function, each code over its maximum code rounded to `half`, nearest even -//! ([`value`], the same decode; measured for a `float4` and a `half4` color input, -//! `metal::format::word`), which Metal's tile holds finer after a clear or an earlier draw of the -//! same pass, as it holds a blend's destination. A read of an 8-bit sRGB word and of an -//! `RGB9E5Float` one is not built (`NotImplemented(Format)`). +//! **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`]). //! //! **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 //! and y at the pixel center (measured). Compiled for such a pipeline -//! (`LoweringInputs::multisampled`), the function reads (and writes) the attachment's sample at its -//! `SampleId` ([`plan_sample`]), which runs it once per covered sample under Vulkan's sample -//! shading; link's sample invocations then read its pixel inputs where Metal does or refuse them -//! ([`StorageSamples`]). Where the device has multisampled storage images, the image is -//! multisampled, of the pipeline's samples (`GraphicsState::rasterization_samples`, which link -//! checks against `storageImageSampleCounts`), read and written with the `Sample` operand. -//! Elsewhere (ANV, MoltenVK) it holds the samples as planes: a single-sample 2D-array image of one -//! layer per sample, sample `s` of pixel `(x, y)` at texel `(x, y, s)`, which the consumer fills -//! from the multisampled attachment before the draws and writes back after them -//! (`StorageAttachmentUse::view`). Either needs `sampleRateShading`. The pixel interlock orders -//! every invocation covering the pixel, and so each sample's. A returned sample mask keeps an -//! invocation's write exactly when it sets the invocation's sample's bit (measured), so each write -//! is gated on that bit ([`sample_bit`]); at one sample on bit 0 (measured). +//! (`LoweringInputs::multisampled`), the function reads the attachment's sample at its `SampleId` +//! ([`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. -//! The write reads the texel at the pixel first and writes those channels back as it read them -//! ([`StorageView::kept`]); inside the interlock no other fragment of the pixel writes the texel in -//! between, so every channel keeps its value (a `half` texel's NaN in the device's decode, -//! `PrecisionNote::DeviceNanEncoding`). A mask that covers none of the format's channels writes -//! nothing. Link checks the kept channels against the pipeline it links into. Every mask that keeps -//! some of a format's channels compiles alike: the function compiles under the mask's class -//! ([`compiled_write_mask`]: none, every channel, or some), and a write of the third class keeps -//! the lanes whose bits the draw's `PushField::StorageKeptChannels` sets -//! ([`StorageView::kept_at_draw`]), which the binder writes from the pipeline's -//! `StorageAttachmentUse::kept`, so the masks of a class share one module and one fragment key -//! (Metal's own backend compiles each new mask). An extended-range attachment's kept -//! channels feed its blend and encode, and an sRGB one merges its bytes, so those compile each mask -//! (no draw word). -//! -//! **An extended-range attachment** (`metal::format::ExtendedRange`): the image holds Metal's raw -//! texels in the raw unsigned format, so the storage image is declared of that format's -//! `uint` texels ([`StorageView::extended`]), and a read decodes the texel into Metal's tile value -//! (`extended_range::tile_value`: each code as the tile holds it, rounded to `half`, a `float` read -//! alike). A padded attachment the function writes under blending takes -//! this form whether or not the function reads it, since no device blends the raw texels: the write -//! reads the texel's tile value, blends the output over it by the device's arithmetic, and stores -//! the kernel write's encode of the result ([`StorageView::blend`]), the channels a write mask -//! keeps as Metal keeps them (`extended_range::encode_keeping`). The blend -//! (`extended_range::blend::native`) takes a `half4` or `float4` output under every factor, -//! operation and write mask, the second source the function's index-1 output and the blend color -//! read as push data (`PushField::HalfBlendColor`), each as it is, then `S·Fs op D·Fd` in `f32` in -//! the equation's order, where Metal's compiler folds the blend into the function in forms of its -//! own; the function notes `PrecisionNote::ExtendedRangeBlendSource` -//! (`ExtendedRangeFloatBlendSource` for a `float4` output). Another output is refused -//! (`Feature::ExtendedRangeBlend` `Output`). A write of every channel with blending disabled stores -//! the texel Metal's unblended write stores, a `float` output rounded to `half` and encoded as a -//! kernel's write (`stage_io::extended_color::texel`). An unblended write that stores some of its -//! channels encodes them so and keeps the others' codes from the texel it reads first -//! (`extended_range::encode_keeping`), as Metal keeps a masked channel's code: the form a mask of -//! some of the codes one word holds takes (`BGR10_XR`'s, the two-plane forms' color word, -//! `color_writes::merged_extended`), which no mask of the raw components gives. One whose mask -//! covers none of them stores nothing, as above. A bfloat attachment's unblended write stores the -//! code Metal's render pass stores, as its color attachment's write does -//! (`stage_io::extended_color::bfloat_output`), and keeps the code of each channel a mask leaves -//! out, a component of its own; its blend is Metal's pipeline error, and a fetch of it is refused. +//! 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` @@ -178,193 +42,49 @@ //! 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 orders fetch in -//! neither form). An unblended write, a masked one included, is built as above: 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 16-bit float attachment's blend** (`R16Float`, `RG16Float`, `RGBA16Float`): no Vulkan blend -//! applies to a storage write, so the shader computes Metal's: the write reads the texel at the pixel inside the interlock, blends the function's `half` -//! or `float` output of one to four lanes over it (a second (index 1) output beside it, and a -//! factor of the second source, take the generic blend, below), and stores the -//! result (`extended_range::Blend::half_float`, [`half_blended`]). Metal's compiler appends the -//! blend to the function, in the output's type: a `half` output blends in `half` arithmetic, a -//! `float` one in `float`, its result converted to `half` by the storage image's store, as Metal's -//! write of a `float` converts it toward zero, as the device does -//! (`PrecisionNote::DeviceColorConversion`), and to nearest even in the shader under -//! `TextureWriteRoundingMode::NearestEven`, which no measured store gives. An output of fewer -//! than four lanes (Metal takes none with fewer than the format's channels, so it writes `R16Float` -//! or `RG16Float`, which have no alpha) blends as four whose missing lanes play no part, but where -//! the color channels' factors read the source alpha (`SourceAlpha`, `OneMinusSourceAlpha`): that -//! alpha is undefined to Metal's compiler, which stores `+0` in each color channel under fast math -//! and its NaN (`0x7e00`) without, whatever the operands (`SourceAlphaSaturated` is its minimum -//! with one minus the destination alpha, 0 in such a format). Our probe: plain Metal on the M3 Max -//! under macOS 27.0.1, our own MSL, `half` and `float` outputs of one, two and three lanes into -//! `R16Float` and `RG16Float` (each width the format takes), the 677 and 1,350 states of our probe -//! below, and the 677 under `RG16Float`'s partial write masks, fast and safe math: every -//! channel the model's rounded, fitted or constant forms name holds Metal's value (some zero signs -//! differ). Without fast math every product and sum rounds on -//! its own (the rounded forms); under fast math Metal's passes fuse and regroup it (the fast -//! forms). Measured on plain Metal on the M3 Max under macOS 27.0.1, our own MSL, a function -//! reading `[[color(0)]]` beside an unwritten second attachment, 16,384 random pixels a draw -//! (`RGBA16Float`, 677 blend states of one key for color and alpha and 1,350 of a key beside one -//! minus the source alpha: the same states into `R16Float` and `RG16Float`, and the 677 under four -//! write masks that keep some channels): without fast math the rounded forms store Metal's value in -//! every channel of every state, for loaded `half4` and `float4` outputs; under fast math every -//! class whose form is no term, one term, one fused multiply-add, a minimum or maximum, or a blend -//! constant's difference (`BlendColor` with `OneMinusBlendColor`, `BlendAlpha` with -//! `OneMinusBlendAlpha`, subtracted: the minuend's product fused, the subtrahend's rounded first) -//! does (`extended_range::Blend::fitted`), the One over OneMinusSourceAlpha blend included, with -//! the infinities, NaNs, signed zeros and values past `half`'s range. Metal's compiler folds the -//! output's own fast-math arithmetic into the blend (a returned product fused into the blend's one -//! minus the source alpha; a sum that reads the fetched color regrouped by a common factor), so the -//! blend is Metal's exactly where its forms are fitted, the module states its math, and every lane -//! of the output is opaque to it ([`folds_into_blend`]). Elsewhere it is a near-equivalent, and the -//! function records `PrecisionNote::HalfOutputFastMathBlend` (`HalfOutputPrecision` for a module -//! that names no math mode): measured within 2 `half` units in the last place at the operands' -//! magnitude, 16 at the output's under cancellation (below one at the function's own largest term). -//! A `half` output's blend stores a `half` in every channel, so no conversion of the device's -//! bears on it, and a `float` one's only by the store's rounding above; a NaN of the blend is the -//! device's arithmetic's, which the storage image's store converts, noted -//! `PrecisionNote::DeviceNanEncoding` (`stage_io::color_write`; Metal stores each as `0x7e00`). An -//! attachment the function does not read takes the form only where a draw moved it into the -//! storage form (`VariantKey::interlocked_colors`) and its blend is exact; elsewhere the variant -//! is refused and the render pass splits around the draw, whose blend is the device's. -//! -//! **An 8-bit unorm attachment's blend** (`R8Unorm`, `RG8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`, and -//! `ARGB8Unorm` as `RGBA8Unorm` in Metal's channel order) of a -//! `half4` or `float4` output the shader computes as Metal does ([`unorm8_blended`]): the write -//! reads the texel at the pixel inside the interlock in Metal's channel order, clamps the output to -//! `[0, 1]` (a NaN to 0), reads each code `c` as `h(c / 255)` (`f(c / 255)` for a `float4` output) -//! and the blend color clamped to `[0, 1]` (pushed as `PushField::HalfBlendColor`), blends in the -//! output's type in the forms Metal's compiler builds (`extended_range::Blend::unorm8`: fused and -//! regrouped under fast math, each step rounded without) (`extended_range::blend::blend_unorm8`), -//! stores the result, which the storage image's store converts to its code by the device's -//! conversion (`PrecisionNote::DeviceColorConversion`), and keeps the codes of the channels its -//! write mask leaves out. Measured with plain Metal on the M3 Max under macOS 27.0.1: our probe -//! (premultiplied source-over, every `half` alpha in `[0, 1]` against every code of each channel, -//! `half4` and `float4`, fast and safe math, each of the four formats: Metal's code in every -//! channel); our probes (every factor and operation pair for color beside source-over alpha and the -//! reverse, the same pair for both, and random pairs, over every destination code times every -//! source alpha code); our probes (write masks, one color channel and alpha alone among them); our -//! probe (blend colors past both ends). The clamp keeps the output's own arithmetic out of the -//! blend (products, sums and a regroup over the fetched color, each the model's over the function's -//! value), so the blend is Metal's wherever the module states its math (`HalfOutputPrecision` for -//! one naming none). A format without alpha's fast-math lerp, common factor or contracted pair -//! (Metal sums those in forms of their own) and an output of fewer lanes take the generic blend -//! (below), as do a factor of the second source and a second (index 1) output. An `ARGB8Unorm` -//! attachment whose blend no Vulkan state on its image gives (`color_writes::shader_rotated_blend`) -//! takes this form whether or not the function reads it, as the device blends it in no other: the -//! pipeline's state names it (`LoweringInputs::framebuffer_fetch`): Metal's blend where the module -//! states its math, else the same arithmetic, noted as a module stating none is -//! (`output_precision::half_output_note`). -//! -//! **A 32-bit float attachment's blend** (`R32Float`, `RG32Float`, `RGBA32Float`) takes the generic -//! blend below where the function reads the attachment. Every device the translation targets blends -//! those formats itself (`VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT`), so an attachment the -//! function does not read takes the device's own blend: a draw that moved it into the storage form -//! (`VariantKey::interlocked_colors`) is refused that variant and the render pass splits around it. -//! -//! **Another format's blend** (a format held directly whose channels read as floats, but a 16-bit -//! float, an sRGB, a word or an extended-range one: a 32-bit float, 16-bit normalized, 8-bit signed -//! normalized, 10-bit, packed float or `A8Unorm` format, among others; and an 8-bit unorm one of an -//! output of fewer than four lanes, or under a blend Metal's model there does not hold), whose -//! Metal arithmetic is not built, of an attachment the function reads: no Vulkan blend -//! applies to the storage write, so the shader computes the pipeline's blend itself, the generic -//! float blend ([`generic_blended`], `extended_range::Blend::generic`): the write reads the texel -//! inside the interlock, blends the output's four lanes (a missing one zero) over it in `float`, -//! each factor, product and sum rounded to nearest even, a factor of zero keeping its product, the -//! source and the blend color (`PushField::HalfBlendColor`) clamped first to a normalized format's -//! range as Vulkan's blend clamps them, and stores the result through the device's conversion -//! (`PrecisionNote::DeviceColorConversion`), the channels a write mask keeps taken back from the -//! texel. Metal's blend arithmetic for these formats is not measured: the function records -//! `PrecisionNote::UnmeasuredFetchBlend`. An attachment the function does not read (one a draw -//! moved into the storage form) does not take it: the variant is refused and the render pass -//! splits around the draw, whose blend is the device's. A factor of the second source reads the -//! function's second (index 1) output, four `half` or `float` lanes, clamped as the first (Metal -//! makes and draws a pipeline that fetches and blends so; one whose function writes no second -//! output Metal refuses, and so is it refused, `DescriptorError::ColorAttachment`). The generic -//! blend also takes a 16-bit float or 8-bit unorm attachment's blend of the second source, or -//! beside a second output, whose Metal arithmetic is not measured. +//! `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. The storage form -//! stores Vulkan's texel output conversion of the output, the rule a color attachment write -//! states for the same formats. +//! `NotImplemented`): no ordered path exists there. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; -use crate::air::abi::{AbiInt, OutputRole, ParamRole}; -use crate::air::intrinsics::{AirIntrinsic, Fragment, PackFormat}; -use crate::air::ir::{Callee, InstKind, Type as AirType, TypeId as AirTypeId, Value}; +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, DescriptorError, Error, ExtendedRangeBlend, Feature, MetalAnswer, - RuntimeInput, Unsupported, -}; -use crate::lower::arith::{extended_range, narrow, ops, pack, FloatFmt, Form, Held}; +use crate::error::{Attachment, Capability, Error, ExtendedRangeBlend, Feature, Unsupported}; +use crate::lower::arith::{extended_range, FloatFmt, Form}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; -use crate::lower::stage_io::{self, Returned}; -use crate::lower::sync::memory_model; -use crate::metal::format::{ - accessed_without_format, color_output_components, rgba_twin, rgba_twin_gaps, sampled_type, - spirv_image_format, without_format_gaps, ExtendedRange, FormatEmulation, StorageUse, - WordAttachment, -}; +use crate::lower::stage_io; +use crate::metal::format::{color_output_components, ExtendedRange, WordAttachment}; use crate::metal::ColorWriteMask; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::lower_inputs::{ - BlendEquation, ExtendedRangeColor, FetchedAttachment, FramebufferFetchInputs, -}; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SampledType, Stage}; -use crate::pipeline::StorageAttachmentUse; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::pipeline::lower_inputs::BlendEquation; +use crate::pipeline::sym::PushField; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value as SValue}; -use crate::spirv::ir::{ - BinOp, ConvOp, Dim, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass, - Type as SType, UnOp, -}; +use crate::spirv::ids::Value as SValue; +use crate::spirv::ir::{ConvOp, ImageOperands, MemAccess, Type as SType}; use crate::vk; -use super::{not_lowered, ColorInput}; - -/// Whether the pixel interlock may choose a form on `p` beyond a raster order group's (`rog`): -/// the storage forms of a framebuffer fetch and of a blend, merge or logic operation the function -/// computes over it ([`interlock_orders`]), of a stencil output (`stencil`), of an imageblock -/// (`imageblock`) and of a snapshot read (`snapshot`). Each is a storage image bound through a -/// descriptor, which the identity domains hold none of, so under them the interlock chooses none -/// of these: each takes the form, or the refusal, it takes on a device without the interlock, and -/// the interlock orders a raster order group on the memory the function reads and writes alone. -pub(crate) fn interlock_forms(p: &DeviceProfile) -> bool { - p.fields().fragment.pixel_interlock && !crate::lower::access::identity(p) -} - -/// Whether `p` orders framebuffer fetch only through the ordered pixel interlock: no -/// rasterization-order color attachment access, with `fragmentShaderPixelInterlock` choosing the -/// storage form ([`interlock_forms`]). -pub(crate) fn interlock_orders(p: &DeviceProfile) -> bool { - !p.fields().fragment.rasterization_order_color_access && interlock_forms(p) -} - /// Whether `p` orders framebuffer fetch through rasterization-order input attachments (lavapipe): -/// rasterization-order color attachment access, which [`interlock_orders`] excludes. +/// 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 neither form: no rasterization-order color attachment -/// access and no `fragmentShaderPixelInterlock`. A fetch there reads the input attachment, which +/// 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 { - !interlock_orders(p) && !inputs_order(p) + !inputs_order(p) } /// Whether Metal's tile memory holds an attachment of `form` as `half` through a render pass and @@ -377,21 +97,15 @@ pub(crate) fn codes_round_the_tile(form: ExtendedRange) -> bool { } /// 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 orders framebuffer -/// fetch in neither form ([`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 -/// the pixel interlock (the storage form) or rasterization-order color attachment access (over the -/// input attachment). +/// 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_any_of( + Unsupported::needs( Feature::FramebufferFetch, - vec![ - vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess, - )], - ], + Capability::Feature(VkFeature::RasterizationOrderColorAttachmentAccess), ) } @@ -405,8 +119,7 @@ pub(crate) fn half_float_format(pf: crate::metal::PixelFormat) -> bool { /// 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 and -/// whose image the function reads and writes in Metal's order ([`StorageView::rotated`]). +/// 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!( @@ -415,16 +128,6 @@ pub(crate) fn unorm8_format(pf: crate::metal::PixelFormat) -> bool { ) } -/// Whether `pf` is an 8-bit sRGB color format, whose blend Metal computes as its unorm twin's over -/// the decoded texel, encoded ([`extended_range::Blend::srgb8`]). -pub(crate) fn srgb8_format(pf: crate::metal::PixelFormat) -> bool { - use crate::metal::PixelFormat as P; - matches!( - pf, - P::R8UnormSRGB | P::RG8UnormSRGB | P::RGBA8UnormSRGB | P::BGRA8UnormSRGB - ) -} - /// Whether `pf` is a packed 16-bit unorm format (`metal::format::WordAttachment::Packed16`), whose /// blend Metal computes in `half` over its decoded codes ([`extended_range::Blend::packed16`]). pub(crate) fn packed16_format(pf: crate::metal::PixelFormat) -> bool { @@ -434,461 +137,6 @@ pub(crate) fn packed16_format(pf: crate::metal::PixelFormat) -> bool { ) } -/// Metal's blend `eq` of a format held directly, which the shader computes in the storage form, -/// storing the channels `written` of four under math `math`: an 8-bit unorm attachment's in -/// `arith` ([`extended_range::Blend::unorm8`]), an 8-bit sRGB one's in `arith` -/// ([`extended_range::Blend::srgb8`], whether Metal's or not), a packed 16-bit one's -/// ([`extended_range::Blend::packed16`], in `half` whatever the output), else a 16-bit float one's -/// ([`extended_range::Blend::half_float`], which takes its arithmetic when it computes). The -/// planning callers pass `BlendArith::Half`: what is refused, what reads the blend color, and the -/// words are the same in either arithmetic. -fn direct_blend( - eq: &BlendEquation, - pf: crate::metal::PixelFormat, - written: ColorWriteMask, - (math, arith): ( - extended_range::blend::BlendMath, - extended_range::blend::BlendArith, - ), -) -> Result { - if packed16_format(pf) { - return extended_range::Blend::packed16(eq, written, math); - } - if srgb8_format(pf) { - return extended_range::Blend::srgb8(eq, pf, written, (math, arith)).map(|(b, _)| b); - } - match unorm8_format(pf) { - true => extended_range::Blend::unorm8(eq, pf, written, (math, arith)), - false => extended_range::Blend::half_float(eq, pf, written, math), - } -} - -/// Whether Metal's blend `eq` into the 8-bit sRGB attachment of `pf` storing the channels `written` -/// of four under math `math` is its 8-bit unorm blend's, or its rounded forms without fast math -/// ([`extended_range::Blend::srgb8`]'s flag): elsewhere the shader computes a near-equivalent. -fn srgb8_exact( - eq: &BlendEquation, - pf: crate::metal::PixelFormat, - written: ColorWriteMask, - math: extended_range::blend::BlendMath, -) -> bool { - let half = extended_range::blend::BlendArith::Half; - extended_range::Blend::srgb8(eq, pf, written, (math, half)).is_ok_and(|(_, exact)| exact) -} - -/// Whether the output a blend into the 8-bit sRGB attachment of `pf` takes is four lanes, its -/// blended output `output` ([`blended_output`]): every output to a four-channel format is -/// ([`select_output`]); another format's where its blended output is, `None` (beside a second -/// output) counting as fewer. -fn srgb_output4( - pf: crate::metal::PixelFormat, - output: Option<(extended_range::blend::BlendArith, u32)>, -) -> bool { - color_output_components(pf) == Some(4) || output.is_some_and(|(_, lanes)| lanes == 4) -} - -/// The generic float blend `eq` into an attachment of `pf` storing the channels `written` of four -/// ([`extended_range::Blend::generic`]): a format without alpha reads a destination alpha of one. -fn generic( - eq: &BlendEquation, - pf: crate::metal::PixelFormat, - written: ColorWriteMask, -) -> Result { - let has_alpha = channels(pf).contains(ColorWriteMask::ALPHA); - extended_range::Blend::generic(eq, has_alpha, written) -} - -/// The arithmetic of Metal's 16-bit float blend of entry `e`'s write of color attachment `color`, -/// and the output's lanes: that of its first (index 0) output there, where it is one to four lanes -/// of `half` or `float`, and the entry writes no second (index 1) output there; `None` for another -/// output, or none. -pub(crate) fn blended_output( - e: &crate::air::Entry, - color: u32, -) -> Option<(extended_range::blend::BlendArith, u32)> { - let types = e.module.types(); - let func = e.module.func(e.func)?; - let Some(AirType::Function { ret, .. }) = types.get(func.ty) else { - return None; - }; - let field = |i: u32| match types.get(*ret) { - Some(AirType::Struct { fields, .. }) => fields.get(i as usize).copied(), - Some(AirType::Void) | None => None, - Some(_) => Some(*ret), - }; - let of = |ty: AirTypeId| match types.get(ty) { - Some(AirType::Half) => Some(extended_range::blend::BlendArith::Half), - Some(AirType::Float) => Some(extended_range::blend::BlendArith::Float), - _ => None, - }; - let arith = |ty: AirTypeId| match types.get(ty) { - Some(AirType::Vector { elem, len }) if (1..=4).contains(len) => Some((of(*elem)?, *len)), - Some(_) => Some((of(ty)?, 1)), - None => None, - }; - let to = |o: &crate::air::abi::OutputBinding, index: u32| { - matches!( - o.role, - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: i, - .. - } if a == color && i == index - ) - }; - let outputs = &e.ep.outputs; - if outputs.iter().any(|o| to(o, 1)) { - return None; - } - outputs - .iter() - .find(|o| to(o, 0)) - .and_then(|o| field(o.field)) - .and_then(arith) -} - -/// Whether Metal's compiler may fold the arithmetic of the function's first output to color -/// attachment `color` into the blend it computes there, under blend math `math`: the blend is -/// code Metal's compiler appends to the function before its fast-math passes, so a lane of the -/// output the function computes by a floating-point operation carrying a fast-math flag (an -/// addition, subtraction, multiply, division or remainder, an `llvm.fmuladd`), a constant, a -/// select or phi of one, or the attachment's own color input, is contracted, regrouped or folded -/// with the blend's arithmetic (plain Metal on the M3 Max under macOS 27.0.1: a -/// returned product fused into the blend's one minus the source alpha, `D·k + D·A` regrouped as -/// `D·(k + A)`). A lane of a load, a call, a conversion, a parameter or an operation without -/// fast-math flags is opaque to it: the blend reads the value the function computes. Each lane -/// is followed back through `insertvalue`, `insertelement`, `shufflevector`, `extractelement` and -/// `fneg`; a return whose field cannot be followed so counts as folded. Without fast math -/// (`BlendMath::Rounded`) nothing folds but exactly: a module without fast-math flags allows only -/// exact rewrites. -fn folds_into_blend( - cx: &SelectCx<'_>, - color: u32, - math: extended_range::blend::BlendMath, -) -> Result { - use crate::air::ir::BinOp as AirBin; - if math == extended_range::blend::BlendMath::Rounded { - return Ok(false); - } - let Some(field) = cx.entry.ep.outputs.iter().find_map(|o| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: 0, - .. - } if a == color => Some(o.field), - _ => None, - }) else { - return Ok(true); - }; - // The output's lanes; the blend reads a missing one as zero. - let lanes = blended_output(cx.entry, color).map_or(4, |(_, n)| n); - let types = cx.entry.module.types(); - let consts = cx.entry.module.consts(); - let structured = cx - .entry - .module - .func(cx.entry.func) - .and_then(|f| match types.get(f.ty) { - Some(AirType::Function { ret, .. }) => types.get(*ret), - _ => None, - }) - .is_some_and(|t| matches!(t, AirType::Struct { .. })); - let color_input = |a: u32| { - cx.entry.ep.params.iter().any(|b| { - b.param == a - && matches!( - b.role, - ParamRole::ColorInput { - index: AbiInt::Const(c), - .. - } if c == color - ) - }) - }; - let const_index = |v: Value| match v { - Value::Const(c) => match consts.get(c).map(|k| &k.value) { - Some(crate::air::ir::Const::Int(b)) => u32::try_from(*b).ok(), - _ => None, - }, - _ => None, - }; - let lanes_of = |v: Value| { - cx.value_ty(v).and_then(|t| match types.get(t) { - Some(AirType::Vector { len, .. }) => Some(*len), - _ => None, - }) - }; - let limit = cx.body.insts.len().saturating_add(8); - // Whether lane `lane` of `v` folds into the blend. - let folds = |mut v: Value, mut lane: u32| -> bool { - for _ in 0..limit { - let at = match v { - Value::Const(_) => return true, - Value::Arg(a) => return color_input(a.raw()), - Value::Inst(at) => at, - }; - let Some(inst) = cx.body.insts.get(at) else { - return true; - }; - match &inst.kind { - InstKind::BinOp { op, fmf, .. } => { - let float = matches!( - op, - AirBin::FAdd | AirBin::FSub | AirBin::FMul | AirBin::FDiv | AirBin::FRem - ); - return float && !fmf.is_empty(); - } - InstKind::FNeg { v: x, .. } => v = *x, - InstKind::InsertElement { vec, elt, idx } => match const_index(*idx) { - Some(k) if k == lane => { - v = *elt; - lane = 0; - } - Some(_) => v = *vec, - None => return true, - }, - InstKind::ShuffleVector { a, b, mask } => { - let Some(Some(pick)) = mask.get(lane as usize).copied() else { - return true; - }; - let Some(n) = lanes_of(*a) else { return true }; - (v, lane) = if pick < n { (*a, pick) } else { (*b, pick - n) }; - } - InstKind::ExtractElement { vec, idx } => match const_index(*idx) { - Some(k) => { - v = *vec; - lane = k; - } - None => return true, - }, - InstKind::Select { t, f, .. } => { - return matches!(t, Value::Const(_)) || matches!(f, Value::Const(_)); - } - InstKind::Phi { incoming, .. } => { - return incoming.iter().any(|(x, _)| matches!(x, Value::Const(_))); - } - InstKind::Call(call) => { - return matches!( - call.callee, - Callee::Llvm { - op: crate::air::intrinsics::LlvmIntrinsic::Float { - op: crate::air::intrinsics::LlvmFloatOp::FMulAdd, - .. - }, - .. - } - ); - } - _ => return false, - } - } - true - }; - // The field's value at each return. - let field_of = |mut v: Value| -> Option { - if !structured { - return Some(v); - } - for _ in 0..limit { - let Value::Inst(at) = v else { return None }; - let InstKind::InsertValue { agg, val, indices } = &cx.body.insts.get(at)?.kind else { - return None; - }; - if indices.as_ref() == [field] { - return Some(*val); - } - v = *agg; - } - None - }; - for (_, inst) in cx.body.insts.iter() { - let InstKind::Ret(Some(r)) = &inst.kind else { - continue; - }; - let Some(v) = field_of(*r) else { - return Ok(true); - }; - if (0..lanes).any(|lane| folds(v, lane)) { - return Ok(true); - } - } - Ok(false) -} - -/// What the function does that the storage form of one color depends on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct ColorUse { - /// The function writes the attachment through a first (index 0) output. - pub writes: bool, - /// The module declares early fragment tests: Metal's function does, or the pipeline has a - /// depth or stencil attachment and the function's writes are Metal's under them (see the - /// module docs). - pub early_tests: bool, - /// The module declares no early tests only because the function discards, and each draw's - /// plan checks that its depth and stencil tests drop no fragment - /// (`RuntimeFact::TestedStorageWrites`): a write then stores before them as Metal's does - /// after them. - pub draw_tested: bool, - /// The function's math, which picks the extended-range blends Metal's model holds - /// (`extended_range::blend::BlendMath`). - pub math: extended_range::blend::BlendMath, - /// The pipeline's private logic operation the function computes over the codes of the - /// attachments it writes (`LoweringInputs::logic_operation`, `logic`). - pub logic_op: Option, -} - -/// How the storage form's image holds the attachment's samples. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum StorageSamples { - /// A pipeline of one sample: a single-sample 2D image, pixel `(x, y)` at texel `(x, y)`. - One, - /// The pipeline's samples in a multisampled 2D image, sample `s` of pixel `(x, y)` read and - /// written at texel `(x, y)` with the `Sample` operand `s`. - Multisampled, - /// The pipeline's samples as planes, on a device without multisampled storage images: a - /// single-sample 2D-array image of one layer per sample, sample `s` of pixel `(x, y)` at - /// texel `(x, y, s)`. - Planes, -} - -/// How the storage form declares and views one attachment. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct StorageView { - /// The attachment's Metal pixel format. - pub pixel_format: crate::metal::PixelFormat, - /// The attachment's Vulkan format, which the view takes (but an sRGB attachment's, - /// [`uint_view`](Self::uint_view), and a BGRA-order one's [`rgba_view`](Self::rgba_view)). - pub format: vk::Format, - /// The declared SPIR-V image format: `Unknown` for a formatless declaration. - pub declared: crate::spv::ImageFormat, - /// The numeric type of the attachment's texels, the declaration's sampled type. - pub numeric: SampledType, - /// How the image holds the attachment's samples. - pub samples: StorageSamples, - /// The format's channels a write of the function keeps from the texel it overwrites: those - /// outside the descriptor's write mask, which the storage write takes from the texel it reads - /// first. Empty where the function does not write the attachment, or the mask covers every - /// channel of the format; all four (`R`, `G`, `B` and `A`) where it covers none of them, so - /// that the write stores nothing. Where [`kept_at_draw`](Self::kept_at_draw), the class's: the - /// channels the descriptor's mask keeps are the draw's. - pub kept: vk::ColorComponentFlags, - /// The write keeps some channels and takes which from the draw: the bits of - /// `PushField::StorageKeptChannels` for the attachment's color (`GraphicsState`'s - /// `StorageAttachmentUse::kept`), not [`kept`](Self::kept), which names the class. - pub kept_at_draw: bool, - /// The attachment's extended-range form, whose image holds Metal's raw texels: the - /// declaration's texels are the raw format's `uint`s ([`numeric`](Self::numeric)), and a read - /// decodes Metal's tile value. `None` for a format held directly. - pub extended: Option, - /// The blend a write computes in the shader, from the texel it reads first: the pipeline's, - /// where it enables blending there, of an extended-range attachment by the device's arithmetic - /// (`extended_range::blend::native`), Metal's of a 16-bit float, 8-bit unorm or packed 16-bit - /// one, or the generic one of another format - /// ([`generic_blend`](Self::generic_blend)). - /// `None` for an unblended write or no write. - pub blend: Option, - /// The shader computes [`blend`](Self::blend) by the generic float blend - /// ([`extended_range::Blend::generic`], [`generic_blended`]): the blend of a format held - /// directly whose Metal arithmetic is not built, a near-equivalent the function notes - /// (`PrecisionNote::UnmeasuredFetchBlend`). - pub generic_blend: bool, - /// The unsigned-integer format of the texel size an sRGB attachment is viewed in - /// (`StorageAttachmentUse::view_alias`): the declaration's texels are its `uint`s, which a - /// read unpacks and decodes and a write encodes and packs, by the device's conversion. - /// `None` for another format. - pub uint_view: Option, - /// The RGBA-order twin a BGRA-order attachment is viewed in (`StorageAttachmentUse:: - /// view_alias`, `metal::format::rgba_twin`) on a device that accesses its own format without - /// one in neither direction: the declaration is the twin's, and every texel read from the - /// image or written to it has red and blue exchanged ([`metal_order`]), so the function sees - /// Metal's channels. `None` for another format and device. - pub rgba_view: Option, - /// The word layout of a packed 16-bit attachment the device renders through a view of its - /// words (`metal::format::WordAttachment`): the view and the declaration are the word's - /// unsigned integer format, and a write encodes Metal's word ([`word_texel`]). `None` for - /// another format and device. - pub word: Option, - /// The attachment's image holds Metal's alpha in red (`metal::format::alpha_in_red`: - /// `A8Unorm` in `R8_UNORM` on a device without `A8_UNORM`): the view and the declaration are - /// `R8_UNORM`'s, a texel read from the image, `(r, 0, 0, 1)`, is Metal's `(0, 0, 0, r)`, and a - /// texel written to it holds Metal's alpha in red ([`metal_order`], [`image_order`]). - pub alpha_in_red: bool, - /// The attachment's image holds Metal's channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`, - /// `metal::format::FormatEmulation::RotatedView`): its red, green, blue and alpha are Metal's - /// alpha, red, green and blue, so a texel read from the image is rotated into Metal's order and - /// one written to it out of it ([`metal_order`], [`image_order`]). - pub rotated: bool, - /// The pipeline's private logic operation a write computes over the codes of the texel it - /// reads first (`logic::operated`), of an attachment whose channels it serves - /// (`logic::channels`). `None` for no write, and for every other attachment. - pub logic_op: Option, -} - -impl StorageView { - /// The numeric class of the function's reads and writes: an extended-range attachment's - /// values are floats, whatever its raw texels. - pub fn read_class(&self) -> SampledType { - match (self.extended, self.uint_view, self.word) { - (Some(_), _, _) | (_, Some(_), _) | (_, _, Some(_)) => SampledType::Float, - (None, None, None) => self.numeric, - } - } - - /// Whether a write stores nothing: the mask covers none of the format's channels. - pub fn stores_nothing(&self) -> bool { - self.kept == vk::ColorComponentFlags::known_bits() - } - - /// Whether a write merges: it keeps some of the format's channels and stores the others. - pub fn merges(&self) -> bool { - !self.kept.is_empty() && !self.stores_nothing() - } - - /// Whether the declaration names no format. - pub fn formatless(&self) -> bool { - self.declared == crate::spv::ImageFormat::Unknown - } -} - -/// One color attachment the function reads in the storage form. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct StorageColor { - pub view: StorageView, - /// The function writes the attachment. - pub writes: bool, - /// The returned value's field that holds the write (0 for a returned value itself) and the - /// output's form, once the stage interface planned it. - pub output: Option<(u32, Form)>, - /// The returned value's field that holds the function's second (index-1) output to the - /// attachment and its form, once the stage interface planned it: the second source of an - /// extended-range blend the shader computes ([`select_second_output`]). - pub second: Option<(u32, Form)>, - /// The 16-bit float blend the shader computes ([`StorageView::blend`] of a format held - /// directly) is Metal's exactly: its forms are fitted (`extended_range::Blend::fitted`), the - /// module states its math, and Metal cannot fold the output's arithmetic into it - /// ([`folds_into_blend`]). Where not, the function notes the near-equivalent. True for - /// another attachment. - pub exact_blend: bool, - /// The pipeline rounds its half-float channels to nearest even - /// (`TextureWriteRoundingMode::NearestEven`), which a 16-bit float blend of a `float4` output - /// rounds its result by, as Metal's blended write does; else toward zero. - pub nearest_even: bool, -} - -fn not_implemented() -> Unsupported { - Unsupported::not_implemented(Feature::FramebufferFetch) -} - -/// Whether `format`'s float channels are narrower than 32 bits (a half-float or a packed float -/// format), whose texels a read decodes into `float`. -fn narrow_float(format: vk::Format) -> bool { - format.block().is_some_and(|b| match b.color { - Some(vk::NumericFormat::Sfloat) => b.component_bits != Some(32), - Some(vk::NumericFormat::Ufloat) => true, - _ => false, - }) -} - /// 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). @@ -906,11 +154,9 @@ fn channels(pf: crate::metal::PixelFormat) -> ColorWriteMask { .fold(ColorWriteMask::NONE, |m, &c| m.union(c)) } -/// Whether a storage-form write to an attachment of `pf` that keeps some of its channels takes -/// them from the draw (`PushField::StorageKeptChannels`), so that the write masks of a class -/// compile alike ([`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, whose write merges the -/// bytes of its `uint` view. +/// 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()) @@ -937,9 +183,9 @@ pub(crate) fn kept_channels( } } -/// The write mask a fragment function compiles the storage form of an attachment of `pf` under, +/// 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 -/// write takes its kept channels from the draw ([`kept_at_draw`]), the class of `mask` alone (none +/// 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 @@ -981,326 +227,15 @@ pub(crate) fn compiled_write_mask( } } -/// The storage form of the read of color attachment `color` of a pipeline whose state is -/// `inputs` (`multisampled`: it rasterizes more than one sample, so the form is per sample) by a -/// function whose use of it is `use_`, on `p` (see the module docs): `Ok(Ok(view))` where the -/// form is exact, `Ok(Err(why))` -/// where the pipeline's state, the function, or the device blocks it, and `Err` for a -/// descriptor error that refuses the pipeline whatever the form (no attachment at `color`, a -/// pixel format no color attachment can have). -pub(crate) fn storage_form( - color: u32, - inputs: &FramebufferFetchInputs, - multisampled: bool, - use_: ColorUse, - p: &DeviceProfile, -) -> Result, Error> { - let attachment: FetchedAttachment = - inputs - .attachments - .get(&color) - .copied() - .flatten() - .ok_or(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::NilWithError, - }))?; - let pf = attachment.pixel_format; - // A packed 16-bit attachment the device samples but does not render renders through a view of - // its words, which the function stores as Metal's word and merges by its fields. - let word = WordAttachment::of(pf, p); - let usages = BTreeSet::from([FormatUsage::ColorAttachment]); - let (format, emulation) = match word { - Some(word) => (word.word_format(), FormatEmulation::Direct), - None => { - let mapping = crate::metal::format::vk_format(pf, &usages, p)?; - (mapping.format, mapping.emulation) - } - }; - // An extended-range attachment holds Metal's raw texels in its raw format, which a read - // decodes. - let extended = ExtendedRange::of(pf); - let srgb = format - .block() - .is_some_and(|b| b.color == Some(vk::NumericFormat::Srgb)); - // An 8-bit sRGB attachment is viewed in the unsigned integer format of its texel (`R8_UINT`, - // `R16_UINT` or `R32_UINT`), whose bytes the function decodes and encodes by the device's - // conversion (`arith::pack`'s, a channel the format lacks 0 and alpha 1, a write's encode of - // Metal's blend where it blends). - // A BGRA-order attachment on a device that accesses its format without one in neither - // direction (SPIR-V names no image format for it) is viewed in its RGBA-order twin, whose red - // and blue the function exchanges on every read and write: the device converts each channel - // as it converts the attachment's, so the values are those of the attachment's own view. - let alias = StorageAttachmentUse::view_alias_of(format, p) - .filter(|_| emulation == FormatEmulation::Direct && word.is_none()); - let uint_view = alias.filter(|&u| { - srgb && matches!( - u, - vk::Format::R8_UINT | vk::Format::R16_UINT | vk::Format::R32_UINT - ) - }); - let rgba_view = alias.filter(|_| !srgb); - let viewed = uint_view.or(rgba_view).unwrap_or(format); - let writes = use_.writes; - // The channels a write keeps from the texel: those of the format the descriptor's mask leaves - // out, or all four where it leaves out every one (the write stores nothing). An `Unspecialized` - // mask is a placeholder, which no form serves. - let all = channels(pf); - let kept = kept_channels(pf, attachment.write_mask, writes); - let merged = !kept.is_empty() && kept != ColorWriteMask::ALL; - // A write that keeps some channels of a format whose kept channels are the draw's: the - // write mask is its class's (`compiled_write_mask`), and the draw's word names them. - let kept_draw = merged && kept_at_draw(pf); - let snorm = format - .block() - .is_some_and(|b| b.color == Some(vk::NumericFormat::Snorm)); - // A returned sample mask keeps the invocation's own sample when it sets its bit: the per-sample - // form gates its write on that bit, and a write at one sample on bit 0. A kept channel of a - // signed normalized format beside a written one is not modelled either: its two codes of -1 - // read alike, so writing back what was read would not keep the texel's bits. A write that - // stores some of an extended-range attachment's channels is built unblended (the codes of the - // channels it keeps merged from the texel), and under a blend Metal's model covers, which the - // shader computes: no device blends the raw texels. A write whose mask covers none of the format's channels stores - // nothing, so nothing a store depends on (the blend, coverage, the sample mask, the depth and - // stencil tests) bears on it; and a blend of one and zero, added, for color and alpha stores - // the source as blending disabled does, a signed normalized NaN aside, and a 16-bit float - // attachment's blend without fast math, which keeps the destination's product by zero (a NaN - // of an infinite or NaN texel, the sum's zero sign). - let stores = writes && kept != ColorWriteMask::ALL; - // The pipeline's private logic operation, which a write that stores computes over the codes - // of an attachment whose channels it serves (`logic`); a float attachment ignores it, as - // Metal's does. Metal's operation reads a signed normalized channel's codes through its value - // too, so a kept channel written back as it was read is Metal's there. - let logic_op = use_ - .logic_op - .filter(|_| stores && super::logic::channels(pf).is_some()); - // The blend of an extended-range attachment the write stores, which the shader computes - // where Metal's measured model holds it (`extended_range::Blend`), its gap refused by name. - // And the blend of a 16-bit float attachment, which no Vulkan blend applies to a storage - // write: the shader computes Metal's, in the arithmetic of a four-lane `half` or `float` - // output, which [`plan`] checks (`extended_range::Blend::half_float`: every factor and - // operation but the second source's, which the generic blend below takes). A channel the - // format lacks counts as written, as [`plan`] plans it. - let kept_zero = use_.math == extended_range::blend::BlendMath::Rounded; - let written_of_four = ColorWriteMask::ALL.difference(kept); - let half_blend = half_float_format(pf) - && attachment.blending_enabled - && (!attachment.replaces || kept_zero) - && attachment.equation.is_some_and(|eq| { - extended_range::Blend::half_float(&eq, pf, written_of_four, use_.math).is_ok() - }); - // And the blend of an 8-bit unorm attachment where Metal's measured model holds it - // (`extended_range::Blend::unorm8`: every factor and operation but the second source's, any - // write mask); its other blends take the generic blend below. - let half = extended_range::blend::BlendArith::Half; - let unorm8_blend = unorm8_format(pf) - && attachment.blending_enabled - && !attachment.replaces - && attachment.equation.is_some_and(|eq| { - extended_range::Blend::unorm8(&eq, pf, written_of_four, (use_.math, half)).is_ok() - }); - // And the blend of a packed 16-bit attachment rendered through its word view, which no - // device blends (`extended_range::Blend::packed16`: every factor and operation but the second - // source's, any write mask). - let word_blend = packed16_format(pf) - && word.is_some() - && attachment.blending_enabled - && !attachment.replaces - && attachment.equation.is_some_and(|eq| { - extended_range::Blend::packed16(&eq, written_of_four, use_.math).is_ok() - }); - // And the blend of an 8-bit sRGB attachment viewed in its unsigned integer format, which no - // device blends: the shader computes Metal's, the 8-bit unorm blend over the decoded texel, - // encoded (`extended_range::Blend::srgb8`: its rounded forms where the 8-bit unorm blend is - // not built, a near-equivalent [`plan`] notes under fast math). - let srgb_blend = uint_view.is_some() - && attachment.blending_enabled - && !attachment.replaces - && attachment.equation.is_some_and(|eq| { - extended_range::Blend::srgb8(&eq, pf, written_of_four, (use_.math, half)).is_ok() - }); - // And any other blend of a float-class format held directly (not an sRGB or a word one), - // whose Metal arithmetic is not built: the shader computes the generic float blend - // (`extended_range::Blend::generic`), a near-equivalent [`plan`] takes only where the function - // reads the attachment, and notes. - let float_class = sampled_type(pf) == Some(SampledType::Float); - let generic_blend = stores - && attachment.blending_enabled - && !(attachment.replaces && !snorm) - && float_class - && !srgb - && extended.is_none() - && word.is_none() - && !(half_blend || unorm8_blend); - let blend = attachment.equation.filter(|_| { - (extended.is_some() - || half_blend - || unorm8_blend - || word_blend - || srgb_blend - || generic_blend) - && stores - }); - if let Some(eq) = blend { - let planned = match extended { - Some(_) => { - let written = all.intersection(attachment.write_mask); - extended_range::blend::NativeBlend::of(&eq, written).map(drop) - } - None if generic_blend => generic(&eq, pf, written_of_four).map(drop), - None => direct_blend(&eq, pf, written_of_four, (use_.math, half)).map(drop), - }; - match planned { - Ok(_) => {} - Err(Error::Unsupported(gap)) => return Ok(Err(gap)), - Err(e) => return Err(e), - } - } - let shader_blends = blend.is_some(); - let blends = attachment.blending_enabled && !(attachment.replaces && !snorm) && !shader_blends; - // An `A8Unorm` attachment whose image holds Metal's alpha in red, for every use of the - // texture (`metal::format::alpha_in_red`), is read and written through its `R8_UNORM` image, - // the function moving Metal's alpha into and out of red. - let alpha_in_red = emulation == FormatEmulation::AlphaInRed - && crate::metal::format::alpha_in_red(pf, p) - && word.is_none(); - // An `ARGB8Unorm` attachment is read and written through its `R8G8B8A8_UNORM` image, the - // function rotating Metal's channels into and out of the image's. - let rotated = emulation == FormatEmulation::RotatedView; - // The logic operation reads the codes of a texel held directly; a word view's, and a write - // under alpha to coverage, are refused naming it (`logic`). - if logic_op.is_some() && (word.is_some() || inputs.alpha_to_coverage) { - let gap = Feature::PrivateRenderState(crate::error::PrivateRenderField::LogicOperation); - return Ok(Err(Unsupported::not_implemented(gap))); - } - // An unblended write of every channel stores Metal's write of the output. - let not_modelled = inputs.amplified - || (emulation != FormatEmulation::Direct && extended.is_none() && !alpha_in_red && !rotated) - || (extended.is_some() && stores && !shader_blends && attachment.blending_enabled) - || (srgb && uint_view.is_none()) - // An `RGB9E5Float` word's mantissas share its exponent: no field is kept apart. - || (word == Some(WordAttachment::Rgb9e5) && stores && merged) - || (writes - && attachment - .write_mask - .contains(ColorWriteMask::UNSPECIALIZED)) - || (stores - && (blends - || (snorm && merged && logic_op.is_none()) - || inputs.alpha_to_coverage - || (inputs.depth_or_stencil && !use_.early_tests && !use_.draw_tested))); - if not_modelled { - return Ok(Err(not_implemented())); - } - let kept = crate::metal::state::color_write_mask(kept)?; - let f = p.fields(); - // What the form needs whatever view it takes, and what the view's own route lacks. - let mut common = Vec::new(); - let mut route = Vec::new(); - // The per-sample form: the image read and written at the invocation's `SampleId`, which needs - // sample-rate shading. It is multisampled where the device has multisampled storage images (its - // sample count is the pipeline's, which link checks against `storageImageSampleCounts`), and - // planes elsewhere. - let samples = match (multisampled, f.images.storage_multisample) { - (false, _) => StorageSamples::One, - (true, true) => StorageSamples::Multisampled, - (true, false) => StorageSamples::Planes, - }; - if multisampled && !f.fragment.sample_rate_shading { - common.push(Capability::Feature(VkFeature::SampleRateShading)); - } - if writes && !f.leaf.fragment_stores_and_atomics { - common.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics)); - } - if !p.supports_format(viewed, FormatUsage::StorageImage) { - route.push(Capability::Format { - format: viewed, - usage: FormatUsage::StorageImage, - }); - } - // Declared without a format where the device's features grant the format that access without - // one, so that the declaration, and with it the module, is the same for every format the - // function reads alike (a `BGRA8Unorm` attachment's and an `RGBA16Float` one's); else with its - // SPIR-V image format where the device can (no format feature beyond storage); else without a - // format where the format's own bits allow it (`without_format_gaps`: Vulkan 1.3 or - // `VK_KHR_format_feature_flags2`). - let use_without = StorageUse::texture(true, writes); - let typed = spirv_image_format(viewed).filter(|d| { - !crate::spirv::requirements::extended_format(*d) || f.images.storage_extended_formats - }); - let declared = match typed { - _ if accessed_without_format(viewed, use_without, p) => { - Some(crate::spv::ImageFormat::Unknown) - } - Some(d) => Some(d), - None => { - let gaps = without_format_gaps(viewed, use_without, p); - if gaps.is_empty() { - Some(crate::spv::ImageFormat::Unknown) - } else { - match spirv_image_format(viewed) { - Some(_) => route.push(Capability::Feature( - VkFeature::ShaderStorageImageExtendedFormats, - )), - None => route.extend(gaps), - } - None - } - } - }; - let numeric = match (extended, uint_view, word) { - (Some(_), _, _) | (_, Some(_), _) | (_, _, Some(_)) => SampledType::Uint, - (None, None, None) => sampled_type(pf).ok_or_else(not_implemented)?, - }; - match declared { - Some(declared) if common.is_empty() && route.is_empty() => Ok(Ok(StorageView { - pixel_format: pf, - format, - declared, - numeric, - samples, - kept, - kept_at_draw: kept_draw, - extended, - blend, - generic_blend: generic_blend && blend.is_some(), - uint_view, - rgba_view, - word, - alpha_in_red, - rotated, - logic_op, - })), - _ => { - // A BGRA-order format no declaration reaches, whose RGBA-order twin lacks something - // too: either route's gaps. - let mut alternatives = vec![[common.clone(), route].concat()]; - let twin_gaps = rgba_twin(viewed) - .filter(|_| declared.is_none()) - .map(|twin| rgba_twin_gaps(twin, p)) - .filter(|gaps| !gaps.is_empty()); - if let Some(twin_gaps) = twin_gaps { - alternatives.push([common, twin_gaps].concat()); - } - Ok(Err(Unsupported::needs_any_of( - Feature::FramebufferFetch, - alternatives, - ))) - } - } -} - /// 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 -/// [`plan`] and [`storage_form`] make for such an attachment, written whole by the function's +/// `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 -/// the pixel interlock alone ([`interlock_orders`]) and that storage form is exact there; `Ok` -/// where it 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, without -/// either ordering the two it needs one of ([`unordered_extended_fetch`]). A bfloat format, which +/// 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. @@ -1326,143 +261,27 @@ pub(crate) fn extended_range_blend( destination_alpha: F::OneMinusSourceAlpha, alpha_operation: O::Add, }; - if !interlock_orders(p) { - 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)), - } - return match extended_range::blend::NativeBlend::of(&equation, channels(pf)) { - Ok(_) => Ok(()), - Err(Error::Unsupported(gap)) => Err(gap), - Err(_) => Err(Unsupported::not_representable(Feature::Format)), - }; + if fetch_unordered(p) { + return Err(unordered_extended_fetch()); } - let attachment = FetchedAttachment { - pixel_format: pf, - blending_enabled: true, - write_mask: ColorWriteMask::ALL, - replaces: false, - equation: Some(equation), - }; - let inputs = FramebufferFetchInputs { - attachments: BTreeMap::from([(0, Some(attachment))]), - depth_or_stencil: false, - alpha_to_coverage: false, - amplified: false, - }; - let use_ = ColorUse { - writes: true, - early_tests: false, - draw_tested: false, - math: extended_range::blend::BlendMath::Fast, - logic_op: None, - }; - match storage_form(0, &inputs, false, use_, p) { - Ok(form) => form.map(drop), + // 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)), } } -/// What the function's body holds that the storage form depends on, from one walk. -#[derive(Default)] -pub(super) struct BodyFacts { - /// The LLVM parameters the body reads. - pub(super) used: BTreeSet, - /// The body discards the fragment. - pub(super) discards: bool, - /// The body writes memory (`discard::side_effect`). - pub(super) side_effects: bool, -} - -/// How the depth and stencil tests bear on the function's storage writes, which it makes before -/// them where the module declares no early tests (module docs). -#[derive(Clone, Copy)] -struct StoredBeforeTests { - /// Only its discard keeps the function from early tests: its stores are Metal's where a - /// draw's tests drop no fragment, and under early tests where they write and count nothing. - tested: bool, - /// It writes other memory, or returns depth, stencil, or a sample mask: its stores are Metal's - /// only where a draw's tests drop no fragment. - untested: bool, -} - -/// [`StoredBeforeTests`] of a function whose body holds `body`, that Metal runs under early tests -/// where `declared_early` and returns depth, stencil, or a sample mask where `exports`, in a -/// pipeline with a depth or stencil attachment where `depth_or_stencil`. -fn stored_before_tests( - body: &BodyFacts, - (declared_early, exports): (bool, bool), - depth_or_stencil: bool, -) -> StoredBeforeTests { - let testable = depth_or_stencil && !(exports || body.side_effects); - StoredBeforeTests { - tested: !declared_early && testable && body.discards, - untested: !declared_early && depth_or_stencil && (exports || body.side_effects), - } -} - -pub(super) fn body_facts(cx: &SelectCx<'_>) -> BodyFacts { - let mut out = BodyFacts::default(); - for (id, inst) in cx.body.insts.iter() { - inst.kind.for_each_value(|v| { - if let Value::Arg(a) = v { - out.used.insert(a.raw()); - } - }); - if let InstKind::Call(call) = &inst.kind { - if matches!( - call.callee, - Callee::Air { - op: AirIntrinsic::Fragment(Fragment::Discard), - .. - } - ) { - out.discards = true; - } - } - if super::discard::side_effect(cx, id, inst) { - out.side_effects = true; - } - } - out -} - -/// The color attachments the function reads: those of its used `[[color(n)]]` parameters of a -/// constant index (another index is refused when the parameter is planned). Each such -/// parameter's type is checked here, so a function no pipeline state would make lowerable is -/// refused before it needs one. -pub(super) fn colors_read(cx: &SelectCx<'_>, used: &BTreeSet) -> Result, Error> { - let mut out = BTreeSet::new(); - for b in cx - .entry - .ep - .params - .iter() - .filter(|b| used.contains(&b.param)) - { - if let ParamRole::ColorInput { - index: AbiInt::Const(color), - .. - } = b.role - { - super::color::param_form(cx, b) - .map_err(|e| e.at_attachment(Attachment::Color(color)))?; - out.insert(color); - } - } - Ok(out) -} - /// The extended-range attachments the function writes through a first output where the -/// pipeline blends them (`LoweringInputs::extended_range_colors`), which only the storage form -/// writes, and the AIR type of each output. A blend into one of Apple's extended-range forms +/// 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(); @@ -1492,419 +311,6 @@ pub(super) fn blended_extended_range(cx: &SelectCx<'_>) -> Result) -> Result<(), Error> { - if cx.stage != Stage::Fragment || !interlock_orders(cx.profile) { - return Ok(()); - } - let body = body_facts(cx); - let outputs = &cx.entry.ep.outputs; - let returns = |role: fn(&OutputRole) -> bool| outputs.iter().any(|o| role(&o.role)); - let exports = returns(|r| { - matches!( - r, - OutputRole::Depth(_) | OutputRole::Stencil | OutputRole::SampleMask - ) - }); - let declared_early = matches!( - cx.entry.ep.stage, - crate::air::abi::Stage::Fragment { - early_fragment_tests: true - } - ); - // A draw may move a color the function writes through its first output into the storage - // form: a color its render pass instance keeps out of its subpass for other draws' - // interlocked form (`VariantKey::interlocked_colors`, single-sampled). The plan of the - // pipeline as compiled, which stores no color so, selects the tests such a draw's variant - // needs from this. - let movable = stored_before_tests(&body, (declared_early, exports), true); - if (movable.tested || movable.untested) - && returns(|r| matches!(r, OutputRole::RenderTarget { index: 0, .. })) - { - cx.facts.insert(RuntimeFact::MovableStorageWrites { - early_variant: movable.tested && !movable.untested, - }); - } - let blended = blended_extended_range(cx)?; - // A blend into a bfloat attachment is Metal's pipeline error (its validation asserts that the - // format is not blendable), which link refuses whatever the function writes there. - let bfloat = blended.iter().find(|&&(color, _)| { - cx.inputs - .extended_range_colors - .get(&color) - .is_some_and(|e| e.form.bfloat()) - }); - if let Some(&(color, _)) = bfloat { - let invalid = DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::EndsProcess, - }; - return Err(Error::InvalidDescriptor(invalid)); - } - let fetched = colors_read(cx, &body.used)?; - let mut read = fetched.clone(); - read.extend(blended.iter().map(|&(color, _)| color)); - // Every other attachment the pipeline's state names that the function writes through its - // first output: a color the draw moved into the storage form (above), written through it as a - // fetched one is, or one named for Metal's 16-bit float blend alone. - if let Some(inputs) = &cx.inputs.framebuffer_fetch { - read.extend(outputs.iter().filter_map(|o| match o.role { - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } if inputs.attachments.contains_key(&color) => Some(color), - _ => None, - })); - } - if read.is_empty() { - return Ok(()); - } - // Metal's blend into an extended-range attachment is modelled for a `half4` output, and for a - // `float4` one under a blend that takes it rounded to `half` (`extended_range::Blend::takes`); - // another `float` one is rounded otherwise, unfitted. - let mut outputs4 = BTreeMap::new(); - for (color, ty) in blended { - let f = - super::color::form(cx, ty).map_err(|e| e.at_attachment(Attachment::Color(color)))?; - if f.lanes == 4 { - if let Some(fmt) = f.float_fmt() { - outputs4.insert(color, fmt); - } - } - } - let Some(inputs) = cx.inputs.framebuffer_fetch.clone() else { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - }; - // The module declares early fragment tests so that a depth or stencil test the fragment - // fails drops its storage writes, as it drops Metal's color write; it may only where they - // keep the function's writes Metal's (no discard, no depth, stencil, or coverage export, no - // other memory write). Without a depth or stencil attachment no test can fail, so the - // declaration would change nothing, and it is left out: Apple's GPU drops the image writes - // of an early-tests fragment shader in a pass of more than one sample. - let testable = inputs.depth_or_stencil && !(exports || body.side_effects); - // A function that only its discard keeps from early tests, on a device that requires ordered - // fetch (`tested`): its storage writes are Metal's where its draws' tests drop no fragment, - // before the tests, and where they write neither attachment and count no visibility result, - // under early tests (`LoweringInputs::read_only_tests`), which then drop no fragment Metal's - // later tests keep and leave the attachments as Metal's do; the plan of each draw checks - // which (`RuntimeFact::TestedStorageWrites`). One that writes other memory, or returns depth, - // stencil, or a sample mask, beside a depth or stencil attachment (`untested`): Metal runs its memory writes for every fragment, - // those its tests then drop included, and tests what it returns (measured on Apple's M4), which - // early tests would not, so its storage writes before the tests are Metal's where its draws' - // tests drop no fragment, which the plan of each draw checks; it has no early-tests variant. - let StoredBeforeTests { tested, untested } = - stored_before_tests(&body, (declared_early, exports), inputs.depth_or_stencil); - let early_tests = declared_early - || (testable && !body.discards && !untested) - || (tested && cx.inputs.read_only_tests && !untested); - for color in read { - // Compiled under the state of a pipeline for another function. - if !inputs.attachments.contains_key(&color) { - return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); - } - let writes = outputs.iter().any(|o| { - matches!( - o.role, - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: 0, - .. - } if a == color - ) - }); - let use_ = ColorUse { - writes, - early_tests, - draw_tested: (tested || untested) && !early_tests, - math: blend_math(cx), - logic_op: cx.inputs.logic_operation, - }; - let tied = |e: Error| e.at_attachment(Attachment::Color(color)); - let form = - storage_form(color, &inputs, cx.inputs.multisampled, use_, cx.profile).map_err(tied)?; - // Metal's blend of a 16-bit float attachment, computed by the shader: exact where its - // forms are fitted and Metal cannot fold the output's arithmetic into it - // ([`folds_into_blend`]), else a near-equivalent the function notes. An attachment the - // function does not read (one a draw moved into the storage form) takes it only where it - // is exact: elsewhere the device blends it, as the render pass splits around the draw. - let mut sixteen_exact = true; - // The generic float blend of a format whose Metal arithmetic is not built, a - // near-equivalent the function notes: taken only where the function reads the - // attachment. Elsewhere the device blends it, as the render pass splits around the draw. - // A blend of the second source reads the function's second (index 1) output, four `half` - // or `float` lanes as the first's. - let second = second_output4(cx, color)?; - // A blend of the second source whose function writes no second output: Metal refuses - // the pipeline ("Fragment shader does not write to render target color(0), index(1) that - // is required for blending"), as link refuses it where the device blends. - let reads_second = inputs - .attachments - .get(&color) - .copied() - .flatten() - .is_some_and(|a| { - a.blending_enabled && a.equation.is_some_and(|eq| eq.reads_second_source()) - }); - if reads_second && second.is_none() { - let invalid = DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::NilWithError, - }; - return Err(Error::InvalidDescriptor(invalid)); - } - let generic_of = |view: StorageView, exact: &mut bool| { - let reads_second = view - .blend - .and_then(|eq| generic(&eq, view.pixel_format, written(view.kept)).ok()) - .is_some_and(|b| b.reads_second()); - match (fetched.contains(&color), reads_second, second) { - (false, _, _) => Err(not_implemented()), - (true, true, Some(None)) => Err(Unsupported::not_implemented( - Feature::ExtendedRangeBlend(ExtendedRangeBlend::Output), - )), - (true, _, _) => { - *exact = false; - Ok(( - StorageView { - generic_blend: true, - ..view - }, - None, - )) - } - } - }; - let form = match form { - Ok(view) if view.generic_blend => generic_of(view, &mut sixteen_exact), - // Metal's 16-bit float blend, of a `half` or `float` output of one to four lanes, or - // its 8-bit unorm blend, of four. - Ok(view) if view.blend.is_some() && view.extended.is_none() => { - let math = blend_math(cx); - let planned = view.blend.map(|eq| { - let written = written(view.kept); - let half = extended_range::blend::BlendArith::Half; - direct_blend(&eq, view.pixel_format, written, (math, half)) - }); - let unorm8 = unorm8_format(view.pixel_format); - let srgb = view.uint_view.is_some(); - match (planned, blended_output(cx.entry, color)) { - // An 8-bit sRGB blend (`extended_range::Blend::srgb8`), whose second source, - // where it reads one, is the function's second output: Metal's where its 8-bit - // unorm blend is built, the output is four lanes and the module states its - // math (Metal clamps the output first, so none of the output's arithmetic - // folds into it), else a near-equivalent the function notes (an output of - // fewer lanes blends as four whose missing lanes are zero, alpha among them), - // taken only where the function reads the attachment. - (Some(Ok(b)), output) if srgb => { - let stated = cx.entry.compile.fast_math.is_some(); - let four = srgb_output4(view.pixel_format, output); - let exact = four - && view.blend.is_some_and(|eq| { - srgb8_exact(&eq, view.pixel_format, written(view.kept), math) - }); - sixteen_exact = stated && exact; - match (b.reads_second(), second) { - (true, Some(None)) => Err(Unsupported::not_implemented( - Feature::ExtendedRangeBlend(ExtendedRangeBlend::Output), - )), - _ if sixteen_exact || fetched.contains(&color) => Ok((view, None)), - _ => Err(not_implemented()), - } - } - // An 8-bit unorm blend of fewer lanes is not measured: the generic blend. - (Some(Ok(_)), Some((_, lanes))) if unorm8 && lanes < 4 => { - generic_of(view, &mut sixteen_exact) - } - // A packed 16-bit one is not built. - (Some(Ok(_)), Some((_, lanes))) if view.word.is_some() && lanes < 4 => { - Err(not_implemented()) - } - // A packed 16-bit blend reads the attachment's codes, where Metal's tile holds - // a clear's or an earlier blend's value finer, and under fast math sums some - // states otherwise (`extended_range::Blend::packed16`): a near-equivalent the - // function notes, taken whether or not the function reads the attachment, as - // no device blends the format. - (Some(Ok(_)), Some(_)) if view.word.is_some() => { - sixteen_exact = false; - Ok((view, None)) - } - // A blend into an attachment held with its channels rotated - // (`StorageView::rotated`), which no Vulkan state on its image may give - // (`color_writes::shader_rotated_blend`): Metal's 8-bit unorm blend wherever - // the module states its math, else a near-equivalent the function notes, - // taken whether or not the function reads the attachment. - (Some(Ok(_)), Some((_, 4))) if view.rotated => { - sixteen_exact = cx.entry.compile.fast_math.is_some(); - Ok((view, None)) - } - (Some(Ok(b)), Some((_, lanes))) => { - let stated = cx.entry.compile.fast_math.is_some(); - // An output of fewer lanes whose color blend reads the source alpha stores - // Metal's constant ([`half_blended`]), whatever the output. - let constant = lanes < 4 && b.color_reads_source_alpha(); - // Metal clamps the output before an 8-bit unorm blend, so none of the - // output's arithmetic folds into it: the blend is - // Metal's wherever the module states its math. - sixteen_exact = stated - && (unorm8 - || constant - || (b.fitted() && !folds_into_blend(cx, color, math)?)); - match sixteen_exact || fetched.contains(&color) { - true => Ok((view, None)), - false => Err(not_implemented()), - } - } - (Some(Err(Error::Unsupported(gap))), _) => Err(gap), - (Some(Err(e)), _) => return Err(tied(e)), - // A second (index 1) output beside the first, which Metal's measured blends - // do not read: the generic blend, which stores it nowhere. - (Some(Ok(_)), None) if second.is_some() && view.word.is_none() => { - generic_of(view, &mut sixteen_exact) - } - _ => Err(not_implemented()), - } - } - Ok(view) => match blend_of(&view, outputs4.get(&color).copied()) { - // A blend of the second source reads the function's index-1 output (which it - // writes: Metal refuses the pipeline otherwise, above), four `half` or `float` - // lanes as the first's. - Ok(Some(b)) if b.reads_second() => match second { - Some(Some(_)) => Ok((view, Some(b))), - _ => Err(Unsupported::not_implemented(Feature::ExtendedRangeBlend( - ExtendedRangeBlend::Output, - ))), - }, - Ok(b) => Ok((view, b)), - Err(Error::Unsupported(gap)) => Err(gap), - Err(e) => return Err(tied(e)), - }, - Err(blocked) => Err(blocked), - }; - match form { - Ok((view, b)) => { - // The blend color, as push data, where the blend reads it. - if b.as_ref() - .is_some_and(extended_range::blend::NativeBlend::reads_constant) - { - cx.push.insert(PushField::HalfBlendColor); - } - // The blend color as the encoder set it, where Metal's 16-bit float blend reads - // it. Where that blend is not Metal's exactly, the function notes it. - if let (Some(eq), None) = (view.blend, view.extended) { - let arith = extended_range::blend::BlendArith::Half; - let math = (blend_math(cx), arith); - let (pf, written) = (view.pixel_format, written(view.kept)); - let half = match view.generic_blend { - true => generic(&eq, pf, written), - false => direct_blend(&eq, pf, written, math), - }; - if half.is_ok_and(|h| h.reads_constant()) { - cx.push.insert(PushField::HalfBlendColor); - } - let four = srgb_output4(pf, blended_output(cx.entry, color)); - let srgb_unmeasured = view.uint_view.is_some() - && !(four && srgb8_exact(&eq, pf, written, blend_math(cx))); - if view.generic_blend || srgb_unmeasured { - cx.precision.insert(PrecisionNote::UnmeasuredFetchBlend); - } else if view.word.is_some() { - cx.precision.insert(PrecisionNote::DeviceColorConversion); - } else if !sixteen_exact { - let note = crate::lower::arith::output_precision::half_output_note(cx); - cx.precision.insert(note); - } - } - // The logic operation's codes of a normalized output, the device's `float` - // product rounded to nearest even, where Metal rounds the exact product (`logic`). - let normalized = super::logic::channels(view.pixel_format) - .is_some_and(super::logic::reads_float); - if view.logic_op.is_some() && normalized { - cx.precision.insert(PrecisionNote::DeviceColorConversion); - } - // The channels a partial write mask keeps, as the draw's word. - if view.kept_at_draw { - cx.push.insert(PushField::StorageKeptChannels); - } - let nearest_even = cx.inputs.texture_write_rounding - == crate::metal::TextureWriteRoundingMode::NearestEven; - cx.families.fragment.fetch.insert( - color, - StorageColor { - view, - writes, - output: None, - second: None, - exact_blend: sixteen_exact, - nearest_even, - }, - ); - // An image holding Metal's alpha in red is read and written as Metal's alpha; the - // interface records the attachment, which link holds the pipeline's to - // (`color_writes::check`). - if view.alpha_in_red { - cx.families - .stage_io - .interface - .alpha_in_red_colors - .insert(color); - } - cx.facts.insert(RuntimeFact::InterlockedFramebufferFetch { - color, - format: view.format, - writes, - early_tests, - kept: view.kept, - blend: view.blend, - rounded: view.blend.is_some() - && use_.math == extended_range::blend::BlendMath::Rounded, - }); - cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(1); - // A merged write stores the kept channels as it read them: a `half` (or a packed - // float) texel's NaN is the device's decode, as for any read of one. - if view.merges() && narrow_float(view.format) { - cx.precision.insert(PrecisionNote::DeviceNanEncoding); - } - } - Err(blocked) => return Err(tied(blocked.into())), - } - } - if !cx.families.fragment.fetch.is_empty() { - cx.families.fragment.fetch_early_tests = early_tests && !declared_early; - } - // Whether a write stores is the draw's tests' to decide. A write whose mask covers none of - // its attachment's channels stores nothing, so no test bears on it: a moved color's neither, - // for which the plan of the pipeline before the move selects no tests either - // (`RuntimeFact::MovableStorageWrites`). - let stores = cx - .families - .fragment - .fetch - .values() - .any(|sc| sc.writes && !sc.view.stores_nothing()); - if (tested || untested) && stores { - cx.facts.insert(RuntimeFact::TestedStorageWrites { - early_tests, - early_variant: tested && !untested, - }); - } - // A per-sample function's returned mask gates its storage writes. At one sample too, on the - // mask's bit 0 (measured: Metal stores no color there without it). - let written = cx.families.fragment.fetch.values().any(|sc| sc.writes); - if written { - cx.families.fragment.fetch_mask = outputs - .iter() - .find(|o| matches!(o.role, OutputRole::SampleMask)) - .map(|o| o.field); - } - Ok(()) -} - /// 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 @@ -1925,68 +331,6 @@ pub(super) fn plan_sample(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } -/// Whether the function reads color attachment `color` in the storage form. -pub(crate) fn is_storage(cx: &SelectCx<'_>, color: u32) -> bool { - cx.families.fragment.fetch.contains_key(&color) -} - -/// Whether a value of `form` has the numeric class of `numeric` (a float of `Float`, an integer -/// of `Uint` or `Sint`). A narrower integer written to a signed-integer attachment is not -/// lowered: which extension fills the attachment's lanes is not established (as for a color -/// output). A read takes the texel's low bits, as an input attachment's does. -fn class_of(form: Form, numeric: SampledType, color: u32, write: bool) -> Result<(), Error> { - let ok = match numeric { - SampledType::Float => form.is_float(), - SampledType::Uint => !form.is_float(), - SampledType::Sint => !form.is_float(), - // No color attachment's format reads as `ulong`. - SampledType::Uint64 => false, - }; - if !ok { - return Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::NilWithError, - })); - } - if write && numeric == SampledType::Sint && !matches!(form.held, Held::Int { bits: 32, .. }) { - return Err(not_lowered()); - } - Ok(()) -} - -/// Plan the read of storage-form color input `c`: its class against the attachment's, and the -/// pixel's `FragCoord`. -pub(super) fn select_read(cx: &mut SelectCx<'_>, c: ColorInput) -> Result<(), Error> { - let Some(sc) = cx.families.fragment.fetch.get(&c.color).copied() else { - return Err(cx.invariant("a storage-form read of an attachment of another form")); - }; - // A packed 16-bit word attachment's read decodes the word, Metal's value - // (`stage_io::word_color::decode`, [`value`]). An 8-bit sRGB word's decode of its bytes, and - // an `RGB9E5Float` word's of its shared exponent, are not built. - if matches!( - sc.view.word, - Some(WordAttachment::Srgb8 { .. } | WordAttachment::Rgb9e5) - ) { - let refused = Unsupported::not_implemented(Feature::Format); - return Err(refused.at_attachment(Attachment::Color(c.color)).into()); - } - class_of(c.form, sc.view.read_class(), c.color, false)?; - // A padded 10-bit texel converts by the device's arithmetic, its read the tile value of its - // codes ([`value`]). An Apple extended-range form's read is refused before - // (`color::select_param`). - if let Some(e) = sc.view.extended { - cx.families.arith.converts(e); - } - // An sRGB texel decodes by the device's conversion. - if sc.view.uint_view.is_some() { - cx.precision.insert(PrecisionNote::DevicePackConversion); - } - plan_sample(cx)?; - let coord = stage_io::frag_coord(cx); - cx.families.fragment.fetch_coord = Some(coord); - 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. @@ -2019,310 +363,8 @@ pub(super) fn second_output4( Ok(None) } -/// Whether the function's second (index-1) output to attachment `color` is the second source of -/// an extended-range or generic blend the shader computes in the storage form -/// ([`select_second_output`]), which no interface variable holds. -pub(crate) fn blends_second(cx: &SelectCx<'_>, color: u32) -> bool { - cx.families.fragment.fetch.get(&color).is_some_and(|sc| { - sc.view.blend.is_some() - && (sc.view.extended.is_some() || sc.view.generic_blend || sc.view.uint_view.is_some()) - }) -} - -/// Plan the second (index-1) output of AIR type `ty` held in field `field` of the returned value -/// to storage-form attachment `color`, whose extended-range or generic blend the shader computes -/// ([`blends_second`]): the blend reads it where its factors name the second source (an -/// extended-range one's rounded to `half`), clamped as the first output; else nothing stores it, -/// as Metal's blend there reads none. -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(sc) = cx.families.fragment.fetch.get_mut(&color) else { - return Err(cx.invariant("a second output of an attachment of another form")); - }; - sc.second = Some((field, form)); - Ok(()) -} - -/// Plan the output of AIR type `ty` held in field `field` of the returned value to storage-form -/// attachment `color` (`stage_io` plans the entry's other outputs): its form has the -/// attachment's class and at least its format's channels, as a color output must. -pub fn select_output( - cx: &mut SelectCx<'_>, - field: u32, - color: u32, - ty: AirTypeId, -) -> Result<(), Error> { - let form = super::color::form(cx, ty)?; - let Some(sc) = cx.families.fragment.fetch.get(&color).copied() else { - return Err(cx.invariant("a storage-form output of an attachment of another form")); - }; - class_of(form, sc.view.read_class(), color, true)?; - // The logic operation takes a normalized channel's `float` or `half` output and an integer - // channel's 32-bit one (`logic::takes`). - let logic = super::logic::channels(sc.view.pixel_format); - if sc.view.logic_op.is_some() && !logic.is_some_and(|ch| super::logic::takes(ch, form)) { - return Err(super::logic::refused(color)); - } - // An extended-range attachment's blend is of a `half4` output, or of a `float4` one where - // the blend takes it ([`plan`]), and an `_sRGB` one's encodes by the device's `Pow`. - let output4 = (form.lanes == 4).then(|| form.float_fmt()).flatten(); - if blend_of(&sc.view, output4).is_err() { - return Err(cx.invariant("an extended-range blend of an output outside its model")); - } - if let Some(e) = sc.view.extended { - // An unblended write stores Metal's write of a `float` or `half` output; a `bfloat` one's - // is not measured. - let measured = matches!( - form.float_fmt(), - Some(crate::lower::arith::FloatFmt::F32 | crate::lower::arith::FloatFmt::Half) - ); - if !measured { - return Err(Unsupported::not_implemented(Feature::Format).into()); - } - cx.families.arith.converts(e); - // A bfloat attachment's `float` output rounds to `half` by the pipeline's - // `textureWriteRoundingMode` (`bfloat_written`), which link holds the pipeline's to. - if e.bfloat() && form.float_fmt() == Some(crate::lower::arith::FloatFmt::F32) { - let mode = cx.inputs.texture_write_rounding; - cx.families.stage_io.interface.texture_write_rounding = Some(mode); - } - } - let pf = cx - .inputs - .framebuffer_fetch - .as_ref() - .and_then(|i| i.attachments.get(&color).copied().flatten()) - .map(|a| a.pixel_format) - .ok_or_else(|| cx.invariant("a storage-form output without its attachment"))?; - if color_output_components(pf).is_some_and(|n| form.lanes < n) { - return Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: color, - metal: MetalAnswer::NilWithError, - })); - } - plan_sample(cx)?; - // The write rounds to the code Metal stores where the format converts it; an sRGB attachment's - // write encodes its bytes itself (`arith::pack::pack` of a `float` or `half` output), and a word - // attachment's Metal's word of a `float` or `half` output ([`word_texel`]): each records the - // pipeline's map, which link checks, without rounding a lane. - if sc.view.word.is_some() { - let measured = matches!( - form.float_fmt(), - Some(crate::lower::arith::FloatFmt::F32 | crate::lower::arith::FloatFmt::Half) - ); - if !measured { - return Err(Unsupported::not_implemented(Feature::Format).into()); - } - // An 8-bit sRGB word encodes by the device's conversion. - if let Some(WordAttachment::Srgb8 { .. }) = sc.view.word { - cx.precision.insert(PrecisionNote::DevicePackConversion); - } - if let Some(rules) = cx.inputs.color_writes.get(&color).copied() { - cx.families - .stage_io - .interface - .color_writes - .insert(color, rules); - } - } else if sc.view.uint_view.is_some() { - let measured = matches!( - form.float_fmt(), - Some(crate::lower::arith::FloatFmt::F32 | crate::lower::arith::FloatFmt::Half) - ); - if !measured { - return Err(Unsupported::not_implemented(Feature::Format).into()); - } - cx.precision.insert(PrecisionNote::DevicePackConversion); - if let Some(rules) = cx.inputs.color_writes.get(&color).copied() { - cx.families - .stage_io - .interface - .color_writes - .insert(color, rules); - } - } else { - let nan_free = stage_io::returns_no_nan(cx, field); - stage_io::color_write::plan(cx, color, form, nan_free); - // An 8-bit unorm blend's result is the storage image's to convert, the device's - // conversion ([`unorm8_blended`]). - if sc.view.blend.is_some() && !sc.view.generic_blend && unorm8_format(sc.view.pixel_format) - { - cx.precision.insert(PrecisionNote::DeviceColorConversion); - } - } - let coord = stage_io::frag_coord(cx); - let fp = &mut cx.families.fragment; - fp.fetch_coord = Some(coord); - match fp.fetch.get_mut(&color) { - Some(sc) if sc.writes && sc.output.is_none() => { - sc.output = Some((field, form)); - Ok(()) - } - _ => Err(invariant("a storage-form output the plan does not expect")), - } -} - -fn invariant(detail: &str) -> Error { - Error::Internal(crate::error::InternalError::new( - crate::error::InternalKind::Invariant, - detail, - )) -} - -/// Check the plan once every output is planned: each written storage-form attachment has its -/// output. -pub(super) fn finish(cx: &SelectCx<'_>) -> Result<(), Error> { - if cx - .families - .fragment - .fetch - .values() - .any(|sc| sc.writes != sc.output.is_some()) - { - return Err(invariant( - "a written storage-form attachment without its output", - )); - } - Ok(()) -} - -/// Declare storage-form attachment `color`'s storage image: a 2D storage image of its declared -/// format and its numeric type, multisampled or arrayed as it holds the samples -/// ([`StorageSamples`]). -pub(super) fn declare(mb: &mut ModuleBuilder, color: u32, sc: &StorageColor) -> BResult { - let sampled_type = scalar_type(mb, sc.view.numeric)?; - let ty = mb.ty(SType::Image(ImageType { - sampled_type, - dim: Dim::D2, - depth: false, - arrayed: sc.view.samples == StorageSamples::Planes, - multisampled: sc.view.samples == StorageSamples::Multisampled, - usage: ImageUsage::Storage, - format: sc.view.declared, - }))?; - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::TileAttachment(color), - index: color, - }; - mb.resource(slot, StorageClass::UniformConstant, ty) -} - -/// The 32-bit scalar type of `numeric`. -fn scalar_type(mb: &mut ModuleBuilder, numeric: SampledType) -> BResult { - match numeric { - SampledType::Float => mb.ty(SType::Float { width: 32 }), - // A `ulong` texture's image is `RG32` unsigned. - SampledType::Uint | SampledType::Uint64 => mb.ty(SType::Int { - width: 32, - signed: false, - }), - SampledType::Sint => mb.ty(SType::Int { - width: 32, - signed: true, - }), - } -} - -/// The storage image of attachment `color` held as `samples`, the texel of the invocation's -/// sample, and the access's image operands: the invocation's [`pixel`] with its [`operands`], -/// or, for planes, the pixel and the invocation's `SampleId` as the layer. -fn image_and_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - samples: StorageSamples, -) -> BResult<(SValue, SValue, ImageOperands)> { - let Some(g) = cx.decl.families.fragment.attachments.get(&color).copied() else { - return Err(cx.fail(format!("storage attachment {color} is not declared"))); - }; - let p = fb.module().global_value(g)?; - let image = fb.load(p, MemAccess::default())?; - let (at, ops) = sample_texel(cx, fb, samples)?; - Ok((image, at, ops)) -} - -/// The texel of the invocation's sample in a storage image holding the samples as `samples`, and -/// the access's image operands: the invocation's [`pixel`] with its [`operands`], or, for planes, -/// the pixel and the invocation's `SampleId` as the layer. -fn sample_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - samples: StorageSamples, -) -> BResult<(SValue, ImageOperands)> { - let pixel = pixel(cx, fb)?; - if samples != StorageSamples::Planes { - let ops = operands(cx, fb)?; - return Ok((pixel, ops)); - } - let Some(layer) = sample(cx, fb)? else { - return Err(cx.fail("a planes access without its SampleId")); - }; - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec3 = fb.module().ty(SType::Vector { elem: u32_, len: 3 })?; - let x = fb.composite_extract(pixel, &[0])?; - let y = fb.composite_extract(pixel, &[1])?; - let texel = fb.composite_construct(uvec3, &[x, y, layer])?; - Ok((texel, ImageOperands::default())) -} - -/// The texel of storage-form attachment `sc`'s image at the invocation's pixel (and sample) of -/// attachment `color`, read inside the interlock, in Metal's channel order ([`metal_order`]): -/// every read of the attachment's image goes through here, so a read, a merge's kept channels, a -/// blend's destination and the per-sample forms see Metal's channels alike. -fn read_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, -) -> BResult { - let (image, at, ops) = image_and_texel(cx, fb, color, sc.view.samples)?; - let mem = memory_model::coherence(cx.plan).texel(fb)?; - let texel = fb.read(image, at, &ops, mem)?; - metal_order(fb, sc, texel) -} - -/// Texel `texel` of storage-form attachment `sc`'s image, in Metal's channel order: an attachment -/// viewed in its RGBA-order twin ([`StorageView::rgba_view`]) has red and blue exchanged, one -/// whose image holds Metal's alpha in red ([`StorageView::alpha_in_red`]) reads `(r, 0, 0, 1)` as -/// Metal's `(0, 0, 0, r)`, and one holding Metal's channels rotated ([`StorageView::rotated`]) -/// reads Metal's red, green, blue and alpha from the image's green, blue, alpha and red; any other -/// is as it is. Every texel read from the attachment's image goes through here ([`read_texel`]), -/// and every one written to it through [`image_order`]. -fn metal_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { - match (sc.view.rgba_view, sc.view.alpha_in_red, sc.view.rotated) { - (Some(_), _, _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), - (None, true, _) => super::color::alpha_in_red(fb, texel), - (None, false, true) => fb.vector_shuffle(texel, texel, &[1, 2, 3, 0]), - (None, false, false) => Ok(texel), - } -} - -/// Metal-ordered texel `texel` of storage-form attachment `sc`, in its image's channel order: -/// [`metal_order`]'s exchange of red and blue, which is its own inverse, for an image holding -/// Metal's alpha in red, Metal's alpha in every lane (the image keeps its red), and for one holding -/// Metal's channels rotated, Metal's alpha, red, green and blue as the image's red, green, blue -/// and alpha (the inverse of [`metal_order`]'s rotation). Every texel written to the attachment's -/// image goes through here ([`emit_return`]). -fn image_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { - match (sc.view.rgba_view, sc.view.alpha_in_red, sc.view.rotated) { - (Some(_), _, _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), - (None, true, _) => fb.vector_shuffle(texel, texel, &[3, 3, 3, 3]), - (None, false, true) => fb.vector_shuffle(texel, texel, &[3, 0, 1, 2]), - (None, false, false) => Ok(texel), - } -} - /// The image operands of a fetched color's read or write in a multisampled image (an input -/// attachment, or a multisampled storage image): the invocation's `SampleId` for a per-sample +/// attachment, or a pushed texture's fetch): the invocation's `SampleId` for a per-sample /// function (`FragmentPlan::fetch_sample`), none for one sample. pub(super) fn operands( cx: &mut EmitCx<'_>, @@ -2348,10 +390,10 @@ pub(super) fn sample(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResu } /// The invocation's pixel, a `uvec2` from the integer part of `FragCoord.xy` (the pixel's -/// center, single-sampled): the texel of a storage image the interlocked forms hold per pixel. +/// center, single-sampled): the texel a fetch of the attachment's pushed texture reads. pub(super) fn pixel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { let Some(coord) = cx.plan.families.fragment.fetch_coord else { - return Err(cx.fail("a storage-form access without its FragCoord")); + return Err(cx.fail("a pushed fetch without its FragCoord")); }; let frag = stage_io::object_global(cx, coord)?; let frag = fb.module().global_value(frag)?; @@ -2368,514 +410,6 @@ pub(super) fn pixel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResul fb.composite_construct(uvec2, &[x, y]) } -/// A `uvec4` of a signed-integer texel's bits, or the texel itself. -fn as_held(fb: &mut FunctionBuilder<'_>, texel: SValue, numeric: SampledType) -> BResult { - if numeric != SampledType::Sint { - return Ok(texel); - } - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; - fb.convert(ConvOp::Bitcast, texel, uvec4) -} - -/// The texel the function reads of storage-form attachment `color` at its pixel (and sample), -/// its image's. The function reads it once, -/// before its body (`fragment::emit_entry`), and every use takes it ([`value`]): Metal hands the -/// function one value of the attachment, and one read keeps the image's accesses in the -/// interlock to that read and the writes at the returns. -pub(super) fn texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, -) -> BResult { - let Some(sc) = cx.plan.families.fragment.fetch.get(&color).copied() else { - return Err(cx.fail(format!("attachment {color} is not in the storage form"))); - }; - read_texel(cx, fb, color, &sc) -} - -/// The value of storage-form color input `c` in its lowered representation, from the texel the -/// function read at its pixel before its body ([`texel`]; as `color::value` reads an input -/// attachment). -pub(super) fn value( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - c: ColorInput, -) -> BResult { - let Some(sc) = cx.plan.families.fragment.fetch.get(&c.color).copied() else { - return Err(cx.fail(format!("attachment {} is not in the storage form", c.color))); - }; - let Some(&(_, texel)) = cx.fetched.iter().find(|&&(color, _)| color == c.color) else { - return Err(cx.fail(format!("attachment {} was not read at entry", c.color))); - }; - let texel = match (sc.view.extended, sc.view.uint_view) { - (Some(form), _) => extended_range::tile_value(fb, form, texel)?, - (None, Some(_)) => { - let word = fb.composite_extract(texel, &[0])?; - srgb_decode(fb, sc.view.format, word)? - } - // A packed 16-bit word attachment's texel is the word, whose channels the read decodes as - // Metal's programmable blending hands them to the function, and as its blend reads them - // (`stage_io::word_color::decode`; the measurement is `metal::format::word`'s). The other - // word kinds' reads are refused in the plan ([`select_read`]). - (None, None) if sc.view.word.is_some() => { - let Some(word) = sc.view.word else { - return Err(cx.fail("a word read of an attachment without a word")); - }; - let w = fb.composite_extract(texel, &[0])?; - stage_io::word_color::decode(fb, word, w)? - } - (None, None) => as_held(fb, texel, sc.view.numeric)?, - }; - let x = match c.form.lanes { - 4 => texel, - 1 => fb.composite_extract(texel, &[0])?, - n => { - let lanes: Vec = (0..u32::from(n)).collect(); - fb.vector_shuffle(texel, texel, &lanes)? - } - }; - let x = ops::mask(fb, c.form, x)?; - narrow::round(fb, c.form, x) -} - -/// Write each written storage-form attachment's output of returned value `v` (in the entry's -/// returned shape) at its pixel, unless a discard was recorded (`discarded`). -pub(super) fn emit_return( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - v: Option, -) -> BResult<()> { - let writes: Vec<(u32, StorageColor, u32, Form)> = cx - .plan - .families - .fragment - .fetch - .iter() - .filter(|(_, sc)| !sc.view.stores_nothing()) - .filter_map(|(&color, sc)| sc.output.map(|(field, form)| (color, *sc, field, form))) - .collect(); - if writes.is_empty() { - return Ok(()); - } - let Some(v) = v else { - return Err(cx.fail("a storage-form output without a returned value")); - }; - let x = cx.operand(fb, v)?; - let mut texels = Vec::with_capacity(writes.len()); - for (color, sc, field, form) in writes { - let part = match cx.plan.families.stage_io.returned { - Returned::Struct => fb.composite_extract(x, &[field])?, - Returned::Value => x, - Returned::Void => return Err(cx.fail("a storage-form output of a void entry")), - }; - // The second (index-1) output, the blend's second source where it reads one. - let second = match (sc.second, cx.plan.families.stage_io.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 = match (sc.view.extended, sc.view.blend) { - (Some(range), Some(_)) => blended(cx, fb, color, &sc, range, (form, part), second)?, - // A bfloat attachment's write. - (Some(range), None) if range.bfloat() => { - bfloat_written(cx, fb, color, &sc, range, (form, part))? - } - (Some(range), None) if sc.view.merges() => { - merged_extended(cx, fb, color, &sc, range, (form, part))? - } - (Some(range), None) => stage_io::extended_color::texel(fb, range, form, part)?, - (None, _) if sc.view.uint_view.is_some() => { - srgb_texel(cx, fb, color, &sc, (form, part), second)? - } - (None, _) if sc.view.word.is_some() => word_texel(cx, fb, color, &sc, form, part)?, - (None, _) => { - // Metal's 16-bit float blend of an output of one to four lanes, its 8-bit unorm - // blend of four, or the generic blend, over the texel. - let part = match sc.view.blend { - Some(eq) if sc.view.generic_blend => { - generic_blended(cx, fb, color, &sc, eq, (form, part), second)? - } - Some(eq) if unorm8_format(sc.view.pixel_format) => { - unorm8_blended(cx, fb, color, &sc, eq, (form, part))? - } - Some(eq) => half_blended(cx, fb, color, &sc, eq, (form, part))?, - None => part, - }; - // The pipeline's private logic operation over the texel's codes. - let part = match sc.view.logic_op { - Some(op) => logic_operated(cx, fb, color, &sc, op, (form, part))?, - None => part, - }; - let part = if sc.view.merges() { - merge(cx, fb, color, &sc, form, part)? - } else { - part - }; - let part = stage_io::color_write::round(cx, fb, color, form, part)?; - texel_of(fb, part, form, sc.view.numeric)? - } - }; - // The image's texel of the Metal-ordered one. - let texel = image_order(fb, &sc, texel)?; - let (image, at, ops) = image_and_texel(cx, fb, color, sc.view.samples)?; - texels.push((image, at, texel, ops)); - } - let mem = memory_model::coherence(cx.plan).texel(fb)?; - let write = move |fb: &mut FunctionBuilder<'_>, texels: &mut Vec| { - for (image, at, texel, ops) in texels.iter() { - fb.write(*image, *at, *texel, ops, mem)?; - } - Ok(()) - }; - // The guard: not discarded, and, for a function that returns a sample mask, the mask's bit of - // the invocation's own sample (bit 0 at one sample). - let discarded = if cx.plan.families.fragment.records_discards() { - let Some(g) = cx.decl.families.fragment.discarded else { - return Err(cx.fail("a recorded discard without its predicate")); - }; - let p = fb.module().global_value(g)?; - let discarded = fb.load(p, MemAccess::default())?; - Some(fb.unary(UnOp::LogicalNot, discarded)?) - } else { - None - }; - let masked = match cx.plan.families.fragment.fetch_mask { - Some(field) => Some(sample_bit(cx, fb, x, field)?), - None => None, - }; - let kept = match (discarded, masked) { - (None, None) => return write(fb, &mut texels), - (Some(k), None) | (None, Some(k)) => k, - (Some(a), Some(b)) => fb.binary(BinOp::LogicalAnd, a, b)?, - }; - let arm: ArmFn<'_, Vec> = Box::new(move |fb, texels| { - write(fb, texels)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut texels, kept, arm, None)?; - Ok(()) -} - -/// One storage write: the image, the texel's coordinate, the texel, and the image operands. -type Write = (SValue, SValue, SValue, ImageOperands); - -/// The output `part` of `form` (one to four `f32` lanes of a `half` or `float` output, or `u32` -/// lanes of an integer one) to attachment `color` under the pipeline's private logic operation -/// `op` (`StorageView::logic_op`): the texel read first at the invocation's pixel (and sample), -/// inside the interlock, in Metal's channel order ([`read_texel`]; a signed integer texel's bits), -/// and the value whose code is the operation of the output's code over the texel's -/// (`logic::operated`). The channels a write mask keeps are [`merge`]'s to take back from the -/// texel. -fn logic_operated( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - op: vk::LogicOp, - (form, part): (Form, SValue), -) -> BResult { - let Some(channels) = super::logic::channels(sc.view.pixel_format) else { - return Err(cx.fail("a logic operation of an attachment it does not serve")); - }; - if !super::logic::takes(channels, form) { - return Err(cx.fail("a logic operation of an output it does not take")); - } - let texel = read_texel(cx, fb, color, sc)?; - let texel = as_held(fb, texel, sc.view.numeric)?; - super::logic::operated(fb, op, channels, (form, part), texel) -} - -/// The output `part` of `form` (one to four `f32` lanes: a `half` output's `half`s, or a `float` -/// one's `float`s) blended into 16-bit float attachment `color` by Metal's blend `eq` -/// (`extended_range::Blend::half_float`, of the function's math): the texel read first at the -/// invocation's pixel (and sample), inside the interlock, as [`merge`] reads it, and Metal's -/// arithmetic of the output over it in the output's type -/// (`extended_range::blend::blend_half_float`; the blend color from `PushField::HalfBlendColor` -/// where the blend reads it), a `float` result converted to `half` by the storage image's store, -/// the device's conversion (where Metal's blended write's is toward zero, the largest finite -/// `half` past it), or rounded to nearest -/// even under `TextureWriteRoundingMode::NearestEven` (`color_writes::HALF_NEAREST`), which no -/// measured device's store gives. A NaN of the blend is the device's arithmetic's, which the -/// store converts (`PrecisionNote::DeviceNanEncoding`). -/// An output of fewer than four lanes blends as four whose missing lanes are zero, alpha among -/// them, and the result keeps the output's lanes. The channels a write -/// mask keeps are [`merge`]'s to take back from the texel. -fn half_blended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - eq: BlendEquation, - (form, part): (Form, SValue), -) -> BResult { - let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); - let (pf, written) = (sc.view.pixel_format, written(sc.view.kept)); - let Ok(b) = extended_range::Blend::half_float(&eq, pf, written, math) else { - return Err(cx.fail("a 16-bit float blend outside Metal's model")); - }; - let arith = match (form.lanes, form.float_fmt()) { - (1..=4, Some(FloatFmt::Half)) => extended_range::blend::BlendArith::Half, - (1..=4, Some(FloatFmt::F32)) => extended_range::blend::BlendArith::Float, - _ => return Err(cx.fail("a 16-bit float blend of another output")), - }; - // The lanes an output of fewer than four lacks are undefined to Metal's compiler, which folds - // color channels whose blend reads the source alpha as a factor to `+0` under fast math and - // stores its NaN without; such an output's format has no alpha channel. - if form.lanes < 4 && b.color_reads_source_alpha() { - let bits = match math { - extended_range::blend::BlendMath::Fast => 0, - extended_range::blend::BlendMath::Rounded => 0x7FC0_0000, - }; - return ops::splat(fb, form.with(Held::Float(FloatFmt::F32)), bits); - } - let texel = read_texel(cx, fb, color, sc)?; - let d = as_held(fb, texel, sc.view.numeric)?; - let constant = match b.reads_constant() { - true => { - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Some(fb.composite_extract(field, &[0])?) - } - false => None, - }; - let s = four_lanes(fb, form, part)?; - let v = extended_range::blend::blend_half_float(fb, &b, arith, (s, d), constant)?; - let v = output_lanes(fb, form, v)?; - if arith == extended_range::blend::BlendArith::Half || !sc.nearest_even { - // The blend's result is the storage image's store's to convert, its NaN the device's - // (`PrecisionNote::DeviceNanEncoding`), and a `float` result's rounding the device's - // (`PrecisionNote::DeviceColorConversion`). - return Ok(v); - } - let rule = crate::pipeline::color_writes::HALF_NEAREST; - crate::lower::arith::color_write::small_float(fb, form, v, rule) -} - -/// The output `part` of `form` (four `f32` lanes: a `half4` output's `half`s, or a `float4` one's -/// `float`s) blended into 8-bit unorm attachment `color` by Metal's blend `eq` -/// (`extended_range::Blend::unorm8`, of the function's math and the output's type), stored as -/// Metal's unorm write stores it: the texel read first at the invocation's pixel (and sample), -/// inside the interlock, in Metal's channel order ([`read_texel`]: an attachment viewed in its -/// RGBA-order twin has red and blue exchanged, and the write exchanges them back, -/// [`emit_return`]), Metal's arithmetic of the clamped output over the destination's code decoded -/// in the output's type, the blend color from `PushField::HalfBlendColor` where the blend reads it -/// (`extended_range::blend::blend_unorm8`), the result written as it is: the storage image's -/// store converts it to its code, the device's conversion (`PrecisionNote::DeviceColorConversion`); -/// a channel the write mask keeps takes the texel's after (the module docs). -fn unorm8_blended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - eq: BlendEquation, - (form, part): (Form, SValue), -) -> BResult { - let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); - let (pf, written) = (sc.view.pixel_format, written(sc.view.kept)); - 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 Ok(b) = direct_blend(&eq, pf, written, (math, arith)) else { - return Err(cx.fail("an 8-bit unorm blend outside Metal's model")); - }; - let texel = read_texel(cx, fb, color, sc)?; - 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) -} - -/// The output `part` of `form` (one to four `f32` lanes: a `half` output's `half`s, or a `float` -/// one's `float`s) blended into attachment `color` by the generic float blend `eq` -/// ([`StorageView::generic_blend`], `extended_range::Blend::generic`): the texel read first at the -/// invocation's pixel (and sample), inside the interlock, in Metal's channel order -/// ([`read_texel`]), and the blend of the output's four lanes (a missing one zero) over it in -/// `float`, each factor, product and sum rounded, the source, the second source (`second`, the -/// function's second output, where the blend reads it) and the blend color (from -/// `PushField::HalfBlendColor` where the blend reads it) clamped first to a normalized format's -/// range, `[0, 1]` or `[-1, 1]` (`extended_range::blend::blend_generic`). The result keeps the -/// output's lanes; the device's conversion stores it, and the channels a write mask keeps are -/// [`merge`]'s to take back from the texel. Metal's arithmetic for the format is not built: the -/// function notes `PrecisionNote::UnmeasuredFetchBlend`. -fn generic_blended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - eq: BlendEquation, - (form, part): (Form, SValue), - second: Option<(Form, SValue)>, -) -> BResult { - if !matches!(form.float_fmt(), Some(FloatFmt::Half | FloatFmt::F32)) { - return Err(cx.fail("a generic blend of another output")); - } - let Ok(b) = generic(&eq, sc.view.pixel_format, written(sc.view.kept)) else { - return Err(cx.fail("a generic blend outside its forms")); - }; - let s1 = match (b.reads_second(), second) { - (true, Some((form, s1))) - if matches!(form.float_fmt(), Some(FloatFmt::Half | FloatFmt::F32)) => - { - Some(four_lanes(fb, form, s1)?) - } - (true, _) => return Err(cx.fail("a blend of the second source without its output")), - (false, _) => None, - }; - let texel = read_texel(cx, fb, color, sc)?; - let d = as_held(fb, texel, sc.view.numeric)?; - let constant = match b.reads_constant() { - true => { - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Some(fb.composite_extract(field, &[0])?) - } - false => None, - }; - let range = match sc.view.format.block().and_then(|b| b.color) { - Some(vk::NumericFormat::Unorm) => Some((0.0, 1.0)), - Some(vk::NumericFormat::Snorm) => Some((-1.0, 1.0)), - _ => None, - }; - let s = four_lanes(fb, form, part)?; - let v = extended_range::blend::blend_generic(fb, &b, range, (s, s1, d), constant)?; - output_lanes(fb, form, v) -} - -/// Output `part` of `form` (one to four `f32` lanes) as the four lanes Metal's blend reads: its -/// own, then zeros. -fn four_lanes(fb: &mut FunctionBuilder<'_>, form: Form, part: SValue) -> BResult { - if form.lanes == 4 { - return Ok(part); - } - let f32_ = scalar_type(fb.module(), SampledType::Float)?; - let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?; - let f32_form = Form { - held: Held::Float(FloatFmt::F32), - lanes: 1, - }; - let zero = ops::fsplat(fb, f32_form, 0.0)?; - let mut lanes = Vec::with_capacity(4); - for lane in 0..4u32 { - lanes.push(match lane { - 0 if form.lanes == 1 => part, - l if l < u32::from(form.lanes) => fb.composite_extract(part, &[l])?, - _ => zero, - }); - } - fb.composite_construct(vec4, &lanes) -} - -/// The lanes of `form` (one to four) of the four `f32` lanes `v`. -fn output_lanes(fb: &mut FunctionBuilder<'_>, form: Form, v: SValue) -> BResult { - match form.lanes { - 4 => Ok(v), - 1 => fb.composite_extract(v, &[0]), - n => { - let lanes: Vec = (0..u32::from(n)).collect(); - fb.vector_shuffle(v, v, &lanes) - } - } -} - -/// Whether the function writes color attachment `color` through the storage form under a blend -/// the shader computes of a format held directly, Metal's 16-bit float, 8-bit unorm or 8-bit sRGB -/// blend, so that the write stores the value the blend gives, whatever the output and the -/// device's conversion (`exact`: and that blend is Metal's exactly, [`StorageColor::exact_blend`]). -/// Not the generic blend ([`StorageView::generic_blend`]), whose result the device's conversion -/// stores as it stores an output. -pub(super) fn blends_in_shader(cx: &SelectCx<'_>, color: u32, exact: bool) -> bool { - cx.families.fragment.fetch.get(&color).is_some_and(|sc| { - sc.view.blend.is_some() - && sc.view.extended.is_none() - && !sc.view.generic_blend - && (sc.exact_blend || !exact) - }) -} - -/// Whether the function writes color attachment `color` through the storage form under Metal's -/// 16-bit float blend, which the shader computes ([`blends_in_shader`]), and so stores `half`s. -pub(super) fn blends_half(cx: &SelectCx<'_>, color: u32) -> bool { - blends_in_shader(cx, color, false) - && cx - .families - .fragment - .fetch - .get(&color) - .is_some_and(|sc| half_float_format(sc.view.pixel_format)) -} - -/// Output `part` (of `form`, in its lowered representation) of storage-form attachment `color` -/// whose write keeps some channels (`StorageView::kept`): each kept channel's lane taken from the -/// texel the write overwrites, read first at the invocation's pixel (and sample), as `value` reads -/// it. Inside the interlock no other fragment of the pixel writes the texel between the read and -/// the write, so the write stores the kept channels as they were (in the device's decode of the -/// texel: a `half` NaN's bits are the device's, `PrecisionNote::DeviceNanEncoding`). -fn merge( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - form: Form, - part: SValue, -) -> BResult { - let texel = read_texel(cx, fb, color, sc)?; - let texel = as_held(fb, texel, sc.view.numeric)?; - let n = u32::from(form.lanes); - if n < 2 { - return Err(cx.fail("a merged storage write of one lane")); - } - let channels = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ]; - // The kept channels the draw's word names: bit `c` of the color's four takes channel `c` - // from the texel. - if sc.view.kept_at_draw { - let word = cx.push_field(fb, PushField::StorageKeptChannels)?; - let shift = fb.u32_const(4 * color)?; - let shift = fb.module().const_value(shift)?; - let bits = fb.binary(BinOp::ShiftRightLogical, word, shift)?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - let mut keeps = Vec::with_capacity(n as usize); - for lane in 0..n { - let bit = fb.u32_const(1 << lane)?; - let bit = fb.module().const_value(bit)?; - let set = fb.binary(BinOp::BitwiseAnd, bits, bit)?; - keeps.push(fb.binary(BinOp::INotEqual, set, zero)?); - } - let bvec = fb.bool_ty(form.lanes)?; - let keep = fb.composite_construct(bvec, &keeps)?; - // The texel's lanes the output has. - let lanes: Vec = (0..n).collect(); - let texel = fb.vector_shuffle(texel, texel, &lanes)?; - return fb.select(keep, texel, part); - } - let lanes: Vec = (0..n) - .zip(channels) - .map(|(lane, c)| { - if sc.view.kept.contains(c) { - n + lane - } else { - lane - } - }) - .collect(); - fb.vector_shuffle(part, texel, &lanes) -} - /// 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( @@ -2904,413 +438,6 @@ pub(super) fn blend_constant( Ok(Some(fb.composite_extract(field, &[0])?)) } -/// The raw texel an unblended write of output `part` (of `form`) to extended-range attachment -/// `color` (held in `range`) stores under a write mask of some of its channels -/// (`StorageView::kept`): the output's `half` as the unblended write takes it -/// (`stage_io::extended_color::held`), encoded as the kernel write encodes it, the codes of the -/// channels the mask keeps taken from the texel read first inside the interlock -/// (`extended_range::encode_keeping`), as Metal keeps a masked channel's code. -fn merged_extended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - range: ExtendedRange, - (form, part): (Form, SValue), -) -> BResult { - let v = stage_io::extended_color::held(fb, range, form, part)?; - let kept = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ] - .map(|c| sc.view.kept.contains(c)); - let texel = read_texel(cx, fb, color, sc)?; - extended_range::encode_keeping(fb, range, v, (texel, kept)) -} - -/// The raw texel an unblended write of output `part` (of `form`) to bfloat attachment `color` -/// (held in `range`) stores: the code Metal's render pass stores of it, as the attachment's color -/// attachment stores it (`stage_io::extended_color::bfloat_output`, at the pipeline's -/// `textureWriteRoundingMode`, [`StorageColor::nearest_even`]), the channels a write mask keeps -/// ([`StorageView::kept`]) as the texel read first inside the interlock holds them. Each channel is -/// a component of its own, so a kept channel keeps its code. -fn bfloat_written( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - range: ExtendedRange, - (form, part): (Form, SValue), -) -> BResult { - let rounding = match sc.nearest_even { - true => crate::metal::TextureWriteRoundingMode::NearestEven, - false => crate::metal::TextureWriteRoundingMode::TowardZero, - }; - let e = ExtendedRangeColor::new(range, false).with_rounding(rounding); - let stored = stage_io::extended_color::bfloat_output(fb, e, form, part)?; - if !sc.view.merges() { - return Ok(stored); - } - let texel = read_texel(cx, fb, color, sc)?; - let lanes: Vec = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ] - .into_iter() - .zip(0..4u32) - .map(|(c, lane)| match sc.view.kept.contains(c) { - true => 4 + lane, - false => lane, - }) - .collect(); - fb.vector_shuffle(stored, texel, &lanes) -} - -/// The raw texel a write of output `part` (of `form`: `half4`, or `float4` under a blend that -/// takes it, rounded to `half`, nearest even, first) to extended-range attachment `color` (held in -/// `range`) stores under the pipeline's blend `eq`: the texel read first at the invocation's pixel -/// (and sample), as [`merge`] reads it, inside the interlock, its tile value -/// (`extended_range::tile_value`), Metal's blend of the output over that -/// (`extended_range::blend::blend`, the second source from `second`, the function's index-1 output, -/// where it reads it; the blend color from `PushField::BlendColor` where it reads it), and the -/// kernel write's encode of the result, the channels a write mask keeps taken from the texel as -/// Metal keeps them (`extended_range::encode_keeping`). -fn blended( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - range: ExtendedRange, - (form, part): (Form, SValue), - second: Option<(Form, SValue)>, -) -> BResult { - let output = (form.lanes == 4).then(|| form.float_fmt()).flatten(); - let Ok(Some(b)) = blend_of(&sc.view, output) else { - return Err(cx.fail("an extended-range blend of another output")); - }; - let s1 = blend_second(cx, &b, second)?; - let texel = read_texel(cx, fb, color, sc)?; - let d = extended_range::tile_value(fb, range, texel)?; - let constant = blend_constant(cx, fb, &b)?; - let v = extended_range::blend::native(fb, &b, (part, s1, d), constant)?; - if !sc.view.merges() { - return extended_range::encode(fb, range, v); - } - let kept = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ] - .map(|c| sc.view.kept.contains(c)); - extended_range::encode_keeping(fb, range, v, (texel, kept)) -} - -/// The bytes of a texel of the sRGB format `format` held in one `u32` (`word`, the texel's bytes -/// in memory order), in red, green, blue, alpha order, as `arith::pack`'s `pack` and `unpack` hold -/// `unorm4x8_srgb`'s: `B8G8R8A8_SRGB`'s blue and red bytes swapped, `R8G8B8A8_SRGB`'s as they -/// are. The swap is its own inverse. -fn rgba_order(fb: &mut FunctionBuilder<'_>, format: vk::Format, word: SValue) -> BResult { - if format != vk::Format::B8G8R8A8_SRGB { - return Ok(word); - } - let k = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult { - let c = fb.u32_const(v)?; - fb.module().const_value(c) - }; - let (ga, low, sixteen) = (k(fb, 0xff00_ff00)?, k(fb, 0xff)?, k(fb, 16)?); - let kept = fb.binary(BinOp::BitwiseAnd, word, ga)?; - let down = fb.binary(BinOp::ShiftRightLogical, word, sixteen)?; - let down = fb.binary(BinOp::BitwiseAnd, down, low)?; - let up = fb.binary(BinOp::BitwiseAnd, word, low)?; - let up = fb.binary(BinOp::ShiftLeftLogical, up, sixteen)?; - let swapped = fb.binary(BinOp::BitwiseOr, kept, down)?; - fb.binary(BinOp::BitwiseOr, swapped, up) -} - -/// The `vec4` a fetch reads from the sRGB texel `word` of `format`: the device's decode -/// (`arith::pack::unpack` of `unorm4x8_srgb`, `PrecisionNote::DevicePackConversion`): each byte -/// by the 8-bit instruction, the color channels through the sRGB transfer by the device's `Pow`, -/// a one- or two-channel format's missing channels 0 and its alpha 1 (its word's bytes are its -/// channels', the rest zero). -fn srgb_decode(fb: &mut FunctionBuilder<'_>, format: vk::Format, word: SValue) -> BResult { - let word = match format { - vk::Format::R8_SRGB | vk::Format::R8G8_SRGB => { - let alpha = fb.u32_const(0xff00_0000)?; - let alpha = fb.module().const_value(alpha)?; - fb.binary(BinOp::BitwiseOr, word, alpha)? - } - _ => word, - }; - let rgba = rgba_order(fb, format, word)?; - let f4 = Form { - held: Held::Float(crate::lower::arith::FloatFmt::F32), - lanes: 4, - }; - pack::unpack(fb, PackFormat::Unorm4x8Srgb, f4, rgba) -} - -/// The `uvec4` texel (its first lane the texel's word, in the view's `R8_UINT`, `R16_UINT` or -/// `R32_UINT`) a write of output `part` (one to four `float` or `half` lanes of `form`, a missing -/// lane 0) to the sRGB attachment `color` stores: the device's encode -/// (`arith::pack::pack` of `unorm4x8_srgb`, `PrecisionNote::DevicePackConversion`: the color -/// channels through the sRGB transfer by the device's `Pow`, then the 8-bit instruction), its -/// bytes in `format`'s order; a write that keeps channels takes their bytes from the texel read -/// first at the invocation's pixel (and sample), inside the interlock, so they stay as they were, -/// bit for bit. Under a blend (`StorageView::blend`) the encode is of Metal's blend of the output -/// over that texel, decoded as a fetch reads it ([`srgb_decode`]), in the output's type, the second -/// source `second` (the function's second output) where the blend reads one, and the blend color -/// from `PushField::HalfBlendColor` where it reads that (`extended_range::Blend::srgb8`, -/// `extended_range::blend::blend_srgb8`). -fn srgb_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - (form, part): (Form, SValue), - second: Option<(Form, SValue)>, -) -> BResult { - if form - .float_fmt() - .map(crate::lower::arith::FloatFmt::container) - != Some(32) - { - return Err(cx.fail("an sRGB storage write of another output than float lanes")); - } - // The output's four lanes, a missing one 0, which the encode packs and the word cuts at the - // format's bytes. - let part = four_lanes(fb, form, part)?; - let form = Form { lanes: 4, ..form }; - // The texel the write reads first: the blend's destination, and the bytes a mask keeps. - let old = match sc.view.blend.is_some() || sc.view.merges() { - true => { - let texel = read_texel(cx, fb, color, sc)?; - Some(fb.composite_extract(texel, &[0])?) - } - false => None, - }; - let part = match (sc.view.blend, old) { - (Some(eq), Some(old)) => { - let arith = match form.float_fmt() { - Some(FloatFmt::Half) => extended_range::blend::BlendArith::Half, - _ => extended_range::blend::BlendArith::Float, - }; - let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); - let (pf, written) = (sc.view.pixel_format, written(sc.view.kept)); - let Ok((b, _)) = extended_range::Blend::srgb8(&eq, pf, written, (math, arith)) else { - return Err(cx.fail("an sRGB blend outside its forms")); - }; - let s1 = match (b.reads_second(), second) { - (true, Some((form, s1))) - if form.lanes == 4 - && matches!(form.float_fmt(), Some(FloatFmt::Half | FloatFmt::F32)) => - { - Some(s1) - } - (true, _) => return Err(cx.fail("a blend of the second source without its output")), - (false, _) => None, - }; - let decoded = srgb_decode(fb, sc.view.format, old)?; - let constant = match b.reads_constant() { - true => { - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Some(fb.composite_extract(field, &[0])?) - } - false => None, - }; - let parts = (part, s1, decoded); - extended_range::blend::blend_srgb8(fb, &b, arith, parts, constant)? - } - (Some(_), None) => return Err(cx.fail("an sRGB blend without its texel")), - (None, _) => part, - }; - let f4 = form.with(Held::Float(crate::lower::arith::FloatFmt::F32)); - let rgba = pack::pack(fb, PackFormat::Unorm4x8Srgb, f4, part)?; - let mut word = rgba_order(fb, sc.view.format, rgba)?; - // A one- or two-channel format's word is its channels' bytes alone: the view's integer format - // holds no other. - let bytes = match sc.view.format { - vk::Format::R8_SRGB => Some(0xffu32), - vk::Format::R8G8_SRGB => Some(0xffff), - _ => None, - }; - if let Some(bytes) = bytes { - let bytes = fb.u32_const(bytes)?; - let bytes = fb.module().const_value(bytes)?; - word = fb.binary(BinOp::BitwiseAnd, word, bytes)?; - } - if sc.view.merges() { - // The kept channels' bytes, in memory order. - let bytes = match sc.view.format { - vk::Format::B8G8R8A8_SRGB => [16u32, 8, 0, 24], - _ => [0u32, 8, 16, 24], - }; - let channels = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ]; - let mask = channels - .iter() - .zip(bytes) - .filter(|(c, _)| sc.view.kept.contains(**c)) - .fold(0u32, |m, (_, at)| m | 0xff << at); - let Some(old) = old else { - return Err(cx.fail("an sRGB merge without its texel")); - }; - let keep = fb.u32_const(mask)?; - let keep = fb.module().const_value(keep)?; - let write = fb.u32_const(!mask)?; - let write = fb.module().const_value(write)?; - let old = fb.binary(BinOp::BitwiseAnd, old, keep)?; - let new = fb.binary(BinOp::BitwiseAnd, word, write)?; - word = fb.binary(BinOp::BitwiseOr, old, new)?; - } - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - fb.composite_construct(uvec4, &[word, zero, zero, zero]) -} - -/// The `uvec4` texel that writes output `part` of `form` (`float` or `half` lanes) to word -/// attachment `color` (`StorageView::word`): Metal's word of the output -/// (`stage_io::word_color::encode`), or under a blend (`StorageView::blend`) of Metal's blend of -/// the four-lane output over the word read first at the pixel, inside the interlock, as Metal's -/// blend reads it (`stage_io::word_color::decode`, `extended_range::blend::blend_packed16`, the -/// blend color from `PushField::HalfBlendColor` where the blend reads it); and where the write -/// keeps some of the format's channels, the fields of those channels taken from the word read -/// first, so they keep their codes as Metal's tile keeps them. The kept channels are the draw's -/// (`PushField::StorageKeptChannels`) where the write takes them from it -/// (`StorageView::kept_at_draw`), else the view's. -fn word_texel( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - color: u32, - sc: &StorageColor, - form: Form, - part: SValue, -) -> BResult { - let Some(word) = sc.view.word else { - return Err(cx.fail("a word texel of an attachment without a word")); - }; - // The word read first, where the blend reads it. - let mut read = None; - let mut value = match sc.view.blend { - Some(eq) => { - if form.lanes != 4 { - return Err(cx.fail("a packed 16-bit blend of another output")); - } - let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); - let Ok(b) = extended_range::Blend::packed16(&eq, written(sc.view.kept), math) else { - return Err(cx.fail("a packed 16-bit blend outside Metal's model")); - }; - let texel = read_texel(cx, fb, color, sc)?; - let old = fb.composite_extract(texel, &[0])?; - read = Some(old); - let d = stage_io::word_color::decode(fb, word, old)?; - let constant = match b.reads_constant() { - true => { - let field = cx.push_field(fb, PushField::HalfBlendColor)?; - Some(fb.composite_extract(field, &[0])?) - } - false => None, - }; - let v = extended_range::blend::blend_packed16(fb, &b, (part, d), constant)?; - let f4 = form.with(Held::Float(FloatFmt::F32)); - stage_io::word_color::encode(fb, word, (f4, v))? - } - None => stage_io::word_color::encode(fb, word, (form, part))?, - }; - if sc.view.merges() { - let channels = [ - vk::ColorComponentFlags::R, - vk::ColorComponentFlags::G, - vk::ColorComponentFlags::B, - vk::ColorComponentFlags::A, - ]; - let field_bits = |f: crate::metal::format::WordField| ((1u32 << f.bits) - 1) << f.shift; - let keep = match sc.view.kept_at_draw { - // Bit `c` of the color's four in the draw's word keeps channel `c`'s field. - true => { - let draw = cx.push_field(fb, PushField::StorageKeptChannels)?; - let shift = fb.u32_const(4 * color)?; - let shift = fb.module().const_value(shift)?; - let bits = fb.binary(BinOp::ShiftRightLogical, draw, shift)?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - let mut keep = zero; - for (lane, field) in word.fields().into_iter().enumerate() { - let Some(field) = field else { - continue; - }; - let bit = fb.u32_const(1 << lane)?; - let bit = fb.module().const_value(bit)?; - let set = fb.binary(BinOp::BitwiseAnd, bits, bit)?; - let set = fb.binary(BinOp::INotEqual, set, zero)?; - let mask = fb.u32_const(field_bits(field))?; - let mask = fb.module().const_value(mask)?; - let mask = fb.select(set, mask, zero)?; - keep = fb.binary(BinOp::BitwiseOr, keep, mask)?; - } - keep - } - false => { - let mask = channels - .iter() - .zip(word.fields()) - .filter(|(c, _)| sc.view.kept.contains(**c)) - .filter_map(|(_, f)| f) - .fold(0u32, |m, f| m | field_bits(f)); - let mask = fb.u32_const(mask)?; - fb.module().const_value(mask)? - } - }; - let old = match read { - Some(old) => old, - None => { - let texel = read_texel(cx, fb, color, sc)?; - fb.composite_extract(texel, &[0])? - } - }; - let old = fb.binary(BinOp::BitwiseAnd, old, keep)?; - let write = fb.unary(UnOp::Not, keep)?; - let new = fb.binary(BinOp::BitwiseAnd, value, write)?; - value = fb.binary(BinOp::BitwiseOr, old, new)?; - } - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - fb.composite_construct(uvec4, &[value, zero, zero, zero]) -} - -/// The blend an extended-range attachment's write computes in the shader -/// (`StorageView::blend`) of an output of four lanes of `output` (`None` for another output), -/// by the device's arithmetic (`extended_range::blend::NativeBlend`): `None` for no blend; `Err` -/// (`Feature::ExtendedRangeBlend` `Output`) for an output other than four `half` or `float` lanes. -fn blend_of( - view: &StorageView, - output: Option, -) -> Result, Error> { - let (Some(eq), Some(_)) = (view.blend, view.extended) else { - return Ok(None); - }; - extended_range_output(output)?; - extended_range::blend::NativeBlend::of(&eq, written(view.kept)).map(Some) -} - /// `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> { @@ -3341,84 +468,5 @@ pub(super) fn written(kept: vk::ColorComponentFlags) -> ColorWriteMask { .fold(ColorWriteMask::NONE, |m, (_, c)| m.union(c)) } -/// Whether returned value `x`'s `[[sample_mask]]` output, in field `field`, sets the bit of the -/// invocation's own sample: `((mask >> SampleId) & 1) != 0`. Under sample shading an invocation -/// shades its one sample, and Metal keeps its write exactly when the mask sets that sample's bit. -/// At one sample, where no `SampleId` is planned, bit 0 (Metal stores no color without it). -fn sample_bit( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - x: SValue, - field: u32, -) -> BResult { - let mask = match cx.plan.families.stage_io.returned { - Returned::Struct => fb.composite_extract(x, &[field])?, - Returned::Value | Returned::Void => { - return Err(cx.fail("a returned sample mask outside a returned struct")) - } - }; - let sample = match sample(cx, fb)? { - Some(sample) => sample, - None => { - let zero = fb.u32_const(0)?; - fb.module().const_value(zero)? - } - }; - let shifted = fb.binary(BinOp::ShiftRightLogical, mask, sample)?; - let one = fb.u32_const(1)?; - let one = fb.module().const_value(one)?; - let bit = fb.binary(BinOp::BitwiseAnd, shifted, one)?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - fb.binary(BinOp::INotEqual, bit, zero) -} - -/// The `vec4` texel of the attachment's sampled type that writes output `x` of `form`: its lanes -/// then zeros (lanes past the format's channels are ignored), a signed-integer one's bits as -/// `int`. -fn texel_of( - fb: &mut FunctionBuilder<'_>, - x: SValue, - form: Form, - numeric: SampledType, -) -> BResult { - let elem = scalar_type( - fb.module(), - if form.is_float() { - SampledType::Float - } else { - SampledType::Uint - }, - )?; - let vec4 = fb.module().ty(SType::Vector { elem, len: 4 })?; - let texel = if form.lanes == 4 { - x - } else { - let zero = ops::splat( - fb, - Form { - held: form.held, - lanes: 1, - }, - 0, - )?; - let mut parts = Vec::with_capacity(4); - for lane in 0..4u32 { - parts.push(match lane { - 0 if form.lanes == 1 => x, - l if l < u32::from(form.lanes) => fb.composite_extract(x, &[l])?, - _ => zero, - }); - } - fb.composite_construct(vec4, &parts)? - }; - if numeric != SampledType::Sint { - return Ok(texel); - } - let i32_ = scalar_type(fb.module(), SampledType::Sint)?; - let ivec4 = fb.module().ty(SType::Vector { elem: i32_, len: 4 })?; - fb.convert(ConvOp::Bitcast, texel, ivec4) -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs b/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs index 36f7aa90e..6e8cb43e1 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs @@ -1,1104 +1,29 @@ -//! The storage form's choice: what blocks it, with which reason, and how it declares an attachment. +//! The extended-range blend's answer by the device's fetch ordering. use super::*; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::lower::arith::extended_range::blend::BlendMath; use crate::metal::PixelFormat; -use crate::pipeline::descriptor::ColorAttachmentDescriptor; -/// Committed profile `stem` with `features` removed from its description. -fn profile(stem: &str, features: &[VkFeature]) -> DeviceProfile { +/// 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 mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - for f in features { - desc.features.remove(f); - } + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) .expect("device") .profile() .clone() } -/// Committed profile `stem` with `features` removed from its description, read at Vulkan 1.2 (the -/// runtime's instance) with `VK_KHR_format_feature_flags2` enabled where `flags2` -/// (`pipeline::testing::description_at_1_2`; without it, a device that lists the extension and a -/// consumer that did not enable it). -fn profile_with(stem: &str, features: &[VkFeature], flags2: bool) -> DeviceProfile { - let mut desc = crate::pipeline::testing::description_at_1_2(stem, flags2).expect("description"); - for f in features { - desc.features.remove(f); - } - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) - .expect("device") - .profile() - .clone() -} - -/// The state of a pipeline of one color attachment of `format` at index 0, changed by `edit`. -fn state( - format: PixelFormat, - edit: impl FnOnce(&mut ColorAttachmentDescriptor), -) -> FramebufferFetchInputs { - let mut c = ColorAttachmentDescriptor::new(format); - edit(&mut c); - FramebufferFetchInputs::of([0], &[Some(c)], false, false, 1) -} - -const WRITES: ColorUse = ColorUse { - writes: true, - early_tests: true, - draw_tested: false, - math: BlendMath::Fast, - logic_op: None, -}; -const READS: ColorUse = ColorUse { - writes: false, - ..WRITES -}; - -fn form( - inputs: &FramebufferFetchInputs, - multisampled: bool, - use_: ColorUse, - p: &DeviceProfile, -) -> Result { - storage_form(0, inputs, multisampled, use_, p).expect("no descriptor error") -} - -fn declared( - r: Result, -) -> (vk::Format, crate::spv::ImageFormat, SampledType) { - let v = r.expect("the storage form"); - (v.format, v.declared, v.numeric) -} - -/// The image format a view of `viewed` for `use_` declares on `p`: none where the device grants -/// that access without a format, else `typed`. -fn expected_declaration( - viewed: vk::Format, - use_: ColorUse, - typed: crate::spv::ImageFormat, - p: &DeviceProfile, -) -> crate::spv::ImageFormat { - match accessed_without_format(viewed, StorageUse::texture(true, use_.writes), p) { - true => crate::spv::ImageFormat::Unknown, - false => typed, - } -} - -/// A clean single-sample state takes the storage form on every device that orders fetch only -/// through the interlock, declared without a format where the device grants the format's storage -/// access without one, else with the format's SPIR-V image format. -#[test] -fn a_clean_state_takes_the_storage_form() { - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "intel-arl-anv", - "intel-irisxe-anv", - "nvidia-rtx50-linux", - ] { - let p = profile(stem, &[]); - assert!(interlock_orders(&p), "{stem}"); - for (pf, want) in [ - ( - PixelFormat::R32Float, - ( - vk::Format::R32_SFLOAT, - crate::spv::ImageFormat::R32f, - SampledType::Float, - ), - ), - ( - PixelFormat::RGBA8Unorm, - ( - vk::Format::R8G8B8A8_UNORM, - crate::spv::ImageFormat::Rgba8, - SampledType::Float, - ), - ), - ( - PixelFormat::RGBA32Uint, - ( - vk::Format::R32G32B32A32_UINT, - crate::spv::ImageFormat::Rgba32ui, - SampledType::Uint, - ), - ), - ( - PixelFormat::RG16Float, - ( - vk::Format::R16G16_SFLOAT, - crate::spv::ImageFormat::Rg16f, - SampledType::Float, - ), - ), - ] { - for use_ in [WRITES, READS] { - let mut want = want; - want.1 = expected_declaration(want.0, use_, want.1, &p); - assert_eq!( - declared(form(&state(pf, |_| {}), false, use_, &p)), - want, - "{stem} {pf:?} {use_:?}" - ); - } - } - } - for stem in ["lavapipe", "runtime-floor"] { - assert!(!interlock_orders(&profile(stem, &[])), "{stem}"); - } -} - -/// What the form does not model is `NotImplemented`: an amplified pipeline, and, for a written -/// attachment only, a signed normalized format under a write mask -/// that keeps some of its channels, alpha to coverage, a returned sample mask at one sample, and a -/// depth or stencil attachment without early fragment tests, but where each draw's plan checks its -/// tests. Another format's blend is the generic one ([`StorageView::generic_blend`]): a 32-bit -/// float attachment's under a blend color, which Metal's own measured arithmetic there does not -/// fit. -#[test] -fn unmodelled_states_are_not_implemented() { - let p = profile("moltenvk-m3", &[]); - let ni = Err(Unsupported::not_implemented(Feature::FramebufferFetch)); - let r32 = state(PixelFormat::R32Float, |_| {}); - let mut amplified = r32.clone(); - amplified.amplified = true; - assert_eq!(form(&lified, false, READS, &p), ni); - // A blend color's lerp, which is no fitted form of a 32-bit float attachment at any channel - // count: the generic blend. - let generic = state(PixelFormat::R32Float, |c| { - c.blending_enabled = true; - c.source_rgb_blend_factor = crate::metal::BlendFactor::BlendColor; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::OneMinusBlendColor; - }); - let view = form(&generic, false, WRITES, &p).expect("the generic blend"); - assert!(view.generic_blend && view.blend.is_some(), "{view:?}"); - // Only the red channel of a one-channel format needs writing. - let red = state(PixelFormat::R32Float, |c| { - c.write_mask = ColorWriteMask::RED - }); - let rg = state(PixelFormat::RGBA8Snorm, |c| { - c.write_mask = ColorWriteMask::RED.union(ColorWriteMask::GREEN) - }); - let mut coverage = r32.clone(); - coverage.alpha_to_coverage = true; - let mut depth = r32.clone(); - depth.depth_or_stencil = true; - let late = ColorUse { - early_tests: false, - ..WRITES - }; - for (what, inputs, use_) in [ - ("signed normalized write mask", &rg, WRITES), - ("alpha to coverage", &coverage, WRITES), - ("depth without early tests", &depth, late), - ] { - assert_eq!(form(inputs, false, use_, &p), ni, "{what}"); - let read = ColorUse { - writes: false, - ..use_ - }; - assert!(form(inputs, false, read, &p).is_ok(), "{what}, read only"); - } - assert!(form(&red, false, WRITES, &p).is_ok()); - assert!(form(&depth, false, WRITES, &p).is_ok()); - // A write before the tests whose draws' plans check them. - let tested = ColorUse { - draw_tested: true, - ..late - }; - assert!(form(&depth, false, tested, &p).is_ok()); -} - -/// An 8-bit four-channel sRGB attachment takes the storage form through a view in `R32_UINT`, -/// declared `R32ui` (without a format where the device grants that) with `uint` texels, which the -/// function reads and writes as floats it decodes and encodes itself; a blend into one is Metal's, -/// which the function computes ([`extended_range::Blend::srgb8`]), its second source's too, and a -/// replacing one stores the source as an unblended write does. -#[test] -fn a_four_channel_srgb_attachment_takes_a_uint_view() { - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "intel-arl-anv", - "nvidia-rtx50-linux", - ] { - let p = profile(stem, &[]); - for (pf, format) in [ - (PixelFormat::RGBA8UnormSRGB, vk::Format::R8G8B8A8_SRGB), - (PixelFormat::BGRA8UnormSRGB, vk::Format::B8G8R8A8_SRGB), - ] { - for use_ in [WRITES, READS] { - let view = form(&state(pf, |_| {}), false, use_, &p).expect("the storage form"); - assert_eq!( - (view.format, view.declared, view.numeric, view.uint_view), - ( - format, - expected_declaration( - vk::Format::R32_UINT, - use_, - crate::spv::ImageFormat::R32ui, - &p - ), - SampledType::Uint, - Some(vk::Format::R32_UINT) - ), - "{stem} {pf:?} {use_:?}" - ); - assert_eq!(view.read_class(), SampledType::Float, "{stem} {pf:?}"); - } - // A mask that keeps channels merges their bytes. - let masked = state(pf, |c| c.write_mask = ColorWriteMask::RED); - assert!(form(&masked, false, WRITES, &p).is_ok(), "{stem} {pf:?}"); - for (destination, blends) in [ - (crate::metal::BlendFactor::One, true), - (crate::metal::BlendFactor::OneMinusSource1Color, true), - (crate::metal::BlendFactor::Zero, false), - ] { - let blended = state(pf, |c| { - c.blending_enabled = true; - c.destination_rgb_blend_factor = destination; - c.destination_alpha_blend_factor = destination; - }); - let view = form(&blended, false, WRITES, &p).expect("the sRGB blend"); - assert_eq!( - view.blend.is_some(), - blends, - "{stem} {pf:?} {destination:?}" - ); - let read = form(&blended, false, READS, &p).expect("a read"); - assert_eq!(read.blend, None, "{stem} {pf:?} {destination:?}"); - } - } - } -} - -/// A one- or two-channel 8-bit sRGB attachment (`R8Unorm_sRGB`, `RG8Unorm_sRGB`) on a device that -/// renders its format (MoltenVK, RADV) takes the storage form as a four-channel one does, through -/// a view in the unsigned integer format of its texel (`R8_UINT`, `R16_UINT`), read and written, -/// under a blend the function computes ([`extended_range::Blend::srgb8`]), and the two-channel -/// one's under a mask that keeps one channel. -#[test] -fn a_one_or_two_channel_srgb_attachment_takes_a_uint_view() { - use crate::spv::ImageFormat as I; - for stem in ["moltenvk-m3", "amd-rdna3-radv"] { - let p = profile(stem, &[]); - for (pf, format, uint, declared) in [ - ( - PixelFormat::R8UnormSRGB, - vk::Format::R8_SRGB, - vk::Format::R8_UINT, - I::R8ui, - ), - ( - PixelFormat::RG8UnormSRGB, - vk::Format::R8G8_SRGB, - vk::Format::R16_UINT, - I::R16ui, - ), - ] { - for use_ in [WRITES, READS] { - let view = form(&state(pf, |_| {}), false, use_, &p).expect("the storage form"); - assert_eq!( - (view.format, view.declared, view.numeric, view.uint_view), - ( - format, - expected_declaration(uint, use_, declared, &p), - SampledType::Uint, - Some(uint) - ), - "{stem} {pf:?} {use_:?}" - ); - assert_eq!(view.read_class(), SampledType::Float, "{stem} {pf:?}"); - } - let blended = state(pf, |c| { - c.blending_enabled = true; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::OneMinusSourceAlpha; - c.destination_alpha_blend_factor = crate::metal::BlendFactor::OneMinusSourceAlpha; - }); - let view = form(&blended, false, WRITES, &p).expect("the sRGB blend"); - assert!(view.blend.is_some(), "{stem} {pf:?}"); - } - let masked = state(PixelFormat::RG8UnormSRGB, |c| { - c.write_mask = ColorWriteMask::GREEN; - }); - let view = form(&masked, false, WRITES, &p).expect("a masked write"); - assert_eq!(view.kept, vk::ColorComponentFlags::R, "{stem}"); - } -} - -/// A BGRA-order attachment (`BGRA8Unorm`, `BGR10A2Unorm`), whose format SPIR-V names no image -/// format for, takes the storage form on a device that accesses its format without one in neither -/// direction (the ANV profiles: no `shaderStorageImageReadWithoutFormat`) through a view in its -/// RGBA-order twin, declared as the twin is (by its SPIR-V image format, or without one where the -/// device grants the twin that), with `float` texels: of one sample -/// and as sample planes, read only, written, and under a write mask that keeps some channels. So -/// does a device whose description states no per-format bits (no `VkFormatProperties3`: -/// `intel-arl-anv`), which reads without a format only the formats Vulkan lists for it, no -/// BGRA-order one among them. On a device that reads and writes the format without one it keeps -/// its own format, declared without one, as before. -#[test] -fn a_bgra_order_attachment_takes_its_rgba_twin_where_no_declaration_reaches_it() { - use crate::spv::ImageFormat as I; - let formats = [ - ( - PixelFormat::BGRA8Unorm, - vk::Format::B8G8R8A8_UNORM, - vk::Format::R8G8B8A8_UNORM, - I::Rgba8, - ), - ( - PixelFormat::BGR10A2Unorm, - vk::Format::A2R10G10B10_UNORM_PACK32, - vk::Format::A2B10G10R10_UNORM_PACK32, - I::Rgb10A2, - ), - ]; - let partial = ColorWriteMask::RED.union(ColorWriteMask::BLUE); - for stem in [ - "intel-irisxe-anv", - "intel-irisxe-rplp-anv", - "intel-uhd770-rpls-anv", - "intel-arl-anv", - ] { - let p = profile(stem, &[]); - assert!(interlock_orders(&p), "{stem}"); - for (pf, format, twin, typed) in formats { - assert_eq!( - StorageAttachmentUse::view_alias_of(format, &p), - Some(twin), - "{stem} {pf:?}" - ); - for multisampled in [false, true] { - for (use_, mask) in [ - (READS, ColorWriteMask::ALL), - (WRITES, ColorWriteMask::ALL), - (WRITES, partial), - ] { - let what = format!("{stem} {pf:?} {multisampled} {use_:?} {mask:?}"); - let view = form(&state(pf, |c| c.write_mask = mask), multisampled, use_, &p) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!( - ( - view.format, - view.rgba_view, - view.uint_view, - view.declared, - view.numeric - ), - ( - format, - Some(twin), - None, - expected_declaration(twin, use_, typed, &p), - SampledType::Float - ), - "{what}" - ); - let samples = match multisampled { - true => StorageSamples::Planes, - false => StorageSamples::One, - }; - assert_eq!(view.samples, samples, "{what}"); - assert_eq!(view.merges(), mask == partial, "{what}"); - } - } - } - } - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "amd-780m-radv", - "nvidia-rtx50-linux", - "nvidia-rtx5080-laptop", - ] { - let p = profile(stem, &[]); - let (pf, format, ..) = formats[0]; - assert_eq!( - StorageAttachmentUse::view_alias_of(format, &p), - None, - "{stem}" - ); - for use_ in [READS, WRITES] { - let view = form(&state(pf, |_| {}), false, use_, &p).expect("the storage form"); - assert_eq!( - (view.rgba_view, view.declared), - (None, I::Unknown), - "{stem}" - ); - } - } -} - -/// The view a fetched attachment takes (`StorageAttachmentUse::view_alias_of`, the one decision of -/// the compile layer and the runtime) on every committed profile: an 8-bit sRGB format's -/// unsigned-integer view whatever the device; any other format the device reads and writes without -/// a format keeps its own view (as every such device had before); and a BGRA-order format it does -/// not takes its RGBA-order twin only where the device stores the twin and declares it. Some -/// committed profile takes a twin. -#[test] -fn a_view_alias_is_a_twin_only_where_no_declaration_reaches_the_format() { - let rw = StorageUse::READ_WRITE_TEXTURE; - let mut twins = 0; - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - for &pf in PixelFormat::ALL { - let Some(format) = crate::metal::format::direct_format(pf) else { - continue; - }; - let srgb = match format { - vk::Format::B8G8R8A8_SRGB | vk::Format::R8G8B8A8_SRGB => Some(vk::Format::R32_UINT), - vk::Format::R8G8_SRGB => Some(vk::Format::R16_UINT), - vk::Format::R8_SRGB => Some(vk::Format::R8_UINT), - _ => None, - }; - let alias = StorageAttachmentUse::view_alias_of(format, &p); - let what = format!("{stem} {pf:?}"); - if srgb.is_some() || accessed_without_format(format, rw, &p) { - assert_eq!(alias, srgb, "{what}"); - continue; - } - match alias { - Some(twin) => { - assert_eq!(rgba_twin(format), Some(twin), "{what}"); - assert!(p.supports_format(twin, FormatUsage::StorageImage), "{what}"); - assert!( - accessed_without_format(twin, rw, &p) || spirv_image_format(twin).is_some(), - "{what}" - ); - twins += 1; - } - None => assert!( - rgba_twin(format).is_none_or(|t| !rgba_twin_gaps(t, &p).is_empty()), - "{what}" - ), - } - } - } - assert!( - twins > 0, - "no committed profile views an attachment in its twin" - ); -} - -/// A BGRA-order attachment whose RGBA-order twin lacks something too is refused naming both -/// routes: `BGR10A2Unorm` on the ANV profile without `shaderStorageImageExtendedFormats` (its -/// twin's `Rgb10A2` is an extended format) needs reads without a format of its own format, or the -/// extended formats for the twin. With `VK_KHR_format_feature_flags2` the first is the format's own -/// `STORAGE_READ_WITHOUT_FORMAT` bit, which `A2R10G10B10_UNORM_PACK32` lacks there; without it, the -/// feature. `BGRA8Unorm`'s twin, a base format, still serves. -#[test] -fn a_bgra_order_attachment_without_either_route_names_both() { - use crate::error::Needs; - let format = vk::Format::A2R10G10B10_UNORM_PACK32; - let own_bit = Capability::Format { - format, - usage: FormatUsage::StorageImageReadWithoutFormat, - }; - let feature = Capability::Feature(VkFeature::ShaderStorageImageReadWithoutFormat); - for (flags2, reads) in [(true, own_bit), (false, feature)] { - let p = profile_with( - "intel-irisxe-anv", - &[VkFeature::ShaderStorageImageExtendedFormats], - flags2, - ); - assert_eq!(StorageAttachmentUse::view_alias_of(format, &p), None); - let refused = form(&state(PixelFormat::BGR10A2Unorm, |_| {}), false, WRITES, &p) - .expect_err("no route"); - assert_eq!( - refused.needs, - Needs::AnyOf(vec![ - vec![reads], - vec![Capability::Feature( - VkFeature::ShaderStorageImageExtendedFormats - )], - ]), - "VK_KHR_format_feature_flags2 enabled: {flags2}" - ); - let bgra8 = form(&state(PixelFormat::BGRA8Unorm, |_| {}), false, WRITES, &p); - assert_eq!( - bgra8.map(|v| v.rgba_view), - Ok(Some(vk::Format::R8G8B8A8_UNORM)) - ); - } -} - -/// On a device without `shaderStorageImageReadWithoutFormat` (the ANV profile), every color format -/// whose storage form is modelled takes it but those whose direct format has neither a SPIR-V -/// image format, nor an RGBA-order twin, nor its own `STORAGE_READ_WITHOUT_FORMAT` bit where -/// `VK_KHR_format_feature_flags2` is enabled, refused naming the reads without a format they would -/// need (the bit, or without the extension the feature): the 16-bit packed formats, whose exact -/// form (a view of their 16-bit words, converted by Metal's measured conversions in the shader) is -/// not built. -#[test] -fn without_formatless_reads_only_formats_no_declaration_reaches_are_refused() { - for flags2 in [true, false] { - formats_no_declaration_reaches_are_refused(flags2); - } -} - -fn formats_no_declaration_reaches_are_refused(flags2: bool) { - use crate::error::Needs; - let p = profile_with("intel-irisxe-anv", &[], flags2); - let mut refused = Vec::new(); - for &pf in PixelFormat::ALL { - let inputs = FramebufferFetchInputs::of( - [0], - &[Some(ColorAttachmentDescriptor::new(pf))], - false, - false, - 1, - ); - for use_ in [READS, WRITES] { - let Ok(Err(u)) = storage_form(0, &inputs, false, use_, &p) else { - continue; - }; - if matches!(u.needs, Needs::NotImplemented | Needs::NotRepresentable) { - continue; - } - let reads = match flags2 { - true => Capability::Format { - format: crate::metal::format::direct_format(pf).expect("a direct format"), - usage: FormatUsage::StorageImageReadWithoutFormat, - }, - false => Capability::Feature(VkFeature::ShaderStorageImageReadWithoutFormat), - }; - let needs_reads = |alt: &Vec| alt.contains(&reads); - let Needs::AnyOf(alternatives) = &u.needs else { - panic!("{pf:?} {use_:?}: {u:?}"); - }; - assert!( - alternatives.iter().all(needs_reads), - "{pf:?} {use_:?}: {u:?}" - ); - if !refused.contains(&pf) { - refused.push(pf); - } - } - } - assert_eq!( - refused, - [ - PixelFormat::B5G6R5Unorm, - PixelFormat::A1BGR5Unorm, - PixelFormat::ABGR4Unorm, - PixelFormat::BGR5A1Unorm, - ], - "VK_KHR_format_feature_flags2 enabled: {flags2}: {refused:?}" - ); -} - -/// A native `A8_UNORM` attachment, which no SPIR-V image format names and whose compatibility class -/// is its own (no other view reaches it), takes the storage form on the ANV profile, which has no -/// `shaderStorageImageReadWithoutFormat`, through a declaration without a format where -/// `VK_KHR_format_feature_flags2` is enabled, as `A8_UNORM`'s own `STORAGE_READ_WITHOUT_FORMAT` bit -/// grants (Mesa 26.2.4 on the Iris Xe reports it); without the extension it is refused naming the -/// feature. A format that lacks the bit there (`B5G6R5Unorm`'s `R5G6B5_UNORM_PACK16`) stays refused, -/// naming the bit. -#[test] -fn an_a8_unorm_attachment_is_fetched_without_a_format_by_its_own_bit() { - use crate::error::Needs; - let a8 = state(PixelFormat::A8Unorm, |_| {}); - for use_ in [READS, WRITES] { - let p = profile_with("intel-irisxe-rplp-anv", &[], true); - assert!(!p.images().storage_read_without_format); - assert_eq!( - declared(form(&a8, false, use_, &p)), - ( - vk::Format::A8_UNORM, - crate::spv::ImageFormat::Unknown, - SampledType::Float - ), - "{use_:?}" - ); - let packed = - form(&state(PixelFormat::B5G6R5Unorm, |_| {}), false, use_, &p).expect_err("no bit"); - assert_eq!( - packed.needs, - Needs::AnyOf(vec![vec![Capability::Format { - format: vk::Format::R5G6B5_UNORM_PACK16, - usage: FormatUsage::StorageImageReadWithoutFormat, - }]]), - "{use_:?}" - ); - let without = profile_with("intel-irisxe-rplp-anv", &[], false); - assert_eq!( - form(&a8, false, use_, &without) - .expect_err("no route") - .needs, - Needs::AnyOf(vec![vec![Capability::Feature( - VkFeature::ShaderStorageImageReadWithoutFormat - )]]), - "{use_:?}" - ); - } -} - -/// A blend of one and zero, added, for color and alpha stores the source as no blend does, so a -/// written attachment under it takes the storage form unblended, but for a signed normalized format -/// (its NaN stores another code under the blend), whose blend the shader computes, the generic -/// one; one and zero for color alone is a blend, and a 32-bit float attachment's blend is the -/// generic one under every state and math: the shader computes `S*Fs op D*Fd` in `float`, as the -/// device's blend unit would. A write whose -/// mask covers none of the format's channels stores nothing: no blend, alpha to coverage, one -/// sample's returned mask, or late depth test bears on it, but an `Unspecialized` mask stays -/// refused. -#[test] -fn a_replacing_blend_and_a_write_that_stores_nothing_take_the_storage_form() { - use crate::metal::{BlendFactor, BlendOperation}; - let p = profile("moltenvk-m3", &[]); - let ni = Err(Unsupported::not_implemented(Feature::FramebufferFetch)); - let replacing = |pf: PixelFormat| state(pf, |c| c.blending_enabled = true); - for pf in [ - PixelFormat::RG16Float, - PixelFormat::R32Float, - PixelFormat::RGBA8Unorm, - ] { - assert!(form(&replacing(pf), false, WRITES, &p).is_ok(), "{pf:?}"); - } - let generic = |inputs: &FramebufferFetchInputs| { - let view = form(inputs, false, WRITES, &p).expect("the generic blend"); - view.generic_blend && view.blend.is_some() - }; - assert!(generic(&replacing(PixelFormat::RG8Snorm))); - assert!(!generic(&replacing(PixelFormat::R32Float))); - // A 32-bit float attachment's blend is the generic one, whatever its state or math. - let alpha_adds = state(PixelFormat::R32Float, |c| { - c.blending_enabled = true; - c.destination_alpha_blend_factor = BlendFactor::One; - }); - let subtracts = state(PixelFormat::R32Float, |c| { - c.blending_enabled = true; - c.rgb_blend_operation = BlendOperation::Subtract; - }); - let source_by_destination = |pf| { - state(pf, |c| { - c.blending_enabled = true; - c.source_rgb_blend_factor = BlendFactor::SourceColor; - c.destination_rgb_blend_factor = BlendFactor::DestinationColor; - c.source_alpha_blend_factor = BlendFactor::SourceColor; - c.destination_alpha_blend_factor = BlendFactor::DestinationColor; - }) - }; - for blended in [ - &alpha_adds, - &subtracts, - &source_by_destination(PixelFormat::R32Float), - &source_by_destination(PixelFormat::RG32Float), - ] { - assert!(generic(blended)); - } - let safe = ColorUse { - math: BlendMath::Rounded, - ..WRITES - }; - let rounded = form(&alpha_adds, false, safe, &p).expect("the storage form"); - assert!(rounded.generic_blend && rounded.blend.is_some()); - // A write that stores nothing, under each state that refuses a store. - let none = |edit: fn(&mut ColorAttachmentDescriptor)| { - state(PixelFormat::RG16Float, |c| { - c.write_mask = ColorWriteMask::NONE; - edit(c); - }) - }; - let blended = none(|c| { - c.blending_enabled = true; - c.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - }); - let mut coverage = none(|_| {}); - coverage.alpha_to_coverage = true; - let mut depth = none(|_| {}); - depth.depth_or_stencil = true; - let late = ColorUse { - early_tests: false, - ..WRITES - }; - for (what, inputs, use_) in [ - ("blending", &blended, WRITES), - ("alpha to coverage", &coverage, WRITES), - ("depth without early tests", &depth, late), - ] { - let view = form(inputs, false, use_, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(view.stores_nothing(), "{what}"); - } - let unspecialized = state(PixelFormat::RG16Float, |c| { - c.write_mask = ColorWriteMask::UNSPECIALIZED - }); - assert_eq!(form(&unspecialized, false, WRITES, &p), ni); - assert!(form(&unspecialized, false, READS, &p).is_ok()); -} - -/// A blend into a 16-bit float attachment that the write stores takes the storage form with the -/// blend the shader computes (`StorageView::blend`), under either blend math, on every device that -/// orders fetch through the pixel interlock alone: for each 16-bit float format, the macOS 27 -/// window server's one over one minus the source alpha among the factors and operations Metal's -/// model holds, the blend color's difference with its one minus (under fast math Metal's form, the -/// minuend's product fused and the subtrahend's rounded), and a write mask that keeps some -/// channels. A factor of the second source takes the generic blend -/// (`StorageView::generic_blend`). A read-only attachment, a replacing blend under fast math and a write that -/// stores nothing take the form without one; a replacing blend without fast math keeps the -/// destination's product by zero, so the shader computes it. -#[test] -fn a_sixteen_bit_float_blend_is_computed_in_the_storage_form() { - use crate::metal::{BlendFactor as F, BlendOperation as O}; - let descriptor = |pf: PixelFormat, (s, d, op): (F, F, O), mask: ColorWriteMask| { - let mut c = ColorAttachmentDescriptor::new(pf); - c.blending_enabled = true; - c.source_rgb_blend_factor = s; - c.destination_rgb_blend_factor = d; - c.rgb_blend_operation = op; - c.source_alpha_blend_factor = s; - c.destination_alpha_blend_factor = d; - c.alpha_blend_operation = op; - c.write_mask = mask; - c - }; - let of = - |c: ColorAttachmentDescriptor| FramebufferFetchInputs::of([0], &[Some(c)], false, false, 1); - let equations = [ - (F::One, F::OneMinusSourceAlpha, O::Add), - (F::SourceAlpha, F::OneMinusSourceAlpha, O::Subtract), - ( - F::DestinationColor, - F::OneMinusDestinationAlpha, - O::ReverseSubtract, - ), - (F::BlendColor, F::OneMinusBlendAlpha, O::Add), - (F::SourceAlphaSaturated, F::One, O::Add), - (F::One, F::One, O::Max), - ]; - let partial = ColorWriteMask::RED.union(ColorWriteMask::ALPHA); - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "intel-arl-anv", - "nvidia-rtx50-linux", - ] { - let p = profile(stem, &[]); - assert!(interlock_orders(&p), "{stem}"); - for pf in [ - PixelFormat::R16Float, - PixelFormat::RG16Float, - PixelFormat::RGBA16Float, - ] { - for math in [BlendMath::Fast, BlendMath::Rounded] { - let writes = ColorUse { math, ..WRITES }; - let reads = ColorUse { math, ..READS }; - for eq in equations { - for mask in [ColorWriteMask::ALL, partial] { - let what = format!("{stem} {pf:?} {math:?} {eq:?} {mask:?}"); - let c = descriptor(pf, eq, mask); - let view = form(&of(c), false, writes, &p) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(view.blend, BlendEquation::of(&c), "{what}"); - assert_eq!(view.extended, None, "{what}"); - let view = form(&of(c), false, reads, &p) - .unwrap_or_else(|e| panic!("{what}: read: {e:?}")); - assert_eq!(view.blend, None, "{what}: read"); - } - } - let what = format!("{stem} {pf:?} {math:?}"); - // A blend of the second source, which Metal's model does not hold: the generic - // blend. - let dual = descriptor(pf, (F::Source1Color, F::Zero, O::Add), ColorWriteMask::ALL); - let view = form(&of(dual), false, writes, &p) - .unwrap_or_else(|e| panic!("{what}: dual: {e:?}")); - assert!(view.generic_blend, "{what}: dual"); - let differs = descriptor( - pf, - (F::BlendColor, F::OneMinusBlendColor, O::Subtract), - ColorWriteMask::ALL, - ); - // Under fast math too: Metal's form, the minuend's product fused, the - // subtrahend's rounded. - assert!( - form(&of(differs), false, writes, &p).is_ok_and(|v| v.blend.is_some()), - "{what}" - ); - let replacing = descriptor(pf, (F::One, F::Zero, O::Add), ColorWriteMask::ALL); - let view = form(&of(replacing), false, writes, &p).expect(&what); - let kept_zero = math == BlendMath::Rounded; - let want = BlendEquation::of(&replacing).filter(|_| kept_zero); - assert_eq!(view.blend, want, "{what}: replacing"); - let none = descriptor(pf, equations[0], ColorWriteMask::NONE); - let view = form(&of(none), false, writes, &p).expect(&what); - assert!( - view.stores_nothing() && view.blend.is_none(), - "{what}: none" - ); - } - } - } -} - -/// A write mask short of the format's channels keeps the others: the view names them, an empty set -/// where the mask covers every channel (or the function only reads), all four where it covers none, -/// so that the write stores nothing. A signed normalized format whose mask covers none of its -/// channels stores nothing either, so nothing of it is lost. A mask that keeps some of a format's -/// channels compiles as its class: the view names the class's channels (every channel but the first -/// left out, so the first kept) and takes the pipeline's own from the draw (`kept_at_draw`), -/// whichever such mask the descriptor sets; an sRGB format's view names the mask's own and takes -/// none from the draw. -#[test] -fn a_write_mask_names_the_channels_the_write_keeps() { - use crate::lower::fragment::kept_channels; - use crate::vk::ColorComponentFlags as C; - let p = profile("moltenvk-m3", &[]); - let kept = |pf: PixelFormat, mask: ColorWriteMask, use_: ColorUse| { - form(&state(pf, |c| c.write_mask = mask), false, use_, &p).map(|view| { - ( - view.kept, - view.kept_at_draw, - view.merges(), - view.stores_nothing(), - ) - }) - }; - let rg = ColorWriteMask::RED.union(ColorWriteMask::GREEN); - let ba = ColorWriteMask::BLUE.union(ColorWriteMask::ALPHA); - let rgba8 = PixelFormat::RGBA8Unorm; - assert_eq!(kept(rgba8, rg, WRITES), Ok((C::R, true, true, false))); - // Another partial mask: the same class, the same view. - assert_eq!( - kept(rgba8, ColorWriteMask::BLUE, WRITES), - kept(rgba8, rg, WRITES) - ); - // The pipeline's own kept channels, which the draw names. - assert_eq!(kept_channels(rgba8, rg, true), ba); - assert_eq!( - kept(rgba8, ColorWriteMask::ALL, WRITES), - Ok((C::empty(), false, false, false)) - ); - assert_eq!( - kept(rgba8, rg, READS), - Ok((C::empty(), false, false, false)) - ); - let green = ColorWriteMask::GREEN; - assert_eq!( - kept(PixelFormat::RG16Float, green, WRITES), - Ok((C::R, true, true, false)) - ); - // Blue and alpha are no channels of `RG16Float`: the write stores nothing. - assert_eq!( - kept(PixelFormat::RG16Float, ba, WRITES), - Ok((C::known_bits(), false, false, true)) - ); - // An sRGB format's write merges its view's bytes under the mask's own channels. - assert_eq!( - kept(PixelFormat::BGRA8UnormSRGB, rg, WRITES), - Ok((C::B | C::A, false, true, false)) - ); - assert_eq!( - kept(PixelFormat::RG8Snorm, ColorWriteMask::NONE, WRITES), - Ok((C::known_bits(), false, false, true)) - ); - assert_eq!( - kept(PixelFormat::RG8Snorm, ColorWriteMask::ALL, WRITES), - Ok((C::empty(), false, false, false)) - ); -} - -/// A multisampled pipeline takes the per-sample form: a multisampled storage image where the device -/// has `shaderStorageImageMultisample` (RADV, NVIDIA), planes, one single-sample layer per sample, -/// where it does not (ANV, MoltenVK); a pipeline of one sample takes one sample's image. The -/// `SampleId` read needs `sampleRateShading`, named where the device lacks it. Its returned sample -/// mask is modelled (the write is gated on the invocation's own sample's bit), one sample's is not. -/// Beside a depth attachment the module declares early tests, and its image writes take the same -/// form. -#[test] -fn a_multisampled_state_takes_the_per_sample_form_or_names_what_it_needs() { - use crate::error::Needs; - let r32 = state(PixelFormat::R32Float, |_| {}); - // Without a depth or stencil attachment the module declares no early tests. - let writes = ColorUse { - early_tests: false, - ..WRITES - }; - let mut depth = r32.clone(); - depth.depth_or_stencil = true; - for (stem, samples) in [ - ("amd-rdna3-radv", StorageSamples::Multisampled), - ("nvidia-rtx50-linux", StorageSamples::Multisampled), - ("moltenvk-m3", StorageSamples::Planes), - ("intel-arl-anv", StorageSamples::Planes), - ("intel-irisxe-anv", StorageSamples::Planes), - ] { - let p = profile(stem, &[]); - for use_ in [READS, writes] { - let r = form(&r32, true, use_, &p); - assert_eq!(r.clone().map(|v| v.samples), Ok(samples), "{stem} {use_:?}"); - assert_eq!( - declared(r), - ( - vk::Format::R32_SFLOAT, - expected_declaration( - vk::Format::R32_SFLOAT, - use_, - crate::spv::ImageFormat::R32f, - &p - ), - SampledType::Float - ), - "{stem} {use_:?}" - ); - } - assert_eq!( - form(&r32, false, READS, &p).map(|v| v.samples), - Ok(StorageSamples::One), - "{stem}" - ); - assert_eq!( - form(&depth, true, WRITES, &p).map(|v| v.samples), - Ok(samples), - "{stem}" - ); - assert_eq!( - form(&depth, true, READS, &p).map(|v| v.samples), - Ok(samples), - "{stem}" - ); - assert!(form(&depth, false, WRITES, &p).is_ok(), "{stem}"); - } - let no_storage_ms = profile( - "amd-rdna3-radv", - &[VkFeature::ShaderStorageImageMultisample], - ); - assert_eq!( - form(&r32, true, READS, &no_storage_ms).map(|v| v.samples), - Ok(StorageSamples::Planes) - ); - for stem in ["amd-rdna3-radv", "moltenvk-m3"] { - let bare = profile(stem, &[VkFeature::SampleRateShading]); - let needs = form(&r32, true, READS, &bare).expect_err("blocked").needs; - assert_eq!( - needs, - Needs::AnyOf(vec![vec![Capability::Feature( - VkFeature::SampleRateShading - )]]), - "{stem}" - ); - assert!(form(&r32, false, READS, &bare).is_ok(), "{stem}"); - } -} - -/// What the device lacks blocks the form with that capability: the fragment-stage store for a -/// written attachment, and, for an extended format without `shaderStorageImageExtendedFormats`, -/// that feature unless the device reads and writes the format without a format, which it then -/// declares: by its features, or, without `shaderStorageImageReadWithoutFormat`, by the format's -/// own bits where `VK_KHR_format_feature_flags2` is enabled (read at the runtime's Vulkan 1.2). -#[test] -fn device_gaps_name_what_the_device_lacks() { - use crate::error::Needs; - let r32 = state(PixelFormat::R32Float, |_| {}); - let no_stores = profile("moltenvk-m3", &[VkFeature::FragmentStoresAndAtomics]); - assert_eq!( - form(&r32, false, WRITES, &no_stores) - .expect_err("blocked") - .needs, - Needs::AnyOf(vec![vec![Capability::Feature( - VkFeature::FragmentStoresAndAtomics - )]]) - ); - assert!(form(&r32, false, READS, &no_stores).is_ok()); - let rg16 = state(PixelFormat::RG16Float, |_| {}); - let formatless = profile( - "moltenvk-m3", - &[VkFeature::ShaderStorageImageExtendedFormats], - ); - assert_eq!( - declared(form(&rg16, false, WRITES, &formatless)).1, - crate::spv::ImageFormat::Unknown - ); - assert!(form(&rg16, false, WRITES, &formatless) - .expect("formatless") - .formatless()); - let without = [ - VkFeature::ShaderStorageImageExtendedFormats, - VkFeature::ShaderStorageImageReadWithoutFormat, - ]; - let own_bits = profile_with("moltenvk-m3", &without, true); - assert_eq!( - declared(form(&rg16, false, READS, &own_bits)).1, - crate::spv::ImageFormat::Unknown - ); - let neither = profile_with("moltenvk-m3", &without, false); - assert_eq!( - form(&rg16, false, READS, &neither) - .expect_err("blocked") - .needs, - Needs::AnyOf(vec![vec![Capability::Feature( - VkFeature::ShaderStorageImageExtendedFormats - )]]) - ); -} - -/// A storage-form read or write of another numeric class than its attachment's format is Metal's -/// pipeline error, which Metal answers nil and an `NSError` ("input of type uint4 is not -/// compatible with a MTLPixelFormatRGBA8Unorm color attachment.", "output of type uint4 ...": an -/// Apple M3 Max under macOS 27.0.1, `color_attachment_answers.m`); a read or write of the -/// format's class is planned. -#[test] -fn a_read_or_write_of_another_class_is_refused_as_metal_answers_it() { - let uint4 = Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 4, - }; - let float4 = Form { - held: Held::Float(FloatFmt::F32), - lanes: 4, - }; - let refused = Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: 1, - metal: MetalAnswer::NilWithError, - })); - for write in [false, true] { - for (form, numeric) in [ - (uint4, SampledType::Float), - (float4, SampledType::Uint), - (float4, SampledType::Sint), - ] { - let got = class_of(form, numeric, 1, write); - assert_eq!(got, refused, "{form:?} into {numeric:?}, write {write}"); - } - for (form, numeric) in [ - (float4, SampledType::Float), - (uint4, SampledType::Uint), - (uint4, SampledType::Sint), - ] { - let got = class_of(form, numeric, 1, write); - assert_eq!(got, Ok(()), "{form:?} into {numeric:?}, write {write}"); - } - } -} - -/// No attachment at the color read refuses the pipeline whatever the form. -#[test] -fn a_missing_attachment_is_a_descriptor_error() { - let p = profile("moltenvk-m3", &[]); - let none = FramebufferFetchInputs::of([0], &[None], false, false, 1); - assert_eq!( - storage_form(0, &none, false, READS, &p), - Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: 0, - metal: MetalAnswer::NilWithError, - })) - ); -} - /// An extended-range format's blend (`extended_range_blend`): a padded form's taken where the device -/// orders fetch through the pixel interlock alone and the storage form holds, and where it orders -/// fetch through rasterization-order input attachments, over which the function blends; the two -/// orderings named where it has neither; 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. +/// 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_follows_the_ordered_storage_form() { +fn an_extended_range_blend_needs_rasterization_order_fetch() { let xr = [ PixelFormat::BGR10XR, PixelFormat::BGR10XRSRGB, @@ -1120,19 +45,27 @@ fn an_extended_range_blend_follows_the_ordered_storage_form() { PixelFormat::RG16Bfloat, PixelFormat::RGBA16Bfloat, ]; - for stem in [ - "moltenvk-m3", - "amd-rdna3-radv", - "amd-780m-radv", - "intel-arl-anv", - "intel-irisxe-anv", - "nvidia-rtx5080-laptop", - "nvidia-pascal-linux", + 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-rdna3-radv", 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!(interlock_orders(&p), "{stem}"); + let p = profile(stem); + assert_eq!(inputs_order(&p), ordered, "{stem}"); for pf in blended { - assert_eq!(extended_range_blend(pf, &p), Ok(()), "{stem}: {pf:?}"); + let want = if ordered { Ok(()) } else { unordered.clone() }; + assert_eq!(extended_range_blend(pf, &p), want, "{stem}: {pf:?}"); } for pf in xr { assert_eq!( @@ -1150,141 +83,8 @@ fn an_extended_range_blend_follows_the_ordered_storage_form() { } assert_eq!( extended_range_blend(PixelFormat::RGBA16Float, &p), - Err(Unsupported::not_implemented(Feature::Format)), + not_implemented, "{stem}" ); } - for stem in ["lavapipe", "gate-lavapipe-x86_64"] { - let p = profile(stem, &[]); - assert!(!interlock_orders(&p), "{stem}"); - for pf in blended { - assert_eq!(extended_range_blend(pf, &p), Ok(()), "{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:?}" - ); - } - } - // Without either ordering, the two features it needs one of. - let unordered = Unsupported::needs_any_of( - Feature::FramebufferFetch, - vec![ - vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess, - )], - ], - ); - let p = profile("runtime-floor", &[]); - assert_eq!( - extended_range_blend(PixelFormat::R10UnormX6, &p), - Err(unordered) - ); - // One of Apple's extended-range forms is refused there too, whatever the device orders. - assert_eq!( - extended_range_blend(PixelFormat::BGRA10XR, &p), - not_implemented - ); - // The storage form's own device needs, named where the device lacks one. - let p = profile("moltenvk-m3", &[VkFeature::FragmentStoresAndAtomics]); - assert!(extended_range_blend(PixelFormat::R10UnormX6, &p) - .is_err_and(|u| u.feature == Feature::FramebufferFetch)); -} - -/// A packed 16-bit attachment the device samples but does not render (`A1BGR5Unorm`, -/// `ABGR4Unorm` on the RTX 5080 profiles) takes the storage form through a view of its words: the -/// view and declaration `R16_UINT`, `uint` texels the function reads as floats, and the word's -/// layout (`StorageView::word`), whose kept fields a partial write mask merges by the draw's word; -/// a replacing blend too. Another blend is the shader's (`StorageView::blend`), but one of the -/// second source, which is not built. A device that renders the format takes it directly, without -/// the word. -#[test] -fn a_word_attachment_takes_the_view_of_its_words() { - use crate::metal::format::WordAttachment; - let ni = Err(Unsupported::not_implemented(Feature::FramebufferFetch)); - for stem in ["nvidia-rtx5080-laptop", "nvidia-rtx50-linux"] { - let p = profile(stem, &[]); - assert!(interlock_orders(&p), "{stem}"); - for pf in [PixelFormat::A1BGR5Unorm, PixelFormat::ABGR4Unorm] { - let what = format!("{stem} {pf:?}"); - let word = WordAttachment::layout(pf); - assert_eq!(WordAttachment::of(pf, &p), word, "{what}"); - for mask in [ - ColorWriteMask::RED | ColorWriteMask::GREEN, - ColorWriteMask::ALPHA, - ColorWriteMask::ALL, - ] { - let view = form(&state(pf, |c| c.write_mask = mask), false, WRITES, &p) - .unwrap_or_else(|e| panic!("{what} {mask:?}: {e:?}")); - assert_eq!( - (view.format, view.declared, view.numeric, view.word), - ( - vk::Format::R16_UINT, - expected_declaration( - vk::Format::R16_UINT, - WRITES, - crate::spv::ImageFormat::R16ui, - &p - ), - SampledType::Uint, - word - ), - "{what} {mask:?}" - ); - assert_eq!(view.read_class(), SampledType::Float, "{what}"); - assert_eq!(view.uint_view.or(view.rgba_view), None, "{what}"); - let partial = mask != ColorWriteMask::ALL; - assert_eq!( - (view.merges(), view.kept_at_draw), - (partial, partial), - "{what}" - ); - } - let replacing = state(pf, |c| { - c.blending_enabled = true; - c.write_mask = ColorWriteMask::RED; - }); - assert!(form(&replacing, false, WRITES, &p).is_ok(), "{what}"); - let blended = state(pf, |c| { - c.blending_enabled = true; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::One; - }); - let view = form(&blended, false, WRITES, &p) - .unwrap_or_else(|e| panic!("{what} blended: {e:?}")); - assert_eq!( - (view.word, view.format), - (word, vk::Format::R16_UINT), - "{what}" - ); - assert!(view.blend.is_some(), "{what}"); - let second = state(pf, |c| { - c.blending_enabled = true; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::Source1Color; - }); - assert_eq!(form(&second, false, WRITES, &p), ni, "{what}"); - } - } - let radv = profile("amd-rdna3-radv", &[]); - let view = form( - &state(PixelFormat::ABGR4Unorm, |c| { - c.write_mask = ColorWriteMask::RED - }), - false, - WRITES, - &radv, - ); - if let Ok(view) = view { - assert_eq!(view.word, None); - assert_eq!(view.format, vk::Format::R4G4B4A4_UNORM_PACK16); - } } diff --git a/crates/metal2vulkan/src/lower/fragment/imageblock.rs b/crates/metal2vulkan/src/lower/fragment/imageblock.rs deleted file mode 100644 index 293e0bcfc..000000000 --- a/crates/metal2vulkan/src/lower/fragment/imageblock.rs +++ /dev/null @@ -1,914 +0,0 @@ -//! Fragment imageblocks: `[[imageblock_data]]` inputs and outputs of a fragment function. -//! -//! **What Metal gives.** A render pass keeps an imageblock in tile memory: one cell per pixel for -//! the whole pass, of the explicit layout's `air.imageblock_data_size` bytes, undefined when the -//! pass begins, and shared by every pipeline of the pass. A fragment function reads a *view* of -//! its pixel's cell as a struct parameter (`air.imageblock_data` input) and writes a view as a -//! member of its returned struct (`air.imageblock_data` output). A view's members name members of -//! the *master* layout (`air.imageblock_master`; the view's own layout when it has none) by their -//! user key, the fifth string of each member tuple (`Member::key`; MSL §4.7.1: `[[user(name)]]`, -//! else the declared name, "must match a data member declared in the master"), and each member -//! lives at its master offset. The master's fingerprint (SHA-256 of its data size and its -//! layout's Merkle digest over each member's offset, size, array length, key, and nested -//! layout's digest, each shared layout hashed once) is the fact's and -//! `FragmentImageblock::master`: a consumer draws only pipelines of one master in a pass. -//! Explicit imageblock layouts cannot alias color attachments (no `[[color(n)]]` member, MSL -//! §4.7), and in a fragment function every master member names a raster order group, which -//! orders the accesses of overlapping fragments in primitive order. -//! -//! **The representation** (`ImageblockMechanism::StorageImageInterlock`). The pass's imageblock -//! is one coherent `R32Uint` 2D-array storage image, `SyntheticBinding::Imageblock`: layer `w` -//! holds word `w` of every pixel's cell, the cell of pixel `(x, y)` at texel `(x, y)`, which the -//! function takes from `FragCoord`. The input view is read once, member by member, in the -//! function's first block ([`emit_entry`]); the output view is written member by member at the -//! return ([`emit_return`]), each member a leaf of the cell's words (`memory::leaf`, a sub-word -//! member replaces only its bytes). The whole body runs inside the ordered pixel-interlock critical -//! section (`fragment::rog`), so the read, the body, and the write of each fragment are one step in -//! primitive order against every other fragment of the pixel, across draws, and its accesses' -//! device-scope coherence (the `Coherent` image under `GLSL450`, `MakeTexel*` under the Vulkan -//! model: `sync::memory_model`) makes each critical section's writes visible to the next one. That -//! is Metal's raster order group ordering, and more (groups only relax it). -//! -//! A discarded fragment writes nothing: a demoted invocation's image writes have no effect, a -//! terminate-form discard returns before the write, and a predicated one skips the write -//! (`discarded`). Nor does a fragment whose returned `[[sample_mask]]` does not cover its one -//! sample (bit 0 clear; the mask's other bits do not keep it): Metal drops the fragment and its -//! imageblock write with it (measured on the M3 Max and an M4), so the write is guarded by the -//! returned mask's bit 0 ([`ImageblockPlan::mask`]). -//! -//! **Two masters.** The input and output views may view different masters: each view's members -//! live at its own master's offsets of the one cell, which spans the largest master (measured on -//! the M3 Max and an M4, a `half` read at byte 0 of one master and written through a smaller master -//! that keys it at byte 2, and back, each reached those bytes and kept the rest). The fact's master -//! is the largest's. -//! -//! **Refused.** A profile without `fragmentShaderPixelInterlock` is -//! `Unsupported{Imageblocks, Feature(FragmentShaderPixelInterlock)}`; an output without -//! `fragmentStoresAndAtomics` names that feature. Not implemented: a second input or output view, -//! an output aliasing the implicit imageblock (`air.alias_implicit_imageblock`: it is the color -//! attachments' storage; an aliased input never reaches this family, `select::param_family` -//! refuses it as `TileShading`), a member that is an array or a struct, names a color -//! attachment, or whose value is wider than its slot, a view member without exactly one master -//! member of its size, a view struct field no member covers, and a view without a data size. -//! Link refuses what the one plane does not -//! model (multisampling, and a write that alpha to coverage, or a late depth or stencil test, can -//! drop: `pipeline::link::imageblock`), and the binder a layered or amplified pass. A packed -//! pixel-format member (`_pixel_type`) is refused before this family plans it, by its conversion -//! (`Lowering(Arith)` or `UnknownIntrinsic`). - -use std::collections::BTreeMap; - -use sha2::{Digest, Sha256}; - -use crate::air::abi::{ImageblockArg, ImageblockKind, Member, OutputRole, StructInfo, StructRef}; -use crate::air::container::Hash256; -use crate::air::ir::{ArgIdx, Type, TypeId as AirTypeId, Value}; -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::{self, Returned}; -use crate::lower::sync::memory_model; -use crate::memory::leaf::{self, k32, Coherence, Leaf, WordMem}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{DemoteTy, GlobalId, Value as SValue}; -use crate::spirv::ir::{ - BinOp, ConvOp, Dim, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass, - Type as SType, UnOp, -}; - -fn not_implemented() -> Error { - Unsupported::not_implemented(Feature::Imageblocks).into() -} - -/// The device capabilities a function that reads (and, when `writes`, writes) the imageblock -/// needs: the ordered pixel interlock, and stores in the fragment stage for a write. A missing -/// one refuses the function naming every missing one. -fn require(cx: &SelectCx<'_>, writes: bool) -> Result<(), Error> { - let f = cx.profile.fields(); - let mut missing = Vec::new(); - if !super::fetch::interlock_forms(cx.profile) { - missing.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock)); - } - if writes && !f.leaf.fragment_stores_and_atomics { - missing.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics)); - } - if missing.is_empty() { - return Ok(()); - } - Err(Unsupported::needs_any_of(Feature::Imageblocks, vec![missing]).into()) -} - -/// One member of a view: the view struct's field that holds it, its leaf, and its byte offset -/// in the cell (the master layout's). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ViewMember { - pub field: u32, - pub leaf: Leaf, - pub offset: u32, -} - -/// A view of the imageblock: the members of its struct value, and the struct's lowered type. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct View { - pub members: Vec, - pub ty: DemoteTy, -} - -/// The fragment imageblock part of the fragment family's plan. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct ImageblockPlan { - /// The 32-bit words of a cell the views reach: the largest data size, rounded up to a word. - pub words: u32, - /// The bytes of a cell (`air.imageblock_data_size`), the largest over the views. - pub data_size: u32, - /// The alignment Metal states for the views (`air.arg_type_align_size`, their master - /// layout's), the largest: what Metal's pipeline aligns the color attachments' bytes beside - /// the cell to (`FragmentImageblock::alignment`). - pub alignment: u32, - /// The input view and the LLVM parameter that holds it. - pub input: Option<(u32, View)>, - /// The output view and the returned struct's field that holds it. - pub output: Option<(u32, View)>, - /// The stage interface's `FragCoord` object, which gives the pixel. - pub coord: usize, - /// The fingerprint of the master layout of the most bytes the function's views view - /// (`fingerprint`; the first planned of equal size). - pub master: Option, - /// The returned struct's field holding the `[[sample_mask]]` the function returns beside an - /// output view: the write is kept only where the mask covers the invocation's sample. - pub mask: Option, - /// The stage interface's `SampleId` object of a function compiled for a multisampled - /// pipeline (`LoweringInputs::multisampled`), which runs once per covered sample and reaches - /// its own sample's cell: words `sample * words` on. - pub sample: Option, - /// The module declares early fragment tests, which the function does not, so that a depth or - /// stencil test the fragment fails drops its write as Metal's does ([`plan_tests`]). - pub early_tests: bool, -} - -/// The alignment a constant byte offset guarantees (at most 16). -fn offset_align(offset: u32) -> u64 { - 1u64 << offset.trailing_zeros().min(4) -} - -/// The layout of struct reference `r`. -fn layout<'a>(cx: &'a SelectCx<'_>, r: StructRef) -> Result<&'a StructInfo, Error> { - cx.entry - .structs - .get(r.0 as usize) - .ok_or_else(|| cx.invariant("an imageblock layout out of range")) -} - -/// The master member view member `m` names: the one whose user key equals `m`'s (MSL §4.7.1, -/// the Metal view-matching ABI), which must be unique and of `m`'s size. -fn master_member<'a>(master: &'a StructInfo, m: &Member) -> Result<&'a Member, Error> { - let mut named = master.members.iter().filter(|x| x.key == m.key); - match (named.next(), named.next()) { - (Some(x), None) if x.size == m.size && x.array_len == 0 && x.layout.is_none() => Ok(x), - _ => Err(not_implemented()), - } -} - -/// The fingerprint of master layout `master` of a cell of `data_size` bytes, over the module's -/// layouts `structs`, and how many layouts it hashed; `None` when a layout reference is out of -/// range or the layouts nest in a cycle. -/// -/// It is SHA-256 over the data size and the master's Merkle digest: a layout's digest is SHA-256 -/// over its member count and, in declaration order, each member's offset, size, array length, -/// and user key, and a nested member's layout digest. Decoded layouts are shared by reference (a -/// DAG), so each is hashed once (`memo`): the work is linear in the distinct layouts the master -/// reaches, however deep they nest. Equal fingerprints are structurally equal masters, whatever -/// metadata nodes state them. -fn fingerprint( - structs: &[StructInfo], - master: StructRef, - data_size: u32, -) -> Option<(Hash256, usize)> { - let mut memo: BTreeMap = BTreeMap::new(); - // Each frame is a layout and its first member whose nested layout is not hashed yet. - let mut stack = vec![(master, 0usize)]; - while let Some(&(r, next)) = stack.last() { - let s = structs.get(usize::try_from(r.0).ok()?)?; - let pending = s - .members - .iter() - .enumerate() - .skip(next) - .find_map(|(i, m)| m.layout.filter(|l| !memo.contains_key(l)).map(|l| (i, l))); - if let Some((at, child)) = pending { - // A layout on the stack twice nests in itself. - if stack.len() > structs.len() { - return None; - } - if let Some(top) = stack.last_mut() { - top.1 = at; - } - stack.push((child, 0)); - continue; - } - stack.pop(); - if memo.contains_key(&r) { - continue; - } - let mut h = Sha256::new(); - h.update((s.members.len() as u64).to_le_bytes()); - for m in &s.members { - for n in [m.offset, m.size, m.array_len] { - h.update(n.to_le_bytes()); - } - h.update((m.key.0.len() as u64).to_le_bytes()); - h.update(&m.key.0); - match m.layout.and_then(|l| memo.get(&l)) { - Some(d) => { - h.update([1]); - h.update(d); - } - None => h.update([0]), - } - } - memo.insert(r, h.finalize().into()); - } - let mut h = Sha256::new(); - h.update(data_size.to_le_bytes()); - h.update(memo.get(&master)?); - Some((h.finalize().into(), memo.len())) -} - -/// The cell a view reaches: its master's data size, the alignment Metal states for the view -/// (`air.arg_type_align_size`: its master layout's, a view of part of a master included), and -/// the master's `fingerprint`. -#[derive(Clone, Copy)] -struct Reached { - data_size: u32, - alignment: u32, - master: Hash256, -} - -/// The view of AIR struct type `ty` that imageblock argument `ib` of stated alignment `align` -/// (`air.arg_type_align_size`) describes, and the cell it reaches. Metal's compiler states the -/// alignment of every view, its master layout's; a view that states none (hand-written AIR) -/// takes its own layout's ABI alignment, which is the master's where the view is its master. -/// A stated alignment that is not a power of two is not implemented. -fn view( - cx: &SelectCx<'_>, - ty: AirTypeId, - ib: &ImageblockArg, - align: Option, -) -> Result<(View, Reached), Error> { - if ib.kind != ImageblockKind::Data { - return Err(cx.invariant("a fragment imageblock of another kind")); - } - // An imageblock aliasing the implicit one is the color attachments' own storage, which the - // side image is not. - if ib.alias_implicit { - return Err(not_implemented()); - } - let data_size = ib - .data_size - .filter(|n| *n > 0) - .ok_or_else(not_implemented)?; - let own = ib.layout.ok_or_else(not_implemented)?; - let view_layout = layout(cx, own)?; - let master_ref = ib.master.unwrap_or(own); - let master = layout(cx, master_ref)?; - // An explicit layout holds no color attachment (MSL §4.7); a member that names one is the - // implicit imageblock's, which the side image is not. - let color = |s: &StructInfo| s.members.iter().any(|m| m.render_target.is_some()); - if color(view_layout) || color(master) { - return Err(not_implemented()); - } - let fields = match cx.entry.module.types().get(ty) { - Some(Type::Struct { - fields, - packed: false, - .. - }) => fields.clone(), - _ => return Err(not_implemented()), - }; - let offsets = cx - .memory - .layouts - .field_offsets(ty) - .ok_or_else(not_implemented)? - .to_vec(); - if view_layout.members.len() != fields.len() { - return Err(not_implemented()); - } - let mut members = Vec::with_capacity(fields.len()); - for m in &view_layout.members { - if m.array_len != 0 || m.layout.is_some() { - return Err(not_implemented()); - } - // The view member is the struct field at its offset in the view. - let field = offsets - .iter() - .position(|o| *o == u64::from(m.offset)) - .ok_or_else(not_implemented)?; - if members - .iter() - .any(|x: &ViewMember| x.field as usize == field) - { - return Err(not_implemented()); - } - let field_ty = *fields.get(field).ok_or_else(not_implemented)?; - let at = master_member(master, m)?; - let leaf = leaf::leaf_of( - cx.entry, - cx.profile, - &cx.memory.layouts, - field_ty, - offset_align(at.offset), - offset_align(at.offset), - )?; - // A value wider than its slot is a packed pixel-format member, which Metal converts. - if leaf.bytes > at.size - || at - .offset - .checked_add(leaf.bytes) - .is_none_or(|e| e > data_size) - { - return Err(not_implemented()); - } - members.push(ViewMember { - field: field as u32, - leaf, - offset: at.offset, - }); - } - let alignment = match align { - Some(stated) => stated, - None => cx - .memory - .layouts - .abi_align(ty) - .and_then(|a| u32::try_from(a).ok()) - .ok_or_else(not_implemented)?, - }; - if !alignment.is_power_of_two() { - return Err(not_implemented()); - } - let lowered = crate::lower::arith::lowered_type(cx.entry, cx.profile, ty)?; - let (master, _) = fingerprint(&cx.entry.structs, master_ref, data_size) - .ok_or_else(|| cx.invariant("an imageblock master whose layouts do not resolve"))?; - let cell = Reached { - data_size, - alignment, - master, - }; - Ok(( - View { - members, - ty: lowered, - }, - cell, - )) -} - -/// Plan the imageblock storage the function reaches with a view of `cell`. Views of structurally -/// different masters each reach their own master's offsets of the one cell, which spans the -/// largest of them (measured on the M3 Max and an M4). -fn reach(cx: &mut SelectCx<'_>, cell: Reached) -> Result<(), Error> { - if cx.stage != Stage::Fragment { - return Err(cx.invariant("a fragment imageblock outside a fragment function")); - } - let known = cx.families.fragment.imageblock.is_some(); - let coord = stage_io::frag_coord(cx); - // Metal keeps a multisampled pass's imageblock per sample, and runs a function that reaches - // it once per covered sample, each run its own sample's cell (measured on the M3 Max). - let sample = if cx.inputs.multisampled { - if !cx.profile.fields().fragment.sample_rate_shading { - return Err(Unsupported::needs( - Feature::Imageblocks, - Capability::Feature(VkFeature::SampleRateShading), - ) - .into()); - } - Some(stage_io::sample_id(cx)) - } else { - None - }; - let ib = cx - .families - .fragment - .imageblock - .get_or_insert_with(ImageblockPlan::default); - if ib.master.is_none() || cell.data_size > ib.data_size { - ib.master = Some(cell.master); - } - ib.coord = coord; - ib.sample = sample; - ib.words = ib.words.max(cell.data_size.div_ceil(4)); - ib.data_size = ib.data_size.max(cell.data_size); - ib.alignment = ib.alignment.max(cell.alignment); - if !known { - cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(1); - } - Ok(()) -} - -/// Plan the imageblock input parameter `param` of role `ib` and stated alignment `align`. -pub(super) fn select_input( - cx: &mut SelectCx<'_>, - param: u32, - ib: &ImageblockArg, - align: Option, -) -> Result<(), Error> { - let v = Value::Arg(ArgIdx::new(param)); - let ty = cx - .value_ty(v) - .ok_or_else(|| cx.invariant("an imageblock parameter without a type"))?; - let (view, cell) = view(cx, ty, ib, align)?; - require(cx, false)?; - reach(cx, cell)?; - let plan = cx - .families - .fragment - .imageblock - .as_mut() - .ok_or_else(|| invariant_error("an imageblock without its plan"))?; - if plan.input.is_some() { - return Err(not_implemented()); - } - plan.input = Some((param, view)); - Ok(()) -} - -/// Plan the imageblock output of role `ib` and stated alignment `align` held in field `field` of -/// the returned value, of AIR type `ty` (`stage_io` plans the entry's other outputs). -pub fn select_output( - cx: &mut SelectCx<'_>, - field: u32, - ib: &ImageblockArg, - align: Option, - ty: AirTypeId, -) -> Result<(), Error> { - let (view, cell) = view(cx, ty, ib, align)?; - require(cx, true)?; - reach(cx, cell)?; - let plan = cx - .families - .fragment - .imageblock - .as_mut() - .ok_or_else(|| invariant_error("an imageblock without its plan"))?; - if plan.output.is_some() { - return Err(not_implemented()); - } - plan.output = Some((field, view)); - let early = plan_tests(cx)?; - if let Some(plan) = cx.families.fragment.imageblock.as_mut() { - plan.early_tests = early; - } - Ok(()) -} - -/// The entry declares `[[early_fragment_tests]]`. -fn declared_early(cx: &SelectCx<'_>) -> bool { - matches!( - cx.entry.ep.stage, - crate::air::abi::Stage::Fragment { - early_fragment_tests: true - } - ) -} - -/// Plan how the depth and stencil tests bear on the imageblock write of a function that writes -/// one, before the stage interface is complete; whether the module declares early fragment tests -/// that the function does not. -/// -/// A fragment its depth or stencil test fails drops its imageblock write, as does one alpha to -/// coverage drops (measured on the M3 Max, at one sample and at four). Tested early, a fragment -/// that fails never writes; tested late, the storage already holds its write. So: -/// -/// - a function whose only effects are its outputs and its imageblock write, which neither -/// discards nor returns depth, stencil or a sample mask, leaves the attachments under early -/// tests as Metal's late tests leave them: the module declares them; -/// - any other writes before Vulkan's tests and states `RuntimeFact::TestedStorageWrites`, as the -/// framebuffer fetch's storage form does: a draw whose tests drop no fragment runs it as -/// compiled, one whose tests drop some but write and count nothing the variant that declares -/// early tests (where only a discard kept them away, `early_variant`); the binder refuses a draw -/// whose depth or stencil test acts (`bind::graphics`). -fn plan_tests(cx: &mut SelectCx<'_>) -> Result { - if declared_early(cx) { - return Ok(false); - } - let exported = cx.entry.ep.outputs.iter().any(|o| { - matches!( - o.role, - OutputRole::Depth(_) | OutputRole::Stencil | OutputRole::SampleMask - ) - }); - let body = super::fetch::body_facts(cx); - let only_outputs = !exported && !body.side_effects; - let fp = &cx.families.fragment; - // A framebuffer fetch's storage form that declares early tests holds the function to them, - // which keeps the write Metal's: it declares them only where the function would here. - if fp.fetch_early_tests { - return Ok(false); - } - if only_outputs && !body.discards { - return Ok(true); - } - let stated = cx.facts.iter().find_map(|f| match *f { - RuntimeFact::TestedStorageWrites { early_variant, .. } => Some(early_variant), - _ => None, - }); - if stated.is_none() { - cx.facts.insert(RuntimeFact::TestedStorageWrites { - early_tests: only_outputs && cx.inputs.read_only_tests, - early_variant: only_outputs, - }); - } - Ok(stated.is_none() && only_outputs && cx.inputs.read_only_tests) -} - -fn invariant_error(detail: &str) -> Error { - Error::Internal(crate::error::InternalError::new( - crate::error::InternalKind::Invariant, - detail, - )) -} - -/// Complete the imageblock plan once the function is selected: its fact. -pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { - // A sample mask the function returns that does not cover the invocation's sample drops its - // imageblock write with the fragment (measured on the M3 Max and an M4 at one sample, and on - // the M3 Max at four, where each sample's run writes where the mask has its bit). - let mask = cx - .entry - .ep - .outputs - .iter() - .find(|o| matches!(o.role, OutputRole::SampleMask)) - .map(|o| o.field); - let Some(plan) = cx.families.fragment.imageblock.as_mut() else { - return Ok(()); - }; - let writes = plan.output.is_some(); - plan.mask = mask.filter(|_| writes); - let Some(master) = plan.master else { - return Err(invariant_error("an imageblock plan without its master")); - }; - let fact = RuntimeFact::FragmentImageblock { - words: plan.words, - writes, - master, - data_size: plan.data_size, - alignment: plan.alignment, - }; - cx.facts.insert(fact); - Ok(()) -} - -/// Declare the imageblock storage image when the plan reaches it. -pub(super) fn declare( - mb: &mut ModuleBuilder, - plan: Option<&ImageblockPlan>, -) -> BResult> { - if plan.is_none() { - return Ok(None); - } - let sampled_type = mb.ty(SType::Int { - width: 32, - signed: false, - })?; - let ty = mb.ty(SType::Image(ImageType { - sampled_type, - dim: Dim::D2, - depth: false, - arrayed: true, - multisampled: false, - usage: ImageUsage::Storage, - format: crate::spv::ImageFormat::R32ui, - }))?; - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Synthetic(SyntheticBinding::Imageblock), - index: 0, - }; - mb.resource(slot, StorageClass::UniformConstant, ty) - .map(Some) -} - -/// The cell of one pixel as a word memory: word `w` is texel `(x, y, w)` of the image, and -/// in a function that runs once per sample texel `(x, y, sample * words + w)`, accessed with the -/// function's coherence (`sync::memory_model`). -struct Cell { - image: SValue, - x: SValue, - y: SValue, - /// The first layer of the invocation's sample's cell, in a function that runs per sample. - base: Option, - coherence: Coherence, -} - -impl Cell { - /// The cell of the invocation's pixel. - fn of_pixel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { - let Some(plan) = &cx.plan.families.fragment.imageblock else { - return Err(cx.fail("an imageblock access without its plan")); - }; - let (coord, words) = (plan.coord, plan.words); - let Some(g) = cx.decl.families.fragment.imageblock else { - return Err(cx.fail("the imageblock storage is not declared")); - }; - let p = fb.module().global_value(g)?; - let image = fb.load(p, MemAccess::default())?; - let frag = stage_io::object_global(cx, coord)?; - let frag = fb.module().global_value(frag)?; - let frag = fb.load(frag, MemAccess::default())?; - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - // `FragCoord` is the pixel's center (or a sample's position inside the pixel): its - // integer part is the pixel. - let fx = fb.composite_extract(frag, &[0])?; - let fy = fb.composite_extract(frag, &[1])?; - let x = fb.convert(ConvOp::ConvertFToU, fx, u32_)?; - let y = fb.convert(ConvOp::ConvertFToU, fy, u32_)?; - let base = match sample_of(cx, fb)? { - Some(sample) => { - let words = k32(fb, words)?; - Some(fb.binary(BinOp::IMul, sample, words)?) - } - None => None, - }; - Ok(Cell { - image, - x, - y, - base, - coherence: memory_model::coherence(cx.plan), - }) - } - - fn texel(&self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult { - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec3 = fb.module().ty(SType::Vector { elem: u32_, len: 3 })?; - let layer = match self.base { - Some(base) => fb.binary(BinOp::IAdd, base, word)?, - None => word, - }; - fb.composite_construct(uvec3, &[self.x, self.y, layer]) - } -} - -/// The invocation's sample (`SampleId`) in a function that runs once per sample. -fn sample_of(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult> { - let Some(object) = cx - .plan - .families - .fragment - .imageblock - .as_ref() - .and_then(|p| p.sample) - else { - return Ok(None); - }; - let g = stage_io::object_global(cx, object)?; - let p = fb.module().global_value(g)?; - fb.load(p, MemAccess::default()).map(Some) -} - -impl WordMem for Cell { - fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult { - let at = self.texel(fb, word)?; - let mem = self.coherence.texel(fb)?; - let t = fb.read(self.image, at, &ImageOperands::default(), mem)?; - fb.composite_extract(t, &[0]) - } - - fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> { - let at = self.texel(fb, word)?; - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; - let zero = k32(fb, 0)?; - let t = fb.composite_construct(uvec4, &[value, zero, zero, zero])?; - let mem = self.coherence.texel(fb)?; - fb.write(self.image, at, t, &ImageOperands::default(), mem) - } - - /// Inside the critical section no other invocation touches the pixel's cell, so a plain - /// read-modify-write replaces exactly the bits `mask`. - fn write_bits( - &mut self, - fb: &mut FunctionBuilder<'_>, - word: SValue, - mask: SValue, - bits: SValue, - ) -> BResult<()> { - let old = self.read(fb, word)?; - let keep = match leaf::known(fb, mask)? { - Some(m) => k32(fb, !m)?, - None => fb.unary(UnOp::Not, mask)?, - }; - let kept = fb.binary(BinOp::BitwiseAnd, old, keep)?; - let new = fb.binary(BinOp::BitwiseOr, kept, bits)?; - self.write(fb, word, new) - } -} - -/// Read the input view, in the function's first block, and hold it for every use: Metal's input -/// is the cell's value when the fragment's critical section begins. -pub(super) fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let Some((param, view)) = cx - .plan - .families - .fragment - .imageblock - .as_ref() - .and_then(|p| p.input.clone()) - else { - return Ok(()); - }; - let Some(v) = cx.plan.values.id(Value::Arg(ArgIdx::new(param))) else { - return Err(cx.fail(format!("imageblock parameter {param} is out of range"))); - }; - let mut cell = Cell::of_pixel(cx, fb)?; - let mut parts = vec![None; view.members.len()]; - for m in &view.members { - let off = k32(fb, m.offset)?; - let x = leaf::load(fb, &mut cell, &m.leaf, off)?; - match parts.get_mut(m.field as usize) { - Some(slot) => *slot = Some(x), - None => return Err(cx.fail("an imageblock member past its struct")), - } - } - let parts: Vec = parts - .into_iter() - .collect::>() - .ok_or_else(|| cx.fail("an imageblock field without a member"))?; - let Some(ty) = crate::lower::arith::spirv_type(fb.module(), &view.ty)? else { - return Err(cx.fail("an imageblock view without a lowered type")); - }; - let x = fb.composite_construct(ty, &parts)?; - cx.hold(v, x); - Ok(()) -} - -/// Write the output view of returned value `v` (in the entry's returned shape) at the return, -/// unless a predicated discard set `discarded` or the returned sample mask does not cover the -/// pixel's one sample (bit 0: the fragment is dropped, and its write with it). -pub(super) fn emit_return( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - v: Option, -) -> BResult<()> { - let Some((field, view, mask)) = cx - .plan - .families - .fragment - .imageblock - .as_ref() - .and_then(|p| p.output.clone().map(|(f, v)| (f, v, p.mask))) - else { - return Ok(()); - }; - let Some(v) = v else { - return Err(cx.fail("an imageblock output without a returned value")); - }; - let whole = cx.operand(fb, v)?; - let (x, covered) = match (cx.plan.families.stage_io.returned, mask) { - (Returned::Struct, mask) => { - let x = fb.composite_extract(whole, &[field])?; - let covered = match mask { - Some(m) => { - let m = fb.composite_extract(whole, &[m])?; - // The invocation's own sample's bit; bit 0 at one sample. - let m = match sample_of(cx, fb)? { - Some(sample) => fb.binary(BinOp::ShiftRightLogical, m, sample)?, - None => m, - }; - let one = k32(fb, 1)?; - let zero = k32(fb, 0)?; - let bit = fb.binary(BinOp::BitwiseAnd, m, one)?; - Some(fb.binary(BinOp::INotEqual, bit, zero)?) - } - None => None, - }; - (x, covered) - } - (Returned::Value, None) => (whole, None), - (Returned::Value, Some(_)) => { - return Err(cx.fail("a sample mask beside an imageblock output that is the value")) - } - (Returned::Void, _) => return Err(cx.fail("an imageblock output of a void entry")), - }; - let mut values = Vec::with_capacity(view.members.len()); - for m in &view.members { - values.push(fb.composite_extract(x, &[m.field])?); - } - let cell = Cell::of_pixel(cx, fb)?; - let write = move |fb: &mut FunctionBuilder<'_>, cell: &mut Cell| -> BResult<()> { - for (m, x) in view.members.iter().zip(values) { - let off = k32(fb, m.offset)?; - leaf::store(fb, cell, &m.leaf, off, x)?; - } - Ok(()) - }; - let mut cell = cell; - let kept = if cx.plan.families.fragment.records_discards() { - let Some(g) = cx.decl.families.fragment.discarded else { - return Err(cx.fail("a recorded discard without its predicate")); - }; - let p = fb.module().global_value(g)?; - let discarded = fb.load(p, MemAccess::default())?; - Some(fb.unary(UnOp::LogicalNot, discarded)?) - } else { - None - }; - let kept = match (kept, covered) { - (None, None) => return write(fb, &mut cell), - (Some(k), None) | (None, Some(k)) => k, - (Some(k), Some(c)) => fb.binary(BinOp::LogicalAnd, k, c)?, - }; - let arm: ArmFn<'_, Cell> = Box::new(move |fb, cell| { - write(fb, cell)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut cell, kept, arm, None)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::air::abi::{MemberKind, UserKey}; - use crate::air::error::DiagName; - - fn member(offset: u32, key: &str, layout: Option) -> Member { - Member { - offset, - size: 4, - array_len: 0, - layout: layout.map(StructRef), - kind: MemberKind::Plain, - render_target: None, - raster_order_group: Some(0), - type_name: DiagName::new("t"), - name: DiagName::new(key), - key: UserKey(key.as_bytes().into()), - } - } - - /// Layouts `0..=depth` where each of layout `l`'s `width` members nests layout `l + 1` (the - /// last is plain), numbered from `base`: a DAG whose in-place expansion has `width^depth` - /// leaves. - fn dag(base: u32, depth: u32, width: u32, deep_key: &str) -> Vec { - (0..=depth) - .map(|l| StructInfo { - members: (0..width) - .map(|i| { - let nested = (l < depth).then_some(base + l + 1); - let key = if l == depth && i == 0 { deep_key } else { "m" }; - member(i * 4, key, nested) - }) - .collect(), - }) - .collect() - } - - /// The fingerprint hashes each distinct layout once: a 32-wide DAG 20 levels deep (32^20 - /// leaves in place) is 21 layouts. Structurally equal masters at other references hash - /// equal; a different key 20 levels down, or a different data size, does not. - #[test] - fn the_fingerprint_hashes_each_shared_layout_once() { - let a = dag(0, 20, 32, "deep"); - let (fa, hashed) = fingerprint(&a, StructRef(0), 16).expect("fingerprint"); - assert_eq!(hashed, 21); - // The same structure behind a layout it does not reach, at other references. - let mut b = vec![StructInfo { - members: vec![member(0, "unreached", None)], - }]; - b.extend(dag(1, 20, 32, "deep")); - let (fb, _) = fingerprint(&b, StructRef(1), 16).expect("fingerprint"); - assert_eq!(fa, fb); - let c = dag(0, 20, 32, "other"); - assert_ne!( - fingerprint(&c, StructRef(0), 16).expect("fingerprint").0, - fa - ); - assert_ne!( - fingerprint(&a, StructRef(0), 32).expect("fingerprint").0, - fa - ); - // A reference out of range, and a layout nesting itself, have none. - assert!(fingerprint(&a, StructRef(99), 16).is_none()); - let cycle = vec![StructInfo { - members: vec![member(0, "self", Some(0))], - }]; - assert!(fingerprint(&cycle, StructRef(0), 16).is_none()); - } -} diff --git a/crates/metal2vulkan/src/lower/fragment/input_blend.rs b/crates/metal2vulkan/src/lower/fragment/input_blend.rs index bb40b7be5..22ac4b6c3 100644 --- a/crates/metal2vulkan/src/lower/fragment/input_blend.rs +++ b/crates/metal2vulkan/src/lower/fragment/input_blend.rs @@ -3,21 +3,21 @@ //! 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 in the pixel interlock the storage form computes the blend in the -//! shader (`fetch`); on one that fetches through input attachments with rasterization-order access -//! (lavapipe) the function computes it over the attachment's input attachment instead: its first +//! 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 and blend color as the storage form reads them, `fetch::blend_second`, -//! `fetch::blend_constant`), +//! 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, as a draw of the storage form does (the -//! announcement, `extended-range-blends-stored-codes`, stays the runtime's there). +//! 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 @@ -31,16 +31,15 @@ //! 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`, as the storage form -//! computes it), and writes the result through the output variable, which the stage interface +//! (`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, as -//! the storage form does (another output is refused, `Feature::ExtendedRangeBlend` `Output`); its +//! 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 @@ -122,8 +121,8 @@ impl RotatedInputBlend { } /// Whether the device orders framebuffer fetch through rasterization-order input attachments, -/// where this module computes an extended-range blend (on one that orders it through the pixel -/// interlock, the storage form does, `fetch::interlock_orders`). +/// 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) } @@ -384,7 +383,7 @@ fn rotated( 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), as the storage form's is. + // 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); diff --git a/crates/metal2vulkan/src/lower/fragment/logic.rs b/crates/metal2vulkan/src/lower/fragment/logic.rs index 7c0f9ecf2..b2fd61b8e 100644 --- a/crates/metal2vulkan/src/lower/fragment/logic.rs +++ b/crates/metal2vulkan/src/lower/fragment/logic.rs @@ -4,9 +4,9 @@ //! 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, the function's first output's write to such an attachment reads the pixel's -//! texel, in the interlocked storage form (`fetch`) or through the attachment's input attachment -//! under rasterization-order access, and stores the operation's result itself ([`operated`]): +//! 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`]): //! //! - 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 @@ -44,14 +44,12 @@ //! 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, under alpha to coverage in the storage -//! form, and, through an input attachment, one held with its channels rotated or with Metal's alpha -//! in red. +//! 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 storage form takes the kept channels back from -//! the texel it read (`fetch`), and over an input attachment the device's write mask keeps them. -//! Each read is ordered after every earlier fragment's write of the pixel (the pixel interlock, or -//! rasterization-order attachment access), so overlapping fragments operate in primitive order, as +//! 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. @@ -454,8 +452,7 @@ pub struct LogicInput { /// 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. (On a device that orders fetch through -/// the pixel interlock, the storage form computes it, `fetch`.) +/// 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(()); diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index 48f04d6d4..cf14e87e8 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -5,30 +5,23 @@ //! reachability, and the profile). A predicated site sets the `Private bool discarded` this //! 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; on a device that orders the read only through the pixel -//! interlock, a storage image of the attachment read and written inside the interlock where the -//! pipeline's state lets that be exact (`fetch`). Compiled for a multisampled pipeline, either -//! form reads (and writes) 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 +//! (`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`). //! - **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` //! kills after the critical section. -//! - **Imageblocks** (`imageblock`): an `[[imageblock_data]]` input is read from the pass's -//! imageblock storage image at the pixel in the function's first block ([`emit_entry`]), an -//! output written at the return ([`emit_return`]), both inside the interlock critical section, -//! which a function that reaches the imageblock always has. +//! - **Imageblocks**: an `[[imageblock_data]]` input or output is not implemented +//! (`Unsupported{Imageblocks, NotImplemented}`). //! - **Sample count** (`get_num_samples`): Metal's header spells `get_num_samples()` as the call //! with operand 0, the pipeline's rasterization sample count. It reads the `SpecKey::SampleCount` //! specialization constant (`RuntimeFact::SampleCount`, default 1), which the binder sets to the //! pipeline's `rasterizationSamples`. A call with another operand is refused: no other operand's //! meaning is established. -//! - **Shader-side stencil** (`stencil`): on a device without stencil export, a `[[stencil]]` -//! output is tested and written by the function itself against a shadow of the stencil, inside -//! the interlock critical section, at each return; a failing fragment is recorded as discarded -//! and killed after the critical section. +//! - **Stencil output**: a `[[stencil]]` output needs `VK_EXT_shader_stencil_export` +//! (`stage_io`), refused naming it on a device without the extension. //! - **Coverage at sample rate** (`coverage`): a function that reads `[[sample_mask]]` and that //! Metal runs once per covered sample runs, compiled for a multisampled pipeline, once per pixel, //! and its body once per covered sample from a loop over the pixel's coverage ([`wrap_entry`]), @@ -38,11 +31,6 @@ //! a `Private u32` before it calls the body, and the body reads that copy //! (`stage_io::coverage_in`). SPIRV-Cross (MoltenVK) declares the input a scalar in the entry //! but passes it to a function as an array, which Metal refuses. -//! - **Snapshot reads** (`snapshot`): a function compiled to read textures through snapshots -//! (`LoweringInputs::snapshot_textures`) opens with an ordered pixel interlock's critical section -//! in which, in the draw that takes the snapshot, each non-helper fragment copies its pixel's -//! texel, and that draw returns after it; in the draw that reads it, each read of the slot reads -//! the snapshot, and a helper reads 0. The body runs outside the critical section. //! - **Pull-model interpolation** (`interpolate`): each `interpolate_at_*` call of an //! `interpolant` reads the interpolant's variable where it says (`stage_io::interpolate`); the //! interpolant itself is planned by `lower::stage_io`. @@ -53,13 +41,10 @@ mod color; mod coverage; mod discard; pub(crate) mod fetch; -mod imageblock; mod input_blend; mod interpolate; mod logic; mod rog; -mod snapshot; -mod stencil; mod word_input; pub(crate) use color::texture_decl; @@ -95,14 +80,8 @@ 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, interlock_forms, - interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples, + compiled_write_mask, extended_range_blend, half_float_format, inputs_order, kept_channels, }; -pub use fetch::{ - select_output as select_storage_output, select_second_output as select_storage_second_output, - StorageColor, -}; -pub use imageblock::{select_output as select_imageblock_output, ImageblockPlan}; 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, @@ -112,11 +91,6 @@ pub(crate) use logic::{ channels as logic_channels, input_operated as logic_input_operated, vulkan_differs as logic_vulkan_differs, }; -#[cfg(test)] -pub(crate) use snapshot::{decode as snapshot_decode, encode as snapshot_encode}; -pub(crate) use snapshot::{prepare as snapshot_prepare, read as snapshot_read}; -pub(crate) use stencil::{face_word, SHADOW_FORMAT}; -pub use stencil::{select_output as select_stencil_output, ShadowStencil}; pub(crate) use word_input::merge as word_input_merge; fn not_lowered() -> Error { @@ -191,11 +165,6 @@ pub struct FragmentPlan { /// 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 function's views of the render pass's imageblock. - pub imageblock: Option, - /// The color attachments the function reads in the interlocked storage form, by index - /// (`fetch`). - pub fetch: BTreeMap, /// 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, @@ -210,33 +179,19 @@ pub struct FragmentPlan { /// 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 of the storage form and - /// of the shader-side stencil. + /// The stage interface's `FragCoord` object, which gives the pixel a color read through a + /// pushed texture fetches (`texture_fetches`). pub fetch_coord: Option, - /// The module declares early fragment tests for the storage form, which the function itself - /// does not. - pub fetch_early_tests: bool, /// The stage interface's `SampleId` object, at which a function compiled for a multisampled - /// pipeline (`LoweringInputs::multisampled`) reads each color it fetches, in either form, and - /// writes each storage-form color: Metal runs such a function once per covered sample and - /// reads its own sample. + /// pipeline (`LoweringInputs::multisampled`) reads each color it fetches: Metal runs such a + /// function once per covered sample and reads its own sample. pub fetch_sample: Option, - /// The field of the returned value holding the function's `[[sample_mask]]` output, which - /// gates each storage-form write of a per-sample function on the invocation's own sample bit, - /// and of a function at one sample on bit 0. - pub fetch_mask: Option, - /// The function's `[[stencil]]` output is a shader-side stencil (`stencil`). - pub stencil: Option, /// The function reads `[[sample_mask]]` and runs once per covered sample on Metal: its loop /// over the covered samples, or why it has none (`coverage`). pub coverage: Option, /// The function returns a `[[depth(...)]]` output (`StageIoPlan::depth_clamp`). Inside an /// interlocked body each return records a positive NaN depth as discarded. pub depth_output: bool, - /// The texture slots the function reads through a snapshot (`snapshot`, - /// `LoweringInputs::snapshot_textures`), by Metal index, each with its snapshot's form. - /// Filled by [`finish`]. - pub snapshot: BTreeMap, } impl FragmentPlan { @@ -255,19 +210,17 @@ impl FragmentPlan { /// sites, or for a helper query where no site demotes. fn reads_helper_input(&self) -> bool { (self.predicated() && !self.quad_exits.is_empty()) - || ((self.helper_queries || !self.snapshot.is_empty()) && !self.demotes()) + || (self.helper_queries && !self.demotes()) } - /// The function declares `discarded`: a predicated site, inside an interlocked body a + /// The function declares `discarded`: a predicated site, or inside an interlocked body a /// terminate-form site (which records the discard and returns to the entry) or a depth output - /// (whose returns record a positive NaN), or a shader-side stencil, which records a failing - /// fragment. + /// (whose returns record a positive NaN). pub fn records_discards(&self) -> bool { self.predicated() || (self.interlock.is_some() && (self.depth_output || self.discards.values().any(|f| *f == DiscardForm::Terminate))) - || self.stencil.is_some() } fn kill_form(&self) -> KillForm { @@ -312,20 +265,11 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { cx.precision.insert(PrecisionNote::QuadsSplitByClipping); } let looped = coverage::finish(cx)?; - imageblock::finish(cx)?; - fetch::finish(cx)?; - stencil::finish(cx)?; - // An imageblock, an attachment in the storage form and the shadow of a shader-side stencil - // are read and written inside the critical section whether or not the function names a raster - // order group. - let shadow = cx.families.fragment.stencil.is_some(); - let storage = !cx.families.fragment.fetch.is_empty() || shadow; - let interlock = if rog::declared(cx) || cx.families.fragment.imageblock.is_some() || storage { + let interlock = if rog::declared(cx) { Some(rog::mode(cx)?) } else { None }; - let snapshot = snapshot::finish(cx, interlock.is_some(), looped)?; let sites: Vec = cx.families.fragment.discards.keys().copied().collect(); let discard::DiscardPlan { forms, @@ -353,7 +297,6 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { fp.guarded = guarded; fp.terminate_invocation = terminate; fp.interlock = interlock; - fp.snapshot = snapshot; Ok(()) } @@ -366,20 +309,13 @@ pub struct Declared { /// The `HelperInvocation` input the whole-quad exits and helper queries where no discard /// demotes read. pub helper: Option, - /// The input attachment of each color index read, or its storage image in the interlocked - /// storage form. + /// The input attachment of each color index read. pub attachments: BTreeMap, - /// The render pass's imageblock storage image. - pub imageblock: Option, - /// The shadow of a shader-side stencil. - pub shadow_stencil: Option, /// The `Private u32` holding the sample of the loop's pass over the covered samples. pub loop_sample: Option, /// The `Private u32` copy of the `SampleMask` input's word, which the entry stores before it /// calls the body it wraps, and the body reads for every read of the input. pub coverage_copy: Option, - /// The snapshots the function reads textures through, and the helper's copy. - pub snapshot: snapshot::Declared, } /// Declare the fragment family's module-scope objects and modes: the discard predicate, the @@ -391,14 +327,9 @@ pub fn declare( ) -> BResult { let fp = &plan.families.fragment; let mut d = Declared::default(); - if let Some(m) = fp.interlock.or(snapshot::mode(&fp.snapshot)) { + if let Some(m) = fp.interlock { modes.push(m); } - // The storage form's writes, and the imageblock's, are Metal's under early tests. - let imageblock_early = fp.imageblock.as_ref().is_some_and(|p| p.early_tests); - if fp.fetch_early_tests || imageblock_early { - modes.push(ExecMode::EarlyFragmentTests); - } if fp.records_discards() { let bool_ = mb.ty(SType::Bool)?; let no = mb.constant(Constant::Scalar { @@ -414,15 +345,12 @@ pub fn declare( d.attachments = color::declare( mb, &fp.colors, - (&fp.fetch, &fp.input_blends, &fp.word_merges), + (&fp.input_blends, &fp.word_merges), (&fp.rotated_blends, &fp.logic_inputs), fp.fetch_sample.is_some(), &fp.texture_fetches, )?; - d.imageblock = imageblock::declare(mb, fp.imageblock.as_ref())?; - d.shadow_stencil = stencil::declare(mb, fp.stencil.as_ref())?; d.loop_sample = coverage::declare(mb, plan)?; - d.snapshot = snapshot::declare(mb, &fp.snapshot)?; if wraps_body(fp) && sample_mask_input(plan).is_some() { let u32_ = mb.ty(SType::Int { width: 32, @@ -500,11 +428,11 @@ pub(super) fn load_coverage( Ok(Some(covered)) } -/// Plan a used parameter this family owns (`select::param_family`): a color input, or an -/// imageblock input. +/// Plan a used parameter this family owns (`select::param_family`): a color input. An imageblock +/// input is not implemented. pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { - if let ParamRole::Imageblock(ib) = &b.role { - return imageblock::select_input(cx, b.param, ib, b.ty.align); + if let ParamRole::Imageblock(_) = &b.role { + return Err(Unsupported::not_implemented(Feature::Imageblocks).into()); } let c = color::select_param(cx, b).map_err(|e| match b.role { ParamRole::ColorInput { @@ -517,11 +445,10 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error Ok(()) } -/// Plan the entry's framebuffer-fetch forms before its stage interface: an output to an attachment -/// in the storage form is no interface variable. 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 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. pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { - fetch::plan(cx)?; input_blend::plan(cx)?; word_input::plan(cx)?; logic::plan(cx)?; @@ -534,55 +461,8 @@ pub fn loops_samples(cx: &SelectCx<'_>) -> bool { cx.families.fragment.coverage.is_some_and(|c| c.looped) } -/// Whether the function reads color attachment `color` in the interlocked storage form, so an -/// output to it is written there, not to an interface variable. -pub fn writes_through_storage(cx: &SelectCx<'_>, color: u32) -> bool { - fetch::is_storage(cx, color) -} - -/// Whether the function writes color attachment `color` in the storage form under Metal's -/// 16-bit float, 8-bit unorm or 8-bit sRGB blend, which the shader computes, and that blend is -/// Metal's exactly: the attachment stores Metal's value. -pub fn blends_half_in_storage(cx: &SelectCx<'_>, color: u32) -> bool { - fetch::blends_in_shader(cx, color, true) -} - -/// Whether the function writes color attachment `color` in the storage form under a write mask -/// that names none of its format's channels: the write stores nothing. -pub fn stores_nothing_in_storage(cx: &SelectCx<'_>, color: u32) -> bool { - (cx.families.fragment.fetch.get(&color)).is_some_and(|sc| sc.writes && sc.view.stores_nothing()) -} - -/// Whether the function writes (or reads) color attachment `color` in the storage form, which the -/// pipeline's color attachments do not hold. -pub fn written_in_storage(cx: &SelectCx<'_>, color: u32) -> bool { - cx.families.fragment.fetch.contains_key(&color) -} - -/// Whether the function writes color attachment `color` in the storage form under Metal's -/// 16-bit float blend, which the shader computes, exactly or not: the write stores a `half` in -/// every channel, whose conversion by the device is exact. -pub fn blends_sixteen_in_storage(cx: &SelectCx<'_>, color: u32) -> bool { - fetch::blends_half(cx, color) -} - -/// Whether the function writes color attachment `color` in the storage form under a blend the -/// shader computes of a format held directly (Metal's 16-bit float, 8-bit unorm or 8-bit sRGB -/// blend), exactly or not: the write stores the value the blend gives, which no conversion of the -/// device's changes (an 8-bit unorm channel's code is rounded by Metal's rule in the shader, an -/// sRGB one's encoded by Metal's table). -pub fn blends_in_storage(cx: &SelectCx<'_>, color: u32) -> bool { - fetch::blends_in_shader(cx, color, false) -} - -/// Whether the function's second (index-1) output to `color` is the second source of the -/// extended-range blend the shader computes in the storage form, outside the stage interface. -pub fn blends_second_through_storage(cx: &SelectCx<'_>, color: u32) -> bool { - fetch::blends_second(cx, color) -} - -/// The extended-range write of attachment `color` the shader computes, in the storage form -/// (`fetch`) or over the input attachment (`input_blend`): the pipeline's blend there (`None` +/// 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). @@ -595,12 +475,6 @@ pub(crate) fn shader_blend( bool, )> { let fp = &cx.families.fragment; - if let Some(sc) = fp.fetch.get(&color) { - return sc - .view - .extended - .map(|form| (sc.view.blend, form, sc.view.stores_nothing())); - } fp.input_blends.get(&color).map(|ib| { let blends = ib.blend.is_some(); ( @@ -618,35 +492,10 @@ pub fn blends_second_through_inputs(cx: &SelectCx<'_>, color: u32) -> bool { input_blend::blends_second(cx, color) } -/// Whether the function writes an output the returned value holds outside the stage interface: -/// an imageblock output, an output to an attachment in the storage form, or a shader-side stencil. -pub fn writes_outside_interface(cx: &SelectCx<'_>) -> bool { - let fp = &cx.families.fragment; - fp.imageblock.as_ref().is_some_and(|p| p.output.is_some()) - || fp.fetch.values().any(|sc| sc.writes) - || fp.stencil.is_some() -} - -/// The work before the body, in the function's first block: read the imageblock input, place the -/// fragment's tile in the pass's tile memory, copy the textures read through snapshots -/// (`snapshot`), and read the texel of each storage-form color the function reads -/// (`EmitCx::fetched`), which every use of the color then takes. +/// 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<()> { - imageblock::emit_entry(cx, fb)?; - crate::lower::access::tile_memory::emit_entry(cx, fb)?; - snapshot::emit_entry(cx, fb)?; - let fp = &cx.plan.families.fragment; - let read: BTreeSet = fp - .colors - .iter() - .map(|c| c.color) - .filter(|color| fp.fetch.contains_key(color)) - .collect(); - for color in read { - let texel = fetch::texel(cx, fb, color)?; - cx.fetched.push((color, texel)); - } - Ok(()) + crate::lower::access::tile_memory::emit_entry(cx, fb) } /// The value of parameter `b` in its lowered representation, read by an instruction or a @@ -777,18 +626,9 @@ pub fn not_discarded(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResu } /// Emit the entry's return terminator after `stage_io::emit_return` stored the outputs: a -/// shader-side stencil tests and writes its shadow, recording a failing fragment as discarded; the -/// outputs of returned value `v` to attachments in the storage form and its imageblock output are written, then a predicated discard kills a discarded -/// invocation, which drops its outputs. An interlocked body only returns; its caller kills after -/// the critical section. -pub fn emit_return( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - v: Option, -) -> BResult<()> { - stencil::emit_return(cx, fb, v)?; - fetch::emit_return(cx, fb, v)?; - imageblock::emit_return(cx, fb, v)?; +/// predicated discard kills a discarded invocation, which drops its outputs. An interlocked body +/// only returns; its caller kills after the critical section. +pub fn emit_return(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { let fp = &cx.plan.families.fragment; if fp.interlock.is_none() && fp.predicated() { let Some(g) = cx.decl.families.fragment.discarded else { diff --git a/crates/metal2vulkan/src/lower/fragment/rog.rs b/crates/metal2vulkan/src/lower/fragment/rog.rs index bd558c670..13524d1c6 100644 --- a/crates/metal2vulkan/src/lower/fragment/rog.rs +++ b/crates/metal2vulkan/src/lower/fragment/rog.rs @@ -27,12 +27,10 @@ //! 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 form**. On a device with neither rasterization-order -//! color attachment access nor the pixel interlock's storage form (`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, on every device without -//! rasterization-order access: there the interlock chooses no fetch form, -//! `fetch::interlock_forms`). A group on such an input, or on a color output of an attachment the +//! **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 //! 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 diff --git a/crates/metal2vulkan/src/lower/fragment/snapshot.rs b/crates/metal2vulkan/src/lower/fragment/snapshot.rs deleted file mode 100644 index 0ace9137a..000000000 --- a/crates/metal2vulkan/src/lower/fragment/snapshot.rs +++ /dev/null @@ -1,674 +0,0 @@ -//! Reads of a texture through a snapshot (`LoweringInputs::snapshot_textures`). -//! -//! A draw that reads a texture `T` its own subpass renders, at the fragment's own pixel alone -//! (`StageInterface::snapshot_textures`), runs twice with one pipeline (`PushField::SnapshotPhase`, -//! the binder's `bind::graphics`). The first draw, every color write mask 0 and the phase 1, copies -//! each non-helper fragment's texel of `T` into the slot's snapshot `S` (`ResourceKind:: -//! SnapshotTexels`) and returns; the second, the pipeline's own masks and the phase 0, copies -//! nothing and runs the function, whose every read of `T` reads `S`, or nothing in a helper -//! invocation. The entry opens, before the body: -//! -//! ```text -//! helper ← this invocation is a helper -//! OpBeginInvocationInterlockEXT -//! if phase ≠ 0 && !helper { for each slot: S[p] ← bits(fetch T[p], level 0) } p = uint(FragCoord.xy) -//! OpEndInvocationInterlockEXT -//! if phase ≠ 0 { return } -//! ``` -//! -//! **Why one draw is not enough.** The function's read of `T[p]` must happen before the same -//! draw's color write of `T[p]`. Vulkan states only an execution order there: "Most operations in -//! the fragment shader are not performed in rasterization order, with exceptions called out in the -//! following sections" (Fragment Shading), and blending and color writes execute in rasterization -//! order (Rasterization Order). Its memory model relates a shader instruction to another only -//! through program order, the interlock's synchronizes-with ("If A is an -//! OpEndInvocationInterlockEXT instruction and B is an OpBeginInvocationInterlockEXT instruction, -//! then A synchronizes-with B if the agent that executes A is ordered before the agent that executes -//! B"), and execution dependencies ("If there is an execution dependency between two operations A -//! and B, then the operation in the first synchronization scope system-synchronizes-with the -//! operation in the second synchronization scope"), none of which reaches the fixed-function color -//! write. So no single-draw form, interlocked or not, orders the read before the write; a form that -//! "simplifies" this back into one draw relies on behaviour the specification does not state. -//! -//! **Why two draws are exact.** Each link rests on a sentence of the specification: -//! -//! - *The copy reads `T` as the draws before left it.* The consumer records a by-region barrier -//! from the color attachment writes to fragment-shader reads before the first draw, with `T`'s -//! attachment in the feedback-loop layout: "A vkCmdPipelineBarrier inside a subpass can -//! synchronize prior attachment writes in the subpass with subsequent non-attachment reads if -//! feedback loop is enabled for the attachment", "In that case the overlap is defined to occur at -//! a per-pixel granularity", and each region "covers a single (x,y,layer) position". The copy -//! reads `T` at its own pixel alone. -//! - *Nothing writes `T` during the first draw.* Every color write mask is 0: "VK_COLOR_COMPONENT_R_BIT -//! specifies that the R value is written to the color attachment for the appropriate sample. -//! Otherwise, the value in memory is unmodified" (Color Write Mask), and likewise for G, B and A. -//! The function writes no memory (the interface fact), and the first draw runs nothing of it past -//! the copy, so the outputs it leaves unwritten reach nothing. -//! - *The two draws shade the same fragments.* They differ only in the write masks, dynamic state of -//! one pipeline: "Rule 2 Changes to the following state values have no side effects ... Write -//! masks (color, depth, stencil)", and "Corollary 1 Fragment generation is invariant with respect -//! to the state values listed in Rule 2" (Invariance). A second pipeline would be another state -//! vector, which those rules do not cover; the side-effect relaxation lifts only "rule 1, -//! corollary 2, and rule 4". Each fragment of the first draw runs the copy: "Otherwise, at least -//! one fragment shader must be executed" (Fragment Shading), which covers each pixel the second -//! draw's fragments read; no fragment operation before shading discards one (no depth or stencil -//! attachment, and the same scissor). -//! - *Fragments that cover one pixel in the first draw write `S[p]` in order.* The entry declares -//! `PixelInterlockOrderedEXT`: "any interlocked operations in a fragment shader must happen before -//! interlocked operations in fragment shader invocations that execute later in rasterization order -//! and cover at least one sample in the same pixel", the End/Begin synchronizes-with above, and -//! `S` is decorated `Coherent`, whose per-instruction availability and visibility the interlock -//! needs ("shaders using fragment shader interlock will declare the relevant resources as -//! coherent", Memory Model). Every such write stores the same bits, since `T` does not change. -//! - *The second draw reads `S` after the first wrote it.* The consumer records a by-region barrier -//! from the first draw's fragment-shader writes to the second draw's fragment-shader reads, which -//! also orders the copy's read of `T` before the second draw's color writes. -//! - *No other access races.* "Data races can only occur due to instructions that are actually -//! executed" (Memory Model): the second draw executes no copy, and the first no read of `S`. A -//! helper invocation copies nothing and reads nothing; its codes of the slot are 0, which reaches -//! no fragment's result, since no value read from the slot reaches a derivative, a quad or -//! subgroup operation or a branch (but a selection whose arms leave through its merge alone and -//! hold none of those, no loop and no undefined operand, which a helper may take either arm of), -//! nor an integer divisor or a dynamic component index, whose behavior SPIR-V leaves undefined -//! at some values (`spirv::requirements::snapshot_textures`): -//! "Stores and atomics performed by helper invocations must not have any effect on memory except -//! for the Function, Private and Output storage classes" (Helper Invocations). -//! -//! **The snapshot's form** (`SnapshotForm`, the binder's choice by the slot's bound view): the -//! copy stores the texel's codes, which it takes from the fetched value, and a read decodes them. -//! -//! - `Bits`: the fetched `vec4`'s 32 bits a lane in an `R32G32B32A32_UINT` image, which come back -//! bit for bit, whatever the texel. -//! - A normalized form: each lane's code `c = RoundEven(clamp(v) * D)` (`D = 2^b - 1`, a signed -//! form's `2^(b-1) - 1` and its clamp `[-1, 1]`), in an `R8G8B8A8_UINT` or `R16G16B16A16_UINT` -//! image, two's complement where signed. The fetched value of a normalized code `c` is "f = -//! c / (2^b - 1)" (a signed one's "f = max(c / (2^(b-1) - 1), -1.0)", Fixed-Point Data -//! Conversions), so `v * D` lies within far less than half of one of `c`, and "OpFMul ... -//! Correctly rounded" with `RoundEven` exact (Precision and Operation of SPIR-V Instructions) -//! give `c` back; a signed form's `-2^(b-1)`, whose value is `-1` as the code above it's is, comes -//! back as that code. A read decodes `c` by the device's arithmetic, `c` times the `f32` nearest -//! `1 / D` (a signed code's at least `-1`), within an `f32` rounding or two of `c / D` -//! (`PrecisionNote::DevicePackConversion`; Metal reads `c / D` correctly rounded). -//! - `Half`: each lane's half-float code (`narrow::to_bits`: the device's narrowing, every half -//! value's bits but a NaN's and, where the device may flush a 16-bit denormal, a denormal's, -//! each recorded, `narrow::encodes_bits`; a code loaded unchanged keeps its bits), in an -//! `R16G16B16A16_UINT` image; a read widens it back as a `half` read -//! from memory widens (`narrow::from_bits`): the device's widening on every device, every code's -//! value but a NaN's bits and, where the device may flush a 16-bit denormal, a denormal, each -//! recorded (`narrow::widens_bits`). -//! - An integer form: each lane's code (the fetched integer lane, a code of the format), its low 8 -//! or 16 bits in an `R8G8B8A8_UINT` or `R16G16B16A16_UINT` image; a read extends it, with its -//! sign where signed. -//! -//! A narrower format's channels the texel lacks are the fetch's constants (0, or 1 in alpha), -//! whose codes the form holds too, and a swizzled view's lanes are channels or those constants. -//! -//! **The view the copy fetches through** is the one the read it stands for would have fetched, and -//! the one the binder names the form by: the slot's own image. - -use std::collections::BTreeMap; - -use crate::device::requirements::VkFeature; -use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; -use crate::lower::arith::legal::{FloatFmt, Form, Held}; -use crate::lower::arith::narrow; -use crate::lower::arith::ops::{splat, ty}; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::lower::stage_io; -use crate::lower::sync::barrier::BarrierModel; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SlotClass, SnapshotForm, Stage}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value as SValue}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, GlslOp, ImageOperands, ImageType, - ImageUsage, MemAccess, StorageClass, TexelMemory, Type as SType, UnOp, -}; - -/// The fragment texture slots function `cx` reads through a snapshot, from its lowering inputs: -/// the stage interface's `FragCoord`, the phase's push field and each snapshot's storage image are -/// planned for them. A function with another interlock or a loop over its covered samples has none -/// (the binder asks for neither), and a device without `fragmentShaderPixelInterlock` refuses them. -pub(super) fn finish( - cx: &mut SelectCx<'_>, - interlocked: bool, - looped: bool, -) -> Result, Error> { - let slots: BTreeMap = cx - .inputs - .snapshot_textures - .iter() - .filter(|(s, _)| s.stage == Stage::Fragment && s.class == SlotClass::Texture) - .map(|(s, form)| (s.index, *form)) - .collect(); - if slots.is_empty() || cx.stage != Stage::Fragment { - return Ok(BTreeMap::new()); - } - if interlocked || looped { - return Err(cx.invariant( - "a snapshot read in a function with another critical section or a sample loop", - )); - } - if !super::fetch::interlock_forms(cx.profile) { - return Err(Unsupported::needs( - Feature::RasterOrderGroups, - Capability::Feature(VkFeature::FragmentShaderPixelInterlock), - ) - .into()); - } - // `S` is `Coherent`, a `GLSL450` decoration; a storage image beside the `GLSL450` form of a - // coherent access, or under the Vulkan model, is not implemented (`sync::memory_model`). - let model = &cx.families.memory_model; - if model.model == BarrierModel::Vulkan || model.coherent_resources { - return Err(Unsupported::not_implemented(Feature::Lowering(LowerFamily::Fragment)).into()); - } - cx.families.fragment.fetch_coord = Some(stage_io::frag_coord(cx)); - cx.push.insert(PushField::SnapshotPhase); - // A normalized form's read decodes its codes by the device's arithmetic. - if slots.values().any(|f| normalized(*f)) { - cx.precision.insert(PrecisionNote::DevicePackConversion); - } - let n = u32::try_from(slots.len()).unwrap_or(u32::MAX); - cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(n); - Ok(slots) -} - -/// The interlock mode of a function with snapshot slots `slots`. -pub(super) fn mode(slots: &BTreeMap) -> Option { - (!slots.is_empty()).then_some(ExecMode::PixelInterlockOrdered) -} - -/// The module-scope objects of the snapshot reads. -#[derive(Clone, Debug, Default)] -pub struct Declared { - /// Each slot's snapshot, `Coherent`. - pub images: BTreeMap, - /// The `Private bool` the entry stores whether the invocation is a helper in. - pub helper: Option, -} - -/// Declare each of `slots`' snapshot, an image of its form's format, and the helper's copy. -pub(super) fn declare( - mb: &mut ModuleBuilder, - slots: &BTreeMap, -) -> BResult { - let mut d = Declared::default(); - if slots.is_empty() { - return Ok(d); - } - let sampled_type = mb.ty(SType::Int { - width: 32, - signed: false, - })?; - for (&index, &form) in slots { - let format = match form.code() { - None => crate::spv::ImageFormat::Rgba32ui, - Some((8, _)) => crate::spv::ImageFormat::Rgba8ui, - Some(_) => crate::spv::ImageFormat::Rgba16ui, - }; - let ty = mb.ty(SType::Image(ImageType { - sampled_type, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: false, - usage: ImageUsage::Storage, - format, - }))?; - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::SnapshotTexels(index), - index, - }; - let g = mb.resource(slot, StorageClass::UniformConstant, ty)?; - mb.coherent(g)?; - d.images.insert(index, g); - } - let bool_ = mb.ty(SType::Bool)?; - let no = mb.constant(Constant::Scalar { - ty: bool_, - bits: ConstBits(0), - })?; - d.helper = Some(mb.plain_global(StorageClass::Private, bool_, Some(no))?); - Ok(d) -} - -/// The image variable the copy of slot `index` fetches from, with its image type: the slot's -/// image. -fn source(cx: &EmitCx<'_>, index: u32) -> Option<(GlobalId, TypeId)> { - cx.decl.families.texture.images.get(&index).copied() -} - -/// Whether `form`'s codes hold every lane an image of sampled type `sampled` returns: a float -/// lane's every form but an integer one's, an integer lane's [`SnapshotForm::Bits`] or an integer -/// form of its signedness. The binder names a form of the slot's class (`SnapshotForm::of`), so a -/// pairing this rejects is an invariant failure. -fn holds(fb: &mut FunctionBuilder<'_>, form: SnapshotForm, sampled: TypeId) -> BResult { - let integer = matches!( - form, - SnapshotForm::Uint8 | SnapshotForm::Uint16 | SnapshotForm::Sint8 | SnapshotForm::Sint16 - ); - let signed_form = matches!(form, SnapshotForm::Sint8 | SnapshotForm::Sint16); - Ok(match fb.module().types().get(sampled)? { - SType::Float { width: 32 } => !integer, - SType::Int { width: 32, signed } => { - form == SnapshotForm::Bits || (integer && *signed == signed_form) - } - _ => false, - }) -} - -/// The sampled type of image type `ty`, or `None` where `ty` is no image. -fn sampled_type(fb: &mut FunctionBuilder<'_>, ty: TypeId) -> BResult> { - Ok(match fb.module().types().get(ty)? { - SType::Image(i) => Some(i.sampled_type), - _ => None, - }) -} - -/// One slot's copy ([`emit_entry`]): the image the slot's reads fetch, the slot's snapshot, and -/// the form its codes are in. -#[derive(Clone, Copy, Debug)] -struct SlotCopy { - image: GlobalId, - snapshot: GlobalId, - form: SnapshotForm, -} - -/// The texel of image variable `g` at `pixel`, level 0: the plain fetch the slot's reads make. -fn fetch(fb: &mut FunctionBuilder<'_>, g: GlobalId, pixel: SValue) -> BResult { - let ptr = fb.module().global_value(g)?; - let img = fb.load(ptr, MemAccess::default())?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - let ops = ImageOperands { - lod: Some(zero), - ..ImageOperands::default() - }; - fb.fetch(img, pixel, &ops) -} - -/// The codes of `form` of the texel image variable `g` returns at `pixel` ([`encode`]). -fn fetched_codes( - fb: &mut FunctionBuilder<'_>, - g: GlobalId, - form: SnapshotForm, - pixel: SValue, -) -> BResult { - let texel = fetch(fb, g, pixel)?; - encode(fb, form, texel) -} - -/// Store codes `bits` in snapshot variable `g` at `pixel`. -fn store(fb: &mut FunctionBuilder<'_>, g: GlobalId, pixel: SValue, bits: SValue) -> BResult<()> { - let ptr = fb.module().global_value(g)?; - let snapshot = fb.load(ptr, MemAccess::default())?; - fb.write( - snapshot, - pixel, - bits, - &ImageOperands::default(), - TexelMemory::PRIVATE, - ) -} - -/// The entry's block before the body ([module docs](self)), in the function's first block. -pub(super) fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let fp = &cx.plan.families.fragment; - if fp.snapshot.is_empty() { - return Ok(()); - } - let decl = &cx.decl.families.fragment.snapshot; - let Some(helper_copy) = decl.helper else { - return Err(cx.fail("a snapshot read without its helper's copy")); - }; - let mut copies: Vec = Vec::with_capacity(fp.snapshot.len()); - for (&index, &form) in &fp.snapshot { - let (Some(&s), Some((t, ty))) = (decl.images.get(&index), source(cx, index)) else { - return Err(cx.fail(format!("snapshot slot {index} is not declared"))); - }; - // The form's codes must hold the lanes the copy's fetch returns: the binder names a form - // of the slot's class, so a float code form over an integer source (or the other way) is - // an invariant failure, not a value for `encode` to clamp or bitcast its way through. - let Some(sampled) = sampled_type(fb, ty)? else { - return Err(cx.fail(format!("snapshot slot {index} is copied from no image"))); - }; - if !holds(fb, form, sampled)? { - return Err(cx.fail(format!( - "the copy of snapshot slot {index} fetches lanes its form {form:?} does not hold" - ))); - } - copies.push(SlotCopy { - image: t, - snapshot: s, - form, - }); - } - let Some(coord) = fp.fetch_coord else { - return Err(cx.fail("a snapshot read without its FragCoord")); - }; - let frag = stage_io::object_global(cx, coord)?; - // At entry no discard has run: a helper is the device's. - let helper = if fp.demotes() { - fb.is_helper_invocation()? - } else { - let Some(g) = cx.decl.families.fragment.helper else { - return Err(cx.fail("a snapshot read without the helper input")); - }; - let p = fb.module().global_value(g)?; - fb.load(p, MemAccess::default())? - }; - let p = fb.module().global_value(helper_copy)?; - fb.store(p, helper, MemAccess::default())?; - let phase = cx.push_field(fb, PushField::SnapshotPhase)?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - let taking = fb.binary(BinOp::INotEqual, phase, zero)?; - fb.begin_interlock()?; - let other = fb.unary(UnOp::LogicalNot, helper)?; - let copy = fb.binary(BinOp::LogicalAnd, taking, other)?; - let arm: ArmFn<'_, ()> = Box::new(move |fb, _| { - let pixel = pixel(fb, frag)?; - for &SlotCopy { - image, - snapshot, - form, - } in &copies - { - let bits = fetched_codes(fb, image, form, pixel)?; - store(fb, snapshot, pixel, bits)?; - } - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut (), copy, arm, None)?; - fb.end_interlock()?; - // The draw that takes the snapshot runs nothing else: its write masks are all 0, and the - // function writes no memory. - let done: ArmFn<'_, ()> = Box::new(|fb, _| { - fb.ret(None)?; - Ok(ArmEnd::Exits) - }); - fb.if_(&mut (), taking, done, None)?; - Ok(()) -} - -/// `uvec2(uint(FragCoord.x), uint(FragCoord.y))` from `FragCoord` variable `frag`: a non-helper -/// fragment's coordinates lie in its pixel `[p, p + 1)`, at or above 0. -fn pixel(fb: &mut FunctionBuilder<'_>, frag: GlobalId) -> BResult { - let frag = fb.module().global_value(frag)?; - let frag = fb.load(frag, MemAccess::default())?; - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let uvec2 = fb.module().ty(SType::Vector { elem: u32_, len: 2 })?; - let fx = fb.composite_extract(frag, &[0])?; - let fy = fb.composite_extract(frag, &[1])?; - let x = fb.convert(ConvOp::ConvertFToU, fx, u32_)?; - let y = fb.convert(ConvOp::ConvertFToU, fy, u32_)?; - fb.composite_construct(uvec2, &[x, y]) -} - -/// The `uvec4` of 32-bit lanes `texel`'s codes in `form` ([module docs](self)), for the -/// snapshot's write: each lane's bits for [`SnapshotForm::Bits`], else each lane's code, its low -/// 8 or 16 bits. -pub(crate) fn encode( - fb: &mut FunctionBuilder<'_>, - form: SnapshotForm, - texel: SValue, -) -> BResult { - let u = lanes(Held::Int { - bits: 32, - container: 32, - }); - let uvec4 = ty(fb, u)?; - let Some((width, signed)) = form.code() else { - return match fb.value_ty(texel)? == uvec4 { - true => Ok(texel), - false => fb.convert(ConvOp::Bitcast, texel, uvec4), - }; - }; - let codes = match form { - SnapshotForm::Unorm8 - | SnapshotForm::Unorm16 - | SnapshotForm::Snorm8 - | SnapshotForm::Snorm16 => { - let f = lanes(Held::Float(FloatFmt::F32)); - let low = match signed { - true => (-1.0f32).to_bits(), - false => 0, - }; - let (low, high) = ( - splat(fb, f, u64::from(low))?, - splat(fb, f, u64::from(1.0f32.to_bits()))?, - ); - let clamped = fb.glsl(GlslOp::FClamp, &[texel, low, high])?; - let d = splat(fb, f, u64::from((scale(width, signed) as f32).to_bits()))?; - let scaled = fb.binary(BinOp::FMul, clamped, d)?; - let code = fb.glsl(GlslOp::RoundEven, &[scaled])?; - match signed { - true => { - let ivec4 = signed_lanes(fb)?; - let c = fb.convert(ConvOp::ConvertFToS, code, ivec4)?; - fb.convert(ConvOp::Bitcast, c, uvec4)? - } - false => fb.convert(ConvOp::ConvertFToU, code, uvec4)?, - } - } - SnapshotForm::Half => narrow::to_bits(fb, lanes(Held::Float(FloatFmt::Half)), texel)?, - _ => match fb.value_ty(texel)? == uvec4 { - true => texel, - false => fb.convert(ConvOp::Bitcast, texel, uvec4)?, - }, - }; - mask_codes(fb, form, codes) -} - -/// The `uvec4` of codes `codes` (32-bit lanes) kept to `form`'s code width: the snapshot's image -/// holds that many bits a lane, so a lane of a wider value loses the rest. -fn mask_codes(fb: &mut FunctionBuilder<'_>, form: SnapshotForm, codes: SValue) -> BResult { - let u = lanes(Held::Int { - bits: 32, - container: 32, - }); - let uvec4 = ty(fb, u)?; - let codes = match fb.value_ty(codes)? == uvec4 { - true => codes, - false => fb.convert(ConvOp::Bitcast, codes, uvec4)?, - }; - let Some((width, _)) = form.code() else { - return Ok(codes); - }; - let mask = splat(fb, u, (1u64 << width) - 1)?; - fb.binary(BinOp::BitwiseAnd, codes, mask) -} - -/// The value of type `texel` the codes `codes` (a `uvec4` read from the snapshot) of `form` stand -/// for ([module docs](self)): the inverse of [`encode`] on every value it encodes. -pub(crate) fn decode( - fb: &mut FunctionBuilder<'_>, - form: SnapshotForm, - codes: SValue, - texel: TypeId, -) -> BResult { - let u = lanes(Held::Int { - bits: 32, - container: 32, - }); - let Some((width, signed)) = form.code() else { - return match fb.value_ty(codes)? == texel { - true => Ok(codes), - false => fb.convert(ConvOp::Bitcast, codes, texel), - }; - }; - // A signed code's lanes, sign-extended from their low `width` bits. - let extended = |fb: &mut FunctionBuilder<'_>| -> BResult { - let ivec4 = signed_lanes(fb)?; - let shift = splat(fb, u, u64::from(32 - width))?; - let up = fb.binary(BinOp::ShiftLeftLogical, codes, shift)?; - let up = fb.convert(ConvOp::Bitcast, up, ivec4)?; - fb.binary(BinOp::ShiftRightArithmetic, up, shift) - }; - // A normalized code `c` times the `f32` nearest `1 / D`. - let f = lanes(Held::Float(FloatFmt::F32)); - let reciprocal = |fb: &mut FunctionBuilder<'_>, signed: bool| -> BResult { - let r = 1.0 / scale(width, signed) as f32; - splat(fb, f, u64::from(r.to_bits())) - }; - let value = match form { - SnapshotForm::Unorm8 | SnapshotForm::Unorm16 => { - let vec4 = ty(fb, f)?; - let c = fb.convert(ConvOp::ConvertUToF, codes, vec4)?; - let r = reciprocal(fb, false)?; - fb.binary(BinOp::FMul, c, r)? - } - SnapshotForm::Snorm8 | SnapshotForm::Snorm16 => { - let n = extended(fb)?; - let vec4 = ty(fb, f)?; - let c = fb.convert(ConvOp::ConvertSToF, n, vec4)?; - let r = reciprocal(fb, true)?; - let v = fb.binary(BinOp::FMul, c, r)?; - // `-2^(b-1)` reads `-1`, as the code above it. - let low = splat(fb, f, u64::from((-1.0f32).to_bits()))?; - fb.glsl(GlslOp::FMax, &[v, low])? - } - SnapshotForm::Half => narrow::from_bits(fb, lanes(Held::Float(FloatFmt::Half)), codes)?, - _ => match signed { - true => extended(fb)?, - false => codes, - }, - }; - match fb.value_ty(value)? == texel { - true => Ok(value), - false => fb.convert(ConvOp::Bitcast, value, texel), - } -} - -/// Whether `form` is a normalized form, whose read decodes its codes by the device's arithmetic. -fn normalized(form: SnapshotForm) -> bool { - matches!( - form, - SnapshotForm::Unorm8 | SnapshotForm::Unorm16 | SnapshotForm::Snorm8 | SnapshotForm::Snorm16 - ) -} - -/// The scale `D` of a normalized code of `width` bits: `2^b - 1`, or `2^(b-1) - 1` where signed. -fn scale(width: u8, signed: bool) -> u32 { - match signed { - true => (1u32 << (width - 1)) - 1, - false => (1u32 << width) - 1, - } -} - -/// The four-lane form of `held`. -fn lanes(held: Held) -> Form { - Form { held, lanes: 4 } -} - -/// The type `ivec4`. -fn signed_lanes(fb: &mut FunctionBuilder<'_>) -> BResult { - let i32_ = fb.module().ty(SType::Int { - width: 32, - signed: true, - })?; - fb.module().ty(SType::Vector { elem: i32_, len: 4 }) -} - -/// What a read of a snapshot slot needs, made in the open block before the read: the snapshot's -/// image, whether the invocation is no helper, and the type the slot's fetch returns. -#[derive(Clone, Copy, Debug)] -pub(crate) struct SnapshotRead { - snapshot: SValue, - other: SValue, - texel: TypeId, - form: SnapshotForm, -} - -/// The snapshot read standing for a fetch of texture slot `index` from image `img` (loaded from -/// the image the copy fetches from), or `None` where the function reads the slot -/// directly. The read must be the fetch of a single-sampled 2D level the copy makes: anything -/// else is an invariant failure, since the slot's interface fact admits no other. -pub(crate) fn prepare( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - index: u32, - img: SValue, - plain_fetch: bool, -) -> BResult> { - let Some(&form) = cx.plan.families.fragment.snapshot.get(&index) else { - return Ok(None); - }; - if !plain_fetch { - return Err(cx.fail(format!( - "a read of snapshot slot {index} that is no plain fetch" - ))); - } - let ty = fb.value_ty(img)?; - let image = match fb.module().types().get(ty)? { - SType::Image(i) => *i, - _ => return Err(cx.fail(format!("snapshot slot {index} read from no image"))), - }; - if image.dim != Dim::D2 || image.arrayed || image.multisampled { - return Err(cx.fail(format!("snapshot slot {index} is no single 2D image"))); - } - if !holds(fb, form, image.sampled_type)? { - return Err(cx.fail(format!( - "snapshot slot {index} returns lanes its form {form:?} does not hold" - ))); - } - let texel = fb.module().ty(SType::Vector { - elem: image.sampled_type, - len: 4, - })?; - let decl = &cx.decl.families.fragment.snapshot; - let (Some(&s), Some(helper)) = (decl.images.get(&index), decl.helper) else { - return Err(cx.fail(format!("snapshot slot {index} is not declared"))); - }; - let ptr = fb.module().global_value(s)?; - let snapshot = fb.load(ptr, MemAccess::default())?; - let ptr = fb.module().global_value(helper)?; - let h = fb.load(ptr, MemAccess::default())?; - let other = fb.unary(UnOp::LogicalNot, h)?; - Ok(Some(SnapshotRead { - snapshot, - other, - texel, - form, - })) -} - -/// The texel at `coord` a read of `r` returns: the snapshot's codes decoded as the slot's lanes -/// ([`decode`]), in a non-helper invocation, and 0 in a helper, which reads nothing. -pub(crate) fn read( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - r: SnapshotRead, - coord: SValue, -) -> BResult { - let texel = r.texel; - let snapshot = r.snapshot; - let form = r.form; - let read: ArmFn<'_, ()> = Box::new(move |fb, _| { - let codes = fb.read( - snapshot, - coord, - &ImageOperands::default(), - TexelMemory::PRIVATE, - )?; - let value = decode(fb, form, codes, texel)?; - Ok(ArmEnd::FallThrough(vec![value])) - }); - let nothing: ArmFn<'_, ()> = Box::new(move |fb, _| { - let zero = fb.module().constant(Constant::Null { ty: texel })?; - let zero = fb.module().const_value(zero)?; - Ok(ArmEnd::FallThrough(vec![zero])) - }); - let merged = fb.if_(&mut (), r.other, read, Some(nothing))?; - match merged.0.as_slice() { - [v] => Ok(*v), - _ => Err(cx.fail("a snapshot read without its merged texel")), - } -} diff --git a/crates/metal2vulkan/src/lower/fragment/stencil.rs b/crates/metal2vulkan/src/lower/fragment/stencil.rs deleted file mode 100644 index c10ed30fb..000000000 --- a/crates/metal2vulkan/src/lower/fragment/stencil.rs +++ /dev/null @@ -1,557 +0,0 @@ -//! A fragment function's `[[stencil]]` output without `VK_EXT_shader_stencil_export`: the -//! shader-side stencil. -//! -//! **Metal's semantics** (measured). The output's low 8 bits `r` are the stencil reference of both -//! faces. The stencil test `(r & readMask) cmp (s & readMask)` against the stored value `s` runs -//! before the depth test, and the face's operation writes `s' = (s & ~writeMask) | (op(s, r) & -//! writeMask)`, per sample in primitive order. A fragment that fails is dropped; a discarded one -//! changes nothing. `[[early_fragment_tests]]` does not compile beside the output, so the tests -//! always follow the function. -//! -//! **The form.** Vulkan's fixed-function stencil test takes one reference per draw, so no state -//! can give each fragment its own. Where the device has the ordered pixel interlock -//! ([`device_form`]), the function applies the test itself: its body runs inside the interlock -//! (`fragment::wrap_entry`), and at each return, unless a discard was recorded, it reads the -//! pixel's value from a coherent `R8Uint` shadow of the stencil (`SyntheticBinding::ShadowStencil`, -//! texel `(x, y)` for pixel `(x, y)`), takes the face's state from `PushField::ShadowStencilState` -//! by `FrontFacing`, applies Metal's comparison and the stencil-failure or pass operation under the -//! masks, writes the shadow, and records a failing fragment as discarded, which the entry kills -//! after the critical section. The ordered interlock makes the read, the operation, and the write -//! of each fragment of a pixel one step in primitive order, across the draws of a subpass; the -//! device-scope coherence of every access inside the critical section (`sync::memory_model`) makes -//! each step's write visible to the next. The fixed-function stencil test is off; the depth test -//! stays fixed-function after the function, so the module never declares early tests. The consumer -//! keeps the shadow (`GraphicsState::shadow_stencil`). -//! -//! **Multisampled** (compiled for a pipeline of more than one sample, -//! `LoweringInputs::multisampled`). Metal tests and writes each covered sample of the fragment -//! against the one reference. The shadow is then a multisampled storage image of the pipeline's -//! count (sample `s` of texel `(x, y)` is sample `s` of pixel `(x, y)`), and the step runs once per -//! sample of the invocation's `SampleMask` input: every covered sample of a pixel-rate invocation, -//! the one sample of an invocation under sample shading (a function that writes memory or reads -//! `[[sample_id]]`). The function writes the samples that pass to the `SampleMask` output, so a -//! failing sample gets no color or depth, and a fragment no sample of which passes is recorded as -//! discarded. The form reads only the invocation's own coverage, never Metal's `[[sample_mask]]` -//! (the pixel's), so the stage interface states the output and not the input. -//! -//! **Exact only where the stencil write cannot depend on the depth result**: the binder refuses a -//! state with a depth attachment, a depth comparison other than `Always`, and a face whose -//! depth-failure operation differs from its pass operation; link refuses alpha to coverage. A -//! returned sample mask and an imageblock beside the output are not implemented. - -use crate::air::abi::OutputRole; -use crate::air::ir::TypeId as AirTypeId; -use crate::device::requirements::{FormatUsage, VkExtension, VkFeature}; -use crate::device::DeviceProfile; -use crate::error::{Capability, Error, Feature, Unsupported}; -use crate::lower::arith::Form; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::lower::stage_io::{self, Returned}; -use crate::lower::sync::memory_model; -use crate::metal::format::{without_format_gaps, StorageUse}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, Value as SValue}; -use crate::spirv::ir::{ - BinOp, Dim, GlslOp, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass, - Type as SType, UnOp, -}; -use crate::vk; - -/// The shadow's format: Metal's stencil values are 8-bit. -pub(crate) const SHADOW_FORMAT: vk::Format = vk::Format::R8_UINT; - -/// Bit 31 of a face's word: the pass has a stencil attachment to test against. -pub(crate) const ATTACHED_BIT: u32 = 1 << 31; - -/// The word of one face of `PushField::ShadowStencilState` (see its docs): Metal's compare -/// function `compare` and operations `stencil_failure` and `pass` by their raw values, the read -/// and write masks' low 8 bits, and [`ATTACHED_BIT`] when `attached`. -pub(crate) fn face_word( - compare: u32, - stencil_failure: u32, - pass: u32, - read_mask: u32, - write_mask: u32, - attached: bool, -) -> u32 { - (compare & 7) - | (stencil_failure & 7) << 3 - | (pass & 7) << 6 - | (read_mask & 0xFF) << 9 - | (write_mask & 0xFF) << 17 - | if attached { ATTACHED_BIT } else { 0 } -} - -/// The shader-side stencil's plan: the output's field of the returned value and its form, and -/// how the module declares the shadow. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ShadowStencil { - /// The returned value's field that holds the output (0 for a returned value itself). - pub field: u32, - pub form: Form, - /// The declared SPIR-V image format: `R8ui`, or `Unknown` for a formatless declaration. - pub declared: crate::spv::ImageFormat, - /// The stage interface's `FrontFacing` object, which selects the face's state. - pub front_facing: usize, - /// The multisampled form's coverage objects (see the module docs); `None` for one sample. - pub samples: Option, -} - -/// The stage interface's objects of the multisampled form: the `SampleMask` input it tests and -/// the `SampleMask` output it writes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct SampleMasks { - pub covered: usize, - pub kept: usize, -} - -/// The declaration of the shadow on `p`, or what the device lacks for the form (see the module -/// docs): the ordered pixel interlock, fragment stores, the shadow's format as a storage image, -/// declared `R8ui` where the device has the extended storage formats, else without a format -/// where it grants that access, and, `multisampled`, multisampled storage images. The refusal names -/// both ways to translate the output: the extension, or what the form lacks (the extended storage -/// formats for the declaration, as the interlocked framebuffer fetch names them for a typed -/// format). -pub(crate) fn device_form( - p: &DeviceProfile, - multisampled: bool, -) -> Result { - let f = p.fields(); - let mut missing = Vec::new(); - if !super::fetch::interlock_forms(p) { - missing.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock)); - } - if !f.leaf.fragment_stores_and_atomics { - missing.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics)); - } - if multisampled && !f.images.storage_multisample { - missing.push(Capability::Feature( - VkFeature::ShaderStorageImageMultisample, - )); - } - if !p.supports_format(SHADOW_FORMAT, FormatUsage::StorageImage) { - missing.push(Capability::Format { - format: SHADOW_FORMAT, - usage: FormatUsage::StorageImage, - }); - } - let use_ = StorageUse::texture(true, true); - let declared = if f.images.storage_extended_formats { - Some(crate::spv::ImageFormat::R8ui) - } else if without_format_gaps(SHADOW_FORMAT, use_, p).is_empty() { - Some(crate::spv::ImageFormat::Unknown) - } else { - // `R8ui` is an extended format: the typed declaration needs only the feature. - missing.push(Capability::Feature( - VkFeature::ShaderStorageImageExtendedFormats, - )); - None - }; - match declared { - Some(d) if missing.is_empty() => Ok(d), - _ => Err(Unsupported::needs_any_of( - Feature::StencilExport, - vec![ - vec![Capability::Extension(VkExtension::ExtShaderStencilExport)], - missing, - ], - )), - } -} - -fn not_implemented() -> Error { - Unsupported::not_implemented(Feature::StencilExport).into() -} - -/// Plan the `[[stencil]]` output of AIR type `ty`, held in field `field` of the returned value, -/// as the shader-side stencil (`stage_io` plans the entry's other outputs; the caller checked the -/// device has no stencil export). -pub fn select_output(cx: &mut SelectCx<'_>, field: u32, ty: AirTypeId) -> Result<(), Error> { - let multisampled = cx.inputs.multisampled; - let declared = device_form(cx.profile, multisampled)?; - let form = stage_io::int_scalar_output(cx, ty)?; - // A returned sample mask would drop samples after the function's write. - let sample_mask = cx - .entry - .ep - .outputs - .iter() - .any(|o| matches!(o.role, OutputRole::SampleMask)); - if sample_mask { - return Err(not_implemented()); - } - if cx.families.fragment.stencil.is_some() { - return Err(cx.invariant("a second stencil output")); - } - let coord = stage_io::frag_coord(cx); - let front_facing = stage_io::front_facing(cx); - let samples = multisampled.then(|| { - let (covered, kept) = stage_io::sample_masks(cx); - SampleMasks { covered, kept } - }); - let fp = &mut cx.families.fragment; - fp.fetch_coord = Some(coord); - fp.stencil = Some(ShadowStencil { - field, - form, - declared, - front_facing, - samples, - }); - cx.facts.insert(RuntimeFact::ShadowStencil { - formatless: declared == crate::spv::ImageFormat::Unknown, - multisampled, - }); - cx.push.insert(PushField::ShadowStencilState); - cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(1); - Ok(()) -} - -/// Check the plan once every output and parameter is planned: an imageblock beside the output -/// is not implemented (what Metal's stencil test does to its writes is not read). -pub(super) fn finish(cx: &SelectCx<'_>) -> Result<(), Error> { - let fp = &cx.families.fragment; - if fp.stencil.is_some() && fp.imageblock.is_some() { - return Err(not_implemented()); - } - Ok(()) -} - -/// Declare the shadow: a 2D `uint` storage image of the planned declaration, multisampled for the -/// multisampled form. -pub(super) fn declare( - mb: &mut ModuleBuilder, - plan: Option<&ShadowStencil>, -) -> BResult> { - let Some(plan) = plan else { - return Ok(None); - }; - let sampled_type = mb.ty(SType::Int { - width: 32, - signed: false, - })?; - let ty = mb.ty(SType::Image(ImageType { - sampled_type, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: plan.samples.is_some(), - usage: ImageUsage::Storage, - format: plan.declared, - }))?; - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Synthetic(SyntheticBinding::ShadowStencil), - index: 0, - }; - mb.resource(slot, StorageClass::UniformConstant, ty) - .map(Some) -} - -/// A `u32` constant. -fn u32_value(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = fb.u32_const(v)?; - fb.module().const_value(c) -} - -/// The bits `[offset, offset + width)` of `word`. -pub(super) fn field_of( - fb: &mut FunctionBuilder<'_>, - word: SValue, - offset: u32, - width: u32, -) -> BResult { - let o = u32_value(fb, offset)?; - let w = u32_value(fb, width)?; - fb.bit_field_extract(false, word, o, w) -} - -/// `choices[code]` for a `code` in `0..8`, as a chain of selections. -fn select_by(fb: &mut FunctionBuilder<'_>, code: SValue, choices: [SValue; 8]) -> BResult { - let mut out = choices[7]; - for (i, &choice) in choices.iter().enumerate().take(7).rev() { - let k = u32_value(fb, i as u32)?; - let is = fb.binary(BinOp::IEqual, code, k)?; - out = fb.select(is, choice, out)?; - } - Ok(out) -} - -/// Whether `a cmp b` under Metal's compare function `code` (`MTLCompareFunction`: never, less, -/// equal, less-equal, greater, not-equal, greater-equal, always), with `a` the masked reference -/// and `b` the masked stored value. -pub(super) fn compare( - fb: &mut FunctionBuilder<'_>, - code: SValue, - a: SValue, - b: SValue, -) -> BResult { - let never = super::bool_const(fb, false)?; - let always = super::bool_const(fb, true)?; - let less = fb.binary(BinOp::ULessThan, a, b)?; - let equal = fb.binary(BinOp::IEqual, a, b)?; - let less_equal = fb.binary(BinOp::ULessThanEqual, a, b)?; - let greater = fb.binary(BinOp::UGreaterThan, a, b)?; - let not_equal = fb.binary(BinOp::INotEqual, a, b)?; - let greater_equal = fb.binary(BinOp::UGreaterThanEqual, a, b)?; - select_by( - fb, - code, - [ - never, - less, - equal, - less_equal, - greater, - not_equal, - greater_equal, - always, - ], - ) -} - -/// The 8-bit value Metal's stencil operation `code` (`MTLStencilOperation`: keep, zero, replace, -/// increment-clamp, decrement-clamp, invert, increment-wrap, decrement-wrap) makes of stored -/// value `s` with reference `r`. -pub(super) fn operation( - fb: &mut FunctionBuilder<'_>, - code: SValue, - s: SValue, - r: SValue, -) -> BResult { - let zero = u32_value(fb, 0)?; - let one = u32_value(fb, 1)?; - let max = u32_value(fb, 0xFF)?; - let up = fb.binary(BinOp::IAdd, s, one)?; - let down = fb.binary(BinOp::ISub, s, one)?; - let at_max = fb.binary(BinOp::IEqual, s, max)?; - let at_zero = fb.binary(BinOp::IEqual, s, zero)?; - let increment_clamp = fb.select(at_max, max, up)?; - let decrement_clamp = fb.select(at_zero, zero, down)?; - let invert = fb.binary(BinOp::BitwiseXor, s, max)?; - let increment_wrap = fb.binary(BinOp::BitwiseAnd, up, max)?; - let decrement_wrap = fb.binary(BinOp::BitwiseAnd, down, max)?; - select_by( - fb, - code, - [ - s, - zero, - r, - increment_clamp, - decrement_clamp, - invert, - increment_wrap, - decrement_wrap, - ], - ) -} - -/// The values one step of the test reads: the face's word, the reference, the pixel, the -/// shadow, and the shadow's texel coherence. -#[derive(Clone, Copy)] -struct Step { - word: SValue, - reference: SValue, - pixel: SValue, - image: SValue, - mem: crate::spirv::ir::TexelMemory, -} - -/// Apply Metal's stencil test and the face's operation to the shadow's texel at `step.pixel` -/// (its sample `sample` in the multisampled form): read it, compare under the read mask, write the -/// stencil-failure or pass operation's value under the write mask. Whether the test passed. -fn apply(fb: &mut FunctionBuilder<'_>, step: Step, sample: Option) -> BResult { - let Step { - word, - reference, - pixel, - image, - mem, - } = step; - let operands = ImageOperands { - sample, - ..ImageOperands::default() - }; - let texel = fb.read(image, pixel, &operands, mem)?; - let stored = fb.composite_extract(texel, &[0])?; - let compare_code = field_of(fb, word, 0, 3)?; - let fail_code = field_of(fb, word, 3, 3)?; - let pass_code = field_of(fb, word, 6, 3)?; - let read_mask = field_of(fb, word, 9, 8)?; - let write_mask = field_of(fb, word, 17, 8)?; - let a = fb.binary(BinOp::BitwiseAnd, reference, read_mask)?; - let b = fb.binary(BinOp::BitwiseAnd, stored, read_mask)?; - let passed = compare(fb, compare_code, a, b)?; - let code = fb.select(passed, pass_code, fail_code)?; - let written = operation(fb, code, stored, reference)?; - let max = u32_value(fb, 0xFF)?; - let keep_mask = fb.binary(BinOp::BitwiseXor, write_mask, max)?; - let kept_bits = fb.binary(BinOp::BitwiseAnd, stored, keep_mask)?; - let new_bits = fb.binary(BinOp::BitwiseAnd, written, write_mask)?; - let value = fb.binary(BinOp::BitwiseOr, kept_bits, new_bits)?; - let u32_ = u32_type(fb)?; - let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; - let zero = u32_value(fb, 0)?; - let texel = fb.composite_construct(uvec4, &[value, zero, zero, zero])?; - fb.write(image, pixel, texel, &operands, mem)?; - Ok(passed) -} - -/// The `u32` type. -fn u32_type(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Int { - width: 32, - signed: false, - }) -} - -/// A pointer to element 0 of the stage interface's array object `i` (a `SampleMask`). -fn element0(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, i: usize) -> BResult { - let g = stage_io::object_global(cx, i)?; - let base = fb.module().global_value(g)?; - let zero = u32_value(fb, 0)?; - fb.access_chain(base, &[zero]) -} - -/// The multisampled form's step over the samples of `covered` (see the module docs): the mask -/// of those that pass. -fn apply_per_sample(fb: &mut FunctionBuilder<'_>, step: Step, covered: SValue) -> BResult { - let u32_ = u32_type(fb)?; - let zero_c = fb.u32_const(0)?; - let left_var = fb.local_var(u32_, Some(zero_c))?; - let left = fb.var_ptr(left_var)?; - let kept_var = fb.local_var(u32_, Some(zero_c))?; - let kept = fb.var_ptr(kept_var)?; - fb.store(left, covered, MemAccess::default())?; - let body: LoopFn<'_, ()> = Box::new(move |fb, ctx, lc| { - let rest = fb.load(left, MemAccess::default())?; - let zero = u32_value(fb, 0)?; - let done = fb.binary(BinOp::IEqual, rest, zero)?; - let exit: ArmFn<'_, ()> = Box::new(move |fb, _| { - lc.break_(fb)?; - Ok(ArmEnd::Exits) - }); - fb.if_(ctx, done, exit, None)?; - // The lowest sample left, then the others. - let sample = fb.glsl(GlslOp::FindILsb, &[rest])?; - let one = u32_value(fb, 1)?; - let below = fb.binary(BinOp::ISub, rest, one)?; - let others = fb.binary(BinOp::BitwiseAnd, rest, below)?; - fb.store(left, others, MemAccess::default())?; - let passed = apply(fb, step, Some(sample))?; - let bit = fb.binary(BinOp::ShiftLeftLogical, one, sample)?; - let bit = fb.select(passed, bit, zero)?; - let so_far = fb.load(kept, MemAccess::default())?; - let so_far = fb.binary(BinOp::BitwiseOr, so_far, bit)?; - fb.store(kept, so_far, MemAccess::default())?; - Ok(()) - }); - fb.loop_(&mut (), LoopSpec::default(), body)?; - fb.load(kept, MemAccess::default()) -} - -/// At a return of returned value `v`: unless a discard was recorded, apply Metal's stencil test -/// and operation of the fragment's face to the shadow at its pixel (at each sample of the -/// invocation in the multisampled form) with the output as the reference, and record a failing -/// fragment as discarded (see the module docs). The multisampled form first keeps every covered -/// sample in the `SampleMask` output, then the samples that pass. Called before the other writes -/// at the return, which a recorded discard skips. -pub(super) fn emit_return( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - v: Option, -) -> BResult<()> { - let Some(plan) = cx.plan.families.fragment.stencil else { - return Ok(()); - }; - let Some(v) = v else { - return Err(cx.fail("a stencil output without a returned value")); - }; - let Some(shadow) = cx.decl.families.fragment.shadow_stencil else { - return Err(cx.fail("the shadow stencil is not declared")); - }; - let Some(discarded) = cx.decl.families.fragment.discarded else { - return Err(cx.fail("a shader-side stencil without its discard predicate")); - }; - let x = cx.operand(fb, v)?; - let output = match cx.plan.families.stage_io.returned { - Returned::Struct => fb.composite_extract(x, &[plan.field])?, - Returned::Value => x, - Returned::Void => return Err(cx.fail("a stencil output of a void entry")), - }; - let max = u32_value(fb, 0xFF)?; - let reference = fb.binary(BinOp::BitwiseAnd, output, max)?; - let state = cx.push_field(fb, PushField::ShadowStencilState)?; - let facing = stage_io::object_global(cx, plan.front_facing)?; - let pixel = super::fetch::pixel(cx, fb)?; - let mem = memory_model::coherence(cx.plan).texel(fb)?; - let masks = match plan.samples { - // The coverage word, from the entry's copy inside an interlocked body. - Some(m) => Some(( - stage_io::coverage_in(cx, fb, m.covered)?, - element0(cx, fb, m.kept)?, - )), - None => None, - }; - let facing = fb.module().global_value(facing)?; - let front = fb.load(facing, MemAccess::default())?; - let front_word = fb.composite_extract(state, &[0])?; - let back_word = fb.composite_extract(state, &[1])?; - let word = fb.select(front, front_word, back_word)?; - let attached_bit = u32_value(fb, ATTACHED_BIT)?; - let attached = fb.binary(BinOp::BitwiseAnd, word, attached_bit)?; - let zero = u32_value(fb, 0)?; - let attached = fb.binary(BinOp::INotEqual, attached, zero)?; - let p = fb.module().global_value(discarded)?; - let was = fb.load(p, MemAccess::default())?; - let kept = fb.unary(UnOp::LogicalNot, was)?; - let test = fb.binary(BinOp::LogicalAnd, kept, attached)?; - // Every covered sample stays unless the test drops it. - let covered = match masks { - Some((c, kept)) => { - fb.store(kept, c, MemAccess::default())?; - Some((c, kept)) - } - None => None, - }; - let arm: ArmFn<'_, ()> = Box::new(move |fb, _| { - let image = fb.module().global_value(shadow)?; - let image = fb.load(image, MemAccess::default())?; - let step = Step { - word, - reference, - pixel, - image, - mem, - }; - // A failing fragment is dropped: the entry kills it after the critical section, and - // the return's other writes skip it. In the multisampled form, a fragment of which - // some samples pass keeps those. - let failed = match covered { - None => { - let passed = apply(fb, step, None)?; - fb.unary(UnOp::LogicalNot, passed)? - } - Some((covered, kept)) => { - let passed = apply_per_sample(fb, step, covered)?; - fb.store(kept, passed, MemAccess::default())?; - let zero = u32_value(fb, 0)?; - fb.binary(BinOp::IEqual, passed, zero)? - } - }; - let p = fb.module().global_value(discarded)?; - fb.store(p, failed, MemAccess::default())?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut (), test, arm, None)?; - Ok(()) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/lower/fragment/stencil/tests.rs b/crates/metal2vulkan/src/lower/fragment/stencil/tests.rs deleted file mode 100644 index a1a25a17d..000000000 --- a/crates/metal2vulkan/src/lower/fragment/stencil/tests.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! The shader-side stencil's device form: where it is declared, and what the refusal names where it -//! is not; and the push word's layout. - -use super::*; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::Needs; - -/// Committed profile `stem` with `features` removed from its description. -fn profile(stem: &str, features: &[VkFeature]) -> 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 mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - for f in features { - desc.features.remove(f); - } - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) - .expect("device") - .profile() - .clone() -} - -fn alternatives(u: Unsupported) -> Vec> { - assert_eq!(u.feature, Feature::StencilExport); - match u.needs { - Needs::AnyOf(a) => a, - other => panic!("{other:?}"), - } -} - -/// Every NVIDIA profile (no stencil export, with the ordered interlock) declares the shadow as -/// `R8ui`. A device that also lacks the extended storage formats, and `R8_UINT` storage without a -/// format, names them; the extension is always the first alternative. -#[test] -fn nvidia_declares_the_shadow_and_a_device_without_the_interlock_names_both_ways() { - for stem in [ - "nvidia-rtx50-linux", - "nvidia-pascal-linux", - "nvidia-rtx5080-laptop", - ] { - let p = profile(stem, &[]); - assert!(!p.fields().fragment.stencil_export, "{stem}"); - assert_eq!( - device_form(&p, false), - Ok(crate::spv::ImageFormat::R8ui), - "{stem}" - ); - assert_eq!( - device_form(&p, true), - Ok(crate::spv::ImageFormat::R8ui), - "{stem}" - ); - } - let ext = vec![Capability::Extension(VkExtension::ExtShaderStencilExport)]; - let p = profile( - "nvidia-rtx50-linux", - &[ - VkFeature::FragmentShaderPixelInterlock, - VkFeature::FragmentStoresAndAtomics, - ], - ); - let a = alternatives(device_form(&p, false).expect_err("no interlock")); - assert_eq!(a[0], ext); - assert_eq!( - a[1], - [ - Capability::Feature(VkFeature::FragmentShaderPixelInterlock), - Capability::Feature(VkFeature::FragmentStoresAndAtomics), - ] - ); - let stem = "runtime-floor"; - let a = alternatives(device_form(&profile(stem, &[]), false).expect_err(stem)); - assert_eq!(a.len(), 2, "{stem}"); - assert_eq!(a[0], ext, "{stem}"); - assert!( - a[1].contains(&Capability::Feature( - VkFeature::FragmentShaderPixelInterlock - )), - "{stem}: {a:?}" - ); -} - -/// The word's fields sit where `PushField::ShadowStencilState` states, each masked to its width. -/// The multisampled form also needs multisampled storage images: a device without them names -/// `shaderStorageImageMultisample` beside the extension, and the single-sample form does not. -#[test] -fn the_multisampled_form_names_multisampled_storage_images() { - let p = profile( - "nvidia-rtx50-linux", - &[VkFeature::ShaderStorageImageMultisample], - ); - assert_eq!(device_form(&p, false), Ok(crate::spv::ImageFormat::R8ui)); - let a = alternatives(device_form(&p, true).expect_err("no multisampled storage")); - assert_eq!( - a, - [ - vec![Capability::Extension(VkExtension::ExtShaderStencilExport)], - vec![Capability::Feature( - VkFeature::ShaderStorageImageMultisample - )], - ] - ); -} - -#[test] -fn a_face_word_packs_the_state_in_its_documented_bits() { - let w = face_word(5, 2, 7, 0x0F, 0xF0, true); - assert_eq!(w & 7, 5); - assert_eq!((w >> 3) & 7, 2); - assert_eq!((w >> 6) & 7, 7); - assert_eq!((w >> 9) & 0xFF, 0x0F); - assert_eq!((w >> 17) & 0xFF, 0xF0); - assert_eq!(w & ATTACHED_BIT, ATTACHED_BIT); - // Wider masks keep their low 8 bits, as Metal's 8-bit stencil does. - let w = face_word(7, 0, 0, u32::MAX, 0x1FF, false); - assert_eq!((w >> 9) & 0xFF, 0xFF); - assert_eq!((w >> 17) & 0xFF, 0xFF); - assert_eq!(w & ATTACHED_BIT, 0); - assert_eq!(w & 0x7E00_0000, 0, "bits 25 to 30 stay clear"); -} diff --git a/crates/metal2vulkan/src/lower/fragment/word_input.rs b/crates/metal2vulkan/src/lower/fragment/word_input.rs index a77870018..308642442 100644 --- a/crates/metal2vulkan/src/lower/fragment/word_input.rs +++ b/crates/metal2vulkan/src/lower/fragment/word_input.rs @@ -3,8 +3,7 @@ //! //! 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 the pixel interlock the storage form merges -//! the word (`fetch`); on one that orders it through input attachments with rasterization-order +//! 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 diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index ea737f1f8..c522816da 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -167,8 +167,6 @@ pub const fn shape(f: PushField) -> FieldShape { PushField::DispatchRegion | PushField::StageInRegion => FieldShape::UVec4Array(2), // A draw's depth clamp range, two `f32`s' bits. PushField::DepthClampRange => FieldShape::UVec2, - // Which of a snapshot variant's draws runs. - PushField::SnapshotPhase => FieldShape::U32, // The alpha test reference's code. PushField::AlphaTestReference => FieldShape::U32, // The blend color and one minus it, four `f32`s' bits each. @@ -179,12 +177,8 @@ pub const fn shape(f: PushField) -> FieldShape { PushField::BaseVertexInstance => FieldShape::UVec2, // The draw's vertices per primitive. PushField::VerticesPerPrimitive => FieldShape::U32, - // The front face's word, then the back face's. - PushField::ShadowStencilState => FieldShape::UVec2, // A zero word, the index count, the first instance, and the base vertex. PushField::CaptureLayout => FieldShape::UVec4Array(1), - // Four bits of kept channels per color attachment. - PushField::StorageKeptChannels => FieldShape::U32, // A constexpr sampler's index in its use's sampler array, and the sampled-texture array's // element a fetched color attachment is read through. PushField::ConstexprSampler(_) | PushField::FetchedColor { .. } => FieldShape::U32, diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index bb600abf9..b1b78e7df 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1275,8 +1275,8 @@ fn select_entry( .collect(); } tessellation::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?; - // The framebuffer-fetch forms first: an output to a storage-form attachment is no interface - // variable. + // The framebuffer-fetch forms first: a write the function computes over its input attachment + // decides its output's interface variable. fragment::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?; stage_io::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?; mesh::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?; diff --git a/crates/metal2vulkan/src/lower/stage_io/color_write.rs b/crates/metal2vulkan/src/lower/stage_io/color_write.rs index 6f27de963..71dd32a45 100644 --- a/crates/metal2vulkan/src/lower/stage_io/color_write.rs +++ b/crates/metal2vulkan/src/lower/stage_io/color_write.rs @@ -31,11 +31,7 @@ //! (`stage_io::returns_no_nan`) stores none, and records no note for one. //! //! An attachment no lane of which rounds is not listed as rounded: it keeps its Vulkan blend of -//! one and zero, through which the facts were measured too. A write in the storage form records -//! the device's conversion: the facts are of the device's conversion of an output variable. A -//! storage write the shader blends into a 16-bit float attachment stores the NaN of the device's -//! arithmetic, which the storage image's store converts, noted `PrecisionNote::DeviceNanEncoding` -//! (Metal stores every NaN of the blend as `0x7e00`). An attachment a lane of +//! one and zero, through which the facts were measured too. An attachment a lane of //! which rounds is listed as rounded (`rounded_colors`), and takes no Vulkan blend of one and zero. use crate::lower::arith::color_write; @@ -51,8 +47,7 @@ use crate::spirv::error::BResult; use crate::spirv::ids::Value; /// Plan the write of a fragment function's output of form `f` to color attachment `color` -/// (dual-source index 0), through an output variable or in the storage form (see the module -/// docs). `nan_free`: every value the function returns there is a constant none of whose lanes is +/// (dual-source index 0), through an output variable (see the module docs). `nan_free`: every value the function returns there is a constant none of whose lanes is /// a NaN, which stores no NaN. pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) { if cx.stage != Stage::Fragment { @@ -66,27 +61,13 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) { .interface .color_writes .insert(color, rules); - // A storage write the shader blends into a 16-bit float attachment stores the blend's result: - // a `half` output's `half` in every channel, which the device converts exactly, and a `float` - // output's `float`, which the storage image's store rounds to `half` as the device rounds it - // (`PrecisionNote::DeviceColorConversion`). No - // conversion of an output variable's bears on it, and its NaN is the device's arithmetic's, - // which the storage image's store converts (`PrecisionNote::DeviceNanEncoding`). - // One the shader blends into an 8-bit unorm attachment stores the blend's result, which the - // storage image's store converts (`fetch::unorm8_blended`, which notes it). - let shader_blended = crate::lower::fragment::blends_in_storage(cx, color); - let sixteen_blended = crate::lower::fragment::blends_sixteen_in_storage(cx, color); let mut lanes = [None; 4]; let mut device = false; let mut blended = false; let mut nans = false; for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) { let Some(rule) = rule else { continue }; - nans |= !shader_blended && !nan_free && color_writes::half_float(rule) && !nan_kept(f); - if sixteen_blended && f.float_fmt() == Some(FloatFmt::F32) { - device = true; - continue; - } + nans |= !nan_free && color_writes::half_float(rule) && !nan_kept(f); match (rule, f.float_fmt()) { (_, None | Some(FloatFmt::F64 | FloatFmt::BFloat)) => {} // A `half` is a half already, whichever way the channel rounds. @@ -103,8 +84,8 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) { ) => {} // The pipeline's rounding mode, which the function applies. (rule @ ChannelWrite::FloatNearestEven { .. }, Some(_)) => *slot = Some(rule), - (ChannelWrite::BlendedNearestEven { .. }, _) => blended |= !shader_blended, - (_, Some(_)) => device |= !shader_blended, + (ChannelWrite::BlendedNearestEven { .. }, _) => blended = true, + (_, Some(_)) => device = true, } } if device { @@ -113,7 +94,6 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) { if blended { cx.precision.insert(PrecisionNote::BlendedWriteRounding); } - nans |= sixteen_blended; if nans { cx.precision.insert(PrecisionNote::DeviceNanEncoding); } diff --git a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs index ddbb8d08e..02057baa6 100644 --- a/crates/metal2vulkan/src/lower/stage_io/extended_color.rs +++ b/crates/metal2vulkan/src/lower/stage_io/extended_color.rs @@ -26,10 +26,10 @@ //! 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 `lower::fragment::fetch`'s storage form), and a dual-source -//! second output to such an attachment is that blend's second source: on a device that orders fetch -//! in neither form the blend is refused naming what it needs (`fetch::unordered_extended_fetch`: -//! `fragmentShaderPixelInterlock` or `rasterizationOrderColorAttachmentAccess`). A blend into one +//! 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. @@ -93,9 +93,9 @@ pub(super) fn plan( 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 (the storage form, or - // over the input attachment, `lower::fragment`), on a device that orders fetch in neither - // form: refused naming the two orderings. + // 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()); } @@ -151,8 +151,7 @@ pub(super) fn raw_components( /// attachment `e` (the module docs): the lanes completed to four as [`held`] completes them, a /// `float` output rounded to `half` toward zero (saturating at 65504) or, where /// `e.nearest_even`, to nearest even, then each lane's bfloat code nearest, ties to even, a NaN -/// `0x7fc0` (`arith::extended_range::bfloat_stored`). Integer operations on the bits alone. The -/// storage form's unblended write stores it too (`lower::fragment::fetch`). +/// `0x7fc0` (`arith::extended_range::bfloat_stored`). Integer operations on the bits alone. pub(crate) fn bfloat_output( fb: &mut FunctionBuilder<'_>, e: ExtendedRangeColor, @@ -181,8 +180,7 @@ const FOUR: Form = Form { /// held in `form`, unblended, as a `uvec4` (`arith::extended_range::encode`): the lanes completed /// to four (a color lane the output lacks 0, a missing alpha 1; an output with fewer lanes than /// the format's channels is refused before), a `float` output rounded to `half` to nearest even, -/// then the kernel write's encode. The storage form's unblended write stores it too -/// (`lower::fragment::fetch`). +/// then the kernel write's encode. pub(crate) fn texel( fb: &mut FunctionBuilder<'_>, form: ExtendedRange, @@ -195,8 +193,8 @@ pub(crate) fn texel( /// The value [`texel`] encodes for output `x` (form `f`) to an attachment held in `form`, a /// `vec4` of `half` values: the lanes completed to four, a `float` output rounded to `half`. -/// Metal's tile holds it until the store, which the storage form's shadow of the attachment keeps -/// (`lower::fragment::fetch`). Not a bfloat form's, whose rounding is the pipeline's and whose +/// Metal's tile holds it until the store. Not a bfloat form's, whose rounding is the pipeline's and +/// whose /// store rounds to the nearest code ([`bfloat_output`]). pub(crate) fn held( fb: &mut FunctionBuilder<'_>, diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 08403aacd..20b1d4b6c 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -406,7 +406,7 @@ pub struct StageIoPlan { /// Whether a kernel reads the stage-in region (`RuntimeFact::StageInRegion`). pub region: bool, /// The lanes of each color attachment's output a fragment function rounds itself - /// (`color_write`), through an output variable or in the storage form: each by its rule, a + /// (`color_write`), through an output variable: each by its rule, a /// half-float channel's under `TextureWriteRoundingMode::NearestEven`. pub rounded: BTreeMap; 4]>, /// The extended-range color attachments whose `float` or `half` output each return stores @@ -618,12 +618,7 @@ pub fn select_return(cx: &mut SelectCx<'_>, _at: InstId, v: Option) -> Re None if void => Ok(()), None => Err(cx.invariant("an entry with outputs returns no value")), Some(_) if void => Err(cx.invariant("an entry without outputs returns a value")), - Some(_) - if cx.families.stage_io.outputs.is_empty() - && !crate::lower::fragment::writes_outside_interface(cx) => - { - Ok(()) - } + Some(_) if cx.families.stage_io.outputs.is_empty() => Ok(()), Some(v) => { let ty = cx .value_ty(v) @@ -871,47 +866,6 @@ pub fn sample_id(cx: &mut SelectCx<'_>) -> usize { ) } -/// Plan the fragment's `FrontFacing` input for a family that reads the fragment's face (the -/// shader-side stencil): the index of its object, shared with a `[[front_facing]]` input. -pub fn front_facing(cx: &mut SelectCx<'_>) -> usize { - plan::builtin( - &mut cx.families.stage_io, - crate::spv::BuiltIn::FrontFacing, - IoDir::Input, - Shape::Bool, - crate::pipeline::stage_io::StageBuiltin::FrontFacing, - ) -} - -/// Plan the fragment's `SampleMask` input and output for the shader-side stencil's multisampled -/// form: the indexes of their objects, the input shared with a `[[sample_mask]]` input. The form -/// reads the invocation's own coverage, which is not Metal's `[[sample_mask]]` (the pixel's -/// coverage), so the stage interface states only the output, which the module writes. -pub fn sample_masks(cx: &mut SelectCx<'_>) -> (usize, usize) { - let sp = &mut cx.families.stage_io; - let covered = plan::builtin_object( - sp, - crate::spv::BuiltIn::SampleMask, - IoDir::Input, - Shape::U32Array(1), - ); - let kept = plan::builtin( - sp, - crate::spv::BuiltIn::SampleMask, - IoDir::Output, - Shape::U32Array(1), - crate::pipeline::stage_io::StageBuiltin::SampleMaskOut, - ); - (covered, kept) -} - -/// The form of an output of AIR type `ty` that must be a 32-bit integer scalar, as a stencil or -/// sample-mask output must, for a family that writes it outside the stage interface (the -/// shader-side stencil). -pub fn int_scalar_output(cx: &SelectCx<'_>, ty: crate::air::ir::TypeId) -> Result { - plan::int_scalar_form(cx, ty) -} - /// The global [`declare`] declared for planned object `i`. pub fn object_global(cx: &mut EmitCx<'_>, i: usize) -> BResult { global(cx, i) @@ -2319,10 +2273,9 @@ fn rotated_second( enum NanDrop { /// Kill the invocation there (`FragmentPlan::return_kill`). Kill(KillForm), - /// Inside an interlocked body, record it in the `discarded` predicate: the storage form's - /// color stores and the other writes at the return skip it, and the entry kills it after the - /// critical section, so a color stored in the shader is dropped as Vulkan's tests would drop an - /// output. + /// Inside an interlocked body, record it in the `discarded` predicate: the writes at the + /// return skip it, and the entry kills it after the critical section, as Vulkan's tests would + /// drop an output. Record(GlobalId), } diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 37696537e..bfb46903e 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -273,13 +273,6 @@ fn int_scalar(f: Form) -> Result<(), Error> { } } -/// The [`io_form`] of AIR type `ty`, which must be [`int_scalar`]. -pub(super) fn int_scalar_form(cx: &SelectCx<'_>, ty: AirTypeId) -> Result { - let f = io_form(cx, ty)?; - int_scalar(f)?; - Ok(f) -} - /// A `float`-lane builtin read into or written from a float of `lanes` lanes. fn float_lanes(f: Form, lanes: u8) -> Result<(), Error> { match f.held { @@ -2123,23 +2116,20 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { float_lanes(io_form(cx, ty)?, 1)?; continue; } - // An imageblock output is written to the pass's imageblock storage, not an interface - // variable. - if let OutputRole::ImageblockData(ib) = &o.role { - if cx.stage != Stage::Fragment { - return Err(cx.invariant("an imageblock output outside a fragment function")); - } - crate::lower::fragment::select_imageblock_output(cx, o.field, ib, o.ty.align, ty)?; - continue; + // An imageblock output is not implemented. + if let OutputRole::ImageblockData(_) = &o.role { + return Err(Unsupported::not_implemented(Feature::Imageblocks).into()); } - // A stencil output on a device without stencil export is the shader-side stencil, - // written to the stencil's shadow, not an interface variable. + // A stencil output needs stencil export. if matches!(o.role, OutputRole::Stencil) && cx.stage == Stage::Fragment && !cx.profile.fields().fragment.stencil_export { - crate::lower::fragment::select_stencil_output(cx, o.field, ty)?; - continue; + return Err(Unsupported::needs( + Feature::StencilExport, + Capability::Extension(VkExtension::ExtShaderStencilExport), + ) + .into()); } // An output to a color the pass lacks is stored nowhere, as plain Metal drops it: no // output variable, so the pipeline writes no location without an attachment. So is one to a @@ -2164,22 +2154,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { } } } - // An output to an attachment the function reads in the interlocked storage form is - // written to its storage image, not an interface variable. - if let OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } = o.role - { - if cx.stage == Stage::Fragment - && crate::lower::fragment::writes_through_storage(cx, color) - { - crate::lower::fragment::select_storage_output(cx, o.field, color, ty) - .map_err(|e| e.at_attachment(Attachment::Color(color)))?; - continue; - } - } // A second output of the function's own to an attachment whose blend reads the one the // rotation needs (`LoweringInputs::rotated_factors`) is stored nowhere: Metal's blend // there reads no second output. @@ -2192,15 +2166,6 @@ 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 or generic blend the shader computes in the - // storage form, which the blend reads from the returned value. - if cx.stage == Stage::Fragment - && crate::lower::fragment::blends_second_through_storage(cx, color) - { - crate::lower::fragment::select_storage_second_output(cx, o.field, color, ty) - .map_err(|e| e.at_attachment(Attachment::Color(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 @@ -2210,8 +2175,8 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { .map_err(|e| e.at_attachment(Attachment::Color(color)))?; continue; } - // Every other write of an extended-range attachment (the storage form's of none of its - // channels or unblended, or the raw texel's through the interface) reads no second + // 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`. if cx.stage == Stage::Fragment && cx.inputs.extended_range_colors.contains_key(&color) { @@ -2902,7 +2867,7 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result { let f = io_form(cx, ty)?; int_scalar(f)?; diff --git a/crates/metal2vulkan/src/lower/stage_io/word_color.rs b/crates/metal2vulkan/src/lower/stage_io/word_color.rs index 7e6d79d1d..265534fa4 100644 --- a/crates/metal2vulkan/src/lower/stage_io/word_color.rs +++ b/crates/metal2vulkan/src/lower/stage_io/word_color.rs @@ -20,10 +20,6 @@ //! //! An integer output to such an attachment is Metal's pipeline error: it is not encoded, and link //! refuses it (`ColorAttachment`). -//! -//! The interlocked storage form writes such an attachment through the same encode where it blends -//! or keeps some channels (`lower::fragment::fetch`), and a blend there reads the word read first -//! as Metal's blend reads it ([`decode`]). use crate::air::intrinsics::PackFormat; use crate::error::{Error, Feature, Unsupported}; @@ -185,57 +181,3 @@ pub(crate) fn encode( } Ok(out) } - -/// The four channels Metal's blend reads from word `x` (a `u32`) of packed 16-bit word attachment -/// `word` (`WordAttachment::Packed16`), as a -/// `vec4` of `f32`, red first: each channel's code over its maximum code rounded to `half`, nearest -/// even, a channel the format lacks 0, alpha 1 (measured: the packed 16-bit blend sweep, -/// `extended_range::Blend::packed16`). The code times the `f32` nearest the maximum's reciprocal -/// lies within two `f32` steps of the quotient, whose `half` it rounds to: the quotient of a code -/// by `2^k - 1` repeats `k` bits without end (or is 0 or 1), which keeps it far from a `half` -/// midpoint, more than `2^-(k+1)` of a `half` step for `k` up to 6. -pub(crate) fn decode( - fb: &mut FunctionBuilder<'_>, - word: WordAttachment, - x: Value, -) -> BResult { - let s = Form { - held: Held::Float(FloatFmt::F32), - lanes: 1, - }; - let u = Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 1, - }; - let st = ty(fb, s)?; - let mut lanes = Vec::with_capacity(4); - for (lane, field) in word.fields().iter().enumerate() { - let Some(field) = field else { - lanes.push(fsplat(fb, s, if lane == 3 { 1.0 } else { 0.0 })?); - continue; - }; - let max = (1u32 << field.bits) - 1; - let code = match field.shift { - 0 => x, - shift => { - let shift = splat(fb, u, u64::from(shift))?; - fb.binary(BinOp::ShiftRightLogical, x, shift)? - } - }; - let mask = splat(fb, u, u64::from(max))?; - let code = fb.binary(BinOp::BitwiseAnd, code, mask)?; - let c = fb.convert(ConvOp::ConvertUToF, code, st)?; - let r = fsplat(fb, s, f64::from(1.0f32 / max as f32))?; - let v = fb.binary_no_contraction(BinOp::FMul, c, r)?; - lanes.push(half_rounded(fb, s, v)?); - } - let v4 = Form { - held: Held::Float(FloatFmt::F32), - lanes: 4, - }; - let t = ty(fb, v4)?; - fb.composite_construct(t, &lanes) -} diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index c9c72d54b..3ec0cabf4 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -2518,23 +2518,6 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR } else { texel_memory(cx, fb, &r.image)? }; - // A slot the draw reads through a snapshot (`LoweringInputs::snapshot_textures`): its - // interface fact admits only the plain fetch of a level the snapshot's copy makes, through the - // slot's image, which the copy fetches from. - let snapshot = match r.image { - ImageRef::Slot(index) => { - let plain = sampled - && !decl.rows - && decl.parts.is_none() - && spec.is_none() - && sample.is_none() - && r.through.is_none() - && !r.level_views - && within.is_none(); - crate::lower::fragment::snapshot_prepare(cx, fb, index, img, plain)? - } - ImageRef::Heap { .. } => None, - }; let access = move |fb: &mut FunctionBuilder<'_>, sparse: bool| -> BResult { match (sampled, sparse) { (true, false) => fb.fetch(img, coord, &ops), @@ -2592,13 +2575,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR inb = Some(and(fb, inb, kept)?); (texel, Some(word)) } - None => match snapshot { - Some(s) => ( - crate::lower::fragment::snapshot_read(cx, fb, s, coord)?, - None, - ), - None => (access(fb, false)?, None), - }, + None => (access(fb, false)?, None), }; // A heap member of a form a heap reads: its raw texel's value, Metal's out-of-bounds texel // selected against its own image, which the float array's test below then leaves, and a read diff --git a/crates/metal2vulkan/src/memory/arena.rs b/crates/metal2vulkan/src/memory/arena.rs index 0421a2fe1..48ae5326c 100644 --- a/crates/metal2vulkan/src/memory/arena.rs +++ b/crates/metal2vulkan/src/memory/arena.rs @@ -509,7 +509,8 @@ pub fn declare_threadgroup( /// Declare a fragment function's threadgroup arena, its tile's memory (the module docs): the /// pass's tile memory buffer, a storage view of the fragment stage, each region at its /// `SpecKey::TgOffset`, and the size `SpecKey::TileThreadgroupLength`. A fragment has no -/// imageblock region (its imageblock is the pass's storage, `lower::fragment::imageblock`). +/// imageblock region: the product refuses a fragment function's imageblock +/// (`Feature::Imageblocks`). fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BResult { let u32_ = u32_ty(mb)?; let slot = ResourceSlot { diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 4fe293295..d97226d7e 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -1031,10 +1031,12 @@ fn copies_only_repr(pf: PixelFormat) -> Repr { /// 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, inside the pixel -/// interlock, from the texel it reads. `Ok` where the device orders fetch through the pixel -/// interlock alone and that form is exact for an attachment of `pf` written whole under a blend -/// Metal's model holds (a padded 10-bit form's); else what blocks it. `BGR10_XR`, `BGRA10_XR`, +/// 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 @@ -2851,71 +2853,6 @@ pub(crate) fn red_blue_exchanged(pf: PixelFormat) -> bool { ) } -/// The RGBA-order twin of a BGRA-order direct format, whose fields are the format's with red and -/// blue exchanged: `R8G8B8A8_UNORM` for `B8G8R8A8_UNORM` and `A2B10G10R10_UNORM_PACK32` for -/// `A2R10G10B10_UNORM_PACK32`, each of the format's texel size and compatibility class (the -/// kernels' `SwizzleBgra` alias views, [`storage_choice`]). SPIR-V names no image format for -/// either BGRA-order format. `None` for every other format. -pub(crate) fn rgba_twin(format: vk::Format) -> Option { - match format { - vk::Format::B8G8R8A8_UNORM => Some(vk::Format::R8G8B8A8_UNORM), - vk::Format::A2R10G10B10_UNORM_PACK32 => Some(vk::Format::A2B10G10R10_UNORM_PACK32), - _ => None, - } -} - -/// What a storage view in `twin`, an RGBA-order twin ([`rgba_twin`]), lacks on `profile` for a -/// function that reads and writes it: the format's storage usage, and a declaration, without a -/// format where the device grants the format that access without one, else by its SPIR-V image -/// format (`shaderStorageImageExtendedFormats` for an extended one). Empty where it lacks -/// nothing. -pub(crate) fn rgba_twin_gaps(twin: vk::Format, profile: &DeviceProfile) -> Vec { - let use_ = StorageUse::READ_WRITE_TEXTURE; - let mut gaps = Vec::new(); - if !profile.supports_format(twin, FormatUsage::StorageImage) { - gaps.push(Capability::Format { - format: twin, - usage: FormatUsage::StorageImage, - }); - } - if !accessed_without_format(twin, use_, profile) { - match spirv_image_format(twin) { - Some(declared) - if crate::spirv::requirements::extended_format(declared) - && !profile.fields().images.storage_extended_formats => - { - gaps.push(Capability::Feature( - VkFeature::ShaderStorageImageExtendedFormats, - )); - } - Some(_) => {} - None => gaps.extend(without_format_gaps(twin, use_, profile)), - } - } - gaps -} - -/// The format other than `format` a fetching draw's storage view of a color attachment of -/// `format` takes in the storage form of framebuffer fetch on `profile` -/// (`StorageAttachmentUse::view_alias_of`, its public door): an 8-bit sRGB format's -/// unsigned-integer format of its texel size on every device, and a BGRA-order format's -/// RGBA-order twin ([`rgba_twin`]) where the device neither reads nor writes the format without a -/// format ([`accessed_without_format`]; SPIR-V names no image format for it, so no declaration -/// reaches it otherwise) and the twin lacks nothing ([`rgba_twin_gaps`]). `None` elsewhere: the -/// view is in `format`, and a device that accesses a BGRA-order format without one keeps that. -pub(crate) fn fetch_view_alias(format: vk::Format, profile: &DeviceProfile) -> Option { - use vk::Format as F; - match format { - F::B8G8R8A8_SRGB | F::R8G8B8A8_SRGB => Some(F::R32_UINT), - F::R8G8_SRGB => Some(F::R16_UINT), - F::R8_SRGB => Some(F::R8_UINT), - _ => rgba_twin(format).filter(|&twin| { - !accessed_without_format(format, StorageUse::READ_WRITE_TEXTURE, profile) - && rgba_twin_gaps(twin, profile).is_empty() - }), - } -} - /// The SPIR-V `Image Format` a storage image of Vulkan format `format` is declared with (Vulkan /// spec "Compatibility Between SPIR-V Image Formats and Vulkan Formats"); `None` for formats only /// a formatless (`Unknown`) declaration can access. Crate-private: only the lowering and the diff --git a/crates/metal2vulkan/src/metal/format/word.rs b/crates/metal2vulkan/src/metal/format/word.rs index f19f80b42..8af5c3817 100644 --- a/crates/metal2vulkan/src/metal/format/word.rs +++ b/crates/metal2vulkan/src/metal/format/word.rs @@ -25,10 +25,10 @@ //! 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: in the pixel interlock -//! (`color_writes::stored_word`), or over the attachment's input attachment on a device that orders -//! fetch through rasterization-order input attachments (`color_writes::merged_word`). A blend of -//! such an attachment, other than one and zero, is not built. +//! 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. //! //! 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,25 +38,14 @@ //! 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: where the device orders -//! fetch through the pixel interlock, the fragment function stores the word in the interlocked -//! storage form, merging the kept fields of the word it reads first (`lower::fragment::fetch`), -//! which hold their codes as Metal's tile holds them. The device blends no such view otherwise, -//! 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 its channels on a device without that -//! interlock is refused as the device lacking the format's attachment, as without the view. -//! -//! A fragment function's color input of a packed 16-bit word attachment reads the word and -//! decodes it, in the interlocked storage form (`lower::fragment::fetch`): each channel's code -//! over its maximum code rounded to `half`, nearest even, which is the value Metal's programmable -//! blending hands the function (measured on an Apple M3 Max under macOS 27.0.1: a `float4` and a -//! `half4` color input of `BGRA4Unorm`, `ABGR4Unorm` and `B5G6R5Unorm`, every code of each 4-bit -//! channel and a sweep of the 5- and 6-bit ones, stored raw into an `RGBA32Float` attachment; an -//! `RGBA8Unorm` control reads the `f32` quotient through a `float4` input, so the two rules are -//! told apart). Metal's tile holds a pass's clear and an earlier draw's write finer than the -//! codes, as it holds them for a blend (`PrecisionNote::DeviceColorConversion`), so a read after -//! one in the same pass reads the code the attachment holds. A color input of an 8-bit sRGB word -//! and of an `RGB9E5Float` one is `NotImplemented(Format)`. +//! 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 +//! `NotImplemented(Format)`. //! //! A multisampled texture of such a format is held in the word's format where the device renders //! that at the texture's count (the runtime's image plan), so every sample holds Metal's word. diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 64eae5819..726fb239b 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -45,8 +45,6 @@ fn stage_module_bytes_are_little_endian_words() { constant_blob: None, rounded_colors: Vec::new(), own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, specialized_notes: Vec::new(), @@ -97,8 +95,6 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { constant_blob: None, rounded_colors: Vec::new(), own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, specialized_notes: vec![ @@ -247,8 +243,6 @@ mod serde_round_trips { line_band: Some(crate::pipeline::BandPrimitive::Triangles), swizzled_storage: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]), addressed_function_tables: true, - interlocked_colors: BTreeSet::from([1]), - read_only_tests: true, address_maps: BTreeMap::from([( slot(Stage::Kernel, SlotClass::Texture, 7), metal::sampler::AddressModeMap::IDENTITY.with( @@ -260,10 +254,6 @@ mod serde_round_trips { primitive_id_indices: Some(metal::IndexType::UInt16), quad_primitive_ids: true, private_list: true, - snapshot_textures: BTreeMap::from([( - slot(Stage::Fragment, SlotClass::Texture, 2), - crate::pipeline::SnapshotForm::Unorm8, - )]), cross_class: BTreeMap::from([( slot(Stage::Kernel, SlotClass::Texture, 8), SampledType::Uint, @@ -346,15 +336,8 @@ mod serde_round_trips { ), (2, None), ]), - depth_or_stencil: true, - alpha_to_coverage: false, - amplified: true, }), srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]), - snapshot_textures: BTreeMap::from([( - slot(Stage::Fragment, SlotClass::Texture, 3), - crate::pipeline::SnapshotForm::Half, - )]), ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]), ycbcr_planes_sampled: BTreeMap::from([( slot(Stage::Fragment, SlotClass::Texture, 9), @@ -442,7 +425,6 @@ mod serde_round_trips { alpha_test: Some(metal::CompareFunction::GreaterEqual), logic_operation: Some(crate::vk::LogicOp::XOR), depth_compare_clamp_mask: 0x8000_0005, - read_only_tests: true, rotated_colors: BTreeSet::from([4]), alpha_in_red_colors: BTreeSet::from([4]), rotated_factors: BTreeMap::from([( @@ -591,29 +573,8 @@ mod serde_round_trips { push_offset: 20, control_point_index_type: metal::TessellationControlPointIndexType::UInt16, }), - fragment_imageblock: Some(FragmentImageblock { - mechanism: ImageblockMechanism::StorageImageInterlock, - words: 3, - master: [9; 32], - data_size: 12, - alignment: 4, - }), vertex_writes_memory: true, writes_viewport_index: true, - storage_attachments: vec![StorageAttachmentUse { - color_index: 1, - format: vk::Format::R16G16B16A16_SFLOAT, - writes: true, - formatless: false, - view: StorageAttachmentView::SamplePlanes { layers: 4 }, - view_alias: Some(vk::Format::R32_UINT), - kept: vk::ColorComponentFlags::G | vk::ColorComponentFlags::A, - }], - shadow_stencil: Some(ShadowStencilUse { - format: vk::Format::R8_UINT, - formatless: true, - samples: 4, - }), writes_point_size: true, writes_depth: true, reads_barycentric_coord: true, @@ -621,7 +582,6 @@ mod serde_round_trips { fragment_writes_memory: true, color_outputs: 0b101, sample_mask: Some(0b1001), - snapshot_reads: true, logic_op: Some(vk::LogicOp::EQUIVALENT), line_band: Some(crate::pipeline::LineBandState { push_offset: 112, @@ -970,9 +930,6 @@ mod bind_serde_round_trips { [8.0, -8.0, 1.75, -1.0], )), resident_ranges: vec![crate::bind::ResidentRange::new(0x9_0000, 0x3_0000, 100)], - interlocked_colors: BTreeSet::from([0, 3]), - fragment_tests: crate::bind::FragmentTests::Depth { writes: true }, - snapshot_textures: BTreeSet::from([2]), blend_color: [0.25, -0.5, 1.5, 0.75], alpha_test_reference: Some(0.375), primitive_type: Some(metal::PrimitiveType::TriangleStrip), @@ -1034,9 +991,6 @@ mod bind_serde_round_trips { depth_clamp_range: true, rotated_weights: true, line_band: Some(crate::pipeline::BandPrimitive::Lines), - interlocked_colors: BTreeSet::from([0, 3]), - fragment_tests: crate::bind::FragmentTests::Pass, - snapshot_textures: BTreeSet::from([2]), primitive_id_indices: Some(metal::IndexType::UInt32), quad_primitive_ids: true, private_list: true, @@ -1204,7 +1158,6 @@ mod bind_serde_round_trips { control_point_index: None, }); round_trip(&WriteSource::TessellationFactors); - round_trip(&WriteSource::ShadowStencil); round_trip(&UseTarget::TessellationFactors); round_trip(&WriteSource::PatchIndices { min_bytes: 16 }); round_trip(&WriteSource::TileMemory { bytes: 480 }); diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 30d112db2..ccbd6ea7b 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -11,7 +11,7 @@ use crate::cache::{Hash256, PipelineKey, SpecializationKey}; use crate::device::requirements::Requirements; use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::graphics::GraphicsState; -use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels, SnapshotRefusal}; +use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels}; use crate::pipeline::layout::PipelineLayout; use crate::pipeline::sym::SpecKey; use crate::pipeline::vertex::VertexInputState; @@ -95,12 +95,7 @@ fn stage_footprint(stage: &StageModule) -> u64 { + vector_bytes::(stage.precision_notes.capacity()) + vector_bytes::(stage.specialized_notes.capacity()) + clauses - + vector_bytes::( - stage.rounded_colors.capacity() - + stage.own_pixel_textures.capacity() - + stage.snapshot_textures.capacity(), - ) - + vector_bytes::<(u32, SnapshotRefusal)>(stage.snapshot_refusals.capacity()) + + vector_bytes::(stage.rounded_colors.capacity() + stage.own_pixel_textures.capacity()) + vector_bytes::(stage.level_reads.capacity()) + (stage.level_reads.iter()) .map(|reads| vector_bytes::(reads.sampled.capacity())) @@ -189,14 +184,6 @@ pub struct StageModule { /// rectangle bounding its scissors, a pixel wider each way for its helper invocations, on a /// framebuffer below `2^24` pixels a side. Empty for every other stage. pub own_pixel_textures: Vec, - /// The texture slots of `own_pixel_textures` a draw can read through a snapshot an earlier - /// draw of the same primitives took (`StageInterface::snapshot_textures`), sorted. Empty for - /// every other stage. - pub snapshot_textures: Vec, - /// Why each slot of `own_pixel_textures` that `snapshot_textures` leaves out is left out - /// (`StageInterface::snapshot_refusals`): every [`SnapshotRefusal`] that holds for it, sorted - /// by slot and then by refusal. Empty for every other stage. - pub snapshot_refusals: Vec<(u32, SnapshotRefusal)>, /// The levels of its bound view each texture slot's reads reach, one entry a slot, sorted by /// slot (`StageInterface::level_reads`). Empty for a kernel and a stage the link makes. pub level_reads: Vec, @@ -807,10 +794,7 @@ pub enum PrecisionNote { /// (`pipeline::link::vertex`): Metal widens its NaN to `0x7fc00000`, and the device's /// widening need not. A pulled attribute's decode records it in the module (a vertex /// function's, a kernel's `[[stage_in]]` attribute's, a post-tessellation function's). Also - /// recorded by a - /// 16-bit float attachment's blend the function computes in the storage form: a NaN of the - /// blend is the device's arithmetic's, which the storage image's store converts, where Metal - /// stores every NaN of the blend as `0x7e00`. Also recorded by a `float` read of a heap's texture buffer on a device without + /// recorded by a `float` read of a heap's texture buffer on a device without /// Metal's sampler: Metal hands back a half-float texel's NaN as `0x7fc00000`, and the handle /// carries no class to convert it by. The runtime announces it too for a GPU blit through an /// `RG11B10Float` texture Metal keeps losslessly compressed: Metal's compression makes a NaN @@ -1021,9 +1005,7 @@ pub enum PrecisionNote { /// Metal's integer store rounds such a channel to nearest even, the device's store as it rounds /// a `float` write (toward zero on every measured driver: within one unit in the last place of /// the channel's value, a finite value past 65504 stored as 65504 where Metal's `half` is the - /// infinity). So does a fragment function's `float` output blended in the shader into a 16-bit - /// float attachment it renders through a storage image (the pixel interlock's fetch), whose - /// `half` the store rounds. + /// infinity). /// /// Also: a blend into a packed 16-bit unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`, /// `ABGR4Unorm`, `BGR5A1Unorm`) reads what the device's attachment holds, its channels' codes, @@ -1038,10 +1020,10 @@ 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 in the storage form into an 8-bit unorm attachment - /// (`R8Unorm`, `RG8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`), whose result the storage image's store - /// converts to its code, where Metal rounds the exact product with 255 (a NaN 0); the store may - /// take the other code near a tie. + /// 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 @@ -1135,8 +1117,8 @@ pub enum PrecisionNote { /// even, and the device's blend converts it by its own rounding (MoltenVK's toward zero), so /// a blended value off the half grid may store the neighbouring half; under a constant factor /// Metal's result is neither rule's on 2,376 of 580,508 `RGBA16Float` channels near the half - /// denormals. The exact path, the blend in the function under the pixel - /// interlock, is not built. + /// denormals. The exact path, the blend in the function over an ordered input attachment, is + /// not built. /// /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review, deferred in C3 until an exact path exists. @@ -1219,8 +1201,8 @@ pub enum PrecisionNote { /// of a module without fast math keeps a zero factor's product, the destination's by zero /// there: a NaN of an infinite or NaN texel, and `+0` of a `-0` output over a texel of `+0` or /// above (plain Metal on the M3 Max under macOS 27.0.1, `half4` and `float4` - /// outputs). Where the function does not compute that blend in the storage form, the pipeline - /// blends the output by the device's blend, whose answer for those texels is the device's own, + /// outputs). The pipeline blends the output by the device's blend, whose answer for those + /// texels is the device's own, /// where a `float` output would otherwise store as written. /// /// Validation derives no tolerance and no explanation from it: a difference stays a @@ -1358,9 +1340,8 @@ pub enum PrecisionNote { /// A fragment function of a module compiled with fast math (`air.compile.fast_math_enable`) /// returns a `half` color output to an attachment the pipeline has that stores some channel /// (its write mask names one of its format's channels; `StageIo::half_fast_colors`, which the - /// pipeline's stage reads, or the interlocked storage form's write), where - /// [`PrecisionNote::HalfOutputPrecision`]'s conditions hold; or computes the blend of a 16-bit - /// float attachment it fetches where Metal's compiler may regroup it (below). Metal's compiler + /// pipeline's stage reads), where [`PrecisionNote::HalfOutputPrecision`]'s conditions hold. + /// Metal's compiler /// folds the attachment's blend and conversion into the function and, under fast math, fuses /// and regroups them per pipeline: it reads the output's `float` or its `half`, rounds each /// factor and product to `half` or keeps it, and takes a lerp or a common factor, by the @@ -1382,22 +1363,6 @@ pub enum PrecisionNote { /// the sweep; the device's `float` blend modelled on the same draws, three units). A consumer /// may relay it as a known difference. The output reaches every device widened to `float`. /// - /// A fragment function that fetches a blended `R16Float`, `RG16Float` or `RGBA16Float` - /// attachment in the interlocked storage form computes the blend itself, no Vulkan blend - /// applying to a storage write (`lower::fragment::fetch`): in the arithmetic of its `half` or - /// `float` output of one to four lanes, as Metal's compiler appends it (plain Metal on the M3 - /// Max under macOS 27.0.1: every channel of 677 and 1,350 blend states into each format, half - /// and float outputs, safe and fast math). Under fast math it records this note where the blend - /// is not Metal's exactly: where Metal's compiler may fold the output's own arithmetic into the - /// blend (a lane computed by a fast-math operation, a constant, or the fetched color: a - /// returned product fused into the blend's one minus the source alpha), or the blend's fast - /// form is a sum, a lerp, a common factor or a product rounded beside a fused one (but a blend - /// constant's difference), which the sweeps fit in most states but not all. It then stores - /// within 2 units in the last place of a `half` of Metal's at the operands' magnitude, 16 at - /// the stored value's under cancellation (below one at the function's own largest term). Where - /// every lane of the output is opaque to the blend and its form fits every state, the blend is - /// Metal's and the function records nothing. - /// /// The pipeline's stage also records it for an attachment of `StageIo::half_fast_colors` that /// stores some channel **without** blending (`color_writes::stores_output`, which is the test /// it makes), and that is deliberate rather than the blend's name read loosely: under fast math @@ -1405,8 +1370,8 @@ pub enum PrecisionNote { /// conversion round once, where this rounds the output to `half` first, so a channel whose format /// converts the `float` and its `half` to different codes may store a value apart from Metal's. /// It is the cause [`PrecisionNote::HalfOutputPrecision`] records for a module naming no math - /// mode, under a name that reads as a blend's alone. Measured in the interlocked storage form, - /// whose write stores the output's `half`: into `BGRA8Unorm`, one code apart from Metal's in + /// mode, under a name that reads as a blend's alone. Measured through a write that stores the + /// output's `half`: into `BGRA8Unorm`, one code apart from Metal's in /// 2.2 to 2.5% of pixels for an output computed through one division or one `fwidth`, and in /// 2.1 to 4.5% for a coverage computed through both, where the same arithmetic with a `float` /// output stores Metal's codes (MoltenVK 1.4.2 on an Apple M3 Max, macOS 27.0.1). The 12 @@ -1768,9 +1733,8 @@ pub enum PrecisionNote { /// the device's. The same conversions serve, noted alike: an implicit imageblock access of a /// normalized attachment (a `half` one's load rounding the unpacked `float` once more, where /// Metal rounds `c / D` once), a fragment function's read and write of an 8-bit sRGB attachment - /// in the interlocked storage form or through its word view, and a snapshot read's decode of a - /// normalized code (`c` times the `f32` nearest `1 / D`, where Metal reads `c / D` correctly - /// rounded). So does every conversion of an extended-range, padded 10-bit or bfloat texel + /// through its word view. So does every conversion of an extended-range, padded 10-bit or + /// bfloat texel /// (`lower::arith::extended_range`; `ArithPlan::converts` records it), on every device, no /// Vulkan format holding them: a read `float(c - 384)` (a padded code's `float(c)`) times the /// `f32` nearest `1 / 510` (`1 / 1023`), a write `RoundEven` of the clamped value's `f32` @@ -1870,33 +1834,6 @@ pub enum PrecisionNote { /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review. DeviceAlphaCoverage, - /// A fragment function reads a color attachment the pipeline blends, in the interlocked - /// storage form (`lower::fragment::fetch`, on a device that orders framebuffer fetch only - /// through the pixel interlock), of a format whose blend arithmetic of Metal's the translation - /// does not build: a format held directly whose channels read as floats, but a 16-bit float - /// one, an sRGB one and an extended-range one (a 32-bit float, 16-bit normalized, 8-bit signed - /// normalized, 10-bit, packed float or `A8Unorm` format, among others), an 8-bit unorm one - /// written by an output of fewer than four lanes, and a 16-bit float or 8-bit unorm one under a - /// blend of the second source or beside a second (index 1) output. No Vulkan blend applies to - /// a storage write, so the shader computes the pipeline's blend itself: in `float`, each - /// factor, product and sum - /// rounded to nearest even, a factor of zero keeping its product, the source and the blend - /// color clamped first to a normalized format's range (`[0, 1]`, `[-1, 1]`; a NaN to its low - /// end) as Vulkan's blend clamps them, an output's missing lane zero, the result stored through - /// the device's conversion. Metal's blend arithmetic for these formats is not measured, so the - /// recorded bound is not known; a blend in `float` of a 32-bit float format agrees with one - /// that fuses a product within that product's rounding, and one of a format of fewer bits than - /// a `float` within the format's own rounding of the result where Metal's arithmetic is at - /// least as fine. A factor of the second source reads the function's second output, clamped as - /// the source. An 8-bit sRGB attachment (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, - /// `BGRA8Unorm_sRGB`) under a blend of the second source, a one- or two-channel one under a - /// lerp, each in a module compiled with fast math, and one written by an output of fewer than - /// four lanes, record it too: there the shader computes Metal's 8-bit unorm blend's rounded - /// forms over the decoded texel, in the output's type (a missing lane zero), and stores the - /// result by Metal's sRGB encode (`extended_range::Blend::srgb8`), which is Metal's without - /// fast math at four lanes; under fast math Metal regroups the blend, unmeasured. - /// Validation derives no tolerance from it. - UnmeasuredFetchBlend, /// A fragment function reads an `interpolant` through `interpolate_at_offset(offset)`, which /// Metal evaluates at the offset as given from the pixel's upper-left corner, at any distance /// and on no grid (the Apple M3 Max, macOS 27.0.1: an offset of 0.999 read at 0.999, one of @@ -1931,8 +1868,8 @@ 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 with neither - /// rasterization-order color attachment access nor `fragmentShaderPixelInterlock`. It reads + /// 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 /// 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 diff --git a/crates/metal2vulkan/src/pipeline/color_writes.rs b/crates/metal2vulkan/src/pipeline/color_writes.rs index 6e7f00022..70d77ee22 100644 --- a/crates/metal2vulkan/src/pipeline/color_writes.rs +++ b/crates/metal2vulkan/src/pipeline/color_writes.rs @@ -55,7 +55,6 @@ use crate::metal::format::{color_output_components, write_conversion, WriteConve use crate::metal::TextureWriteRoundingMode; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::descriptor::ColorAttachmentDescriptor; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::graphics::ColorAttachmentState; use crate::pipeline::lower_inputs::{ChannelWrite, ExtendedRangeColor, FactorLane}; use crate::pipeline::rotated_blend::{inexact, rotated_blend, RotatedBlend}; @@ -330,12 +329,10 @@ pub(crate) fn extended_range_colors( /// 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: in the interlocked storage form (`lower::fragment::fetch`) -/// where the device orders fetch through the pixel interlock alone, over the attachment's input -/// attachment (`lower::fragment`'s `input_blend`, `RuntimeFact::WordInputMerge`) where it orders -/// it through rasterization-order input attachments. On a device that orders fetch in neither -/// form, link names the orderings the merge needs -/// (`lower::fragment::fetch::unordered_extended_fetch`). +/// 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`). pub(crate) fn merged_extended(c: &ColorAttachmentDescriptor) -> bool { merges_extended(c.pixel_format, c.write_mask, c.blending_enabled) } @@ -361,9 +358,8 @@ pub(crate) fn merges_extended( /// 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 the function stores in the -/// interlocked storage form ([`stored_word`]), or one that takes its format's own attachment, as -/// the device has it or not. +/// 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, @@ -422,54 +418,6 @@ pub(crate) fn merged_word( merges_over_input(c, word, p).then(|| word_channels(word).difference(c.write_mask)) } -/// The word view of color attachment `c` of a render pipeline on profile `p` whose writes the -/// fragment function stores in the interlocked storage form (`lower::fragment::fetch`), reading -/// the word first inside the interlock: a packed 16-bit word attachment -/// (`metal::format::WordAttachment::of`) written under a blend other than one and zero, added, -/// whose factors read no second source (Metal's packed 16-bit blend, which the function computes -/// over the word, `extended_range::Blend::packed16`), or a word attachment other than -/// `RGB9E5Float`'s written unblended under a write mask of some of the format's channels (the -/// function merges the fields of the channels the mask keeps), on a device that orders fetch -/// through the pixel interlock alone. -/// `None` for every other attachment, and for a write mask of none of the format's channels. -pub(crate) fn stored_word( - c: &ColorAttachmentDescriptor, - p: &DeviceProfile, -) -> Option { - use metal::{BlendFactor as F, ColorWriteMask as M}; - let word = metal::format::WordAttachment::of(c.pixel_format, p)?; - let channels = [M::RED, M::GREEN, M::BLUE, M::ALPHA] - .into_iter() - .zip(word.fields()) - .filter(|(_, f)| f.is_some()) - .fold(M::NONE, |m, (bit, _)| m | bit); - let kept = c.write_mask & channels; - let partial = !kept.is_empty() && kept != channels; - let unblended = !c.blending_enabled || replaces(c); - let second = [ - c.source_rgb_blend_factor, - c.destination_rgb_blend_factor, - c.source_alpha_blend_factor, - c.destination_alpha_blend_factor, - ] - .iter() - .any(|f| { - matches!( - f, - F::Source1Color | F::OneMinusSource1Color | F::Source1Alpha | F::OneMinusSource1Alpha - ) - }); - // Metal's blend of a packed 16-bit word is built; an 8-bit sRGB word's is not, nor is an - // `RGB9E5Float` word's blend or partial mask (its mantissas share the exponent). - let packed = matches!(word, metal::format::WordAttachment::Packed16 { .. }); - let fielded = word != metal::format::WordAttachment::Rgb9e5; - let stored = match unblended { - true => partial && fielded, - false => packed && !kept.is_empty() && !second, - }; - (stored && crate::lower::fragment::interlock_orders(p)).then_some(word) -} - /// 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( @@ -576,9 +524,8 @@ pub(crate) fn alpha_in_red_colors( /// The attachments holding Metal's alpha in red that the fragment stage `fragment` writes or reads /// in a render pipeline whose color attachments are `colors` on `p`: [`alpha_in_red_colors`]'s, -/// for the attachments it writes through output variables of either dual-source index, reads -/// through an input attachment, or reads in the interlocked storage form -/// (`RuntimeFact::InterlockedFramebufferFetch`), the set it must have compiled under +/// for the attachments it writes through output variables of either dual-source index or reads +/// through an input attachment, the set it must have compiled under /// (`StageIo::alpha_in_red_colors`). pub(crate) fn wanted_alpha_in_red( fragment: &FunctionArtifact, @@ -602,11 +549,7 @@ pub(crate) fn wanted_alpha_in_red( crate::pipeline::sym::ResourceKind::InputAttachment(color) => Some(color), _ => None, }); - let interlocked = fragment.facts.iter().filter_map(|f| match *f { - RuntimeFact::InterlockedFramebufferFetch { color, .. } => Some(color), - _ => None, - }); - let used: BTreeSet = written.chain(inputs).chain(interlocked).collect(); + let used: BTreeSet = written.chain(inputs).collect(); let mut out = alpha_in_red_colors(colors, p); out.retain(|a| used.contains(a)); out @@ -621,11 +564,10 @@ pub(crate) fn wanted_alpha_in_red( /// 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: in the interlocked storage form where the -/// device orders fetch through the pixel interlock (`lower::fragment::fetch`), over the -/// attachment's input attachment where it orders it through rasterization-order input attachments -/// (`lower::fragment`'s `input_blend`). A device that orders fetch in neither form refuses the -/// pipeline (`fetch::unordered_extended_fetch`, at link). +/// 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) } @@ -794,7 +736,7 @@ pub(crate) fn wanted_extended_range( /// The color writes the fragment stage `fragment` compiles under in a render pipeline whose /// color attachments are `colors` (alpha-to-coverage on where `alpha_to_coverage`, rounding by /// `rounding`) on `p`: the pipeline's, for the attachments it writes through output variables of -/// dual-source index 0 or in the storage form ([`written`]). +/// dual-source index 0 ([`written`]). pub(crate) fn wanted( fragment: &FunctionArtifact, colors: &[Option], @@ -805,7 +747,7 @@ pub(crate) fn wanted( } /// The color attachments the fragment stage `fragment` writes through output variables of -/// dual-source index 0 or in the storage form. +/// dual-source index 0. fn written(fragment: &FunctionArtifact) -> impl Iterator + '_ { let outputs = fragment .interface @@ -819,15 +761,7 @@ fn written(fragment: &FunctionArtifact) -> impl Iterator + '_ { } => Some(attachment), _ => None, }); - let storage = fragment.facts.iter().filter_map(|f| match *f { - RuntimeFact::InterlockedFramebufferFetch { - color, - writes: true, - .. - } => Some(color), - _ => None, - }); - outputs.chain(storage) + outputs } /// Whether the color writes the fragment stage `fragment` compiled under @@ -913,8 +847,7 @@ pub(crate) fn stores_output(c: &ColorAttachmentState) -> bool { /// fast math (`StageIo::half_blend_colors`, `StageIo::float_blend_colors`), whose blend there /// Metal computes keeping the destination's product by zero (a NaN of an infinite or NaN texel, /// `+0` of a `-0` output over a texel of `+0` or above), which no write of the -/// output alone stores. The pipeline blends it and announces `PrecisionNote::HalfOutputPrecision`; -/// the storage form computes Metal's (`lower::fragment::fetch`). +/// output alone stores. The pipeline blends it and announces `PrecisionNote::HalfOutputPrecision`. pub(crate) fn keeps_zero( io: &crate::pipeline::stage_io::StageIo, color: u32, diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 1b61afa81..534edb943 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -103,9 +103,10 @@ 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 only - /// through the pixel interlock the state of the attachments the entry reads - /// (`LoweringInputs::framebuffer_fetch`), and, for each index the pipeline's vertex function + /// 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 /// writes (the [`RawIndices`]), whether the entry reads it /// (`LoweringInputs::viewport_index_varying`; /// `LoweringInputs::render_target_array_index_varying`). The pipeline's @@ -134,17 +135,14 @@ pub enum InputsFrom<'a> { pub(crate) static NO_PRIMITIVE_VARYINGS: BTreeSet = BTreeSet::new(); /// The pipeline state a fragment stage compiles under ([`InputsFrom::Fragment`]): its render -/// pipeline's, or its mesh render pipeline's, which has no vertex amplification and no call stack -/// depth of its own (Metal's default, 1). +/// pipeline's, or its mesh render pipeline's, which has no call stack depth of its own (Metal's +/// default, 1). #[derive(Clone, Copy, Debug)] pub struct FragmentPass<'a> { pub(crate) color_attachments: &'a [Option; 8], - /// The pipeline has a depth or a stencil attachment. - pub(crate) depth_or_stencil: bool, pub(crate) raster_sample_count: u32, pub(crate) rasterization_enabled: bool, pub(crate) alpha_to_coverage: bool, - pub(crate) max_vertex_amplification_count: u32, pub(crate) max_call_stack_depth: u32, /// The pipeline's `textureWriteRoundingMode`. pub(crate) texture_write_rounding_mode: crate::metal::TextureWriteRoundingMode, @@ -171,11 +169,9 @@ impl<'a> From<&'a RenderPipelineDescriptor> for FragmentPass<'a> { fn from(d: &'a RenderPipelineDescriptor) -> FragmentPass<'a> { FragmentPass { color_attachments: &d.color_attachments, - depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(), raster_sample_count: d.raster_sample_count, rasterization_enabled: d.rasterization_enabled, alpha_to_coverage: d.alpha_to_coverage, - max_vertex_amplification_count: d.max_vertex_amplification_count, max_call_stack_depth: d.max_fragment_call_stack_depth, texture_write_rounding_mode: d.texture_write_rounding_mode, sample_mask: None, @@ -194,11 +190,9 @@ impl<'a> From<&'a MeshPipelineDescriptor> for FragmentPass<'a> { fn from(d: &'a MeshPipelineDescriptor) -> FragmentPass<'a> { FragmentPass { color_attachments: &d.color_attachments, - depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(), raster_sample_count: d.raster_sample_count, rasterization_enabled: d.rasterization_enabled, alpha_to_coverage: d.alpha_to_coverage, - max_vertex_amplification_count: 1, max_call_stack_depth: 1, texture_write_rounding_mode: d.texture_write_rounding_mode, sample_mask: None, @@ -2497,34 +2491,26 @@ pub(crate) fn unattached_colors_written( } /// The framebuffer-fetch state of pass `d` for the specialized fragment entry `spec` on `p` -/// (`LoweringInputs::framebuffer_fetch`): on a device that orders fetch only through the pixel -/// interlock, the state of every attachment the entry reads through a `[[color(n)]]` input of a -/// constant index (one an instruction of its specialized body uses: an input the function's -/// constants leave unread reads nothing), of every extended-range attachment it writes that the -/// pass blends (whose blend the function computes from the texel it reads) or writes unblended -/// under a mask of some of the codes one word holds (`color_writes::merged_extended`), of every -/// attachment held with its channels rotated whose blend the function computes -/// (`color_writes::shader_rotated_blend`, in either form below), and of every attachment variant -/// `v`'s instance keeps out of its subpass that the entry writes through its first output -/// (`VariantKey::interlocked_colors`); `None` on another device or for an entry that declares none -/// of them. 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 -/// 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`), and 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`). On either device, under a private logic operation the function computes -/// (`FragmentPass::logic_operation`), the state of every attachment whose format the operation -/// serves that the entry writes through its first output (`lower::fragment`'s `logic`). +/// (`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<'_>, - v: &VariantKey, p: &DeviceProfile, ) -> Option { - let interlock = crate::lower::fragment::interlock_orders(p); - let inputs = crate::lower::fragment::inputs_order(p); - if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) || !(interlock || inputs) { + if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) + || !crate::lower::fragment::inputs_order(p) + { return None; } let blended = |color: u32| { @@ -2546,15 +2532,6 @@ pub(crate) fn fetch_inputs( .flatten() .is_some_and(|c| crate::pipeline::color_writes::merged_extended(&c)) }; - // A word attachment whose writes the function blends over, or merges into, the word it reads. - let stored_word = |color: u32| { - d.color_attachments - .get(color as usize) - .copied() - .flatten() - .and_then(|c| crate::pipeline::color_writes::stored_word(&c, p)) - .is_some() - }; // A word attachment whose writes the function merges into the word its input attachment // holds. let merged_word = |color: u32| { @@ -2586,23 +2563,11 @@ pub(crate) fn fetch_inputs( .flatten() .is_some_and(|c| crate::lower::fragment::logic_channels(c.pixel_format).is_some()) }; - // A color input counts only where the specialized body reads it, as the lowering plans only - // a used parameter: a read the function's constants make dead reads nothing, so it takes - // neither the storage form nor its blend in the shader. - let used = params_used(spec); let read: BTreeSet = spec .ep - .params + .outputs .iter() - .filter(|b| used.contains(&b.param)) - .filter_map(|b| match b.role { - ParamRole::ColorInput { - index: AbiInt::Const(color), - .. - } if interlock => Some(color), - _ => None, - }) - .chain(spec.ep.outputs.iter().filter_map(|o| match o.role { + .filter_map(|o| match o.role { OutputRole::RenderTarget { attachment: AbiInt::Const(color), index: 0, @@ -2610,42 +2575,23 @@ pub(crate) fn fetch_inputs( } if blended(color) || rotated_blend(color) || logic(color) - || (interlock && (stored_word(color) || merged_extended(color))) - || (inputs && (merged_word(color) || merged_extended(color))) => + || merged_word(color) + || merged_extended(color) => { Some(color) } - // A color the draw's instance keeps out of its subpass, written through the storage - // form as a fetched one is. - OutputRole::RenderTarget { - attachment: AbiInt::Const(color), - index: 0, - .. - } if interlock && v.interlocked_colors.contains(&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(match interlock { - true => crate::pipeline::lower_inputs::FramebufferFetchInputs::of( - read, - d.color_attachments, - d.depth_or_stencil, - d.alpha_to_coverage, - d.max_vertex_amplification_count, - ), - false => crate::pipeline::lower_inputs::FramebufferFetchInputs::of( - read, - d.color_attachments, - false, - false, - 1, - ), - }) + 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 @@ -2826,7 +2772,7 @@ fn lower_inputs( )); out.unattached_colors = unattached_colors_written(spec, d.color_attachments, d.alpha_to_coverage); - out.framebuffer_fetch = fetch_inputs(spec, d, variant, p); + 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; @@ -3239,37 +3185,9 @@ fn lower_bounded( // count's) are the product's. let writes_memory = crate::spirv::requirements::writes_memory(&module)?; // A fragment function's texture slots read only at the fragment's own pixel. - let mut own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?; + let own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?; // The levels of its bound view each texture slot's reads reach. let level_reads = crate::spirv::requirements::level_reads(&module, m)?; - // Those a draw can read through a snapshot an earlier draw of the same primitives took, of a - // function that writes no memory, and why each other one is left out. A variant compiled to - // read them so states its own, and judges none: its only texel access of each is the entry's - // copy, at the fragment's own pixel. - let snapshots: Vec = plan.families.fragment.snapshot.keys().copied().collect(); - let snapshot_textures = match snapshots.is_empty() { - false => { - if !crate::spirv::requirements::snapshot_copies_alone(&module, &snapshots, m)? { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - "a snapshot variant that reads its texture outside the copy", - ))); - } - own_pixel_textures.extend(&snapshots); - own_pixel_textures.sort_unstable(); - own_pixel_textures.dedup(); - crate::spirv::requirements::Judged { - slots: snapshots, - refusals: Vec::new(), - } - } - true => crate::spirv::requirements::snapshot_textures( - &module, - &own_pixel_textures, - writes_memory, - m, - )?, - }; // A `half` rounded through `OpQuantizeToF16` (`QuantizeForm::Device`): the module records the // native note on every profile, a result below the smallest normal half the device's. let mut precision = plan.precision.clone(); @@ -3365,7 +3283,7 @@ fn lower_bounded( &function_tables, (reaches_command_buffers, command_writes), (writes_textures, numbered_samplers), - (own_pixel_textures, snapshot_textures, level_reads), + (own_pixel_textures, level_reads), unbound, ); let mut requirements = module.requirements.clone(); @@ -3533,11 +3451,7 @@ fn stage_interface( function_tables: &std::collections::BTreeSet, (reaches_command_buffers, command_writes): (bool, crate::pipeline::interface::CommandWrites), (writes_textures, numbered_samplers): (bool, Vec), - (own_pixel_textures, snapshots, level_reads): ( - Vec, - crate::spirv::requirements::Judged, - Vec, - ), + (own_pixel_textures, level_reads): (Vec, Vec), unbound: unbound::Unbound, ) -> StageInterface { use crate::pipeline::interface::{BufferKind, BufferSlot}; @@ -3603,8 +3517,6 @@ fn stage_interface( unbound_storage_textures: unbound.storage_textures, numbered_samplers, own_pixel_textures, - snapshot_textures: snapshots.slots, - snapshot_refusals: snapshots.refusals, level_reads, private_bytes: plan.private_bytes, sampler_arrays: crate::lower::sampler::sampler_arrays(plan), diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 48c155c5a..d183a5bac 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -24,7 +24,7 @@ use crate::budget::{Budget, Meter}; use crate::cache::VariantKey; -use crate::device::requirements::{Requirements, VkExtension, VkFeature, VkLimit, VkProperty}; +use crate::device::requirements::{Requirements, VkExtension, VkFeature, VkLimit}; use crate::device::{mechanism, Device, DeviceProfile}; use crate::error::{ ComputePipelineProblem, DescriptorError, Error, Feature, InternalError, InternalKind, @@ -51,7 +51,7 @@ use crate::pipeline::descriptor::{ RenderPipelineDescriptor, StageSource, TileRenderPipelineDescriptor, }; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::graphics::{GraphicsState, StorageAttachmentView}; +use crate::pipeline::graphics::GraphicsState; use crate::pipeline::link::tessellation::{note_evaluation_stage, synthesized_stages}; use crate::pipeline::link::{link, LinkInputs, Linked, RenderLinkInputs}; use crate::pipeline::lower_inputs::LoweringInputs; @@ -101,8 +101,9 @@ pub struct RenderPipelineKeys { 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 it reads where the device orders framebuffer - /// fetch only through the pixel interlock). `None` for a `Compiled` fragment stage or none. + /// 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. pub fragment_inputs: Option, } @@ -447,8 +448,7 @@ impl Device { // Every fragment function is decoded, to learn which colors it writes that the // pipeline has no attachment for, as `compile_render_pipeline` and a mesh // pipeline's fragment learn them; and so which signed-integer attachments it - // writes, which attachments it reads on a device that orders framebuffer fetch only - // through the pixel interlock, and whether it reads the `[[viewport_array_index]]` + // writes, and whether it reads the `[[viewport_array_index]]` // or `[[render_target_array_index]]` its vertex function writes. Some(source @ StageSource::Function(f)) => { // Whether the function applies the private masks itself shows only in its @@ -575,15 +575,9 @@ impl Device { v: &VariantKey, m: &mut Meter, ) -> Result { - // A mesh draw's plan zeroes and drops no color, nor writes one through the interlock it - // does not fetch, nor shadows one. - if !v.zeroed_colors.is_empty() - || !v.dropped_colors.is_empty() - || !v.interlocked_colors.is_empty() - { - return Err(invariant( - "a mesh variant zeroing, dropping, interlocking or shadowing colors", - )); + // A mesh draw's plan zeroes and drops no color. + if !v.zeroed_colors.is_empty() || !v.dropped_colors.is_empty() { + return Err(invariant("a mesh variant zeroing or dropping colors")); } check_mesh_fields(d)?; let p = self.profile(); @@ -969,7 +963,6 @@ impl Device { graphics.sample_mask = crate::pipeline::private_state::sample_mask( d, fragment.as_ref().map(|f| f.artifact()), - &graphics, )?; crate::pipeline::private_state::alpha_tested(d, fragment.as_ref().map(|f| f.artifact()))?; crate::pipeline::private_state::depth_compares_clamped( @@ -979,7 +972,6 @@ impl Device { crate::pipeline::private_state::logic_operated( logic, fragment.as_ref().map(|f| f.artifact()), - &graphics, )?; let logic_op = crate::pipeline::private_state::LogicDraw::vulkan(logic); graphics.logic_op = logic_op; @@ -1093,13 +1085,6 @@ fn graphics_requirements( requirements .features .extend(graphics.dynamic_state_features()?); - // A pipeline that reads through snapshots samples a color attachment of its subpass in the - // feedback loop layout, created with its flag (`GraphicsState::snapshot_reads`). - if graphics.snapshot_reads { - requirements - .features - .insert(VkFeature::AttachmentFeedbackLoopLayout); - } // Its color blend state: attachments that blend differently, dual-source blending. requirements .features @@ -1146,46 +1131,6 @@ fn graphics_requirements( .features .insert(VkFeature::RasterizationOrderColorAttachmentAccess); } - // The interlocked form's storage views of the attachments; the module's own requirements name - // the interlock and the fragment stores. - for a in &graphics.storage_attachments { - requirements.formats.extend(a.format_usages()); - } - // The shader-side stencil's shadow; the module's own requirements name the interlock, the - // fragment stores, and multisampled storage images. A multisampled shadow is copied by image - // copies (`maintenance8`), and it, or the neutral that stands in for it without a stencil - // attachment, is a storage image of the pipeline's samples. - if let Some(s) = &graphics.shadow_stencil { - requirements.formats.extend(s.format_usages()); - if s.samples > 1 { - requirements.features.insert(VkFeature::Maintenance8); - } - } - let multisampled_shadow = artifacts.iter().any(|a| { - a.facts.iter().any(|f| { - matches!( - f, - RuntimeFact::ShadowStencil { - multisampled: true, - .. - } - ) - }) - }); - // A per-sample framebuffer fetch's multisampled storage images have the pipeline's - // samples; planes are single-sample. - let multisampled_storage = graphics - .storage_attachments - .iter() - .any(|a| a.view == StorageAttachmentView::Attachment) - && graphics.rasterization_samples.as_raw() > 1; - if multisampled_shadow || multisampled_storage { - requirements - .properties - .insert(VkProperty::StorageImageSampleCount( - graphics.rasterization_samples.as_raw(), - )); - } // 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. @@ -1691,8 +1636,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result assert_eq!( - (u.feature, u.needs), - (Feature::FramebufferFetch, Needs::NotImplemented) - ), - other => panic!("{:?}", other.map(|_| ())), - } - let mut without = interlocked.clone(); without.features.remove(&INTERLOCK); - let pipe = compile(&without, DevicePolicy::RESIDENT_TABLES, &d).expect("neither"); - assert!(unordered(&pipe)); - assert_eq!(pipe.graphics.input_attachments.len(), 1); - assert!(pipe.graphics.storage_attachments.is_empty()); - assert!(!pipe.graphics.rasterization_order_attachment_access); - for f in [ORDERED, INTERLOCK] { - assert!(!pipe.requirements.features.contains(&f), "{f:?}"); - } - let mut grouped = d.clone(); - grouped.fragment = Some(StageSource::Function(FunctionDescriptor::new( - Library::from_air(&fetch) - .expect("library") - .function("fetch_ordered") - .expect("fragment"), - ))); - let pipe = compile(&interlocked, DevicePolicy::RESIDENT_TABLES, &grouped).expect("grouped"); - assert!(!unordered(&pipe)); - assert!(pipe.requirements.features.contains(&INTERLOCK)); - let pipe = - compile(&without, DevicePolicy::RESIDENT_TABLES, &grouped).expect("grouped, neither"); - assert!(unordered(&pipe)); - assert_eq!(pipe.graphics.input_attachments.len(), 1); - for f in [ORDERED, INTERLOCK] { - assert!(!pipe.requirements.features.contains(&f), "{f:?}"); + for desc in [&interlocked, &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:?}"); + } + } } } @@ -2041,10 +1962,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.storage_attachments.is_empty(), - "{fragment} {format:?}" - ); assert!(!pipe.graphics.rasterization_order_attachment_access); assert!( (pipe.layout.sets.iter()) @@ -2102,80 +2019,20 @@ fn images_and_sample_id(words: &[u32]) -> (Vec<(u32, u32, u32)>, bool) { (images, sample_id) } -/// The guard of the one storage write in `words` where a returned sample mask's bit gates it: -/// `Some(shift)` where the write's block is the true arm of a branch on -/// `((mask >> shift) & 1) != 0`, `shift` the shift's constant (`Some(0)` where no shift is left), -/// or `None` where the shift is not a constant (the invocation's `SampleId`); `None` where no -/// such branch guards the write. -fn mask_gate(words: &[u32]) -> Option> { - const IMAGE_WRITE: u32 = 99; - const CONSTANT: u32 = 43; - const I_NOT_EQUAL: u32 = 171; - const SHIFT_RIGHT_LOGICAL: u32 = 194; - const BITWISE_AND: u32 = 199; - const LABEL: u32 = 248; - const BRANCH_CONDITIONAL: u32 = 250; - let mut defs = std::collections::HashMap::new(); - let (mut branches, mut writes, mut label) = (Vec::new(), Vec::new(), 0); - let mut at = 5; - while at < words.len() { - let (count, op) = ((words[at] >> 16) as usize, words[at] & 0xFFFF); - let inst = &words[at..at + count.max(1)]; - match op { - CONSTANT | I_NOT_EQUAL | SHIFT_RIGHT_LOGICAL | BITWISE_AND => { - defs.insert(inst[2], (op, &inst[3..])); - } - LABEL => label = inst[1], - BRANCH_CONDITIONAL => branches.push((inst[1], inst[2])), - IMAGE_WRITE => writes.push(label), - _ => {} - } - at += count.max(1); - } - let def = |id: &u32, want: u32| match defs.get(id) { - Some(&(op, operands)) if op == want => Some(operands), - _ => None, - }; - let constant = |id: &u32| def(id, CONSTANT).and_then(|v| v.first().copied()); - let [write] = writes.as_slice() else { - return None; - }; - let (condition, _) = branches.iter().find(|(_, arm)| arm == write)?; - let [bit, zero] = def(condition, I_NOT_EQUAL)? else { - return None; - }; - let [shifted, one] = def(bit, BITWISE_AND)? else { - return None; - }; - if (constant(zero), constant(one)) != (Some(0), Some(1)) { - return None; - } - Some(match def(shifted, SHIFT_RIGHT_LOGICAL) { - Some([_, shift]) => constant(shift), - _ => Some(0), - }) -} - /// 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): on -/// lavapipe through a multisampled `SubpassData` image under rasterization-order access, on a -/// device that orders fetch only through the pixel interlock through a multisampled storage image -/// of the pipeline's samples (`shaderStorageImageMultisample`, `storageImageSampleCounts`), and, -/// where that device has no multisampled storage image (ANV, MoltenVK), through planes: a -/// single-sample 2D-array storage image of one layer per sample, which needs neither. Where the -/// device lacks what the form needs, the refusal names it; a returned sample mask is exact per -/// sample (the storage write is gated on the sample's bit) and at one sample (gated on bit 0, as -/// Metal stores); `[[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. +/// 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 +/// 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] fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { - use crate::device::requirements::{VkFeature, VkProperty}; - use crate::error::{Capability, Unsupported}; - use crate::pipeline::{RenderPipeline, StorageAttachmentView}; + use crate::device::requirements::VkFeature; + use crate::error::Capability; + use crate::pipeline::{PrecisionNote, RenderPipeline}; const ORDERED: VkFeature = VkFeature::RasterizationOrderColorAttachmentAccess; const SUBPASS_DATA: u32 = 6; - const D2: u32 = 1; let (Some(io), Some(blend), Some(ms)) = ( fixture("stage_io"), fixture("exf_fetch_blend"), @@ -2218,161 +2075,44 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() { Err(Error::Unsupported(u)) => (u.feature, u.needs), other => panic!("{:?}", other.map(|_| ())), }; + let unordered = |pipe: &RenderPipeline| { + pipe.stages[1] + .precision_notes + .contains(&PrecisionNote::UnorderedFetchWithinDraw) + }; - // Raster order: the input attachment's own sample. + // The input attachment's own sample, ordered where the device orders it. let lavapipe = description("lavapipe"); - let pipe = compile(&lavapipe, &descriptor(&blend, "exf_fetch_blend", 4)).expect("lavapipe"); - assert_eq!(pipe.graphics.input_attachments.len(), 1); - assert!(pipe.graphics.storage_attachments.is_empty()); - assert!(pipe.graphics.rasterization_order_attachment_access); - assert_eq!( - pipe.graphics.rasterization_samples, - vk::SampleCountFlags::COUNT_4 - ); - for f in [ORDERED, VkFeature::SampleRateShading] { - assert!(pipe.requirements.features.contains(&f), "{f:?}"); - } - assert_eq!( - images_and_sample_id(&fragment_words(&pipe)), - (vec![(SUBPASS_DATA, 0, 1)], true) - ); - let one = compile(&lavapipe, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one"); - assert_eq!( - images_and_sample_id(&fragment_words(&one)), - (vec![(SUBPASS_DATA, 0, 0)], false) - ); - // The returned mask and alpha to coverage stay the fixed function's. - compile(&lavapipe, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out"); - - // The pixel interlock: a multisampled storage image of the pipeline's samples. - let mut interlocked = lavapipe.clone(); - interlocked.features.remove(&ORDERED); - let pipe = compile(&interlocked, &descriptor(&blend, "exf_fetch_blend", 4)).expect("storage"); - assert!(pipe.graphics.input_attachments.is_empty()); - let [s] = pipe.graphics.storage_attachments.as_slice() else { - panic!("{:?}", pipe.graphics.storage_attachments); - }; - assert_eq!( - (s.color_index, s.format, s.writes, s.view), - ( - 0, - vk::Format::R32G32B32A32_SFLOAT, - true, - StorageAttachmentView::Attachment - ) - ); - for f in [ - VkFeature::FragmentShaderPixelInterlock, - VkFeature::ShaderStorageImageMultisample, - VkFeature::SampleRateShading, - ] { - assert!(pipe.requirements.features.contains(&f), "{f:?}"); - } - assert!(pipe - .requirements - .properties - .contains(&VkProperty::StorageImageSampleCount(4))); - assert_eq!( - images_and_sample_id(&fragment_words(&pipe)), - (vec![(D2, 0, 1)], true) - ); - let one = compile(&interlocked, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one"); - assert_eq!( - images_and_sample_id(&fragment_words(&one)), - (vec![(D2, 0, 0)], false) - ); - assert!(!one - .requirements - .properties - .contains(&VkProperty::StorageImageSampleCount(1))); - // A returned mask (`msf_fetch_mask_out` returns 0x5) gates the write on the invocation's own - // sample's bit; at one sample, where no `SampleId` is read, on bit 0, as Metal stores no color - // without it (before, refused `NotImplemented(FramebufferFetch)`). - let four = compile(&interlocked, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out"); - assert_eq!( - images_and_sample_id(&fragment_words(&four)), - (vec![(D2, 0, 1)], true) - ); - assert_eq!(mask_gate(&fragment_words(&four)), Some(None)); - let one = compile(&interlocked, &descriptor(&ms, "msf_fetch_mask_out", 1)).expect("one mask"); - let [s] = one.graphics.storage_attachments.as_slice() else { - panic!("{:?}", one.graphics.storage_attachments); - }; - assert_eq!( - (s.color_index, s.writes, s.view), - (0, true, StorageAttachmentView::Attachment) - ); - assert_eq!( - images_and_sample_id(&fragment_words(&one)), - (vec![(D2, 0, 0)], false) - ); - assert_eq!(mask_gate(&fragment_words(&one)), Some(Some(0))); - // Without multisampled storage images: planes, one single-sample layer per sample, which - // need neither the feature nor a sample count of storage images. ANV and MoltenVK. - let mut no_storage_ms = interlocked.clone(); - no_storage_ms - .features - .remove(&VkFeature::ShaderStorageImageMultisample); - no_storage_ms.limits.storage_image_sample_counts = vk::SampleCountFlags::COUNT_1; - for desc in [ - &no_storage_ms, - &description("moltenvk-m3"), - &description("intel-arl-anv"), - ] { - let pipe = compile(desc, &descriptor(&blend, "exf_fetch_blend", 4)).expect("planes"); - let [s] = pipe.graphics.storage_attachments.as_slice() else { - panic!("{:?}", pipe.graphics.storage_attachments); - }; + let mut unordered_device = lavapipe.clone(); + unordered_device.features.remove(&ORDERED); + for (desc, ordered) in [(&lavapipe, true), (&unordered_device, false)] { + 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_eq!( - (s.color_index, s.format, s.writes, s.view), - ( - 0, - vk::Format::R32G32B32A32_SFLOAT, - true, - StorageAttachmentView::SamplePlanes { layers: 4 } - ) + pipe.graphics.rasterization_samples, + vk::SampleCountFlags::COUNT_4 ); - for f in [ - VkFeature::FragmentShaderPixelInterlock, - VkFeature::SampleRateShading, - ] { - assert!(pipe.requirements.features.contains(&f), "{f:?}"); - } - assert!(!pipe + assert!(pipe .requirements .features - .contains(&VkFeature::ShaderStorageImageMultisample)); - assert!(!pipe - .requirements - .properties - .iter() - .any(|p| matches!(p, VkProperty::StorageImageSampleCount(_)))); + .contains(&VkFeature::SampleRateShading)); + assert_eq!(pipe.requirements.features.contains(&ORDERED), ordered); assert_eq!( images_and_sample_id(&fragment_words(&pipe)), - (vec![(D2, 1, 0)], true) + (vec![(SUBPASS_DATA, 0, 1)], true) ); - compile(desc, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out"); let one = compile(desc, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one"); - assert_eq!( - one.graphics.storage_attachments[0].view, - StorageAttachmentView::Attachment - ); assert_eq!( images_and_sample_id(&fragment_words(&one)), - (vec![(D2, 0, 0)], false) + (vec![(SUBPASS_DATA, 0, 0)], false) ); + // The returned mask and alpha to coverage stay the fixed function's. + compile(desc, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out"); } - let mut no_count = interlocked.clone(); - no_count.limits.storage_image_sample_counts = vk::SampleCountFlags::COUNT_1; - assert_eq!( - compile(&no_count, &descriptor(&blend, "exf_fetch_blend", 4)).map(|_| ()), - Err(Error::Unsupported(Unsupported::needs( - Feature::FramebufferFetch, - Capability::Property(VkProperty::StorageImageSampleCount(4)) - ))) - ); // Without sample-rate shading no form reads a sample. - for desc in [&lavapipe, &interlocked, &no_storage_ms] { + for desc in [&lavapipe, &unordered_device] { let mut no_rate = desc.clone(); no_rate.features.remove(&VkFeature::SampleRateShading); let (feature, needs) = @@ -2387,7 +2127,7 @@ 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, &interlocked, &no_storage_ms] { + for desc in [&lavapipe, &unordered_device] { assert_eq!( refusal(compile(desc, &descriptor(&ms, "msf_fetch_mask_in", 4))), (Feature::PixelCoverageAtSampleRate, Needs::NotRepresentable) @@ -3019,221 +2759,6 @@ fn the_interface_states_the_textures_read_at_the_fragments_own_pixel() { assert_eq!(checks.len(), 2, "both read checks"); } -/// The interface states why it leaves an own-pixel slot out of those a draw can read through a -/// snapshot (`StageInterface::snapshot_refusals`, `spirv::requirements::snapshot`): owned fixture -/// `snapshot_discard`'s `sd_read_discarding`, which discards by the texel it read, states none on -/// the Radeon 780M's profile, where the discard demotes the invocation and the slot qualifies, and -/// its branch alone where the profile withholds `shaderDemoteToHelperInvocation` and the discard -/// ends the invocation; `tob_renders`'s `tob_read` states none on either. The stage module of a -/// render pipeline of it states the same. -#[test] -fn the_interface_states_why_a_slot_takes_no_snapshot() { - use crate::device::requirements::VkFeature; - use crate::pipeline::interface::SnapshotRefusal; - let (Some(discarding), Some(reading)) = (fixture("snapshot_discard"), fixture("tob_renders")) - else { - return; - }; - let demotes = device("amd-780m-radv"); - let mut d = description("amd-780m-radv"); - assert!( - (d.features).remove(&VkFeature::ShaderDemoteToHelperInvocation), - "the 780M's profile demotes" - ); - let ends = Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).expect("device"); - for (name, dev, refusals) in [ - ("demote", &demotes, Vec::new()), - ("no demote", &ends, vec![(0, SnapshotRefusal::Branch)]), - ] { - let p = dev.profile(); - let a = crate::pipeline::testing::compile(&discarding, "sd_read_discarding", p) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(a.interface.own_pixel_textures, [0u32], "{name}"); - let slots: &[u32] = if refusals.is_empty() { &[0] } else { &[] }; - assert_eq!(a.interface.snapshot_textures, slots, "{name}"); - assert_eq!(a.interface.snapshot_refusals, refusals, "{name}"); - let read = crate::pipeline::testing::compile(&reading, "tob_read", p) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(read.interface.snapshot_textures, [0u32], "{name}: tob_read"); - assert!( - read.interface.snapshot_refusals.is_empty(), - "{name}: tob_read" - ); - let rect = Library::from_air(&reading).expect("library"); - let rect = rect.function("tob_rect").expect("vertex"); - let discard = Library::from_air(&discarding).expect("library"); - let discard = discard.function("sd_read_discarding").expect("fragment"); - let mut d = - RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(rect))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new(discard))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( - metal::PixelFormat::RGBA8Unorm, - )); - let pipe = (dev.compile_render_pipeline(&d, &Budget::standard())) - .unwrap_or_else(|e| panic!("{name}: {e}")); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - assert_eq!(fragment.snapshot_textures, slots, "{name}: the stage"); - assert_eq!(fragment.snapshot_refusals, refusals, "{name}: the stage"); - } -} - -/// A selection on the texel a fragment read at its own pixel keeps the slot where a helper -/// invocation may take either arm (`spirv::requirements::snapshot`'s `arms`): owned fixture -/// `snapshot_select`'s `ss_read_selecting`, whose arm halves the red, states none on the Radeon -/// 780M's profile and on lavapipe's; `ss_read_selecting_dfdx`, whose arm also takes a derivative, -/// and `wlk_readers`'s `wlk_read_branch`, whose texel decides a loop's trip count, state their -/// branch. -#[test] -fn a_selection_on_the_texel_keeps_the_slot_where_a_helper_may_take_either_arm() { - use crate::pipeline::interface::SnapshotRefusal; - let (Some(selecting), Some(looping)) = (fixture("snapshot_select"), fixture("wlk_readers")) - else { - return; - }; - for stem in ["amd-780m-radv", "lavapipe"] { - let p = crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES) - .expect("profile"); - for (bc, entry, refusals) in [ - (&selecting, "ss_read_selecting", Vec::new()), - ( - &selecting, - "ss_read_selecting_dfdx", - vec![(0, SnapshotRefusal::Branch)], - ), - ( - &looping, - "wlk_read_branch", - vec![(0, SnapshotRefusal::Branch)], - ), - ] { - let a = crate::pipeline::testing::compile(bc, entry, &p) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); - assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem} {entry}"); - let slots: &[u32] = if refusals.is_empty() { &[0] } else { &[] }; - assert_eq!(a.interface.snapshot_textures, slots, "{stem} {entry}"); - assert_eq!(a.interface.snapshot_refusals, refusals, "{stem} {entry}"); - } - } -} - -/// The interface states the own-pixel slots a draw can read through a snapshot -/// (`spirv::requirements::snapshot`): `tob_read`'s, whose texel reaches only its output. Its -/// snapshot variant (`LoweringInputs::snapshot_textures`) links and validates on every profile with -/// the pixel interlock, which it requires; binds the slot's snapshot; places the phase in the -/// fragment window; still states the slot, as read at the own pixel and through a snapshot; and -/// writes no memory of the function's. A profile without the interlock refuses it, naming the -/// feature. A variant asked for `tob_sample`'s slot, which the fact does not list, would sample the -/// texture beside the copy: refused, never compiled so. -#[test] -fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() { - use crate::device::requirements::VkFeature; - use crate::error::Capability; - use crate::pipeline::interface::PushLoc; - use crate::pipeline::sym::{PushField, ResourceKind, SlotClass, SlotRef, SnapshotForm, Stage}; - let Some(bc) = fixture("tob_renders") else { - return; - }; - let inputs = |form: SnapshotForm| { - let mut inputs = LoweringInputs::new(); - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 0, - }; - inputs.snapshot_textures.insert(slot, form); - inputs - }; - let mut interlocked = 0; - for stem in [ - "intel-irisxe-anv", - "nvidia-rtx5080-laptop", - "amd-780m-radv", - "lavapipe", - "moltenvk-m3", - "runtime-floor", - ] { - let p = crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES) - .expect("profile"); - let base = crate::pipeline::testing::compile(&bc, "tob_read", &p) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(base.interface.snapshot_textures, [0u32], "{stem}"); - let sampled = crate::pipeline::testing::compile(&bc, "tob_sample", &p) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!(sampled.interface.snapshot_textures.is_empty(), "{stem}"); - let variant = crate::pipeline::testing::compile_with( - &bc, - "tob_read", - &p, - &inputs(SnapshotForm::Bits), - ); - if !p.fields().fragment.pixel_interlock { - assert_eq!( - variant.map(|_| ()), - Err(Error::Unsupported(crate::error::Unsupported::needs( - Feature::RasterOrderGroups, - Capability::Feature(VkFeature::FragmentShaderPixelInterlock), - ))), - "{stem}" - ); - continue; - } - interlocked += 1; - // Each form of a float slot's codes compiles, its copy alone reading the texture. - for form in [ - SnapshotForm::Unorm8, - SnapshotForm::Snorm8, - SnapshotForm::Unorm16, - SnapshotForm::Snorm16, - SnapshotForm::Half, - ] { - let narrow = crate::pipeline::testing::compile_with(&bc, "tob_read", &p, &inputs(form)) - .unwrap_or_else(|e| panic!("{stem} {form:?}: {e}")); - assert_eq!( - narrow.interface.snapshot_textures, - [0u32], - "{stem} {form:?}" - ); - } - let a = variant.unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(a.interface.snapshot_textures, [0u32], "{stem}"); - assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem}"); - assert!(!a.interface.writes_memory, "{stem}"); - assert!( - a.interface - .descriptors - .iter() - .any(|d| d.slot.kind == ResourceKind::SnapshotTexels(0)), - "{stem}" - ); - assert!( - a.interface.push.fields.iter().any(|f| { - f.field == PushField::SnapshotPhase && matches!(f.loc, PushLoc::Push { .. }) - }), - "{stem}" - ); - assert!( - a.requirements - .features - .contains(&VkFeature::FragmentShaderPixelInterlock), - "{stem}" - ); - crate::pipeline::testing::link_and_validate(&a, &p) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - match crate::pipeline::testing::compile_with( - &bc, - "tob_sample", - &p, - &inputs(SnapshotForm::Bits), - ) { - Err(Error::Internal(e)) if e.kind == InternalKind::Invariant => {} - other => panic!("{stem} tob_sample: {other:?}"), - } - } - assert!(interlocked >= 4, "the interlocked profiles"); -} - /// The interface states whether the function writes memory another invocation or a later command /// can read: a buffer store, an image write (through an argument buffer's handle too), in a /// fragment function or a kernel alike; a function that only reads does not, nor does one that only diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index a3ee93a86..98be8ba3d 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -4,8 +4,6 @@ //! their values, and `device::mechanism(fact, profile)` is a total function with one [`Mechanism`] //! per (fact, profile). -use crate::air::container::Hash256; - use crate::pipeline::sym::{ImageHandleClass, SlotRef, Stage}; /// Translation-relevant state that Metal binds at pipeline or encode time. @@ -124,24 +122,6 @@ pub enum RuntimeFact { /// buffer slot the pipeline writes may be bound overlapping its window: instantiation checks /// the Metal addresses (`BindError::UniformViewAliased`). UniformViewAliasing { slot: SlotRef }, - /// The fragment function reads or writes the render pass's imageblock, whose cells take - /// `words` 32-bit words per pixel (`air.imageblock_data_size` rounded up to a word): the - /// consumer binds the pass's imageblock storage (`SyntheticBinding::Imageblock`), which - /// `GraphicsState::fragment_imageblock` describes. `writes`: the function writes the - /// imageblock, so the storage holds its write before the pipeline's coverage (alpha to - /// coverage) could drop the fragment (the depth and stencil tests run before its write: its - /// module declares early tests, or it states [`TestedStorageWrites`](Self::TestedStorageWrites)); - /// `master`: the fingerprint of the master - /// layout its views view (`FragmentImageblock::master`); `data_size`: the cell's bytes - /// (`air.imageblock_data_size`); `alignment`: the alignment Metal states for its views - /// (`air.arg_type_align_size`, `FragmentImageblock::alignment`). - FragmentImageblock { - words: u32, - writes: bool, - master: Hash256, - data_size: u32, - alignment: u32, - }, /// The kernel is a tile function (`Device::compile_tile_pipeline`): a dispatch covers the /// render pass's render area (`BindState::render_area`, `SpecKey::RenderAreaWidth` and /// `SpecKey::RenderAreaHeight`) in tiles of the imageblock size (`BindState::imageblock_size`), @@ -228,52 +208,6 @@ pub enum RuntimeFact { /// one). A slot read only this way needs no acceleration-structure descriptor, so no ray /// tracing feature. AccelerationStructureInstanceCount { slot: SlotRef }, - /// The function reads color attachment `color`, and writes it when `writes`, as a storage - /// image inside the ordered pixel interlock: framebuffer fetch on a device that orders it - /// only that way (no `rasterizationOrderColorAttachmentAccess`, with - /// `fragmentShaderPixelInterlock`), where its render pipeline's state - /// (`LoweringInputs::framebuffer_fetch`) lets the form be exact - /// (`GraphicsState::storage_attachments`). `format` is the attachment's Vulkan format, which - /// the module's storage image declaration serves. `early_tests`: the module declares early - /// fragment tests: Metal's function declares them, or its pipeline state has a depth or - /// stencil attachment and they keep its writes Metal's (it runs no discard, exports no depth, - /// stencil, or coverage, and writes no other memory), or its draws' tests write nothing - /// (`TestedStorageWrites`). Link checks the form against the pipeline it links into: one whose - /// state would not choose it, would view another format, or needs early tests the module does - /// not declare (a depth or stencil attachment where it was compiled without one, but for - /// `TestedStorageWrites`) is `NeedsInput(FramebufferFetch)`. `kept`: the format's channels each - /// write keeps from the texel it overwrites, those outside the descriptor's write mask, which - /// the write takes from the texel it reads first (all four where the mask covers none of the - /// format's channels, so it stores nothing; empty where it covers every one, or the function - /// does not write the attachment); a pipeline of another mask is `NeedsInput(FramebufferFetch)` - /// too. `blend`: the blend the function computes in the shader, from the texel it reads first, - /// for an extended-range attachment it writes under blending, which the function then need not - /// read, or a 16-bit float one (Metal's blend in the output's arithmetic); a pipeline of another - /// blend there is `NeedsInput(FramebufferFetch)` too. `rounded`: that blend is computed - /// without fast math, each product rounded before the sum - /// (`lower::arith::extended_range::blend::BlendMath::Rounded`), whose model holds blends the - /// fast one refuses; link checks the blend under that math. - InterlockedFramebufferFetch { - color: u32, - format: crate::vk::Format, - writes: bool, - early_tests: bool, - kept: crate::vk::ColorComponentFlags, - blend: Option, - rounded: bool, - }, - /// The function's `[[stencil]]` output is a shader-side stencil: on a device without - /// `VK_EXT_shader_stencil_export`, with the ordered pixel interlock, the function applies - /// Metal's stencil test and operations to a shadow of the stencil attachment inside the - /// interlock (`SyntheticBinding::ShadowStencil`, `PushField::ShadowStencilState`) and kills a - /// fragment that fails (`GraphicsState::shadow_stencil`). `formatless`: the module declares - /// the shadow without a format (`Unknown`), else as `R8ui`. `multisampled`: compiled for a - /// pipeline of more than one sample (`LoweringInputs::multisampled`), the shadow is a - /// multisampled image and the function tests each sample of its coverage. - ShadowStencil { - formatless: bool, - multisampled: bool, - }, /// The kernel's predicated walk votes in a workgroup word of its own /// (`lower::simd::divergent::VOTE_BYTES`, 4 bytes beside its threadgroup arena): it runs a /// workgroup barrier that part of the workgroup skips in the source in every invocation, and @@ -406,10 +340,9 @@ pub enum RuntimeFact { /// The tile function declares an explicit imageblock that stands alone (no implicit one /// beside it, and not aliased onto one), of `data_size` bytes (`air.imageblock_data_size`) /// whose layout aligns to `alignment` (`air.arg_type_align_size`). Its cells are the render - /// pass's imageblock storage (`SyntheticBinding::Imageblock`), which the pass's fragment - /// functions' imageblocks are in and the consumer keeps for the pass: a dispatch whose plan - /// writes `WriteSource::Imageblock` binds it, and the pass's draws and dispatches share it - /// by its bytes. With the color attachments it gives the tile pipeline state's + /// pass's imageblock storage (`SyntheticBinding::Imageblock`), which the consumer keeps for + /// the pass: a dispatch whose plan writes `WriteSource::Imageblock` binds it, and the pass's + /// dispatches share it by its bytes. With the color attachments it gives the tile pipeline state's /// `imageblockSampleLength` as a fragment function's explicit imageblock does (measured on an /// M4). TileImageblock { data_size: u32, alignment: u32 }, @@ -479,49 +412,6 @@ pub enum RuntimeFact { /// through its device address (`VariantKey::addressed_function_tables`). `addressed` states /// that this compile is that variant. FunctionTableRange { addressed: bool }, - /// The fragment function stores some channels of a color attachment through the interlocked - /// storage form (`InterlockedFramebufferFetch`) in a pipeline with a depth or stencil - /// attachment, and discards, but declares no `[[early_fragment_tests]]`, exports no depth, - /// stencil, or coverage, and writes no other memory: Metal tests its fragments after it runs, - /// so whether its write stores is the draw's depth and stencil tests' to decide. Without - /// `early_tests` its module stores before Vulkan's tests, Metal's store wherever the draw's - /// tests drop no fragment; with it (`LoweringInputs::read_only_tests`) the module declares - /// early fragment tests, Metal's store wherever they write neither attachment and count no - /// visibility result. The plan of a draw whose tests drop fragments asks for the variant with - /// `early_tests` where they write and count nothing (`VariantKey::read_only_tests`), and - /// refuses any other (`BindShape::fragment_tests`). - /// - /// `early_variant`: whether that variant serves a draw whose tests drop fragments but write and - /// count nothing, which it does for a function that only its discard keeps from early tests. A - /// function that writes other memory, or returns depth, stencil, or a sample mask, beside a - /// depth or stencil attachment states the fact without it: Metal runs its memory writes for the - /// fragments its tests then drop, and tests what it returns, which early tests would not. Its - /// stores before the tests are Metal's only where the draw's tests drop no fragment, and the - /// plan refuses every other draw. - TestedStorageWrites { - early_tests: bool, - early_variant: bool, - }, - /// On a device that orders framebuffer fetch only through the ordered pixel interlock, the - /// fragment function writes - /// a color through its first output and does not declare early fragment tests, and it - /// discards, writes other memory, or returns depth, stencil, or a sample mask. A draw may move - /// such a color into the interlocked storage form (`BindShape::interlocked_colors`), whose - /// variant then stores before the - /// depth and stencil tests and states [`TestedStorageWrites`](Self::TestedStorageWrites) with - /// this `early_variant`, where the write stores something. So the plan of a pipeline that - /// writes no color so selects the tests of such a draw from this as from that fact, and the - /// variant it names plans itself. - /// - /// The plan reads it only for a draw that moves a color the function writes as an ordinary - /// output under a write mask that names some of the attachment's components (and only where - /// the pipeline has a depth or stencil attachment, whose tests the variant then depends on). A - /// write whose mask names none of them stores nothing: no test bears on it, its variant states - /// no store before the tests, and the plan selects none for it, as for a draw that moves - /// nothing. A draw whose tests neither the early-tests variant nor the function's own tests - /// serve (tests the draw does not state) is refused, as any draw whose variant is refused: the - /// runtime keeps the color out of the storage form there (the pass splits, or the shadow ends). - MovableStorageWrites { early_variant: bool }, /// The tile function reads a builtin whose answer depends on its pipeline's /// `threadgroupSizeMatchesTileSize` (its threads per threadgroup, simdgroups or quadgroups /// per threadgroup or their `dispatch_` forms, its position in the grid, the threads per @@ -864,7 +754,6 @@ impl RuntimeFact { RuntimeFact::StageInStride { .. } => "StageInStride", RuntimeFact::UniformViewRange { .. } => "UniformViewRange", RuntimeFact::UniformViewAliasing { .. } => "UniformViewAliasing", - RuntimeFact::FragmentImageblock { .. } => "FragmentImageblock", RuntimeFact::TileFunction => "TileFunction", RuntimeFact::TileAttachmentFormat { .. } => "TileAttachmentFormat", RuntimeFact::StorageTextureNumericType { .. } => "StorageTextureNumericType", @@ -876,8 +765,6 @@ impl RuntimeFact { RuntimeFact::AccelerationStructureInstanceCount { .. } => { "AccelerationStructureInstanceCount" } - RuntimeFact::InterlockedFramebufferFetch { .. } => "InterlockedFramebufferFetch", - RuntimeFact::ShadowStencil { .. } => "ShadowStencil", RuntimeFact::PredicationVote => "PredicationVote", RuntimeFact::SrgbTexture { .. } => "SrgbTexture", RuntimeFact::UlongAtomicView { .. } => "UlongAtomicView", @@ -905,8 +792,6 @@ impl RuntimeFact { RuntimeFact::RotatedWeights => "RotatedWeights", RuntimeFact::ConstantLanes { .. } => "ConstantLanes", RuntimeFact::FunctionTableRange { .. } => "FunctionTableRange", - RuntimeFact::TestedStorageWrites { .. } => "TestedStorageWrites", - RuntimeFact::MovableStorageWrites { .. } => "MovableStorageWrites", RuntimeFact::TileThreadgroup { .. } => "TileThreadgroup", RuntimeFact::ConstexprSampled { .. } => "ConstexprSampled", RuntimeFact::CubicSampler { .. } => "CubicSampler", diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index 87e837705..c7da0d89c 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -7,9 +7,7 @@ use std::collections::BTreeSet; -use crate::air::container::Hash256; use crate::device::requirements::{VkFeature, VkProperty}; -use crate::device::DeviceProfile; use crate::error::{ Attachment, Capability, Error, Feature, InternalError, InternalKind, Unsupported, }; @@ -62,9 +60,8 @@ pub struct GraphicsState { /// `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 the feature but with - /// `fragmentShaderPixelInterlock` takes no input attachment: a fetch there is the interlocked - /// storage form or refused. A device with neither reads them without this flag: the consumer + /// 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 @@ -87,10 +84,6 @@ pub struct GraphicsState { /// its stages are the synthesized vertex and tessellation control stages, then the function's /// evaluation stage, then the fragment stage. pub tessellation: Option, - /// The render pass's fragment imageblock, when the fragment function reads or writes it: the - /// consumer binds the pass's imageblock storage to every draw of the pass - /// (`WriteSource::Imageblock`). - pub fragment_imageblock: Option, /// The vertex function (a post-tessellation vertex function included) writes memory /// (`StageInterface::writes_memory`): each run of the pipeline's vertex stage repeats its /// side effects. A rate-mapped pass drawn region by region records each draw once per region, @@ -108,26 +101,6 @@ pub struct GraphicsState { /// one, and the runtime refuses it. #[cfg_attr(feature = "serde", serde(default))] pub writes_viewport_index: bool, - /// The color attachments the fragment function reads, and may write, as storage images - /// inside the ordered pixel interlock (framebuffer fetch on a device without - /// `rasterizationOrderColorAttachmentAccess`): each such attachment's entry of - /// `color_attachments` is `None`, its subpass color reference is `VK_ATTACHMENT_UNUSED`, and - /// the consumer binds a 2D view of the attachment's image as a storage image - /// (`WriteSource::TileAttachment`) in `GENERAL` layout, over the pixels of the render pass; in - /// a pipeline of more than one sample the image has `rasterization_samples` samples, or, where - /// the attachment's `view` is [`StorageAttachmentView::SamplePlanes`], the consumer binds a - /// 2D-array view of a single-sample image of one layer per sample in its place. See - /// [`StorageAttachmentUse`] for the consumer contract. - #[cfg_attr(feature = "serde", serde(default))] - pub storage_attachments: Vec, - /// The fragment function's `[[stencil]]` output is a shader-side stencil over a shadow of - /// the pass's stencil attachment: on a device without `VK_EXT_shader_stencil_export`, the - /// function applies Metal's stencil test and operations itself, inside the ordered pixel - /// interlock. `None` for every other pipeline, and for one whose pass has no stencil - /// attachment (the function then tests nothing, as Metal's output reaches no attachment). - /// See [`ShadowStencilUse`] for the consumer contract. - #[cfg_attr(feature = "serde", serde(default))] - pub shadow_stencil: Option, /// A render pipeline variant that draws its lines as bands of triangles /// (`VariantKey::line_band`, `pipeline::link::band`): its `topology` is `PATCH_LIST` (never /// dynamic), its stages the vertex stage, the band's synthesized tessellation control and @@ -176,9 +149,7 @@ pub struct GraphicsState { pub fragment_writes_memory: bool, /// The color attachments the fragment function may write, as a mask: bit `n` for color /// attachment `n`. Each attachment that a first (`[[color(n)]]`, index 0) output of the - /// function names is set, whether the function writes it through an output variable or, for - /// an attachment it reads in the interlocked storage form, through its storage image. It is - /// decided from the stage's outputs, which come from the AIR's output metadata of the entry its + /// function names is set. It is decided from the stage's outputs, which come from the AIR's output metadata of the entry its /// function constants specialized, never from names. /// /// An attachment not set is one the function never writes: @@ -211,15 +182,6 @@ pub struct GraphicsState { /// or declares `[[early_fragment_tests]]` does; the consumer then passes no mask. #[cfg_attr(feature = "serde", serde(default))] pub sample_mask: Option, - /// The fragment function reads textures through snapshots (`VariantKey::snapshot_textures`): - /// each draw of the pipeline is drawn twice in its subpass, the texture's attachment in - /// `VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`, first with every color write mask 0, - /// then with the pipeline's own (`PushHole::SnapshotPhase`), which it sets for every color - /// blend element: `dynamic_states` holds `VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`. The consumer - /// creates the pipeline with `VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`. Its - /// requirements name `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`. - #[cfg_attr(feature = "serde", serde(default))] - pub snapshot_reads: bool, /// `VkPipelineColorBlendStateCreateInfo::logicOp` with `logicOpEnable`: the descriptor's /// private `logicOperation` /// ([`PrivateRenderState::logic_operation`](crate::pipeline::PrivateRenderState::logic_operation)), @@ -364,11 +326,8 @@ impl GraphicsState { max_vertex_amplification_count: 1, declares_layer: false, tessellation: None, - fragment_imageblock: None, vertex_writes_memory: false, writes_viewport_index: false, - storage_attachments: Vec::new(), - shadow_stencil: None, line_band: None, writes_point_size: false, writes_depth: false, @@ -377,7 +336,6 @@ impl GraphicsState { fragment_writes_memory: false, color_outputs: 0, sample_mask: None, - snapshot_reads: false, logic_op: None, } } @@ -570,9 +528,6 @@ fn dynamic_state_feature(state: vk::DynamicState) -> Result, E // `VK_EXT_extended_dynamic_state2`'s first feature (core in Vulkan 1.3 without one), made // dynamic only where the profile has it. D::PRIMITIVE_RESTART_ENABLE => Some(VkFeature::ExtendedDynamicState2), - // `VK_EXT_extended_dynamic_state3`'s color write masks, dynamic only in a pipeline that - // reads through snapshots (`GraphicsState::snapshot_reads`). - D::COLOR_WRITE_MASK_EXT => Some(VkFeature::ExtendedDynamicState3ColorWriteMask), other => { return Err(Error::Internal(InternalError::new( InternalKind::Invariant, @@ -585,56 +540,6 @@ fn dynamic_state_feature(state: vk::DynamicState) -> Result, E }) } -/// How a render pipeline's fragment function reaches the render pass's imageblock. -/// -/// Metal keeps a fragment imageblock in tile memory: per pixel, for the whole render pass, its -/// contents undefined when the pass begins, and every pipeline of the pass that declares -/// `[[imageblock_data]]` sees the same bytes at its layout's offsets. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct FragmentImageblock { - /// The representation the profile's capabilities chose. - pub mechanism: ImageblockMechanism, - /// The 32-bit words of each pixel's cell the function reaches: the pass's storage needs at - /// least this many, and the largest over the pass's pipelines. - pub words: u32, - /// The fingerprint of the master layout the fragment function's views view: SHA-256 over - /// its data size and the layout's Merkle digest (SHA-256 over each member's offset, size, - /// array length, user key, and nested layout's digest). Equal fingerprints are structurally - /// equal masters. A view of another master of the same `data_size` and `alignment` in the - /// same pass reaches the same bytes at its own offsets, as each layout's words in the storage - /// hold them (measured on an M3 Max and an M4 without Metal's API validation, which stops - /// such a pass); which bytes one of another size or alignment reaches is not read in full, so a - /// consumer refuses such a pass (the translator sees one pipeline at a time and cannot). - pub master: Hash256, - /// The bytes of a cell (`air.imageblock_data_size`). - pub data_size: u32, - /// The alignment Metal states for the fragment function's views (`air.arg_type_align_size`: - /// their master layout's). With `data_size` it gives Metal's `imageblockSampleLength` of the - /// pipeline (measured on an M3 Max): `data_size` plus the bytes its color attachments pack to, - /// rounded up to 8 and then to `alignment`. - pub alignment: u32, -} - -/// The representation of a fragment imageblock. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ImageblockMechanism { - /// One coherent `R32Uint` 2D-array storage image per render pass instance: layer `w` holds - /// word `w` of the cell of pixel `(x, y)` at texel `(x, y)`, the pixel's framebuffer - /// coordinate (`FragCoord`). The fragment function reads its input view and writes its - /// output view inside the ordered pixel-interlock critical section - /// (`fragmentShaderPixelInterlock`), which orders overlapping fragments of the pass in - /// primitive order across draws, as Metal's raster order groups do. The consumer creates the - /// image with `STORAGE` usage, an extent covering the pass's render area's offset plus its - /// extent (texel `(x, y)` is framebuffer pixel `(x, y)`, not relative to the area), and at - /// least `words` layers, keeps it in `GENERAL` layout for the whole pass, binds it to every - /// draw of the pass, and draws only pipelines of one `master` in the pass. - StorageImageInterlock, -} - /// One color attachment's format, write mask, and blend state. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -715,271 +620,6 @@ impl BlendState { } } -/// A color attachment a render pipeline's fragment function reads, and may write, as a storage -/// image inside the ordered pixel interlock (`GraphicsState::storage_attachments`). -/// -/// The draw orders every fragment's read, body, and write of a pixel after the earlier fragments -/// of the pixel in primitive order, across draws and instances of the subpass, as Metal orders -/// framebuffer fetch. The consumer: -/// -/// - leaves the attachment out of the color attachments of every subpass a pipeline that names -/// it draws in (its color reference there is `VK_ATTACHMENT_UNUSED`): an image a subpass -/// writes as an attachment is no storage image of the same subpass; -/// - binds the image `view` names, in `format` with the identity mapping, as the plan's -/// `WriteSource::TileAttachment { color_index, format, view }` (which carries the same `view`), -/// in `GENERAL` layout, texel `(x, y)` being framebuffer pixel `(x, y)` (so the image covers -/// the render area's offset plus its extent): -/// - [`StorageAttachmentView::Attachment`]: a 2D view of the attachment's own image, of the -/// render pass's layer and level, the image created with `STORAGE` usage (beside its own). -/// In a pipeline of more than one sample that image is the pass's multisampled attachment, -/// of the pipeline's `GraphicsState::rasterization_samples`, the one sample count of the -/// pipeline and its storage images, and the fragment function runs once per covered sample, -/// reading and writing its own sample; the pipeline's requirements name -/// `shaderStorageImageMultisample` and the count's `storageImageSampleCounts` bit; -/// - [`StorageAttachmentView::SamplePlanes`] `{ layers }` (a pipeline of more than one sample -/// on a device without multisampled storage images): a 2D-array view -/// (`VK_IMAGE_VIEW_TYPE_2D_ARRAY`) of all `layers` layers of the attachment's sample planes, -/// a single-sample 2D-array image the consumer keeps beside the attachment, of `format`, with -/// `STORAGE` usage and `layers` (the pipeline's `rasterization_samples`) layers, never a 2D -/// view and never the multisampled attachment itself. The fragment function runs once per -/// covered sample and reads and writes sample `s` of pixel `(x, y)` at texel `(x, y)` of -/// layer `s`, so the planes need no multisampled storage image and no -/// `storageImageSampleCounts` bit. The consumer fills layer `s` from sample `s` of the -/// attachment's image before the draws (no copy changes a sample count, so a per-sample -/// shader read does), and after them writes layer `s` back into sample `s` (a sample-rate -/// pass that writes only its own sample), or, where the pass resolves the attachment or the -/// attachment is memoryless, resolves from the planes as Metal resolves the samples; -/// - makes earlier writes of the image visible to the fragment shader's storage reads before -/// the draws (a color attachment write of an earlier subpass or pass, a transfer, a load -/// operation), and the fragment shader's storage writes visible to later uses after them. -/// -/// A pass of more than one layer, and an amplified draw, are not implemented: the binder refuses -/// them. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct StorageAttachmentUse { - pub color_index: u32, - /// The attachment's format, which the storage view takes. - pub format: vk::Format, - /// The fragment function writes the attachment (otherwise it only reads it). - pub writes: bool, - /// The function declares the storage image without a format (`Unknown`), so the view's - /// format ([`view_format`](Self::view_format)) supports storage reads (and, when `writes`, - /// writes) without one (`VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT` and its write - /// twin); otherwise the declaration names the view's format's SPIR-V image format. - pub formatless: bool, - /// The image the consumer binds and how it views it: the attachment's own image, or its - /// sample planes (see the type's docs). The plan's `WriteSource::TileAttachment` carries the - /// same value. - #[cfg_attr(feature = "serde", serde(default))] - pub view: StorageAttachmentView, - /// Where `Some`, the storage view is in this format, not in `format`, which stays the - /// attachment's own ([`view_alias_of`](Self::view_alias_of) decides it from `format` and the - /// device): - /// - /// - an 8-bit sRGB attachment's unsigned-integer format of its texel size (`R32_UINT` for a - /// 4-byte texel): its format has no storage access, and the function unpacks the texels in - /// `format`'s byte order and decodes and encodes them itself, by Metal's measured - /// conversions; - /// - a BGRA-order attachment's RGBA-order twin (`R8G8B8A8_UNORM` for `B8G8R8A8_UNORM`, - /// `A2B10G10R10_UNORM_PACK32` for `A2R10G10B10_UNORM_PACK32`) on a device that neither - /// reads nor writes `format` without a format (SPIR-V names no image format for it): the - /// function exchanges red and blue on every read and write, and the device converts each - /// channel as it converts `format`'s. - /// - /// The consumer binds such a view of an image made with `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT` - /// (and `VK_IMAGE_CREATE_EXTENDED_USAGE_BIT` where `format` has no storage access), whose - /// `VkImageFormatListCreateInfo` lists `format` and this format, with `STORAGE` usage (the - /// sample planes of [`StorageAttachmentView::SamplePlanes`] in this format); its draws that - /// do not fetch render the image through a view in `format`. `None` for any other format, and - /// on a device that accesses a BGRA-order format without one: the view is in `format`. - #[cfg_attr(feature = "serde", serde(default, alias = "uint_view"))] - pub view_alias: Option, - /// The channels the function's write keeps from the texel it reads first, by the pipeline's - /// write mask: empty where it does not write the attachment or the mask covers every channel of - /// the format, all four where it covers none of them (the write stores nothing), else those of - /// the format the mask leaves out. One module serves every write mask that keeps some of a - /// format's channels (a blended 8-bit unorm attachment with alpha: each of alpha alone, one - /// color channel, and more): the binder writes these into each draw's push bytes, where the - /// function reads them. Nothing for the consumer to do. - #[cfg_attr(feature = "serde", serde(default))] - pub kept: vk::ColorComponentFlags, -} - -/// The image a storage view of a color attachment binds, and how it is viewed -/// (`StorageAttachmentUse::view`, `WriteSource::TileAttachment`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum StorageAttachmentView { - /// A 2D view (`VK_IMAGE_VIEW_TYPE_2D`) of the attachment's own image, of the pass's layer - /// and level: single-sample in a pass of one sample, of the pass's samples in a multisampled - /// pass. - #[default] - Attachment, - /// A 2D-array view (`VK_IMAGE_VIEW_TYPE_2D_ARRAY`) of every layer of the attachment's sample - /// planes: a single-sample 2D-array image of `layers` layers (the pipeline's - /// `rasterization_samples`), layer `s` holding sample `s` of each pixel, which the consumer - /// fills from the multisampled attachment before the draws and writes back (or resolves) - /// after them. - SamplePlanes { layers: u32 }, -} - -impl StorageAttachmentUse { - /// Color attachment `color_index` of `format` bound as a storage image through `view`, written - /// where `writes`, declared without a format where `formatless`. - pub fn new( - color_index: u32, - format: vk::Format, - writes: bool, - formatless: bool, - view: StorageAttachmentView, - ) -> StorageAttachmentUse { - StorageAttachmentUse { - color_index, - format, - writes, - formatless, - view, - view_alias: None, - kept: vk::ColorComponentFlags::empty(), - } - } - - /// The use whose write keeps `kept` from the texel ([`kept`](Self::kept)). - pub fn with_kept(self, kept: vk::ColorComponentFlags) -> StorageAttachmentUse { - StorageAttachmentUse { kept, ..self } - } - - /// The use with its storage view in `view_alias` ([`view_alias`](Self::view_alias)). - pub fn with_view_alias(self, view_alias: vk::Format) -> StorageAttachmentUse { - StorageAttachmentUse { - view_alias: Some(view_alias), - ..self - } - } - - /// The format of the storage view: [`view_alias`](Self::view_alias) where it is set, else - /// `format`. - pub fn view_format(&self) -> vk::Format { - self.view_alias.unwrap_or(self.format) - } - - /// The format other than `format` a fetching draw views a color attachment of `format` in, - /// where a fragment function reads it in the storage form on `profile` - /// ([`view_alias`](Self::view_alias)): `R32_UINT` for `B8G8R8A8_SRGB` and `R8G8B8A8_SRGB`, - /// `R16_UINT` for `R8G8_SRGB` and `R8_UINT` for `R8_SRGB`, on every device; `R8G8B8A8_UNORM` - /// for `B8G8R8A8_UNORM` and `A2B10G10R10_UNORM_PACK32` for `A2R10G10B10_UNORM_PACK32` where - /// the device neither reads nor writes the attachment's format without a format, and stores - /// the twin and declares it (without a format, or by its SPIR-V image format, - /// `shaderStorageImageExtendedFormats` for an extended one); `None` for any other format and - /// device. The compile layer and a consumer that makes an attachment's image before it knows - /// the pipeline (a memoryless attachment's backing, a render target's free usage) both take - /// it from here, so the image is made mutable to the view the pipeline binds. The compile - /// layer sets an sRGB view only where it builds the form (today the four-byte formats). - pub fn view_alias_of(format: vk::Format, profile: &DeviceProfile) -> Option { - crate::metal::format::fetch_view_alias(format, profile) - } - - /// The format usages the consumer's image and view need: `StorageImage` of the view's - /// format, and the without-format accesses of a formatless declaration. - pub(crate) fn format_usages( - &self, - ) -> Vec<(vk::Format, crate::device::requirements::FormatUsage)> { - use crate::device::requirements::FormatUsage as U; - let view = self.view_format(); - let mut out = vec![(view, U::StorageImage)]; - if self.formatless { - out.push((view, U::StorageImageReadWithoutFormat)); - if self.writes { - out.push((view, U::StorageImageWriteWithoutFormat)); - } - } - out - } -} - -/// A render pipeline whose fragment function's `[[stencil]]` output is a shader-side stencil -/// (`GraphicsState::shadow_stencil`). -/// -/// Metal tests and writes the stencil with the function's output as the reference of both faces -/// (its low 8 bits): `(r & readMask) cmp (s & readMask)`, then `s' = (s & ~writeMask) | -/// (op(s, r) & writeMask)`, before the depth test, per sample in primitive order. Without -/// `VK_EXT_shader_stencil_export` no fixed-function state takes a per-fragment reference, so the -/// function does it: inside the ordered pixel interlock it reads the pixel's value from a shadow -/// of the stencil, applies the face's test and operation from the encoder's state -/// (`BindState::depth_stencil`, written as `PushField::ShadowStencilState`), writes the shadow, -/// and kills a fragment that fails. A discarded fragment changes nothing. The depth test stays -/// fixed-function, after the function. In a pipeline of more than one sample the shadow holds -/// each sample, the function tests each sample of its coverage, and its `SampleMask` output keeps -/// the samples that pass. -/// -/// The consumer, for each draw with such a pipeline: -/// -/// - creates the pipeline with the stencil test disabled (`stencilTestEnable` false, or -/// `vkCmdSetStencilTestEnable(false)` where the pipeline makes it dynamic): the function is the -/// test, and the attachment's stencil is not written during the draw; -/// - keeps the shadow: a 2D image of `format` and `samples` samples (the pipeline's) with -/// `STORAGE` and transfer usage, of the stencil attachment's extent, whose texel `(x, y)` (each -/// sample) is framebuffer pixel `(x, y)` (that sample), bound in `GENERAL` layout as the plan's -/// `WriteSource::ShadowStencil`; -/// - copies the stencil into the shadow before the draw and back after it, outside the render -/// pass: of one sample, `vkCmdCopyImageToBuffer` of the attachment's stencil aspect (one byte -/// per texel) then `vkCmdCopyBufferToImage` into the shadow, and the reverse afterwards; of more, -/// `vkCmdCopyImage` between the stencil aspect and the shadow, both ways, which -/// `VK_KHR_maintenance8`'s depth/stencil-to-color copies allow (no buffer copy takes a -/// multisampled image; the pipeline requires `maintenance8` then). A render pass instance -/// that holds such a draw is therefore split around it: end the pass, copy in, begin it again -/// loading every attachment, draw, end it, copy out, and begin it again. Consecutive such draws -/// share one copy in and one copy out while nothing else writes the stencil between them. Each -/// copy needs its barriers: attachment writes before the copy out of the stencil, the copy into -/// the shadow before the fragment shader's storage reads and writes, those before the copy -/// back, and that copy before the next attachment access; -/// - sets `BindState::depth_stencil` to the encoder's `MTLDepthStencilDescriptor` for the draw. -/// The binder refuses a state whose stencil write could depend on the depth test, typed as -/// needing the extension: a depth attachment, a depth comparison other than `Always`, and a -/// face whose depth-failure operation differs from its pass operation. The stencil references -/// are unused (the function's output is the reference of both faces), and the front face is the -/// pipeline's, from the encoder's winding. -/// -/// The split costs a render pass instance per such draw (or run of draws). Synchronizing the -/// shadow inside the pass (an input-attachment read of the stencil under a feedback-loop layout, -/// and an in-pass write-back) would avoid it; that is a possible later optimisation, not part of -/// this contract. -/// -/// An amplified draw and a pass of more than one layer are not implemented: the binder refuses -/// them. Alpha to coverage, which changes a fragment's samples before Metal's stencil test, is -/// refused at link as needing the extension. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ShadowStencilUse { - /// The shadow's format, `R8_UINT`. - pub format: vk::Format, - /// The function declares the shadow without a format (`Unknown`), so the format supports - /// storage reads and writes without one (`VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT` - /// and its write twin); otherwise the declaration names `R8ui`. - pub formatless: bool, - /// The shadow's samples: the pipeline's rasterization samples. - pub samples: u32, -} - -impl ShadowStencilUse { - /// The format usages the consumer's shadow image and view need: `StorageImage`, and the - /// without-format accesses of a formatless declaration. - pub(crate) fn format_usages( - &self, - ) -> Vec<(vk::Format, crate::device::requirements::FormatUsage)> { - use crate::device::requirements::FormatUsage as U; - let mut out = vec![(self.format, U::StorageImage)]; - if self.formatless { - out.push((self.format, U::StorageImageReadWithoutFormat)); - out.push((self.format, U::StorageImageWriteWithoutFormat)); - } - out - } -} - /// 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 diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index c2f5b75ce..30ad78a74 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -351,8 +351,8 @@ pub struct StageInterface { /// a buffer or a texture, or updates one atomically (`spirv::requirements::writes_memory`). /// Metal runs a multisampled fragment function with such a side effect once per covered /// sample. The `ExecutionStatus` buffer's words, which the resident-miss count updates, are not - /// the function's, nor a color's interlocked storage form's or `half` shadow's, which carry - /// Metal's color attachment write. + /// the function's, nor a tile function's color attachment's, which carry Metal's color + /// attachment write. #[cfg_attr(feature = "serde", serde(default))] pub writes_memory: bool, /// An object or mesh function's payload arena's bytes (`memory::arena::payload_bytes` of its @@ -430,22 +430,6 @@ pub struct StageInterface { /// its helper invocations, clamped as the coordinate is. Empty for every other stage. #[cfg_attr(feature = "serde", serde(default))] pub own_pixel_textures: Vec, - /// Those of `own_pixel_textures` a draw can read through a snapshot an earlier draw of the - /// same primitives took, sorted (`spirv::requirements::snapshot_textures`): no value a fetch - /// of the slot returns reaches, directly or through a call, a derivative, a sample, a quad or - /// subgroup operation, a branch, an integer divisor, a dynamic vector index, or a store other - /// than to a `Function`, `Private` or `Output` variable, so a helper invocation's value of it - /// reaches no fragment's result and gives it no undefined behavior; and the function writes no - /// memory and holds no interlock. Its variant (`LoweringInputs::snapshot_textures`) reads the slot through - /// the snapshot. Empty for every other stage. - #[cfg_attr(feature = "serde", serde(default))] - pub snapshot_textures: Vec, - /// Why each slot of `own_pixel_textures` that `snapshot_textures` leaves out is left out: - /// every [`SnapshotRefusal`] that holds for it, sorted by slot and then by refusal, so a slot - /// may appear more than once. Empty for every other stage, and for a function compiled to read - /// slots through snapshots (`LoweringInputs::snapshot_textures`), which judges none. - #[cfg_attr(feature = "serde", serde(default))] - pub snapshot_refusals: Vec<(u32, SnapshotRefusal)>, /// The levels of its bound view that each texture slot's reads reach, one entry a slot, sorted /// by slot ([`LevelReads`]): what a runtime needs to tell whether a slot whose texture presents /// a color attachment of the draw's render pass instance at some level reads that level. @@ -478,51 +462,6 @@ pub struct SamplerArray { pub samplers: Vec, } -/// What leaves an own-pixel texture slot of a fragment function out of the slots a draw can read -/// through a snapshot an earlier draw of the same primitives took -/// (`StageInterface::snapshot_refusals`, `StageModule::snapshot_refusals`). A helper invocation -/// reads a constant from the snapshot, so the slot is left out where a helper's value of it could -/// reach another invocation's result, give it undefined behavior, or where the snapshot cannot be -/// made beside the function. The first eight say where a value that a fetch of the slot reaches, -/// through any instruction, phi, call, or `Function`, `Private` or `Output` variable, is used. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum SnapshotRefusal { - /// It decides a conditional branch or a switch, but for a selection whose arms leave through - /// its merge alone and hold no derivative, implicit-level sample or level-of-detail query, - /// subgroup or quad operation, loop, or operand undefined at a value that is not a constant, - /// nor call a function that does (a helper may take either of those arms). - Branch, - /// It is an operand of a derivative. - Derivative, - /// It is an operand of a sample, a gather or a level-of-detail query of any image. - Sample, - /// It is an operand of a subgroup or quad operation. - GroupOperation, - /// It is stored to a storage class other than `Function`, `Private` or `Output`, or through - /// a function parameter's pointer. - Store, - /// It is an operand of an atomic. - Atomic, - /// It is an operand of an image write or a texel pointer. - ImageWrite, - /// It is an operand an instruction's behavior is undefined for at some value: an integer - /// divisor, the dividend of a signed division or remainder whose divisor may be `-1`, or a - /// dynamic vector component index. - UndefinedOperand, - /// The function writes memory (`StageInterface::writes_memory`). - WritesMemory, - /// The module holds a fragment interlock critical section. - Interlock, - /// The module has a `Coherent` resource or uses the Vulkan memory model. - Coherent, - /// Anything else: the slot's index is 128 or more, its values take more than 16 passes over - /// the module to settle, or one is an operand of a ray query, a mesh output count or a call - /// whose callee's parameters it does not match, or the entry's returned value. - Other, -} - /// The levels of its bound view that a texture slot's reads reach, each counted from the view's /// first level (`StageInterface::level_reads`, `StageModule::level_reads`), as the module's /// instructions decide them (`spirv::requirements::level_reads`, structural). A sample's level is diff --git a/crates/metal2vulkan/src/pipeline/layout.rs b/crates/metal2vulkan/src/pipeline/layout.rs index db21bca9b..7f4db2555 100644 --- a/crates/metal2vulkan/src/pipeline/layout.rs +++ b/crates/metal2vulkan/src/pipeline/layout.rs @@ -141,9 +141,6 @@ pub enum BindingSource { stage: Stage, sampler: CombinedSampler, }, - /// The snapshot of the texture the draw binds at this fragment texture slot - /// (`ResourceKind::SnapshotTexels`), bound as a storage image. - SnapshotTexels(u32), /// A constexpr sampler array of `stage` (`ResourceKind::SamplerArray`) that samples set-1 /// heap images, made for the use with comparison or without (`compare`) of an integer texture /// or not (`integer`): its samplers are the binding's `immutable_samplers`, which take no diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 44a37fe40..05deac0db 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -40,7 +40,7 @@ //! descriptors; otherwise the same layout is used as a pooled set. //! - **Render state** ([`vertex`], [`graphics`]): `VertexInputState` and `GraphicsState` from the //! descriptor, checked against the vertex stage's compiled fetch projection, with the fragment -//! stage's imageblock ([`imageblock`]) and interlocked framebuffer fetch ([`fetch`]), and the +//! stage's framebuffer fetch over input attachments ([`fetch`]), and the //! precision notes of the formats fixed-function vertex input converts for the vertex stage //! (`vertex::fixed_function_notes`), which the module, shared by every such format, cannot //! record, with the measured properties a conversion relies on in place of a note. A mesh @@ -52,9 +52,7 @@ pub mod band; pub mod contract; pub mod fetch; pub mod graphics; -pub mod imageblock; pub mod mesh; -pub mod stencil; pub mod tessellation; pub mod varyings; pub mod vertex; @@ -517,15 +515,6 @@ fn render_state( ts: Option, p: &DeviceProfile, ) -> Result { - // The imageblock's refusals first: a multisampled imageblock is the specific reason where - // its storage writes would also refuse the sample invocations. - let ib = imageblock::fragment_imageblock(r, fragment)?; - // The interlocked fetch's form against this pipeline's state, before the sample invocations - // its storage writes would also refuse. - let storage = fetch::storage_attachments(r, fragment, p)?; - // The shader-side stencil against this pipeline's state, before the sample invocations its - // shadow writes would also refuse. - let shadow = stencil::shadow_stencil(r, fragment, p)?; // The extended-range blends the fragment computes over input attachments, against this // pipeline's attachments. let input_blends = fetch::input_blends(r, fragment, p)?; @@ -551,22 +540,16 @@ fn render_state( (r.alpha_to_coverage, r.texture_write_rounding_mode), p, )?; - gs.fragment_imageblock = ib; - gs.color_outputs = color_outputs(fs, &storage)?; - gs.storage_attachments = storage; - gs.shadow_stencil = shadow; + gs.color_outputs = color_outputs(fs)?; Ok(gs) } /// The color attachments fragment stage `fs` writes (`GraphicsState::color_outputs`), bit `n` -/// for attachment `n`: those a first (index 0) color output of its function names, and those it -/// writes in the interlocked storage form (`storage`). An index past the mask is no output link -/// admits (`maxFragmentOutputAttachments` and Metal's eight colors are below it). -fn color_outputs( - fs: Option<&StageInterface>, - storage: &[crate::pipeline::graphics::StorageAttachmentUse], -) -> Result { - let outputs = fs +/// for attachment `n`: those a first (index 0) color output of its function names. An index past +/// the mask is no output link admits (`maxFragmentOutputAttachments` and Metal's eight colors are +/// below it). +fn color_outputs(fs: Option<&StageInterface>) -> Result { + let mut outputs = fs .into_iter() .flat_map(|f| &f.io.outputs) .filter_map(|o| match o.role { @@ -576,8 +559,7 @@ fn color_outputs( } => Some(attachment), _ => None, }); - let stored = storage.iter().filter(|s| s.writes).map(|s| s.color_index); - outputs.chain(stored).try_fold(0u32, |mask, color| { + outputs.try_fold(0u32, |mask, color| { 1u32.checked_shl(color) .map(|bit| mask | bit) .ok_or_else(|| { @@ -719,7 +701,6 @@ fn binding_source(slot: ResourceSlot) -> BindingSource { stage: slot.stage, sampler: CombinedSampler::from_heap_index(sampler, slot.index), }, - ResourceKind::SnapshotTexels(texture) => BindingSource::SnapshotTexels(texture), ResourceKind::YCbCrPlanes(_) => BindingSource::YCbCrPlanes(metal(SlotClass::Texture)), ResourceKind::SamplerArray { compare, integer } => BindingSource::SamplerArray { stage: slot.stage, diff --git a/crates/metal2vulkan/src/pipeline/link/band.rs b/crates/metal2vulkan/src/pipeline/link/band.rs index 1b081b46b..1d03ce00a 100644 --- a/crates/metal2vulkan/src/pipeline/link/band.rs +++ b/crates/metal2vulkan/src/pipeline/link/band.rs @@ -384,8 +384,6 @@ impl LineBand { rounded_colors: Vec::new(), specialized_notes: Vec::new(), own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, stats, diff --git a/crates/metal2vulkan/src/pipeline/link/fetch.rs b/crates/metal2vulkan/src/pipeline/link/fetch.rs index ba53fb4fa..df6fcc63d 100644 --- a/crates/metal2vulkan/src/pipeline/link/fetch.rs +++ b/crates/metal2vulkan/src/pipeline/link/fetch.rs @@ -1,28 +1,4 @@ -//! A render pipeline's interlocked framebuffer fetch: `GraphicsState::storage_attachments` from the -//! fragment stage's `RuntimeFact::InterlockedFramebufferFetch`. -//! -//! On a device that orders framebuffer fetch only through the ordered pixel interlock, the fragment -//! function reads each color attachment, and writes it, as a storage image inside the interlock -//! where the pipeline's state lets that form be exact (`lower::fragment`'s `fetch`). The function -//! compiled under its pipeline's state (`LoweringInputs::framebuffer_fetch`); link decides the form -//! again from the state of the pipeline it links into, with the same rule, and a stage whose form, -//! attachment format, kept channels (a write mask short of the format's channels), or in-shader -//! blend (an extended-range or 16-bit float attachment's) that state would not choose (a write -//! before a depth or stencil attachment's tests only where the function states -//! `RuntimeFact::TestedStorageWrites`, which each draw's plan checks) was compiled for another -//! pipeline: `NeedsInput(FramebufferFetch)`. A write mask that keeps some of a format's channels -//! compiles as its class (`FramebufferFetchInputs::of`), so the comparison holds across the masks -//! of a class, and the pipeline's own kept channels go in `StorageAttachmentUse::kept`, which the -//! binder writes into each draw's push bytes. An attachment the function reads in the storage form -//! is no color attachment of the subpass (`graphics_state` gives it no state), and the consumer -//! binds it as `GraphicsState::storage_attachments` states. -//! -//! In a multisampled pipeline the form is per sample. Where the device has multisampled storage -//! images, the image has the pipeline's samples, so the device's `storageImageSampleCounts` must -//! hold that count (`VkProperty::StorageImageSampleCount`), as for the shader-side stencil's -//! shadow; otherwise the fetch is refused naming it. Elsewhere the image holds the samples as -//! planes (`StorageAttachmentView::SamplePlanes`), a single-sample image of one layer per sample, -//! which needs no sample count of storage images. +//! 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 @@ -43,142 +19,17 @@ use std::collections::BTreeMap; -use crate::device::requirements::VkProperty; use crate::device::DeviceProfile; -use crate::error::{ - Capability, Error, Feature, InternalError, InternalKind, RuntimeInput, Unsupported, -}; +use crate::error::{Error, InternalError, InternalKind, RuntimeInput}; use crate::library::FunctionArtifact; -use crate::lower::fragment::{ - inputs_order, interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples, -}; +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::graphics::{StorageAttachmentUse, StorageAttachmentView}; use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs}; +use crate::pipeline::lower_inputs::BlendEquation; use crate::pipeline::stage_io::IoRole; -/// The attachments the fragment stage `fragment` of render inputs `r` reads in the storage form -/// on `p`, by color index (see the module docs). -pub fn storage_attachments( - r: &RenderLinkInputs, - fragment: Option<&FunctionArtifact>, - p: &DeviceProfile, -) -> Result, Error> { - let Some(fragment) = fragment else { - return Ok(Vec::new()); - }; - let reads: Vec<( - u32, - crate::vk::Format, - bool, - bool, - crate::vk::ColorComponentFlags, - (Option, bool), - )> = fragment - .facts - .iter() - .filter_map(|fact| match *fact { - RuntimeFact::InterlockedFramebufferFetch { - color, - format, - writes, - early_tests, - kept, - blend, - rounded, - } => Some((color, format, writes, early_tests, kept, (blend, rounded))), - _ => None, - }) - .collect(); - if reads.is_empty() { - return Ok(Vec::new()); - } - if !interlock_orders(p) { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - "an interlocked framebuffer fetch on a device that orders fetch otherwise", - ))); - } - let inputs = FramebufferFetchInputs::of( - reads.iter().map(|&(color, ..)| color), - &r.color_attachments, - r.depth_format.is_some() || r.stencil_format.is_some(), - r.alpha_to_coverage, - r.max_vertex_amplification_count, - ); - let multisampled = r.raster_sample_count > 1 && r.rasterization_enabled; - // A write before the tests, which each draw's plan checks. - let draw_tested = fragment.facts.iter().any(|f| { - matches!( - f, - RuntimeFact::TestedStorageWrites { - early_tests: false, - .. - } - ) - }); - let mut out = Vec::with_capacity(reads.len()); - let mut multisampled_image = false; - for (color, format, writes, early_tests, kept, (blend, rounded)) in reads { - let math = match rounded { - true => crate::lower::arith::extended_range::blend::BlendMath::Rounded, - false => crate::lower::arith::extended_range::blend::BlendMath::Fast, - }; - let use_ = ColorUse { - writes, - early_tests, - draw_tested, - math, - logic_op: fragment.interface.io.logic_operation, - }; - match storage_form(color, &inputs, multisampled, use_, p)? { - Ok(view) if view.format == format && view.kept == kept && view.blend == blend => { - multisampled_image |= view.samples == StorageSamples::Multisampled; - let view_of = match view.samples { - StorageSamples::One | StorageSamples::Multisampled => { - StorageAttachmentView::Attachment - } - StorageSamples::Planes => StorageAttachmentView::SamplePlanes { - layers: r.raster_sample_count, - }, - }; - // The pipeline's own kept channels, not the class the function compiled under. - let kept = match r.color_attachments.get(color as usize).copied().flatten() { - Some(a) => { - color_write_mask(kept_channels(a.pixel_format, a.write_mask, writes))? - } - None => return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)), - }; - out.push(StorageAttachmentUse { - color_index: color, - format, - writes, - formatless: view.formatless(), - view: view_of, - view_alias: view.uint_view.or(view.rgba_view), - kept, - }); - } - _ => return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)), - } - } - // The per-sample form's multisampled image has the pipeline's samples. - if multisampled_image { - let property = VkProperty::StorageImageSampleCount(r.raster_sample_count); - if !p.fields().enabled.properties.contains(&property) { - return Err(Unsupported::needs( - Feature::FramebufferFetch, - Capability::Property(property), - ) - .into()); - } - } - Ok(out) -} - /// 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 diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index c978aa33f..c81b67b17 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -51,21 +51,18 @@ //! scissor, depth bias, blend constants, and the stencil reference and masks; with extended //! dynamic state also cull mode, front face, topology, the depth/stencil test state, and the //! vertex strides of `PerBind` layouts. -//! - **Storage attachments**: an attachment the fragment stage reads in the interlocked storage -//! form (`ResourceKind::TileAttachment`) has no color attachment state: the subpass leaves it -//! out, and `link::fetch` states how the consumer binds it. //! - **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 -//! an input attachment only on a device without the pixel interlock either -//! (`lower::fragment::color`), whose consumer orders the draws by barriers alone. In a +//! an input attachment ordered between draws alone (`lower::fragment::color`), whose consumer +//! 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 (or, -//! in the storage form, a multisampled storage image) at its `SampleId`, whose input runs it once +//! the pipeline (`LoweringInputs::multisampled`), reads a multisampled `SubpassData` image at +//! its `SampleId`, whose input runs it once //! per covered sample: it is a per-sample function under the sample invocations below. A fetching //! stage compiled for the other kind of pipeline (one sample against more, or the reverse) //! declares an image of the wrong sample count: `NeedsInput(Multisampled)`. A color input the @@ -357,16 +354,6 @@ pub fn graphics_state( }; let written = colors(false); let declared = colors(true); - // An attachment the function reads in the interlocked storage form is no color attachment of - // the subpass (`link::fetch`). - let storage: BTreeSet = fs - .into_iter() - .flat_map(|f| &f.descriptors) - .filter_map(|d| match d.slot.kind { - ResourceKind::TileAttachment(color) => Some(color), - _ => None, - }) - .collect(); // A blend into a bfloat attachment is Metal's pipeline error, whatever the fragment function // writes there and whatever the mask: its pipeline validation asserts that the format is not // blendable (an Apple M3 Max under macOS 27.0.1, with and without the validation layer, with @@ -387,7 +374,6 @@ pub fn graphics_state( for (index, a) in r.color_attachments.iter().take(used as usize).enumerate() { color_attachments.push(match a { None => None, - Some(_) if storage.contains(&(index as u32)) => None, Some(a) => { let state = || -> Result { // A word attachment renders through the view of its word, which the function @@ -499,8 +485,8 @@ pub fn graphics_state( } // 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 orders it in neither form, - // the orderings the merge needs. + // 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); @@ -526,9 +512,9 @@ pub fn graphics_state( (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, in the storage form (no - // color attachment here) or over the input attachment (above): one that - // does not was compiled for another pipeline. Unwritten, it writes nothing. + // 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 => { @@ -537,8 +523,7 @@ pub fn graphics_state( false => None, } } - // Where the device orders fetch in neither form, the orderings that - // blend needs. + // Where the device does not order fetch, the ordering that blend needs. (false, true) if color_writes::rotated_blend_in_shader(a, p) => { return Err( crate::lower::fragment::fetch::unordered_extended_fetch().into() @@ -659,12 +644,12 @@ pub fn graphics_state( } let textured = textured_fetches(r, fs)?; let rasterization_samples = samples(r.raster_sample_count)?; - // A fetched attachment is read (and, in the storage form, written) at the invocation's own + // A fetched attachment is read at the invocation's own // sample by a stage compiled for a multisampled pipeline, and at the pixel by one compiled // for one sample (see the module docs): a stage compiled for the other kind declares an image // of the wrong sample count. if let Some(fs) = fs { - let fetches = !input_attachments.is_empty() || !storage.is_empty() || textured; + let fetches = !input_attachments.is_empty() || textured; if fetches && fs.io.multisampled != (r.raster_sample_count > 1) { return Err(Error::NeedsInput(RuntimeInput::Multisampled)); } @@ -719,15 +704,6 @@ pub fn graphics_state( dynamic_states.push(D::VERTEX_INPUT_BINDING_STRIDE); } } - // A fragment stage that binds a snapshot reads through it, drawn twice with its color write - // masks as dynamic state (`GraphicsState::snapshot_reads`). - let snapshot_reads = fs - .into_iter() - .flat_map(|f| &f.descriptors) - .any(|d| matches!(d.slot.kind, ResourceKind::SnapshotTexels(_))); - if snapshot_reads { - dynamic_states.push(D::COLOR_WRITE_MASK_EXT); - } let state = GraphicsState { topology: match tessellation { Some(_) => vk::PrimitiveTopology::PATCH_LIST, @@ -748,11 +724,6 @@ pub fn graphics_state( max_vertex_amplification_count, declares_layer, tessellation, - // The fragment stage's facts decide it (`link::imageblock`). - fragment_imageblock: None, - // The fragment stage's facts decide them (`link::fetch`). - storage_attachments: Vec::new(), - shadow_stencil: None, vertex_writes_memory: vs.writes_memory, // Stored as the builtin or (on a device with one viewport) nowhere: the raw varying is // written in both. @@ -774,10 +745,9 @@ pub fn graphics_state( reads_barycentric_coord: fs.is_some_and(|fs| reads_barycentric_coord(&fs.io)), reads_primitive_id: fs.is_some_and(|fs| reads_primitive_id(&fs.io)), fragment_writes_memory: fs.is_some_and(|fs| fs.writes_memory), - // The storage form's writes join the outputs' once `link::fetch` decided them. + // The outputs' writes, once the color attachments are decided. color_outputs: 0, sample_mask: None, - snapshot_reads, // The pipeline's private logic operation, once compile decided it // (`private_state::logic_operation`). logic_op: None, @@ -1072,12 +1042,11 @@ fn uniform_blend( /// (`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`): in the interlocked storage form, which leaves the attachment -/// out of the subpass, where the device orders fetch through the pixel interlock, and over the -/// input attachment, whose write the caller makes of every raw component, where it 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 -/// orders it in neither form, the caller names the orderings the merge needs. A bfloat form's channels +/// (`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 /// 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/imageblock.rs b/crates/metal2vulkan/src/pipeline/link/imageblock.rs deleted file mode 100644 index 7fc9af5e3..000000000 --- a/crates/metal2vulkan/src/pipeline/link/imageblock.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! A render pipeline's fragment imageblock: `GraphicsState::fragment_imageblock` from the fragment -//! stage's `RuntimeFact::FragmentImageblock`. -//! -//! The fragment function reads and writes the pass's imageblock storage, one plane of cells per -//! pixel, and per sample in a multisampled pass (`ImageblockMechanism::StorageImageInterlock`), -//! and writes it inside its body. Its depth and stencil tests run before its write: its module -//! declares early tests, or each draw's plan checks them (`RuntimeFact::TestedStorageWrites`, -//! `lower::fragment::imageblock`). Link refuses: -//! -//! - a function compiled for another sample count than the pipeline's (`NeedsInput(Multisampled)`): -//! one compiled for a multisampled pipeline reaches its own sample's cell, one compiled for one -//! sample the pixel's; -//! - as not implemented, a pipeline whose alpha to coverage can drop a fragment after the function -//! wrote its imageblock: Metal drops the write with the fragment (measured on the M3 Max, at one -//! sample and at four), and the storage already holds it. - -use crate::error::{Error, Feature, RuntimeInput, Unsupported}; -use crate::library::FunctionArtifact; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::graphics::{FragmentImageblock, ImageblockMechanism}; -use crate::pipeline::link::RenderLinkInputs; - -/// The fragment imageblock of render inputs `r` whose fragment stage is `fragment` (see the -/// module docs). -pub fn fragment_imageblock( - r: &RenderLinkInputs, - fragment: Option<&FunctionArtifact>, -) -> Result, Error> { - let Some(fragment) = fragment else { - return Ok(None); - }; - let Some((words, writes, master, data_size, alignment)) = - fragment.facts.iter().find_map(|fact| match *fact { - RuntimeFact::FragmentImageblock { - words, - writes, - master, - data_size, - alignment, - } => Some((words, writes, master, data_size, alignment)), - _ => None, - }) - else { - return Ok(None); - }; - if fragment.interface.io.multisampled != (r.raster_sample_count > 1) { - return Err(Error::NeedsInput(RuntimeInput::Multisampled)); - } - if writes && r.alpha_to_coverage { - return Err(Unsupported::not_implemented(Feature::Imageblocks).into()); - } - Ok(Some(FragmentImageblock { - mechanism: ImageblockMechanism::StorageImageInterlock, - words, - master, - data_size, - alignment, - })) -} diff --git a/crates/metal2vulkan/src/pipeline/link/stencil.rs b/crates/metal2vulkan/src/pipeline/link/stencil.rs deleted file mode 100644 index 04b8f9ad1..000000000 --- a/crates/metal2vulkan/src/pipeline/link/stencil.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! A render pipeline's shader-side stencil: `GraphicsState::shadow_stencil` from the fragment -//! stage's `RuntimeFact::ShadowStencil`. -//! -//! On a device without `VK_EXT_shader_stencil_export`, a fragment function's `[[stencil]]` -//! output is tested and written by the function itself against a shadow of the stencil -//! (`lower::fragment`'s `stencil`). Link checks the pipeline's state against the function's form: -//! -//! - the form follows the pipeline's samples: a function compiled for a pipeline of more than one -//! sample (`LoweringInputs::multisampled`) tests each sample of a multisampled shadow, and one -//! linked into a pipeline of another kind is `NeedsInput(Multisampled)`; -//! - a multisampled shadow (or the neutral that stands in for it) is a storage image of the -//! pipeline's samples (`storageImageSampleCounts`), and the consumer copies it to and from the -//! stencil with image copies (`maintenance8`): where the device lacks either, the output is -//! refused naming the extension or what the form lacks; -//! - alpha to coverage changes the fragment's samples before Metal's stencil test, after the -//! function's write: refused as needing the extension; -//! - a pipeline without a stencil attachment states no shadow (Metal's output reaches no -//! attachment): the binder binds a neutral image and the function tests nothing. - -use crate::device::requirements::{VkExtension, VkFeature, VkProperty}; -use crate::device::DeviceProfile; -use crate::error::{Capability, Error, Feature, RuntimeInput, Unsupported}; -use crate::library::FunctionArtifact; -use crate::lower::fragment::SHADOW_FORMAT; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::graphics::ShadowStencilUse; -use crate::pipeline::link::RenderLinkInputs; - -/// The shader-side stencil of the fragment stage `fragment` of render inputs `r` on `p` (see the -/// module docs). -pub fn shadow_stencil( - r: &RenderLinkInputs, - fragment: Option<&FunctionArtifact>, - p: &DeviceProfile, -) -> Result, Error> { - let Some((formatless, multisampled)) = fragment.and_then(|f| { - f.facts.iter().find_map(|fact| match *fact { - RuntimeFact::ShadowStencil { - formatless, - multisampled, - } => Some((formatless, multisampled)), - _ => None, - }) - }) else { - return Ok(None); - }; - if !r.rasterization_enabled { - return Ok(None); - } - let samples = r.raster_sample_count.max(1); - if multisampled != (samples > 1) { - return Err(Error::NeedsInput(RuntimeInput::Multisampled)); - } - if r.alpha_to_coverage { - return Err(Unsupported::needs( - Feature::StencilExport, - Capability::Extension(VkExtension::ExtShaderStencilExport), - ) - .into()); - } - let attached = r.stencil_format.is_some(); - if samples > 1 { - let f = p.fields(); - let mut missing = Vec::new(); - let property = VkProperty::StorageImageSampleCount(samples); - if !f.enabled.properties.contains(&property) { - missing.push(Capability::Property(property)); - } - if attached && !f.enabled.features.contains(&VkFeature::Maintenance8) { - missing.push(Capability::Feature(VkFeature::Maintenance8)); - } - if !missing.is_empty() { - return Err(Unsupported::needs_any_of( - Feature::StencilExport, - vec![ - vec![Capability::Extension(VkExtension::ExtShaderStencilExport)], - missing, - ], - ) - .into()); - } - } - Ok(attached.then_some(ShadowStencilUse { - format: SHADOW_FORMAT, - formatless, - samples, - })) -} diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index 919d90efa..0a779eb56 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -429,8 +429,6 @@ pub fn synthesized_stages( rounded_colors: Vec::new(), specialized_notes: Vec::new(), own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, stats, diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 69f15eed1..1ad45b667 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -136,8 +136,6 @@ pub(super) fn iface( unbound_storage_textures: false, numbered_samplers: Vec::new(), own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, sampler_arrays: Vec::new(), diff --git a/crates/metal2vulkan/src/pipeline/link/tests/render.rs b/crates/metal2vulkan/src/pipeline/link/tests/render.rs index 47a829973..b05c711f9 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests/render.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests/render.rs @@ -1347,138 +1347,6 @@ fn a_framebuffer_fetch_links_into_the_sample_count_it_was_compiled_for() { } } -/// A fragment stage that reads color attachment 0 in the interlocked storage form links into a -/// pipeline whose state chooses that form with the format the stage declares: the attachment is a -/// storage attachment, with no color attachment state and no input attachment. A pipeline whose -/// state chooses otherwise (another format, a blending attachment) did not compile the stage: -/// `NeedsInput(FramebufferFetch)`, and one of more samples did not compile it for its sample count: -/// `NeedsInput(Multisampled)`, and one with a depth attachment did not compile it with early tests. -/// A device that orders fetch otherwise never compiles such a stage. Compiled for more than one -/// sample, the stage reads planes where the device has no multisampled storage image (MoltenVK), -/// which need no sample count of storage images, and the pipeline's multisampled attachment -/// elsewhere (RADV). -#[test] -fn an_interlocked_fetch_links_only_into_the_state_it_was_compiled_for() { - use crate::error::{InternalKind, RuntimeInput}; - use crate::metal::BlendFactor; - use crate::pipeline::descriptor::ColorAttachmentDescriptor; - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::graphics::{StorageAttachmentUse, StorageAttachmentView}; - let p = profile("moltenvk-m3"); - let va = artifact(iface(Stage::Vertex, vec![], vec![]), None); - let fr = Stage::Fragment; - let storage = StageDescriptor::new( - res(fr, ResourceKind::TileAttachment(0), 0), - vk::DescriptorType::STORAGE_IMAGE, - 1, - ); - let mut fa = artifact(iface(fr, vec![storage], vec![]), None); - // Compiled without a depth or stencil attachment: no early tests. - fa.facts.push(RuntimeFact::InterlockedFramebufferFetch { - color: 0, - format: vk::Format::R32_SFLOAT, - writes: true, - early_tests: false, - kept: vk::ColorComponentFlags::empty(), - blend: None, - rounded: false, - }); - // Blending adds the destination: a blend of one and zero, added, stores the source as no - // blending does, and links into the storage form. - let state_with = |format, blending: bool, samples: u32, depth: bool| { - let mut r = RenderLinkInputs::new(); - let mut c = ColorAttachmentDescriptor::new(format); - if blending { - c.blending_enabled = true; - c.destination_rgb_blend_factor = BlendFactor::One; - } - r.color_attachments[0] = Some(c); - r.raster_sample_count = samples; - r.depth_format = depth.then_some(PixelFormat::Depth32Float); - LinkInputs::Render(Box::new(r)) - }; - let state = |format, blending: bool, samples: u32| state_with(format, blending, samples, false); - let g = link(&[&va, &fa], &state(PixelFormat::R32Float, false, 1), &p) - .expect("link") - .graphics - .expect("graphics"); - assert_eq!( - g.storage_attachments, - [StorageAttachmentUse { - color_index: 0, - format: vk::Format::R32_SFLOAT, - writes: true, - // Declared without a format where the device grants that. - formatless: crate::metal::format::accessed_without_format( - vk::Format::R32_SFLOAT, - crate::metal::format::StorageUse::texture(true, true), - &p - ), - view: StorageAttachmentView::Attachment, - view_alias: None, - kept: vk::ColorComponentFlags::empty(), - }] - ); - assert_eq!(g.color_attachments, [None]); - assert!(g.input_attachments.is_empty()); - assert!(!g.rasterization_order_attachment_access); - for other in [ - state(PixelFormat::RGBA8Unorm, false, 1), - state(PixelFormat::R32Float, true, 1), - // Its writes would precede a failed depth test. - state_with(PixelFormat::R32Float, false, 1, true), - ] { - assert_eq!( - link(&[&va, &fa], &other, &p).unwrap_err(), - Error::NeedsInput(RuntimeInput::FramebufferFetch), - "{other:?}" - ); - } - assert_eq!( - link(&[&va, &fa], &state(PixelFormat::R32Float, false, 4), &p).unwrap_err(), - Error::NeedsInput(RuntimeInput::Multisampled) - ); - // Compiled for more than one sample: planes without multisampled storage images. - let mut per_sample = fa.clone(); - per_sample.interface.io.multisampled = true; - per_sample - .interface - .io - .builtins - .push(crate::pipeline::stage_io::StageBuiltin::SampleId); - let radv = profile("amd-rdna3-radv"); - for (p, view) in [ - (&p, StorageAttachmentView::SamplePlanes { layers: 4 }), - (&radv, StorageAttachmentView::Attachment), - ] { - let g = link( - &[&va, &per_sample], - &state(PixelFormat::R32Float, false, 4), - p, - ) - .expect("link") - .graphics - .expect("graphics"); - assert_eq!( - g.storage_attachments - .iter() - .map(|a| a.view) - .collect::>(), - [view] - ); - assert_eq!(g.rasterization_samples, vk::SampleCountFlags::COUNT_4); - } - - match link( - &[&va, &fa], - &state(PixelFormat::R32Float, false, 1), - &profile("lavapipe"), - ) { - Err(Error::Internal(e)) => assert_eq!(e.kind, InternalKind::Invariant), - other => panic!("{other:?}"), - } -} - /// A color attachment that no output of the fragment function names keeps its contents, as Metal /// kept one where measured: its write mask is empty, while every attachment the function writes /// keeps the descriptor's mask and every attachment its blend state. A pipeline without a fragment diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index ce2feb3d6..69d60a0e3 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -17,7 +17,7 @@ use crate::metal; use crate::pipeline::descriptor::{ StageInputDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, }; -use crate::pipeline::sym::{SampledType, SlotRef, SnapshotForm, VaryingKey}; +use crate::pipeline::sym::{SampledType, SlotRef, VaryingKey}; use crate::vk; /// Per-function lowering inputs, public projection. @@ -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, and in the storage form - /// writes, each one's multisampled image at its `SampleId`, running once per covered sample, as + /// that reads its color attachments (`framebuffer_fetch`) 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,20 +131,15 @@ 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 a fragment function's framebuffer fetch takes its form from, on - /// a device that orders a fetch only through the ordered pixel interlock (no - /// `rasterizationOrderColorAttachmentAccess`, with `fragmentShaderPixelInterlock`): there each - /// color attachment the function reads is read, and written, as a storage image inside the - /// interlock where the pipeline's state lets that form be exact, and otherwise is refused. - /// `Device::compile_render_pipeline` - /// sets it for a `Function` fragment stage that declares a `[[color(n)]]` input 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)`. On a device that orders - /// fetch through rasterization-order input attachments, the state of each extended-range - /// attachment the function writes where the pipeline blends it, whose blend the function - /// computes over its input attachment (its depth, coverage and amplification bits unset, - /// which that blend does not read); without it such a function is - /// `NeedsInput(FramebufferFetch)` there too. `None` on every other device and for every other + /// 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, @@ -156,20 +151,6 @@ pub struct LoweringInputs { /// `PrecisionNote::SrgbTexelDecode`. A slot of no such access is ignored. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, - /// Fragment texture slots of `StageInterface::snapshot_textures` the draw reads through a - /// snapshot (`VariantKey::snapshot_textures`), each with its snapshot's form, drawn twice - /// (`PushField::SnapshotPhase`). The entry opens with the ordered pixel interlock's critical - /// section, in which, in the draw that takes the snapshot, a non-helper invocation copies - /// each slot's texel at its pixel into the slot's snapshot (`ResourceKind::SnapshotTexels`), - /// in the slot's form; that draw then returns. In the draw that - /// reads it, the critical section is empty, and every read of the slot reads the snapshot, or - /// nothing in a helper invocation (`lower::fragment`'s `snapshot`). The binder names only slots - /// of that interface fact (`bind::graphics`); for another, the reads are not Metal's. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub snapshot_textures: BTreeMap, /// Texture slots bound to a two-plane YCbCr texture whose planes are read in place /// (`VariantKey::ycbcr_in_place`, `RuntimeFact::YCbCrInPlace`): each is declared as the /// planes' uniform texel buffer, and its samples, reads and size queries read the codes and @@ -492,7 +473,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 stored in the interlocked storage form instead, named in + /// 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 /// 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 @@ -630,14 +611,6 @@ pub struct LoweringInputs { /// `Function` fragment stage. Any other function compiles as with 0. #[cfg_attr(feature = "serde", serde(default))] pub depth_compare_clamp_mask: u32, - /// The depth and stencil tests of the draws that run the fragment function write neither - /// attachment and count no visibility result (`VariantKey::read_only_tests`): a function that - /// stores a color through the interlocked storage form and declares no early tests only - /// because it discards (`RuntimeFact::TestedStorageWrites`) is lowered with early fragment - /// tests, which then drop what Metal's later tests drop and leave the attachments as Metal's - /// do, and states the fact with `early_tests`. Any other function compiles as without it. - #[cfg_attr(feature = "serde", serde(default))] - pub read_only_tests: bool, /// The color attachments the fragment function's render pipeline gives a format held with /// its channels rotated (`metal::format::rotated_channels`, `ARGB8Unorm`), by color index: /// each such attachment's image holds Metal's alpha, red, green and blue in its red, green, @@ -659,7 +632,7 @@ pub struct LoweringInputs { /// red), so alpha to coverage through attachment 0 reads Metal's alpha as Metal's does; a /// color input (`[[color(n)]]`) of one reads the image's red as Metal's alpha, `(0, 0, 0, r)`, /// as Metal reads an `A8Unorm` attachment (probe `a8`'s uses on an M3 Max under macOS - /// 27.0.1), through the input attachment or the interlocked storage form alike. + /// 27.0.1), through the input attachment. /// `Device::compile_render_pipeline` sets it for a `Function` fragment stage from the /// pipeline's color attachments, and link refuses a fragment compiled under another set as /// `NeedsInput(ColorWrites)`. Empty for any other function. @@ -1020,8 +993,9 @@ impl AmplificationDraws { } } -/// The render pipeline state a fragment function's interlocked framebuffer fetch depends on -/// (`LoweringInputs::framebuffer_fetch`). +/// 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))] @@ -1029,26 +1003,14 @@ 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>, - /// The pipeline has a depth or a stencil attachment, whose tests can drop a fragment after - /// its function ran. - pub depth_or_stencil: bool, - /// The descriptor enables alpha to coverage. - pub alpha_to_coverage: bool, - /// The descriptor's `maxVertexAmplificationCount` is above 1: the pipeline may draw - /// multiview. - pub amplified: bool, } impl FramebufferFetchInputs { - /// The state of a pipeline whose color attachments are `colors` (by Metal index), whose depth - /// and stencil formats are `depth` and `stencil`, under `alpha_to_coverage` and - /// `max_vertex_amplification_count`, for a function that declares color inputs at `read`. + /// 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], - depth_or_stencil: bool, - alpha_to_coverage: bool, - max_vertex_amplification_count: u32, ) -> FramebufferFetchInputs { FramebufferFetchInputs { attachments: read @@ -1073,14 +1035,12 @@ impl FramebufferFetchInputs { (color, attachment) }) .collect(), - depth_or_stencil, - alpha_to_coverage, - amplified: max_vertex_amplification_count > 1, } } } -/// What the interlocked framebuffer fetch reads of one color attachment's descriptor. +/// 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))] @@ -1137,28 +1097,6 @@ impl BlendEquation { alpha_operation: c.alpha_blend_operation, }) } - - /// Whether a factor reads the fragment's second output (`[[color(n), index(1)]]`): dual-source - /// blending. - pub(crate) fn reads_second_source(&self) -> bool { - use metal::BlendFactor as F; - [ - self.source_rgb, - self.destination_rgb, - self.source_alpha, - self.destination_alpha, - ] - .into_iter() - .any(|f| { - matches!( - f, - F::Source1Color - | F::OneMinusSource1Color - | F::Source1Alpha - | F::OneMinusSource1Alpha - ) - }) - } } impl LoweringInputs { diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index f191580ad..82dea3ba7 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -117,16 +117,15 @@ pub use descriptor::{ VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; pub use graphics::{ - BandPrimitive, BlendState, ColorAttachmentState, FragmentImageblock, GraphicsState, - ImageblockMechanism, InputAttachmentUse, LineBandState, ShadowStencilUse, StorageAttachmentUse, - StorageAttachmentView, TessellationState, + BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse, + LineBandState, TessellationState, }; pub use indirect_draws::IndirectDrawLayout; pub use interface::{ AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface, - SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, Window, + TextureAccess, TextureSlot, ThreadgroupArgument, Window, }; pub use layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -159,8 +158,7 @@ pub use crate::lower::simd::workgroup::arena_bytes; pub use sym::{ AccelerationStructureLevel, AirUserKey, Axis, CombinedSampler, HandleClass, ImageAccess, ImageDim, ImageHandleClass, PushField, ResourceKind, ResourceSlot, SampledType, SamplerRef, - SlotClass, SlotRef, SnapshotForm, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding, - VaryingKey, + SlotClass, SlotRef, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding, VaryingKey, }; pub use vertex::{PulledAttribute, VertexAttribute, VertexBinding, VertexInputState, VertexStride}; diff --git a/crates/metal2vulkan/src/pipeline/private_state.rs b/crates/metal2vulkan/src/pipeline/private_state.rs index cc90670f0..86d29ae2b 100644 --- a/crates/metal2vulkan/src/pipeline/private_state.rs +++ b/crates/metal2vulkan/src/pipeline/private_state.rs @@ -63,8 +63,8 @@ //! (`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 (the -//! pixel interlock, or rasterization-order input attachments) has the fragment function compute +//! 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`, @@ -77,8 +77,8 @@ //! 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 shadow stencil, an imageblock or a merged word ([`logic_operated`]). A device that -//! orders fetch in neither form refuses the operation naming the features. So is an operation +//! 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 @@ -327,18 +327,15 @@ pub(crate) fn shader_sample_mask( applied_masks(d).filter(|m| !uniform(m) || observes_sample_mask(a)) } -/// [`GraphicsState::sample_mask`] for the pipeline `d`, its fragment function `fragment` and -/// its graphics state `g`, or the refusal where neither Vulkan's mask nor the function's own +/// [`GraphicsState::sample_mask`] for the pipeline `d` and its fragment function `fragment`, or +/// the refusal where neither Vulkan's mask nor the function's own /// (`StageIo::sample_mask`) is Metal's. A function that could tell Vulkan's mask from Metal's, /// or of a pipeline whose masks differ between the places of a quad, applies the masks itself, /// and the pipeline has no Vulkan mask; one compiled without them, or for others, is compiled for -/// the pipeline again (`NeedsInput(SampleMask)`). A pipeline whose fragment function writes an -/// attachment itself (a storage attachment, a shadow stencil or an imageblock, none measured -/// under the masks) is refused, naming the sample coverage where it is not 1. +/// the pipeline again (`NeedsInput(SampleMask)`). pub(crate) fn sample_mask( d: &RenderPipelineDescriptor, fragment: Option<&FunctionArtifact>, - g: &GraphicsState, ) -> Result, Error> { let applied = applied_masks(d); let own = fragment.and_then(|f| f.interface.io.sample_mask); @@ -348,15 +345,6 @@ pub(crate) fn sample_mask( let Some(masks) = applied else { return Ok(None); }; - let writes_itself = !g.storage_attachments.is_empty() - || g.shadow_stencil.is_some() - || g.fragment_imageblock.is_some(); - if writes_itself { - return Err(refused(match d.private.sample_coverage == 1.0 { - true => PrivateRenderField::SampleMask, - false => PrivateRenderField::SampleCoverage, - })); - } match (own, fragment) { (Some(_), _) => Ok(None), (None, Some(f)) if observes_sample_mask(f) || !uniform(&masks) => { @@ -488,14 +476,11 @@ pub(crate) fn logic_operation<'a>( 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::interlock_orders(p) || crate::lower::fragment::inputs_order(p)) - { + if shader && !crate::lower::fragment::inputs_order(p) { return Err(Unsupported::needs_any_of( Feature::PrivateRenderState(PrivateRenderField::LogicOperation), vec![ vec![Capability::Feature(VkFeature::LogicOp)], - vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], vec![Capability::Feature( VkFeature::RasterizationOrderColorAttachmentAccess, )], @@ -549,16 +534,13 @@ pub(crate) fn logic_operation<'a>( /// `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 writes an attachment itself (a storage attachment, a shadow -/// stencil, an imageblock, or a word it merges with its input attachment's) is refused +/// 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)`), and is refused beside a shadow stencil, an imageblock or a -/// merged word, which it does not compute over. +/// else `NeedsInput(LogicOperation)`). pub(crate) fn logic_operated( draw: Option, fragment: Option<&FunctionArtifact>, - g: &GraphicsState, ) -> Result<(), Error> { let compiled = fragment.and_then(|f| f.interface.io.logic_operation); let Some(draw) = draw else { @@ -575,16 +557,12 @@ pub(crate) fn logic_operated( ) }) }); - let beside = g.shadow_stencil.is_some() || g.fragment_imageblock.is_some() || merges; match draw { - LogicDraw::Vulkan(_) if beside || !g.storage_attachments.is_empty() => { - Err(refused(PrivateRenderField::LogicOperation)) - } + LogicDraw::Vulkan(_) if merges => Err(refused(PrivateRenderField::LogicOperation)), LogicDraw::Vulkan(_) => match compiled { Some(_) => Err(Error::NeedsInput(RuntimeInput::LogicOperation)), None => Ok(()), }, - LogicDraw::Shader(_) if beside => Err(refused(PrivateRenderField::LogicOperation)), LogicDraw::Shader(op) => match compiled == Some(op) { true => Ok(()), false => Err(Error::NeedsInput(RuntimeInput::LogicOperation)), diff --git a/crates/metal2vulkan/src/pipeline/rotated_blend.rs b/crates/metal2vulkan/src/pipeline/rotated_blend.rs index fe158abad..8909c9c82 100644 --- a/crates/metal2vulkan/src/pipeline/rotated_blend.rs +++ b/crates/metal2vulkan/src/pipeline/rotated_blend.rs @@ -28,9 +28,8 @@ //! 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`: the interlocked storage form, or over the input -//! attachment); a device that orders fetch in neither form refuses the pipeline naming both -//! orderings. A factor of the second source (Metal's own second output beside one the rotation +//! (`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 //! among Vulkan's factors: it would round apart from the blend's own. diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index 1629e2aca..86b03cd7c 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -157,8 +157,8 @@ pub struct StageIo { #[cfg_attr(feature = "serde", serde(default))] pub coverage_loop: CoverageLoop, /// How the fragment function writes each color attachment whose format converts its float - /// output (`LoweringInputs::color_writes`), for every attachment it writes, through an output - /// variable or in the storage form: link refuses a stage compiled for another map than the + /// output (`LoweringInputs::color_writes`), for every attachment it writes through an output + /// variable: link refuses a stage compiled for another map than the /// pipeline's (`NeedsInput(ColorWrites)`). #[cfg_attr(feature = "serde", serde(default))] pub color_writes: BTreeMap; 4]>, @@ -202,8 +202,8 @@ pub struct StageIo { pub rotated_colors: std::collections::BTreeSet, /// The attachments whose image holds Metal's alpha in red /// (`LoweringInputs::alpha_in_red_colors`) that the fragment function writes through an output - /// variable of either dual-source index, or reads (`[[color(n)]]`) through an input attachment - /// or the interlocked storage form, by color index: each such output holds Metal's alpha in + /// variable of either dual-source index, or reads (`[[color(n)]]`) through an input + /// attachment, by color index: each such output holds Metal's alpha in /// the image's alpha lane too, which alpha to coverage reads, and each read takes the image's /// red as Metal's alpha. Link refuses a stage compiled for another set than the pipeline's /// (`NeedsInput(ColorWrites)`). @@ -323,8 +323,7 @@ pub struct StageIo { #[cfg_attr(feature = "serde", serde(default))] pub float_blend_colors: Vec, /// The attachments a `half` color output of a module compiled with fast math - /// (`air.compile.fast_math_enable`) reaches as color attachments, by color index, sorted (not - /// one the function writes in the storage form). + /// (`air.compile.fast_math_enable`) reaches as color attachments, by color index, sorted. /// Metal's compiler folds the attachment's blend and conversion into the function under fast /// math, so the pipeline's stage records `PrecisionNote::HalfOutputFastMathBlend` where one of /// these attachments stores some channel (`color_writes::stores_output`). One whose write mask diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 40eb0a779..c10fb9103 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -87,111 +87,6 @@ pub enum SampledType { Uint64, } -/// How a draw read through a snapshot keeps a texture's texel in the snapshot -/// (`VariantKey::snapshot_textures`): the texel's codes, from which the read gives back the -/// fetched value bit for bit, in as few bytes as hold them, or the fetched lanes' bits. -/// -/// The copy takes the codes from the value the fetch returns, and the read decodes them as Metal -/// reads the format: a normalized code `c` as `c / (2^b - 1)` correctly rounded (a signed one's -/// magnitude so, `-1` at most), a half-float code widened exactly, an integer code extended. A -/// device whose own decode is exactly that (its value one Metal reads) is given back its fetched -/// value; one whose decode is not is given Metal's. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum SnapshotForm { - /// The fetched `vec4`'s 32 bits a lane (`R32G32B32A32_UINT`): any texel. - Bits, - /// Four 8-bit unsigned normalized codes (`R8G8B8A8_UINT`). - Unorm8, - /// Four 8-bit signed normalized codes (`R8G8B8A8_UINT`, two's complement). - Snorm8, - /// Four 16-bit unsigned normalized codes (`R16G16B16A16_UINT`). - Unorm16, - /// Four 16-bit signed normalized codes (`R16G16B16A16_UINT`, two's complement). - Snorm16, - /// Four half-float codes (`R16G16B16A16_UINT`). - Half, - /// Four 8-bit unsigned integer codes (`R8G8B8A8_UINT`). - Uint8, - /// Four 8-bit signed integer codes (`R8G8B8A8_UINT`, two's complement). - Sint8, - /// Four 16-bit unsigned integer codes (`R16G16B16A16_UINT`). - Uint16, - /// Four 16-bit signed integer codes (`R16G16B16A16_UINT`, two's complement). - Sint16, -} - -impl SnapshotForm { - /// The form a texture slot of sampled type `ty` keeps its texels in, read through a sampled - /// view of `format`: the codes of an 8- or 16-bit normalized, half-float or integer format - /// whose class is the slot's, one, two or four channels; [`Bits`](Self::Bits) for any other - /// format (an sRGB format's view decodes its codes, so its texels are no codes' values). - pub fn of(format: vk::Format, ty: SampledType) -> SnapshotForm { - use vk::Format as F; - let form = match format { - F::R8_UNORM - | F::R8G8_UNORM - | F::R8G8B8A8_UNORM - | F::B8G8R8A8_UNORM - | F::A8B8G8R8_UNORM_PACK32 => SnapshotForm::Unorm8, - F::R8_SNORM | F::R8G8_SNORM | F::R8G8B8A8_SNORM | F::A8B8G8R8_SNORM_PACK32 => { - SnapshotForm::Snorm8 - } - F::R16_UNORM | F::R16G16_UNORM | F::R16G16B16A16_UNORM => SnapshotForm::Unorm16, - F::R16_SNORM | F::R16G16_SNORM | F::R16G16B16A16_SNORM => SnapshotForm::Snorm16, - F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT => SnapshotForm::Half, - F::R8_UINT | F::R8G8_UINT | F::R8G8B8A8_UINT | F::A8B8G8R8_UINT_PACK32 => { - SnapshotForm::Uint8 - } - F::R8_SINT | F::R8G8_SINT | F::R8G8B8A8_SINT | F::A8B8G8R8_SINT_PACK32 => { - SnapshotForm::Sint8 - } - F::R16_UINT | F::R16G16_UINT | F::R16G16B16A16_UINT => SnapshotForm::Uint16, - F::R16_SINT | F::R16G16_SINT | F::R16G16B16A16_SINT => SnapshotForm::Sint16, - _ => SnapshotForm::Bits, - }; - let class = match form { - SnapshotForm::Bits => return form, - SnapshotForm::Uint8 | SnapshotForm::Uint16 => SampledType::Uint, - SnapshotForm::Sint8 | SnapshotForm::Sint16 => SampledType::Sint, - _ => SampledType::Float, - }; - match class == ty { - true => form, - false => SnapshotForm::Bits, - } - } - - /// The snapshot's format: an unsigned integer format of the codes' width, four channels. - pub fn format(self) -> vk::Format { - match self { - SnapshotForm::Bits => vk::Format::R32G32B32A32_UINT, - SnapshotForm::Unorm8 - | SnapshotForm::Snorm8 - | SnapshotForm::Uint8 - | SnapshotForm::Sint8 => vk::Format::R8G8B8A8_UINT, - SnapshotForm::Unorm16 - | SnapshotForm::Snorm16 - | SnapshotForm::Half - | SnapshotForm::Uint16 - | SnapshotForm::Sint16 => vk::Format::R16G16B16A16_UINT, - } - } - - /// The width in bits of each code, and whether it is signed; `None` for - /// [`Bits`](Self::Bits). - pub(crate) fn code(self) -> Option<(u8, bool)> { - match self { - SnapshotForm::Bits => None, - SnapshotForm::Unorm8 | SnapshotForm::Uint8 => Some((8, false)), - SnapshotForm::Snorm8 | SnapshotForm::Sint8 => Some((8, true)), - SnapshotForm::Unorm16 | SnapshotForm::Half | SnapshotForm::Uint16 => Some((16, false)), - SnapshotForm::Snorm16 | SnapshotForm::Sint16 => Some((16, true)), - } - } -} - /// Whether an image is sampled or used as a storage image. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -289,9 +184,9 @@ pub enum SyntheticBinding { /// instanceStride:`), a read-only storage buffer of a tessellation pipeline's synthesized /// control stage, declared with the vertex stage's symbols. TessellationFactors, - /// The render pass's fragment imageblock: a coherent `R32Uint` 2D-array storage image - /// whose layer `w` holds word `w` of every pixel's imageblock cell, read and written inside the - /// fragment's ordered pixel-interlock critical section. + /// The render pass's imageblock storage: a coherent `R32Uint` 2D-array storage image whose + /// layer `w` holds word `w` of every pixel's imageblock cell, which a tile dispatch whose + /// function's explicit imageblock stands alone stages its tile's cells from and back. Imageblock, /// The sampler table: the handle table's layout over the argument buffers' samplers, whose /// resource ids live apart from the textures' (the sampler half): 16-byte entries `{id low, id @@ -301,11 +196,6 @@ pub enum SyntheticBinding { /// the index of the entry its id finds (0 for an id the table lacks), and every use of it reads /// that entry's element and word. SamplerTable, - /// The shadow of the render pass's stencil attachment a fragment function's shader-side - /// stencil tests and writes (`GraphicsState::shadow_stencil`): a coherent `R8Uint` 2D storage - /// image holding pixel `(x, y)`'s stencil value at texel `(x, y)`, read and written inside the - /// fragment's ordered pixel-interlock critical section. - ShadowStencil, /// The function-table directory: the handle table's layout over the visible-function tables /// the pipeline state made, whose resource ids live apart from textures' and samplers'. FunctionTableDirectory, @@ -377,11 +267,6 @@ pub enum ResourceKind { /// constexpr sampler is the binding's immutable sampler. `ResourceSlot::index` is the use /// ([`ResourceSlot::separate_sampler`]), as a heap sampler's is. SeparateSampler(SamplerRef), - /// The snapshot of the texture bound at fragment texture slot `n` (`ResourceSlot::index` too) - /// for a draw that reads it through one (`LoweringInputs::snapshot_textures`): an - /// `R32G32B32A32_UINT` 2D storage image covering the draw's render area, each texel the bits - /// of the four values a fetch of the texture's level 0 there returned. - SnapshotTexels(u32), /// The planes of the two-plane YCbCr texture bound at the stage's texture slot /// `ResourceSlot::index`, held as an image of the multi-planar format that the device's own /// sampler Y′CbCr conversion samples (`LoweringInputs::ycbcr_planes_sampled`): a combined @@ -948,12 +833,6 @@ pub enum PushField { /// sequences ([`PushField::IndirectSequence`]) from 0, and pushes each part's first here. 0 /// for a direct draw. Placed beside the addresses, so the vertex window always holds it. IndirectBase, - /// Which draw of a fragment function compiled under `LoweringInputs::snapshot_textures` runs - /// (`u32`): a hole the consumer fills (`PushHole::SnapshotPhase`), placed beside the addresses - /// so the fragment window always holds it. 1 in the draw that takes the snapshot, whose - /// fragments copy their pixels' texels into it and run nothing else; 0 in the draw that reads - /// it, whose fragments copy nothing and run the function. - SnapshotPhase, // The three amplification words come right after the addresses in the order, so every stage // window holds them (at most 32 bytes before them, 12 of them): a draw of one amplification // writes them alone, between its draws, never through an `ArgumentTable`. @@ -1033,13 +912,6 @@ pub enum PushField { /// the device replay's preprocess module reads (`bind::replay`). No translated function /// reads it. CommandRecordsAddress, - /// The render encoder's stencil state for a fragment function's shader-side stencil - /// (`RuntimeFact::ShadowStencil`), a `uvec2`: the front face's word, then the back face's. - /// Each word holds the face's `MTLCompareFunction` in bits 0 to 2, its stencil-failure and - /// depth-stencil-pass `MTLStencilOperation`s in bits 3 to 5 and 6 to 8, its read mask in bits - /// 9 to 16, its write mask in bits 17 to 24, and in bit 31 whether the draw's pass has a - /// stencil attachment for the function to test against (`bind::shadow_stencil_words`). - ShadowStencilState, /// The whole indices (`u64`) from an indexed indirect draw's bound index offset to its index /// buffer's end, which the index-clamp prepass reads. No translated function reads it. IndexCapacity, @@ -1086,12 +958,6 @@ pub enum PushField { /// reads its raw index at `PushField::CaptureIndexAddress`, and its vertex is that index plus /// the base vertex. CaptureLayout, - /// The channels each storage-form color attachment's write keeps from its texel, where the - /// fragment function takes them from the draw: one `u32` whose bits `4c` to `4c + 3` are color - /// `c`'s `R`, `G`, `B` and `A`, set where the pipeline's write mask leaves the channel out - /// (`StorageAttachmentUse::kept`), so every write mask that keeps some of a format's channels - /// shares one module. - StorageKeptChannels, /// The channel widths of the storage texture bound to the slot (`u32`; /// `metal::format::integer_channels_word`, 0 where the binder binds a neutral): byte `c` /// holds `32 - bits` of channel `c` (red to alpha) of an integer format narrower than 32 bits, @@ -1107,7 +973,7 @@ pub enum PushField { BicubicTexels(SlotRef), /// The render encoder's blend color (`setBlendColorRed:green:blue:alpha:`) for a fragment /// function that computes a blend in the shader under a blend that reads it (an - /// extended-range attachment's, or a fetched attachment's in the storage form): one `uvec4` + /// extended-range attachment's, or a rotated one's): one `uvec4` /// holding the four `f32`s' bits as the encoder set them (`BindState::blend_color`). HalfBlendColor, /// The render encoder's alpha test reference (`setAlphaTestReferenceValue:`) for a fragment @@ -1289,7 +1155,6 @@ mod tests { PushField::RootTableAddress, PushField::ExecutionStatusAddress, PushField::CaptureIndexAddress, - PushField::SnapshotPhase, PushField::DispatchRegion, PushField::ReplayRegionAddress, PushField::BaseVertexInstance, diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 848d19e5b..711aad72e 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -75,8 +75,6 @@ pub struct ModuleBuilder { /// Every storage buffer and storage image resource is decorated `Coherent` /// (`ModuleBuilder::coherent_resources`). coherent: bool, - /// Storage-image resources decorated `Coherent` one by one (`ModuleBuilder::coherent`). - coherent_images: BTreeSet, /// Storage-image resources decorated `Volatile` (`ModuleBuilder::volatile`). volatile: BTreeSet, /// Buffer bindings whose memory nothing in the module writes (`ModuleBuilder::unwritten_buffer`). @@ -850,31 +848,6 @@ impl ModuleBuilder { self.coherent = true; } - /// Decorate storage-image resource `g` `Coherent`: under the `GLSL450` memory model each access - /// to its texels is made available and visible at device scope, as - /// [`coherent_resources`](ModuleBuilder::coherent_resources) makes every shared resource's, - /// for one image whose accesses an ordered fragment-interlock critical section orders while - /// the module's other resources keep plain accesses. Only a `UniformConstant` resource whose - /// type is a storage image can be; the Vulkan memory model bans the decoration - /// ([`ModuleBuilder::finalize`]). - pub fn coherent(&mut self, g: GlobalId) -> BResult<()> { - let gv = self.global(g)?; - let storage = gv.class == StorageClass::UniformConstant - && matches!(gv.kind, GlobalKind::Resource(_)) - && matches!( - self.types.get(gv.pointee)?, - Type::Image(ImageType { - usage: ImageUsage::Storage, - .. - }) - ); - if !storage { - return Err(BuildError::Global(GlobalRule::CoherentTarget)); - } - self.coherent_images.insert(g); - Ok(()) - } - /// Decorate storage-image resource `g` `Volatile`: under the `GLSL450` memory model every /// access to its texels is a volatile access, so a load never returns a value the invocation /// stored to that out-of-bounds location and the device's robustness discarded. Vulkan lets @@ -1260,15 +1233,14 @@ impl ModuleBuilder { if !self.volatile.is_empty() && vulkan { return Err(BuildError::Global(GlobalRule::VolatileTarget)); } - if (self.coherent || !self.coherent_images.is_empty()) && vulkan { + if self.coherent && vulkan { return Err(BuildError::Global(GlobalRule::CoherentTarget)); } - let mut coherent = if self.coherent { + let coherent = if self.coherent { shared_resources(&self.types, &self.globals)? } else { BTreeSet::new() }; - coherent.extend(self.coherent_images); Ok(TypedModule { types: self.types, consts: self.consts, diff --git a/crates/metal2vulkan/src/spirv/builder/tests.rs b/crates/metal2vulkan/src/spirv/builder/tests.rs index 60daf0422..3c70c8fe2 100644 --- a/crates/metal2vulkan/src/spirv/builder/tests.rs +++ b/crates/metal2vulkan/src/spirv/builder/tests.rs @@ -867,57 +867,6 @@ fn only_storage_images_are_volatile_and_never_under_the_vulkan_model() { ); } -/// `coherent` decorates the one storage image it names `Coherent`, leaving the module's other -/// shared resources plain, and refuses a sampled image. -#[test] -fn coherent_decorates_one_storage_image_alone() { - let texture = |index| ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Texture, - index, - }; - let image = |t: &mut T, usage, format| { - let u = t.u32(); - t.ty(Type::Image(ImageType { - sampled_type: u, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: false, - usage, - format, - })) - }; - let mut t = T::new(); - let storage = image( - &mut t, - ImageUsage::Storage, - crate::spv::ImageFormat::Rgba32ui, - ); - let sampled = image( - &mut t, - ImageUsage::Sampled, - crate::spv::ImageFormat::Unknown, - ); - let one = - t.b.resource(texture(0), StorageClass::UniformConstant, storage) - .expect("image"); - let other = - t.b.resource(texture(1), StorageClass::UniformConstant, storage) - .expect("other image"); - let read = - t.b.resource(texture(2), StorageClass::UniformConstant, sampled) - .expect("sampled"); - t.b.coherent(one).expect("a storage image"); - assert_eq!( - t.b.coherent(read).err(), - Some(BuildError::Global(GlobalRule::CoherentTarget)) - ); - let m = finish_compute(t.b).expect("a GLSL450 module with one coherent image"); - assert_eq!(m.coherent, BTreeSet::from([one])); - assert!(!m.coherent.contains(&other)); -} - /// `coherent_resources` decorates every storage buffer and storage image resource of the module /// `Coherent` (a descriptor array of storage images included, those declared after it too), and no /// uniform buffer or sampled image; a module under the Vulkan memory model, which bans the diff --git a/crates/metal2vulkan/src/spirv/requirements/mod.rs b/crates/metal2vulkan/src/spirv/requirements/mod.rs index 15b631b3d..b4ad0a1f2 100644 --- a/crates/metal2vulkan/src/spirv/requirements/mod.rs +++ b/crates/metal2vulkan/src/spirv/requirements/mod.rs @@ -90,12 +90,10 @@ fn independence_needed(widths: &BTreeSet) -> Independence { mod level_reads; mod own_pixel; -mod snapshot; mod writes; pub use level_reads::level_reads; pub use own_pixel::own_pixel_textures; -pub use snapshot::{snapshot_copies_alone, snapshot_textures, Judged}; pub use writes::writes_memory; #[cfg(test)] diff --git a/crates/metal2vulkan/src/spirv/requirements/snapshot.rs b/crates/metal2vulkan/src/spirv/requirements/snapshot.rs deleted file mode 100644 index 5294d4074..000000000 --- a/crates/metal2vulkan/src/spirv/requirements/snapshot.rs +++ /dev/null @@ -1,624 +0,0 @@ -//! Which own-pixel texture slots a fragment module can read through a snapshot an earlier draw of -//! the same primitives took (`StageInterface::snapshot_textures`). -//! -//! A runtime may serve a draw that reads a texture its own render pass renders, at the fragment's -//! own pixel alone (`own_pixel`), by drawing the draw twice with one pipeline: first with every -//! color write mask zero, each fragment copying the texel it would read into a snapshot image, then -//! with the draw's own masks, each fragment reading the snapshot (the runtime's -//! `texture/attached_reads.rs`). A helper invocation reads nothing there: its pixel may hold no -//! fragment of the draw, so no copy wrote its snapshot texel, and the by-region barriers that order -//! a copy before the reads order it for fragments of the same pixel alone. So the slot's value in a -//! helper invocation is a constant, which is exact only where no fragment's result depends on a -//! helper's value of it, and only where the constant gives the helper no undefined behavior. -//! -//! A helper invocation's values reach other invocations' results only through derivatives and quad -//! operations ("When performing derivative or quad group operations in a fragment shader, -//! additional invocations may be spawned in order to ensure correct results", the Shaders -//! chapter's Helper Invocations), and its stores have no effect ("Stores and atomics performed by -//! helper invocations must not have any effect on memory except for the Function, Private and -//! Output storage classes"). A value that decides a branch can also move a helper off its quad's -//! path, which changes what a derivative there reads, or keep it in a loop the texture's own texel -//! would end. And where a helper's constant is an operand that an instruction's behavior is -//! undefined for, the helper has undefined behavior that Metal's read of the texel need not give -//! it: an integer division's ("Behavior is undefined if any component of Operand 2 is 0", the -//! SPIR-V specification's `OpUDiv`, `OpUMod`; `OpSDiv`, `OpSRem` and `OpSMod` also at `-1` beside -//! the minimum) and a dynamic component index's ("Behavior is undefined if Index's value is less -//! than zero or greater than or equal to the number of components in Vector", -//! `OpVectorExtractDynamic`, `OpVectorInsertDynamic`). So a slot qualifies only where no value that -//! a fetch of it reaches, through any instruction, phi, or `Function`, `Private` or `Output` -//! variable it is stored in and loaded from, is an operand of: -//! -//! - a derivative, a sample, gather or level-of-detail query of any image, a subgroup or quad -//! operation, an atomic, an image write or texel pointer, a ray query, a mesh output count, or a -//! store to any other storage class; -//! - a conditional branch or a switch, but for a selection whose arms a helper may take in place -//! of a fragment's to no one's harm (below), or the entry's returned value; -//! - the divisor of an integer division or remainder, the dividend of a signed one whose divisor -//! is not a constant without a `-1` lane, or a dynamic vector component index. -//! -//! A selection on such a value keeps the slot where its arms leave through its merge block alone -//! (no break, continue, return, `OpKill`, `OpTerminateInvocation` or unreachable end) and hold no -//! derivative, implicit-level sample or level-of-detail query, subgroup or quad operation, loop, -//! or operand undefined at some value that is not a constant, nor do the functions they call -//! ([`arms`]). A helper whose constant takes it down another arm than the texel would then -//! changes nothing another invocation reads: no tangled instruction runs in its arms ("When performing derivative or quad -//! group operations in a fragment shader, additional invocations may be spawned in order to ensure -//! correct results", so only those read a helper's values), it reaches the merge as a fragment -//! does, and `OpDemoteToHelperInvocation` in an arm leaves it what it is ("is not considered a -//! flow control instruction"). What it leaves behind, the merge's phis and what its arms store in -//! `Function`, `Private` and `Output` variables, takes the condition's reach, and its uses are -//! judged as any other. A loop's exit is a branch out of it, which no such selection holds. -//! -//! A call is followed into its callee: "Argument N is the object to copy to parameter N of -//! Function" (`OpFunctionCall`), so each argument's reach is its parameter's, a pointer argument's -//! memory is its parameter's (what either side stores through it the other may load), and the -//! values the callee returns reach the call's result. The callee's instructions are the module's, -//! judged as any other; a callee called from several sites takes the reach of them all. -//! -//! A module that already holds an interlock critical section has none: the variant's entry opens -//! its own. Nor has one with a `Coherent` resource or under the Vulkan memory model: the variant -//! decorates its snapshot `Coherent`. The test is structural, never a name. -//! -//! Each slot left out is stated with every clause that leaves it out ([`SnapshotRefusal`], -//! `StageInterface::snapshot_refusals`): the analysis keeps one reach for each clause. -//! -//! [`snapshot_copies_alone`] checks a variant compiled to read such slots through snapshots: its -//! only texel access of each is the entry's copy. - -use crate::budget::Meter; -use crate::error::Error; -use crate::pipeline::interface::SnapshotRefusal; -use crate::pipeline::sym::ResourceKind; -use crate::spirv::ids::Value; -use crate::spirv::ir::{ - BinOp, ConstKind, Constant, ExecModel, GlobalKind, Inst, StorageClass, Terminator, Type, - TypedModule, UnOp, ValueOrigin, -}; - -use super::own_pixel::{carried_on, holds_image, use_of, Use}; - -use arms::Arms; - -/// The most passes over the module the reach is followed for; a module whose values take more to -/// settle (a chain of loop-carried copies longer than this) has no slot. -const MOST_PASSES: u32 = 16; - -/// No slot's image. -const NONE: u32 = u32::MAX; - -mod arms; - -#[cfg(test)] -mod tests; - -/// What [`snapshot_textures`] finds of a fragment module's own-pixel texture slots. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Judged { - /// The slots a draw can read through a snapshot (`StageInterface::snapshot_textures`), sorted. - pub slots: Vec, - /// Each other slot with every clause that leaves it out - /// (`StageInterface::snapshot_refusals`), sorted by slot and then by clause. - pub refusals: Vec<(u32, SnapshotRefusal)>, -} - -/// The slots among `own` (fragment module `m`'s own-pixel texture slots, `own_pixel_textures`, -/// sorted) whose fetched values reach none of the uses the module docs list, in a module that -/// holds no interlock, coherent resource or Vulkan memory model, of a function that writes no -/// memory (`writes_memory`, `StageInterface::writes_memory`), and every clause that leaves out -/// each other one: those of the module and the function, and those of the uses its values reach, -/// which the walk states in every case. A slot at or past 128 is left out unwalked. Nothing for a -/// module of another stage. It charges `meter` for its tables while it holds them. -pub fn snapshot_textures( - m: &TypedModule, - own: &[u32], - writes_memory: bool, - meter: &mut Meter, -) -> Result { - if own.is_empty() || m.entry().model != ExecModel::Fragment { - return Ok(Judged::default()); - } - let interlocked = m - .blocks() - .iter() - .flat_map(|b| &b.insts) - .any(|n| matches!(n.inst, Inst::BeginInterlock | Inst::EndInterlock)); - // The variant decorates its snapshot `Coherent`, which the Vulkan memory model bans, beside - // which no other resource of the function may be coherent (`lower::sync::memory_model`). - let coherent = !m.coherent.is_empty() || super::uses_vulkan_memory_model(m.requirements()); - let walked: Vec = own.iter().copied().filter(|&s| s < 128).collect(); - let every: u128 = walked.iter().fold(0, |acc, &s| acc | (1u128 << s)); - let mut refused = Refused::default(); - for (holds, why) in [ - (writes_memory, SnapshotRefusal::WritesMemory), - (interlocked, SnapshotRefusal::Interlock), - (coherent, SnapshotRefusal::Coherent), - ] { - if holds { - refused.add(why, every); - } - } - if !walked.is_empty() { - let n = m.values().len(); - // Each value's slot image (`NONE` for none), its reach (the slots whose fetched values it - // holds), the reach of the memory behind it where it is a variable's pointer, and the - // variable a pointer points into; each block's function, and the reach each function - // returns; and the walks over the selections' arms. - let (blocks, functions) = (m.blocks().len(), m.functions().len()); - let tables = - n * (4 + 16 + 16 + 4) + 4 * blocks + 16 * functions + Arms::bytes(blocks, functions); - meter.charge(tables)?; - let result = reach(m, &walked, n, &mut refused); - meter.release(tables); - result?; - } - let mut judged = refused.judged(&walked); - let past = own.iter().filter(|&&s| s >= 128); - (judged.refusals).extend(past.map(|&s| (s, SnapshotRefusal::Other))); - judged.refusals.sort_unstable(); - Ok(judged) -} - -/// The slots each clause leaves out, as masks of slot bits, indexed by [`SnapshotRefusal`]. -#[derive(Default)] -struct Refused([u128; 12]); - -impl Refused { - /// The clauses each mask stands for, in the masks' order. - const CLAUSES: [SnapshotRefusal; 12] = [ - SnapshotRefusal::Branch, - SnapshotRefusal::Derivative, - SnapshotRefusal::Sample, - SnapshotRefusal::GroupOperation, - SnapshotRefusal::Store, - SnapshotRefusal::Atomic, - SnapshotRefusal::ImageWrite, - SnapshotRefusal::UndefinedOperand, - SnapshotRefusal::WritesMemory, - SnapshotRefusal::Interlock, - SnapshotRefusal::Coherent, - SnapshotRefusal::Other, - ]; - - /// Leave out the slots of `reach` for `why`. - fn add(&mut self, why: SnapshotRefusal, reach: u128) { - let at = Self::CLAUSES.iter().position(|&c| c == why); - if let Some(mask) = at.and_then(|i| self.0.get_mut(i)) { - *mask |= reach; - } - } - - /// Whether any clause leaves `slot` out. - fn any(&self, slot: u32) -> bool { - self.0.iter().any(|mask| mask & (1u128 << slot) != 0) - } - - /// The slots of `own` none leaves out, and each other one with every clause that does. - fn judged(&self, own: &[u32]) -> Judged { - let mut judged = Judged::default(); - for &slot in own { - if !self.any(slot) { - judged.slots.push(slot); - } - for (mask, &why) in self.0.iter().zip(&Self::CLAUSES) { - if mask & (1u128 << slot) != 0 { - judged.refusals.push((slot, why)); - } - } - } - judged - } -} - -/// [`snapshot_textures`]'s walk once its tables are charged: each slot of `own` the uses its -/// values reach leave out, added to `bad`. -fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<(), Error> { - let mut carried = vec![NONE; n]; - let mut base: Vec = (0..n as u32).collect(); - for g in m.globals() { - if let GlobalKind::Resource(slot) = &g.kind { - let texture = match slot.kind { - ResourceKind::Texture - | ResourceKind::CombinedTextureSampler(_) - | ResourceKind::YCbCrPlanes(_) => Some(slot.index), - ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t), - _ => None, - }; - if let (Some(t), Some(c)) = (texture, carried.get_mut(g.value.index())) { - *c = t; - } - } - } - let mut mask = vec![0u128; n]; - let mut memory = vec![0u128; n]; - let mut function = vec![NONE; m.blocks().len()]; - for (i, f) in m.functions().iter().enumerate() { - for b in &f.blocks { - if let Some(at) = function.get_mut(b.index()) { - *at = i as u32; - } - } - } - let mut returned = vec![0u128; m.functions().len()]; - let mut arms = Arms::new(m); - let wanted: u128 = own.iter().fold(0, |acc, &s| acc | (1u128 << s)); - let get = |table: &[u128], v: Value| table.get(v.index()).copied().unwrap_or(0); - for _ in 0..MOST_PASSES { - let mut changed = false; - for (at, b) in m.blocks().iter().enumerate() { - for phi in &b.phis { - let reach = phi - .incoming - .iter() - .fold(0, |acc, (v, _)| acc | get(&mask, *v)); - changed |= join(&mut mask, phi.result, reach); - } - for node in &b.insts { - let mut operands: u128 = 0; - node.inst.for_each_value(|v| operands |= get(&mask, v)); - match &node.inst { - // What carries a slot's image on, and the variable a pointer points into. - inst if carried_on(inst).is_some() => { - let (Some(r), Some(from)) = (node.result, carried_on(inst)) else { - continue; - }; - if holds_image(m, r)? { - let slot = carried.get(from.index()).copied().unwrap_or(NONE); - if let Some(c) = carried.get_mut(r.index()).filter(|c| **c != slot) { - *c = slot; - changed = true; - } - } - let mut reach = operands; - if let Inst::Load { ptr, .. } = inst { - reach |= get(&memory, root(&base, *ptr)); - } - if let Inst::Unary { - op: UnOp::CopyObject, - a, - } = inst - { - changed |= point(&mut base, r, *a); - } - changed |= join(&mut mask, r, reach); - } - Inst::ImageFetch { image, .. } => { - let slot = carried.get(image.index()).copied().unwrap_or(NONE); - let source = match slot { - s if s < 128 && wanted & (1u128 << s) != 0 => 1u128 << s, - _ => 0, - }; - if let Some(r) = node.result { - changed |= join(&mut mask, r, operands | source); - } - } - Inst::AccessChain { base: from, .. } => { - if let Some(r) = node.result { - changed |= point(&mut base, r, *from); - changed |= join(&mut mask, r, operands); - } - } - // What a kept branch's arms store takes its condition's reach too. - Inst::Store { ptr, value, .. } => { - let reach = get(&mask, *value) | get(&mask, *ptr) | arms.control(at); - if kept_class(m, *ptr)? { - let root = root(&base, *ptr); - changed |= join(&mut memory, root, reach); - } else { - bad.add(SnapshotRefusal::Store, reach); - } - } - // Each argument to its parameter, a pointer argument's memory both ways, and the - // callee's returned reach to the result. - Inst::Call { func, args } => { - let params = m.functions().get(func.index()).map(|f| f.params.as_slice()); - let Some(params) = params.filter(|p| p.len() == args.len()) else { - bad.add(SnapshotRefusal::Other, operands); - continue; - }; - for (&arg, ¶m) in args.iter().zip(params) { - let reach = get(&mask, arg); - changed |= join(&mut mask, param, reach); - if matches!(m.types().get(m.value(arg)?.ty)?, Type::Pointer { .. }) { - let at = root(&base, arg); - let (caller, callee) = (get(&memory, at), get(&memory, param)); - changed |= join(&mut memory, param, caller); - changed |= join(&mut memory, at, callee); - } - } - if let Some(r) = node.result { - let back = returned.get(func.index()).copied().unwrap_or(0); - changed |= join(&mut mask, r, back); - } - } - // A divisor, and a signed dividend beside a divisor that may be `-1`. - Inst::Binary { - op: - op @ (BinOp::UDiv | BinOp::SDiv | BinOp::UMod | BinOp::SRem | BinOp::SMod), - a, - b, - .. - } => { - bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *b)); - let unsigned = matches!(op, BinOp::UDiv | BinOp::UMod); - if !unsigned && !lanes_all(m, *b, |bits, ones| bits != ones)? { - bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *a)); - } - if let Some(r) = node.result { - changed |= join(&mut mask, r, operands); - } - } - Inst::VectorExtractDynamic { index, .. } - | Inst::VectorInsertDynamic { index, .. } => { - bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *index)); - if let Some(r) = node.result { - changed |= join(&mut mask, r, operands); - } - } - inst @ (Inst::Derivative { .. } - | Inst::ImageSample { .. } - | Inst::ImageGather { .. } - | Inst::ImageDrefGather { .. } - | Inst::ImageQueryLod { .. } - | Inst::Group { .. } - | Inst::Atomic { .. } - | Inst::AtomicLoad { .. } - | Inst::AtomicStore { .. } - | Inst::AtomicCompareExchange { .. } - | Inst::ImageWrite { .. } - | Inst::ImageTexelPointer { .. } - | Inst::RayQuery(_) - | Inst::SetMeshOutputs { .. }) => { - bad.add(refused_by(inst), operands); - if let Some(r) = node.result { - changed |= join(&mut mask, r, operands); - } - } - _ => { - if let Some(r) = node.result { - changed |= join(&mut mask, r, operands); - } - } - } - } - match &b.term { - // A selection whose arms a helper may take in place of a fragment's hands its - // condition's reach to its merge's phis and its arms' stores alone. - Terminator::CondBranch { cond: v, .. } | Terminator::Switch { sel: v, .. } => { - let reach = get(&mask, *v); - if reach != 0 { - match arms.keeps(m, at, reach)? { - Some((merge, grew)) => { - changed |= grew; - for phi in - m.blocks().get(merge.index()).map_or(&[][..], |b| &b.phis) - { - changed |= join(&mut mask, phi.result, reach); - } - } - None => bad.add(SnapshotRefusal::Branch, reach), - } - } - } - // A callee's returned value reaches its calls' results; the entry's, the stage. - Terminator::ReturnValue(v) => { - let f = function.get(at).copied().unwrap_or(NONE); - let reach = get(&mask, *v); - match f { - f if f == m.entry().func.index() as u32 => { - bad.add(SnapshotRefusal::Other, reach) - } - f => match returned.get_mut(f as usize) { - Some(r) if *r | reach != *r => { - *r |= reach; - changed = true; - } - Some(_) => {} - None => bad.add(SnapshotRefusal::Other, reach), - }, - } - } - _ => {} - } - } - if !changed { - return Ok(()); - } - } - bad.add(SnapshotRefusal::Other, wanted); - Ok(()) -} - -/// The clause an operand of `inst`, an instruction that leaves out every slot whose values reach -/// it, leaves them out for. -fn refused_by(inst: &Inst) -> SnapshotRefusal { - match inst { - Inst::Derivative { .. } => SnapshotRefusal::Derivative, - Inst::ImageSample { .. } - | Inst::ImageGather { .. } - | Inst::ImageDrefGather { .. } - | Inst::ImageQueryLod { .. } => SnapshotRefusal::Sample, - Inst::Group { .. } => SnapshotRefusal::GroupOperation, - Inst::Atomic { .. } - | Inst::AtomicLoad { .. } - | Inst::AtomicStore { .. } - | Inst::AtomicCompareExchange { .. } => SnapshotRefusal::Atomic, - Inst::ImageWrite { .. } | Inst::ImageTexelPointer { .. } => SnapshotRefusal::ImageWrite, - _ => SnapshotRefusal::Other, - } -} - -/// Whether module `m`, compiled to read texture slots `slots` through snapshots -/// (`LoweringInputs::snapshot_textures`), reads each slot's texels in the entry's copy alone, -/// with the one `OpImageFetch` of the slot's image that copy makes. Every other use of the slot's -/// images is one that carries them -/// on or queries their size. A read the lowering left on the texture would race the draw's own -/// color writes, and shows here as a fetch the copy does not make. It charges `meter` for its -/// table while it holds it. -pub fn snapshot_copies_alone( - m: &TypedModule, - slots: &[u32], - meter: &mut Meter, -) -> Result { - let n = m.values().len(); - let table = 4 * n; - meter.charge(table)?; - let result = copies_alone(m, slots, n); - meter.release(table); - result -} - -/// [`snapshot_copies_alone`] once its table is charged. -fn copies_alone(m: &TypedModule, slots: &[u32], n: usize) -> Result { - let mut carried = vec![NONE; n]; - for g in m.globals() { - if let GlobalKind::Resource(slot) = &g.kind { - let texture = match slot.kind { - ResourceKind::Texture - | ResourceKind::CombinedTextureSampler(_) - | ResourceKind::YCbCrPlanes(_) => Some(slot.index), - ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t), - _ => None, - }; - if let (Some(t), Some(c)) = (texture, carried.get_mut(g.value.index())) { - *c = t; - } - } - } - let mut settled = false; - for _ in 0..MOST_PASSES { - let mut changed = false; - for node in m.blocks().iter().flat_map(|b| &b.insts) { - let (Some(r), Some(from)) = (node.result, carried_on(&node.inst)) else { - continue; - }; - let slot = carried.get(from.index()).copied().unwrap_or(NONE); - if slot != NONE && holds_image(m, r)? { - if let Some(c) = carried.get_mut(r.index()).filter(|c| **c != slot) { - *c = slot; - changed = true; - } - } - } - if !changed { - settled = true; - break; - } - } - if !settled { - return Ok(false); - } - let watched = |v: Value| { - carried - .get(v.index()) - .copied() - .filter(|s| slots.contains(s)) - }; - let mut fetches = vec![0u32; slots.len()]; - let mut elsewhere = false; - for b in m.blocks() { - let merged = b - .phis - .iter() - .flat_map(|phi| phi.incoming.iter().map(|(v, _)| *v)); - let returned = match &b.term { - Terminator::ReturnValue(v) => Some(*v), - _ => None, - }; - if merged.chain(returned).any(|v| watched(v).is_some()) { - return Ok(false); - } - for node in &b.insts { - node.inst.for_each_value(|v| { - let Some(slot) = watched(v) else { - return; - }; - match use_of(node, v) { - Use::NoTexel => {} - Use::Fetch { .. } => { - let at = slots.iter().position(|&s| s == slot); - if let Some(f) = at.and_then(|i| fetches.get_mut(i)) { - *f += 1; - } - } - Use::Elsewhere => elsewhere = true, - } - }); - } - } - Ok(!elsewhere && fetches.iter().all(|&f| f == 1)) -} - -/// Add `reach` to `table[v]`; whether it grew. -fn join(table: &mut [u128], v: Value, reach: u128) -> bool { - match table.get_mut(v.index()) { - Some(t) if *t | reach != *t => { - *t |= reach; - true - } - _ => false, - } -} - -/// Point pointer `r` into the variable `from` points into; whether that changed. -fn point(base: &mut [u32], r: Value, from: Value) -> bool { - let to = base - .get(from.index()) - .copied() - .unwrap_or(from.index() as u32); - match base.get_mut(r.index()) { - Some(b) if *b != to => { - *b = to; - true - } - _ => false, - } -} - -/// The value of the variable pointer `ptr` points into, as far as the passes found it. -fn root(base: &[u32], ptr: Value) -> Value { - let at = base.get(ptr.index()).copied().unwrap_or(ptr.index() as u32); - Value::new(at) -} - -/// Whether `v` is a plain integer constant each of whose lanes' bits, within the lane's width, -/// pass `keep(bits, ones)`, `ones` every bit of the width set. -fn lanes_all(m: &TypedModule, v: Value, keep: impl Fn(u64, u64) -> bool) -> Result { - let ValueOrigin::Const(c) = m.value(v)?.origin else { - return Ok(false); - }; - let elem = match m.types().get(m.value(v)?.ty)? { - Type::Vector { elem, .. } => *elem, - _ => m.value(v)?.ty, - }; - let Type::Int { width, .. } = m.types().get(elem)? else { - return Ok(false); - }; - let ones = match *width { - 64.. => u64::MAX, - w => (1u64 << w) - 1, - }; - let lane = |bits: u64| keep(bits & ones, ones); - Ok(match &m.consts().get(c)?.kind { - ConstKind::Plain(Constant::Scalar { bits, .. }) => lane(bits.0), - ConstKind::Plain(Constant::Composite { parts, .. }) => parts - .iter() - .all(|part| m.consts().scalar_bits(*part).is_some_and(|b| lane(b.0))), - ConstKind::Plain(Constant::Null { .. }) => lane(0), - _ => false, - }) -} - -/// Whether a store through `ptr` keeps its value where the module's own loads read it alone: a -/// `Function`, `Private` or `Output` variable's. -fn kept_class(m: &TypedModule, ptr: Value) -> Result { - let class = match m.types().get(m.value(ptr)?.ty)? { - Type::Pointer { class, .. } => *class, - _ => return Ok(false), - }; - let origin_ok = !matches!(m.value(ptr)?.origin, ValueOrigin::Param { .. }); - Ok(origin_ok - && matches!( - class, - StorageClass::Function | StorageClass::Private | StorageClass::Output - )) -} diff --git a/crates/metal2vulkan/src/spirv/requirements/snapshot/arms.rs b/crates/metal2vulkan/src/spirv/requirements/snapshot/arms.rs deleted file mode 100644 index 23ecf04f1..000000000 --- a/crates/metal2vulkan/src/spirv/requirements/snapshot/arms.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Which branches on a snapshot slot's fetched value keep the slot: the selections whose arms hold -//! nothing a helper invocation's path through them could pass on (the module docs of -//! [`super`]). -//! -//! A selection's arms are the blocks a walk from its header's targets reaches before its merge -//! block, and the blocks of every function a call in them reaches. The branch keeps the slot only -//! where the walk leaves the arms through the merge alone: no arm block is the merge or continue -//! target of a construct the selection lies in (a loop's break or continue, a switch's break), -//! returns, ends the invocation (`OpKill`, `OpTerminateInvocation`) or is unreachable; and where -//! no arm block or callee holds a tangled instruction (`Inst::is_tangled`: an implicit-level -//! sample or level-of-detail query, a derivative, a subgroup or quad operation), a loop, or an -//! operand an instruction's behavior is undefined for at some value that is not a constant -//! (an integer divisor, a signed one that may be `-1`, a dynamic vector component index). -//! -//! The merge then post-dominates the header, so whatever follows it runs in a helper as in a -//! fragment, and what the arms leave behind is all a helper's other path can change: the merge's -//! phis and the `Function`, `Private` and `Output` variables an arm or its callees store to. Those -//! take the branch's reach ([`Arms::control`]), and the walk judges their uses as any other. - -use crate::error::Error; -use crate::spirv::ids::BlockId; -use crate::spirv::ir::{BinOp, Block, Inst, Merge, Terminator, TypedModule, ValueOrigin}; - -use super::{lanes_all, NONE}; - -/// A block declared by more than one header. -const MANY: u32 = u32::MAX - 1; - -/// A header's verdict, before it is judged. -const UNJUDGED: u8 = 0; -/// A header whose arms keep the slot. -const KEPT: u8 = 1; -/// A header whose arms leave it out. -const LEFT_OUT: u8 = 2; - -/// The tables of the walks over a module's selections, one entry for each block or function. -pub(super) struct Arms { - /// The header that declares each block its merge or continue target, `NONE` for none, `MANY` - /// for more than one. - declared: Vec, - /// The walk that last reached each block, and each function. - walked: Vec, - walked_fn: Vec, - walks: u32, - /// Each header's verdict. - verdict: Vec, - /// The reach each kept header has handed its arms. - applied: Vec, - /// Each block's reach of the branches it is control dependent on: the slots whose fetched - /// values decide a kept branch whose arms hold it. - control: Vec, - /// The blocks a walk reached, and its open blocks and functions. - reached: Vec, - stack: Vec, - calls: Vec, -} - -impl Arms { - /// The bytes the tables take for a module of `blocks` blocks and `functions` functions. - pub(super) fn bytes(blocks: usize, functions: usize) -> usize { - blocks * (4 + 4 + 1 + 16 + 16 + 4 + 4) + functions * (4 + 4) - } - - /// The tables of module `m`. - pub(super) fn new(m: &TypedModule) -> Arms { - let blocks = m.blocks().len(); - let mut declared = vec![NONE; blocks]; - for (at, b) in m.blocks().iter().enumerate() { - let targets = match b.merge { - Some(Merge::Selection { merge }) => [Some(merge), None], - Some(Merge::Loop { merge, cont }) => [Some(merge), Some(cont)], - _ => [None, None], - }; - for t in targets.into_iter().flatten() { - if let Some(d) = declared.get_mut(t.index()) { - *d = if *d == NONE { at as u32 } else { MANY }; - } - } - } - Arms { - declared, - walked: vec![0; blocks], - walked_fn: vec![0; m.functions().len()], - walks: 0, - verdict: vec![UNJUDGED; blocks], - applied: vec![0; blocks], - control: vec![0; blocks], - reached: Vec::with_capacity(blocks), - stack: Vec::with_capacity(blocks), - calls: Vec::with_capacity(m.functions().len()), - } - } - - /// The reach of the kept branches block `at` is control dependent on. - pub(super) fn control(&self, at: usize) -> u128 { - self.control.get(at).copied().unwrap_or(0) - } - - /// Whether the branch ending block `header`, whose condition holds the fetched values of the - /// slots of `reach`, keeps them: its merge block where it does, which takes `reach` into its - /// phis, its arms taking it into [`Arms::control`] (and whether that grew); `None` where it - /// leaves them out. - pub(super) fn keeps( - &mut self, - m: &TypedModule, - header: usize, - reach: u128, - ) -> Result, Error> { - let verdict = self.verdict.get(header).copied().unwrap_or(LEFT_OUT); - let applied = self.applied.get(header).copied().unwrap_or(0); - let merge = match verdict { - LEFT_OUT => return Ok(None), - KEPT if applied | reach == applied => { - return Ok(merge_of(m, header).map(|b| (b, false))) - } - _ => self.walk(m, header)?, - }; - let Some(merge) = merge else { - if let Some(v) = self.verdict.get_mut(header) { - *v = LEFT_OUT; - } - return Ok(None); - }; - if let Some(v) = self.verdict.get_mut(header) { - *v = KEPT; - } - if let Some(a) = self.applied.get_mut(header) { - *a |= reach; - } - let mut grew = false; - for &b in &self.reached { - if let Some(c) = self.control.get_mut(b as usize) { - grew |= *c | reach != *c; - *c |= reach; - } - } - Ok(Some((merge, grew))) - } - - /// Walk the arms of the selection block `header` heads, recording the blocks reached in - /// `reached`: its merge block where the arms keep the slot, else `None`. - fn walk(&mut self, m: &TypedModule, header: usize) -> Result, Error> { - let Some(merge) = merge_of(m, header) else { - return Ok(None); - }; - let blocks = m.blocks(); - self.walks += 1; - let w = self.walks; - self.reached.clear(); - self.stack.clear(); - self.calls.clear(); - if let Some(s) = self.walked.get_mut(header) { - *s = w; - } - let Some(head) = blocks.get(header) else { - return Ok(None); - }; - targets(&head.term, |t| self.stack.push(t)); - while let Some(b) = self.stack.pop() { - let at = b.index(); - if b == merge || (self.walked.get(at) == Some(&w) && at != header) { - continue; - } - // Back at the header, or at a merge or continue target of a construct the selection - // lies in: the arm leaves it. - let declared = self.declared.get(at).copied().unwrap_or(MANY); - let inner = declared == NONE || self.walked.get(declared as usize) == Some(&w); - if at == header || !inner { - return Ok(None); - } - if let Some(s) = self.walked.get_mut(at) { - *s = w; - } - let Some(block) = blocks.get(at) else { - return Ok(None); - }; - if !self.clean(m, block, w)? { - return Ok(None); - } - match block.term { - Terminator::Branch(_) - | Terminator::CondBranch { .. } - | Terminator::Switch { .. } => {} - _ => return Ok(None), - } - self.reached.push(at as u32); - targets(&block.term, |t| self.stack.push(t)); - } - // Every function a call in the arms reaches runs in them; its returns go back to them. - while let Some(f) = self.calls.pop() { - let Some(func) = m.functions().get(f as usize) else { - return Ok(None); - }; - for &b in &func.blocks { - let Some(block) = blocks.get(b.index()) else { - return Ok(None); - }; - if !self.clean(m, block, w)? { - return Ok(None); - } - match block.term { - Terminator::Branch(_) - | Terminator::CondBranch { .. } - | Terminator::Switch { .. } - | Terminator::Return - | Terminator::ReturnValue(_) => {} - _ => return Ok(None), - } - self.reached.push(b.index() as u32); - } - } - Ok(Some(merge)) - } - - /// Whether block `block` of walk `w` heads no loop and holds no tangled instruction and no - /// operand undefined at some value that is not a constant; each function it calls is queued. - fn clean(&mut self, m: &TypedModule, block: &Block, w: u32) -> Result { - if matches!(block.merge, Some(Merge::Loop { .. })) { - return Ok(false); - } - for node in &block.insts { - let inst = &node.inst; - if inst.is_tangled() { - return Ok(false); - } - let defined = match inst { - Inst::Binary { op, b, .. } => match op { - BinOp::UDiv | BinOp::UMod => lanes_all(m, *b, |bits, _| bits != 0)?, - BinOp::SDiv | BinOp::SRem | BinOp::SMod => { - lanes_all(m, *b, |bits, ones| bits != 0 && bits != ones)? - } - _ => true, - }, - Inst::VectorExtractDynamic { index, .. } - | Inst::VectorInsertDynamic { index, .. } => { - matches!(m.value(*index)?.origin, ValueOrigin::Const(_)) - } - Inst::Call { func, .. } => { - if let Some(s) = self.walked_fn.get_mut(func.index()).filter(|s| **s != w) { - *s = w; - self.calls.push(func.index() as u32); - } - true - } - _ => true, - }; - if !defined { - return Ok(false); - } - } - Ok(true) - } -} - -/// The merge block of the selection block `header` heads, if it heads one. -fn merge_of(m: &TypedModule, header: usize) -> Option { - match m.blocks().get(header)?.merge { - Some(Merge::Selection { merge }) => Some(merge), - _ => None, - } -} - -/// Call `f` on each block `term` may branch to. -fn targets(term: &Terminator, mut f: impl FnMut(BlockId)) { - match term { - Terminator::Branch(t) => f(*t), - Terminator::CondBranch { t, f: e, .. } => { - f(*t); - f(*e); - } - Terminator::Switch { default, cases, .. } => { - f(*default); - for &(_, t) in cases { - f(t); - } - } - _ => {} - } -} diff --git a/crates/metal2vulkan/src/spirv/requirements/snapshot/tests.rs b/crates/metal2vulkan/src/spirv/requirements/snapshot/tests.rs deleted file mode 100644 index dc5b17b2f..000000000 --- a/crates/metal2vulkan/src/spirv/requirements/snapshot/tests.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! [`snapshot_textures`] on hand-built fragment modules: a fetched value that reaches only -//! arithmetic and an output qualifies, directly, through a variable or through a call; one that -//! reaches a derivative, an implicit sample, a quad operation, an integer divisor or a dynamic -//! index, a store elsewhere, an atomic or an image write, directly, through a variable, or into -//! and out of a callee, does not; nor does a module with an interlock or a coherent resource, of a -//! function that writes memory, or a slot past 127. A selection on it qualifies where its arms -//! leave through its merge alone and hold nothing tangled, no loop and no undefined operand, and -//! what its arms leave behind reaches nothing that leaves the slot out. Each slot left out is -//! stated with the clauses that leave it out. - -use super::snapshot_textures; -use crate::budget::{Budget, Meter}; -use crate::pipeline::interface::SnapshotRefusal; -use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, KillForm, LoopSpec}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::ids::{TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, AtomicOp, BinOp, ConstBits, Constant, ConvOp, DerivOp, Dim, ExecMode, - ExecModel, ImageOperands, ImageType, ImageUsage, IoDir, LayoutRule, MemAccess, QuadDirection, - Scope, Semantics, StorageClass, TexelMemory, Type, TypedModule, -}; - -/// Where slot 0's fetched value goes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Sink { - /// Added to itself and stored to a `Private` variable. - Output, - /// Through a `Function` variable to the output. - ThroughVariable, - /// Its derivative stored to the output. - Derivative, - /// Through a `Function` variable to a derivative. - DerivativeThroughVariable, - /// Compared, and the comparison branched on. - Branch, - /// The coordinate of an implicit-level sample of slot 1. - SampleCoordinate, - /// An output, in a module whose entry also holds an interlock. - Interlocked, - /// Through a call whose callee returns its square. - ThroughCall, - /// Its derivative, of a call's result that returns it. - DerivativeOfCall, - /// Through a call whose callee branches on it. - BranchInCall, - /// Stored in a variable whose pointer a callee takes, loads through, and branches on. - BranchInCallThroughPointer, - /// Handed to a callee that stores it through a pointer the caller loads and branches on. - StoredByCallee, - /// Its bits the divisor of an unsigned division. - Divisor, - /// Its bits the dividend of an unsigned division by 3. - UnsignedDividend, - /// Its bits the dividend of a signed division by 3. - SignedDividend, - /// Its bits the dividend of a signed division by -1. - SignedDividendByMinusOne, - /// Its bits, masked, the index of a dynamic extract. - DynamicIndex, - /// The vector of a dynamic extract at a constant index. - DynamicVector, - /// Compared, and the invocation demoted where the comparison holds. - DemoteGuard, - /// Compared, and the invocation demoted in the else arm of the comparison. - DemoteInElse, - /// Compared, and the invocation demoted and the output written where the comparison holds. - DemoteAndStore, - /// Compared, the invocation demoted where the comparison holds, and the arms' different values - /// merged. - DemoteMergingValues, - /// Swapped across the quad. - QuadSwap, - /// Compared, and an arm on the comparison stores the position to a `Private` variable. - ArmStores, - /// Compared, and an arm on the comparison takes a derivative of the position. - ArmDerivative, - /// Compared, and an arm on the comparison calls a callee that takes a derivative. - ArmCallsDerivative, - /// Compared, and an arm on the comparison ends the invocation. - ArmKills, - /// Compared, and an arm on the comparison runs a loop. - ArmLoop, - /// Compared, and an arm on the comparison divides by the position's bits. - ArmDivides, - /// Compared, and a loop left where the comparison holds. - LoopExit, - /// Compared, an arm on the comparison storing to a `Function` variable whose value after the - /// merge reaches a derivative. - ArmToDerivative, - /// Compared, the arms' different values of the position merged and the merge's derivative - /// taken. - MergeToDerivative, - /// Its bits stored to a storage buffer's word. - StorageStore, - /// Its bits added to a storage buffer's word by an atomic. - AtomicAdd, - /// Written to a storage image of slot 3. - ImageWrite, - /// An output, in a module whose storage image of slot 3 is `Coherent`. - CoherentImage, -} - -/// Whether lane 0 of `v` is above one half. -fn above_half(f: &mut FunctionBuilder<'_>, v: Value, f32_: TypeId) -> Value { - let x = f.composite_extract(v, &[0]).expect("x"); - let half = scalar(f, f32_, u64::from(0.5f32.to_bits())); - f.binary(BinOp::FOrdGreaterThan, x, half).expect("compare") -} - -/// Branch on whether lane 0 of `v` is above one half. -fn branch_on(f: &mut FunctionBuilder<'_>, v: Value, f32_: TypeId) { - let c = above_half(f, v, f32_); - let arm: crate::spirv::builder::constructs::ArmFn<'_, ()> = - Box::new(|_, _| Ok(ArmEnd::FallThrough(Vec::new()))); - f.if_(&mut (), c, arm, None).expect("if"); -} - -fn scalar(f: &mut FunctionBuilder<'_>, ty: crate::spirv::ids::TypeId, bits: u64) -> Value { - let c = f - .module() - .constant(Constant::Scalar { - ty, - bits: ConstBits(bits), - }) - .expect("constant"); - f.module().const_value(c).expect("value") -} - -fn module(sink: Sink) -> TypedModule { - let mut b = ModuleBuilder::new(); - let u32_ = b - .ty(Type::Int { - width: 32, - signed: false, - }) - .expect("uint"); - let f32_ = b.ty(Type::Float { width: 32 }).expect("float"); - let vec2 = b.ty(Type::Vector { elem: f32_, len: 2 }).expect("vec2"); - let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 }).expect("vec4"); - let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 }).expect("uvec2"); - let image = b - .ty(Type::Image(ImageType { - sampled_type: f32_, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: false, - usage: ImageUsage::Sampled, - format: crate::spv::ImageFormat::Unknown, - })) - .expect("image"); - let sampled = b.ty(Type::SampledImage { image }).expect("sampled image"); - let t = b - .resource( - ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Texture, - index: 0, - }, - StorageClass::UniformConstant, - image, - ) - .expect("slot 0"); - let u = b - .resource( - ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::CombinedTextureSampler(CombinedSampler::new( - SamplerRef::Slot(1), - false, - false, - )), - index: 1, - }, - StorageClass::UniformConstant, - sampled, - ) - .expect("slot 1"); - // A storage buffer of words at buffer slot 2, and a float storage image at texture slot 3, - // for the sinks that write them. - let words = match sink { - Sink::StorageStore | Sink::AtomicAdd => { - let rta = b - .ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - }) - .expect("array"); - let layout = - natural_layout(b.types(), LayoutRule::Std430, true, &[rta]).expect("layout"); - let block = b - .ty(Type::Struct { - members: [rta].into(), - layout: Some(layout), - }) - .expect("block"); - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Buffer, - index: 2, - }; - Some( - b.resource(slot, StorageClass::StorageBuffer, block) - .expect("slot 2"), - ) - } - _ => None, - }; - let storage = match sink { - Sink::ImageWrite | Sink::CoherentImage => { - let ty = b - .ty(Type::Image(ImageType { - sampled_type: f32_, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: false, - usage: ImageUsage::Storage, - format: crate::spv::ImageFormat::Rgba32f, - })) - .expect("storage image"); - let slot = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::Texture, - index: 3, - }; - let g = b - .resource(slot, StorageClass::UniformConstant, ty) - .expect("slot 3"); - if sink == Sink::CoherentImage { - b.coherent(g).expect("coherent"); - } - Some(g) - } - _ => None, - }; - let out = b - .builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4) - .expect("FragCoord"); - let color = b - .plain_global(StorageClass::Private, vec4, None) - .expect("color"); - let i32_ = b - .ty(Type::Int { - width: 32, - signed: true, - }) - .expect("int"); - let void = b.ty(Type::Void).expect("void"); - let ptr = b - .ty(Type::Pointer { - class: StorageClass::Function, - pointee: vec4, - }) - .expect("pointer"); - let callee = match sink { - Sink::ArmCallsDerivative => { - let mut g = b.function(vec4).expect("routine"); - let x = g.param(vec4).expect("x"); - let d = g.derivative(DerivOp::DPdx, x).expect("derivative"); - g.ret(Some(d)).expect("ret"); - Some(g.finish().expect("callee")) - } - Sink::ThroughCall | Sink::DerivativeOfCall | Sink::BranchInCall => { - let mut g = b.function(vec4).expect("routine"); - let x = g.param(vec4).expect("x"); - let y = match sink { - Sink::BranchInCall => { - branch_on(&mut g, x, f32_); - x - } - _ => g.binary(BinOp::FMul, x, x).expect("square"), - }; - g.ret(Some(y)).expect("ret"); - Some(g.finish().expect("callee")) - } - Sink::BranchInCallThroughPointer => { - let mut g = b.function(void).expect("routine"); - let p = g.param(ptr).expect("p"); - let v = g.load(p, MemAccess::default()).expect("load"); - branch_on(&mut g, v, f32_); - g.ret(None).expect("ret"); - Some(g.finish().expect("callee")) - } - Sink::StoredByCallee => { - let mut g = b.function(void).expect("routine"); - let p = g.param(ptr).expect("p"); - let x = g.param(f32_).expect("x"); - let zero = scalar(&mut g, u32_, 0); - let e = g.access_chain(p, &[zero]).expect("lane"); - g.store(e, x, MemAccess::default()).expect("store"); - g.ret(None).expect("ret"); - Some(g.finish().expect("callee")) - } - _ => None, - }; - let mut f = b.function(void).expect("main"); - let tv = f.module().global_value(t).expect("t"); - let uv = f.module().global_value(u).expect("u"); - let position = f.module().global_value(out).expect("position"); - let cv = f.module().global_value(color).expect("color"); - let img = f.load(tv, MemAccess::default()).expect("t image"); - let zero = scalar(&mut f, u32_, 0); - let coord = f.composite_construct(uvec2, &[zero, zero]).expect("coord"); - let ops = ImageOperands { - lod: Some(zero), - ..ImageOperands::default() - }; - if sink == Sink::Interlocked { - f.begin_interlock().expect("begin"); - } - let texel = f.fetch(img, coord, &ops).expect("fetch"); - if sink == Sink::Interlocked { - f.end_interlock().expect("end"); - } - let value = match sink { - Sink::Output | Sink::Interlocked | Sink::CoherentImage => { - f.binary(BinOp::FAdd, texel, texel).expect("sum") - } - Sink::QuadSwap => f - .group_quad_swap(texel, QuadDirection::Horizontal) - .expect("quad swap"), - Sink::StorageStore | Sink::AtomicAdd => { - let words = f - .module() - .global_value(words.expect("words")) - .expect("words"); - let word = f.access_chain(words, &[zero, zero]).expect("word"); - let x = f.composite_extract(texel, &[0]).expect("x"); - let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits"); - match sink { - Sink::StorageStore => f.store(word, bits, MemAccess::default()).expect("store"), - _ => { - f.atomic( - AtomicOp::IAdd, - word, - Scope::Device, - Semantics::RELAXED, - bits, - ) - .expect("atomic"); - } - } - texel - } - Sink::ImageWrite => { - let g = f - .module() - .global_value(storage.expect("storage")) - .expect("image"); - let image = f.load(g, MemAccess::default()).expect("storage image"); - f.write( - image, - coord, - texel, - &ImageOperands::default(), - TexelMemory::Private { volatile: false }, - ) - .expect("write"); - texel - } - Sink::ThroughVariable | Sink::DerivativeThroughVariable => { - let var = f.local_var(vec4, None).expect("var"); - let p = f.var_ptr(var).expect("pointer"); - f.store(p, texel, MemAccess::default()).expect("store"); - let back = f.load(p, MemAccess::default()).expect("load"); - match sink { - Sink::DerivativeThroughVariable => { - f.derivative(DerivOp::DPdx, back).expect("derivative") - } - _ => back, - } - } - Sink::Derivative => f.derivative(DerivOp::DPdx, texel).expect("derivative"), - Sink::Branch => { - branch_on(&mut f, texel, f32_); - texel - } - Sink::ThroughCall | Sink::BranchInCall | Sink::DerivativeOfCall => { - let callee = callee.expect("callee"); - let r = f.call(callee, &[texel]).expect("call").expect("result"); - match sink { - Sink::DerivativeOfCall => f.derivative(DerivOp::DPdx, r).expect("derivative"), - _ => r, - } - } - Sink::BranchInCallThroughPointer | Sink::StoredByCallee => { - let callee = callee.expect("callee"); - let var = f.local_var(vec4, None).expect("var"); - let p = f.var_ptr(var).expect("pointer"); - if sink == Sink::StoredByCallee { - let x = f.composite_extract(texel, &[0]).expect("x"); - f.call(callee, &[p, x]).expect("call"); - let back = f.load(p, MemAccess::default()).expect("load"); - branch_on(&mut f, back, f32_); - } else { - f.store(p, texel, MemAccess::default()).expect("store"); - f.call(callee, &[p]).expect("call"); - } - texel - } - Sink::Divisor | Sink::UnsignedDividend => { - let x = f.composite_extract(texel, &[0]).expect("x"); - let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits"); - let other = scalar(&mut f, u32_, 3); - let (a, d) = match sink { - Sink::Divisor => (other, bits), - _ => (bits, other), - }; - f.binary(BinOp::UDiv, a, d).expect("quotient"); - texel - } - Sink::SignedDividend | Sink::SignedDividendByMinusOne => { - let x = f.composite_extract(texel, &[0]).expect("x"); - let bits = f.convert(ConvOp::Bitcast, x, i32_).expect("bits"); - let d = match sink { - Sink::SignedDividend => 3, - _ => u64::from(u32::MAX), - }; - let d = scalar(&mut f, i32_, d); - f.binary(BinOp::SDiv, bits, d).expect("quotient"); - texel - } - Sink::DynamicIndex | Sink::DynamicVector => { - let index = match sink { - Sink::DynamicIndex => { - let x = f.composite_extract(texel, &[0]).expect("x"); - let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits"); - let three = scalar(&mut f, u32_, 3); - f.binary(BinOp::BitwiseAnd, bits, three).expect("index") - } - _ => zero, - }; - f.vector_extract_dynamic(texel, index).expect("lane"); - texel - } - Sink::DemoteGuard | Sink::DemoteAndStore => { - let c = above_half(&mut f, texel, f32_); - let store = sink == Sink::DemoteAndStore; - let arm: crate::spirv::builder::constructs::ArmFn<'_, ()> = Box::new(move |f, _| { - f.demote()?; - if store { - f.store(cv, texel, MemAccess::default())?; - } - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), c, arm, None).expect("if"); - texel - } - Sink::DemoteInElse | Sink::DemoteMergingValues => { - let c = above_half(&mut f, texel, f32_); - let merging = sink == Sink::DemoteMergingValues; - let other = f.binary(BinOp::FAdd, texel, texel).expect("sum"); - let kept: crate::spirv::builder::constructs::ArmFn<'_, ()> = Box::new(move |_, _| { - Ok(ArmEnd::FallThrough(match merging { - true => vec![other], - false => Vec::new(), - })) - }); - let demoted: crate::spirv::builder::constructs::ArmFn<'_, ()> = - Box::new(move |f, _| { - f.demote()?; - Ok(ArmEnd::FallThrough(match merging { - true => vec![texel], - false => Vec::new(), - })) - }); - let merged = f.if_(&mut (), c, kept, Some(demoted)).expect("if"); - merged.0.first().copied().unwrap_or(texel) - } - Sink::ArmStores - | Sink::ArmDerivative - | Sink::ArmCallsDerivative - | Sink::ArmKills - | Sink::ArmLoop - | Sink::ArmDivides => { - let c = above_half(&mut f, texel, f32_); - let pos = f.load(position, MemAccess::default()).expect("position"); - let arm: ArmFn<'_, ()> = Box::new(move |f, _| { - match sink { - Sink::ArmStores => f.store(cv, pos, MemAccess::default())?, - Sink::ArmDerivative => { - f.derivative(DerivOp::DPdx, pos)?; - } - Sink::ArmCallsDerivative => { - f.call(callee.expect("callee"), &[pos])?; - } - Sink::ArmKills => { - f.kill(KillForm::Kill)?; - return Ok(ArmEnd::Exits); - } - Sink::ArmLoop => { - f.loop_( - &mut (), - LoopSpec::default(), - Box::new(|f, _, exits| exits.break_(f)), - )?; - } - _ => { - let x = f.composite_extract(pos, &[0])?; - let bits = f.convert(ConvOp::Bitcast, x, u32_)?; - let three = scalar(f, u32_, 3); - f.binary(BinOp::UDiv, three, bits)?; - } - } - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), c, arm, None).expect("if"); - texel - } - Sink::LoopExit => { - let c = above_half(&mut f, texel, f32_); - let body: crate::spirv::builder::constructs::LoopFn<'_, ()> = - Box::new(move |f, _, exits| { - let arm: ArmFn<'_, ()> = Box::new(move |f, _| { - exits.break_(f)?; - Ok(ArmEnd::Exits) - }); - f.if_(&mut (), c, arm, None)?; - Ok(()) - }); - f.loop_(&mut (), LoopSpec::default(), body).expect("loop"); - texel - } - Sink::ArmToDerivative | Sink::MergeToDerivative => { - let c = above_half(&mut f, texel, f32_); - let pos = f.load(position, MemAccess::default()).expect("position"); - let twice = f.binary(BinOp::FAdd, pos, pos).expect("twice"); - let left = match sink { - Sink::ArmToDerivative => { - let var = f.local_var(vec4, None).expect("var"); - let p = f.var_ptr(var).expect("pointer"); - f.store(p, pos, MemAccess::default()).expect("store"); - let arm: ArmFn<'_, ()> = Box::new(move |f, _| { - f.store(p, twice, MemAccess::default())?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), c, arm, None).expect("if"); - f.load(p, MemAccess::default()).expect("load") - } - _ => { - let then: ArmFn<'_, ()> = - Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![pos]))); - let other: ArmFn<'_, ()> = - Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![twice]))); - let merged = f.if_(&mut (), c, then, Some(other)).expect("if"); - merged.0.first().copied().expect("merged") - } - }; - f.derivative(DerivOp::DPdx, left).expect("derivative"); - texel - } - Sink::SampleCoordinate => { - let si = f.load(uv, MemAccess::default()).expect("u"); - let xy = f.vector_shuffle(texel, texel, &[0, 1]).expect("xy"); - let _ = vec2; - f.sample(si, xy, None, false, &ImageOperands::default()) - .expect("sample") - } - }; - f.store(cv, value, MemAccess::default()).expect("output"); - f.ret(None).expect("ret"); - let main = f.finish().expect("finish"); - let modes = match sink { - Sink::Interlocked => vec![ExecMode::PixelInterlockOrdered], - _ => Vec::new(), - }; - b.entry(ExecModel::Fragment, main, modes).expect("entry"); - b.finalize().expect("finalize") -} - -/// A fetched value that reaches arithmetic and a color output alone, directly, through a -/// `Function` variable or through a call, qualifies, as does an unsigned dividend, a signed one -/// beside a constant divisor without `-1`, and a dynamically indexed vector; a derivative of it, -/// directly, through a variable or of a call's result, an implicit sample at it, a quad swap of -/// it, a divisor, a signed dividend beside `-1`, a dynamic index, a store of it to a storage -/// buffer, an atomic of it, or an image write of it leaves the slot out, as does an interlock or a -/// coherent resource anywhere in the module. A selection on it qualifies, in the entry or in a -/// callee it reaches as an argument, through a pointer argument's memory or back out of it: with -/// an arm that is empty, demotes (in either arm, also writing, or with the arms' values merging -/// apart) or stores to a `Private` variable. One whose arm takes a derivative or calls a function -/// that does, ends the invocation, runs a loop or divides by a value that is not a constant leaves -/// the slot out for its branch, as does a loop it leaves; one whose arm's store or whose merge's -/// phi reaches a derivative, for the derivative. Each slot left out is stated with the one clause -/// that leaves it out. The analysis releases every charge. -#[test] -fn only_values_no_helper_can_pass_on_qualify() { - use SnapshotRefusal as R; - for (sink, refused) in [ - (Sink::Output, None), - (Sink::ThroughVariable, None), - (Sink::Derivative, Some(R::Derivative)), - (Sink::DerivativeThroughVariable, Some(R::Derivative)), - (Sink::Branch, None), - (Sink::SampleCoordinate, Some(R::Sample)), - (Sink::Interlocked, Some(R::Interlock)), - (Sink::ThroughCall, None), - (Sink::DerivativeOfCall, Some(R::Derivative)), - (Sink::BranchInCall, None), - (Sink::BranchInCallThroughPointer, None), - (Sink::StoredByCallee, None), - (Sink::Divisor, Some(R::UndefinedOperand)), - (Sink::UnsignedDividend, None), - (Sink::SignedDividend, None), - (Sink::SignedDividendByMinusOne, Some(R::UndefinedOperand)), - (Sink::DynamicIndex, Some(R::UndefinedOperand)), - (Sink::DynamicVector, None), - (Sink::DemoteGuard, None), - (Sink::DemoteInElse, None), - (Sink::DemoteAndStore, None), - (Sink::DemoteMergingValues, None), - (Sink::ArmStores, None), - (Sink::ArmDerivative, Some(R::Branch)), - (Sink::ArmCallsDerivative, Some(R::Branch)), - (Sink::ArmKills, Some(R::Branch)), - (Sink::ArmLoop, Some(R::Branch)), - (Sink::ArmDivides, Some(R::Branch)), - (Sink::LoopExit, Some(R::Branch)), - (Sink::ArmToDerivative, Some(R::Derivative)), - (Sink::MergeToDerivative, Some(R::Derivative)), - (Sink::QuadSwap, Some(R::GroupOperation)), - (Sink::StorageStore, Some(R::Store)), - (Sink::AtomicAdd, Some(R::Atomic)), - (Sink::ImageWrite, Some(R::ImageWrite)), - (Sink::CoherentImage, Some(R::Coherent)), - ] { - let mut meter = Meter::new(&Budget::default()); - let judged = snapshot_textures(&module(sink), &[0], false, &mut meter).expect("analysis"); - assert_eq!(meter.ledger(), 0, "{sink:?}: every charge released"); - let (slots, refusals): (&[u32], Vec<(u32, SnapshotRefusal)>) = match refused { - None => (&[0], Vec::new()), - Some(why) => (&[], vec![(0, why)]), - }; - assert_eq!(judged.slots, slots, "{sink:?}"); - assert_eq!(judged.refusals, refusals, "{sink:?}"); - } -} - -/// A function that writes memory leaves every slot out for it, beside what the walk finds of its -/// values: the qualifying output alone, and the derivative too. A slot past 127 is left out -/// unwalked, beside a slot below it that qualifies. -#[test] -fn a_slot_left_out_by_the_function_or_its_index_says_so() { - use SnapshotRefusal as R; - let mut meter = Meter::new(&Budget::default()); - let mut judged = |sink: Sink, own: &[u32], writes: bool| { - snapshot_textures(&module(sink), own, writes, &mut meter).expect("analysis") - }; - let written = judged(Sink::Output, &[0], true); - assert!(written.slots.is_empty(), "writes memory"); - assert_eq!(written.refusals, [(0, R::WritesMemory)], "writes memory"); - let both = judged(Sink::Derivative, &[0], true); - assert_eq!( - both.refusals, - [(0, R::Derivative), (0, R::WritesMemory)], - "writes memory, and a derivative" - ); - let past = judged(Sink::Output, &[0, 200], false); - assert_eq!(past.slots, [0], "slot 0 qualifies"); - assert_eq!(past.refusals, [(200, R::Other)], "slot 200 is not walked"); - assert_eq!(meter.ledger(), 0, "every charge released"); -} diff --git a/crates/metal2vulkan/src/spirv/requirements/writes.rs b/crates/metal2vulkan/src/spirv/requirements/writes.rs index 814886fcd..1daf54ee6 100644 --- a/crates/metal2vulkan/src/spirv/requirements/writes.rs +++ b/crates/metal2vulkan/src/spirv/requirements/writes.rs @@ -24,17 +24,10 @@ //! The trace also ends at an `OpIAdd` whose one operand is a load of the address member, whatever //! the other: the guest does not hold the address, so no sum of the guest's has such an operand. //! -//! The shader-side stencil's shadow (`Synthetic(ShadowStencil)`) is the product's too: its writes -//! carry Metal's stencil test, which Metal applies per sample whether the function runs per pixel -//! or per sample, so they do not make the function run per sample. An image write counts unless its -//! image is a load of that binding. -//! -//! So is a color attachment's interlocked storage form (`TileAttachment`): its writes carry -//! Metal's color attachment write, a -//! color output, which Metal masks as it masks any (a sample mask, a failed test) and stores per -//! sample whether the function runs per pixel or per sample, and which no other invocation or -//! command reads but through the attachment. A multisampled pipeline's storage form runs per sample -//! by its own `SampleId`. The function's other writes count as before. +//! A tile function's color attachment (`TileAttachment`) is the product's too: its writes carry +//! Metal's color attachment write, a color output, which no other invocation or command reads but +//! through the attachment. An image write counts unless its image is a load of that binding. The +//! function's other writes count as before. #[cfg(test)] mod tests; @@ -93,8 +86,7 @@ fn class(m: &TypedModule, ptr: Value) -> BResult { struct Status<'m> { /// The variables of the `Synthetic(ExecutionStatus)` binding. bindings: Vec, - /// The variables of the `Synthetic(ShadowStencil)`, `TileAttachment` and `SnapshotTexels` - /// bindings, and the loads of them. + /// The variables of the `TileAttachment` bindings, and the loads of them. shadows: Vec, /// The push block's variable. block: Option, @@ -119,12 +111,7 @@ impl<'m> Status<'m> { s.bindings.push(g.value); } GlobalKind::Resource(slot) - if matches!( - slot.kind, - ResourceKind::Synthetic(SyntheticBinding::ShadowStencil) - | ResourceKind::TileAttachment(_) - | ResourceKind::SnapshotTexels(_) - ) => + if matches!(slot.kind, ResourceKind::TileAttachment(_)) => { s.shadows.push(g.value); } @@ -178,8 +165,8 @@ impl<'m> Status<'m> { Ok(s) } - /// Whether image `image` is the product's (the shadow of a shader-side stencil, the depth's - /// stand-in, a color's storage form or `half` shadow): a load of its binding. + /// Whether image `image` is the product's (a tile function's color attachment): a load of its + /// binding. fn shadow(&self, image: Value) -> bool { self.shadows.contains(&image) } diff --git a/crates/metal2vulkan/src/spirv/requirements/writes/tests.rs b/crates/metal2vulkan/src/spirv/requirements/writes/tests.rs index ca37976ed..0841e27a7 100644 --- a/crates/metal2vulkan/src/spirv/requirements/writes/tests.rs +++ b/crates/metal2vulkan/src/spirv/requirements/writes/tests.rs @@ -234,20 +234,10 @@ fn image_write(kind: ResourceKind) -> TypedModule { fragment(b, main) } -/// The shader-side stencil's shadow is the product's, so its writes do not make the function run -/// per sample; a write of another storage image (the function's texture) does. -#[test] -fn the_shadow_stencils_writes_are_not_the_functions() { - let shadow = ResourceKind::Synthetic(SyntheticBinding::ShadowStencil); - assert!(!writes_memory(&image_write(shadow)).expect("shadow")); - let imageblock = ResourceKind::Synthetic(SyntheticBinding::Imageblock); - assert!(writes_memory(&image_write(imageblock)).expect("another image")); -} - -/// A color's interlocked storage form is the product's, carrying Metal's color attachment write, +/// A tile function's color attachment is the product's, carrying Metal's color attachment write, /// so its writes are not the function's; a texture's write is. #[test] -fn a_colors_storage_form_writes_are_not_the_functions() { +fn a_tile_attachments_writes_are_not_the_functions() { let color = ResourceKind::TileAttachment(2); assert!(!writes_memory(&image_write(color)).expect("color")); assert!(writes_memory(&image_write(ResourceKind::Texture)).expect("a texture")); diff --git a/crates/metal2vulkan/src/tests/bind_shape_of.rs b/crates/metal2vulkan/src/tests/bind_shape_of.rs index 17c4fdf87..db45b0b9d 100644 --- a/crates/metal2vulkan/src/tests/bind_shape_of.rs +++ b/crates/metal2vulkan/src/tests/bind_shape_of.rs @@ -5,7 +5,7 @@ use crate::bind::{ ArgumentFunctionTable, ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture, - BufferRanges, FragmentTests, ImageblockSize, ResourceClass, SamplerDescriptor, StageTable, + BufferRanges, ImageblockSize, ResourceClass, SamplerDescriptor, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts, TileThreadgroupArgument, TileThreadgroupMemory, UsedResource, VertexAmplification, }; @@ -247,10 +247,6 @@ fn states() -> Vec { }), with(|s| s.kept_imageblock_bytes = Some(8)), with(|s| s.depth_clamp_range = Some([0.0, 1.0])), - with(|s| { - s.interlocked_colors.insert(1); - }), - with(|s| s.fragment_tests = FragmentTests::Pass), with(|s| s.quad_primitive_ids = true), with(|s| s.private_list = true), ] diff --git a/crates/metal2vulkan/src/tests/engine_absent_value_arguments.rs b/crates/metal2vulkan/src/tests/engine_absent_value_arguments.rs index 41c2827c8..7f39a7dc9 100644 --- a/crates/metal2vulkan/src/tests/engine_absent_value_arguments.rs +++ b/crates/metal2vulkan/src/tests/engine_absent_value_arguments.rs @@ -17,15 +17,14 @@ use std::sync::Arc; use crate::budget::SPIRV_WORDS; use crate::device::{DevicePolicy, DeviceProfile}; -use crate::error::{Error, RuntimeInput}; +use crate::error::Error; use crate::library::{FunctionArtifact, FunctionConstantValue, FunctionConstantValues}; use crate::lower::select::Plan; -use crate::metal::{DataType, PixelFormat}; +use crate::metal::DataType; use crate::pipeline::compile::{compile_bitcode, EntryRef}; -use crate::pipeline::descriptor::ColorAttachmentDescriptor; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; -use crate::pipeline::lower_inputs::{FramebufferFetchInputs, LoweringInputs}; +use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::stage_io::{IoRole, StageBuiltin}; use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; use crate::pipeline::testing::{ @@ -279,42 +278,13 @@ fn each_fragment_input_gated_on_is_declared() { barycentric.interface.io.builtins ); link_and_validate(&barycentric, &p).expect("has_barycentric: L3"); - // `moltenvk-m3` orders a fetch only through the pixel interlock: the color input reads its - // attachment in the interlocked storage form under its pipeline's state, which a standalone - // compile does not have. - match compile_with(&bc, entry, &[HAS_PRIOR], &p) { - Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)) => {} - other => panic!("declared color input: {:?}", other.map(|_| ())), - } - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &[Some(ColorAttachmentDescriptor::new( - PixelFormat::RGBA8Unorm, - ))], - false, - false, - 1, - )); - let prior = compile_bitcode( - &bc, - EntryRef::Name(entry), - &constants(&[HAS_PRIOR]), - &p, - &inputs, - &mut meter(), - SPIRV_WORDS, - ) - .expect("has_prior"); + // The color input reads its input attachment. + let prior = compile_with(&bc, entry, &[HAS_PRIOR], &p).expect("has_prior"); assert!( - prior.facts.iter().any(|f| matches!( - f, - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes: true, - .. - } - )), + prior + .facts + .iter() + .any(|f| matches!(f, RuntimeFact::FramebufferFetch { color: 0 })), "{:?}", prior.facts ); diff --git a/crates/metal2vulkan/src/tests/engine_dead_fetch.rs b/crates/metal2vulkan/src/tests/engine_dead_fetch.rs index eb7abb652..b7c33a264 100644 --- a/crates/metal2vulkan/src/tests/engine_dead_fetch.rs +++ b/crates/metal2vulkan/src/tests/engine_dead_fetch.rs @@ -10,14 +10,10 @@ //! Specialized with the read dead (`dfk_reads` false, `dfk_weight` zero), each function reads //! 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, no storage attachment (no pixel interlock, no blend computed in the -//! shader) and no input attachment, its stages passing L3. Specialized with the read live, each -//! reads color 0 in the form the device orders a fetch by: a written storage attachment and no -//! color attachment where it orders fetch through the pixel interlock alone, an input attachment -//! where it orders it through rasterization-order input attachments, and an input attachment -//! ordered between draws alone where it has neither, its fragment stage noting -//! `UnorderedFetchWithinDraw`. Before the fetch state was decided from the specialized function's uses, a dead read -//! took the storage form on every interlock profile, with the blend computed in the shader. +//! 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 +//! fragment stage noting `UnorderedFetchWithinDraw`. //! No GPU is used. use std::path::Path; @@ -26,7 +22,7 @@ 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, interlock_orders}; +use crate::lower::fragment::inputs_order; use crate::metal::{BlendFactor, BlendOperation, DataType, PixelFormat}; use crate::pipeline::artifact::{PrecisionNote, RenderPipeline}; use crate::pipeline::descriptor::{ @@ -106,20 +102,10 @@ fn pipeline( dev.compile_render_pipeline(&d, &Budget::standard()) } -/// Each storage attachment of `pipe`: its color and whether the function writes it. -fn storage(pipe: &RenderPipeline) -> Vec<(u32, bool)> { - (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.writes)) - .collect() -} - /// The dead specialization's misses in `pipe` (color 0 `blended` or not): each way it differs from /// the pipeline of a function that declares no color input. fn dead_misses(pipe: &RenderPipeline, blended: bool) -> Vec<&'static str> { let mut out = Vec::new(); - if !pipe.graphics.storage_attachments.is_empty() { - out.push("it takes the storage form"); - } if !pipe.graphics.input_attachments.is_empty() { out.push("it takes an input attachment"); } @@ -137,8 +123,8 @@ fn a_framebuffer_read_dead_after_specialization_takes_no_fetch_form() { return; }; let mut misses = std::collections::BTreeMap::<&str, Vec>::new(); - // Pipelines checked dead, and live on an interlock profile. - let (mut dead, mut interlocked) = (0, 0); + // Pipelines checked dead. + let mut dead = 0; for (stem, p) in committed_profiles().expect("profiles") { let dev = device(&stem); for entry in ENTRIES { @@ -154,37 +140,24 @@ fn a_framebuffer_read_dead_after_specialization_takes_no_fetch_form() { .unwrap_or_else(|e| panic!("{what}, dead: L3: {e}")); } dead += 1; - let live = pipeline(&dev, &library, entry, true, blended); - if interlock_orders(&p) { - let pipe = live.unwrap_or_else(|e| panic!("{what}, live: {e}")); - assert_eq!(storage(&pipe), [(0, true)], "{what}, live"); - assert!( - pipe.graphics.color_attachments[0].is_none(), - "{what}, live: {:?}", - pipe.graphics.color_attachments[0] - ); - interlocked += 1; - } else { - // Rasterization-order input attachments, or with neither ordered form input - // attachments ordered between draws alone, noted. - let pipe = live.unwrap_or_else(|e| panic!("{what}, live: {e}")); - let read: Vec = (pipe.graphics.input_attachments.iter()) - .map(|u| u.color_index) - .collect(); - assert_eq!(read, [0], "{what}, live"); - assert_eq!(storage(&pipe), [], "{what}, live"); - let noted = (pipe.stages.iter()).any(|s| { - (s.precision_notes).contains(&PrecisionNote::UnorderedFetchWithinDraw) - }); - assert_eq!(noted, !inputs_order(&p), "{what}, live"); - } + // Rasterization-order input attachments, or input attachments 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()) + .map(|u| u.color_index) + .collect(); + assert_eq!(read, [0], "{what}, live"); + let noted = (pipe.stages.iter()).any(|s| { + (s.precision_notes).contains(&PrecisionNote::UnorderedFetchWithinDraw) + }); + assert_eq!(noted, !inputs_order(&p), "{what}, live"); } } } - eprintln!("{dead} dead pipelines, {interlocked} live interlocked ones"); + eprintln!("{dead} dead pipelines"); for (kind, whats) in &misses { eprintln!("{}: {kind} (first: {})", whats.len(), whats[0]); } assert!(misses.is_empty(), "{misses:#?}"); - assert!(interlocked > 0, "no interlock profile checked"); } diff --git a/crates/metal2vulkan/src/tests/engine_dead_reads.rs b/crates/metal2vulkan/src/tests/engine_dead_reads.rs index e07d018f3..19dd77282 100644 --- a/crates/metal2vulkan/src/tests/engine_dead_reads.rs +++ b/crates/metal2vulkan/src/tests/engine_dead_reads.rs @@ -8,11 +8,12 @@ //! draws `dfr_color` (a color 0 input in group 0) and `dfr_buffer` (a buffer in group 0) over //! 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, each takes the -//! pixel interlock where the device has it, and is refused where it has neither interlock but -//! orders a color read in rasterization order. On a device with neither ordered fetch form -//! (`vk12-floor`) the group on `dfr_output`'s color orders only what its read orders there: the -//! input attachment, between draws, compiled without an interlock and noted +//! 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 //! (`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 @@ -128,11 +129,10 @@ fn interlocks(words: &[u32]) -> bool { false } -/// Whether `dev` orders framebuffer fetch in neither form: no rasterization-order color attachment -/// access and no pixel interlock. +/// Whether `dev` orders framebuffer fetch between draws alone: no rasterization-order color +/// attachment access. fn unordered(dev: &Device) -> bool { - let f = dev.profile().fragment(); - !f.rasterization_order_color_access && !f.pixel_interlock + !dev.profile().fragment().rasterization_order_color_access } fn fragment(p: &RenderPipeline) -> &[u32] { @@ -153,10 +153,11 @@ fn validate(p: &RenderPipeline, dev: &Device, what: &str) { /// A raster order group on an input the specialized body never reads orders nothing (the module /// docs): dead, `dfr_color`, `dfr_buffer` (five colors) and `dfr_output` (one) compile without an /// interlock on `lavapipe`, `moltenvk-m3` and `moltenvk-m3` without either interlock, and -/// `dfr_output` on `vk12-floor` (no interlock); live, each interlocks where the device has the -/// pixel interlock, and is refused on `moltenvk-m3` without either interlock. `dfr_output` live on -/// `vk12-floor`, which has neither ordered fetch form, reads its color as the input attachment -/// without an interlock, its fragment stage noting `UnorderedFetchWithinDraw`. +/// `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`. #[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 { @@ -209,13 +210,9 @@ fn a_raster_order_group_on_an_input_dead_after_specialization_takes_no_interlock let live = dev.compile_render_pipeline(&specialized(&vs, &fs, entry, colors, true), &budget); match (interlock, live) { - (true, Ok(p)) => { - assert!(interlocks(fragment(&p)), "{what}: no interlock"); - validate(&p, dev, &what); - } - // Neither ordered fetch form: the group orders the color read alone, which is ordered - // between draws there. - (false, Ok(p)) if unordered(dev) => { + // 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" => { assert!(!interlocks(fragment(&p)), "{what}: interlocked"); assert_eq!(p.graphics.input_attachments.len(), 1, "{what}"); let noted = (p.stages.iter()).any(|m| { @@ -225,8 +222,12 @@ fn a_raster_order_group_on_an_input_dead_after_specialization_takes_no_interlock assert!(noted, "{what}: not noted"); validate(&p, dev, &what); } - // What the device lacks: the interlock, or a fetch form for a color read. - (false, Err(Error::Unsupported(_))) => {} + (true, Ok(p)) => { + assert!(interlocks(fragment(&p)), "{what}: no interlock"); + validate(&p, dev, &what); + } + // What the device lacks: the interlock. + (false, Err(Error::Unsupported(u))) if u.feature == Feature::RasterOrderGroups => {} (_, other) => panic!("{what}: {:?}", other.map(|_| ())), } } @@ -283,7 +284,6 @@ fn a_color_input_without_an_attachment_is_refused_dead_or_live() { .compile_render_pipeline(&d, &budget) .unwrap_or_else(|e| panic!("dfr_lacks dead with color 1 on {stem}: {e}")); assert!(p.graphics.input_attachments.is_empty(), "{stem}"); - assert!(p.graphics.storage_attachments.is_empty(), "{stem}"); validate(&p, &dev, stem); } for (kind, whats) in &misses { 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 312e4ad46..efbc61343 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/blended_pipelines.rs @@ -16,7 +16,8 @@ //! `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 in the storage form where the device orders fetch through the interlock. No GPU is used. +//! them over the input attachment where the device orders fetch through rasterization-order input +//! attachments. No GPU is used. //! //! `llvm-as` assembles the fixture `rt6_samples`; without it the tests skip visibly. @@ -120,11 +121,6 @@ fn attachment( a } -/// Whether `pipe` reads and writes color 0 in the interlocked storage form. -fn stored(pipe: &RenderPipeline) -> bool { - (pipe.graphics.storage_attachments.iter()).any(|u| u.color_index == 0) -} - /// Every shape a wide-gamut client makes writes the blended attachment, so each is refused on every /// venue, under a mask of every channel and of none alike. #[test] @@ -267,7 +263,6 @@ fn unwritten_and_masked_extended_range_attachments_are_made() { continue; }; made_count += 1; - assert!(!stored(&pipe), "{what}"); let a = pipe.graphics.color_attachments[0].expect("attachment"); assert!(a.blend.is_none(), "{what}"); assert_eq!(a.format, vk::Format::R16G16B16A16_UINT, "{what}"); @@ -347,17 +342,14 @@ 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: where the device orders fetch only through the pixel interlock, the function -/// merges its codes into the word it reads first, in the interlocked storage form (color 0 leaves -/// the subpass), at one sample and four, from a `half4` output and a `float4` one, and every stage -/// passes L3. On lavapipe, which orders fetch through rasterization-order input attachments, the -/// function merges them over the input attachment: 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 orders fetch in neither form the refusal names the -/// orderings the merge needs. Before, every venue refused the mask `NotImplemented(Format)` at link. +/// 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. #[test] -fn a_mask_of_some_codes_of_a_word_merges_them_in_the_storage_form() { +fn a_mask_of_some_codes_of_a_word_merges_them_over_the_input_attachment() { let Some(library) = library() else { return; }; @@ -388,7 +380,6 @@ fn a_mask_of_some_codes_of_a_word_merges_them_in_the_storage_form() { "runtime-floor", ] { let dev = device(stem); - let interlock = crate::lower::fragment::interlock_orders(dev.profile()); let inputs = crate::lower::fragment::inputs_order(dev.profile()); for pf in formats { for mask in masks { @@ -402,8 +393,7 @@ fn a_mask_of_some_codes_of_a_word_merges_them_in_the_storage_form() { format!("{stem} {pf:?} mask {} {fill} x{samples}", mask.as_raw()); match dev.compile_render_pipeline(&d, &Budget::standard()) { Ok(pipe) => { - assert!(interlock || inputs, "{what}"); - assert_eq!(stored(&pipe), interlock, "{what}"); + assert!(inputs, "{what}"); if inputs { let a = pipe.graphics.color_attachments[0].expect("attachment"); let form = ExtendedRange::of(pf).expect("a form"); @@ -436,7 +426,7 @@ fn a_mask_of_some_codes_of_a_word_merges_them_in_the_storage_form() { } merged += 1; } - Err(Error::Unsupported(u)) if !interlock && !inputs => { + Err(Error::Unsupported(u)) if !inputs => { assert_eq!(u.feature, unordered.feature, "{what}: {u:?}"); assert_eq!(u.needs, unordered.needs, "{what}: {u:?}"); } @@ -448,6 +438,6 @@ fn a_mask_of_some_codes_of_a_word_merges_them_in_the_storage_form() { } } } - // Four interlock venues at both counts, lavapipe at one sample. - assert_eq!(merged, (4 * 2 + 1) * formats.len() * masks.len() * 2); + // Lavapipe at one sample. + assert_eq!(merged, 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 2c9d3ffbd..80f8e6fd1 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs @@ -113,30 +113,18 @@ fn is_format_refusal(e: &Error) -> bool { /// [`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 only through the interlock (`compile::fetch_inputs`) or through rasterization-order -/// input attachments. +/// 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 blends_in_shader(p) { + if crate::lower::fragment::inputs_order(p) { inputs.framebuffer_fetch = Some(crate::pipeline::FramebufferFetchInputs::of( [0], &r.color_attachments, - false, - false, - 1, )); } inputs } -/// Whether `p` blends an extended-range attachment in the shader: in the storage form where it -/// orders fetch only through the interlock, over the input attachment where it orders fetch -/// through rasterization-order input attachments. -fn blends_in_shader(p: &crate::device::profile::DeviceProfile) -> bool { - crate::lower::fragment::interlock_orders(p) - || p.fields().fragment.rasterization_order_color_access -} - /// 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). @@ -332,8 +320,7 @@ fn fragment_outputs_to_bfloat_targets_write_raw_codes() { } } } - // Blended: Metal's pipeline error, in the lowering (by the storage form's plan where - // the device orders fetch only through the interlock) and at link, with no fragment + // Blended: Metal's pipeline error, in the lowering and at link, with no fragment // function too. let what = format!("{stem} {pf:?} blended"); let invalid = Error::InvalidDescriptor(DescriptorError::ColorAttachment { @@ -487,13 +474,20 @@ fn unmodelled_extended_range_targets_are_refused() { ); } form => { - // Merged by a stage compiled with the pipeline's fetch state, which this one - // was not (`blended_pipelines`). + // 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); - assert!( - matches!(e, Error::NeedsInput(RuntimeInput::FramebufferFetch)), - "{what} red mask: {e}" - ); + let unordered = crate::lower::fragment::fetch::unordered_extended_fetch(); + match (crate::lower::fragment::fetch::fetch_unordered(&p), e) { + (true, Error::Unsupported(u)) => assert_eq!( + (u.feature, u.needs), + (unordered.feature, unordered.needs), + "{what} red mask" + ), + (false, Error::NeedsInput(RuntimeInput::FramebufferFetch)) => {} + (_, e) => panic!("{what} red mask: {e}"), + } // The two-plane forms' three color codes alone are the color word, the // first raw component. if let ExtendedRange::Planes { .. } = form { diff --git a/crates/metal2vulkan/src/tests/engine_fetch_blend16.rs b/crates/metal2vulkan/src/tests/engine_fetch_blend16.rs deleted file mode 100644 index 64b441396..000000000 --- a/crates/metal2vulkan/src/tests/engine_fetch_blend16.rs +++ /dev/null @@ -1,303 +0,0 @@ -//! A fragment function that fetches a blended 16-bit float attachment, in the shape of a macOS 27 -//! window-server composite (the owned fixture `engine/fbl_fetch_blend16`): color 0 `RGBA16Float` -//! blended with one over one minus the source alpha for color and alpha, color 1 `RGBA16Float` of -//! mask none, each function reading color 0 under fast math. -//! -//! On every committed profile that orders fetch through the pixel interlock alone, each function -//! compiles with color 0 in the storage form and the blend it computes -//! (`RuntimeFact::InterlockedFramebufferFetch` names the blend, not rounded), and its module -//! passes L3; the whole pipeline is made there, color 0 a written storage attachment and no color -//! attachment of the subpass, its stages passing L3. `fbl_over_loaded` (a loaded `half4`) and -//! `fbl_over_loaded_float` (a loaded `float4`) output what Metal's compiler cannot fold into its -//! blend, so the blend is Metal's exactly and neither records `HalfOutputFastMathBlend`; -//! `fbl_over_product`'s product Metal folds into the blend, so it records the note. The same module -//! stating no fast math (`air.compile.fast_math_disable`) computes the rounded forms, exact, noted -//! by none, rounded in the fact. Before the shader computed the blend, each was refused -//! `NotImplemented(FramebufferFetch)` at color 0. A NaN of the blend is the device's arithmetic's, -//! which the storage image's store converts: every module records `DeviceNanEncoding`. No GPU is -//! used. -//! -//! `llvm-as` assembles the fixture; a missing tool skips visibly. - -use std::path::Path; - -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::library::{FunctionArtifact, Library}; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use crate::pipeline::artifact::PrecisionNote; -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::testing::{ - compile_with, engine_dir, fragment_inputs, link_and_validate, AssembleError, -}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; - -/// The fixture's text. -fn text() -> String { - std::fs::read_to_string(engine_dir().join("fbl_fetch_blend16.ll")).expect("the fixture") -} - -/// `text` assembled; `None` (skipped) without `llvm-as`. -fn assembled(text: &str) -> Option> { - 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 fbl_fetch_blend16: {why}"), - } -} - -/// 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 blended by `eq` (the guest's [`OVER`]), color 1 of mask none. -fn attachments(eq: BlendEquation) -> RenderLinkInputs { - let mut blended = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - 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; - assert_eq!(BlendEquation::of(&blended), Some(eq)); - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - unwritten.write_mask = ColorWriteMask::NONE; - let mut r = RenderLinkInputs::new(); - r.color_attachments[0] = Some(blended); - r.color_attachments[1] = Some(unwritten); - r -} - -/// The lowering inputs of a function that reads color 0 in [`attachments`]`(eq)` on `p`. -fn state(p: &DeviceProfile, eq: BlendEquation) -> LoweringInputs { - let r = attachments(eq); - let mut inputs = fragment_inputs(&r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &r.color_attachments, - false, - false, - 1, - )); - inputs -} - -/// Color 0's storage form in `a`: whether it writes, its blend, and whether that is rounded. -fn fetched(a: &FunctionArtifact) -> Option<(bool, Option, bool)> { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes, - blend, - rounded, - .. - } => Some((*writes, *blend, *rounded)), - _ => None, - }) -} - -/// The device of committed profile `stem`. -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -#[test] -fn a_blended_sixteen_bit_float_fetch_computes_metals_blend() { - let fast_text = text(); - let option = "!{!\"air.compile.fast_math_enable\"}"; - assert_eq!( - fast_text.matches(option).count(), - 1, - "the fixture's math mode" - ); - let safe_text = fast_text.replacen(option, "!{!\"air.compile.fast_math_disable\"}", 1); - let (Some(fast), Some(safe)) = (assembled(&fast_text), assembled(&safe_text)) else { - return; - }; - // Each entry, and whether Metal's compiler folds its output into the blend under fast math. - let entries = [ - ("fbl_over_loaded", false), - ("fbl_over_loaded_float", false), - ("fbl_over_product", true), - ]; - let note = PrecisionNote::HalfOutputFastMathBlend; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let inputs = state(&p, OVER); - for (entry, folds) in entries { - for (bc, rounded) in [(&fast, false), (&safe, true)] { - let what = format!("{stem} {entry} rounded {rounded}"); - let a = match compile_with(bc, entry, &p, &inputs) { - Ok(a) => a, - // A device without the format's storage refuses the form whatever the blend. - Err(crate::error::Error::Unsupported(u)) - if u.needs != crate::error::Needs::NotImplemented => - { - eprintln!("{what}: {u}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!( - fetched(&a), - Some((true, Some(OVER), rounded)), - "{what}: {:?}", - a.facts - ); - assert_eq!( - a.precision.contains(¬e), - folds && !rounded, - "{what}: {:?}", - a.precision - ); - // The blend's NaN is the device's arithmetic's, which the store converts, noted on - // every profile. - assert!( - a.precision.contains(&PrecisionNote::DeviceNanEncoding), - "{what}: {:?}", - a.precision - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - // The whole pipeline, as the guest makes it. - let dev = device(&stem); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&fast) - .expect("library") - .function(name) - .expect("function"), - )) - }; - for (entry, folds) in entries { - let what = format!("{stem} {entry}: the pipeline"); - let mut d = RenderPipelineDescriptor::new(function("fbl_vertex")); - d.fragment = Some(function(entry)); - let r = attachments(OVER); - d.color_attachments[0] = r.color_attachments[0]; - d.color_attachments[1] = r.color_attachments[1]; - let pipe = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(pipe) => pipe, - Err(crate::error::Error::Unsupported(u)) - if u.needs != crate::error::Needs::NotImplemented => - { - eprintln!("{what}: {u}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - let storage: Vec<(u32, bool)> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.writes)) - .collect(); - assert_eq!(storage, [(0, true)], "{what}"); - assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - assert_eq!( - fragment.precision_notes.contains(¬e), - folds, - "{what}: {:?}", - fragment.precision_notes - ); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} - -/// Each blend constant's difference into color 0 under fast math (`BlendColor` with -/// `OneMinusBlendColor`, `BlendAlpha` with `OneMinusBlendAlpha`, either as the source factor, under -/// `Subtract` and `ReverseSubtract`, for color and alpha): on every committed profile that orders -/// fetch through the pixel interlock alone, `fbl_over_loaded` and `fbl_over_loaded_float` compute -/// it in the storage form, Metal's form (the minuend's product fused, the -/// subtrahend's rounded first), so neither records `HalfOutputFastMathBlend`, and pass L3. Before, -/// the color channels' blend color difference took a rounded near-equivalent and every difference -/// recorded the note. -#[test] -fn a_fetched_blend_constant_difference_records_no_note() { - let Some(fast) = assembled(&text()) else { - return; - }; - use BlendFactor as F; - let pairs = [ - (F::BlendColor, F::OneMinusBlendColor), - (F::OneMinusBlendColor, F::BlendColor), - (F::BlendAlpha, F::OneMinusBlendAlpha), - (F::OneMinusBlendAlpha, F::BlendAlpha), - ]; - let note = PrecisionNote::HalfOutputFastMathBlend; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for (fs, fd) in pairs { - for op in [BlendOperation::Subtract, BlendOperation::ReverseSubtract] { - let eq = BlendEquation { - source_rgb: fs, - destination_rgb: fd, - rgb_operation: op, - source_alpha: fs, - destination_alpha: fd, - alpha_operation: op, - }; - let inputs = state(&p, eq); - for entry in ["fbl_over_loaded", "fbl_over_loaded_float"] { - let what = format!("{stem} {entry} {fs:?} {fd:?} {op:?}"); - let a = match compile_with(&fast, entry, &p, &inputs) { - Ok(a) => a, - // A device without the format's storage refuses the form whatever the - // blend. - Err(crate::error::Error::Unsupported(u)) - if u.needs != crate::error::Needs::NotImplemented => - { - eprintln!("{what}: {u}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!( - fetched(&a), - Some((true, Some(eq), false)), - "{what}: {:?}", - a.facts - ); - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} diff --git a/crates/metal2vulkan/src/tests/engine_fetch_blend16_narrow.rs b/crates/metal2vulkan/src/tests/engine_fetch_blend16_narrow.rs deleted file mode 100644 index 0fa8c81ac..000000000 --- a/crates/metal2vulkan/src/tests/engine_fetch_blend16_narrow.rs +++ /dev/null @@ -1,497 +0,0 @@ -//! Fragment functions that fetch a blended 16-bit float attachment through an output of one to -//! four lanes (the owned fixture `engine/fbl_fetch_blend16_narrow`), each reading color 1 in its -//! output's type and writing it beside colors 0 and 2 of mask none, under fast math, and the same -//! module stating no fast math (`air.compile.fast_math_disable`). -//! -//! The guest's shape, a macOS 26 window-server pass: color 1 `RG16Float` blended with the -//! destination color times the source plus zero for color and alpha under a mask of red and green, -//! through a `half2` (`fbl_narrow_half2`) or `float2` (`fbl_narrow_float2`) output. On every -//! committed profile that orders fetch through the pixel interlock alone, each compiles with color -//! 1 in the storage form and the blend it computes (`RuntimeFact::InterlockedFramebufferFetch`), -//! exact, noted by none (the blend's one term, of an output Metal's compiler cannot fold into -//! it), and its module passes L3; the whole pipeline is made there, color 1 a written storage -//! attachment and no color attachment of the subpass, its stages passing L3. Before the shader -//! blended an output of fewer than four lanes, each was refused `NotImplemented(FramebufferFetch)` -//! at color 1. -//! -//! The class, on the first such profile that takes the form: every output width into each 16-bit -//! float format with no more channels than it has lanes (Metal refuses fewer), under blends that -//! put every factor but the second source's in each of the four factors and every operation in -//! each class, the guest's, and the color channels' blend color difference, under the format's -//! partial write masks (one color channel of `RGBA16Float` among them), each under fast math and -//! not in turn: each compiles in the storage form, the blend its fact names, and passes L3. Before, -//! besides the narrow outputs, the fast-math blend color difference was refused -//! `ExtendedRangeBlend(ConstantColorDifference)`. No GPU is used. -//! -//! `llvm-as` assembles the fixture; a missing tool skips visibly. - -use std::path::Path; -use std::sync::Arc; - -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::library::{FunctionArtifact, Library}; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use crate::pipeline::artifact::PrecisionNote; -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::testing::{ - compile_with, engine_dir, fragment_inputs, link_and_validate, AssembleError, -}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; - -/// The fixture's text. -fn text() -> String { - std::fs::read_to_string(engine_dir().join("fbl_fetch_blend16_narrow.ll")).expect("the fixture") -} - -/// `text` assembled; `None` (skipped) without `llvm-as`. -fn assembled(text: &str) -> Option> { - 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 fbl_fetch_blend16_narrow: {why}") - } - } -} - -/// Each entry and its output's lanes. -const ENTRIES: [(&str, u8); 8] = [ - ("fbl_narrow_half", 1), - ("fbl_narrow_half2", 2), - ("fbl_narrow_half3", 3), - ("fbl_narrow_half4", 4), - ("fbl_narrow_float", 1), - ("fbl_narrow_float2", 2), - ("fbl_narrow_float3", 3), - ("fbl_narrow_float4", 4), -]; - -/// The guest's blend: the destination color times the source plus zero, for color and alpha. -const GUEST: BlendEquation = BlendEquation { - source_rgb: BlendFactor::DestinationColor, - destination_rgb: BlendFactor::Zero, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::DestinationAlpha, - destination_alpha: BlendFactor::Zero, - alpha_operation: BlendOperation::Add, -}; - -/// Every factor but the second source's. -const FACTORS: [BlendFactor; 15] = [ - 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, -]; - -/// Every operation. -const OPERATIONS: [BlendOperation; 5] = [ - BlendOperation::Add, - BlendOperation::Subtract, - BlendOperation::ReverseSubtract, - BlendOperation::Min, - BlendOperation::Max, -]; - -/// Blends that put every factor of [`FACTORS`] in each of the four factors (each position a -/// permutation of them) and every operation in each class, then the guest's and the color -/// channels' blend color difference. -fn equations() -> Vec { - let n = FACTORS.len(); - let ops = OPERATIONS.len(); - let mut out: Vec = (0..n) - .map(|i| BlendEquation { - source_rgb: FACTORS[i], - destination_rgb: FACTORS[(7 * i + 3) % n], - rgb_operation: OPERATIONS[i % ops], - source_alpha: FACTORS[(4 * i + 5) % n], - destination_alpha: FACTORS[(11 * i + 2) % n], - alpha_operation: OPERATIONS[(i + 2) % ops], - }) - .collect(); - out.push(GUEST); - out.push(BlendEquation { - source_rgb: BlendFactor::BlendColor, - destination_rgb: BlendFactor::OneMinusBlendColor, - rgb_operation: BlendOperation::Subtract, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::OneMinusSourceAlpha, - alpha_operation: BlendOperation::Add, - }); - out -} - -/// A format's channels, and the write masks that store some of them. -fn formats() -> [(PixelFormat, u8, Vec); 3] { - use ColorWriteMask as M; - [ - (PixelFormat::R16Float, 1, vec![M::ALL, M::RED]), - ( - PixelFormat::RG16Float, - 2, - vec![M::ALL, M::RED, M::GREEN, M::RED.union(M::GREEN)], - ), - ( - PixelFormat::RGBA16Float, - 4, - vec![ - M::ALL, - M::RED, - M::GREEN.union(M::ALPHA), - M::RED.union(M::BLUE), - M::ALPHA, - ], - ), - ] -} - -/// The attachments: color 1 of `pf` blended by `eq` under `mask`, colors 0 and 2 `RGBA16Float` of -/// mask none. -fn attachments(pf: PixelFormat, eq: BlendEquation, mask: ColorWriteMask) -> 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)); - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - unwritten.write_mask = ColorWriteMask::NONE; - let mut r = RenderLinkInputs::new(); - r.color_attachments[0] = Some(unwritten); - r.color_attachments[1] = Some(blended); - r.color_attachments[2] = Some(unwritten); - r -} - -/// The lowering inputs of a function that reads color 1 in pipeline `r` on `p`. -fn state(r: &RenderLinkInputs, p: &DeviceProfile) -> LoweringInputs { - let mut inputs = fragment_inputs(r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [1], - &r.color_attachments, - false, - false, - 1, - )); - inputs -} - -/// Color 1's storage form in `a`: whether it writes, its blend, and whether that is rounded. -fn fetched(a: &FunctionArtifact) -> Option<(bool, Option, bool)> { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 1, - writes, - blend, - rounded, - .. - } => Some((*writes, *blend, *rounded)), - _ => None, - }) -} - -/// The device of committed profile `stem`. -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// `compile_with`, `None` where the device lacks a format's storage (refused whatever the blend). -fn compiled( - bc: &[u8], - entry: &str, - p: &DeviceProfile, - inputs: &LoweringInputs, - what: &str, -) -> Option> { - match compile_with(bc, entry, p, inputs) { - Ok(a) => Some(a), - Err(crate::error::Error::Unsupported(u)) - if u.needs != crate::error::Needs::NotImplemented => - { - eprintln!("{what}: {u}"); - None - } - Err(e) => panic!("{what}: {e}"), - } -} - -#[test] -fn a_narrow_output_blends_a_fetched_sixteen_bit_float_attachment() { - let fast_text = text(); - let option = "!{!\"air.compile.fast_math_enable\"}"; - assert_eq!( - fast_text.matches(option).count(), - 1, - "the fixture's math mode" - ); - let safe_text = fast_text.replacen(option, "!{!\"air.compile.fast_math_disable\"}", 1); - let (Some(fast), Some(safe)) = (assembled(&fast_text), assembled(&safe_text)) else { - return; - }; - let note = PrecisionNote::HalfOutputFastMathBlend; - let guest_mask = ColorWriteMask::RED.union(ColorWriteMask::GREEN); - let mut class: Option = None; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let r = attachments(PixelFormat::RG16Float, GUEST, guest_mask); - let inputs = state(&r, &p); - let mut took = false; - for entry in ["fbl_narrow_half2", "fbl_narrow_float2"] { - for (bc, rounded) in [(&fast, false), (&safe, true)] { - let what = format!("{stem} {entry} rounded {rounded}"); - let Some(a) = compiled(bc, entry, &p, &inputs, &what) else { - continue; - }; - assert_eq!( - fetched(&a), - Some((true, Some(GUEST), rounded)), - "{what}: {:?}", - a.facts - ); - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - // A `float2` output's blend result is the storage image's store's to round to - // `half`, the device's, noted. A `half2` output's is a `half`. - let float = entry == "fbl_narrow_float2"; - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceColorConversion), - float, - "{what}: {:?}", - a.precision - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - took = true; - checked += 1; - } - } - if took && class.is_none() { - class = Some(p.clone()); - } - // The whole pipeline, as the guest makes it. - let dev = device(&stem); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&fast) - .expect("library") - .function(name) - .expect("function"), - )) - }; - for entry in ["fbl_narrow_half2", "fbl_narrow_float2"] { - let what = format!("{stem} {entry}: the pipeline"); - let mut d = RenderPipelineDescriptor::new(function("fbl_narrow_vertex")); - d.fragment = Some(function(entry)); - for (k, c) in r.color_attachments.iter().enumerate().take(3) { - d.color_attachments[k] = *c; - } - let pipe = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(pipe) => pipe, - Err(crate::error::Error::Unsupported(u)) - if u.needs != crate::error::Needs::NotImplemented => - { - eprintln!("{what}: {u}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - let storage: Vec<(u32, bool)> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.writes)) - .collect(); - assert_eq!(storage, [(1, true)], "{what}"); - assert!(pipe.graphics.color_attachments[1].is_none(), "{what}"); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - assert!( - !fragment.precision_notes.contains(¬e), - "{what}: {:?}", - fragment.precision_notes - ); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); - // The class, on the first profile that took the form. - let p = class.expect("a profile that took the form"); - let equations = equations(); - let mut built = 0; - for (n, (entry, lanes)) in ENTRIES.into_iter().enumerate() { - for (pf, channels, masks) in formats() { - // Metal refuses an output of fewer lanes than the format's channels. - if lanes < channels { - continue; - } - for (i, eq) in equations.iter().enumerate() { - let mask = masks[(i + n) % masks.len()]; - let (bc, rounded) = match (i + n) % 2 { - 0 => (&fast, false), - _ => (&safe, true), - }; - let what = format!("{entry} {pf:?} {eq:?} {mask:?} rounded {rounded}"); - let r = attachments(pf, *eq, mask); - let Some(a) = compiled(bc, entry, &p, &state(&r, &p), &what) else { - continue; - }; - assert_eq!( - fetched(&a), - Some((true, Some(*eq), rounded)), - "{what}: {:?}", - a.facts - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - built += 1; - } - } - } - assert!(built > 0, "the class built nothing"); -} - -/// The attachments of [`attachments`], color 1 written unblended. -fn unblended(pf: PixelFormat) -> RenderLinkInputs { - let mut r = attachments(pf, GUEST, ColorWriteMask::ALL); - if let Some(c) = r.color_attachments[1].as_mut() { - c.blending_enabled = false; - } - r -} - -/// A one- or two-channel 8-bit sRGB attachment (`R8Unorm_sRGB`, `RG8Unorm_sRGB`) the function -/// fetches, on every committed profile that orders fetch through the pixel interlock alone and -/// renders the format itself: each entry of as many lanes as the format's channels or more, fast -/// and safe math, compiles in the storage form through the format's integer view, unblended and -/// under source-alpha over and the guest's blend, which the function computes -/// (`extended_range::Blend::srgb8`): noted `UnmeasuredFetchBlend` exactly where that is not -/// Metal's (a no-alpha form the 8-bit unorm blend does not build under fast math, or an output of -/// fewer than four lanes, which blends as four whose missing lanes are zero), and its module passes -/// L3. Before, each was refused `NotImplemented(FramebufferFetch)`. -#[test] -fn a_fetched_one_or_two_channel_srgb_attachment_is_written_and_blended() { - use crate::lower::arith::extended_range::blend::{BlendArith, BlendMath}; - use crate::lower::arith::extended_range::Blend; - let fast_text = text(); - let option = "!{!\"air.compile.fast_math_enable\"}"; - let safe_text = fast_text.replacen(option, "!{!\"air.compile.fast_math_disable\"}", 1); - let (Some(fast), Some(safe)) = (assembled(&fast_text), assembled(&safe_text)) else { - return; - }; - let over = BlendEquation { - source_rgb: BlendFactor::SourceAlpha, - destination_rgb: BlendFactor::OneMinusSourceAlpha, - rgb_operation: BlendOperation::Add, - source_alpha: BlendFactor::One, - destination_alpha: BlendFactor::OneMinusSourceAlpha, - alpha_operation: BlendOperation::Add, - }; - let note = PrecisionNote::UnmeasuredFetchBlend; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for (pf, channels) in [ - (PixelFormat::R8UnormSRGB, 1), - (PixelFormat::RG8UnormSRGB, 2), - ] { - // A device that renders the format through a word view: not this form. - if crate::metal::format::WordAttachment::of(pf, &p).is_some() { - continue; - } - for (entry, lanes) in ENTRIES { - if lanes < channels { - continue; - } - for (bc, math) in [(&fast, BlendMath::Fast), (&safe, BlendMath::Rounded)] { - let rounded = math == BlendMath::Rounded; - let what = format!("{stem} {pf:?} {entry} rounded {rounded}"); - let r = unblended(pf); - let a = compile_with(bc, entry, &p, &state(&r, &p)) - .unwrap_or_else(|e| panic!("{what} unblended: {e}")); - assert_eq!( - fetched(&a).map(|f| (f.0, f.1)), - Some((true, None)), - "{what}" - ); - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - for eq in [over, GUEST] { - let what = format!("{what} {eq:?}"); - let r = attachments(pf, eq, ColorWriteMask::ALL); - let a = compile_with(bc, entry, &p, &state(&r, &p)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(fetched(&a), Some((true, Some(eq), rounded)), "{what}"); - let half = (math, BlendArith::Half); - let exact = lanes == 4 - && Blend::srgb8(&eq, pf, ColorWriteMask::ALL, half) - .is_ok_and(|(_, exact)| exact); - assert_eq!(a.precision.contains(¬e), !exact, "{what}"); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); - // A `half` output under fast math: its storage write is noted `HalfOutputFastMathBlend` where - // it stores a channel, and not under a mask that names none of the format's (blue into - // `R8Unorm_sRGB`), which stores nothing. - let fast_note = PrecisionNote::HalfOutputFastMathBlend; - for (stem, p) in committed_profiles().expect("profiles") { - let pf = PixelFormat::R8UnormSRGB; - if !crate::lower::fragment::interlock_orders(&p) - || crate::metal::format::WordAttachment::of(pf, &p).is_some() - { - continue; - } - for (mask, noted) in [(ColorWriteMask::RED, true), (ColorWriteMask::BLUE, false)] { - let mut r = unblended(pf); - if let Some(c) = r.color_attachments[1].as_mut() { - c.write_mask = mask; - } - let what = format!("{stem} {mask:?}"); - let a = compile_with(&fast, "fbl_narrow_half4", &p, &state(&r, &p)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - a.precision.contains(&fast_note), - noted, - "{what}: {:?}", - a.precision - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs b/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs index 4a1e81e07..cedb72162 100644 --- a/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs +++ b/crates/metal2vulkan/src/tests/engine_fetch_blend8.rs @@ -1,52 +1,21 @@ //! 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 fixtures `engine/fbl_fetch_blend8`, -//! under fast math, and `engine/fbl_fetch_blend8_safe`, without): color 0 blended with one over -//! one minus the source alpha for color and alpha, color 1 `RGBA16Float` of mask none, each -//! function reading color 0. -//! -//! On every committed profile that orders fetch through the pixel interlock alone, each function -//! compiles with color 0 in the storage form for each 8-bit unorm format (`BGRA8Unorm`, -//! `RGBA8Unorm`, `RG8Unorm`, `R8Unorm`) and the blend it computes -//! (`RuntimeFact::InterlockedFramebufferFetch` names the blend, rounded without fast math), and -//! its module passes L3. Every output, the fast-math product of `fbl8_over_product` too, blends -//! as Metal does (Metal clamps the output before the blend, so nothing folds into it): no -//! function records `HalfOutputFastMathBlend` or `HalfOutputPrecision`. The storage image's store -//! converts the blend's result to its code, the device's conversion: every function records -//! `DeviceColorConversion`; an sRGB attachment's encode and decode are the device's -//! (`DevicePackConversion`). -//! The guest's format (`BGRA8Unorm`) takes the form on every such profile (ANV's through its -//! RGBA-order twin, the shader exchanging red and blue around the blend), and the guest's whole -//! pipeline is made there, color 0 a written storage attachment and no color attachment of the -//! subpass, its stages passing L3. Before the shader computed the -//! blend, each was refused `NotImplemented(FramebufferFetch)` at color 0. Other blends (the blend -//! color's among them) and write masks that keep channels compile the same way; a blend that reads -//! the second source of a function that writes none is refused as Metal refuses its pipeline -//! (`InvalidDescriptor(ColorAttachment)`). 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. +//! 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. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. -use std::path::Path; - -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{Attachment, DescriptorError, Error, Feature, MetalAnswer, Needs}; -use crate::library::{FunctionArtifact, Library}; +use crate::device::DeviceProfile; +use crate::error::{Attachment, Error, Feature, Needs}; use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::facts::RuntimeFact; +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, link_and_validate, AssembleError, -}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; +use crate::pipeline::testing::{compile_with, engine_dir, fragment_inputs, AssembleError}; +use crate::spirv::testing::committed_profiles; /// Fixture `stem` assembled; `None` (skipped) without `llvm-as`. fn assembled(stem: &str) -> Option> { @@ -72,20 +41,6 @@ const OVER: BlendEquation = BlendEquation { alpha_operation: BlendOperation::Add, }; -/// The 8-bit unorm formats. -const FORMATS: [PixelFormat; 4] = [ - PixelFormat::BGRA8Unorm, - PixelFormat::RGBA8Unorm, - PixelFormat::RG8Unorm, - PixelFormat::R8Unorm, -]; - -/// The notes a draw announces where the blend's arithmetic may be another than Metal's. -const NOTES: [PrecisionNote; 2] = [ - PrecisionNote::HalfOutputFastMathBlend, - PrecisionNote::HalfOutputPrecision, -]; - /// 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 { let mut blended = ColorAttachmentDescriptor::new(pf); @@ -115,398 +70,10 @@ fn state( ) -> LoweringInputs { let r = attachments(pf, eq, mask); let mut inputs = fragment_inputs(&r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &r.color_attachments, - false, - false, - 1, - )); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); inputs } -/// Color 0's storage form in `a`: whether it writes, its blend, and whether that is rounded. -fn fetched(a: &FunctionArtifact) -> Option<(bool, Option, bool)> { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes, - blend, - rounded, - .. - } => Some((*writes, *blend, *rounded)), - _ => None, - }) -} - -/// The device of committed profile `stem`. -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// Whether `e` is a refusal the device's lack of a capability makes, whatever the blend (a -/// format without the storage access the form needs). -fn device_gap(e: &Error) -> bool { - matches!(e, Error::Unsupported(u) if u.needs != Needs::NotImplemented) -} - -#[test] -fn a_blended_eight_bit_unorm_fetch_computes_metals_blend() { - let (Some(fast), Some(safe)) = ( - assembled("fbl_fetch_blend8"), - assembled("fbl_fetch_blend8_safe"), - ) else { - return; - }; - // Each fixture's functions, and whether its blend is rounded. - let entries = [ - (&fast, "fbl8_over_loaded", false), - (&fast, "fbl8_over_loaded_float", false), - (&fast, "fbl8_over_product", false), - (&safe, "fbl8_safe_loaded", true), - (&safe, "fbl8_safe_loaded_float", true), - (&safe, "fbl8_safe_product", true), - ]; - let mut checked = 0; - // An ANV profile compiled the guest's shape. - let mut anv = false; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for pf in FORMATS { - let inputs = state(&p, pf, OVER, ColorWriteMask::ALL); - for &(bc, entry, rounded) in &entries { - let what = format!("{stem} {pf:?} {entry}"); - // The guest's format takes the form on every such profile, ANV's through its - // RGBA-order twin; another may lack its storage there. - let a = match compile_with(bc, entry, &p, &inputs) { - Ok(a) => a, - Err(e) if device_gap(&e) && pf != PixelFormat::BGRA8Unorm => { - eprintln!("{what}: {e}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - anv |= stem.contains("anv") && pf == PixelFormat::BGRA8Unorm; - assert_eq!( - fetched(&a), - Some((true, Some(OVER), rounded)), - "{what}: {:?}", - a.facts - ); - for note in NOTES { - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - } - assert!( - a.precision.contains(&PrecisionNote::DeviceColorConversion), - "{what}: {:?}", - a.precision - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - // The whole pipeline, as the guest makes it. - let dev = device(&stem); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&fast) - .expect("library") - .function(name) - .expect("function"), - )) - }; - for entry in ["fbl8_over_loaded", "fbl8_over_product"] { - let what = format!("{stem} {entry}: the pipeline"); - let mut d = RenderPipelineDescriptor::new(function("fbl8_vertex")); - d.fragment = Some(function(entry)); - let r = attachments(PixelFormat::BGRA8Unorm, OVER, ColorWriteMask::ALL); - d.color_attachments[0] = r.color_attachments[0]; - d.color_attachments[1] = r.color_attachments[1]; - let pipe = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let storage: Vec<(u32, bool)> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.writes)) - .collect(); - assert_eq!(storage, [(0, true)], "{what}"); - assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - for note in NOTES { - assert!( - !fragment.precision_notes.contains(¬e), - "{what}: {:?}", - fragment.precision_notes - ); - } - assert!( - (fragment.precision_notes).contains(&PrecisionNote::DeviceColorConversion), - "{what}: {:?}", - fragment.precision_notes - ); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); - assert!(anv, "no ANV profile compiled the guest's shape"); -} - -/// A blended 8-bit four-channel sRGB attachment (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`): on every -/// committed profile that orders fetch through the pixel interlock alone, each function compiles -/// in the storage form through the format's `R32_UINT` view with the blend it computes (Metal's -/// 8-bit unorm blend over the decoded texel, encoded: `extended_range::Blend::srgb8`), rounded -/// without fast math, and announces nothing, a write mask that keeps channels and the blend color -/// too; and its module passes L3. Before, each was refused `NotImplemented(FramebufferFetch)`. -/// The second source's blend (the owned fixture `engine/fbl_fetch_dual`, fast math), which Metal's -/// 8-bit unorm blend does not build, takes its rounded forms, noted `UnmeasuredFetchBlend`. -#[test] -fn a_blended_four_channel_srgb_fetch_computes_metals_blend() { - let (Some(fast), Some(safe), Some(dual)) = ( - assembled("fbl_fetch_blend8"), - assembled("fbl_fetch_blend8_safe"), - assembled("fbl_fetch_dual"), - ) else { - return; - }; - use BlendFactor as F; - let entries = [ - (&fast, "fbl8_over_loaded", false), - (&fast, "fbl8_over_loaded_float", false), - (&safe, "fbl8_safe_loaded", true), - (&safe, "fbl8_safe_loaded_float", true), - ]; - let lerp = BlendEquation { - source_rgb: F::BlendColor, - destination_rgb: F::OneMinusBlendColor, - ..OVER - }; - let states = [ - (OVER, ColorWriteMask::ALL), - (OVER, ColorWriteMask::RED.union(ColorWriteMask::ALPHA)), - (lerp, ColorWriteMask::ALL), - ]; - let second = BlendEquation { - source_rgb: F::Source1Color, - destination_rgb: F::OneMinusSource1Color, - source_alpha: F::Source1Alpha, - destination_alpha: F::OneMinusSource1Alpha, - ..OVER - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB] { - for (eq, mask) in states { - let inputs = state(&p, pf, eq, mask); - for &(bc, entry, rounded) in &entries { - let what = format!("{stem} {pf:?} {eq:?} {mask:?} {entry}"); - let a = compile_with(bc, entry, &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(fetched(&a), Some((true, Some(eq), rounded)), "{what}"); - for note in NOTES.into_iter().chain([ - PrecisionNote::UnmeasuredFetchBlend, - PrecisionNote::DeviceColorConversion, - ]) { - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - } - assert!( - a.precision.contains(&PrecisionNote::DevicePackConversion), - "{what}: {:?}", - a.precision - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - let inputs = state(&p, pf, second, ColorWriteMask::ALL); - for entry in ["fbd_dual_half", "fbd_dual_float"] { - let what = format!("{stem} {pf:?} {entry}"); - let a = compile_with(&dual, entry, &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(fetched(&a), Some((true, Some(second), false)), "{what}"); - assert!( - a.precision.contains(&PrecisionNote::UnmeasuredFetchBlend), - "{what}: {:?}", - a.precision - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} - -/// Other blends and write masks of an 8-bit unorm attachment: on every committed profile that -/// orders fetch through the pixel interlock alone, each compiles in the storage form with the -/// blend it computes, rounded without fast math, and announces only the device's conversion of its -/// result (`DeviceColorConversion`); one reading the blend -/// color pushes it as `half` (`PushField::HalfBlendColor`), and its module passes L3. -#[test] -fn another_eight_bit_unorm_blend_or_mask_computes_metals_blend() { - let (Some(fast), Some(safe)) = ( - assembled("fbl_fetch_blend8"), - assembled("fbl_fetch_blend8_safe"), - ) else { - return; - }; - use crate::pipeline::sym::PushField; - use BlendFactor as F; - use BlendOperation as O; - let rgb = ColorWriteMask::RED - .union(ColorWriteMask::GREEN) - .union(ColorWriteMask::BLUE); - // Each blend, its write mask, and whether it reads the blend color. - let cases = [ - ( - BlendEquation { - source_rgb: F::SourceAlpha, - ..OVER - }, - ColorWriteMask::ALL, - false, - ), - ( - BlendEquation { - destination_rgb: F::One, - destination_alpha: F::One, - ..OVER - }, - ColorWriteMask::ALL, - false, - ), - ( - BlendEquation { - source_rgb: F::BlendColor, - destination_rgb: F::OneMinusBlendAlpha, - rgb_operation: O::ReverseSubtract, - source_alpha: F::DestinationAlpha, - destination_alpha: F::OneMinusSourceColor, - alpha_operation: O::Subtract, - }, - ColorWriteMask::ALL, - true, - ), - ( - BlendEquation { - rgb_operation: O::Max, - alpha_operation: O::Min, - ..OVER - }, - ColorWriteMask::ALL, - false, - ), - (OVER, rgb, false), - (OVER, ColorWriteMask::BLUE, false), - (OVER, ColorWriteMask::ALPHA, false), - ( - BlendEquation { - source_rgb: F::OneMinusDestinationAlpha, - destination_rgb: F::SourceColor, - rgb_operation: O::ReverseSubtract, - ..OVER - }, - ColorWriteMask::GREEN.union(ColorWriteMask::ALPHA), - false, - ), - ]; - let entries = [ - (&fast, "fbl8_over_loaded", false), - (&safe, "fbl8_safe_loaded", true), - ]; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for (eq, mask, reads_color) in cases { - let inputs = state(&p, PixelFormat::BGRA8Unorm, eq, mask); - for &(bc, entry, rounded) in &entries { - let what = format!("{stem} {entry} {eq:?} {mask:?}"); - let a = - compile_with(bc, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - fetched(&a), - Some((true, Some(eq), rounded)), - "{what}: {:?}", - a.facts - ); - for note in NOTES { - assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision); - } - assert!( - a.precision.contains(&PrecisionNote::DeviceColorConversion), - "{what}: {:?}", - a.precision - ); - let pushes = - |field: PushField| a.interface.push.fields.iter().any(|x| x.field == field); - assert_eq!(pushes(PushField::HalfBlendColor), reads_color, "{what}"); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - checked += 1; - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} - -/// A blend of an 8-bit unorm attachment that reads the second source, of a function that writes no -/// second output: Metal refuses the pipeline ("Fragment shader does not write to render target -/// color(0), index(1) that is required for blending", plain Metal on the M3 Max under macOS -/// 27.0.1), and on every committed profile that orders fetch through the pixel interlock alone it -/// is refused so, `InvalidDescriptor(ColorAttachment)` of color 0. -#[test] -fn a_second_source_blend_without_its_output_is_refused_as_metal_refuses_it() { - let Some(fast) = assembled("fbl_fetch_blend8") else { - return; - }; - use BlendFactor as F; - let cases = [ - BlendEquation { - source_rgb: F::Source1Color, - ..OVER - }, - BlendEquation { - destination_alpha: F::OneMinusSource1Alpha, - ..OVER - }, - ]; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for eq in cases { - let inputs = state(&p, PixelFormat::BGRA8Unorm, eq, ColorWriteMask::ALL); - let what = format!("{stem} {eq:?}"); - match compile_with(&fast, "fbl8_over_loaded", &p, &inputs) { - Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: 0, - metal: MetalAnswer::NilWithError, - })) => { - checked += 1; - } - Err(e) if device_gap(&e) => eprintln!("{what}: {e}"), - other => panic!("{what}: {:?}", other.map(|a| a.facts.clone())), - } - } - } - assert!(checked > 0, "no interlock profile refused"); -} - /// 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 diff --git a/crates/metal2vulkan/src/tests/engine_fetch_generic_blend.rs b/crates/metal2vulkan/src/tests/engine_fetch_generic_blend.rs deleted file mode 100644 index 511acfa54..000000000 --- a/crates/metal2vulkan/src/tests/engine_fetch_generic_blend.rs +++ /dev/null @@ -1,497 +0,0 @@ -//! Fragment functions that fetch a blended attachment of a format whose Metal blend arithmetic -//! the translation does not build (the owned fixtures `engine/fbl_fetch_blend8`, a four-lane output -//! to color 0 beside color 1 of mask none, under fast math and not, and -//! `engine/fbl_fetch_blend16_narrow`, outputs of one to four lanes to color 1 beside colors 0 and 2 -//! of mask none). -//! -//! On every committed profile that orders fetch through the pixel interlock alone, each such -//! attachment the device can view as a storage image takes the storage form with the generic -//! float blend (`StorageView::generic_blend`): a 16-bit normalized, 8-bit signed normalized, -//! 10-bit, packed float, 32-bit float and `A8Unorm` attachment of a four-lane output, and an 8-bit -//! unorm or 32-bit float one of fewer lanes, under several blends and either math. Each names the blend in its `RuntimeFact::InterlockedFramebufferFetch`, records -//! `PrecisionNote::UnmeasuredFetchBlend`, pushes the blend color as `PushField::HalfBlendColor` -//! exactly where the blend reads it, and its module passes L3. Before, each was refused -//! `NotImplemented(FramebufferFetch)` at its color. -//! -//! The whole pipeline is made for `RGBA32Float` there, color 0 a written storage attachment and -//! no color attachment of the subpass, its stages passing L3 and its fragment stage carrying the -//! generic blend's note. -//! A blend that reads the second source, or any blend beside a second (index 1) output (the owned -//! fixture `engine/fbl_fetch_dual`), takes the generic blend too, a 16-bit float and an 8-bit -//! unorm attachment's among them; one of a function that writes no second output is refused as -//! Metal refuses its pipeline, `InvalidDescriptor(ColorAttachment)`. No GPU is used. -//! -//! `llvm-as` assembles the fixtures; a missing tool skips visibly. - -use std::path::Path; -use std::sync::Arc; - -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{DescriptorError, Error, MetalAnswer, Needs}; -use crate::library::{FunctionArtifact, Library}; -use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use crate::pipeline::artifact::PrecisionNote; -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::sym::PushField; -use crate::pipeline::testing::{ - compile_with, engine_dir, fragment_inputs, link_and_validate, AssembleError, -}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; - -/// Fixture `stem` assembled, under fast math or (`safe`) without; `None` (skipped) without -/// `llvm-as`. -fn assembled(stem: &str, safe: bool) -> Option> { - let text = - std::fs::read_to_string(engine_dir().join(format!("{stem}.ll"))).expect("the fixture"); - let option = "!{!\"air.compile.fast_math_enable\"}"; - assert_eq!(text.matches(option).count(), 1, "{stem}'s math mode"); - let text = match safe { - true => text.replacen(option, "!{!\"air.compile.fast_math_disable\"}", 1), - false => text, - }; - 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 {stem}: {why}"), - } -} - -/// 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, -}; - -/// Blends of several factors and operations, each with whether it reads the blend color. -fn equations() -> [(BlendEquation, bool); 4] { - use BlendFactor as F; - use BlendOperation as O; - [ - (OVER, false), - ( - BlendEquation { - source_rgb: F::BlendColor, - destination_rgb: F::OneMinusBlendAlpha, - rgb_operation: O::ReverseSubtract, - source_alpha: F::DestinationAlpha, - destination_alpha: F::OneMinusSourceColor, - alpha_operation: O::Subtract, - }, - true, - ), - // The minimum and the maximum, which read no factor. - ( - BlendEquation { - rgb_operation: O::Max, - alpha_operation: O::Min, - ..OVER - }, - false, - ), - ( - BlendEquation { - source_rgb: F::SourceAlphaSaturated, - destination_rgb: F::DestinationColor, - ..OVER - }, - false, - ), - ] -} - -/// The pipeline: color `color` of `pf` blended by `eq` under `mask`, the colors below it and the -/// one above it `RGBA16Float` of mask none. -fn attachments( - color: usize, - pf: PixelFormat, - eq: BlendEquation, - mask: ColorWriteMask, -) -> 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)); - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - unwritten.write_mask = ColorWriteMask::NONE; - let mut r = RenderLinkInputs::new(); - for slot in r.color_attachments.iter_mut().take(color + 2) { - *slot = Some(unwritten); - } - r.color_attachments[color] = Some(blended); - r -} - -/// The lowering inputs of a function that reads color `color` in pipeline `r` on `p`. -fn state(color: u32, r: &RenderLinkInputs, p: &DeviceProfile) -> LoweringInputs { - let mut inputs = fragment_inputs(r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [color], - &r.color_attachments, - false, - false, - 1, - )); - inputs -} - -/// Color `color`'s storage form in `a`: whether it writes, and its blend. -fn fetched(a: &FunctionArtifact, color: u32) -> Option<(bool, Option)> { - a.facts.iter().find_map(|f| match *f { - RuntimeFact::InterlockedFramebufferFetch { - color: c, - writes, - blend, - .. - } if c == color => Some((writes, blend)), - _ => None, - }) -} - -/// `compile_with`, `None` where the device lacks the format's storage (refused whatever the -/// blend). -fn compiled( - bc: &[u8], - entry: &str, - p: &DeviceProfile, - inputs: &LoweringInputs, - what: &str, -) -> Option> { - match compile_with(bc, entry, p, inputs) { - Ok(a) => Some(a), - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => { - eprintln!("{what}: {u}"); - None - } - Err(e) => panic!("{what}: {e}"), - } -} - -/// Check `a`, compiled for a blend of color `color` by `eq` (reading the blend color where -/// `reads_color`): the generic blend in the storage form, noted, its module valid. -fn check_generic( - a: &FunctionArtifact, - p: &DeviceProfile, - (color, eq, reads_color): (u32, BlendEquation, bool), - what: &str, -) { - assert_eq!( - fetched(a, color), - Some((true, Some(eq))), - "{what}: {:?}", - a.facts - ); - assert!( - a.precision.contains(&PrecisionNote::UnmeasuredFetchBlend), - "{what}: {:?}", - a.precision - ); - let pushes = |field: PushField| a.interface.push.fields.iter().any(|x| x.field == field); - assert_eq!(pushes(PushField::HalfBlendColor), reads_color, "{what}"); - link_and_validate(a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); -} - -/// The device of committed profile `stem`. -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -#[test] -fn a_blended_fetch_of_another_format_computes_the_generic_blend() { - let (Some(fast), Some(safe)) = ( - assembled("fbl_fetch_blend8", false), - assembled("fbl_fetch_blend8", true), - ) else { - return; - }; - let formats = [ - PixelFormat::RGBA32Float, - PixelFormat::RGBA16Unorm, - PixelFormat::RGBA16Snorm, - PixelFormat::RGBA8Snorm, - PixelFormat::RGB10A2Unorm, - PixelFormat::BGR10A2Unorm, - PixelFormat::RG11B10Float, - PixelFormat::A8Unorm, - ]; - // Each module and its entry, under fast math and not. - let entries = [ - (&fast, "fbl8_over_loaded"), - (&fast, "fbl8_over_loaded_float"), - (&safe, "fbl8_over_product"), - ]; - let mut checked = 0; - // Profiles on which `RGBA32Float` took the form. - let mut float32 = Vec::new(); - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for pf in formats { - for (eq, reads_color) in equations() { - let r = attachments(0, pf, eq, ColorWriteMask::ALL); - let inputs = state(0, &r, &p); - for &(bc, entry) in &entries { - let what = format!("{stem} {pf:?} {entry} {eq:?}"); - let Some(a) = compiled(bc, entry, &p, &inputs, &what) else { - continue; - }; - check_generic(&a, &p, (0, eq, reads_color), &what); - checked += 1; - if pf == PixelFormat::RGBA32Float && !float32.contains(&stem) { - float32.push(stem.clone()); - } - } - } - } - } - assert!(checked > 0, "no interlock profile took the generic blend"); - assert!( - float32.iter().any(|s| s.starts_with("moltenvk")), - "no MoltenVK profile took RGBA32Float's form: {float32:?}" - ); - // The whole pipeline, on each profile that took `RGBA32Float`'s form. - for stem in float32 { - let dev = device(&stem); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&fast) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let what = format!("{stem}: the pipeline"); - let mut d = RenderPipelineDescriptor::new(function("fbl8_vertex")); - d.fragment = Some(function("fbl8_over_loaded")); - let r = attachments(0, PixelFormat::RGBA32Float, OVER, ColorWriteMask::ALL); - d.color_attachments[0] = r.color_attachments[0]; - d.color_attachments[1] = r.color_attachments[1]; - let pipe = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let storage: Vec<(u32, bool)> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.writes)) - .collect(); - assert_eq!(storage, [(0, true)], "{what}"); - assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - // The shader computes the blend, as the device's blend unit would, and says so. - assert!( - fragment - .precision_notes - .contains(&PrecisionNote::UnmeasuredFetchBlend), - "{what}: {:?}", - fragment.precision_notes - ); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - } -} - -/// Outputs of fewer than four lanes into the one- and two-channel 8-bit unorm and 32-bit float -/// formats (an 8-bit unorm blend of such an output is not measured), and a partial write mask: -/// the generic blend, under fast math and not. -#[test] -fn a_narrow_output_takes_the_generic_blend() { - let (Some(fast), Some(safe)) = ( - assembled("fbl_fetch_blend16_narrow", false), - assembled("fbl_fetch_blend16_narrow", true), - ) else { - return; - }; - use ColorWriteMask as M; - // Each format, the entries of its channels' lanes, and its write masks. - let cases = [ - ( - PixelFormat::R8Unorm, - ["fbl_narrow_half", "fbl_narrow_float"], - vec![M::ALL], - ), - ( - PixelFormat::RG8Unorm, - ["fbl_narrow_half2", "fbl_narrow_float2"], - vec![M::ALL, M::GREEN], - ), - ( - PixelFormat::R32Float, - ["fbl_narrow_half", "fbl_narrow_float"], - vec![M::ALL], - ), - ( - PixelFormat::RG32Float, - ["fbl_narrow_half2", "fbl_narrow_float2"], - vec![M::ALL, M::RED], - ), - ]; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for (pf, entries, masks) in &cases { - for mask in masks { - for (eq, reads_color) in equations() { - let r = attachments(1, *pf, eq, *mask); - let inputs = state(1, &r, &p); - for bc in [&fast, &safe] { - for entry in entries { - let what = format!("{stem} {pf:?} {mask:?} {entry} {eq:?}"); - let Some(a) = compiled(bc, entry, &p, &inputs, &what) else { - continue; - }; - check_generic(&a, &p, (1, eq, reads_color), &what); - checked += 1; - } - } - } - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} - -/// A blend of the second source, or any blend beside a second (index 1) output, of a function that -/// reads the attachment (the owned fixture `engine/fbl_fetch_dual`, under fast math and not): the -/// generic blend, which reads the second output where the blend names it, into a 32-bit float, a -/// 16-bit normalized, a 16-bit float and an 8-bit unorm attachment alike (Metal makes and draws -/// such pipelines; its blend of a 16-bit float or 8-bit unorm one with the second source is not -/// measured). Noted, its module valid. -#[test] -fn a_second_source_blend_takes_the_generic_blend() { - let (Some(fast), Some(safe)) = ( - assembled("fbl_fetch_dual", false), - assembled("fbl_fetch_dual", true), - ) else { - return; - }; - use BlendFactor as F; - let formats = [ - PixelFormat::RGBA32Float, - PixelFormat::RGBA16Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA8Unorm, - ]; - let equations = [ - BlendEquation { - source_rgb: F::Source1Color, - destination_rgb: F::OneMinusSource1Color, - ..OVER - }, - BlendEquation { - source_alpha: F::Source1Alpha, - destination_alpha: F::OneMinusSource1Alpha, - ..OVER - }, - OVER, - ]; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for pf in formats { - for eq in equations { - let r = attachments(0, pf, eq, ColorWriteMask::ALL); - let inputs = state(0, &r, &p); - for bc in [&fast, &safe] { - for entry in ["fbd_dual_half", "fbd_dual_float"] { - let what = format!("{stem} {pf:?} {entry} {eq:?}"); - let Some(a) = compiled(bc, entry, &p, &inputs, &what) else { - continue; - }; - check_generic(&a, &p, (0, eq, false), &what); - checked += 1; - } - } - } - } - } - assert!(checked > 0, "no interlock profile took the storage form"); -} - -/// A blend of the second source of a function that writes no second output: Metal refuses the -/// pipeline ("Fragment shader does not write to render target color(0), index(1) that is required -/// for blending", plain Metal on the M3 Max under macOS 27.0.1, a fetching function and a plain -/// one, `half4` and `float4`), and so is it refused, `InvalidDescriptor(ColorAttachment)` of color -/// 0, whatever the format. -#[test] -fn a_second_source_blend_without_its_output_is_refused_as_metal_refuses_it() { - let Some(fast) = assembled("fbl_fetch_blend8", false) else { - return; - }; - use BlendFactor as F; - let cases = [ - ( - PixelFormat::RGBA32Float, - BlendEquation { - source_rgb: F::Source1Color, - ..OVER - }, - ), - ( - PixelFormat::RGBA16Unorm, - BlendEquation { - destination_alpha: F::OneMinusSource1Alpha, - ..OVER - }, - ), - ( - PixelFormat::RGBA16Float, - BlendEquation { - destination_rgb: F::Source1Alpha, - ..OVER - }, - ), - ]; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for (pf, eq) in cases { - let r = attachments(0, pf, eq, ColorWriteMask::ALL); - let inputs = state(0, &r, &p); - let what = format!("{stem} {pf:?} {eq:?}"); - match compile_with(&fast, "fbl8_over_loaded", &p, &inputs) { - Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment { - index: 0, - metal: MetalAnswer::NilWithError, - })) => { - checked += 1; - } - Err(Error::Unsupported(u)) => eprintln!("{what}: {u}"), - other => panic!("{what}: {:?}", other.map(|a| a.facts.clone())), - } - } - } - assert!(checked > 0, "no interlock profile refused"); -} diff --git a/crates/metal2vulkan/src/tests/engine_fetch_word_read.rs b/crates/metal2vulkan/src/tests/engine_fetch_word_read.rs deleted file mode 100644 index f39196c23..000000000 --- a/crates/metal2vulkan/src/tests/engine_fetch_word_read.rs +++ /dev/null @@ -1,200 +0,0 @@ -//! A fragment function's color input of a packed 16-bit attachment the device renders only -//! through the view of its word (`metal::format::WordAttachment::Packed16`, -//! `lower::fragment::fetch`). -//! -//! The function reads the attachment's word out of its `R16_UINT` storage image in the ordered -//! pixel interlock and decodes it into the value Metal's programmable blending hands it: each -//! channel's code over its maximum code rounded to `half`, nearest even -//! (`stage_io::word_color::decode`, the same decode a blend of such an attachment reads its -//! destination through). The value is Metal's, measured on an Apple M3 Max under macOS 27.0.1 by -//! the probe `conformance/probes/packed16_word_fetch.m`: a `float4` and a `half4` color input of -//! `BGRA4Unorm`, `ABGR4Unorm` and `B5G6R5Unorm`, stored raw into an `RGBA32Float` attachment, -//! read every code of each 4-bit channel as that `half`, while an `RGBA8Unorm` control read the -//! `f32` quotient through a `float4` input, so the run tells the two rules apart. The sixteen -//! `f32` patterns are `metal::format::word`'s table. -//! -//! On every committed profile that orders fetch through the pixel interlock alone, the fixture's -//! `half4` and `float4` readers (`engine/fbl_fetch_blend8`, whose color 0 is read and written) -//! compile for each such attachment with color 0 in the storage form of `R16_UINT` -//! (`RuntimeFact::InterlockedFramebufferFetch`), and their modules pass L3. MoltenVK renders -//! `BGRA4Unorm` through such a word alone, the RTX 5080 `A1BGR5Unorm`, `ABGR4Unorm` and -//! `BGRA4Unorm`. Before the decode, each was refused `NotImplemented(Format)` at color 0. -//! -//! The other two word kinds' reads are still not built: an 8-bit sRGB word's decode of its bytes -//! and an `RGB9E5Float` word's of its shared exponent are `NotImplemented(Format)` at the -//! attachment. No GPU is used. -//! -//! `llvm-as` assembles the fixture; a missing tool skips visibly. - -use crate::device::DeviceProfile; -use crate::error::{Error, Needs}; -use crate::library::FunctionArtifact; -use crate::metal::format::WordAttachment; -use crate::metal::{ColorWriteMask, PixelFormat}; -use crate::pipeline::descriptor::ColorAttachmentDescriptor; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::link::RenderLinkInputs; -use crate::pipeline::lower_inputs::{FramebufferFetchInputs, LoweringInputs}; -use crate::pipeline::testing::{ - compile_with, engine_dir, fragment_inputs, link_and_validate, AssembleError, -}; -use crate::spirv::testing::committed_profiles; -use crate::vk; - -/// The fixture's two readers: a `half4` color input and a `float4` one. -const ENTRIES: [&str; 2] = ["fbl8_over_loaded", "fbl8_over_loaded_float"]; - -/// Fixture `stem` assembled; `None` (skipped) without `llvm-as`. -fn assembled(stem: &str) -> Option> { - let text = - std::fs::read_to_string(engine_dir().join(format!("{stem}.ll"))).expect("the fixture"); - 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 {stem}: {why}"), - } -} - -/// Color 0 of `pf`, written whole and unblended, beside color 1 of mask none (the fixture's -/// second output). -fn attachments(pf: PixelFormat) -> RenderLinkInputs { - let mut written = ColorAttachmentDescriptor::new(pf); - written.write_mask = ColorWriteMask::ALL; - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - unwritten.write_mask = ColorWriteMask::NONE; - let mut r = RenderLinkInputs::new(); - r.color_attachments[0] = Some(written); - r.color_attachments[1] = Some(unwritten); - r -} - -/// The lowering inputs of a function that reads color 0 in [`attachments`] on `p`. -fn state(p: &DeviceProfile, pf: PixelFormat) -> LoweringInputs { - let r = attachments(pf); - let mut inputs = fragment_inputs(&r, p); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &r.color_attachments, - false, - false, - 1, - )); - inputs -} - -/// Color 0's storage form in `a`: its Vulkan format, whether it writes, and its blend. -fn fetched(a: &FunctionArtifact) -> Option<(vk::Format, bool, bool)> { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - format, - writes, - blend, - .. - } => Some((*format, *writes, blend.is_some())), - _ => None, - }) -} - -/// Whether `e` refuses a capability the compile layer does not implement. -fn not_implemented(e: &Error) -> bool { - matches!(e, Error::Unsupported(u) if u.needs == Needs::NotImplemented) -} - -#[test] -fn a_packed_sixteen_word_fetch_decodes_the_word() { - let Some(bc) = assembled("fbl_fetch_blend8") else { - return; - }; - let mut checked: Vec<(String, PixelFormat)> = Vec::new(); - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for &pf in PixelFormat::ALL { - if !matches!( - WordAttachment::of(pf, &p), - Some(WordAttachment::Packed16 { .. }) - ) { - continue; - } - let inputs = state(&p, pf); - for entry in ENTRIES { - let what = format!("{stem} {pf:?} {entry}"); - let a = - compile_with(&bc, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - fetched(&a), - Some((vk::Format::R16_UINT, true, false)), - "{what}: {:?}", - a.facts - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - checked.push((stem.clone(), pf)); - } - } - // MoltenVK renders `BGRA4Unorm` through a packed 16-bit word; the 5080 three such formats. - { - let stem = "moltenvk-m3"; - let formats: Vec = (checked.iter()) - .filter(|(s, _)| s == stem) - .map(|&(_, pf)| pf) - .collect(); - assert_eq!(formats, [PixelFormat::BGRA4Unorm], "{stem}: {checked:?}"); - } - let nvidia: Vec = (checked.iter()) - .filter(|(s, _)| s == "nvidia-rtx5080-laptop") - .map(|&(_, pf)| pf) - .collect(); - assert_eq!( - nvidia, - [ - PixelFormat::A1BGR5Unorm, - PixelFormat::ABGR4Unorm, - PixelFormat::BGRA4Unorm - ], - "{checked:?}" - ); -} - -/// An 8-bit sRGB word's read and an `RGB9E5Float` word's are not built: the attachment refuses -/// the pipeline `NotImplemented(Format)` where the function reads it (the module docs). -#[test] -fn srgb_and_shared_exponent_word_fetches_are_not_built() { - let Some(bc) = assembled("fbl_fetch_blend8") else { - return; - }; - let mut refused = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for &pf in PixelFormat::ALL { - if !matches!( - WordAttachment::of(pf, &p), - Some(WordAttachment::Srgb8 { .. } | WordAttachment::Rgb9e5) - ) { - continue; - } - let inputs = state(&p, pf); - for entry in ENTRIES { - let what = format!("{stem} {pf:?} {entry}"); - match compile_with(&bc, entry, &p, &inputs) { - Ok(a) => panic!("{what}: compiled: {:?}", a.facts), - Err(e) => { - assert!(not_implemented(&e), "{what}: {e}"); - refused += 1; - } - } - } - } - } - assert!( - refused > 0, - "no profile renders an 8-bit sRGB or shared-exponent format through a word" - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_fragment.rs b/crates/metal2vulkan/src/tests/engine_fragment.rs index e88c97d9c..e24a2fe18 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment.rs @@ -6,21 +6,20 @@ //! matrix, the module contains exactly that form's instructions, and it passes L3. The owned //! 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 the ordered forms of framebuffer -//! fetch: input attachments, and storage images inside the pixel interlock, with the binder's -//! writes. No GPU is used. +//! 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. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. use std::path::Path; -use crate::bind::{BindState, WriteSource}; use crate::budget::Budget; use crate::device::requirements::VkFeature; use crate::device::subgroup::OpBits; use crate::device::{Device, DeviceDescription}; use crate::device::{DevicePolicy, DeviceProfile}; -use crate::error::{BindError, Capability, Error, Feature, LowerFamily, Needs, RuntimeInput}; +use crate::error::{Capability, Error, Feature, LowerFamily, Needs}; use crate::library::Library; use crate::lower::fragment::DiscardForm; use crate::metal::PixelFormat; @@ -29,16 +28,15 @@ use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, }; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; use crate::pipeline::lower_inputs::{FramebufferFetchInputs, LoweringInputs}; use crate::pipeline::sym::ResourceKind; use crate::pipeline::testing::{ compile, compile_with, engine_dir, interlocked_coherence, link_and_validate, llvm_assemble, - moltenvk_msl_compile, profile, typed_module, typed_module_with, AssembleError, Scratch, + moltenvk_msl_compile, profile, typed_module, AssembleError, Scratch, }; use crate::spirv::ids::FuncId; use crate::spirv::ir::{ExecMode, Inst, Terminator, TypedModule}; -use crate::spirv::testing::{check_words_valid, committed_profiles, is_moltenvk_capture}; +use crate::spirv::testing::{committed_profiles, is_moltenvk_capture}; use crate::vk; fn assemble(path: &Path) -> Option> { @@ -436,69 +434,24 @@ fn attachments(a: &crate::library::FunctionArtifact) -> Vec { .collect() } -/// The storage-form attachments `a` declares, by color index, each a `STORAGE_IMAGE` descriptor -/// with its `InterlockedFramebufferFetch` fact. -fn storage_attachments(a: &crate::library::FunctionArtifact) -> Vec { - a.interface - .descriptors - .iter() - .filter_map(|d| match d.slot.kind { - ResourceKind::TileAttachment(c) => { - assert_eq!(d.ty, vk::DescriptorType::STORAGE_IMAGE, "{d:?}"); - assert_eq!(d.slot.index, c, "{d:?}"); - assert!( - a.facts.iter().any(|f| matches!( - f, - RuntimeFact::InterlockedFramebufferFetch { color, .. } if *color == c - )), - "{:?}", - a.facts - ); - Some(c) - } - _ => None, - }) - .collect() -} - /// The framebuffer-fetch state of a pipeline whose color attachments are `formats` (by index), -/// read at `read`, `blending` the first (adding the destination: a blend of one and zero would -/// replace it). -fn fetch_state(read: &[u32], formats: &[PixelFormat], blending: bool) -> LoweringInputs { +/// read at `read`. +fn fetch_state(read: &[u32], formats: &[PixelFormat]) -> LoweringInputs { let colors: Vec> = formats .iter() - .enumerate() - .map(|(i, &f)| { - let mut c = ColorAttachmentDescriptor::new(f); - if blending && i == 0 { - c.blending_enabled = true; - c.destination_rgb_blend_factor = crate::metal::BlendFactor::One; - } - Some(c) - }) + .map(|&f| Some(ColorAttachmentDescriptor::new(f))) .collect(); let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - read.iter().copied(), - &colors, - false, - false, - 1, - )); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of(read.iter().copied(), &colors)); inputs } - -/// Each color index a function reads is read in an ordered form wherever the device has one. With -/// rasterization-order color attachment access it is one input attachment with a `FramebufferFetch` -/// fact. With only the ordered pixel interlock it is one storage image read (and written) inside -/// the interlock, under its pipeline's state (standalone, the function needs that state); a -/// blended attachment's blend the shader computes, Metal's of a 16-bit float or 8-bit unorm one, -/// the generic one, noted `UnmeasuredFetchBlend`, of another. With neither, it is one input -/// attachment with a `FramebufferFetch` fact, ordered between draws alone and noted -/// `UnorderedFetchWithinDraw`, a raster order group on it (`fetch_ordered`) taking no interlock. -/// Every compiled module passes L3. +/// 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. #[test] -fn framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one() { +fn framebuffer_fetch_reads_an_input_attachment_ordered_where_the_device_orders_it() { let Some(bc) = fixture("fragment_fetch") else { return; }; @@ -517,17 +470,15 @@ fn framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one() { ("fetch_scalar", &[0], &[PixelFormat::R32Float]), ("fetch_ordered", &[0], &[PixelFormat::RGBA16Float]), ]; - let mut forms = [0usize; 3]; + // [unordered, ordered] + let mut forms = [0usize; 2]; 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; with neither ordered form the group orders the read alone - // (below). - if entry == "fetch_ordered" - && !frag.pixel_interlock - && frag.rasterization_order_color_access - { + // 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()), @@ -535,76 +486,9 @@ fn framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one() { ); continue; } - let clean = fetch_state(colors, formats, false); - if frag.rasterization_order_color_access { - forms[0] += 1; - for inputs in [LoweringInputs::new(), clean] { - 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!( - !a.precision - .contains(&PrecisionNote::UnorderedFetchWithinDraw), - "{entry} on {stem}" - ); - } - } else if frag.pixel_interlock { - forms[1] += 1; - assert!( - matches!( - compile(&bc, entry, &strict), - Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)) - ), - "{entry} on {stem}" - ); - let a = compile_with(&bc, entry, &strict, &clean) - .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!(storage_attachments(&a), colors, "{entry} on {stem}"); - assert!(attachments(&a).is_empty(), "{entry} on {stem}"); - // Blending the written color 0: the shader computes the blend, Metal's of a 16-bit - // float or 8-bit unorm one, the generic one, noted, of another (`R32Float`). - let blended = fetch_state(colors, formats, true); - let a = compile_with(&bc, entry, &strict, &blended) - .unwrap_or_else(|e| panic!("{entry} on {stem}: blended: {e}")); - link_and_validate(&a, &strict) - .unwrap_or_else(|e| panic!("{entry} on {stem}: blended: L3: {e}")); - assert_eq!(storage_attachments(&a), colors, "{entry} on {stem}"); - assert!( - a.facts.iter().any(|f| matches!( - f, - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - blend: Some(_), - .. - } - )), - "{entry} on {stem}: {:?}", - a.facts - ); - let generic = !matches!( - formats[0], - PixelFormat::RGBA16Float | PixelFormat::RGBA8Unorm - ); - assert_eq!( - a.precision.contains(&PrecisionNote::UnmeasuredFetchBlend), - generic, - "{entry} on {stem}: {:?}", - a.precision - ); - } else { - forms[2] += 1; - let a = compile_with(&bc, entry, &strict, &LoweringInputs::new()) + 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}")); @@ -616,9 +500,10 @@ fn framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one() { a.facts ); } - assert!( + assert_eq!( a.precision .contains(&PrecisionNote::UnorderedFetchWithinDraw), + !ordered, "{entry} on {stem}: {:?}", a.precision ); @@ -628,7 +513,6 @@ fn framebuffer_fetch_reads_in_an_ordered_form_where_the_device_has_one() { // The committed profiles cover each kind of device. assert!(forms.iter().all(|&n| n > 0), "{forms:?}"); } - /// 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. pub(super) fn holds_srgb_table(words: &[u32]) -> bool { @@ -736,1628 +620,6 @@ fn an_srgb_input_attachment_reads_the_devices_decode() { } } -/// On a device that orders fetch only through the pixel interlock (`moltenvk-m3`), the binder -/// writes a storage-form attachment to its fragment binding as the attachment's own storage view, -/// and refuses a pass of more than one layer, whose layers one 2D view does not reach. -#[test] -fn the_binder_writes_storage_attachments_and_refuses_layered_passes() { - let (Some(io), Some(fetch)) = (fixture("stage_io"), fixture("fragment_fetch")) else { - return; - }; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&fetch, "fetch_scalar")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float)); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - let storage: Vec<_> = plan - .descriptors - .iter() - .filter(|w| { - w.source - == WriteSource::TileAttachment { - color_index: 0, - format: vk::Format::R32_SFLOAT, - view: crate::pipeline::StorageAttachmentView::Attachment, - view_alias: None, - } - }) - .collect(); - assert_eq!(storage.len(), 1, "{:?}", plan.descriptors); - let b = p - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .find(|b| b.binding == storage[0].binding) - .expect("binding"); - assert_eq!(b.ty, vk::DescriptorType::STORAGE_IMAGE); - assert_eq!(b.source, BindingSource::TileAttachment(0)); - let layered = BindState { - render_target_array_length: 2, - ..Default::default() - }; - match p.plan(&dev, &layered.shape()) { - Err(BindError::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::FramebufferFetch, Needs::NotImplemented) - ), - other => panic!("{:?}", other.map(|_| ())), - } -} - -/// A draw into a render pass instance that keeps a color out of its subpass for other draws' -/// interlocked storage form runs the variant whose fragment function writes that color through the -/// same form. `rt6_resolve_white`, writing color 0 of an `RGBA16Float` attachment, planned with -/// colors 0 and 1 interlocked asks for color 0 alone (it writes no color 1); the variant's pipeline -/// writes color 0 as a storage attachment and declares no output for it, passes L3, plans the same -/// variant against itself, and binds the attachment's storage view. The pipeline itself states -/// nothing of the sort. Blended, the variant is refused (the storage form keeps no blend but one -/// and zero), so the runtime keeps such a draw in its own instance. -#[test] -fn a_draw_writes_an_interlocked_color_through_the_storage_form() { - let Some(bc) = fixture("rt6_resolves") else { - return; - }; - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let descriptor = |blended: bool| { - let mut d = RenderPipelineDescriptor::new(function("rt6_resolve_full")); - d.fragment = Some(function("rt6_resolve_white")); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - if blended { - color.blending_enabled = true; - color.destination_rgb_blend_factor = crate::metal::BlendFactor::One; - } - d.color_attachments[0] = Some(color); - d - }; - for stem in [ - "moltenvk-m3", - "amd-780m-radv", - "intel-uhd770-rpls-anv", - "nvidia-rtx5080-laptop", - ] { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let d = descriptor(false); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!(base.graphics.storage_attachments.is_empty(), "{stem}"); - let state = BindState { - interlocked_colors: [0, 1].into(), - ..Default::default() - }; - let plan = base.plan(&dev, &state.shape()).expect("plan"); - assert_eq!( - plan.variant.interlocked_colors, - [0].into(), - "{stem}: the colors it writes" - ); - let variant = dev - .compile_render_variant(&d, &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: variant: {e}")); - let stored: Vec<(u32, bool)> = variant - .graphics - .storage_attachments - .iter() - .map(|a| (a.color_index, a.writes)) - .collect(); - assert_eq!(stored, [(0, true)], "{stem}"); - let again = variant - .plan(&dev, &state.shape()) - .expect("unblended variant plan"); - assert_eq!( - again.variant, plan.variant, - "{stem}: unblended: a fixed point" - ); - assert!( - again - .graphics - .as_ref() - .is_some_and(|t| !t.other_layer_variant), - "{stem}: unblended: the variant's draws run on it: {:?}", - variant - .dependencies - .iter() - .map(|d| &d.fact) - .collect::>() - ); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - } - let again = variant.plan(&dev, &state.shape()).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{stem}: a fixed point"); - assert!( - again - .graphics - .as_ref() - .is_some_and(|t| !t.other_layer_variant), - "{stem}: the variant's draws run on it: {:?} {:?}", - variant - .dependencies - .iter() - .map(|d| &d.fact) - .collect::>(), - variant.graphics.storage_attachments - ); - assert!( - again - .descriptors - .iter() - .any(|w| matches!(w.source, WriteSource::TileAttachment { color_index: 0, .. })), - "{stem}: {:?}", - again.descriptors - ); - // Blended, the form is not built: the variant is refused. - let blended = descriptor(true); - let base = dev - .compile_render_pipeline(&blended, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: blended: {e}")); - let plan = base.plan(&dev, &state.shape()).expect("blended plan"); - assert!( - dev.compile_render_variant(&blended, &plan.variant, &Budget::standard()) - .is_err(), - "{stem}: a blended interlocked color" - ); - } -} - -/// `fragment_fetch` with `fetch_scalar` discarding a fragment whose color input is negative. -fn fetch_with_discard() -> Option> { - let src = engine_dir().join("fragment_fetch.ll"); - let text = std::fs::read_to_string(&src).expect("fixture text"); - let body = " %2 = fmul fast float %0, 5.000000e-01\n ret float %2\n"; - assert!(text.contains(body), "the fixture's fetch_scalar body"); - let discarding = " %2 = fmul fast float %0, 5.000000e-01\n %3 = fcmp fast olt float %0, 0.000000e+00\n br i1 %3, label %4, label %5\n4:\n tail call void @air.discard_fragment()\n br label %5\n5:\n ret float %2\n"; - let edited = text - .replace(body, discarding) - .replace( - "\n; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none)\ndefine <4 x float> @fetch_ordered", - "\ndeclare void @air.discard_fragment() local_unnamed_addr\n\n; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none)\ndefine <4 x float> @fetch_ordered", - ) - .replace( - "define float @fetch_scalar(float noundef %0) local_unnamed_addr #2", - "define float @fetch_scalar(float noundef %0) local_unnamed_addr", - ); - let scratch = Scratch::new("m2v-fetch-discard"); - let dir = scratch.path(); - let path = dir.join("fetch_discard.ll"); - std::fs::write(&path, edited).expect("write"); - assemble(&path) -} - -/// The storage form declares early fragment tests where a depth or stencil attachment's tests could -/// drop a fragment after its writes, and where they keep the function's writes Metal's (no discard, -/// no depth, stencil, or coverage export, no other memory write): without a depth or stencil -/// attachment no test can fail, so the module declares none. A function that may discard reads and -/// writes in the storage form without them (a discarded fragment writes nothing). Beside a depth -/// attachment, where its write precedes the depth test, it states `TestedStorageWrites` without -/// early tests, whose draws' plans check their tests, and under `read_only_tests` declares early -/// tests and states it with them. A stage compiled without a depth attachment declares no early -/// tests, so it links into no pipeline with one: `NeedsInput(FramebufferFetch)`. -#[test] -fn the_storage_form_declares_early_tests_only_where_they_keep_metals_writes() { - let (Some(plain), Some(discarding)) = (fixture("fragment_fetch"), fetch_with_discard()) else { - return; - }; - let p = profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile"); - let state = |depth: bool| { - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &[Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float))], - depth, - false, - 1, - )); - inputs - }; - let early = |a: &crate::library::FunctionArtifact| { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { early_tests, .. } => Some(*early_tests), - _ => None, - }) - }; - let tested = |a: &crate::library::FunctionArtifact| { - a.facts.iter().find_map(|f| match f { - RuntimeFact::TestedStorageWrites { - early_tests, - early_variant: true, - } => Some(*early_tests), - _ => None, - }) - }; - for (bc, discards) in [(&plain, false), (&discarding, true)] { - let what = if discards { "discarding" } else { "plain" }; - for (depth, read_only) in [(false, false), (true, false), (true, true)] { - let mut inputs = state(depth); - inputs.read_only_tests = read_only; - let declared = depth && (!discards || read_only); - let a = compile_with(bc, "fetch_scalar", &p, &inputs) - .unwrap_or_else(|e| panic!("{what} depth {depth} read-only {read_only}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!(early(&a), Some(declared), "{what} depth {depth}"); - assert_eq!( - tested(&a), - (discards && depth).then_some(read_only), - "{what} depth {depth} read-only {read_only}" - ); - let (_, m) = typed_module_with(bc, "fetch_scalar", &p, &inputs) - .unwrap_or_else(|e| panic!("{what} depth {depth}: {e}")); - let modes = &m.entry().modes; - assert!(modes.contains(&ExecMode::PixelInterlockOrdered), "{what}"); - assert_eq!( - modes.contains(&ExecMode::EarlyFragmentTests), - declared, - "{what} depth {depth} read-only {read_only}: {modes:?}" - ); - } - } - // Compiled without a depth attachment, into a pipeline with one. - let Some(io) = fixture("stage_io") else { - return; - }; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - let fragment = dev - .compile_function( - &function(&plain, "fetch_scalar"), - &state(false), - &Budget::standard(), - ) - .expect("fragment"); - d.fragment = Some(StageSource::Compiled(fragment)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float)); - d.depth_format = Some(PixelFormat::Depth32Float); - assert_eq!( - dev.compile_render_pipeline(&d, &Budget::standard()) - .map(|_| ()) - .unwrap_err(), - Error::NeedsInput(RuntimeInput::FramebufferFetch) - ); -} - -/// A fetching function that writes other memory (`dvp_rog_coherence`'s `fetch_coherent`), beside a -/// depth or stencil attachment, compiles in the storage form without early tests, its stores before -/// the tests, and states `TestedStorageWrites` without the early-tests variant: Metal runs its -/// memory writes for the fragments its tests drop. Without such an attachment it -/// states nothing. The whole pipeline on `moltenvk-m3` (a `BGRA8Unorm_sRGB` color, -/// `Depth32Float_Stencil8`) plans a draw whose tests drop no fragment, and refuses at the depth -/// attachment one that does not state its tests, whose tests a visibility result counts, or whose -/// tests may drop fragments but write and count nothing. -#[test] -fn a_fetch_that_writes_memory_beside_depth_runs_only_draws_whose_tests_drop_nothing() { - use crate::bind::FragmentTests; - use crate::error::{Attachment, Unsupported}; - let (Some(bc), Some(io)) = (fixture("dvp_rog_coherence"), fixture("stage_io")) else { - return; - }; - let state = |depth: bool| { - let mut inputs = fetch_state(&[0], &[PixelFormat::BGRA8UnormSRGB], false); - let colors = [Some(ColorAttachmentDescriptor::new( - PixelFormat::BGRA8UnormSRGB, - ))]; - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &colors, depth, false, 1)); - inputs - }; - let tested = |a: &crate::library::FunctionArtifact| { - a.facts.iter().find_map(|f| match f { - RuntimeFact::TestedStorageWrites { - early_tests, - early_variant, - } => Some((*early_tests, *early_variant)), - _ => None, - }) - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for depth in [false, true] { - let a = compile_with(&bc, "fetch_coherent", &p, &state(depth)) - .unwrap_or_else(|e| panic!("{stem} depth {depth}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert_eq!(storage_attachments(&a), [0], "{stem}"); - assert_eq!(tested(&a), depth.then_some((false, false)), "{stem}"); - let (_, m) = typed_module_with(&bc, "fetch_coherent", &p, &state(depth)) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - !m.entry().modes.contains(&ExecMode::EarlyFragmentTests), - "{stem} depth {depth}" - ); - } - checked += 1; - } - assert!(checked > 0, "no interlock profile"); - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&bc, "fetch_coherent")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::BGRA8UnormSRGB)); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("the pipeline"); - let shape = |fragment_tests: FragmentTests| { - BindState { - fragment_tests, - ..Default::default() - } - .shape() - }; - let pass = base.plan(&dev, &shape(FragmentTests::Pass)).expect("pass"); - assert!(!pass.variant.read_only_tests); - assert_eq!( - base.plan(&dev, &shape(FragmentTests::Any)).map(|_| ()), - Err(BindError::Unsupported( - Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(Attachment::Depth) - )) - ); - assert_eq!( - base.plan(&dev, &shape(FragmentTests::Drop)).map(|_| ()), - Err(BindError::Unsupported( - Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(Attachment::Depth) - )) - ); -} - -/// The pipeline state of `con_fetch_coverage`, as the guest's path-coverage pipeline has it: a -/// blended `RGBA16Float` color 0 the function writes, the `RG16Float` color 1 it reads and writes -/// under `mask`, an `RGBA16Float` color 2 it never writes (mask none), and a depth and stencil -/// attachment. -fn coverage_colors( - coverage: PixelFormat, - mask: crate::metal::ColorWriteMask, -) -> Vec> { - use crate::metal::{BlendFactor, ColorWriteMask}; - let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - color.blending_enabled = true; - color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - let mut covered = ColorAttachmentDescriptor::new(coverage); - covered.write_mask = mask; - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - unwritten.write_mask = ColorWriteMask::NONE; - vec![Some(color), Some(covered), Some(unwritten)] -} - -/// In the storage form a write mask short of the fetched attachment's channels keeps the others: -/// the write reads the texel first and writes the kept channels back as it read them, and the fact -/// names its mask's class, so a stage compiled under a mask of one class links into no pipeline of -/// another (`NeedsInput(FramebufferFetch)`). A mask of none of the format's channels writes -/// nothing; one of all of them reads nothing more. A merged `half` write notes the device's NaN -/// decode. A signed normalized format with a kept channel stays refused (its two codes of -1 -/// read alike). Every compiled module passes L3, on every committed profile that orders fetch -/// through the interlock; the guest's whole pipeline compiles on `moltenvk-m3`. -#[test] -fn a_masked_fetched_write_keeps_the_channels_its_mask_leaves_out() { - use crate::metal::ColorWriteMask; - let Some(bc) = fixture("con_fetch_coverage") else { - return; - }; - let entry = "con_fetch_coverage"; - let state = |coverage: PixelFormat, mask: ColorWriteMask| { - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [1], - &coverage_colors(coverage, mask), - true, - false, - 1, - )); - inputs - }; - let kept = |a: &crate::library::FunctionArtifact| { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { color: 1, kept, .. } => Some(*kept), - _ => None, - }) - }; - let count = |m: &TypedModule| { - let mut reads = 0; - let mut writes = 0; - for b in m.blocks() { - for n in &b.insts { - match n.inst { - Inst::ImageRead { .. } => reads += 1, - Inst::ImageWrite { .. } => writes += 1, - _ => {} - } - } - } - (reads, writes) - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let all = state(PixelFormat::RG16Float, ColorWriteMask::ALL); - let whole = match compile_with(&bc, entry, &p, &all) { - Ok(a) => a, - // A device without the format's storage refuses every mask alike. - Err(e) => { - let green = state(PixelFormat::RG16Float, ColorWriteMask::GREEN); - assert_eq!(compile_with(&bc, entry, &p, &green).map(|_| ()), Err(e)); - continue; - } - }; - checked += 1; - link_and_validate(&whole, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert_eq!( - kept(&whole), - Some(vk::ColorComponentFlags::empty()), - "{stem}" - ); - let (_, m) = typed_module_with(&bc, entry, &p, &all).expect("module"); - let (reads, writes) = count(&m); - // The guest's mask: green alone, so red is kept. - let green = state(PixelFormat::RG16Float, ColorWriteMask::GREEN); - let a = compile_with(&bc, entry, &p, &green).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert_eq!(kept(&a), Some(vk::ColorComponentFlags::R), "{stem}"); - assert!( - a.precision.contains(&PrecisionNote::DeviceNanEncoding), - "{stem}: {:?}", - a.precision - ); - let (_, m) = typed_module_with(&bc, entry, &p, &green).expect("module"); - assert_eq!(count(&m), (reads + 1, writes), "{stem}"); - // A mask that covers neither channel: no storage write at all. - let none = state(PixelFormat::RG16Float, ColorWriteMask::BLUE); - let a = compile_with(&bc, entry, &p, &none).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert_eq!( - kept(&a), - Some(vk::ColorComponentFlags::known_bits()), - "{stem}" - ); - let (_, m) = typed_module_with(&bc, entry, &p, &none).expect("module"); - assert_eq!(count(&m), (reads, writes - 1), "{stem}"); - // A signed normalized format with a kept channel. - let snorm = state(PixelFormat::RG8Snorm, ColorWriteMask::GREEN); - match compile_with(&bc, entry, &p, &snorm) { - Err(Error::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::FramebufferFetch, Needs::NotImplemented), - "{stem}" - ), - other => panic!("{stem}: {:?}", other.map(|_| ())), - } - } - assert!( - checked > 0, - "no interlock profile compiled the storage form" - ); - // The guest's pipeline, and a stage compiled under its mask linked into another. - let Some(io) = fixture("stage_io") else { - return; - }; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let pipeline = |fragment: StageSource, mask: ColorWriteMask| { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - d.fragment = Some(fragment); - for (i, c) in coverage_colors(PixelFormat::RG16Float, mask) - .into_iter() - .enumerate() - { - d.color_attachments[i] = c; - } - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - dev.compile_render_pipeline(&d, &Budget::standard()) - }; - let source = StageSource::Function(function(&bc, entry)); - pipeline(source, ColorWriteMask::GREEN).expect("the guest's pipeline"); - let fragment = dev - .compile_function( - &function(&bc, entry), - &state(PixelFormat::RG16Float, ColorWriteMask::GREEN), - &Budget::standard(), - ) - .expect("fragment"); - assert_eq!( - pipeline(StageSource::Compiled(fragment), ColorWriteMask::ALL) - .map(|_| ()) - .unwrap_err(), - Error::NeedsInput(RuntimeInput::FramebufferFetch) - ); -} - -/// The write masks that keep some of a fetched attachment's channels share one fragment key and one -/// module in each form. In the storage form (`moltenvk-m3`) the stage compiles under the mask's -/// class: its write still reads the texel first (one image read more than a write of every -/// channel), and the draw's `PushField::StorageKeptChannels` names the channels the pipeline's own -/// mask keeps (`StorageAttachmentUse::kept`, which the plan packs at bits `4c` to `4c + 3`). A -/// stage compiled under one partial mask links into a pipeline of another, and into none of a mask -/// of every channel. In the ordered form (each committed profile with rasterization order access) -/// the stage's inputs hold no mask at all. -#[test] -fn the_partial_write_masks_of_a_fetched_attachment_share_one_module() { - use crate::bind::FragmentTests; - use crate::metal::ColorWriteMask; - use crate::pipeline::artifact::RenderPipeline; - use crate::pipeline::sym::PushField; - let (Some(bc), Some(io)) = (fixture("con_fetch_coverage"), fixture("stage_io")) else { - return; - }; - let entry = "con_fetch_coverage"; - let device = |stem: &str| { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") - }; - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let descriptor = |fragment: StageSource, mask: ColorWriteMask| { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - d.fragment = Some(fragment); - for (i, c) in coverage_colors(PixelFormat::RG16Float, mask) - .into_iter() - .enumerate() - { - d.color_attachments[i] = c; - } - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - d - }; - let source = || StageSource::Function(function(&bc, entry)); - // The storage form: red alone keeps green, green alone keeps red. - let dev = device("moltenvk-m3"); - let keys = |mask| { - dev.render_pipeline_key(&descriptor(source(), mask), &Budget::standard()) - .expect("keys") - }; - let (red, green, all) = ( - keys(ColorWriteMask::RED), - keys(ColorWriteMask::GREEN), - keys(ColorWriteMask::ALL), - ); - assert_eq!(red.fragment, green.fragment); - assert_eq!(red.fragment_inputs, green.fragment_inputs); - assert_ne!(red.fragment, all.fragment); - let made = |source: StageSource, mask| { - dev.compile_render_pipeline(&descriptor(source, mask), &Budget::standard()) - }; - let fragment_words = |p: &RenderPipeline| { - p.stages - .iter() - .find(|m| m.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage") - .spirv - .clone() - }; - let shape = BindState { - fragment_tests: FragmentTests::Pass, - ..Default::default() - } - .shape(); - let kept_word = |p: &RenderPipeline| { - p.plan(&dev, &shape) - .expect("plan") - .graphics - .expect("a graphics template") - .storage_kept - }; - let reads_word = |p: &RenderPipeline| { - p.interface.push.iter().any(|pl| { - pl.fields - .iter() - .any(|f| f.field == PushField::StorageKeptChannels) - }) - }; - let (r, g) = ( - made(source(), ColorWriteMask::RED).expect("red"), - made(source(), ColorWriteMask::GREEN).expect("green"), - ); - assert_eq!(fragment_words(&r), fragment_words(&g)); - assert!(reads_word(&r) && reads_word(&g)); - let kept = |p: &RenderPipeline| p.graphics.storage_attachments[0].kept; - assert_eq!(kept(&r), vk::ColorComponentFlags::G); - assert_eq!(kept(&g), vk::ColorComponentFlags::R); - // Color 1's four bits. - assert_eq!(kept_word(&r), 0x2 << 4); - assert_eq!(kept_word(&g), 0x1 << 4); - let w = made(source(), ColorWriteMask::ALL).expect("all"); - assert!(!reads_word(&w)); - assert_eq!(kept(&w), vk::ColorComponentFlags::empty()); - assert_eq!(kept_word(&w), 0); - // The partial class's write reads the texel it merges. - let p = dev.profile(); - let reads = |inputs: &LoweringInputs| { - let (_, m) = typed_module_with(&bc, entry, p, inputs).expect("module"); - m.blocks() - .iter() - .flat_map(|b| &b.insts) - .filter(|n| matches!(n.inst, Inst::ImageRead { .. })) - .count() - }; - let partial = red.fragment_inputs.as_ref().expect("fragment inputs"); - let whole = all.fragment_inputs.as_ref().expect("fragment inputs"); - assert_eq!(reads(partial), reads(whole) + 1); - // A stage compiled under red's class links under green, and not under every channel. - let compiled = dev - .compile_function(&function(&bc, entry), partial, &Budget::standard()) - .expect("fragment"); - let linked = made( - StageSource::Compiled(compiled.clone()), - ColorWriteMask::GREEN, - ) - .expect("linked under green"); - assert_eq!(kept(&linked), vk::ColorComponentFlags::R); - assert_eq!( - made(StageSource::Compiled(compiled), ColorWriteMask::ALL) - .map(|_| ()) - .unwrap_err(), - Error::NeedsInput(RuntimeInput::FramebufferFetch) - ); - // The ordered form: no mask in the inputs. - let mut ordered = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !p.fields().fragment.rasterization_order_color_access { - continue; - } - let dev = device(&stem); - let keys = |mask| { - dev.render_pipeline_key(&descriptor(source(), mask), &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")) - }; - let (red, green) = (keys(ColorWriteMask::RED), keys(ColorWriteMask::GREEN)); - let inputs = red.fragment_inputs.as_ref().expect("fragment inputs"); - assert_eq!(inputs.framebuffer_fetch, None, "{stem}"); - assert_eq!(red.fragment, green.fragment, "{stem}"); - ordered += 1; - } - assert!( - ordered > 0, - "no committed profile orders fetch by rasterization order" - ); -} - -/// A fetched attachment of `BGRA8Unorm`, `RGBA8Unorm` or `RGBA16Float`, read and written -/// (`fragment_fetch`'s `fetch_ordered`, color 0), is declared without a format wherever the -/// device grants those formats' storage access without one, and its write selects its rounding -/// at the draw, so the fragment stage's module is the same for the three, on every committed -/// profile that orders fetch through the interlock and does not store Metal's color writes -/// itself. -#[test] -fn a_fetched_attachment_s_module_is_the_same_for_each_format_it_reads_alike() { - use crate::lower::fragment::fetch::interlock_orders; - use crate::metal::format::{accessed_without_format, StorageUse}; - let (Some(bc), Some(io)) = (fixture("fragment_fetch"), fixture("stage_io")) else { - return; - }; - let formats = [ - (PixelFormat::BGRA8Unorm, vk::Format::B8G8R8A8_UNORM), - (PixelFormat::RGBA8Unorm, vk::Format::R8G8B8A8_UNORM), - (PixelFormat::RGBA16Float, vk::Format::R16G16B16A16_SFLOAT), - ]; - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let mut shared = 0; - for (stem, p) in committed_profiles().expect("profiles") { - let access = StorageUse::texture(true, true); - let untyped = formats - .iter() - .all(|&(_, f)| accessed_without_format(f, access, &p)); - if !interlock_orders(&p) || !untyped { - continue; - } - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let mut modules = Vec::new(); - for (pf, _) in formats { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - d.fragment = Some(StageSource::Function(function(&bc, "fetch_ordered"))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf)); - let made = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - let fragment = (made.stages.iter()) - .find(|m| m.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - modules.push(fragment.spirv.clone()); - } - assert!( - modules.windows(2).all(|m| m[0] == m[1]), - "{stem}: {:?} words", - modules.iter().map(|m| m.len()).collect::>() - ); - shared += 1; - } - assert!(shared > 0, "no committed profile shares the module"); -} - -/// In the shape of the pipeline a guest made on ANV: `fetch_ordered` reads and writes color 0, a -/// `BGRA8Unorm` attachment, beside an `RGBA16Float` color 1, no blending, every channel written. On -/// the ANV profile (no `shaderStorageImageReadWithoutFormat`, and SPIR-V names no image format for -/// `B8G8R8A8_UNORM`) the whole pipeline is made, its fetched attachment a written storage -/// attachment viewed in `R8G8B8A8_UNORM` (`StorageAttachmentUse::view_alias`), declared `Rgba8`, -/// which the plan's write binds; the fragment module exchanges red and blue (an `OpVectorShuffle` -/// of lanes 2, 1, 0, 3 on its read and its write) and passes `spirv-val`. So at 4 samples, through -/// sample planes, and under a write mask that keeps green and alpha. A pipeline fetching an -/// `RGBA16Float` color 0 alone is made there too, viewed in its own format, declared `Rgba16f`. On -/// a profile that reads and writes `B8G8R8A8_UNORM` without a format the pipeline keeps its own -/// format, declared without one, as before. -#[test] -fn a_fetched_bgra_attachment_is_viewed_in_its_rgba_twin_where_no_declaration_reaches_it() { - use crate::metal::ColorWriteMask; - use crate::pipeline::{StorageAttachmentUse, StorageAttachmentView}; - let (Some(io), Some(fetch)) = (fixture("stage_io"), fixture("fragment_fetch")) else { - return; - }; - let device = |stem: &str| { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") - }; - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let descriptor = |colors: &[PixelFormat], samples: u32, mask: ColorWriteMask| { - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&fetch, "fetch_ordered")); - for (i, &pf) in colors.iter().enumerate() { - d.color_attachments[i] = Some(ColorAttachmentDescriptor::new(pf)); - } - if let Some(c) = d.color_attachments[0].as_mut() { - c.write_mask = mask; - } - d.raster_sample_count = samples; - d - }; - // The instructions of opcode `op` in `words`, each as its words. - let instructions = |words: &[u32], op: u32| { - let mut at = 5; - let mut found = Vec::new(); - while at < words.len() { - let count = (words[at] >> 16) as usize; - if count == 0 || at + count > words.len() { - break; - } - if words[at] & 0xffff == op { - found.push(words[at..at + count].to_vec()); - } - at += count; - } - found - }; - // The `OpVectorShuffle`s (79) of four lanes 2, 1, 0, 3: an exchange of red and blue. - let exchanges = |words: &[u32]| { - instructions(words, 79) - .iter() - .filter(|i| i.len() == 9 && i[5..] == [2, 1, 0, 3]) - .count() - }; - // Whether `words` declare an `OpTypeImage` (25) of storage (`Sampled` 2) in `format`. - let declares = |words: &[u32], format: crate::spv::ImageFormat| { - instructions(words, 25) - .iter() - .any(|i| i.len() >= 9 && i[7] == 2 && i[8] == format as u32) - }; - let consumer = [PixelFormat::BGRA8Unorm, PixelFormat::RGBA16Float]; - let partial = ColorWriteMask::RED.union(ColorWriteMask::BLUE); - let anv = device("intel-irisxe-anv"); - for (samples, mask) in [ - (1, ColorWriteMask::ALL), - (4, ColorWriteMask::ALL), - (1, partial), - ] { - let what = format!("{samples}x {mask:?}"); - let p = anv - .compile_render_pipeline(&descriptor(&consumer, samples, mask), &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let view = match samples { - 1 => StorageAttachmentView::Attachment, - layers => StorageAttachmentView::SamplePlanes { layers }, - }; - let kept = match mask == partial { - true => vk::ColorComponentFlags::G | vk::ColorComponentFlags::A, - false => vk::ColorComponentFlags::empty(), - }; - let want = StorageAttachmentUse::new(0, vk::Format::B8G8R8A8_UNORM, true, false, view) - .with_view_alias(vk::Format::R8G8B8A8_UNORM) - .with_kept(kept); - assert_eq!(p.graphics.storage_attachments, [want], "{what}"); - assert_eq!(want.view_format(), vk::Format::R8G8B8A8_UNORM); - let plan = p.plan(&anv, &BindState::default().shape()).expect("plan"); - let bound = plan.descriptors.iter().any(|w| { - w.source - == WriteSource::TileAttachment { - color_index: 0, - format: vk::Format::B8G8R8A8_UNORM, - view, - view_alias: Some(vk::Format::R8G8B8A8_UNORM), - } - }); - assert!(bound, "{what}: {:?}", plan.descriptors); - let fragment = (p.stages.iter()) - .find(|m| m.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - let rgba8 = declares(&fragment.spirv, crate::spv::ImageFormat::Rgba8); - assert!(rgba8, "{what}: no Rgba8 storage image"); - // A read, a write and, under the partial mask, the merge's read of the kept channels. - let reads = 1 + usize::from(mask == partial); - assert_eq!(exchanges(&fragment.spirv), reads + 1, "{what}"); - check_words_valid(&fragment.spirv, &p.requirements, anv.profile()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - } - // `RGBA16Float` fetched alone: its own format, declared `Rgba16f`. - let p = anv - .compile_render_pipeline( - &descriptor(&[PixelFormat::RGBA16Float], 1, ColorWriteMask::ALL), - &Budget::standard(), - ) - .expect("an RGBA16Float fetch"); - let want = StorageAttachmentUse::new( - 0, - vk::Format::R16G16B16A16_SFLOAT, - true, - false, - StorageAttachmentView::Attachment, - ); - assert_eq!(p.graphics.storage_attachments, [want]); - let fragment = (p.stages.iter()) - .find(|m| m.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - assert!(declares(&fragment.spirv, crate::spv::ImageFormat::Rgba16f)); - assert_eq!(exchanges(&fragment.spirv), 0); - // A device that reads and writes `B8G8R8A8_UNORM` without a format keeps its own view. - for stem in ["amd-rdna3-radv", "nvidia-rtx5080-laptop"] { - let dev = device(stem); - let p = dev - .compile_render_pipeline( - &descriptor(&consumer, 1, ColorWriteMask::ALL), - &Budget::standard(), - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want = StorageAttachmentUse::new( - 0, - vk::Format::B8G8R8A8_UNORM, - true, - true, - StorageAttachmentView::Attachment, - ); - assert_eq!(p.graphics.storage_attachments, [want], "{stem}"); - } -} - -/// In the shapes of two pipelines a guest made: a fetched attachment written under a blend of one -/// and zero, added, for color and alpha (all of `RG16Float`'s channels) beside two -/// `RGB10A8_2P_XR10` attachments of mask none, with early tests (`con_fetch_coverage`); and a -/// fetched attachment written under mask none by a function that discards, beside a depth and -/// stencil attachment, so without early tests (`msf_fetch_discard`). Each takes the storage form on -/// every committed profile that orders fetch through the interlock (a write of mask none stores -/// nothing), passes L3, and the first makes its whole pipeline on `moltenvk-m3`; under a blend that -/// adds the destination too, the function computing Metal's blend of its `half2` output (one and -/// one, added: Metal's `h(s + d)`, measured bit-exact by the narrow sweeps), its -/// fact naming the blend, and passes L3. A stored channel without early tests compiles, stating -/// `TestedStorageWrites`, whose draws' plans check their tests; the write of mask none states -/// nothing of them. -#[test] -fn a_replacing_blend_or_a_write_that_stores_nothing_takes_the_storage_form() { - use crate::metal::{BlendFactor, ColorWriteMask}; - let (Some(coverage), Some(discard)) = (fixture("con_fetch_coverage"), fixture("msf_fetch_ms")) - else { - return; - }; - // `con_fetch_coverage`'s pipeline: color 1 replaced under `blend`, the others of mask none. - let replacing = |blend: BlendFactor| { - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGB10A82PXR10); - unwritten.write_mask = ColorWriteMask::NONE; - let mut replaced = ColorAttachmentDescriptor::new(PixelFormat::RG16Float); - replaced.blending_enabled = true; - replaced.destination_rgb_blend_factor = blend; - replaced.write_mask = ColorWriteMask::RED.union(ColorWriteMask::GREEN); - vec![Some(unwritten), Some(replaced), Some(unwritten)] - }; - // `msf_fetch_discard`'s: color 0 under `mask`. - let discarding = |mask: ColorWriteMask| { - let mut c = ColorAttachmentDescriptor::new(PixelFormat::RG16Float); - c.write_mask = mask; - vec![Some(c)] - }; - // The pipeline's state for a function that reads color `read`: its color writes and - // extended-range attachments too, as the render pipeline compile sets them. - let state = |read: u32, 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([read], colors, true, false, 1)); - inputs - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let one_zero = state(1, &replacing(BlendFactor::Zero), &p); - let a = match compile_with(&coverage, "con_fetch_coverage", &p, &one_zero) { - Ok(a) => a, - // A device without the format's storage refuses the form whatever the blend. - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => continue, - Err(e) => panic!("{stem}: {e}"), - }; - checked += 1; - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let adds = state(1, &replacing(BlendFactor::One), &p); - let a = compile_with(&coverage, "con_fetch_coverage", &p, &adds) - .unwrap_or_else(|e| panic!("{stem}: adds: {e}")); - let fetched = a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 1, - writes, - blend, - .. - } => Some((*writes, blend.is_some())), - _ => None, - }); - assert_eq!(fetched, Some((true, true)), "{stem}: adds: {:?}", a.facts); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: adds: L3: {e}")); - let none = state(0, &discarding(ColorWriteMask::NONE), &p); - let a = compile_with(&discard, "msf_fetch_discard", &p, &none) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert!( - a.facts.iter().any(|f| matches!( - f, - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes: true, - early_tests: false, - .. - } - )), - "{stem}: {:?}", - a.facts - ); - let tested = |a: &crate::library::FunctionArtifact| { - a.facts.iter().any(|f| { - matches!( - f, - RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant: true - } - ) - }) - }; - assert!(!tested(&a), "{stem}: {:?}", a.facts); - let stored = state(0, &discarding(ColorWriteMask::ALL), &p); - let a = compile_with(&discard, "msf_fetch_discard", &p, &stored) - .unwrap_or_else(|e| panic!("{stem}: stored: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: stored: L3: {e}")); - assert!(tested(&a), "{stem}: {:?}", a.facts); - } - assert!( - checked > 0, - "no interlock profile compiled the storage form" - ); - // The first pipeline, whole, on `moltenvk-m3`. - let Some(io) = fixture("stage_io") else { - return; - }; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - d.fragment = Some(StageSource::Function(function( - &coverage, - "con_fetch_coverage", - ))); - for (i, c) in replacing(BlendFactor::Zero).into_iter().enumerate() { - d.color_attachments[i] = c; - } - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - dev.compile_render_pipeline(&d, &Budget::standard()) - .expect("the replacing pipeline"); -} - -/// In the shape of a pipeline a guest made: `con_fetch_coverage` writes a `half4` to color 0, an -/// `RGB10A8_2P_XR10` attachment blended with source factor one and destination factor one minus the -/// source's alpha, added, for color and alpha (premultiplied over), and reads color 1 (`RG16Float`, -/// written under mask none) beside a second `RGB10A8_2P_XR10` attachment of mask none and a depth -/// and stencil attachment. On every committed profile that orders fetch through the interlock the -/// shader blends color 0: it reads the texel, blends the output over its tile value and stores the -/// encode (one image read and one write more than the pipeline unblended), the fact names the -/// blend, and the module passes L3. Color 0 and color 2 are `RGB10A2Unorm_sRGB`, the -/// four-channel padded form, where the guest's were `RGB10A8_2P_XR10`, whose blend is refused -/// (`blended_pipelines`). The whole pipeline is made on `moltenvk-m3` -/// (no vertex descriptor), color 0 a written storage attachment of the raw format, as are its -/// pipelines blending one plus one, one and zero, and source alpha over, and a stage compiled under -/// its state links into no pipeline of another blend there. The `float4` fill -/// (`rt6_fill_rgba32float`) under the premultiplied blend compiles; so do source alpha over and the -/// `half4` fill. The function is built without fast math; the color channels' blend color -/// difference makes the whole pipeline in it and in the same function switched to fast math. The -/// consumer's mask blend (G345: color source factor zero over one minus the source's alpha) is -/// computed in the shader too, for the `half4` output and for the `float4` fill, and makes the -/// whole pipeline on the MoltenVK profile. -#[test] -fn a_premultiplied_blend_into_a_padded_attachment_is_computed_in_the_shader() { - use crate::metal::format::ExtendedRange; - use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask}; - use crate::pipeline::lower_inputs::BlendEquation; - let (Some(coverage), Some(fills)) = (fixture("con_fetch_coverage"), fixture("rt6_samples")) - else { - return; - }; - // The coverage function is built without fast math; the same function under fast math. - let text = std::fs::read_to_string(engine_dir().join("con_fetch_coverage.ll")).expect("text"); - assert_eq!(text.matches("air.compile.fast_math_disable").count(), 1); - let fast = text.replace( - "air.compile.fast_math_disable", - "air.compile.fast_math_enable", - ); - let fast_coverage = match metal2vulkan_devtools::llvm_assemble_text(&fast) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the fast coverage: {why}"), - }; - // The guest's attachments, color 0 blended with source factor `source` for color and - // destination factor `destination` for color and alpha. - let colors = |source: BlendFactor, destination: BlendFactor| { - let mut blended = ColorAttachmentDescriptor::new(PixelFormat::RGB10A2UnormSRGB); - blended.blending_enabled = true; - blended.source_rgb_blend_factor = source; - blended.destination_rgb_blend_factor = destination; - blended.destination_alpha_blend_factor = destination; - let mut read = ColorAttachmentDescriptor::new(PixelFormat::RG16Float); - read.write_mask = ColorWriteMask::NONE; - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGB10A2UnormSRGB); - unwritten.write_mask = ColorWriteMask::NONE; - vec![Some(blended), Some(read), Some(unwritten)] - }; - let premul = || colors(BlendFactor::One, BlendFactor::OneMinusSourceAlpha); - // The color channels' blend color difference, which the shader blends under either math. - let difference = || { - let mut c = colors(BlendFactor::BlendColor, BlendFactor::OneMinusBlendColor); - if let Some(a) = c[0].as_mut() { - a.rgb_blend_operation = BlendOperation::Subtract; - } - c - }; - // The pipeline's state for a function that reads (or blends) the colors `read`, as the render - // pipeline compile sets it. - let state = |read: &[u32], 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( - read.iter().copied(), - colors, - true, - false, - 1, - )); - inputs - }; - let fetched = |a: &crate::library::FunctionArtifact, color: u32| { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: c, - writes, - blend, - .. - } if *c == color => Some((*writes, *blend)), - _ => None, - }) - }; - let count = |m: &TypedModule| { - let mut out = (0, 0); - for b in m.blocks() { - for n in &b.insts { - match n.inst { - Inst::ImageRead { .. } => out.0 += 1, - Inst::ImageWrite { .. } => out.1 += 1, - _ => {} - } - } - } - out - }; - let equation = 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, - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let a_state = state(&[0, 1], &premul(), &p); - let a = match compile_with(&coverage, "con_fetch_coverage", &p, &a_state) { - Ok(a) => a, - // A device without the raw formats' storage refuses the form whatever the blend. - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => continue, - Err(e) => panic!("{stem}: {e}"), - }; - checked += 1; - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - assert_eq!( - fetched(&a, 0), - Some((true, Some(equation))), - "{stem}: {:?}", - a.facts - ); - assert_eq!(fetched(&a, 1), Some((true, None)), "{stem}: {:?}", a.facts); - // Against the same pipeline unblended (color 0 a color attachment, color 1 written - // nowhere under mask none): color 0's texel is read and written once more. - let mut unblended = premul(); - if let Some(c) = unblended[0].as_mut() { - c.blending_enabled = false; - } - let plain = state(&[1], &unblended, &p); - let (_, m) = - typed_module_with(&coverage, "con_fetch_coverage", &p, &plain).expect("module"); - let (reads, writes) = count(&m); - let (_, m) = - typed_module_with(&coverage, "con_fetch_coverage", &p, &a_state).expect("module"); - assert_eq!(count(&m), (reads + 1, writes + 1), "{stem}"); - let over = state( - &[0, 1], - &colors(BlendFactor::SourceAlpha, BlendFactor::OneMinusSourceAlpha), - &p, - ); - let a = compile_with(&coverage, "con_fetch_coverage", &p, &over) - .unwrap_or_else(|e| panic!("{stem}: over: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: over: L3: {e}")); - let differs = state(&[0, 1], &difference(), &p); - let made = compile_with(&coverage, "con_fetch_coverage", &p, &differs) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference: {e}")); - link_and_validate(&made, &p) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference: L3: {e}")); - let made = compile_with(&fast_coverage, "con_fetch_coverage", &p, &differs) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference, fast: {e}")); - link_and_validate(&made, &p) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference, fast: L3: {e}")); - let fill = state(&[0], &premul(), &p); - let float = compile_with(&fills, "rt6_fill_rgba32float", &p, &fill) - .unwrap_or_else(|e| panic!("{stem}: float4: {e}")); - link_and_validate(&float, &p).unwrap_or_else(|e| panic!("{stem}: float4: L3: {e}")); - let half = compile_with(&fills, "rt6_fill_rgba16float", &p, &fill) - .unwrap_or_else(|e| panic!("{stem}: half4: {e}")); - link_and_validate(&half, &p).unwrap_or_else(|e| panic!("{stem}: half4: L3: {e}")); - let masked = || colors(BlendFactor::Zero, BlendFactor::OneMinusSourceAlpha); - let mask = state(&[0, 1], &masked(), &p); - let a = compile_with(&coverage, "con_fetch_coverage", &p, &mask) - .unwrap_or_else(|e| panic!("{stem}: the mask blend: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: the mask blend: L3: {e}")); - let mask_equation = BlendEquation { - source_rgb: BlendFactor::Zero, - ..equation - }; - assert_eq!(fetched(&a, 0), Some((true, Some(mask_equation))), "{stem}"); - let fill = state(&[0], &masked(), &p); - for name in ["rt6_fill_rgba32float", "rt6_fill_rgba16float"] { - let f = compile_with(&fills, name, &p, &fill) - .unwrap_or_else(|e| panic!("{stem}: {name} under the mask blend: {e}")); - link_and_validate(&f, &p) - .unwrap_or_else(|e| panic!("{stem}: {name} under the mask blend: L3: {e}")); - } - } - assert!( - checked > 0, - "no interlock profile compiled the storage form" - ); - // The whole pipeline on each MoltenVK profile (no vertex descriptor; color 2 of mask none and - // the depth and stencil attachment in the interlocked pass), and a stage compiled under its - // state linked into a pipeline of another blend. - let Some(io) = fixture("stage_io") else { - return; - }; - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - { - let stem = "moltenvk-m3"; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let pipeline = |fragment: StageSource, colors: Vec>| { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &io, - "stage_io_vertex_position", - ))); - d.fragment = Some(fragment); - for (i, c) in colors.into_iter().enumerate() { - d.color_attachments[i] = c; - } - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - dev.compile_render_pipeline(&d, &Budget::standard()) - }; - let source = StageSource::Function(function(&coverage, "con_fetch_coverage")); - let pipe = pipeline(source, premul()) - .unwrap_or_else(|e| panic!("{stem}: the guest's pipeline: {e}")); - let uses: Vec<(u32, vk::Format, bool)> = pipe - .graphics - .storage_attachments - .iter() - .map(|s| (s.color_index, s.format, s.writes)) - .collect(); - assert_eq!( - uses, - [ - (0, ExtendedRange::Rgb10A2Srgb.raw_format(), true), - (1, vk::Format::R16G16_SFLOAT, true), - ], - "{stem}" - ); - let fragment = dev - .compile_function( - &function(&coverage, "con_fetch_coverage"), - &state(&[0, 1], &premul(), dev.profile()), - &Budget::standard(), - ) - .expect("fragment"); - let added = colors(BlendFactor::One, BlendFactor::One); - assert_eq!( - pipeline(StageSource::Compiled(fragment), added) - .map(|_| ()) - .unwrap_err(), - Error::NeedsInput(RuntimeInput::FramebufferFetch), - "{stem}" - ); - // Each blend the shader computes makes the whole pipeline, the color channels' blend color - // difference under either math. - for (src, dst) in [ - (BlendFactor::One, BlendFactor::One), - (BlendFactor::One, BlendFactor::Zero), - (BlendFactor::Zero, BlendFactor::OneMinusSourceAlpha), - (BlendFactor::SourceAlpha, BlendFactor::OneMinusSourceAlpha), - ] { - let source = StageSource::Function(function(&coverage, "con_fetch_coverage")); - pipeline(source, colors(src, dst)) - .unwrap_or_else(|e| panic!("{stem}: {src:?}, {dst:?}: {e}")); - } - let source = StageSource::Function(function(&coverage, "con_fetch_coverage")); - pipeline(source, difference()) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference: {e}")); - let source = StageSource::Function(function(&fast_coverage, "con_fetch_coverage")); - pipeline(source, difference()) - .unwrap_or_else(|e| panic!("{stem}: the blend color difference, fast: {e}")); - } -} - -/// Without fast math, a blend of the second source into an extended-range attachment reads the -/// function's index-1 output in the shader. `stage_io`'s dual-source function, its -/// `air.compile.fast_math_enable` switched to `_disable`, makes the whole pipeline on `moltenvk-m3` -/// into an `RGB10A8_2P_XR10` color 0 blended with the second source's factors in -/// color and alpha: color 0 a written storage attachment, the fact naming the blend and its rounded -/// math, and no dual-source output (`dualSrcBlend` not required); under a write mask of no channel -/// it is made too, the second output stored nowhere. Under fast math the same pipeline is made too; -/// the blend of a function that writes no second output is refused as Metal refuses its pipeline, -/// `InvalidDescriptor(ColorAttachment)`. -/// Into each of the six extended-range formats unblended (the raw texel through the interface), with -/// and without fast math, the function's two outputs make the pipeline, the second stored nowhere: -/// no dual-source output. Blended premultiplied over, which reads no second source, each is refused -/// `NotImplemented(Format)`, as every blend into one of Apple's extended-range forms is. -#[test] -fn a_second_source_blend_without_fast_math_reads_the_second_output() { - use crate::metal::format::ExtendedRange; - use crate::metal::BlendFactor; - use crate::pipeline::lower_inputs::BlendEquation; - use metal2vulkan_devtools::AssembleError; - let Some(fast) = fixture("stage_io") else { - return; - }; - let text = std::fs::read_to_string(engine_dir().join("stage_io.ll")).expect("text"); - let enable = "air.compile.fast_math_enable"; - assert_eq!(text.matches(enable).count(), 1); - let text = text.replace(enable, "air.compile.fast_math_disable"); - let safe = match metal2vulkan_devtools::llvm_assemble_text(&text) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the safe stage_io: {why}"), - }; - let function = |bc: &[u8], name: &str| { - FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - ) - }; - let equation = BlendEquation { - source_rgb: BlendFactor::Source1Color, - destination_rgb: BlendFactor::OneMinusSource1Alpha, - rgb_operation: crate::metal::BlendOperation::Add, - source_alpha: BlendFactor::Source1Alpha, - destination_alpha: BlendFactor::OneMinusSource1Color, - alpha_operation: crate::metal::BlendOperation::Add, - }; - let mut blended = ColorAttachmentDescriptor::new(PixelFormat::RGB10A2UnormSRGB); - blended.blending_enabled = true; - blended.source_rgb_blend_factor = equation.source_rgb; - blended.destination_rgb_blend_factor = equation.destination_rgb; - blended.source_alpha_blend_factor = equation.source_alpha; - blended.destination_alpha_blend_factor = equation.destination_alpha; - { - let stem = "moltenvk-m3"; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let pipeline = |bc: &[u8], fragment: &str| { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - bc, - "stage_io_vertex_position", - ))); - d.fragment = Some(StageSource::Function(function(bc, fragment))); - d.color_attachments[0] = Some(blended); - dev.compile_render_pipeline(&d, &Budget::standard()) - }; - let pipe = pipeline(&safe, "stage_io_fragment_dual_source") - .unwrap_or_else(|e| panic!("{stem}: the second source without fast math: {e}")); - let uses: Vec<(u32, vk::Format, bool)> = pipe - .graphics - .storage_attachments - .iter() - .map(|s| (s.color_index, s.format, s.writes)) - .collect(); - assert_eq!( - uses, - [(0, ExtendedRange::Rgb10A2Srgb.raw_format(), true)], - "{stem}" - ); - assert!( - pipe.dependencies.iter().any(|d| matches!( - d.fact, - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes: true, - blend: Some(b), - rounded: true, - .. - } if b == equation - )), - "{stem}: {:?}", - pipe.dependencies - ); - // No dual-source output: the shader reads the second output itself. - assert!( - !pipe - .requirements - .features - .contains(&VkFeature::DualSrcBlend), - "{stem}" - ); - // A write of none of the attachment's channels stores nothing, and reads no second - // output: made, with no dual-source output either. - let none = { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - &safe, - "stage_io_vertex_position", - ))); - d.fragment = Some(StageSource::Function(function( - &safe, - "stage_io_fragment_dual_source", - ))); - let mut unwritten = blended; - unwritten.write_mask = crate::metal::ColorWriteMask::NONE; - d.color_attachments[0] = Some(unwritten); - dev.compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: the second source under no channel: {e}")) - }; - assert!( - !none - .requirements - .features - .contains(&VkFeature::DualSrcBlend), - "{stem}: no channel" - ); - let fast_pipe = pipeline(&fast, "stage_io_fragment_dual_source") - .unwrap_or_else(|e| panic!("{stem}: the second source under fast math: {e}")); - assert!( - !fast_pipe - .requirements - .features - .contains(&VkFeature::DualSrcBlend), - "{stem}: fast math" - ); - match pipeline(&safe, "stage_io_fragment_point") { - Err(Error::InvalidDescriptor(crate::error::DescriptorError::ColorAttachment { - index: 0, - metal: crate::error::MetalAnswer::NilWithError, - })) => {} - r => panic!("{stem}: no second output: {:?}", r.map(|_| ())), - } - // A second output no blend reads, into each extended-range format: stored nowhere where - // the attachment is unblended; a blend into one is refused (`blended_pipelines`). - for raw in 550..=555u32 { - let pf = PixelFormat::try_from(raw).expect("format"); - for (bc, math) in [(&safe, "safe"), (&fast, "fast")] { - for blending in [false, true] { - let mut color = ColorAttachmentDescriptor::new(pf); - color.blending_enabled = blending; - color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function( - bc, - "stage_io_vertex_position", - ))); - d.fragment = Some(StageSource::Function(function( - bc, - "stage_io_fragment_dual_source", - ))); - d.color_attachments[0] = Some(color); - let what = format!("{stem}: {pf:?} {math} blended {blending}"); - let made = dev.compile_render_pipeline(&d, &Budget::standard()); - if blending { - match made { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::Format, "{what}: {u:?}"); - assert_eq!(u.needs, Needs::NotImplemented, "{what}: {u:?}"); - } - r => panic!("{what}: {:?}", r.map(|_| ())), - } - continue; - } - let pipe = made.unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - !pipe - .requirements - .features - .contains(&VkFeature::DualSrcBlend), - "{what}" - ); - } - } - } - } -} - /// In the shape of a pipeline a guest made: a function that reads color 0, an `RGB10A8_2P_XR10` /// attachment, and writes it back under every channel with blending disabled, beside an `RG16Float` /// color 1 and a second `RGB10A8_2P_XR10` attachment, both of mask none. Metal's tile holds such an @@ -2393,13 +655,7 @@ 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, - true, - false, - 1, - )); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of(read.iter().copied(), colors)); inputs }; let refused = |r: Result, Error>, @@ -2475,512 +731,6 @@ fn a_fetched_extended_range_attachment_is_refused() { } } -/// In the shape of a pipeline a guest made: `tsw_fetch_discard` writes a `half4` to color 0, an -/// `RGB10A8_2P_XR10` attachment premultiplied over (which the shader blends), reads color 1 -/// (`RG16Float`, written under mask none) beside a second `RGB10A8_2P_XR10` attachment of mask none -/// and a depth and stencil attachment, and discards, without early tests. On every committed -/// profile that orders fetch through the interlock the function compiles, its color 0 write before -/// the tests, and states `TestedStorageWrites` without early tests; under `read_only_tests` it -/// declares early tests and states the fact with them; each module passes L3. `con_fetch_coverage`, -/// which declares early tests, states no such fact. Color 0 and color 2 are -/// `RGB10A2Unorm_sRGB`, the four-channel padded form, where the guest's were `RGB10A8_2P_XR10`, -/// whose blend is refused (`blended_pipelines`). On `moltenvk-m3` the whole pipeline is made; a -/// draw whose tests drop no fragment runs it as compiled, one whose tests drop fragments but write -/// and count nothing asks for the early-tests variant, whose plan states the same key; one whose -/// depth test writes is refused `NotImplemented(FramebufferFetch)` at the depth attachment, one -/// whose stencil test acts at the stencil attachment, and any other (or one that states nothing) -/// so without an attachment. -#[test] -fn a_discarding_fetch_beside_depth_stores_before_the_tests_its_draws_check() { - use crate::bind::FragmentTests; - use crate::metal::{BlendFactor, ColorWriteMask, CompareFunction, StencilOperation}; - let (Some(tested), Some(early), Some(io)) = ( - fixture("tsw_fetch_discard"), - fixture("con_fetch_coverage"), - fixture("stage_io"), - ) else { - return; - }; - let colors = || { - let mut blended = ColorAttachmentDescriptor::new(PixelFormat::RGB10A2UnormSRGB); - blended.blending_enabled = true; - blended.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - blended.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - let mut read = ColorAttachmentDescriptor::new(PixelFormat::RG16Float); - read.write_mask = ColorWriteMask::NONE; - let mut unwritten = ColorAttachmentDescriptor::new(PixelFormat::RGB10A2UnormSRGB); - unwritten.write_mask = ColorWriteMask::NONE; - vec![Some(blended), Some(read), Some(unwritten)] - }; - // The pipeline's state, as the render pipeline compile sets it. - let state = |p: &DeviceProfile, read_only: bool| { - let colors = colors(); - 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([0, 1], &colors, true, false, 1)); - inputs.read_only_tests = read_only; - inputs - }; - let facts = |a: &crate::library::FunctionArtifact| { - let fetched: Vec<(u32, bool, bool)> = a - .facts - .iter() - .filter_map(|f| match *f { - RuntimeFact::InterlockedFramebufferFetch { - color, - writes, - early_tests, - .. - } => Some((color, writes, early_tests)), - _ => None, - }) - .collect(); - let tested = a.facts.iter().find_map(|f| match *f { - RuntimeFact::TestedStorageWrites { - early_tests, - early_variant: true, - } => Some(early_tests), - _ => None, - }); - (fetched, tested) - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - for read_only in [false, true] { - let a = match compile_with(&tested, "tsw_fetch_discard", &p, &state(&p, read_only)) { - Ok(a) => a, - // A device without the raw formats' storage refuses the form whatever the tests. - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => continue, - Err(e) => panic!("{stem} read-only {read_only}: {e}"), - }; - checked += 1; - link_and_validate(&a, &p) - .unwrap_or_else(|e| panic!("{stem} read-only {read_only}: L3: {e}")); - assert_eq!( - facts(&a), - ( - vec![(0, true, read_only), (1, true, read_only)], - Some(read_only) - ), - "{stem} read-only {read_only}" - ); - let (_, m) = typed_module_with(&tested, "tsw_fetch_discard", &p, &state(&p, read_only)) - .expect("module"); - assert_eq!( - m.entry().modes.contains(&ExecMode::EarlyFragmentTests), - read_only, - "{stem} read-only {read_only}" - ); - } - if let Ok(a) = compile_with(&early, "con_fetch_coverage", &p, &state(&p, false)) { - assert_eq!(facts(&a).1, None, "{stem}: declared early tests"); - } - } - assert!( - checked > 0, - "no interlock profile compiled the storage form" - ); - // The whole pipeline on `moltenvk-m3`, and its draws' plans. - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&tested, "tsw_fetch_discard")); - for (i, c) in colors().into_iter().enumerate() { - d.color_attachments[i] = c; - } - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("the guest's pipeline"); - assert!(base.dependencies.iter().any(|x| x.fact - == RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant: true - })); - // The draw's tests: depth `Always`; a stencil `Equal` that keeps the stencil; and a depth - // `Less` that writes. - let always = crate::metal::state::DepthStencilDescriptor::default(); - let mut equal = always; - for face in [&mut equal.front_face_stencil, &mut equal.back_face_stencil] { - face.stencil_compare_function = CompareFunction::Equal; - } - let mut less = always; - less.depth_compare_function = CompareFunction::Less; - less.depth_write_enabled = true; - let mut replaced = equal; - replaced.front_face_stencil.depth_stencil_pass_operation = StencilOperation::Replace; - let tests = |ds: &crate::metal::state::DepthStencilDescriptor, counted: bool| { - FragmentTests::of(ds, true, true, counted) - }; - assert_eq!(tests(&always, true), FragmentTests::Pass); - assert_eq!(tests(&less, false), FragmentTests::Depth { writes: true }); - assert_eq!(tests(&less, true), FragmentTests::Any); - assert_eq!(tests(&equal, false), FragmentTests::Drop); - assert_eq!(tests(&equal, true), FragmentTests::Any); - assert_eq!(tests(&replaced, false), FragmentTests::Stencil); - assert_eq!(tests(&replaced, true), FragmentTests::Any); - // Without a stencil attachment the stencil drops nothing. - assert_eq!( - FragmentTests::of(&equal, true, false, false), - FragmentTests::Pass - ); - let shape = |fragment_tests: FragmentTests| { - BindState { - fragment_tests, - ..Default::default() - } - .shape() - }; - let pass = base.plan(&dev, &shape(FragmentTests::Pass)).expect("pass"); - assert!(!pass.variant.read_only_tests); - let drop = base.plan(&dev, &shape(FragmentTests::Drop)).expect("drop"); - assert!(drop.variant.read_only_tests); - for refused in [FragmentTests::Any, FragmentTests::default()] { - assert_eq!( - base.plan(&dev, &shape(refused)).map(|_| ()), - Err(BindError::Unsupported( - crate::error::Unsupported::not_implemented(Feature::FramebufferFetch) - )), - "{refused:?}" - ); - } - let variant = dev - .compile_render_variant(&d, &drop.variant, &Budget::standard()) - .expect("the early-tests variant"); - assert!(variant.dependencies.iter().any(|x| x.fact - == RuntimeFact::TestedStorageWrites { - early_tests: true, - early_variant: true - })); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("L3: {e}")); - } - let again = variant - .plan(&dev, &shape(FragmentTests::Drop)) - .expect("variant plan"); - assert_eq!(again.variant, drop.variant, "a fixed point"); - // A depth test that writes nothing keeps the early-tests variant; one that writes, and a - // stencil test that acts, are refused at their attachments: the function stores before - // Vulkan's tests. - let read_only = base - .plan(&dev, &shape(FragmentTests::Depth { writes: false })) - .expect("depth without writes"); - assert!(read_only.variant.read_only_tests); - for (tests, at) in [ - ( - FragmentTests::Depth { writes: true }, - crate::error::Attachment::Depth, - ), - (FragmentTests::Stencil, crate::error::Attachment::Stencil), - ] { - assert_eq!( - base.plan(&dev, &shape(tests)).map(|_| ()), - Err(BindError::Unsupported( - crate::error::Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(at) - )), - "{tests:?}" - ); - } -} - -/// At 4 samples a discarding fetch that stores a color through the interlock beside a -/// `Depth32Float_Stencil8` attachment, without early tests: a draw whose depth test writes is -/// refused `NotImplemented(FramebufferFetch)` at the depth attachment on every device (MoltenVK on -/// the M3 Max, RADV, Intel's ANV), as at one sample. -#[test] -fn a_per_sample_depth_test_is_refused_at_the_depth_attachment() { - use crate::bind::FragmentTests; - use crate::error::{Attachment, Unsupported}; - let (Some(tested), Some(io)) = (fixture("tsw_fetch_discard"), fixture("stage_io")) else { - return; - }; - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let device = |stem: &str| { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{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") - }; - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&tested, "tsw_fetch_discard")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float)); - // Color 1 is fetched and written, as the guest's color 0 is. - d.color_attachments[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::RG16Float)); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - d.raster_sample_count = 4; - let shape = |fragment_tests: FragmentTests| { - BindState { - fragment_tests, - ..Default::default() - } - .shape() - }; - for stem in ["moltenvk-m3", "amd-780m-radv", "intel-irisxe-rplp-anv"] { - let dev = device(stem); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!( - base.plan(&dev, &shape(FragmentTests::Depth { writes: true })) - .map(|_| ()), - Err(BindError::Unsupported( - Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(Attachment::Depth) - )), - "{stem}" - ); - } -} - -/// A fetch that writes its color through the interlock and returns its depth -/// (`dsx_fetch_returned_depth`), beside a `Depth32Float` attachment, stores before the tests and -/// has no early-tests variant. At one sample and at four on MoltenVK (M3 Max, M4), RADV and Intel's -/// ANV alike, the compiled pipeline (a draw under `Always`, `FragmentTests::Pass`) records a -/// positive NaN it returns as discarded and kills it once, after the critical section (the lanes: -/// before, the compiled pipeline stored its color), and a draw whose depth test writes is refused -/// `NotImplemented(FramebufferFetch)` at the depth attachment. -#[test] -fn a_fetch_that_returns_its_depth_refuses_a_draw_whose_depth_test_writes() { - use crate::bind::FragmentTests; - let (Some(returned), Some(io)) = (fixture("dsx_fetch_returned_depth"), fixture("stage_io")) - else { - return; - }; - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let device = |stem: &str| { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{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") - }; - let shape = |fragment_tests: FragmentTests| { - BindState { - fragment_tests, - ..Default::default() - } - .shape() - }; - let profiles = ["moltenvk-m3", "amd-780m-radv", "intel-irisxe-rplp-anv"]; - for samples in [1u32, 4] { - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&returned, "fetch_returned_depth")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float)); - d.depth_format = Some(PixelFormat::Depth32Float); - d.raster_sample_count = samples; - for stem in profiles { - let at = format!("{stem} at {samples}x"); - let dev = device(stem); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("the pipeline"); - assert!(base.graphics.writes_depth, "{at}"); - assert!( - kills_after_the_interlock(&base.stages), - "{at}: the compiled pipeline drops a positive NaN after the critical section" - ); - assert!( - base.dependencies.iter().any(|x| x.fact - == RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant: false, - }), - "{at}: stores before the tests, without an early-tests variant" - ); - assert_eq!( - base.plan(&dev, &shape(FragmentTests::Depth { writes: true })) - .map(|_| ()), - Err(BindError::Unsupported( - crate::error::Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(crate::error::Attachment::Depth) - )), - "{at}" - ); - } - } -} - -/// Fetches that write their color through the interlock and return a stencil, a sample mask, or -/// both (`dsx_fetch_returned_stencil`), beside a `Depth32Float_Stencil8` attachment, store before -/// the tests without an early-tests variant. At one sample on RADV, Intel's ANV and NVIDIA (without -/// stencil export, whose compiled pipeline holds a returned stencil in the shader-side stencil's -/// shadow, and refuses a returned sample mask beside it), and at four on RADV, a draw whose stencil -/// test acts or whose depth test writes is refused `NotImplemented(FramebufferFetch)` at the depth -/// attachment. -#[test] -fn a_returned_stencil_or_sample_mask_refuses_a_draw_whose_tests_act() { - use crate::bind::FragmentTests; - let (Some(returned), Some(io)) = (fixture("dsx_fetch_returned_stencil"), fixture("stage_io")) - else { - return; - }; - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let device = |stem: &str| { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{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") - }; - let shape = |fragment_tests: FragmentTests| { - BindState { - fragment_tests, - ..Default::default() - } - .shape() - }; - let shipped = [ - ("amd-780m-radv", 1), - ("intel-irisxe-rplp-anv", 1), - ("nvidia-rtx5080-laptop", 1), - ]; - let functions = [ - "fetch_returned_stencil", - "fetch_returned_mask", - "fetch_returned_stencil_mask", - ]; - let radv = device("amd-780m-radv"); - for name in functions { - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&returned, name)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float)); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - d.raster_sample_count = 4; - let base = radv - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{name} at 4x: {e:?}")); - for tests in [ - FragmentTests::Stencil, - FragmentTests::Depth { writes: true }, - ] { - assert_eq!( - base.plan(&radv, &shape(tests)).map(|_| ()), - Err(BindError::Unsupported( - crate::error::Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(crate::error::Attachment::Depth) - )), - "{name} at 4x under {tests:?}" - ); - } - } - for (stem, samples) in shipped { - let dev = device(stem); - for name in functions { - let at = format!("{name} on {stem} at {samples}x"); - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&returned, name)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Float)); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - d.raster_sample_count = samples; - // Without stencil export the compiled pipeline holds a returned stencil in the - // shader-side stencil's shadow, which refuses a returned sample mask beside it. - let shadow_beside_mask = !dev.profile().fields().fragment.stencil_export - && name == "fetch_returned_stencil_mask"; - let base = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) if shadow_beside_mask => { - assert_eq!(u.feature, Feature::StencilExport, "{at}"); - continue; - } - Ok(_) if shadow_beside_mask => panic!("{at}: not refused"), - compiled => compiled.unwrap_or_else(|e| panic!("{at}: the pipeline: {e:?}")), - }; - assert!( - base.dependencies.iter().any(|x| x.fact - == RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant: false, - }), - "{at}: stores before the tests, without an early-tests variant" - ); - for tests in [ - FragmentTests::Stencil, - FragmentTests::Depth { writes: true }, - ] { - assert_eq!( - base.plan(&dev, &shape(tests)).map(|_| ()), - Err(BindError::Unsupported( - crate::error::Unsupported::not_implemented(Feature::FramebufferFetch) - .at_attachment(crate::error::Attachment::Depth) - )), - "{at} under {tests:?}" - ); - } - } - } -} - -/// Whether the fragment module of `stages` kills (`OpKill` or `OpTerminateInvocation`) exactly -/// once, after its `OpEndInvocationInterlockEXT`: the interlocked entry's kill of a recorded -/// discard. -fn kills_after_the_interlock(stages: &[crate::pipeline::artifact::StageModule]) -> bool { - let Some(m) = stages.iter().find(|m| m.stage == vk::ShaderStage::FRAGMENT) else { - return false; - }; - let (mut end, mut kills) = (None, Vec::new()); - let mut i = 5; - while i < m.spirv.len() { - let op = m.spirv[i] & 0xffff; - if op == crate::spv::Op::EndInvocationInterlockEXT as u32 { - end = Some(i); - } - if op == crate::spv::Op::Kill as u32 || op == crate::spv::Op::TerminateInvocation as u32 { - kills.push(i); - } - i += ((m.spirv[i] >> 16) as usize).max(1); - } - matches!((end, kills.as_slice()), (Some(end), [kill]) if *kill > end) -} - /// `moltenvk-m3` with `features` removed from its description. pub(super) fn moltenvk_without(features: &[VkFeature]) -> DeviceProfile { let path = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -3493,140 +1243,55 @@ fn an_interlocked_discard_kills_only_in_the_entry() { } } -/// A function reads each color it fetches in the storage form once, before its body, and every -/// use takes that texel: the coverage chain's discarding fill (`dsx_coverage_chain`'s -/// `chain_color_discarding`, its coverage fetched, under the lane's attachments) tests the -/// coverage for its discard and multiplies its color by it, two uses in two blocks, and reads -/// the coverage's image once, in the first block of the function that holds the read, on every -/// committed profile that orders fetch through the interlock. Every module passes L3, and on -/// `moltenvk-m3` compiles through SPIRV-Cross to Metal. -#[test] -fn a_fetched_color_is_read_once_before_the_body() { - let Some(chain) = fixture("dsx_coverage_chain") else { - return; - }; - let entry = "chain_color_discarding"; - let colors = [ - PixelFormat::RGBA16Float, - PixelFormat::RG16Float, - PixelFormat::RGBA16Float, - ] - .map(|f| Some(ColorAttachmentDescriptor::new(f))); - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([1], &colors, true, false, 1)); - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !crate::lower::fragment::interlock_orders(&p) { - continue; - } - let what = format!("{entry} on {stem}"); - let a = match compile_with(&chain, entry, &p, &inputs) { - Ok(a) => a, - // A device without the attachments' storage formats refuses the form. - Err(Error::Unsupported(_)) => continue, - Err(e) => panic!("{what}: {e}"), - }; - let (_, m) = - typed_module_with(&chain, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); - // Each image read, with whether it sits in its function's first block. - let reads: Vec = (m.functions().iter()) - .flat_map(|f| { - f.blocks.iter().enumerate().flat_map(|(i, b)| { - (m.blocks()[b.index()].insts.iter()) - .filter(|n| matches!(n.inst, Inst::ImageRead { .. })) - .map(move |_| i == 0) - }) - }) - .collect(); - assert_eq!(reads, [true], "{what}: one read, in a first block"); - let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - if is_moltenvk_capture(&stem) { - match moltenvk_msl_compile(&words) { - Ok(()) => {} - Err(AssembleError::Missing(why)) => eprintln!("SKIPPED MSL: {why}"), - Err(AssembleError::Rejected(why)) => panic!("{what}: MSL: {why}"), - } - } - checked += 1; - } - assert!( - checked > 0, - "no interlock profile compiled the storage form" - ); -} - -/// One function the interlock coherence test compiles: its fixture, its entry, the -/// framebuffer-fetch colors it reads (with their formats), and whether it needs the Vulkan -/// memory model. +/// One function the interlock coherence test compiles: its fixture, its entry, and whether it +/// needs the Vulkan memory model. struct Interlocked<'a> { bc: &'a [u8], entry: &'static str, - fetch: Option<(&'static [u32], &'static [PixelFormat])>, vulkan: bool, } /// Every access of memory another invocation may write inside the interlock is coherent at device -/// scope, on all three kinds of that memory: buffers, device addresses, and storage images (a -/// texture's, a storage-form attachment's, an imageblock's, `engine_fragment_imageblock`). -/// Under `GLSL450` the resources are `Coherent` (`rog_buffer`, `rog_texture`, the storage-form -/// fetch); a coherent access (`rog_texture_coherent`, `fetch_coherent`) or a device address, which -/// no decoration covers (`a3_rog_argument_buffer`, `rog_texture_pointer`), selects the Vulkan +/// scope, on all three kinds of that memory: buffers, device addresses, and a texture's storage +/// images. Under `GLSL450` the resources are `Coherent` (`rog_buffer`, `rog_texture`); a coherent +/// access (`rog_texture_coherent`) or a device address, which no decoration covers +/// (`a3_rog_argument_buffer`, `rog_texture_pointer`), selects the Vulkan /// model, whose accesses carry `MakePointer*`/`MakeTexel*` at `Device` scope, and a volatile /// texture's `VolatileTexel`. A device without that model refuses what needs it, naming the /// feature. Every module passes L3, and on `moltenvk-m3` compiles through SPIRV-Cross to Metal. #[test] fn every_access_inside_the_interlock_is_coherent() { - let (Some(rog), Some(dvp), Some(arg), Some(fetch)) = ( + let (Some(rog), Some(dvp), Some(arg)) = ( fixture("fragment_rog"), fixture("dvp_rog_coherence"), fixture("a3_rog_argument_buffer"), - fixture("fragment_fetch"), ) else { return; }; - const R32: &[PixelFormat] = &[PixelFormat::R32Float]; - const RGBA16: &[PixelFormat] = &[PixelFormat::RGBA16Float]; let cases = [ Interlocked { bc: &rog, entry: "rog_buffer", - fetch: None, vulkan: false, }, Interlocked { bc: &rog, entry: "rog_texture", - fetch: None, - vulkan: false, - }, - Interlocked { - bc: &fetch, - entry: "fetch_scalar", - fetch: Some((&[0], R32)), vulkan: false, }, Interlocked { bc: &arg, entry: "a3_rog_argument_buffer", - fetch: None, vulkan: true, }, Interlocked { bc: &dvp, entry: "rog_texture_coherent", - fetch: None, vulkan: true, }, Interlocked { bc: &dvp, entry: "rog_texture_pointer", - fetch: None, - vulkan: true, - }, - Interlocked { - bc: &dvp, - entry: "fetch_coherent", - fetch: Some((&[0], RGBA16)), vulkan: true, }, ]; @@ -3640,12 +1305,8 @@ fn every_access_inside_the_interlock_is_coherent() { } for c in &cases { let what = format!("{} on {stem}", c.entry); - let inputs = match c.fetch { - Some((read, formats)) => fetch_state(read, formats, false), - None => LoweringInputs::new(), - }; let texture = c.entry.starts_with("rog_texture"); - let a = match compile_with(c.bc, c.entry, &p, &inputs) { + let a = match compile(c.bc, c.entry, &p) { Ok(a) => a, // A read_write texture without format-less storage reads needs its format. Err(Error::NeedsInput(_)) if texture => continue, @@ -3783,8 +1444,9 @@ 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 -/// interlock profile that makes the storage form, whatever the module's math and however it -/// computes the output: the shader blends it by the device's arithmetic, where Metal's compiler +/// 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 @@ -3881,7 +1543,7 @@ fn a_blended_padded_output_records_its_blend_note() { ); inputs.extended_range_colors = crate::pipeline::color_writes::extended_range_colors(colors, Default::default()); - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0u32], colors, true, false, 1)); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0u32], colors)); inputs }; let notes = [ @@ -3891,7 +1553,7 @@ fn a_blended_padded_output_records_its_blend_note() { 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::interlock_orders(&p) { + if !crate::lower::fragment::inputs_order(&p) { continue; } let blended = state(&colors(true), &p); @@ -3911,7 +1573,8 @@ fn a_blended_padded_output_records_its_blend_note() { }; let float_fill = match compile_with(&fills, "rt6_fill_rgba32float", &p, &blended) { Ok(a) => recorded(&a), - // A device without the raw formats' storage refuses the form whatever the source. + // 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}"), }; @@ -3993,7 +1656,7 @@ fn a_blended_padded_output_records_its_blend_note() { "{stem}: a computed half4 without fast math" ); } - assert!(checked > 0, "no interlock profile made the storage form"); + assert!(checked > 0, "no profile blended over the input attachment"); } /// The opcodes of every instruction in `words`, and the capabilities it declares. @@ -4048,256 +1711,3 @@ fn a_fragment_functions_derivatives_are_fine() { } assert!(compiled >= 10, "{compiled} profiles compiled it"); } - -/// A draw that reads a texture its subpass renders through a snapshot (`BindState:: -/// snapshot_textures`): owned fixture `tob_renders`'s `tob_rect` and `tob_read` -/// (`t.read(uint2(in.position.xy))`, whose texel reaches only its output), planned with slots 0 -/// and 3 asking for snapshots, keeps slot 0 alone (the function has no slot 3) on every profile -/// with the pixel interlock, fragment stores, the feedback loop layout and dynamic color write -/// masks. Its variant binds slot 0's snapshot as a storage image, states `snapshot_reads`, makes -/// the write masks dynamic, requires the feedback loop layout, writes no memory of the -/// function's, passes L3, and plans the same variant -/// against itself, writing `WriteSource::SnapshotTexels` and leaving the phase to the consumer as a -/// fragment hole, zero in the plan's bytes. A pipeline with a depth attachment, a multisampled -/// one, a profile without one of those features, and a draw that asks for no snapshot keep the -/// plain pipeline. -#[test] -fn a_snapshot_read_plans_its_variant_where_the_pipeline_can() { - use crate::bind::{DrawCall, PushHole}; - use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SnapshotForm, Stage}; - let Some(bc) = fixture("tob_renders") else { - return; - }; - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(&bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let descriptor = |depth: bool, samples: u32| { - let mut d = RenderPipelineDescriptor::new(function("tob_rect")); - d.fragment = Some(function("tob_read")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - if depth { - d.depth_format = Some(PixelFormat::Depth32Float); - } - d.raster_sample_count = samples; - d - }; - let snapshots = |p: &crate::pipeline::RenderPipeline| -> Vec<(u32, vk::DescriptorType)> { - p.layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .filter_map(|b| match b.source { - BindingSource::SnapshotTexels(slot) => Some((slot, b.ty)), - _ => None, - }) - .collect() - }; - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 0, - }; - let state = BindState { - snapshot_textures: [0, 3].into(), - ..Default::default() - }; - let draw = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 4, - instance_count: 1, - base_instance: 0, - }; - let mut planned = 0; - for stem in [ - "intel-irisxe-anv", - "amd-780m-radv", - "nvidia-rtx5080-laptop", - "lavapipe", - "runtime-floor", - ] { - let desc = crate::pipeline::testing::description(stem).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let base = dev - .compile_render_pipeline(&descriptor(false, 1), &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!(snapshots(&base).is_empty(), "{stem}"); - assert!(!base.graphics.snapshot_reads, "{stem}"); - let plain = base - .plan(&dev, &BindState::default().shape()) - .expect("plain plan"); - assert!(plain.variant.snapshot_textures.is_empty(), "{stem}"); - let plan = base.plan(&dev, &state.shape()).expect("plan"); - // The binder plans the variant where the device enabled what its draws take: the pixel - // interlock, fragment stores, the feedback loop layout and dynamic write masks. - let enabled = &dev.profile().fields().enabled.features; - let takes = dev.profile().fields().fragment.pixel_interlock - && [ - VkFeature::FragmentStoresAndAtomics, - VkFeature::AttachmentFeedbackLoopLayout, - VkFeature::ExtendedDynamicState3ColorWriteMask, - ] - .iter() - .all(|feature| enabled.contains(feature)); - if !takes { - assert!(plan.variant.snapshot_textures.is_empty(), "{stem}"); - continue; - } - planned += 1; - // No texture bound: the fetched lanes' bits. - assert_eq!( - plan.variant.snapshot_textures, - [(slot, SnapshotForm::Bits)].into(), - "{stem}" - ); - assert!( - matches!( - plan.instantiate_draw(&state, &draw), - Err(BindError::NeedsVariant { .. }) - ), - "{stem}: the base pipeline is the other variant" - ); - let variant = dev - .compile_render_variant(&descriptor(false, 1), &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: variant: {e}")); - assert_eq!( - snapshots(&variant), - [(0, vk::DescriptorType::STORAGE_IMAGE)], - "{stem}" - ); - assert!(variant.graphics.snapshot_reads, "{stem}"); - assert!( - variant - .graphics - .dynamic_states - .contains(&vk::DynamicState::COLOR_WRITE_MASK_EXT), - "{stem}: dynamic write masks" - ); - assert!( - variant - .requirements - .features - .contains(&VkFeature::AttachmentFeedbackLoopLayout) - && variant - .requirements - .features - .contains(&VkFeature::ExtendedDynamicState3ColorWriteMask), - "{stem}: {:?}", - variant.requirements.features - ); - assert!(!variant.graphics.fragment_writes_memory, "{stem}"); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - } - let again = variant.plan(&dev, &state.shape()).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{stem}: a fixed point"); - assert!( - again - .descriptors - .iter() - .any(|w| w.source == WriteSource::SnapshotTexels { slot: 0 }), - "{stem}: {:?}", - again.descriptors - ); - let cmds = again - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{stem}: draw: {e:?}")); - let holes: Vec<(vk::ShaderStageFlags, u32)> = cmds - .push_holes - .iter() - .filter_map(|h| match *h { - PushHole::SnapshotPhase { stages, offset } => Some((stages, offset)), - _ => None, - }) - .collect(); - assert_eq!(holes.len(), 1, "{stem}: {:?}", cmds.push_holes); - let (stages, offset) = holes[0]; - assert_eq!(stages, vk::ShaderStageFlags::FRAGMENT, "{stem}"); - let at = offset as usize; - let bytes = cmds - .push_constants - .iter() - .find(|w| w.stages == stages) - .map(|w| (w.offset as usize, &w.bytes)) - .expect("the fragment's push bytes"); - assert_eq!( - bytes.1.get(at - bytes.0..at - bytes.0 + 4), - Some(&[0u8; 4][..]), - "{stem}: phase 0 in the plan's bytes" - ); - assert!( - again - .push - .fields - .iter() - .any(|f| f.field == PushField::SnapshotPhase), - "{stem}" - ); - // A bound texture's form: the codes of a normalized or half-float format, the bits of a - // 32-bit float format's lanes and of an sRGB format's decoded ones; each variant passes L3 - // and binds its snapshot. - for (format, form) in [ - (PixelFormat::RGBA8Unorm, SnapshotForm::Unorm8), - (PixelFormat::BGRA8Unorm, SnapshotForm::Unorm8), - (PixelFormat::R8Unorm, SnapshotForm::Unorm8), - (PixelFormat::RGBA8Snorm, SnapshotForm::Snorm8), - (PixelFormat::RG16Unorm, SnapshotForm::Unorm16), - (PixelFormat::RGBA16Float, SnapshotForm::Half), - (PixelFormat::RGBA32Float, SnapshotForm::Bits), - (PixelFormat::RGB10A2Unorm, SnapshotForm::Bits), - ] { - let mut bound = state.clone(); - let mut table = crate::bind::state::StageTable::default(); - let facts = - crate::bind::state::TextureFacts::new(crate::metal::TextureType::Type2D, format); - table.textures.insert( - 0, - crate::bind::state::BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - bound.stages.insert(Stage::Fragment, table); - let plan = base.plan(&dev, &bound.shape()).expect("bound plan"); - assert_eq!( - plan.variant.snapshot_textures, - [(slot, form)].into(), - "{stem}: {format:?}" - ); - let variant = dev - .compile_render_variant(&descriptor(false, 1), &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {format:?}: {e}")); - assert_eq!( - snapshots(&variant), - [(0, vk::DescriptorType::STORAGE_IMAGE)], - "{stem}: {format:?}" - ); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem}: {format:?}: L3: {e}")); - } - } - // No snapshot again: the plain pipeline. - let unread = variant - .plan(&dev, &BindState::default().shape()) - .expect("plain plan of the variant"); - assert!(unread.variant.snapshot_textures.is_empty(), "{stem}"); - // A depth attachment, or more than one sample, keeps the plain pipeline. - for (depth, samples) in [(true, 1), (false, 4)] { - let other = dev - .compile_render_pipeline(&descriptor(depth, samples), &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {depth} {samples}: {e}")); - let plan = other.plan(&dev, &state.shape()).expect("plan"); - assert!( - plan.variant.snapshot_textures.is_empty(), - "{stem}: {depth} {samples}" - ); - } - } - assert!(planned >= 4, "the interlocked profiles"); -} diff --git a/crates/metal2vulkan/src/tests/engine_fragment_imageblock.rs b/crates/metal2vulkan/src/tests/engine_fragment_imageblock.rs deleted file mode 100644 index d99bcccfa..000000000 --- a/crates/metal2vulkan/src/tests/engine_fragment_imageblock.rs +++ /dev/null @@ -1,886 +0,0 @@ -//! Fragment imageblocks through a coherent storage image and the ordered pixel interlock, over the -//! owned fixture `engine/fragment_imageblock_views` and the public -//! `fragment_custom_imageblock`: -//! -//! - Where the device has `fragmentShaderPixelInterlock` (and `fragmentStoresAndAtomics` for a -//! function that writes its imageblock), each function runs its body inside -//! `PixelInterlockOrderedEXT`, reaches the imageblock through one `Coherent` `R32ui` 2D-array -//! storage image whose layer `w` is word `w` of the pixel's cell, reads its input view and writes -//! its output view at the master layout's offsets, notes `RuntimeFact::FragmentImageblock`, and -//! passes L3. Elsewhere it is refused, naming every capability it lacks. -//! - A function that writes its imageblock and returns a sample mask writes only where the mask -//! covers the pixel's sample (bit 0), and views of two structurally different masters each reach -//! their own master's bytes of a cell as large as the larger master. -//! - Not implemented: an imageblock aliasing the implicit one (an aliased input is refused as tile -//! shading), a member that is an array or a struct or names a color attachment, a view without -//! a data size, and a function under the Vulkan memory model. -//! - A function that reaches no raster order group runs outside the interlock, whatever other -//! layouts of its module name. -//! - A discarded fragment writes nothing: a demoted one is a helper, whose stores have no effect, -//! and a predicated one skips the stores. -//! - A function whose only effects are its outputs and its imageblock write declares early tests -//! (a fragment its tests fail drops its write, Metal's answer); one that discards states -//! `RuntimeFact::TestedStorageWrites`, whose draws' plans choose its variant. -//! - Compiled for a multisampled pipeline, a function runs once per sample (`SampleId`) and reaches -//! its sample's cell at layers `sample * words` on; on a driver that drops an early-tests -//! shader's image writes at more than one sample, none declares early tests, and one whose Metal -//! function does is refused as that defect. -//! - A render pipeline's `GraphicsState::fragment_imageblock` records the storage and its master's -//! fingerprint (equal for views of one master, different for another); link refuses a write -//! alpha to coverage can drop after the function made it, and links beside a depth or stencil -//! attachment and at four samples. -//! - The binder writes the storage to the fragment's synthetic binding and refuses a layered or -//! amplified pass. -//! -//! `llvm-as` assembles the fixtures and `spirv-dis` disassembles the modules; a missing tool skips -//! visibly. No GPU is used. - -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - -use crate::bind::{BindState, VertexAmplification, ViewMapping, WriteSource}; -use crate::budget::Budget; -use crate::device::requirements::VkFeature; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{BindError, Capability, Error, Feature, Needs}; -use crate::library::Library; -use crate::lower::fragment::DiscardForm; -use crate::metal::PixelFormat; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{Stage, SyntheticBinding}; -use crate::pipeline::testing::{ - compile, engine_dir, fixtures_dir, interlocked_coherence, link_and_validate, llvm_assemble, - typed_module, AssembleError, Scratch, -}; -use crate::pipeline::{ImageblockMechanism, RenderPipeline}; -use crate::spirv::ir::{ExecMode, Inst, Terminator, TypedModule}; -use crate::spirv::testing::{committed_profiles, spirv_dis}; -use crate::vk; - -fn assemble(path: &Path) -> Option> { - match llvm_assemble(path) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {}: {why}", path.display()), - } -} - -fn views() -> Option> { - assemble(&engine_dir().join("fragment_imageblock_views.ll")) -} - -/// How the depth and stencil tests bear on a function's imageblock write. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Tests { - /// It writes none. - None, - /// The module declares early fragment tests. - Early, - /// It writes before Vulkan's tests and states `RuntimeFact::TestedStorageWrites`. - Tested { early_variant: bool }, -} - -/// The tests of compiled function `a` whose typed module is `m`. -fn tests(a: &crate::library::FunctionArtifact, m: &TypedModule) -> Tests { - let tested = a.facts.iter().find_map(|f| match *f { - RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant, - } => Some(early_variant), - _ => None, - }); - match ( - m.entry().modes.contains(&ExecMode::EarlyFragmentTests), - tested, - ) { - (true, None) => Tests::Early, - (false, Some(early_variant)) => Tests::Tested { early_variant }, - (false, None) => Tests::None, - (true, Some(_)) => panic!("early tests beside a tested write"), - } -} - -/// One fragment function's imageblock: whether it writes it, how the tests bear on the write at -/// one sample, its cell's words and bytes, its views' alignment, and the cell words it reads and -/// writes (the layers of its image reads and writes; a write of part of a word reads that word -/// first). -struct Expect { - entry: &'static str, - writes: bool, - tests: Tests, - words: u32, - data_size: u32, - alignment: u32, - read_layers: &'static [u32], - written_layers: &'static [u32], -} - -/// The views fixture's fragment functions. `imageblock_transition` reads `b` (the high half of -/// word 0) and `sum` (word 2) and writes `a` (the low half of word 0), `tag` (word 1), and `n` -/// (the low half of word 3), each at its master offset, through views aligned to 4 bytes; the -/// `Cell` functions, whose layout is aligned to 8, hold `color` in words 0 and 1 and `depth` in -/// the low half of word 2. Each cell is 16 bytes. -const VIEWS: [Expect; 4] = [ - Expect { - entry: "imageblock_transition", - writes: true, - tests: Tests::Early, - words: 4, - data_size: 16, - alignment: 4, - read_layers: &[0, 2, 3], - written_layers: &[0, 1, 3], - }, - Expect { - entry: "imageblock_accumulate", - writes: true, - tests: Tests::Early, - words: 4, - data_size: 16, - alignment: 8, - read_layers: &[0, 1, 2], - written_layers: &[0, 1, 2], - }, - Expect { - entry: "imageblock_clear_odd", - writes: true, - tests: Tests::Tested { - early_variant: true, - }, - words: 4, - data_size: 16, - alignment: 8, - read_layers: &[2], - written_layers: &[0, 1, 2], - }, - Expect { - entry: "imageblock_resolve", - writes: false, - tests: Tests::None, - words: 4, - data_size: 16, - alignment: 8, - read_layers: &[0, 1, 2], - written_layers: &[], - }, -]; - -fn description(stem: &str) -> DeviceDescription { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles") - .join(format!("{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - DeviceDescription::from_khronos_json(&text, None).expect("description") -} - -fn device(stem: &str) -> Device { - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// `moltenvk-m3` without `features`. -fn moltenvk_without(features: &[VkFeature]) -> DeviceProfile { - let mut desc = description("moltenvk-m3"); - for f in features { - assert!(desc.features.remove(f), "moltenvk-m3 has {f:?}"); - } - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) - .expect("device") - .profile() - .clone() -} - -/// The `FragmentImageblock` fact of an artifact's facts: its words, whether the function writes -/// the imageblock, its cell's bytes, and its views' alignment. -fn fact(facts: &[RuntimeFact]) -> Option<(u32, bool, u32, u32)> { - facts.iter().find_map(|f| match *f { - RuntimeFact::FragmentImageblock { - words, - writes, - data_size, - alignment, - .. - } => Some((words, writes, data_size, alignment)), - _ => None, - }) -} - -/// Whether compiling `entry` of `bc` on `p` is refused `Unsupported{Imageblocks, NotImplemented}`. -fn not_implemented(bc: &[u8], entry: &str, p: &DeviceProfile) { - match compile(bc, entry, p) { - Err(Error::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::Imageblocks, Needs::NotImplemented), - "{entry}" - ), - other => panic!("{entry}: {:?}", other.map(|_| ())), - } -} - -/// The layers of the image reads and writes of disassembled module `dis`, and whether it -/// declares exactly one image, a `Coherent` `R32ui` 2D-array storage image. -fn cell_words(dis: &str) -> (BTreeSet, BTreeSet) { - let images: Vec<&str> = dis.lines().filter(|l| l.contains("OpTypeImage")).collect(); - assert_eq!(images.len(), 1, "one image type: {images:?}"); - assert!( - images[0].ends_with("OpTypeImage %uint 2D 0 1 0 2 R32ui"), - "{}", - images[0] - ); - assert_eq!( - dis.lines().filter(|l| l.ends_with(" Coherent")).count(), - 1, - "one coherent variable" - ); - // `%c = OpCompositeConstruct %v3uint %x %y %uint_` - let mut layer = BTreeMap::new(); - for l in dis.lines() { - let t: Vec<&str> = l.split_whitespace().collect(); - if let [id, "=", "OpCompositeConstruct", "%v3uint", _, _, w] = t[..] { - if let Some(n) = w.strip_prefix("%uint_") { - layer.insert(id.to_owned(), n.parse::().expect("layer")); - } - } - } - let at = |coord: &str| { - *layer - .get(coord) - .unwrap_or_else(|| panic!("layer of {coord}")) - }; - let (mut reads, mut writes) = (BTreeSet::new(), BTreeSet::new()); - for l in dis.lines() { - let t: Vec<&str> = l.split_whitespace().collect(); - match t[..] { - [_, "=", "OpImageRead", _, _, coord, ..] => { - reads.insert(at(coord)); - } - ["OpImageWrite", _, coord, ..] => { - writes.insert(at(coord)); - } - _ => {} - } - } - (reads, writes) -} - -/// The refusal of an imageblock function on a device that lacks `missing`. -fn lacks(missing: &[VkFeature]) -> Needs { - Needs::AnyOf(vec![missing - .iter() - .map(|f| Capability::Feature(*f)) - .collect()]) -} - -/// On every committed profile with pixel interlock (and fragment stores for a writer) each function -/// compiles inside the ordered interlock, notes its imageblock, and passes L3; on `moltenvk-m3` its -/// image reads and writes reach exactly the words of its views at their master offsets through one -/// coherent word-plane image. Every other profile refuses it, naming each capability it lacks. -#[test] -fn each_view_reaches_its_master_words_inside_the_interlock() { - let Some(bc) = views() else { - return; - }; - let (mut compiled, mut refused) = (0, 0); - for (stem, p) in committed_profiles().expect("profiles") { - let f = p.fields(); - for e in &VIEWS { - let what = format!("{} on {stem}", e.entry); - let mut missing = Vec::new(); - if !f.fragment.pixel_interlock { - missing.push(VkFeature::FragmentShaderPixelInterlock); - } - if e.writes && !f.leaf.fragment_stores_and_atomics { - missing.push(VkFeature::FragmentStoresAndAtomics); - } - if !missing.is_empty() { - match compile(&bc, e.entry, &p) { - Err(Error::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::Imageblocks, lacks(&missing)), - "{what}" - ); - } - other => panic!("{what}: {:?}", other.map(|_| ())), - } - refused += 1; - continue; - } - let (_, m) = typed_module(&bc, e.entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - m.entry().modes.contains(&ExecMode::PixelInterlockOrdered), - "{what}" - ); - let a = compile(&bc, e.entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - fact(&a.facts), - Some((e.words, e.writes, e.data_size, e.alignment)), - "{what}" - ); - assert_eq!(tests(&a, &m), e.tests, "{what}"); - let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - if stem == "moltenvk-m3" { - let (reads, writes) = cell_words(&spirv_dis(&words)); - assert_eq!( - reads, - e.read_layers.iter().copied().collect(), - "{what}: reads" - ); - assert_eq!( - writes, - e.written_layers.iter().copied().collect(), - "{what}: writes" - ); - } - compiled += 1; - } - } - assert!( - compiled > 0 && refused > 0, - "compiled {compiled}, refused {refused}" - ); - // A device that lacks both names both in one alternative; a reader needs only the interlock. - let p = moltenvk_without(&[ - VkFeature::FragmentShaderPixelInterlock, - VkFeature::FragmentStoresAndAtomics, - ]); - for e in &VIEWS { - let missing: &[VkFeature] = if e.writes { - &[ - VkFeature::FragmentShaderPixelInterlock, - VkFeature::FragmentStoresAndAtomics, - ] - } else { - &[VkFeature::FragmentShaderPixelInterlock] - }; - match compile(&bc, e.entry, &p) { - Err(Error::Unsupported(u)) => { - assert_eq!((u.feature, u.needs), (Feature::Imageblocks, lacks(missing))) - } - other => panic!("{}: {:?}", e.entry, other.map(|_| ())), - } - } -} - -/// A function that writes its imageblock and returns a sample mask keeps its write only where the -/// mask covers the pixel's one sample: Metal drops the fragment, and its write, where bit 0 is -/// clear (measured on the M3 Max and an M4, whatever the other bits). The plan names the mask's -/// field, every image write runs on the branch the bit leaves, and the pipeline links -/// single-sampled (link refuses a multisampled one). -#[test] -fn a_write_beside_a_sample_mask_is_kept_where_the_mask_covers_the_sample() { - let Some(bc) = views() else { - return; - }; - let p = moltenvk_without(&[]); - let entry = "imageblock_masked"; - let (plan, m) = typed_module(&bc, entry, &p).expect("typed module"); - let ib = plan.families.fragment.imageblock.as_ref().expect("plan"); - assert_eq!(ib.mask, Some(1)); - let writing = writing_blocks(&m); - assert!(!writing.is_empty()); - let guarded = |b: &usize| { - m.blocks().iter().any(|h| { - matches!(h.term, Terminator::CondBranch { t, f, .. } - if t.index() == *b || f.index() == *b) - }) - }; - assert!(writing.iter().all(guarded), "{writing:?}"); - let a = compile(&bc, entry, &p).expect("compile"); - assert_eq!(fact(&a.facts), Some((4, true, 16, 8))); - // A returned mask keeps the write from early tests. - assert_eq!( - tests(&a, &m), - Tests::Tested { - early_variant: false - } - ); - link_and_validate(&a, &p).expect("L3"); - let dev = device("moltenvk-m3"); - dev.compile_render_pipeline(&render(&bc, entry), &Budget::standard()) - .expect("pipeline"); - // A function that only reads its imageblock and returns a mask plans no guard. - let (plan, _) = typed_module(&bc, "imageblock_transition", &p).expect("typed module"); - assert_eq!(plan.families.fragment.imageblock.expect("plan").mask, None); -} - -/// An imageblock aliasing the implicit one is the color attachments' own storage, which the side -/// image is not: a function that only writes it is not implemented (`Imageblocks`), and one that -/// reads it is refused as tile shading with every other aliased imageblock parameter -/// (`select::param_family`). -#[test] -fn an_imageblock_aliasing_the_implicit_one_is_not_implemented() { - let Some(bc) = views() else { - return; - }; - let p = moltenvk_without(&[]); - not_implemented(&bc, "imageblock_aliased", &p); - match compile(&bc, "imageblock_aliased_in", &p) { - Err(Error::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::TileShading, Needs::NotImplemented) - ), - other => panic!("{:?}", other.map(|_| ())), - } -} - -/// `imageblock_two_masters` reads `a` through `Master` (byte 0) and writes it through `Swapped` -/// (byte 2). Each view reaches its own master's bytes of the one cell, as Metal's do (measured on -/// the M3 Max and an M4): the input reads word 0's low half and the output replaces its high half. -/// The cell spans the larger master, `Master`'s 16 bytes at its alignment, and the fact names -/// `Master`, which `imageblock_transition` views too. -#[test] -fn views_of_two_masters_reach_each_masters_bytes() { - let Some(bc) = views() else { - return; - }; - let p = moltenvk_without(&[]); - let entry = "imageblock_two_masters"; - let (plan, _) = typed_module(&bc, entry, &p).expect("typed module"); - let ib = plan.families.fragment.imageblock.expect("plan"); - let (input, output) = (ib.input.expect("input").1, ib.output.expect("output").1); - let input: Vec = input.members.iter().map(|m| m.offset).collect(); - let output: Vec = output.members.iter().map(|m| m.offset).collect(); - assert_eq!((input, output), (vec![0], vec![2])); - let a = compile(&bc, entry, &p).expect("compile"); - assert_eq!(fact(&a.facts), Some((4, true, 16, 4))); - let (_, words) = link_and_validate(&a, &p).expect("L3"); - let (reads, writes) = cell_words(&spirv_dis(&words)); - assert_eq!((reads, writes), ([0].into(), [0].into())); - let dev = device("moltenvk-m3"); - let master = |entry: &str| { - dev.compile_render_pipeline(&render(&bc, entry), &Budget::standard()) - .unwrap_or_else(|e| panic!("{entry}: {e}")) - .graphics - .fragment_imageblock - .expect("imageblock") - .master - }; - assert_eq!(master(entry), master("imageblock_transition")); -} - -/// A function that reaches no raster order group runs outside the interlock, and so compiles on -/// every committed profile, pixel interlock or not, although other layouts of its module (the -/// imageblock masters) name groups. -#[test] -fn a_function_without_a_group_runs_outside_the_interlock() { - let Some(bc) = views() else { - return; - }; - for (stem, p) in committed_profiles().expect("profiles") { - let (_, m) = typed_module(&bc, "plain_color", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - !m.entry().modes.contains(&ExecMode::PixelInterlockOrdered), - "{stem}" - ); - let a = compile(&bc, "plain_color", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - } -} - -/// A fragment function `probe` whose imageblock input is struct `Cell = { fields }` of layout -/// `members`, with `size` the `air.imageblock_data_size` operands (or none), a device buffer at -/// index 0, and `body` computing its `<4 x half>` result `%r`. -fn probe(fields: &str, members: &str, size: &str, body: &str, decls: &str) -> String { - format!( - r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" -target triple = "air64_v28-apple-macosx26.0.0" - -%struct.Inner = type {{ half, half }} -%struct.Cell = type {{ {fields} }} - -define <4 x half> @probe(%struct.Cell %0, ptr addrspace(1) %1) {{ -{body} - ret <4 x half> %r -}} -{decls} -!air.fragment = !{{!0}} -!air.version = !{{!10}} -!air.language_version = !{{!11}} -!0 = !{{ptr @probe, !1, !2}} -!1 = !{{!3}} -!3 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}} -!2 = !{{!4, !5}} -!4 = !{{i32 0, !"air.imageblock_data", {size}!"air.struct_type_info", !6, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Cell", !"air.arg_name", !"in"}} -!5 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"buf"}} -!6 = !{{{members}}} -!7 = !{{i32 0, i32 2, i32 0, !"half", !"x", i32 2, i32 2, i32 0, !"half", !"y"}} -!10 = !{{i32 2, i32 8, i32 0}} -!11 = !{{!"Metal", i32 4, i32 0, i32 0}} -"# - ) -} - -/// Assemble `text` through a scratch file named after `name`, removed after. -fn assemble_text(name: &str, text: &str) -> Option> { - let scratch = Scratch::new(&format!("m2v-fragment-imageblock-{name}")); - let dir = scratch.path(); - let path = dir.join(format!("{name}.ll")); - std::fs::write(&path, text).expect("write scratch .ll"); - assemble(&path) -} - -const CELL: &str = "<4 x half>, half"; -const CELL_MEMBERS: &str = r#"i32 0, i32 8, i32 0, !"half4", !"color", !"air.raster_order_group", i32 0, i32 8, i32 2, i32 0, !"half", !"depth", !"air.raster_order_group", i32 0"#; -const SIZE: &str = "!\"air.imageblock_data_size\", i32 16, "; -const READ_COLOR: &str = " %r = extractvalue %struct.Cell %0, 0"; - -/// What a view's structure puts out of reach is not implemented: a member that is an array or a -/// struct, a member naming a color attachment (crafted: an explicit layout cannot hold one, so it -/// is the implicit imageblock's), and a view without a data size. The control, the same function -/// without any of them, compiles, and so does one under the Vulkan memory model (a coherent buffer -/// load selects it), whose imageblock accesses then carry `MakeTexel*` at device scope where the -/// control's image is `Coherent`. -#[test] -fn unmodelled_views_are_not_implemented() { - let coherent = format!( - "{READ_COLOR}\n %v = call i32 @air.load.system_coherent.volatile.i32.p1i32(ptr addrspace(1) %1)\n %h = trunc i32 %v to i16\n %f = bitcast i16 %h to half\n %r = insertelement <4 x half> %c, half %f, i32 3" - ) - .replace("%r = extractvalue", "%c = extractvalue"); - let cases = [ - ("control", CELL, CELL_MEMBERS, SIZE, READ_COLOR.to_owned(), "", true), - ( - "coherent", - CELL, - CELL_MEMBERS, - SIZE, - coherent, - "declare i32 @air.load.system_coherent.volatile.i32.p1i32(ptr addrspace(1))", - true, - ), - ("unsized", CELL, CELL_MEMBERS, "", READ_COLOR.to_owned(), "", false), - ( - "color", - CELL, - r#"i32 0, i32 8, i32 0, !"half4", !"color", !"air.render_target", i32 0, i32 8, i32 2, i32 0, !"half", !"depth", !"air.raster_order_group", i32 0"#, - SIZE, - READ_COLOR.to_owned(), - "", - false, - ), - ( - "array", - "[2 x half]", - r#"i32 0, i32 2, i32 2, !"half", !"pair", !"air.raster_order_group", i32 0"#, - "!\"air.imageblock_data_size\", i32 4, ", - " %e = extractvalue %struct.Cell %0, 0, 1\n %r = insertelement <4 x half> zeroinitializer, half %e, i32 0".to_owned(), - "", - false, - ), - ( - "struct", - "%struct.Inner", - r#"!"air.struct_type_info", !7, i32 0, i32 4, i32 0, !"Inner", !"inner", !"air.raster_order_group", i32 0"#, - "!\"air.imageblock_data_size\", i32 4, ", - " %e = extractvalue %struct.Cell %0, 0, 1\n %r = insertelement <4 x half> zeroinitializer, half %e, i32 0".to_owned(), - "", - false, - ), - ]; - let mut profiles = committed_profiles().expect("profiles"); - profiles.retain(|(_, p)| p.fields().fragment.pixel_interlock && p.fields().vulkan_memory_model); - assert!(!profiles.is_empty()); - for (name, fields, members, size, body, decls, ok) in cases { - let Some(bc) = assemble_text(name, &probe(fields, members, size, &body, decls)) else { - return; - }; - for (stem, p) in &profiles { - if ok { - let a = compile(&bc, "probe", p).unwrap_or_else(|e| panic!("{name} {stem}: {e}")); - let (_, words) = - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{name} {stem}: L3: {e}")); - let n = - interlocked_coherence(&words).unwrap_or_else(|e| panic!("{name} {stem}: {e}")); - assert_eq!(n.vulkan, name == "coherent", "{name} {stem}"); - assert!(n.storage_image > 0, "{name} {stem}: {n:?}"); - } else { - not_implemented(&bc, "probe", p); - } - } - } -} - -/// The public fixture's imageblock (read and written, no master) compiles the same way. -#[test] -fn the_public_imageblock_fixture_compiles_inside_the_interlock() { - let Some(bc) = assemble(&fixtures_dir().join("fragment_custom_imageblock.ll")) else { - return; - }; - let p = moltenvk_without(&[]); - let a = compile(&bc, "fragment_custom_imageblock", &p).expect("compile"); - assert!( - matches!(fact(&a.facts), Some((_, true, ..))), - "{:?}", - a.facts - ); - let (_, words) = link_and_validate(&a, &p).expect("L3"); - let (reads, writes) = cell_words(&spirv_dis(&words)); - assert!(!reads.is_empty() && !writes.is_empty()); -} - -/// The blocks of `m`'s functions that write an image. -fn writing_blocks(m: &TypedModule) -> Vec { - m.blocks() - .iter() - .enumerate() - .filter(|(_, b)| { - b.insts - .iter() - .any(|n| matches!(n.inst, Inst::ImageWrite { .. })) - }) - .map(|(i, _)| i) - .collect() -} - -/// A discarded fragment writes nothing to its imageblock. Where the device demotes, the discarded -/// fragment is a helper, whose stores have no effect, so the writes stand unguarded; where it -/// predicates, the writes run only on the branch the predicate leaves. -#[test] -fn a_discarded_fragment_writes_nothing() { - let Some(bc) = views() else { - return; - }; - let entry = "imageblock_clear_odd"; - for (p, form) in [ - (moltenvk_without(&[]), DiscardForm::Demote), - ( - moltenvk_without(&[VkFeature::ShaderDemoteToHelperInvocation]), - DiscardForm::Predicate, - ), - ] { - let (plan, m) = typed_module(&bc, entry, &p).unwrap_or_else(|e| panic!("{form:?}: {e}")); - let forms: Vec = plan.families.fragment.discards.values().copied().collect(); - assert_eq!(forms, [form]); - let writing = writing_blocks(&m); - assert!(!writing.is_empty(), "{form:?}"); - let guarded = |b: &usize| { - m.blocks().iter().any(|h| { - matches!(h.term, Terminator::CondBranch { t, f, .. } - if t.index() == *b || f.index() == *b) - }) - }; - match form { - DiscardForm::Demote => assert!(!writing.iter().any(guarded), "{form:?}"), - _ => assert!(writing.iter().all(guarded), "{form:?}"), - } - let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{form:?}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{form:?}: L3: {e}")); - } -} - -/// A render pipeline of `imageblock_vertex` and `fragment` with one `RGBA16Float` color -/// attachment. -fn render(bc: &[u8], fragment: &str) -> RenderPipelineDescriptor { - let lib = Library::from_air(bc).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(stage("imageblock_vertex")); - d.fragment = Some(stage(fragment)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float)); - d -} - -fn refused_not_implemented(r: Result, what: &str) { - match r { - Err(Error::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::Imageblocks, Needs::NotImplemented), - "{what}" - ), - other => panic!("{what}: {:?}", other.map(|_| ())), - } -} - -/// Link records the pass's imageblock storage in the graphics state, links beside a depth or -/// stencil attachment (the tests run before each write: early, or as each draw's plan chooses), -/// and refuses a write alpha to coverage can drop after the function made it. -#[test] -fn link_records_the_imageblock_and_refuses_what_it_does_not_model() { - let Some(bc) = views() else { - return; - }; - let dev = device("moltenvk-m3"); - let budget = Budget::standard(); - let mut masters = BTreeMap::new(); - for e in &VIEWS { - let p = dev - .compile_render_pipeline(&render(&bc, e.entry), &budget) - .unwrap_or_else(|err| panic!("{}: {err}", e.entry)); - let fi = p.graphics.fragment_imageblock.expect("imageblock"); - assert_eq!( - (fi.mechanism, fi.words), - (ImageblockMechanism::StorageImageInterlock, e.words), - "{}", - e.entry - ); - masters.insert(e.entry, fi.master); - for depth in [ - (Some(PixelFormat::Depth32Float), None), - (None, Some(PixelFormat::Stencil8)), - ] { - let mut d = render(&bc, e.entry); - (d.depth_format, d.stencil_format) = depth; - dev.compile_render_pipeline(&d, &budget) - .unwrap_or_else(|err| panic!("{} with {depth:?}: {err}", e.entry)); - } - let mut d = render(&bc, e.entry); - d.alpha_to_coverage = true; - let r = dev.compile_render_pipeline(&d, &budget); - if e.writes { - refused_not_implemented(r, &format!("{} alpha to coverage", e.entry)); - } else { - r.unwrap_or_else(|err| panic!("{} alpha to coverage: {err}", e.entry)); - } - } - // The `Cell` functions view one layout (no master); `imageblock_transition` views `Master`. - let cell = masters["imageblock_accumulate"]; - for entry in ["imageblock_clear_odd", "imageblock_resolve"] { - assert_eq!(masters[entry], cell, "{entry}"); - } - assert_ne!(masters["imageblock_transition"], cell); -} - -/// The binder writes the pass's imageblock storage to the fragment's storage-image binding and -/// refuses a pass of more than one layer and an amplified draw. -#[test] -fn the_binder_writes_the_storage_and_refuses_layered_passes() { - let Some(bc) = views() else { - return; - }; - let dev = device("moltenvk-m3"); - let mut d = render(&bc, "imageblock_transition"); - d.max_vertex_amplification_count = 2; - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - let imageblock: Vec<_> = plan - .descriptors - .iter() - .filter(|w| w.source == WriteSource::Imageblock) - .collect(); - assert_eq!(imageblock.len(), 1, "{:?}", plan.descriptors); - let b = p - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .find(|b| b.binding == imageblock[0].binding) - .expect("binding"); - assert_eq!(b.ty, vk::DescriptorType::STORAGE_IMAGE); - assert_eq!( - b.source, - BindingSource::Synthetic { - stage: Stage::Fragment, - binding: SyntheticBinding::Imageblock - } - ); - let layered = BindState { - render_target_array_length: 2, - ..Default::default() - }; - // Two views over the two layers of a layered pass: multiview the binder plans. - let amplified = BindState { - vertex_amplification: VertexAmplification::new( - 2, - vec![ViewMapping::new(0, 0), ViewMapping::new(0, 1)], - ), - render_target_array_length: 2, - ..Default::default() - }; - let single = BindState { - vertex_amplification: VertexAmplification::new(1, Vec::new()), - ..Default::default() - }; - p.plan(&dev, &single.shape()).expect("one view"); - for (what, s) in [("layered", layered), ("amplified", amplified)] { - match p.plan(&dev, &s.shape()) { - Err(BindError::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::Imageblocks, Needs::NotImplemented), - "{what}" - ), - other => panic!("{what}: {:?}", other.map(|_| ())), - } - } -} - -/// At four samples each function runs once per sample (`SampleId`) and reaches its sample's cell, -/// layers `sample * words + w`; the pipeline links, and the graphics state records the storage. A -/// function whose only effects are its outputs and its write declares early tests as at one -/// sample, on MoltenVK on the M3 Max and on RADV alike; a function that states -/// `TestedStorageWrites`, for a draw whose depth test acts, is refused `NotImplemented(Imageblocks)` -/// at the depth attachment on every device, as its write precedes Vulkan's tests. -#[test] -fn a_multisampled_pipeline_reaches_each_sample_s_cell() { - use crate::bind::FragmentTests; - let Some(bc) = views() else { - return; - }; - let budget = Budget::standard(); - for stem in ["moltenvk-m3", "amd-780m-radv"] { - let dev = device(stem); - for e in &VIEWS { - let what = format!("{} on {stem}", e.entry); - let mut d = render(&bc, e.entry); - d.raster_sample_count = 4; - d.depth_format = Some(PixelFormat::Depth32Float); - let p = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|err| panic!("{what}: {err}")); - let fi = p.graphics.fragment_imageblock.expect("imageblock"); - assert_eq!(fi.words, e.words, "{what}"); - let fragment = (p.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - let dis = spirv_dis(&fragment.spirv); - assert!(dis.contains("BuiltIn SampleId"), "{what}"); - assert!(dis.contains("OpIMul"), "{what}"); - let early = dis.contains("EarlyFragmentTests"); - let tested = p.dependencies.iter().find_map(|x| match x.fact { - RuntimeFact::TestedStorageWrites { - early_tests: false, - early_variant, - } => Some(early_variant), - _ => None, - }); - let want = e.tests; - let got = match (early, tested) { - (true, None) => Tests::Early, - (false, Some(early_variant)) => Tests::Tested { early_variant }, - (false, None) => Tests::None, - (true, Some(_)) => panic!("{what}: early tests beside a tested write"), - }; - assert_eq!(got, want, "{what}"); - // A draw whose depth test acts is refused: the write precedes Vulkan's tests. - if let Tests::Tested { .. } = got { - let shape = BindState { - fragment_tests: FragmentTests::Depth { writes: true }, - ..Default::default() - } - .shape(); - match p.plan(&dev, &shape) { - Err(BindError::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::Imageblocks, Needs::NotImplemented), - "{what}" - ); - let at = u.location.as_ref().and_then(|l| l.attachment()); - assert_eq!(at, Some(crate::error::Attachment::Depth), "{what}"); - } - other => panic!("{what}: the plan: {:?}", other.map(|_| ())), - } - } - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs index 734462289..68f1c4c89 100644 --- a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs +++ b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs @@ -208,10 +208,9 @@ 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. `vk12-floor` has - // neither ordered form, so it reads color 0's input attachment, ordered between draws alone - // and noted; `moltenvk-m3` orders a fetch only through the pixel interlock, in a storage form - // that needs its pipeline's state, which a standalone compile does not have. + // 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. for stem in ["runtime-floor", "moltenvk-m3"] { let r = compile_bitcode( &bc, @@ -223,8 +222,8 @@ fn an_unobserved_gated_off_input_compiles() { &mut meter(), SPIRV_WORDS, ); - match (stem, r) { - ("runtime-floor", Ok(a)) => { + match r { + Ok(a) => { assert!( a.facts .contains(&RuntimeFact::FramebufferFetch { color: 0 }), @@ -238,8 +237,7 @@ fn an_unobserved_gated_off_input_compiles() { a.precision ); } - ("moltenvk-m3", Err(Error::NeedsInput(RuntimeInput::FramebufferFetch))) => {} - (_, other) => panic!("{stem}: declared color input: {:?}", other.map(|_| ())), + other => panic!("{stem}: declared color input: {:?}", other.map(|_| ())), } } } diff --git a/crates/metal2vulkan/src/tests/engine_identity_interlock.rs b/crates/metal2vulkan/src/tests/engine_identity_interlock.rs index 8915204d7..bd79e9f53 100644 --- a/crates/metal2vulkan/src/tests/engine_identity_interlock.rs +++ b/crates/metal2vulkan/src/tests/engine_identity_interlock.rs @@ -1,6 +1,6 @@ //! The pixel interlock under the identity domains (`PointerDomain::Identity` with //! `HandleDomain::Identity`): it orders a raster order group on memory the function reads and -//! writes, and chooses no other form (`lower::fragment::fetch::interlock_forms`). +//! writes, and chooses no other form. //! //! On lavapipe's profile under the identity domains without rasterization-order color attachment //! access (which the runtime does not enable), with `fragmentShaderPixelInterlock` and without it, @@ -10,8 +10,8 @@ //! runs its body in the ordered pixel interlock where the profile has the feature, its modules //! L3-valid, and is refused `Unsupported{RasterOrderGroups}` naming the feature where not. //! - `fetch_ordered` (engine `fragment_fetch`), whose group holds only the color it reads, reads it -//! through the pushed texture (`PushField::FetchedColor`) on both: no storage attachment, no -//! interlock, and its fragment stage notes `UnorderedFetchWithinDraw`. Its modules are word for +//! through the pushed texture (`PushField::FetchedColor`) on both: no interlock, and its +//! fragment stage notes `UnorderedFetchWithinDraw`. Its modules are word for //! word the same with and without the feature, so the interlock chose nothing of its form. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used. @@ -162,10 +162,6 @@ fn the_pixel_interlock_orders_a_raster_order_group_on_memory_alone_under_the_ide for (p, what) in [(&read_with, "with"), (&read_without, "without")] { let m = fragment(p); assert!(!interlocks(&m.spirv), "fetch_ordered {what}: no interlock"); - assert!( - p.graphics.storage_attachments.is_empty(), - "fetch_ordered {what}: no storage attachment" - ); assert!( (m.precision_notes).contains(&PrecisionNote::UnorderedFetchWithinDraw), "fetch_ordered {what}: {:?}", diff --git a/crates/metal2vulkan/src/tests/engine_moved_writers.rs b/crates/metal2vulkan/src/tests/engine_moved_writers.rs deleted file mode 100644 index 282404b24..000000000 --- a/crates/metal2vulkan/src/tests/engine_moved_writers.rs +++ /dev/null @@ -1,409 +0,0 @@ -//! Plain color writers a draw moves into the interlocked storage form. -//! -//! A render pass instance can keep a color out of its subpass for other draws' interlocked storage -//! form (`BindShape::interlocked_colors`); a draw there of a pipeline that writes the color as an -//! ordinary output runs the variant that writes it through the storage form, inside the fragment -//! function and so before the depth and stencil tests. The owned fixture `smw_writers` has one -//! plain writer of color 0 per way those tests bear on such a store: none (no discard, no other -//! write, or Metal's early tests), its discard alone (the early-tests variant where the tests -//! write nothing, refused where they write), and a write of other memory or a returned depth or -//! sample mask (refused wherever the draw's tests can drop a fragment). -//! -//! On every committed profile that orders fetch through the pixel interlock alone, in a pass with -//! a depth and stencil attachment, under each kind of draw tests: the plan of the pipeline as -//! compiled selects the variant the moved writer needs at once, and that variant, compiled, plans -//! itself (a fixed point, which the runtime requires of every variant it compiles), or both refuse -//! the draw. A writer whose write mask covers none of the color's channels stores nothing, so no -//! test bears on its write: its plan selects no tests under any draw tests, and its variant states -//! no store before them. A writer that declares the color as an input it never reads (the owned -//! fixture `smw_unread`) reads nothing there, so it takes no storage form as compiled and every draw -//! that moves no color runs it so. No GPU is used. - -use std::path::Path; - -use crate::bind::{BindState, FragmentTests}; -use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::BindError; -use crate::library::Library; -use crate::lower::fragment::interlock_orders; -use crate::metal::{ColorWriteMask, PixelFormat}; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; - -/// How the depth and stencil tests bear on a writer's store before them. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Class { - /// The variant declares early tests: no draw's tests constrain it. - Free, - /// Only its discard keeps it from early tests. - EarlyVariant, - /// It writes other memory or returns depth or a sample mask: only tests that drop nothing. - Untested, -} - -/// The writers of `smw_writers` and their classes. -const WRITERS: [(&str, Class); 6] = [ - ("smw_plain", Class::Free), - ("smw_early", Class::Free), - ("smw_discard", Class::EarlyVariant), - ("smw_store", Class::Untested), - ("smw_depth", Class::Untested), - ("smw_mask", Class::Untested), -]; - -const TESTS: [FragmentTests; 6] = [ - FragmentTests::Pass, - FragmentTests::Drop, - FragmentTests::Depth { writes: false }, - FragmentTests::Depth { writes: true }, - FragmentTests::Stencil, - FragmentTests::Any, -]; - -/// The library of the owned fixture `name`, assembled with `llvm-as`; `None` where the tool is -/// missing (the test then skips visibly). -fn fixture_library(name: &str) -> Option { - match llvm_assemble(&engine_dir().join(format!("{name}.ll"))) { - Ok(bc) => Some(Library::from_air(&bc).expect("library")), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), - } -} - -/// The function `name` of `library`, as a stage of a render pipeline descriptor. -fn stage(library: &Library, name: &str) -> StageSource { - StageSource::Function(FunctionDescriptor::new( - library.function(name).expect("function"), - )) -} - -/// The committed profiles that order fetch through the pixel interlock, each with its device. -fn ordering_devices() -> Vec<(String, Device)> { - let profiles = committed_profiles().expect("profiles"); - profiles - .iter() - .filter(|(_, profile)| interlock_orders(profile)) - .map(|(stem, _)| (stem.clone(), device(stem))) - .collect() -} - -/// The bind state of a draw under `tests` that moves color 0 into the interlocked storage form -/// where `moved`. -fn moving(tests: FragmentTests, moved: bool) -> BindState { - let mut state = BindState { - fragment_tests: tests, - ..Default::default() - }; - if moved { - state.interlocked_colors.insert(0); - } - state -} - -/// The `early_variant` of the store before the tests `pipeline` states, if it states one. -fn stored_before_tests(pipeline: &crate::pipeline::artifact::RenderPipeline) -> Option { - pipeline.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::TestedStorageWrites { early_variant, .. } => Some(early_variant), - _ => None, - }) -} - -/// Whether `pipeline` writes color 0 through the storage form, and the channels that write keeps. -fn storage_write( - pipeline: &crate::pipeline::artifact::RenderPipeline, -) -> Option { - pipeline - .graphics - .storage_attachments - .iter() - .find(|a| a.color_index == 0 && a.writes) - .map(|a| a.kept) -} - -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{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") -} - -/// Whether a writer of `class` needs the early-tests variant (`read_only_tests`) under `tests`; -/// `None` where the draw is refused (tests that may drop a fragment and write or count, or that -/// the draw does not state). -fn wanted(class: Class, tests: FragmentTests) -> Option { - match (class, tests) { - (Class::Free, _) | (_, FragmentTests::Pass) => Some(false), - (Class::EarlyVariant, FragmentTests::Drop | FragmentTests::Depth { writes: false }) => { - Some(true) - } - _ => None, - } -} - -#[test] -fn a_moved_writer_selects_its_tests_in_its_first_plan() { - let Some(library) = fixture_library("smw_writers") else { - return; - }; - let devices = ordering_devices(); - // The profiles checked, and the writers' variants that planned themselves, by the tests - // they run (`read_only_tests`). - let mut checked = Vec::new(); - let mut fixed_points = std::collections::BTreeSet::<(&str, bool)>::new(); - for (stem, dev) in &devices { - checked.push(stem.as_str()); - for (writer, class) in WRITERS { - let mut d = RenderPipelineDescriptor::new(stage(&library, "smw_full")); - d.fragment = Some(stage(&library, writer)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float)); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - let what = format!("{stem} {writer}"); - // A device short of what the writer needs (a fragment store) refuses it whole. - let base = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(base) => base, - Err(e) => { - eprintln!("{what}: refused as compiled: {e}"); - continue; - } - }; - assert!(base.graphics.storage_attachments.is_empty(), "{what}"); - // The `early_variant` the function states, and its variant with it. - let stated = match class { - Class::Free => None, - Class::EarlyVariant => Some(true), - Class::Untested => Some(false), - }; - let movable = base.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::MovableStorageWrites { early_variant } => Some(early_variant), - _ => None, - }); - assert_eq!(movable, stated, "{what}: the function's movable writes"); - for tests in TESTS { - let shape = moving(tests, true).shape(); - let what = format!("{what} {tests:?}"); - let planned = base.plan(dev, &shape); - // The variant the plan names, compiled, plans itself: the runtime fails a draw - // whose compiled variant asks for another one. - let variant = planned.as_ref().ok().map(|plan| { - let variant = dev - .compile_render_variant(&d, &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: the variant: {e}")); - let again = variant.plan(dev, &shape).unwrap_or_else(|e| { - panic!("{what}: the variant planned refuses the draw: {e}") - }); - assert_eq!(again.variant, plan.variant, "{what}: a fixed point"); - variant - }); - let plan = match (planned, wanted(class, tests)) { - (Ok(plan), Some(_)) => plan, - (Err(BindError::Unsupported(_)), None) => continue, - (planned, want) => { - panic!( - "{what}: planned {:?}, wanted {want:?}", - planned.map(|p| p.variant) - ) - } - }; - let read_only = wanted(class, tests).expect("planned"); - assert_eq!(plan.variant.read_only_tests, read_only, "{what}"); - let variant = variant.expect("compiled for the plan"); - assert!( - storage_write(&variant).is_some(), - "{what}: the variant writes color 0 through the storage form" - ); - assert_eq!( - stored_before_tests(&variant), - stated, - "{what}: the variant's store before the tests" - ); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - fixed_points.insert((writer, read_only)); - } - } - } - // Not vacuous: each writer planned itself under every kind of tests it takes. - eprintln!("moved writers: checked on {checked:?}"); - for (writer, class) in WRITERS { - let kinds: &[bool] = match class { - Class::Free | Class::Untested => &[false], - Class::EarlyVariant => &[false, true], - }; - for kind in kinds { - assert!( - fixed_points.contains(&(writer, *kind)), - "{writer}: no fixed point with tests {kind:?}" - ); - } - } -} - -/// A moved writer whose write mask covers none of color 0's channels stores nothing there, so the -/// depth and stencil tests bear on nothing it stores: under every kind of draw tests, `Any` -/// included, the plan of the pipeline as compiled names the variant that moves the color and -/// selects no tests, and that variant, compiled, writes color 0 through the storage form keeping -/// every channel, states no store before the tests, and plans itself. Every state is checked and -/// the misses are counted by kind before the test fails, so its output says how far a plan strays. -#[test] -fn a_moved_writer_that_stores_nothing_selects_no_tests() { - let Some(library) = fixture_library("smw_writers") else { - return; - }; - let devices = ordering_devices(); - let mut planned = std::collections::BTreeSet::<(&str, String)>::new(); - // The states that miss, by kind of miss. - let mut misses = std::collections::BTreeMap::<&str, Vec>::new(); - let mut states = 0usize; - for (stem, dev) in &devices { - for (writer, _) in WRITERS { - let mut d = RenderPipelineDescriptor::new(stage(&library, "smw_full")); - d.fragment = Some(stage(&library, writer)); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - color.write_mask = ColorWriteMask::NONE; - d.color_attachments[0] = Some(color); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - let what = format!("{stem} {writer} (write mask none)"); - let base = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Ok(base) => base, - Err(e) => { - eprintln!("{what}: refused as compiled: {e}"); - continue; - } - }; - assert_eq!(stored_before_tests(&base), None, "{what}"); - for tests in TESTS { - states += 1; - let shape = moving(tests, true).shape(); - let what = format!("{what} {tests:?}"); - let mut miss = |kind: &'static str| { - misses.entry(kind).or_default().push(what.clone()); - }; - let plan = match base.plan(dev, &shape) { - Ok(plan) => plan, - Err(e) => { - miss("the plan refuses the draw"); - eprintln!("{what}: the plan refuses the draw: {e}"); - continue; - } - }; - let key = &plan.variant; - if key.read_only_tests { - miss("the plan selects tests"); - } - let variant = dev - .compile_render_variant(&d, key, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: the variant: {e}")); - assert_eq!( - storage_write(&variant), - Some(vk::ColorComponentFlags::known_bits()), - "{what}: the variant's write of color 0 keeps every channel" - ); - if stored_before_tests(&variant).is_some() { - miss("the variant states a store before the tests"); - } - match variant.plan(dev, &shape) { - Ok(again) if again.variant == *key => {} - Ok(_) => miss("the variant's plan asks for another variant"), - Err(_) => miss("the variant's plan refuses the draw"), - } - planned.insert((writer, format!("{tests:?}"))); - } - } - } - eprintln!( - "moved writers storing nothing: {states} states on {} profiles", - devices.len() - ); - for (kind, whats) in &misses { - eprintln!("{} states: {kind} (first: {})", whats.len(), whats[0]); - } - assert!(misses.is_empty(), "{misses:#?}"); - // Not vacuous: every writer and kind of tests planned on some profile. - assert_eq!(planned.len(), WRITERS.len() * TESTS.len(), "{planned:?}"); -} - -/// A writer that declares color 0 as an input it never reads (`smw_unread`, which discards) reads -/// nothing there, so it takes no storage form as compiled, under a write mask that stores and one -/// that covers none of the color's channels: color 0 is a color attachment of the pipeline, the -/// pipeline states no store before the tests, and every draw that moves no color, one whose tests -/// may count what they keep (`Any`) included, runs it as compiled. The misses are counted by kind -/// before the test fails. -#[test] -fn an_unread_color_input_takes_no_storage_form() { - let (Some(writers), Some(unread)) = ( - fixture_library("smw_writers"), - fixture_library("smw_unread"), - ) else { - return; - }; - let devices = ordering_devices(); - let mut misses = std::collections::BTreeMap::<&str, Vec>::new(); - let mut states = 0usize; - for (stem, dev) in &devices { - for mask in [ColorWriteMask::ALL, ColorWriteMask::NONE] { - let mut d = RenderPipelineDescriptor::new(stage(&writers, "smw_full")); - d.fragment = Some(stage(&unread, "smw_unread")); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float); - color.write_mask = mask; - d.color_attachments[0] = Some(color); - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - let what = format!("{stem} smw_unread under {mask:?}"); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: refused as compiled: {e}")); - if !base.graphics.storage_attachments.is_empty() { - misses - .entry("it takes the storage form") - .or_default() - .push(what.clone()); - } - if base.graphics.color_attachments[0].is_none() { - misses - .entry("color 0 is no color attachment") - .or_default() - .push(what.clone()); - } - if stored_before_tests(&base).is_some() { - misses - .entry("it states a store before the tests") - .or_default() - .push(what.clone()); - } - for tests in TESTS { - states += 1; - let what = format!("{what} {tests:?}"); - let kind = match base.plan(dev, &moving(tests, false).shape()) { - Ok(plan) if plan.variant == VariantKey::new() => continue, - Ok(_) => "the plan asks for a variant", - Err(_) => "the plan refuses the draw", - }; - misses.entry(kind).or_default().push(what); - } - } - } - eprintln!( - "unread color input: {states} draws on {} profiles", - devices.len() - ); - for (kind, whats) in &misses { - eprintln!("{}: {kind} (first: {})", whats.len(), whats[0]); - } - assert!(misses.is_empty(), "{misses:#?}"); - assert!(states > 0, "no profile checked"); -} diff --git a/crates/metal2vulkan/src/tests/engine_padded_blends.rs b/crates/metal2vulkan/src/tests/engine_padded_blends.rs index d1492fb41..3019aa46b 100644 --- a/crates/metal2vulkan/src/tests/engine_padded_blends.rs +++ b/crates/metal2vulkan/src/tests/engine_padded_blends.rs @@ -3,18 +3,16 @@ //! `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::fetch`, -//! `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 the pixel interlock alone, `rt6_samples`' `half4` and `float4` fills -//! compile with color 0 in the storage form under premultiplied source-over and one plus one, the -//! fact naming the blend, and pass L3; so do `xrb_dual`'s second-source blends, whose index-1 -//! output the blend reads, and a write mask of some of the channels. On every one that orders it -//! through rasterization-order input attachments the whole pipeline is made 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 orders it in neither form -//! the pipeline is refused naming the two orderings. Before the blend was built every one of these -//! was refused `NotImplemented(Format)`. No GPU is used. +//! 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. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. @@ -23,7 +21,7 @@ use std::path::Path; use crate::budget::Budget; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; use crate::error::{DescriptorError, Error, MetalAnswer, Needs}; -use crate::library::{FunctionArtifact, Library}; +use crate::library::Library; use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; use crate::pipeline::artifact::{PrecisionNote, RenderPipeline}; use crate::pipeline::descriptor::{ @@ -32,9 +30,7 @@ use crate::pipeline::descriptor::{ use crate::pipeline::facts::RuntimeFact; use crate::pipeline::link::RenderLinkInputs; use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs, LoweringInputs}; -use crate::pipeline::testing::{ - compile_with, engine_dir, fragment_inputs, link_and_validate, AssembleError, -}; +use crate::pipeline::testing::{compile_with, engine_dir, fragment_inputs, AssembleError}; use crate::spirv::testing::committed_profiles; use crate::vk; @@ -128,29 +124,10 @@ fn state( 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, - false, - false, - 1, - )); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); inputs } -/// Color 0's storage form in `a`: whether it writes, and its blend. -fn fetched(a: &FunctionArtifact) -> Option<(bool, Option)> { - a.facts.iter().find_map(|f| match f { - RuntimeFact::InterlockedFramebufferFetch { - color: 0, - writes, - blend, - .. - } => Some((*writes, *blend)), - _ => None, - }) -} - /// The device of committed profile `stem`. fn device(stem: &str) -> Device { let path = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -161,8 +138,7 @@ fn device(stem: &str) -> Device { Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") } -/// Whether `e` is a refusal the device's lack of a capability makes, whatever the blend (a -/// raw format without the storage access the form needs). +/// Whether `e` is a refusal the device's lack of a capability makes, whatever the blend. fn device_gap(e: &Error) -> bool { matches!(e, Error::Unsupported(u) if u.needs != Needs::NotImplemented) } @@ -228,7 +204,7 @@ fn a_blend_into_a_padded_attachment_is_computed_in_the_shader() { let rgb = ColorWriteMask::RED .union(ColorWriteMask::GREEN) .union(ColorWriteMask::BLUE); - let (mut interlocked, mut inputs, mut unordered) = (0, 0, 0); + let (mut inputs, mut unordered) = (0, 0); for (stem, p) in committed_profiles().expect("profiles") { let dev = device(&stem); for pf in PADDED { @@ -237,29 +213,7 @@ fn a_blend_into_a_padded_attachment_is_computed_in_the_shader() { 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::interlock_orders(&p) { - let a = match compile_with(bc, fragment, &p, &state(&p, pf, eq, mask)) { - Ok(a) => a, - Err(e) if device_gap(&e) => { - eprintln!("{what}: {e}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!( - fetched(&a), - Some((true, Some(eq))), - "{what}: {:?}", - a.facts - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let made = made.unwrap_or_else(|e| panic!("{what}: the pipeline: {e}")); - assert!( - !made.graphics.storage_attachments.is_empty(), - "{what}: no storage attachment" - ); - interlocked += 1; - } else if crate::lower::fragment::inputs_order(&p) { + 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:?}"); @@ -283,9 +237,8 @@ fn a_blend_into_a_padded_attachment_is_computed_in_the_shader() { } } } - assert!(interlocked > 0, "no profile blends in the storage form"); assert!(inputs > 0, "no profile blends over the input attachment"); - assert!(unordered > 0, "no profile orders fetch in neither form"); + assert!(unordered > 0, "no profile leaves fetch unordered"); } /// A blend into a bfloat attachment (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) is Metal's @@ -344,18 +297,16 @@ fn a_blend_into_a_bfloat_attachment_is_metals_pipeline_error() { /// (`extended_range::tile_value`), as Metal's fetch does: each loaded code's value rounded to /// `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 that orders fetch: -/// through the pixel interlock with color 0 a storage attachment of the raw format the function -/// does not write, or through rasterization-order input attachments with color 0 an attachment of -/// the raw format read as an unsigned input attachment. On one that orders it in neither form it -/// takes that input attachment too, ordered between draws alone, its fragment stage noting -/// `UnorderedFetchWithinDraw`. Before the read was built each was refused -/// `NotImplemented(FramebufferFetch)`. The negative control: a fetch of a bfloat attachment, whose -/// read Metal answers unmeasured, stays `NotImplemented(Format)` on every profile. +/// 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 +/// 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, interlock_orders}; + use crate::lower::fragment::inputs_order; use crate::metal::format::ExtendedRange; let Some(bc) = assembled("pfx_fetch") else { return; @@ -378,52 +329,32 @@ 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 interlocked, mut inputs, mut unordered, mut bfloat) = (0, 0, 0, 0); + let (mut inputs, mut unordered, mut bfloat) = (0, 0, 0); for (stem, p) 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(); - let made = made(&dev, fragment, pf); - if interlock_orders(&p) { - let a = match made { - Ok(a) => a, - Err(e) if device_gap(&e) => { - eprintln!("{what}: {e}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - let uses: Vec<(u32, vk::Format, bool)> = a - .graphics - .storage_attachments - .iter() - .map(|s| (s.color_index, s.format, s.writes)) - .collect(); - assert_eq!(uses, [(0, raw, false)], "{what}"); - interlocked += 1; - } else { - // Rasterization-order input attachments, or with neither ordered form input - // attachments ordered between draws alone, noted. - let a = made.unwrap_or_else(|e| panic!("{what}: {e}")); - let state0 = a.graphics.color_attachments[0].expect("color 0"); - assert_eq!(state0.format, raw, "{what}"); - let read: Vec = a - .graphics - .input_attachments - .iter() - .map(|i| i.color_index) - .collect(); - assert_eq!(read, [0], "{what}"); - 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, - } + // Rasterization-order input attachments, or 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}"); + let read: Vec = a + .graphics + .input_attachments + .iter() + .map(|i| i.color_index) + .collect(); + assert_eq!(read, [0], "{what}"); + 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, } } for pf in BFLOAT { @@ -440,89 +371,7 @@ fn a_fetch_of_a_padded_attachment_reads_the_tile_value_of_its_codes() { } } } - assert!(interlocked > 0, "no profile reads in the storage form"); assert!(inputs > 0, "no profile reads through the input attachment"); - assert!(unordered > 0, "no profile orders fetch in neither form"); + assert!(unordered > 0, "no profile leaves fetch unordered"); assert!(bfloat > 0, "no bfloat fetch was refused"); } - -/// An unblended bfloat attachment (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) the draw moves into -/// the interlocked storage form (named in `LoweringInputs::framebuffer_fetch`, as a render pass -/// instance names a color it keeps out of its subpass for other draws) is written there as the -/// fixed-function path writes it: Metal's bfloat code of the output's `half` -/// (`extended_color::bfloat_output`), and under a mask of some channels the texel's kept channels -/// as the attachment held them (the raw lanes of the texel the write read, as the fixed-function -/// write mask keeps them). On every committed profile that orders fetch through the pixel -/// interlock alone, `rt6_samples`' `float4` and `half4` fills compile with color 0 a written -/// storage attachment under every mask and pass L3, the `float4` fill recording the pipeline's -/// `textureWriteRoundingMode` its write rounds by. The same functions without the naming take no -/// storage form (the control). Before, a write of some channels failed inside the lowering, and -/// a write of every one stored a kernel write's code, which drops the low bits. -#[test] -fn an_unblended_bfloat_attachment_is_written_in_the_storage_form() { - use crate::lower::fragment::interlock_orders; - let Some(fills) = assembled("rt6_samples") else { - return; - }; - let masks = [ - ColorWriteMask::ALL, - ColorWriteMask::RED, - ColorWriteMask::GREEN.union(ColorWriteMask::ALPHA), - ColorWriteMask::NONE, - ]; - let inputs = |p: &DeviceProfile, pf: PixelFormat, mask: ColorWriteMask, named: bool| { - let mut r = RenderLinkInputs::new(); - let mut c = ColorAttachmentDescriptor::new(pf); - c.write_mask = mask; - r.color_attachments[0] = Some(c); - let mut inputs = fragment_inputs(&r, p); - if named { - inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( - [0], - &r.color_attachments, - false, - false, - 1, - )); - } - inputs - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if !interlock_orders(&p) { - continue; - } - for pf in BFLOAT { - for fill in ["rt6_fill_rgba32float", "rt6_fill_rgba16float"] { - for mask in masks { - let what = format!("{stem} {pf:?} {fill} {mask:?}"); - let a = match compile_with(&fills, fill, &p, &inputs(&p, pf, mask, true)) { - Ok(a) => a, - Err(e) if device_gap(&e) => { - eprintln!("{what}: {e}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!(fetched(&a), Some((true, None)), "{what}: {:?}", a.facts); - // A `float` output rounds by the pipeline's mode, which link holds. - if mask != ColorWriteMask::NONE { - let rounds = (fill == "rt6_fill_rgba32float") - .then_some(crate::metal::TextureWriteRoundingMode::TowardZero); - assert_eq!(a.interface.io.texture_write_rounding, rounds, "{what}"); - } - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - // The control: unnamed, the attachment is the fixed function's. - let plain = compile_with(&fills, fill, &p, &inputs(&p, pf, mask, false)) - .unwrap_or_else(|e| panic!("{what}: unnamed: {e}")); - assert_eq!(fetched(&plain), None, "{what}"); - checked += 1; - } - } - } - } - assert!( - checked > 0, - "no interlock profile wrote a bfloat attachment" - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_private_render_state.rs b/crates/metal2vulkan/src/tests/engine_private_render_state.rs index 0fb192a12..265342c26 100644 --- a/crates/metal2vulkan/src/tests/engine_private_render_state.rs +++ b/crates/metal2vulkan/src/tests/engine_private_render_state.rs @@ -16,8 +16,8 @@ //! - 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 (MoltenVK, and lavapipe with the feature off), and are refused -//! where neither holds and where Metal's operation is not built. +//! 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. //! - 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 +627,15 @@ 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 MoltenVK, which lacks it, the -/// fragment function computes it through the storage form, and on lavapipe without 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 orders fetch in neither form the operation is refused -/// naming the three features. 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). 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`. #[test] fn the_logic_operation_draws_as_metal_s_or_is_refused() { use crate::device::requirements::VkFeature; @@ -666,6 +666,17 @@ 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( + Feature::PrivateRenderState(PrivateRenderField::LogicOperation), + vec![ + vec![C::Feature(V::LogicOp)], + vec![C::Feature(V::RasterizationOrderColorAttachmentAccess)], + ], + )) + }; for stem in STEMS { let dev = device(stem); let has = stem == "lavapipe"; @@ -698,12 +709,8 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { ] { let blended = pf != PixelFormat::RGBA16Float; let d = with(pf, blended, Some(raw)); - match ( - has, - pf, - dev.compile_render_pipeline(&d, &Budget::standard()), - ) { - (true, _, Ok(p)) => { + match (has, dev.compile_render_pipeline(&d, &Budget::standard())) { + (true, Ok(p)) => { assert_eq!(p.graphics.logic_op, Some(vk::LogicOp::XOR), "{pf:?}"); let a = p.graphics.color_attachments[0].expect("attachment 0"); assert!(a.blend.is_none(), "{stem} {pf:?} blends"); @@ -714,20 +721,9 @@ 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 orders fetch through the pixel - // interlock: the fragment function computes it. - (false, _, Ok(p)) => { - let what = format!("{stem} {pf:?} xor"); - shader_operated(&p, pf != PixelFormat::RGBA16Float, &what); - assert!(!native_logic(&p), "{what}"); - let stored = p - .graphics - .storage_attachments - .iter() - .any(|s| s.color_index == 0); - assert_eq!(stored, pf != PixelFormat::RGBA16Float, "{what}"); - } - (_, _, other) => panic!("{stem} {pf:?} xor: {other:?}"), + // MoltenVK lacks Vulkan's operation and does not order fetch. + (false, Err(e)) => assert_eq!(e, unordered(), "{stem} {pf:?} xor"), + (_, other) => panic!("{stem} {pf:?} xor: {other:?}"), } } } @@ -738,27 +734,22 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { (PixelFormat::RGBA16Float, true), (PixelFormat::RG11B10Float, false), ] { - let refused = has || pf != PixelFormat::RGBA16Float; - match ( - refused, - dev.compile_render_pipeline(&with(pf, blended, Some(10)), &Budget::standard()), - ) { - (true, Err(e)) => assert_eq!(e, not_built(0), "{stem} {pf:?}"), - (false, Ok(p)) => { - let a = p.graphics.color_attachments[0].expect("attachment 0"); - assert!(a.blend.is_some(), "{stem} {pf:?} keeps its blend"); - shader_operated(&p, false, &format!("{stem} {pf:?}")); - } - (_, other) => panic!("{stem} {pf:?} xor: {other:?}"), + let want = if has { not_built(0) } else { unordered() }; + 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(|_| ())), } } // Each operation keys a pipeline of its own, apart from copy's, whose attachments are the // same unblended ones. - let key = - |raw: u64| compile(&dev, &with(PixelFormat::RGBA8Unorm, true, Some(raw)), "key").key; - let keys = [key(0), key(10), key(15), key(2)]; - for (i, a) in keys.iter().enumerate() { - assert!(keys[i + 1..].iter().all(|b| a != b), "{stem} keys {keys:?}"); + if has { + let key = |raw: u64| { + compile(&dev, &with(PixelFormat::RGBA8Unorm, true, Some(raw)), "key").key + }; + let keys = [key(0), key(10), key(15), key(2)]; + for (i, a) in keys.iter().enumerate() { + assert!(keys[i + 1..].iter().all(|b| a != b), "{stem} keys {keys:?}"); + } } // Off, the pipeline is the one without the property. let off = compile(&dev, &with(PixelFormat::RGBA8Unorm, true, None), "off"); @@ -815,7 +806,6 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { let operated = pf != PixelFormat::RGBA16Float; shader_operated(&p, operated, &what); assert!(!native_logic(&p), "{what}"); - assert!(p.graphics.storage_attachments.is_empty(), "{what}"); let read = p .graphics .input_attachments @@ -831,17 +821,12 @@ fn the_logic_operation_draws_as_metal_s_or_is_refused() { } let unordered = device_without( "lavapipe", - &[ - "logicOp", - "fragmentShaderPixelInterlock", - "rasterizationOrderColorAttachmentAccess", - ], + &["logicOp", "rasterizationOrderColorAttachmentAccess"], ); let wanted = Error::Unsupported(Unsupported::needs_any_of( Feature::PrivateRenderState(PrivateRenderField::LogicOperation), vec![ vec![Capability::Feature(VkFeature::LogicOp)], - vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], vec![Capability::Feature( VkFeature::RasterizationOrderColorAttachmentAccess, )], @@ -896,8 +881,7 @@ fn shader_operated(p: &RenderPipeline, operated: bool, what: &str) { .precision_notes .contains(&PrecisionNote::DeviceColorConversion); assert!(noted, "{what}"); - // Attachment 0 is a color attachment of the subpass over an input attachment, and none - // in the storage form, which writes it as a storage image. + // 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"); } diff --git a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs index 6bf0fcc63..ce1c7dfbf 100644 --- a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs +++ b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs @@ -12,9 +12,9 @@ //! 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 (the interlocked storage form, or over the input attachment, -//! `RotatedInputBlend`), noting the device's conversion, and a device that orders it in neither -//! form refuses naming both orderings; alpha to coverage over the image is refused +//! 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; //! - a blend not exact by construction records `PrecisionNote::RotatedBlendRounding`. //! @@ -287,11 +287,9 @@ fn argb8_attachments_take_the_output_mask_and_blend_rotated() { } } // 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, in the interlocked - // storage form (color 0 is no attachment of the subpass) or over the attachment's input - // attachment (`RotatedInputBlend`, no Vulkan blend there), and a device that orders it in - // neither form names both orderings. - let interlock = crate::lower::fragment::interlock_orders(dev.profile()); + // 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()); for c in [ blended(F::DestinationAlpha, F::Zero, O::Add, O::Add), @@ -301,17 +299,6 @@ 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 interlock => { - assert!(p.graphics.color_attachments[0].is_none(), "{stem}: {c:?}"); - let stored = &p.graphics.storage_attachments; - assert!( - stored.iter().any(|s| s.color_index == 0 - && s.writes - && s.format == vk::Format::R8G8B8A8_UNORM), - "{stem}: {c:?}: {stored:?}" - ); - assert!(notes(&p, PrecisionNote::DeviceColorConversion), "{stem}"); - } Ok(p) if inputs => { let state = p.graphics.color_attachments[0].expect("color 0"); assert_eq!(state.blend, None, "{stem}: {c:?}"); @@ -326,16 +313,13 @@ fn argb8_attachments_take_the_output_mask_and_blend_rotated() { assert!(notes(&p, PrecisionNote::DeviceColorConversion), "{stem}"); } Ok(_) => panic!("{stem}: {c:?}: made on a device that orders no fetch"), - Err(Error::Unsupported(u)) if !interlock && !inputs => { + Err(Error::Unsupported(u)) if !inputs => { assert_eq!(u.feature, Feature::FramebufferFetch, "{stem}: {c:?}"); assert_eq!( u.needs, - Needs::AnyOf(vec![ - vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], - vec![Capability::Feature( - VkFeature::RasterizationOrderColorAttachmentAccess - )], - ]), + Needs::AnyOf(vec![vec![Capability::Feature( + VkFeature::RasterizationOrderColorAttachmentAccess + )]]), "{stem}: {c:?}" ); let at = u.location.as_ref().and_then(|l| l.attachment()); diff --git a/crates/metal2vulkan/src/tests/engine_snapshot_exact.rs b/crates/metal2vulkan/src/tests/engine_snapshot_exact.rs deleted file mode 100644 index 1903dd0cb..000000000 --- a/crates/metal2vulkan/src/tests/engine_snapshot_exact.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! A texture read through a snapshot at a slot whose reads may take any bound format. -//! -//! The copy that fills a snapshot (`lower::fragment`'s `snapshot`) fetches through one view, and -//! the read the snapshot stands for must be the fetch through that same view: the slot's own image, -//! whose bound view the binder names the snapshot's form by. -//! -//! - Every form the binder can name for a `texture2d` slot — the bound -//! view's codes, or the fetched lanes' bits — translates and passes L3 under the resident-table -//! domains. An 8-bit sRGB texture, whose view decodes its codes, keeps the -//! fetched lanes' bits. -//! - The copy pairs the form with its fetch's lanes where the invariant lives: a form whose codes -//! those lanes do not hold is named, not left to the builder to refuse (a float code form over -//! integer lanes walks into `FClamp`, and an integer form over float lanes bitcasts the value). -//! Every one of the ten forms, over float lanes and over unsigned integer lanes. -//! -//! `llvm-as` assembles the fixtures; a missing tool skips a test visibly. - -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::bind::{BindState, BoundTexture, TextureFacts}; -use crate::budget::Budget; -use crate::device::{Device, DevicePolicy}; -use crate::library::Library; -use crate::metal::{PixelFormat, TextureType, TextureUsage}; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{SlotClass, SlotRef, SnapshotForm, Stage}; -use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; -use crate::spirv::testing::check_words_valid; - -/// The snapshot slot under test. -const SLOT: SlotRef = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 0, -}; - -/// Every form a snapshot can keep its texels in, in declaration order. -const FORMS: [SnapshotForm; 10] = [ - SnapshotForm::Bits, - SnapshotForm::Unorm8, - SnapshotForm::Snorm8, - SnapshotForm::Unorm16, - SnapshotForm::Snorm16, - SnapshotForm::Half, - SnapshotForm::Uint8, - SnapshotForm::Sint8, - SnapshotForm::Uint16, - SnapshotForm::Sint16, -]; - -/// Whether `form`'s codes hold every lane an image whose sampled type is `f32` (`float_lanes`) -/// or `u32` returns: a float lane's every form but an integer one's codes, an unsigned integer -/// lane's the bits and the unsigned integer codes. The bits hold any lanes. -fn holds(form: SnapshotForm, float_lanes: bool) -> bool { - match float_lanes { - true => !matches!( - form, - SnapshotForm::Uint8 | SnapshotForm::Uint16 | SnapshotForm::Sint8 | SnapshotForm::Sint16 - ), - false => matches!( - form, - SnapshotForm::Bits | SnapshotForm::Uint8 | SnapshotForm::Uint16 - ), - } -} - -/// The profiles whose draws can take a snapshot (the pixel interlock, fragment stores, the -/// feedback loop layout and dynamic color write masks); `vk12-floor` has none, and is left out. -const PROFILES: [&str; 4] = [ - "intel-irisxe-anv", - "amd-780m-radv", - "nvidia-rtx5080-laptop", - "lavapipe", -]; - -const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; - -/// A fragment function returning the `uint4` texel of a `texture2d` slot under -/// its own pixel, the read an integer-lane snapshot slot stands for. -const UINT_READ: &str = r#"define <4 x i32> @sx_read_u(<4 x float> %0, ptr addrspace(1) %1) { - %3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> - %4 = call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) - %5 = call ptr addrspace(2) @air.get_read_sampler() - %6 = call { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1) %1, ptr addrspace(2) %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) - %7 = extractvalue { <4 x i32>, i8 } %6, 0 - ret <4 x i32> %7 -} - -declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) -declare ptr addrspace(2) @air.get_read_sampler() -declare { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) - -!air.fragment = !{!0} -!0 = !{ptr @sx_read_u, !1, !3} -!1 = !{!2} -!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"uint4"} -!3 = !{!4, !5} -!4 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} -!5 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -"#; - -/// Bitcode of the owned fixture `name`, or `None` (skipped visibly) without `llvm-as`. -fn fixture(name: &str) -> Option> { - match llvm_assemble(&engine_dir().join(format!("{name}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), - } -} - -/// Bitcode of the module `text`, or `None` (skipped visibly) without `llvm-as`. -fn assemble(text: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-snapshot-exact-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("f.ll"); - std::fs::write(&ll, format!("{HEADER}{text}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the fragment: {why}"), - } -} - -/// Function `name` of `bc` as a stage source. -fn function(bc: &[u8], name: &str) -> StageSource { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) -} - -/// A draw state that asks for a snapshot of texture slot 0 with `pixel_format` bound there. -fn state(pixel_format: Option) -> BindState { - let mut s = BindState { - snapshot_textures: [0].into(), - ..Default::default() - }; - if let Some(pf) = pixel_format { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - s.stages - .entry(Stage::Fragment) - .or_default() - .textures - .insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - s -} - -/// A `texture2d` slot the draw reads through a snapshot translates under -/// every form the binder names for it under the resident-table domains. An 8-bit sRGB texture, -/// whose view decodes its codes, keeps the fetched bits. Each variant passes -/// L3 and binds the snapshot as a storage image. -#[test] -fn a_snapshot_slot_translates_under_every_form() { - let Some(bc) = fixture("tob_renders") else { - return; - }; - let mut d = RenderPipelineDescriptor::new(function(&bc, "tob_rect")); - d.fragment = Some(function(&bc, "tob_read")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - // Each form `SnapshotForm::of` names for a float slot, by a texture the binder names it for. - let bound = [ - (PixelFormat::RGBA8Unorm, SnapshotForm::Unorm8), - (PixelFormat::RGBA8Snorm, SnapshotForm::Snorm8), - (PixelFormat::RGBA16Unorm, SnapshotForm::Unorm16), - (PixelFormat::RGBA16Snorm, SnapshotForm::Snorm16), - (PixelFormat::RGBA16Float, SnapshotForm::Half), - (PixelFormat::R16Float, SnapshotForm::Half), - (PixelFormat::RGBA32Float, SnapshotForm::Bits), - (PixelFormat::RGBA8UnormSRGB, SnapshotForm::Bits), - ]; - for stem in PROFILES { - { - let (label, policy) = ("the default", DevicePolicy::RESIDENT_TABLES); - let desc = crate::pipeline::testing::description(stem).expect("description"); - let dev = Device::from_queries(desc, policy).expect("device"); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}/{label}: {e}")); - for (pf, form) in bound { - let plan = base - .plan(&dev, &state(Some(pf)).shape()) - .unwrap_or_else(|e| panic!("{stem}/{label}/{pf:?}: plan: {e}")); - assert_eq!( - plan.variant.snapshot_textures, - [(SLOT, form)].into(), - "{stem}/{label}/{pf:?}" - ); - let variant = dev - .compile_render_variant(&d, &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}/{label}/{pf:?}: {e}")); - assert!( - variant - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .any(|b| b.source == BindingSource::SnapshotTexels(0)), - "{stem}/{label}/{pf:?}: no snapshot binding" - ); - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem}/{label}/{pf:?}: L3: {e}")); - } - } - } - } -} - -/// The copy of a snapshot slot names a form whose codes its fetch's lanes do not hold, where that -/// invariant lives, instead of leaving the builder to refuse the encode: over float lanes every -/// integer form, and over unsigned integer lanes every float code form (the pairing that otherwise -/// reaches `FClamp`). The binder never names such a pairing (`SnapshotForm::of`), so the key is -/// forged. On ANV's Iris Xe profile. -#[test] -fn the_copy_of_a_snapshot_slot_refuses_a_form_its_fetch_s_lanes_do_not_hold() { - let (Some(bc), Some(uint)) = (fixture("tob_renders"), assemble(UINT_READ)) else { - return; - }; - let stem = "intel-irisxe-anv"; - let desc = crate::pipeline::testing::description(stem).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - // The float slot's fragment, and the unsigned integer slot's into an integer attachment. - let legs = [ - ("uint", "sx_read_u", &uint, PixelFormat::RGBA8Uint, false), - ("float", "tob_read", &bc, PixelFormat::RGBA8Unorm, true), - ]; - for (leg, entry, module, attachment, float_lanes) in legs { - let mut d = RenderPipelineDescriptor::new(function(&bc, "tob_rect")); - d.fragment = Some(function(module, entry)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(attachment)); - let base = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{leg}: {e}")); - let plan = base - .plan(&dev, &state(None).shape()) - .unwrap_or_else(|e| panic!("{leg}: plan: {e}")); - assert!( - !plan.variant.snapshot_textures.is_empty(), - "{leg}: no snapshot variant" - ); - for form in FORMS { - let mut key = plan.variant.clone(); - key.snapshot_textures = [(SLOT, form)].into(); - let r = dev.compile_render_variant(&d, &key, &Budget::standard()); - if holds(form, float_lanes) { - r.unwrap_or_else(|e| panic!("{leg}/{form:?}: {e}")); - continue; - } - let e = r.err().map(|e| e.to_string()).unwrap_or_default(); - assert!( - e.contains(&format!( - "the copy of snapshot slot 0 fetches lanes its form {form:?} does not hold" - )), - "{leg}/{form:?}: {e}" - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs b/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs index fd7ae0c62..a170e9054 100644 --- a/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs +++ b/crates/metal2vulkan/src/tests/engine_spirv_cross_forms.rs @@ -7,9 +7,8 @@ //! owned fixture `engine/stage_io_tail`'s `tail_vertex_bool` returns such a struct. //! - Only the entry reads the `SampleMask` input: where the entry wraps the body (an interlock; the //! loop over the covered samples), the body reads the entry's copy. SPIRV-Cross declares the -//! input a scalar in the entry and passes it to a function as an array. The owned fixtures -//! `engine/msf_fetch_ms`'s `msf_fetch_mask_in` (the interlocked storage form of a framebuffer -//! fetch) and `engine/coverage_loop`'s `cov_loop_record` (the loop) read it. +//! input a scalar in the entry and passes it to a function as an array. The owned fixture +//! `engine/coverage_loop`'s `cov_loop_record` (the loop) reads it. //! //! And one form that keeps MoltenVK's pipeline creation within the ceiling: SPIRV-Cross //! force-inlines every function it writes, so Metal's back end compiles a routine once per call. A @@ -27,14 +26,10 @@ use std::path::Path; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::Error; use crate::library::Library; -use crate::metal::PixelFormat; use crate::pipeline::testing::{ engine_dir, link_standalone, llvm_assemble, moltenvk_msl_compile, AssembleError, }; -use crate::pipeline::{ - ColorAttachmentDescriptor, FramebufferFetchInputs, FunctionDescriptor, LoweringInputs, - RenderPipelineDescriptor, StageSource, -}; +use crate::pipeline::{FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, StageSource}; use crate::spirv::testing::check_words_valid; use crate::Budget; @@ -202,49 +197,6 @@ fn a_bool_vector_member_is_held_as_words() { } } -/// `msf_fetch_mask_in` reads `[[sample_mask]]` beside a framebuffer fetch. Wherever it compiles to -/// the interlocked storage form (the entry calls the body inside the critical section), at one and -/// four samples, only the entry reads the `SampleMask` input; every module passes L3 and, on macOS, -/// compiles as MoltenVK's MSL. -#[test] -fn only_the_entry_reads_the_coverage_of_an_interlocked_body() { - let Some(lib) = library("msf_fetch_ms") else { - return; - }; - let mut wrapped = 0; - for (stem, dev) in devices() { - for samples in [1u32, 4] { - let what = format!("{stem} msf_fetch_mask_in at {samples}"); - let colors = vec![Some(ColorAttachmentDescriptor::new( - PixelFormat::RGBA32Float, - ))]; - let mut inputs = LoweringInputs::new(); - inputs.framebuffer_fetch = - Some(FramebufferFetchInputs::of(0..1, &colors, false, false, 1)); - inputs.multisampled = samples > 1; - let f = FunctionDescriptor::new(lib.function("msf_fetch_mask_in").expect("fragment")); - let c = match dev.compile_function(&f, &inputs, &Budget::standard()) { - Ok(c) => c, - Err(Error::Unsupported(_) | Error::NeedsInput(_)) => continue, - Err(e) => panic!("{what}: {e}"), - }; - let words = link_standalone(c.artifact(), dev.profile()) - .unwrap_or_else(|e| panic!("{what}: link: {e}")) - .1; - let functions = instructions(&words) - .iter() - .filter(|(op, _)| *op == OP_FUNCTION) - .count(); - wrapped += usize::from(functions > 1); - assert!(!sample_mask_input_outside_entry(&words), "{what}"); - check_words_valid(&words, &c.artifact().requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - compiles_as_moltenvk_msl(&stem, &words, &what); - } - } - assert!(wrapped >= 2, "{wrapped} interlocked modules"); -} - /// The loop over the covered samples of `cov_loop_record` at four samples reads the coverage in /// the entry, and the body reads the entry's copy, on every profile where it compiles; on macOS the /// MoltenVK profiles' modules compile as MoltenVK's MSL. diff --git a/crates/metal2vulkan/src/tests/engine_stencil.rs b/crates/metal2vulkan/src/tests/engine_stencil.rs index 1348244dc..be0313006 100644 --- a/crates/metal2vulkan/src/tests/engine_stencil.rs +++ b/crates/metal2vulkan/src/tests/engine_stencil.rs @@ -1,32 +1,22 @@ //! A fragment function's `[[stencil]]` output end to end: the direct `FragStencilRefEXT` where the -//! device has stencil export, the shader-side stencil over a shadow inside the ordered pixel -//! interlock where it has only the interlock, and a refusal naming both ways elsewhere; the render -//! pipeline's contract and the binder's writes and push words. The public fixture -//! `fragment_depth_stencil` returns a depth and a stencil. No GPU is used. +//! device has stencil export, and elsewhere a refusal naming the extension, of the function and of +//! its render pipeline. The public fixture `fragment_depth_stencil` returns a depth and a stencil. +//! No GPU is used. //! //! `llvm-as` assembles the fixture; a missing tool skips visibly. -use crate::bind::{BindState, DrawCall, WriteSource}; use crate::budget::Budget; -use crate::device::requirements::{FormatUsage, VkExtension, VkFeature, VkProperty}; +use crate::device::requirements::VkExtension; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Capability, Error, Feature, Needs}; +use crate::error::{Capability, Error, Feature, Needs}; use crate::library::Library; -use crate::lower::select::LowerInputs; -use crate::metal::state::DepthStencilDescriptor; -use crate::metal::{CompareFunction, PixelFormat, StencilOperation}; +use crate::metal::PixelFormat; use crate::pipeline::descriptor::{FunctionDescriptor, RenderPipelineDescriptor, StageSource}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; use crate::pipeline::stage_io::StageBuiltin; -use crate::pipeline::sym::{PushField, SyntheticBinding}; use crate::pipeline::testing::{ - compile, compile_with, engine_dir, fixtures_dir, interlocked_coherence, link_and_validate, - llvm_assemble, AssembleError, + compile, engine_dir, fixtures_dir, link_and_validate, llvm_assemble, AssembleError, }; -use crate::pipeline::RenderPipeline; use crate::spirv::testing::committed_profiles; -use crate::vk; fn assemble(path: &std::path::Path) -> Option> { match llvm_assemble(path) { @@ -45,125 +35,41 @@ fn stencil_fixture() -> Option> { assemble(&fixtures_dir().join("fragment_depth_stencil.ll")) } -fn device(stem: &str) -> Device { - device_without(stem, &[]) -} - -/// Committed profile `stem` with `features` removed from its description. -fn device_without(stem: &str, features: &[VkFeature]) -> Device { - 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 mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - for f in features { - desc.features.remove(f); - } - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") +/// The refusal of a stencil output on a device without stencil export. +fn needs_export() -> (Feature, Needs) { + ( + Feature::StencilExport, + Needs::AnyOf(vec![vec![Capability::Extension( + VkExtension::ExtShaderStencilExport, + )]]), + ) } /// On every committed profile the output is the direct `FragStencilRefEXT` where the device has -/// stencil export, the shader-side stencil where it has the ordered pixel interlock (every NVIDIA -/// profile), and otherwise refused naming the extension or what the shader-side stencil lacks. The -/// shader-side module passes L3, runs its body inside the interlock, holds every access there -/// coherent, and states its fact and push field. +/// stencil export, the module passing L3, and is otherwise refused naming the extension alone. #[test] -fn the_stencil_output_takes_the_extension_the_shadow_or_a_refusal_naming_both() { +fn the_stencil_output_takes_the_extension_or_a_refusal_naming_it() { let Some(bc) = stencil_fixture() else { return; }; - let mut forms = [0usize; 3]; + // [exported, refused] + let mut forms = [0usize; 2]; for (stem, p) in committed_profiles().expect("profiles") { - let f = p.fields(); let result = compile(&bc, ENTRY, &p); - if f.fragment.stencil_export { + if p.fields().fragment.stencil_export { forms[0] += 1; let a = result.unwrap_or_else(|e| panic!("{stem}: {e}")); assert!( - !a.facts - .iter() - .any(|x| matches!(x, RuntimeFact::ShadowStencil { .. })), - "{stem}" + a.interface.io.builtins.contains(&StageBuiltin::StencilRef), + "{stem}: {:?}", + a.interface.io.builtins ); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - } else if f.fragment.pixel_interlock { - forms[1] += 1; - let a = result.unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - a.facts.contains(&RuntimeFact::ShadowStencil { - formatless: false, - multisampled: false - }), - "{stem}: {:?}", - a.facts - ); - assert!( - a.interface - .push - .fields - .iter() - .any(|pf| pf.field == PushField::ShadowStencilState), - "{stem}" - ); - assert!(a - .requirements - .features - .contains(&VkFeature::FragmentShaderPixelInterlock)); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let n = interlocked_coherence(&words).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(n.storage_image, 2, "{stem}: the shadow's read and write"); - // Compiled for a multisampled pipeline: a multisampled shadow, tested per sample of - // the invocation's coverage, the samples that pass written to `SampleMask`. - let mut inputs = LowerInputs::new(); - inputs.multisampled = true; - let ms = compile_with(&bc, ENTRY, &p, &inputs) - .unwrap_or_else(|e| panic!("{stem}: multisampled: {e}")); - assert!( - ms.facts.contains(&RuntimeFact::ShadowStencil { - formatless: false, - multisampled: true - }), - "{stem}: {:?}", - ms.facts - ); - assert!(ms - .requirements - .features - .contains(&VkFeature::ShaderStorageImageMultisample)); - assert!(ms - .interface - .io - .builtins - .contains(&StageBuiltin::SampleMaskOut)); - assert!(!ms - .interface - .io - .builtins - .contains(&StageBuiltin::SampleMaskIn)); - let (_, words) = link_and_validate(&ms, &p) - .unwrap_or_else(|e| panic!("{stem}: multisampled L3: {e}")); - let n = interlocked_coherence(&words).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(n.storage_image, 2, "{stem}: the shadow's read and write"); } else { - forms[2] += 1; + forms[1] += 1; match result { Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::StencilExport, "{stem}"); - let Needs::AnyOf(a) = u.needs else { - panic!("{stem}: {:?}", u.needs) - }; - assert_eq!( - a[0], - [Capability::Extension(VkExtension::ExtShaderStencilExport)], - "{stem}" - ); - assert!( - a[1].contains(&Capability::Feature( - VkFeature::FragmentShaderPixelInterlock - )), - "{stem}: {a:?}" - ); + assert_eq!((u.feature, u.needs), needs_export(), "{stem}") } other => panic!("{stem}: {:?}", other.map(|_| ())), } @@ -173,9 +79,23 @@ fn the_stencil_output_takes_the_extension_the_shadow_or_a_refusal_naming_both() assert!(forms.iter().all(|&n| n > 0), "{forms:?}"); } -/// A render pipeline of `stage_io_vertex_position` and the fixture's fragment with a combined -/// depth/stencil attachment (none when `!attached`). -fn render(io: &[u8], stencil: &[u8], attached: bool) -> RenderPipelineDescriptor { +/// A render pipeline of `stage_io_vertex_position` and the fixture's fragment, on a device without +/// stencil export (`nvidia-rtx50-linux`), is refused naming the extension, with a combined +/// depth/stencil attachment and without one, at one sample and at four. +#[test] +fn a_render_pipeline_without_stencil_export_is_refused_naming_it() { + let (Some(io), Some(stencil)) = ( + assemble(&engine_dir().join("stage_io.ll")), + stencil_fixture(), + ) else { + return; + }; + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles/nvidia-rtx50-linux.json"); + let text = std::fs::read_to_string(path).expect("profile"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); + assert!(!dev.profile().fields().fragment.stencil_export); let function = |bc: &[u8], name: &str| { StageSource::Function(FunctionDescriptor::new( Library::from_air(bc) @@ -184,267 +104,22 @@ fn render(io: &[u8], stencil: &[u8], attached: bool) -> RenderPipelineDescriptor .expect("function"), )) }; - let mut d = RenderPipelineDescriptor::new(function(io, "stage_io_vertex_position")); - d.fragment = Some(function(stencil, ENTRY)); - if attached { - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - } - d -} - -fn refusal(r: Result) -> (Feature, Needs) { - match r { - Err(Error::Unsupported(u)) => (u.feature, u.needs), - other => panic!("{:?}", other.map(|_| ())), - } -} - -/// A render pipeline with a stencil attachment states the shadow (`R8_UINT`, declared with its -/// format) and requires its storage access; one without states none. A multisampled pipeline states -/// a shadow of its samples and requires multisampled storage images of that count and -/// `maintenance8` for the copies. Link refuses alpha to coverage as needing the extension. -#[test] -fn the_render_pipeline_states_the_shadow_and_refuses_what_it_cannot_order() { - let (Some(io), Some(stencil)) = ( - assemble(&engine_dir().join("stage_io.ll")), - stencil_fixture(), - ) else { - return; - }; - let dev = device("nvidia-rtx50-linux"); - let b = Budget::standard(); - let p = dev - .compile_render_pipeline(&render(&io, &stencil, true), &b) - .expect("pipeline"); - let s = p.graphics.shadow_stencil.expect("the shadow"); - assert_eq!((s.format, s.formatless), (vk::Format::R8_UINT, false)); - assert!(p - .requirements - .formats - .contains(&(vk::Format::R8_UINT, FormatUsage::StorageImage))); - let b_shadow = p.layout.sets.iter().flat_map(|s| &s.bindings).find(|b| { - b.source - == BindingSource::Synthetic { - stage: crate::pipeline::sym::Stage::Fragment, - binding: SyntheticBinding::ShadowStencil, + for attached in [true, false] { + for samples in [1, 4] { + let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); + d.fragment = Some(function(&stencil, ENTRY)); + if attached { + d.depth_format = Some(PixelFormat::Depth32FloatStencil8); + d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); } - }); - assert!(b_shadow.is_some(), "{:?}", p.layout.sets); - assert_eq!( - b_shadow.map(|b| b.ty), - Some(vk::DescriptorType::STORAGE_IMAGE) - ); - let none = dev - .compile_render_pipeline(&render(&io, &stencil, false), &b) - .expect("pipeline without a stencil"); - assert!(none.graphics.shadow_stencil.is_none()); - - // Four samples: a multisampled shadow, copied by image copies (`maintenance8`), of a count - // the device's storage images support; without a stencil attachment the neutral is of that - // count too, and nothing is copied. - let mut ms = render(&io, &stencil, true); - ms.raster_sample_count = 4; - let four = dev.compile_render_pipeline(&ms, &b).expect("four samples"); - let s = four - .graphics - .shadow_stencil - .expect("the multisampled shadow"); - assert_eq!( - (s.format, s.formatless, s.samples), - (vk::Format::R8_UINT, false, 4) - ); - // The shadow's writes are the product's: a function that writes no memory of its own records - // nothing of its runs, and tests each covered sample. - assert!(!four.stages.iter().any(|m| m - .precision_notes - .contains(&crate::pipeline::PrecisionNote::DeviceFragmentRuns))); - assert!(four - .requirements - .features - .contains(&VkFeature::Maintenance8)); - assert!(four - .requirements - .features - .contains(&VkFeature::ShaderStorageImageMultisample)); - assert!(four - .requirements - .properties - .contains(&VkProperty::StorageImageSampleCount(4))); - let mut ms_none = render(&io, &stencil, false); - ms_none.raster_sample_count = 4; - let four_none = dev - .compile_render_pipeline(&ms_none, &b) - .expect("four samples without a stencil"); - assert!(four_none.graphics.shadow_stencil.is_none()); - assert!(!four_none - .requirements - .features - .contains(&VkFeature::Maintenance8)); - assert!(four_none - .requirements - .properties - .contains(&VkProperty::StorageImageSampleCount(4))); - // A device without `maintenance8` cannot copy a multisampled shadow. - let no_copy = device_without("nvidia-rtx50-linux", &[VkFeature::Maintenance8]); - assert_eq!( - refusal(no_copy.compile_render_pipeline(&ms, &b)), - ( - Feature::StencilExport, - Needs::AnyOf(vec![ - vec![Capability::Extension(VkExtension::ExtShaderStencilExport)], - vec![Capability::Feature(VkFeature::Maintenance8)], - ]) - ) - ); - let mut a2c = render(&io, &stencil, true); - a2c.alpha_to_coverage = true; - assert_eq!( - refusal(dev.compile_render_pipeline(&a2c, &b)), - ( - Feature::StencilExport, - Needs::AnyOf(vec![vec![Capability::Extension( - VkExtension::ExtShaderStencilExport - )]]) - ) - ); -} - -fn draw() -> DrawCall { - DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, + d.raster_sample_count = samples; + let what = format!("attached {attached}, {samples} samples"); + match dev.compile_render_pipeline(&d, &Budget::standard()) { + Err(Error::Unsupported(u)) => { + assert_eq!((u.feature, u.needs), needs_export(), "{what}") + } + other => panic!("{what}: {:?}", other.map(|_| ())), + } + } } } - -/// The fragment push words of `state`'s draw under `p`. -fn words(p: &RenderPipeline, dev: &Device, state: &BindState) -> Result<[u32; 2], BindError> { - let plan = p.plan(dev, &state.shape())?; - let cmds = plan.instantiate_draw(state, &draw())?; - let placed = p - .interface - .push - .iter() - .flat_map(|pl| &pl.fields) - .find(|f| f.field == PushField::ShadowStencilState) - .expect("the stencil state field"); - let crate::pipeline::PushLoc::Push { offset } = placed.loc else { - panic!("the state spilled: {placed:?}") - }; - let w = cmds - .push_constants - .iter() - .find(|w| w.offset <= offset && offset + 8 <= w.offset + w.bytes.len() as u32) - .expect("the push write"); - let at = (offset - w.offset) as usize; - let word = - |i: usize| u32::from_le_bytes(w.bytes[at + 4 * i..at + 4 * i + 4].try_into().unwrap()); - Ok([word(0), word(1)]) -} - -/// The binder writes the shadow (a neutral where the pass has no stencil attachment, whose words -/// say nothing is attached), writes each face's state in the documented bits, refuses a state whose -/// stencil write could depend on the depth test as needing the extension, and refuses a pass of -/// more than one layer as not implemented. -#[test] -fn the_binder_writes_the_shadow_and_the_encoders_stencil_state() { - let (Some(io), Some(stencil)) = ( - assemble(&engine_dir().join("stage_io.ll")), - stencil_fixture(), - ) else { - return; - }; - let dev = device("nvidia-rtx50-linux"); - let b = Budget::standard(); - let p = dev - .compile_render_pipeline(&render(&io, &stencil, true), &b) - .expect("pipeline"); - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - assert_eq!( - plan.descriptors - .iter() - .filter(|w| w.source == WriteSource::ShadowStencil) - .count(), - 1, - "{:?}", - plan.descriptors - ); - - let mut state = BindState::default(); - let mut ds = DepthStencilDescriptor::default(); - ds.front_face_stencil.stencil_compare_function = CompareFunction::Less; - ds.front_face_stencil.stencil_failure_operation = StencilOperation::IncrementClamp; - ds.front_face_stencil.depth_stencil_pass_operation = StencilOperation::Replace; - ds.front_face_stencil.depth_failure_operation = StencilOperation::Replace; - ds.front_face_stencil.read_mask = 0x0F; - ds.front_face_stencil.write_mask = 0xF0; - ds.back_face_stencil.stencil_compare_function = CompareFunction::Equal; - ds.back_face_stencil.depth_stencil_pass_operation = StencilOperation::Invert; - ds.back_face_stencil.depth_failure_operation = StencilOperation::Invert; - state.depth_stencil = ds; - let [front, back] = words(&p, &dev, &state).expect("words"); - let fields = |w: u32| { - ( - w & 7, - (w >> 3) & 7, - (w >> 6) & 7, - (w >> 9) & 0xFF, - (w >> 17) & 0xFF, - w >> 31, - ) - }; - assert_eq!(fields(front), (1, 3, 2, 0x0F, 0xF0, 1)); - assert_eq!(fields(back), (2, 0, 5, 0xFF, 0xFF, 1)); - - // A depth comparison that can fail, with a face whose depth-failure and pass operations - // differ, makes the write depend on the depth test, which runs after the function. - ds.depth_compare_function = CompareFunction::Less; - state.depth_stencil = ds; - words(&p, &dev, &state).expect("equal depth-failure and pass operations"); - ds.back_face_stencil.depth_failure_operation = StencilOperation::Keep; - state.depth_stencil = ds; - match words(&p, &dev, &state) { - Err(BindError::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - ( - Feature::StencilExport, - Needs::AnyOf(vec![vec![Capability::Extension( - VkExtension::ExtShaderStencilExport - )]]) - ) - ), - other => panic!("{other:?}"), - } - // Under `Always` the depth test cannot fail. - ds.depth_compare_function = CompareFunction::Always; - state.depth_stencil = ds; - words(&p, &dev, &state).expect("an `Always` depth test"); - - let layered = BindState { - render_target_array_length: 2, - ..Default::default() - }; - match p.plan(&dev, &layered.shape()) { - Err(BindError::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - (Feature::StencilExport, Needs::NotImplemented) - ), - other => panic!("{:?}", other.map(|_| ())), - } - - // Without a stencil attachment a neutral stands in and nothing is attached. - let none = dev - .compile_render_pipeline(&render(&io, &stencil, false), &b) - .expect("pipeline without a stencil"); - let plan = none - .plan(&dev, &BindState::default().shape()) - .expect("plan"); - assert!(!plan - .descriptors - .iter() - .any(|w| w.source == WriteSource::ShadowStencil)); - let [front, back] = words(&none, &dev, &BindState::default()).expect("words"); - assert_eq!((front >> 31, back >> 31), (0, 0)); -} diff --git a/crates/metal2vulkan/src/tests/engine_tile.rs b/crates/metal2vulkan/src/tests/engine_tile.rs index 58b71dca7..163ecbc2c 100644 --- a/crates/metal2vulkan/src/tests/engine_tile.rs +++ b/crates/metal2vulkan/src/tests/engine_tile.rs @@ -53,8 +53,7 @@ use crate::pipeline::sym::{ }; use crate::pipeline::testing::{engine_dir, llvm_assemble, typed_module_with, AssembleError}; use crate::pipeline::{ - ComputePipeline, FunctionDescriptor, StageSource, StorageAttachmentView, - TileRenderPipelineDescriptor, + ComputePipeline, FunctionDescriptor, StageSource, TileRenderPipelineDescriptor, }; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; @@ -548,8 +547,6 @@ fn a_float_attachment_is_bound_through_its_bits() { == WriteSource::TileAttachment { color_index: c as u32, format: view, - view: StorageAttachmentView::Attachment, - view_alias: None, }), "{stem} {c}: {:?}", plan.descriptors @@ -1017,8 +1014,6 @@ fn a_tile_pipeline_binds_its_attachments() { == WriteSource::TileAttachment { color_index: c, format: vk::Format::R32_UINT, - view: StorageAttachmentView::Attachment, - view_alias: None, }), "{stem} {c}" ); @@ -2444,8 +2439,6 @@ fn a_normalized_attachment_is_bound_through_its_bits() { == WriteSource::TileAttachment { color_index: 0, format: view, - view: StorageAttachmentView::Attachment, - view_alias: None, }), "{stem} {entry} {pf:?}: {:?}", plan.descriptors diff --git a/crates/metal2vulkan/src/tests/engine_word_attachments.rs b/crates/metal2vulkan/src/tests/engine_word_attachments.rs index ca1c003c4..19e1c73d2 100644 --- a/crates/metal2vulkan/src/tests/engine_word_attachments.rs +++ b/crates/metal2vulkan/src/tests/engine_word_attachments.rs @@ -9,16 +9,11 @@ //! 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 orders fetch through -//! the pixel interlock: the whole render pipeline, made on the profile's device, writes the -//! attachment in the interlocked storage form (`color_writes::stored_word`), a written storage -//! attachment of `R16_UINT` without a view alias, keeping the channels the mask leaves out, and -//! no color attachment of the subpass; a blended one's fragment notes `DeviceColorConversion`; -//! its stages pass L3. Compiled without the pipeline's fetch state, such a mask or blend is the -//! device's lack of the format. +//! - 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. //! - The 8-bit sRGB formats the 5080 renders through their words (`R8Unorm_sRGB`, -//! `RG8Unorm_sRGB`) write the word too, and merge a partial mask in the interlock; a blend of one -//! is the device's lack of the format. +//! `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 @@ -214,11 +209,11 @@ fn device(stem: &str) -> Device { Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") } -/// A word attachment written under a mask of some of its channels, or blended, takes the -/// interlocked storage form in the whole pipeline on the 5080's device, a blended one noting -/// `DeviceColorConversion` (the module docs). +/// A word attachment written under a mask of some of its channels, or blended, is the device's +/// lack of the format in the whole pipeline on the 5080's device, which does not order fetch (the +/// module docs). #[test] -fn masked_and_blended_word_attachments_take_the_interlock() { +fn masked_and_blended_word_attachments_are_the_devices_lack_of_the_format() { let Some(bc) = fixture() else { return; }; @@ -229,7 +224,6 @@ fn masked_and_blended_word_attachments_take_the_interlock() { library.function(name).expect("function"), )) }; - let note = PrecisionNote::DeviceColorConversion; let mut checked = 0; for pf in FORMATS { for entry in ENTRIES { @@ -247,30 +241,11 @@ fn masked_and_blended_word_attachments_take_the_interlock() { 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]; - let pipe = dev + let e = dev .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let storage: Vec<_> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.format, u.writes, u.view_alias)) - .collect(); - assert_eq!(storage, [(0, vk::Format::R16_UINT, true, None)], "{what}"); - let kept = vk::ColorComponentFlags::known_bits() - .difference(crate::metal::state::color_write_mask(mask).expect("mask")); - assert_eq!(pipe.graphics.storage_attachments[0].kept, kept, "{what}"); - assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); - let fragment = (pipe.stages.iter()) - .find(|s| s.stage == vk::ShaderStage::FRAGMENT) - .expect("a fragment stage"); - assert_eq!( - fragment.precision_notes.contains(¬e), - blended, - "{what}: {:?}", - fragment.precision_notes - ); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } + .map(|_| ()) + .expect_err(&what); + assert!(lacks_attachment(&e), "{what}: {e}"); checked += 1; } } @@ -279,11 +254,11 @@ fn masked_and_blended_word_attachments_take_the_interlock() { assert_eq!(checked, 28); } -/// An 8-bit sRGB word attachment written under a mask of some of its channels takes the -/// interlocked storage form in the whole pipeline on the 5080's device, without a note; blended, -/// it is the device's lack of the format (Metal's sRGB blend over the word is not built). +/// 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). #[test] -fn srgb_word_attachments_merge_but_do_not_blend() { +fn srgb_word_attachments_neither_merge_nor_blend_without_an_ordered_fetch() { let Some(bc) = fixture() else { return; }; @@ -305,28 +280,11 @@ fn srgb_word_attachments_merge_but_do_not_blend() { 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]; - let made = dev.compile_render_pipeline(&d, &Budget::standard()); - if blended { - let e = made.expect_err(&what); - assert!(lacks_attachment(&e), "{what}: {e}"); - continue; - } - let pipe = made.unwrap_or_else(|e| panic!("{what}: {e}")); - let storage: Vec<_> = (pipe.graphics.storage_attachments.iter()) - .map(|u| (u.color_index, u.format, u.writes, u.view_alias)) - .collect(); - assert_eq!(storage, [(0, vk::Format::R16_UINT, true, None)], "{what}"); - assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); - for s in &pipe.stages { - assert!( - !s.precision_notes - .contains(&PrecisionNote::DeviceColorConversion), - "{what}: {:?}", - s.precision_notes - ); - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } + let e = dev + .compile_render_pipeline(&d, &Budget::standard()) + .map(|_| ()) + .expect_err(&what); + assert!(lacks_attachment(&e), "{what}: {e}"); } } } @@ -359,13 +317,7 @@ fn srgb_word_attachments_merge_over_input_attachments() { // 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, - false, - false, - 1, - )); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of([0], &r.color_attachments)); compile_with(&bc, entry, p, &inputs).expect("fragment") }; for entry in ENTRIES { @@ -391,7 +343,6 @@ fn srgb_word_attachments_merge_over_input_attachments() { (vk::Format::R16_UINT, vk::ColorComponentFlags::R, None), "{what}" ); - assert!(pipe.graphics.storage_attachments.is_empty(), "{what}"); let inputs: Vec<_> = (pipe.graphics.input_attachments.iter()) .map(|u| (u.color_index, u.input_attachment_index, u.format_class)) .collect(); @@ -432,7 +383,7 @@ fn srgb_word_attachments_merge_over_input_attachments() { } /// An `RGB9E5Float` attachment on the 5080's device renders a `float` output through an -/// `R32_UINT` view, no storage form and no conversion note; a `half` output is `NotImplemented(Format)`, and +/// `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). #[test] fn an_rgb9e5_attachment_takes_a_float_outputs_word() { @@ -479,7 +430,6 @@ fn an_rgb9e5_attachment_takes_a_float_outputs_word() { continue; } let pipe = made.unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(pipe.graphics.storage_attachments.is_empty(), "{what}"); let a = pipe.graphics.color_attachments[0].expect("attachment"); assert_eq!(a.format, vk::Format::R32_UINT, "{what}"); assert_eq!(a.write_mask, vk::ColorComponentFlags::R, "{what}"); diff --git a/crates/metal2vulkan/src/tests/golden_hashes.rs b/crates/metal2vulkan/src/tests/golden_hashes.rs index ea1203355..788e08d8b 100644 --- a/crates/metal2vulkan/src/tests/golden_hashes.rs +++ b/crates/metal2vulkan/src/tests/golden_hashes.rs @@ -15,13 +15,10 @@ //! `engine/multisample`'s render pipelines of four samples. A fragment function of a pipeline //! of four samples compiles under `LoweringInputs::multisampled`. Each framebuffer-fetch fixture //! (`engine/fragment_fetch`, `exf_*`, `exf2_fetch_unwritten`, `msf_fetch_ms`) adds its fragment -//! functions under the fetch state of a pipeline of the attachment formats its cases use, which the -//! interlocked storage form needs, and each whose cases draw multisampled (`exf_fetch_blend`, -//! `exf_fetch_count`, `msf_fetch_ms`) the same state at four samples, compiled under -//! `multisampled`: the per-sample forms. `engine/tob_renders` adds the snapshot of its own-pixel -//! texture read (`tob_read` under `LoweringInputs::snapshot_textures`) in the form that holds a -//! 16-bit float texel's code and in one of narrower codes: the two-draw copy-and-read form, which -//! the entry alone, compiled without the input, never reaches. +//! functions under the fetch state of a pipeline of the attachment formats its cases use, which a +//! write the function computes over its input attachment needs, and each whose cases draw +//! multisampled (`exf_fetch_blend`, `exf_fetch_count`, `msf_fetch_ms`) the same state at four +//! samples, compiled under `multisampled`: the per-sample form. //! //! A cell is the first 64 bits of SHA-256 over the final SPIR-V words of the subject's stage //! modules (each prefixed by its word count), or the typed outcome class of a refusal, so a new @@ -61,8 +58,8 @@ use crate::pipeline::testing::{ }; use crate::pipeline::{ ColorAttachmentDescriptor, ComputePipelineDescriptor, FramebufferFetchInputs, - FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, SlotClass, SlotRef, SnapshotForm, - Stage, StageSource, StorageImageClass, TileRenderPipelineDescriptor, VertexAttributeDescriptor, + FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, SlotClass, SlotRef, Stage, + StageSource, StorageImageClass, TileRenderPipelineDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; use crate::Budget; @@ -128,23 +125,15 @@ enum Subject { 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 interlocked storage form - /// on a device that orders fetch only through the pixel interlock, which the entry alone, - /// compiled without the state, needs. Above one sample, compiled under `multisampled`: the - /// per-sample forms. + /// 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. Fetch { entry: &'static str, formats: &'static [PixelFormat], samples: u32, }, - /// Fragment `entry` compiled under a snapshot of its texture slot 0 in `form` - /// (`LoweringInputs::snapshot_textures`), linked alone: the two-draw copy-and-read form a draw - /// that reads a texture its own subpass renders takes, which the entry alone, compiled without - /// the input, never reaches. - Snapshot { - entry: &'static str, - form: SnapshotForm, - }, /// The module does not decode: its refusal class in every column. Undecodable(String), /// The installed assembler rejects the fixture. Every committed fixture assembles with the @@ -252,10 +241,6 @@ fn pipelines(fixture: &str) -> Vec<(String, Subject)> { [1, 4].map(|samples| fetch_subject(entry, &[PixelFormat::RGBA32Float], samples)) }) .collect(), - "engine/tob_renders.ll" => [SnapshotForm::Half, SnapshotForm::Unorm8] - .into_iter() - .map(|form| snapshot_subject("tob_read", form)) - .collect(), "engine/multisample.ll" => [ "multisample_center_at_sample", "multisample_sampled_varying", @@ -303,13 +288,6 @@ fn fetch_subject( ) } -fn snapshot_subject(entry: &'static str, form: SnapshotForm) -> (String, Subject) { - ( - format!("snapshot {entry} as {form:?}"), - Subject::Snapshot { entry, form }, - ) -} - const STORAGE_FIXTURE: &str = "engine/storage_texture_write.ll"; fn storage_subject(format: PixelFormat) -> String { @@ -613,25 +591,13 @@ fn compiled(lib: &Library, subject: &Subject, dev: &Device) -> Result 1; let f = FunctionDescriptor::new(lib.function(entry)?); let c = dev.compile_function(&f, &inputs, &b)?; Ok(vec![link_standalone(c.artifact(), dev.profile())?.1]) } - Subject::Snapshot { entry, form } => { - let mut inputs = LoweringInputs::new(); - inputs.snapshot_textures.insert(snapshot_slot(), *form); - let f = FunctionDescriptor::new(lib.function(entry)?); - let c = dev.compile_function(&f, &inputs, &b)?; - Ok(vec![link_standalone(c.artifact(), dev.profile())?.1]) - } Subject::Undecodable(_) | Subject::Unassembled => { unreachable!("a subject without a library compiles nothing") } @@ -646,15 +612,6 @@ fn storage_slot() -> SlotRef { } } -/// The fragment texture slot a snapshot subject reads through its snapshot. -fn snapshot_slot() -> SlotRef { - SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 0, - } -} - fn cell(fixture: &Fixture, subject: &Subject, stem: &str, dev: &Device, what: &str) -> String { match subject { Subject::Undecodable(class) => class.clone(), diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index ac3e38f39..983912bee 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -52,17 +52,12 @@ mod engine_dynamic_libraries; mod engine_dynamic_roots; mod engine_extended_range; mod engine_fast_math_order; -mod engine_fetch_blend16; -mod engine_fetch_blend16_narrow; mod engine_fetch_blend8; -mod engine_fetch_generic_blend; -mod engine_fetch_word_read; mod engine_fill_moduli; mod engine_float_call_notes; mod engine_fpc_frames; mod engine_fragment; mod engine_fragment_depth_clamp; -mod engine_fragment_imageblock; mod engine_front_facing_byte; mod engine_function_constant_interface; mod engine_function_constant_pointers; @@ -112,7 +107,6 @@ mod engine_metal_readings; mod engine_metal_routines; mod engine_metered_walks; mod engine_metering; -mod engine_moved_writers; mod engine_multisample; mod engine_must_fallback; mod engine_name_independence; @@ -168,7 +162,6 @@ mod engine_simd_past_n; mod engine_simd_products; mod engine_simd_unit_axes; mod engine_skeleton; -mod engine_snapshot_exact; mod engine_sparse_unmapped; mod engine_spec_bits; mod engine_specialized_folds; diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index 727195131..262ded39e 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use crate::bind::{self, PlanesCopy}; use crate::device::{Device, DevicePolicy}; -use crate::error::{Error, Feature}; +use crate::error::Error; use crate::spirv::testing::{all_ones_divisions, committed_descriptions}; /// A module function at one parameter: what it is called, and its words on a device. @@ -32,10 +32,6 @@ fn modules() -> Vec { out.push((name, build)); }; for copy in PlanesCopy::ALL { - push( - format!("planes_split_module({copy:?})"), - Box::new(move |d| Ok(bind::planes_split_module(d, copy)?.spirv)), - ); for samples in [2, 4, 8] { push( format!("interleave_split_module({copy:?}, {samples})"), @@ -52,10 +48,6 @@ fn modules() -> Vec { Box::new(move |d| Ok(bind::mesh_arguments_module(d, form)?.spirv)), ); } - push( - "stencil_split_module".into(), - Box::new(|d| Ok(bind::stencil_split_module(d, Feature::Format)?.spirv)), - ); out } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 406e4c03d..c12882ec3 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -96,13 +96,7 @@ assoc-const metal2vulkan::bind::MeshArgumentsModule::SET pub const SET: u32 assoc-const metal2vulkan::bind::MeshArgumentsModule::SOURCE_BINDING pub const SOURCE_BINDING: u32 assoc-const metal2vulkan::bind::MeshArgumentsModule::STATUS_BINDING pub const STATUS_BINDING: u32 assoc-const metal2vulkan::bind::NeutralResource::SINK_BYTES pub const SINK_BYTES: u32 -assoc-const metal2vulkan::bind::PlanesCopy::ALL pub const ALL: [PlanesCopy; 6] -assoc-const metal2vulkan::bind::PlanesMergeModules::PLANES_BINDING pub const PLANES_BINDING: u32 -assoc-const metal2vulkan::bind::PlanesMergeModules::SET pub const SET: u32 -assoc-const metal2vulkan::bind::PlanesSplitModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::PlanesSplitModule::PLANES_BINDING pub const PLANES_BINDING: u32 -assoc-const metal2vulkan::bind::PlanesSplitModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::PlanesSplitModule::SOURCE_BINDING pub const SOURCE_BINDING: u32 +assoc-const metal2vulkan::bind::PlanesCopy::ALL pub const ALL: [PlanesCopy; 5] assoc-const metal2vulkan::bind::PvrtcDecode::BLOCK_BYTES pub const BLOCK_BYTES: u32 assoc-const metal2vulkan::bind::PvrtcDecode::TEXEL_BYTES pub const TEXEL_BYTES: u32 assoc-const metal2vulkan::bind::RateMapRegions::MAX_REGIONS pub const MAX_REGIONS: usize @@ -129,10 +123,6 @@ assoc-const metal2vulkan::bind::StatusBits::REPLAY_FAULT pub const REPLAY_FAULT: assoc-const metal2vulkan::bind::StatusBits::RESIDENT_MISS pub const RESIDENT_MISS: StatusBits assoc-const metal2vulkan::bind::StatusWord::ALL pub const ALL: [StatusWord; 4] assoc-const metal2vulkan::bind::StencilBit::ALL pub const ALL: [StencilBit; 8] -assoc-const metal2vulkan::bind::StencilSplitModule::DESTINATION_BINDING pub const DESTINATION_BINDING: u32 -assoc-const metal2vulkan::bind::StencilSplitModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::StencilSplitModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::StencilSplitModule::SOURCE_BINDING pub const SOURCE_BINDING: u32 assoc-const metal2vulkan::bind::TexelRows::FIRST pub const FIRST: usize assoc-const metal2vulkan::bind::TexelRows::HEIGHT pub const HEIGHT: usize assoc-const metal2vulkan::bind::TexelRows::ROW pub const ROW: usize @@ -327,13 +317,7 @@ assoc-const-value metal2vulkan::bind::MeshArgumentsModule::SET 0 assoc-const-value metal2vulkan::bind::MeshArgumentsModule::SOURCE_BINDING 0 assoc-const-value metal2vulkan::bind::MeshArgumentsModule::STATUS_BINDING 2 assoc-const-value metal2vulkan::bind::NeutralResource::SINK_BYTES 64 -assoc-const-value metal2vulkan::bind::PlanesCopy::ALL [PlanesCopy::R8, PlanesCopy::R16, PlanesCopy::R32, PlanesCopy::Rg32, PlanesCopy::Rgba32, PlanesCopy::Alpha8] -assoc-const-value metal2vulkan::bind::PlanesMergeModules::PLANES_BINDING 0 -assoc-const-value metal2vulkan::bind::PlanesMergeModules::SET 0 -assoc-const-value metal2vulkan::bind::PlanesSplitModule::LOCAL_SIZE 8 -assoc-const-value metal2vulkan::bind::PlanesSplitModule::PLANES_BINDING 1 -assoc-const-value metal2vulkan::bind::PlanesSplitModule::SET 0 -assoc-const-value metal2vulkan::bind::PlanesSplitModule::SOURCE_BINDING 0 +assoc-const-value metal2vulkan::bind::PlanesCopy::ALL [PlanesCopy::R8, PlanesCopy::R16, PlanesCopy::R32, PlanesCopy::Rg32, PlanesCopy::Rgba32] assoc-const-value metal2vulkan::bind::PvrtcDecode::BLOCK_BYTES 8 assoc-const-value metal2vulkan::bind::PvrtcDecode::TEXEL_BYTES 4 assoc-const-value metal2vulkan::bind::RateMapRegions::MAX_REGIONS 128 * 128 @@ -360,10 +344,6 @@ assoc-const-value metal2vulkan::bind::StatusBits::REPLAY_FAULT StatusBits(1 <<1) assoc-const-value metal2vulkan::bind::StatusBits::RESIDENT_MISS StatusBits(1 <<0) assoc-const-value metal2vulkan::bind::StatusWord::ALL [StatusWord::Status, StatusWord::ResidentMisses, StatusWord::ReplayFaults, StatusWord::SeqCstFences] assoc-const-value metal2vulkan::bind::StencilBit::ALL [StencilBit(0), StencilBit(1), StencilBit(2), StencilBit(3), StencilBit(4), StencilBit(5), StencilBit(6), StencilBit(7)] -assoc-const-value metal2vulkan::bind::StencilSplitModule::DESTINATION_BINDING 1 -assoc-const-value metal2vulkan::bind::StencilSplitModule::LOCAL_SIZE 8 -assoc-const-value metal2vulkan::bind::StencilSplitModule::SET 0 -assoc-const-value metal2vulkan::bind::StencilSplitModule::SOURCE_BINDING 0 assoc-const-value metal2vulkan::bind::TexelRows::FIRST 3 assoc-const-value metal2vulkan::bind::TexelRows::HEIGHT 1 assoc-const-value metal2vulkan::bind::TexelRows::ROW 2 @@ -815,7 +795,6 @@ enum metal2vulkan::bind::BoundBuffer #[cfg_attr(feature = "serde", derive(serde: enum metal2vulkan::bind::BoundTexture #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BoundTexture enum metal2vulkan::bind::BufferShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferShape enum metal2vulkan::bind::ChromaDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ChromaDecode -enum metal2vulkan::bind::CopySource #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum CopySource enum metal2vulkan::bind::DepthStencilCopy #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DepthStencilCopy enum metal2vulkan::bind::Dispatch #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Dispatch enum metal2vulkan::bind::DrawCall #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DrawCall @@ -823,7 +802,6 @@ enum metal2vulkan::bind::DrawReplayRule #[derive(Clone, Copy, Debug, PartialEq, enum metal2vulkan::bind::EtcDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum EtcDecode enum metal2vulkan::bind::EtcTexels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum EtcTexels enum metal2vulkan::bind::FieldLocation #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FieldLocation -enum metal2vulkan::bind::FragmentTests #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FragmentTests enum metal2vulkan::bind::GeneratedRefusal #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum GeneratedRefusal enum metal2vulkan::bind::HeapElement #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum HeapElement enum metal2vulkan::bind::HeapPlacement #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HeapPlacement @@ -942,7 +920,6 @@ enum metal2vulkan::pipeline::FactorLane #[cfg_attr(feature = "serde", derive(ser enum metal2vulkan::pipeline::HandleClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum HandleClass enum metal2vulkan::pipeline::ImageAccess #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ImageAccess enum metal2vulkan::pipeline::ImageDim #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ImageDim -enum metal2vulkan::pipeline::ImageblockMechanism #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ImageblockMechanism enum metal2vulkan::pipeline::KernelVariant #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum KernelVariant enum metal2vulkan::pipeline::LinkedList #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum LinkedList<'a> enum metal2vulkan::pipeline::Mechanism #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Mechanism @@ -958,12 +935,9 @@ enum metal2vulkan::pipeline::SampledType #[cfg_attr(feature = "serde", derive(se enum metal2vulkan::pipeline::SamplerRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SamplerRef enum metal2vulkan::pipeline::SlotClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum SlotClass enum metal2vulkan::pipeline::SlotInterface #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum SlotInterface -enum metal2vulkan::pipeline::SnapshotForm #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SnapshotForm -enum metal2vulkan::pipeline::SnapshotRefusal #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SnapshotRefusal enum metal2vulkan::pipeline::SpecKey #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SpecKey enum metal2vulkan::pipeline::Stage #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum Stage enum metal2vulkan::pipeline::StageSource #[derive(Clone, Debug, PartialEq, Eq)] pub enum StageSource -enum metal2vulkan::pipeline::StorageAttachmentView #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum StorageAttachmentView enum metal2vulkan::pipeline::StorageFormatClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StorageFormatClass enum metal2vulkan::pipeline::StorageImageClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StorageImageClass enum metal2vulkan::pipeline::Symbol #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum Symbol @@ -2044,10 +2018,8 @@ field metal2vulkan::bind::BindShape.argument_samplers pub argument_samplers: Arg field metal2vulkan::bind::BindShape.depth_clamp_range pub depth_clamp_range: bool field metal2vulkan::bind::BindShape.dropped_colors pub dropped_colors: BTreeSet field metal2vulkan::bind::BindShape.far_vertex_buffers pub far_vertex_buffers: BTreeSet -field metal2vulkan::bind::BindShape.fragment_tests pub fragment_tests: FragmentTests field metal2vulkan::bind::BindShape.function_tables pub function_tables: FunctionTablesShape field metal2vulkan::bind::BindShape.imageblock_size pub imageblock_size: ImageblockSize -field metal2vulkan::bind::BindShape.interlocked_colors pub interlocked_colors: BTreeSet field metal2vulkan::bind::BindShape.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::bind::BindShape.line_band pub line_band: Option field metal2vulkan::bind::BindShape.primitive_id_indices pub primitive_id_indices: Option @@ -2057,7 +2029,6 @@ field metal2vulkan::bind::BindShape.region_viewports pub region_viewports: bool field metal2vulkan::bind::BindShape.render_area pub render_area: [u32; 2] field metal2vulkan::bind::BindShape.render_target_array_length pub render_target_array_length: u32 field metal2vulkan::bind::BindShape.rotated_weights pub rotated_weights: bool -field metal2vulkan::bind::BindShape.snapshot_textures pub snapshot_textures: BTreeSet field metal2vulkan::bind::BindShape.stages pub stages: BTreeMap field metal2vulkan::bind::BindShape.tessellation_factor_buffer pub tessellation_factor_buffer: bool field metal2vulkan::bind::BindShape.tile_threadgroup pub tile_threadgroup: TileThreadgroupMemory @@ -2071,11 +2042,9 @@ field metal2vulkan::bind::BindState.depth_clamp_range pub depth_clamp_range: Opt field metal2vulkan::bind::BindState.depth_stencil pub depth_stencil: metal::state::DepthStencilDescriptor field metal2vulkan::bind::BindState.dropped_colors pub dropped_colors: BTreeSet field metal2vulkan::bind::BindState.far_vertex_buffers pub far_vertex_buffers: BTreeSet -field metal2vulkan::bind::BindState.fragment_tests pub fragment_tests: FragmentTests field metal2vulkan::bind::BindState.function_tables pub function_tables: Vec field metal2vulkan::bind::BindState.heap_placement pub heap_placement: HeapPlacement field metal2vulkan::bind::BindState.imageblock_size pub imageblock_size: ImageblockSize -field metal2vulkan::bind::BindState.interlocked_colors pub interlocked_colors: BTreeSet field metal2vulkan::bind::BindState.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::bind::BindState.line_band pub line_band: Option<(crate::pipeline::BandPrimitive, [f32; 4])> field metal2vulkan::bind::BindState.primitive_id_indices pub primitive_id_indices: Option @@ -2088,7 +2057,6 @@ field metal2vulkan::bind::BindState.render_target_array_length pub render_target field metal2vulkan::bind::BindState.resident_apart pub resident_apart: bool field metal2vulkan::bind::BindState.resident_ranges pub resident_ranges: Vec field metal2vulkan::bind::BindState.rotated_weights pub rotated_weights: bool -field metal2vulkan::bind::BindState.snapshot_textures pub snapshot_textures: BTreeSet field metal2vulkan::bind::BindState.stage_in_region pub stage_in_region: Option field metal2vulkan::bind::BindState.stages pub stages: BTreeMap field metal2vulkan::bind::BindState.tessellation_factors pub tessellation_factors: TessellationFactors @@ -2274,11 +2242,6 @@ field metal2vulkan::bind::ObjectFold.dispatch pub dispatch: [u32; 3] field metal2vulkan::bind::ObjectFold.past pub past: bool field metal2vulkan::bind::ObjectFold.pieces pub pieces: u32 field metal2vulkan::bind::ObjectFold.record pub record: [u32; 8] -field metal2vulkan::bind::PlanesMergeModules.fragment pub fragment: Arc<[u32]> -field metal2vulkan::bind::PlanesMergeModules.requirements pub requirements: Requirements -field metal2vulkan::bind::PlanesMergeModules.vertex pub vertex: Arc<[u32]> -field metal2vulkan::bind::PlanesSplitModule.requirements pub requirements: Requirements -field metal2vulkan::bind::PlanesSplitModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::PushConstantWrite.bytes pub bytes: Vec field metal2vulkan::bind::PushConstantWrite.offset pub offset: u32 field metal2vulkan::bind::PushConstantWrite.stages pub stages: vk::ShaderStageFlags @@ -2388,8 +2351,6 @@ field metal2vulkan::bind::StatusReport.replay_fault pub replay_fault: bool field metal2vulkan::bind::StatusReport.replay_faults pub replay_faults: ReplayFaults field metal2vulkan::bind::StatusReport.resident_miss pub resident_miss: bool field metal2vulkan::bind::StatusReport.resident_misses pub resident_misses: u32 -field metal2vulkan::bind::StencilSplitModule.requirements pub requirements: Requirements -field metal2vulkan::bind::StencilSplitModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::TessellationFactorBuffer.instance_stride pub instance_stride: u64 field metal2vulkan::bind::TessellationFactorBuffer.length pub length: u64 field metal2vulkan::bind::TessellationFactorBuffer.offset pub offset: u64 @@ -2483,7 +2444,6 @@ field metal2vulkan::cache::VariantKey.emulated_simdgroups pub emulated_simdgroup field metal2vulkan::cache::VariantKey.extended_range pub extended_range: BTreeMap field metal2vulkan::cache::VariantKey.flat_grid pub flat_grid: bool field metal2vulkan::cache::VariantKey.folded_groups pub folded_groups: bool -field metal2vulkan::cache::VariantKey.interlocked_colors pub interlocked_colors: BTreeSet field metal2vulkan::cache::VariantKey.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::cache::VariantKey.line_band pub line_band: Option field metal2vulkan::cache::VariantKey.merged_draws pub merged_draws: bool @@ -2495,11 +2455,9 @@ field metal2vulkan::cache::VariantKey.private_list pub private_list: bool field metal2vulkan::cache::VariantKey.psb_slots pub psb_slots: BTreeSet field metal2vulkan::cache::VariantKey.pulled_vertex_buffers pub pulled_vertex_buffers: BTreeSet field metal2vulkan::cache::VariantKey.quad_primitive_ids pub quad_primitive_ids: bool -field metal2vulkan::cache::VariantKey.read_only_tests pub read_only_tests: bool field metal2vulkan::cache::VariantKey.region_viewports pub region_viewports: bool field metal2vulkan::cache::VariantKey.replay_bindings pub replay_bindings: bool field metal2vulkan::cache::VariantKey.rotated_weights pub rotated_weights: bool -field metal2vulkan::cache::VariantKey.snapshot_textures pub snapshot_textures: BTreeMap field metal2vulkan::cache::VariantKey.srgb_textures pub srgb_textures: BTreeSet field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots: BTreeSet @@ -2949,15 +2907,7 @@ field metal2vulkan::pipeline::FetchedAttachment.equation pub equation: Option> -field metal2vulkan::pipeline::FramebufferFetchInputs.depth_or_stencil pub depth_or_stencil: bool field metal2vulkan::pipeline::FunctionDescriptor.constants pub constants: FunctionConstantValues field metal2vulkan::pipeline::FunctionDescriptor.function pub function: Function field metal2vulkan::pipeline::FunctionDescriptor.libraries pub libraries: DynamicLibraries @@ -2970,7 +2920,6 @@ field metal2vulkan::pipeline::GraphicsState.color_outputs pub color_outputs: u32 field metal2vulkan::pipeline::GraphicsState.declares_layer pub declares_layer: bool field metal2vulkan::pipeline::GraphicsState.depth_format pub depth_format: Option field metal2vulkan::pipeline::GraphicsState.dynamic_states pub dynamic_states: Vec -field metal2vulkan::pipeline::GraphicsState.fragment_imageblock pub fragment_imageblock: Option field metal2vulkan::pipeline::GraphicsState.fragment_writes_memory pub fragment_writes_memory: bool field metal2vulkan::pipeline::GraphicsState.input_attachments pub input_attachments: Vec field metal2vulkan::pipeline::GraphicsState.line_band pub line_band: Option @@ -2982,10 +2931,7 @@ field metal2vulkan::pipeline::GraphicsState.rasterizer_discard pub rasterizer_di field metal2vulkan::pipeline::GraphicsState.reads_barycentric_coord pub reads_barycentric_coord: bool field metal2vulkan::pipeline::GraphicsState.reads_primitive_id pub reads_primitive_id: bool field metal2vulkan::pipeline::GraphicsState.sample_mask pub sample_mask: Option -field metal2vulkan::pipeline::GraphicsState.shadow_stencil pub shadow_stencil: Option -field metal2vulkan::pipeline::GraphicsState.snapshot_reads pub snapshot_reads: bool field metal2vulkan::pipeline::GraphicsState.stencil_format pub stencil_format: Option -field metal2vulkan::pipeline::GraphicsState.storage_attachments pub storage_attachments: Vec field metal2vulkan::pipeline::GraphicsState.tessellation pub tessellation: Option field metal2vulkan::pipeline::GraphicsState.topology pub topology: vk::PrimitiveTopology field metal2vulkan::pipeline::GraphicsState.vertex_writes_memory pub vertex_writes_memory: bool @@ -3057,7 +3003,6 @@ field metal2vulkan::pipeline::LoweringInputs.private_list pub private_list: bool field metal2vulkan::pipeline::LoweringInputs.psb_slots pub psb_slots: BTreeSet field metal2vulkan::pipeline::LoweringInputs.push_base pub push_base: u32 field metal2vulkan::pipeline::LoweringInputs.quad_primitive_ids pub quad_primitive_ids: bool -field metal2vulkan::pipeline::LoweringInputs.read_only_tests pub read_only_tests: bool field metal2vulkan::pipeline::LoweringInputs.region_viewports pub region_viewports: bool field metal2vulkan::pipeline::LoweringInputs.render_target_array_index_varying pub render_target_array_index_varying: bool field metal2vulkan::pipeline::LoweringInputs.replay_bindings pub replay_bindings: bool @@ -3067,7 +3012,6 @@ field metal2vulkan::pipeline::LoweringInputs.rotated_factors pub rotated_factors field metal2vulkan::pipeline::LoweringInputs.rotated_weights pub rotated_weights: bool field metal2vulkan::pipeline::LoweringInputs.sample_mask pub sample_mask: Option<[u32; 4]> field metal2vulkan::pipeline::LoweringInputs.signed_color_attachments pub signed_color_attachments: BTreeSet -field metal2vulkan::pipeline::LoweringInputs.snapshot_textures pub snapshot_textures: BTreeMap field metal2vulkan::pipeline::LoweringInputs.srgb_textures pub srgb_textures: BTreeSet field metal2vulkan::pipeline::LoweringInputs.stage_input pub stage_input: Option field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: BTreeMap @@ -3224,9 +3168,6 @@ field metal2vulkan::pipeline::SamplerLevels.max_lod pub max_lod: f32 field metal2vulkan::pipeline::SamplerLevels.min_lod pub min_lod: f32 field metal2vulkan::pipeline::SamplerSlot.compare pub compare: bool field metal2vulkan::pipeline::SamplerSlot.coordinate_sensitive pub coordinate_sensitive: bool -field metal2vulkan::pipeline::ShadowStencilUse.format pub format: vk::Format -field metal2vulkan::pipeline::ShadowStencilUse.formatless pub formatless: bool -field metal2vulkan::pipeline::ShadowStencilUse.samples pub samples: u32 field metal2vulkan::pipeline::SlotRef.class pub class: SlotClass field metal2vulkan::pipeline::SlotRef.index pub index: u32 field metal2vulkan::pipeline::SlotRef.stage pub stage: Stage @@ -3262,8 +3203,6 @@ field metal2vulkan::pipeline::StageModule.private_bytes pub private_bytes: u64 field metal2vulkan::pipeline::StageModule.reconvergence pub reconvergence: Reconvergence field metal2vulkan::pipeline::StageModule.required_subgroup_size pub required_subgroup_size: Option field metal2vulkan::pipeline::StageModule.rounded_colors pub rounded_colors: Vec -field metal2vulkan::pipeline::StageModule.snapshot_refusals pub snapshot_refusals: Vec<(u32, SnapshotRefusal)> -field metal2vulkan::pipeline::StageModule.snapshot_textures pub snapshot_textures: Vec field metal2vulkan::pipeline::StageModule.specialization pub specialization: SpecializationLayout field metal2vulkan::pipeline::StageModule.specialized_notes pub specialized_notes: Vec field metal2vulkan::pipeline::StageModule.spirv pub spirv: Arc<[u32]> @@ -3273,13 +3212,6 @@ field metal2vulkan::pipeline::StageModule.stats pub stats: ModuleStats field metal2vulkan::pipeline::StageModule.strategies pub strategies: StrategyCensus field metal2vulkan::pipeline::StandaloneModule.layout pub layout: PipelineLayout field metal2vulkan::pipeline::StandaloneModule.words pub words: Vec -field metal2vulkan::pipeline::StorageAttachmentUse.color_index pub color_index: u32 -field metal2vulkan::pipeline::StorageAttachmentUse.format pub format: vk::Format -field metal2vulkan::pipeline::StorageAttachmentUse.formatless pub formatless: bool -field metal2vulkan::pipeline::StorageAttachmentUse.kept pub kept: vk::ColorComponentFlags -field metal2vulkan::pipeline::StorageAttachmentUse.view pub view: StorageAttachmentView -field metal2vulkan::pipeline::StorageAttachmentUse.view_alias pub view_alias: Option -field metal2vulkan::pipeline::StorageAttachmentUse.writes pub writes: bool field metal2vulkan::pipeline::StorageImageChoice.alias pub alias: Option field metal2vulkan::pipeline::StorageImageChoice.class pub class: StorageImageClass field metal2vulkan::pipeline::StorageImageChoice.numeric pub numeric: Option @@ -3448,14 +3380,11 @@ fn metal2vulkan::bind::interleave_split_module pub fn interleave_split_module(de fn metal2vulkan::bind::mesh_arguments_module pub fn mesh_arguments_module(device: &Device, form: MeshArgumentsForm) -> Result fn metal2vulkan::bind::metal_object_grid pub fn metal_object_grid(groups: [u32; 3], threads: [u32; 3], direct: bool) -> Option<([u32; 3], [u32; 3])> fn metal2vulkan::bind::part_texels pub fn part_texels(limits: &Limits) -> u64 -fn metal2vulkan::bind::planes_merge_modules pub fn planes_merge_modules(device: &Device, copy: PlanesCopy) -> Result -fn metal2vulkan::bind::planes_split_module pub fn planes_split_module(device: &Device, copy: PlanesCopy) -> Result fn metal2vulkan::bind::primitive_wrap pub fn primitive_wrap(reference: u64, geometry_table_offset: u32) -> Result fn metal2vulkan::bind::replay_preprocess pub fn replay_preprocess(device: &Device, state: &BindState, execution: &ReplayExecution, variants: &[ReplayVariant]) -> Result fn metal2vulkan::bind::replay_preprocess_generated pub fn replay_preprocess_generated(device: &Device, state: &BindState, execution: &ReplayExecution, variants: &[ReplayVariant], generated: &[GeneratedVariant<'_>]) -> Result fn metal2vulkan::bind::replay_preprocess_module pub fn replay_preprocess_module(device: &Device) -> Result fn metal2vulkan::bind::sampler_desc pub fn sampler_desc(device: &crate::device::Device, desc: &crate::bind::state::SamplerDescriptor, use_: SamplerUse, opaque_black: OpaqueBlackBorder, image_format: Option) -> Result -fn metal2vulkan::bind::stencil_split_module pub fn stencil_split_module(device: &Device, feature: Feature) -> Result fn metal2vulkan::bind::texel_buffer_parts pub fn texel_buffer_parts(limits: &Limits, texels: u64) -> u32 fn metal2vulkan::bind::ycbcr_read pub fn ycbcr_read(codes: YCbCrCodes, (range, matrix): (YCbCrRange, YCbCrMatrix), [y, cb, cr]: [u16; 3]) -> [u16; 3] fn metal2vulkan::bind::ycbcr_texel pub fn ycbcr_texel(range: YCbCrRange, matrix: YCbCrMatrix, y: u8, cb: u8, cr: u8) -> [u16; 3] @@ -6868,7 +6797,6 @@ method metal2vulkan::bind::EtcDecode::texel_bytes pub fn texel_bytes(self, texel method metal2vulkan::bind::EtcDecode::texel_format pub fn texel_format(self, texels: EtcTexels) -> Format method metal2vulkan::bind::ExecutionStatus::decode pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport method metal2vulkan::bind::ExecutionStatus::initial pub const fn initial() -> [u8; ExecutionStatus::BYTES] -method metal2vulkan::bind::FragmentTests::of pub fn of(depth_stencil: &metal::state::DepthStencilDescriptor, depth: bool, stencil: bool, counted: bool) -> FragmentTests method metal2vulkan::bind::FunctionTableSnapshot::byte_len pub fn byte_len(&self) -> u64 method metal2vulkan::bind::FunctionTableSnapshot::bytes pub fn bytes<'a>(&self, tables: impl IntoIterator) -> Option> method metal2vulkan::bind::FunctionTableSnapshot::of pub fn of(sizes: impl IntoIterator) -> Option @@ -6909,7 +6837,6 @@ method metal2vulkan::bind::NeutralResource::for_image pub fn for_image(class: &I method metal2vulkan::bind::NeutralResource::format pub fn format(&self) -> Option method metal2vulkan::bind::ObjectFold::bytes pub fn bytes(&self) -> Vec method metal2vulkan::bind::PlanesCopy::format pub fn format(self) -> Format -method metal2vulkan::bind::PlanesCopy::moves_bits pub fn moves_bits(self) -> bool method metal2vulkan::bind::PvrtcDecode::block_extent pub fn block_extent(self) -> [u32; 2] method metal2vulkan::bind::PvrtcDecode::decode pub fn decode(self, blocks: &[u8], [width, height, depth]: [u32; 3]) -> Vec method metal2vulkan::bind::PvrtcDecode::decode_rows pub fn decode_rows(self, blocks: &[u8], [width, height]: [u32; 2], [first, rows]: [u32; 2], out: &mut [u8]) @@ -7306,7 +7233,7 @@ 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], depth_or_stencil: bool, alpha_to_coverage: bool, max_vertex_amplification_count: u32) -> FramebufferFetchInputs +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 @@ -7383,8 +7310,6 @@ method metal2vulkan::pipeline::SampledLevels::lowest_lod pub fn lowest_lod(&self method metal2vulkan::pipeline::SamplerLevels::finite_texels pub fn finite_texels(format: vk::Format) -> bool method metal2vulkan::pipeline::SamplerLevels::of pub fn of(desc: &vk::SamplerDesc, finite_texels: bool) -> SamplerLevels method metal2vulkan::pipeline::SamplerRef::constexpr_address_modes pub fn constexpr_address_modes(self) -> Option<[crate::metal::SamplerAddressMode; 3]> -method metal2vulkan::pipeline::SnapshotForm::format pub fn format(self) -> vk::Format -method metal2vulkan::pipeline::SnapshotForm::of pub fn of(format: vk::Format, ty: SampledType) -> SnapshotForm method metal2vulkan::pipeline::SpecTest::differ pub fn differ(key: SpecKey, mask: u32, bits: u32) -> SpecTest method metal2vulkan::pipeline::SpecTest::equal pub fn equal(key: SpecKey, mask: u32, bits: u32) -> SpecTest method metal2vulkan::pipeline::StageEntries::counts pub fn counts(&self) -> (u64, u64) @@ -7396,11 +7321,6 @@ method metal2vulkan::pipeline::StageInputDescriptor::new pub fn new() -> StageIn method metal2vulkan::pipeline::StageInputLayoutDescriptor::new pub fn new(stride: Option) -> StageInputLayoutDescriptor method metal2vulkan::pipeline::StageModule::precision_notes_bound pub fn precision_notes_bound(&self, specialization: &SpecializationKey, bound: &dyn Fn(SpecKey) -> Option) -> Vec method metal2vulkan::pipeline::StageModule::spirv_bytes pub fn spirv_bytes(&self) -> Vec -method metal2vulkan::pipeline::StorageAttachmentUse::new pub fn new(color_index: u32, format: vk::Format, writes: bool, formatless: bool, view: StorageAttachmentView) -> StorageAttachmentUse -method metal2vulkan::pipeline::StorageAttachmentUse::view_alias_of pub fn view_alias_of(format: vk::Format, profile: &DeviceProfile) -> Option -method metal2vulkan::pipeline::StorageAttachmentUse::view_format pub fn view_format(&self) -> vk::Format -method metal2vulkan::pipeline::StorageAttachmentUse::with_kept pub fn with_kept(self, kept: vk::ColorComponentFlags) -> StorageAttachmentUse -method metal2vulkan::pipeline::StorageAttachmentUse::with_view_alias pub fn with_view_alias(self, view_alias: vk::Format) -> StorageAttachmentUse method metal2vulkan::pipeline::StorageImageChoice::new pub fn new(vk_format: vk::Format, class: StorageImageClass) -> StorageImageChoice method metal2vulkan::pipeline::TextureAccess::new pub fn new(sample: bool, read: bool, write: bool) -> TextureAccess method metal2vulkan::pipeline::TileRenderPipelineDescriptor::new pub fn new(tile: StageSource) -> TileRenderPipelineDescriptor @@ -7783,8 +7703,6 @@ struct metal2vulkan::bind::MeshGridLimits #[derive(Clone, Copy, Debug, PartialEq struct metal2vulkan::bind::MeshGridRule #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshGridRule struct metal2vulkan::bind::MetalInstance #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct MetalInstance struct metal2vulkan::bind::ObjectFold #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ObjectFold -struct metal2vulkan::bind::PlanesMergeModules #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct PlanesMergeModules -struct metal2vulkan::bind::PlanesSplitModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct PlanesSplitModule struct metal2vulkan::bind::PushConstantWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushConstantWrite struct metal2vulkan::bind::PushFieldPlacement #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushFieldPlacement struct metal2vulkan::bind::PushTemplate #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushTemplate @@ -7815,7 +7733,6 @@ struct metal2vulkan::bind::StageTable #[cfg_attr(feature = "serde", derive(serde struct metal2vulkan::bind::StatusBits #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct StatusBits(pub u32) struct metal2vulkan::bind::StatusReport #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StatusReport struct metal2vulkan::bind::StencilBit #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct StencilBit(u8) -struct metal2vulkan::bind::StencilSplitModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct StencilSplitModule struct metal2vulkan::bind::TessellationFactorBuffer #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TessellationFactorBuffer struct metal2vulkan::bind::TessellationFactors #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct TessellationFactors struct metal2vulkan::bind::TexelRows #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct TexelRows @@ -7923,7 +7840,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::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::FragmentImageblock #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct FragmentImageblock 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) @@ -7955,7 +7871,6 @@ struct metal2vulkan::pipeline::SampledLevels #[cfg_attr(feature = "serde", deriv struct metal2vulkan::pipeline::SamplerArray #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerArray struct metal2vulkan::pipeline::SamplerLevels #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerLevels struct metal2vulkan::pipeline::SamplerSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerSlot -struct metal2vulkan::pipeline::ShadowStencilUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ShadowStencilUse struct metal2vulkan::pipeline::SlotRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SlotRef struct metal2vulkan::pipeline::SpecClause #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct SpecClause struct metal2vulkan::pipeline::SpecConstant #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SpecConstant @@ -7968,7 +7883,6 @@ struct metal2vulkan::pipeline::StageInputDescriptor #[cfg_attr(feature = "serde" struct metal2vulkan::pipeline::StageInputLayoutDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct StageInputLayoutDescriptor struct metal2vulkan::pipeline::StageModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct StageModule struct metal2vulkan::pipeline::StandaloneModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct StandaloneModule -struct metal2vulkan::pipeline::StorageAttachmentUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StorageAttachmentUse struct metal2vulkan::pipeline::StorageImageChoice #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct StorageImageChoice struct metal2vulkan::pipeline::StrategyCensus #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StrategyCensus struct metal2vulkan::pipeline::StrategyUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StrategyUse @@ -9470,7 +9384,6 @@ variant metal2vulkan-runtime::PrecisionNote::TessellationFactorScale Tessellatio variant metal2vulkan-runtime::PrecisionNote::TessellationFractionalSpacing TessellationFractionalSpacing variant metal2vulkan-runtime::PrecisionNote::TessellationTriangleOrder TessellationTriangleOrder variant metal2vulkan-runtime::PrecisionNote::TessellationWinding TessellationWinding -variant metal2vulkan-runtime::PrecisionNote::UnmeasuredFetchBlend UnmeasuredFetchBlend variant metal2vulkan-runtime::PrecisionNote::UnmeasuredGroupSpeculation UnmeasuredGroupSpeculation variant metal2vulkan-runtime::PrecisionNote::UnorderedFetchWithinDraw UnorderedFetchWithinDraw variant metal2vulkan-runtime::PrecisionNote::ViewBaseTexelOffset ViewBaseTexelOffset @@ -9574,9 +9487,7 @@ variant metal2vulkan-runtime::RenderPipelineKind::DepthStencilFormats DepthStenc variant metal2vulkan-runtime::RenderPipelineKind::DeviceFeature DeviceFeature variant metal2vulkan-runtime::RenderPipelineKind::DrawInput DrawInput variant metal2vulkan-runtime::RenderPipelineKind::DynamicState DynamicState -variant metal2vulkan-runtime::RenderPipelineKind::Imageblock Imageblock variant metal2vulkan-runtime::RenderPipelineKind::SampleCount SampleCount -variant metal2vulkan-runtime::RenderPipelineKind::ShaderStencil ShaderStencil variant metal2vulkan-runtime::RenderPipelineKind::Specialization Specialization variant metal2vulkan-runtime::RenderPipelineKind::SynthesizedStages SynthesizedStages variant metal2vulkan-runtime::RenderPipelineKind::Tessellation Tessellation @@ -9668,15 +9579,13 @@ variant metal2vulkan::bind::BufferShape::Buffer Buffer { attribute_stride: Optio variant metal2vulkan::bind::BufferShape::Bytes Bytes { attribute_stride: Option } variant metal2vulkan::bind::ChromaDecode::Bgrg Bgrg variant metal2vulkan::bind::ChromaDecode::Gbgr Gbgr -variant metal2vulkan::bind::CopySource::Aspect Aspect -variant metal2vulkan::bind::CopySource::Shadow Shadow variant metal2vulkan::bind::DepthStencilCopy::Depth Depth variant metal2vulkan::bind::DepthStencilCopy::Depth16Bits Depth16Bits variant metal2vulkan::bind::DepthStencilCopy::Depth16Code Depth16Code variant metal2vulkan::bind::DepthStencilCopy::DepthBits DepthBits variant metal2vulkan::bind::DepthStencilCopy::StencilBits StencilBits -variant metal2vulkan::bind::DepthStencilCopy::StencilExport StencilExport { source: CopySource } -variant metal2vulkan::bind::DepthStencilCopy::StencilPlane StencilPlane { source: CopySource, bit: StencilBit } +variant metal2vulkan::bind::DepthStencilCopy::StencilExport StencilExport +variant metal2vulkan::bind::DepthStencilCopy::StencilPlane StencilPlane { bit: StencilBit } variant metal2vulkan::bind::Dispatch::ThreadgroupRange ThreadgroupRange { groups: [u32; 3], first: [u32; 3], count: [u32; 3], threads_per_group: [u32; 3] } variant metal2vulkan::bind::Dispatch::Threadgroups Threadgroups { groups: [u32; 3], threads_per_group: [u32; 3] } variant metal2vulkan::bind::Dispatch::ThreadgroupsIndirect ThreadgroupsIndirect { indirect: IndirectRef, threads_per_group: [u32; 3] } @@ -9692,7 +9601,6 @@ variant metal2vulkan::bind::DrawCall::Primitives Primitives { vertex_start: u32, variant metal2vulkan::bind::DrawReplayRule::Amplified Amplified variant metal2vulkan::bind::DrawReplayRule::ArgumentsOnCpu ArgumentsOnCpu variant metal2vulkan::bind::DrawReplayRule::CommandTypes CommandTypes -variant metal2vulkan::bind::DrawReplayRule::FragmentImageblock FragmentImageblock variant metal2vulkan::bind::DrawReplayRule::FragmentWritesMemory FragmentWritesMemory variant metal2vulkan::bind::DrawReplayRule::IndexedPrimitiveIds IndexedPrimitiveIds variant metal2vulkan::bind::DrawReplayRule::InputAttachments InputAttachments @@ -9701,7 +9609,6 @@ variant metal2vulkan::bind::DrawReplayRule::NoDraws NoDraws variant metal2vulkan::bind::DrawReplayRule::Operations Operations(u32) variant metal2vulkan::bind::DrawReplayRule::OwnPipelineStates OwnPipelineStates variant metal2vulkan::bind::DrawReplayRule::PrimitiveTypes PrimitiveTypes(u8) -variant metal2vulkan::bind::DrawReplayRule::ShaderStencil ShaderStencil variant metal2vulkan::bind::DrawReplayRule::SharedSlotTable SharedSlotTable variant metal2vulkan::bind::DrawReplayRule::VertexAttributes VertexAttributes variant metal2vulkan::bind::DrawReplayRule::VertexWritesMemory VertexWritesMemory @@ -9716,11 +9623,6 @@ variant metal2vulkan::bind::EtcTexels::Compact Compact variant metal2vulkan::bind::EtcTexels::Float Float variant metal2vulkan::bind::FieldLocation::ArgumentTable ArgumentTable { offset: u32 } variant metal2vulkan::bind::FieldLocation::PushWindow PushWindow { offset: u32 } -variant metal2vulkan::bind::FragmentTests::Any Any -variant metal2vulkan::bind::FragmentTests::Depth Depth { writes: bool } -variant metal2vulkan::bind::FragmentTests::Drop Drop -variant metal2vulkan::bind::FragmentTests::Pass Pass -variant metal2vulkan::bind::FragmentTests::Stencil Stencil variant metal2vulkan::bind::GeneratedRefusal::Descriptors Descriptors { index: usize } variant metal2vulkan::bind::GeneratedRefusal::NoComputePipelineBinding NoComputePipelineBinding variant metal2vulkan::bind::GeneratedRefusal::NotEnabled NotEnabled @@ -9759,7 +9661,6 @@ variant metal2vulkan::bind::PlanDiagnostic::CrossClassHeapNeutral CrossClassHeap variant metal2vulkan::bind::PlanDiagnostic::CrossClassNeutral CrossClassNeutral { slot: SlotRef, substituted: NeutralResource } variant metal2vulkan::bind::PlanDiagnostic::IncompatibleBinding IncompatibleBinding { slot: SlotRef, substituted: NeutralResource } variant metal2vulkan::bind::PlanDiagnostic::IncompatibleHeapEntry IncompatibleHeapEntry { class: HandleClass, element: u32, source: HeapSource, substituted: NeutralResource } -variant metal2vulkan::bind::PlanesCopy::Alpha8 Alpha8 variant metal2vulkan::bind::PlanesCopy::R16 R16 variant metal2vulkan::bind::PlanesCopy::R32 R32 variant metal2vulkan::bind::PlanesCopy::R8 R8 @@ -9771,7 +9672,6 @@ variant metal2vulkan::bind::PushHole::ExecutionStatusAddress ExecutionStatusAddr variant metal2vulkan::bind::PushHole::MergedDrawAddress MergedDrawAddress { stages: vk::ShaderStageFlags, offset: u32 } variant metal2vulkan::bind::PushHole::ReplayRegionAddress ReplayRegionAddress { stages: vk::ShaderStageFlags, offset: u32 } variant metal2vulkan::bind::PushHole::RootTableAddress RootTableAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::SnapshotPhase SnapshotPhase { stages: vk::ShaderStageFlags, offset: u32 } variant metal2vulkan::bind::RateMapError::ExtentMismatch ExtentMismatch { layer: usize, axis: usize } variant metal2vulkan::bind::RateMapError::Granularity Granularity { granularity: u32 } variant metal2vulkan::bind::RateMapError::LayerCount LayerCount { count: usize } @@ -9859,13 +9759,11 @@ variant metal2vulkan::bind::WriteSource::InlineBytes InlineBytes { slot: SlotRef variant metal2vulkan::bind::WriteSource::Neutral Neutral(NeutralResource) variant metal2vulkan::bind::WriteSource::PatchIndices PatchIndices { min_bytes: u32 } variant metal2vulkan::bind::WriteSource::Sampler Sampler { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder } -variant metal2vulkan::bind::WriteSource::ShadowStencil ShadowStencil -variant metal2vulkan::bind::WriteSource::SnapshotTexels SnapshotTexels { slot: u32 } variant metal2vulkan::bind::WriteSource::TessellationFactors TessellationFactors variant metal2vulkan::bind::WriteSource::TexelBuffer TexelBuffer { slot: SlotRef, format: vk::Format, window: Window } variant metal2vulkan::bind::WriteSource::TexelRows TexelRows { slot: SlotRef, format: vk::Format } variant metal2vulkan::bind::WriteSource::Texture Texture { slot: SlotRef, view: ImageViewDesc } -variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_index: u32, format: vk::Format, view: StorageAttachmentView, view_alias: Option } +variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_index: u32, format: vk::Format } variant metal2vulkan::bind::WriteSource::TileMap TileMap { slot: SlotRef } variant metal2vulkan::bind::WriteSource::TileMemory TileMemory { bytes: u64 } variant metal2vulkan::bind::WriteSource::YCbCrInPlace YCbCrInPlace { slot: SlotRef } @@ -10523,7 +10421,6 @@ 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::OneColorChannel OneColorChannel variant metal2vulkan::error::ExtendedRangeBlend::Output Output variant metal2vulkan::error::Feature::AddressSpace AddressSpace(u32) variant metal2vulkan::error::Feature::AgxUnmodeled AgxUnmodeled @@ -10745,7 +10642,6 @@ variant metal2vulkan::error::PrivateRenderField::FragmentDepthCompareClamp Fragm variant metal2vulkan::error::PrivateRenderField::LogicOperation LogicOperation variant metal2vulkan::error::PrivateRenderField::PointSmooth PointSmooth variant metal2vulkan::error::PrivateRenderField::SampleCoverage SampleCoverage -variant metal2vulkan::error::PrivateRenderField::SampleMask SampleMask variant metal2vulkan::error::PrivateRenderField::TextureWriteRounding TextureWriteRounding variant metal2vulkan::error::Retry::Later Later variant metal2vulkan::error::Retry::Never Never @@ -10879,7 +10775,6 @@ variant metal2vulkan::pipeline::BindingSource::Sampler Sampler(SlotRef) variant metal2vulkan::pipeline::BindingSource::SamplerArray SamplerArray { stage: Stage, compare: bool, integer: bool } variant metal2vulkan::pipeline::BindingSource::SeparateSampler SeparateSampler { stage: Stage, sampler: CombinedSampler } variant metal2vulkan::pipeline::BindingSource::SeparateTexture SeparateTexture { texture: SlotRef, sampler: CombinedSampler } -variant metal2vulkan::pipeline::BindingSource::SnapshotTexels SnapshotTexels(u32) variant metal2vulkan::pipeline::BindingSource::Synthetic Synthetic { stage: Stage, binding: SyntheticBinding } variant metal2vulkan::pipeline::BindingSource::Texture Texture(SlotRef) variant metal2vulkan::pipeline::BindingSource::TileAttachment TileAttachment(u32) @@ -10916,7 +10811,6 @@ variant metal2vulkan::pipeline::ImageDim::Cube Cube variant metal2vulkan::pipeline::ImageDim::D1 D1 variant metal2vulkan::pipeline::ImageDim::D2 D2 variant metal2vulkan::pipeline::ImageDim::D3 D3 -variant metal2vulkan::pipeline::ImageblockMechanism::StorageImageInterlock StorageImageInterlock variant metal2vulkan::pipeline::KernelVariant::EmulatedSimdgroups EmulatedSimdgroups variant metal2vulkan::pipeline::KernelVariant::PartialThreadgroups PartialThreadgroups variant metal2vulkan::pipeline::KernelVariant::Plain Plain @@ -11024,7 +10918,6 @@ variant metal2vulkan::pipeline::PrecisionNote::TessellationFactorScale Tessellat variant metal2vulkan::pipeline::PrecisionNote::TessellationFractionalSpacing TessellationFractionalSpacing variant metal2vulkan::pipeline::PrecisionNote::TessellationTriangleOrder TessellationTriangleOrder variant metal2vulkan::pipeline::PrecisionNote::TessellationWinding TessellationWinding -variant metal2vulkan::pipeline::PrecisionNote::UnmeasuredFetchBlend UnmeasuredFetchBlend variant metal2vulkan::pipeline::PrecisionNote::UnmeasuredGroupSpeculation UnmeasuredGroupSpeculation variant metal2vulkan::pipeline::PrecisionNote::UnorderedFetchWithinDraw UnorderedFetchWithinDraw variant metal2vulkan::pipeline::PrecisionNote::ViewBaseTexelOffset ViewBaseTexelOffset @@ -11058,14 +10951,11 @@ variant metal2vulkan::pipeline::PushField::PrivateArenaAddress PrivateArenaAddre variant metal2vulkan::pipeline::PushField::RenderTargetArrayLength RenderTargetArrayLength variant metal2vulkan::pipeline::PushField::ReplayRegionAddress ReplayRegionAddress variant metal2vulkan::pipeline::PushField::RootTableAddress RootTableAddress -variant metal2vulkan::pipeline::PushField::ShadowStencilState ShadowStencilState variant metal2vulkan::pipeline::PushField::SlotBindOffset SlotBindOffset(SlotRef) variant metal2vulkan::pipeline::PushField::SlotBounds SlotBounds(SlotRef) variant metal2vulkan::pipeline::PushField::SlotGuestBase SlotGuestBase(SlotRef) -variant metal2vulkan::pipeline::PushField::SnapshotPhase SnapshotPhase variant metal2vulkan::pipeline::PushField::StageInRegion StageInRegion variant metal2vulkan::pipeline::PushField::StageInStride StageInStride(u32) -variant metal2vulkan::pipeline::PushField::StorageKeptChannels StorageKeptChannels variant metal2vulkan::pipeline::PushField::TailWord TailWord variant metal2vulkan::pipeline::PushField::TessellationFactorAddress TessellationFactorAddress variant metal2vulkan::pipeline::PushField::TessellationFactorInstanceStride TessellationFactorInstanceStride @@ -11093,7 +10983,6 @@ variant metal2vulkan::pipeline::ResourceKind::Sampler Sampler variant metal2vulkan::pipeline::ResourceKind::SamplerArray SamplerArray { compare: bool, integer: bool } variant metal2vulkan::pipeline::ResourceKind::SeparateSampler SeparateSampler(SamplerRef) variant metal2vulkan::pipeline::ResourceKind::SeparateTexture SeparateTexture(SamplerRef) -variant metal2vulkan::pipeline::ResourceKind::SnapshotTexels SnapshotTexels(u32) variant metal2vulkan::pipeline::ResourceKind::Synthetic Synthetic(SyntheticBinding) variant metal2vulkan::pipeline::ResourceKind::Texture Texture variant metal2vulkan::pipeline::ResourceKind::TileAttachment TileAttachment(u32) @@ -11125,7 +11014,6 @@ 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::FragmentImageblock FragmentImageblock { words: u32, writes: bool, master: Hash256, data_size: u32, alignment: u32 } variant metal2vulkan::pipeline::RuntimeFact::FramebufferFetch FramebufferFetch { color: u32 } variant metal2vulkan::pipeline::RuntimeFact::FunctionTableRange FunctionTableRange { addressed: bool } variant metal2vulkan::pipeline::RuntimeFact::GridTiles GridTiles @@ -11138,11 +11026,9 @@ variant metal2vulkan::pipeline::RuntimeFact::HeapWriteRounding HeapWriteRounding variant metal2vulkan::pipeline::RuntimeFact::ImageViewShape ImageViewShape { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::ImageblockSize ImageblockSize { cell_bytes: u32 } variant metal2vulkan::pipeline::RuntimeFact::IndirectGroupCount IndirectGroupCount -variant metal2vulkan::pipeline::RuntimeFact::InterlockedFramebufferFetch InterlockedFramebufferFetch { color: u32, format: crate::vk::Format, writes: bool, early_tests: bool, kept: crate::vk::ColorComponentFlags, blend: Option, rounded: bool } variant metal2vulkan::pipeline::RuntimeFact::LocalSizeConstraint LocalSizeConstraint { multiple: u32 } variant metal2vulkan::pipeline::RuntimeFact::LocalSizeLimits LocalSizeLimits variant metal2vulkan::pipeline::RuntimeFact::MergedDraws MergedDraws -variant metal2vulkan::pipeline::RuntimeFact::MovableStorageWrites MovableStorageWrites { early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::ObjectThreadgroupArena ObjectThreadgroupArena { static_bytes: u32, payload: Option } variant metal2vulkan::pipeline::RuntimeFact::OneRow OneRow variant metal2vulkan::pipeline::RuntimeFact::OpenClLineTexture OpenClLineTexture { slot: SlotRef } @@ -11164,7 +11050,6 @@ variant metal2vulkan::pipeline::RuntimeFact::RowLockstep RowLockstep variant metal2vulkan::pipeline::RuntimeFact::SampleCount SampleCount variant metal2vulkan::pipeline::RuntimeFact::SamplerCoordinates SamplerCoordinates { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::SamplerReduction SamplerReduction { slot: SlotRef } -variant metal2vulkan::pipeline::RuntimeFact::ShadowStencil ShadowStencil { formatless: bool, multisampled: bool } variant metal2vulkan::pipeline::RuntimeFact::SimdgroupEmulation SimdgroupEmulation { bytes_per_simdgroup: u32, arena: Option } variant metal2vulkan::pipeline::RuntimeFact::SparseTexture SparseTexture { slot: SlotRef, sparse_arm: bool, tile_map: bool } variant metal2vulkan::pipeline::RuntimeFact::SparseTextureWrites SparseTextureWrites { slot: SlotRef, atomic: bool } @@ -11177,7 +11062,6 @@ variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevelViews StorageTex variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevels StorageTextureLevels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTextureNumericType { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureWriteRounding StorageTextureWriteRounding { slot: SlotRef, halves: bool } -variant metal2vulkan::pipeline::RuntimeFact::TestedStorageWrites TestedStorageWrites { early_tests: bool, early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferParts TexelBufferParts { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelRows TexelRows { slot: SlotRef } @@ -11211,28 +11095,6 @@ variant metal2vulkan::pipeline::SlotClass::Texture Texture variant metal2vulkan::pipeline::SlotInterface::Buffer Buffer(BufferSlot) variant metal2vulkan::pipeline::SlotInterface::Sampler Sampler(SamplerSlot) variant metal2vulkan::pipeline::SlotInterface::Texture Texture(TextureSlot) -variant metal2vulkan::pipeline::SnapshotForm::Bits Bits -variant metal2vulkan::pipeline::SnapshotForm::Half Half -variant metal2vulkan::pipeline::SnapshotForm::Sint16 Sint16 -variant metal2vulkan::pipeline::SnapshotForm::Sint8 Sint8 -variant metal2vulkan::pipeline::SnapshotForm::Snorm16 Snorm16 -variant metal2vulkan::pipeline::SnapshotForm::Snorm8 Snorm8 -variant metal2vulkan::pipeline::SnapshotForm::Uint16 Uint16 -variant metal2vulkan::pipeline::SnapshotForm::Uint8 Uint8 -variant metal2vulkan::pipeline::SnapshotForm::Unorm16 Unorm16 -variant metal2vulkan::pipeline::SnapshotForm::Unorm8 Unorm8 -variant metal2vulkan::pipeline::SnapshotRefusal::Atomic Atomic -variant metal2vulkan::pipeline::SnapshotRefusal::Branch Branch -variant metal2vulkan::pipeline::SnapshotRefusal::Coherent Coherent -variant metal2vulkan::pipeline::SnapshotRefusal::Derivative Derivative -variant metal2vulkan::pipeline::SnapshotRefusal::GroupOperation GroupOperation -variant metal2vulkan::pipeline::SnapshotRefusal::ImageWrite ImageWrite -variant metal2vulkan::pipeline::SnapshotRefusal::Interlock Interlock -variant metal2vulkan::pipeline::SnapshotRefusal::Other Other -variant metal2vulkan::pipeline::SnapshotRefusal::Sample Sample -variant metal2vulkan::pipeline::SnapshotRefusal::Store Store -variant metal2vulkan::pipeline::SnapshotRefusal::UndefinedOperand UndefinedOperand -variant metal2vulkan::pipeline::SnapshotRefusal::WritesMemory WritesMemory variant metal2vulkan::pipeline::SpecKey::AmplificationCount AmplificationCount variant metal2vulkan::pipeline::SpecKey::BicubicTexels BicubicTexels(SlotRef) variant metal2vulkan::pipeline::SpecKey::BorderTexels BorderTexels(SlotRef) @@ -11275,8 +11137,6 @@ variant metal2vulkan::pipeline::Stage::Object Object variant metal2vulkan::pipeline::Stage::Vertex Vertex variant metal2vulkan::pipeline::StageSource::Compiled Compiled(CompiledFunction) variant metal2vulkan::pipeline::StageSource::Function Function(FunctionDescriptor) -variant metal2vulkan::pipeline::StorageAttachmentView::Attachment Attachment -variant metal2vulkan::pipeline::StorageAttachmentView::SamplePlanes SamplePlanes { layers: u32 } variant metal2vulkan::pipeline::StorageFormatClass::Format Format(vk::Format) variant metal2vulkan::pipeline::StorageFormatClass::NotStorage NotStorage variant metal2vulkan::pipeline::StorageFormatClass::Unknown Unknown @@ -11303,7 +11163,6 @@ variant metal2vulkan::pipeline::SyntheticBinding::Imageblock Imageblock variant metal2vulkan::pipeline::SyntheticBinding::PatchIndices PatchIndices variant metal2vulkan::pipeline::SyntheticBinding::RootTable RootTable variant metal2vulkan::pipeline::SyntheticBinding::SamplerTable SamplerTable -variant metal2vulkan::pipeline::SyntheticBinding::ShadowStencil ShadowStencil variant metal2vulkan::pipeline::SyntheticBinding::TessellationFactors TessellationFactors variant metal2vulkan::pipeline::SyntheticBinding::TileMemory TileMemory variant metal2vulkan::pipeline::UniformViewChoice::Kept Kept diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 75524906e..4300d3c23 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -355,14 +355,9 @@ surface! { enum BandPrimitive E; struct BlendState N; struct ColorAttachmentState N; - struct FragmentImageblock N; struct GraphicsState N; - enum ImageblockMechanism N; struct InputAttachmentUse N; struct LineBandState N; - struct ShadowStencilUse N; - struct StorageAttachmentUse N; - enum StorageAttachmentView E; struct TessellationState N; struct AccessSet N; enum AttributeFetch E; @@ -383,7 +378,6 @@ surface! { struct SamplerLevels N; struct SamplerSlot N; enum SlotInterface N; - enum SnapshotRefusal N; struct TextureAccess N; struct TextureSlot N; struct ThreadgroupArgument N; @@ -428,7 +422,6 @@ surface! { enum SamplerRef N; enum SlotClass E; struct SlotRef E; - enum SnapshotForm N; enum SpecKey N; enum Stage N; enum StorageFormatClass N; @@ -531,7 +524,6 @@ surface! { struct FunctionTablesShape N; struct TileThreadgroupMemory N; struct TileThreadgroupArgument N; - enum FragmentTests N; struct ExecutionStatus E; struct StatusBits E; struct StatusReport N; @@ -635,22 +627,15 @@ surface! { enum YCbCrOutput N; enum YCbCrRange N; enum YCbCrMatrix N; - fn planes_merge_modules; - fn planes_split_module; enum PlanesCopy N; - struct PlanesMergeModules N; - struct PlanesSplitModule N; fn interleave_merge_modules; fn interleave_split_module; struct InterleaveMergeModules N; struct InterleaveSplitModule N; fn depth_stencil_copy_modules; - fn stencil_split_module; - enum CopySource E; enum DepthStencilCopy N; struct DepthStencilCopyModules N; struct StencilBit O; - struct StencilSplitModule N; mod indirect_commands; } "bind::indirect_commands" => metal2vulkan::bind::indirect_commands { diff --git a/docs/API.md b/docs/API.md index 881bc1d12..f572f27bf 100644 --- a/docs/API.md +++ b/docs/API.md @@ -25,8 +25,7 @@ differences from Metal. The runtime's own guide is [its README](../crates/metal2 The exceptions are exhaustive on purpose: keys and Vulkan structs (`SlotRef`, `ResourceSlot`, `ApiVersion`, ...), and the enums a consumer must interpret completely to bind and draw correctly (`StageSource`, `PushHole`, `HeapSource`, `ImageSource`, `SamplerSource`, - `UseTarget`, `SlotClass`, `StorageAttachmentView`, `VertexStride`, `TileMapping`, `CopySource`, - `DrawCommand`, `PrecisionNote`, and Metal's `PrimitiveType`, `IndexType`, `CullMode`, `Winding` + `UseTarget`, `SlotClass`, `VertexStride`, `TileMapping`, `DrawCommand`, `PrecisionNote`, and Metal's `PrimitiveType`, `IndexType`, `CullMode`, `Winding` and `TextureType`), where a new variant breaks your build on purpose. - **Semver** covers this surface from 0.2.0 (still `0.x`: a breaking change bumps the minor version). @@ -818,27 +817,17 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: samples but does not render (the RTX 5080) renders through an `R16_UINT` view of its texture (`metal::format::WordAttachment`, `LoweringInputs::word_colors`): the fragment function writes the word Metal stores and `graphics` gives the attachment that format; a pass clears it to the - word of Metal's clear. Exact, for a write unblended (or blended one and zero); under a mask of - some of its channels the function merges the word into the texel in the interlocked storage - form (a `GraphicsState::storage_attachments` entry of `R16_UINT`) where the device orders fetch - through the pixel interlock. Blended otherwise, there too the function computes Metal's blend of - a `half4` or `float4` output over the word it reads, within one code of Metal's - (`PrecisionNote::DeviceColorConversion`: the attachment holds codes where Metal's tile holds a - clear's or an earlier blend's result in the pass as a `half`, and under fast math Metal sums a - few states otherwise). A blend of the second source, and a blend or - partial mask on a device without the interlock, is refused as the device lacking the format; a - blend of an output of fewer lanes is `NotImplemented`; a color input of - one is read in the interlocked storage form, the word decoded to each channel's code over its - maximum code rounded to `half`, nearest even, which is Metal's value (measured on an Apple M3 - Max under macOS 27.0.1 for a `float4` and a `half4` input, every code of each 4-bit channel). + word of Metal's clear. Exact, for a write unblended (or blended one and zero). Another blend + and a mask of some of its channels are refused as the device lacking the format; a color input + of one is `NotImplemented(Format)`. - An 8-bit sRGB attachment of one or two channels (`R8Unorm_sRGB`, `RG8Unorm_sRGB`) the device 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 in the interlock, or over the attachment's input attachment on a device that - orders fetch through rasterization-order input attachments (lavapipe; - `RuntimeFact::WordInputMerge`). A blend of one + 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)`. - An `RGB9E5Float` attachment the device does not render (the RTX 5080) renders through an @@ -859,9 +848,9 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: codes, a tie rounded down (a one-bit field's up), within one code of Metal's, which averages its tile's finer values. A device whose word's format renders one sample at that count refuses the texture (`TextureSampleCount`). -- A fragment function that reads a color attachment (framebuffer fetch) reads it in an ordered - form wherever the device has one. On a device with neither ordered form it reads the attachment - as an input attachment without rasterization-order access +- 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 @@ -875,19 +864,15 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: (`InvalidDescriptor` at the color attachment), or one of a rotated, Y'CbCr or extended-range format (`Unsupported{Format}`). A read of one of Apple's extended-range formats (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), and a blend into one, are refused on - every device in either form (`Unsupported{Format}` at the color attachment): Metal's tile holds + 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. A - raster order group on such 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}`). - The ordered forms are rasterization-order attachment access, or the interlocked - storage form, which binds the attachment as a storage image viewed in - `StorageAttachmentUse::view_format()`: its own format, an 8-bit sRGB format's unsigned-integer - view, or, where the device declares a BGRA-order format neither typed nor without a format, its - RGBA-order twin (the shader exchanges red and blue). A `[[stencil]]` output uses - `VK_EXT_shader_stencil_export`. + 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 + `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 Vulkan's first-vertex order and Metal's for every primitive type. A `float3` read takes the first two weights and computes the third as `1 - (x + y)` in `float`, as Metal does, not the @@ -1477,8 +1462,7 @@ What you record from `DispatchCommands` or `DrawCommands`: `bind::handle_entry_flags`), as the runtime does. - **Push constants.** Write `push_constants`, and fill each of the `push_holes` with the device address it names: the uploaded root table, the command buffer's `ExecutionStatus` buffer, an - indirect command buffer's records. A snapshot variant's `PushHole::SnapshotPhase` is a word, not - an address (below). + indirect command buffer's records. - **The dispatch or draw.** Record `regions` or `draw` as given: the binder has already applied Metal's offsets, bases and clamps. - **Status.** Per command buffer, keep one `ExecutionStatus` buffer for what translated shaders @@ -1486,73 +1470,6 @@ What you record from `DispatchCommands` or `DrawCommands`: binds it as `WriteSource::ExecutionStatus` on a device that does not address buffers: bind the same buffer there, its `ExecutionStatus::BYTES` bytes. -### Snapshot reads - -A draw that reads, at its fragments' own pixels, a texture its own subpass renders can read it -through a snapshot instead of a copy taken before the render pass instance. The interface lists -the fragment slots that allow it (`StageInterface::snapshot_textures`, `StageModule:: -snapshot_textures`): own-pixel slots whose texels reach no derivative, sample, quad or subgroup -operation, branch, integer divisor, dynamic vector index or store outside the invocation, directly -or through a call, in a function that writes no memory. A selection on a texel is allowed where -its arms leave through its merge alone and hold no derivative, implicit-level sample or -level-of-detail query, quad or subgroup operation, loop or undefined operand, nor call a function -that does; what its arms leave behind (its merge's phis, the variables they store to) is judged -as the texel is. It says why it leaves out each other -own-pixel slot (`snapshot_refusals`: each slot with every `SnapshotRefusal` that holds for it). -Name the slots in `BindState::snapshot_textures`; the plan keeps those its pipeline can read so -and states them in `variant.snapshot_textures`, each with the form its snapshot holds texels in -(`SnapshotForm::of` the slot's bound view and declared type: the texel's codes for an 8- or 16-bit -normalized, half-float or integer format of the slot's class, which a read decodes as Metal reads -the format, and the fetched lanes' bits for any other), compiled like any other variant. It keeps -none on a -device without `fragmentShaderPixelInterlock`, `fragmentStoresAndAtomics`, -`attachmentFeedbackLoopLayout` or `extendedDynamicState3ColorWriteMask`, for a pipeline of more -than one sample, a depth or stencil attachment, attachments in the storage form, input -attachments, an imageblock, tile memory, a shader-side stencil or tests, tessellation or mesh -stages, or a function that writes memory, and for an amplified or layered draw. Serve every other -read as before. - -A pipeline of that variant states `GraphicsState::snapshot_reads`: create it with -`VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`; its `dynamic_states` hold -`VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`, and its requirements `attachmentFeedbackLoopLayout` and -`extendedDynamicState3ColorWriteMask`. Bind the slot's own texture in the attachment's feedback-loop -layout, and at `WriteSource::SnapshotTexels` a storage image of the slot's form's -`SnapshotForm::format` (`R8G8B8A8_UINT`, `R16G16B16A16_UINT` or `R32G32B32A32_UINT`) covering the -render area, in `GENERAL` layout. Record each draw twice in its subpass: first with every color -write mask 0 and `PushHole::SnapshotPhase` set to 1, each fragment copying its texel into the -snapshot and running nothing else; then with the pipeline's own masks and the phase 0 (the plan's -bytes), each fragment reading the snapshot. A by-region pipeline barrier before the first draw -makes the attachment's earlier writes visible to the copy, and one between the two makes the copy -visible to the reads and orders it before the second draw's color writes. Each step rests on a -sentence of the Vulkan specification: the feedback loop's per-pixel barrier, the color write mask -leaving memory unmodified, the invariance of fragment generation under write masks (Rule 2, -Corollary 1), and the ordered pixel interlock. One draw alone cannot be exact: nothing orders a -fragment shader's read of a texel before the same draw's color write of it. - -Where the attachment's image lacks feedback-loop usage (NVIDIA's drivers make no linear image with -it), the two draws can run in two render pass instances instead, after the instance before them -ends. Record the first in a render pass instance of its own over the framebuffer of the instance -that follows, of a render pass compatible with that instance's that loads every attachment and -stores none (`VK_ATTACHMENT_STORE_OP_NONE`, core in Vulkan 1.3 and brought below it by -`VK_KHR_load_store_op_none` or `VK_EXT_load_store_op_none`), every color in `GENERAL` and the -slot's texture bound in `GENERAL`, between pipeline barriers from everything before and to -everything after; then begin the next instance and record the second draw first in it, with no -barrier between the draws. Neither instance enables a feedback loop, and neither needs one: the -first writes no color, by its masks or by its load and store operations -(`VUID-vkCmdDraw-None-10795`, `VUID-vkCmdDraw-None-12338`), and the second's fetch of the texture -never runs. The same pipeline serves both, as render pass compatibility ignores load and store -operations and layouts. The runtime takes this form for such a read after a memory barrier inside -the instance (`WorkCounts::reading_draws_snapshotted_leading`), where it would otherwise split the -instance and copy the texture, and where it weighs cheaper than the split by the scissors' area or, -on a device with precise occlusion queries, by the pixels the draw covered in its last measured -pass, even over a buffer's bytes: its first draw reads the texture at every pixel the draw covers. - -A draw whose pipeline writes no channel of the color it reads so needs no snapshot: the runtime -creates its pipeline (the variant without snapshots) with the feedback-loop flag, binds the slot's -own texture in the attachment's feedback-loop layout, and records a by-region barrier before the -draw, from the color writes to the fragment shader's reads, and one after it, from those reads to -the color output (section 10 says what it then reads). - ### Levels a slot reads Each texture slot of a stage states the levels of its bound view its reads reach, counted from the @@ -1769,8 +1686,7 @@ bound. color resolve averages through Vulkan's `AVERAGE` mode, which leaves the rounding of the average (and the sRGB encoding) to the device: any color attachment but an extended-range one and one resolving into its format's sRGB twin (each - resolved after the pass), one a fetching pass's sample planes hold as it ends included (the - planes merged back first). Also, on every device, a resolve into an 8-bit UNORM attachment's + resolved after the pass). Also, on every device, a resolve into an 8-bit UNORM attachment's sRGB twin where the device has the sRGB format: the crate-owned resolve decodes the samples and encodes their average by the device's own sRGB conversions, where Metal's resolve takes its own 12-bit tables (with correctly @@ -2037,41 +1953,12 @@ bound. mip filter or a runtime sampler's word does. The device takes the level of detail by Vulkan's rules, whose scale factor may be approximated; Metal's level of detail from derivatives is not measured. The sample may read another level or filter than Metal's near a boundary. -- `metal2vulkan-degrade-unmeasured-fetch-blend` (precision). `PrecisionNote::UnmeasuredFetchBlend`: - A fragment function reads a color attachment the pipeline blends, on a device that orders - framebuffer fetch only through the pixel interlock (MoltenVK, RADV, ANV), of a format whose Metal - blend arithmetic is not built: a format whose channels read as floats but a 16-bit float, a 32-bit - float, an sRGB and an extended-range one (a 16-bit normalized, 8-bit signed normalized, 10-bit, - packed float or `A8Unorm` format, among others), an 8-bit unorm one written by an output of fewer - than four lanes, a 32-bit float one (`R32Float`, `RG32Float`, `RGBA32Float`) written by an output - of fewer than four lanes, by a module without fast math, or under a blend state the one sweep that - measured that family does not fit: a color or alpha arithmetic of more than a lone term, a lone - fused multiply-add, or a minimum or maximum, outside the states measured word for word. A - one-channel attachment's `SourceColor` over `DestinationColor` is such a state, and so is a blend - color's difference, which a 16-bit float attachment's blend fits and a 32-bit float one's does - not; a lone term that reads the blend color, `OneMinusBlendColor` over `Zero` among them, is - fitted and takes the exact form. Also a 16-bit float or 8-bit unorm one under a blend of the - second source or beside a second (index 1) output. No Vulkan blend applies to the storage write, - so the shader computes the pipeline's blend in `float`: each factor, product and sum rounded to - nearest even, the source and the blend color clamped first to a normalized format's range (a NaN - to its low end), an output's missing lane zero, and the result stored through the device's - conversion. Metal's blend arithmetic for these formats is not measured, so the bound is not known. - A factor of the second source reads the function's second output, clamped as the source. An 8-bit - sRGB attachment (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`) under a - blend of the second source, a one- or two-channel one under a lerp, each in a module compiled with - fast math, and one written by an output of fewer than four lanes, record it too: the shader - computes Metal's 8-bit unorm blend's rounded forms over the decoded texel, in the output's type (a - missing lane zero), and stores the result by the device's sRGB encode (`DevicePackConversion`), - Metal's blend without fast math at four lanes; under fast math Metal regroups the blend, - unmeasured. - `metal2vulkan-degrade-unordered-fetch-within-draw` (precision). `PrecisionNote::UnorderedFetchWithinDraw`: A fragment function reads a color attachment - (framebuffer fetch) on a device with neither rasterization-order color attachment access nor - `fragmentShaderPixelInterlock` (Honeykrisp on Apple's M2 Pro; RADV on the RX 550), or under the - identity domains on any device without rasterization-order access, the pixel interlock's included: - there the interlock chooses no fetch form, as its storage form is a descriptor the identity - domains do not hold. 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 + (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 + 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 color, and before each draw that writes a color after an earlier one read them: a fetch reads what every earlier draw stored at its pixel, Metal's answer. Under the identity domains it reads the @@ -2145,10 +2032,7 @@ bound. - `metal2vulkan-degrade-device-nan-encoding` (precision). `PrecisionNote::DeviceNanEncoding`: A `float` NaN result's bit pattern follows the device: Metal answers the canonical `0x7fc00000` for the NaN results of its float arithmetic and functions, and Vulkan states no encoding, so a device - may answer another sign or payload (llvmpipe: `0xffc00000`). Also a blend - a fragment function computes into a 16-bit float attachment through the pixel interlock: a NaN - of the blend is the device's arithmetic's, which the storage image's store converts, where Metal - stores every NaN of the blend as `0x7e00`. A texture write records it where the stored NaN is the + may answer another sign or payload (llvmpipe: `0xffc00000`). A texture write records it where the stored NaN is the device's: a constant texel none of whose lanes is a NaN records nothing, and a `half` or `float` write through an argument buffer holds only where the command can name a texture of a format family whose stored NaN is the device's (for a `half` write, a texture of any format that @@ -2224,10 +2108,7 @@ bound. the float class that may hold a half-float or small-float format, which Metal rounds to nearest even and the device's store as it rounds a `float` (toward zero on every measured driver, one unit in the last place, a finite value past 65504 stored as 65504); and a fragment function's - `float` blend into a 16-bit float attachment through the pixel interlock, and a blend into an - 8-bit unorm attachment through - the pixel interlock, whose result the storage image's store converts to its code, or into an - `ARGB8Unorm` attachment over its input attachment where no Vulkan blend state on its rotated + blend into an `ARGB8Unorm` attachment over its input attachment where no Vulkan blend state on its rotated image gives Metal's (a destination alpha in a color factor, say), whose result the attachment's write converts; and a render pipeline's private logic operation that the fragment function computes on a device without `logicOp` into an 8- or 16-bit unorm or snorm attachment, which @@ -2429,17 +2310,9 @@ bound. `PrecisionNote::HalfOutputFastMathBlend`: A fragment function of a module compiled with fast math (`air.compile.fast_math_enable`) returns a `half` color output to an attachment the pipeline has that stores some channel (its write mask names one of its format's channels; - `StageIo::half_fast_colors`, which the pipeline's stage reads, or the interlocked storage form's - write), where `PrecisionNote::HalfOutputPrecision`'s conditions hold; or - computes the blend of a 16-bit float attachment it fetches in the interlocked storage - form (no Vulkan blend applies to a storage write) where Metal's compiler may fold the output's - own arithmetic into that blend or regroup a sum of it: within 2 `half` units in the last place of - Metal's at the operands' magnitude, 16 at the stored value's under cancellation. Where the output - is opaque to the blend and its form fits every measured state, the function's blend is Metal's - and records nothing; so does the blend of a fetched 8-bit unorm attachment it computes there - (every factor, operation, write mask and blend color it builds), which Metal reads the output - into clamped, folding none of it (the storage image's store of its result is the device's - conversion, `DeviceColorConversion`). Every device receives the output widened to `float`. + `StageIo::half_fast_colors`, which the pipeline's stage reads), where + `PrecisionNote::HalfOutputPrecision`'s conditions hold. Every device receives the output widened + to `float`. - `metal2vulkan-degrade-device-sampling` (precision). `PrecisionNote::DeviceSampling`: Native device sampler, on every device (the module requires `VkProperty::DeviceSampling`), its level clamp the descriptor's as given (a `lodMinClamp` past level 15, past every texture's last level, handed as @@ -2652,8 +2525,7 @@ bound. `unorm4x8_srgb`'s pack. Recorded on every device. The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), a fragment function's read and write of an 8-bit sRGB attachment - in the interlocked storage form or through its word view, and a snapshot read's decode of a - normalized code (`c` times the `f32` nearest `1 / D`), noted alike. So does every conversion of + through its word view. So does every conversion of an extended-range, padded 10-bit or bfloat texel (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12`, their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`), which no Vulkan format holds: a read is `float(c - 384)` (a padded code `c`) diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 4f51278e2..ad32deb51 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -40,7 +40,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 43 | 56 | 0 | 0 | 36 | +| Translator and front-end refusals | 0 | 0 | 0 | 44 | 55 | 0 | 0 | 36 | | 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 | 0 | 0 | 0 | 5 | @@ -94,7 +94,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` | 70: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)` (+38) | `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` | 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) | | `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,8 +109,8 @@ Columns: | `SamplerCompare` | Sampler compare functions outside what Vulkan allows for the image | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: compare samplers a device cannot apply to the image | | `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; devices without VkFeature::FragmentShaderSampleInterlock; devices without a capability the site computes (`alternatives`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/fragment/rog.rs (mode, 2 sites)` (+1) | `rare`: raster order groups | -| `FramebufferFetch` | Framebuffer fetch without an ordered form on the device (rasterization-order attachment access, or the pixel interlock's storage form where the... | devices short of a Vulkan property the site names; devices without VkFeature::FragmentShaderPixelInterlock; devices without VkFeature::RasterizationOrderColorAttachmentAccess; devices without VkFeature::SampleRateShading; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/sample_planes.rs (finish)`, `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (packed16)` (+8) | `system`: programmable blending (framebuffer fetch); macOS 26.6.2's login reaches it (two WindowServer and RenderBox pipelines fetch RGB10A8_2P_XR10 attachments, the consumer's boots) | +| `RasterOrderGroups` | Raster order groups without fragment shader interlock | devices without VkFeature::FragmentShaderPixelInterlock; devices without VkFeature::FragmentShaderSampleInterlock; devices without a capability the site computes (`alternatives`); 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) | | `PrimitiveId` | `[[primitive_id]]` in a fragment function | devices without a capability the site computes; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` | `rare`: primitive_id on a device without geometry or tessellation shaders, in an indexed draw or behind a mesh function | | `PrivatePrimitives` | One of Metal's private primitive types (a line loop, a triangle fan, quads, a quad strip) drawn in the pulled list form... | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` | `rare`: a private primitive type drawn in the pulled list form (a vertex function that writes memory or the primitive_id varying, a vertex start past 2^31) on a device without device addresses | | `VertexAmplification` | Vertex amplification | devices 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 | @@ -118,7 +118,7 @@ Columns: | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | `device` | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | `device` | 3: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)` (+1) | `rare`: dual-source blending on a device without it | | `Barycentrics` | Barycentric coordinates | devices without VkFeature::FragmentShaderBarycentric | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` | `rare`: barycentric coordinates | -| `StencilExport` | Stencil export | devices without VkExtension::ExtShaderStencilExport; every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/graphics.rs (shadow_stencil_words)`, `crates/metal2vulkan/src/lower/fragment/stencil.rs (device_form)` (+2) | `rare`: stencil from the shader | +| `StencilExport` | Stencil export | devices without VkExtension::ExtShaderStencilExport | `device` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)` | `rare`: stencil from the shader | | `SampleRateShading` | Per-sample shading | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations, 3 sites)` | `rare`: per-sample shading | | `PullModelInterpolation` | Metal's pull-model interpolation (`interpolant` fragment inputs and their `interpolate_at_center`, `_centroid`, `_sample` and `_offset` functions)... | devices without VkProperty::InterpolateAtOffsetCentered; devices without VkProperty::InterpolateAtOffsetFromSevenSixteenths; devices without a capability the site computes (`lacks`); every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/fragment/interpolate.rs (select, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant, 2 sites)` (+1) | `rare`: interpolant inputs read at the centroid, a sample or an offset | | `DivergentInterpolation` | Metal's pull-model interpolation at a sample or an offset (`interpolate_at_sample`, `interpolate_at_offset`) outside the fragment function's first... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` | `rare`: an interpolant read at a sample or an offset in a branch, a loop or after a discard | @@ -132,7 +132,7 @@ Columns: | `Tessellation` | Tessellation | devices without VkFeature::TessellationShader; devices without VkLimit::MaxTessellationGenerationLevel; every device (not implemented) | `ours` | 13: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)` (+8) | `rare`: tessellation | | `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`, `crates/metal2vulkan/src/bind/graphics.rs (plan)` (+3) | `rare`: mesh pipelines | | `TileShading` | | devices without VkLimit::MaxStorageBufferRange; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`, `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)` (+2) | `rare`: tile shaders (Apple GPU families) | -| `Imageblocks` | An imageblock outside the forms implemented | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+6) | `rare`: imageblocks (Apple GPU families) | +| `Imageblocks` | An imageblock outside the forms implemented | every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+4) | `rare`: imageblocks (Apple GPU families) | | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)` (+5) | `rare`: ray tracing (out of scope by ruling) | | `Tensors` | | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`, `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: shader tensors | | `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` | `rare`: rasterization rate maps | @@ -147,7 +147,7 @@ Columns: | `SubgroupOperations` | Simdgroup operations of a class the stage's subgroups do not support (the stage is not in `subgroupSupportedStages`, or an operation class is... | devices without VkFeature::ShaderQuadControl; devices without VkFeature::ShaderSubgroupExtendedTypes | `device` | 2: `crates/metal2vulkan/src/lower/simd/mod.rs (full_quads)`, `crates/metal2vulkan/src/lower/simd/mod.rs (select_group)` | `app`: simdgroup functions in a stage a device's subgroups do not support | | `DirectCall` | A call to a defined function the inliner cannot take | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` | `rare`: variadic or byval calls the inliner cannot take | | `WideSwitchLiteral` | A switch case literal wider than 32 bits | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` | `rare`: 64-bit switch literals | -| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices short of a device limit the site names; devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 37: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`, `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)` (+34) | `system`: the catch-all of lowering families not landed: any shader can meet one | +| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices short of a device limit the site names; devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 36: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`, `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)` (+33) | `system`: the catch-all of lowering families not landed: any shader can meet one | | `SamplerAddressMode` | A sampler address mode the device lacks (`MirrorClampToEdge`) | devices without VkFeature::SamplerMirrorClampToEdge; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`, `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: mirror-clamp-to-edge on a device without it | | `AlphaToOne` | `alphaToOneEnabled` on a device without Vulkan's `alphaToOne` feature, the exact counterpart... | devices without VkFeature::AlphaToOne | `device` | 1: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` | `rare`: alphaToOneEnabled on a device without alphaToOne | | `StageStoresAndAtomics` | Buffer or image stores or atomics in a vertex or fragment function without the stage's store feature (`vertexPipelineStoresAndAtomics`,... | devices without VkFeature::FragmentStoresAndAtomics | `device` | 1: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` | `app`: stores or atomics in vertex or fragment functions on a device without the feature | @@ -182,8 +182,8 @@ Columns: | `RenderTargetSize` | A render pass whose render area or layers are past the device's framebuffer limits (`Capability::Limit` names `MaxFramebufferWidth`,... | - | `-` | 0 | `rare`: a render area past a device's framebuffer limits | | `IndirectRenderState` | A render state a function sets on an indirect render command (`render_command::set_cull_mode`, `set_front_facing_winding`,... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/access/encode.rs (select_command)` | `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::FragmentShaderPixelInterlock; 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` | 5: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (refused)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_output)` (+1) | `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; 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 | | `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,... | - | `-` | 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 | @@ -435,7 +435,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/bind/sample_interleave.rs (interleave_split_module)`; `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, 6 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_output, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_read)`; `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/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::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)` @@ -450,8 +450,8 @@ Each refusal's sites, with the function that builds it. - `feature::SamplerCompare`: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `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)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs (finish)` -- `feature::FramebufferFetch`: `crates/metal2vulkan/src/bind/sample_planes.rs (finish)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (packed16)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (srgb8)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (unorm8, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/color.rs (unordered)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (unordered_extended_fetch)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs (storage_attachments)` +- `feature::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::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)` @@ -459,7 +459,7 @@ Each refusal's sites, with the function that builds it. - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` - `feature::DualSourceBlending`: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::Barycentrics`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` -- `feature::StencilExport`: `crates/metal2vulkan/src/bind/graphics.rs (shadow_stencil_words)`; `crates/metal2vulkan/src/lower/fragment/stencil.rs (device_form)`; `crates/metal2vulkan/src/lower/fragment/stencil.rs (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/stencil.rs (shadow_stencil, 2 sites)` +- `feature::StencilExport`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)` - `feature::SampleRateShading`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations, 3 sites)` - `feature::PullModelInterpolation`: `crates/metal2vulkan/src/lower/fragment/interpolate.rs (select, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` - `feature::DivergentInterpolation`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` @@ -472,7 +472,7 @@ Each refusal's sites, with the function that builds it. - `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (primitive_id_output)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan, 2 sites)` - `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`; `crates/metal2vulkan/src/bind/graphics.rs (plan)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)` - `feature::TileShading`: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs (tile_pipeline)` -- `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (reach)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (require)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs (fragment_imageblock)` +- `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)` - `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` @@ -487,7 +487,7 @@ Each refusal's sites, with the function that builds it. - `feature::SubgroupOperations`: `crates/metal2vulkan/src/lower/simd/mod.rs (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_group)` - `feature::DirectCall`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` - `feature::WideSwitchLiteral`: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` -- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs (finish)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air, 2 sites)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_through)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` +- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air, 2 sites)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_through)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` - `feature::SamplerAddressMode`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`; `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `feature::AlphaToOne`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` @@ -509,7 +509,7 @@ Each refusal's sites, with the function that builds it. - `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs (select_command)` - `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)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan, 3 sites)` +- `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)`