diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 1dd27cc66..e831d7b2f 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2055,8 +2055,13 @@ while the driver's exit handler waited on a lock, with every runtime thread alre (`Refusal::TextureCopyMismatch`), and a region outside either texture or off its block grid (`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. + held in two Vulkan formats by the textures' usages, a 1D texture with another type), and + overlapping regions of one level and slice of one image, which Metal leaves undefined (Apple's + `copy(from:...to:...)` page: "unexpected behavior"). +- Within one level and slice of one image (a texture into itself, or a texture and its view, + which shares its image), regions apart copy with one `vkCmdCopyImage`, that subresource in the + general layout: one barrier moves it there and one home, the same three barriers as any copy. + The same region copies nothing and records no command, every texel already its own. - `copy_from_buffer` is `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:` `sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:` and `copy_from_texture_to_buffer` is `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:` diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index b38fe70ae..6171e5106 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -135,13 +135,16 @@ impl BlitCommandEncoder { /// deep copies into or out of /// a 2D slice. A size of 0 on an axis one of the textures lacks (depth on any but a 3D /// texture, height on a 1D one) copies one texel there, and a size of 0 on another axis copies - /// nothing, as plain Metal does where its validation stops the call. The command buffer keeps - /// both textures until it retires. + /// nothing, as plain Metal does where its validation stops the call. Within one level and + /// slice of one image (the texture into itself, or a texture and its view), regions apart + /// copy with that subresource in the general layout, and the same region copies nothing and + /// records no command, every texel already its own; Metal leaves overlapping regions + /// undefined. The command buffer keeps both textures until it retires. /// /// Err: [`Refusal::OtherDevice`] for another device's texture; [`Refusal::TextureRegion`] for /// a level, slice or region outside either texture or off its format's block grid; - /// [`Refusal::TextureCopyMismatch`]; [`Gap::TextureCopy`]; [`Error::Vulkan`] where the - /// command buffer cannot record. + /// [`Refusal::TextureCopyMismatch`]; [`Gap::TextureCopy`], overlapping regions of one + /// subresource among it; [`Error::Vulkan`] where the command buffer cannot record. pub fn copy_from_texture( &mut self, source: &Texture, @@ -174,19 +177,36 @@ impl BlitCommandEncoder { building.wrote_host(); } building.overs_after(overs, false); - let (read, write) = ( - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - vk::ImageLayout::TRANSFER_DST_OPTIMAL, - ); + let (read, write) = match copy.shared { + false => ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + ), + true => (vk::ImageLayout::GENERAL, vk::ImageLayout::GENERAL), + }; let earlier = [memory_barrier(Reach::Commands)]; - let away = [ - source.away(©.from, read, vk::AccessFlags2::TRANSFER_READ), - destination.away(©.to, write, vk::AccessFlags2::TRANSFER_WRITE), - ]; - let back = [ - source.back(©.from, read), - destination.back(©.to, write), - ]; + // Regions apart in one subresource: one barrier moves it to the general layout and one + // home, the copy reading and writing it there. + let (away_two, back_two, away_one, back_one); + let (away, back): (&[_], &[_]) = match copy.shared { + false => { + away_two = [ + source.away(©.from, read, vk::AccessFlags2::TRANSFER_READ), + destination.away(©.to, write, vk::AccessFlags2::TRANSFER_WRITE), + ]; + back_two = [ + source.back(©.from, read), + destination.back(©.to, write), + ]; + (&away_two, &back_two) + } + true => { + let both = vk::AccessFlags2::TRANSFER_READ | vk::AccessFlags2::TRANSFER_WRITE; + away_one = [destination.away(©.to, write, both)]; + back_one = [destination.back(©.to, write)]; + (&away_one, &back_one) + } + }; let regions = [vk::ImageCopy { src_subresource: copy.from.layers(copy.aspect), src_offset: copy.from.offset(), @@ -197,15 +217,15 @@ impl BlitCommandEncoder { let device = &core.device; let (named_read, named_write) = (source.copy_layout(read), destination.copy_layout(write)); // SAFETY: the command buffer records outside any render pass and keeps both images until - // it retires; each subresource is in its home layout between commands, and the two are - // different subresources where the textures are one (`texture_copy`), in their copy - // layouts between the barriers; the region lies in both. + // it retires; each subresource is in its home layout between commands, and in its copy + // layout between the barriers: two subresources, or one in the general layout whose two + // regions lie apart (`texture_copy`); the region lies in both. unsafe { device.cmd_pipeline_barrier2( command, &vk::DependencyInfo::default() .memory_barriers(&earlier) - .image_memory_barriers(&away), + .image_memory_barriers(away), ); device.cmd_copy_image( command, @@ -215,7 +235,7 @@ impl BlitCommandEncoder { named_write, ®ions, ); - close(core, command, &back); + close(core, command, back); } building.count(Metric::Barriers); building.count(Metric::Barriers); @@ -1063,11 +1083,14 @@ impl<'a> Side<'a> { } } -/// A copy between two textures, checked: the region in each, and the aspect it copies. +/// A copy between two textures, checked: the region in each, the aspect it copies, and whether +/// the two regions lie apart in one subresource of one image, which the copy takes in the +/// general layout. pub(crate) struct ImageCopy { pub(crate) from: Placed, pub(crate) to: Placed, pub(crate) aspect: vk::ImageAspectFlags, + pub(crate) shared: bool, } /// Checks a fill of `range` of a buffer at `base` in its block, `len` bytes long: its offset in @@ -1391,14 +1414,26 @@ pub(crate) fn texture_copy( let (Some(from), Some(to)) = placed else { return Ok(None); }; - // One subresource is in one layout at a time. - if same && from.level == to.level && from.layer == to.layer { + // One subresource of one image, the textures one or a texture and its view: Metal leaves a + // copy whose regions overlap undefined (Apple's `copy(from:...to:...)` page: "unexpected + // behavior"). The same region copies nothing, every texel already its own; disjoint regions + // copy in the general layout (`VUID-vkCmdCopyImage-srcImage-09460`, `-pRegions-00124`). + let shared = same && from.level == to.level && from.layer == to.layer; + if shared && from.origin == to.origin { + return Ok(None); + } + let apart = (0..3).any(|axis| { + let (a, b, extent) = (from.origin[axis], to.origin[axis], from.size[axis]); + a + extent <= b || b + extent <= a + }); + if shared && !apart { return Err(gap()); } Ok(Some(ImageCopy { from, to, aspect: unit.aspect, + shared, })) } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 90b380dbb..2b1846455 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1053,11 +1053,13 @@ pub enum Gap { /// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture) /// that no single `vkCmdCopyImage` in the floor makes: a multisample texture; a format of /// depth and stencil both; one pixel format held in two Vulkan formats, which the two - /// textures' usages chose; a 1D texture with one of another type; or a region of one - /// texture's level and slice into the same level and slice. + /// textures' usages chose; a 1D texture with one of another type; or overlapping regions of + /// one level and slice of one image (one texture, or a texture and its view), which Metal + /// leaves undefined. Regions apart there copy, and the same region copies nothing. /// /// Basis: ours (Vulkan 1.3 copies none of these with one command; each is built when a replay - /// stream makes one). + /// stream makes one; Apple's `copy(from:sourceSlice:sourceLevel:sourceOrigin:sourceSize:to:` + /// page calls a copy between overlapping regions of one texture "unexpected behavior"). TextureCopy { /// The source texture's pixel format. source: PixelFormat, diff --git a/crates/metal2vulkan-runtime/src/tests/blit.rs b/crates/metal2vulkan-runtime/src/tests/blit.rs index 7cb44949c..6fdf4a371 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit.rs @@ -3,7 +3,10 @@ //! - 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; //! what one copy command in the floor does not make, one pixel format held in two Vulkan formats -//! among it, is `Gap::TextureCopy`; a level, slice or region outside a texture or +//! among it, is `Gap::TextureCopy`; within one level and slice of one image (one texture, or a +//! texture and its view), regions apart copy in the general layout, the same region copies +//! nothing, and overlapping regions, which Metal leaves undefined, are `Gap::TextureCopy`; a +//! level, slice or region outside a texture or //! off its block grid is `Refusal::TextureRegion`; a size of 0 on an axis a texture lacks copies //! one texel there, and on another copies nothing; a 3D texture's image copies to and from a 2D //! slice. @@ -11,7 +14,8 @@ //! land in a slice of a 2D array, a cube's face in an //! image of a 3D texture, an image of a 3D texture in a 2D texture, a slice of an array in //! another slice of it, and a block-compressed region in another texture where the device makes -//! one, everything around each region kept. One copy alone is one submission, two barriers and +//! one, everything around each region kept; a texture's region into another of the same level +//! and slice, from the texture or from its view, the same. One copy alone is one submission, two barriers and //! the segment's end, and copies no byte of the runtime's own; a barrier an encoder owed is paid //! by the copy's first. Every gauge comes back to zero with the device. The bytes each copy //! must leave are plain Metal's: their FNV-1a 64 hashes are those of probe `blit_copy_layouts.m` @@ -229,34 +233,38 @@ fn a_3d_image_copies_to_and_from_a_2d_slice_and_a_cube_face_is_its_slice() { )), Refusal::TextureRegion { .. } )); - // One texture's two slices copy; one slice into itself is not built. + // One texture's two slices copy; within one slice, regions apart copy in the general layout, + // the same region copies nothing, and overlapping regions are not built. let mut array = descriptor(TextureType::Type2DArray, PixelFormat::R8Unorm, [4, 4, 1]); array.array_length = 2; let a = side(&array, vk::Format::R8_UNORM, color(1)); - assert!(texture_copy( - &a, - at(0, 0, [0; 3]), - [2, 2, 1], - &a, - at(1, 0, [2, 2, 0]), - true - ) - .expect("a copy") - .is_some()); - assert_eq!( - gap(texture_copy( - &a, - at(0, 0, [0; 3]), - [2, 2, 1], - &a, - at(0, 0, [2, 2, 0]), - true - )), - Gap::TextureCopy { - source: PixelFormat::R8Unorm, - destination: PixelFormat::R8Unorm - } - ); + let within = |to, size| texture_copy(&a, at(0, 0, [0; 3]), size, &a, to, true); + let across = copied(within(at(1, 0, [0; 3]), [2, 2, 1])); + assert!(!across.shared, "two slices"); + for (to, size) in [ + ([2, 2, 0], [2, 2, 1]), + ([2, 0, 0], [2, 4, 1]), + ([0, 3, 0], [4, 1, 1]), + ] { + let apart = copied(within(at(0, 0, to), size)); + assert!(apart.shared, "{to:?} {size:?}"); + assert_eq!(apart.to, placed(0, 0, to, size)); + } + assert!(matches!(within(at(0, 0, [0; 3]), [3, 3, 1]), Ok(None))); + for (to, size) in [ + ([1, 1, 0], [2, 2, 1]), + ([1, 0, 0], [2, 1, 1]), + ([0, 1, 0], [4, 2, 1]), + ] { + assert_eq!( + gap(within(at(0, 0, to), size)), + Gap::TextureCopy { + source: PixelFormat::R8Unorm, + destination: PixelFormat::R8Unorm + }, + "{to:?} {size:?}" + ); + } } #[test] @@ -1319,6 +1327,131 @@ pub(crate) mod on_device { }); } + /// A copy within one subresource of one image, from a texture's view or from the texture + /// itself into the texture: disjoint regions copy, one submission and three barriers as any + /// copy, everything around the region kept; the same region copies nothing and records no + /// command; overlapping regions, which Metal leaves undefined, are `Gap::TextureCopy`. + #[test] + fn every_device_copies_within_one_subresource_of_a_texture_and_its_view() { + each_device("blit_within", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 4) + .expect("a grant"); + let texture = texture( + &device, + TextureType::Type2D, + PixelFormat::RGBA8Unorm, + [8, 8, 1], + TextureUsage::SHADER_READ, + 4096, + ) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let view = (texture.new_texture_view( + PixelFormat::RGBA8Unorm, + TextureType::Type2D, + 0..1, + 0..1, + Some(4097), + )) + .unwrap_or_else(|error| panic!("{name}: the view: {error}")); + let level = |texture| Level { + texture, + slice: 0, + level: 0, + unit: 4, + block: 1, + }; + let (whole, through_view) = (level(&texture), level(&view)); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + let mut source = whole.write(11); + // The upload goes with a command buffer of its own, one with commands. + let first = queue.command_buffer().expect("a command buffer"); + first + .record_for_test(&[], |_, _| {}) + .expect("a command buffer's commands"); + first.commit().expect("a commit"); + finished(name, &first); + for (case, from) in [("from the view", &through_view), ("from itself", &whole)] { + let copy = Expect { + from, + source: &source, + at: [0, 0, 0], + to: &whole, + before: source.clone(), + to_at: [4, 3, 0], + size: [4, 2, 1], + }; + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + copy.record(name, &command_buffer); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: {case}"); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.bytes_copied - before.bytes_copied, + ), + (1, 3, 0), + "{name}: {case}: submissions, barriers, bytes copied" + ); + let expected = copy.after(); + assert_eq!(whole.read(), expected, "{name}: {case}"); + source = expected; + } + + // The same region: nothing to copy, no command, every byte kept. + settled(&device); + 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"); + let at = |origin| TexturePlace { + slice: 0, + level: 0, + origin, + }; + (encoder.copy_from_texture(&view, at([2, 1, 0]), [3, 3, 1], &texture, at([2, 1, 0]))) + .unwrap_or_else(|error| panic!("{name}: the same region: {error}")); + // Overlapping regions are not built. + assert!( + matches!( + encoder.copy_from_texture( + &view, + at([0, 0, 0]), + [4, 4, 1], + &texture, + at([2, 2, 0]) + ), + Err(Error::Unsupported(Gap::TextureCopy { .. })) + ), + "{name}: overlapping regions" + ); + 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 + ), + (0, 0), + "{name}: the same region records nothing" + ); + assert_eq!( + whole.read(), + source, + "{name}: the same region keeps every byte" + ); + println!("{name}: copies within one subresource, through a view and of itself"); + }); + } + /// Writes `bytes` over the start of a Shared buffer. fn write(buffer: &Buffer, bytes: &[u8]) { let contents = buffer.contents().expect("a Shared buffer"); diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 6c892d7a9..06390f578 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -3229,12 +3229,15 @@ impl TextureInner { /// The barrier that moves `placed`'s level and layer back home from the copy layout of /// `layout` once a copy has run, its writes (a copy into the image, whose transfer layout is - /// `TRANSFER_DST_OPTIMAL`) visible to every later command. + /// `TRANSFER_DST_OPTIMAL`, or within one subresource, in `GENERAL`) visible to every later + /// command. fn back(&self, placed: &Placed, layout: vk::ImageLayout) -> vk::ImageMemoryBarrier2<'static> { use vk::AccessFlags2 as Access; use vk::PipelineStageFlags2 as Stage; let written = match layout { - vk::ImageLayout::TRANSFER_DST_OPTIMAL => Access::TRANSFER_WRITE, + vk::ImageLayout::TRANSFER_DST_OPTIMAL | vk::ImageLayout::GENERAL => { + Access::TRANSFER_WRITE + } _ => Access::NONE, }; self.barrier(placed, self.image.copy_layout(layout), self.image.home) diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index e81f9ebba..c127b35d1 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -376,7 +376,7 @@ Columns: | `LodClamps` | A sampler state bound with LOD clamps its samples read otherwise through (`ComputeCommandEncoder::set_sampler_state_with_lod_clamps` and the... | every device (a public call's own check of its arguments) | `ours`: no replay stream binds such clamps: every bind-time clamp the streams make reads as its state's own | 1: `crates/metal2vulkan-runtime/src/sampler.rs (clamps_at_bind)` | `-` | | `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-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/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-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/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-runtime/src/blit.rs (texture_copy)` | `-` | +| `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; Apple's `copy(from:sourceSlice:sourceLevel:sourceOrigin:sourceSize:to:` page calls a copy between overlapping regions of one texture "unexpected behavior" | 1: `crates/metal2vulkan-runtime/src/blit.rs (texture_copy)` | `-` | | `TextureOverBuffer` | A texture over a buffer (`Buffer::new_texture`) the runtime does not make | every device (a public call's own check of its arguments) | `ours`: the in-place linear image and the copy form take one 2D color image | 3: `crates/metal2vulkan-runtime/src/texture.rs (check_over)`, `crates/metal2vulkan-runtime/src/texture.rs (error)` (+1) | `-` | | `HeapTexture` | A heap texture the runtime does not place (`Device::new_heap_texture`, `Device::new_heap_texture_for_views` 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-runtime/src/texture.rs (heap_fit)`, `crates/metal2vulkan-runtime/src/texture.rs (heap_source)` | `-` | | `SurfaceUsage` | A surface plane in place (`Device::new_exported_surface`) whose texture's uses ask an image usage its linear tiling lacks (storage, for one) | at the device's limit | `device`: the image format query and the format features of the plane's tiling | 3: `crates/metal2vulkan-runtime/src/d3d11.rs (d3d11_plane)`, `crates/metal2vulkan-runtime/src/surface.rs (plane)` (+1) | `-` |