From da3cea76339fb30ea454d9e083f0d4086359ef6b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 14:25:03 -0800 Subject: [PATCH] A heap texture's chosen constexpr samplers are one sampler array, not a switch A heap texture sampled through one of several constexpr samplers that a sampler handle names at run time (a table of constexpr samplers read at a computed index) was a switch-at-use with one arm per candidate: each arm its own heap sampling and raw-texel emulation. On large kernels that multiplies the sampling code by the candidate count. Where every candidate is a constexpr sampler, their handles are consecutive, each candidate's sampling is the same but for its sampler and the state its raw emulation follows, the use is not tangled, and the device indexes a sampler array non-uniformly (shaderSampledImageArrayNonUniformIndexing, which heap textures already need), the sampling is now one sampling through a set-0 array of the candidates' samplers (ResourceKind::SamplerArray, BindingSource::SamplerArray): element handle - first, NonUniform, its immutable samplers each made as the heap sampler of that candidate alone would be (DescriptorBinding::immutable_samplers, listed per stage in StageInterface::sampler_arrays). A handle outside the array reads zero, as the switch's null arm. The raw emulation reads the element's sampler word from a constant table at the same index (heap_raw::State::Table), through the runtime-word path. Elsewhere the switch stays. The runtime bakes one sampler per element into the set layout, pushes each element's own sampler where set 0 is pushed, and keys the set-0 shape on them. Tests: the array form on every profile with the sampled heap (one sampled image, L3), the switch kept for non-consecutive handles, each element equal to the immutable sampler of the candidate sampled alone and never written by the plan, and a device test (lavapipe under m2v_cpu_icd) that each lane reads what its sampler alone reads and what the address modes define. Docs: API.md section 5, the sampler module doc, api_signatures, api_surface, REFUSALS regenerated. --- crates/metal2vulkan-runtime/src/heap_sets.rs | 2 +- .../src/pipeline/objects.rs | 50 +++-- .../src/pipeline/shared_layouts.rs | 11 +- .../src/tests/heap_sampler_array.rs | 182 ++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + crates/metal2vulkan/src/bind/graphics.rs | 8 +- crates/metal2vulkan/src/bind/heap.rs | 24 ++- crates/metal2vulkan/src/bind/heap/tests.rs | 2 + crates/metal2vulkan/src/bind/plan/compute.rs | 4 + crates/metal2vulkan/src/cache/codec.rs | 12 +- crates/metal2vulkan/src/cache/tests.rs | 4 + .../src/lower/sampler/constexpr.rs | 8 + crates/metal2vulkan/src/lower/sampler/emit.rs | 66 +++++- .../src/lower/sampler/heap_raw.rs | 76 ++++++- crates/metal2vulkan/src/lower/sampler/mod.rs | 196 +++++++++++++++++- .../metal2vulkan/src/lower/sampler/select.rs | 140 ++++++++++++- crates/metal2vulkan/src/pipeline/api_tests.rs | 2 + crates/metal2vulkan/src/pipeline/compile.rs | 1 + crates/metal2vulkan/src/pipeline/interface.rs | 18 ++ crates/metal2vulkan/src/pipeline/layout.rs | 14 ++ crates/metal2vulkan/src/pipeline/link.rs | 47 +++++ .../metal2vulkan/src/pipeline/link/tests.rs | 1 + crates/metal2vulkan/src/pipeline/mod.rs | 5 +- crates/metal2vulkan/src/pipeline/sym.rs | 10 + .../metal2vulkan/src/spirv/builder/module.rs | 7 + .../metal2vulkan/src/tests/engine_handles.rs | 128 ++++++++++++ .../src/tests/engine_heap_binder.rs | 69 ++++++ crates/metal2vulkan/tests/api_signatures.tsv | 6 + crates/metal2vulkan/tests/api_surface.rs | 1 + docs/API.md | 11 + 30 files changed, 1061 insertions(+), 46 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/heap_sampler_array.rs diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index f8cf3a327..afe9af556 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -1911,7 +1911,7 @@ impl RawLayout { if layout .bindings .iter() - .any(|b| b.immutable_sampler.is_some()) + .any(|b| b.immutable_sampler.is_some() || !b.immutable_samplers.is_empty()) { return Err(internal("a heap set with an immutable sampler")); } diff --git a/crates/metal2vulkan-runtime/src/pipeline/objects.rs b/crates/metal2vulkan-runtime/src/pipeline/objects.rs index be95f6a71..9cf9a95c5 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/objects.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/objects.rs @@ -691,13 +691,16 @@ impl VariantObjects { let push_set_zero = pushes_set_zero(device, layout, stages, pipeline); let dynamic = dynamic_bindings(device, layout, push_set_zero); let set_needs = needs_of(device, layout, push_set_zero, &dynamic)?; - // One sampler per binding that bakes one, in the layout's order: the live set of the same - // samplers where it holds one, else one made now (`sampler_set`). + // One sampler per binding that bakes one, and one per element of a sampler array, in the + // layout's order: the live set of the same samplers where it holds one, else one made now + // (`sampler_set`). let descs: Vec = layout .sets .iter() .flat_map(|set| &set.bindings) - .filter_map(|binding| binding.immutable_sampler) + .flat_map(|binding| { + (binding.immutable_sampler.into_iter()).chain(binding.immutable_samplers.clone()) + }) .collect(); let (samplers, made) = sampler_set(device, descs)?; if made && exit_guard::in_host_step() { @@ -1440,6 +1443,7 @@ fn set_zero_shape(layout: &PipelineLayout, push_set_zero: bool, dynamic: &[u32]) binding.count.hash(&mut hasher); binding.stages.hash(&mut hasher); binding.immutable_sampler.hash(&mut hasher); + binding.immutable_samplers.hash(&mut hasher); binding.flags.hash(&mut hasher); } } @@ -1860,22 +1864,34 @@ fn immutable_pushes( let mut baked = samplers.iter().copied(); let mut pushes = Vec::new(); for (index, set) in layout.sets.iter().enumerate() { - for binding in set - .bindings - .iter() - .filter(|b| b.immutable_sampler.is_some()) - { - let sampler = baked - .next() - .ok_or_else(|| internal("a sampler set shorter than its layout"))?; + for binding in &set.bindings { + // The sampler of each element: a binding's one for all, a sampler array's its own. + let each: Vec = match binding.immutable_sampler { + Some(_) => { + let sampler = baked + .next() + .ok_or_else(|| internal("a sampler set shorter than its layout"))?; + vec![sampler; binding.count as usize] + } + None => (&mut baked) + .take(binding.immutable_samplers.len()) + .collect(), + }; + if each.len() < binding.immutable_samplers.len() { + return Err(internal("a sampler set shorter than its layout")); + } let ty: vk::DescriptorType = binding.ty.into(); if index == 0 && ty == vk::DescriptorType::SAMPLER { - pushes.extend((0..binding.count).map(|element| SetWrite { - binding: binding.binding, - element, - ty, - info: Info::Image(vk::DescriptorImageInfo::default().sampler(sampler)), - })); + pushes.extend( + (0..binding.count) + .zip(each) + .map(|(element, sampler)| SetWrite { + binding: binding.binding, + element, + ty, + info: Info::Image(vk::DescriptorImageInfo::default().sampler(sampler)), + }), + ); } } } diff --git a/crates/metal2vulkan-runtime/src/pipeline/shared_layouts.rs b/crates/metal2vulkan-runtime/src/pipeline/shared_layouts.rs index 6baddedfc..2f7033279 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/shared_layouts.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/shared_layouts.rs @@ -130,7 +130,16 @@ pub(crate) fn shared_layout( .ok_or_else(|| internal("a sampler set shorter than its layout"))?; vec![sampler; binding.count as usize] } - None => Vec::new(), + // A sampler array's: one sampler per element, each its own. + None => { + let each: Vec = (&mut baked) + .take(binding.immutable_samplers.len()) + .collect(); + if each.len() != binding.immutable_samplers.len() { + return Err(internal("a sampler set shorter than its layout")); + } + each + } }; let ty: vk::DescriptorType = binding.ty.into(); let made_dynamic = index == 0 && dynamic.contains(&binding.binding); diff --git a/crates/metal2vulkan-runtime/src/tests/heap_sampler_array.rs b/crates/metal2vulkan-runtime/src/tests/heap_sampler_array.rs new file mode 100644 index 000000000..dd6e582fc --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/heap_sampler_array.rs @@ -0,0 +1,182 @@ +//! A heap texture sampled through the constexpr sampler each lane chooses among three (the +//! translator's constexpr sampler array, `ResourceKind::SamplerArray`) answers, lane by lane, what +//! a kernel sampling it through that lane's sampler alone answers, and what Metal's address modes +//! define: an `R32Float` texture four texels wide holding `10, 11, 12, 13`, sampled nearest at +//! level 0 and `(1.375, 0.5)`, reads texel 3 clamped to the edge, texel 1 repeating, and texel 2 +//! mirrored. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernels are LLVM text written here +//! (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use crate::{ + Buffer, CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, Region, + ResourceOptions, Size, Texture, TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; + +/// The constexpr samplers' words: nearest, normalized coordinates, no mip filter, every axis +/// clamped to the edge, repeating, and mirrored, with the fields Apple's compiler writes for the +/// rest. +const SAMPLERS: [u64; 3] = [ + 0x007b_ff00_0008_0000 | 0o111, + 0x007b_ff00_0008_0000 | 0o222, + 0x007b_ff00_0008_0000 | 0o333, +]; + +/// The texels of the texture's one row. +const TEXELS: [f32; 4] = [10.0, 11.0, 12.0, 13.0]; + +/// What each sampler reads at `(1.375, 0.5)`: texel 3 clamped to the edge, texel 1 repeating +/// (`0.375`), texel 2 mirrored (`0.625`). +const READ: [f32; 3] = [13.0, 11.0, 12.0]; + +/// The lanes of a dispatch: each sampler twice. +const LANES: usize = 6; + +/// A kernel `k` sampling the `texture2d` its argument buffer (buffer 0) holds at level 0 +/// and `(1.375, 0.5)` through `pick[gid % pick.len()]` (indices of [`SAMPLERS`], each a constexpr +/// sampler of the module), written to buffer 1's lane `gid`. +fn kernel(pick: &[usize]) -> String { + let n = pick.len(); + let mut choose = format!(" %m = urem i32 %gid, {n}\n"); + let mut chosen = format!("@s{}", pick[n - 1]); + for (k, s) in pick[..n - 1].iter().enumerate().rev() { + choose += &format!( + " %c{k} = icmp eq i32 %m, {k}\n %p{k} = select i1 %c{k}, ptr addrspace(2) @s{s}, ptr addrspace(2) {chosen}\n" + ); + chosen = format!("%p{k}"); + } + let globals: String = (SAMPLERS.iter().enumerate()) + .map(|(i, w)| { + format!("@s{i} = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n") + }) + .collect(); + format!( + r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct.M = type {{ ptr addrspace(1) }} +{globals} +define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out, i32 %gid) {{ + %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 +{choose} %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) {chosen}, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0) + %v = extractvalue {{ <4 x float>, i8 }} %r, 0 + %o = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %gid + store <4 x float> %v, ptr addrspace(1) %o, align 16 + ret void +}} +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.kernel = !{{!0}} +!air.version = !{{!11}} +!air.language_version = !{{!12}} +!air.sampler_states = !{{!20, !21, !22}} +!0 = !{{ptr @k, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !6, !8}} +!3 = !{{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"M", !"air.arg_name", !"m"}} +!4 = !{{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5}} +!5 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} +!6 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, 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", !"out"}} +!8 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} +!11 = !{{i32 2, i32 8, i32 0}} +!12 = !{{!"Metal", i32 4, i32 0, i32 0}} +!20 = !{{!"air.sampler_state", ptr addrspace(2) @s0}} +!21 = !{{!"air.sampler_state", ptr addrspace(2) @s1}} +!22 = !{{!"air.sampler_state", ptr addrspace(2) @s2}} +"# + ) +} + +/// The compute state of [`kernel`]`(pick)` on `device`. +fn state(device: &Device, pick: &[usize]) -> ComputePipelineState { + let air = metal2vulkan_devtools::llvm_assemble_text(&kernel(pick)).unwrap(); + let library = metal2vulkan::library::Library::from_air(&air).unwrap(); + let function = device + .new_library_with_compile_library(library) + .new_function_with_name("k") + .unwrap(); + let descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A shared buffer holding `bytes`. +fn holding(device: &Device, bytes: &[u8]) -> Buffer { + device + .new_buffer_with_bytes(bytes, ResourceOptions::shared()) + .unwrap() +} + +/// The `R32Float` texture of one row of [`TEXELS`]. +fn texture(device: &Device) -> Texture { + let width = TEXELS.len() as u64; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::R32Float, width, 1, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let bytes: Vec = TEXELS.iter().flat_map(|t| t.to_le_bytes()).collect(); + let row = bytes.len() as u64; + texture + .replace_region(Region::new_2d(0, 0, width, 1), 0, 0, &bytes, row, 0) + .unwrap(); + texture +} + +/// What [`kernel`]`(pick)` reads of `texture`, named by its resource ID in an argument buffer, in +/// each of [`LANES`] lanes. +fn run(device: &Device, pick: &[usize], texture: &Texture) -> Vec<[f32; 4]> { + let state = state(device, pick); + let argument = holding(device, &texture.gpu_resource_id().0.to_le_bytes()); + let out = holding(device, &[0; 16 * LANES]); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&argument), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + let threads = Size::new(LANES as u64, 1, 1); + encoder.dispatch_threads(threads, threads).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 contents = out.contents().unwrap(); + // SAFETY: the buffer's bytes, which the completed command buffer wrote. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), 16 * LANES) }; + let words: Vec = bytes + .as_chunks::<4>() + .0 + .iter() + .map(|&word| f32::from_le_bytes(word)) + .collect(); + words.as_chunks::<4>().0.to_vec() +} + +#[test] +fn a_lane_sampling_through_its_chosen_constexpr_sampler_reads_what_that_sampler_reads() { + let scratch = Scratch::new("heap-sampler-array"); + let device = device(&scratch.0); + let texture = texture(&device); + let chosen = run(&device, &[0, 1, 2], &texture); + for (sampler, read) in READ.iter().enumerate() { + let alone = run(&device, &[sampler], &texture); + for lane in (sampler..LANES).step_by(SAMPLERS.len()) { + assert_eq!( + chosen[lane], alone[lane], + "lane {lane}: through sampler {sampler} chosen and alone" + ); + assert_eq!( + chosen[lane], + [*read, 0.0, 0.0, 1.0], + "lane {lane}: sampler {sampler}'s texel" + ); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 4d7ab6cc0..9781a6d2f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -249,6 +249,8 @@ mod heap_one_plane_rows; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_refused_notice; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod heap_sampler_array; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_set_copies; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod heap_set_unlocked; diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 3491cd87e..d6e6c77f5 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -1915,6 +1915,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result WriteSource::ExecutionStatus, other => return Err(internal(format!("a render binding {other:?}"))), }, - BindingSource::Heap(_) | BindingSource::HeapSampler { .. } => { + BindingSource::Heap(_) + | BindingSource::HeapSampler { .. } + | BindingSource::SamplerArray { .. } => { return Err(internal("a heap binding outside the heap planner")) } BindingSource::SeparateSampler { .. } => { diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index d448d50d9..cc84854d5 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -72,7 +72,10 @@ //! - **Heap samplers**. A heap image is sampled through a separate sampler binding //! (`BindingSource::HeapSampler`) in set 0: a constexpr sampler is the layout's immutable sampler //! and takes no write; a runtime `[[sampler(n)]]` is written with the sampler bound at slot `n` -//! made for the use, or the neutral sampler where none is. One with an opaque-black border (the +//! made for the use, or the neutral sampler where none is. A sampling that chooses among +//! constexpr samplers by its sampler handle reads an element of a constexpr sampler array +//! (`BindingSource::SamplerArray`), whose elements are the layout's immutable samplers and take +//! no write, each checked as a constexpr heap sampler is. One with an opaque-black border (the //! immutable sampler's, or the bound sampler's shape) meets every member a sampled array holds, //! so each such member's sampled view must read that border exactly //! (`metal::sampler::check_border_view`), as a separate slot sampler's textures must. One that @@ -926,6 +929,25 @@ impl<'a> HeapPlanner<'a> { }); } } + // A constexpr sampler array's elements: each its immutable sampler's border + // and filtering. + BindingSource::SamplerArray { + stage, + compare, + integer, + } => { + for d in &b.immutable_samplers { + opaque_black |= opaque_black_border(d); + let filtering = desc_filtering(d); + if filtering.0 && !integer { + filters.push(HeapFilter { + stage, + filtering, + compare, + }); + } + } + } _ => {} } } diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index 21c2e1542..fdf2f2f3a 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -1418,6 +1418,7 @@ fn a_form_a_heap_reads_is_held_raw_in_the_unsigned_class() { immutable_sampler: None, flags: vk::DescriptorBindingFlags::empty(), variables: 1, + immutable_samplers: Vec::new(), }; let mut reads = planner(vec![f2d, u2d], BTreeSet::new()); let float = reads.array(1, &binding(f2d)).expect("float array"); @@ -1469,6 +1470,7 @@ fn a_heap_member_a_mode_two_write_would_round_is_refused() { immutable_sampler: None, flags: vk::DescriptorBindingFlags::empty(), variables: 1, + immutable_samplers: Vec::new(), }; let mut checked = 0; for (stem, p) in committed_profiles().expect("profiles") { diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 4ca231da1..3020250e1 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -512,6 +512,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result Option<[SamplerAddressMode; 3]> { ]) } +/// The word of constexpr sampler `words` (`metal::sampler::SamplerWord`): the word a runtime +/// sampler of the same state holds, of its `MTLSamplerDescriptor`. +pub(crate) fn sampler_word(words: [u64; 2]) -> Result { + Ok(crate::metal::sampler::SamplerWord::of(&descriptor( + &state_of(words)?, + )?)) +} + /// The `MTLSamplerDescriptor` a constexpr sampler state states (the fields Metal's runtime /// descriptor shares with it). fn descriptor(s: &SamplerState) -> Result { diff --git a/crates/metal2vulkan/src/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 4009787cc..bf356417f 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -705,9 +705,61 @@ pub(super) fn sampled_image( }; Ok((si, image, Some(element.live))) } + Source::HeapArray { + handle, + sampler, + key, + } => { + let Some(g) = cx.decl.families.sampler.heap_arrays.get(&key).copied() else { + return Err(cx.fail(format!("constexpr sampler array {key:?} is not declared"))); + }; + let element = heap_element(cx, fb, (key.group, !key.compare), handle)?; + // The element the sampler handle names (element 0 where it names none, whose result + // `sampling_value` makes zero), which may differ between invocations. + let (index, _) = array_element(cx, fb, sampler, key)?; + let base = fb.module().global_value(g)?; + let p = fb.access_chain_non_uniform(base, index)?; + let sampler = fb.load(p, MemAccess::default())?; + let si = fb.sampled_image(element.img, sampler)?; + let image = CombinedImage { + plane: super::plane_of(element.decl.dim), + arrayed: element.decl.arrayed, + texel: element.decl.texel, + }; + Ok((si, image, Some(element.live))) + } } } +/// The element of constexpr sampler array `key` that sampler handle `sampler` names (its distance +/// from the array's first candidate's handle), 0 where it names none, and whether it names one (a +/// `bool`): a handle outside the array is a switch over the candidates' null arm. +pub(super) fn array_element( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + sampler: ValueId, + key: super::HeapArrayKey, +) -> BResult<(SValue, SValue)> { + let array = usize::try_from(key.array) + .ok() + .and_then(|a| cx.plan.families.sampler.arrays.get(a)); + let Some(array) = array else { + return Err(cx.fail(format!("constexpr sampler array {key:?} is not planned"))); + }; + let (first, len) = (array.first, array.samplers.len()); + let len = u32::try_from(len).map_err(|_| cx.fail("a constexpr sampler array past u32"))?; + let h = cx.operand(fb, sampler)?; + let first = fb.u32_const(first)?; + let first = fb.module().const_value(first)?; + let i = fb.binary(BinOp::ISub, h, first)?; + let len = fb.u32_const(len)?; + let len = fb.module().const_value(len)?; + let named = fb.binary(BinOp::ULessThan, i, len)?; + let zero = fb.u32_const(0)?; + let zero = fb.module().const_value(zero)?; + Ok((fb.select(named, i, zero)?, named)) +} + /// Where a sampling operation observes its residency on a slot with a sparse arm: the slot's /// `SparseTexture` specialization, and the combined binding, whose sampled image each arm makes (a /// sampled image is consumed in the block that makes it). @@ -754,6 +806,14 @@ pub fn sampling_value( cubic_reach(cx, fb, sampler)?; } } + // A sampler handle outside a constexpr sampler array: zero, as the switch's null arm. + if let Source::HeapArray { sampler, key, .. } = s.source { + let (_, named) = array_element(cx, fb, sampler, key)?; + let ty = fb.value_ty(value)?; + let zero = fb.module().constant(Constant::Null { ty })?; + let zero = fb.module().const_value(zero)?; + return fb.select(named, value, zero); + } Ok(value) } @@ -931,7 +991,7 @@ pub(super) fn sampled_value( // selection gives a slot whose observed samples or gathers it does not answer no tile-map arm. let tiled = match s.source { Source::Combined(key) => tile_map(cx, key.texture), - Source::Heap { .. } | Source::HeapSampler { .. } => None, + Source::Heap { .. } | Source::HeapSampler { .. } | Source::HeapArray { .. } => None, }; let fetched = matches!(s.op, SampleOp::PixelFetch { .. }); if arm.is_some() && tiled.is_some() && !fetched && s.footprint.is_none() { @@ -2072,7 +2132,9 @@ pub(super) fn held_value( Source::Combined(key) if !s.depth && s.half_texel => { half_class(cx, &ImageRef::Slot(key.texture), form) } - Source::Heap { handle, .. } | Source::HeapSampler { handle, .. } + Source::Heap { handle, .. } + | Source::HeapSampler { handle, .. } + | Source::HeapArray { handle, .. } if !s.depth && s.half_texel => { crate::lower::texture::heap_half_class(cx, fb, handle, form)? diff --git a/crates/metal2vulkan/src/lower/sampler/heap_raw.rs b/crates/metal2vulkan/src/lower/sampler/heap_raw.rs index df686b1bb..c70cc968f 100644 --- a/crates/metal2vulkan/src/lower/sampler/heap_raw.rs +++ b/crates/metal2vulkan/src/lower/sampler/heap_raw.rs @@ -70,8 +70,16 @@ pub enum State { /// filter, the address modes, the border color, and the coordinates; emulated where it states /// one filter for minification and magnification, no mip filter, and no anisotropy. Slot { sampler: u32 }, + /// The constexpr sampler a sampling through a constexpr sampler array reads + /// (`Source::HeapArray`): each element's [`SamplerWord`], in element order, the one at the + /// element the sampler handle names read as a runtime slot's word is. + Table { words: Vec }, } +/// The words of one element of a [`State::Table`] word's selection: its comparison, its select, +/// and their constants. +const TABLE_ELEMENT_WORDS: u32 = 5 + 6 + 2 * 4; + /// The census words of the emulation's head: the handle's class index, its test and the form, the /// word's tests, the branch and its merge, the unsigned element's access chain and load, and the /// form's bits' selects. @@ -105,10 +113,23 @@ impl HeapRaw { let (word, taps) = match &self.state { State::Constant { pixel: true, .. } => (0, 0), State::Constant { pixel: false, .. } => (position, 0), - State::Slot { .. } => ( - super::linear::WORD_WORDS + position + axes * super::position::MODE_POSITION_WORDS, - axes * super::linear::WORD_TAP_WORDS, - ), + State::Slot { .. } | State::Table { .. } => { + // A table's element index, read again, and its selection of the element's word. + let table = match &self.state { + State::Table { words } => super::ELEMENT_WORDS.saturating_add( + TABLE_ELEMENT_WORDS + .saturating_mul(u32::try_from(words.len()).unwrap_or(u32::MAX)), + ), + _ => 0, + }; + ( + super::linear::WORD_WORDS + + table + + position + + axes * super::position::MODE_POSITION_WORDS, + axes * super::linear::WORD_TAP_WORDS, + ) + } }; let linear = super::linear::PLANE_WORDS + 4 * DECODE_CALL_WORDS + offset + word + 2 * taps; let nearest = @@ -137,6 +158,7 @@ pub(crate) fn emit( let (group, handle) = match s.source { Source::Heap { handle, key } => (key.group, handle), Source::HeapSampler { handle, key, .. } => (key.group, handle), + Source::HeapArray { handle, key, .. } => (key.group, handle), Source::Combined(_) => return Err(cx.fail("a raw heap sample of a slot")), }; let f32_routine = cx.decl.families.texture.heap_raw.get(&false).copied(); @@ -152,9 +174,11 @@ pub(crate) fn emit( let flags = crate::lower::texture::heap_flags(cx, fb, h)?; let (form, member) = crate::lower::texture::heap_raw_form(fb, cx.plan.stage, flags)?; let bfloat = bfloat_form(fb, &t, form)?; - // A runtime sampler's word, and whether it states a filter the emulation answers. + // A runtime sampler's word, or the word of the constexpr sampler a sampler array's element + // holds, and whether it states a filter the emulation answers. let word = match &raw.state { State::Slot { sampler } => Some(super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?), + State::Table { words } => Some(table_word(cx, fb, s, words)?), State::Constant { .. } => None, }; let mut take = member; @@ -221,8 +245,12 @@ pub(crate) fn emit( border: *border, pixel: *pixel, }, - (State::Slot { .. }, Some(word)) => Addressing::Word { word, axes: AXES }, - (State::Slot { .. }, None) => return Err(cx.fail("a raw heap sample without its word")), + (State::Slot { .. } | State::Table { .. }, Some(word)) => { + Addressing::Word { word, axes: AXES } + } + (State::Slot { .. } | State::Table { .. }, None) => { + return Err(cx.fail("a raw heap sample without its word")) + } }; // Whether Metal filters linearly: a linear sampler's sample of a form but a bfloat one. let filter = match (raw.gather, &raw.state, linear_word) { @@ -230,11 +258,11 @@ pub(crate) fn emit( (None, State::Constant { linear: true, .. }, _) => { Some(fb.unary(crate::spirv::ir::UnOp::LogicalNot, bfloat)?) } - (None, State::Slot { .. }, Some(linear)) => { + (None, State::Slot { .. } | State::Table { .. }, Some(linear)) => { let not_bfloat = fb.unary(crate::spirv::ir::UnOp::LogicalNot, bfloat)?; Some(fb.binary(BinOp::LogicalAnd, linear, not_bfloat)?) } - (None, State::Slot { .. }, None) => { + (None, State::Slot { .. } | State::Table { .. }, None) => { return Err(cx.fail("a raw heap sample without its word's filter")) } }; @@ -272,6 +300,36 @@ pub(crate) fn emit( } } +/// The word of the constexpr sampler at the element of sampling `s`'s sampler array its sampler +/// handle names (`Source::HeapArray`): `words[element]`, selected at run time (element 0's where +/// the handle names none, whose result the sampling makes zero). +fn table_word( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + s: &Sampling, + words: &[u32], +) -> BResult { + let Source::HeapArray { sampler, key, .. } = s.source else { + return Err(cx.fail("a sampler array's word outside a sampler array")); + }; + let (element, _) = super::emit::array_element(cx, fb, sampler, key)?; + let mut word = None; + for (k, &w) in (0u32..).zip(words) { + let w = fb.u32_const(w)?; + let w = fb.module().const_value(w)?; + word = Some(match word { + None => w, + Some(v) => { + let k = fb.u32_const(k)?; + let k = fb.module().const_value(k)?; + let is = fb.binary(BinOp::IEqual, element, k)?; + fb.select(is, w, v)? + } + }); + } + word.ok_or_else(|| cx.fail("a sampler array without samplers")) +} + /// Whether the form at index `form` (a `u32`) of `ExtendedRange::HEAP_READ` is a bfloat one (a /// `bool`): the bfloat forms close the list. fn bfloat_form(fb: &mut FunctionBuilder<'_>, t: &Tys, form: SValue) -> BResult { diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index d225e9351..d079608f8 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -14,9 +14,14 @@ //! class through a comparison heap sampler. A runtime `[[sampler(n)]]` beside a heap image is a //! heap sampler binding without an immutable sampler, which the binder writes with the sampler //! bound at slot `n` made for the use, as a combined binding's runtime sampler. A sampler of -//! several static candidates beside a heap image (a table of constexpr samplers read at an index -//! the run knows) is a switch-at-use over them, one arm per candidate, each the heap element -//! through that candidate's heap sampler. +//! several constexpr candidates beside a heap image (a table of constexpr samplers read at an index +//! the run knows), their handles consecutive, each candidate's sampling the same but for its +//! sampler, is one sampling through a set-0 array of their samplers (`ResourceKind::SamplerArray`, +//! one immutable sampler per candidate, its element `NonUniform` and at the handle's distance from +//! the first candidate's; a handle outside it reads zero), where the device indexes a sampler array +//! by a value that may differ between invocations (`shaderSampledImageArrayNonUniformIndexing`). +//! Any other sampler of several static candidates beside a heap image is a switch-at-use over +//! them, one arm per candidate, each the heap element through that candidate's heap sampler. //! //! **Argument buffers' samplers** (the sampler half). A heap image sampled through a sampler loaded //! from an argument buffer reads `OpSampledImage` of its heap element and of the heap sampler's @@ -261,6 +266,37 @@ pub struct HeapSamplerKey { pub compare: bool, } +/// One use of a constexpr sampler array: heap group `group` sampled, with comparison or without, +/// through the element of array `array` ([`SamplerPlan::arrays`]) a sampler handle chooses. Its +/// binding is final once the group's numeric type is ([`finish`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct HeapArrayKey { + pub group: u32, + pub compare: bool, + pub array: u32, +} + +/// The constexpr samplers a sampler handle chooses among in one heap sampling: element `i` is the +/// candidate of handle `first + i` (`memory::handles::CONSTEXPR_SAMPLER_BASE` plus the entry's +/// ordinal), every handle of `first..first + samplers.len()` one candidate's. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ConstexprArray { + pub first: u32, + /// Each element's canonical state words (`SamplerRef::Constexpr`). + pub samplers: Vec<[u64; 2]>, +} + +/// The SPIR-V words of one reading of a constexpr sampler array's element index +/// (`emit::array_element`): the handle less the first candidate's, its range test, and the select +/// of a valid index. +pub(crate) const ELEMENT_WORDS: u32 = 5 + 5 + 6; + +/// The SPIR-V words a sampling through a constexpr sampler array adds to a heap element's: the +/// element index read for the sampler and again for the result, their constants (the first +/// handle, the length, zero), the access chain and the sampler's load, and the select of the +/// result or zero (a handle outside the array is the switch's null arm) with its constant. +pub(crate) const ARRAY_WORDS: u32 = 2 * ELEMENT_WORDS + 3 * 4 + 5 + 4 + 6 + 4; + /// An upper estimate of the SPIR-V words of an argument-buffer sampler's cubic test past its /// entry's word: the mask, the test, the selection construct, and the status mark (the push field's /// load, the address, the pointer, the bit, and the atomic `OR`). @@ -281,6 +317,15 @@ pub enum Source { sampler: ValueId, key: HeapSamplerKey, }, + /// Element `handle` of the heap array of `key.group`, through element `sampler - first` (a + /// constexpr sampler handle's value, [`ConstexprArray::first`]) of the constexpr sampler array + /// of `key`, whose elements are the candidates' samplers. A handle outside the array reads + /// zero, as a switch over the candidates' null arm does. + HeapArray { + handle: ValueId, + sampler: ValueId, + key: HeapArrayKey, + }, } /// How a fragment's nonzero bias reaches the level. Metal shifts the level by its own reading of @@ -810,6 +855,16 @@ impl Sampling { SampleOp::QueryLevel { .. } => "sampler.argument_sampler.query_level", }; } + if let Source::HeapArray { .. } = self.source { + return match &self.op { + SampleOp::Sample { .. } => "sampler.sampler_array.sample", + SampleOp::PixelFetch { .. } => "sampler.sampler_array.pixel_fetch", + SampleOp::Bicubic(_) => "sampler.sampler_array.bicubic", + SampleOp::Gather { .. } => "sampler.sampler_array.gather", + SampleOp::Lod { .. } => "sampler.sampler_array.query_lod", + SampleOp::QueryLevel { .. } => "sampler.sampler_array.query_level", + }; + } if let Source::Heap { .. } = self.source { return match &self.op { SampleOp::Sample { .. } => "sampler.heap.sample", @@ -956,6 +1011,7 @@ impl Sampling { let heap = match self.source { Source::Combined(_) => 0, Source::Heap { .. } => 32, + Source::HeapArray { .. } => 32 + ARRAY_WORDS, Source::HeapSampler { .. } => 56 + 2 * ENTRY_FIELD_WORDS + CUBIC_REACH_WORDS, }; let residency = if self.residency { @@ -971,7 +1027,9 @@ impl Sampling { // A heap color texture's call reads the class its handle carries first. (_, Some(f)) if f.conv == crate::lower::texture::TexelConv::F16 => { let class = match self.source { - Source::Heap { .. } | Source::HeapSampler { .. } if !self.depth => { + Source::Heap { .. } | Source::HeapSampler { .. } | Source::HeapArray { .. } + if !self.depth => + { crate::lower::texture::HEAP_CLASS_WORDS } _ => 0, @@ -1157,6 +1215,13 @@ pub struct SamplerPlan { pub heap_samplers: BTreeSet, /// The sampler array each reads, by its use, set by [`finish`]. pub heap_sampler_decls: BTreeMap, + /// The constexpr sampler arrays heap samplings choose among, by [`HeapArrayKey::array`]. + pub arrays: Vec, + /// Every use of a constexpr sampler array. + pub heap_arrays: BTreeSet, + /// The use each one's binding is made for, set by [`finish`]: one binding per distinct array + /// and use. + pub heap_array_decls: BTreeMap, /// The texture slots a bicubic sample reads, each with its `BicubicTexels` specialization. pub bicubic: BTreeSet, /// The bicubic routines the samples call, by dimension, an extended-range sample's among them. @@ -1216,6 +1281,8 @@ pub struct Declared { pub heap: BTreeMap, /// The set-1 sampler array of each use of an argument buffer's sampler. pub heap_samplers: BTreeMap, + /// The constexpr sampler array variable of each use of one. + pub heap_arrays: BTreeMap, /// The `SamplerState` specialization constant (`u32`) of each runtime sampler slot whose /// word the function reads, masked by [`RuntimeSlot::fields`]. pub words: BTreeMap, @@ -1322,18 +1389,53 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { // One heap sampler binding per distinct sampler use (`declare`). let heap_samplers: BTreeSet = heap_decls.values().copied().collect(); let count = |n: usize| u32::try_from(n).unwrap_or(u32::MAX); + // One constexpr sampler array binding per distinct array and use (`declare`), each element a + // sampler of the stage. + let mut heap_array_decls = BTreeMap::new(); + for key in &cx.families.sampler.heap_arrays { + let h = cx + .families + .texture + .heap + .get(&key.group) + .filter(|h| h.decl.is_some()) + .ok_or_else(|| invariant("a constexpr sampler array of an undeclared heap group"))?; + let texel = h.texel.unwrap_or(TexelClass::Float); + let use_ = SamplerUse::new(key.compare, texel != TexelClass::Float); + let array = usize::try_from(key.array) + .ok() + .and_then(|a| cx.families.sampler.arrays.get(a)) + .ok_or_else(|| invariant("a constexpr sampler array out of range"))?; + for words in &array.samplers { + constexpr_desc(*words, use_, cx.profile)?; + } + heap_array_decls.insert(*key, use_); + } + let array_bindings: BTreeSet<(u32, SamplerUse)> = heap_array_decls + .iter() + .map(|(k, u)| (k.array, *u)) + .collect(); + let array_samplers = array_bindings + .iter() + .filter_map(|(a, _)| usize::try_from(*a).ok()) + .filter_map(|a| cx.families.sampler.arrays.get(a)) + .fold(0u32, |n, a| n.saturating_add(count(a.samplers.len()))); // Each combined binding is one sampled image and one sampler. Where they are more samplers than // the stage may have, the stage takes them apart: the same sampled image per binding, and one // separate sampler per distinct use, which counts as one sampler however many textures it // samples. The sampled images, and every other count, are the same in both forms, so this is // the one limit the separate form relieves; one it still exceeds is the stage's refusal // (`select`). - let combined = count(decls.len()).saturating_add(count(heap_samplers.len())); + let combined = count(decls.len()) + .saturating_add(count(heap_samplers.len())) + .saturating_add(array_samplers); let limit = cx.profile.fields().limits.max_per_stage_descriptor_samplers; let separate = combined > limit; let uses: BTreeSet = decls.values().map(|d| d.sampler).collect(); counts.samplers = if separate { - count(uses.len()).saturating_add(count(heap_samplers.len())) + count(uses.len()) + .saturating_add(count(heap_samplers.len())) + .saturating_add(array_samplers) } else { combined }; @@ -1389,6 +1491,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.sampler.separate = separate; cx.families.sampler.heap_decls = heap_decls; cx.families.sampler.heap_sampler_decls = heap_sampler_decls; + cx.families.sampler.heap_array_decls = heap_array_decls; cx.descriptors = cx.descriptors.plus(&counts); Ok(()) } @@ -1408,6 +1511,48 @@ pub fn heap_layout_features(plan: &Plan) -> Vec ResourceSlot { + ResourceSlot { + stage, + kind: ResourceKind::SamplerArray { + compare: use_.compare, + integer: use_.integer_texture, + }, + index: array, + } +} + +/// The constexpr sampler arrays `plan` declares (`StageInterface::sampler_arrays`): each binding's +/// samplers in element order, which link bakes into the layout. +pub fn sampler_arrays(plan: &Plan) -> Vec { + let bindings: BTreeSet<(u32, SamplerUse)> = plan + .families + .sampler + .heap_array_decls + .iter() + .map(|(k, u)| (k.array, *u)) + .collect(); + bindings + .into_iter() + .filter_map(|(array, use_)| { + let a = plan + .families + .sampler + .arrays + .get(usize::try_from(array).ok()?)?; + Some(crate::pipeline::interface::SamplerArray { + slot: array_slot(plan.stage, array, use_), + samplers: a + .samplers + .iter() + .map(|w| SamplerRef::Constexpr(*w)) + .collect(), + }) + }) + .collect() +} + /// Declare the combined bindings, or their separate textures and samplers, and the runtime /// samplers' coordinate constants. pub fn declare( @@ -1497,6 +1642,45 @@ pub fn declare( }; d.heap_samplers.insert(*key, g); } + // One constexpr sampler array per distinct array and use: a sized array of samplers. + let mut constexpr_arrays: BTreeMap<(u32, SamplerUse), GlobalId> = BTreeMap::new(); + for (key, use_) in &plan.families.sampler.heap_array_decls { + let g = match constexpr_arrays.get(&(key.array, *use_)) { + Some(g) => *g, + None => { + let missing = crate::spirv::error::BuildError::Global( + crate::spirv::error::GlobalRule::ResourceType, + ); + let len = usize::try_from(key.array) + .ok() + .and_then(|a| plan.families.sampler.arrays.get(a)) + .map(|a| a.samplers.len()) + .ok_or(missing)?; + let u32_ = mb.ty(SType::Int { + width: 32, + signed: false, + })?; + let len = mb.constant(crate::spirv::ir::Constant::Scalar { + ty: u32_, + bits: ConstBits(u64::try_from(len).unwrap_or(u64::MAX)), + })?; + let sampler = mb.ty(SType::Sampler)?; + let array = mb.ty(SType::Array { + elem: sampler, + len, + stride: None, + })?; + let g = mb.resource( + array_slot(plan.stage, key.array, *use_), + StorageClass::UniformConstant, + array, + )?; + constexpr_arrays.insert((key.array, *use_), g); + g + } + }; + d.heap_arrays.insert(*key, g); + } for (n, r) in &plan.families.sampler.slots { let fields = r.fields(); if fields != 0 { diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 6dd8857a9..d5684c407 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -522,6 +522,9 @@ fn select_heap_switch( cands: &[Candidate], m: &mut Meter, ) -> Result { + if let Some(array) = select_heap_array(cx, call, heap, smp_handle, cands, m)? { + return Ok(array); + } let ops = Operands { t: call.t, args: call.args, @@ -547,6 +550,138 @@ fn select_heap_switch( }))) } +/// A heap image sampled through one of the constexpr samplers `cands`, chosen by handle +/// `smp_handle`, as one sampling through an array of the candidates' samplers +/// (`Source::HeapArray`): its element `smp_handle - first` is exactly the sampler of the candidate +/// of that handle, and the raw emulation reads that element's state word +/// (`heap_raw::State::Table`). Where every candidate is a constexpr sampler, their handles +/// consecutive (`first..first + n`); the device indexes an array of samplers by a value that may +/// differ between invocations (`shaderSampledImageArrayNonUniformIndexing`, which the heap's own +/// image array already needs); the use is not tangled; and each candidate's sampling is the same +/// but for its sampler and the state its raw emulation follows. `None` otherwise, and the switch +/// over the candidates stays. +fn select_heap_array( + cx: &mut SelectCx<'_>, + call: Call<'_>, + heap: (u32, ValueId), + smp_handle: ValueId, + cands: &[Candidate], + m: &mut Meter, +) -> Result, Error> { + use super::heap_raw::State; + if cands.len() < 2 || !cx.profile.fields().descriptors.non_uniform_sampled_image { + return Ok(None); + } + if !cands + .iter() + .all(|c| matches!(c, Candidate::Constexpr { .. })) + { + return Ok(None); + } + let ops = Operands { + t: call.t, + args: call.args, + }; + if !matches!(tangled(cx, &ops, 1)?, (None, false)) { + return Ok(None); + } + let mut order = cands.to_vec(); + order.sort_by_key(|c| c.handle()); + let Some(first) = order.first().map(|c| c.handle()) else { + return Ok(None); + }; + if order.iter().zip(first..).any(|(c, h)| c.handle() != h) { + return Ok(None); + } + // Each candidate's sampling, as the switch's arm would take it; the heap sampler uses they + // add are dropped where the array replaces them. + let before = cx.families.sampler.heap.clone(); + let mut arms = Vec::with_capacity(order.len()); + for &c in &order { + let sampler = sampler_of(cx, c)?; + match select_heap_arm(cx, call, heap, sampler, Some(false), m)? { + TextureStrategy::Sampling(x) => arms.push(*x), + _ => return Ok(None), + } + } + // A candidate's sampling but for its sampler and its raw emulation's constant state. + let shape = |x: &Sampling| -> Option { + let mut y = x.clone(); + let Source::Heap { handle, key } = y.source else { + return None; + }; + y.source = Source::Heap { + handle, + key: HeapKey { + sampler: SamplerRef::Slot(0), + ..key + }, + }; + if let Some(raw) = &mut y.heap_raw { + if !matches!(raw.state, State::Constant { .. }) { + return None; + } + raw.state = State::Table { words: Vec::new() }; + } + Some(y) + }; + let Some(one) = arms.first().and_then(shape) else { + return Ok(None); + }; + if arms.iter().any(|x| shape(x).as_ref() != Some(&one)) { + return Ok(None); + } + let mut samplers = Vec::with_capacity(arms.len()); + for x in &arms { + match x.source { + Source::Heap { + key: + HeapKey { + sampler: SamplerRef::Constexpr(words), + .. + }, + .. + } => samplers.push(words), + _ => return Ok(None), + } + } + let mut words = Vec::with_capacity(samplers.len()); + for w in &samplers { + words.push(super::constexpr::sampler_word(*w)?.0); + } + let array = super::ConstexprArray { first, samplers }; + let arrays = &mut cx.families.sampler.arrays; + let index = match arrays.iter().position(|a| *a == array) { + Some(i) => i, + None => { + arrays.push(array); + arrays.len() - 1 + } + }; + let index = + u32::try_from(index).map_err(|_| cx.invariant("constexpr sampler arrays past u32"))?; + let mut x = one; + let Source::Heap { handle, key } = x.source else { + return Err(cx.invariant("a heap sampling without its heap source")); + }; + let key = super::HeapArrayKey { + group: key.group, + compare: key.compare, + array: index, + }; + x.source = Source::HeapArray { + handle, + sampler: smp_handle, + key, + }; + if let Some(raw) = &mut x.heap_raw { + raw.state = State::Table { words }; + } + cx.families.sampler.heap = before; + cx.families.sampler.heap_arrays.insert(key); + Ok(Some(TextureStrategy::Sampling(Box::new(x)))) +} + /// The emulation of heap sampling call `call` of element `handle` of heap group `group` through /// `sampler` that answers a texture the heap holds by its raw texels alone as Metal does /// (`heap_raw`), where the call's texture type may hold one: a non-multisampled color texture @@ -712,7 +847,7 @@ fn heap_raw_sample( State::Constant { address, .. } => address .get(a) .is_some_and(|m| matches!(m, TapAddress::Repeat | TapAddress::Mirror)), - State::Slot { .. } => true, + State::Slot { .. } | State::Table { .. } => true, }; let moved = offset.as_deref().unwrap_or_default(); if moved.iter().enumerate().any(|(a, k)| *k != 0 && wraps(a)) { @@ -731,7 +866,8 @@ fn heap_raw_sample( let note = PrecisionNote::BicubicFilterArithmetic; let raw = NoteTest::equal(NoteOn::HeapRaw(cx.stage), FILTERED, FILTERED); let when: Vec = match state { - State::Constant { linear: false, .. } => Vec::new(), + // A sampler array's table is made of candidates whose states each noted their own. + State::Constant { linear: false, .. } | State::Table { .. } => Vec::new(), State::Constant { .. } => vec![[raw].into()], State::Slot { sampler: n } => super::linear::filtering_word(n) .into_iter() diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index e479c1e8b..a8a9d7c37 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -502,6 +502,7 @@ mod serde_round_trips { immutable_sampler: None, flags: vk::DescriptorBindingFlags::empty(), variables: 1, + immutable_samplers: Vec::new(), }, DescriptorBinding { binding: 1, @@ -515,6 +516,7 @@ mod serde_round_trips { immutable_sampler: None, flags: vk::DescriptorBindingFlags::empty(), variables: 1, + immutable_samplers: Vec::new(), }, ], flags: vk::DescriptorSetLayoutCreateFlags::empty(), diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 321f453fe..1e05e1dae 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3326,5 +3326,6 @@ fn stage_interface( snapshot_refusals: snapshots.refusals, level_reads, private_bytes: plan.private_bytes, + sampler_arrays: crate::lower::sampler::sampler_arrays(plan), } } diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index 12ceca3c7..be20e646f 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -407,6 +407,24 @@ pub struct StageInterface { /// `PrecisionNote::FunctionStorageAssumed`'s announcement names. #[cfg_attr(feature = "serde", serde(default))] pub private_bytes: u64, + /// The samplers of each constexpr sampler array the module declares + /// (`ResourceKind::SamplerArray`), which link bakes into its binding as the immutable samplers + /// (`DescriptorBinding::immutable_samplers`). + #[cfg_attr(feature = "serde", serde(default))] + pub sampler_arrays: Vec, +} + +/// One constexpr sampler array of a stage (`ResourceKind::SamplerArray`): the binding a heap +/// sampling indexes by its sampler handle's distance from the first candidate's, Metal's +/// `constexpr sampler`s it chooses among. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct SamplerArray { + /// The array's binding symbol, whose kind states the use its samplers are made for. + pub slot: ResourceSlot, + /// Each element's constexpr sampler, in element order. + pub samplers: Vec, } /// What leaves an own-pixel texture slot of a fragment function out of the slots a draw can read diff --git a/crates/metal2vulkan/src/pipeline/layout.rs b/crates/metal2vulkan/src/pipeline/layout.rs index 56d6a265c..d81aa0ae4 100644 --- a/crates/metal2vulkan/src/pipeline/layout.rs +++ b/crates/metal2vulkan/src/pipeline/layout.rs @@ -62,6 +62,11 @@ pub struct DescriptorBinding { /// binding of more than one. #[cfg_attr(feature = "serde", serde(default))] pub variables: u32, + /// The constexpr samplers baked into a sampler array's binding + /// (`BindingSource::SamplerArray`), one per element (`count` of them); empty for every other + /// binding. + #[cfg_attr(feature = "serde", serde(default))] + pub immutable_samplers: Vec, } /// What feeds a [`DescriptorBinding`]. @@ -138,6 +143,15 @@ pub enum BindingSource { /// The snapshot of the texture the draw binds at this fragment texture slot /// (`ResourceKind::SnapshotTexels`), bound as a storage image. SnapshotTexels(u32), + /// A constexpr sampler array of `stage` (`ResourceKind::SamplerArray`) that samples set-1 + /// heap images, made for the use with comparison or without (`compare`) of an integer texture + /// or not (`integer`): its samplers are the binding's `immutable_samplers`, which take no + /// descriptor write. + SamplerArray { + stage: Stage, + compare: bool, + integer: bool, + }, } /// One push-constant range of a [`PipelineLayout`]: a stage's fixed window (vertex `[0, 64)`, diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 24594ced6..aba48ad67 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -784,9 +784,54 @@ fn binding_source(slot: ResourceSlot) -> BindingSource { ResourceKind::ExtendedShadow(color) => BindingSource::ExtendedShadow(color), ResourceKind::SnapshotTexels(texture) => BindingSource::SnapshotTexels(texture), ResourceKind::YCbCrPlanes(_) => BindingSource::YCbCrPlanes(metal(SlotClass::Texture)), + ResourceKind::SamplerArray { compare, integer } => BindingSource::SamplerArray { + stage: slot.stage, + compare, + integer, + }, } } +/// The immutable samplers of constexpr sampler array `slot` (`ResourceKind::SamplerArray`), +/// whose binding holds `count` of them: each element's constexpr sampler, as its stage's interface +/// lists them, made for the kind's use. Empty for every other binding. +fn immutable_samplers( + slot: ResourceSlot, + count: u32, + ifaces: &[&StageInterface], + p: &DeviceProfile, +) -> Result, Error> { + let ResourceKind::SamplerArray { compare, integer } = slot.kind else { + return Ok(Vec::new()); + }; + let invariant = |detail: &str| { + Error::Internal(InternalError::new( + InternalKind::Invariant, + format!("sampler array {slot:?}: {detail}"), + )) + }; + let array = ifaces + .iter() + .filter(|i| i.stage == slot.stage) + .flat_map(|i| &i.sampler_arrays) + .find(|a| a.slot == slot) + .ok_or_else(|| invariant("not in its stage's interface"))?; + if u32::try_from(array.samplers.len()).ok() != Some(count) { + return Err(invariant("its samplers do not fill its count")); + } + let use_ = crate::metal::sampler::SamplerUse::new(compare, integer); + array + .samplers + .iter() + .map(|s| match *s { + crate::pipeline::sym::SamplerRef::Constexpr(words) => { + crate::lower::sampler::constexpr_desc(words, use_, p) + } + crate::pipeline::sym::SamplerRef::Slot(_) => Err(invariant("a runtime sampler")), + }) + .collect() +} + /// The immutable sampler of binding `slot`: a combined image sampler's, heap sampler's, or /// separate sampler's constexpr sampler, made for its use; a planes image's device conversion /// (`ResourceKind::YCbCrPlanes`). @@ -982,6 +1027,7 @@ fn layout( immutable_sampler: immutable_sampler(slot, p)?, flags: vk::DescriptorBindingFlags::empty(), variables: 0, + immutable_samplers: immutable_samplers(slot, d.count, ifaces, p)?, }); } check_set_limits(&bindings, p)?; @@ -1111,6 +1157,7 @@ fn heap_set( immutable_sampler: None, flags, variables: 0, + immutable_samplers: Vec::new(), }); } Ok(Some(DescriptorSetLayout { diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 6df04a9ba..5c01a2376 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -141,6 +141,7 @@ pub(super) fn iface( snapshot_refusals: Vec::new(), level_reads: Vec::new(), private_bytes: 0, + sampler_arrays: Vec::new(), } } diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 5f343631a..b7ef8095a 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -125,8 +125,9 @@ pub use graphics::{ pub use interface::{ AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads, MeshRecords, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, - PushPlacement, RecordField, RecordValue, SampledLevels, SamplerLevels, SamplerSlot, - SlotInterface, SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, Window, + PushPlacement, RecordField, RecordValue, SampledLevels, SamplerArray, SamplerLevels, + SamplerSlot, SlotInterface, SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, + Window, }; pub use layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 318a85495..c2234b6ee 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -429,6 +429,16 @@ pub enum ResourceKind { /// image sampler whose immutable sampler is the device's conversion of this /// (`vk::SamplerDesc::ycbcr`), whose image the consumer views with the same conversion. YCbCrPlanes(crate::bind::YCbCrPlanesSampler), + /// The constexpr samplers one heap sampling chooses among by its sampler handle: an array of + /// one immutable sampler per candidate, each made for this use (with comparison or without, + /// of an integer texture or not), indexed by the handle's distance from the first + /// candidate's. `ResourceSlot::index` numbers the stage's arrays; the stage's interface lists + /// each one's samplers in element order (`StageInterface::sampler_arrays`), which link bakes + /// into the layout. + SamplerArray { + compare: bool, + integer: bool, + }, } /// What a bound acceleration structure holds: the binder binds a top-level structure, so a diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index bb85f0150..9e9515ef9 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -645,6 +645,13 @@ impl ModuleBuilder { }) if !matches!(dim, Dim::Buffer | Dim::SubpassData) ), ResourceKind::SeparateSampler(_) => matches!(self.types.get(ty)?, Type::Sampler), + // A constexpr sampler array is exactly a sized array of samplers. + ResourceKind::SamplerArray { .. } => match self.types.get(ty)? { + Type::Array { + elem, stride: None, .. + } => matches!(self.types.get(*elem)?, Type::Sampler), + _ => false, + }, _ => true, }; if !ok { diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index cad34aeda..6fc3cb164 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -2457,6 +2457,134 @@ declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr a link_and_validate(&a, &p).unwrap_or_else(|e| panic!("L3: {e}")); } +/// The words of a nearest constexpr sampler in normalized coordinates, every axis addressed by +/// `address` (1 clamp to edge, 2 repeat, 3 mirrored repeat), no mip filter, with the fields Apple's +/// compiler writes for the rest (as `LINEAR_EDGE`'s). +pub(super) const fn nearest_sampler(address: u64) -> u64 { + 0x007b_ff00_0008_0000 | address | address << 3 | address << 6 +} + +/// The constexpr samplers [`chosen_sampler_kernel`] lists, in order: clamped to the edge, +/// repeating, and mirrored. +pub(super) const CHOSEN_SAMPLERS: [u64; 3] = + [nearest_sampler(1), nearest_sampler(2), nearest_sampler(3)]; + +/// A kernel `chosen` that samples the `texture2d` its argument buffer (buffer 0) holds at +/// level 0 and `(1.375, 0.5)` through the constexpr sampler its lane `gid` chooses, +/// `pick[gid % pick.len()]` (indices of [`CHOSEN_SAMPLERS`], each a constexpr sampler of the +/// module, listed in order), adds the sample through sampler `direct` alone where it names one, and +/// writes the sum to buffer 1's lane `gid` (a `float4`). +pub(super) fn chosen_sampler_kernel(pick: &[usize], direct: Option) -> String { + let call = |s: &str| { + format!( + "call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) {s}, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)" + ) + }; + let n = pick.len(); + let mut choose = format!(" %m = urem i32 %gid, {n}\n"); + let mut chosen = format!("@s{}", pick[n - 1]); + for (k, s) in pick[..n - 1].iter().enumerate().rev() { + choose += &format!( + " %c{k} = icmp eq i32 %m, {k}\n %p{k} = select i1 %c{k}, ptr addrspace(2) @s{s}, ptr addrspace(2) {chosen}\n" + ); + chosen = format!("%p{k}"); + } + let sum = match direct { + Some(d) => format!( + " %dr = {}\n %dv = extractvalue {{ <4 x float>, i8 }} %dr, 0\n %y = fadd <4 x float> %v, %dv\n", + call(&format!("@s{d}")) + ), + None => " %y = fadd <4 x float> %v, zeroinitializer\n".to_string(), + }; + let globals: String = (CHOSEN_SAMPLERS.iter().enumerate()) + .map(|(i, w)| { + format!("@s{i} = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n") + }) + .collect(); + let states: String = (0..CHOSEN_SAMPLERS.len()) + .map(|i| { + format!( + "!{} = !{{!\"air.sampler_state\", ptr addrspace(2) @s{i}}}\n", + 20 + i + ) + }) + .collect(); + format!( + r#"%struct.M = type {{ ptr addrspace(1) }} +{globals} +define void @chosen(ptr addrspace(2) %m, ptr addrspace(1) %out, i32 %gid) {{ + %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 +{choose} %r = {} + %v = extractvalue {{ <4 x float>, i8 }} %r, 0 +{sum} %o = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %gid + store <4 x float> %y, ptr addrspace(1) %o, align 16 + ret void +}} +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.kernel = !{{!0}} +!air.version = !{{!11}} +!air.language_version = !{{!12}} +!air.sampler_states = !{{!20, !21, !22}} +!0 = !{{ptr @chosen, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !6, !8}} +!3 = !{{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"M", !"air.arg_name", !"m"}} +!4 = !{{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5}} +!5 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} +!6 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, 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", !"out"}} +!8 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}} +!11 = !{{i32 2, i32 8, i32 0}} +!12 = !{{!"Metal", i32 4, i32 0, i32 0}} +{states}"#, + call(&chosen) + ) +} + +/// Constexpr samplers of consecutive handles that a lane chooses among beside a heap texture are +/// one sampling through a set-0 array of their samplers (`ResourceKind::SamplerArray`, one element +/// per candidate), indexed by the handle: one sampled image, where a switch over them makes one +/// per candidate. Where the handles are not consecutive (a constexpr sampler between them sampled +/// through apart), the switch stays: a sampled image per candidate and one for the sample apart. +/// Every profile with the sampled heap compiles both and passes L3. +#[test] +fn chosen_constexpr_samplers_beside_a_heap_texture_are_one_sampler_array() { + let (Some(array), Some(apart)) = ( + assemble("chosen_samplers", &chosen_sampler_kernel(&[0, 1, 2], None)), + assemble( + "chosen_samplers_apart", + &chosen_sampler_kernel(&[0, 2], Some(1)), + ), + ) else { + return; + }; + let arrays = |a: &FunctionArtifact| -> Vec { + (a.interface.descriptors.iter()) + .filter(|d| matches!(d.slot.kind, ResourceKind::SamplerArray { .. })) + .map(|d| d.count) + .collect() + }; + let mut compiled = 0; + for (stem, p) in committed_profiles().expect("profiles") { + if !has_sampled_heap(&p) { + continue; + } + let a = compile(&array, "chosen", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert_eq!(arrays(&a), vec![3], "{stem}"); + assert_eq!(uses(&a, "sampler.sampler_array.sample"), 1, "{stem}"); + assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{stem}"); + assert!(heap_samplers(&a).is_empty(), "{stem}"); + let b = compile(&apart, "chosen", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&b, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert!(arrays(&b).is_empty(), "{stem}"); + assert_eq!(uses(&b, "sampler.sampler_array.sample"), 0, "{stem}"); + assert_eq!(count(&b, OP_SAMPLED_IMAGE), 3, "{stem}"); + compiled += 1; + } + assert!(compiled > 0, "no committed profile has the sampled heap"); +} + /// A kernel that writes a slice of its explicit imageblock (one `elem` field per cell, `lanes` /// lanes) to the texture of an argument buffer's one member (`texture2d` or /// `texture2d`). diff --git a/crates/metal2vulkan/src/tests/engine_heap_binder.rs b/crates/metal2vulkan/src/tests/engine_heap_binder.rs index 280d80bd2..964c30824 100644 --- a/crates/metal2vulkan/src/tests/engine_heap_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_heap_binder.rs @@ -1252,6 +1252,75 @@ fn heap_samplers_take_no_write_and_meet_every_held_member() { } } +/// Constexpr samplers a lane chooses among beside a heap texture are one set-0 sampler array +/// (`BindingSource::SamplerArray`): a `SAMPLER` binding of one element per candidate whose +/// immutable samplers are, element by element, exactly the immutable sampler a heap texture sampled +/// through that candidate alone bakes, and which the plan never writes. +#[test] +fn a_constexpr_sampler_array_bakes_each_candidates_own_sampler() { + use super::engine_handles::{chosen_sampler_kernel, CHOSEN_SAMPLERS}; + let dev = m3(); + let Some(bc) = assemble("chosen", &chosen_sampler_kernel(&[0, 1, 2], None)) else { + return; + }; + let pipe = compute(&dev, &bc, "chosen"); + let set = &pipe.layout.sets[0].bindings; + assert!( + !set.iter() + .any(|b| matches!(b.source, BindingSource::HeapSampler { .. })), + "{set:?}" + ); + let arrays: Vec<_> = set + .iter() + .filter(|b| matches!(b.source, BindingSource::SamplerArray { .. })) + .collect(); + assert_eq!(arrays.len(), 1, "{set:?}"); + let array = arrays[0]; + assert_eq!( + array.source, + BindingSource::SamplerArray { + stage: Stage::Kernel, + compare: false, + integer: false, + } + ); + assert_eq!(array.ty, vk::DescriptorType::SAMPLER); + assert_eq!(array.count, 3); + assert_eq!(array.immutable_sampler, None); + // Each element is the sampler a heap sample through that candidate alone bakes. + let alone: Vec = (0..CHOSEN_SAMPLERS.len()) + .map(|i| { + let bc = assemble("chosen_alone", &chosen_sampler_kernel(&[i], None)) + .expect("assembled once already"); + let one = compute(&dev, &bc, "chosen"); + let heap: Vec<_> = (one.layout.sets[0].bindings.iter()) + .filter(|b| matches!(b.source, BindingSource::HeapSampler { .. })) + .collect(); + assert_eq!(heap.len(), 1, "sampler {i}"); + heap[0].immutable_sampler.expect("a constexpr heap sampler") + }) + .collect(); + assert_eq!(array.immutable_samplers, alone); + let state = BindState { + used_resources: vec![used( + 1, + TextureType::Type2D, + PixelFormat::R32Float, + read(), + Some(A), + )], + ..Default::default() + }; + let plan = pipe.plan(&dev, &state.shape()).expect("plan"); + assert!( + !plan + .descriptors + .iter() + .any(|d| d.set == 0 && d.binding == array.binding), + "the plan writes an immutable sampler array" + ); +} + /// `argument_buffer_runtime_sampler` of the owned `handles` fixture samples a heap texture through /// its runtime `[[sampler(0)]]`. Its set-0 heap sampler binding has no immutable sampler; the plan /// writes it with the sampler bound at the kernel's slot 0, made for the use (no comparison, a diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index a5f25e146..054731972 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -4648,6 +4648,7 @@ field metal2vulkan::pipeline::DescriptorBinding.binding pub binding: u32 field metal2vulkan::pipeline::DescriptorBinding.count pub count: u32 field metal2vulkan::pipeline::DescriptorBinding.flags pub flags: vk::DescriptorBindingFlags field metal2vulkan::pipeline::DescriptorBinding.immutable_sampler pub immutable_sampler: Option +field metal2vulkan::pipeline::DescriptorBinding.immutable_samplers pub immutable_samplers: Vec field metal2vulkan::pipeline::DescriptorBinding.source pub source: BindingSource field metal2vulkan::pipeline::DescriptorBinding.stages pub stages: vk::ShaderStageFlags field metal2vulkan::pipeline::DescriptorBinding.ty pub ty: vk::DescriptorType @@ -4960,6 +4961,8 @@ field metal2vulkan::pipeline::SampledLevels.computed pub computed: bool field metal2vulkan::pipeline::SampledLevels.highest_lod_bits pub highest_lod_bits: Option field metal2vulkan::pipeline::SampledLevels.lowest_lod_bits pub lowest_lod_bits: Option field metal2vulkan::pipeline::SampledLevels.sampler pub sampler: crate::pipeline::sym::SamplerRef +field metal2vulkan::pipeline::SamplerArray.samplers pub samplers: Vec +field metal2vulkan::pipeline::SamplerArray.slot pub slot: ResourceSlot field metal2vulkan::pipeline::SamplerLevels.bias pub bias: f32 field metal2vulkan::pipeline::SamplerLevels.finite_texels pub finite_texels: bool field metal2vulkan::pipeline::SamplerLevels.linear pub linear: bool @@ -10498,6 +10501,7 @@ struct metal2vulkan::pipeline::RenderPipelineKeys #[derive(Clone, Debug, Partial struct metal2vulkan::pipeline::ResourceSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ResourceSlot struct metal2vulkan::pipeline::RuntimeDependency #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct RuntimeDependency struct metal2vulkan::pipeline::SampledLevels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SampledLevels +struct metal2vulkan::pipeline::SamplerArray #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerArray struct metal2vulkan::pipeline::SamplerLevels #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerLevels struct metal2vulkan::pipeline::SamplerSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerSlot struct metal2vulkan::pipeline::ShaderTestsUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ShaderTestsUse @@ -14460,6 +14464,7 @@ variant metal2vulkan::pipeline::BindingSource::Heap Heap(HandleClass) variant metal2vulkan::pipeline::BindingSource::HeapSampler HeapSampler { stage: Stage, sampler: CombinedSampler } variant metal2vulkan::pipeline::BindingSource::InputAttachment InputAttachment(u32) variant metal2vulkan::pipeline::BindingSource::Sampler Sampler(SlotRef) +variant metal2vulkan::pipeline::BindingSource::SamplerArray SamplerArray { stage: Stage, compare: bool, integer: bool } variant metal2vulkan::pipeline::BindingSource::SeparateSampler SeparateSampler { stage: Stage, sampler: CombinedSampler } variant metal2vulkan::pipeline::BindingSource::SeparateTexture SeparateTexture { texture: SlotRef, sampler: CombinedSampler } variant metal2vulkan::pipeline::BindingSource::SnapshotTexels SnapshotTexels(u32) @@ -14667,6 +14672,7 @@ variant metal2vulkan::pipeline::ResourceKind::Heap Heap(HandleClass) variant metal2vulkan::pipeline::ResourceKind::HeapSampler HeapSampler(SamplerRef) variant metal2vulkan::pipeline::ResourceKind::InputAttachment InputAttachment(u32) variant metal2vulkan::pipeline::ResourceKind::Sampler Sampler +variant metal2vulkan::pipeline::ResourceKind::SamplerArray SamplerArray { compare: bool, integer: bool } variant metal2vulkan::pipeline::ResourceKind::SeparateSampler SeparateSampler(SamplerRef) variant metal2vulkan::pipeline::ResourceKind::SeparateTexture SeparateTexture(SamplerRef) variant metal2vulkan::pipeline::ResourceKind::SnapshotTexels SnapshotTexels(u32) diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index e4022267b..342c9ea3b 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -406,6 +406,7 @@ surface! { struct RecordField N; enum RecordValue N; struct SampledLevels N; + struct SamplerArray N; struct SamplerLevels N; struct SamplerSlot N; enum SlotInterface N; diff --git a/docs/API.md b/docs/API.md index 3e3458cd2..4f3e8e67c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1243,6 +1243,17 @@ for dependency in &pipeline.dependencies { (`DescriptorCount`), and a stage that would bind it only to test its argument samplers for a cubic filter binds nothing, so the plan refuses a cubic sampler listed beside it (`SamplerBicubicFilter`). +- A heap texture sampled through one of several constexpr samplers, the one a sampler handle names + at run time (a table of constexpr samplers read at a computed index), samples once through a + set-0 array of those samplers (`ResourceKind::SamplerArray`, `BindingSource::SamplerArray`), + at the element the handle names. The binding's `immutable_samplers` holds each element's sampler, + `count` of them, each made as a heap texture sampled through that sampler alone bakes it; it takes + no descriptor write, and a pushed set 0 pushes them. `StageInterface::sampler_arrays` lists each + array's constexpr samplers by its slot. The module takes this form where the candidates' handles + are consecutive, each candidate's sampling is the same but for its sampler, and the device indexes + a sampler array by a value that may differ between invocations + (`shaderSampledImageArrayNonUniformIndexing`, which heap textures already need); otherwise it + switches over the candidates, one sampling per candidate. - Each binding's `variables` is the most variables one stage's entry point uses at it (those its `OpEntryPoint` lists): a function that reaches a buffer through several types uses a variable of each type at the buffer's binding. A set-0 uniform or storage buffer binding may be created as its dynamic type