diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 40b0c4b2e..a881e2d2f 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -332,6 +332,7 @@ fn read_only_slot( } => (*at == slot).then_some(true), WriteSource::YCbCrInPlace { slot: at } | WriteSource::YCbCrPlanesImage { slot: at } + | WriteSource::TexelRows { slot: at, .. } | WriteSource::TexelBuffer { slot: at, .. } | WriteSource::HeapEntry { source: HeapSource::Bound(at), @@ -931,6 +932,7 @@ pub(super) fn rebind_into( WriteSource::TexelBuffer { slot, .. } | WriteSource::YCbCrInPlace { slot } | WriteSource::YCbCrPlanesImage { slot } + | WriteSource::TexelRows { slot, .. } if changed(slot) => { return Ok(false) @@ -2023,6 +2025,14 @@ fn texel_descriptor( device.shared().counts.thread().ycbcr_planes_bound(); texture.planes_view() } + // The rows of a shadowed 2D texture read and written in place + // (`texture/texel_rows.rs`). + WriteSource::TexelRows { slot, format } => { + let texture = slot_texture(tables, *slot) + .ok_or_else(|| internal("the plan binds an unbound texture slot's rows"))?; + device.shared().counts.thread().texel_rows_bound(); + texture.rows_view(*format, storage) + } other => Err(unexpected(other)), } } @@ -3215,6 +3225,16 @@ fn other_use( .planes_use(access(read, resource.access.read)) .map(Some); } + // A shadowed texture's rows read and written in place: their bytes, through a + // uniform or a storage texel buffer, not the shadow (`texture/texel_rows.rs`). + if resource.class == AccessClass::TexelRows { + use vk::AccessFlags2 as A; + let read = A::SHADER_SAMPLED_READ | A::SHADER_STORAGE_READ; + let write = A::SHADER_STORAGE_WRITE; + let read = access(read, resource.access.read); + let write = access(write, resource.access.write); + return texture.rows_use(read, write).map(Some); + } let (read, write) = image_access(resource.class)?; let storage = resource.class == AccessClass::StorageImage; let accesses = ( diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index 2da5b17cd..339627aed 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -650,6 +650,27 @@ pub(crate) enum ShadowCause { Refused(Refusal, String), } +/// Whether a shadow made for `cause` leaves a function's reads and writes of its rows in place +/// (`texture/texel_rows.rs`): the device refused the image over them for its format, features, +/// usage or limits, the rows' pitch, or the bytes' place, or the dma-buf import of the texture's +/// pages refused it, none of which a texel buffer over the same bytes meets. Not the device's +/// policy (`HostPageTexturePolicy::Shadow`, which asks the shadow everywhere), a class's check +/// (pending, failed or unmade), a write's width, rows that share bytes, or bytes detached from +/// their pages. +pub(crate) fn leaves_rows(cause: &ShadowCause) -> bool { + matches!( + cause, + ShadowCause::Refused( + Refusal::Image + | Refusal::Pitch + | Refusal::Placement + | Refusal::Source + | Refusal::DmaBuf, + _ + ) + ) +} + /// Why the device makes no image in place over a texture's texels. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Refusal { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 89592808d..a4debfdc9 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -11727,7 +11727,7 @@ impl RenderLowering { && live.state.extended_shadows.is_empty() && !plan.variant.extended_range.values().any(planes) && !(self.layout.colors.iter().flatten()).any(extended) - && !facts.ycbcr(); + && !facts.in_place(); let plain = plain_but_heap && heap.is_none() && texture_table.is_none() && sampler_table.is_none(); // A replayed draw that reads the heap is plain where a kept recording of it binds the heap diff --git a/crates/metal2vulkan-runtime/src/render/plan_facts.rs b/crates/metal2vulkan-runtime/src/render/plan_facts.rs index b1a04f353..16f8a35c1 100644 --- a/crates/metal2vulkan-runtime/src/render/plan_facts.rs +++ b/crates/metal2vulkan-runtime/src/render/plan_facts.rs @@ -23,8 +23,9 @@ pub(crate) struct PlanFacts { tile_memory: Option, /// The colors whose extended-range shadows a write binds, ascending, each once. extended: Vec, - /// Whether a write binds a YCbCr texture in place or its planes' image. - ycbcr: bool, + /// Whether a write binds a YCbCr texture in place or its planes' image, or a shadowed + /// texture's rows in place (`texture/texel_rows.rs`). + in_place: bool, } impl PlanFacts { @@ -38,7 +39,7 @@ impl PlanFacts { reads_handles: false, tile_memory: None, extended: Vec::new(), - ycbcr: false, + in_place: false, }; for write in &plan.descriptors { let storage = write.ty == DescriptorType::STORAGE_IMAGE; @@ -54,9 +55,9 @@ impl PlanFacts { facts.tile_memory = facts.tile_memory.or(Some(*bytes)); } WriteSource::ExtendedShadow { color_index } => facts.extended.push(*color_index), - WriteSource::YCbCrInPlace { .. } | WriteSource::YCbCrPlanesImage { .. } => { - facts.ycbcr = true; - } + WriteSource::YCbCrInPlace { .. } + | WriteSource::YCbCrPlanesImage { .. } + | WriteSource::TexelRows { .. } => facts.in_place = true, _ => {} } } @@ -90,9 +91,10 @@ impl PlanFacts { &self.extended } - /// Whether the plan binds a YCbCr texture in place or its planes' image. - pub(crate) fn ycbcr(&self) -> bool { - self.ycbcr + /// Whether the plan binds a YCbCr texture in place or its planes' image, or a shadowed + /// texture's rows in place. + pub(crate) fn in_place(&self) -> bool { + self.in_place } } diff --git a/crates/metal2vulkan-runtime/src/shadow_log.rs b/crates/metal2vulkan-runtime/src/shadow_log.rs index 2d0c62c38..a9485d0ac 100644 --- a/crates/metal2vulkan-runtime/src/shadow_log.rs +++ b/crates/metal2vulkan-runtime/src/shadow_log.rs @@ -21,7 +21,9 @@ //! - **What a shadowed texture's first draw or dispatch reads.** One line per shadowed texture //! (one whose reads go through a shadow of its truth, a usage shadow or two faces that take //! turns), at the first draw or dispatch whose pipeline uses a slot that binds it, after the -//! command's bindings made the shadow it reads: the slot, whether the function fetches, samples +//! command's bindings made the shadow it reads: the slot, what it goes through (its rows in +//! place, not its shadow, where the slot binds a shadowed texture's rows as a texel buffer, +//! `texture/texel_rows.rs`), whether the function fetches, samples //! or writes it, and for each sampler it samples it through, a sampler state's minification, //! magnification and mipmap filters (Metal's names) or a constexpr sampler's (Vulkan's names, //! as the layout bakes it). A texture's line names it once in the process, at whichever command @@ -41,7 +43,7 @@ use super::driver_facts::inform_through; use super::texture_descriptor::{TextureDescriptor, TextureLayout}; use super::texture_placement::TexturePlacement; use super::{Buffer, Device, Error, Texture}; -use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan::pipeline::{ BindingSource, ComputePipeline, PipelineInterface, PipelineLayout, RenderPipeline, SamplerRef, SlotClass, SlotInterface, SlotRef, Stage, StageModule, @@ -205,6 +207,13 @@ fn first_binds( class: SlotClass::Texture, index, }; + // A shadowed 2D texture's rows read and written in place (`texture/texel_rows.rs`): + // its slot's binding is a texel buffer, not the shadow. + let buffer = texture.texture_type() == TextureType::TextureBuffer; + let kind = match rows_bound(layout, slot) && !buffer { + true => "its rows in place, not its shadow", + false => kind, + }; let Some(SlotInterface::Texture(used)) = interface.slots.get(&slot) else { continue; }; @@ -240,6 +249,17 @@ fn first_binds( } } +/// Whether `layout` binds texture slot `slot` as a texel buffer. +fn rows_bound(layout: &PipelineLayout, slot: SlotRef) -> bool { + (layout.sets.iter()).flat_map(|set| &set.bindings).any(|b| { + b.source == BindingSource::Texture(slot) + && matches!( + b.ty, + vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER + ) + }) +} + /// What a draw's reads of `texture` go through, where they go through a shadow: its faces /// (`texture/faces.rs`), a usage shadow (`texture/usage_shadow.rs`) or a shadow of its truth. fn shadowed(texture: &Texture) -> Option<&'static str> { diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 31786be05..70ce6caab 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -742,6 +742,8 @@ mod surface_two_planes; mod sync_file; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod teardown_threads; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod texel_rows_device; mod texture; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod texture_aggregates; diff --git a/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs index 09444ce00..d2d5ae0e4 100644 --- a/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs @@ -875,6 +875,12 @@ fn the_shadow_log_names_a_twin_not_in_place_and_a_dispatch_s_first_read() { let not_in_place = after.read_twin_textures_not_in_place - before.read_twin_textures_not_in_place; let shadowed = texture.shadow().is_some(); + // A shadow whose rows a kernel reads in place (`texture/texel_rows.rs`) binds them, not the + // shadow. + let kind = match after.texel_rows_textures > before.texel_rows_textures { + true => "its rows in place, not its shadow", + false => "a shadow of its truth", + }; let state = invert(&device); let out = square(&device, PixelFormat::BGRA8Unorm); for _ in 0..2 { @@ -898,8 +904,8 @@ fn the_shadow_log_names_a_twin_not_in_place_and_a_dispatch_s_first_read() { ); let twin = named(&format!("the read twin of the {texture_named}, ")); let dispatch = named(&format!( - "the first dispatch that binds the {texture_named}, through a shadow of its truth, at \ - Kernel texture 0: its function fetches it" + "the first dispatch that binds the {texture_named}, through {kind}, at Kernel texture 0: \ + its function fetches it" )); eprintln!( "SHADOW-LOG: twins not in place {not_in_place}, the texture a shadow {shadowed}: {}", diff --git a/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs b/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs new file mode 100644 index 000000000..83a0ab619 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs @@ -0,0 +1,672 @@ +//! A shadowed 2D texture's rows read and written in place on a device (`texture/texel_rows.rs`). +//! +//! - **In place.** A texture over a no-copy buffer at a pitch of its row plus 16 bytes, whose +//! image the device refuses, is a shadow whose rows a kernel that asks its size, reads and +//! writes it binds as a texel buffer: its texels are inverted in the pages, the bytes between +//! its rows and past it keep theirs, and its commands copy nothing into or out of the shadow. +//! Each test runs over a buffer imported over its pages in place and over one that is a copy of +//! them (the caller's gate refusing the import, `copied.rs`), whose writes merge back into the +//! pages at completion; lavapipe lays the rows over the pages in place, and refuses an image at +//! that pitch over the copy. +//! - **The shadow still serves a sample.** A kernel that samples the texture after the rows' +//! writes, in the same command buffer and in the next, reads the inverted texels through the +//! shadow, copied in. +//! - **The image route's answers.** The rows read and write what the image route does, bit for +//! bit: every `RGBA8Unorm` code read, and a sweep of floats written (each code's value, the +//! midpoints between codes, and values outside `[0, 1]`); every `RGBA16Float` code read, and +//! each code's value, a value between it and the next, and its negation written. That is the +//! evidence behind the route's lack of a precision note: a texel buffer's texels go through the +//! device's conversion as an image's do. +//! - **Pipeline creation.** The time the first dispatch of a kernel over the rows takes to make its +//! rows variant, and a second state's, against the same over the image route: printed, for a +//! device's run to compare with Metal's range. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). A device that +//! imports no host memory, or that lays the rows in place over both buffers (no shadow), says so +//! and passes; lavapipe must take the rows over the copy. + +use crate::{ + Buffer, CommandBufferStatus, ComputePipelineState, Device, DeviceKind, DeviceOptions, + HostMemory, ImportGate, Region, ResourceOptions, Size, Texture, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::alloc::Layout; +use std::ptr::NonNull; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const WAIT: Duration = Duration::from_secs(120); + +/// Host memory of whole pages, freed when dropped (after the device). +struct Pages { + pointer: NonNull, + layout: Layout, +} + +impl Pages { + fn new(length: usize, seed: u8) -> Pages { + let layout = Layout::from_size_align(length.next_multiple_of(1 << 16), 1 << 16).unwrap(); + // SAFETY: the layout's size is not zero. + let pointer = NonNull::new(unsafe { std::alloc::alloc(layout) }).unwrap(); + let pages = Pages { pointer, layout }; + let bytes: Vec = (0..layout.size()) + .map(|at| (at as u8).wrapping_mul(29).wrapping_add(seed)) + .collect(); + pages.write(0, &bytes); + pages + } + + fn bytes(&self) -> Vec { + // SAFETY: the allocation's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(self.pointer.as_ptr(), self.layout.size()) }.to_vec() + } + + fn write(&self, at: usize, bytes: &[u8]) { + assert!(at + bytes.len() <= self.layout.size()); + // SAFETY: the allocation's bytes, which no command uses now. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + self.pointer.as_ptr().add(at), + bytes.len(), + ) + }; + } + + /// A `Shared` no-copy buffer over the pages, lying as `over` says. + fn buffer(&self, device: &Device, over: Over) -> Buffer { + // SAFETY: the pages outlive the buffer and the device (dropped after both). + let memory = unsafe { HostMemory::new(self.pointer) }; + let memory = match over { + Over::Pages => memory, + Over::Copy => { + let refused: ImportGate = Arc::new(|_| false); + memory.with_import_gate(refused) + } + }; + // SAFETY: as above. + unsafe { + device.new_buffer_with_bytes_no_copy( + memory, + self.layout.size() as u64, + ResourceOptions::shared(), + None, + ) + } + .expect("a no-copy buffer over the pages") + } +} + +impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `new`. + unsafe { std::alloc::dealloc(self.pointer.as_ptr(), self.layout) }; + } +} + +/// How a test's buffer lies over its pages: imported over them in place, or a copy of them, the +/// caller's gate refusing the import (`copied.rs`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Over { + Pages, + Copy, +} + +/// Both, each test's runs. +const OVER: [Over; 2] = [Over::Pages, Over::Copy]; + +/// Whether a test that took the rows over no buffer of `taken` (`OVER`'s) passes: on a device +/// other than lavapipe, which may lay every such texture in place; lavapipe refuses an image at +/// the tests' pitch over the copy, so it must take them there. +fn untaken_passes(taken: &[Over]) -> bool { + if cfg!(m2v_cpu_icd) { + assert!( + taken.contains(&Over::Copy), + "lavapipe refuses an image at this pitch over a copy, and the shadow's rows are read \ + in place" + ); + } + taken.is_empty() +} + +fn device() -> Option { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + ..DeviceOptions::default() + }; + let device = Device::system_default_with(&options).unwrap(); + if device.shared().host_import.is_err() { + eprintln!("TEXEL-ROWS: the device imports no host memory here; nothing to test"); + return None; + } + let exportable = crate::device::lock(&device.shared().memory) + .fd_buffer_types + .is_ok(); + if exportable { + assert!(device.settle_in_place_checks(Duration::from_secs(120))); + } + Some(device) +} + +/// The state of `kernel` of `examples/texel_rows.metal`. +fn state(device: &Device, kernel: &str) -> ComputePipelineState { + let function = super::encoder_holds::library(device, "examples/texel_rows.ll") + .new_function_with_name(kernel) + .unwrap(); + device + .new_compute_pipeline_state_with_function(&function, &crate::PipelineOptions::default()) + .unwrap() +} + +/// A texture of `format` (texels of `texel` bytes), `width` x `height`, `ShaderRead` and +/// `ShaderWrite`, over `buffer`'s bytes from its first, rows `pitch` bytes apart, and whether +/// its rows are read and written in place. `over` is how the buffer lies, for the line. +fn texture_over( + device: &Device, + (buffer, over): (&Buffer, Over), + (format, width, height): (PixelFormat, u64, u64), + pitch: u64, +) -> (Texture, bool) { + let mut descriptor = TextureDescriptor::texture_2d(format, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + descriptor.resource_options = ResourceOptions::shared(); + let before = device.work_counts(); + let texture = buffer.new_texture(&descriptor, 0, pitch).unwrap(); + let after = device.work_counts(); + let rows = after.texel_rows_textures - before.texel_rows_textures; + eprintln!( + "TEXEL-ROWS: {format:?} {width}x{height} at a pitch of {pitch} over the {over:?}: a \ + shadow {}, rows {rows}, refused pitch {} image {} placement {} source {}", + texture.shadow().is_some(), + after.host_texture_shadows_refused_pitch - before.host_texture_shadows_refused_pitch, + after.host_texture_shadows_refused_image - before.host_texture_shadows_refused_image, + after.host_texture_shadows_refused_placement + - before.host_texture_shadows_refused_placement, + after.host_texture_shadows_refused_source - before.host_texture_shadows_refused_source, + ); + (texture, rows == 1) +} + +/// A `Shared` texture of the device's own of `format`, `width` x `height`, `ShaderRead` and +/// `ShaderWrite`, holding `bytes` (rows tight, `texel` bytes a texel): the image route. +fn own_texture( + device: &Device, + (format, width, height): (PixelFormat, u64, u64), + texel: u64, + bytes: &[u8], +) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(format, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let region = Region::new_2d(0, 0, width, height); + texture + .replace_region(region, 0, 0, bytes, width * texel, 0) + .unwrap(); + texture +} + +/// A buffer of the device's own holding `bytes`. +fn own_buffer(device: &Device, bytes: &[u8]) -> Buffer { + let buffer = device + .new_buffer(bytes.len() as u64, ResourceOptions::shared()) + .unwrap(); + let at = buffer.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), at.as_ptr(), bytes.len()) }; + buffer +} + +/// `buffer`'s first `length` bytes as the CPU reads them. +fn contents(buffer: &Buffer, length: usize) -> Vec { + let at = buffer.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(at.as_ptr(), length) }.to_vec() +} + +/// One dispatch of `state` over a `grid`, `columns` (the grid's width) at buffer 1, `texture` at +/// texture 0 and `buffer` at buffer 0 where given. +struct Dispatch<'a> { + state: &'a ComputePipelineState, + texture: &'a Texture, + buffer: Option<&'a Buffer>, + grid: [u64; 2], +} + +/// Commit one command buffer of `dispatches`, each in an encoder of its own, wait for it, and +/// answer its status. +fn run(device: &Device, dispatches: &[Dispatch<'_>]) -> CommandBufferStatus { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + for d in dispatches { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(d.state).unwrap(); + encoder.set_texture(Some(d.texture), 0).unwrap(); + if let Some(buffer) = d.buffer { + encoder.set_buffer(Some(buffer), 0, 0).unwrap(); + } + let columns = (d.grid[0] as u32).to_le_bytes(); + encoder.set_bytes(&columns, 1).unwrap(); + encoder + .dispatch_threads(Size::new(d.grid[0], d.grid[1], 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + command_buffer.status() +} + +/// `bytes` laid in rows `pitch` apart, `width` texels of `texel` bytes each, `height` of them, +/// with each row's own bytes `f(x, y, byte)`. +fn rows_of( + bytes: &mut [u8], + (width, height, texel, pitch): (u64, u64, u64, u64), + f: impl Fn(u64, u64, u64) -> u8, +) { + for y in 0..height { + for b in 0..width * texel { + bytes[(y * pitch + b) as usize] = f(b / texel, y, b % texel); + } + } +} + +/// The texels of `bytes` laid in rows `pitch` apart, rows tight. +fn tight(bytes: &[u8], (width, height, texel, pitch): (u64, u64, u64, u64)) -> Vec { + (0..height) + .flat_map(|y| { + let start = (y * pitch) as usize; + bytes[start..start + (width * texel) as usize].to_vec() + }) + .collect() +} + +fn shadow_copies(before: &WorkCounts, after: &WorkCounts) -> u64 { + after.shadow_copies - before.shadow_copies +} + +const SIDE: u64 = 64; + +/// A kernel that asks the size, reads and writes a shadowed texture binds its rows: its texels +/// inverted in the pages with no shadow copy, the bytes between and past the rows kept; a sample +/// of it afterwards, in the same command buffer and the next, reads the inversion through the +/// shadow. +#[test] +fn a_kernel_reads_and_writes_a_shadowed_texture_s_rows_in_place() { + let Some(device) = device() else { return }; + let taken: Vec = (OVER.into_iter()) + .filter(|&over| reads_and_writes(&device, over)) + .collect(); + if untaken_passes(&taken) { + eprintln!("TEXEL-ROWS: this device lays the rows in place; nothing to test"); + } +} + +/// [`a_kernel_reads_and_writes_a_shadowed_texture_s_rows_in_place`] over a buffer lying as +/// `over` says; `false` where the texture's rows are not read in place. +fn reads_and_writes(device: &Device, over: Over) -> bool { + let pitch = SIDE * 4 + 16; + let pages = Pages::new((pitch * SIDE) as usize, 7); + let buffer = pages.buffer(device, over); + let shape = (PixelFormat::BGRA8Unorm, SIDE, SIDE); + let (texture, rows) = texture_over(device, (&buffer, over), shape, pitch); + if !rows { + return false; + } + let invert = state(device, "rows_invert"); + let sample = state(device, "rows_sample"); + let original = pages.bytes(); + let layout = (SIDE, SIDE, 4, pitch); + let inverted: Vec = (tight(&original, layout).as_chunks::<4>().0.iter()) + .flat_map(|t| [255 - t[0], 255 - t[1], 255 - t[2], t[3]]) + .collect(); + // The grid crosses the texture's edges: the kernel's own test stores nothing past them. + let before = device.work_counts(); + let status = run( + device, + &[Dispatch { + state: &invert, + texture: &texture, + buffer: None, + grid: [SIDE + 8, SIDE + 8], + }], + ); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(shadow_copies(&before, &after), 0, "no shadow copy"); + assert!( + after.texel_rows_bound > before.texel_rows_bound, + "the rows bound" + ); + let now = pages.bytes(); + assert!( + tight(&now, layout) == inverted, + "the texels inverted in the pages" + ); + let mut kept = now.clone(); + rows_of(&mut kept, layout, |x, y, b| { + original[(y * pitch + x * 4 + b) as usize] + }); + assert!(kept == original, "the bytes between and past the rows kept"); + // A sample after the rows' writes, in the same command buffer: the shadow copied in. + let out = device + .new_buffer(SIDE * SIDE * 16, ResourceOptions::shared()) + .unwrap(); + let before = device.work_counts(); + let status = run( + device, + &[ + Dispatch { + state: &invert, + texture: &texture, + buffer: None, + grid: [SIDE, SIDE], + }, + Dispatch { + state: &sample, + texture: &texture, + buffer: Some(&out), + grid: [SIDE, SIDE], + }, + ], + ); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + shadow_copies(&before, &after) > 0, + "the sample reads the shadow" + ); + let sampled = contents(&out, (SIDE * SIDE * 16) as usize); + // Inverted twice: the original texels, as the device samples them from a texture of its own + // holding them (its conversion of a code, not Metal's). + let shape = (PixelFormat::BGRA8Unorm, SIDE, SIDE); + let want = sampled_from( + device, + &sample, + &own_texture(device, shape, 4, &tight(&original, layout)), + ); + let once = sampled_from(device, &sample, &own_texture(device, shape, 4, &inverted)); + assert_eq!( + first_difference(&sampled, &want, 16), + None, + "the sample reads the rows' writes (the first write's alone: {})", + first_difference(&sampled, &once, 16).is_none() + ); + // And the next command buffer's sample reads them too. + let status = run( + device, + &[Dispatch { + state: &sample, + texture: &texture, + buffer: Some(&out), + grid: [SIDE, SIDE], + }], + ); + assert_eq!(status, CommandBufferStatus::Completed); + assert!(contents(&out, sampled.len()) == want, "the next sample too"); + drop((texture, buffer)); + true +} + +/// What `sample` (`rows_sample`) answers for each texel of `texture`, one command buffer of its +/// own. +fn sampled_from(device: &Device, sample: &ComputePipelineState, texture: &Texture) -> Vec { + let length = SIDE * SIDE * 16; + let out = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + let status = run( + device, + &[Dispatch { + state: sample, + texture, + buffer: Some(&out), + grid: [SIDE, SIDE], + }], + ); + assert_eq!(status, CommandBufferStatus::Completed); + contents(&out, length as usize) +} + +/// The rows' texels and the image route's, read through `rows_read` from two textures of +/// `format` holding the same `texels` (rows tight), as bits; and their stores of `values` +/// through `rows_write`, as bytes. The rows' texture lies over a buffer lying as `over` says. +/// `None` where the device lays the rows in place. +fn both_routes( + (device, over): (&Device, Over), + (format, width, height, texel): (PixelFormat, u64, u64, u64), + texels: &[u8], + values: &[f32], +) -> Option<[(Vec, Vec); 2]> { + let pitch = width * texel + 16; + let pages = Pages::new((pitch * height) as usize, 3); + let layout = (width, height, texel, pitch); + let mut bytes = pages.bytes(); + rows_of(&mut bytes, layout, |x, y, b| { + texels[((y * width + x) * texel + b) as usize] + }); + pages.write(0, &bytes); + let buffer = pages.buffer(device, over); + let (rows, taken) = texture_over(device, (&buffer, over), (format, width, height), pitch); + if !taken { + return None; + } + let image = own_texture(device, (format, width, height), texel, texels); + let read = state(device, "rows_read"); + let write = state(device, "rows_write"); + let length = (width * height * 16) as usize; + let mut reads = Vec::new(); + for texture in [&rows, &image] { + let out = device + .new_buffer(length as u64, ResourceOptions::shared()) + .unwrap(); + let status = run( + device, + &[Dispatch { + state: &read, + texture, + buffer: Some(&out), + grid: [width, height], + }], + ); + assert_eq!(status, CommandBufferStatus::Completed); + reads.push(contents(&out, length)); + } + let input: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + let input = own_buffer(device, &input); + let mut stores = Vec::new(); + for texture in [&rows, &image] { + let status = run( + device, + &[Dispatch { + state: &write, + texture, + buffer: Some(&input), + grid: [width, height], + }], + ); + assert_eq!(status, CommandBufferStatus::Completed); + let mut stored = vec![0; (width * height * texel) as usize]; + let region = Region::new_2d(0, 0, width, height); + texture + .get_bytes(&mut stored, width * texel, 0, region, 0, 0) + .unwrap(); + stores.push(stored); + } + assert!( + tight(&pages.bytes(), layout) == stores[0], + "the rows' stores are in the pages" + ); + drop((rows, buffer)); + let [a, b] = [reads, stores].map(|mut x| (x.swap_remove(0), x.swap_remove(0))); + Some([a, b]) +} + +/// The first index at which `a` and `b` differ, as `what` reads it. +fn first_difference(a: &[u8], b: &[u8], unit: usize) -> Option { + (a.chunks(unit).zip(b.chunks(unit))).position(|(x, y)| x != y) +} + +/// Every `RGBA8Unorm` code read through the rows is the image route's texel, bit for bit, and a +/// sweep of floats stores the same codes. +#[test] +fn rgba8_unorm_rows_answer_the_image_route_s_texels() { + let Some(device) = device() else { return }; + // 256 texels: every code in every channel, each channel a different order of them. + let (width, height) = (64, 4); + let texels: Vec = (0..256u32) + .flat_map(|i| [i, 255 - i, (i * 7) & 255, (i * 13 + 5) & 255].map(|c| c as u8)) + .collect(); + // Each code's value, the midpoint above it, just under that midpoint, and values outside + // [0, 1]. + let values: Vec = (0..256u32) + .flat_map(|k| { + let c = k as f32; + [ + c / 255.0, + (c + 0.5) / 255.0, + (c + 0.499) / 255.0, + (c - 128.0) / 64.0, + ] + }) + .collect(); + let shape = (PixelFormat::RGBA8Unorm, width, height, 4); + let mut taken = Vec::new(); + for over in OVER { + let Some([(rows_read, image_read), (rows_store, image_store)]) = + both_routes((&device, over), shape, &texels, &values) + else { + continue; + }; + assert_eq!(first_difference(&rows_read, &image_read, 16), None, "reads"); + assert_eq!( + first_difference(&rows_store, &image_store, 4), + None, + "stores" + ); + eprintln!( + "TEXEL-ROWS: RGBA8Unorm over the {over:?}: 1024 codes read and 1024 floats stored \ + alike" + ); + taken.push(over); + } + if untaken_passes(&taken) { + eprintln!("TEXEL-ROWS: this device lays the rows in place; nothing to compare"); + } +} + +/// A `half`'s value as a `float`. +fn half(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exponent = i32::from((h >> 10) & 0x1f); + let mantissa = f32::from(h & 0x3ff); + match exponent { + 0 => sign * mantissa * 2f32.powi(-24), + 31 if mantissa == 0.0 => sign * f32::INFINITY, + 31 => f32::NAN, + e => sign * (1.0 + mantissa / 1024.0) * 2f32.powi(e - 15), + } +} + +/// Every `RGBA16Float` code read through the rows is the image route's texel, bit for bit, and a +/// sweep of floats stores the same codes. +#[test] +fn rgba16_float_rows_answer_the_image_route_s_texels() { + let Some(device) = device() else { return }; + // 16384 texels: every code once. + let (width, height) = (128, 128); + let texels: Vec = (0..=u16::MAX).flat_map(u16::to_le_bytes).collect(); + // Each code's value, a value between it and the next, and its negation. + let values: Vec = (0..16384u32) + .flat_map(|t| { + let h = (t * 4) as u16; + let (v, next) = (half(h), half(h.wrapping_add(1))); + [v, v + (next - v) * 0.5, v + (next - v) * 0.25, -v] + }) + .collect(); + let shape = (PixelFormat::RGBA16Float, width, height, 8); + let mut taken = Vec::new(); + for over in OVER { + let Some([(rows_read, image_read), (rows_store, image_store)]) = + both_routes((&device, over), shape, &texels, &values) + else { + continue; + }; + assert_eq!(first_difference(&rows_read, &image_read, 16), None, "reads"); + assert_eq!( + first_difference(&rows_store, &image_store, 8), + None, + "stores" + ); + eprintln!( + "TEXEL-ROWS: RGBA16Float over the {over:?}: 65536 codes read and 65536 floats \ + stored alike" + ); + taken.push(over); + } + if untaken_passes(&taken) { + eprintln!("TEXEL-ROWS: this device lays the rows in place; nothing to compare"); + } +} + +/// The first dispatch of a new state over a texture, timed: the pipeline and its variant made. +fn first_dispatch(device: &Device, kernel: &str, texture: &Texture) -> Duration { + let state = state(device, kernel); + let start = Instant::now(); + let status = run( + device, + &[Dispatch { + state: &state, + texture, + buffer: None, + grid: [SIDE, SIDE], + }], + ); + let took = start.elapsed(); + assert_eq!(status, CommandBufferStatus::Completed); + took +} + +/// The first dispatch over the rows makes the rows variant; printed against the image route's, +/// cold (the first state) and warm (a second state of the same function). +#[test] +fn a_rows_variant_s_creation_is_timed() { + let Some(device) = device() else { return }; + let pitch = SIDE * 4 + 16; + let pages = Pages::new((pitch * SIDE) as usize, 5); + let shape = (PixelFormat::RGBA8Unorm, SIDE, SIDE); + // The first buffer whose texture's rows are read in place. + let found = OVER.into_iter().find_map(|over| { + let buffer = pages.buffer(&device, over); + let (rows, taken) = texture_over(&device, (&buffer, over), shape, pitch); + taken.then_some((rows, buffer, over)) + }); + let Some((rows, buffer, over)) = found else { + untaken_passes(&[]); + eprintln!("TEXEL-ROWS: this device lays the rows in place; nothing to time"); + return; + }; + let image = own_texture( + &device, + (PixelFormat::RGBA8Unorm, SIDE, SIDE), + 4, + &vec![0; (SIDE * SIDE * 4) as usize], + ); + let base_cold = first_dispatch(&device, "rows_invert", &image); + let rows_cold = first_dispatch(&device, "rows_invert", &rows); + let base_warm = first_dispatch(&device, "rows_invert", &image); + let rows_warm = first_dispatch(&device, "rows_invert", &rows); + eprintln!( + "TEXEL-ROWS: first dispatch of a new state, base cold {base_cold:?} warm {base_warm:?}, \ + rows (over the {over:?}) cold {rows_cold:?} warm {rows_warm:?}" + ); + assert!(rows_cold < Duration::from_secs(20), "within the ceiling"); + drop((rows, buffer)); +} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index cb3b52153..aa05178f7 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -197,6 +197,7 @@ pub(super) mod surface_depth; pub(super) mod surface_two_planes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod swapped_out_book; +mod texel_rows; pub(crate) mod twin_decode; mod usage_shadow; mod view_shadow; @@ -204,6 +205,7 @@ pub(super) mod wrapped; mod ycbcr_image; mod ycbcr_planes; pub(crate) use decoded_twin::TwinRead; +pub(crate) use texel_rows::RowsInPlace; pub(crate) use ycbcr_image::{KeptImage, PlanesInPlace}; pub(crate) use ycbcr_planes::KeptTexels; @@ -545,6 +547,11 @@ pub(super) struct TextureParts { /// (`texture/ycbcr_image.rs`): a slot of a function that reads it only so binds them, not the /// image. `None` for every other texture, a view of one among them. planes_in_place: Option, + /// A shadowed 2D texture's rows as a function reads and writes them in place + /// (`texture/texel_rows.rs`): a slot of a function that only reads, writes or asks the size + /// of it binds them, not the shadow. `None` for every other texture, a view of one among + /// them. + rows_in_place: Option, } impl std::ops::Deref for TextureShared { @@ -2700,7 +2707,9 @@ impl Device { ) -> Result { let mut record = ViewRecord::of_descriptor(layout, descriptor); let mut pending = None; - let over = (Arc::new(texels), &mut pending); + let mut rows = false; + let texels = Arc::new(texels); + let over = (Arc::clone(&texels), &mut pending, &mut rows); // An `A8Unorm` texture that only reads, where the device's linear `A8_UNORM` image lacks // what its optimal one does, is an `R8Unorm` texture's storage read through a swizzle // (`texture/red_held_alpha.rs`). @@ -2718,7 +2727,18 @@ impl Device { } None => self.storage_over_buffer(call, over, descriptor, layout)?, }; - let texture = Texture::made(self, storage, record, None, id_use); + // A shadow whose image the device refused over bytes that stay in place: its rows, read + // and written there by a function that only reads, writes or asks its size + // (`texture/texel_rows.rs`). Not an `A8Unorm` texture held in red, whose rows hold no + // texels of the format its slots read, nor a texture of the runtime's own (a read twin, + // which it keeps only in place, or a check's). + let program = matches!(id_use, IdUse::Program(_)); + let rows = match rows && program && record.read_as.is_none() { + true => self.rows_in_place(&texels, descriptor, layout), + false => None, + }; + let made = (storage, None, rows); + let texture = Texture::made_with_planes(self, made, record, None, id_use); // A shadow made before its pages' (or its pooled memory's) in-place verdict moves in // place once it passes. if let Some(pending) = pending { @@ -2737,7 +2757,7 @@ impl Device { fn storage_over_buffer( &self, call: &'static str, - (texels, pending): (Arc, &mut Option), + (texels, pending, rows): (Arc, &mut Option, &mut bool), descriptor: &TextureDescriptor, layout: &TextureLayout, ) -> Result { @@ -2783,7 +2803,7 @@ impl Device { } => String::new(), Route::Host { class, - rows, + rows: lines, padding, way: HostWay::InPlace { storable }, } => { @@ -2805,16 +2825,18 @@ impl Device { } Err((refusal, why)) => ShadowCause::Refused(refusal, why), }; - let shadowed = ((class, texels.buffer.copied()), (rows, padding), cause); + *rows = in_place::leaves_rows(&cause); + let shadowed = ((class, texels.buffer.copied()), (lines, padding), cause); self.host_shadowed(shadowed, (usage, &plan), descriptor, pending)? } Route::Host { class, - rows, + rows: lines, padding, way: HostWay::Shadow(cause), } => { - let shadowed = ((class, texels.buffer.copied()), (rows, padding), cause); + *rows = in_place::leaves_rows(&cause); + let shadowed = ((class, texels.buffer.copied()), (lines, padding), cause); self.host_shadowed(shadowed, (usage, &plan), descriptor, pending)? } Route::Device { holds } => { @@ -5590,14 +5612,19 @@ impl Texture { parent: Option, id_use: IdUse, ) -> Texture { - Texture::made_with_planes(device, (storage, None), record, parent, id_use) + Texture::made_with_planes(device, (storage, None, None), record, parent, id_use) } /// [`made`](Self::made), of a two-plane YCbCr texture whose planes a function may read in - /// place where `planes_in_place` holds them. + /// place where `planes_in_place` holds them, or of a shadowed 2D texture whose rows it may + /// read and write in place where `rows_in_place` holds them (`texture/texel_rows.rs`). fn made_with_planes( device: &Device, - (storage, planes_in_place): (Storage, Option), + (storage, planes_in_place, rows_in_place): ( + Storage, + Option, + Option, + ), record: ViewRecord, parent: Option, id_use: IdUse, @@ -5646,6 +5673,7 @@ impl Texture { render_shadow: Mutex::new(None), facts: OnceLock::new(), planes_in_place, + rows_in_place, }), retain: weak, record, @@ -6468,6 +6496,8 @@ impl Texture { Some(_) => p.words.with_planes_image(), None => p.words, }); + // A shadowed texture whose rows a function may read and write in place. + facts.texel_rows = self.s().rows_in_place.map(|r| r.rows); facts } diff --git a/crates/metal2vulkan-runtime/src/texture/texel_rows.rs b/crates/metal2vulkan-runtime/src/texture/texel_rows.rs new file mode 100644 index 000000000..2d0a89cbe --- /dev/null +++ b/crates/metal2vulkan-runtime/src/texture/texel_rows.rs @@ -0,0 +1,168 @@ +//! A 2D texture over a buffer's rows whose image is a shadow, its rows read and written in place +//! (`metal2vulkan::bind::texel_rows`). +//! +//! **Which.** A texture over a buffer is a shadow where the device makes no image over its bytes +//! (`shadow.rs`). Where the device refused that image for its format, features or limits, the +//! rows' pitch, or the bytes' place, or where the dma-buf import of the texture's pages refused +//! it (`in_place::Refusal::{Image, Pitch, Placement, Source, DmaBuf}`), the bytes are still the +//! buffer's own, in place: a texture of one level, slice and sample, of an uncompressed format +//! with no swizzle, whose rows start on a texel and lie a whole number of texels apart, and that +//! runs past no byte of its buffer, states its rows in its facts (`TextureFacts::texel_rows`). A +//! slot whose function only reads, writes or asks the size of it then binds a texel buffer over +//! the rows' bytes instead of the shadow (`WriteSource::TexelRows`), and its commands copy +//! nothing into or out of the shadow; every other slot binds the shadow as before. A shadow the +//! device's policy asks for (`HostPageTexturePolicy::Shadow`), and one made before or after its +//! class's check, keeps its shadow everywhere. So does one over a buffer with a read twin +//! (`read_twin.rs`): a slot that only reads it binds the texture's read twin, over the pages in +//! place, where it has one; a rows binding would read the buffer's copy instead. +//! +//! **The view.** It starts at the texture's first byte rounded down to the device's +//! `minTexelBufferOffsetAlignment` in the buffer's `VkBuffer`, the texels before the texture's +//! first the rows' `first`, and ends at the last row's last texel, at most +//! `maxTexelBufferElements` texels. A texture whose first byte lies a part of a texel past that +//! alignment, or whose view would hold more texels, keeps its shadow everywhere. +//! +//! **Ordering.** A binding's use is a use of the texture's bytes in its buffer +//! ([`Texture::rows_use`]): its shadow's entry meets it (`ShadowCopies::meets`), so a command +//! that binds the rows after one that wrote the shadow copies the shadow back first, and one that +//! writes both through the shadow and through the rows merges them, as for any other use of the +//! bytes. + +use super::{Storage, Texture}; +use crate::buffer_texture::Texels; +use crate::error::{internal, Error}; +use crate::resource::ResourceKey; +use crate::shadow::{ShadowSource, ShadowTarget}; +use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; +use crate::tracker::{Access, Use, UseRange}; +use crate::Device; +use ash::vk; +use metal2vulkan::bind::TexelRows; +use metal2vulkan::metal::format::byte_format; +use metal2vulkan::metal::{TextureSwizzleChannels, TextureType}; +use metal2vulkan::vk::Format; + +/// A shadowed texture's rows as a function reads and writes them in place (the module docs). +#[derive(Clone, Copy, Debug)] +pub(crate) struct RowsInPlace { + /// The words of a binding's push field. + pub(super) rows: TexelRows, + /// The bytes from the view's first to the texture's first. + before: u64, + /// The bytes of one texel. + texel_bytes: u64, +} + +impl RowsInPlace { + /// The bytes the view holds. + fn view_bytes(&self) -> u64 { + self.rows.elements() * self.texel_bytes + } +} + +impl Device { + /// The rows in place of a shadowed texture of `descriptor` (checked as `layout`) over + /// `texels`, whose image the device refused for a reason that leaves its bytes in place (the + /// module docs), or `None` where it keeps its shadow everywhere. + pub(super) fn rows_in_place( + &self, + texels: &Texels, + descriptor: &TextureDescriptor, + layout: &TextureLayout, + ) -> Option { + let format = byte_format(descriptor.pixel_format)?; + let block = format.block().filter(|b| b.texels == 1)?; + let texel_bytes = u64::from(block.size); + let at = &texels.layout; + let [width, height, depth] = layout.extent; + let plain = layout.texture_type == TextureType::Type2D + && layout.levels == 1 + && layout.layers == 1 + && depth == 1 + && layout.samples == 1 + && descriptor.swizzle == TextureSwizzleChannels::DEFAULT + && texels.texel_bytes() == texel_bytes + && texels.past().is_none() + && texels.staged().is_none() + && texels.buffer.read_twin().is_none() + && at.offset.is_multiple_of(texel_bytes) + && at.row_pitch.is_multiple_of(texel_bytes) + && at.row_pitch >= at.row_bytes; + if !plain { + return None; + } + let limits = self.compile_device().profile().limits(); + let alignment = limits.min_texel_buffer_offset_alignment.max(1); + let (_, first_byte) = texels.buffer.at(at.offset); + let before = first_byte % alignment; + if !before.is_multiple_of(texel_bytes) { + return None; + } + let rows = TexelRows::new( + [width, height], + at.row_pitch / texel_bytes, + before / texel_bytes, + )?; + if rows.elements() > u64::from(limits.max_texel_buffer_elements) { + return None; + } + self.shared().counts.texel_rows_texture(); + Some(RowsInPlace { + rows, + before, + texel_bytes, + }) + } +} + +impl Texture { + /// The texels in its buffer and the rows a function reads and writes in place, of a texture + /// whose rows are (the module docs). + fn rows_texels(&self) -> Result<(&Texels, &RowsInPlace), Error> { + let rows = self.s().rows_in_place.as_ref(); + let texels = match self.storage() { + Storage::Shadow { texels, copies, .. } => match &copies.source { + ShadowSource::Bytes { + target: ShadowTarget::Image { .. }, + .. + } => Some(&**texels), + _ => None, + }, + _ => None, + }; + match (texels, rows) { + (Some(texels), Some(rows)) => Ok((texels, rows)), + _ => Err(internal( + "a rows binding of a texture whose rows are not in place", + )), + } + } + + /// The texel buffer view in `format` (the plan's, `WriteSource::TexelRows`) of the texture's + /// rows read and written in place, a storage texel buffer's (`storage`) or a uniform one's, + /// which a slot under its rows variant binds. Internal for a texture whose rows are not. + pub(crate) fn rows_view(&self, format: Format, storage: bool) -> Result { + let (texels, rows) = self.rows_texels()?; + let (_, first_byte) = texels.buffer.at(texels.layout.offset); + let start = first_byte - rows.before; + texels.view_of(format, storage, (start, rows.view_bytes())) + } + + /// A use of the texture's bytes in its buffer, reading by `read` and writing by `write`, which + /// a binding of its rows makes (the module docs). Internal for a texture whose rows are not + /// in place. + pub(crate) fn rows_use(&self, read: Access, write: Access) -> Result, Error> { + let (texels, rows) = self.rows_texels()?; + let start = texels.layout.offset; + let first = u64::from(rows.rows.words()[TexelRows::FIRST]); + let end = start + (rows.rows.elements() - first) * rows.texel_bytes; + let (identity, range) = texels.buffer.tracked(start..end); + Ok(Use { + key: identity.key, + tracked: texels.tracked(), + range: UseRange::Bytes(range), + read, + write, + }) + } +} diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index 7aeec5275..4828ada8b 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -167,7 +167,7 @@ impl Texture { .check(self.generation().properties().texture_rules()) .map_err(|_| refused(None))?; // A view's storage never moves in place (`texture/storage_form.rs`). - let over = (Arc::clone(texels), &mut None); + let over = (Arc::clone(texels), &mut None, &mut false); self.generation() .storage_over_buffer(call, over, &descriptor, &layout) } diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index 9b3025314..a851bece4 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -269,7 +269,7 @@ impl Device { } let storage = self.converted_storage(call, texels, &descriptor, layout, (planes, span))?; - let made = (storage, in_place.ok()); + let made = (storage, in_place.ok(), None); return Ok(Texture::made_with_planes(self, made, record, None, id_use)); } // Over a surface of a P3 matrix: an image of the codes of the code-reading format, its diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 9de9c7887..663b6d97b 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -195,6 +195,7 @@ pub(crate) struct Counters { ycbcr_refreshes: AtomicU64, ycbcr_whole_conversions: AtomicU64, ycbcr_textures_in_place: AtomicU64, + texel_rows_textures: AtomicU64, ycbcr_images_kept: [AtomicU64; 7], ycbcr_planes_images: AtomicU64, fd_blocks_awaited: AtomicU64, @@ -835,6 +836,7 @@ struct CommandCounters { tile_dispatches_recorded: AtomicU64, ycbcr_planes_bound: AtomicU64, ycbcr_planes_images_bound: AtomicU64, + texel_rows_bound: AtomicU64, residual_form_draws: AtomicU64, residual_form_makings: AtomicU64, draws_unkept: AtomicU64, @@ -1380,6 +1382,12 @@ impl Counting<'_> { self.0.add(|counts| &counts.ycbcr_planes_bound, 1); } + /// A binding of a shadowed texture's rows read and written in place was written + /// (`binding.rs`, `texture/texel_rows.rs`). + pub(crate) fn texel_rows_bound(&self) { + self.0.add(|counts| &counts.texel_rows_bound, 1); + } + /// A binding of a two-plane YCbCr texture's planes image was written (`binding.rs`). pub(crate) fn ycbcr_planes_image_bound(&self) { self.0.add(|counts| &counts.ycbcr_planes_images_bound, 1); @@ -2304,6 +2312,12 @@ impl Counters { self.ycbcr_textures_in_place.fetch_add(1, Ordering::Relaxed); } + /// A shadowed texture was made with its rows read and written in place + /// (`texture/texel_rows.rs`). + pub(crate) fn texel_rows_texture(&self) { + self.texel_rows_textures.fetch_add(1, Ordering::Relaxed); + } + /// A two-plane YCbCr texture was made keeping its image alone for `kept` /// (`texture/ycbcr_image.rs`). pub(crate) fn ycbcr_image_kept(&self, kept: crate::texture::KeptImage) { @@ -6871,6 +6885,14 @@ pub struct WorkCounts { pub ycbcr_images_kept_view: u64, /// Bindings of two-plane YCbCr textures' planes read in place written into descriptor sets. pub ycbcr_planes_bound: u64, + /// Shadowed 2D textures over a buffer's rows made with their rows read and written in place + /// (`texture/texel_rows.rs`): the device made no image over the rows (its format, features or + /// limits, the rows' pitch or place, or the dma-buf import refused one), and a slot whose + /// function only reads, writes or asks the size of such a texture binds a texel buffer over + /// the rows' bytes, which its commands read and write with no copy into or out of the shadow. + pub texel_rows_textures: u64, + /// Bindings of such textures' rows written into descriptor sets. + pub texel_rows_bound: u64, /// Two-plane YCbCr textures whose planes read in place are also an image the device's own /// sampler Y′CbCr conversion samples, a linear image of the multi-planar 4:2:0 format over /// their bytes (`texture/ycbcr_planes.rs`): a slot whose every sample the device's sampler @@ -11087,6 +11109,8 @@ impl Device { ycbcr_images_kept_reach: counters.ycbcr_images_kept[5].load(Ordering::Relaxed), ycbcr_images_kept_view: counters.ycbcr_images_kept[6].load(Ordering::Relaxed), ycbcr_planes_bound: commands(|counts| &counts.ycbcr_planes_bound), + texel_rows_textures: counters.texel_rows_textures.load(Ordering::Relaxed), + texel_rows_bound: commands(|counts| &counts.texel_rows_bound), ycbcr_planes_images: counters.ycbcr_planes_images.load(Ordering::Relaxed), fd_blocks_awaited: counters.fd_blocks_awaited.load(Ordering::Relaxed), fd_blocks_refused: counters.fd_blocks_refused.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN index e2a382fb9..c57dfa8b6 100644 --- a/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN @@ -4,3 +4,5 @@ macosx-sdk: 27.0 (26A425) llvm: 21 (pinned: llvm-dis writes each .ll, and llvm-as must accept it) llvm-dis: Homebrew LLVM version 21.1.8 llvm-as: Homebrew LLVM version 21.1.8 +# Fixtures compiled by another Metal toolchain (regen-air-fixtures.sh ...). +fixture texel_rows: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.air.ll b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.air.ll new file mode 100644 index 000000000..78015f609 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.air.ll @@ -0,0 +1,198 @@ +; Generated by scripts/regen-air-fixtures from texel_rows.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +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._texture_2d_t = type opaque +%struct._sampler_t = type opaque + +@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 34901797601050697, i64 0], align 8 + +; Function Attrs: mustprogress nounwind willreturn +define void @rows_invert(%struct._texture_2d_t addrspace(1)* %0, <2 x i32> noundef %1) local_unnamed_addr #0 { + %3 = extractelement <2 x i32> %1, i64 0 + %4 = tail call i32 @air.get_width_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, i32 0) #8, !alias.scope !35 + %5 = icmp ult i32 %3, %4 + br i1 %5, label %6, label %18 + +6: ; preds = %2 + %7 = extractelement <2 x i32> %1, i64 1 + %8 = tail call i32 @air.get_height_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, i32 0) #8, !alias.scope !35 + %9 = icmp ult i32 %7, %8 + br i1 %9, label %10, label %18 + +10: ; preds = %6 + %11 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #9 + %12 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %11, <2 x i32> %1, <2 x i32> zeroinitializer, i32 0, i32 3) #8 + %13 = extractvalue { <4 x float>, i8 } %12, 0 + %14 = shufflevector <4 x float> %13, <4 x float> poison, <3 x i32> + %15 = fsub fast <3 x float> , %14 + %16 = shufflevector <3 x float> %15, <3 x float> poison, <4 x i32> + %17 = shufflevector <4 x float> %16, <4 x float> %13, <4 x i32> + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %0, <2 x i32> %1, <4 x float> %17, i32 0, i32 3) #10, !alias.scope !35 + br label %18 + +18: ; preds = %2, %6, %10 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @rows_read(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, i32 addrspace(2)* nocapture noundef readonly align 4 dereferenceable(4) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #1 { + %5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #9 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %5, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 1) #8 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = extractelement <2 x i32> %3, i64 1 + %9 = load i32, i32 addrspace(2)* %2, align 4, !tbaa !38, !alias.scope !42, !noalias !45 + %10 = mul i32 %9, %8 + %11 = extractelement <2 x i32> %3, i64 0 + %12 = add i32 %10, %11 + %13 = zext i32 %12 to i64 + %14 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %13 + store <4 x float> %7, <4 x float> addrspace(1)* %14, align 16, !tbaa !48, !alias.scope !49, !noalias !50 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @rows_write(<4 x float> addrspace(1)* nocapture noundef readonly "air-buffer-no-alias" %0, i32 addrspace(2)* nocapture noundef readonly align 4 dereferenceable(4) "air-buffer-no-alias" %1, %struct._texture_2d_t addrspace(1)* %2, <2 x i32> noundef %3) local_unnamed_addr #0 { + %5 = extractelement <2 x i32> %3, i64 1 + %6 = load i32, i32 addrspace(2)* %1, align 4, !tbaa !38, !alias.scope !51, !noalias !54 + %7 = mul i32 %6, %5 + %8 = extractelement <2 x i32> %3, i64 0 + %9 = add i32 %7, %8 + %10 = zext i32 %9 to i64 + %11 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %0, i64 %10 + %12 = load <4 x float>, <4 x float> addrspace(1)* %11, align 16, !tbaa !48, !alias.scope !57, !noalias !58 + tail call void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture %2, <2 x i32> %3, <4 x float> %12, i32 0, i32 2) #10, !alias.scope !59, !noalias !60 + ret void +} + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind willreturn +define void @rows_sample(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, i32 addrspace(2)* nocapture noundef readonly align 4 dereferenceable(4) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #2 { + %5 = tail call fast <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32> %3) #11 + %6 = fadd fast <2 x float> %5, + %7 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* nocapture readonly bitcast ([2 x i64] addrspace(2)* @__air_sampler_state to %struct._sampler_t addrspace(2)*), <2 x float> %6, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) #12 + %8 = extractvalue { <4 x float>, i8 } %7, 0 + %9 = extractelement <2 x i32> %3, i64 1 + %10 = load i32, i32 addrspace(2)* %2, align 4, !tbaa !38, !alias.scope !61, !noalias !64 + %11 = mul i32 %10, %9 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %14 + store <4 x float> %8, <4 x float> addrspace(1)* %15, align 16, !tbaa !48, !alias.scope !67, !noalias !68 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32>) local_unnamed_addr #3 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare i32 @air.get_width_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly, i32) local_unnamed_addr #4 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare i32 @air.get_height_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly, i32) local_unnamed_addr #4 + +; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn +declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #4 + +; Function Attrs: argmemonly mustprogress nounwind willreturn +declare void @air.write_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture, <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: argmemonly convergent mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)* nocapture readonly, <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { argmemonly convergent mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree nosync nounwind readnone willreturn } +attributes #4 = { argmemonly mustprogress nofree nounwind readonly willreturn } +attributes #5 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn } +attributes #6 = { argmemonly mustprogress nounwind willreturn } +attributes #7 = { argmemonly convergent mustprogress nofree nounwind readonly willreturn } +attributes #8 = { argmemonly nounwind readonly willreturn } +attributes #9 = { inaccessiblememonly nounwind readonly willreturn } +attributes #10 = { argmemonly nounwind willreturn } +attributes #11 = { nounwind readnone willreturn } +attributes #12 = { argmemonly convergent nounwind readonly willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !14, !20, !25} +!air.compile_options = !{!28, !29, !30} +!air.sampler_states = !{!31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{void (%struct._texture_2d_t addrspace(1)*, <2 x i32>)* @rows_invert, !10, !11} +!10 = !{} +!11 = !{!12, !13} +!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"texels"} +!13 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"position"} +!14 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(1)*, i32 addrspace(2)*, <2 x i32>)* @rows_read, !10, !15} +!15 = !{!16, !17, !18, !19} +!16 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!17 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"output"} +!18 = !{i32 2, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"columns"} +!19 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"position"} +!20 = !{void (<4 x float> addrspace(1)*, i32 addrspace(2)*, %struct._texture_2d_t addrspace(1)*, <2 x i32>)* @rows_write, !10, !21} +!21 = !{!22, !23, !24, !19} +!22 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"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", !"input"} +!23 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"columns"} +!24 = !{i32 2, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"destination"} +!25 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(1)*, i32 addrspace(2)*, <2 x i32>)* @rows_sample, !10, !26} +!26 = !{!27, !17, !18, !19} +!27 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!28 = !{!"air.compile.denorms_disable"} +!29 = !{!"air.compile.fast_math_enable"} +!30 = !{!"air.compile.framebuffer_fetch_enable"} +!31 = !{!"air.sampler_state", [2 x i64] addrspace(2)* @__air_sampler_state} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36} +!36 = distinct !{!36, !37, !"air-alias-scope-textures"} +!37 = distinct !{!37, !"air-alias-scopes(rows_invert)"} +!38 = !{!39, !39, i64 0} +!39 = !{!"int", !40, i64 0} +!40 = !{!"omnipotent char", !41, i64 0} +!41 = !{!"Simple C++ TBAA"} +!42 = !{!43} +!43 = distinct !{!43, !44, !"air-alias-scope-arg(2)"} +!44 = distinct !{!44, !"air-alias-scopes(rows_read)"} +!45 = !{!46, !47} +!46 = distinct !{!46, !44, !"air-alias-scope-textures"} +!47 = distinct !{!47, !44, !"air-alias-scope-arg(1)"} +!48 = !{!40, !40, i64 0} +!49 = !{!47} +!50 = !{!46, !43} +!51 = !{!52} +!52 = distinct !{!52, !53, !"air-alias-scope-arg(1)"} +!53 = distinct !{!53, !"air-alias-scopes(rows_write)"} +!54 = !{!55, !56} +!55 = distinct !{!55, !53, !"air-alias-scope-arg(0)"} +!56 = distinct !{!56, !53, !"air-alias-scope-textures"} +!57 = !{!55} +!58 = !{!52, !56} +!59 = !{!56} +!60 = !{!55, !52} +!61 = !{!62} +!62 = distinct !{!62, !63, !"air-alias-scope-arg(2)"} +!63 = distinct !{!63, !"air-alias-scopes(rows_sample)"} +!64 = !{!65, !66} +!65 = distinct !{!65, !63, !"air-alias-scope-textures"} +!66 = distinct !{!66, !63, !"air-alias-scope-arg(1)"} +!67 = !{!66} +!68 = !{!65, !62} diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.ll b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.ll new file mode 100644 index 000000000..03fc0f99c --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.ll @@ -0,0 +1,195 @@ +; Generated by scripts/regen-air-fixtures from texel_rows.metal (llvm-dis of texel_rows.air). Do not edit. +; ModuleID = '' +source_filename = "-" +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" + +@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 34901797601050697, i64 0], align 8 + +; Function Attrs: mustprogress nounwind willreturn +define void @rows_invert(ptr addrspace(1) %0, <2 x i32> noundef %1) local_unnamed_addr #0 { + %3 = extractelement <2 x i32> %1, i64 0 + %4 = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) readonly captures(none) %0, i32 0) #8, !alias.scope !35 + %5 = icmp ult i32 %3, %4 + br i1 %5, label %6, label %18 + +6: ; preds = %2 + %7 = extractelement <2 x i32> %1, i64 1 + %8 = tail call i32 @air.get_height_texture_2d(ptr addrspace(1) readonly captures(none) %0, i32 0) #8, !alias.scope !35 + %9 = icmp ult i32 %7, %8 + br i1 %9, label %10, label %18 + +10: ; preds = %6 + %11 = tail call ptr addrspace(2) @air.get_read_sampler() #9 + %12 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %11, <2 x i32> %1, <2 x i32> zeroinitializer, i32 0, i32 3) #8 + %13 = extractvalue { <4 x float>, i8 } %12, 0 + %14 = shufflevector <4 x float> %13, <4 x float> poison, <3 x i32> + %15 = fsub fast <3 x float> splat (float 1.000000e+00), %14 + %16 = shufflevector <3 x float> %15, <3 x float> poison, <4 x i32> + %17 = shufflevector <4 x float> %16, <4 x float> %13, <4 x i32> + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %0, <2 x i32> %1, <4 x float> %17, i32 0, i32 3) #10, !alias.scope !35 + br label %18 + +18: ; preds = %10, %6, %2 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @rows_read(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, ptr addrspace(2) noundef readonly align 4 captures(none) dereferenceable(4) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #1 { + %5 = tail call ptr addrspace(2) @air.get_read_sampler() #9 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %5, <2 x i32> %3, <2 x i32> zeroinitializer, i32 0, i32 1) #8 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + %8 = extractelement <2 x i32> %3, i64 1 + %9 = load i32, ptr addrspace(2) %2, align 4, !tbaa !38, !alias.scope !42, !noalias !45 + %10 = mul i32 %9, %8 + %11 = extractelement <2 x i32> %3, i64 0 + %12 = add i32 %10, %11 + %13 = zext i32 %12 to i64 + %14 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %13 + store <4 x float> %7, ptr addrspace(1) %14, align 16, !tbaa !48, !alias.scope !49, !noalias !50 + ret void +} + +; Function Attrs: mustprogress nounwind willreturn +define void @rows_write(ptr addrspace(1) noundef readonly captures(none) "air-buffer-no-alias" %0, ptr addrspace(2) noundef readonly align 4 captures(none) dereferenceable(4) "air-buffer-no-alias" %1, ptr addrspace(1) %2, <2 x i32> noundef %3) local_unnamed_addr #0 { + %5 = extractelement <2 x i32> %3, i64 1 + %6 = load i32, ptr addrspace(2) %1, align 4, !tbaa !38, !alias.scope !51, !noalias !54 + %7 = mul i32 %6, %5 + %8 = extractelement <2 x i32> %3, i64 0 + %9 = add i32 %7, %8 + %10 = zext i32 %9 to i64 + %11 = getelementptr inbounds <4 x float>, ptr addrspace(1) %0, i64 %10 + %12 = load <4 x float>, ptr addrspace(1) %11, align 16, !tbaa !48, !alias.scope !57, !noalias !58 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none) %2, <2 x i32> %3, <4 x float> %12, i32 0, i32 2) #10, !alias.scope !59, !noalias !60 + ret void +} + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) +define void @rows_sample(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, ptr addrspace(2) noundef readonly align 4 captures(none) dereferenceable(4) "air-buffer-no-alias" %2, <2 x i32> noundef %3) local_unnamed_addr #2 { + %5 = tail call fast <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32> %3) #11 + %6 = fadd fast <2 x float> %5, splat (float 5.000000e-01) + %7 = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) readonly captures(none) @__air_sampler_state, <2 x float> %6, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) #12 + %8 = extractvalue { <4 x float>, i8 } %7, 0 + %9 = extractelement <2 x i32> %3, i64 1 + %10 = load i32, ptr addrspace(2) %2, align 4, !tbaa !38, !alias.scope !61, !noalias !64 + %11 = mul i32 %10, %9 + %12 = extractelement <2 x i32> %3, i64 0 + %13 = add i32 %11, %12 + %14 = zext i32 %13 to i64 + %15 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %14 + store <4 x float> %8, ptr addrspace(1) %15, align 16, !tbaa !48, !alias.scope !67, !noalias !68 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <2 x float> @air.convert.f.v2f32.u.v2i32(<2 x i32>) local_unnamed_addr #3 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare i32 @air.get_width_texture_2d(ptr addrspace(1) readonly captures(none), i32) local_unnamed_addr #4 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare i32 @air.get_height_texture_2d(ptr addrspace(1) readonly captures(none), i32) local_unnamed_addr #4 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) +declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #4 + +; Function Attrs: mustprogress nounwind willreturn memory(argmem: readwrite) +declare void @air.write_texture_2d.v4f32(ptr addrspace(1) captures(none), <2 x i32>, <4 x float>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: convergent mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2) readonly captures(none), <2 x float>, i1, <2 x i32>, i1, float, float, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #2 = { convergent mustprogress nofree nounwind willreturn memory(argmem: readwrite) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree nosync nounwind willreturn memory(none) } +attributes #4 = { mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #5 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) } +attributes #6 = { mustprogress nounwind willreturn memory(argmem: readwrite) } +attributes #7 = { convergent mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #8 = { nounwind willreturn memory(argmem: read) } +attributes #9 = { nounwind willreturn memory(inaccessiblemem: read) } +attributes #10 = { nounwind willreturn memory(argmem: readwrite) } +attributes #11 = { nounwind willreturn memory(none) } +attributes #12 = { convergent nounwind willreturn memory(argmem: read) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.kernel = !{!9, !14, !20, !25} +!air.compile_options = !{!28, !29, !30} +!air.sampler_states = !{!31} +!llvm.ident = !{!32} +!air.version = !{!33} +!air.language_version = !{!34} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @rows_invert, !10, !11} +!10 = !{} +!11 = !{!12, !13} +!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"texels"} +!13 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"position"} +!14 = !{ptr @rows_read, !10, !15} +!15 = !{!16, !17, !18, !19} +!16 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!17 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"output"} +!18 = !{i32 2, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"columns"} +!19 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"position"} +!20 = !{ptr @rows_write, !10, !21} +!21 = !{!22, !23, !24, !19} +!22 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"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", !"input"} +!23 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"columns"} +!24 = !{i32 2, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"destination"} +!25 = !{ptr @rows_sample, !10, !26} +!26 = !{!27, !17, !18, !19} +!27 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!28 = !{!"air.compile.denorms_disable"} +!29 = !{!"air.compile.fast_math_enable"} +!30 = !{!"air.compile.framebuffer_fetch_enable"} +!31 = !{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state} +!32 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!33 = !{i32 2, i32 8, i32 0} +!34 = !{!"Metal", i32 4, i32 0, i32 0} +!35 = !{!36} +!36 = distinct !{!36, !37, !"air-alias-scope-textures"} +!37 = distinct !{!37, !"air-alias-scopes(rows_invert)"} +!38 = !{!39, !39, i64 0} +!39 = !{!"int", !40, i64 0} +!40 = !{!"omnipotent char", !41, i64 0} +!41 = !{!"Simple C++ TBAA"} +!42 = !{!43} +!43 = distinct !{!43, !44, !"air-alias-scope-arg(2)"} +!44 = distinct !{!44, !"air-alias-scopes(rows_read)"} +!45 = !{!46, !47} +!46 = distinct !{!46, !44, !"air-alias-scope-textures"} +!47 = distinct !{!47, !44, !"air-alias-scope-arg(1)"} +!48 = !{!40, !40, i64 0} +!49 = !{!47} +!50 = !{!46, !43} +!51 = !{!52} +!52 = distinct !{!52, !53, !"air-alias-scope-arg(1)"} +!53 = distinct !{!53, !"air-alias-scopes(rows_write)"} +!54 = !{!55, !56} +!55 = distinct !{!55, !53, !"air-alias-scope-arg(0)"} +!56 = distinct !{!56, !53, !"air-alias-scope-textures"} +!57 = !{!55} +!58 = !{!52, !56} +!59 = !{!56} +!60 = !{!55, !52} +!61 = !{!62} +!62 = distinct !{!62, !63, !"air-alias-scope-arg(2)"} +!63 = distinct !{!63, !"air-alias-scopes(rows_sample)"} +!64 = !{!65, !66} +!65 = distinct !{!65, !63, !"air-alias-scope-textures"} +!66 = distinct !{!66, !63, !"air-alias-scope-arg(1)"} +!67 = !{!66} +!68 = !{!65, !62} diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.metal b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.metal new file mode 100644 index 000000000..04e2a3aa4 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/texel_rows.metal @@ -0,0 +1,45 @@ +// Owned fixture: the kernels the metal2vulkan-runtime crate's texel rows device tests run +// (src/tests/texel_rows_device.rs). Written from scratch for them; `scripts/regen-air-fixtures/ +// regen-air-fixtures.sh --dir examples texel_rows` compiles it. No translator sweep reads this +// directory. +#include +using namespace metal; + +// Each texel of `texels` with its color channels inverted, in place; a thread past the +// texture's size stores nothing. +kernel void rows_invert(texture2d texels [[texture(0)]], + uint2 position [[thread_position_in_grid]]) { + if (position.x >= texels.get_width() || position.y >= texels.get_height()) { + return; + } + float4 texel = texels.read(position); + texels.write(float4(1.0 - texel.rgb, texel.a), position); +} + +// Each texel of `source` (Metal's out-of-bounds texel past it) into `output`, `columns` elements +// a grid row. +kernel void rows_read(texture2d source [[texture(0)]], + device float4 *output [[buffer(0)]], + constant uint &columns [[buffer(1)]], + uint2 position [[thread_position_in_grid]]) { + output[position.y * columns + position.x] = source.read(position); +} + +// Each element of `input`, `columns` elements a grid row, into texel `position` of +// `destination` (dropped past it). +kernel void rows_write(device const float4 *input [[buffer(0)]], + constant uint &columns [[buffer(1)]], + texture2d destination [[texture(0)]], + uint2 position [[thread_position_in_grid]]) { + destination.write(input[position.y * columns + position.x], position); +} + +// The texel of `source` at each texel's center, sampled through a nearest filter, into +// `output`, `columns` elements a grid row. +kernel void rows_sample(texture2d source [[texture(0)]], + device float4 *output [[buffer(0)]], + constant uint &columns [[buffer(1)]], + uint2 position [[thread_position_in_grid]]) { + constexpr sampler nearest(filter::nearest, coord::pixel); + output[position.y * columns + position.x] = source.sample(nearest, float2(position) + 0.5); +} diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index 532b704eb..52553b47d 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -856,8 +856,9 @@ impl BindingPlan { /// - **Buffer slots**: `true`. Their offsets, lengths and addresses place the descriptor /// ranges, the push bytes and the root table. /// - **Texture slots**: `true` where the plan binds a texture buffer's range as a texel-buffer - /// view, a push field carries a texture's in-place planes (`PushField::YCbCrInPlace`), or a - /// handle table names the texture bound at a slot by its resource ID; `false` otherwise, as + /// view, a push field carries a texture's in-place planes (`PushField::YCbCrInPlace`) or + /// rows (`PushField::TexelRows`), or a handle table names the texture bound at a slot by its + /// resource ID; `false` otherwise, as /// the commands read a texture slot nowhere else (the consumer binds its view itself). /// - **Sampler slots**: `false`. The commands read no sampler slot. /// @@ -872,7 +873,12 @@ impl BindingPlan { SlotClass::Texture => { let resources = &t.resources; !resources.texel_buffers.is_empty() - || (t.fields.iter()).any(|f| matches!(f.field, PushField::YCbCrInPlace(_))) + || (t.fields.iter()).any(|f| { + matches!( + f.field, + PushField::YCbCrInPlace(_) | PushField::TexelRows(_) + ) + }) || (resources.heap_members.iter()) .any(|m| matches!(m.source, HeapSource::Bound(_))) } diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index d6f4071dd..b23908640 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -1794,8 +1794,9 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result {} // A structure's instance count, which instantiation reads from the state. PushField::InstanceCount(_) => {} - // An in-place YCbCr texture's words, which instantiation reads from the state. - PushField::YCbCrInPlace(_) => {} + // An in-place YCbCr texture's words, and a texture's rows in its texel buffer + // view, which instantiation reads from the state. + PushField::YCbCrInPlace(_) | PushField::TexelRows(_) => {} // The encoder's stencil state, which instantiation reads from the state. PushField::ShadowStencilState if stage == Stage::Fragment => {} // The encoder's depth state, which instantiation reads from the state, and its @@ -2631,6 +2632,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result( } (slot, LooseWord::Stride(layout)) } - // A changed texture's in-place planes. - PushField::YCbCrInPlace(slot) if slots.contains(&slot) => return Some(None), + // A changed texture's in-place planes or rows. + PushField::YCbCrInPlace(slot) | PushField::TexelRows(slot) + if slots.contains(&slot) => + { + return Some(None) + } _ => return None, }; let field = push.map(|push| FieldAt { diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index fdf2f2f3a..fad84f703 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -35,6 +35,7 @@ fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) -> offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: ty, pixel_format: pf, sample_count: samples, diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index 47a12f3fd..7c838ef94 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -863,6 +863,25 @@ pub(crate) fn slot_field( } Some(FieldBytes::of(&bytes)) } + // The rows of the texture bound at the slot in its texel buffer view, zeros where none + // is (the plan names the slot's variant only where one is). + PushField::TexelRows(slot) => { + let words = match state + .stages + .get(&slot.stage) + .and_then(|t| t.textures.get(&slot.index)) + { + Some(BoundTexture::Texture { facts, .. }) => facts + .texel_rows + .map_or([0; crate::bind::TexelRows::WORDS], |r| r.words()), + _ => [0; crate::bind::TexelRows::WORDS], + }; + let mut bytes = [0u8; 4 * crate::bind::TexelRows::WORDS]; + for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + chunk.copy_from_slice(&word.to_le_bytes()); + } + Some(FieldBytes::of(&bytes)) + } // The level count the plan bound. PushField::TextureLevels(slot) => resources .texture_levels diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index a9b78447e..358b162cd 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -182,6 +182,7 @@ pub(crate) mod state; pub(crate) mod status; pub(crate) mod table; pub(crate) mod tessellation_scan; +pub(crate) mod texel_rows; pub(crate) mod tile_map; pub(crate) mod tiled_texels; pub(crate) mod two_plane_texels; @@ -340,6 +341,7 @@ pub use table::{FunctionTableSnapshot, FunctionTableWords}; pub use tessellation_scan::{ tessellation_scan_module, TessellationScanKernel, TessellationScanModule, }; +pub use texel_rows::TexelRows; pub use tile_map::{SparseTileMap, TileMapError, TileMapping}; pub use tiled_texels::{tiled_texels_module, TiledLevelMove, TiledTexelsModule}; pub use two_plane_texels::{two_plane_texels_module, PlaneLayout, TwoPlaneTexelsModule}; diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index c67ae8e1c..e765fef17 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -646,6 +646,15 @@ pub enum WriteSource { /// `GENERAL`. Only a slot under its planes-image variant binds it /// (`VariantKey::ycbcr_planes_sampled`, `BindingSource::YCbCrPlanes`). YCbCrPlanesImage { slot: SlotRef }, + /// The rows of the 2D texture bound at `slot`, read and written in place + /// (`TextureFacts::texel_rows`, `bind::texel_rows`): a texel buffer in `format` over the + /// texture's bytes, from its first texel, or before it where the device's texel buffer offset + /// alignment asks, through its last row's last texel ([`TexelRows::elements`]); uniform where + /// the slot's function only reads the texture, storage where it writes it. Only a slot under + /// its rows variant binds it (`VariantKey::texel_rows`). + /// + /// [`TexelRows::elements`]: crate::bind::TexelRows::elements + TexelRows { slot: SlotRef, format: vk::Format }, /// The texture buffer bound at `slot`, as a texel buffer view. TexelBuffer { slot: SlotRef, @@ -1112,6 +1121,9 @@ pub enum AccessClass { /// (`WriteSource::YCbCrInPlace`) or the image of them the device's conversion samples /// (`WriteSource::YCbCrPlanesImage`): a read of the planes' bytes, not of the texture's image. YCbCrPlanes, + /// A 2D texture's rows, read or written in place through the slot's texel buffer + /// (`WriteSource::TexelRows`): a use of the rows' bytes, not of the texture's image. + TexelRows, } /// A byte range relative to the bound offset. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 1b5033188..35998796c 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -448,8 +448,9 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result {} // A structure's instance count, which instantiation reads from the state. PushField::InstanceCount(_) => {} - // An in-place YCbCr texture's words, which instantiation reads from the state. - PushField::YCbCrInPlace(_) => {} + // An in-place YCbCr texture's words, and a texture's rows in its texel buffer view, + // which instantiation reads from the state. + PushField::YCbCrInPlace(_) | PushField::TexelRows(_) => {} // A stage-in buffer's bound stride, which instantiation reads from the state. PushField::StageInStride(_) => {} other => return Err(internal(format!("a compute push field {other:?}"))), diff --git a/crates/metal2vulkan/src/bind/plan/resources.rs b/crates/metal2vulkan/src/bind/plan/resources.rs index 168871a5a..36b8efaac 100644 --- a/crates/metal2vulkan/src/bind/plan/resources.rs +++ b/crates/metal2vulkan/src/bind/plan/resources.rs @@ -685,6 +685,97 @@ impl ResourcePlanner<'_> { } } + /// The texel buffer format of the rows (`bind::texel_rows`) of the texture the shape binds at + /// `slot`, a storage slot where `storage`, where its function reads, writes and asks the size + /// of them through it (`RuntimeFact::TexelRows`): a single-sample 2D texture whose rows the + /// runtime states (`TextureShape::Texture::texel_rows`), of a color format of the slot's + /// numeric type that is no sRGB format, its texels unswizzled and unconverted (its image the + /// direct format, which holds Metal's bytes), whose direct format the device views as the + /// slot's texel buffer: a uniform one, or a storage one read and written as the function + /// does without a declared format. The device converts such a view's texels "in the same way + /// as they are for an image" (Uniform Texel Buffer, Storage Texel Buffer), so the function + /// reads and writes the texels the image route does. `None` for any other slot. + fn rows_format(&self, slot: SlotRef, storage: bool) -> Option { + if !self.has_fact(RuntimeFact::TexelRows { slot }) { + return None; + } + let Some(&TextureShape::Texture { + texture_type: TextureType::Type2D, + pixel_format: pf, + sample_count: 1, + swizzle, + texel_rows: true, + .. + }) = self.texture_shape(slot) + else { + return None; + }; + let t = self.texture_slot(slot).ok()?; + let plain = swizzle.is_default() + && !t.access.sample + && t.sampled_type != SampledType::Uint64 + && texel_type_binds(pf, t.sampled_type) + && !is_depth_stencil(pf) + && srgb_raw_twin(pf).is_none() + && ExtendedRange::of(pf).is_none(); + let format = crate::metal::format::byte_format(pf).filter(|_| plain)?; + if format.block().is_none_or(|b| b.texels != 1) { + return None; + } + let usage = match storage { + true => FormatUsage::StorageTexelBuffer, + false => FormatUsage::UniformTexelBuffer, + }; + let mapping = vk_format(pf, &[usage].into(), self.profile).ok()?; + let direct = mapping.format == format + && mapping.emulation == crate::metal::format::FormatEmulation::Direct; + let accessed = match storage { + true => accessed_without_format( + format, + StorageUse::texel_buffer(t.access.read, t.access.write), + self.profile, + ), + false => true, + }; + (direct && accessed).then_some(format) + } + + /// The write of `slot`'s binding under its rows variant (`VariantKey::texel_rows`), declared + /// `ty`, a texel buffer: the texel buffer of the rows of the texture the shape binds there + /// ([`rows_format`](Self::rows_format)), a use of their bytes; the neutral of the declared + /// texel buffer where the shape binds no such rows, which the plan's key then leaves. + fn rows_write( + &mut self, + ty: vk::DescriptorType, + slot: SlotRef, + ) -> Result<(WriteSource, NeutralResource), BindError> { + let t = *self.texture_slot(slot)?; + let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER; + let buffer = TextureSlot { + texture_type: TextureType::TextureBuffer, + ..t + }; + let n = neutral(&declared( + &buffer, + ty, + false, + false, + StorageFormatClass::Unknown, + )?)?; + let Some(format) = self.rows_format(slot, storage) else { + return Ok((WriteSource::Neutral(n), n)); + }; + self.variant.texel_rows.insert(slot); + self.uses.push(ResourceUse { + resource: UseTarget::Slot(slot), + access: texture_access(t.access), + class: AccessClass::TexelRows, + stages: (self.stage_flags)(slot.stage), + range: None, + }); + Ok((WriteSource::TexelRows { slot, format }, n)) + } + /// The write of `slot`'s binding under its planes-image variant (`BindingSource::YCbCrPlanes`, /// `VariantKey::ycbcr_planes_sampled`): the image of the planes of the two-plane YCbCr texture /// the shape binds there, viewed with the device's conversion of `TextureShape::Texture:: @@ -828,16 +919,40 @@ impl ResourcePlanner<'_> { ty: vk::DescriptorType, slot: SlotRef, ) -> Result<(WriteSource, NeutralResource), BindError> { - // A texture slot that is no texture buffer is declared a uniform texel buffer only under - // its in-place variant (`VariantKey::ycbcr_in_place`). - if ty == vk::DescriptorType::UNIFORM_TEXEL_BUFFER - && self.texture_slot(slot)?.texture_type != TextureType::TextureBuffer - { - return Ok(self.in_place_write(slot)); + // A texture slot that is no texture buffer is declared a texel buffer only under its + // in-place variant (`VariantKey::ycbcr_in_place`), a uniform one, or its rows variant + // (`VariantKey::texel_rows`): the rows' where the shape binds a texture whose rows are + // read in place there, else the planes'. + let texel_buffer = matches!( + ty, + vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER + ); + if texel_buffer && self.texture_slot(slot)?.texture_type != TextureType::TextureBuffer { + let rows = matches!( + self.texture_shape(slot), + Some(TextureShape::Texture { + texel_rows: true, + .. + }) + ); + return match rows || ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER { + true => self.rows_write(ty, slot), + false => Ok(self.in_place_write(slot)), + }; } let levels_read = self.has_fact(RuntimeFact::StorageTextureLevels { slot }); let write = self.plain_texture(set, binding, ty, slot)?; self.write_rounding(slot, &write.0)?; + // A slot whose texture's rows are read in place takes its rows variant where its image is + // declared as the rows' texel buffer is, without a storage format + // ([`rows_format`](Self::rows_format)). + let storage = ty == vk::DescriptorType::STORAGE_IMAGE; + if matches!(write.0, WriteSource::Texture { .. }) + && !self.variant.storage_images.contains_key(&slot) + && self.rows_format(slot, storage).is_some() + { + self.variant.texel_rows.insert(slot); + } if levels_read { let levels = match write.0 { WriteSource::Texture { .. } => self.bound_levels(slot), diff --git a/crates/metal2vulkan/src/bind/plan/resources/tests.rs b/crates/metal2vulkan/src/bind/plan/resources/tests.rs index 47223d880..de4490359 100644 --- a/crates/metal2vulkan/src/bind/plan/resources/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/resources/tests.rs @@ -94,6 +94,7 @@ fn compatibility_is_type_samples_numeric_type_and_depth() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type, pixel_format, sample_count, @@ -165,6 +166,7 @@ fn a_ulong_slot_binds_only_rg32uint_textures() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format, sample_count: 1, @@ -259,6 +261,7 @@ fn a_numeric_slot_binds_either_integer_type() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format, sample_count: 1, @@ -332,6 +335,7 @@ fn a_texture_held_for_copies_alone_is_refused_at_a_float_slot() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format, sample_count: 1, @@ -735,6 +739,7 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format: pf, sample_count: 1, @@ -836,6 +841,7 @@ fn a_linear_compare_sampler_needs_no_filterable_view() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format: pf, sample_count: 1, @@ -931,6 +937,7 @@ fn bicubic_texels_follow_the_bound_format() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format: pf, sample_count: 1, @@ -1092,6 +1099,7 @@ fn texel_format_follows_the_bound_format() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format, sample_count: 1, @@ -1276,6 +1284,7 @@ fn a_separate_pair_takes_the_combined_pairs_checks() { offset_base_axes: 0, ycbcr_in_place: false, ycbcr_planes_sampler: None, + texel_rows: false, texture_type: TextureType::Type2D, pixel_format: pf, sample_count: 1, diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index d08546d85..d1fb94068 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -1322,7 +1322,9 @@ impl TextureFacts { /// storage slot's level views and pushed level count, its swizzle, its address-mode map, its /// [`offset_base_axes`](Self::offset_base_axes), and whether its planes are read in place /// ([`ycbcr_in_place`](Self::ycbcr_in_place), whose words the slot's push field carries, not - /// the shape) and through which device conversion where they are held as an image. Its array length only changes the view's subresource range, which is every + /// the shape) and through which device conversion where they are held as an image, and whether + /// its rows are read and written in place ([`texel_rows`](Self::texel_rows), whose words the + /// slot's push field carries). Its array length only changes the view's subresource range, which is every /// layer. /// /// The level count is stated whatever the usage: plain Metal writes a texture made without @@ -1343,6 +1345,7 @@ impl TextureFacts { offset_base_axes: self.offset_base_axes(), ycbcr_in_place: self.ycbcr_in_place.is_some(), ycbcr_planes_sampler: self.ycbcr_in_place.and_then(|p| p.planes_sampler()), + texel_rows: self.texel_rows.is_some(), } } } @@ -1556,6 +1559,15 @@ pub struct TextureFacts { /// image. `None` for every other texture. #[cfg_attr(feature = "serde", serde(default))] pub ycbcr_in_place: Option, + /// The texture's rows in a texel buffer view of its buffer's bytes, where its image is a + /// shadow ([`TexelRows`](crate::bind::TexelRows), the runtime's extension): a 2D texture over a + /// buffer the device makes no image over. A slot whose function only reads, writes or asks + /// the size of it (`RuntimeFact::TexelRows`) takes its rows variant (`VariantKey::texel_rows`), + /// which binds that view ([`WriteSource::TexelRows`](crate::bind::WriteSource)) and pushes + /// these words (`PushField::TexelRows`); any other slot binds the texture's image. `None` for + /// every other texture. + #[cfg_attr(feature = "serde", serde(default))] + pub texel_rows: Option, } impl TextureFacts { @@ -1574,6 +1586,7 @@ impl TextureFacts { parent_relative_level: 0, parent_base_size: [0; 3], ycbcr_in_place: None, + texel_rows: None, } } @@ -2332,6 +2345,11 @@ pub enum TextureShape { /// (`VariantKey::ycbcr_planes_sampled`). #[cfg_attr(feature = "serde", serde(default))] ycbcr_planes_sampler: Option, + /// The texture's rows are read and written in place where a slot's function only reads, + /// writes or asks the size of it ([`TextureFacts::texel_rows`]): such a slot takes its + /// rows variant (`VariantKey::texel_rows`). + #[cfg_attr(feature = "serde", serde(default))] + texel_rows: bool, }, Buffer { pixel_format: metal::PixelFormat, diff --git a/crates/metal2vulkan/src/bind/texel_rows.rs b/crates/metal2vulkan/src/bind/texel_rows.rs new file mode 100644 index 000000000..1acc5e76f --- /dev/null +++ b/crates/metal2vulkan/src/bind/texel_rows.rs @@ -0,0 +1,130 @@ +//! A 2D texture over a buffer's rows whose image is a shadow, read and written in place through a +//! texel buffer view of the rows' bytes. +//! +//! **Where.** A texture over a buffer's bytes lies in an image over them where the device makes +//! one; where it makes none (the runtime's image refusals), the texture is a shadow, an image of +//! the runtime's own memory its commands' encoders copy the texels into and back. The buffer +//! itself is still in place. A texture in such a shadow states its rows in its facts +//! (`TextureFacts::texel_rows`), and a texture slot whose function only reads, writes or asks the +//! size of it (`RuntimeFact::TexelRows`: no sample, gather, atomic, read through a sampler or +//! level past the first) takes the slot's rows variant (`VariantKey::texel_rows`). +//! +//! **The binding.** Under the variant the slot's one descriptor is a texel buffer over the rows' +//! bytes (`WriteSource::TexelRows`), uniform where the function only reads the texture and storage +//! where it writes it, in the format a texture buffer of the texture's pixel format takes +//! (`bind::plan`'s texel formats: the format's own, an alias, or `R8_UNORM` for `A8Unorm`). Vulkan +//! states a texel buffer's texels "going through format conversion when read in a shader in the +//! same way as they are for an image" (Uniform Texel Buffer, Storage Texel Buffer), so a read +//! answers the device's conversion of the texel, as the shadow's image does. The view starts at +//! the texture's first texel, or before it where the device's texel buffer offset alignment asks: +//! the texture's size, its rows in texels and its first texel in the view are the slot's push +//! field (`PushField::TexelRows`, [`TexelRows::words`]). +//! +//! **What a function reads.** Texel `(x, y)` is the view's texel `first + y · row + x`. A read of +//! a texel outside the texture, or at a level past its one, is Metal's out-of-bounds texel, and a +//! write there is dropped, by the function's own test of the coordinate against the texture's +//! size: a coordinate past the width names a texel of the next row in the view, which the +//! device's robustness, bounding the view alone, would read. A size query answers the field's +//! size, at a level as at any texture, and the level count 1. +//! +//! **Ordering.** The slot's use is a use of the rows' bytes (`AccessClass::TexelRows`), as a +//! texture buffer's is: the consumer orders it against every use of the buffer, its shadow's +//! copies among them. A store to a texel buffer writes its texel's bytes alone (Vulkan's memory +//! model: "A memory operation must not affect memory at a memory location not within its set of +//! memory locations"), and a buffer view has no layout moves or load and store operations, so the +//! bytes between the rows keep whatever the CPU or another command writes there. + +/// A 2D texture's rows in a texel buffer view of its buffer's bytes, where its image is a shadow +/// (the module docs): the words of its slot's push field (`PushField::TexelRows`), and the texels +/// the view holds ([`elements`](Self::elements)). A texture states one in its facts +/// (`TextureFacts::texel_rows`), and a slot whose function only reads, writes or asks the size of +/// it (`RuntimeFact::TexelRows`) takes the rows variant (`VariantKey::texel_rows`), which binds +/// the view (`WriteSource::TexelRows`) and addresses texel `(x, y)` at `first + y · row + x`. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct TexelRows { + words: [u32; TexelRows::WORDS], +} + +impl TexelRows { + /// The words of the slot's push field ([`words`](Self::words)), one `uvec4`. + pub const WORDS: usize = 4; + /// Word: the texture's width in texels. + pub const WIDTH: usize = 0; + /// Word: the texture's height in texels. + pub const HEIGHT: usize = 1; + /// Word: the texels from one row's first to the next's in the view. + pub const ROW: usize = 2; + /// Word: the view's texel that is the texture's first. + pub const FIRST: usize = 3; + + /// The rows of a texture of `size` texels whose rows lie `row` texels apart from the view's + /// texel `first`. `None` for an empty texture, rows shorter than its width, or a view past + /// `u32::MAX` texels, which no texel buffer holds (`maxTexelBufferElements` is a `u32`). + pub fn new(size: [u32; 2], row: u64, first: u64) -> Option { + let [width, height] = size; + if width == 0 || height == 0 || row < u64::from(width) { + return None; + } + let elements = first + .checked_add(row.checked_mul(u64::from(height) - 1)?)? + .checked_add(u64::from(width))?; + if elements > u64::from(u32::MAX) { + return None; + } + let mut words = [0; Self::WORDS]; + words[Self::WIDTH] = width; + words[Self::HEIGHT] = height; + words[Self::ROW] = u32::try_from(row).ok()?; + words[Self::FIRST] = u32::try_from(first).ok()?; + Some(TexelRows { words }) + } + + /// The words of the slot's push field. + pub fn words(&self) -> [u32; Self::WORDS] { + self.words + } + + /// The texture's width and height in texels. + pub fn size(&self) -> [u32; 2] { + [self.words[Self::WIDTH], self.words[Self::HEIGHT]] + } + + /// The texels the view holds, from its first through the texture's last + /// (`maxTexelBufferElements` bounds them). + pub fn elements(&self) -> u64 { + let [width, height] = self.size().map(u64::from); + u64::from(self.words[Self::FIRST]) + u64::from(self.words[Self::ROW]) * (height - 1) + width + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The words are the size, the row and the first texel; the view holds the texels through the + /// last row's last texel, none past it. + #[test] + fn the_view_ends_at_the_last_texel() { + let rows = TexelRows::new([61, 4], 68, 3).expect("rows"); + assert_eq!(rows.words(), [61, 4, 68, 3]); + assert_eq!(rows.size(), [61, 4]); + assert_eq!(rows.elements(), 3 + 3 * 68 + 61); + // One row: its texels alone. + assert_eq!(TexelRows::new([5, 1], 5, 0).map(|r| r.elements()), Some(5)); + } + + /// No rows for an empty texture, rows shorter than the width, or a view past `u32::MAX` + /// texels. + #[test] + fn rows_no_view_holds_are_none() { + assert_eq!(TexelRows::new([0, 4], 8, 0), None); + assert_eq!(TexelRows::new([4, 0], 8, 0), None); + assert_eq!(TexelRows::new([9, 4], 8, 0), None); + let last = TexelRows::new([65536, 65536], 65536, 0).map(|r| r.elements()); + assert_eq!(last, None, "2^32 texels"); + let fits = TexelRows::new([65535, 65537], 65535, 0).map(|r| r.elements()); + assert_eq!(fits, Some(65535 * 65537)); + } +} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 3f41b4b19..2219a2a33 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -919,6 +919,7 @@ codec_enum! { LineBand, RegionProbe, RegionFirst, + TexelRows(f0), } Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) } } @@ -1320,6 +1321,7 @@ codec_enum! { BorderTexels { slot }, RegionViewports, PartialThreadgroups, + TexelRows { slot }, } UniformViewChoice { Viewed, Spare, Kept } Mechanism { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index ac05e8686..3ba6bb5be 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2111; +pub const SEMANTICS_VERSION: u32 = 2112; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2303; +pub const RUNTIME_VERSION: u32 = 2304; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles @@ -234,6 +234,13 @@ pub struct VariantKey { serde(default, with = "crate::pipeline::serde_pairs") )] pub ycbcr_planes_sampled: BTreeMap, + /// Texture slots whose function only reads, writes or asks the size of the 2D texture the + /// shape binds there, whose rows are read and written in place: every slot of a + /// `RuntimeFact::TexelRows` the shape binds such a texture at + /// (`TextureShape::Texture::texel_rows`). Each such slot binds a texel buffer over the rows' + /// bytes alone (`bind::TexelRows`). The plan of a pipeline compiled under it states it. + #[cfg_attr(feature = "serde", serde(default))] + pub texel_rows: BTreeSet, /// Texture slots a constexpr sampler samples, each with the address-mode map of the texture /// the shape binds there where it is not the identity: every slot of a /// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr @@ -577,6 +584,7 @@ impl VariantKey { && self.snapshot_textures.is_empty() && self.ycbcr_in_place.is_empty() && self.ycbcr_planes_sampled.is_empty() + && self.texel_rows.is_empty() && self.address_maps.is_empty() && !self.flat_grid && !self.call_threadgroups @@ -709,6 +717,12 @@ impl VariantKey { .filter(|(s, _)| s.stage == stage) .map(|(s, sampler)| (*s, *sampler)) .collect(); + out.texel_rows = self + .texel_rows + .iter() + .filter(|s| s.stage == stage) + .copied() + .collect(); out.address_maps = self .address_maps .iter() diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 452450da3..2de6cf0e0 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -195,6 +195,8 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // Keyed by the slots bound to a texture whose planes are read in place, on a profile that // reads them so (`ProfileFields::ycbcr_in_place`). RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, + // Keyed by the slots bound to a texture whose rows are read and written in place. + RuntimeFact::TexelRows { .. } => Mechanism::Variant, // The function marks the `ExecutionStatus` buffer its `ExecutionStatus` fact binds; the // consumer reads the bit after the command buffer. RuntimeFact::AbsentArgumentRead { .. } => Mechanism::None, diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 9c61d8497..227f818dc 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -169,6 +169,7 @@ fn every_fact() -> Vec { samplers: 1, device: true, }, + RuntimeFact::TexelRows { slot }, RuntimeFact::MeshLastFirst, RuntimeFact::AbsentArgumentRead { stage: Stage::Fragment, @@ -388,6 +389,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::RegionViewports => 96, RuntimeFact::CallThreadgroups => 97, RuntimeFact::PartialThreadgroups => 98, + RuntimeFact::TexelRows { .. } => 99, } } @@ -395,7 +397,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..99).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..100).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -476,6 +478,7 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::PrivateList | RuntimeFact::RegionViewports | RuntimeFact::YCbCrInPlace { .. } + | RuntimeFact::TexelRows { .. } | RuntimeFact::ZeroedColor { .. } | RuntimeFact::DroppedColor { .. } | RuntimeFact::DepthClampRange diff --git a/crates/metal2vulkan/src/lower/access/tile.rs b/crates/metal2vulkan/src/lower/access/tile.rs index 10b874302..f55118063 100644 --- a/crates/metal2vulkan/src/lower/access/tile.rs +++ b/crates/metal2vulkan/src/lower/access/tile.rs @@ -1048,6 +1048,7 @@ fn image_decl(s: &TileSlot) -> ImageDecl { x_channel: false, in_place: false, planes_sampler: None, + rows: false, } } diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index 01989d282..5769a7acb 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -115,6 +115,8 @@ pub const fn shape(f: PushField) -> FieldShape { PushField::Specialized(_) => FieldShape::U32, // An in-place YCbCr texture's size, planes and conversion. PushField::YCbCrInPlace(_) => FieldShape::UVec4Array(2), + // A texture's size, rows and first texel in its texel buffer view. + PushField::TexelRows(_) => FieldShape::UVec4Array(1), // The residual is below `min{Storage,Uniform}BufferOffsetAlignment`. PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32, // A texture's mipmap level count, an acceleration structure's instance count, the render diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index 11596fae7..2f1782874 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -1374,6 +1374,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { x_channel: false, in_place: false, planes_sampler: None, + rows: false, }; let symbol = ResourceSlot { stage: cx.stage, diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index ceb88121c..fff425425 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -2415,7 +2415,20 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR // read through a sampler is tested as it accesses, with its addressed coordinate against the // size at its level, so only its layer or sample index can fail. let mut in_range = None; - if (r.checked() || spec.is_some()) && !volume { + if decl.rows { + // A rows slot's texel (`ImageDecl::rows`): its index in the view, of the coordinate + // clamped into the texture, and in range inside the texture at its one level (the select + // checks every such read). + let words = rows_words(cx, fb, &r.image)?; + let (index, mut inside) = rows_texel(fb, words, coord)?; + if let Some(l) = level.take() { + let zero = u32s(fb, 1, 0)?; + let first = fb.binary(BinOp::IEqual, l, zero)?; + inside = fb.binary(BinOp::LogicalAnd, inside, first)?; + } + coord = index; + in_range = Some(inside); + } else if (r.checked() || spec.is_some()) && !volume { let size = match (&through, level) { // The size at the level the read through a sampler accesses, which is the image's. (Some((_, a)), _) => a.size, @@ -2482,6 +2495,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR let snapshot = match r.image { ImageRef::Slot(index) => { let plain = sampled + && !decl.rows && spec.is_none() && sample.is_none() && r.through.is_none() @@ -3006,6 +3020,16 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul true => Some(volume_write(cx, fb, img, coord, w.level)?), false => None, }; + // A rows slot's write (`ImageDecl::rows`): to its texel's index in the view, stored only + // inside the texture, by the function's own test on every profile, as a two-plane 3D + // texture's is. + let volume = match (volume, decl.rows) { + (None, true) => { + let words = rows_words(cx, fb, &w.image)?; + Some(rows_texel(fb, words, coord)?) + } + (volume, _) => volume, + }; let coord = volume.map_or(coord, |(at, _)| at); let v = cx.operand(fb, w.value)?; // A texture of another numeric class: the declared lanes as its own class's texel. @@ -3397,6 +3421,9 @@ fn query_value( if decl.in_place { return in_place_query(cx, fb, q); } + if decl.rows { + return rows_query(cx, fb, q); + } let sampled_mips = decl.usage == ImageUsage::Sampled && !decl.multisampled && decl.dim != Dim::Buffer; let n = coord_len(decl); @@ -3520,6 +3547,71 @@ fn in_place_query( } } +/// The answer of query `q` of a rows slot (`ImageDecl::rows`): its texture's width or height +/// from the slot's push field, at a level as at any texture's ([`level_extent`]), and its one +/// level. +fn rows_query(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, q: &QueryOp) -> BResult { + let words = rows_words(cx, fb, &q.image)?; + match q.kind { + QueryKind::Size { + component: c @ (0 | 1), + } => { + let e = fb.composite_extract(words, &[u32::from(c)])?; + match q.level { + Some(l) => { + let l = cx.operand(fb, l)?; + level_extent(fb, e, l) + } + None => Ok(e), + } + } + QueryKind::Levels => u32s(fb, 1, 1), + _ => Err(cx.fail("a rows query the rows do not answer")), + } +} + +/// The words of rows slot `image`'s push field (`PushField::TexelRows`, `bind::TexelRows`), a +/// `uvec4` of the texture's width, height, row and first texel in the view, in the open block. +fn rows_words( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + image: &ImageRef, +) -> BResult { + let ImageRef::Slot(index) = *image else { + return Err(cx.fail("the rows of a heap element")); + }; + let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else { + return Err(cx.fail(format!("texture slot {index} is not planned"))); + }; + let field = cx.push_field(fb, crate::pipeline::sym::PushField::TexelRows(slot))?; + fb.composite_extract(field, &[0]) +} + +/// The texel at `coord` (a `uvec2`) of rows `words` ([`rows_words`]): its index in the view, +/// `first + y · row + x` of the coordinate clamped into the texture (whose width and height are +/// never 0), so the access stays inside the view, which ends at the last row's last texel; and +/// whether `coord` lies in the texture. +fn rows_texel( + fb: &mut FunctionBuilder<'_>, + words: SValue, + coord: SValue, +) -> BResult<(SValue, SValue)> { + use crate::bind::TexelRows as W; + let at = |i: usize| i as u32; + let size = fb.vector_shuffle(words, words, &[at(W::WIDTH), at(W::HEIGHT)])?; + let lt = fb.binary(BinOp::ULessThan, coord, size)?; + let inside = fb.unary(UnOp::All, lt)?; + let clamped = clamp_below(fb, coord, size, 2)?; + let x = fb.composite_extract(clamped, &[0])?; + let y = fb.composite_extract(clamped, &[1])?; + let row = fb.composite_extract(words, &[at(W::ROW)])?; + let first = fb.composite_extract(words, &[at(W::FIRST)])?; + let down = fb.binary(BinOp::IMul, y, row)?; + let start = fb.binary(BinOp::IAdd, first, down)?; + let index = fb.binary(BinOp::IAdd, start, x)?; + Ok((index, inside)) +} + /// The extent Metal answers at level `l` of a texture whose first level's extent is `e`: /// `max(1, e >> (l & 255))`, at every level, past the texture's level count too, a shift of 32 or /// more answering 1. Measured on an Apple M3 Max under macOS 27.0.1: the width, height, and depth diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 9ba1e9831..391d7da86 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -2046,6 +2046,7 @@ pub fn select( }; for index in slots { not_in_place(cx, index); + not_rows(cx, index); if extended_range(cx, ImageRef::Slot(index))?.is_some() { return Err(Unsupported::not_implemented(Feature::Format).into()); } @@ -2090,6 +2091,7 @@ pub fn select( // A switch-at-use's arm reads its slot's image. Candidate::Texture(index) => { not_in_place(cx, index); + not_rows(cx, index); select_image(cx, (at, inst), t, &ops, ImageRef::Slot(index), m)? } Candidate::Absent => AbsentArgument::select(cx, at, inst, t)?, @@ -2854,6 +2856,14 @@ pub(crate) fn not_in_place(cx: &mut SelectCx<'_>, index: u32) { } } +/// Record an access of texture slot `index` that its texture's rows read in place do not answer +/// (`slot::SlotPlan::not_rows`): the slot takes no rows variant. +pub(crate) fn not_rows(cx: &mut SelectCx<'_>, index: u32) { + if let Some(s) = cx.families.texture.slots.get_mut(&index) { + s.not_rows = true; + } +} + /// Whether the function observes any of texture call `at`'s status word. pub(crate) fn observes_status(cx: &mut SelectCx<'_>, at: InstId) -> bool { status_use(cx, at).is_some() @@ -2952,6 +2962,16 @@ pub(crate) fn swizzled_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result, image: ImageRef) -> Result { + let ImageRef::Slot(index) = image else { + return Ok(false); + }; + let slot = slot_of(cx, index)?.slot; + Ok(cx.inputs.texel_rows.contains(&slot)) +} + /// Record that texture slot `index`'s function applies its bound texture's swizzle: the slot's /// `TextureSwizzle` specialization (`RuntimeFact::TextureSwizzle`). pub(crate) fn swizzles(cx: &mut SelectCx<'_>, index: u32) -> Result<(), Error> { @@ -3037,6 +3057,17 @@ fn select_image( ) { not_in_place(cx, index); } + // The rows read and write a texel by its coordinate, and answer the size, the level + // count and the presence; nothing else. + if !matches!( + t.op, + TexOp::Read + | TexOp::Write + | TexOp::IsNull + | TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels) + ) { + not_rows(cx, index); + } } let texel = match t.texel { Some(x) if matches!(t.op, TexOp::Read | TexOp::Write | TexOp::Atomic(_)) => Some( @@ -3244,6 +3275,9 @@ fn select_read_as( } if let Some(t) = through { select_through(cx, image, texel, t)?; + if let ImageRef::Slot(index) = image { + not_rows(cx, index); + } } let residency = residency(cx, at, image)?; let (storage, write_only) = image_access(cx, image)?; @@ -3275,6 +3309,9 @@ fn select_read_as( } let check = match slot::read_check(cx, shape.dim == ImageDim::Buffer) { ReadCheck::Device if extended.is_some() => ReadCheck::Shader, + // A rows slot's coordinate past the width names the next row's texel in the view + // (`bind::texel_rows`): the shader selects Metal's out-of-bounds texel on every profile. + _ if texel_rows(cx, image)? => ReadCheck::Shader, c => c, }; // A storage read at a level reads the slot's level views, and past the bound level count diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index fda106e51..263a39d81 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -143,6 +143,11 @@ pub struct ImageDecl { /// sampler of a sampled 2D `float` image (`ResourceKind::YCbCrPlanes`), whose immutable /// sampler bakes the conversion; `in_place` holds, so its size is still the push field's. pub planes_sampler: Option, + /// The slot's variant reads and writes a 2D texture's rows in place + /// (`LoweringInputs::texel_rows`, `bind::texel_rows`): the image is the rows' texel buffer, + /// uniform for a sampled slot and storage for a storage one, texel `(x, y)` its texel + /// `first + y · row + x` and the texture's size the push field's. + pub rows: bool, } impl ImageDecl { @@ -252,6 +257,10 @@ pub struct SlotPlan { pub offset_base: bool, /// How its accesses read a two-plane YCbCr texture's planes in place. pub in_place: InPlaceReads, + /// An access its texture's rows read in place do not answer (`bind::texel_rows`): anything + /// but a read or write of a texel by its coordinate, a query of the width, the height or the + /// level count, and a presence test. The uses rule out the rest ([`rows_reads`]). + pub not_rows: bool, /// The declaration, set by [`finish`] for a slot that is read, written, or queried, or /// whose faces are fetched. pub decl: Option, @@ -280,6 +289,7 @@ impl SlotPlan { constant_lanes: false, offset_base: false, in_place: InPlaceReads::default(), + not_rows: false, decl: None, } } @@ -570,6 +580,7 @@ fn declare_heap( x_channel: false, in_place: false, planes_sampler: None, + rows: false, }; Ok((class, decl)) } @@ -1041,6 +1052,7 @@ fn declare_slot( x_channel: false, in_place: true, planes_sampler: Some(sampler), + rows: false, }); } // A slot under its in-place variant is the uniform texel buffer of its texture's planes, of @@ -1063,6 +1075,54 @@ fn declare_slot( x_channel: false, in_place: true, planes_sampler: None, + rows: false, + }); + } + // A slot under its rows variant is the texel buffer of its texture's rows, with the field of + // their words (`bind::texel_rows`): a uniform one for a sampled slot, a storage one, declared + // as the slot's storage image would be, for a storage slot. + if cx.inputs.texel_rows.contains(&s.slot) { + if !rows_reads(s) { + return Err(cx.invariant("a rows slot whose accesses the rows do not answer")); + } + push.push(PushField::TexelRows(s.slot)); + let texel = image_class(cx.inputs, s); + let (format, class) = match storage { + true => { + facts.push(RuntimeFact::StorageTextureFormat { slot: s.slot }); + storage_format(cx, s, texel)? + } + false => ( + crate::spv::ImageFormat::Unknown, + StorageImageClass::Identity, + ), + }; + if class != StorageImageClass::Identity { + return Err(cx.invariant("a rows slot whose storage image converts its texels")); + } + match storage { + true => counts.storage_images = counts.storage_images.saturating_add(1), + false => counts.sampled_images = counts.sampled_images.saturating_add(1), + } + return Ok(ImageDecl { + dim: Dim::Buffer, + arrayed: false, + multisampled: false, + depth: false, + usage: match storage { + true => ImageUsage::Storage, + false => ImageUsage::Sampled, + }, + format, + texel, + cube_as_array: false, + class, + level_views: None, + extended: None, + x_channel: false, + in_place: false, + planes_sampler: None, + rows: true, }); } // A slot bound in an extended-range format holds its raw texels in an unsigned integer @@ -1193,6 +1253,7 @@ fn declare_slot( x_channel, in_place: false, planes_sampler: None, + rows: false, }) } @@ -1211,6 +1272,25 @@ fn in_place_reads(cx: &SelectCx<'_>, s: &SlotPlan) -> bool { && matches!(s.texel, None | Some(TexelClass::Float)) } +/// Whether every access of slot `s` is one its texture's rows read in place answer +/// (`bind::texel_rows`): a single-sample 2D color texture's (not an array, multisampled or depth +/// one) of a 32-bit class, read, written or asked its size, every access of a texel at the first +/// level of a storage slot (no level views), and nothing sampled, gathered, updated by an atomic, +/// read through a sampler or a switch, its residency observed or its integer channels read; no +/// access blocked ([`SlotPlan::not_rows`]). +fn rows_reads(s: &SlotPlan) -> bool { + let u = &s.uses; + (u.read || u.write || u.query) + && !(u.sample || u.compare || u.atomic || u.level_views || u.residency || u.faces) + && !(u.int_channels || u.narrow_result || s.not_rows) + && s.shape + .is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth) + && matches!( + s.texel, + None | Some(TexelClass::Float | TexelClass::Sint | TexelClass::Uint) + ) +} + /// Whether a slot of `shape` can have a tile map: a single-sample 2D, 2D array, or 3D color texture /// (`bind::SparseTileMap`), the sparse types the case model measures. fn tiled_shape(shape: ImageShape) -> bool { @@ -1267,7 +1347,8 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { } Err(error) => return Err(error), }; - let volatile = forwards(cx, &s.uses, shape.dim == ImageDim::Buffer); + // A rows slot's every load and store is the function's own test's, inside the view. + let volatile = !d.rows && forwards(cx, &s.uses, shape.dim == ImageDim::Buffer); decls.push((*index, d, volatile)); } // The slots read, sampled or gathered in any class (a slot only sampled is declared by its @@ -1299,6 +1380,13 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { }); } } + // The slots whose every access the rows answer: their compile under the rows variant states + // the same, which its plan holds to. + for s in cx.families.texture.slots.values() { + if rows_reads(s) { + facts.push(RuntimeFact::TexelRows { slot: s.slot }); + } + } let mut heap = Vec::new(); for (group, h) in &cx.families.texture.heap { let used = h.uses.read || h.uses.write || h.uses.query || h.uses.sample; diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index a228ac76c..f000747f7 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -222,6 +222,7 @@ mod serde_round_trips { slot(Stage::Kernel, SlotClass::Texture, 7), planes_sampler(), )]), + texel_rows: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 9)]), flat_grid: true, call_threadgroups: true, replay_bindings: true, @@ -362,6 +363,7 @@ mod serde_round_trips { slot(Stage::Fragment, SlotClass::Texture, 9), planes_sampler(), )]), + texel_rows: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 10)]), viewport_index_varying: true, // An emulated post-tessellation vertex function's state. tessellation: Some(crate::pipeline::TessellationDescriptor { diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index da67dbd0b..28a4fc39d 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -261,6 +261,11 @@ pub fn function_key( .bytes(format!("{:?}", inputs.ycbcr_planes_sampled).as_bytes()); } // Appended only when set, as `storage_view_slots`. + if !inputs.texel_rows.is_empty() { + h.bytes(b"texel-rows") + .bytes(format!("{:?}", inputs.texel_rows).as_bytes()); + } + // Appended only when set, as `storage_view_slots`. if !inputs.extended_range.is_empty() { h.bytes(b"extended-range") .bytes(format!("{:?}", inputs.extended_range).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index bccd017cb..9e5fd0c0a 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -793,6 +793,17 @@ pub enum RuntimeFact { samplers: u32, device: bool, }, + /// The function only reads, writes or asks the size of the 2D texture bound to the slot + /// (`bind::TexelRows`): `read` at level 0 or a computed level, `write`, its width, height or + /// level count, `is_null` and a texture fence; no sample, gather, LOD query, atomic, read + /// through a sampler, imageblock slice or access of a level past the first through a storage + /// slot, and no arm of a handle that switches between slots. Where the binder binds a texture + /// whose rows are read and written in place (`TextureShape::Texture::texel_rows`), the slot + /// joins the plan's variant (`VariantKey::texel_rows`, `LoweringInputs::texel_rows`), under + /// which its one binding is a texel buffer over the rows' bytes (`WriteSource::TexelRows`), + /// texel `(x, y)` the view's `first + y · row + x`, those words in the slot's push field + /// (`PushField::TexelRows`). Elsewhere the slot binds the texture's image as before. + TexelRows { slot: SlotRef }, /// The object function runs a partial threadgroup of a `drawMeshThreads` as Metal does /// (`lower::dispatch`'s partial object threadgroups): where its `DispatchRegion` (or a folded /// variant's region record) carries `lower::dispatch::NONUNIFORM`, it answers its diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 1b5b6bf11..53cb07776 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -194,6 +194,13 @@ pub struct LoweringInputs { serde(default, with = "crate::pipeline::serde_pairs") )] pub ycbcr_planes_sampled: BTreeMap, + /// Texture slots bound to a 2D texture whose rows are read and written in place + /// (`VariantKey::texel_rows`, `RuntimeFact::TexelRows`): each is declared as a texel buffer of + /// the rows, uniform where the function only reads it and storage where it writes it, its + /// reads and writes of texel `(x, y)` addressing the view's `first + y · row + x` and its size + /// queries reading the slot's push field (`bind::TexelRows`). + #[cfg_attr(feature = "serde", serde(default))] + pub texel_rows: BTreeSet, /// The fragment function's render pipeline has a vertex function that writes /// `[[viewport_array_index]]`. That function stores `ViewportIndex` as 0 for an index at or /// past the draw's viewport count, where Metal draws through viewport 0 and its fragment diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 83cccfdf8..7a64684fb 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1189,6 +1189,11 @@ pub enum PushField { /// conversion (`bind::YCbCrInPlace::words`), from the bound texture's facts /// (`TextureFacts::ycbcr_in_place`). YCbCrInPlace(SlotRef), + /// The rows of the 2D texture bound to the slot in its texel buffer view, read and written in + /// place (`RuntimeFact::TexelRows`, `LoweringInputs::texel_rows`): one `uvec4`, the texture's + /// width and height, its rows in texels and its first texel in the view + /// (`bind::TexelRows::words`), from the bound texture's facts (`TextureFacts::texel_rows`). + TexelRows(SlotRef), /// The value a draw or dispatch binds for specialization key `key`, carried as data rather /// than specialized: one `u32` holding exactly the value the binder computes for the key's /// specialization constant from the bound textures and samplers (a boolean key as 1 or 0; a diff --git a/crates/metal2vulkan/src/tests/engine_texel_rows.rs b/crates/metal2vulkan/src/tests/engine_texel_rows.rs new file mode 100644 index 000000000..c70db413b --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_texel_rows.rs @@ -0,0 +1,312 @@ +//! A 2D texture's rows read and written in place through a texel buffer (`bind::texel_rows`), on +//! the CPU interpreter. +//! +//! - A slot whose function only reads, writes or asks the size of its texture states +//! `RuntimeFact::TexelRows`; one that samples it states none. +//! - Under the rows variant (`LoweringInputs::texel_rows`) the slot is a texel buffer (uniform +//! for an `access::read` slot, storage for an `access::write` or `read_write` one) that the +//! profile validates, and its push field holds the rows' words. +//! - A read of texel `(x, y)` reads the view's texel `first + y · row + x`, and Metal's +//! out-of-bounds texel past the texture's width or height; a write stores there, and nothing +//! past the texture, so the texels between the rows and before the first keep their values; +//! a size query answers the field's size. The interpreter's texel buffer traps every access +//! outside the view, so each access lies within it. +//! +//! The kernels are the runtime's device tests' (`examples/texel_rows.metal`). `llvm-as` assembles +//! them; without it the tests skip visibly. + +use std::collections::BTreeMap; + +use crate::bind::TexelRows; +use crate::device::profile::DeviceProfile; +use crate::device::DevicePolicy; +use crate::lower::select::{LowerInputs, Plan}; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::interface::PushLoc; +use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef}; +use crate::pipeline::sym::{SpecKey, Stage}; +use crate::pipeline::testing::{ + compile, compile_with, fixtures_dir, link_and_validate, llvm_assemble, profile, + typed_module_with, AssembleError, +}; +use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; +use crate::spirv::ir::{Dim, GlobalKind, ImageUsage, Type as SType, TypedModule}; + +const TEXTURE: SlotRef = SlotRef { + stage: Stage::Kernel, + class: SlotClass::Texture, + index: 0, +}; + +/// The texture's width and height, its rows' texels apart in the view, and the view's texel +/// that is its first: rows of 5 texels 7 apart, after 3 texels of the view. +const SIZE: [u32; 2] = [5, 4]; +const ROW: u64 = 7; +const FIRST: u64 = 3; + +/// The grid: past the texture's width and height, so its edges are crossed. +const GRID: [u32; 2] = [8, 6]; + +/// The kernels' bitcode, or `None` without `llvm-as`. +fn bitcode() -> Option> { + let ll = fixtures_dir().join("examples/texel_rows.ll"); + match llvm_assemble(&ll) { + Ok(x) => Some(x), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("texel_rows.ll: {why}"), + } +} + +fn lavapipe() -> DeviceProfile { + profile("lavapipe", DevicePolicy::default()).expect("profile") +} + +/// The rows variant's inputs: slot 0's rows. +fn rows_inputs() -> LowerInputs { + let mut inputs = LowerInputs::new(); + inputs.texel_rows.insert(TEXTURE); + inputs +} + +fn rows() -> TexelRows { + TexelRows::new(SIZE, ROW, FIRST).expect("rows") +} + +/// The view's texel `i` before any write: a value of its own in each lane, as `float` bits. +fn view_texel(i: u32) -> [u32; 4] { + std::array::from_fn(|lane| (i as f32 * 4.0 + lane as f32 + 0.25).to_bits()) +} + +/// Each texel of the texture by its view index, `(x, y)` row-major. +fn texture_indices() -> Vec<((u32, u32), u32)> { + let [w, h] = SIZE; + (0..h) + .flat_map(|y| (0..w).map(move |x| ((x, y), (FIRST + u64::from(y) * ROW + u64::from(x))))) + .map(|(at, i)| (at, i as u32)) + .collect() +} + +/// The texture's binding, a texel buffer of `usage`. +fn rows_binding(m: &TypedModule, usage: ImageUsage) -> ResourceSlot { + let (slot, pointee) = m + .globals() + .iter() + .find_map(|g| match g.kind { + GlobalKind::Resource( + s @ ResourceSlot { + kind: ResourceKind::Texture, + index: 0, + .. + }, + ) => Some((s, g.pointee)), + _ => None, + }) + .expect("the texture's binding"); + match m.types().get(pointee).expect("its type") { + SType::Image(i) => { + assert_eq!(i.dim, Dim::Buffer, "the rows' binding is a texel buffer"); + assert_eq!(i.usage, usage, "the rows' texel buffer's kind"); + } + other => panic!("the rows' binding is {other:?}"), + } + slot +} + +/// The view, `elements` texels of [`view_texel`], bound at `slot`. +fn view(slot: ResourceSlot) -> Image { + let n = rows().elements() as u32; + let mut image = Image::new(slot, [n, 1, 1], 1, 1, 1); + for x in 0..n { + let i = image.index(0, 0, 0, [x, 0, 0]).expect("element"); + image.texels[i] = view_texel(x); + } + image +} + +/// Resources of a dispatch of one-thread threadgroups: `[[buffer(i)]]` holding `init[i]`, the +/// slot's push field holding the rows' words, and Metal's out-of-bounds alpha of a format with +/// alpha (0). +fn resources(plan: &Plan, init: &[Vec]) -> Resources { + let mut spec = BTreeMap::new(); + for axis in [Axis::X, Axis::Y, Axis::Z] { + spec.insert(SpecKey::LocalSize(axis), 1); + } + spec.insert(SpecKey::FlatLocalSize, 1); + spec.insert(SpecKey::OutOfBoundsAlpha(TEXTURE), 0); + let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; + let mut written = false; + for f in &plan.push.fields { + if let (PushField::TexelRows(TEXTURE), PushLoc::Push { offset }) = (f.field, f.loc) { + let at = offset as usize; + for (i, w) in rows().words().into_iter().enumerate() { + push[at + 4 * i..at + 4 * i + 4].copy_from_slice(&w.to_le_bytes()); + } + written = true; + } + } + assert!(written, "the rows' push field"); + let buffers = init + .iter() + .enumerate() + .map(|(i, b)| Buffer { + slot: Some(ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: i as u32, + }), + address: None, + bytes: b.clone(), + }) + .collect(); + Resources { + buffers, + push, + spec, + } +} + +/// `m` over the grid with `image` bound, in both scheduling orders, which must agree: the final +/// buffers and the view. +fn run(m: &TypedModule, res: &Resources, image: &Image) -> (Vec>, Image) { + let mut outs = Vec::new(); + for order in [Order::Forward, Order::Reverse] { + let cfg = Config { + workgroups: [GRID[0], GRID[1], 1], + order, + ..Config::default() + }; + let (o, images) = run_with_images(m, &cfg, res.clone(), vec![image.clone()]) + .unwrap_or_else(|e| panic!("interpreter: {e:?}")); + let image = images.into_iter().next().expect("the view"); + outs.push((o.buffers, image.texels.clone(), image)); + } + assert_eq!(outs[0].0, outs[1].0, "the scheduling orders disagree"); + assert_eq!(outs[0].1, outs[1].1, "the scheduling orders disagree"); + let (buffers, _, image) = outs.swap_remove(0); + (buffers, image) +} + +/// The grid's columns, as the kernels' `constant uint &columns`. +fn columns() -> Vec { + GRID[0].to_le_bytes().to_vec() +} + +/// A slot whose function only reads, writes or asks the size of its texture states its rows; a +/// slot that samples it states none. +#[test] +fn reads_writes_and_sizes_state_rows_and_samples_do_not() { + let Some(bitcode) = bitcode() else { return }; + let p = lavapipe(); + let fact = RuntimeFact::TexelRows { slot: TEXTURE }; + for entry in ["rows_invert", "rows_read", "rows_write"] { + let a = compile(&bitcode, entry, &p).unwrap_or_else(|e| panic!("{entry}: {e}")); + assert!(a.facts.contains(&fact), "{entry} states its rows"); + } + let a = compile(&bitcode, "rows_sample", &p).expect("rows_sample"); + assert!(!a.facts.contains(&fact), "a sample states no rows"); +} + +/// Under the rows variant each kernel's module validates on the profile, the slot a texel +/// buffer: uniform for a slot that only reads, storage for one that writes. +#[test] +fn the_rows_variant_validates() { + let Some(bitcode) = bitcode() else { return }; + let p = lavapipe(); + for (entry, usage) in [ + ("rows_invert", ImageUsage::Storage), + ("rows_read", ImageUsage::Sampled), + ("rows_write", ImageUsage::Storage), + ] { + let a = compile_with(&bitcode, entry, &p, &rows_inputs()) + .unwrap_or_else(|e| panic!("{entry}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{entry}: {e}")); + let (_, m) = typed_module_with(&bitcode, entry, &p, &rows_inputs()).expect(entry); + rows_binding(&m, usage); + let fact = RuntimeFact::TexelRows { slot: TEXTURE }; + assert!( + a.facts.contains(&fact), + "{entry}'s variant states its rows, as the plan holds it to" + ); + } +} + +/// A read of texel `(x, y)` reads the view's texel `first + y · row + x`, and Metal's zero texel +/// past the texture's width or height, never the next row's. +#[test] +fn a_read_takes_its_texel_by_row() { + let Some(bitcode) = bitcode() else { return }; + let p = lavapipe(); + let (plan, m) = typed_module_with(&bitcode, "rows_read", &p, &rows_inputs()).expect("module"); + let slot = rows_binding(&m, ImageUsage::Sampled); + let out = vec![0u8; (GRID[0] * GRID[1] * 16) as usize]; + let res = resources(&plan, &[out, columns()]); + let (buffers, _) = run(&m, &res, &view(slot)); + let (words, _) = buffers[0].as_chunks::<4>(); + let texels: Vec<[u32; 4]> = (words.as_chunks::<4>().0.iter()) + .map(|t| t.map(u32::from_le_bytes)) + .collect(); + let inside: BTreeMap<(u32, u32), u32> = texture_indices().into_iter().collect(); + for y in 0..GRID[1] { + for x in 0..GRID[0] { + let got = texels[(y * GRID[0] + x) as usize]; + let want = inside.get(&(x, y)).map_or([0; 4], |&i| view_texel(i)); + assert_eq!(got, want, "texel ({x}, {y})"); + } + } +} + +/// A write of texel `(x, y)` stores the view's texel `first + y · row + x`, and nothing past the +/// texture: the texels before the first and between the rows keep their values. +#[test] +fn a_write_stores_its_texel_by_row_and_nothing_else() { + let Some(bitcode) = bitcode() else { return }; + let p = lavapipe(); + let (plan, m) = typed_module_with(&bitcode, "rows_write", &p, &rows_inputs()).expect("module"); + let slot = rows_binding(&m, ImageUsage::Storage); + let value = |x: u32, y: u32| -> [u32; 4] { + std::array::from_fn(|lane| { + (1000.0 + (y * GRID[0] + x) as f32 * 4.0 + lane as f32).to_bits() + }) + }; + let mut input = Vec::new(); + for y in 0..GRID[1] { + for x in 0..GRID[0] { + for lane in value(x, y) { + input.extend(lane.to_le_bytes()); + } + } + } + let res = resources(&plan, &[input, columns()]); + let (_, image) = run(&m, &res, &view(slot)); + let mut want: Vec<[u32; 4]> = (0..rows().elements() as u32).map(view_texel).collect(); + for ((x, y), i) in texture_indices() { + want[i as usize] = value(x, y); + } + assert_eq!(image.texels, want, "the view after the writes"); +} + +/// A kernel that asks the size, reads and writes inverts each texel inside the texture by its +/// row, and nothing else. +#[test] +fn a_read_write_kernel_asks_the_rows_size() { + let Some(bitcode) = bitcode() else { return }; + let p = lavapipe(); + let (plan, m) = typed_module_with(&bitcode, "rows_invert", &p, &rows_inputs()).expect("module"); + let slot = rows_binding(&m, ImageUsage::Storage); + let res = resources(&plan, &[]); + let (_, image) = run(&m, &res, &view(slot)); + let mut want: Vec<[u32; 4]> = (0..rows().elements() as u32).map(view_texel).collect(); + for (_, i) in texture_indices() { + let t = view_texel(i).map(f32::from_bits); + want[i as usize] = [ + (1.0 - t[0]).to_bits(), + (1.0 - t[1]).to_bits(), + (1.0 - t[2]).to_bits(), + t[3].to_bits(), + ]; + } + assert_eq!(image.texels, want, "the view after the inversion"); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 903cfa75a..6b18c247c 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -176,6 +176,7 @@ mod engine_swizzled_storage; mod engine_table_copies; mod engine_tables; mod engine_tessellation; +mod engine_texel_rows; mod engine_texture; mod engine_texture_atomic_unk; mod engine_texture_interp; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 93bb995a8..1788d7e6c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -370,6 +370,11 @@ assoc-const metal2vulkan::bind::TessellationScanModule::RECORDS_BINDING pub cons assoc-const metal2vulkan::bind::TessellationScanModule::SET pub const SET: u32 assoc-const metal2vulkan::bind::TessellationScanModule::STATUS_BINDING pub const STATUS_BINDING: u32 assoc-const metal2vulkan::bind::TessellationScanModule::WORK_BINDING pub const WORK_BINDING: u32 +assoc-const metal2vulkan::bind::TexelRows::FIRST pub const FIRST: usize +assoc-const metal2vulkan::bind::TexelRows::HEIGHT pub const HEIGHT: usize +assoc-const metal2vulkan::bind::TexelRows::ROW pub const ROW: usize +assoc-const metal2vulkan::bind::TexelRows::WIDTH pub const WIDTH: usize +assoc-const metal2vulkan::bind::TexelRows::WORDS pub const WORDS: usize assoc-const metal2vulkan::bind::TiledTexelsModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 assoc-const metal2vulkan::bind::TiledTexelsModule::MAX_LEVELS pub const MAX_LEVELS: u32 assoc-const metal2vulkan::bind::TiledTexelsModule::SET pub const SET: u32 @@ -865,6 +870,11 @@ assoc-const-value metal2vulkan::bind::TessellationScanModule::RECORDS_BINDING 1 assoc-const-value metal2vulkan::bind::TessellationScanModule::SET 0 assoc-const-value metal2vulkan::bind::TessellationScanModule::STATUS_BINDING 2 assoc-const-value metal2vulkan::bind::TessellationScanModule::WORK_BINDING 0 +assoc-const-value metal2vulkan::bind::TexelRows::FIRST 3 +assoc-const-value metal2vulkan::bind::TexelRows::HEIGHT 1 +assoc-const-value metal2vulkan::bind::TexelRows::ROW 2 +assoc-const-value metal2vulkan::bind::TexelRows::WIDTH 0 +assoc-const-value metal2vulkan::bind::TexelRows::WORDS 4 assoc-const-value metal2vulkan::bind::TiledTexelsModule::LOCAL_SIZE 64 assoc-const-value metal2vulkan::bind::TiledTexelsModule::MAX_LEVELS 16 assoc-const-value metal2vulkan::bind::TiledTexelsModule::SET 0 @@ -3644,6 +3654,8 @@ field metal2vulkan-runtime::WorkCounts.submit_stalls_on_work pub submit_stalls_o field metal2vulkan-runtime::WorkCounts.submits_behind_idle_stalls pub submits_behind_idle_stalls: u64 field metal2vulkan-runtime::WorkCounts.sync_files_after_host_copies pub sync_files_after_host_copies: u64 field metal2vulkan-runtime::WorkCounts.sync_files_exported pub sync_files_exported: u64 +field metal2vulkan-runtime::WorkCounts.texel_rows_bound pub texel_rows_bound: u64 +field metal2vulkan-runtime::WorkCounts.texel_rows_textures pub texel_rows_textures: u64 field metal2vulkan-runtime::WorkCounts.texel_shadow_bytes pub texel_shadow_bytes: u64 field metal2vulkan-runtime::WorkCounts.texel_shadow_reads pub texel_shadow_reads: u64 field metal2vulkan-runtime::WorkCounts.texel_shadows_dropped pub texel_shadows_dropped: u64 @@ -4299,6 +4311,7 @@ field metal2vulkan::bind::TextureFacts.pixel_format pub pixel_format: metal::Pix field metal2vulkan::bind::TextureFacts.sample_count pub sample_count: u32 field metal2vulkan::bind::TextureFacts.sparse pub sparse: bool field metal2vulkan::bind::TextureFacts.swizzle pub swizzle: metal::TextureSwizzleChannels +field metal2vulkan::bind::TextureFacts.texel_rows pub texel_rows: Option field metal2vulkan::bind::TextureFacts.texture_type pub texture_type: metal::TextureType field metal2vulkan::bind::TextureFacts.usage pub usage: metal::TextureUsage field metal2vulkan::bind::TextureFacts.ycbcr_in_place pub ycbcr_in_place: Option @@ -4433,6 +4446,7 @@ field metal2vulkan::cache::VariantKey.srgb_textures pub srgb_textures: BTreeSet< field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots: BTreeSet field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet +field metal2vulkan::cache::VariantKey.texel_rows pub texel_rows: BTreeSet field metal2vulkan::cache::VariantKey.viewport_compensation pub viewport_compensation: Option field metal2vulkan::cache::VariantKey.window_depth_varying pub window_depth_varying: bool field metal2vulkan::cache::VariantKey.ycbcr_in_place pub ycbcr_in_place: BTreeSet @@ -5051,6 +5065,7 @@ field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: field metal2vulkan::pipeline::LoweringInputs.storage_view_slots pub storage_view_slots: BTreeSet field metal2vulkan::pipeline::LoweringInputs.swizzled_storage pub swizzled_storage: BTreeSet field metal2vulkan::pipeline::LoweringInputs.tessellation pub tessellation: Option +field metal2vulkan::pipeline::LoweringInputs.texel_rows pub texel_rows: BTreeSet field metal2vulkan::pipeline::LoweringInputs.texture_write_rounding pub texture_write_rounding: metal::TextureWriteRoundingMode field metal2vulkan::pipeline::LoweringInputs.threadgroup_size_matches_tile_size pub threadgroup_size_matches_tile_size: bool field metal2vulkan::pipeline::LoweringInputs.tile_attachments pub tile_attachments: Option> @@ -9642,6 +9657,10 @@ method metal2vulkan::bind::TessellationFactorBuffer::new pub fn new(length: u64, method metal2vulkan::bind::TessellationFactors::new pub fn new(buffer: Option, scale: f32) -> TessellationFactors method metal2vulkan::bind::TessellationRecords::bytes pub fn bytes(&self) -> u64 method metal2vulkan::bind::TessellationScanKernel::max_patch_triangles pub fn max_patch_triangles(&self) -> u32 +method metal2vulkan::bind::TexelRows::elements pub fn elements(&self) -> u64 +method metal2vulkan::bind::TexelRows::new pub fn new(size: [u32; 2], row: u64, first: u64) -> Option +method metal2vulkan::bind::TexelRows::size pub fn size(&self) -> [u32; 2] +method metal2vulkan::bind::TexelRows::words pub fn words(&self) -> [u32; Self::WORDS] method metal2vulkan::bind::TextureFacts::new pub fn new(texture_type: metal::TextureType, pixel_format: metal::PixelFormat) -> Self method metal2vulkan::bind::TextureFacts::offset_base_axes pub fn offset_base_axes(&self) -> u8 method metal2vulkan::bind::TextureFacts::shape pub fn shape(&self) -> TextureShape @@ -10633,6 +10652,7 @@ struct metal2vulkan::bind::TessellationFactors #[cfg_attr(feature = "serde", der struct metal2vulkan::bind::TessellationRecordsFault #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TessellationRecordsFault struct metal2vulkan::bind::TessellationScanKernel #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TessellationScanKernel struct metal2vulkan::bind::TessellationScanModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct TessellationScanModule +struct metal2vulkan::bind::TexelRows #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct TexelRows struct metal2vulkan::bind::TextureFacts #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TextureFacts struct metal2vulkan::bind::TileThreadgroupArgument #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct TileThreadgroupArgument struct metal2vulkan::bind::TileThreadgroupMemory #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct TileThreadgroupMemory @@ -13253,6 +13273,7 @@ variant metal2vulkan::bind::AccessClass::Indirect Indirect variant metal2vulkan::bind::AccessClass::Sampled Sampled variant metal2vulkan::bind::AccessClass::Storage Storage variant metal2vulkan::bind::AccessClass::StorageImage StorageImage +variant metal2vulkan::bind::AccessClass::TexelRows TexelRows variant metal2vulkan::bind::AccessClass::Uniform Uniform variant metal2vulkan::bind::AccessClass::VertexInput VertexInput variant metal2vulkan::bind::AccessClass::YCbCrPlanes YCbCrPlanes @@ -13523,7 +13544,7 @@ variant metal2vulkan::bind::StatusWord::Status Status variant metal2vulkan::bind::TessellationRecords::Exact Exact { records: u32 } variant metal2vulkan::bind::TessellationRecords::Pool Pool variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels } -variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool, ycbcr_planes_sampler: Option } +variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool, ycbcr_planes_sampler: Option, texel_rows: bool } variant metal2vulkan::bind::TileMapError::Region Region { level: u32, slice: u32, origin: [u32; 3], size: [u32; 3] } variant metal2vulkan::bind::TileMapError::Shape Shape variant metal2vulkan::bind::TileMapError::TextureType TextureType { texture_type: TextureType } @@ -13577,6 +13598,7 @@ variant metal2vulkan::bind::WriteSource::TessellationFactors TessellationFactors variant metal2vulkan::bind::WriteSource::TessellationRecords TessellationRecords variant metal2vulkan::bind::WriteSource::TessellationWork TessellationWork variant metal2vulkan::bind::WriteSource::TexelBuffer TexelBuffer { slot: SlotRef, format: vk::Format, window: Window } +variant metal2vulkan::bind::WriteSource::TexelRows TexelRows { slot: SlotRef, format: vk::Format } variant metal2vulkan::bind::WriteSource::Texture Texture { slot: SlotRef, view: ImageViewDesc } variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_index: u32, format: vk::Format, view: StorageAttachmentView, view_alias: Option } variant metal2vulkan::bind::WriteSource::TileMap TileMap { slot: SlotRef } @@ -14982,6 +15004,7 @@ variant metal2vulkan::pipeline::PushField::TessellationChunk TessellationChunk variant metal2vulkan::pipeline::PushField::TessellationFactorInstanceStride TessellationFactorInstanceStride variant metal2vulkan::pipeline::PushField::TessellationFactorOffset TessellationFactorOffset variant metal2vulkan::pipeline::PushField::TessellationFactorScale TessellationFactorScale +variant metal2vulkan::pipeline::PushField::TexelRows TexelRows(SlotRef) variant metal2vulkan::pipeline::PushField::TextureIntegerChannels TextureIntegerChannels(SlotRef) variant metal2vulkan::pipeline::PushField::TextureLevels TextureLevels(SlotRef) variant metal2vulkan::pipeline::PushField::VertexBufferStride VertexBufferStride(u32) @@ -15106,6 +15129,7 @@ variant metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry SynthesizedGeom variant metal2vulkan::pipeline::RuntimeFact::TestedStorageWrites TestedStorageWrites { early_tests: bool, early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelFormat TexelFormat { slot: SlotRef } +variant metal2vulkan::pipeline::RuntimeFact::TexelRows TexelRows { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TextureSwizzle TextureSwizzle { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::ThreadgroupMemoryLength ThreadgroupMemoryLength { index: u32 } variant metal2vulkan::pipeline::RuntimeFact::ThreadsPerThreadgroup ThreadsPerThreadgroup diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index f43cbe5d2..64510ec68 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -750,6 +750,7 @@ surface! { struct YCbCrPlanes N; struct YCbCrInPlace N; struct YCbCrPlanesSampler N; + struct TexelRows N; struct YCbCrConversion N; struct YCbCrCodes N; enum YCbCrOutput N; diff --git a/docs/API.md b/docs/API.md index 5a750b272..929691983 100644 --- a/docs/API.md +++ b/docs/API.md @@ -472,7 +472,18 @@ reason apart (the texel width, `_store_width`), and of them all those whose usag them (`_render_target`) and those a shader writes (`_shader_write`). A shadow is an optimal image of the runtime's own memory, whose texels the encoders copy in from the pages before a use and back (merged back: only the bytes the commands changed) after a write; no image -is bound to the pages, and `Texture::vk_image` gives `None` for it. A texture in place renders and +is bound to the pages, and `Texture::vk_image` gives `None` for it. A shadow whose image the +device refused for its format, features or limits, the bytes' pitch or placement, or the dma-buf +import (not one the policy, a check or a write's width asks for) still has its bytes in place: a +2D texture of one level, slice and sample, of an uncompressed format and no swizzle, whose rows +start on a texel and lie a whole number of texels apart within a buffer that has no read twin, +binds its rows as a texel buffer of the buffer's bytes (the pages, or the buffer's copy of them) +at a slot whose function only reads, writes or asks its size (section 5, +`TextureFacts::texel_rows`), and those commands copy nothing into or out of the shadow +(`WorkCounts::texel_rows_textures`, `texel_rows_bound`); a slot that samples it reads the shadow. +Over a buffer with a read twin, a slot that only reads the texture binds the texture's read twin +where it has one in place, and the shadow otherwise. +A texture in place renders and is written beyond its declared usage, as plain Metal allows, through its usage shadow and an attachment stand-in, whose copies touch its texels alone. `Buffer::texture_placement` and `Buffer::texture_placement_with_iosurface_plane` answer, for the @@ -1408,6 +1419,25 @@ for dependency in &pipeline.dependencies { the image's view with an identically defined conversion, and sizes a pool for the format's `combinedImageSamplerDescriptorCount` descriptors at the binding. Each sample is the device's, at level 0, its conversion and filter of the codes rather than Metal's. +- A 2D texture whose image is a shadow but whose bytes the consumer reads and writes in place + states its rows in its facts (`TextureFacts::texel_rows`, a `TexelRows`: its width, height, the + texels from one row's first to the next's, and its first texel in a texel buffer view of its + bytes; the runtime states one for a shadow over host pages whose image the device refused, not + one its policy asks for). A slot whose function only reads, writes or asks the size of it (no + sample, gather, atomic, read through a sampler, level views, switch at use or residency; + `RuntimeFact::TexelRows`) takes the pipeline's rows variant (`VariantKey::texel_rows`) where + the device views the texture's format as a texel buffer of the slot's kind (uniform where the + slot's declaration only reads, storage otherwise, read and written without a declared format): + the slot binds a texel buffer of the format over the rows' bytes (`WriteSource::TexelRows`, + from the view's first texel through the last row's last; a use of class `AccessClass::TexelRows` + of those bytes), its push field (`PushField::TexelRows`) holds `TexelRows::words`, and the + function addresses texel `(x, y)` at `first + y · row + x`, testing every read and write against + the texture's size itself (a coordinate past the width names the next row's texel in the view): + a read outside is Metal's out-of-bounds texel and a write there is dropped, and a size query + answers the field's size and one level. A texel buffer's texels go through the device's format + conversion as an image's do, so the reads and writes are the image route's, bit for bit (the + runtime's `texel_rows_device` tests compare every `RGBA8Unorm` and `RGBA16Float` code), and no + precision note is recorded. Any other slot, and any texture without the fact, binds the image. - `interface.reaches_command_buffers` and `interface.texture_writing_stages` say, provably, which pipelines may touch an indirect command buffer and which stages may write a texture. `interface.command_writes` (`CommandWrites`) says what its functions may write into the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index d62f317ea..28e5d1f79 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -804,7 +804,7 @@ driver's. Each is open work. and the pages past a no-copy buffer's length are not the buffer's to import. A `BGRA8Unorm` 1024x1014 texture at rows 14592 bytes apart over a no-copy buffer of 3612 pages, which holds 13056 bytes of its last row, is a shadow on the RTX 3090, and in place over a buffer one page - longer. + longer. A slot whose function only reads, writes or asks the size of such a texture (of one level, slice and sample, an uncompressed format and no swizzle) binds its rows in place as a texel buffer of the pages, with no copy (`TextureFacts::texel_rows`, docs/API.md section 5, `WorkCounts::texel_rows_textures`); a slot that samples it reads the shadow. - **On RADV, a texture whose rows lie a number of bytes apart that is no multiple of 256 is a shadow where only an image at that pitch would hold it** (`shadowed-texture`, naming the pitch; `WorkCounts::host_texture_shadows_refused_pitch` over host pages and dma-bufs). RADV lays a @@ -826,7 +826,7 @@ driver's. Each is open work. at rows 16, 32, 64, 112, 208 or 448 bytes apart over a `Shared` buffer are shadows there. The surface or the dma-buf sets the pitch, not the runtime: a consumer that lays out a surface of its own can lay its rows at the alignment - `Device::minimum_linear_texture_alignment_for_pixel_format` answers. + `Device::minimum_linear_texture_alignment_for_pixel_format` answers. A slot whose function only reads, writes or asks the size of such a texture (of one level, slice and sample, an uncompressed format and no swizzle) binds its rows in place as a texel buffer of the pages, with no copy (`TextureFacts::texel_rows`, docs/API.md section 5, `WorkCounts::texel_rows_textures`); a slot that samples it reads the shadow. - **On NVIDIA, a texture that renders over rows with bytes between them in memory only the device's ordered commands write is a shadow** (`shadowed-texture`, `BytesBetweenRows`): a `Private` buffer's, or a `Managed` one's own copy. Such a texture is in place where the @@ -2206,7 +2206,7 @@ driver's. Each is open work. image of the runtime's own memory, copied in before a use and merged back after a write. On RADV, the buffer under it is in place, bound over several dma-bufs (above). A consumer's run on a Radeon 780M (RADV) logged one: a `BGRA8Unorm` 1024x1024 texture at rows 14592 bytes apart over - guest pages in 3648 runs. + guest pages in 3648 runs. A slot whose function only reads, writes or asks the size of such a texture (of one level, slice and sample, an uncompressed format and no swizzle) binds its rows in place as a texel buffer of the pages, with no copy (`TextureFacts::texel_rows`, docs/API.md section 5, `WorkCounts::texel_rows_textures`); a slot that samples it reads the shadow. - **On NVIDIA's proprietary driver, a process that exits with a device live can fault in the driver's own worker thread during its exit handler**: the exit handler of `libEGL_nvidia.so`