diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 8b525f081..f18f9b421 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -108,10 +108,6 @@ pub enum Degradation { ArgumentPixelSamplerScaling, /// [`PrecisionNote::HalfOutputPrecision`]. HalfOutputPrecision, - /// [`PrecisionNote::AnisotropicFilter`]. - AnisotropicFilter, - /// [`PrecisionNote::DeviceAnisotropicFilter`]. - DeviceAnisotropicFilter, /// [`PrecisionNote::DevicePointSize`]. DevicePointSize, /// [`PrecisionNote::ClippedCoverageSplit`]. @@ -233,8 +229,6 @@ impl Degradation { Degradation::LinkedSamplerNumbering, Degradation::ArgumentPixelSamplerScaling, Degradation::HalfOutputPrecision, - Degradation::AnisotropicFilter, - Degradation::DeviceAnisotropicFilter, Degradation::DevicePointSize, Degradation::ClippedCoverageSplit, Degradation::LoopedSampleOutputs, @@ -330,8 +324,6 @@ impl Degradation { Degradation::LinkedSamplerNumbering => PrecisionNote::LinkedSamplerNumbering, Degradation::ArgumentPixelSamplerScaling => PrecisionNote::ArgumentPixelSamplerScaling, Degradation::HalfOutputPrecision => PrecisionNote::HalfOutputPrecision, - Degradation::AnisotropicFilter => PrecisionNote::AnisotropicFilter, - Degradation::DeviceAnisotropicFilter => PrecisionNote::DeviceAnisotropicFilter, Degradation::DevicePointSize => PrecisionNote::DevicePointSize, Degradation::ClippedCoverageSplit => PrecisionNote::ClippedCoverageSplit, Degradation::LoopedSampleOutputs => PrecisionNote::LoopedSampleOutputs, @@ -413,8 +405,6 @@ impl Degradation { PrecisionNote::LinkedSamplerNumbering => Degradation::LinkedSamplerNumbering, PrecisionNote::ArgumentPixelSamplerScaling => Degradation::ArgumentPixelSamplerScaling, PrecisionNote::HalfOutputPrecision => Degradation::HalfOutputPrecision, - PrecisionNote::AnisotropicFilter => Degradation::AnisotropicFilter, - PrecisionNote::DeviceAnisotropicFilter => Degradation::DeviceAnisotropicFilter, PrecisionNote::DevicePointSize => Degradation::DevicePointSize, PrecisionNote::ClippedCoverageSplit => Degradation::ClippedCoverageSplit, PrecisionNote::LoopedSampleOutputs => Degradation::LoopedSampleOutputs, diff --git a/crates/metal2vulkan-conformance/src/replay.rs b/crates/metal2vulkan-conformance/src/replay.rs index 9b62e3934..2b9579b21 100644 --- a/crates/metal2vulkan-conformance/src/replay.rs +++ b/crates/metal2vulkan-conformance/src/replay.rs @@ -479,8 +479,8 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool { /// visibility result (`device-occlusion-count`), announced by every such mode set. /// /// **What is not here**, and stays each case's to declare: a note of what the device **lacks** -/// (`device-signed-zero-inf-nan`, `device-anisotropic-filter`, `device-point-size`, -/// `restricted-depth-range`, `restricted-depth-upload`), of an emulation's own precision (`grad-from-bias`, +/// (`device-signed-zero-inf-nan`, `device-point-size`, `restricted-depth-range`, +/// `restricted-depth-upload`), of an emulation's own precision (`grad-from-bias`, /// `pixel-sampler-scaling`, `bicubic-filter-arithmetic`), of a Metal form not measured or not built /// (`blended-write-rounding`, `device-interpolation`, `reduction-order`), a native answer whose /// catalogue entry states the bound the cases that read it hold it to (the device's decode of a diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 7ad188ef3..520697a2c 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -4523,8 +4523,8 @@ cache is answered compile-required on both. `a_storage_cube_written_by_face_is_the_2d_array_element_of_its_faces`; - a texture argument sampled through a sampler the identity sampling does not take ("a texture argument sampled through a sampler the identity sampling does not take"), and a sampler - argument whose minimum level or emulated filter the function specializes ("a sampler argument - whose minimum level or emulated filter the function specializes"): no test yet. A clamped LOD + argument whose minimum level the function specializes ("a sampler argument whose minimum level + the function specializes"): no test yet. A clamped LOD query outside a fragment function through a sampler argument is lowered, its level read from the word of the sampler's resource ID (docs/API.md, Accepted differences): the translator test `under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`; diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 747d07e67..ba314dd58 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -b369da90281b9e18a37347585baa6c31498764bc993d780ed3ac76a9a2489c60 +33ebe1edbb044de9d8562b94ef26a1e72899caadb81f75f81b1538d1b2650b34 diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 4890a8659..6381a9802 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -368,8 +368,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::CubeGradientFootprint | N::SrgbTexelDecode | N::QuadsCountedBeforeDiscard - | N::AnisotropicFilter - | N::DeviceAnisotropicFilter | N::ClippedCoverageSplit | N::HalfOutputFastMathBlend | N::DeviceSampling diff --git a/crates/metal2vulkan-validation/src/observation_contract/words.rs b/crates/metal2vulkan-validation/src/observation_contract/words.rs index 90d5a2e0b..436890a49 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/words.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/words.rs @@ -279,8 +279,6 @@ pub fn reach(note: PrecisionNote) -> Reach { | N::SrgbTexelDecode | N::ViewBaseTexelOffset | N::LinkedSamplerNumbering - | N::AnisotropicFilter - | N::DeviceAnisotropicFilter | N::DeviceSampling | N::DeviceTexelConversion | N::DeviceSampleLevel diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index e9aad71cf..38dc91b65 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -851,7 +851,7 @@ codec_enum! { RenderAreaWidth, RenderAreaHeight, OutOfBoundsAlpha(f0), SparseTexture(f0), TgOffset(f0), TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0), ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0), - OffsetBaseAxes(f0), SamplerAnisotropy(f0), + OffsetBaseAxes(f0), NearestPixelSampler(f0), BorderTexels(f0), DeepThreadgroup, WorkgroupSize(f0), TexelBufferWords { stage, handles }, @@ -1364,8 +1364,6 @@ codec_enum! { LinkedSamplerNumbering, ArgumentPixelSamplerScaling, HalfOutputPrecision, - AnisotropicFilter, - DeviceAnisotropicFilter, DevicePointSize, ClippedCoverageSplit, LoopedSampleOutputs, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index e74821549..cf89159e7 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2362; +pub const SEMANTICS_VERSION: u32 = 2363; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -281,11 +281,6 @@ pub struct VariantKey { /// a list's base vertex cannot carry (`RuntimeFact::PrivateList`). #[cfg_attr(feature = "serde", serde(default))] pub private_list: bool, - /// The runtime sampler slots that the shape binds to a sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`, - /// `LoweringInputs::anisotropic_samplers`): the variant whose function takes Metal's - /// anisotropic filter, emulated, at each one's samples. - #[cfg_attr(feature = "serde", serde(default))] - pub anisotropic_samplers: BTreeSet, /// The texture slots of a kernel of OpenCL mode whose `RuntimeFact::OpenClLineTexture` (a 1D /// image it reads as the 2D texture of height 1 Apple's OpenCL binds) the shape binds a 1D or /// 1D array texture at (`LoweringInputs::open_cl_lines`): the variant's kernel declares each @@ -329,13 +324,12 @@ impl VariantKey { && self.primitive_id_indices.is_none() && !self.quad_primitive_ids && !self.private_list - && self.anisotropic_samplers.is_empty() && self.open_cl_lines.is_empty() && !self.region_viewports } /// The lowering inputs of the function of `stage` under this key: its storage-image choices, - /// device-address slots, kept storage views, raw sRGB slots, anisotropic samplers, + /// device-address slots, kept storage views, raw sRGB slots, /// for the kernel the emulated simdgroups, the flat grid, the folded groups, the partial /// threadgroups and the replay's bindings, for the vertex and fragment functions the draws of one amplification each, for /// the fragment function the colors it writes zero to and those it drops, its depth's clamp @@ -383,12 +377,6 @@ impl VariantKey { .filter(|_| stage != crate::pipeline::sym::Stage::Kernel); out.region_viewports = self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex; - out.anisotropic_samplers = self - .anisotropic_samplers - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); out.open_cl_lines = self .open_cl_lines .iter() diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 54c0d5fcc..4f955a05b 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -691,7 +691,8 @@ pub enum Feature { StorageTextureInVertexStage, /// Cube arrays. CubeArray, - /// Sampler anisotropy an argument buffer lists, on a device without `samplerAnisotropy`. + /// A sampler of `maxAnisotropy` above 1 for a use that filters, on a device without + /// `samplerAnisotropy` (`metal::sampler::check_sampler`). SamplerAnisotropy, /// Sampler border colors Vulkan cannot express. SamplerBorderColor, @@ -1109,8 +1110,7 @@ pub enum IdentityCause { /// function. ObjectOrMeshStage, /// A sample through a sampler the identity sampling does not take: a sampler argument whose - /// minimum level or emulated filter the function specializes, a bicubic filter of a 1D - /// texture, or an anisotropic sampler slot whose filter the function emulates. + /// minimum level the function specializes, or a bicubic filter of a 1D texture. SamplerState, /// A storage texture access the device takes only with a declared format, whose bound format /// no input names under the identity domains. diff --git a/crates/metal2vulkan/src/lower/sampler/anisotropic.rs b/crates/metal2vulkan/src/lower/sampler/anisotropic.rs deleted file mode 100644 index 6a7d26c6b..000000000 --- a/crates/metal2vulkan/src/lower/sampler/anisotropic.rs +++ /dev/null @@ -1,1254 +0,0 @@ -//! Metal's anisotropic filter, emulated by the device's samples at explicit levels. -//! -//! **The rule** (an Apple M4 on macOS 27.0.1, seven probe rounds, our own -//! synthetic textures and gradients; the M3 Max on macOS 26.7 answered every compared footprint -//! identically). For a sample of a 2D plane with gradients `gx`, `gy` in level-0 -//! texels through a sampler of `maxAnisotropy` rounded up to a power of two, `a = 2^la` -//! (`metal::sampler::vk_sampler`): -//! -//! - each gradient's length is `max(M + 3m/16, 49M/64 + 21m/32)` of its larger and smaller -//! component magnitudes `M`, `m`; the major axis is the longer, and the taps step along it -//! divided by that length (not its Euclidean length); -//! - Metal takes logarithms by a four-segment piecewise-linear `log2` of its own; the emulation -//! takes the device's `Log2` (and `Exp2` for the powers): the determinant `|gx.x gy.y - gx.y -//! gy.x|` of the gradients gives the minor axis's; -//! - the level is `max(log2(det) - max(log2(major), 0), log2(major) - la)`: the minor axis held -//! at a texel of the major or more, and the major over `a` (Metal rounds it to 256ths); -//! - the tap count is the first of 1, 2, 3, 4, 6, 8, 10, 12, 14 and 16 whose `ceil(64 log2 n) / -//! 64` the log ratio `log2(major) - max(log2(det) - log2(major), 0)` does not pass, at most `a` -//! (11,090 of 11,096 footprints under Metal's logarithm); -//! - tap `j` of `n` weighs `floor(256 / n)` 256ths, the remainder one each to the middle taps, -//! and sits `(j - (n - 1) / 2) s0` texels from the centre along the major axis, with the -//! spacing `s0 = major · g · S`: `r'` the log ratio's power (at most `a`), `g = (r' - 1) / 2` -//! for two taps and `(1 - κ_n (1 - r'/n)) / n` past two (`κ_n` fitted per count), `S` the power -//! `2^-λ` of the level past the texture's levels (the level past 0 under no mip filter); Metal -//! rounds `r'` to `1/256`, `g · S` to `1/4096` and `S` to a 6-bit mantissa of sixty-fourths; -//! - each tap reads the level by the sampler's mip filter: level 0 without one, the level -//! `L + 1` past half a level under a nearest one, and under a linear one the fractional level, -//! whose two levels the device's own linear mip filter blends (Metal blends them by `256 - q` -//! and `q` 256ths). -//! -//! **Exactness** (the emulation's residue against the M4's answers): the length, the tap count's -//! thresholds, the weights and the direction are Metal's; the logarithms, the powers, the level's -//! fraction and the levels' blend are the device's (`PrecisionNote::AnisotropicFilter`), so the -//! level, a tap count at a threshold and the spacing may differ from Metal's by their rounding. -//! The spacing past two taps below the cap is an approximation (`κ_n`). Each tap is the device's -//! own filter at the level handed to it, so its footprint and sum are the device's, measured on -//! `rgba8Unorm` at `maxAnisotropy` 2 to 16. -//! -//! **The form.** Each tap is one device sample at an explicit level: under a linear mip filter the -//! fractional level, which the device's linear mip filter blends: the device's blend, which need -//! not be Metal's (an RTX 3090's is 1.03 codes off without anisotropy). A level of -//! 0 where Metal minifies (its level, before the texture's levels hold it, above 0, so on a -//! texture of one level too) is handed as `2^-12`, which keeps the device's minification filter -//! and blends nothing a device's mip precision keeps. A nearest mip filter's level is handed -//! whole: the 3090's anisotropic sampler blends the next level at a fractional explicit level -//! whatever its mipmap mode. Under a nearest mip -//! filter or none, level 0 where Metal minifies is handed as `0.25` where the device's sampler of -//! the binding is isotropic (`metal::sampler::device_anisotropy`), where Vulkan reads level 0 by -//! the min filter at it on every device, and which a device that rounds `2^-12` to 0 (the 780M's -//! RADV) still minifies at; as `2^-12` where it is anisotropic, whose level and taps Vulkan leaves -//! to the implementation (an RTX 5080's read past level 0 at `0.25`). -//! -//! **Cubes** ([`cube_face`]). Metal under macOS 27 samples a cube with explicit gradients as it -//! samples the 2D plane of the direction's face with Metal's face gradients, each gradient without -//! its normal component (the Apple M3 Max, every inner lane of each probed sampler equal to a 2D -//! array sample of the face; `emit::cube_footprint`'s `Face` form). The emulation reads those, in -//! the face's texels, as the plane's gradients, and moves the direction across the face by each -//! tap's step, which the device projects onto the face again (a tap past the face's edge onto the -//! next face, as the device projects it). Through an isotropic constexpr sampler the module takes -//! Metal's level alone, its major axis's (an isotropic cube's measured so: a footprint past -//! `1 + 3/2048` minifies, `unk_cube_grad_table`'s turning points), and one tap, where no exact -//! path of the sample's own answers it (a fetched coordinate): its levels are Metal's, each the -//! device's filter. -//! -//! **The loop**. Tap 0 is written out, and taps 1 to `n - 1` are one loop's body, which asks the -//! driver not to unroll it (`LoopControl` `DontUnroll`): each tap's arithmetic and the sum's order -//! are those of the taps written out one by one, so the answer is the same (the lane's statistics, -//! every sampler alike), and a driver compiles one tap's code instead of sixteen. A guest -//! fragment's variant of 135 emulated samples took 1.49M words instead of 1.79M, and its pipeline -//! 29.0 s to make on an RTX 3090 instead of 38.9 s. -//! -//! **The routine** (`routine::Filter`). The emulation (the level-0 size and level count, the -//! degree and mip filter, the footprint and the taps' sum) is one routine per shape: the binding, -//! the sampler's degree, mip filter and device anisotropy, a cube, an array, a `min_lod_clamp` and -//! a texel offset. Every sample of the shape calls it with what its site computes (the -//! coordinate, the gradients, a cube's face steps, the layer and the clamp), and converts the sum -//! as its texel. Where the profile admits the `Offset` operand on a sample (`maintenance8` and -//! `shaderImageGatherExtended`), the call passes the texel offset, constant or dynamic, and the -//! taps' samples take it as that operand, which adds the same offset to the texel coordinates at -//! each level as `ConstOffset` does (the specification's texel coordinate offset), so the samples -//! at every offset call one routine; elsewhere a constant offset is the shape's `ConstOffset`. Each -//! answer is the one the code written at the site gave, and the module holds one copy of the code -//! a driver compiles, where a sample costs a call -//! (`anisotropic_samples_call_one_routine`). Written at each site, the emulation was about 2,100 -//! words a sample, each compiled again: a guest fragment's variant of an anisotropic runtime -//! sampler under the exact forms took 1,113,991 words where the plain function took 572,061, and -//! 33.6 to 40.7 s to make on the RTX 5080 Laptop GPU; as the routine, 659,590 words, made in 20.9 -//! to 26.1 s on a loaded host whose plain function took 16.7 to 22.3 s, its calls kept calls there -//! (the routine is declared `DontInline`). A sample at a -//! dynamic texel offset on a profile without the `Offset` operand on a sample, whose arms the -//! taps' samples read, keeps the code at its site. -//! -//! **Reach** (`select`): a sample without comparison of a 2D texture or 2D array of `float` or -//! `half` texels, at the fragment's implicit level (with a bias, through Metal's biased minor -//! axis) or with explicit gradients, or of a cube or cube array with explicit gradients, through a -//! constexpr sampler whose `maxAnisotropy` is above 1 (a cube's isotropic one too) or a runtime -//! sampler slot whose word states anisotropy, on a device without `samplerAnisotropy`: every -//! Vulkan sampler is isotropic there (`metal::sampler::device_anisotropy`), so the emulation goes -//! where that feature's refusal was, the device's own sampling unchanged where the feature is. A -//! runtime slot's degree is its `SpecKey::SamplerAnisotropy` specialization; where its word states no -//! anisotropy, the sample is the plain one. Elsewhere (a cube's implicit level, a 3D texture, a -//! comparison, an observed residency, an argument buffer's sampler) the device filters, recorded -//! as `PrecisionNote::DeviceAnisotropicFilter` where the sampler's anisotropy is known (on Metal's -//! own sampler, Metal's filter, unrecorded); without `samplerAnisotropy` isotropically, and an -//! argument buffer's anisotropic sampler, which the function cannot record, is refused there -//! (`metal::sampler::check_argument_sampler`). -//! -//! **The variant**. A runtime slot's emulation, at every sample it reaches, made a guest's -//! fragment function of 337 such samples twice its size (2.35M words from 1.18M, the emulation -//! written at each site), whatever samplers its draws bind, and every making of its pipeline hands -//! the driver the whole module. Such a sample takes the emulation only under the variant -//! naming the slot (`LoweringInputs::anisotropic_samplers`), which the binder asks for wherever -//! the bound sampler's word states anisotropy; elsewhere it is the plain sample, which is -//! Metal's for every word the function is then bound with. Under the variant the sample is the -//! form above, its word's test included, so a slot named or not, each word's answer is the one -//! before. - -use crate::air::abi::{Coordinates, MipFilter}; -use crate::air::intrinsics::{ImageDim, ImageShape}; -use crate::error::Error; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::lower::texture::ImageRef; -use crate::metal::sampler::{device_anisotropy_by_filters, SamplerUse, SamplerWord}; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::sym::SamplerRef; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec, Merged}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{FuncId, TypeId, Value as SValue}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, Contraction, ConvOp, DerivOp, GlslOp, ImageOperands, ImageQuery, - MemAccess, Type as SType, UnOp, -}; - -use super::routine::{Filter, Shape}; -use super::{BindingKey, Lod, Offset, SampleOp, Sampling, Source}; - -/// A sample that takes Metal's anisotropic filter, emulated (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Anisotropic { - /// The sampler's degree. - pub degree: Degree, - /// The sampler's mip filter. - pub mip: Mip, - /// Whether the device's sampler of the sample's binding filters anisotropically, which - /// decides the level handed for level 0 where Metal minifies ([`read_levels`]). - pub device: DeviceAnisotropy, - /// Whether the profile admits the `Offset` operand on a sample (`maintenance8` and - /// `shaderImageGatherExtended`), so the routine's call passes the sample's texel offset - /// (`routine::Filter::passed_offset`). - pub offset_operand: bool, -} - -/// Whether the device's sampler of an emulated sample's binding filters anisotropically -/// (`anisotropyEnable`), as `metal::sampler::vk_sampler` makes it -/// (`metal::sampler::device_anisotropy`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum DeviceAnisotropy { - /// A constexpr sampler's: its Vulkan sampler's own flag. - Const(bool), - /// A runtime sampler slot's, by the filters its word states: `(linear, nearest)`, the flag - /// where both filters are linear and where one is nearest - /// (`metal::sampler::device_anisotropy_by_filters`). A word with a cubic filter, whose other - /// filter it does not state, is taken as anisotropic. - Filters(bool, bool), -} - -/// The degree a sampler filters with, as `log2` of its `maxAnisotropy` rounded up to a power of -/// two. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Degree { - /// A constexpr sampler's: 1 to 4. - Const(u32), - /// Runtime sampler slot `n`'s: its `SpecKey::SamplerAnisotropy` specialization (0 for an - /// isotropic sampler, whose sample is the plain one). - Slot(u32), -} - -/// The mip filter a sample reads its levels by. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Mip { - /// A constexpr sampler's. - Const(MipFilter), - /// A runtime sampler slot's word's `SamplerWord::MIP_FILTER` field. - Word, -} - -/// The most taps Metal's filter takes (at `maxAnisotropy` 16); a degree past it (a runtime -/// sampler's 32) takes 16, its tap counts past 16 not being measured. -pub const MOST_TAPS: u32 = 16; - -/// `log2` of [`MOST_TAPS`]. -const MOST_LOG: i32 = 4; - -/// The tap counts, and the log ratio (in sixty-fourths of a level) each holds up to: -/// `ceil(64 log2 n)`. -const COUNTS: [(i32, i32); 10] = [ - (1, 0), - (2, 64), - (3, 102), - (4, 128), - (6, 166), - (8, 192), - (10, 213), - (12, 230), - (14, 244), - (16, 256), -]; - -/// The spacing's correction past two taps, `κ_n`, fitted per tap count to the rounds 5 and 6 (an -/// approximation below the ratio cap, exact at it). -const KAPPA: [(i32, f32); 8] = [ - (3, 0.0600), - (4, 0.0348), - (6, 0.0255), - (8, 0.0159), - (10, 0.0210), - (12, 0.0392), - (14, 0.0153), - (16, 0.0178), -]; - -/// The level handed for level 0 where Metal's level is above 0 under a linear mip filter, and under -/// a nearest one or none where the device's sampler filters anisotropically: the device minifies -/// there, and blends nothing of level 1 at any mip precision up to 11 bits. Vulkan leaves an -/// anisotropic sampler's level and taps to the implementation ("Texel Anisotropic Filtering": "The -/// particular scheme for anisotropic texture filtering is implementation-dependent"), and an RTX -/// 5080's reads past level 0 at a fractional level whatever its mipmap mode (measured at -/// `MINIFIED_NEAREST`: a linear filter under a nearest mip filter at `maxAnisotropy` 8 off by up to -/// 147 codes). -const MINIFIED_ZERO: f32 = 1.0 / 4096.0; - -/// The level handed for level 0 where Metal's level is above 0 under a nearest mip filter or -/// none where the device's sampler is isotropic (`anisotropyEnable` false), where Vulkan defines -/// the level and the filter ("Image Level(s) Selection": under `VK_SAMPLER_MIPMAP_MODE_NEAREST` -/// the level is `nearest(d')`, `ceil(d' + 0.5) - 1` or `floor(d' + 0.5)`, with `d' = level_base + -/// clamp(λ, 0, q)`, level 0 for `λ` up to `0.5`; "Texel Filtering": "If λ is less than or equal to -/// zero, the texture is said to be magnified, and the filter mode within a mip level is selected -/// by the magFilter in the sampler. If λ is greater than zero, the texture is said to be minified, -/// and the filter mode within a mip level is selected by the minFilter in the sampler."). It is a -/// multiple of `2^-4`, the coarsest `mipLodPrecisionBits` Vulkan allows. A sampler without -/// mipmapping holds its levels at `metal::sampler::NOT_MIPMAPPED_MAX_LOD`, this level. Handed -/// `MINIFIED_ZERO` there, the 780M's RADV magnified: every lane of `unk_cube_grad_table`'s probes -/// that Metal minifies read the nearest texel of a sampler that minifies linearly and magnifies -/// nearest. -const MINIFIED_NEAREST: f32 = 0.25; - -/// Whether sample `op` of a texture of `shape` (`image`) through static sampler `sampler` (`None` -/// for an argument buffer's) takes Metal's anisotropic filter emulated (the module's reach), with -/// its note recorded: `AnisotropicFilter` where it does, `DeviceAnisotropicFilter` where the -/// sampler's anisotropy is known and the sample, filtered at an implicit level or with -/// gradients, is out of reach; a runtime sampler slot's under its word's anisotropy alone. A -/// device whose own sampler answers the sample, anisotropy included, takes neither: one with -/// `samplerAnisotropy`. -/// `integer`: the texel class is an integer one (never filtered); `observed`: the function -/// reads the sample's residency; `swizzled`: the slot swizzles its converted texels -/// (`LoweringInputs::swizzled_storage`). `use_` is the sample's binding's use of its sampler, -/// which with the sampler decides the device's sampler. -pub(super) fn select( - cx: &mut SelectCx<'_>, - op: &SampleOp, - (sampler, image, shape): (Option, ImageRef, ImageShape), - (integer, observed, swizzled): (bool, bool, bool), - use_: SamplerUse, -) -> Result, Error> { - // Without `samplerAnisotropy` every Vulkan sampler is isotropic - // (`metal::sampler::device_anisotropy`): the emulation goes where it reaches an anisotropic - // sampler's sample there on every device, and the device's isotropic filter is recorded - // elsewhere. - let anisotropy = cx.profile.fields().images.sampler_anisotropy; - let SampleOp::Sample { lod, dref, .. } = op else { - return Ok(None); - }; - let derived = matches!( - lod, - Lod::Implicit { .. } | Lod::Grad(..) | Lod::Hoisted | Lod::CubeGrad(..) - ); - if integer || !derived { - return Ok(None); - } - let cube = matches!(lod, Lod::CubeGrad(..)); - if anisotropy { - cx.families.sampler.device_sampling = true; - return Ok(None); - } - let (degree, mip, device) = match sampler { - Some(SamplerRef::Constexpr(words)) => { - let state = super::constexpr::state_of(words)?; - if state.max_anisotropy <= 1 || state.coordinates == Coordinates::Pixel { - return Ok(None); - } - let la = state.max_anisotropy.next_power_of_two().trailing_zeros(); - let device = super::constexpr::constexpr_desc(words, use_, cx.profile)? - .max_anisotropy - .is_some(); - ( - Degree::Const(la), - Mip::Const(state.mip_filter), - DeviceAnisotropy::Const(device), - ) - } - Some(SamplerRef::Slot(n)) => { - let (linear, nearest) = device_anisotropy_by_filters(use_, cx.profile); - ( - Degree::Slot(n), - Mip::Word, - DeviceAnisotropy::Filters(linear, nearest), - ) - } - None => return Ok(None), - }; - let reached = dref.is_none() - && (shape.dim == ImageDim::D2 || cube) - && !shape.ms - && !shape.depth - && !observed - && !swizzled - && matches!(image, ImageRef::Slot(_)); - let note = match reached { - true => PrecisionNote::AnisotropicFilter, - false => PrecisionNote::DeviceAnisotropicFilter, - }; - match degree { - Degree::Const(_) => { - cx.precision.insert(note); - } - Degree::Slot(n) => { - // A reached sample would take the emulation only under a variant naming the slot, - // which no binder of the identity domains chooses. - if reached { - return Err(crate::error::Unsupported::identity( - crate::error::IdentityCause::SamplerState, - ) - .into()); - } - if let Some(s) = cx.families.sampler.slots.get_mut(&n) { - s.anisotropy = true; - } - cx.precision.insert(note); - } - } - let images = &cx.profile.fields().images; - Ok(reached.then_some(Anisotropic { - degree, - mip, - device, - offset_operand: images.dynamic_sample_offset && images.gather_extended, - })) -} - -/// The image facts of combined binding `key`, which no module declares: every sampling reads the -/// set-1 arrays (`sampler::IdentitySampling`), so an emulation that needs the binding fails. -fn combined_image(cx: &mut EmitCx<'_>, key: super::BindingKey) -> BResult { - Err(cx.fail(format!("combined binding {key:?} is not declared"))) -} - -/// Sample `s` through Metal's anisotropic filter (the module docs), in its result's form: for a -/// runtime sampler slot, where its word states anisotropy, else the plain sample. `grads` are a -/// switch-at-use's hoisted gradients (`Lod::Hoisted`). -pub(super) fn sample( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - a: &Anisotropic, - grads: Option<(SValue, SValue)>, -) -> BResult { - let SampleOp::Sample { - lod, - dref: None, - min_lod, - offset, - } = &s.op - else { - return Err(cx.fail("an anisotropic emulation of another access than a plain sample")); - }; - let Source::Combined(key) = s.source else { - return Err(cx.fail("an anisotropic emulation of a heap element")); - }; - let image = combined_image(cx, key)?; - let coord = super::emit::plane_coord(cx, fb, s)?; - // A cube's direction with its ties broken as Metal breaks them, whose face Metal reads. - let coord = match s.cube { - true => super::face::metal_ties(fb, coord)?, - false => coord, - }; - // The gradients, in the sample's own position. - let (dx, dy) = match lod { - Lod::Grad(dx, dy) | Lod::CubeGrad(dx, dy, _) => { - (cx.operand(fb, *dx)?, cx.operand(fb, *dy)?) - } - Lod::Hoisted => match grads { - Some(g) => g, - None => return Err(cx.fail("a hoisted anisotropic sample without its gradients")), - }, - Lod::Implicit { bias: None, .. } => ( - fb.derivative(DerivOp::DPdx, coord)?, - fb.derivative(DerivOp::DPdy, coord)?, - ), - // Metal's bias shifts the footprint's minor axis alone, in the level-0 size's texels. - Lod::Implicit { bias: Some(b), .. } => { - let b = cx.operand(fb, *b)?; - let b = super::emit::metal_bias(fb, b)?; - let (si, _, _) = super::emit::sampled_image(cx, fb, s.source)?; - let img = fb.image(si)?; - let zero = u32c(fb, 0)?; - let size = fb.query(ImageQuery::SizeLod(zero), img)?; - let size_lanes = image.plane + u8::from(image.arrayed); - super::emit::plane_axis_gradients(fb, coord, b, (size, size_lanes))? - } - _ => return Err(cx.fail("an anisotropic emulation of a sample at an explicit level")), - }; - let min_lod = match min_lod { - Some(m) => Some(cx.operand(fb, *m)?), - None => None, - }; - let layer = match s.layer { - Some(l) => Some(cx.operand(fb, l)?), - None => None, - }; - // A cube's face, and Metal's gradients on it. - let (face, on_face) = match lod { - Lod::CubeGrad(..) => { - let (face, on_face) = cube_face(fb, coord, (dx, dy))?; - (Some(face), on_face) - } - _ => (None, (dx, dy)), - }; - let site = Site { - coord, - grads: on_face, - face, - layer, - min_lod, - }; - let a = *a; - match a.degree { - Degree::Const(_) => { - let x = filter(cx, fb, s, (key, a), &site, offset)?; - super::emit::texel_value(cx, fb, s, image, x, None) - } - Degree::Slot(n) => { - // The plain sample where the bound sampler's word states no anisotropy. - let word = super::emit::sampler_word(cx, fb, super::Pixel::Spec(n))?; - let anisotropic = super::emit::word_states_any(fb, word, SamplerWord::ANISOTROPIC)?; - let plain = Sampling { - anisotropic: None, - ..s.clone() - }; - let emulation: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = filter(cx, fb, s, (key, a), &site, offset)?; - let x = super::emit::texel_value(cx, fb, s, image, x, None)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let device: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = super::emit::sampled_value(cx, fb, &plain, grads)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let Merged(merged) = fb.if_(cx, anisotropic, emulation, Some(device))?; - match merged[..] { - [x] => Ok(x), - _ => Err(cx.fail("an anisotropic sample without its merged result")), - } - } - } -} - -/// What a sample's emulation reads that its site computes: the coordinate and its gradients, a -/// cube's face, the array layer and the `min_lod_clamp`. -#[derive(Clone, Copy)] -struct Site { - /// The plane coordinate (normalized); a cube's direction, its ties broken as Metal breaks - /// them. - coord: SValue, - /// The plane coordinate's gradients (normalized); a cube's, Metal's gradients on its face. - grads: (SValue, SValue), - /// A cube's face, across which its taps step. - face: Option, - /// The array layer (an integer), for an array. - layer: Option, - /// The sample's `min_lod_clamp`. - min_lod: Option, -} - -/// The emulation's sum of the taps of sample `s` through binding `key` (the device's texels, before -/// the texel's conversion), as filter `a` takes it: its shape's routine's call -/// (`routine::Filter`), or its code in the open block where the texel offset is dynamic and takes -/// arms, which the site's samples read. -fn filter( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sampling, - (key, a): (BindingKey, Anisotropic), - site: &Site, - offset: &Option, -) -> BResult { - // Where the profile admits the `Offset` operand on a sample, the call passes the offset, a - // constant one too, and the taps' samples read it; else a constant offset is the shape's - // `ConstOffset`, and a dynamic one's arms are the site's. - let (offset, passed) = match offset { - Some(Offset::Dynamic(_, Some(_))) => { - let mut ops = ImageOperands::default(); - super::emit::offset_operands(cx, fb, offset, s.lanes, &mut ops)?; - return emulate(cx, fb, (s.source, s.lanes), a, site, ops); - } - Some(Offset::Dynamic(_, None)) => { - let mut ops = ImageOperands::default(); - super::emit::offset_operands(cx, fb, offset, s.lanes, &mut ops)?; - match ops.offset { - Some(v) => (None, Some(v)), - None => return Err(cx.fail("a dynamic texel offset without its operand")), - } - } - Some(Offset::Const(k)) if a.offset_operand => { - (None, Some(super::emit::const_offset(fb, k)?)) - } - Some(Offset::Const(k)) => (Some(k.clone()), None), - None => (None, None), - }; - let mut args = vec![site.coord, site.grads.0, site.grads.1]; - if let Some(face) = site.face { - args.extend([face.s, face.t]); - } - args.extend(site.layer); - args.extend(site.min_lod); - args.extend(passed); - let mut tys = Vec::with_capacity(args.len()); - for &v in &args { - tys.push(fb.value_ty(v)?); - } - let shape = Shape::Anisotropic(Filter { - binding: key, - filter: a, - lanes: s.lanes, - cube: site.face.is_some(), - layer: site.layer.is_some(), - min_lod: site.min_lod.is_some(), - offset, - passed_offset: passed.is_some(), - }); - let f = match cx.sampling.get(&shape, &tys) { - Some(f) => f, - None => { - let Shape::Anisotropic(r) = &shape else { - return Err(cx.fail("an anisotropic routine of another shape")); - }; - let mut rcx = cx.for_new_function(); - let made = define(&mut rcx, fb.module(), r, &tys); - cx.adopt(rcx); - let f = made?; - cx.sampling.insert(shape, tys, f); - f - } - }; - match fb.call(f, &args)? { - Some(x) => Ok(x), - None => Err(cx.fail("an anisotropic routine without its result")), - } -} - -/// Define the routine of emulation `r` (`routine::Filter`) in `mb`, its parameters of types `tys` -/// in [`filter`]'s order: the sum the emulation's code gave at the site, read from `r`'s binding -/// and its sampler's specializations. -fn define( - cx: &mut EmitCx<'_>, - mb: &mut ModuleBuilder, - r: &Filter, - tys: &[TypeId], -) -> BResult { - let f32_ = mb.ty(SType::Float { width: 32 })?; - let ret = mb.ty(SType::Vector { elem: f32_, len: 4 })?; - let mut fb = mb.kept_routine(ret)?; - let mut params = Vec::with_capacity(tys.len()); - for &ty in tys { - params.push(fb.param(ty)?); - } - let want = 3 - + 2 * usize::from(r.cube) - + usize::from(r.layer) - + usize::from(r.min_lod) - + usize::from(r.passed_offset); - if params.len() != want { - return Err(cx.fail("an anisotropic routine without its parameters")); - } - let mut params = params.into_iter(); - let (Some(coord), Some(dx), Some(dy)) = (params.next(), params.next(), params.next()) else { - return Err(cx.fail("an anisotropic routine without its coordinate")); - }; - let face = match r.cube { - true => match (params.next(), params.next()) { - (Some(s), Some(t)) => Some(Face { s, t }), - _ => return Err(cx.fail("an anisotropic routine without its face")), - }, - false => None, - }; - let layer = r.layer.then(|| params.next()).flatten(); - let min_lod = r.min_lod.then(|| params.next()).flatten(); - let passed = r.passed_offset.then(|| params.next()).flatten(); - let site = Site { - coord, - grads: (dx, dy), - face, - layer, - min_lod, - }; - let mut ops = ImageOperands::default(); - if let Some(k) = &r.offset { - ops.const_offset = Some(super::emit::const_offset(&mut fb, k)?); - } - ops.offset = passed; - let x = emulate( - cx, - &mut fb, - (Source::Combined(r.binding), r.lanes), - r.filter, - &site, - ops, - )?; - fb.ret(Some(x))?; - fb.finish() -} - -/// The emulation's sum in the open block for the sample of `source` (its coordinate of `lanes` -/// plane lanes) at `site` with offset operands `ops`: the level-0 size and the level count, the -/// sampler's degree and mip filter, then [`filtered`]. -fn emulate( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (source, lanes): (Source, u8), - a: Anisotropic, - site: &Site, - ops: ImageOperands, -) -> BResult { - let (si, _, _) = super::emit::sampled_image(cx, fb, source)?; - let img = fb.image(si)?; - let zero = u32c(fb, 0)?; - let size = fb.query(ImageQuery::SizeLod(zero), img)?; - let levels = fb.query(ImageQuery::Levels, img)?; - let at = At { - coord: site.coord, - grads: site.grads, - size, - levels, - min_lod: site.min_lod, - ops, - layer: site.layer, - face: site.face, - }; - let (la, mip, minified) = match (a.degree, a.mip, a.device) { - (Degree::Const(la), Mip::Const(mip), DeviceAnisotropy::Const(device)) => { - let la = i32c(fb, la.min(MOST_LOG as u32) as i32)?; - let mip = u32c(fb, mip_code(mip))?; - let minified = f32c(fb, minified_level(device))?; - (la, mip, minified) - } - (Degree::Slot(n), Mip::Word, DeviceAnisotropy::Filters(linear, nearest)) => { - let Some(&spec) = cx.decl.families.sampler.degrees.get(&n) else { - return Err(cx.fail(format!("sampler slot {n} has no anisotropy degree"))); - }; - let word = super::emit::sampler_word(cx, fb, super::Pixel::Spec(n))?; - let field = u32c(fb, SamplerWord::MIP_FILTER_SHIFT)?; - let mip = fb.binary(BinOp::ShiftRightLogical, word, field)?; - let three = u32c(fb, 3)?; - let mip = fb.binary(BinOp::BitwiseAnd, mip, three)?; - let i = int(fb)?; - let la = fb.convert(ConvOp::Bitcast, spec, i)?; - let most = i32c(fb, MOST_LOG)?; - let la = fb.glsl(GlslOp::SMin, &[la, most])?; - let minified = word_minified_level(fb, word, (linear, nearest))?; - (la, mip, minified) - } - _ => return Err(cx.fail("an anisotropic emulation of a mixed degree and mip filter")), - }; - let most = match a.degree { - Degree::Const(la) => 1 << la.min(MOST_LOG as u32), - Degree::Slot(_) => MOST_TAPS, - }; - filtered(cx, fb, (source, lanes), &at, (la, mip, minified), most) -} - -/// What a sample's emulation reads, taken in the sample's own position. -#[derive(Clone, Copy)] -struct At { - /// The plane coordinate (normalized); a cube's direction, its ties broken as Metal breaks - /// them. - coord: SValue, - /// The plane coordinate's gradients (normalized); a cube's, Metal's gradients on its face. - grads: (SValue, SValue), - /// The level-0 size (`u32` components, the layer count last for an array). - size: SValue, - /// The level count (`u32`). - levels: SValue, - /// The sample's `min_lod_clamp`. - min_lod: Option, - /// The sample's offset operands. - ops: ImageOperands, - /// The array layer (an integer), for an array. - layer: Option, - /// A cube's face, across which its taps step. - face: Option, -} - -/// A cube sample's face: the steps of its direction that move the face's normalized `s` and `t` -/// by one, `2 |m_a| σ_s e_s` and `2 |m_a| σ_t e_t` (`vec3`s), in Vulkan's face table ("Cube -/// Map Face Selection"), whose faces and their axes are Metal's. -#[derive(Clone, Copy)] -pub(super) struct Face { - pub(super) s: SValue, - pub(super) t: SValue, -} - -/// The face of cube direction `p` (its ties broken as Metal breaks them, so the major axis is -/// `emit::Major`'s), and Metal's gradients on it (`vec2`s, normalized) of the direction's `dx` and -/// `dy`: each without its normal component, `σ_s (g_s, g_t) / (2 |m_a|)` for `dx` and `σ_t (g_s, -/// g_t) / (2 |m_a|)` for `dy`, the face's two tangents `s` and `t` and their signs `σ` as Vulkan's -/// face table states them. That is Vulkan's face gradients of the two, `dx`'s `t` and `dy`'s `s` -/// mirrored where `σ_s σ_t` is `-1` (the `-x`, `-y` and `+z` faces): Metal under macOS 27 samples -/// a cube as it samples the face's 2D plane with these gradients (the Apple M3 Max, every inner -/// lane of each probed sampler equal, `emit::cube_footprint`'s `Face` form). -pub(super) fn cube_face( - fb: &mut FunctionBuilder<'_>, - p: SValue, - (dx, dy): (SValue, SValue), -) -> BResult<(Face, (SValue, SValue))> { - let f = float(fb)?; - let v2 = fb.module().ty(SType::Vector { elem: f, len: 2 })?; - let v3 = fb.module().ty(SType::Vector { elem: f, len: 3 })?; - let m = super::emit::Major::of(fb, p)?; - let [px, py, pz] = super::emit::components(fb, p)?; - let ma = fb.select(m.y, py, px)?; - let ma = fb.select(m.z, pz, ma)?; - let zf = f32c(fb, 0.0)?; - let negative = fb.binary(BinOp::FOrdLessThan, ma, zf)?; - let onef = f32c(fb, 1.0)?; - let minus = f32c(fb, -1.0)?; - // `σ_s`: `-sign(m_a)` on an `x` face, 1 on a `y` face, `sign(m_a)` on a `z` face. `σ_t`: - // `sign(m_a)` on a `y` face, -1 on the others. - let on_x = fb.select(negative, onef, minus)?; - let on_z = fb.select(negative, minus, onef)?; - let sigma_s = fb.select(m.z, on_z, on_x)?; - let sigma_s = fb.select(m.y, onef, sigma_s)?; - let on_y = fb.select(negative, minus, onef)?; - let sigma_t = fb.select(m.y, on_y, minus)?; - let mag = fb.glsl(GlslOp::FAbs, &[ma])?; - let two = f32c(fb, 2.0)?; - let span = fb.binary(BinOp::FMul, mag, two)?; - // The steps: `s` lies on `z` on an `x` face and on `x` on the others; `t` on `z` on a `y` - // face and on `y` on the others. - let s_len = fb.binary(BinOp::FMul, sigma_s, span)?; - let t_len = fb.binary(BinOp::FMul, sigma_t, span)?; - let s_on_x = fb.select(m.y_or_z, s_len, zf)?; - let s_on_z = fb.select(m.y_or_z, zf, s_len)?; - let s = fb.composite_construct(v3, &[s_on_x, zf, s_on_z])?; - let t_on_y = fb.select(m.y, zf, t_len)?; - let t_on_z = fb.select(m.y, t_len, zf)?; - let t = fb.composite_construct(v3, &[zf, t_on_y, t_on_z])?; - // Metal's gradients on the face. - let gradient = |fb: &mut FunctionBuilder<'_>, g: SValue, sigma: SValue| -> BResult { - let [gx, gy, gz] = super::emit::components(fb, g)?; - let gs = fb.select(m.y_or_z, gx, gz)?; - let gt = fb.select(m.y, gz, gy)?; - let gs = fb.binary(BinOp::FMul, gs, sigma)?; - let gt = fb.binary(BinOp::FMul, gt, sigma)?; - let gs = fb.binary(BinOp::FDiv, gs, span)?; - let gt = fb.binary(BinOp::FDiv, gt, span)?; - fb.composite_construct(v2, &[gs, gt]) - }; - let gx = gradient(fb, dx, sigma_s)?; - let gy = gradient(fb, dy, sigma_t)?; - Ok((Face { s, t }, (gx, gy))) -} - -/// Metal's mip filter code in the sampler word's field: 0 none, 1 nearest, 2 linear. -fn mip_code(mip: MipFilter) -> u32 { - match mip { - MipFilter::None => 0, - MipFilter::Nearest => 1, - MipFilter::Linear => 2, - } -} - -/// The level handed for level 0 where Metal minifies under a nearest mip filter or none, where the -/// device's sampler filters anisotropically (`device`) or not: [`MINIFIED_ZERO`] or -/// [`MINIFIED_NEAREST`]. -fn minified_level(device: bool) -> f32 { - match device { - true => MINIFIED_ZERO, - false => MINIFIED_NEAREST, - } -} - -/// [`minified_level`] of the device's sampler of a runtime sampler slot bound with sampler word -/// `word`, its anisotropy `(linear, nearest)` by the filters the word states -/// ([`DeviceAnisotropy::Filters`]); a word with a cubic filter takes the anisotropic one's. -fn word_minified_level( - fb: &mut FunctionBuilder<'_>, - word: SValue, - (linear, nearest): (bool, bool), -) -> BResult { - if linear == nearest { - return f32c(fb, minified_level(linear)); - } - let both = u32c(fb, SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR)?; - let filters = fb.binary(BinOp::BitwiseAnd, word, both)?; - let both_linear = fb.binary(BinOp::IEqual, filters, both)?; - let cubic = u32c(fb, SamplerWord::CUBIC)?; - let cubic = fb.binary(BinOp::BitwiseAnd, word, cubic)?; - let zero = u32c(fb, 0)?; - let cubic = fb.binary(BinOp::INotEqual, cubic, zero)?; - // The flags differ: the device's sampler is anisotropic where the word's filters are the - // anisotropic case's (both linear, or one nearest), or where it states a cubic filter. - let device = match linear { - true => both_linear, - false => fb.unary(UnOp::LogicalNot, both_linear)?, - }; - let device = fb.binary(BinOp::LogicalOr, device, cubic)?; - let zero_level = f32c(fb, MINIFIED_ZERO)?; - let nearest_level = f32c(fb, MINIFIED_NEAREST)?; - fb.select(device, zero_level, nearest_level) -} - -/// The emulation's sum of the device's texels of `source` (its coordinate of `lanes` plane lanes): -/// the footprint, then up to `most` taps. -/// `minified` is the level handed for level 0 where Metal minifies under a nearest mip filter or -/// none ([`minified_level`]). -fn filtered( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - src: (Source, u8), - at: &At, - (la, mip, minified): (SValue, SValue, SValue), - most: u32, -) -> BResult { - let f = float(fb)?; - let v2 = fb.module().ty(SType::Vector { elem: f, len: 2 })?; - let plane = fb.vector_shuffle(at.size, at.size, &[0, 1])?; - let texels = fb.convert(ConvOp::ConvertUToF, plane, v2)?; - let gx = fb.binary(BinOp::FMul, at.grads.0, texels)?; - let gy = fb.binary(BinOp::FMul, at.grads.1, texels)?; - let foot = footprint(fb, (gx, gy), (la, mip), at.levels)?; - let levels = read_levels(fb, &foot, at, (mip, minified))?; - // The taps' weights: `floor(256 / n)` each, the remainder one each to the middle taps. - let n = foot.n; - let full = i32c(fb, 256)?; - let each = fb.binary(BinOp::SDiv, full, n)?; - let used = fb.binary(BinOp::IMul, each, n)?; - let rem = fb.binary(BinOp::ISub, full, used)?; - let lo = fb.binary(BinOp::ISub, n, rem)?; - let one = i32c(fb, 1)?; - let lo = fb.binary(BinOp::ShiftRightArithmetic, lo, one)?; - let hi = fb.binary(BinOp::IAdd, lo, rem)?; - // The first tap's offset in texels along the major axis: `-(n - 1) s0 / 2`. - let nf = fb.convert(ConvOp::ConvertSToF, n, f)?; - let onef = f32c(fb, 1.0)?; - let span = fb.binary(BinOp::FSub, nf, onef)?; - let half = f32c(fb, 0.5)?; - let span = fb.binary(BinOp::FMul, span, half)?; - let taps = Taps { - at: *at, - u: foot.u, - s0: foot.s0, - span, - texels, - levels, - weights: (each, lo, hi), - }; - // Tap 0, then taps 1 to `n - 1` (at most `most`) in a loop of one tap's code that asks the - // driver not to unroll it: each tap's arithmetic and the sum's order are those of the taps - // written out one by one, so the answer is the same, and the driver compiles one tap instead - // of `most`. - let zero = i32c(fb, 0)?; - let first = tap(cx, fb, src, &taps, zero)?; - if most == 1 { - return Ok(first); - } - let i = int(fb)?; - let sum_ty = fb.value_ty(first)?; - let sum = fb.local_var(sum_ty, None)?; - let sum = fb.var_ptr(sum)?; - fb.store(sum, first, MemAccess::default())?; - let index = fb.local_var(i, None)?; - let index = fb.var_ptr(index)?; - let one = i32c(fb, 1)?; - fb.store(index, one, MemAccess::default())?; - let most = i32c(fb, most as i32)?; - let body: LoopFn<'_, EmitCx<'_>> = Box::new(move |fb, cx, lc| { - let j = fb.load(index, MemAccess::default())?; - let past_n = fb.binary(BinOp::SGreaterThanEqual, j, n)?; - let past_most = fb.binary(BinOp::SGreaterThanEqual, j, most)?; - let done = fb.binary(BinOp::LogicalOr, past_n, past_most)?; - let exit: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { - lc.break_(fb)?; - Ok(ArmEnd::Exits) - }); - fb.if_(cx, done, exit, None)?; - let t = tap(cx, fb, src, &taps, j)?; - let kept = fb.load(sum, MemAccess::default())?; - let total = fb.binary(BinOp::FAdd, kept, t)?; - fb.store(sum, total, MemAccess::default())?; - let one = i32c(fb, 1)?; - let next = fb.binary(BinOp::IAdd, j, one)?; - fb.store(index, next, MemAccess::default()) - }); - let spec = LoopSpec { - exit_sel: None, - unrolling: crate::spirv::ir::Unrolling::DontUnroll, - }; - fb.loop_(cx, spec, body)?; - fb.load(sum, MemAccess::default()) -} - -/// Metal's footprint of one sample (the module docs). -struct Footprint { - /// The level, held within the texture's levels. - lambda: SValue, - /// The level before it is held within the texture's levels: above 0 where Metal minifies. - raw: SValue, - /// The tap count (`i32`). - n: SValue, - /// The step direction in texels (`vec2`). - u: SValue, - /// The spacing in level-0 texels. - s0: SValue, -} - -/// Metal's footprint of gradients `gx`, `gy` (level-0 texels) through a sampler of degree `2^la` -/// (`i32`) and mip filter code `mip` (`u32`) on a texture of `levels` (`u32`) levels, its -/// logarithms and powers the device's `Log2` and `Exp2` (module docs). -fn footprint( - fb: &mut FunctionBuilder<'_>, - (gx, gy): (SValue, SValue), - (la, mip): (SValue, SValue), - levels: SValue, -) -> BResult { - let f = float(fb)?; - let i = int(fb)?; - let v2 = fb.module().ty(SType::Vector { elem: f, len: 2 })?; - let lx = length(fb, gx)?; - let ly = length(fb, gy)?; - let major = fb.glsl(GlslOp::FMax, &[lx, ly])?; - let x_major = fb.binary(BinOp::FOrdGreaterThanEqual, lx, ly)?; - let b2 = bool2(fb)?; - let pick = fb.composite_construct(b2, &[x_major, x_major])?; - let g = fb.select(pick, gx, gy)?; - let zf = f32c(fb, 0.0)?; - let some = fb.binary(BinOp::FOrdGreaterThan, major, zf)?; - let ux = fb.composite_extract(g, &[0])?; - let uy = fb.composite_extract(g, &[1])?; - let ux = fb.binary(BinOp::FDiv, ux, major)?; - let uy = fb.binary(BinOp::FDiv, uy, major)?; - let onef = f32c(fb, 1.0)?; - let ux = fb.select(some, ux, onef)?; - let uy = fb.select(some, uy, zf)?; - let u = fb.composite_construct(v2, &[ux, uy])?; - // A logarithm of no length: far below every level. - let none = f32c(fb, -1.0e9)?; - let lmaj = fb.glsl(GlslOp::Log2, &[major])?; - let lmaj = fb.select(some, lmaj, none)?; - let one = i32c(fb, 1)?; - // The determinant of the gradients. - let component = |fb: &mut FunctionBuilder<'_>, v: SValue, c: u32| -> BResult { - fb.composite_extract(v, &[c]) - }; - let (gxx, gyy) = (component(fb, gx, 0)?, component(fb, gy, 1)?); - let (gxy, gyx) = (component(fb, gx, 1)?, component(fb, gy, 0)?); - let p = fb.binary(BinOp::FMul, gxx, gyy)?; - let q = fb.binary(BinOp::FMul, gxy, gyx)?; - let det = fb.binary(BinOp::FSub, p, q)?; - let det = fb.glsl(GlslOp::FAbs, &[det])?; - let has_det = fb.binary(BinOp::FOrdGreaterThan, det, zf)?; - let ldet = fb.glsl(GlslOp::Log2, &[det])?; - // The minor axis's level, the major held at a texel or more; the major's past the degree. - let held = fb.glsl(GlslOp::FMax, &[lmaj, zf])?; - let lmin = fb.binary(BinOp::FSub, ldet, held)?; - let lmin = fb.select(has_det, lmin, none)?; - let laf = fb.convert(ConvOp::ConvertSToF, la, f)?; - let capped = fb.binary(BinOp::FSub, lmaj, laf)?; - let lv = fb.glsl(GlslOp::FMax, &[lmin, capped])?; - // The log ratio, the minor at a texel or more. - let excess = fb.binary(BinOp::FSub, ldet, lmaj)?; - let excess = fb.glsl(GlslOp::FMax, &[excess, zf])?; - let excess = fb.select(has_det, excess, zf)?; - let lr = fb.binary(BinOp::FSub, lmaj, excess)?; - // The tap count: the first count whose threshold the ratio does not pass, at most `2^la`. - let degree = fb.binary(BinOp::ShiftLeftLogical, one, la)?; - let mut n = degree; - for &(count, th) in COUNTS.iter().rev() { - let th = f32c(fb, th as f32 / 64.0)?; - let within = fb.binary(BinOp::FOrdLessThanEqual, lr, th)?; - let count = i32c(fb, count)?; - n = fb.select(within, count, n)?; - } - let n = fb.glsl(GlslOp::SMin, &[n, degree])?; - // The spacing: `major · g · S`. - let r = fb.glsl(GlslOp::Exp2, &[lr])?; - let degf = fb.convert(ConvOp::ConvertSToF, degree, f)?; - let rp = fb.glsl(GlslOp::FMin, &[r, degf])?; - let nf = fb.convert(ConvOp::ConvertSToF, n, f)?; - let half = f32c(fb, 0.5)?; - let two_g = fb.binary(BinOp::FSub, rp, onef)?; - let two_g = fb.binary(BinOp::FMul, two_g, half)?; - let mut kappa = f32c(fb, KAPPA.last().map_or(0.0, |&(_, k)| k))?; - for &(count, k) in KAPPA.iter().rev().skip(1) { - let c = i32c(fb, count)?; - let is = fb.binary(BinOp::IEqual, n, c)?; - let k = f32c(fb, k)?; - kappa = fb.select(is, k, kappa)?; - } - let share = fb.binary(BinOp::FDiv, rp, nf)?; - let short = fb.binary(BinOp::FSub, onef, share)?; - let short = fb.binary(BinOp::FMul, kappa, short)?; - let many_g = fb.binary(BinOp::FSub, onef, short)?; - let many_g = fb.binary(BinOp::FDiv, many_g, nf)?; - let two = i32c(fb, 2)?; - let is_two = fb.binary(BinOp::IEqual, n, two)?; - let g = fb.select(is_two, two_g, many_g)?; - // `S = 2^-past`: the level past 0, less the level past the texture's last under a mip filter. - let lvs = fb.glsl(GlslOp::FMax, &[lv, zf])?; - let zi = i32c(fb, 0)?; - let last = fb.convert(ConvOp::Bitcast, levels, i)?; - let last = fb.binary(BinOp::ISub, last, one)?; - let last = fb.glsl(GlslOp::SMax, &[last, zi])?; - let top = fb.convert(ConvOp::ConvertSToF, last, f)?; - let within = fb.glsl(GlslOp::FMin, &[lvs, top])?; - let zu = u32c(fb, 0)?; - let mipped = fb.binary(BinOp::INotEqual, mip, zu)?; - let lvc = fb.select(mipped, within, zf)?; - let past = fb.binary(BinOp::FSub, lvc, lvs)?; - let sc = fb.glsl(GlslOp::Exp2, &[past])?; - let gs = fb.binary(BinOp::FMul, g, sc)?; - let s0 = fb.binary(BinOp::FMul, major, gs)?; - let several = fb.binary(BinOp::SGreaterThan, n, one)?; - let s0 = fb.select(several, s0, zf)?; - // The level within the texture's levels. - let lambda = fb.glsl(GlslOp::FClamp, &[lv, zf, top])?; - Ok(Footprint { - lambda, - raw: lv, - n, - u, - s0, - }) -} - -/// Metal's length of gradient `v` (a `vec2`): `max(M + 3m/16, 49M/64 + 21m/32)`. -fn length(fb: &mut FunctionBuilder<'_>, v: SValue) -> BResult { - let x = fb.composite_extract(v, &[0])?; - let y = fb.composite_extract(v, &[1])?; - metal_length(fb, x, y) -} - -/// Metal's length of the gradient of components `x` and `y` (`f32`s): `max(M + 3m/16, 49M/64 + -/// 21m/32)` of their larger and smaller magnitude `M` and `m`, each product and sum rounded as -/// written (no contraction). -pub(super) fn metal_length(fb: &mut FunctionBuilder<'_>, x: SValue, y: SValue) -> BResult { - let x = fb.glsl(GlslOp::FAbs, &[x])?; - let y = fb.glsl(GlslOp::FAbs, &[y])?; - let big = fb.glsl(GlslOp::FMax, &[x, y])?; - let small = fb.glsl(GlslOp::FMin, &[x, y])?; - let term = |fb: &mut FunctionBuilder<'_>, p: f32, q: f32| -> BResult { - let pc = f32c(fb, p)?; - let qc = f32c(fb, q)?; - let a = fb.binary_with(BinOp::FMul, big, pc, Contraction::Forbidden)?; - let b = fb.binary_with(BinOp::FMul, small, qc, Contraction::Forbidden)?; - fb.binary_with(BinOp::FAdd, a, b, Contraction::Forbidden) - }; - let first = term(fb, 1.0, 0.1875)?; - let second = term(fb, 0.765_625, 0.656_25)?; - fb.glsl(GlslOp::FMax, &[first, second]) -} - -/// The level each tap reads ([`read_levels`]). -#[derive(Clone, Copy)] -struct Levels { - first: SValue, -} - -/// The level a tap reads at Metal's level `foot.lambda`, raised to the sample's `min_lod_clamp`, -/// by mip filter code `mip`: the level itself without a mip filter (so the device chooses its -/// minification or magnification filter by its sign), the nearer whole level under a nearest one -/// (`L + 1` past half a level), and the fractional level under a linear one, whose two levels the -/// device's own linear mip filter blends. Level 0 where Metal minifies is handed as -/// `MINIFIED_ZERO` under a linear mip filter and as `minified` under the others -/// ([`minified_level`], by the device's sampler's anisotropy): where its level before the -/// texture's levels hold it (`foot.raw`, with the clamp) is above 0, so a texture of one level -/// minifies as Metal does (an isotropic cube's threshold, `1 + 3/2048`, measured on a cube of one -/// level). -fn read_levels( - fb: &mut FunctionBuilder<'_>, - foot: &Footprint, - at: &At, - (mip, minified_nearest): (SValue, SValue), -) -> BResult { - let level = |fb: &mut FunctionBuilder<'_>, l: SValue| -> BResult { - match at.min_lod { - Some(m) => fb.glsl(GlslOp::FMax, &[l, m]), - None => Ok(l), - } - }; - let lf = level(fb, foot.lambda)?; - let raw = level(fb, foot.raw)?; - let zf = f32c(fb, 0.0)?; - let above = fb.binary(BinOp::FOrdGreaterThan, raw, zf)?; - let whole = fb.glsl(GlslOp::Floor, &[lf])?; - let q = fb.binary(BinOp::FSub, lf, whole)?; - let half = f32c(fb, 0.5)?; - let up = fb.binary(BinOp::FOrdGreaterThan, q, half)?; - let onef = f32c(fb, 1.0)?; - let next = fb.binary(BinOp::FAdd, whole, onef)?; - let nearest = fb.select(up, next, whole)?; - // Level 0 above Metal's 0 is handed as `MINIFIED_ZERO` or `minified_nearest`, which keep the - // device's minification filter. - let minified = f32c(fb, MINIFIED_ZERO)?; - let nearest_at_zero = fb.binary(BinOp::FOrdEqual, nearest, zf)?; - let lift = fb.binary(BinOp::LogicalAnd, nearest_at_zero, above)?; - let nearest = fb.select(lift, minified_nearest, nearest)?; - let at_zero = fb.binary(BinOp::FOrdEqual, lf, zf)?; - let lift = fb.binary(BinOp::LogicalAnd, at_zero, above)?; - let linear = fb.select(lift, minified, lf)?; - let one = u32c(fb, 1)?; - let two = u32c(fb, 2)?; - let is_nearest = fb.binary(BinOp::IEqual, mip, one)?; - let is_linear = fb.binary(BinOp::IEqual, mip, two)?; - let unfiltered = fb.select(lift, minified_nearest, lf)?; - let first = fb.select(is_nearest, nearest, unfiltered)?; - let first = fb.select(is_linear, linear, first)?; - Ok(Levels { first }) -} - -/// Everything a tap reads. -#[derive(Clone, Copy)] -struct Taps { - at: At, - u: SValue, - s0: SValue, - /// `(n - 1) / 2`. - span: SValue, - /// The plane's level-0 size as floats. - texels: SValue, - levels: Levels, - /// `floor(256 / n)`, and the taps from `lo` below `hi` that take one more 256th. - weights: (SValue, SValue, SValue), -} - -/// Tap `j`'s weighted texel (`vec4`), `j` an `int`, its samples made in the open block (and in -/// an arm of its own for the second level). -fn tap( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - (source, lanes): (Source, u8), - t: &Taps, - j: SValue, -) -> BResult { - let f = float(fb)?; - let jf = fb.convert(ConvOp::ConvertSToF, j, f)?; - let k = fb.binary(BinOp::FSub, jf, t.span)?; - let off = fb.binary(BinOp::FMul, k, t.s0)?; - let step = fb.binary(BinOp::VectorTimesScalar, t.u, off)?; - let step = fb.binary(BinOp::FDiv, step, t.texels)?; - // A cube's tap: the direction moved across its face by the step in the face's `s` and `t`, - // which the device projects back onto that face (or, past its edge, onto the next). - let step = match t.at.face { - Some(face) => { - let ds = fb.composite_extract(step, &[0])?; - let dt = fb.composite_extract(step, &[1])?; - let along_s = fb.binary(BinOp::VectorTimesScalar, face.s, ds)?; - let along_t = fb.binary(BinOp::VectorTimesScalar, face.t, dt)?; - fb.binary(BinOp::FAdd, along_s, along_t)? - } - None => step, - }; - let p = fb.binary(BinOp::FAdd, t.at.coord, step)?; - let p = match t.at.layer { - Some(l) => { - let lf = fb.convert(ConvOp::ConvertUToF, l, f)?; - let with_layer = fb.module().ty(SType::Vector { - elem: f, - len: lanes + 1, - })?; - fb.composite_construct(with_layer, &[p, lf])? - } - None => p, - }; - let (each, lo, hi) = t.weights; - let from = fb.binary(BinOp::SGreaterThanEqual, j, lo)?; - let below = fb.binary(BinOp::SLessThan, j, hi)?; - let middle = fb.binary(BinOp::LogicalAnd, from, below)?; - let one = i32c(fb, 1)?; - let zi = i32c(fb, 0)?; - let extra = fb.select(middle, one, zi)?; - let w = fb.binary(BinOp::IAdd, each, extra)?; - let w = fb.convert(ConvOp::ConvertSToF, w, f)?; - let inv = f32c(fb, 1.0 / 256.0)?; - let w = fb.binary(BinOp::FMul, w, inv)?; - let ops = t.at.ops; - let x = read(cx, fb, source, (p, ops), t.levels.first)?; - fb.binary(BinOp::VectorTimesScalar, x, w) -} - -/// The device's sample of `source` at `p` with offset operands `ops` at explicit level `lod`, from -/// a sampled image made in the open block. -fn read( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - source: Source, - (p, mut ops): (SValue, ImageOperands), - lod: SValue, -) -> BResult { - let (si, _, _) = super::emit::sampled_image(cx, fb, source)?; - ops.lod = Some(lod); - fb.sample(si, p, None, false, &ops) -} - -fn float(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Float { width: 32 }) -} - -fn int(fb: &mut FunctionBuilder<'_>) -> BResult { - fb.module().ty(SType::Int { - width: 32, - signed: true, - }) -} - -fn bool2(fb: &mut FunctionBuilder<'_>) -> BResult { - let b = fb.module().ty(SType::Bool)?; - fb.module().ty(SType::Vector { elem: b, len: 2 }) -} - -fn f32c(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult { - let f = float(fb)?; - let c = fb.module().constant(Constant::Scalar { - ty: f, - bits: ConstBits(u64::from(x.to_bits())), - })?; - fb.module().const_value(c) -} - -fn i32c(fb: &mut FunctionBuilder<'_>, x: i32) -> BResult { - let i = int(fb)?; - let c = fb.module().constant(Constant::Scalar { - ty: i, - bits: ConstBits(u64::from(x as u32)), - })?; - fb.module().const_value(c) -} - -fn u32c(fb: &mut FunctionBuilder<'_>, x: u32) -> BResult { - let c = fb.u32_const(x)?; - fb.module().const_value(c) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs b/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs deleted file mode 100644 index af20da20b..000000000 --- a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! Metal's anisotropic filter: where a sample takes the device's own filter, the module's shape and -//! the notes it records; every module validated by `spirv-val` under its profile. These are shape -//! tests. -//! -//! `llvm-as` assembles the fixtures; without it the tests skip visibly. - -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::air::abi::{Filter, MipFilter}; -use crate::device::profile::DeviceProfile; -use crate::device::requirements::VkFeature; -use crate::device::Device; -use crate::library::FunctionArtifact; -use crate::pipeline::artifact::PrecisionNote; -use crate::pipeline::testing::{compile, link_and_validate, llvm_assemble, profile, AssembleError}; - -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 public fixture's constexpr sampler words (bit 63 clear), the base of the states below. -const BASE_WORDS: u64 = 34901797601036873; - -const OP_IMAGE_SAMPLE_IMPLICIT_LOD: u16 = 87; -const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u16 = 88; -const OP_IMAGE_QUERY_LEVELS: u16 = 106; - -/// The constexpr sampler words of linear filters, mip filter `mip` and `maxAnisotropy` `aniso`. -fn words(mip: MipFilter, aniso: u32) -> u64 { - let mut s = super::super::constexpr::state_of([BASE_WORDS, 0]).expect("state"); - s.min_filter = Filter::Linear; - s.mag_filter = Filter::Linear; - s.mip_filter = mip; - s.max_anisotropy = aniso; - super::super::constexpr::state_words(&s)[0] -} - -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-anisotropic-{}-{}-{name}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).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 {name}: {why}\n{body}"), - } -} - -/// A fragment function sampling `texture2d` slot 0 at its position over 16 at its -/// implicit level, through the constexpr sampler of first state word `words`. -fn constexpr_fragment(words: u64) -> String { - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define <4 x float> @k(<4 x float> %pos, ptr addrspace(1) %t) {{ - %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> - %uv = fmul <2 x float> %xy, - %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) - %v = extractvalue {{ <4 x float>, i8 }} %r, 0 - ret <4 x float> %v -}} - -declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) - -!air.fragment = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !3}} -!1 = !{{!2}} -!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}} -!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.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -/// Committed profile `stem` without `samplerAnisotropy`: every Vulkan sampler is isotropic there, -/// so Metal's anisotropic filter is emulated (the emulation's home), the profile the emulation's -/// shape tests compile under. -fn p(stem: &str) -> DeviceProfile { - let mut desc = crate::pipeline::testing::description(stem).expect(stem); - desc.features.remove(&VkFeature::SamplerAnisotropy); - Device::from_queries(desc).expect(stem).profile().clone() -} - -/// Committed profile `stem` as described, `samplerAnisotropy` included: the device's own -/// anisotropic filter. -fn full(stem: &str) -> DeviceProfile { - profile(stem).expect(stem) -} - -fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc { - let a = compile(bc, entry, p).unwrap_or_else(|e| panic!("{entry}: compile: {e}")); - link_and_validate(&a, p).unwrap_or_else(|e| panic!("{entry}: L3: {e}")); - a -} - -/// The count of instructions of opcode `op` in `a`'s module. -fn count(a: &FunctionArtifact, op: u16) -> usize { - let words = &a.module.words; - let mut n = 0; - let mut i = 5; - while i < words.len() { - let len = ((words[i] >> 16) as usize).max(1); - n += usize::from((words[i] & 0xffff) as u16 == op); - i += len; - } - n -} - -/// The loops of `a`'s module whose `OpLoopMerge` asks the driver not to unroll them -/// (`LoopControl` `DontUnroll`, `0x2`). -fn dont_unroll_loops(a: &FunctionArtifact) -> usize { - const OP_LOOP_MERGE: u32 = 246; - const DONT_UNROLL: u32 = 0x2; - let words = &a.module.words; - let mut n = 0; - let mut i = 5; - while i < words.len() { - let len = ((words[i] >> 16) as usize).max(1); - if words[i] & 0xffff == OP_LOOP_MERGE && len >= 4 { - n += usize::from(words[i + 3] & DONT_UNROLL != 0); - } - i += len; - } - n -} - -/// A fragment's implicit-level sample through a constexpr sampler of `maxAnisotropy` 3, 8 and 16 -/// under a linear mip filter is the device's own sample on a device with `samplerAnisotropy` (the -/// runtime's floor requires it; MoltenVK's here): one implicit-level sample, unrecorded. An -/// isotropic sampler's is untouched too. -#[test] -fn a_constexpr_anisotropic_sample_takes_metals_filter() { - for aniso in [3, 8, 16] { - let what = format!("maxAnisotropy {aniso}"); - let Some(bc) = assemble(&what, &constexpr_fragment(words(MipFilter::Linear, aniso))) else { - return; - }; - let a = ok(&bc, "k", &full("moltenvk-m3")); - assert_eq!( - count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD), - 1, - "{what}, MoltenVK" - ); - assert!( - !a.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}" - ); - } - // An isotropic sampler is untouched. - let Some(bc) = assemble( - "isotropic", - &constexpr_fragment(words(MipFilter::Linear, 1)), - ) else { - return; - }; - let a = ok(&bc, "k", &full("lavapipe")); - assert_eq!(count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "isotropic"); - assert!(!a.precision.contains(&PrecisionNote::AnisotropicFilter)); -} - -/// A fragment function sampling slot 0, a texture of AIR type `tex_ty`, at its implicit level -/// through the constexpr sampler of first state word `words`: `call` makes `%v` (a `float4`) of -/// `%uv` (the position over 16) or `%uvw` (`%uv` and 0.5); `decl` is the intrinsic's declaration. -fn out_of_reach_fragment(words: u64, tex_ty: &str, call: &str, decl: &str) -> String { - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define <4 x float> @k(<4 x float> %pos, ptr addrspace(1) %t) {{ - %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> - %uv = fmul <2 x float> %xy, - %uvw = shufflevector <2 x float> %uv, <2 x float> , <3 x i32> - {call} - ret <4 x float> %v -}} - -declare {decl} - -!air.fragment = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !3}} -!1 = !{{!2}} -!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}} -!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.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -/// [`out_of_reach_fragment`]'s call and declaration of a cube's implicit-level sample. -const CUBE_CALL: &str = "%r = call { <4 x float>, i8 } @air.sample_texture_cube.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <3 x float> %uvw, i1 false, float 0.0, float 0.0, i32 0)\n %v = extractvalue { <4 x float>, i8 } %r, 0"; -const CUBE_DECL: &str = "{ <4 x float>, i8 } @air.sample_texture_cube.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, float, float, i32)"; - -/// An implicit-level sample out of the emulation's reach (a cube, a 3D texture, a depth texture, a -/// comparison) through a constexpr sampler of `maxAnisotropy` 8 is the device's own filter, and -/// records `DeviceAnisotropicFilter` (never `AnisotropicFilter`) on every device without -/// `samplerAnisotropy`: the sample stays at its implicit level, with no tap. With the feature -/// (MoltenVK's here) neither note is recorded. The same samples through an isotropic sampler record -/// neither. -#[test] -fn an_anisotropic_sample_out_of_reach_records_the_device_filter() { - let anisotropic = words(MipFilter::Linear, 8); - let isotropic = words(MipFilter::Linear, 1); - // `compare_func::less` in a constexpr sampler's first word. - let less = |w: u64| w & !(0xf << 16) | 1 << 16; - let depth = |what: &str| { - format!( - "%r = call {{ float, i8 }} @air.{what}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, i32 1, <2 x float> %uv,{} i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)\n %f = extractvalue {{ float, i8 }} %r, 0\n %v = insertelement <4 x float> , float %f, i64 0", - if what.starts_with("sample_compare") { " float 0.5," } else { "" } - ) - }; - let cases: [(&str, u64, u64, &str, String, &str); 4] = [ - ( - "cube", - anisotropic, - isotropic, - "texturecube", - CUBE_CALL.to_owned(), - CUBE_DECL, - ), - ( - "3d", - anisotropic, - isotropic, - "texture3d", - "%r = call { <4 x float>, i8 } @air.sample_texture_3d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <3 x float> %uvw, i1 true, <3 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)\n %v = extractvalue { <4 x float>, i8 } %r, 0".to_owned(), - "{ <4 x float>, i8 } @air.sample_texture_3d.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, <3 x i32>, i1, float, float, i32)", - ), - ( - "depth", - anisotropic, - isotropic, - "depth2d", - depth("sample_depth_2d.f32"), - "{ float, i8 } @air.sample_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, i1, <2 x i32>, i1, float, float, i32)", - ), - ( - "compare", - less(anisotropic), - less(isotropic), - "depth2d", - depth("sample_compare_depth_2d.f32"), - "{ float, i8 } @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32)", - ), - ]; - for (name, anisotropic, isotropic, tex_ty, call, decl) in &cases { - let text = out_of_reach_fragment(*anisotropic, tex_ty, call, decl); - let Some(bc) = assemble(name, &text) else { - return; - }; - for stem in ["lavapipe", "amd-780m-radv", "intel-irisxe-anv"] { - let what = format!("{name}, {stem}"); - let a = ok(&bc, "k", &p(stem)); - assert!( - a.precision - .contains(&PrecisionNote::DeviceAnisotropicFilter), - "{what}: {:?}", - a.precision - ); - assert!( - !a.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}" - ); - assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 0, "{what}"); - assert_eq!(dont_unroll_loops(&a), 0, "{what}"); - } - let a = ok(&bc, "k", &full("moltenvk-m3")); - assert!( - !a.precision - .contains(&PrecisionNote::DeviceAnisotropicFilter), - "{name}, MoltenVK" - ); - let text = out_of_reach_fragment(*isotropic, tex_ty, call, decl); - let Some(bc) = assemble(name, &text) else { - return; - }; - let a = ok(&bc, "k", &p("lavapipe")); - assert!( - !a.precision - .contains(&PrecisionNote::DeviceAnisotropicFilter), - "{name}, isotropic" - ); - } -} - -/// A kernel sampling `texturecube` slot 0 with explicit gradients through the constexpr -/// sampler of first state word `words`, writing the texel to buffer 0. -fn constexpr_cube_kernel(words: u64) -> String { - format!( - r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {words}, i64 0], align 8 - -define void @k(ptr addrspace(1) %t, ptr addrspace(1) %o, i32 %gid) {{ - %xf = uitofp i32 %gid to float - %y = fmul float %xf, 1.562500e-02 - %d = insertelement <3 x float> , float %y, i64 1 - %r = call {{ <4 x float>, i8 }} @air.sample_texture_cube_grad.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <3 x float> %d, <3 x float> , <3 x float> , float 0.000000e+00, i32 0) - %v = extractvalue {{ <4 x float>, i8 }} %r, 0 - %p = getelementptr <4 x float>, ptr addrspace(1) %o, i32 %gid - store <4 x float> %v, ptr addrspace(1) %p, align 16 - ret void -}} - -declare {{ <4 x float>, i8 }} @air.sample_texture_cube_grad.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, <3 x float>, <3 x float>, float, i32) - -!air.kernel = !{{!0}} -!air.sampler_states = !{{!6}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"o"}} -!5 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} -!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} -"# - ) -} - -/// A cube's explicit gradients through a constexpr sampler of `maxAnisotropy` 8 or 1 under a -/// linear mip filter keep the device's own gradient sample on `moltenvk-m3`, whose sampler is -/// anisotropic: Vulkan's rule's form, recorded as `CubeGradientFootprint`, with no level query and -/// no `AnisotropicFilter`. -#[test] -fn a_cubes_explicit_gradients_take_metals_level_and_taps() { - const GRAD: u32 = 0x4; - for aniso in [8, 1] { - let what = format!("maxAnisotropy {aniso}, moltenvk-m3"); - let Some(bc) = assemble( - &what, - &constexpr_cube_kernel(words(MipFilter::Linear, aniso)), - ) else { - return; - }; - let a = ok(&bc, "k", &full("moltenvk-m3")); - assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{what}"); - assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{what}"); - assert_eq!(gradient_masks(&a), vec![GRAD], "{what}"); - assert!( - !a.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}: {:?}", - a.precision - ); - // Vulkan's rule's form, the device's reading. - assert!( - a.precision.contains(&PrecisionNote::CubeGradientFootprint), - "{what}: {:?}", - a.precision - ); - } -} - -/// The `Grad` and `Lod` bits of each `OpImageSampleExplicitLod`'s image operands in `a`'s module. -fn gradient_masks(a: &FunctionArtifact) -> Vec { - let words = &a.module.words; - let mut out = Vec::new(); - let mut i = 5; - while i < words.len() { - let len = ((words[i] >> 16) as usize).max(1); - if (words[i] & 0xffff) as u16 == OP_IMAGE_SAMPLE_EXPLICIT_LOD && len > 5 { - out.push(words[i + 5] & 0x6); - } - i += len; - } - out -} diff --git a/crates/metal2vulkan/src/lower/sampler/constexpr.rs b/crates/metal2vulkan/src/lower/sampler/constexpr.rs index ab1b356e0..ec830f539 100644 --- a/crates/metal2vulkan/src/lower/sampler/constexpr.rs +++ b/crates/metal2vulkan/src/lower/sampler/constexpr.rs @@ -393,12 +393,12 @@ mod tests { (d.min_filter, d.mag_filter), (vk::Filter::NEAREST, vk::Filter::NEAREST) ); - // Anisotropy maps on every device: its Vulkan sampler is isotropic without the feature. + // Anisotropy maps where the device has `samplerAnisotropy`, which the runtime's floor + // requires; a device without it makes no anisotropic sampler (`check_sampler`). let mut s = state(FIXTURE_WORDS[0]); s.max_anisotropy = 8; let d = constexpr_desc(state_words(&s), SamplerUse::default(), &p).expect("maps"); - let aniso_ok = p.fields().images.sampler_anisotropy; - assert_eq!(d.max_anisotropy.is_some(), aniso_ok, "{d:?}"); + assert!(d.max_anisotropy.is_some(), "{d:?}"); // A bias beyond every device's limit. let mut s = state(FIXTURE_WORDS[0]); s.lod_bias = Half(0x7bff); // 65504 diff --git a/crates/metal2vulkan/src/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 88edd4f80..7514903d4 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -8,8 +8,8 @@ use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, OperandRule}; use crate::spirv::ids::{TypeId, Value as SValue}; use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, DerivOp, GlslOp, ImageOperands, ImageQuery, MemAccess, - Type as SType, UnOp, + BinOp, ConstBits, Constant, Contraction, ConvOp, DerivOp, GlslOp, ImageOperands, ImageQuery, + MemAccess, Type as SType, UnOp, }; use crate::air::ir::ValueId; @@ -415,8 +415,8 @@ fn scaled_axis_gradients( /// /// - [`CubeFootprint::Length`] (an isotropic sampler): each gradient's two tangent components /// combined by Metal's length, `max(M + 3m/16, 49M/64 + 21m/32)` of the larger and smaller -/// magnitude (the anisotropic emulation's, measured on 2D textures), on the tangent `(a + 2) mod -/// 3` alone. Vulkan's rule ("Cube Map Derivative Transformation") reads a gradient whose normal +/// magnitude (Metal's gradient length, measured on 2D textures; [`metal_length`]), on the +/// tangent `(a + 2) mod 3` alone. Vulkan's rule ("Cube Map Derivative Transformation") reads a gradient whose normal /// component is zero as `∂s_c / (2 |m_a|)` and `∂t_c / (2 |m_a|)`, so the device reads Metal's /// length whatever its approximation of a vector's (one component is nonzero); its level is its /// own logarithm of it, where Metal's piecewise-linear one minifies only past a footprint of @@ -535,7 +535,7 @@ fn tangent_length( // and `y` on a `z` face. let first = fb.select(m.y_or_z, gx, gy)?; let second = fb.select(m.z, gy, gz)?; - let length = super::anisotropic::metal_length(fb, first, second)?; + let length = metal_length(fb, first, second)?; // The tangent `(a + 2) mod 3`: `z` for an `x` face, `x` for a `y` face, `y` for a `z` // face. let on_x = fb.select(m.y, length, zero)?; @@ -849,11 +849,6 @@ pub(super) fn sampled_value( s: &Sampling, grads: Option<(SValue, SValue)>, ) -> BResult { - // Metal's anisotropic filter emulated by the device's samples at explicit levels; a runtime - // sampler's where its word states anisotropy, the rest of this path elsewhere. - if let Some(a) = s.anisotropic.as_ref() { - return super::anisotropic::sample(cx, fb, s, a, grads); - } let (si, image, live) = sampled_image(cx, fb, s.source)?; if let SampleOp::QueryLevel { min } = &s.op { let x = query_level(cx, fb, si, *min)?; @@ -1636,20 +1631,6 @@ pub(super) fn plane_axis_gradients( axis_gradients(fb, (dx, dy), bias, size, size_lanes) } -/// Whether sampler word `word` (a `u32`) has any bit of `bits`. -pub(super) fn word_states_any( - fb: &mut FunctionBuilder<'_>, - word: SValue, - bits: u32, -) -> BResult { - let m = fb.u32_const(bits)?; - let m = fb.module().const_value(m)?; - let zero = fb.u32_const(0)?; - let zero = fb.module().const_value(zero)?; - let have = fb.binary(BinOp::BitwiseAnd, word, m)?; - fb.binary(BinOp::INotEqual, have, zero) -} - /// The derivatives of plane coordinate `plane` (`lanes` floats) in the open block, scaled by /// `2^bias` ([`bias_gradients`]). fn plane_bias_gradients( @@ -1768,6 +1749,27 @@ fn word_min_level(fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult } /// The `f32` constant with bits `bits`. +/// Metal's length of the gradient of components `x` and `y` (`f32`s): `max(M + 3m/16, 49M/64 + +/// 21m/32)` of their larger and smaller magnitude `M` and `m`, each product and sum rounded as +/// written (no contraction). Measured on an Apple M4 under macOS 27.0.1, 2D textures sampled with +/// gradients through anisotropic samplers. +fn metal_length(fb: &mut FunctionBuilder<'_>, x: SValue, y: SValue) -> BResult { + let x = fb.glsl(GlslOp::FAbs, &[x])?; + let y = fb.glsl(GlslOp::FAbs, &[y])?; + let big = fb.glsl(GlslOp::FMax, &[x, y])?; + let small = fb.glsl(GlslOp::FMin, &[x, y])?; + let term = |fb: &mut FunctionBuilder<'_>, p: f32, q: f32| -> BResult { + let pc = f32_const(fb, p.to_bits())?; + let qc = f32_const(fb, q.to_bits())?; + let a = fb.binary_with(BinOp::FMul, big, pc, Contraction::Forbidden)?; + let b = fb.binary_with(BinOp::FMul, small, qc, Contraction::Forbidden)?; + fb.binary_with(BinOp::FAdd, a, b, Contraction::Forbidden) + }; + let first = term(fb, 1.0, 0.1875)?; + let second = term(fb, 0.765_625, 0.656_25)?; + fb.glsl(GlslOp::FMax, &[first, second]) +} + fn f32_const(fb: &mut FunctionBuilder<'_>, bits: u32) -> BResult { let f = f32_ty(fb)?; let c = fb.module().constant(Constant::Scalar { diff --git a/crates/metal2vulkan/src/lower/sampler/extended.rs b/crates/metal2vulkan/src/lower/sampler/extended.rs index 51f0bc544..250c8879b 100644 --- a/crates/metal2vulkan/src/lower/sampler/extended.rs +++ b/crates/metal2vulkan/src/lower/sampler/extended.rs @@ -550,9 +550,7 @@ pub(crate) fn emit( let f = match cx.sampling.get(&shape, &tys) { Some(f) => f, None => { - let Shape::Extended(r) = &shape else { - return Err(cx.fail("an extended-range routine of another shape")); - }; + let Shape::Extended(r) = &shape; let mut rcx = cx.for_new_function(); let made = define(&mut rcx, fb.module(), r, &tys); cx.adopt(rcx); diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests.rs b/crates/metal2vulkan/src/lower/sampler/face/tests.rs index 6aedd41c8..d6ed928f5 100644 --- a/crates/metal2vulkan/src/lower/sampler/face/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/face/tests.rs @@ -1,7 +1,6 @@ //! `metal_ties` on the interpreter against Metal's rule. Each kernel invocation reads a direction's -//! bits and writes the bits of the direction the device is handed. `anisotropic` checks -//! `emit::cube_footprint`'s gradients through a constexpr anisotropic sampler, and `routines` the -//! sampling routines' function controls. +//! bits and writes the bits of the direction the device is handed. `routines` checks the sampling +//! routines' function controls. use super::metal_ties; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; @@ -598,5 +597,4 @@ fn the_estimate_bounds_the_emitted_words() { } } -mod anisotropic; mod routines; diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/anisotropic.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/anisotropic.rs deleted file mode 100644 index 3654b75f5..000000000 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/anisotropic.rs +++ /dev/null @@ -1,300 +0,0 @@ -//! `emit::cube_footprint`, on the interpreter, against Metal's footprint. Each kernel invocation -//! reads a direction's bits and writes the bits of the gradient the device is handed for a constant -//! explicit gradient `g`. -//! -//! - Metal under macOS 27.0.1 (the Apple M3 Max, the probe `emit::cube_footprint` cites) reads, -//! on the direction's face, the face's two tangent components, `(σ_s g[s], σ_t g[t])` in -//! Vulkan's face orientation, `s` and `t` the axes of the face's `s_c` and `t_c` and `σ` their -//! signs, with `dPdx`'s `t` component and `dPdy`'s `s` component times `ρ = σ_s σ_t` through an -//! anisotropic sampler. Vulkan's cube derivative rule must read that from the `Face` form over -//! `2 |m_a|`, and nothing on the normal; and the `Length` form must hand Metal's length of the -//! two on one tangent. -//! -//! Through a runtime sampler `emit::word_footprint` hands one of those forms or the isotropic one -//! by the sampler's word (`emit::by_anisotropy`). - -use super::super::super::anisotropic::cube_face; -use super::super::super::emit::{by_anisotropy, cube_footprint}; -use super::super::super::CubeFootprint; -use super::{kernel_on, run_records}; -use crate::metal::sampler::SamplerWord; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::ir::{ConstBits, Constant, Type}; - -/// Vulkan's face of direction `d` ("Cube map face selection"; no ties among `d`'s magnitudes): -/// its major axis, and the axis and sign of its `s_c` and of its `t_c`. Metal's faces are the -/// same. -fn face_of(d: [f32; 3]) -> (usize, (usize, f32), (usize, f32)) { - let m = d.map(f32::abs); - let a = if m[2] >= m[0] && m[2] >= m[1] { - 2 - } else if m[1] >= m[0] { - 1 - } else { - 0 - }; - let positive = d[a] > 0.0; - let (s, t) = match (a, positive) { - (0, true) => ((2, -1.0), (1, -1.0)), - (0, false) => ((2, 1.0), (1, -1.0)), - (1, true) => ((0, 1.0), (2, 1.0)), - (1, false) => ((0, 1.0), (2, -1.0)), - (_, true) => ((0, 1.0), (1, -1.0)), - (_, false) => ((0, -1.0), (1, -1.0)), - }; - (a, s, t) -} - -/// The face gradient Metal reads under macOS 27 from gradient `g` (`dPdx` where `is_dx`, else -/// `dPdy`) at direction `d` through an anisotropic sampler, in Vulkan's face orientation. -fn metal_reading(g: [f32; 3], d: [f32; 3], is_dx: bool) -> [f32; 2] { - let (_, (s, s_sign), (t, t_sign)) = face_of(d); - let rho = s_sign * t_sign; - match is_dx { - true => [s_sign * g[s], rho * t_sign * g[t]], - false => [rho * s_sign * g[s], t_sign * g[t]], - } -} - -/// Metal's length of a gradient of components `x` and `y`: `max(M + 3m/16, 49M/64 + 21m/32)`. -fn metal_length(x: f32, y: f32) -> f32 { - let (big, small) = (x.abs().max(y.abs()), x.abs().min(y.abs())); - (big + small * 0.1875).max(big * 0.765_625 + small * 0.656_25) -} - -/// Directions on each of the six faces, at the face's center and off it. -fn directions() -> Vec<[f32; 3]> { - let mut out = Vec::new(); - for a in 0..3 { - for sign in [1.0f32, -1.0] { - for (u, v) in [(0.0f32, 0.0f32), (0.25, -0.5), (-0.75, 0.125)] { - let mut d = [0.0f32; 3]; - d[a] = 2.0 * sign; - d[(a + 1) % 3] = u; - d[(a + 2) % 3] = v; - out.push(d); - } - } - } - out -} - -/// The gradients `cube_footprint` hands the device in `form` for gradient `g` (as `dPdx` where -/// `is_dx`, else as `dPdy`), per direction of `lanes`. -fn handed_as(form: CubeFootprint, g: [f32; 3], lanes: &[[f32; 3]], is_dx: bool) -> Vec<[f32; 3]> { - let records: Vec = lanes.iter().flat_map(|d| d.map(f32::to_bits)).collect(); - let m = kernel_on(ModuleBuilder::new(), 3, &|f, p, _| { - let f32_ = f.module().ty(Type::Float { width: 32 })?; - let vec3 = f.module().ty(Type::Vector { elem: f32_, len: 3 })?; - let zero = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(0), - })?; - let zero = f.module().const_value(zero)?; - let mut c = Vec::new(); - for x in g { - let k = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(u64::from(x.to_bits())), - })?; - c.push(f.module().const_value(k)?); - } - let g = f.composite_construct(vec3, &c)?; - let other = f.composite_construct(vec3, &[zero, zero, zero])?; - let (dx, dy) = cube_footprint(f, p, (g, other), form)?; - let (dx2, dy2) = cube_footprint(f, p, (other, g), form)?; - let _ = (dy, dx2); - Ok(match is_dx { - true => dx, - false => dy2, - }) - }) - .expect("kernel"); - run_records(&m, &records, lanes.len()) -} - -/// The gradients `cube_footprint` hands the device in `form` for `dPdx` `g`, per direction of -/// `lanes`. -fn handed(form: CubeFootprint, g: [f32; 3], lanes: &[[f32; 3]]) -> Vec<[f32; 3]> { - handed_as(form, g, lanes, true) -} - -const GRADIENTS: [[f32; 3]; 3] = [[1.0, 2.0, 4.0], [-3.0, 0.5, -7.25], [0.0, -1.5, 6.0]]; - -/// Vulkan's rule reads Metal's macOS 27 face gradients from the `Face` form, for `dPdx` and -/// `dPdy` alike, the normal's component zero. -#[test] -fn a_face_footprint_keeps_metals_face_gradients() { - let lanes = directions(); - for g in GRADIENTS { - for is_dx in [true, false] { - for (d, h) in lanes - .iter() - .zip(handed_as(CubeFootprint::Face, g, &lanes, is_dx)) - { - let (a, (s, s_sign), (t, t_sign)) = face_of(*d); - assert_eq!(h[a], 0.0, "{d:?} {g:?}: the normal's component {h:?}"); - let read = [s_sign * h[s], t_sign * h[t]]; - let metal = metal_reading(g, *d, is_dx); - assert_eq!(read, metal, "{d:?} {g:?} dx {is_dx}: handed {h:?}"); - } - } - } -} - -/// The `Length` form hands Metal's length of the face's two tangent components on the tangent `(a -/// + 2) mod 3` alone, bit for bit, which Vulkan's rule and every Metal reading read alike. -#[test] -fn a_length_footprint_hands_metals_length_on_one_tangent() { - let lanes = directions(); - for g in GRADIENTS { - for (d, h) in lanes.iter().zip(handed(CubeFootprint::Length, g, &lanes)) { - let (a, (s, _), (t, _)) = face_of(*d); - let b = (a + 2) % 3; - let mut want = [0.0f32; 3]; - want[b] = metal_length(g[s], g[t]); - assert_eq!( - h.map(f32::to_bits), - want.map(f32::to_bits), - "{d:?} {g:?}: handed {h:?}" - ); - } - } -} - -/// What `by_anisotropy` hands the device for gradient `g` through a sampler of word `word`, per -/// direction of `lanes`, choosing between the gradients `cube_footprint` hands in form `set` and in -/// form `clear`. -fn by_word( - (set, clear): (CubeFootprint, CubeFootprint), - word: u32, - g: [f32; 3], - lanes: &[[f32; 3]], -) -> Vec<[f32; 3]> { - let records: Vec = lanes - .iter() - .flat_map(|d| [d[0].to_bits(), d[1].to_bits(), d[2].to_bits(), word]) - .collect(); - let m = kernel_on(ModuleBuilder::new(), 4, &|f, p, w| { - let f32_ = f.module().ty(Type::Float { width: 32 })?; - let vec3 = f.module().ty(Type::Vector { elem: f32_, len: 3 })?; - let mut c = Vec::new(); - for x in g { - let k = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(u64::from(x.to_bits())), - })?; - c.push(f.module().const_value(k)?); - } - let g = f.composite_construct(vec3, &c)?; - let a = cube_footprint(f, p, (g, g), set)?; - let i = cube_footprint(f, p, (g, g), clear)?; - Ok(by_anisotropy(f, w, a, i)?.0) - }) - .expect("kernel"); - run_records(&m, &records, lanes.len()) -} - -/// A runtime sampler's footprint by its word (`word_footprint`) takes, on every lane and bit for -/// bit, the anisotropic arm where the word states `SamplerWord::ANISOTROPIC`, whatever its other -/// fields, and the isotropic arm where it does not: the choice is `by_anisotropy`'s, between -/// whatever two forms it is given. -#[test] -fn a_footprint_by_the_word_takes_the_form_its_anisotropy_states() { - let lanes = directions(); - let others = SamplerWord::MIN_LINEAR - | SamplerWord::MAG_LINEAR - | (2 << SamplerWord::MIP_FILTER_SHIFT) - | SamplerWord::LEVEL_MAX; - let bits = - |v: &[[f32; 3]]| -> Vec<[u32; 3]> { v.iter().map(|x| x.map(f32::to_bits)).collect() }; - let (set, clear) = (CubeFootprint::Face, CubeFootprint::Length); - for g in GRADIENTS { - let (when_set, when_clear) = ( - bits(&handed(set, g, &lanes)), - bits(&handed(clear, g, &lanes)), - ); - assert_ne!(when_set, when_clear, "{g:?}"); - for (word, want) in [ - (0, &when_clear), - (others, &when_clear), - (SamplerWord::ANISOTROPIC, &when_set), - (SamplerWord::ANISOTROPIC | others, &when_set), - ] { - let got = bits(&by_word((set, clear), word, g, &lanes)); - assert_eq!(&got, want, "{g:?} {word:#x}"); - } - } -} - -/// The emulation's face of each direction of `lanes` and gradient `g` (`anisotropic::cube_face`): -/// `out` 0 and 1, Metal's face gradient of `g` as `dPdx` and as `dPdy` (on `x` and `y`, `z` 0); -/// 2 and 3, the steps of the direction that move the face's `s` and `t` by one. -fn emulated_face(g: [f32; 3], lanes: &[[f32; 3]], out: usize) -> Vec<[f32; 3]> { - let records: Vec = lanes.iter().flat_map(|d| d.map(f32::to_bits)).collect(); - let m = kernel_on(ModuleBuilder::new(), 3, &|f, p, _| { - let f32_ = f.module().ty(Type::Float { width: 32 })?; - let vec3 = f.module().ty(Type::Vector { elem: f32_, len: 3 })?; - let zero = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(0), - })?; - let zero = f.module().const_value(zero)?; - let mut c = Vec::new(); - for x in g { - let k = f.module().constant(Constant::Scalar { - ty: f32_, - bits: ConstBits(u64::from(x.to_bits())), - })?; - c.push(f.module().const_value(k)?); - } - let g = f.composite_construct(vec3, &c)?; - let other = f.composite_construct(vec3, &[zero, zero, zero])?; - let (face, (gx, _)) = cube_face(f, p, (g, other))?; - let (_, (_, gy)) = cube_face(f, p, (other, g))?; - let pair = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, v| { - let x = f.composite_extract(v, &[0])?; - let y = f.composite_extract(v, &[1])?; - f.composite_construct(vec3, &[x, y, zero]) - }; - match out { - 0 => pair(f, gx), - 1 => pair(f, gy), - 2 => Ok(face.s), - _ => Ok(face.t), - } - }) - .expect("kernel"); - run_records(&m, &records, lanes.len()) -} - -/// The anisotropic emulation's face of a cube direction takes Metal's macOS 27 face gradients -/// (`metal_reading`) over `2 |m_a|`, bit for bit (the directions' major magnitude is 2), for -/// `dPdx` and `dPdy` alike; and its steps move the direction along the face's `s` and `t` axes by -/// `2 |m_a|` times their signs, so the face coordinate Vulkan projects moves by one. -#[test] -fn the_emulations_face_takes_metals_gradients_and_steps() { - let lanes = directions(); - for g in GRADIENTS { - for (out, is_dx) in [(0, true), (1, false)] { - for (d, h) in lanes.iter().zip(emulated_face(g, &lanes, out)) { - let metal = metal_reading(g, *d, is_dx); - let want = [metal[0] / 4.0, metal[1] / 4.0, 0.0]; - assert_eq!( - h.map(f32::to_bits), - want.map(f32::to_bits), - "{d:?} {g:?} dx {is_dx}: {h:?}" - ); - } - } - } - for (out, axis) in [(2, 0), (3, 1)] { - for (d, h) in lanes.iter().zip(emulated_face(GRADIENTS[0], &lanes, out)) { - let (_, s, t) = face_of(*d); - let (on, sign) = [s, t][axis]; - let mut want = [0.0f32; 3]; - want[on] = 4.0 * sign; - assert_eq!(h, want, "{d:?}: step {axis} {h:?}"); - } - } -} diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index 9bd92bb01..dc68d93f7 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -123,7 +123,6 @@ //! sampled through several sampler candidates, the binding-array rule, and the bicubic forms //! [`bicubic`] refuses. -pub mod anisotropic; pub mod bicubic; mod constexpr; mod emit; @@ -653,10 +652,6 @@ pub struct Sampling { /// base-level size, which Metal reads, is not a power of two where the bound view's is /// (`position::offset_dropped`). pub offset_base: bool, - /// A sample through an anisotropic sampler that Metal's anisotropic filter, emulated by the - /// device's samples at explicit levels, answers ([`anisotropic`]): through a constexpr - /// sampler always, through a runtime sampler slot where its word states anisotropy. - pub anisotropic: Option, /// A fragment function's depth comparison whose reference the pipeline's private /// `fragmentDepthCompareClampMask` clamps (`LoweringInputs::depth_compare_clamp_mask`): the /// reference is clamped to `[0, 1]`, a NaN taken as 0, before every comparison @@ -973,9 +968,6 @@ pub struct RuntimeSlot { /// extended-range sample whose linear mip filter blends two levels (`extended::Level::Word`): /// the function reads its `SpecKey::SamplerMinLevel` specialization. pub min_level: bool, - /// An emulated anisotropic sample reads it ([`anisotropic`]): the function reads its word's - /// anisotropy and mip filter and its `SpecKey::SamplerAnisotropy` specialization. - pub emulated: bool, /// A Metal 4.1 read through it addresses its texel by its word (`texture::Through`): the /// function reads its word's address modes, border color, and mip filter. pub reads: bool, @@ -1085,9 +1077,6 @@ pub struct Declared { /// The `SamplerMinLevel` specialization constant (`u32`) of each runtime sampler slot a /// clamped LOD query outside a fragment function reads. pub min_levels: BTreeMap, - /// The `SamplerAnisotropy` specialization constant (`u32`) of each runtime sampler slot an - /// emulated anisotropic sample reads ([`anisotropic`]). - pub degrees: BTreeMap, /// The 2D bicubic samples' routine, when the module has one. pub bicubic_plane: Option, /// The 1D bicubic samples' routine, when the module has one. @@ -1353,14 +1342,6 @@ pub fn declare( let c = mb.spec(SpecKey::SamplerMinLevel(r.slot), u, ConstBits(0))?; d.min_levels.insert(*n, mb.const_value(c)?); } - if r.emulated { - let u = mb.ty(SType::Int { - width: 32, - signed: false, - })?; - let c = mb.spec(SpecKey::SamplerAnisotropy(r.slot), u, ConstBits(0))?; - d.degrees.insert(*n, mb.const_value(c)?); - } } for r in &plan.families.sampler.bicubic_routines { match r { @@ -1413,7 +1394,6 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error fetch_levels: false, anisotropy: false, min_level: false, - emulated: false, reads: false, }); } diff --git a/crates/metal2vulkan/src/lower/sampler/routine.rs b/crates/metal2vulkan/src/lower/sampler/routine.rs index 057947fd5..44dd38fc0 100644 --- a/crates/metal2vulkan/src/lower/sampler/routine.rs +++ b/crates/metal2vulkan/src/lower/sampler/routine.rs @@ -8,13 +8,9 @@ //! emulation as one routine that 256 sites call, declared `DontInline`, made in 0.39 s on the RTX //! 3090 where the 256 inlined copies took 10.2 s. //! -//! **What a routine holds.** One per shape ([`Shape`]): -//! - [`Filter`]: Metal's anisotropic filter emulated (`anisotropic`): the level-0 size and level -//! count, the sampler's degree and mip filter, the footprint, and the taps' samples at explicit -//! levels and their sum. -//! - [`Extended`]: an extended-range texture's sample (`extended`): the levels its mip filter -//! reads, the filter's footprint and addressing, the fetches and their decodes, the sums' calls, -//! the border and the swizzle. +//! **What a routine holds.** One per shape ([`Shape`]): [`Extended`], an extended-range texture's +//! sample (`extended`): the levels its mip filter reads, the filter's footprint and addressing, +//! the fetches and their decodes, the sums' calls, the border and the swizzle. //! //! The routine reads its binding's image and sampler variables and its slots' specialization //! constants (the runtime sampler's word, the offset tests) itself, so no image handle crosses a @@ -22,23 +18,15 @@ //! keeps the word's tests, the device's sample with its level, bias or gradients, and the texel's //! conversion: no implicit level crosses a call, so every answer is the one the inline code gave. //! -//! An anisotropic sample's call passes its coordinate (a cube's direction, its ties broken), its -//! gradients (a cube's on its face) and a cube's face steps, the array layer and the -//! `min_lod_clamp`, and its texel offset, constant or dynamic, where the profile admits the -//! `Offset` operand on a sample (`maintenance8` and `shaderImageGatherExtended`), which the taps' -//! samples take, so the samples at every offset call one routine; elsewhere a constant offset is -//! the shape's, as the taps' `ConstOffset`. The site keeps the gradients (no implicit derivative -//! crosses a call), the word's test, the plain arm and the texel's conversion of the sum. An -//! extended-range sample's call passes its coordinate, the array layer and the level its mip +//! An extended-range sample's call passes its coordinate, the array layer and the level its mip //! filter reads at (an explicit level, or the level of detail its site takes from derivatives or //! gradients), and its constant texel offset, which the routine places on each lane, so the //! samples at every offset call one routine; the site keeps the result's status word. //! //! **Not routines.** A heap image's sample (an argument buffer's), whose `NonUniform` handle a //! call would carry (a later step's check); a switch-at-use's shared emulation -//! (`sampler::shared_value`), which runs once already; a gather's fetches; an anisotropic sample -//! at a dynamic texel offset on a profile without the `Offset` operand on a sample, whose arms its -//! site's access reads; and the bicubic filter's site code. +//! (`sampler::shared_value`), which runs once already; a gather's fetches; and the bicubic filter's +//! site code. //! //! **The call's control.** A sampling routine is a kept routine (`ModuleBuilder::kept_routine`), //! declared `DontInline` on every device: a driver that honours the control (NVIDIA's) compiles @@ -47,18 +35,16 @@ //! //! **Census**. An extended-range sample's routine is counted once per shape the plan notes //! ([`note_extended`], `sampler::routine_words`), under `sampler.extended_range.routine` -//! (`extended::Sample::words` its site's). The census counts no anisotropic emulation, at its -//! sites or in a routine. +//! (`extended::Sample::words` its site's). use std::collections::HashMap; use crate::metal::format::ExtendedRange; use crate::spirv::ids::{FuncId, TypeId}; -use super::anisotropic::Anisotropic; use super::bicubic::Bicubic; use super::extended; -use super::{BindingKey, SamplerPlan}; +use super::SamplerPlan; /// The estimated words a routine adds besides its body: `OpFunction`, its parameters, the entry /// label, the return, and `OpFunctionEnd`. @@ -72,8 +58,6 @@ pub const CALL_WORDS: u32 = 32; /// argument types. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Shape { - /// Metal's anisotropic filter emulated (`anisotropic`). - Anisotropic(Filter), /// An extended-range texture's sample (`extended`). Extended(Box), } @@ -82,7 +66,6 @@ impl Shape { /// The census name of the shape's routines. pub fn census_name(&self) -> &'static str { match self { - Shape::Anisotropic(_) => "sampler.anisotropic.routine", Shape::Extended(_) => "sampler.extended_range.routine", } } @@ -91,41 +74,11 @@ impl Shape { /// the function's own. pub fn words(&self) -> u32 { match self { - Shape::Anisotropic(_) => FILTER_WORDS + ROUTINE_WORDS, Shape::Extended(e) => e.words + ROUTINE_WORDS, } } } -/// The estimated words of an anisotropic emulation's body (`anisotropic`), its taps past the first -/// in one loop: about 2,100 measured on a runtime slot's. -pub const FILTER_WORDS: u32 = 2_400; - -/// Metal's anisotropic filter emulated (`anisotropic`), as a sample of a texture slot through its -/// combined binding takes it. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Filter { - /// The sample's combined binding. - pub binding: BindingKey, - /// The sampler's degree, mip filter and the device's anisotropy. - pub filter: Anisotropic, - /// The coordinate's plane lanes (2; a cube direction's 3). - pub lanes: u8, - /// The sample reads a cube: its call passes the face's steps. - pub cube: bool, - /// The sample reads an array's layer. - pub layer: bool, - /// The sample states a `min_lod_clamp`. - pub min_lod: bool, - /// The constant texel offset the taps' samples take as `ConstOffset`, where the sample has one - /// and the profile admits no `Offset` operand on a sample. - pub offset: Option>, - /// The call passes the sample's texel offset, constant or dynamic, which the taps' samples - /// take as their `Offset` operand: on a profile that admits it on a sample (`maintenance8` - /// and `shaderImageGatherExtended`), so the samples at every offset call one routine. - pub passed_offset: bool, -} - /// An extended-range texture's sample (`extended::Sample`) without the operands its call passes: /// its coordinate, layer and the level its mip filter reads at. #[derive(Clone, Debug, PartialEq, Eq, Hash)] diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 5cda9cebe..c564f8693 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -16,7 +16,6 @@ use crate::lower::texture::{ TexelForm, TextureStrategy, }; use crate::memory::handles::Candidate; -use crate::metal::sampler::SamplerUse; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::{ImageAccess, SamplerRef, SlotClass, SlotRef, Stage}; @@ -1968,28 +1967,14 @@ fn select_one( } _ => false, }; - // Metal's anisotropic filter emulated by the device's samples at explicit levels, where it - // reaches the sample; the device's anisotropic filter, recorded, where it does not. - let anisotropic = super::anisotropic::select( - cx, - &op, - (stat.map(|(r, _)| r), image, shape), - (integer, observed, swizzle), - SamplerUse::new(compare, integer), - )?; // A cube's explicit gradients handed to the device in a form other than Metal's own: the - // footprint's note, but where a constexpr sampler's emulation answers every word of the - // sample (a runtime sampler's answers only the words its variant names). + // footprint's note. if let SampleOp::Sample { lod: Lod::CubeGrad(..), .. } = &op { - let emulated = - anisotropic.is_some_and(|a| matches!(a.degree, super::anisotropic::Degree::Const(_))); - if !emulated { - cx.precision.insert(PrecisionNote::CubeGradientFootprint); - } + cx.precision.insert(PrecisionNote::CubeGradientFootprint); } let result = cx.lowered_repr(Value::Inst(at), inst.ty)?; let value = id(cx, Value::Inst(at))?; @@ -2014,7 +1999,6 @@ fn select_one( cube, swizzle, offset_base, - anisotropic, clamp_reference, }; Ok(sampling) diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 63baa1799..1bb9af908 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1891,8 +1891,8 @@ fn identity_refusal(plan: &Plan) -> Option<(IdentityCause, String)> { BICUBIC_LINE_FORM, ), ( - (sampled.slots.values()).any(|r| r.min_level || r.emulated), - "a sampler argument whose minimum level or emulated filter the function specializes", + (sampled.slots.values()).any(|r| r.min_level), + "a sampler argument whose minimum level the function specializes", ), ]; if let Some((_, form)) = refused.iter().find(|(refused, _)| *refused) { diff --git a/crates/metal2vulkan/src/metal/sampler.rs b/crates/metal2vulkan/src/metal/sampler.rs index 26bd67925..b28c82a26 100644 --- a/crates/metal2vulkan/src/metal/sampler.rs +++ b/crates/metal2vulkan/src/metal/sampler.rs @@ -285,14 +285,12 @@ pub(crate) fn query_min_level(desc: &SamplerDescriptor) -> u32 { /// never disagree. /// /// Refusals, in this order: `MirrorClampToEdge` without `samplerMirrorClampToEdge`; comparison on -/// a portability-subset device without `mutableComparisonSamplers`. NaN or inverted LOD clamps are -/// invalid descriptors. A min or max reduction is no refusal: the sampler reads the weighted -/// average ([`vk_sampler`]). Nor is anisotropy above 1 without `samplerAnisotropy`: the Vulkan -/// sampler is isotropic there, and a function samples through it with Metal's anisotropic filter -/// emulated where the emulation reaches the sample (`PrecisionNote::AnisotropicFilter`) and the -/// device's isotropic filter, recorded, elsewhere (`PrecisionNote::DeviceAnisotropicFilter`). An -/// argument buffer's anisotropic sampler, whose anisotropy the function does not know, is refused -/// there where the binding plan checks it (`Unsupported`, `SamplerAnisotropy`). +/// a portability-subset device without `mutableComparisonSamplers`; `maxAnisotropy` above 1 for a +/// use that filters (any but an integer texture's) without `samplerAnisotropy` +/// (`Feature::SamplerAnisotropy`), every Vulkan sampler being isotropic there: a constexpr +/// sampler's where the function that samples through it is compiled, a runtime or argument +/// buffer's sampler's where it is made. NaN or inverted LOD clamps are invalid descriptors. A min +/// or max reduction is no refusal: the sampler reads the weighted average ([`vk_sampler`]). pub fn check_sampler( shape: &SamplerShape, use_: SamplerUse, @@ -313,6 +311,13 @@ pub fn check_sampler( Unsupported::needs(Feature::SamplerCompare, Capability::Feature(mutable)).into(), ); } + if shape.anisotropic && !use_.integer_texture && !images.sampler_anisotropy { + return Err(Unsupported::needs( + Feature::SamplerAnisotropy, + Capability::Feature(VkFeature::SamplerAnisotropy), + ) + .into()); + } if !shape.valid_lod_clamps { return Err(Error::InvalidDescriptor(DescriptorError::SamplerLodClamp)); } @@ -457,9 +462,9 @@ pub fn vk_sampler( /// Anisotropy is a quality bound in both APIs; Vulkan requires it within the limit. It is a /// filter, so an integer texture has none. A sampler with a nearest min or mag filter is handed /// its degree too: Vulkan leaves the anisotropic scheme to the implementation (ANV's filters a -/// nearest one linearly). A sampler on a device without `samplerAnisotropy` is handed none, where -/// the emulation's taps read the isotropic sampler -/// (`VUID-VkSamplerCreateInfo-anisotropyEnable-01070`: "If the samplerAnisotropy feature is not +/// nearest one linearly). A device without `samplerAnisotropy` makes no sampler of `maxAnisotropy` +/// above 1 for a use that filters ([`check_sampler`]; +/// `VUID-VkSamplerCreateInfo-anisotropyEnable-01070`: "If the samplerAnisotropy feature is not /// enabled, anisotropyEnable must be VK_FALSE"). pub(crate) fn device_anisotropy( desc: &SamplerDescriptor, @@ -469,29 +474,6 @@ pub(crate) fn device_anisotropy( desc.max_anisotropy > 1 && profile.fields().images.sampler_anisotropy && !use_.integer_texture } -/// [`device_anisotropy`] of an anisotropic sampler under `use_` on `profile`, by the filters a -/// sampler word states (`SamplerWord::MIN_LINEAR`, `SamplerWord::MAG_LINEAR`): `(linear, nearest)`, -/// its value where both filters are linear and where one is nearest. A word with a cubic filter -/// (`SamplerWord::CUBIC`) states neither: its other filter may be nearest or not. -pub(crate) fn device_anisotropy_by_filters( - use_: SamplerUse, - profile: &DeviceProfile, -) -> (bool, bool) { - let of = |min_filter, mag_filter| { - let desc = SamplerDescriptor { - min_filter, - mag_filter, - max_anisotropy: 2, - ..SamplerDescriptor::new() - }; - device_anisotropy(&desc, use_, profile) - }; - ( - of(SamplerMinMagFilter::Linear, SamplerMinMagFilter::Linear), - of(SamplerMinMagFilter::Nearest, SamplerMinMagFilter::Linear), - ) -} - /// The one border color a sampler replaces texels with, if any axis clamps to a border: the /// descriptor's, under `ClampToZero` as under `ClampToBorderColor`. Metal's `ClampToZero` reads /// the sampler's border color, not transparent black (an Apple M3 Max and an Apple M4, every probed @@ -2347,73 +2329,4 @@ mod tests { } } } - - /// The anisotropic emulation hands its level for level 0 by the device's sampler's anisotropy - /// (`lower::sampler::anisotropic`'s `minified_level`): a runtime sampler's by the filters its - /// word states (`device_anisotropy_by_filters`), which must be `vk_sampler`'s own flag - /// (`anisotropyEnable`, `max_anisotropy` set) for every sampler a word of those filters - /// states, on every committed profile, for the use the emulation reaches (no comparison, no - /// integer texture), whatever the sampler's other fields. - #[test] - fn the_word_filters_state_the_device_samplers_anisotropy() { - use SamplerMinMagFilter as F; - let mut checked = 0; - for (stem, desc) in committed_descriptions() { - let mut desc = desc; - desc.features.insert(VkFeature::SamplerAnisotropy); - desc.limits.max_sampler_anisotropy_bits = 16f32.to_bits(); - let dev = Device::from_queries(desc).unwrap(); - { - let use_ = SamplerUse::new(false, false); - let (linear, nearest) = device_anisotropy_by_filters(use_, dev.profile()); - for (min, mag) in [ - (F::Nearest, F::Nearest), - (F::Nearest, F::Linear), - (F::Linear, F::Nearest), - (F::Linear, F::Linear), - ] { - for mip in [ - SamplerMipFilter::NotMipmapped, - SamplerMipFilter::Nearest, - SamplerMipFilter::Linear, - ] { - for (degree, (lo, hi)) in [2, 3, 8, 16].into_iter().zip([ - (0.0, f32::MAX), - (0.25, 4.0), - (1.0, 2.5), - (0.0, 0.0), - ]) { - let d = SamplerDescriptor { - min_filter: min, - mag_filter: mag, - mip_filter: mip, - max_anisotropy: degree, - lod_min_clamp: lo, - lod_max_clamp: hi, - s_address_mode: SamplerAddressMode::Repeat, - ..metal_default() - }; - let Ok(made) = vk_sampler(&d, use_, dev.profile()) else { - continue; - }; - let word = SamplerWord::of(&d).0; - let both = SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR; - let stated = match word & both == both { - true => linear, - false => nearest, - }; - assert_eq!( - stated, - made.max_anisotropy.is_some(), - "{stem}: {d:?} under {use_:?}" - ); - assert_eq!(stated, device_anisotropy(&d, use_, dev.profile())); - checked += 1; - } - } - } - } - } - assert!(checked > 0); - } } diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index ea85f5a1e..2cbe9d0fa 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -119,7 +119,6 @@ mod serde_round_trips { primitive_id_indices: Some(metal::IndexType::UInt16), quad_primitive_ids: true, private_list: true, - anisotropic_samplers: BTreeSet::from([slot(Stage::Fragment, SlotClass::Sampler, 1)]), open_cl_lines: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 1)]), region_viewports: true, }); @@ -264,7 +263,6 @@ mod serde_round_trips { threadgroup_size_matches_tile_size: true, rotated_blends: BTreeSet::from([4, 6]), texture_write_rounding: metal::TextureWriteRoundingMode::NearestEven, - anisotropic_samplers: BTreeSet::from([slot(Stage::Fragment, SlotClass::Sampler, 3)]), open_cl_lines: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 2)]), uniform_varyings: BTreeSet::from([VaryingKey::user(b"user(tint)")]), instanced_attributes: BTreeSet::from([1]), diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 2233b4247..cc3559d36 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -690,10 +690,6 @@ pub enum PrecisionNote { /// select another level or filter than Metal's. A runtime or argument buffer's sampler takes /// the form its word's anisotropy states. /// - /// Not recorded where the module takes Metal's footprint itself through an anisotropic - /// constexpr sampler on a device without `samplerAnisotropy` (`lower::sampler::anisotropic`): - /// Metal's level and taps (`PrecisionNote::AnisotropicFilter`). - /// /// Also recorded for every cube access whose level comes from the fragment's derivatives (an /// implicit-level sample, one whose gradients a switch-at-use hoisted, or an LOD query): its /// level is the device's, of the direction handed to it, and Metal's rule there is not @@ -1052,58 +1048,6 @@ pub enum PrecisionNote { /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review, deferred until an exact path exists. HalfOutputPrecision, - /// The module samples a texture through an anisotropic sampler with Metal's anisotropic - /// filter emulated by the device's samples at explicit levels (`lower::sampler::anisotropic`), - /// on a device without `samplerAnisotropy`, every Vulkan sampler being isotropic there, each - /// tap the device's isotropic filter: a sample without comparison of a 2D texture or 2D array - /// at the fragment's implicit level or with explicit gradients, or of a cube or cube array with - /// explicit gradients, through a constexpr sampler of `maxAnisotropy` above 1, or through a - /// runtime sampler slot whose word states anisotropy (under that word alone). A device with - /// the feature samples with its own anisotropic filter. Metal's footprint (its gradient lengths, - /// level rule, tap count thresholds, tap weights and direction) is reproduced as measured on - /// an Apple M4 (the M3 Max answering identically), in the device's arithmetic: its `Log2` and - /// `Exp2` where Metal takes a piecewise-linear `log2` and its chords, the level and the - /// spacing unrounded where Metal rounds them to 256ths and 4096ths, and under a linear mip - /// filter the device's own blend of the two levels at the fractional level where Metal blends - /// them by 256ths. The residue: - /// - the level may differ from Metal's by its rounding (Metal's `log2` is within about - /// `0.006` of a level of the true one), and a tap count at a threshold may differ by one - /// count; - /// - the tap spacing is a fitted approximation for three or more taps below the cap (up to - /// about 18/256 of a texel at the outer tap of 10 or more taps), and otherwise the device's - /// unrounded value; - /// - the blend of two levels is the device's linear mip filter at the fractional level, within - /// its `mipmapPrecisionBits`; - /// - each tap is the device's own filter at the level the shader hands it, so its footprint - /// and sum are the device's (Metal's own on MoltenVK; elsewhere - /// [`PrecisionNote::DeviceSampling`]); - /// - a cube's taps step across the direction's face by Metal's face gradients (Metal under - /// macOS 27 samples a cube as the face's 2D plane, measured on the Apple M3 Max), the - /// direction moved and projected onto the face again by the device, and a tap past the - /// face's edge reads the next face as the device projects it, where Metal's is not measured. - /// - /// Measured against the M4's answers on `rgba8Unorm` - /// at `maxAnisotropy` 2 to 16, with Metal's logarithm and blend (the device's are not yet - /// measured there). With a linear filter, every channel is within a code: at most - /// 0.53 (mean up to 0.071) on lavapipe, 0.41 (0.027) on ANV (Iris Xe), 0.91 (0.043) on RADV - /// (Radeon 780M; its bilinear filter's own residue) and 0.68 (0.075) on an RTX 3090. An RTX - /// 3090's own anisotropic filter misses by up to 62 codes (mean 6.8). With a nearest filter, - /// the same on every device: up to 24.5 codes where a tap lies within the spacing's residue of - /// a texel edge and reads the neighbouring texel. That is 4 of 5,072 channels (mean up to - /// 0.024) at `maxAnisotropy` 8 or less, and 37 to 47 (mean up to 0.066) at 16. The 3090's own - /// nearest anisotropic filter misses by up to 194 (mean 16). Validation derives no tolerance - /// from it. - AnisotropicFilter, - /// The module samples a texture through a sampler whose anisotropy is known where Metal's - /// anisotropic filter is not emulated ([`PrecisionNote::AnisotropicFilter`]'s reach), on a - /// device without `samplerAnisotropy`, which filters it isotropically: a cube, a 3D texture, a - /// comparison, a sample whose residency the function observes, or a texture of another class - /// than its declared one, at an implicit level or with explicit gradients, through a constexpr - /// sampler of `maxAnisotropy` above 1 or a runtime sampler slot whose word states anisotropy - /// (under that word alone). An argument buffer's anisotropic sampler, whose anisotropy the - /// function does not know, is refused there (`SamplerAnisotropy`). Validation derives no - /// tolerance from it. - DeviceAnisotropicFilter, /// A vertex function writes `[[point_size]]`, or a mesh function that outputs points /// `set_point_size` (a line or triangle mesh's size draws nothing, and records no note), on a /// device whose `pointSizeRange` ends below Metal's largest point, 511 pixels @@ -2143,10 +2087,6 @@ impl PrecisionNote { "metal2vulkan-degrade-argument-pixel-sampler-scaling" } PrecisionNote::HalfOutputPrecision => "metal2vulkan-degrade-half-output-precision", - PrecisionNote::AnisotropicFilter => "metal2vulkan-degrade-anisotropic-filter", - PrecisionNote::DeviceAnisotropicFilter => { - "metal2vulkan-degrade-device-anisotropic-filter" - } PrecisionNote::DevicePointSize => "metal2vulkan-degrade-device-point-size", PrecisionNote::ClippedCoverageSplit => "metal2vulkan-degrade-clipped-coverage-split", PrecisionNote::LoopedSampleOutputs => "metal2vulkan-degrade-looped-sample-outputs", diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 5426dd345..ededc79e5 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -403,12 +403,6 @@ pub fn function_key( if inputs.texture_write_rounding != crate::metal::TextureWriteRoundingMode::TowardZero { h.bytes(b"texture-write-rounding-nearest-even"); } - // Appended only when set, as `signed_color_attachments`: a function bound to no anisotropic - // sampler keeps every key. - if !inputs.anisotropic_samplers.is_empty() { - h.bytes(b"anisotropic-samplers") - .bytes(format!("{:?}", inputs.anisotropic_samplers).as_bytes()); - } // Appended only when set, as `signed_color_attachments`: a kernel whose 1D images are bound as Apple's // OpenCL binds them keeps its key. if !inputs.open_cl_lines.is_empty() { diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index c75550790..51f1a2b04 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -663,7 +663,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", threadgroup_size_matches_tile_size: false", "") .replace(", rotated_blends: {}", "") .replace(", texture_write_rounding: TowardZero", "") - .replace(", anisotropic_samplers: {}", "") .replace(", open_cl_lines: {}", "") .replace(", uniform_varyings: {}", "") .replace(", instanced_attributes: {}", "") diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index d7ab5bee3..49058dfab 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -629,15 +629,6 @@ pub struct LoweringInputs { /// that writes no such texel, compiles as without it. #[cfg_attr(feature = "serde", serde(default))] pub texture_write_rounding: metal::TextureWriteRoundingMode, - /// The runtime sampler slots bound to a sampler whose word states anisotropy - /// (`VariantKey::anisotropic_samplers`): a sample through - /// such a slot that Metal's anisotropic filter, emulated, reaches - /// (`lower::sampler::anisotropic`) takes it where the slot's word states anisotropy and the - /// plain sample elsewhere. A slot the function samples through without being named here takes - /// the plain sample, with no emulation in the module: the binder names every slot whose bound - /// word states anisotropy. Empty for any other function. - #[cfg_attr(feature = "serde", serde(default))] - pub anisotropic_samplers: BTreeSet, /// With [`open_cl_mode`](Self::open_cl_mode), the kernel's texture slots of a 1D image /// (`RuntimeFact::OpenClLineTexture`) bound to a 1D or 1D array texture /// (`VariantKey::open_cl_lines`), where Apple's OpenCL binds a 2D texture of height 1: the diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 7d20bd827..4a740dd00 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -432,11 +432,6 @@ pub enum SpecKey { /// size, the parent's, is not a power of two. A slot bound to any other texture, or to none, /// takes 0. OffsetBaseAxes(SlotRef), - /// The degree the runtime sampler bound to the slot filters with (`u32`, default 0): `log2` - /// of its `maxAnisotropy` as Metal samples it (rounded up to a power of two; 32 for 17 to 31), - /// which an emulated anisotropic sample reads. A slot bound to an isotropic sampler, or to - /// none, takes 0. - SamplerAnisotropy(SlotRef), /// Boolean: the runtime sampler bound to the slot is a nearest pixel sampler of one level /// (default false): it reads pixel coordinates (`normalizedCoordinates` false) through nearest /// minification and magnification filters, without a mip filter and isotropically (its word diff --git a/crates/metal2vulkan/src/tests/engine_bias_reach.rs b/crates/metal2vulkan/src/tests/engine_bias_reach.rs index ae27eeaa5..2f9e70a68 100644 --- a/crates/metal2vulkan/src/tests/engine_bias_reach.rs +++ b/crates/metal2vulkan/src/tests/engine_bias_reach.rs @@ -441,10 +441,6 @@ fn an_anisotropic_sampler_takes_the_axis_gradients() { assert_eq!(s.glsl_count(GLSL_LENGTH), 2, "{what}"); s.reads_metals_bias(1, &what); assert!(a.precision.contains(&PrecisionNote::GradFromBias), "{what}"); - assert!( - !a.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}" - ); } } } diff --git a/crates/metal2vulkan/src/tests/engine_sampler_unk.rs b/crates/metal2vulkan/src/tests/engine_sampler_unk.rs index e01044346..e12d77455 100644 --- a/crates/metal2vulkan/src/tests/engine_sampler_unk.rs +++ b/crates/metal2vulkan/src/tests/engine_sampler_unk.rs @@ -309,18 +309,10 @@ fn explicit_cube_gradients_take_metals_footprint() { assert!(compiled >= 4, "{compiled}"); } -/// The textures `unk_cube_grad_lod` samples, a cube and a cube array, twice each: Metal's level and -/// taps of a cube's explicit gradients, emulated, is one sampling routine per texture -/// (`routine::Filter`), which each of its samples calls. -const CUBE_GRAD_TEXTURES: usize = 2; - /// An anisotropic constexpr sampler (`max_anisotropy(2)`, bits 20-23 of the state's first word) on /// a cube's explicit gradients takes Metal's footprint on every profile that compiles the isotropic -/// fixture. Without `samplerAnisotropy`, whose Vulkan sampler is isotropic, the shader takes -/// Metal's level and taps: each texture's routine, which its samples call, queries the level count -/// and loops over its taps, `AnisotropicFilter` is recorded and `CubeGradientFootprint` is not; -/// with the feature, and through the isotropic sampler on every profile, the device's sample at -/// Metal's footprint: no loop, no level query, `CubeGradientFootprint` recorded. Neither module +/// fixture, each with `samplerAnisotropy`: the device's sample at Metal's footprint, as through the +/// isotropic sampler: no loop, no level query, `CubeGradientFootprint` recorded. Neither module /// has a `Length`. #[test] fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { @@ -349,7 +341,7 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { let Some(i) = artifact(&iso, "unk_cube_grad_lod", &stem, &p) else { continue; }; - let shader = !p.fields().images.sampler_anisotropy; + assert!(p.fields().images.sampler_anisotropy, "{stem}"); assert_eq!(glsl(&i, GLSL_LENGTH), 0, "{stem}"); let samples = uses(&i, "sampler.sample_cube_grad") as usize; assert!(samples > 0, "{stem}"); @@ -359,10 +351,6 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { i.precision.contains(&PrecisionNote::CubeGradientFootprint), "{stem}" ); - assert!( - !i.precision.contains(&PrecisionNote::AnisotropicFilter), - "{stem}" - ); let a = artifact(&aniso, "unk_cube_grad_lod", &stem, &p) .unwrap_or_else(|| panic!("{stem}: the anisotropic sampler refused")); compiled += 1; @@ -372,20 +360,10 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { "{stem}" ); assert_eq!(glsl(&a, GLSL_LENGTH), 0, "{stem}"); - assert_eq!( - count(&a, OP_LOOP_MERGE), - if shader { CUBE_GRAD_TEXTURES } else { 0 }, - "{stem}" - ); - assert_eq!( - a.precision.contains(&PrecisionNote::AnisotropicFilter), - shader, - "{stem}: {:?}", - a.precision - ); - assert_eq!( + assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{stem}"); + assert_eq!(count(&a, OP_LOOP_MERGE), 0, "{stem}"); + assert!( a.precision.contains(&PrecisionNote::CubeGradientFootprint), - !shader, "{stem}: {:?}", a.precision ); @@ -395,8 +373,7 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() { /// Vulkan's cube-gradient rule: `moltenvk-m3` takes the device's own reading of the form handed /// to it: `unk_cube_grad_lod` through its isotropic sampler and through an anisotropic constexpr -/// one queries no level count, loops over no taps and records `CubeGradientFootprint`, not -/// `AnisotropicFilter`. +/// one queries no level count, loops over no taps and records `CubeGradientFootprint`. #[test] fn a_cube_gradient_route_takes_the_devices_reading() { let path = engine_dir().join("unk_cube_grad_lod.ll"); @@ -431,11 +408,6 @@ fn a_cube_gradient_route_takes_the_devices_reading() { assert!(samples > 0, "{what}"); assert_eq!(count(&u, OP_IMAGE_QUERY_LEVELS), 0, "{what}"); assert_eq!(count(&u, OP_LOOP_MERGE), 0, "{what}"); - assert!( - !u.precision.contains(&PrecisionNote::AnisotropicFilter), - "{what}: {:?}", - u.precision - ); assert!( u.precision.contains(&PrecisionNote::CubeGradientFootprint), "{what}: {:?}", diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c382dad5a..c412cac05 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2049,7 +2049,6 @@ field metal2vulkan::cache::SpecializationKey.data pub data: Vec field metal2vulkan::cache::SpecializationKey.entries pub entries: Vec field metal2vulkan::cache::VariantKey.addressed_function_tables pub addressed_function_tables: bool field metal2vulkan::cache::VariantKey.amplification_draws pub amplification_draws: Option -field metal2vulkan::cache::VariantKey.anisotropic_samplers pub anisotropic_samplers: BTreeSet field metal2vulkan::cache::VariantKey.call_threadgroups pub call_threadgroups: bool field metal2vulkan::cache::VariantKey.depth_clamp_range pub depth_clamp_range: bool field metal2vulkan::cache::VariantKey.dropped_colors pub dropped_colors: BTreeSet @@ -2537,7 +2536,6 @@ field metal2vulkan::pipeline::LoweringInputs.addressed_function_tables pub addre field metal2vulkan::pipeline::LoweringInputs.alpha_in_red_colors pub alpha_in_red_colors: BTreeSet field metal2vulkan::pipeline::LoweringInputs.alpha_test pub alpha_test: Option field metal2vulkan::pipeline::LoweringInputs.amplification_draws pub amplification_draws: Option -field metal2vulkan::pipeline::LoweringInputs.anisotropic_samplers pub anisotropic_samplers: BTreeSet field metal2vulkan::pipeline::LoweringInputs.arrayed_fetches pub arrayed_fetches: BTreeSet field metal2vulkan::pipeline::LoweringInputs.call_threadgroups pub call_threadgroups: bool field metal2vulkan::pipeline::LoweringInputs.color_writes pub color_writes: BTreeMap; 4]> @@ -8602,7 +8600,6 @@ variant metal2vulkan-runtime::PartialThreadgroupsSite::SimdGroups SimdGroups { w variant metal2vulkan-runtime::PartialThreadgroupsSite::Structure Structure { cause: PartialThreadgroupsCause } variant metal2vulkan-runtime::PartialThreadgroupsSite::Translator Translator variant metal2vulkan-runtime::PartialThreadgroupsSite::VoteWord VoteWord { static_length: u32, max: u32 } -variant metal2vulkan-runtime::PrecisionNote::AnisotropicFilter AnisotropicFilter variant metal2vulkan-runtime::PrecisionNote::ArgumentPixelSamplerScaling ArgumentPixelSamplerScaling variant metal2vulkan-runtime::PrecisionNote::BicubicFilterArithmetic BicubicFilterArithmetic variant metal2vulkan-runtime::PrecisionNote::BlendedWriteRounding BlendedWriteRounding @@ -8613,7 +8610,6 @@ variant metal2vulkan-runtime::PrecisionNote::CoverageReadsRoundedAlpha CoverageR variant metal2vulkan-runtime::PrecisionNote::CubeGradientFootprint CubeGradientFootprint variant metal2vulkan-runtime::PrecisionNote::DepthDenormals DepthDenormals variant metal2vulkan-runtime::PrecisionNote::DeviceAlphaCoverage DeviceAlphaCoverage -variant metal2vulkan-runtime::PrecisionNote::DeviceAnisotropicFilter DeviceAnisotropicFilter variant metal2vulkan-runtime::PrecisionNote::DeviceArithmetic DeviceArithmetic variant metal2vulkan-runtime::PrecisionNote::DeviceColorConversion DeviceColorConversion variant metal2vulkan-runtime::PrecisionNote::DeviceDenormals DeviceDenormals @@ -10007,7 +10003,6 @@ variant metal2vulkan::pipeline::OwnKernel::ExecutionCounts ExecutionCounts variant metal2vulkan::pipeline::OwnKernel::SamplesToBytes SamplesToBytes { aspect: SampleAspect, arrayed: bool } variant metal2vulkan::pipeline::PatchDomain::Quad Quad variant metal2vulkan::pipeline::PatchDomain::Triangle Triangle -variant metal2vulkan::pipeline::PrecisionNote::AnisotropicFilter AnisotropicFilter variant metal2vulkan::pipeline::PrecisionNote::ArgumentPixelSamplerScaling ArgumentPixelSamplerScaling variant metal2vulkan::pipeline::PrecisionNote::BicubicFilterArithmetic BicubicFilterArithmetic variant metal2vulkan::pipeline::PrecisionNote::BlendedWriteRounding BlendedWriteRounding @@ -10018,7 +10013,6 @@ variant metal2vulkan::pipeline::PrecisionNote::CoverageReadsRoundedAlpha Coverag variant metal2vulkan::pipeline::PrecisionNote::CubeGradientFootprint CubeGradientFootprint variant metal2vulkan::pipeline::PrecisionNote::DepthDenormals DepthDenormals variant metal2vulkan::pipeline::PrecisionNote::DeviceAlphaCoverage DeviceAlphaCoverage -variant metal2vulkan::pipeline::PrecisionNote::DeviceAnisotropicFilter DeviceAnisotropicFilter variant metal2vulkan::pipeline::PrecisionNote::DeviceArithmetic DeviceArithmetic variant metal2vulkan::pipeline::PrecisionNote::DeviceColorConversion DeviceColorConversion variant metal2vulkan::pipeline::PrecisionNote::DeviceDenormals DeviceDenormals @@ -10245,7 +10239,6 @@ variant metal2vulkan::pipeline::SpecKey::Presence Presence(SlotRef) variant metal2vulkan::pipeline::SpecKey::RenderAreaHeight RenderAreaHeight variant metal2vulkan::pipeline::SpecKey::RenderAreaWidth RenderAreaWidth variant metal2vulkan::pipeline::SpecKey::SampleCount SampleCount -variant metal2vulkan::pipeline::SpecKey::SamplerAnisotropy SamplerAnisotropy(SlotRef) variant metal2vulkan::pipeline::SpecKey::SamplerMinLevel SamplerMinLevel(SlotRef) variant metal2vulkan::pipeline::SpecKey::SparseTexture SparseTexture(SlotRef) variant metal2vulkan::pipeline::SpecKey::TexelBufferWords TexelBufferWords { stage: Stage, handles: bool } diff --git a/docs/API.md b/docs/API.md index deffdf748..8ef08ceb6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -277,7 +277,7 @@ the runtime's, the command line's, the compile worker's and every validation too 0-11 of the ID's word, a slot's pushed and a member's in the argument buffer). Any other function is refused as `Unsupported{IdentityDomains}`, whose cause (`Cause::Identity`) names the family of the first such form the function holds and whose symbol names the form: one that samples through an argument buffer's sampler or samples an - argument buffer's texture, emulates a sampler's anisotropy, samples a 1D + argument buffer's texture, samples a 1D texture through a bicubic filter, uses a slot's swizzle, a two-plane, extended-range or sRGB-twin form, reads an argument buffer's texture through another numeric type or as raw texels, or uses any other state of a texture or sampler @@ -2045,8 +2045,7 @@ category, and says what makes an operation carry the note and what may differ. E `PrecisionNote::CubeGradientFootprint`: An explicit-gradient sample of a cube texture takes Metal's footprint in the form Vulkan's rule reads, in every stage on every device. Cost: the sample takes the device's logarithm of Metal's footprint and, if anisotropic, the device's taps, - so a level or blend near a boundary can differ from Metal's. Where the shader takes Metal's level - and taps itself (`PrecisionNote::AnisotropicFilter`) this note is not recorded. + so a level or blend near a boundary can differ from Metal's. - `metal2vulkan-degrade-half-texel-conversion` (precision). `PrecisionNote::HalfTexelConversion`: The module reads, gathers, or samples a texture with a `half` result, the device's `float` texel rounded to nearest even on every device: within one `half` ulp of Metal's, but a 32-bit float @@ -2259,28 +2258,6 @@ category, and says what makes an operation carry the note and what may differ. E some channel written (`StageIo::half_blend_colors`, which the pipeline's stage reads), or its module names no math mode (under fast math the pipeline's stage records `PrecisionNote::HalfOutputFastMathBlend` instead). -- `metal2vulkan-degrade-anisotropic-filter` (precision). `PrecisionNote::AnisotropicFilter`: The - module samples a texture through an anisotropic sampler with Metal's anisotropic filter emulated - by the device's samples at explicit levels (`lower::sampler::anisotropic`), on a device without - `samplerAnisotropy`, every Vulkan sampler being isotropic there, each tap the device's isotropic - filter: a sample without comparison of a 2D texture or 2D array at the fragment's implicit - level or with explicit gradients, or of a cube or cube array with explicit gradients, through a - constexpr sampler of `maxAnisotropy` above 1, or through a runtime sampler slot whose word states - anisotropy (under that word alone). A device with the feature samples with its own anisotropic - filter. The footprint's logarithms and powers are the device's `Log2` and `Exp2`, its level and - spacing unrounded, and a linear mip filter's two levels the device's own blend at the fractional - level, where Metal takes a piecewise-linear `log2`, 256ths and 4096ths. Cost: a - cube's taps step across its face by Metal's face gradients, and a tap past the face's edge reads - the next face as the device projects it, which Metal's own is not measured against. -- `metal2vulkan-degrade-device-anisotropic-filter` (precision). - `PrecisionNote::DeviceAnisotropicFilter`: The module samples a texture through a sampler whose - anisotropy is known where Metal's anisotropic filter is not emulated - (`PrecisionNote::AnisotropicFilter`'s reach), on a device without `samplerAnisotropy`, which - filters it isotropically: a cube, a 3D texture, a comparison, a sample whose residency the - function observes, or a texture of another class than its declared one, at an implicit level or - with explicit gradients, through a constexpr sampler of `maxAnisotropy` above 1 or a runtime - sampler slot whose word states anisotropy (under that word alone). An argument buffer's - anisotropic sampler, which the function cannot record, is refused there (`SamplerAnisotropy`). - `metal2vulkan-degrade-device-point-size` (precision). `PrecisionNote::DevicePointSize`: A vertex function writes `[[point_size]]`, or a mesh function that outputs points `set_point_size`, on a device whose `pointSizeRange` ends below Metal's largest point, 511 pixels diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 79c5b32e7..6ec054fb0 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -26,7 +26,7 @@ Columns: | Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed | |---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 120 | 115 | 6 | 27 | 66 | 21 | 0 | +| Translator and front-end refusals | 120 | 116 | 6 | 27 | 66 | 21 | 0 | | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | @@ -39,7 +39,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 3 | 45 | 67 | 0 | 0 | 5 | +| Translator and front-end refusals | 0 | 0 | 3 | 46 | 67 | 0 | 0 | 4 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | @@ -101,7 +101,7 @@ Columns: | `StorageImageMultisample` | Multisampled storage images | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)`, `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot)` | `rare`: writable multisampled textures | | `StorageTextureInVertexStage` | Storage images in the vertex stage | devices short of a Vulkan feature the site names | `device` | via a helper: 1: `crates/metal2vulkan/src/lower/texture/slot.rs (stage_stores)` | `rare`: writable textures in vertex functions | | `CubeArray` | Cube arrays | devices without VkFeature::ImageCubeArray | `device` | 2: `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`, `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)` | `rare`: cube arrays on a device without imageCubeArray | -| `SamplerAnisotropy` | Sampler anisotropy an argument buffer lists, on a device without `samplerAnisotropy` | - | `-` | 0 | `app`: anisotropic samplers an argument buffer lists, on a device without samplerAnisotropy | +| `SamplerAnisotropy` | A sampler of `maxAnisotropy` above 1 for a use that filters, on a device without `samplerAnisotropy` (`metal::sampler::check_sampler`) | devices without VkFeature::SamplerAnisotropy | `device` | 1: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: anisotropic samplers on a device without samplerAnisotropy | | `SamplerBorderColor` | Sampler border colors Vulkan cannot express | devices without a capability the site computes (`missing`); devices without a capability the site computes (`need`); devices without a capability the site computes (`vec![need]`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/metal/sampler.rs (border_read, 4 sites)` | `app`: border colors a device cannot express | | `SamplerLodBias` | Sampler LOD bias | devices short of a Vulkan feature the site names; devices without VkLimit::MaxSamplerLodBias; every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (constexpr_desc, 3 sites)` | `app`: constexpr samplers with an LOD bias | | `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 | @@ -436,6 +436,7 @@ Each refusal's sites, with the function that builds it. - `feature::StorageImageMultisample`: `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot)` - `feature::StorageTextureInVertexStage`: `crates/metal2vulkan/src/lower/texture/slot.rs (stage_stores)` - `feature::CubeArray`: `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)` +- `feature::SamplerAnisotropy`: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `feature::SamplerBorderColor`: `crates/metal2vulkan/src/metal/sampler.rs (border_read, 4 sites)` - `feature::SamplerLodBias`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (constexpr_desc, 3 sites)` - `feature::SamplerCompare`: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index 0ae9bb80e..c8850445d 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -51,7 +51,7 @@ feature GatherExtended rare gathers with dynamic offsets or components feature StorageImageMultisample rare writable multisampled textures feature StorageTextureInVertexStage rare writable textures in vertex functions feature CubeArray rare cube arrays on a device without imageCubeArray -feature SamplerAnisotropy app anisotropic samplers an argument buffer lists, on a device without samplerAnisotropy +feature SamplerAnisotropy app anisotropic samplers on a device without samplerAnisotropy feature SamplerBorderColor app border colors a device cannot express feature SamplerLodBias app constexpr samplers with an LOD bias feature SamplerCompare app compare samplers a device cannot apply to the image