From 0709ba7ba5b1046fbc0debe5dc762df8cc3c03a7 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 01:55:35 -0800 Subject: [PATCH] A sampler state's lodBias moves the level on a device presenting an Intel or AMD Mac What: vk_sampler set mipLodBias 0 whatever the descriptor's lodBias, read as Apple9 (an Apple M3 Max samples every level as with no bias). The consumer's oracle (an AMD Radeon Pro 5300M and an Intel UHD 630) shows a Mac with an Intel or AMD GPU adds the bias to every sample's level, explicit (level()), gradient and implicit alike, clamped into the texture's levels. So a guest presenting such a Mac read the wrong level. How: the translator's SamplerUse gains lod_bias (with_lod_bias), a fact the consumer states per bind from the Mac it presents; a plan's uses leave it unset. With it, vk_sampler's mipLodBias is device_lod_bias's (new, public): the bias within the device's maxSamplerLodBias, the limit of its sign past it (Capped), none for a NaN (NotANumber) and none where the portability subset withholds samplerMipLodBias (Withheld). Without it, 0 as before; a use of texel coordinates takes none either way. Vulkan adds mipLodBias to an explicit level too, so the device's sampler gives the measured answer within the limit. The runtime keeps the resolved MacClass in DeviceProperties (one place, presented_class; lossless_compression derives from it). A state's taken descriptor keeps its bias on IntelOrAmd (-0 as 0, NaN as none) and 0 on AppleSilicon, and SamplerState::bound_use adds the flag at every bind: a slot's, an argument sampler's, a heap set's array element, and the attached-levels reckoning of the levels a draw samples. A bias the device cannot take as it is is announced once as the state is made, the new precision kind CappedLodBias (capped-lod-bias), never fatal. Docs: vk_sampler, SamplerDescriptor::lod_bias, the runtime sampler module, MacClass and DeviceOptions::mac_class name the answer per class; API.md's catalogue lists capped-lod-bias and the Mac-class section the bias. The api_surface and api_signatures tables take DeviceLodBias, device_lod_bias, SamplerUse::lod_bias/with_lod_bias and the new kind. REFUSALS.md regenerated unchanged. Tests: metal::sampler's a_lod_bias_is_the_device_s_where_the_use_adds_it (every committed profile, both uses) and the_device_lod_bias_is_the_bias_within_what_the_device_takes (exact, capped finite and infinite, NaN, withheld on MoltenVK's profile); tests::sampler takes the bias per class; the lane's lod_bias tests a device presenting each class: AppleSilicon reads the unbiased level (kernel explicit, fragment implicit), IntelOrAmd the biased one, the capped ones announced once (CAPPED_LOD_BIAS, listed as a site). Evidence: potluck jobs in the report to main. --- crates/metal2vulkan-runtime/src/binding.rs | 4 +- .../metal2vulkan-runtime/src/capabilities.rs | 46 ++- .../metal2vulkan-runtime/src/degradation.rs | 14 + .../metal2vulkan-runtime/src/device/create.rs | 3 +- .../src/families/features.rs | 8 +- crates/metal2vulkan-runtime/src/heap_sets.rs | 2 +- .../src/render/attached_levels.rs | 2 +- crates/metal2vulkan-runtime/src/sampler.rs | 104 +++++- .../metal2vulkan-runtime/src/tests/sampler.rs | 75 ++++- .../src/runtime_lane/degrade_notices.rs | 4 + .../src/runtime_lane/lod_bias.rs | 300 ++++++++++++++++-- crates/metal2vulkan/src/bind/state.rs | 18 +- crates/metal2vulkan/src/metal/sampler.rs | 195 ++++++++++-- crates/metal2vulkan/tests/api_signatures.tsv | 10 + crates/metal2vulkan/tests/api_surface.rs | 2 + docs/API.md | 20 ++ 16 files changed, 708 insertions(+), 99 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 30295928a..43eb75717 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -1954,7 +1954,7 @@ fn image_descriptor( let desc = metal2vulkan::bind::sampler_desc( device.compile_device(), &descriptor, - use_, + state.bound_use(use_), opaque_black, format, ) @@ -2158,7 +2158,7 @@ fn image_descriptor( let desc = metal2vulkan::bind::sampler_desc( device.compile_device(), state.descriptor(), - SamplerUse::new(*compare, *integer), + state.bound_use(SamplerUse::new(*compare, *integer)), OpaqueBlackBorder::Stated, None, ) diff --git a/crates/metal2vulkan-runtime/src/capabilities.rs b/crates/metal2vulkan-runtime/src/capabilities.rs index d5a0656cc..78cb241a9 100644 --- a/crates/metal2vulkan-runtime/src/capabilities.rs +++ b/crates/metal2vulkan-runtime/src/capabilities.rs @@ -201,6 +201,8 @@ pub struct DeviceProperties { /// The compile layer lowers an `interpolant` read at its centroid, a sample or an offset /// ([`DeviceProperties::supports_pull_model_interpolation`]). pull_model_interpolation: bool, + /// The class of Mac the device presents ([`presented_class`]). + mac_class: MacClass, } /// What [`DeviceProperties::new`] reads of the physical device itself, beside the description @@ -249,10 +251,11 @@ pub(crate) fn working_set_buffer_bound(working_set: u64) -> u64 { /// The class of Mac a device presents, whose GPU decides answers Metal gives without a property /// of its own: what a new `Private` texture reads before anything writes it, the encoding a GPU -/// blit through a compressed texture writes, a `half` NaN clear's sign, and how far a `Clear` +/// blit through a compressed texture writes, a `half` NaN clear's sign, how far a `Clear` /// load reaches past the render area of a pass without a draw call (docs/API.md, the accepted -/// differences). Every Mac's Metal answers one class's way, by the GPU it has (Apple -/// silicon, or an Intel or AMD GPU); the runtime answers the class the consumer declares +/// differences), and whether a sampler state's `lodBias` moves its samples' level +/// (`SamplerDescriptor::lod_bias`). Every Mac's Metal answers one class's way, by the GPU it has +/// (Apple silicon, or an Intel or AMD GPU); the runtime answers the class the consumer declares /// ([`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class)), else the one of the device's /// GPU ([`MacClass::of_vendor`]), and states it as /// [`DeviceProperties::lossless_compression`]. No Metal counterpart: a Mac's GPU is what it is. @@ -268,7 +271,9 @@ pub enum MacClass { /// whole level and slice past the render area, and any other texture's render area rounded /// up to 32x32 tiles, as a pass with a draw call clears every texture, other levels and /// slices untouched (our probes and the consumer's on the M3 Max). The runtime writes the pattern and the zeros (a pattern no clear or copy writes - /// exactly reads zero, announced as `fresh-pattern-zeroed`), and clears so. + /// exactly reads zero, announced as `fresh-pattern-zeroed`), and clears so. Its GPU samples + /// every level through a sampler state as with no LOD bias, whatever the state's `lodBias` + /// (an Apple M3 Max, Apple9): so does the runtime. AppleSilicon, /// A Mac with an Intel or AMD GPU, which keeps no texture compressed: a new `Private` /// texture holds what its memory held (zero, or a released texture's texels: an Intel UHD @@ -279,7 +284,12 @@ pub enum MacClass { /// (`WorkCounts::private_textures_zero_filled`). A `Clear` load in a pass of one layer /// without a draw call clears the whole level and slice past the render area, the AMD Radeon /// Pro 5300M's answer; an Intel UHD 630 clears anything from the render area alone to the - /// whole texture there, by format and shape (the consumer's probes). + /// whole texture there, by format and shape (the consumer's probes). Its GPU adds a sampler + /// state's `lodBias` to every sample's level, an explicit level's, a gradient's and an + /// implicit one's alike, the sum clamped into the texture's levels (both GPUs, the + /// consumer's probes): so does the runtime, through the device's `mipLodBias`, within its + /// `maxSamplerLodBias` (`Degradation::CappedLodBias` past it, and where the device's + /// portability subset withholds `samplerMipLodBias`). IntelOrAmd, } @@ -298,13 +308,14 @@ impl MacClass { } } -/// Whether the Mac a device of `identity`, its class declared as `declared`, presents keeps -/// textures losslessly compressed ([`DeviceProperties::lossless_compression`]): the one place the -/// runtime decides it. Every answer that differs between an Apple silicon Mac and a Mac with an -/// Intel or AMD GPU because the first compresses (a new `Private` texture's contents, a blit's -/// canonical encodings, a `half` NaN clear's sign) reads that field, and nothing else decides it. -fn presents_lossless_compression(identity: &DeviceIdentity, declared: Option) -> bool { - declared.unwrap_or_else(|| MacClass::of_vendor(identity.vendor_id)) == MacClass::AppleSilicon +/// The class of Mac a device of `identity`, its class declared as `declared`, presents: the one +/// place the runtime decides it. Every answer that differs between an Apple silicon Mac and a Mac +/// with an Intel or AMD GPU reads it: because the first compresses +/// ([`DeviceProperties::lossless_compression`]: a new `Private` texture's contents, a blit's +/// canonical encodings, a `half` NaN clear's sign), and because the second adds a sampler's LOD +/// bias to every sample's level (`sampler.rs`). +fn presented_class(identity: &DeviceIdentity, declared: Option) -> MacClass { + declared.unwrap_or_else(|| MacClass::of_vendor(identity.vendor_id)) } impl DeviceProperties { @@ -317,7 +328,8 @@ impl DeviceProperties { compile: &metal2vulkan::device::Device, mac_class: Option, ) -> DeviceProperties { - let lossless_compression = presents_lossless_compression(&identity, mac_class); + let mac_class = presented_class(&identity, mac_class); + let lossless_compression = mac_class == MacClass::AppleSilicon; let metal = compile.metal_properties(); let max_buffer_length = identity .device_local_heap @@ -362,12 +374,20 @@ impl DeviceProperties { ), max_vertex_amplification_count, pull_model_interpolation: compile.profile().interpolation_function_needs().is_empty(), + mac_class, driver_defects: driver_defects::of(&description), driver_facts: description.driver_facts(), description, } } + /// The class of Mac the device presents: the one + /// [`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class) declares, else its GPU's + /// ([`MacClass::of_vendor`]). + pub(crate) fn mac_class(&self) -> MacClass { + self.mac_class + } + /// `areRasterOrderGroupsSupported`: the pixel interlock is enabled /// (`fragmentShaderPixelInterlock`), so the compile layer orders the raster order groups of /// every fragment function the device draws as Metal does: its body runs in the pixel's diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 601dce7ac..4d7b3ee50 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1227,6 +1227,20 @@ degradations! { "it filters with the device's largest anisotropy (16 on every venue measured), where \ Metal filters with 32: a footprint more than 16 times as long as it is wide reads a \ coarser level than Metal's (one level coarser at 32 to 1 and beyond)"; + /// A sampler state whose `lodBias` the GPU of the Mac the device presents adds to every + /// sample's level (`MacClass::IntelOrAmd`), where the device's samplers cannot add it as + /// it is (`metal2vulkan::metal::sampler::DeviceLodBias`): past the device's + /// `maxSamplerLodBias` (an infinity included), a NaN, or a bias other than 0 where the + /// device's portability subset withholds `samplerMipLodBias` (MoltenVK). Announced once, + /// where the device makes the state; the payload names the bias and what the device's + /// samplers add for it. + CappedLodBias = "capped-lod-bias", Precision, + "its samples add the device's limit of the bias's sign where the bias is past it, and \ + no bias where the device withholds it or the bias is NaN: a sample whose level with \ + what the device adds has not reached the last level the sampler reads (a positive \ + bias) or level 0 (a negative one) reads another level than Metal's, which adds the \ + whole bias and then clamps the level into the texture's levels; what Metal samples \ + for a NaN bias is not measured"; /// A sampler state with anisotropy, no mip filter (`NotMipmapped`) and different /// minification and magnification filters, on a device that samples through Metal's own /// sampler (MoltenVK on Apple's GPU, `DriverDeviation::MetalSampler`): Vulkan has no diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 77889bf7a..5c76a0975 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -165,7 +165,8 @@ pub struct DeviceOptions { /// answers it gives where a Mac's GPU decides them: what a new `Private` texture reads before /// anything writes it, the encoding a GPU blit through a compressed texture writes, and a /// `half` NaN clear's sign ([`DeviceProperties::lossless_compression`](crate::DeviceProperties::lossless_compression) - /// states it). `None` by default: the class of the device's GPU + /// states it), and whether a sampler state's `lodBias` moves its samples' level. `None` by + /// default: the class of the device's GPU /// ([`MacClass::of_vendor`](crate::MacClass::of_vendor): an Apple GPU presents an Apple /// silicon Mac, every other GPU a Mac with an Intel or AMD GPU). A consumer that presents /// another Mac than its GPU's (an x86-64 macOS guest, an Intel or AMD Mac, on an Apple GPU) diff --git a/crates/metal2vulkan-runtime/src/families/features.rs b/crates/metal2vulkan-runtime/src/families/features.rs index f37cc3bd9..cedee7f98 100644 --- a/crates/metal2vulkan-runtime/src/families/features.rs +++ b/crates/metal2vulkan-runtime/src/families/features.rs @@ -976,9 +976,11 @@ impl FeatureRow { f.properties.supports_sampler_reduction_mode(), Query::SamplerReductionMode, )]), - // `SamplerDescriptor::lod_bias` (Apple10): the runtime samples it as an Apple9 GPU - // does, every level as with no bias (an Apple M3 Max on macOS 27.0.1). Apple10's - // biased level is not built. + // `SamplerDescriptor::lod_bias` (Apple10): on a device presenting an Apple silicon + // Mac the runtime samples it as an Apple9 GPU does, every level as with no bias (an + // Apple M3 Max on macOS 27.0.1); on one presenting a Mac with an Intel or AMD GPU, + // whose GPUs add it though the table lists it under Apple10 alone, it adds it as they + // do (`MacClass::IntelOrAmd`). Apple10's biased level is not built. F::SamplerLodBias => first([gap(G::Textures)]), // 16-bit coordinates in a texture read, a texture's swizzle, `Shared` and `Managed` // depth/stencil textures, and the clamp-to-edge read: the compile layer and the diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index 146fc5302..63b570c19 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -1544,7 +1544,7 @@ fn sampler_writes( let made = metal2vulkan::bind::sampler_desc( device.compile_device(), state.descriptor(), - array.use_, + state.bound_use(array.use_), OpaqueBlackBorder::Stated, None, ) diff --git a/crates/metal2vulkan-runtime/src/render/attached_levels.rs b/crates/metal2vulkan-runtime/src/render/attached_levels.rs index a594744cd..14fed0a6f 100644 --- a/crates/metal2vulkan-runtime/src/render/attached_levels.rs +++ b/crates/metal2vulkan-runtime/src/render/attached_levels.rs @@ -185,7 +185,7 @@ impl RenderLowering { let table = stage_table(stages, bound.stage)?; let (state, clamps) = table.samplers.get(&index)?; let descriptor = binding::bound_sampler(state, *clamps); - let use_ = SamplerUse::new(compare, integer); + let use_ = state.bound_use(SamplerUse::new(compare, integer)); let format = Some(view.format); let compile = device.compile_device(); metal2vulkan::bind::sampler_desc( diff --git a/crates/metal2vulkan-runtime/src/sampler.rs b/crates/metal2vulkan-runtime/src/sampler.rs index 66aa54955..d96a5179d 100644 --- a/crates/metal2vulkan-runtime/src/sampler.rs +++ b/crates/metal2vulkan-runtime/src/sampler.rs @@ -64,9 +64,18 @@ //! on an Apple M4 without Metal's validation layer (which refuses one), and //! `DeviceProperties::supports_sampler_reduction_mode` answers no. Metal takes any `lodBias`, its //! validation layer too (an M3 Max on macOS 27.0.1: -100 to 100, ±16 and past them, NaN and the -//! infinities), and samples nothing differently for it there: every sample reads the level a bias -//! of 0 reads (`SamplerDescriptor::lod_bias`). So does the runtime: a state samples with a bias of -//! 0 ([`taken_descriptor`]), and a state of another bias is another state ([`SamplerKey`]). +//! infinities), and a state of another bias is another state ([`SamplerKey`]). What the bias +//! changes is the GPU's, so the runtime samples it as the Mac the device presents does +//! (`MacClass`; `SamplerDescriptor::lod_bias`). On an Apple silicon Mac every sample reads the +//! level a bias of 0 reads (the M3 Max, Apple9): a state samples with a bias of 0 +//! ([`taken_descriptor`]). A Mac with an Intel or AMD GPU adds the bias to every sample's level, +//! explicit, gradient and implicit alike, and clamps the sum into the texture's levels (an AMD +//! Radeon Pro 5300M and an Intel UHD 630, the consumer's probes): a state's binds hand the device +//! its bias as `mipLodBias` (`SamplerUse::lod_bias`, [`SamplerState::bound_use`]), which Vulkan +//! adds to every level, an explicit one's included. A bias the device's samplers cannot take as +//! it is, past its `maxSamplerLodBias`, NaN, or where its portability subset withholds +//! `samplerMipLodBias`, samples with the nearest they take (`metal::sampler::device_lod_bias`), +//! announced once (`Degradation::CappedLodBias`). //! //! A min or mag filter `Cubic` (`MTLSamplerMinMagFilterCubic`, raw value 2) is made. Without a //! mip filter, Metal samples through such a state as through a constexpr `filter::bicubic` @@ -85,12 +94,13 @@ use super::key_hash::KeyMap; use super::resource_ids::{ElementHold, Holder, IdHold, IdPlacement, IdSpace, ResourceId}; use super::retained::HeldBy; use super::Device; +use super::MacClass; use crate::release; use ash::vk; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::device::VkFeature; use metal2vulkan::error::DriverDeviation; -use metal2vulkan::metal::sampler::{check_sampler, SamplerUse}; +use metal2vulkan::metal::sampler::{check_sampler, device_lod_bias, DeviceLodBias, SamplerUse}; use metal2vulkan::metal::{ CompareFunction, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter, SamplerReductionMode, @@ -476,21 +486,35 @@ pub fn sampler_border_color(raw: u64) -> SamplerBorderColor { } } -/// The descriptor a state of `descriptor` samples with (the module's rules): `descriptor` itself -/// with plain Metal's anisotropy ([`metal_anisotropy`]) and LOD clamps ([`metal_lod_clamps`]), a -/// LOD bias of 0 whatever its own (Metal samples none on the families the runtime claims), and -/// for a pixel-coordinate one its repeat and mirrored-repeat axes `ClampToEdge`, its `r` -/// axis's `MirrorClampToEdge` too (`r` addresses nothing such a sampler samples), mip filter -/// `NotMipmapped` and anisotropy 1, as plain Metal samples it. A pixel-coordinate -/// `MirrorClampToEdge` `s` or `t` axis keeps its mode, which Metal mirrors once by texel index and -/// then clamps. -pub(super) fn taken_descriptor(descriptor: &SamplerDescriptor) -> SamplerDescriptor { +/// The LOD bias a state of `lod_bias` samples with on a device presenting a Mac of `class` (the +/// module's rules): none on an Apple silicon Mac, whatever its own; on a Mac with an Intel or AMD +/// GPU its own, `-0` as `0` and a NaN as none (what such a GPU samples for it is not measured, +/// announced as the state is made). +pub(super) fn taken_lod_bias(lod_bias: f32, class: MacClass) -> f32 { + match class { + MacClass::IntelOrAmd if !lod_bias.is_nan() => lod_bias + 0.0, + _ => 0.0, + } +} + +/// The descriptor a state of `descriptor` samples with on a device presenting a Mac of `class` +/// (the module's rules): `descriptor` itself with plain Metal's anisotropy +/// ([`metal_anisotropy`]) and LOD clamps ([`metal_lod_clamps`]), the LOD bias that class samples +/// with ([`taken_lod_bias`]), and for a pixel-coordinate one its repeat and mirrored-repeat axes +/// `ClampToEdge`, its `r` axis's `MirrorClampToEdge` too (`r` addresses nothing such a sampler +/// samples), mip filter `NotMipmapped` and anisotropy 1, as plain Metal samples it. A +/// pixel-coordinate `MirrorClampToEdge` `s` or `t` axis keeps its mode, which Metal mirrors once +/// by texel index and then clamps. +pub(super) fn taken_descriptor( + descriptor: &SamplerDescriptor, + class: MacClass, +) -> SamplerDescriptor { use SamplerAddressMode as A; let mut taken = *descriptor; taken.max_anisotropy = metal_anisotropy(descriptor.max_anisotropy); [taken.lod_min_clamp, taken.lod_max_clamp] = metal_lod_clamps([descriptor.lod_min_clamp, descriptor.lod_max_clamp]); - taken.lod_bias = 0.0; + taken.lod_bias = taken_lod_bias(descriptor.lod_bias, class); if !descriptor.normalized_coordinates { for mode in [&mut taken.s_address_mode, &mut taken.t_address_mode] { if matches!(*mode, A::Repeat | A::MirrorRepeat) { @@ -545,6 +569,9 @@ pub(super) struct SamplerShared { device: Device, /// The descriptor the state samples with ([`taken_descriptor`]). descriptor: SamplerDescriptor, + /// Its binds add its LOD bias to every sample's level: the device presents a Mac with an + /// Intel or AMD GPU ([`SamplerState::bound_use`]). + lod_bias: bool, /// The state's `gpuResourceID`. id: IdHold, /// The state's element of the set-1 sampler arrays (`resource_ids.rs`). @@ -660,7 +687,8 @@ impl Device { descriptor: &SamplerDescriptor, options: SamplerStateOptions, ) -> Result { - let taken = taken_descriptor(descriptor); + let class = self.properties().mac_class(); + let taken = taken_descriptor(descriptor, class); // The LOD clamps are checked where they are used: a bind's clamps replace them. let mut shape_of = taken; shape_of.lod_min_clamp = 0.0; @@ -718,6 +746,41 @@ impl Device { ) }); } + // A Mac with an Intel or AMD GPU adds the bias to every sample's level; the device's + // samplers add the nearest they take (`metal::sampler::device_lod_bias`). + let lod_bias = class == MacClass::IntelOrAmd; + if lod_bias { + let bias = descriptor.lod_bias; + let why = match device_lod_bias(bias, profile) { + DeviceLodBias::Capped(limit) => Some(format!( + "the device's samplers add at most {} (maxSamplerLodBias), so its samples add \ + {limit}", + limit.abs() + )), + DeviceLodBias::Withheld => Some( + "the device's portability subset withholds samplerMipLodBias, so its samples \ + add none" + .to_owned(), + ), + DeviceLodBias::NotANumber => Some( + "its samples add none; what a Mac with an Intel or AMD GPU samples for a NaN \ + bias is not measured" + .to_owned(), + ), + _ => None, + }; + if let Some(why) = why { + self.degrade(Degradation::CappedLodBias, || { + ( + format!( + "a sampler state of lodBias {bias} on a device presenting a Mac with \ + an Intel or AMD GPU, which adds it to every sample's level" + ), + why, + ) + }); + } + } let shared = self.shared(); let key = SamplerKey::of(descriptor, options); // The ID a state the program released held is back, whichever thread let go of it last @@ -734,6 +797,7 @@ impl Device { let state = SamplerState(Arc::new(SamplerShared { device: self.clone(), descriptor: taken, + lod_bias, id, element, kept: Mutex::new(KeptSamplers::new()), @@ -916,6 +980,16 @@ impl SamplerState { &self.0.descriptor } + /// `use_` as a bind of this state hands it to `bind::sampler_desc`: adding the descriptor's + /// LOD bias to every sample's level where the device presents a Mac whose GPU adds it + /// (`SamplerUse::lod_bias`, `MacClass::IntelOrAmd`). Every bind of a state makes its Vulkan + /// samplers through it, a slot's, an argument buffer's and a heap set's sampler array's, and + /// so does the reckoning of the levels a draw samples of an attachment's texture + /// (`render/attached_levels.rs`). + pub(super) fn bound_use(&self, use_: SamplerUse) -> SamplerUse { + use_.with_lod_bias(self.0.lod_bias) + } + /// Whether an access through an argument buffer that names this state may hand the device a /// pixel coordinate scaled by the texture's size (`Device::degrade_argument_pixel_samplers`): /// its coordinates are pixels. Every gather, comparison and sample through such a state but a diff --git a/crates/metal2vulkan-runtime/src/tests/sampler.rs b/crates/metal2vulkan-runtime/src/tests/sampler.rs index 415b44dfc..1a542ebd5 100644 --- a/crates/metal2vulkan-runtime/src/tests/sampler.rs +++ b/crates/metal2vulkan-runtime/src/tests/sampler.rs @@ -4,9 +4,10 @@ //! (`SamplerCount`). use super::super::sampler::{ - metal_anisotropy, metal_lod_clamps, sampler_border_color, taken_descriptor, SamplerCount, + metal_anisotropy, metal_lod_clamps, sampler_border_color, taken_descriptor, taken_lod_bias, + SamplerCount, }; -use super::super::{Error, SamplerLimit}; +use super::super::{Error, MacClass, SamplerLimit}; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{ CompareFunction, SamplerAddressMode as A, SamplerBorderColor, SamplerMinMagFilter as F, @@ -102,7 +103,7 @@ fn metal_takes_what_probe_7_saw_it_take() { ]; // Each is taken as it is: Metal samples it as its descriptor states. for (name, d) in taken { - assert_eq!(taken_descriptor(&d), d, "{name}"); + assert_eq!(taken_descriptor(&d, MacClass::AppleSilicon), d, "{name}"); } // Both border modes, which plain Metal makes and reads the border color on every border axis // of, whatever the color. @@ -116,7 +117,11 @@ fn metal_takes_what_probe_7_saw_it_take() { d.r_address_mode = A::ClampToBorderColor; d.border_color = color; }); - assert_eq!(taken_descriptor(&mixed), mixed, "{color:?}"); + assert_eq!( + taken_descriptor(&mixed, MacClass::AppleSilicon), + mixed, + "{color:?}" + ); } // Any LOD clamps, at creation (inverted ones as the upper clamp alone, // `inverted_lod_clamps_read_the_upper_clamps_level`). @@ -135,7 +140,7 @@ fn metal_takes_what_probe_7_saw_it_take() { d.lod_min_clamp = min; d.lod_max_clamp = max; }); - let taken = taken_descriptor(&d); + let taken = taken_descriptor(&d, MacClass::AppleSilicon); let [a, b] = metal_lod_clamps([min, max]); assert_eq!( [taken.lod_min_clamp.to_bits(), taken.lod_max_clamp.to_bits()], @@ -143,8 +148,10 @@ fn metal_takes_what_probe_7_saw_it_take() { "clamps {min}..{max}" ); } - // Any LOD bias, taken as none: Metal samples every level as with no bias (an M3 Max on macOS - // 27.0.1, `runtime_lane::lod_bias` in the validation crate). + // Any LOD bias, taken as none on an Apple silicon Mac: Metal samples every level as with no + // bias (an M3 Max on macOS 27.0.1, `runtime_lane::lod_bias` in the validation crate). On a + // Mac with an Intel or AMD GPU, which adds it to every level, taken as it is, `-0` as `0`, + // and a NaN as none (`taken_lod_bias`); the rest of the descriptor alike. for bias in [ 1.0, -1.0, @@ -157,12 +164,35 @@ fn metal_takes_what_probe_7_saw_it_take() { f32::INFINITY, f32::NEG_INFINITY, ] { + let intel_or_amd = match bias.is_nan() { + true => 0.0, + false => bias + 0.0, + }; for d in [descriptor(|_| {}), pixel(|_| {})] { let mut biased = d; biased.lod_bias = bias; - let taken = taken_descriptor(&biased); + let taken = taken_descriptor(&biased, MacClass::AppleSilicon); assert_eq!(taken.lod_bias.to_bits(), 0, "bias {bias}"); - assert_eq!(taken, taken_descriptor(&d), "bias {bias}"); + assert_eq!( + taken, + taken_descriptor(&d, MacClass::AppleSilicon), + "bias {bias}" + ); + assert_eq!(taken_lod_bias(bias, MacClass::AppleSilicon).to_bits(), 0); + let mut taken = taken_descriptor(&biased, MacClass::IntelOrAmd); + assert_eq!( + taken.lod_bias.to_bits(), + intel_or_amd.to_bits(), + "bias {bias}" + ); + let got = taken_lod_bias(bias, MacClass::IntelOrAmd); + assert_eq!(got.to_bits(), intel_or_amd.to_bits(), "bias {bias}"); + taken.lod_bias = 0.0; + assert_eq!( + taken, + taken_descriptor(&d, MacClass::IntelOrAmd), + "bias {bias}" + ); } } } @@ -225,7 +255,7 @@ fn an_anisotropy_metal_stops_samples_as_plain_metal_samples_it() { ] { assert_eq!(metal_anisotropy(value), sampled, "{value}"); let d = descriptor(|d| d.max_anisotropy = value); - let taken = taken_descriptor(&d); + let taken = taken_descriptor(&d, MacClass::AppleSilicon); assert_eq!(taken.max_anisotropy, sampled, "{value}"); let mut want = d; want.max_anisotropy = sampled; @@ -255,7 +285,7 @@ fn inverted_lod_clamps_read_the_upper_clamps_level() { d.lod_min_clamp = min; d.lod_max_clamp = max; }); - let got = taken_descriptor(&d); + let got = taken_descriptor(&d, MacClass::AppleSilicon); assert_eq!( [got.lod_min_clamp, got.lod_max_clamp], taken, @@ -338,10 +368,18 @@ fn a_pixel_sampler_samples_as_plain_metal_samples_it() { ]; for (name, mut d) in taken { let pixel_default = pixel(|_| {}); - assert_eq!(taken_descriptor(&d), pixel_default, "{name}"); + assert_eq!( + taken_descriptor(&d, MacClass::AppleSilicon), + pixel_default, + "{name}" + ); d.min_filter = F::Linear; d.mag_filter = F::Linear; - assert_eq!(taken_descriptor(&d), clamped, "{name}, linear"); + assert_eq!( + taken_descriptor(&d, MacClass::AppleSilicon), + clamped, + "{name}, linear" + ); } // Clamping axes, and a normalized descriptor, are taken as they are. let border = pixel(|d| { @@ -349,13 +387,16 @@ fn a_pixel_sampler_samples_as_plain_metal_samples_it() { d.t_address_mode = A::ClampToBorderColor; d.border_color = SamplerBorderColor::OpaqueWhite; }); - assert_eq!(taken_descriptor(&border), border); + assert_eq!(taken_descriptor(&border, MacClass::AppleSilicon), border); let normalized = descriptor(|d| { d.max_anisotropy = 8; d.mip_filter = M::Linear; d.s_address_mode = A::Repeat; }); - assert_eq!(taken_descriptor(&normalized), normalized); + assert_eq!( + taken_descriptor(&normalized, MacClass::AppleSilicon), + normalized + ); for d in [ pixel(|d| d.s_address_mode = A::MirrorClampToEdge), pixel(|d| d.t_address_mode = A::MirrorClampToEdge), @@ -366,7 +407,7 @@ fn a_pixel_sampler_samples_as_plain_metal_samples_it() { d.mag_filter = F::Linear; }), ] { - assert_eq!(taken_descriptor(&d), d, "{d:?}"); + assert_eq!(taken_descriptor(&d, MacClass::AppleSilicon), d, "{d:?}"); } // Its `r` axis's, which addresses nothing it samples, clamps as a repeating one's. let r = pixel(|d| { @@ -374,7 +415,7 @@ fn a_pixel_sampler_samples_as_plain_metal_samples_it() { d.r_address_mode = A::MirrorClampToEdge; }); let r_taken = pixel(|d| d.s_address_mode = A::MirrorClampToEdge); - assert_eq!(taken_descriptor(&r), r_taken); + assert_eq!(taken_descriptor(&r, MacClass::AppleSilicon), r_taken); } #[test] diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index d600d9863..5a88a2c24 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -83,6 +83,8 @@ //! vertex's depth, or cannot, and bias factors in depth clamp mode through a range past 1 there //! ([`VERTEX_CLAMPS`]), //! sampler states of an anisotropy past the device's largest here ([`CAPPED_ANISOTROPY`]), +//! sampler states of a LOD bias past the device's limit, or NaN, on a device presenting a Mac with +//! an Intel or AMD GPU in `lod_bias` ([`CAPPED_LOD_BIAS`]), //! anisotropic sampler states without a mip filter through Metal's own sampler //! ([`NOT_MIPMAPPED_ANISOTROPY`]), draws that read an attachment's bytes in place in //! `attachment_reads` ([`IN_PLACE`]), textures @@ -205,6 +207,7 @@ use super::interlocked_primitive_order::BOUND_INTERLOCKS; use super::kept_buffer_bytes::KEPT_BYTES; use super::line_widths::{LINE_TIES, SUBPIXEL_SNAP, WIDE_LINES}; use super::linear_attachments::{CHOSEN_COPIES, LINEAR_COPIES}; +use super::lod_bias::CAPPED_LOD_BIAS; use super::memoryless::MEMORYLESS_TEXEL_BUFFERS; use super::mesh_draws::EMULATED_MESH; use super::no_copy_heaps::HEAP; @@ -551,6 +554,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &LINE_TIES, &SUBPIXEL_SNAP, &CAPPED_ANISOTROPY, + &CAPPED_LOD_BIAS, &NOT_MIPMAPPED_ANISOTROPY, &IN_PLACE, &ARGUMENT_BUFFERS, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/lod_bias.rs b/crates/metal2vulkan-validation/src/runtime_lane/lod_bias.rs index 98601c1e1..567273720 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/lod_bias.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/lod_bias.rs @@ -1,14 +1,26 @@ -//! A sampler state's `lodBias` on the device the cfg selects, under the validation layer: Metal -//! samples nothing differently for it on the families the runtime claims (an Apple M3 Max on macOS -//! 27.0.1, Apple9: every sample kind, biases from -1000 to 1000, NaN and the infinities), and makes -//! another state for another bias, one state for `0` and `-0`, and one for two NaNs of one -//! encoding. +//! A sampler state's `lodBias` on the device the cfg selects, under the validation layer, as the +//! Mac the device presents samples it (`DeviceOptions::mac_class`): //! -//! The kernel is `mip_level_sampling`'s `mip_bias_kernel` (`validation/fixtures/public/engine`): -//! each thread samples the runtime sampler at slot 0 at its own coordinate with its own shader -//! bias, a kernel's default level 0 shifted by it. The texture is `r32Float`, of five levels whose -//! level `L` holds `L` in every texel, so a linear mip filter's sample states the level it read. +//! - an Apple silicon Mac samples nothing differently for it (an Apple M3 Max on macOS 27.0.1, +//! Apple9: every sample kind, biases from -1000 to 1000, NaN and the infinities); +//! - a Mac with an Intel or AMD GPU adds it to every sample's level, explicit, gradient and +//! implicit alike, and clamps the sum into the texture's levels (an AMD Radeon Pro 5300M and an +//! Intel UHD 630, the consumer's probe): the device adds what its samplers take of it +//! (`metal::sampler::device_lod_bias`), a bias they cannot take as it is announced once +//! ([`CAPPED_LOD_BIAS`]). +//! +//! Either way Metal makes another state for another bias, one state for `0` and `-0`, and one for +//! two NaNs of one encoding. +//! +//! The functions are `mip_level_sampling`'s (`validation/fixtures/public/engine`), over an +//! `r32Float` texture of five levels whose level `L` holds `L` in every texel, so a nearest +//! sample, or a linear mip filter's at a whole level, states the level it read. Its kernel +//! `mip_bias_kernel` samples the runtime sampler at slot 0 at each thread's coordinate with its +//! own shader bias, a kernel's default level 0 shifted by it: the device's explicit level. Its +//! fragment function `mip_implicit_fragment`, drawn by `tob_renders`'s `tob_rect` over a target of +//! one row of 2x2 quads, samples quad `q` at an implicit level of exactly `q`. +use super::degrade_notices::{assert_once, counts}; use super::mip_levels::{texture, LEVELS}; use super::{ at_plan, buffer_with, layer_reported_nothing_at_all, read_buffer, validated_device_with, @@ -17,12 +29,25 @@ use super::{ use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::metal::{SamplerMinMagFilter, SamplerMipFilter, TextureType}; -use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; +use metal2vulkan::metal::sampler::{device_lod_bias, DeviceLodBias}; +use metal2vulkan::metal::{ + PixelFormat, PrimitiveType, SamplerMinMagFilter, SamplerMipFilter, TextureType, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - ComputePipelineState, Device, PipelineOptions, ResourceOptions, SamplerState, Size, Texture, + ClearColor, CommandBufferStatus, ComputePipelineState, Degradation, Device, LoadAction, + MacClass, PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, + SamplerState, Size, StoreAction, Texture, TextureDescriptor, }; +use std::collections::BTreeMap; + +/// The kind a state of a bias the device's samplers cannot take as it is takes, on a device +/// presenting a Mac with an Intel or AMD GPU +/// ([`a_sampler_s_lod_bias_moves_the_level_on_an_intel_or_amd_mac`]). +pub(super) const CAPPED_LOD_BIAS: [Degradation; 1] = [Degradation::CappedLodBias]; /// The shader biases each thread samples at, one thread each: whole levels, levels between them, /// below the first and past the last. @@ -44,6 +69,10 @@ const SAMPLER_BIASES: [f32; 10] = [ f32::INFINITY, ]; +/// The quads along the fragment function's target: quad `q` samples at level `q`, the last one +/// past the texture's last level. +const QUADS: u64 = LEVELS + 1; + /// The kernel on `device`. fn pipeline(device: &Device) -> ComputePipelineState { let bitcode = llvm_assemble(&engine_dir().join("mip_level_sampling.ll")).unwrap(); @@ -57,6 +86,28 @@ fn pipeline(device: &Device) -> ComputePipelineState { .unwrap() } +/// `tob_renders`'s `tob_rect` and `mip_level_sampling`'s `mip_implicit_fragment` on `device`, into +/// an `RGBA32Float` color attachment. +fn implicit_pipeline(device: &Device) -> RenderPipelineState { + let function = |fixture: &str, name: &str| { + let bitcode = llvm_assemble(&engine_dir().join(fixture)).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_renders.ll", "tob_rect")); + descriptor.fragment = Some(function("mip_level_sampling.ll", "mip_implicit_fragment")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + /// A sampler state of nearest filters, mip filter `mip` and LOD bias `bias`. fn sampler(device: &Device, mip: SamplerMipFilter, bias: f32) -> SamplerState { let mut descriptor = SamplerDescriptor::new(); @@ -110,19 +161,95 @@ fn run( .collect() } -/// Every sample through a state with a LOD bias reads what the unbiased state reads, bit for bit, -/// under a linear and a nearest mip filter: the level the shader bias alone selects, which the -/// unbiased state reads at each whole level. A state of another bias is another state, `-0` is -/// `0`'s, and a NaN bias's state is the next NaN's. Prints the samples checked. +/// What each quad of the fragment function's target reads of `texture` through `sampler` at its +/// implicit level, every pixel of the quad alike. +fn drawn( + device: &Device, + pipeline: &RenderPipelineState, + texture: &Texture, + sampler: &SamplerState, +) -> Vec { + let (w, h) = (2 * QUADS, 2); + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA32Float, w, h, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::shared(); + let target = device.new_texture(&target).unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(-1.0, 0.0, 0.0, 0.0); + let corners: Vec = [-1.0f32, -1.0, 1.0, 1.0] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let corners = buffer_with(device, &corners).unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(pipeline).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + encoder + .set_fragment_sampler_state(Some(sampler), 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + let mut bytes = vec![0u8; (16 * w * h) as usize]; + target + .get_bytes(&mut bytes, 16 * w, 0, Region::new_2d(0, 0, w, h), 0, 0) + .unwrap(); + let red: Vec = bytes + .as_chunks::<16>() + .0 + .iter() + .map(|c| f32::from_le_bytes(c[..4].try_into().unwrap())) + .collect(); + (0..QUADS as usize) + .map(|q| { + let quad = [red[2 * q], red[2 * q + 1], red[w as usize + 2 * q]]; + let last = red[w as usize + 2 * q + 1]; + assert!( + quad.iter().all(|r| r.to_bits() == last.to_bits()), + "quad {q}: {quad:?} {last}" + ); + last + }) + .collect() +} + +/// A lane device presenting a Mac of `class`. +fn presenting(messages: &Messages, cache: &ScratchCache, class: MacClass) -> Device { + validated_device_with(TEST_DEVICE, messages, cache.path(), |options| { + at_plan(options); + options.mac_class = Some(class); + }) + .unwrap() +} + +/// On a device presenting an Apple silicon Mac, every sample through a state with a LOD bias +/// reads what the unbiased state reads, bit for bit: the kernel's under a linear and a nearest mip +/// filter, the level the shader bias alone selects, which the unbiased state reads at each whole +/// level; and the fragment function's implicit level `q` under a nearest one. A state of another +/// bias is another state, `-0` is `0`'s, and a NaN bias's state is the next NaN's. Nothing is +/// announced for any bias. Prints the samples checked. #[test] -fn a_sampler_s_lod_bias_reads_the_unbiased_level() { +fn a_sampler_s_lod_bias_reads_the_unbiased_level_on_an_apple_silicon_mac() { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); { - let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), at_plan).unwrap(); + let device = presenting(&messages, &cache, MacClass::AppleSilicon); let name = device.name().to_owned(); let levels = texture(&device, TextureType::Type2D, |l, _, _, _| l as f32); let state = pipeline(&device); + let render = implicit_pipeline(&device); let mut checked = 0; for mip in [SamplerMipFilter::Linear, SamplerMipFilter::Nearest] { let unbiased = sampler(&device, mip, 0.0); @@ -135,13 +262,27 @@ fn a_sampler_s_lod_bias_reads_the_unbiased_level() { assert_eq!(w, level, "{name}: {mip:?}, shader bias {b}"); } } + let implicit = (mip == SamplerMipFilter::Nearest) + .then(|| drawn(&device, &render, &levels, &unbiased)); + if let Some(implicit) = &implicit { + for (q, &got) in implicit.iter().enumerate() { + let level = (q as f32).min((LEVELS - 1) as f32); + assert_eq!(got, level, "{name}: implicit level {q}"); + } + } for bias in SAMPLER_BIASES { + messages.take_notices(); let biased = sampler(&device, mip, bias); assert_ne!( biased.gpu_resource_id(), unbiased.gpu_resource_id(), "{name}: bias {bias} is another state" ); + assert_eq!( + counts(&messages.take_notices()), + BTreeMap::new(), + "{name}: bias {bias}" + ); let got = run(&device, &state, &levels, &biased); for ((&b, g), w) in SHADER_BIASES.iter().zip(&got).zip(&want) { assert_eq!( @@ -152,6 +293,18 @@ fn a_sampler_s_lod_bias_reads_the_unbiased_level() { ); checked += 1; } + if let Some(implicit) = &implicit { + let got = drawn(&device, &render, &levels, &biased); + for (q, (g, w)) in got.iter().zip(implicit).enumerate() { + assert_eq!( + g.to_bits(), + w.to_bits(), + "{name}: sampler bias {bias}, implicit level {q}: {g} against the \ + unbiased {w}" + ); + checked += 1; + } + } } let zero = sampler(&device, mip, -0.0); assert_eq!(zero.gpu_resource_id(), unbiased.gpu_resource_id()); @@ -165,3 +318,114 @@ fn a_sampler_s_lod_bias_reads_the_unbiased_level() { } layer_reported_nothing_at_all(&messages); } + +/// The sampler biases of [`a_sampler_s_lod_bias_moves_the_level_on_an_intel_or_amd_mac`]: whole +/// ones of both signs, so each whole shader bias's sum is a whole level, ones past every device's +/// `maxSamplerLodBias`, an infinity and a NaN. +const INTEL_OR_AMD_BIASES: [f32; 8] = + [1.0, -1.0, 2.0, -3.0, 100.0, -100.0, f32::INFINITY, f32::NAN]; + +/// On a device presenting a Mac with an Intel or AMD GPU, a sample through a state with a LOD +/// bias reads the level its own level and the bias select, clamped into the texture's levels: the +/// kernel's at its shader bias plus the device's bias, under a linear and a nearest mip filter, +/// and the fragment function's at its implicit level `q` plus it, under a nearest one. The +/// device's bias is what its samplers take of the state's (`device_lod_bias`): the bias, its +/// limit past it, none for a NaN and none where the device withholds `samplerMipLodBias`, the +/// state announced `capped-lod-bias` once where it is not the bias itself. Checked where the sum +/// is a whole level; on lavapipe the biased levels differ from the unbiased ones. Prints the +/// samples checked and how many read another level than the unbiased state. +#[test] +fn a_sampler_s_lod_bias_moves_the_level_on_an_intel_or_amd_mac() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = presenting(&messages, &cache, MacClass::IntelOrAmd); + let name = device.name().to_owned(); + let profile = device.compile_device().profile(); + let levels = texture(&device, TextureType::Type2D, |l, _, _, _| l as f32); + let state = pipeline(&device); + let render = implicit_pipeline(&device); + let last = (LEVELS - 1) as f32; + let (mut checked, mut moved) = (0, 0); + let capped = INTEL_OR_AMD_BIASES + .iter() + .any(|&b| !matches!(device_lod_bias(b, profile), DeviceLodBias::Exact(_))); + for mip in [SamplerMipFilter::Linear, SamplerMipFilter::Nearest] { + let unbiased = sampler(&device, mip, 0.0); + let want = run(&device, &state, &levels, &unbiased); + messages.take_notices(); + let states: Vec<(f32, SamplerState)> = INTEL_OR_AMD_BIASES + .iter() + .map(|&bias| (bias, sampler(&device, mip, bias))) + .collect(); + // Announced once per device: at the first mip filter's states. + let notices = messages.take_notices(); + if capped && mip == SamplerMipFilter::Linear { + assert_eq!(assert_once(¬ices, &CAPPED_LOD_BIAS).len(), 1, "{name}"); + } else { + assert_eq!(counts(¬ices), BTreeMap::new(), "{name}: {mip:?}"); + } + for (bias, biased) in &states { + assert_ne!( + biased.gpu_resource_id(), + unbiased.gpu_resource_id(), + "{name}: bias {bias} is another state" + ); + let added = device_lod_bias(*bias, profile).bias(); + let got = run(&device, &state, &levels, biased); + for ((&b, &g), &w) in SHADER_BIASES.iter().zip(&got).zip(&want) { + let sum = b + added; + if sum.fract() != 0.0 { + continue; + } + let level = sum.clamp(0.0, last); + assert_eq!( + g, level, + "{name}: {mip:?}, sampler bias {bias} (the device's {added}), shader \ + bias {b}: {g} against level {level}" + ); + checked += 1; + moved += usize::from(g.to_bits() != w.to_bits()); + } + if mip != SamplerMipFilter::Nearest { + continue; + } + for (q, &g) in drawn(&device, &render, &levels, biased).iter().enumerate() { + let sum = q as f32 + added; + if sum.fract() != 0.0 { + continue; + } + let level = sum.clamp(0.0, last); + let unbiased_level = (q as f32).min(last); + assert_eq!( + g, level, + "{name}: sampler bias {bias} (the device's {added}), implicit level {q}: \ + {g} against level {level}" + ); + checked += 1; + moved += usize::from(g != unbiased_level); + } + } + let zero = sampler(&device, mip, -0.0); + assert_eq!(zero.gpu_resource_id(), unbiased.gpu_resource_id()); + let (nan, again) = ( + sampler(&device, mip, f32::NAN), + sampler(&device, mip, f32::NAN), + ); + assert_eq!(nan.gpu_resource_id(), again.gpu_resource_id()); + } + let withheld = matches!(device_lod_bias(1.0, profile), DeviceLodBias::Withheld); + assert!(checked > 0, "{name}"); + // Where the device takes a bias, the biased states read other levels. + assert_eq!( + moved > 0, + !withheld, + "{name}: {moved} moved, withheld {withheld}" + ); + println!( + "LOD-BIAS {name}: {checked} biased samples read the biased level, {moved} of them \ + another than the unbiased state's" + ); + } + layer_reported_nothing_at_all(&messages); +} diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 9857c97aa..5049c3c63 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -1556,13 +1556,17 @@ pub struct SamplerDescriptor { pub compare_function: metal::CompareFunction, pub reduction_mode: metal::SamplerReductionMode, /// `lodBias`: any value, NaN and the infinities included, as Metal takes it, its validation - /// layer too. It changes no sample: an Apple GPU of the families the runtime claims, which - /// lists the bias under Apple10 alone, samples every level as with a bias of 0 (an Apple M3 - /// Max on macOS 27.0.1, Apple9: implicit, biased, explicit-level, gradient and clamped samples - /// in fragment functions and kernels, float and integer textures, every mip filter, biases - /// from -1000 to 1000), so the Vulkan sampler's `mipLodBias` is 0 whatever it holds - /// ([`vk_sampler`](crate::metal::sampler::vk_sampler)). Metal makes another sampler state for - /// another bias. + /// layer too. What it changes is the GPU's (`metal::sampler::SamplerUse::lod_bias`). An Apple + /// GPU of the families the runtime claims, which lists the bias under Apple10 alone, samples + /// every level as with a bias of 0 (an Apple M3 Max on macOS 27.0.1, Apple9: implicit, + /// biased, explicit-level, gradient and clamped samples in fragment functions and kernels, + /// float and integer textures, every mip filter, biases from -1000 to 1000): there the Vulkan + /// sampler's `mipLodBias` is 0 whatever it holds. A Mac with an Intel or AMD GPU adds it to + /// every sample's level and clamps the sum into the texture's levels (an AMD Radeon Pro 5300M + /// and an Intel UHD 630: explicit-level, gradient and implicit samples): there it is the + /// device's `mipLodBias`, within the device's limit + /// ([`device_lod_bias`](crate::metal::sampler::device_lod_bias)). Metal makes another sampler + /// state for another bias. #[cfg_attr(feature = "serde", serde(default))] pub lod_bias: f32, } diff --git a/crates/metal2vulkan/src/metal/sampler.rs b/crates/metal2vulkan/src/metal/sampler.rs index e29ff11c5..6fe7ced20 100644 --- a/crates/metal2vulkan/src/metal/sampler.rs +++ b/crates/metal2vulkan/src/metal/sampler.rs @@ -111,15 +111,24 @@ pub struct SamplerUse { /// coordinates, one minification and magnification filter, no mip filter or anisotropy, and /// `s` and `t` clamped to the edge, to zero or to the border. pub unnormalized: bool, + /// The GPU the device presents adds a sampler descriptor's `lodBias` to every sample's level, + /// as a Mac with an Intel or AMD GPU does: [`vk_sampler`] makes the device's `mipLodBias` + /// of it ([`device_lod_bias`]). Without it (the default) the sampler samples as an Apple GPU + /// of the families the runtime claims does, every level as with no bias. Not a fact of the + /// function: the consumer states it per bind, from the Mac it presents (the runtime's + /// `MacClass`), and a plan's uses leave it unset. + pub lod_bias: bool, } impl SamplerUse { - /// A use with the given comparison and texture numeric type, in normalized coordinates. + /// A use with the given comparison and texture numeric type, in normalized coordinates, of + /// no LOD bias. pub fn new(compare: bool, integer_texture: bool) -> SamplerUse { SamplerUse { compare, integer_texture, unnormalized: false, + lod_bias: false, } } @@ -131,6 +140,71 @@ impl SamplerUse { ..self } } + + /// This use, adding the descriptor's `lodBias` to every sample's level where `lod_bias` + /// holds ([`SamplerUse::lod_bias`]). + pub fn with_lod_bias(self, lod_bias: bool) -> SamplerUse { + SamplerUse { lod_bias, ..self } + } +} + +/// The LOD bias a device's sampler adds to every sample's level for a sampler descriptor's +/// `lodBias`, on a GPU that adds it ([`SamplerUse::lod_bias`]; [`device_lod_bias`]). Vulkan adds +/// a sampler's `mipLodBias` to every sample's level, an explicit level's included, and takes one +/// of at most `maxSamplerLodBias` (`VUID-VkSamplerCreateInfo-mipLodBias-01069`), and a +/// portability subset without `samplerMipLodBias` none but 0. Each variant but `Exact` is a +/// near-equivalent, which the runtime announces as it makes the state +/// (`Degradation::CappedLodBias`). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DeviceLodBias { + /// The descriptor's bias, which the device's sampler takes as it is (0 included). + Exact(f32), + /// A bias past the device's `maxSamplerLodBias`, an infinity included: the device's sampler + /// adds that limit, of the bias's sign. Metal's GPU clamps the biased level into the + /// texture's levels (an AMD Radeon Pro 5300M and an Intel UHD 630), so this reads Metal's + /// level wherever the level with the limit added already reaches the last level the sampler + /// reads (a positive bias) or level 0 (a negative one). + Capped(f32), + /// A bias other than 0 on a device whose portability subset withholds `samplerMipLodBias` + /// (MoltenVK): the device's sampler adds none. + Withheld, + /// A NaN bias: the device's sampler adds none. What a Mac's GPU samples for it is not + /// measured. + NotANumber, +} + +impl DeviceLodBias { + /// The bias the device's sampler adds: its `mipLodBias`. + pub fn bias(self) -> f32 { + match self { + DeviceLodBias::Exact(bias) | DeviceLodBias::Capped(bias) => bias, + DeviceLodBias::Withheld | DeviceLodBias::NotANumber => 0.0, + } + } +} + +/// The LOD bias the device of `profile` adds to every sample's level for a sampler descriptor's +/// `lod_bias`, on a GPU that adds it ([`DeviceLodBias`]): the bias where the device takes it, +/// `-0.0` as `0.0`; else the nearest it takes. +pub fn device_lod_bias(lod_bias: f32, profile: &DeviceProfile) -> DeviceLodBias { + if lod_bias.is_nan() { + return DeviceLodBias::NotANumber; + } + // Adding `0.0` takes `-0.0` to `0.0`. + let bias = lod_bias + 0.0; + if bias == 0.0 { + return DeviceLodBias::Exact(bias); + } + if (profile.fields().enabled).portability_withholds(VkFeature::SamplerMipLodBias) { + return DeviceLodBias::Withheld; + } + let limit = f32::from_bits(profile.fields().limits.max_sampler_lod_bias_bits).max(0.0); + if bias.abs() > limit { + DeviceLodBias::Capped(limit.copysign(bias)) + } else { + DeviceLodBias::Exact(bias) + } } /// Whether the device's unnormalized sampler (`VkSamplerCreateInfo::unnormalizedCoordinates`) @@ -354,11 +428,18 @@ pub(crate) fn vk_filtering( /// a nearest mip filter's next level past one half; MoltenVK hands the clamp to Metal's sampler, /// which does so itself. /// -/// Its `mipLodBias` is 0 whatever the descriptor's `lod_bias`: an Apple GPU of the families the -/// runtime claims samples every level as with no bias ([`SamplerDescriptor::lod_bias`]), and -/// Vulkan adds `mipLodBias` to every sample's level, an explicit one's included. So no bias is -/// past the device's `maxSamplerLodBias`, and none needs `samplerMipLodBias` of a portability -/// subset. +/// Its `mipLodBias` follows the GPU the device presents ([`SamplerUse::lod_bias`]). Vulkan adds +/// `mipLodBias` to every sample's level, an explicit one's included (the specification's +/// "Level-of-Detail Operation"). An Apple GPU of the families the runtime claims samples every +/// level as with no bias ([`SamplerDescriptor::lod_bias`]): without `lod_bias` it is 0, whatever +/// the descriptor's. A Mac with an Intel or AMD GPU adds the bias to every sample's level, an +/// explicit level's, a gradient's and an implicit one's alike, and clamps the sum into the +/// texture's levels (an AMD Radeon Pro 5300M and an Intel UHD 630, as the consumer's probe +/// measured them): with `lod_bias` it is [`device_lod_bias`]'s, the descriptor's bias within the +/// device's `maxSamplerLodBias` and where a portability subset withholds `samplerMipLodBias` +/// none, never a refusal; the device clamps its sum with a sample's own `Bias` into that limit, as +/// it clamps the sample's bias alone. A use that reads texel coordinates takes none: such a +/// sampler reads level 0 by one filter, so a bias selects nothing. /// /// A use that reads texel coordinates ([`SamplerUse::unnormalized`]) takes the device's /// unnormalized sampler: its filters, address modes and border as above, the nearest mip mode at @@ -456,7 +537,10 @@ pub fn vk_sampler( address_mode_u: address[0], address_mode_v: address[1], address_mode_w: address[2], - mip_lod_bias: 0.0, + mip_lod_bias: match use_.lod_bias && !use_.unnormalized { + true => device_lod_bias(desc.lod_bias, profile).bias(), + false => 0.0, + }, max_anisotropy, compare: use_.compare.then(|| compare_op(desc.compare_function)), min_lod, @@ -1275,14 +1359,15 @@ mod tests { assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE); } - /// A descriptor's LOD bias makes, on every committed device and for every use, the Vulkan - /// sampler and the binding shape its zero bias makes: an Apple GPU of the families the runtime - /// claims samples every level as with no bias (`SamplerDescriptor::lod_bias`). So a bias is - /// never the device's `mipLodBias` and is refused nowhere: past the device's - /// `maxSamplerLodBias`, NaN or infinite, and through a portability subset that withholds - /// `samplerMipLodBias`. + /// A descriptor's LOD bias makes, on every committed device and for every use, the binding + /// shape its zero bias makes, and the Vulkan sampler its zero bias makes but for its + /// `mipLodBias`: without `SamplerUse::lod_bias` (an Apple GPU of the families the runtime + /// claims, which samples every level as with no bias) 0; with it (a Mac with an Intel or AMD + /// GPU) `device_lod_bias`'s, the bias within the device's `maxSamplerLodBias` and none through + /// a portability subset that withholds `samplerMipLodBias`, and 0 for a use of texel + /// coordinates. Refused nowhere: past the limit, NaN or infinite, and withheld. #[test] - fn a_lod_bias_makes_the_unbiased_sampler() { + fn a_lod_bias_is_the_device_s_where_the_use_adds_it() { use crate::bind::state::BoundSampler; use SamplerMinMagFilter::{Linear, Nearest}; let biases = [ @@ -1336,20 +1421,32 @@ mod tests { pixel.mag_filter = Linear; pixel.min_filter = Linear; descs.push((pixel, SamplerUse::default().with_unnormalized(true))); - for (unbiased, use_) in descs { - let want = vk_sampler(&unbiased, use_, p); + for (unbiased, plain) in descs { + let want = vk_sampler(&unbiased, plain, p); let shape = BoundSampler::new(unbiased).shape(); for bias in biases { let mut d = unbiased; d.lod_bias = bias; - let got = vk_sampler(&d, use_, p); - assert_eq!(got, want, "{stem}: bias {bias}, {d:?} {use_:?}"); - if let Ok(s) = got { - assert_eq!(s.mip_lod_bias.to_bits(), 0, "{stem}: bias {bias}"); + for use_ in [plain, plain.with_lod_bias(true)] { + let added = match use_.lod_bias && !use_.unnormalized { + true => device_lod_bias(bias, p).bias(), + false => 0.0, + }; + assert!(added.abs() <= limit, "{stem}: bias {bias}"); + let got = vk_sampler(&d, use_, p).map(|mut s| { + assert_eq!( + s.mip_lod_bias.to_bits(), + added.to_bits(), + "{stem}: bias {bias}, {use_:?}" + ); + s.mip_lod_bias = 0.0; + s + }); + assert_eq!(got, want, "{stem}: bias {bias}, {d:?} {use_:?}"); + checked += 1; } assert_eq!(BoundSampler::new(d).shape(), shape, "{stem}: bias {bias}"); past_limit += usize::from(bias.abs() > limit); - checked += 1; } } } @@ -1359,6 +1456,62 @@ mod tests { assert!(checked > 0); } + /// The bias a device adds for a descriptor's `lod_bias` where the GPU it presents adds it: the + /// bias, `-0` as `0`, within `maxSamplerLodBias`; the limit of its sign past it, an infinity + /// included; none for a NaN; and none for a bias other than 0 through a portability subset + /// that withholds `samplerMipLodBias`, whose 0 is exact. + #[test] + fn the_device_lod_bias_is_the_bias_within_what_the_device_takes() { + use DeviceLodBias::{Capped, Exact, NotANumber, Withheld}; + let mut floor = committed_descriptions() + .into_iter() + .find(|(s, _)| s == "vk12-floor") + .unwrap() + .1; + floor.limits.max_sampler_lod_bias_bits = 15.5f32.to_bits(); + let floor = Device::new(floor, DevicePolicy::default()).unwrap(); + let p = floor.profile(); + assert!(!(p.fields().enabled).portability_withholds(VkFeature::SamplerMipLodBias)); + let exact = |b: f32| match device_lod_bias(b, p) { + Exact(got) => got.to_bits(), + other => panic!("bias {b}: {other:?}"), + }; + for b in [0.0, 1.0, -1.0, 0.25, 15.5, -15.5] { + assert_eq!(exact(b), b.to_bits(), "bias {b}"); + } + assert_eq!(exact(-0.0), 0f32.to_bits()); + for (b, want) in [ + (15.75, 15.5), + (16.0, 15.5), + (-100.0, -15.5), + (f32::MAX, 15.5), + (f32::INFINITY, 15.5), + (f32::NEG_INFINITY, -15.5), + ] { + assert_eq!(device_lod_bias(b, p), Capped(want), "bias {b}"); + } + assert_eq!(device_lod_bias(f32::NAN, p), NotANumber); + assert_eq!(device_lod_bias(-f32::NAN, p).bias().to_bits(), 0); + let (stem, mvk) = committed_descriptions() + .into_iter() + .map(|(stem, d)| (stem, Device::new(d, DevicePolicy::default()).unwrap())) + .find(|(_, dev)| { + (dev.profile().fields().enabled).portability_withholds(VkFeature::SamplerMipLodBias) + }) + .expect("a committed device withholds samplerMipLodBias"); + let p = mvk.profile(); + for b in [1.0, -1.0, 0.25, 100.0, f32::INFINITY] { + assert_eq!(device_lod_bias(b, p), Withheld, "{stem}: bias {b}"); + assert_eq!( + device_lod_bias(b, p).bias().to_bits(), + 0, + "{stem}: bias {b}" + ); + } + assert_eq!(device_lod_bias(0.0, p), Exact(0.0), "{stem}"); + assert_eq!(device_lod_bias(f32::NAN, p), NotANumber, "{stem}"); + } + /// A sampler without a mip filter reads the base level, its minification filter exactly where /// Metal's level raised to `lodMinClamp` and lowered to `lodMaxClamp` is above 0 (the device's /// `λ > 0`), as Metal chooses between a min and a mag filter that differ. diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2fab39654..acfefa7fd 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1511,6 +1511,7 @@ enum metal2vulkan::metal::format::Footprint #[cfg_attr(feature = "serde", derive enum metal2vulkan::metal::format::FormatEmulation #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FormatEmulation enum metal2vulkan::metal::format::WordAttachment #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum WordAttachment enum metal2vulkan::metal::format::YCbCrReads #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum YCbCrReads +enum metal2vulkan::metal::sampler::DeviceLodBias #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub enum DeviceLodBias enum metal2vulkan::metal::sampler::OpaqueBlackBorder #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum OpaqueBlackBorder enum metal2vulkan::metal::vertex::AttributeFetch #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum AttributeFetch enum metal2vulkan::pipeline::AccelerationStructureLevel #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum AccelerationStructureLevel @@ -4458,6 +4459,7 @@ field metal2vulkan::metal::format::YCbCrFormat.reads pub reads: YCbCrReads field metal2vulkan::metal::format::YCbCrFormat.subsampling pub subsampling: ChromaSubsampling field metal2vulkan::metal::sampler::SamplerUse.compare pub compare: bool field metal2vulkan::metal::sampler::SamplerUse.integer_texture pub integer_texture: bool +field metal2vulkan::metal::sampler::SamplerUse.lod_bias pub lod_bias: bool field metal2vulkan::metal::sampler::SamplerUse.unnormalized pub unnormalized: bool field metal2vulkan::metal::state::DepthBias.clamp pub clamp: f32 field metal2vulkan::metal::state::DepthBias.constant_factor pub constant_factor: f32 @@ -5203,6 +5205,7 @@ fn metal2vulkan::metal::sampler::check_border_swizzle pub fn check_border_swizzl fn metal2vulkan::metal::sampler::check_border_view pub fn check_border_view(opaque_black: bool, pf: PixelFormat, mapping: &FormatMapping, swizzle: TextureSwizzleChannels, profile: &DeviceProfile) -> Result<(), Error> fn metal2vulkan::metal::sampler::check_sampler pub fn check_sampler(shape: &SamplerShape, use_: SamplerUse, profile: &DeviceProfile) -> Result<(), Error> fn metal2vulkan::metal::sampler::compare_op pub fn compare_op(f: CompareFunction) -> vk::CompareOp +fn metal2vulkan::metal::sampler::device_lod_bias pub fn device_lod_bias(lod_bias: f32, profile: &DeviceProfile) -> DeviceLodBias fn metal2vulkan::metal::sampler::opaque_black_border pub fn opaque_black_border(pf: PixelFormat, mapping: &FormatMapping, swizzle: TextureSwizzleChannels, profile: &DeviceProfile) -> Result fn metal2vulkan::metal::sampler::opaque_black_reads_transparent pub fn opaque_black_reads_transparent(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> bool fn metal2vulkan::metal::sampler::vk_sampler pub fn vk_sampler(desc: &SamplerDescriptor, use_: SamplerUse, profile: &DeviceProfile) -> Result @@ -5467,6 +5470,7 @@ macro-member metal2vulkan-runtime::Degradation::BiasedDepthPastUnitRange BiasedD macro-member metal2vulkan-runtime::Degradation::BicubicFilterArithmetic BicubicFilterArithmetic = "bicubic-filter-arithmetic"; macro-member metal2vulkan-runtime::Degradation::BlendedWriteRounding BlendedWriteRounding = "blended-write-rounding"; macro-member metal2vulkan-runtime::Degradation::CappedAnisotropy CappedAnisotropy = "capped-anisotropy", Precision, +macro-member metal2vulkan-runtime::Degradation::CappedLodBias CappedLodBias = "capped-lod-bias", Precision, macro-member metal2vulkan-runtime::Degradation::CarriedDecodedTwin CarriedDecodedTwin = "carried-decoded-twin", Performance, macro-member metal2vulkan-runtime::Degradation::ClippedCoverageSplit ClippedCoverageSplit = "clipped-coverage-split"; macro-member metal2vulkan-runtime::Degradation::ClippedDepthPieces ClippedDepthPieces = "clipped-depth-pieces", Precision, @@ -9566,7 +9570,9 @@ method metal2vulkan::metal::sampler::AddressModeMap::is_identity pub fn is_ident method metal2vulkan::metal::sampler::AddressModeMap::mode pub fn mode(&self, from: SamplerAddressMode) -> SamplerAddressMode method metal2vulkan::metal::sampler::AddressModeMap::sampler pub fn sampler(&self, mut desc: SamplerDescriptor) -> SamplerDescriptor method metal2vulkan::metal::sampler::AddressModeMap::with pub fn with(mut self, from: SamplerAddressMode, to: SamplerAddressMode) -> AddressModeMap +method metal2vulkan::metal::sampler::DeviceLodBias::bias pub fn bias(self) -> f32 method metal2vulkan::metal::sampler::SamplerUse::new pub fn new(compare: bool, integer_texture: bool) -> SamplerUse +method metal2vulkan::metal::sampler::SamplerUse::with_lod_bias pub fn with_lod_bias(self, lod_bias: bool) -> SamplerUse method metal2vulkan::metal::sampler::SamplerUse::with_unnormalized pub fn with_unnormalized(self, unnormalized: bool) -> SamplerUse method metal2vulkan::metal::sampler::SamplerWord::nearest_pixel pub fn nearest_pixel(integer: bool) -> u32 method metal2vulkan::metal::sampler::SamplerWord::of pub fn of(desc: &SamplerDescriptor) -> SamplerWord @@ -14284,6 +14290,10 @@ variant metal2vulkan::metal::format::YCbCrReads::ExtendedRange ExtendedRange variant metal2vulkan::metal::format::YCbCrReads::Hlg Hlg variant metal2vulkan::metal::format::YCbCrReads::Pq Pq variant metal2vulkan::metal::format::YCbCrReads::Srgb Srgb +variant metal2vulkan::metal::sampler::DeviceLodBias::Capped Capped(f32) +variant metal2vulkan::metal::sampler::DeviceLodBias::Exact Exact(f32) +variant metal2vulkan::metal::sampler::DeviceLodBias::NotANumber NotANumber +variant metal2vulkan::metal::sampler::DeviceLodBias::Withheld Withheld variant metal2vulkan::metal::sampler::OpaqueBlackBorder::Mapped Mapped(vk::ComponentMapping) variant metal2vulkan::metal::sampler::OpaqueBlackBorder::Stated Stated variant metal2vulkan::metal::sampler::OpaqueBlackBorder::Transparent Transparent diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index b695a59f5..a29351e39 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -956,9 +956,11 @@ surface! { struct SamplerWord E; struct AddressModeMap O; enum OpaqueBlackBorder N; + enum DeviceLodBias N; const NOT_MIPMAPPED_MAX_LOD; fn check_sampler; fn vk_sampler; + fn device_lod_bias; fn check_border_swizzle; fn check_border_view; fn opaque_black_reads_transparent; diff --git a/docs/API.md b/docs/API.md index faa1858f8..ee29bac8c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2717,6 +2717,18 @@ bound. samples with 32. Cost: it filters with the device's largest anisotropy (16 on every venue measured), where Metal filters with 32: a footprint more than 16 times as long as it is wide reads a coarser level than Metal's (one level coarser at 32 to 1 and beyond). +- `metal2vulkan-degrade-capped-lod-bias` (precision). `CappedLodBias`: A sampler state whose + `lodBias` the GPU of the Mac the device presents adds to every sample's level + (`MacClass::IntelOrAmd`), where the device's samplers cannot add it as it is + (`metal::sampler::DeviceLodBias`): past the device's `maxSamplerLodBias` (an infinity included), + a NaN, or a bias other than 0 where the device's portability subset withholds + `samplerMipLodBias` (MoltenVK). Announced once, where the device makes the state; the payload + names the bias and what the device's samplers add for it. Cost: its samples add the device's + limit of the bias's sign where the bias is past it, and no bias where the device withholds it or + the bias is NaN: a sample whose level with what the device adds has not reached the last level + the sampler reads (a positive bias) or level 0 (a negative one) reads another level than Metal's, + which adds the whole bias and then clamps the level into the texture's levels; what Metal samples + for a NaN bias is not measured. - `metal2vulkan-degrade-not-mipmapped-anisotropic-sampler` (precision). `NotMipmappedAnisotropicSampler`: A sampler state with anisotropy, no mip filter (`NotMipmapped`) and different minification and magnification filters, on a device that samples through Metal's @@ -5006,6 +5018,14 @@ each item named states the rule in full. anything from the render area alone (a level past the first, a slice past the first, 4x multisampled) to the whole texture (plain 4-, 8- and 16-byte color formats). Metal guarantees nothing past the render area, and the runtime gives the 5300M's answer. + - a sampler state's `lodBias` is added to every sample's level, an explicit level's, a + gradient's and an implicit one's alike, the sum clamped into the texture's levels, as an AMD + Radeon Pro 5300M and an Intel UHD 630 sample it (the consumer's probe): the state's binds + hand the device its bias as `mipLodBias` (`SamplerUse::lod_bias`), which Vulkan adds to an + explicit level too. A bias past the device's `maxSamplerLodBias` adds that limit, and a NaN, + or any bias where the device's portability subset withholds `samplerMipLodBias` (MoltenVK), + none, announced (`capped-lod-bias`). A device that presents an Apple silicon Mac samples + every level as with no bias, as an Apple M3 Max (Apple9) does. Metal leaves a new texture's contents undefined, and zero and a released texture's texels are both what such a Mac reads, so this trades no accuracy and no `DevicePolicy` switch fills the