diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 11b23d936..9c12504a6 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -520,8 +520,29 @@ that touch blocks first. (`Refusal::TextureRegion`). Not built (`Gap::TextureCopy`): what one `vkCmdCopyImage` in the floor does not make (a multisample texture, a format of depth and stencil both, one pixel format held in two Vulkan formats by the textures' usages, a 1D texture with another type), and one - level and slice of a texture into itself. The slice-and-level and whole-texture forms of `copyFromTexture`, and the - other blit commands, are not built yet. + level and slice of a texture into itself. +- `copy_from_buffer` is `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:` + `sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:` and + `copy_from_texture_to_buffer` is `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:` + `sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:`, a + `BufferLayout` holding the offset and the two strides; their options forms with no option are + the same calls. Each records `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` against the + buffer's own range of its block, one region an image of the region, each at its own offset, so + an image stride of no whole number of rows copies too. The bytes between the region's rows and + images are kept. It records the same two barriers as a copy between textures; the second also + makes a write into the buffer visible to every later command, and a write into a Shared buffer + marks the segment, whose end barrier then reaches the host. A command buffer of one copy into a + Shared buffer has three barriers. +- Refused (`Refusal::BufferCopyLayout`), as Metal's validation stops them: an offset or row + stride of no whole number of a format's texels, rows or images closer than the region's, and a + region past the buffer's end. Metal reads no row stride of a region one row high and no image + stride of a region one image deep, and neither does the runtime. Not built + (`Gap::BufferCopyAlignment`), though Metal takes them: an image's offset in the buffer's block + that is no multiple of a texel block's bytes, or of 4 for a depth or stencil aspect, and a row + stride of no whole number of a compressed format's blocks; also what `replace_region` and + `get_bytes` refuse (`Gap::TextureBytes`, and `Gap::FloatDepthUpload` into a texture). +- The slice-and-level and whole-texture forms of `copyFromTexture`, and the other blit commands, + are not built yet. ## Compute pipeline states diff --git a/crates/metal2vulkan-rt/src/blit.rs b/crates/metal2vulkan-rt/src/blit.rs index 962382781..84b09a2ba 100644 --- a/crates/metal2vulkan-rt/src/blit.rs +++ b/crates/metal2vulkan-rt/src/blit.rs @@ -6,7 +6,13 @@ //! barrier an earlier encoder owed, and the hazard sets start again. The second moves them home //! once the copy has run, its writes visible to every later command. Nothing is copied but the //! region Metal names. +//! +//! A copy between a buffer and a texture is the same: `vkCmdCopyBufferToImage` or +//! `vkCmdCopyImageToBuffer` against the buffer's own range of its block, one region per image of +//! the region, between the same two barriers; the second also makes a write into the buffer +//! visible to every later command, and to the host where the buffer is Shared. +use crate::buffer::Buffer; use crate::command::{Building, CommandBuffer}; use crate::counters::Metric; use crate::error::{Error, Gap, Refusal}; @@ -29,6 +35,21 @@ pub struct TexturePlace { pub origin: [u32; 3], } +/// No Metal counterpart as a type: where a texture's region lies in a buffer, which Metal's +/// copies between a buffer and a texture take as three arguments +/// (`sourceOffset:sourceBytesPerRow:sourceBytesPerImage:`, or the destination's). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct BufferLayout { + /// The region's first byte in the buffer. + pub offset: u64, + /// From one row's first byte to the next's: a row of texels, or of blocks of a compressed + /// format. Unused for a region one row high. + pub bytes_per_row: u64, + /// From one image's first byte to the next's, for a region of a 3D texture more than one image + /// deep; unused for any other. + pub bytes_per_image: u64, +} + /// `MTLBlitCommandEncoder`: records each copy into its command buffer at once. /// /// A copy runs after every earlier command of its command buffer, and every later command runs @@ -152,6 +173,145 @@ impl BlitCommandEncoder { Ok(()) } + /// `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:` + /// `toTexture:destinationSlice:destinationLevel:destinationOrigin:`: `size` texels from + /// `source`, laid out as `layout` says, to `to` in `destination`, one + /// `vkCmdCopyBufferToImage` a 3D region's image. The options form with no option is this + /// call. Sizes of 0 copy as [`copy_from_texture`](Self::copy_from_texture)'s do. The command + /// buffer keeps the texture and the buffer's block until it retires. + /// + /// Err: [`Refusal::OtherDevice`] for another device's buffer or texture; + /// [`Refusal::TextureRegion`]; [`Refusal::BufferCopyLayout`] for a layout Metal's validation + /// stops; [`Gap::BufferCopyAlignment`] for one no copy command in the floor addresses; + /// [`Gap::TextureBytes`]; [`Gap::FloatDepthUpload`]; [`Error::Vulkan`] where the command + /// buffer cannot record. + pub fn copy_from_buffer( + &mut self, + source: &Buffer, + layout: BufferLayout, + size: [u32; 3], + destination: &Texture, + to: TexturePlace, + ) -> Result<(), Error> { + self.buffer_copy(destination, to, size, source, layout, true) + } + + /// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:` + /// `destinationOffset:destinationBytesPerRow:destinationBytesPerImage:`: `size` texels at + /// `from` in `source` to `destination`, laid out as `layout` says, one + /// `vkCmdCopyImageToBuffer` a 3D region's image. The options form with no option is this + /// call. Bytes between the region's rows and images are kept. Sizes of 0 copy as + /// [`copy_from_texture`](Self::copy_from_texture)'s do. The command buffer keeps the texture + /// and the buffer's block until it retires. + /// + /// Err: as [`copy_from_buffer`](Self::copy_from_buffer)'s, but for [`Gap::FloatDepthUpload`]. + pub fn copy_from_texture_to_buffer( + &mut self, + source: &Texture, + from: TexturePlace, + size: [u32; 3], + destination: &Buffer, + layout: BufferLayout, + ) -> Result<(), Error> { + self.buffer_copy(source, from, size, destination, layout, false) + } + + /// A copy of `size` texels at `at` in `texture` from or, not `into_image`, to `buffer`. + fn buffer_copy( + &mut self, + texture: &Texture, + at: TexturePlace, + size: [u32; 3], + buffer: &Buffer, + layout: BufferLayout, + into_image: bool, + ) -> Result<(), Error> { + let building = self.building(); + let core = Arc::clone(building.device.core()); + if !texture.is_of(&core) || !buffer.is_of(&core) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + let lies = Lies { + base: buffer.offset(), + len: buffer.length(), + layout, + }; + let Some(copy) = buffer_copy(&Side::of(texture), at, size, lies, into_image)? else { + return Ok(()); + }; + building.keep_texture(texture); + building.keep(buffer.held_block()); + let command = building.ordered_command()?; + // Marked after `ordered_command`, which may have split the recording at a signal: the + // mark is the copy's own segment's. + if !into_image && buffer.is_shared() { + building.wrote_host(); + } + use vk::AccessFlags2 as Access; + use vk::PipelineStageFlags2 as Stage; + let (layout, access) = match into_image { + true => ( + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + Access::TRANSFER_WRITE, + ), + false => (vk::ImageLayout::TRANSFER_SRC_OPTIMAL, Access::TRANSFER_READ), + }; + let earlier = [memory_barrier(Reach::Commands)]; + let away = [texture.away(©.placed, layout, access)]; + let back = [texture.back(©.placed, layout)]; + let written = [vk::MemoryBarrier2::default() + .src_stage_mask(Stage::COPY) + .src_access_mask(Access::TRANSFER_WRITE) + .dst_stage_mask(Stage::ALL_COMMANDS) + .dst_access_mask(Access::MEMORY_READ | Access::MEMORY_WRITE)]; + let written = match into_image { + true => &written[..0], + false => &written[..], + }; + let device = &core.device; + let vk_buffer = buffer.held_block().memory.buffer; + // SAFETY: the command buffer records outside any render pass and keeps the image and the + // buffer's block until it retires; the subresource is in its home layout between + // commands and in `layout` between the barriers; each region lies in the image and, by + // `buffer_copy`, in the buffer's range of the block, its offset aligned as the command + // requires. + unsafe { + device.cmd_pipeline_barrier2( + command, + &vk::DependencyInfo::default() + .memory_barriers(&earlier) + .image_memory_barriers(&away), + ); + for region in copy.regions() { + match into_image { + true => device.cmd_copy_buffer_to_image( + command, + vk_buffer, + texture.image(), + layout, + &[region], + ), + false => device.cmd_copy_image_to_buffer( + command, + texture.image(), + layout, + vk_buffer, + &[region], + ), + } + } + device.cmd_pipeline_barrier2( + command, + &vk::DependencyInfo::default() + .memory_barriers(written) + .image_memory_barriers(&back), + ); + } + core.counters.count(Metric::Barriers); + core.counters.count(Metric::Barriers); + Ok(()) + } + /// `endEncoding`. Each copy ordered itself, so the encoder owes no barrier. pub fn end_encoding(mut self) { self.end(); @@ -194,6 +354,172 @@ pub(crate) struct ImageCopy { pub(crate) aspect: vk::ImageAspectFlags, } +/// A buffer's side of a copy: its offset in its block, its length, and where the region lies +/// in it. +#[derive(Clone, Copy)] +pub(crate) struct Lies { + pub(crate) base: u64, + pub(crate) len: u64, + pub(crate) layout: BufferLayout, +} + +/// A copy between a buffer and a texture, checked: the texture's region, its aspect, and where +/// each image of it lies in the buffer's block. +pub(crate) struct BufferCopy { + pub(crate) placed: Placed, + pub(crate) aspect: vk::ImageAspectFlags, + /// The first image's first byte in the block. + pub(crate) offset: u64, + /// A row's stride in texels; 0 for a region one row high. + pub(crate) row_length: u32, + pub(crate) bytes_per_image: u64, +} + +impl BufferCopy { + /// One region an image of the texture's region, each with its own offset: a stride of + /// images that is no whole number of rows needs no row count. + pub(crate) fn regions(&self) -> impl Iterator + '_ { + let [x, y, z] = self.placed.origin; + let [width, height, depth] = self.placed.size; + (0..depth).map(move |image| vk::BufferImageCopy { + buffer_offset: self.offset + u64::from(image) * self.bytes_per_image, + buffer_row_length: self.row_length, + buffer_image_height: 0, + image_subresource: self.placed.layers(self.aspect), + image_offset: vk::Offset3D { + x: x as i32, + y: y as i32, + z: (z + image) as i32, + }, + image_extent: vk::Extent3D { + width, + height, + depth: 1, + }, + }) + } +} + +/// Checks a copy of `size` texels at `at` in `texture` and the bytes `lies` names in a buffer, +/// `into_image` for a copy into the texture. `None` where it copies nothing. +/// +/// Metal's validation stops an offset or a row stride of a format of single texels that is no +/// whole number of its texels, rows or images closer than the region's, and a region past the +/// buffer's end ([`Refusal::BufferCopyLayout`]). A copy command in the floor further takes an +/// offset of whole texel blocks, a multiple of 4 for a depth or stencil aspect, for each image, +/// and a row stride of whole blocks ([`Gap::BufferCopyAlignment`]). +/// +/// Err: [`Gap::TextureBytes`]; [`Gap::FloatDepthUpload`]; [`Refusal::TextureRegion`]; +/// [`Refusal::BufferCopyLayout`]; [`Gap::BufferCopyAlignment`]. +pub(crate) fn buffer_copy( + texture: &Side<'_>, + at: TexturePlace, + size: [u32; 3], + lies: Lies, + into_image: bool, +) -> Result, Error> { + let d = texture.descriptor; + let pixel_format = d.pixel_format; + let Some(unit) = texture.unit else { + return Err(Error::Unsupported(Gap::TextureBytes { pixel_format })); + }; + if into_image && unit.float_depth() { + return Err(Error::Unsupported(Gap::FloatDepthUpload { pixel_format })); + } + let mut size = size; + if size[1] == 0 + && matches!( + d.texture_type, + TextureType::Type1D | TextureType::Type1DArray + ) + { + size[1] = 1; + } + if size[2] == 0 && d.texture_type != TextureType::Type3D { + size[2] = 1; + } + let region = Region { + origin: at.origin, + size, + }; + let Some(placed) = place(d, unit.block, region, at.level, at.slice)? else { + return Ok(None); + }; + let Lies { base, len, layout } = lies; + let BufferLayout { + offset, + bytes_per_row, + bytes_per_image, + } = layout; + let refused = || { + Error::Refused(Refusal::BufferCopyLayout { + offset, + bytes_per_row, + bytes_per_image, + len, + }) + }; + let [bw, bh] = unit.block; + let bytes = u64::from(unit.bytes); + let row = u64::from(placed.size[0].div_ceil(bw)) * bytes; + let rows = u64::from(placed.size[1].div_ceil(bh)); + let images = u64::from(placed.size[2]); + let single = unit.block == [1, 1]; + if single && (offset % bytes != 0 || (rows > 1 && bytes_per_row % bytes != 0)) { + return Err(refused()); + } + let image_span = match rows { + 1 => Some(row), + _ if bytes_per_row < row => return Err(refused()), + _ => (rows - 1) + .checked_mul(bytes_per_row) + .and_then(|span| span.checked_add(row)), + }; + let span = match (images, image_span) { + (_, None) => None, + (1, span) => span, + (_, Some(image_span)) if bytes_per_image < image_span => return Err(refused()), + (_, Some(image_span)) => (images - 1) + .checked_mul(bytes_per_image) + .and_then(|span| span.checked_add(image_span)), + }; + if span + .and_then(|span| span.checked_add(offset)) + .is_none_or(|end| end > len) + { + return Err(refused()); + } + let align = match unit.aspect { + vk::ImageAspectFlags::COLOR => bytes, + _ => 4, + }; + let start = base + offset; + let row_length = match rows { + 1 => Some(0), + _ => u32::try_from(bytes_per_row / bytes) + .ok() + .and_then(|elements| elements.checked_mul(bw)), + }; + let aligned = start % align == 0 + && (rows == 1 || bytes_per_row % bytes == 0) + && (images == 1 || bytes_per_image % align == 0); + let (Some(row_length), true) = (row_length, aligned) else { + return Err(Error::Unsupported(Gap::BufferCopyAlignment { + pixel_format, + offset, + bytes_per_row, + bytes_per_image, + })); + }; + Ok(Some(BufferCopy { + placed, + aspect: unit.aspect, + offset: start, + row_length, + bytes_per_image, + })) +} + /// Checks a copy of `size` texels from `from` in `source` to `to` in `destination`, `same` where /// they are one texture. `None` where it copies nothing. /// diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index fa2efa787..84fc093fb 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -342,6 +342,32 @@ pub enum Refusal { /// The bytes given. len: u64, }, + /// [`BlitCommandEncoder::copy_from_buffer`](crate::BlitCommandEncoder::copy_from_buffer) or + /// [`BlitCommandEncoder::copy_from_texture_to_buffer`](crate::BlitCommandEncoder::copy_from_texture_to_buffer) + /// whose offset or row stride, for a format of single texels, is no whole number of its + /// texels; whose rows or images are closer than the region's; or whose region runs past the + /// buffer's end. A row stride of a region one row high and an image stride of one one image + /// deep are not read. + /// + /// Basis: metal-measured (an Apple M3 Max, macOS 27.0.1, probe `blit_buffer_copy_rules.m` in + /// the conformance crate, jobs m3-max-43541 and m3-max-43545: Metal's validation layer stops an + /// RGBA8Unorm offset of 2, `sourceOffset (2) must be a multiple of 4 bytes`, a row stride of + /// 18, `sourceBytesPerRow (18) must be a multiple of 4 bytes`, and the same of a copy into a + /// buffer, a row stride of 12 for rows of 16 bytes, an image stride of 12 for images of 16, + /// and a region 16 bytes past the buffer's end, `totalBytesUsed(4112) must be <= [sourceBuffer + /// length](4096)`; it takes an R8Unorm offset of 2, a row stride of 0 for one row, image + /// strides of no whole number of rows, and an image stride on a 2D texture and on a slice of a + /// 1D array). + BufferCopyLayout { + /// The region's first byte in the buffer. + offset: u64, + /// The bytes from one row's start to the next's. + bytes_per_row: u64, + /// The bytes from one image's start to the next's. + bytes_per_image: u64, + /// The buffer's length. + len: u64, + }, /// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture) /// between textures of two pixel formats, or of two sample counts. /// @@ -476,18 +502,20 @@ pub enum Gap { /// Basis: ours (the translator's identity domains do not filter bicubically, and Vulkan's /// cubic filter is not Metal's). CubicSampler, - /// [`Texture::replace_region`](crate::Texture::replace_region) or - /// [`Texture::get_bytes`](crate::Texture::get_bytes) of a texture whose image is no plain - /// copy of Metal's bytes in one aspect: a format of depth and stencil both, or a multisample - /// texture. + /// [`Texture::replace_region`](crate::Texture::replace_region), + /// [`Texture::get_bytes`](crate::Texture::get_bytes) or a blit copy between a buffer and a + /// texture ([`BlitCommandEncoder::copy_from_buffer`](crate::BlitCommandEncoder::copy_from_buffer)) + /// of a texture whose image is no plain copy of Metal's bytes in one aspect: a format of depth + /// and stencil both, or a multisample texture. /// /// Basis: ours (no copy between such an image and bytes is built). TextureBytes { /// The texture's pixel format. pixel_format: PixelFormat, }, - /// [`Texture::replace_region`](crate::Texture::replace_region) into a 32-bit float depth - /// (`Depth32Float`). Metal keeps any `float` there; Vulkan copies no depth outside `[0, 1]` + /// [`Texture::replace_region`](crate::Texture::replace_region) or + /// [`BlitCommandEncoder::copy_from_buffer`](crate::BlitCommandEncoder::copy_from_buffer) into a + /// 32-bit float depth (`Depth32Float`). Metal keeps any `float` there; Vulkan copies no depth outside `[0, 1]` /// into a depth aspect without `VK_EXT_depth_range_unrestricted`, which the floor does not /// require (the Intel devices measured lack it), and no recorded stream uploads one. /// @@ -522,6 +550,25 @@ pub enum Gap { /// The texture's pixel format. pixel_format: PixelFormat, }, + /// [`BlitCommandEncoder::copy_from_buffer`](crate::BlitCommandEncoder::copy_from_buffer) or + /// [`BlitCommandEncoder::copy_from_texture_to_buffer`](crate::BlitCommandEncoder::copy_from_texture_to_buffer) + /// whose bytes no copy command in the floor addresses, though Metal takes them: an image's + /// offset in the buffer's block that is no multiple of a texel block's bytes (of 4 for a depth + /// or stencil aspect: a 16-bit depth at an offset of 2), or a row stride of no whole number of + /// a compressed format's blocks. + /// + /// Basis: ours (Vulkan 1.3 places a copy's rows in a buffer by a count of texels from an + /// aligned offset; each is built when a replay stream makes one). + BufferCopyAlignment { + /// The texture's pixel format. + pixel_format: PixelFormat, + /// The region's first byte in the buffer. + offset: u64, + /// The bytes from one row's start to the next's. + bytes_per_row: u64, + /// The bytes from one image's start to the next's. + bytes_per_image: u64, + }, } /// A limit a call ran into, with what it was asked. @@ -796,6 +843,15 @@ impl fmt::Display for Refusal { f, "rows {bytes_per_row} and images {bytes_per_image} bytes apart in {len} bytes do not hold the region" ), + Refusal::BufferCopyLayout { + offset, + bytes_per_row, + bytes_per_image, + len, + } => write!( + f, + "a region at {offset} with rows {bytes_per_row} and images {bytes_per_image} bytes apart is no layout Metal takes in a buffer of {len} bytes" + ), Refusal::TextureCopyMismatch { source, destination, @@ -869,6 +925,15 @@ impl fmt::Display for Gap { f, "a heap texture of {pixel_format:?} is not placed in this heap on this device" ), + Gap::BufferCopyAlignment { + pixel_format, + offset, + bytes_per_row, + bytes_per_image, + } => write!( + f, + "a copy of {pixel_format:?} at {offset} with rows {bytes_per_row} and images {bytes_per_image} bytes apart in a buffer is not built" + ), } } } diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index 3179c8de0..0feb221eb 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -41,7 +41,7 @@ mod texture; mod times; pub use arrays::{IndexClass, IndexGrant, ResourceId}; -pub use blit::{BlitCommandEncoder, TexturePlace}; +pub use blit::{BlitCommandEncoder, BufferLayout, TexturePlace}; pub use buffer::{Buffer, MAX_BUFFER_LENGTH}; pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus}; pub use counters::{Counters, Gauges, Metrics}; diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs index d379fdfa7..23c0fc19e 100644 --- a/crates/metal2vulkan-rt/src/tests/blit.rs +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -1,4 +1,4 @@ -//! Blit copies between textures. +//! Blit copies between textures, and between buffers and textures. //! //! - The rules: a texture copies into one of its own pixel format and sample count; two formats //! or two sample counts are `Refusal::TextureCopyMismatch`, as Metal's validation refuses them; @@ -17,8 +17,18 @@ //! must leave are plain Metal's: their FNV-1a 64 hashes are those of probe `blit_copy_layouts.m` //! in the conformance crate (an Apple M3 Max, macOS 27.0.1, job m3-max-43464, plain and under //! the validation layer). +//! - Between a buffer and a texture: each image of the region lies at its own offset, its rows a +//! count of texels apart; what Metal's validation stops is `Refusal::BufferCopyLayout`, and an +//! offset or row stride a copy command cannot address `Gap::BufferCopyAlignment`. Under a device +//! cfg: bytes from a buffer land in a mipmap level, a slice of a 1D array and BC1 blocks, and a +//! slice's and a 3D region's bytes land in buffers at padded strides, everything around each +//! region kept and each result plain Metal's (job m3-max-43555); one copy into a Shared buffer +//! alone is one submission and three barriers, the segment's end reaching the host, and copies +//! no byte of the runtime's own. -use crate::blit::{texture_copy, ImageCopy, Side, TexturePlace}; +use crate::blit::{ + buffer_copy, texture_copy, BufferCopy, BufferLayout, ImageCopy, Lies, Side, TexturePlace, +}; use crate::error::{Error, Gap, Refusal}; use crate::texture::{CopyUnit, Placed}; use crate::{PixelFormat, TextureDescriptor, TextureType}; @@ -77,7 +87,7 @@ fn copied(result: Result, Error>) -> ImageCopy { } } -fn refused(result: Result, Error>) -> Refusal { +fn refused(result: Result, Error>) -> Refusal { match result { Err(Error::Refused(refusal)) => refusal, Err(other) => panic!("not a refusal: {other}"), @@ -85,7 +95,7 @@ fn refused(result: Result, Error>) -> Refusal { } } -fn gap(result: Result, Error>) -> Gap { +fn gap(result: Result, Error>) -> Gap { match result { Err(Error::Unsupported(gap)) => gap, Err(other) => panic!("not a gap: {other}"), @@ -384,12 +394,320 @@ fn what_metal_refuses_is_refused_and_what_one_command_does_not_make_is_a_gap() { )); } +/// A buffer at `base` in its block, `len` bytes long, and a region in it at `offset`, rows +/// `bytes_per_row` and images `bytes_per_image` apart. +fn lies(base: u64, len: u64, offset: u64, bytes_per_row: u64, bytes_per_image: u64) -> Lies { + Lies { + base, + len, + layout: BufferLayout { + offset, + bytes_per_row, + bytes_per_image, + }, + } +} + +/// The buffer copy `result` checked, which copies something. +fn buffer_copied(result: Result, Error>) -> BufferCopy { + match result { + Ok(Some(copy)) => copy, + Ok(None) => panic!("it copies nothing"), + Err(error) => panic!("{error}"), + } +} + +/// Each region's offset in the block, image offset and extent. +fn regions(copy: &BufferCopy) -> Vec<(u64, [i32; 3], [u32; 3])> { + copy.regions() + .map(|region| { + let (o, e) = (region.image_offset, region.image_extent); + ( + region.buffer_offset, + [o.x, o.y, o.z], + [e.width, e.height, e.depth], + ) + }) + .collect() +} + +#[test] +fn a_buffer_copy_places_each_image_at_its_own_offset() { + let mut rgba = descriptor(TextureType::Type2D, PixelFormat::RGBA8Unorm, [13, 7, 1]); + rgba.mipmap_level_count = 3; + let rgba = side(&rgba, vk::Format::R8G8B8A8_UNORM, color(4)); + // Rows 32 bytes apart are 8 texels apart, from the buffer's offset in its block on. + let copy = buffer_copied(buffer_copy( + &rgba, + at(0, 1, [1, 1, 0]), + [4, 2, 1], + lies(256, 256, 16, 32, 0), + true, + )); + assert_eq!(copy.placed, placed(1, 0, [1, 1, 0], [4, 2, 1])); + assert_eq!(copy.row_length, 8); + assert_eq!(regions(©), [(272, [1, 1, 0], [4, 2, 1])]); + // One row reads no row stride. + let row = buffer_copied(buffer_copy( + &rgba, + at(0, 0, [0; 3]), + [4, 1, 1], + lies(0, 256, 0, 0, 0), + false, + )); + assert_eq!(row.row_length, 0); + // A 3D region's images each at their own offset, 24 bytes apart: no whole number of rows. + let volume = descriptor(TextureType::Type3D, PixelFormat::R8Unorm, [4, 4, 3]); + let volume = side(&volume, vk::Format::R8_UNORM, color(1)); + let copy = buffer_copied(buffer_copy( + &volume, + at(0, 0, [1, 0, 0]), + [3, 4, 3], + lies(0, 128, 8, 5, 24), + false, + )); + assert_eq!(copy.row_length, 5); + assert_eq!( + regions(©), + [ + (8, [1, 0, 0], [3, 4, 1]), + (32, [1, 0, 1], [3, 4, 1]), + (56, [1, 0, 2], [3, 4, 1]) + ] + ); + // A 1D array's slice, a height and depth of 0 one texel; its image stride is not read. + let mut line = descriptor(TextureType::Type1DArray, PixelFormat::R32Float, [16, 1, 1]); + line.array_length = 2; + let line = side(&line, vk::Format::R32_SFLOAT, color(4)); + let copy = buffer_copied(buffer_copy( + &line, + at(1, 0, [3, 0, 0]), + [8, 0, 0], + lies(0, 256, 16, 32, 40), + true, + )); + assert_eq!(copy.placed, placed(0, 1, [3, 0, 0], [8, 1, 1])); + assert_eq!(regions(©), [(16, [3, 0, 0], [8, 1, 1])]); + // BC1 blocks: a row of blocks is 8 bytes. + let bc1 = descriptor(TextureType::Type2D, PixelFormat::BC1RGBA, [8, 8, 1]); + let block = Some(CopyUnit { + aspect: vk::ImageAspectFlags::COLOR, + bytes: 8, + block: [4, 4], + }); + let bc1 = side(&bc1, vk::Format::BC1_RGBA_UNORM_BLOCK, block); + let copy = buffer_copied(buffer_copy( + &bc1, + at(0, 0, [0; 3]), + [8, 8, 1], + lies(0, 64, 8, 24, 0), + true, + )); + assert_eq!(copy.row_length, 12); + assert!(matches!( + buffer_copy( + &bc1, + at(0, 0, [0; 3]), + [0, 8, 1], + lies(0, 64, 0, 16, 0), + true + ), + Ok(None) + )); +} + +#[test] +fn a_layout_metal_stops_is_refused_and_one_a_copy_command_cannot_address_is_a_gap() { + let rgba = descriptor(TextureType::Type2D, PixelFormat::RGBA8Unorm, [8, 8, 1]); + let rgba = side(&rgba, vk::Format::R8G8B8A8_UNORM, color(4)); + let two_rows = + |lies, into_image| buffer_copy(&rgba, at(0, 0, [0; 3]), [4, 2, 1], lies, into_image); + let layout = |offset, bytes_per_row, bytes_per_image, len| Refusal::BufferCopyLayout { + offset, + bytes_per_row, + bytes_per_image, + len, + }; + // Metal's validation: an offset or a row stride of no whole texels, rows closer than the + // region's, and a region past the buffer's end. + assert_eq!( + refused(two_rows(lies(0, 4096, 2, 16, 0), true)), + layout(2, 16, 0, 4096) + ); + assert_eq!( + refused(two_rows(lies(0, 4096, 0, 18, 0), false)), + layout(0, 18, 0, 4096) + ); + assert_eq!( + refused(two_rows(lies(0, 4096, 0, 12, 0), true)), + layout(0, 12, 0, 4096) + ); + assert_eq!( + refused(two_rows(lies(0, 4096, 4080, 16, 0), true)), + layout(4080, 16, 0, 4096) + ); + assert!(two_rows(lies(0, 4096, 4064, 16, 0), true).is_ok()); + let volume = descriptor(TextureType::Type3D, PixelFormat::R8Unorm, [4, 4, 2]); + let volume = side(&volume, vk::Format::R8_UNORM, color(1)); + let deep = |bytes_per_image| { + buffer_copy( + &volume, + at(0, 0, [0; 3]), + [4, 4, 2], + lies(0, 4096, 0, 4, bytes_per_image), + true, + ) + }; + assert_eq!(refused(deep(12)), layout(0, 4, 12, 4096)); + assert!(deep(18).is_ok()); + // Metal takes an R8Unorm offset of 2. + let r8 = descriptor(TextureType::Type2D, PixelFormat::R8Unorm, [8, 8, 1]); + let r8 = side(&r8, vk::Format::R8_UNORM, color(1)); + assert!(buffer_copy( + &r8, + at(0, 0, [0; 3]), + [4, 2, 1], + lies(0, 4096, 2, 8, 0), + true + ) + .is_ok()); + // A copy command: a depth offset a multiple of 4, every image's offset whole texel blocks, + // rows whole blocks. + let alignment = + |pixel_format, offset, bytes_per_row, bytes_per_image| Gap::BufferCopyAlignment { + pixel_format, + offset, + bytes_per_row, + bytes_per_image, + }; + let depth = descriptor(TextureType::Type2D, PixelFormat::Depth16Unorm, [8, 8, 1]); + let unit = |aspect, bytes, block| { + Some(CopyUnit { + aspect, + bytes, + block, + }) + }; + let depth = side( + &depth, + vk::Format::D16_UNORM, + unit(vk::ImageAspectFlags::DEPTH, 2, [1, 1]), + ); + let out_of_depth = |offset| { + buffer_copy( + &depth, + at(0, 0, [0; 3]), + [4, 2, 1], + lies(0, 4096, offset, 8, 0), + false, + ) + }; + assert_eq!( + gap(out_of_depth(2)), + alignment(PixelFormat::Depth16Unorm, 2, 8, 0) + ); + assert!(out_of_depth(4).is_ok()); + let bc1 = descriptor(TextureType::Type2D, PixelFormat::BC1RGBA, [8, 8, 1]); + let bc1 = side( + &bc1, + vk::Format::BC1_RGBA_UNORM_BLOCK, + unit(vk::ImageAspectFlags::COLOR, 8, [4, 4]), + ); + let blocks = |offset, bytes_per_row| { + buffer_copy( + &bc1, + at(0, 0, [0; 3]), + [8, 8, 1], + lies(0, 4096, offset, bytes_per_row, 0), + true, + ) + }; + assert_eq!( + gap(blocks(0, 20)), + alignment(PixelFormat::BC1RGBA, 0, 20, 0) + ); + assert_eq!( + gap(blocks(4, 16)), + alignment(PixelFormat::BC1RGBA, 4, 16, 0) + ); + // The buffer's own offset in its block counts. + assert_eq!( + gap(two_rows(lies(2, 4096, 0, 16, 0), true)), + alignment(PixelFormat::RGBA8Unorm, 0, 16, 0) + ); + let words = descriptor(TextureType::Type3D, PixelFormat::RGBA8Unorm, [4, 4, 2]); + let words = side(&words, vk::Format::R8G8B8A8_UNORM, color(4)); + assert_eq!( + gap(buffer_copy( + &words, + at(0, 0, [0; 3]), + [4, 4, 2], + lies(0, 4096, 0, 16, 66), + true + )), + alignment(PixelFormat::RGBA8Unorm, 0, 16, 66) + ); + // No plain copy of the image's bytes, and no upload of a 32-bit float depth. + let mut msaa = descriptor( + TextureType::Type2DMultisample, + PixelFormat::RGBA8Unorm, + [8, 8, 1], + ); + msaa.sample_count = 4; + let msaa = side(&msaa, vk::Format::R8G8B8A8_UNORM, None); + assert_eq!( + gap(buffer_copy( + &msaa, + at(0, 0, [0; 3]), + [4, 2, 1], + lies(0, 4096, 0, 16, 0), + false + )), + Gap::TextureBytes { + pixel_format: PixelFormat::RGBA8Unorm + } + ); + let float = descriptor(TextureType::Type2D, PixelFormat::Depth32Float, [8, 8, 1]); + let float = side( + &float, + vk::Format::D32_SFLOAT, + unit(vk::ImageAspectFlags::DEPTH, 4, [1, 1]), + ); + let float_copy = |into_image| { + buffer_copy( + &float, + at(0, 0, [0; 3]), + [4, 2, 1], + lies(0, 4096, 0, 16, 0), + into_image, + ) + }; + assert_eq!( + gap(float_copy(true)), + Gap::FloatDepthUpload { + pixel_format: PixelFormat::Depth32Float + } + ); + assert!(float_copy(false).is_ok()); + assert!(matches!( + refused(buffer_copy( + &rgba, + at(1, 0, [0; 3]), + [4, 2, 1], + lies(0, 4096, 0, 16, 0), + true + )), + Refusal::TextureRegion { level: 0, slice: 1 } + )); +} + #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { use crate::tests::command::on_device::{each_device, finished}; use crate::{ - CommandBuffer, Device, DispatchType, Error, Gap, IndexClass, PixelFormat, Refusal, Region, - StorageMode, Texture, TextureDescriptor, TexturePlace, TextureType, TextureUsage, + Buffer, BufferLayout, CommandBuffer, Device, DispatchType, Error, Gap, IndexClass, + MemoryClass, PixelFormat, Refusal, Region, StorageMode, Texture, TextureDescriptor, + TexturePlace, TextureType, TextureUsage, }; /// A byte pattern of `len` bytes, different at every offset of one call and between calls. @@ -814,4 +1132,262 @@ mod on_device { )); }); } + + /// Writes `bytes` over the start of a Shared buffer. + fn write(buffer: &Buffer, bytes: &[u8]) { + let contents = buffer.contents().expect("a Shared buffer"); + assert!(bytes.len() as u64 <= buffer.length()); + // SAFETY: the range lies in the buffer, which is alive, and no GPU work uses it. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + } + + /// A Shared buffer's bytes, as the host reads them. + fn read(buffer: &Buffer) -> Vec { + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: the buffer is alive, `length` bytes long, and no GPU work uses it. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() + } + + /// `into` with `rows` (an offset in `from`, one in `into`) of `len` bytes each copied over. + fn moved( + mut into: Vec, + from: &[u8], + rows: impl Iterator, + len: usize, + ) -> Vec { + for (from_at, into_at) in rows { + into[into_at..into_at + len].copy_from_slice(&from[from_at..from_at + len]); + } + into + } + + /// Bytes from buffers land in a mipmap level, a 1D array's slice and BC1 blocks, and a + /// slice's and a 3D region's bytes land in buffers at padded strides, as plain Metal leaves + /// them; one copy into a Shared buffer alone costs one submission and three barriers, the + /// segment's end reaching the host, and copies nothing of the runtime's own. + #[test] + fn every_device_copies_between_buffers_and_textures() { + each_device("blit_buffers", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 16) + .expect("a grant"); + device + .grant_indices(IndexClass::StorageTexture, 1, 16) + .expect("a grant"); + let read_usage = TextureUsage::SHADER_READ; + let make = |texture_type, format, extent, index| { + texture(&device, texture_type, format, extent, read_usage, index) + .unwrap_or_else(|error| panic!("{name}: {format:?}: {error}")) + }; + let levels = make( + TextureType::Type2D, + PixelFormat::RGBA8Unorm, + [13, 7, 1], + 4096, + ); + let slices = make( + TextureType::Type2DArray, + PixelFormat::RGBA8Unorm, + [8, 8, 1], + 4097, + ); + let volume = make(TextureType::Type3D, PixelFormat::R8Unorm, [4, 4, 3], 4098); + let mut line = + TextureDescriptor::new(TextureType::Type1DArray, PixelFormat::R32Float, 16, 1); + line.array_length = 2; + line.usage = read_usage; + line.storage_mode = StorageMode::Shared; + let lines = (device.new_texture(&line, Some(4099))) + .unwrap_or_else(|error| panic!("{name}: a 1D array: {error}")); + let level = |texture, slice, level, unit| Level { + texture, + slice, + level, + unit, + block: 1, + }; + let (level1, slice2) = (level(&levels, 0, 1, 4), level(&slices, 2, 0, 4)); + let (volume0, line1) = (level(&volume, 0, 0, 1), level(&lines, 1, 0, 4)); + let level_before = level1.write(12); + let slice_bytes = slice2.write(13); + let volume_bytes = volume0.write(15); + let line_before = line1.write(19); + let block = (device.take_block(MemoryClass::Shared, 4096)) + .expect("a Shared block") + .id; + let mut next = 0; + let mut buffer = |len: u64, seed: u8| { + let buffer = (device.new_buffer(block, next, len, true)).expect("a buffer"); + next += len.next_multiple_of(256); + let bytes = pattern(len as usize, seed); + write(&buffer, &bytes); + (buffer, bytes) + }; + let (into_level, level_source) = buffer(256, 11); + let (from_slice, slice_before) = buffer(1024, 14); + let (from_volume, volume_before) = buffer(128, 16); + let (into_line, line_source) = buffer(256, 18); + let (into_blocks, block_source) = buffer(64, 17); + let layout = |offset, bytes_per_row, bytes_per_image| BufferLayout { + offset, + bytes_per_row, + bytes_per_image, + }; + let place = |slice, level, origin| TexturePlace { + slice, + level, + origin, + }; + let queue = device.new_command_queue(4).expect("a queue"); + let first = queue.command_buffer().expect("a command buffer"); + first.commit().expect("a commit"); + finished(name, &first); + + // A slice's region into a buffer at 64, rows 48 apart, alone. + let counters = device.counters(); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + encoder + .copy_from_texture_to_buffer( + &slices, + place(2, 0, [2, 3, 0]), + [5, 4, 1], + &from_slice, + layout(64, 48, 0), + ) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.bytes_copied - before.bytes_copied, + after.passes - before.passes, + ), + (1, 3, 0, 1), + "{name}: submissions, barriers, bytes copied, passes" + ); + let rows = (0..4).map(|y| (((3 + y) * 8 + 2) * 4, 64 + y * 48)); + assert_eq!( + read(&from_slice), + metal( + moved(slice_before, &slice_bytes, rows, 20), + 0x186e_870a_23ed_18a5 + ), + "{name}: a slice into a buffer" + ); + + // Into a level at 16, rows 32 apart; a 3D region out at 8, rows 5 and images 24 + // apart; into a 1D array's slice; and BC1 blocks where the device makes them. + let bc1 = texture( + &device, + TextureType::Type2D, + PixelFormat::BC1RGBA, + [8, 8, 1], + read_usage, + 4100, + ); + let bc1 = match bc1 { + Ok(texture) => Some(texture), + Err(Error::Unsupported(Gap::TextureFormat { .. })) => { + println!("{name}: no BC1 texture on this device"); + None + } + Err(error) => panic!("{name}: BC1: {error}"), + }; + let blocks0 = bc1.as_ref().map(|texture| Level { + texture, + slice: 0, + level: 0, + unit: 8, + block: 4, + }); + let blocks_before = blocks0.as_ref().map(|level| level.write(20)); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + let copied = [ + encoder.copy_from_buffer( + &into_level, + layout(16, 32, 0), + [4, 2, 1], + &levels, + place(0, 1, [1, 1, 0]), + ), + encoder.copy_from_texture_to_buffer( + &volume, + place(0, 0, [1, 0, 0]), + [3, 4, 3], + &from_volume, + layout(8, 5, 24), + ), + encoder.copy_from_buffer( + &into_line, + layout(16, 32, 40), + [8, 1, 1], + &lines, + place(1, 0, [3, 0, 0]), + ), + ]; + for result in copied { + result.unwrap_or_else(|error| panic!("{name}: {error}")); + } + if let Some(bc1) = &bc1 { + encoder + .copy_from_buffer( + &into_blocks, + layout(8, 16, 0), + [4, 4, 1], + bc1, + place(0, 0, [4, 4, 0]), + ) + .unwrap_or_else(|error| panic!("{name}: BC1: {error}")); + } + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let rows = (0..2).map(|y| (16 + y * 32, ((1 + y) * 6 + 1) * 4)); + assert_eq!( + level1.read(), + metal( + moved(level_before, &level_source, rows, 16), + 0xa5b4_4bf7_f3be_f955 + ), + "{name}: a buffer into a level" + ); + let rows = + (0..3).flat_map(|z| (0..4).map(move |y| (z * 16 + y * 4 + 1, 8 + z * 24 + y * 5))); + assert_eq!( + read(&from_volume), + metal( + moved(volume_before, &volume_bytes, rows, 3), + 0xf57f_e637_5f8f_f12d + ), + "{name}: a 3D region into a buffer" + ); + assert_eq!( + line1.read(), + metal( + moved(line_before, &line_source, [(16, 12)].into_iter(), 32), + 0x8ec4_0174_4810_bfc5 + ), + "{name}: a buffer into a 1D array's slice" + ); + if let (Some(blocks0), Some(blocks_before)) = (blocks0, blocks_before) { + assert_eq!( + blocks0.read(), + metal( + moved(blocks_before, &block_source, [(8, 24)].into_iter(), 8), + 0x2be2_b29b_0bcd_00a5 + ), + "{name}: BC1 blocks from a buffer" + ); + } + }); + } } diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 3d4dec1bc..8e79d0bac 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -271,7 +271,7 @@ pub(crate) struct CopyUnit { impl CopyUnit { /// Whether the unit is a 32-bit float depth, which no upload takes /// ([`Gap::FloatDepthUpload`]). - fn float_depth(&self) -> bool { + pub(crate) fn float_depth(&self) -> bool { self.aspect == vk::ImageAspectFlags::DEPTH && self.bytes == 4 } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f095a4536..eed58f865 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2237,6 +2237,9 @@ field metal2vulkan-rt::BlockInfo.len pub len: u64 field metal2vulkan-rt::BytesPlace.bytes_per_image pub bytes_per_image: u64 field metal2vulkan-rt::BytesPlace.bytes_per_row pub bytes_per_row: u64 field metal2vulkan-rt::BytesPlace.offset pub offset: u64 +field metal2vulkan-rt::BufferLayout.bytes_per_image pub bytes_per_image: u64 +field metal2vulkan-rt::BufferLayout.bytes_per_row pub bytes_per_row: u64 +field metal2vulkan-rt::BufferLayout.offset pub offset: u64 field metal2vulkan-rt::ComputePipelineDescriptor.buffers pub buffers: BTreeMap field metal2vulkan-rt::ComputePipelineDescriptor.kernel pub kernel: StageSource field metal2vulkan-rt::ComputePipelineDescriptor.max_call_stack_depth pub max_call_stack_depth: u32 @@ -9233,7 +9236,9 @@ method metal2vulkan-air::tensor_ops::OperandForm::is_cooperative pub const fn is method metal2vulkan-air::tensor_ops::OperandIndex::from_raw pub fn from_raw(raw: u64) -> Option method metal2vulkan-air::tensor_ops::RunForm::arity pub fn arity(&self) -> usize method metal2vulkan-air::tensor_ops::RunForm::operand_args pub fn operand_args(&self) -> [usize; 3] +method metal2vulkan-rt::BlitCommandEncoder::copy_from_buffer pub fn copy_from_buffer(&mut self, source: &Buffer, layout: BufferLayout, size: [u32; 3], destination: &Texture, to: TexturePlace) -> Result<(), Error> method metal2vulkan-rt::BlitCommandEncoder::copy_from_texture pub fn copy_from_texture(&mut self, source: &Texture, from: TexturePlace, size: [u32; 3], destination: &Texture, to: TexturePlace) -> Result<(), Error> +method metal2vulkan-rt::BlitCommandEncoder::copy_from_texture_to_buffer pub fn copy_from_texture_to_buffer(&mut self, source: &Texture, from: TexturePlace, size: [u32; 3], destination: &Buffer, layout: BufferLayout) -> Result<(), Error> method metal2vulkan-rt::BlitCommandEncoder::end_encoding pub fn end_encoding(mut self) method metal2vulkan-rt::BlockId::get pub fn get(self) -> u32 method metal2vulkan-rt::Buffer::block pub fn block(&self) -> BlockId @@ -11379,6 +11384,7 @@ struct metal2vulkan-rt::BlockId #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash struct metal2vulkan-rt::BlockInfo #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct BlockInfo struct metal2vulkan-rt::Buffer #[derive(Clone)] pub struct Buffer struct metal2vulkan-rt::BytesPlace #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct BytesPlace +struct metal2vulkan-rt::BufferLayout #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct BufferLayout struct metal2vulkan-rt::CommandBuffer #[derive(Clone)] pub struct CommandBuffer struct metal2vulkan-rt::CommandQueue #[derive(Clone)] pub struct CommandQueue struct metal2vulkan-rt::ComputeCommandEncoder pub struct ComputeCommandEncoder @@ -13297,6 +13303,7 @@ variant metal2vulkan-rt::Error::Thread Thread(io::Error) variant metal2vulkan-rt::Error::Translation Translation(metal2vulkan::error::Error) variant metal2vulkan-rt::Error::Unsupported Unsupported(Gap) variant metal2vulkan-rt::Error::Vulkan Vulkan { call: &'static str, result: vk::Result } +variant metal2vulkan-rt::Gap::BufferCopyAlignment BufferCopyAlignment { pixel_format: PixelFormat, offset: u64, bytes_per_row: u64, bytes_per_image: u64 } variant metal2vulkan-rt::Gap::CubicSampler CubicSampler variant metal2vulkan-rt::Gap::FloatDepthUpload FloatDepthUpload { pixel_format: PixelFormat } variant metal2vulkan-rt::Gap::HeapTexture HeapTexture { pixel_format: PixelFormat } @@ -13406,6 +13413,7 @@ variant metal2vulkan-rt::PrecisionNote::UnmeasuredGroupSpeculation UnmeasuredGro variant metal2vulkan-rt::PrecisionNote::UnorderedFetchWithinDraw UnorderedFetchWithinDraw variant metal2vulkan-rt::PrecisionNote::VertexSimdgroupGrouping VertexSimdgroupGrouping variant metal2vulkan-rt::PrecisionNote::ViewBaseTexelOffset ViewBaseTexelOffset +variant metal2vulkan-rt::Refusal::BufferCopyLayout BufferCopyLayout { offset: u64, bytes_per_row: u64, bytes_per_image: u64, len: u64 } variant metal2vulkan-rt::Refusal::BufferIndex BufferIndex { index: u32 } variant metal2vulkan-rt::Refusal::BufferPastBlock BufferPastBlock { offset: u64, length: u64, block_len: u64 } variant metal2vulkan-rt::Refusal::BufferTooLong BufferTooLong { length: u64, max: u64 } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 817a36588..d23dca549 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,9 +37,9 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 7 | 7 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 35 | 35 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 36 | 36 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Gap` | 12 | 12 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Gap` | 13 | 13 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -55,9 +55,9 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 10 | 8 | 0 | 0 | 17 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 11 | 8 | 0 | 0 | 17 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 7 | 3 | 0 | 0 | 0 | -| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 12 | 0 | 0 | 0 | +| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 13 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -619,7 +619,7 @@ Columns: | `ManagedBlockNotShared` | A Managed buffer whose bytes are in a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: a Managed buffer's bytes are the consumer's, which it maps; a Private block has no mapping | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | -| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image and a pipeline belong to the `VkDevice` that made them | 10: `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`, `crates/metal2vulkan-rt/src/command.rs (check)` (+7) | `-` | +| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image and a pipeline belong to the `VkDevice` that made them | 11: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)` (+8) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | | `NoPipeline` | A dispatch with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | @@ -645,6 +645,7 @@ Columns: | `TextureBytesPrivate` | `Texture::replace_region` or `Texture::get_bytes` of a Private or Memoryless texture | every device (a public call's own check of its arguments) | `metal-documented`: Apple's documentation of `MTLStorageModePrivate`: "The resource is accessible only to the GPU." | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | | `TextureRegion` | `Texture::replace_region`, `Texture::get_bytes` or a blit copy (`BlitCommandEncoder::copy_from_texture`) of a level or slice past the texture's,... | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to copy | 1: `crates/metal2vulkan-rt/src/texture.rs (place)` | `-` | | `TextureBytesLayout` | `Texture::replace_region` or `Texture::get_bytes` with rows closer than a row of the region, images closer than an image of it, or bytes too few... | every device (a public call's own check of its arguments) | `ours`: the call would read or write past the bytes it is given, or one texel's bytes over another's | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | +| `BufferCopyLayout` | `BlitCommandEncoder::copy_from_buffer` or `BlitCommandEncoder::copy_from_texture_to_buffer` whose offset or row stride, for a format of single... | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1, probe `blit_buffer_copy_rules.m` in the conformance crate, jobs m3-max-43541 and m3-max-43545: Metal's validation layer stops an RGBA8Unorm offset of 2, `sourceOffset (2) must be a multiple of 4 bytes`, a row stride of 18, `sourceBytesPerRow (18) must be a multiple of 4 bytes`, and the same of a copy into a buffer, a row stride of 12 for rows of 16 bytes, an image stride of 12 for images of 16, and a region 16 bytes past the buffer's end, `totalBytesUsed(4112) must be <= [sourceBuffer length](4096)`; it takes an R8Unorm offset of 2, a row stride of 0 for one row, image strides of no whole number of rows, and an image stride on a 2D texture and on a slice of a 1D array | 1: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` | `-` | | `TextureCopyMismatch` | `BlitCommandEncoder::copy_from_texture` between textures of two pixel formats, or of two sample counts | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1, probe `blit_copy_format_pairs.m` in the conformance crate: Metal's validation layer stops every pair of two formats it was given, sRGB, integer, float, channel order, depth and compressed pairs among them, with `[sourceTexture pixelFormat](...) must equal [destinationTexture pixelFormat](...)`, and a source of four samples into one of one with `[sourceTexture sampleCount](4) must equal [destinationTexture sampleCount](1)` | 1: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` | `-` | | `ManagedTextureBytes` | A Managed texture's bytes the device cannot copy in place (`Device::new_managed_texture`) | every device (a public call's own check of its arguments) | `ours`: a buffer-to-image copy reads a place only so laid out, and the consumer's bytes are the place the copy reads | 4: `crates/metal2vulkan-rt/src/texture.rs (check_places)`, `crates/metal2vulkan-rt/src/texture.rs (named)` (+2) | `-` | | `HeapTexturePlace` | A heap texture whose image does not lie in its heap (`Device::new_heap_texture`) | every device (a public call's own check of its arguments) | `ours`: an image bound past its heap's range would take memory the heap does not hold, and Vulkan binds an image only at its alignment | 1: `crates/metal2vulkan-rt/src/texture.rs (make)` | `-` | @@ -676,10 +677,11 @@ Columns: | `TextureBuffer` | A texture buffer (`MTLTextureTypeTextureBuffer`) | every device (a public call's own check of its arguments) | `ours`: no texel-buffer array; no replay stream uses one | 2: `crates/metal2vulkan-rt/src/texture.rs (shape, 2 sites)` | `-` | | `TextureFormat` | A texture of a pixel format the runtime makes no image of on this device for the descriptor's usage | every device (a public call's own check of its arguments) | `ours`: the device's format query, or the identity domains' shaders read every texture through its view alone | 1: `crates/metal2vulkan-rt/src/texture.rs (plan)` | `-` | | `CubicSampler` | A sampler state whose minification or magnification filter is cubic (`Device::new_sampler_state`) | every device (a public call's own check of its arguments) | `ours`: the translator's identity domains do not filter bicubically, and Vulkan's cubic filter is not Metal's | 1: `crates/metal2vulkan-rt/src/sampler.rs (new_sampler_state)` | `-` | -| `TextureBytes` | `Texture::replace_region` or `Texture::get_bytes` of a texture whose image is no plain copy of Metal's bytes in one aspect | every device (a public call's own check of its arguments) | `ours`: no copy between such an image and bytes is built | 2: `crates/metal2vulkan-rt/src/texture.rs (check_places)`, `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | -| `FloatDepthUpload` | `Texture::replace_region` into a 32-bit float depth (`Depth32Float`) | every device (a public call's own check of its arguments) | `ours`: no upload of a 32-bit float depth is built | 2: `crates/metal2vulkan-rt/src/texture.rs (replace_region)`, `crates/metal2vulkan-rt/src/texture.rs (upload_region)` | `-` | +| `TextureBytes` | `Texture::replace_region`, `Texture::get_bytes` or a blit copy between a buffer and a texture (`BlitCommandEncoder::copy_from_buffer`) of a... | every device (a public call's own check of its arguments) | `ours`: no copy between such an image and bytes is built | 3: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/texture.rs (check_places)` (+1) | `-` | +| `FloatDepthUpload` | `Texture::replace_region` or `BlitCommandEncoder::copy_from_buffer` into a 32-bit float depth (`Depth32Float`) | every device (a public call's own check of its arguments) | `ours`: no upload of a 32-bit float depth is built | 3: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/texture.rs (replace_region)` (+1) | `-` | | `TextureCopy` | `BlitCommandEncoder::copy_from_texture` that no single `vkCmdCopyImage` in the floor makes | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 copies none of these with one command; each is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` | `-` | | `HeapTexture` | A heap texture the runtime does not place (`Device::new_heap_texture` and `Device::heap_texture_size_and_align`) | every device (a public call's own check of its arguments) | `ours`: heap textures are built for Private heaps of placeable images | 2: `crates/metal2vulkan-rt/src/texture.rs (heap_fit)`, `crates/metal2vulkan-rt/src/texture.rs (new_heap_texture)` | `-` | +| `BufferCopyAlignment` | `BlitCommandEncoder::copy_from_buffer` or `BlitCommandEncoder::copy_from_texture_to_buffer` whose bytes no copy command in the floor addresses,... | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 places a copy's rows in a buffer by a count of texels from an aligned offset; each is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` | `-` | ## Appendix: every site @@ -1174,7 +1176,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (open)` -- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` +- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-rt/src/command.rs (open)` - `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` @@ -1200,6 +1202,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::TextureBytesPrivate`: `crates/metal2vulkan-rt/src/texture.rs (copy)` - `rt:Refusal::TextureRegion`: `crates/metal2vulkan-rt/src/texture.rs (place)` - `rt:Refusal::TextureBytesLayout`: `crates/metal2vulkan-rt/src/texture.rs (copy)` +- `rt:Refusal::BufferCopyLayout`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` - `rt:Refusal::TextureCopyMismatch`: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` - `rt:Refusal::ManagedTextureBytes`: `crates/metal2vulkan-rt/src/texture.rs (check_places)`; `crates/metal2vulkan-rt/src/texture.rs (named)`; `crates/metal2vulkan-rt/src/texture.rs (named_host)`; `crates/metal2vulkan-rt/src/texture.rs (upload_region)` - `rt:Refusal::HeapTexturePlace`: `crates/metal2vulkan-rt/src/texture.rs (make)` @@ -1221,8 +1224,9 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::TextureBuffer`: `crates/metal2vulkan-rt/src/texture.rs (shape, 2 sites)` - `rt:Gap::TextureFormat`: `crates/metal2vulkan-rt/src/texture.rs (plan)` - `rt:Gap::CubicSampler`: `crates/metal2vulkan-rt/src/sampler.rs (new_sampler_state)` -- `rt:Gap::TextureBytes`: `crates/metal2vulkan-rt/src/texture.rs (check_places)`; `crates/metal2vulkan-rt/src/texture.rs (copy)` -- `rt:Gap::FloatDepthUpload`: `crates/metal2vulkan-rt/src/texture.rs (replace_region)`; `crates/metal2vulkan-rt/src/texture.rs (upload_region)` +- `rt:Gap::TextureBytes`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/texture.rs (check_places)`; `crates/metal2vulkan-rt/src/texture.rs (copy)` +- `rt:Gap::FloatDepthUpload`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/texture.rs (replace_region)`; `crates/metal2vulkan-rt/src/texture.rs (upload_region)` - `rt:Gap::TextureCopy`: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` - `rt:Gap::HeapTexture`: `crates/metal2vulkan-rt/src/texture.rs (heap_fit)`; `crates/metal2vulkan-rt/src/texture.rs (new_heap_texture)` +- `rt:Gap::BufferCopyAlignment`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`