diff --git a/crates/metal2vulkan-conformance/probes/resolve_texture_usage.m b/crates/metal2vulkan-conformance/probes/resolve_texture_usage.m index 99fd4d079..f7543d6c6 100644 --- a/crates/metal2vulkan-conformance/probes/resolve_texture_usage.m +++ b/crates/metal2vulkan-conformance/probes/resolve_texture_usage.m @@ -1,5 +1,6 @@ // Whether Metal resolves a multisample colour attachment into a texture made without -// `MTLTextureUsageRenderTarget`, and what the resolved texels read. +// `MTLTextureUsageRenderTarget`, into such a texture over a Shared buffer among them, and what the +// resolved texels read. // // ONE CASE PER PROCESS, chosen on the command line, run once under MTL_DEBUG_LAYER=1 and once // without it: the validation layer stops the process at a call it does not take, so a case that @@ -21,13 +22,29 @@ // control RenderTarget, but RGBA8Unorm_sRGB: a resolve Metal's validation stops (the // formats differ), which shows the layer is on // -// A case prints the resolve texture's usage, whether the encoder was made, the command buffer's -// status and error, and, read back by a blit into a Shared buffer (BGRA bytes, rows tight), the -// FNV-1a 64 of the 256 bytes and the texels at (0, 0), (7, 7), (3, 4) and (4, 3). +// Three cases take a guest's pass instead, at 600x600: a first pass clears the colour attachment +// to the clear above and its depth and stencil, and stores all three; a second pass loads all +// three, stores the depth and the stencil, draws nothing, and resolves the colour +// (MultisampleResolve) into a 1-sample BGRA8Unorm_sRGB 2D texture of ShaderRead usage alone: +// +// over Shared, made over a Shared buffer at offset 0 (newTextureWithDescriptor:offset: +// bytesPerRow:), its rows the row (2,400 bytes) rounded up to the device's +// minimumLinearTextureAlignmentForPixelFormat:, the buffer exactly its rows +// over-padded the same at 2,560 bytes a row (the row rounded up to 256), so each row has 160 +// bytes past its texels +// read600 Private, of its own memory: the control the two read as +// +// Before the pass the buffer's bytes are 0xee. A case prints the resolve texture's usage, whether +// the encoder was made, the command buffer's status and error, and, read back by a blit into a +// Shared buffer (BGRA bytes, rows tight), the FNV-1a 64 of its bytes and the texels at (0, 0), +// (7, 7), (3, 4) and (4, 3) (at 600x600: (0, 0), (599, 599), (299, 300) and (300, 299)). An over +// case prints, too, the alignment, the pitch and the buffer's length, what the texture answers +// of its buffer, the FNV-1a 64 of the texels read from the buffer's own bytes at its pitch, +// whether those equal the blit's, and how many bytes past the texels changed from 0xee. // // xcrun clang -fobjc-arc -framework Metal -framework QuartzCore -framework Foundation \ // -o resolve_texture_usage resolve_texture_usage.m -// for c in rt read readwrite drawable drawable-readable control; do +// for c in rt read readwrite drawable drawable-readable control over over-padded read600; do // MTL_DEBUG_LAYER=1 ./resolve_texture_usage $c // env -u MTL_DEBUG_LAYER ./resolve_texture_usage $c // done @@ -48,19 +65,30 @@ static const char *SOURCE = "}\n" "fragment half4 red() { return half4(1, 0, 0, 1); }\n"; +// The side of every texture of the case: 8, or 600 for a guest's pass. +static NSUInteger side = 8; + static id texture(id device, MTLPixelFormat format, NSUInteger samples, MTLTextureUsage usage) { MTLTextureDescriptor *d = [MTLTextureDescriptor new]; d.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D; d.pixelFormat = format; - d.width = 8; - d.height = 8; + d.width = side; + d.height = side; d.sampleCount = samples; d.usage = usage; d.storageMode = MTLStorageModePrivate; return [device newTextureWithDescriptor:d]; } +static uint64_t fnv(uint64_t hash, const uint8_t *bytes, NSUInteger length) { + for (NSUInteger i = 0; i < length; i++) { + hash ^= bytes[i]; + hash *= 0x100000001b3ull; + } + return hash; +} + int main(int argc, const char **argv) { @autoreleasepool { if (argc != 2) { @@ -73,7 +101,10 @@ int main(int argc, const char **argv) { const MTLPixelFormat depth = MTLPixelFormatDepth32Float_Stencil8; id resolve = nil; id drawable = nil; + id backing = nil; + NSUInteger pitch = 0; BOOL readable = YES; + BOOL guest = NO; if (strcmp(name, "rt") == 0) { resolve = texture(device, color, 1, MTLTextureUsageRenderTarget); } else if (strcmp(name, "read") == 0) { @@ -97,6 +128,38 @@ int main(int argc, const char **argv) { return 0; } resolve = drawable.texture; + } else if (strcmp(name, "read600") == 0) { + side = 600; + guest = YES; + resolve = texture(device, color, 1, MTLTextureUsageShaderRead); + } else if (strcmp(name, "over") == 0 || strcmp(name, "over-padded") == 0) { + side = 600; + guest = YES; + NSUInteger align = [device minimumLinearTextureAlignmentForPixelFormat:color]; + NSUInteger row = side * 4; + pitch = strcmp(name, "over") == 0 ? (row + align - 1) / align * align + : (row + 255) / 256 * 256; + backing = [device newBufferWithLength:pitch * side + options:MTLResourceStorageModeShared]; + memset(backing.contents, 0xee, backing.length); + MTLTextureDescriptor *d = [MTLTextureDescriptor new]; + d.textureType = MTLTextureType2D; + d.pixelFormat = color; + d.width = side; + d.height = side; + d.usage = MTLTextureUsageShaderRead; + d.storageMode = MTLStorageModeShared; + resolve = [backing newTextureWithDescriptor:d offset:0 bytesPerRow:pitch]; + printf("%s: minimum linear alignment %lu, bytes per row %lu, buffer %lu bytes\n", name, + (unsigned long)align, (unsigned long)pitch, (unsigned long)backing.length); + if (resolve == nil) { + printf("%s: no texture over the buffer\n", name); + return 0; + } + printf("%s: texture's buffer %s, offset %lu, bytes per row %lu, storage %lu\n", name, + resolve.buffer == backing ? "the buffer" : "another", + (unsigned long)resolve.bufferOffset, (unsigned long)resolve.bufferBytesPerRow, + (unsigned long)resolve.storageMode); } else { printf("no case %s\n", name); return 2; @@ -125,41 +188,65 @@ int main(int argc, const char **argv) { printf("%s: no pipeline: %s\n", name, error.description.UTF8String); return 3; } - MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; - pass.colorAttachments[0].texture = msaa; - pass.colorAttachments[0].loadAction = MTLLoadActionClear; - pass.colorAttachments[0].clearColor = MTLClearColorMake(0.25, 0.5, 0.75, 1.0); - pass.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve; - pass.colorAttachments[0].resolveTexture = resolve; - pass.depthAttachment.texture = ds; - pass.depthAttachment.loadAction = MTLLoadActionClear; - pass.depthAttachment.storeAction = MTLStoreActionDontCare; - pass.stencilAttachment.texture = ds; - pass.stencilAttachment.loadAction = MTLLoadActionClear; - pass.stencilAttachment.storeAction = MTLStoreActionDontCare; id queue = [device newCommandQueue]; id cb = [queue commandBuffer]; + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = msaa; + pass.colorAttachments[0].clearColor = MTLClearColorMake(0.25, 0.5, 0.75, 1.0); + pass.depthAttachment.texture = ds; + pass.stencilAttachment.texture = ds; + if (guest) { + // The first pass: every attachment cleared and stored. + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + pass.depthAttachment.loadAction = MTLLoadActionClear; + pass.depthAttachment.storeAction = MTLStoreActionStore; + pass.stencilAttachment.loadAction = MTLLoadActionClear; + pass.stencilAttachment.storeAction = MTLStoreActionStore; + id first = [cb renderCommandEncoderWithDescriptor:pass]; + if (first == nil) { + printf("%s: first encoder nil\n", name); + return 0; + } + [first endEncoding]; + // The guest's pass: every attachment loaded, the colour resolved. + pass.colorAttachments[0].loadAction = MTLLoadActionLoad; + pass.depthAttachment.loadAction = MTLLoadActionLoad; + pass.stencilAttachment.loadAction = MTLLoadActionLoad; + } else { + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.depthAttachment.loadAction = MTLLoadActionClear; + pass.depthAttachment.storeAction = MTLStoreActionDontCare; + pass.stencilAttachment.loadAction = MTLLoadActionClear; + pass.stencilAttachment.storeAction = MTLStoreActionDontCare; + } + pass.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve; + pass.colorAttachments[0].resolveTexture = resolve; id encoder = [cb renderCommandEncoderWithDescriptor:pass]; printf("%s: encoder %s\n", name, encoder ? "made" : "nil"); if (encoder == nil) { return 0; } - [encoder setRenderPipelineState:state]; - [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; + if (!guest) { + [encoder setRenderPipelineState:state]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; + } [encoder endEncoding]; - id out = [device newBufferWithLength:256 options:MTLResourceStorageModeShared]; - memset(out.contents, 0xee, 256); + const NSUInteger row = side * 4; + const NSUInteger bytes = row * side; + id out = [device newBufferWithLength:bytes options:MTLResourceStorageModeShared]; + memset(out.contents, 0xee, bytes); if (readable) { id blit = [cb blitCommandEncoder]; [blit copyFromTexture:resolve sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) - sourceSize:MTLSizeMake(8, 8, 1) + sourceSize:MTLSizeMake(side, side, 1) toBuffer:out destinationOffset:0 - destinationBytesPerRow:32 - destinationBytesPerImage:256]; + destinationBytesPerRow:row + destinationBytesPerImage:bytes]; [blit endEncoding]; } [cb commit]; @@ -170,18 +257,33 @@ int main(int argc, const char **argv) { return 0; } const uint8_t *got = out.contents; - uint64_t hash = 0xcbf29ce484222325ull; - for (NSUInteger i = 0; i < 256; i++) { - hash ^= got[i]; - hash *= 0x100000001b3ull; - } - printf("%s: texels fnv %016llx", name, (unsigned long long)hash); - const int at[4][2] = {{0, 0}, {7, 7}, {3, 4}, {4, 3}}; + printf("%s: texels fnv %016llx", name, + (unsigned long long)fnv(0xcbf29ce484222325ull, got, bytes)); + const int last = (int)side - 1; + const int half = (int)side / 2; + const int at[4][2] = {{0, 0}, {last, last}, {half - 1, half}, {half, half - 1}}; for (int i = 0; i < 4; i++) { - const uint8_t *t = got + (at[i][1] * 8 + at[i][0]) * 4; + const uint8_t *t = got + (at[i][1] * side + at[i][0]) * 4; printf(" (%d,%d)=%02x%02x%02x%02x", at[i][0], at[i][1], t[0], t[1], t[2], t[3]); } printf("\n"); + if (backing != nil) { + const uint8_t *held = backing.contents; + uint64_t hash = 0xcbf29ce484222325ull; + BOOL same = YES; + NSUInteger changed = 0; + for (NSUInteger y = 0; y < side; y++) { + hash = fnv(hash, held + y * pitch, row); + same = same && memcmp(held + y * pitch, got + y * row, row) == 0; + for (NSUInteger x = row; x < pitch; x++) { + changed += held[y * pitch + x] != 0xee; + } + } + printf("%s: buffer's texels fnv %016llx, %s the blit's; %lu of %lu bytes past the " + "texels changed\n", + name, (unsigned long long)hash, same ? "equal to" : "NOT equal to", + (unsigned long)changed, (unsigned long)((pitch - row) * side)); + } } return 0; } diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 6bf652d69..2046f4bb7 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3552,11 +3552,22 @@ cache is answered compile-required on both. attachment's pixel format and one sample, and its level the attachment level's width and height. Metal resolves into a texture of any usage, and so does the runtime into a one-sample colour texture, 2D, a 2D array, a cube or a cube array, whose image is optimal: such a texture - takes the attachment usage on every device where its format renders, whatever Metal's usage. A - resolve into a texture made without `RenderTarget` usage whose image has no attachment usage is a - known gap (`RenderPassKind::ResolveUsage`): a depth or stencil texture, a colour texture of - another type or of a format the device's optimal image does not render, and a texture over a - buffer in place, whose linear image takes no attachment usage for a resolve alone. Refused as + takes the attachment usage on every device where its format renders, whatever Metal's usage. + So does the linear image of a texture in place over a buffer of the runtime's own memory, where + the device's linear tiling renders its format and its image format query makes the image with + the usage, which left its layout as it was on every venue counted. A resolve into a texture made + without `RenderTarget` usage whose image has no attachment usage is a known gap + (`RenderPassKind::ResolveUsage`): a depth or stencil texture, a colour texture of another type + or of a format the device's optimal image does not render, and a texture in place over a buffer + whose linear image takes none. On the RTX 3090 and on KosmicKrisp that is every texture in place + over a buffer, as their linear tiling features hold the attachment for no format (and a pitch of + the row rounded up to the alignment answer, 128 and 16, lies in place). Elsewhere it is one over + a dma-buf's import, one of a format the device's linear tiling does not render, and one whose + subresource reaches past its own rows or its buffer, as a resolve "may read and write back any + memory locations within the image subresource bound for that attachment" (Vulkan's multisample + resolve operations): on every venue counted, a buffer that ends at the texture's last texel + where its rows are padded. + Such a texture stays in place, never copied to gain the usage. Refused as Metal refuses it: a resolving action with no resolve texture (`Refusal::ResolveTexture`, also where an encoder sets it later) and an integer format's resolve (`Refusal::ResolveFormat`). `Metrics::resolves` counts the attachments passes resolved. @@ -3955,9 +3966,13 @@ cache is answered compile-required on both. without `RenderTarget` usage whose image has no attachment usage (`ResolveUsage`: Metal resolves into a texture of any usage; Vulkan only into a view with the attachment usage, `VUID-VkRenderingInfo-colorAttachmentCount-09476`, which a one-sample colour texture of an - optimal image takes where its format renders, and a depth or stencil texture or a texture over - a buffer in place does not; the usage grows a 1920 x 1080 `RGBA8Unorm` image of one level 1.0056 - times on the Radeon 780M, `RenderPassKind::ResolveUsage` has the measure), + optimal image takes where its format renders, and a texture's linear image in place over a + buffer of the runtime's own memory where the device's linear tiling renders its format, and a + depth or stencil texture does not, nor a texture in place on the RTX 3090 or KosmicKrisp, whose + linear tiling features hold the attachment for no format, over a dma-buf's import, or whose + subresource reaches past its own rows or its buffer, which a resolve may write back whole; the + usage grows a 1920 x 1080 `RGBA8Unorm` optimal image of one level 1.0056 times on the Radeon + 780M and changes no linear image's layout, `RenderPassKind::ResolveUsage` has the measures), a depth or stencil resolve the device's resolve modes do not offer (`ResolveFilter`: `Min` or `Max` where `supportedDepthResolveModes` lacks it, the stencil filter `DepthResolvedSample`, which no Vulkan resolve mode is, and two aspects paired where `independentResolve` or diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index ee1e938e2..0d5f43e83 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1792,13 +1792,22 @@ pub enum RenderPassKind { /// usage) whose image has no attachment usage: a depth or stencil texture; a colour texture of /// a type but 2D, a 2D array, a cube or a cube array, or whose format the device's optimal /// image does not render, by its format features or its image format query at the texture's - /// extent; or a texture over a buffer whose linear image lies in place, which takes no - /// attachment usage for a resolve alone, so it stays in place and is never copied to gain one. + /// extent; or a texture in place over a buffer whose linear image takes none: over a dma-buf's + /// import; of a format the device's linear tiling does not render, by its linear features or + /// its image format query at the texture's extent (on the RTX 3090 and KosmicKrisp, every + /// format); or whose + /// subresource reaches past its own rows or its buffer, as a resolve "may read and write back + /// any memory locations within the image subresource bound for that attachment" (Vulkan's + /// multisample resolve operations). Such a texture stays in place, and is never copied to + /// gain the usage. /// Metal resolves into a texture of any usage: probe `resolve_texture_usage.m` in the /// conformance crate (an Apple M3 Max, macOS 27.0.1, job m3-max-59768) resolved a 4-sample /// `BGRA8Unorm_sRGB` attachment into a texture of `ShaderRead` usage and of `ShaderRead | /// ShaderWrite` usage, plain and under Metal's validation layer, each reading the texels of a - /// `RenderTarget` one. Vulkan resolves only into a view with the attachment usage + /// `RenderTarget` one; and (job m3-max-66994) a 600 x 600 pass that loads its colour, depth + /// and stencil into a `ShaderRead` texture over a Shared buffer, its rows 2,400 and 2,560 + /// bytes apart, whose buffer then read the resolved texels and kept every byte past them. + /// Vulkan resolves only into a view with the attachment usage /// (VUID-VkRenderingInfo-colorAttachmentCount-09476), so every one-sample colour texture of an /// optimal image, 2D, a 2D array, a cube or a cube array, takes that usage on every device /// where its format renders, whatever Metal's usage. It grows memory on RADV: of optimal @@ -1808,8 +1817,17 @@ pub enum RenderPassKind { /// 780M (every 1920 x 1080 one; `RGBA8Unorm` of one level from 8,847,360 to 8,896,512 bytes, /// 1.0056 times) and 14 of 36 on the RX 550 (8,847,360 to 8,882,200), alignments equal, and /// none on the Iris Xe, the RTX 3090, llvmpipe or KosmicKrisp (jobs m3-max-59774, m3-max-59775 - /// and m3-max-59776). No depth format was measured, so a depth or stencil texture takes no - /// attachment usage for a resolve alone. + /// and m3-max-59776). A texture's linear image in place over a buffer of the runtime's own + /// memory takes it too, where the device's linear tiling renders its format and its query + /// makes the image with it: of each colour format a texture over a buffer is made of, at 600 x + /// 600 and 1920 x 1080, of `ShaderRead` and `ShaderRead | ShaderWrite` usage, adding the + /// attachment usage changed no linear image's row pitch, offset, size, alignment or memory + /// types on the Radeon 780M, the RX 550, the RX 7900 XTX, the Iris Xe, the RTX 3090 (where + /// its query makes the image) and llvmpipe, so no texture leaves its place for it; the linear + /// tiling features of the RTX 3090 and of KosmicKrisp hold the attachment for none of them, so + /// there no such texture takes it (jobs m3-max-67028, m3-max-67035, m3-max-67029, + /// m3-max-67030, m3-max-67031, m3-max-67021 and m3-max-67032). No depth format was measured, + /// so a depth or stencil texture takes no attachment usage for a resolve alone. ResolveUsage, /// A depth or stencil resolve the device's resolve modes do not offer /// (`VkPhysicalDeviceDepthStencilResolveProperties`): a depth attachment's `Min` or `Max` diff --git a/crates/metal2vulkan-runtime/src/pass.rs b/crates/metal2vulkan-runtime/src/pass.rs index f7d25b4d4..4b9eb46db 100644 --- a/crates/metal2vulkan-runtime/src/pass.rs +++ b/crates/metal2vulkan-runtime/src/pass.rs @@ -223,9 +223,10 @@ pub struct RenderPassColorAttachmentDescriptor { /// attachment's pixel format and one sample, and its level the attachment level's width and /// height; another is [`Gap::RenderPass`] of [`RenderPassKind::Resolve`]. Metal resolves into /// a texture of any usage, and so does the runtime into a colour texture whose format the - /// device's optimal image renders; into one made without `RenderTarget` usage whose image has - /// no attachment usage, such as a texture over a buffer in place, it is [`Gap::RenderPass`] - /// of [`RenderPassKind::ResolveUsage`]. + /// device's optimal image renders, and into one in place over a buffer whose format the + /// device's linear tiling renders; into one made without `RenderTarget` usage whose image has + /// no attachment usage, such as a texture in place over a buffer whose linear tiling does not + /// render its format, it is [`Gap::RenderPass`] of [`RenderPassKind::ResolveUsage`]. pub resolve_texture: Option, /// `resolveLevel`: the resolve texture's mipmap level resolved into. pub resolve_level: u32, diff --git a/crates/metal2vulkan-runtime/src/tests/resolve.rs b/crates/metal2vulkan-runtime/src/tests/resolve.rs index 913d0b4e6..00a9ca947 100644 --- a/crates/metal2vulkan-runtime/src/tests/resolve.rs +++ b/crates/metal2vulkan-runtime/src/tests/resolve.rs @@ -20,10 +20,15 @@ //! cleared to (0.25, 0.5, 0.75, 1) resolves into a one-sample Shared texture of `ShaderRead` //! usage, and of `ShaderRead | ShaderWrite`, whose image took the attachment usage, and reads //! the clear colour within one code; so does a 900 x 900 pass of every load `Load`, its colour -//! beside a 4-sample `Depth32Float_Stencil8`, of what an earlier pass cleared. A depth resolve -//! into a `Depth32Float` texture of `ShaderRead` usage is the gap `ResolveUsage`, and so is a -//! resolve into a `ShaderRead` texture over a Shared buffer whose linear image lies in place, -//! which stays in place, with no attachment usage. +//! beside a 4-sample `Depth32Float_Stencil8`, of what an earlier pass cleared. So does a 600 x +//! 600 such pass into a `ShaderRead` texture over a Managed and over a Shared buffer, at tight +//! rows, at its row rounded up to the device's linear alignment (where it lies in place on +//! every device) and at 2,560 bytes: in place, its linear image took the attachment usage where +//! the device's linear tiling renders the format, and the pass copies nothing (a Managed +//! buffer's synchronize aside); the buffer reads the clear within one code and keeps the bytes +//! past each row's texels. Where the linear tiling does not render the format, a resolve into +//! such a texture in place is the gap `ResolveUsage`, and so is a depth resolve into a +//! `Depth32Float` texture of `ShaderRead` usage. //! - Under a device cfg, on every device of the cfg's kind, whether it has //! `shaderStorageImageMultisample` or not: a 4-sample `RGBA8Unorm` texture made for shader //! reads, shader writes and rendering, as Metal makes one, has no storage usage in its image and @@ -79,8 +84,8 @@ mod on_device { use crate::{ ClearColor, CullMode, DepthStencilDescriptor, Device, Error, Gap, IndexClass, LoadAction, MemoryClass, MultisampleDepthResolveFilter, MultisampleStencilResolveFilter, PixelFormat, - PrecisionNote, PrimitiveType, Refusal, Region, RenderPassKind, StorageMode, StoreAction, - Texture, TextureDescriptor, TextureType, TextureUsage, + PrecisionNote, PrimitiveType, Refusal, Region, RenderPassKind, Resource, StorageMode, + StoreAction, Texture, TextureDescriptor, TextureType, TextureUsage, }; use ash::vk; @@ -592,9 +597,8 @@ mod on_device { /// Probe `resolve_texture_usage.m`'s case, which Metal resolves: a 4-sample /// `BGRA8Unorm_sRGB` attachment cleared to (0.25, 0.5, 0.75, 1) resolves into a one-sample /// Shared texture of `ShaderRead` usage, and of `ShaderRead | ShaderWrite`, whose image took - /// the attachment usage. And the resolves the runtime does not build into a texture of no - /// `RenderTarget` usage: a depth one, and one into a texture over a Shared buffer in place, - /// whose linear image takes no attachment usage. + /// the attachment usage. And the resolve the runtime does not build into a texture of no + /// `RenderTarget` usage: a depth one. #[test] fn every_device_resolves_into_a_texture_of_shader_read_usage() { each_device("resolve_usage", |name, _, device| { @@ -655,43 +659,7 @@ mod on_device { "{name}: a depth resolve into a ShaderRead texture" ); - // A resolve into a texture over a Shared buffer. - let format = PixelFormat::RGBA8Unorm; - let align = (device.minimum_linear_texture_alignment(format)) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let pitch = u64::from(SIDE * 4).next_multiple_of(align); - let len = u64::from(SIDE) * pitch; - let block = (device.take_block(MemoryClass::Shared, len)) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let buffer = (device.new_buffer(block.id, 0, len, None)) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let mut td = TextureDescriptor::new(TextureType::Type2D, format, SIDE, SIDE); - td.usage = TextureUsage::SHADER_READ; - let first = IndexClass::Texture.range().start; - (device.grant_indices(IndexClass::Texture, first, 1)).expect("a grant"); - let index = Some(first); - let over = (buffer.new_texture(&td, index, 0, pitch)) - .unwrap_or_else(|error| panic!("{name}: {error}")); - if over.copied_over().is_some() { - println!("{name}: the texture over the buffer is copied, not in place"); - } else { - let image = over.object().image_usage(); - assert!( - !image.contains(vk::ImageUsageFlags::COLOR_ATTACHMENT), - "{name}: in place over the buffer, the image's usage {:#x}", - image.as_raw() - ); - let mut p = pass(&color, None); - p.color_attachments[0].store_action = StoreAction::MultisampleResolve; - p.color_attachments[0].resolve_texture = Some(over.clone()); - assert_eq!( - refused(&device, &p).map(|e| e.to_string()), - Some(gap(RenderPassKind::ResolveUsage).to_string()), - "{name}: a resolve into a ShaderRead texture in place over a buffer" - ); - println!("{name}: in place over a buffer, a resolve into it is ResolveUsage"); - } - drop((samples, color, depth, over, buffer, block)); + drop((samples, color, depth)); }); } @@ -743,4 +711,169 @@ mod on_device { println!("{name}: the 900 x 900 loaded pass resolved into a ShaderRead texture"); }); } + + /// The pass of a guest's walk into a texture over a buffer, which Metal resolves (probe + /// `resolve_texture_usage.m`'s `over` and `over-padded`): 600 x 600, a 4-sample + /// `BGRA8Unorm_sRGB` colour beside a 4-sample `Depth32Float_Stencil8` depth and stencil, + /// every load `Load`, the colour resolved into a one-sample `BGRA8Unorm_sRGB` texture of + /// `ShaderRead` usage over a Managed buffer and over a Shared one, at offset 0, its rows + /// 2,400 bytes apart (tight), its row rounded up to the device's linear alignment, and 2,560. + /// At the rounded row the texture lies in place on every device. In place, its linear image + /// took the attachment usage where the device's linear tiling renders its format, and the + /// pass copies nothing; copied, the copies are counted. The buffer's bytes read the clear + /// within one code, and the bytes past each row's texels keep the host's. Where the linear + /// tiling does not render the format, a resolve into the texture in place is `ResolveUsage`. + #[test] + fn every_device_resolves_a_loaded_pass_into_a_shader_read_texture_over_a_buffer() { + const WALK: u32 = 600; + const ROW: u64 = WALK as u64 * 4; + each_device("resolve_over", |name, _, device| { + let format = PixelFormat::BGRA8UnormSRGB; + let color = four_of(name, &device, format, WALK) + .unwrap_or_else(|error| panic!("{name}: Vulkan requires 4 samples: {error}")); + let Ok(depth) = four_of(name, &device, PixelFormat::Depth32FloatStencil8, WALK) else { + println!("{name}: no 4-sample Depth32Float_Stencil8"); + return; + }; + let attached = |load: LoadAction| { + let mut p = pass(&color, None); + p.color_attachments[0].load_action = load; + p.depth_attachment.texture = Some(depth.clone()); + p.depth_attachment.load_action = load; + p.depth_attachment.store_action = StoreAction::Store; + p.stencil_attachment.texture = Some(depth.clone()); + p.stencil_attachment.load_action = load; + p.stencil_attachment.store_action = StoreAction::Store; + p + }; + let mut first = attached(LoadAction::Clear); + first.color_attachments[0].clear_color = CLEAR; + first.color_attachments[0].store_action = StoreAction::Store; + let align = (device.minimum_linear_texture_alignment(format)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let rounded = ROW.next_multiple_of(align); + let mut pitches = vec![ROW, rounded, 2_560]; + pitches.dedup(); + let mut index = IndexClass::Texture.range().start; + (device.grant_indices(IndexClass::Texture, index, 2 * pitches.len() as u32)) + .expect("a grant"); + let queue = device.new_command_queue(1).expect("a queue"); + for pitch in pitches { + for managed in [true, false] { + let kind = if managed { "Managed" } else { "Shared" }; + let len = u64::from(WALK) * pitch; + let block = (device.take_block(MemoryClass::Shared, len)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let buffer = match managed { + true => crate::tests::managed::on_device::new_managed( + &device, block.id, 0, len, 0, + ), + false => device.new_buffer(block.id, 0, len, None), + } + .unwrap_or_else(|error| panic!("{name}: {kind}: {error}")); + let contents = buffer.contents().expect("host bytes"); + // SAFETY: the buffer's bytes, which no command uses yet. + unsafe { contents.as_ptr().write_bytes(0xee, len as usize) }; + if managed { + (buffer.did_modify_range(0, len)).expect("a modified range"); + } + let mut td = TextureDescriptor::new(TextureType::Type2D, format, WALK, WALK); + td.usage = TextureUsage::SHADER_READ; + let over = (buffer.new_texture(&td, Some(index), 0, pitch)) + .unwrap_or_else(|error| panic!("{name}: {kind} at {pitch}: {error}")); + index += 1; + let in_place = over.copied_over().is_none(); + assert!( + in_place || pitch != rounded, + "{name}: {kind}: at its row rounded up to {align}, in place" + ); + let renders = over + .object() + .image_usage() + .contains(vk::ImageUsageFlags::COLOR_ATTACHMENT); + let (linear, _) = device.core().format_features(TextureObject::format(&over)); + let tiling = linear.contains(vk::FormatFeatureFlags2::COLOR_ATTACHMENT); + let form = match in_place { + true => "in place", + false => "copied", + }; + let mut walk = attached(LoadAction::Load); + walk.color_attachments[0].store_action = StoreAction::MultisampleResolve; + walk.color_attachments[0].resolve_texture = Some(over.clone()); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let encoder = (command_buffer.render_command_encoder(&first)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + if in_place && !tiling { + assert!(!renders, "{name}: {kind} at {pitch}: no attachment usage"); + assert_eq!( + (command_buffer.render_command_encoder(&walk).err()) + .map(|e| e.to_string()), + Some(gap(RenderPassKind::ResolveUsage).to_string()), + "{name}: {kind} at {pitch}: in place, its tiling renders no {format:?}" + ); + run(name, &command_buffer); + println!( + "resolve_over: {name}: {kind} pitch {pitch}: in place, its linear \ + tiling renders no {format:?}: ResolveUsage" + ); + continue; + } + assert!( + renders, + "{name}: {kind} at {pitch}: {form}, the attachment usage" + ); + let before = device.counters().metrics(); + let encoder = (command_buffer.render_command_encoder(&walk)) + .unwrap_or_else(|error| panic!("{name}: {kind} at {pitch}: {error}")); + encoder.end_encoding(); + if managed { + let mut blit = command_buffer.blit_command_encoder().expect("a blit"); + (blit.synchronize_resource(Resource::Buffer(&buffer))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + blit.end_encoding(); + } + run(name, &command_buffer); + let after = device.counters().metrics(); + assert_eq!(after.resolves - before.resolves, 1, "{name}: one resolve"); + let copied = after.bytes_copied - before.bytes_copied; + // A Managed buffer's synchronize copies its device copy, where it has one. + let synchronized = managed && !device.has_unified_memory(); + assert!( + ((copied == 0 || synchronized) && in_place) || (copied > 0 && !in_place), + "{name}: {kind} at {pitch}: {form}, {copied} bytes copied" + ); + // SAFETY: the buffer's bytes, which no command uses now. + let held = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), len as usize) }; + let (row, pitch_bytes) = (ROW as usize, pitch as usize); + let texels: Vec = (held.chunks(pitch_bytes)) + .flat_map(|r| r[..row].iter().copied()) + .collect(); + let past = (held.chunks(pitch_bytes)).flat_map(|r| &r[row..]); + let changed = past.filter(|&&byte| byte != 0xee).count(); + cleared(name, &texels); + assert_eq!( + changed, 0, + "{name}: {kind} at {pitch}: bytes past the texels" + ); + let fnv = (texels.iter()).fold(0xcbf2_9ce4_8422_2325u64, |hash, &byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + println!( + "resolve_over: {name}: {kind} pitch {pitch}: {form}, resolved; texels fnv \ + {fnv:016x} (0,0)={:02x}{:02x}{:02x}{:02x}; {changed} of {} bytes past \ + the texels changed; bytes copied {copied}", + texels[0], + texels[1], + texels[2], + texels[3], + (pitch - ROW) * u64::from(WALK) + ); + drop((over, buffer, block)); + } + } + drop((color, depth)); + }); + } } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index b50630cae..1ee4181e7 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -1388,7 +1388,7 @@ impl Device { source: Source<'_>, ) -> Result { let d = *descriptor; - let (shape, plan, usage) = self.prepare(&d)?; + let (shape, mut plan, usage) = self.prepare(&d)?; let index = match reach { Reach::Index(index) if reached(d.pixel_format, usage) != index.is_some() => { return Err(Error::Refused(Refusal::TextureIndex { index })); @@ -1416,7 +1416,8 @@ impl Device { (Some(named), vk::ImageLayout::UNDEFINED, plan.home) } Source::Over(buffer, offset, bytes_per_row) => { - let checked = check_over(core, &d, &shape, &plan, buffer, *offset, *bytes_per_row)?; + let checked = + check_over(core, &d, &shape, &mut plan, buffer, *offset, *bytes_per_row)?; laid = checked.ok(); let named = Named { buffer: Arc::clone(buffer.object()), @@ -1439,6 +1440,9 @@ impl Device { let placed = matches!(source, Source::Plain | Source::Managed(..)); // Over a dma-buf's import in place, the import's buffer and the image's offset in it. let mut acquired = None; + // In place, where its linear image takes the attachment usage for resolves, the bytes + // from its first texel a resolve into it may reach (`render_reach`). + let mut resolve_reach = None; let (bind, mut block) = match source { Source::Plain | Source::Managed(..) => (Bind::Pooled, None), Source::Heap(block, heap, offset) => { @@ -1481,6 +1485,8 @@ impl Device { let rows = u64::from(d.height) * bytes_per_row; let reach = (usage.contains(TextureUsage::RENDER_TARGET)) .then(|| render_reach(rows, buffer.length() - offset)); + resolve_reach = + (plan.linear_resolves).then(|| render_reach(rows, buffer.length() - offset)); let bind = Bind::InPlace { memory: memory.device_memory(), base: memory.base(), @@ -1520,6 +1526,21 @@ impl Device { // (`Plan::linear_usage`); any other keeps its home, shader-read-only or general, which a // pass moves it from to the feedback layout and back. let laid_over = named.as_ref().is_some_and(|n| n.form == Form::InPlace); + // A pass resolves into a linear image in place where its subresource lies within its + // own rows and the buffer, as a resolve may write back any byte of it (Vulkan's + // multisample resolve operations); else it takes no attachment use, and stays in place. + let resolved = laid_over + && resolve_reach.is_some_and(|reach| { + let color = vk::ImageSubresource { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + array_layer: 0, + }; + // SAFETY: the image is the device's, linear, of one level and layer of a colour + // format. + let layout = unsafe { core.device.get_image_subresource_layout(image, color) }; + in_reach(layout.size, Some(reach)) + }); let attachment_reads = plan.attachment_reads && !laid_over; // On a device without the feedback loop, a draw reads such an image through its shadow. let shadowing = (attachment_reads && core.feedback.is_none()).then(|| { @@ -1541,10 +1562,12 @@ impl Device { shadow: false, aspects: plan.aspects, format: plan.format, - // A linear image in place takes no attachment usage for a resolve alone. - usage: match laid_over { - true => plan.usage, - false => plan.image_usage(), + // A linear image in place takes the attachment usage for its resolves where they stay + // within reach. + usage: match (laid_over, resolved) { + (true, true) => plan.usage | vk::ImageUsageFlags::COLOR_ATTACHMENT, + (true, false) => plan.usage, + (false, _) => plan.image_usage(), }, view_formats: plan.view_formats.clone(), cube: plan.cube, @@ -1682,9 +1705,15 @@ struct Plan { /// one-sample colour texture, 2D, a 2D array, a cube or a cube array, made without /// `RenderTarget` usage, where the format's features hold the attachment and the device's image /// format query makes the image with it at the texture's extent ([`plan`]). A linear image in - /// place over a buffer, of `linear_usage`, takes no attachment usage for a resolve alone, so it - /// stays in place. + /// place over a buffer takes it on its own terms (`linear_resolves`). resolves: bool, + /// The linear image of a texture in place over a buffer of the runtime's own memory takes the + /// colour attachment usage too, so that a pass resolves into it as into the optimal image of + /// `resolves`: where the plan resolves, the device's linear tiling features hold the + /// attachment and its image format query makes the linear image with it at the texture's + /// extent ([`check_over`]). Its layout is the one it has without it on every venue counted + /// (`RenderPassKind::ResolveUsage`), so no texture leaves its place for it. + linear_resolves: bool, } impl Plan { @@ -1700,12 +1729,16 @@ impl Plan { /// The usage of a linear image of the plan, over a buffer in place: without the feedback /// usage, as no pass moves it to the feedback layout, and without the sampled usage where /// shaders do not read the texture, as a colour render target takes it for attachment reads - /// alone. + /// alone; with the colour attachment usage where a pass resolves into it + /// (`linear_resolves`). fn linear_usage(&self) -> vk::ImageUsageFlags { let mut usage = self.usage & !vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT; if !self.read { usage &= !vk::ImageUsageFlags::SAMPLED; } + if self.linear_resolves { + usage |= vk::ImageUsageFlags::COLOR_ATTACHMENT; + } usage } @@ -1749,6 +1782,7 @@ impl Plan { storage: false, attachment_reads: false, resolves: false, + linear_resolves: false, view_formats: self.view_formats.clone(), ..*self } @@ -1840,12 +1874,14 @@ fn check_places( /// the answer: memory that did not spill, of a block of the runtime's own or a dma-buf's one /// import, for a format and usage the device makes linear images of (for that dma-buf, where the /// image binds in its memory), with every format feature its optimal image has that the usage -/// uses. Where the texture is the counted copy, why ([`OverCause`]). +/// uses. Where the texture is the counted copy, why ([`OverCause`]). Where it lies in place in a +/// block of the runtime's own, whether its linear image takes the colour attachment usage for +/// a pass's resolves (`Plan::linear_resolves`). fn check_over( core: &Core, d: &TextureDescriptor, shape: &Shape, - plan: &Plan, + plan: &mut Plan, buffer: &Buffer, offset: u64, bytes_per_row: u64, @@ -1901,10 +1937,20 @@ fn check_over( (None, Some(own)) => return Ok(Err(memory_cause(own))), }; let spilled = copy.is_none() && block.memory.spilled(); - let extent = linear_extent(core, shape, plan, laid.handle()) - .is_some_and(|max| d.width <= max.width && d.height <= max.height); + let fits = |max: Option| { + max.is_some_and(|max| d.width <= max.width && d.height <= max.height) + }; + let extent = fits(linear_extent(core, shape, plan, laid.handle())); let (linear, optimal) = core.format_features(plan.format); let features = linear.contains(optimal & kept_features(plan.usage)); + // In place in a block of the runtime's own, its linear image takes the colour attachment + // usage where the plan resolves, its tiling's features hold the attachment and the query + // makes the image with it; else it is made without it, and stays in place. + let attached = linear.contains(vk::FormatFeatureFlags2::COLOR_ATTACHMENT); + if !spilled && extent && features && plan.resolves && attached && matches!(laid, Laid::Own) { + plan.linear_resolves = true; + plan.linear_resolves = fits(linear_extent(core, shape, plan, None)); + } Ok(if spilled { Err(OverCause::Spilled) } else if !extent { @@ -2572,6 +2618,7 @@ fn form(core: &Core, d: &TextureDescriptor, usage: TextureUsage) -> Result Result {