diff --git a/crates/metal2vulkan-runtime/src/tests/attachment_views.rs b/crates/metal2vulkan-runtime/src/tests/attachment_views.rs index bbaa08ffc..9d1d7196e 100644 --- a/crates/metal2vulkan-runtime/src/tests/attachment_views.rs +++ b/crates/metal2vulkan-runtime/src/tests/attachment_views.rs @@ -190,4 +190,148 @@ mod on_device { drop((queue, other, device)); }); } + + /// A 1-mip, 1-layer 2D color render target with identity swizzle and a sampled view reuses + /// its sampled `VkImageView` directly for render-pass attachments without calling + /// `vkCreateImageView` a second time or bumping `Gauge::AttachmentViews`. + #[test] + fn every_device_reuses_sampled_view_for_single_slice_2d_color_attachment() { + each_device("attachment_views_reuse_sampled", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 1) + .expect("a grant"); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::BGRA8Unorm, 8, 8); + d.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + d.storage_mode = StorageMode::Private; + let tex = device.new_texture(&d, Some(4096)).expect("a 2D target"); + + let before_creates = counters.metrics().image_view_creates.count; + let before_gauge = counters.gauges().attachment_views; + run(name, &queue, &tex, 0, 1); + assert_eq!( + counters.metrics().image_view_creates.count, + before_creates, + "{name}: render pass must reuse sampled view without vkCreateImageView" + ); + assert_eq!( + counters.gauges().attachment_views, + before_gauge, + "{name}: AttachmentViews gauge stays unchanged on sampled-view reuse" + ); + assert!( + views(&tex).is_empty(), + "{name}: no AttachmentView pushed into attachments list" + ); + drop(tex); + within("reused sampled view drops cleanly", || { + counters.gauges().attachment_views == before_gauge + }); + drop((queue, device)); + }); + } + + /// Combined depth-stencil, swizzled, and multi-mip textures must NOT reuse their sampled view + /// for render-pass attachments (Vulkan requires full attachment aspects, identity swizzle, + /// and a single mip level). + #[test] + fn every_device_allocates_dedicated_attachment_view_when_sampled_view_is_ineligible() { + each_device("attachment_views_ineligible_sampled", |name, _, device| { + use crate::{TextureSwizzle, TextureSwizzleChannels}; + device + .grant_indices(IndexClass::Texture, 4096, 4) + .expect("a grant"); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + + // (1) Combined Depth32FloatStencil8: sampled view has DEPTH aspect only, attachment needs DEPTH|STENCIL. + let mut ds_desc = TextureDescriptor::new( + TextureType::Type2D, + PixelFormat::Depth32FloatStencil8, + 8, + 8, + ); + ds_desc.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + ds_desc.storage_mode = StorageMode::Private; + let ds = device.new_texture(&ds_desc, Some(4096)).expect("ds target"); + + // (2) Non-identity swizzle on a 1-mip 2D color target (created via view, since Metal + // permits swizzled views over RENDER_TARGET textures while rejecting swizzle on the + // texture's own descriptor). + let mut base_desc = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 8, 8); + base_desc.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + base_desc.storage_mode = StorageMode::Private; + let base = device + .new_texture(&base_desc, Some(4097)) + .expect("base target"); + let swz = base + .new_texture_view_with_swizzle( + PixelFormat::RGBA8Unorm, + TextureType::Type2D, + 0..1, + 0..1, + TextureSwizzleChannels { + red: TextureSwizzle::Blue, + green: TextureSwizzle::Green, + blue: TextureSwizzle::Red, + alpha: TextureSwizzle::Alpha, + }, + Some(4098), + ) + .expect("swizzled view"); + + // (3) Multi-mip 2D color target. + let mut mip_desc = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 8, 8); + mip_desc.mipmap_level_count = 2; + mip_desc.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + mip_desc.storage_mode = StorageMode::Private; + let mip = device + .new_texture(&mip_desc, Some(4099)) + .expect("mipped target"); + + let before_creates = counters.metrics().image_view_creates.count; + let before_gauge = counters.gauges().attachment_views; + + // Clear depth-stencil + swizzled color together, then clear level 0 of multi-mip. + let cb = queue.command_buffer().expect("cb"); + let mut rp = RenderPassDescriptor::default(); + rp.color_attachments[0].texture = Some(swz.clone()); + rp.color_attachments[0].load_action = LoadAction::Clear; + rp.color_attachments[0].store_action = StoreAction::Store; + rp.depth_attachment.texture = Some(ds.clone()); + rp.depth_attachment.load_action = LoadAction::Clear; + rp.depth_attachment.store_action = StoreAction::Store; + rp.stencil_attachment.texture = Some(ds.clone()); + rp.stencil_attachment.load_action = LoadAction::Clear; + rp.stencil_attachment.store_action = StoreAction::Store; + cb.render_command_encoder(&rp) + .expect("swz+ds pass") + .end_encoding(); + cb.commit().expect("commit"); + finished(name, &cb); + assert_eq!(cb.error(), None, "{name}: swz+ds pass"); + + run(name, &queue, &mip, 0, 1); + + assert_eq!( + counters.metrics().image_view_creates.count, + before_creates + 3, + "{name}: ds, swizzled, and multi-mip must each allocate a dedicated attachment view" + ); + assert_eq!( + counters.gauges().attachment_views, + before_gauge + 3, + "{name}: AttachmentViews gauge must reflect all 3 dedicated views" + ); + + drop((ds, swz, base, mip, rp, cb)); + within("all 3 dedicated views freed", || { + counters.gauges().attachment_views == before_gauge + }); + drop((queue, device)); + }); + } } diff --git a/crates/metal2vulkan-runtime/src/tests/pass.rs b/crates/metal2vulkan-runtime/src/tests/pass.rs index d6f139449..1eacc7b79 100644 --- a/crates/metal2vulkan-runtime/src/tests/pass.rs +++ b/crates/metal2vulkan-runtime/src/tests/pass.rs @@ -427,10 +427,12 @@ mod on_device { (1, 3, 0, 1), "{name}: submissions, barriers, bytes copied, passes" ); + // `colors` (2 mips) and `stencil` (no sampled view) allocate attachment views; + // 1-mip 1-layer 2D `words` reuses its compatible sampled view directly. assert_eq!( counters.gauges().attachment_views - views, - 3, - "{name}: a view of each attachment" + 2, + "{name}: a view of each attachment without a reusable sampled view" ); assert_eq!(read(&colors, 0, 0, 4), level0, "{name}: level 0 kept"); assert_eq!( @@ -488,7 +490,7 @@ mod on_device { ); assert_eq!( counters.gauges().attachment_views - views, - 3, + 2, "{name}: views kept" ); assert_eq!( diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 1ca153307..c03e34630 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -500,6 +500,10 @@ struct View { /// parent's, as Metal combines them, or its parent's where it was made with none. reads: TextureSwizzleChannels, views: Views, + /// `views.sampled` satisfies every Vulkan render-pass attachment-view invariant (2D, 1 mip, + /// 1 layer, identity swizzle, full image aspects, attachment usage) and can be reused directly + /// by [`TextureObject::attachment_view`] with `Attachment.held = None`. + sampled_is_attachment: bool, /// The view is of a format the device stores, which its texture, made for shader writes, /// lists, but the device's image format query made the image without the storage usage for it /// ([`Plan`]'s `extended`): it has no storage element ([`StorageElementCase::Unextended`]). @@ -534,6 +538,10 @@ pub(crate) struct Image { /// the view a draw reads an attachment through (`attachment_reads`), which a colour render /// target not read has for that alone. sampled: Option, + /// `sampled` satisfies every Vulkan render-pass attachment-view invariant (2D, 1 mip, 1 layer, + /// identity swizzle, full image aspects, attachment usage) and can be reused directly by + /// [`TextureObject::attachment_view`] with `Attachment.held = None`. + sampled_is_attachment: bool, /// The view of the storage-texture array's element, where shaders write it and the device /// stores its format through a storage image without a format. storage: Option, @@ -1125,7 +1133,7 @@ impl Image { let (d, shape, plan) = &shadowing.made; // SAFETY: the device is live, and the texture's plan checked the shadow's usage against // its image format query for the shape (`plan`). - let (image, backing, bytes, _, _) = unsafe { make(core, d, shape, plan, Bind::Pooled) } + let (image, backing, bytes, _, _, _) = unsafe { make(core, d, shape, plan, Bind::Pooled) } .map_err(|unmade| unmade.error(d))?; core.counters.rise(Gauge::Shadows); core.counters.rise_by(Gauge::ShadowBytes, bytes); @@ -1135,6 +1143,7 @@ impl Image { backing, bytes, sampled: None, + sampled_is_attachment: false, storage: None, home: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, attachment_reads: false, @@ -1753,12 +1762,12 @@ impl Device { let mut made = Made::default(); // SAFETY: the image is the device's and bound (the caller's contract), of the plan's // format, and has the plan's usage. - let views = unsafe { made.views(core, image, &shape, &plan, plan.usage) }; + let views = unsafe { made.views(core, image, &shape, &plan, plan.usage, 1) }; if views.is_err() { // SAFETY: nothing else holds the views; `made` holds no image. unsafe { made.destroy(core) }; } - let (sampled, storage) = views?; + let (sampled, storage, sampled_is_attachment) = views?; core.counters.rise(Gauge::Textures); let image = Arc::new(Image { core: Arc::clone(core), @@ -1766,6 +1775,7 @@ impl Device { backing: Backing::Drawable, bytes: 0, sampled, + sampled_is_attachment, storage, home: plan.home, attachment_reads: false, @@ -2022,7 +2032,8 @@ impl Device { // SAFETY: as above. made = unsafe { make(core, &d, &shape, &plan, Bind::Pooled) }; } - let (image, backing, bytes, sampled, storage) = made.map_err(|unmade| unmade.error(&d))?; + let (image, backing, bytes, sampled, storage, sampled_is_attachment) = + made.map_err(|unmade| unmade.error(&d))?; // The import's range the image's memory is: its bytes from its place. let foreign = acquired.map(|(buffer, offset)| (buffer, offset, bytes)); core.counters.rise(Gauge::Textures); @@ -2092,6 +2103,7 @@ impl Device { backing, bytes, sampled, + sampled_is_attachment, storage, home, attachment_reads, @@ -3707,14 +3719,22 @@ fn whole(aspects: vk::ImageAspectFlags) -> vk::ImageSubresourceRange { } } -/// The image, its memory and the memory's bytes, and its views (the sampled view and the storage -/// view). +fn is_identity_component_mapping(components: vk::ComponentMapping) -> bool { + components.r == vk::ComponentSwizzle::IDENTITY + && components.g == vk::ComponentSwizzle::IDENTITY + && components.b == vk::ComponentSwizzle::IDENTITY + && components.a == vk::ComponentSwizzle::IDENTITY +} + +/// The image, its memory and the memory's bytes, its views (the sampled view and the storage +/// view), and whether the sampled view can be reused directly as a render-pass attachment view. type Objects = ( vk::Image, Backing, u64, Option, Option, + bool, ); /// Why [`make`] made no image. @@ -4031,13 +4051,15 @@ impl Made { bound.map_err(Error::vulkan("vkBindImageMemory"))?; // SAFETY: the image is bound, of the plan's format, and has `info`'s usage. let usage = info.usage; - let (sampled, storage) = unsafe { self.views(core, image, shape, plan, usage) }?; + let (sampled, storage, sampled_is_attachment) = + unsafe { self.views(core, image, shape, plan, usage, d.mipmap_level_count) }?; return Ok(( image, Backing::Import(memory, requirements.size), requirements.size, sampled, storage, + sampled_is_attachment, )); } let memory_fits = dedicated.requires_dedicated_allocation == vk::FALSE @@ -4132,8 +4154,16 @@ impl Made { bound.map_err(Error::vulkan("vkBindImageMemory"))?; // SAFETY: the image is bound, of the plan's format, and has `info`'s usage. let usage = info.usage; - let (sampled, storage) = unsafe { self.views(core, image, shape, plan, usage) }?; - Ok((image, backing, requirements.size, sampled, storage)) + let (sampled, storage, sampled_is_attachment) = + unsafe { self.views(core, image, shape, plan, usage, d.mipmap_level_count) }?; + Ok(( + image, + backing, + requirements.size, + sampled, + storage, + sampled_is_attachment, + )) } /// Makes `image`'s views of `plan`: its sampled view, where it has one and the image's @@ -4152,22 +4182,53 @@ impl Made { shape: &Shape, plan: &Plan, usage: vk::ImageUsageFlags, - ) -> Result<(Option, Option), Error> { + mip_levels: u32, + ) -> Result<(Option, Option, bool), Error> { let own = plan.own_views(usage); - let mut view = |view_type, (format, own), components, aspect| { + let single_2d = + shape.view_type == vk::ImageViewType::TYPE_2D && mip_levels == 1 && shape.layers == 1; + let mut view = |view_type, (format, own), components, aspect, explicit_single| { // SAFETY: the caller's contract. - let range = whole(aspect); + let range = if explicit_single { + vk::ImageSubresourceRange { + aspect_mask: aspect, + base_mip_level: 0, + level_count: 1, + base_array_layer: 0, + layer_count: 1, + } + } else { + whole(aspect) + }; let view = unsafe { image_view(core, image, view_type, format, components, range, own) }?; self.views.push(view); Ok::<_, Error>(view) }; let sampled = match plan.sampled { - Some((components, aspect)) if usage.contains(vk::ImageUsageFlags::SAMPLED) => Some( - view(shape.view_type, (plan.format, own), components, aspect)?, - ), + Some((components, aspect)) if usage.contains(vk::ImageUsageFlags::SAMPLED) => { + Some(view( + shape.view_type, + (plan.format, own), + components, + aspect, + single_2d, + )?) + } _ => None, }; + let renders = + vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT; + let effective_usage = own.unwrap_or(usage); + let sampled_is_attachment = matches!( + plan.sampled, + Some((components, aspect)) + if sampled.is_some() + && single_2d + && is_identity_component_mapping(components) + && aspect == plan.aspects + && effective_usage.intersects(renders) + ); // An sRGB texture's storage view is its UNORM twin's, of the storage usage alone. let twin = (plan.twin).map(|twin| (twin, Some(vk::ImageUsageFlags::STORAGE))); let storage = match plan.storage.then_some((plan.format, own)).or(twin) { @@ -4176,10 +4237,11 @@ impl Made { format, vk::ComponentMapping::default(), vk::ImageAspectFlags::COLOR, + false, )?), None => None, }; - Ok((sampled, storage)) + Ok((sampled, storage, sampled_is_attachment)) } /// Destroys what was made, the allocation's gauge falling with it. @@ -5197,6 +5259,20 @@ impl Texture { // view is refused its index. made?; let image = inner.imaged(); + let renders = + vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT; + let sampled_is_attachment = matches!( + plan.sampled, + Some((components, aspect)) + if sampled.is_some() + && views_usage.is_none() + && shape.view_type == vk::ImageViewType::TYPE_2D + && level_count == 1 + && shape.layers == 1 + && is_identity_component_mapping(components) + && aspect == image.aspects + && image.usage.intersects(renders) + ); let shadow = ShadowView::of(image, &plan, index, shape.view_type, range); let index = match index { Some(index) => { @@ -5256,6 +5332,7 @@ impl Texture { base, reads, views, + sampled_is_attachment, unextended, extended, }), @@ -5989,7 +6066,7 @@ pub(crate) trait TextureObject { None => { // SAFETY: the device is live, and the texture's plan checked the image's usage // against its image format query for the shape (`Plan::resolves`). - let (image, backing, bytes, _, _) = + let (image, backing, bytes, _, _, _) = unsafe { make(core, d, shape, plan, Bind::Pooled) } .map_err(|unmade| unmade.error(d))?; core.counters.rise(Gauge::ResolveImages); @@ -6084,7 +6161,8 @@ pub(crate) trait TextureObject { })); } // SAFETY: the device is live, and the plan was checked against its image format query. - let (image, backing, bytes, _, _) = unsafe { make(core, &d, &shape, &plan, Bind::Pooled) } + let (image, backing, bytes, _, _, _) = + unsafe { make(core, &d, &shape, &plan, Bind::Pooled) } .map_err(|unmade| unmade.error(&d))?; core.counters.rise(Gauge::PlaneStandIns); core.counters.rise_by(Gauge::PlaneStandInBytes, bytes); @@ -6197,6 +6275,41 @@ pub(crate) trait TextureObject { samples: vk::SampleCountFlags::from_raw(d.sample_count), linear: image.stand_ins.is_some(), }; + if level == 0 + && slice == 0 + && plane.is_none() + && layers == 1 + && d.mipmap_level_count == 1 + && slices(d) == 1 + { + let reusable = match &self.object().view { + Some(view) => view + .sampled_is_attachment + .then_some(view.views.sampled) + .flatten(), + None => image + .sampled_is_attachment + .then_some(image.sampled) + .flatten(), + }; + if let Some(view) = reusable { + return Ok(Attachment { + view, + held: None, + image: image.image, + level: level_in_image, + layer, + layers, + volume: false, + aspects: image.aspects, + home: image.home, + extent: [d.width, d.height], + format: self.object().format, + samples: vk::SampleCountFlags::from_raw(d.sample_count), + linear: image.stand_ins.is_some(), + }); + } + } if let Some(held) = self.object().sole_attachment.get().filter(|held| { (held.level, held.layer, held.layers) == (level_in_image, first, layers) @@ -7378,8 +7491,8 @@ impl Device { let mut views = Made::default(); // SAFETY: the image is the device's and bound, of the plan's format or mutable with it // listed, with the plan's usage and more, which the plan's format's features hold. - let made_views = unsafe { views.views(core, made.image, &shape, &plan, made.usage) }; - let (sampled, storage) = match made_views { + let made_views = unsafe { views.views(core, made.image, &shape, &plan, made.usage, 1) }; + let (sampled, storage, sampled_is_attachment) = match made_views { Ok(made_views) => made_views, Err(error) => { // SAFETY: nothing else holds the views; `views` holds no image. Nothing uses the @@ -7418,6 +7531,7 @@ impl Device { backing: made.backing, bytes: made.bytes, sampled, + sampled_is_attachment: sampled_is_attachment && made.format == plan.format, storage, home, attachment_reads: looped || shadowing.is_some(),