diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 9c2d5b2b7..86caaf5a8 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -3363,6 +3363,10 @@ fn other_use( let write = access(write, resource.access.write); return texture.rows_use(read, write).map(Some); } + // Any other slot binds the texture's image: a shadow left unmade is made here, + // before the command's copies are planned from its uses + // (`texture/lazy_shadow.rs`). + texture.made_for_use()?; let (read, write) = image_access(resource.class)?; let storage = resource.class == AccessClass::StorageImage; let accesses = ( diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index fd31fc285..d96129bd3 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -2213,7 +2213,7 @@ impl BlitCommandEncoder { // of that format over the same levels: the same bits, filtered alike (a filter // takes each channel alone, and `metal::format::swizzle_over` pairs formats of the // same channels). - match texture.bound_twin() { + match texture.bound_twin()? { Some(twin) => this.mipmaps(&twin), None => this.mipmaps(texture), } diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index ef60de946..2dbc3c818 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1285,6 +1285,13 @@ impl ComputeCommandEncoder { self.core.fail_memoryless_use(); return Ok(()); } + // A texture's shadow left unmade is made as the encoder makes it resident: its resource + // ID reads it from then on (`texture/lazy_shadow.rs`). + for resource in resources { + if let ResourceRef::Texture(texture) = resource { + texture.made_for_use()?; + } + } for &resource in resources { // Its records held where they lie in device-local memory, before any listing of // them reads where they lie (`indirect_command_buffer/home.rs`). diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index a4dc48825..ccbc7ccd8 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -604,6 +604,11 @@ impl DeviceHeaps { }; // The holder may be a texture's last handle: it goes once the lock is free. held.push(texture.clone()); + // A shadow left unmade holds the neutral's entry until it is made, which places it + // (`texture/lazy_shadow.rs`). + if texture.shadow_unmade() { + return self.clear(device, id); + } let facts = texture.facts(); let flags = handle_entry_flags(&facts); let bytes = texture.bytes_key(); diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index f427c7d2c..3aee46fa5 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -202,7 +202,7 @@ impl Texture { /// call answers the new one's. pub unsafe fn vk_image(&self) -> Option { let _held = self.hold(); - if self.shadow().is_some() { + if self.shadows_bytes() { return None; } self.exported_image().ok() diff --git a/crates/metal2vulkan-runtime/src/render/arguments.rs b/crates/metal2vulkan-runtime/src/render/arguments.rs index b184c0265..1bc69a7fa 100644 --- a/crates/metal2vulkan-runtime/src/render/arguments.rs +++ b/crates/metal2vulkan-runtime/src/render/arguments.rs @@ -95,6 +95,13 @@ impl RenderLowering { self.core.fail_memoryless_use(); return Ok(()); } + // A texture's shadow left unmade is made as the encoder makes it resident: its resource + // ID reads it from then on (`texture/lazy_shadow.rs`). + for resource in resources { + if let ResourceRef::Texture(texture) = resource { + texture.made_for_use()?; + } + } for &resource in resources { // Its records held where they lie in device-local memory, before any listing of // them reads where they lie (`indirect_command_buffer/home.rs`). diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index d816f5fbb..42d200be1 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -744,6 +744,8 @@ impl RenderLowering { .map(|texture| (texture, true)); let mut shadows = Vec::new(); for (texture, writes) in tables.chain(snapshot.residency.textures_written()) { + // A shadow left unmade is made here: a command may bind it (`texture/lazy_shadow.rs`). + texture.made_for_use()?; if let Some(copies) = texture.shadow() { let used = ShadowUse { copies: Arc::clone(copies), diff --git a/crates/metal2vulkan-runtime/src/render_pass.rs b/crates/metal2vulkan-runtime/src/render_pass.rs index e6fb7e802..7cbe94ab2 100644 --- a/crates/metal2vulkan-runtime/src/render_pass.rs +++ b/crates/metal2vulkan-runtime/src/render_pass.rs @@ -1940,6 +1940,8 @@ fn target( true => texture.ycbcr_render_shadow(call)?, false => texture.pass_texture()?, }; + // A shadow left unmade is made as the pass's attachment (`texture/lazy_shadow.rs`). + texture.made_for_use()?; let plan = texture.image_plan()?; // A 3D attachment is a 2D view of its planes, which its image takes 2D-array compatible // (`image_plan.rs`): a device whose portability subset withholds `imageView2DOn3DImage` makes diff --git a/crates/metal2vulkan-runtime/src/tests/joined_residency.rs b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs index 812cead2f..dd63802ed 100644 --- a/crates/metal2vulkan-runtime/src/tests/joined_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs @@ -87,7 +87,9 @@ fn shadowed(device: &Device) -> (Buffer, Texture) { descriptor.usage = TextureUsage::SHADER_READ; descriptor.resource_options = buffer.resource_options(); let texture = buffer.new_texture(&descriptor, 0, 352).unwrap(); - assert!(texture.shadow().is_some(), "the device took no shadow"); + // A shadow whose rows are in place is made as a residency makes it resident + // (`texture/lazy_shadow.rs`). + assert!(texture.shadows_bytes(), "the device took no shadow"); (buffer, texture) } diff --git a/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs b/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs index 83a0ab619..87f6a5e28 100644 --- a/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/texel_rows_device.rs @@ -11,6 +11,12 @@ //! - **The shadow still serves a sample.** A kernel that samples the texture after the rows' //! writes, in the same command buffer and in the next, reads the inverted texels through the //! shadow, copied in. +//! - **Its shadow made at use.** The texture is made with its shadow left unmade +//! (`texture/lazy_shadow.rs`): one only written through its rows makes none and copies nothing; +//! the first kernel that samples one makes it at its binding, copied in after an earlier +//! encoder's writes of the rows in the same command buffer, and reads what a texture of the +//! device's own holding the texels gives; a `use_resource` of one makes it at the call +//! (`WorkCounts::shadows_left_unmade`, `shadows_made_at_use`, `shadowed_textures`). //! - **The image route's answers.** The rows read and write what the image route does, bit for //! bit: every `RGBA8Unorm` code read, and a sweep of floats written (each code's value, the //! midpoints between codes, and values outside `[0, 1]`); every `RGBA16Float` code read, and @@ -29,7 +35,7 @@ use crate::{ Buffer, CommandBufferStatus, ComputePipelineState, Device, DeviceKind, DeviceOptions, HostMemory, ImportGate, Region, ResourceOptions, Size, Texture, TextureDescriptor, WorkCounts, }; -use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::metal::{PixelFormat, ResourceUsage, TextureUsage}; use std::alloc::Layout; use std::ptr::NonNull; use std::sync::Arc; @@ -415,6 +421,154 @@ fn reads_and_writes(device: &Device, over: Over) -> bool { true } +/// A dispatch of `invert` (`rows_invert`) over `texture`'s texels. +fn inverting<'a>(invert: &'a ComputePipelineState, texture: &'a Texture) -> Dispatch<'a> { + Dispatch { + state: invert, + texture, + buffer: None, + grid: [SIDE, SIDE], + } +} + +/// Shadows left unmade, made at use, and made in all, from `before` to `after`. +fn unmade_made(before: &WorkCounts, after: &WorkCounts) -> (u64, u64, u64) { + ( + after.shadows_left_unmade - before.shadows_left_unmade, + after.shadows_made_at_use - before.shadows_made_at_use, + after.shadowed_textures - before.shadowed_textures, + ) +} + +/// A texture whose rows are in place is made with its shadow left unmade: a kernel that only +/// writes it through its rows makes none and copies nothing; the first kernel that samples one +/// makes the shadow at its binding, its copy in after an earlier encoder's writes of the rows in +/// the same command buffer, and reads what a texture of the device's own holding those texels +/// gives; a `use_resource` of one makes its shadow at the call. +#[test] +fn a_shadow_is_made_at_the_first_reach_of_its_image() { + let Some(device) = device() else { return }; + let taken: Vec = (OVER.into_iter()) + .filter(|&over| made_at_use(&device, over)) + .collect(); + if untaken_passes(&taken) { + eprintln!("TEXEL-ROWS: this device lays the rows in place; nothing to test"); + } +} + +/// [`a_shadow_is_made_at_the_first_reach_of_its_image`] over a buffer lying as `over` says; +/// `false` where the texture's rows are not read in place. +fn made_at_use(device: &Device, over: Over) -> bool { + let pitch = SIDE * 4 + 16; + let pages = Pages::new((pitch * SIDE) as usize, 11); + let buffer = pages.buffer(device, over); + let shape = (PixelFormat::BGRA8Unorm, SIDE, SIDE); + let invert = state(device, "rows_invert"); + let sample = state(device, "rows_sample"); + let original = pages.bytes(); + let layout = (SIDE, SIDE, 4, pitch); + let inverted: Vec = (tight(&original, layout).as_chunks::<4>().0.iter()) + .flat_map(|t| [255 - t[0], 255 - t[1], 255 - t[2], t[3]]) + .collect(); + // Written through its rows alone: no shadow made, nothing copied, the texels inverted in the + // pages; dropped unmade. + let before = device.work_counts(); + let (written, rows) = texture_over(device, (&buffer, over), shape, pitch); + if !rows { + return false; + } + let made = device.work_counts(); + assert_eq!( + unmade_made(&before, &made), + (1, 0, 0), + "{over:?}: left unmade" + ); + assert!(written.shadow().is_none(), "{over:?}: no shadow"); + let status = run(device, &[inverting(&invert, &written)]); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!( + unmade_made(&made, &after), + (0, 0, 0), + "{over:?}: written, none made" + ); + assert_eq!(shadow_copies(&made, &after), 0, "{over:?}: nothing copied"); + assert!(written.shadow().is_none(), "{over:?}: still no shadow"); + assert!( + tight(&pages.bytes(), layout) == inverted, + "{over:?}: the texels inverted in the pages" + ); + drop(written); + // Inverted back through its rows, then sampled, in one command buffer: the sample's binding + // makes the shadow, whose copy in follows the first encoder's writes. + let before = device.work_counts(); + let (sampled, _) = texture_over(device, (&buffer, over), shape, pitch); + let out = device + .new_buffer(SIDE * SIDE * 16, ResourceOptions::shared()) + .unwrap(); + let made = device.work_counts(); + assert_eq!( + unmade_made(&before, &made), + (1, 0, 0), + "{over:?}: left unmade" + ); + let read = Dispatch { + state: &sample, + texture: &sampled, + buffer: Some(&out), + grid: [SIDE, SIDE], + }; + let status = run(device, &[inverting(&invert, &sampled), read]); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!( + unmade_made(&made, &after), + (0, 1, 1), + "{over:?}: made at the sample" + ); + assert!(shadow_copies(&made, &after) > 0, "{over:?}: copied in"); + assert!(sampled.shadow().is_some(), "{over:?}: a shadow now"); + let answer = contents(&out, (SIDE * SIDE * 16) as usize); + let want = sampled_from( + device, + &sample, + &own_texture(device, shape, 4, &tight(&original, layout)), + ); + let stale = sampled_from(device, &sample, &own_texture(device, shape, 4, &inverted)); + assert_eq!( + first_difference(&answer, &want, 16), + None, + "{over:?}: the sample reads the rows' writes (what the pages held before them: {})", + first_difference(&answer, &stale, 16).is_none() + ); + // A `use_resource` makes it at the call. + let before = device.work_counts(); + let (used, _) = texture_over(device, (&buffer, over), shape, pitch); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + let made = device.work_counts(); + (encoder.use_resource(used.as_resource(), ResourceUsage::READ)).unwrap(); + let after = device.work_counts(); + assert_eq!( + unmade_made(&before, &made), + (1, 0, 0), + "{over:?}: left unmade" + ); + assert_eq!( + unmade_made(&made, &after), + (0, 1, 1), + "{over:?}: made at use_resource" + ); + assert!(used.shadow().is_some(), "{over:?}: a shadow now"); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drop((sampled, used, buffer)); + true +} + /// What `sample` (`rows_sample`) answers for each texel of `texture`, one command buffer of its /// own. fn sampled_from(device: &Device, sample: &ComputePipelineState, texture: &Texture) -> Vec { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 800e135d2..beb0f296b 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -136,6 +136,7 @@ use first_move::{ }; use heap_tiled::{FreshDepth, FreshPattern}; use heap_two_planes::TwoPlaneHeapLayout; +use lazy_shadow::{LazyShadow, Over, ShadowRecipe, StorageCell, Stored}; use metal2vulkan::bind::{AstcDecode, EtcDecode, ImageViewDesc, PvrtcDecode, TextureFacts}; use metal2vulkan::device::{ DeviceDescription, DeviceProfile, DriverFact, FormatSupport, VkFeature, @@ -183,6 +184,7 @@ pub(crate) mod host_copy; pub(crate) mod host_shadow; mod in_place_image; pub(super) mod kept_image; +mod lazy_shadow; pub(super) mod linear_alignment; mod red_held_alpha; pub(super) mod requirements; @@ -507,7 +509,9 @@ pub(super) struct TextureShared { /// A texture's parts on one generation of its device ([`TextureShared::parts`]): its storage /// and what is made of it there. pub(super) struct TextureParts { - storage: Storage, + /// Its storage: made with it, or a shadow left unmade until a reach needs it + /// (`texture/lazy_shadow.rs`). + storage: StorageCell, /// The storage a shadow over host pages made before its pages' in-place verdict moved to /// once the verdict passed (`texture/storage_form.rs`): an image in place over its texels, /// which the texture presents from then on instead of `storage` ([`Texture::storage`]). @@ -584,12 +588,18 @@ impl Drop for TextureShared { self.leave_slot(); return; } - let (owned, device) = match (&self.storage, &self.heap) { - (Storage::Image(image), Some(_)) => (Owned::TextureInHeap, &image.device), - (Storage::Image(image), None) => (Owned::TextureImage, &image.device), - (Storage::Shadow { image, .. }, _) => (Owned::TextureShadow, &image.device), - (Storage::Alias { image, .. }, _) => (Owned::TextureAlias, &image.device), - (Storage::Texels(texels), _) => (Owned::TextureTexels, texels.buffer.generation()), + let (owned, device) = match (self.storage.stored(), &self.heap) { + (Stored::Made(Storage::Image(image)), Some(_)) => (Owned::TextureInHeap, &image.device), + (Stored::Made(Storage::Image(image)), None) => (Owned::TextureImage, &image.device), + (Stored::Made(Storage::Shadow { image, .. }), _) => { + (Owned::TextureShadow, &image.device) + } + // A shadow left unmade (`texture/lazy_shadow.rs`). + (Stored::Unmade(recipe), _) => (Owned::TextureShadow, recipe.texels.generation()), + (Stored::Made(Storage::Alias { image, .. }), _) => (Owned::TextureAlias, &image.device), + (Stored::Made(Storage::Texels(texels)), _) => { + (Owned::TextureTexels, texels.buffer.generation()) + } }; device.shared().counts.churn.released(owned); self.leave_slot(); @@ -604,7 +614,7 @@ impl Drop for TextureShared { // later submission's move of this image would write over. if let (true, Some(heap)) = (last, &self.heap) { if let Some(place) = self.storage.heap_place() { - if let Storage::Image(image) = &self.storage { + if let Some(Storage::Image(image)) = self.storage.made() { drop(image.take()); } place.give_back(heap); @@ -649,7 +659,12 @@ impl TextureShared { /// The device of the texture's parts on their generation, and what keeps their image while a /// command buffer that bound its ID there may read it ([`leave_slot`](Self::leave_slot)). pub(super) fn slot_keeper(&self) -> (&Device, Option>) { - match &self.storage { + let storage = match self.storage.stored() { + Stored::Made(storage) => storage, + // A shadow left unmade holds no slot (`texture/lazy_shadow.rs`). + Stored::Unmade(recipe) => return (recipe.texels.generation(), None), + }; + match storage { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => { @@ -1886,7 +1901,19 @@ impl Texture { texture.storage_mode(), ); let over = |texels: &Texels| texels.buffer.object_id().get(); - let standing = match texture.storage() { + let storage = match texture.stored() { + Stored::Made(storage) => storage, + // A shadow left unmade (`texture/lazy_shadow.rs`). + Stored::Unmade(recipe) => { + let _ = write!( + facts, + ", an unmade shadow of buffer #{}", + over(&recipe.texels) + ); + return Some((facts, Standing::Held)); + } + }; + let standing = match storage { Storage::Image(image) => image.failure_facts(&mut facts, types), Storage::Texels(texels) => { let _ = write!(facts, ", a texture buffer over buffer #{}", over(texels)); @@ -2743,6 +2770,19 @@ impl Device { true => self.rows_in_place(&texels, descriptor, layout), false => None, }; + // Such a shadow, waiting for no verdict to move in place and over no heap's buffer (which + // a heap's residency makes resident), is made at the first reach of the texture's + // storage, not here: a texture only ever bound through its rows makes none + // (`texture/lazy_shadow.rs`). + let lazy = rows.is_some() && pending.is_none() && texels.buffer.heap().is_none(); + let storage = match storage { + Over::Storage(storage) => StorageCell::Made(storage), + Over::Shadow(recipe) if lazy => { + self.shared().counts.shadow_left_unmade(); + StorageCell::Lazy(Box::new(LazyShadow::new(*recipe))) + } + Over::Shadow(recipe) => StorageCell::Made(self.made_shadow(&recipe)?), + }; let made = (storage, None, rows); let texture = Texture::made_with_planes(self, made, record, None, id_use); // A shadow made before its pages' (or its pooled memory's) in-place verdict moves in @@ -2755,7 +2795,8 @@ impl Device { /// The storage of a texture of `descriptor` (checked as `layout`) over `texels`, as /// [`new_texture_over_buffer`](Self::new_texture_over_buffer) makes it: an aliasing image (one - /// in place over host pages), else a shadow (announced once, counted by why over host pages). + /// in place over host pages), else a shadow (counted by why over host pages), planned and + /// checked here and made by [`made_shadow`](Self::made_shadow) (announced once). /// A shadow over host pages made before their class's verdict for its access, or over the /// device's pooled memory before its class's verdict for an image at Metal's pitch there /// (`Device::pooled_pitched_image`), sets `pending` to what it needs to move in place once the @@ -2766,7 +2807,7 @@ impl Device { (texels, pending, rows): (Arc, &mut Option, &mut bool), descriptor: &TextureDescriptor, layout: &TextureLayout, - ) -> Result { + ) -> Result { let facts = self .shared() .textures @@ -2827,7 +2868,7 @@ impl Device { counts.feedback_loop_alias_image(); } } - return Ok(Storage::Alias { image, texels }); + return Ok(Over::Storage(Storage::Alias { image, texels })); } Err((refusal, why)) => ShadowCause::Refused(refusal, why), }; @@ -2852,7 +2893,7 @@ impl Device { if !in_place::checking() { count.count(&self.shared().counts); } - return Ok(Storage::Alias { image, texels }); + return Ok(Over::Storage(Storage::Alias { image, texels })); } // The device's check of its pooled or exported memory makes no shadow: // its round is not made, refused with why. @@ -2894,12 +2935,6 @@ impl Device { Some(candidate) => self.if_free(plan, candidate, layout.texture_type)?, None => plan, }; - if plan - .usage - .contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT) - { - self.shared().counts.feedback_loop_shadow_image(); - } // Where the device copies a shadow back faster by a dispatch, the image takes the // integer view the dispatch reads (`shadow_copy_back.rs`). Both views are 2D: a 1D // texture over an IOSurface plane's row (`linear_plan.rs`) takes neither, nor does a tiled @@ -2945,7 +2980,52 @@ impl Device { (false, true) => Some(Start::Zero), (false, false) => None, }; - let identity = Identity::new(hazard, false); + Ok(Over::Shadow(Box::new(ShadowRecipe { + call, + texels, + descriptor: *descriptor, + layout: *layout, + plan, + views: (word, unorm), + aspects, + start, + identity: Identity::new(hazard, false), + device_copy, + why, + }))) + } + + /// The shadow `recipe` plans (`storage_over_buffer`), made: its image, its views and its + /// copies, announced as a shadow (`shadowed-texture`) and counted as made, but a device copy, + /// which degrades nothing. Its image is made as its memory lies but where the recipe says how + /// it starts. Refused as the image's making is (out of memory among them). + fn made_shadow(&self, recipe: &ShadowRecipe) -> Result { + let ShadowRecipe { + call, + ref texels, + ref descriptor, + ref layout, + ref plan, + views: (word, unorm), + aspects, + start, + identity, + device_copy, + ref why, + } = *recipe; + let texels = Arc::clone(texels); + let plan = plan.clone(); + let levels = layout.levels; + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + if plan + .usage + .contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT) + { + self.shared().counts.feedback_loop_shadow_image(); + } let owner = Device::runtime_owner; let image = match start { Some(start) => { @@ -3020,7 +3100,7 @@ impl Device { }); } let (offset, bytes_per_row) = (texels.layout.offset, texels.layout.row_pitch); - crate::shadow_log::made(self, call, (descriptor, layout), &texels, &why); + crate::shadow_log::made(self, call, (descriptor, layout), &texels, why); self.degrade(Degradation::ShadowedTexture, || { let format = descriptor.pixel_format; let [width, height, _] = layout.extent; @@ -3032,7 +3112,7 @@ impl Device { "a 2D {format:?} texture of {width}x{height}{levels} over a buffer at offset \ {offset} with rows of {bytes_per_row} bytes" ); - (object, why) + (object, why.clone()) }); self.shared().counts.shadowed_texture_made(start.is_some()); Ok(Storage::Shadow { @@ -5618,16 +5698,19 @@ impl Texture { parent: Option, id_use: IdUse, ) -> Texture { + let storage = StorageCell::Made(storage); Texture::made_with_planes(device, (storage, None, None), record, parent, id_use) } /// [`made`](Self::made), of a two-plane YCbCr texture whose planes a function may read in /// place where `planes_in_place` holds them, or of a shadowed 2D texture whose rows it may - /// read and write in place where `rows_in_place` holds them (`texture/texel_rows.rs`). + /// read and write in place where `rows_in_place` holds them (`texture/texel_rows.rs`), whose + /// shadow may be left unmade (`texture/lazy_shadow.rs`): such a texture takes its slot as its + /// shadow is made. fn made_with_planes( device: &Device, (storage, planes_in_place, rows_in_place): ( - Storage, + StorageCell, Option, Option, ), @@ -5647,18 +5730,23 @@ impl Texture { }; // A heap's image's heap lives while a texture is made from it, or while a texture of it a // view is made of lives. - let heap = match &storage { - Storage::Image(image) => match &image.owner { + let heap = match storage.made() { + Some(Storage::Image(image)) => match &image.owner { Owner::Sparse(sparse) => sparse.heap.upgrade(), owner => owner.heap_place().and_then(|place| place.heap.upgrade()), }, - Storage::Texels(_) | Storage::Alias { .. } | Storage::Shadow { .. } => None, + Some(Storage::Texels(_) | Storage::Alias { .. } | Storage::Shadow { .. }) | None => { + None + } }; - let options = match &storage { - Storage::Image(image) => image.options, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => texels.options(), + let options = match storage.stored() { + Stored::Made(Storage::Image(image)) => image.options, + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels.options(), + Stored::Unmade(recipe) => recipe.texels.options(), }; let memoryless = matches!(options.storage_mode(), Ok(StorageMode::Memoryless)); let mut retain = None; @@ -5700,24 +5788,11 @@ impl Texture { } }); let texture = Texture(shared, retain); - if let Some(objects) = texture.storage().objects() { + if let Some(objects) = texture.s().storage.objects() { objects.object_made(); } - // A texture over host pages' bytes, or in a heap over them (a view of one too): a - // detach of them makes its image present a stand-in (`stand_in.rs`). - // A tiled texture's image is its own copy of them instead, presenting none. - if let Some((bytes, image, exact)) = texture.image_over_bytes() { - let sink = image.plan().usage.contains(ImageUsageFlags::STORAGE); - let keeps = texture.tiled_levels(); - let shared: Arc = Arc::clone(&texture.0) as _; - let image: Arc = Arc::clone(image) as _; - bytes.note_texture(NotedTexture::new( - Arc::downgrade(&shared), - Arc::downgrade(&image), - texture.0.object_id, - (exact, sink, keeps), - )); - } + texture.note_over_bytes(); + let unmade = matches!(texture.stored(), Stored::Unmade(_)); if let IdUse::Program(placement) = id_use { if texture.0.parent.is_none() { let made = device.shared().counts.submissions_made(); @@ -5731,11 +5806,33 @@ impl Texture { .0 .id .hold(Holder::Texture(Arc::downgrade(&texture.0))); - heap_sets::place(device, &texture); + // A shadow left unmade takes its slot as it is made (`texture/lazy_shadow.rs`). + if !unmade { + heap_sets::place(device, &texture); + } } } texture } + + /// A texture over host pages' bytes, or in a heap over them (a view of one too): a detach of + /// them makes its image present a stand-in (`stand_in.rs`), noted as its image is made. A + /// tiled texture's image is its own copy of them instead, presenting none. + fn note_over_bytes(&self) { + let Some((bytes, image, exact)) = self.image_over_bytes() else { + return; + }; + let sink = image.plan().usage.contains(ImageUsageFlags::STORAGE); + let keeps = self.tiled_levels(); + let shared: Arc = Arc::clone(&self.0) as _; + let image: Arc = Arc::clone(image) as _; + bytes.note_texture(NotedTexture::new( + Arc::downgrade(&shared), + Arc::downgrade(&image), + self.0.object_id, + (exact, sink, keeps), + )); + } } /// A call outside command buffers' work on a texture ([`Texture::hold`]), until it goes. @@ -5764,21 +5861,35 @@ impl Texture { if self.0.parent.is_some() { return Err(internal("a range token for a texture view")); } - match self.storage().objects() { + let objects = match self.stored() { + Stored::Made(storage) => storage.objects(), + Stored::Unmade(_) => None, + }; + match objects { Some(objects) => objects.keep(token), None => Err(internal("a range token for a texture over a buffer")), } } - /// The texture's storage: the one it was made with, the image in place a shadow made - /// before its pages' in-place verdict moved to (`TextureShared::moved`), or the second of its - /// faces where it presents that one (`texture/faces.rs`). - fn storage(&self) -> &Storage { + /// The texture's storage: the one it was made with (its shadow made first where it was left + /// unmade, `texture/lazy_shadow.rs`), the image in place a shadow made before its pages' + /// in-place verdict moved to (`TextureShared::moved`), or the second of its faces where it + /// presents that one (`texture/faces.rs`). Refused where its shadow's making is. + fn storage(&self) -> Result<&Storage, Error> { + match self.presented() { + Some(storage) => Ok(storage), + None => self.made_lazily(), + } + } + + /// The storage the texture presents in place of the one it was made with: the second of its + /// faces, or the image in place it moved to; `None` where it presents its own. + fn presented(&self) -> Option<&Storage> { let shared = self.s(); if let Some(presented) = shared.faces.get().and_then(faces::Faces::presented) { - return presented; + return Some(presented); } - shared.moved.get().unwrap_or(&shared.storage) + shared.moved.get() } /// The texture's parts (its storage and what is made of it, `TextureShared`) as the work at @@ -5877,7 +5988,7 @@ impl Texture { /// The texture's image. Refused for a texture buffer, which has none (`NotImplemented`): a /// call that needs one is not built on texture buffers. fn image(&self) -> Result<&Arc, Error> { - match self.storage() { + match self.storage()? { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => Ok(image), @@ -5885,17 +5996,35 @@ impl Texture { } } + /// The texture's image where it is made: `None` for a texture buffer and a shadow left + /// unmade (`texture/lazy_shadow.rs`), which this makes not. What a question of the image a + /// texture whose shadow is unmade answers as one without (an attachment's, a placement's) + /// asks. + fn made_image(&self) -> Option<&Arc> { + match self.stored() { + Stored::Made( + Storage::Image(image) + | Storage::Alias { image, .. } + | Storage::Shadow { image, .. }, + ) => Some(image), + Stored::Made(Storage::Texels(_)) | Stored::Unmade(_) => None, + } + } + /// Whether the texture's image took its storage form (`texture/storage_form.rs`): what the - /// pass log names (`pass_log.rs`). A texture buffer, which has no image, took none. + /// pass log names (`pass_log.rs`). A texture buffer, which has no image, took none, nor did a + /// shadow left unmade. pub(crate) fn took_storage_form(&self) -> bool { - self.image().is_ok_and(|image| image.form.plan().is_some()) + self.made_image() + .is_some_and(|image| image.form.plan().is_some()) } /// The buffer's bytes a texture buffer is, or `None` for a texture with an image. pub(super) fn texels(&self) -> Option<&Texels> { - match self.storage() { - Storage::Image(_) | Storage::Alias { .. } | Storage::Shadow { .. } => None, - Storage::Texels(texels) => Some(texels), + match self.stored() { + Stored::Made(Storage::Texels(texels)) => Some(texels), + Stored::Made(Storage::Image(_) | Storage::Alias { .. } | Storage::Shadow { .. }) + | Stored::Unmade(_) => None, } } @@ -5903,11 +6032,14 @@ impl Texture { /// texture or array with an aliasing or a shadow image), or `None` for a texture of an image /// alone. pub(super) fn buffer_texels(&self) -> Option<&Texels> { - match self.storage() { - Storage::Image(_) => None, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => Some(texels), + match self.stored() { + Stored::Made(Storage::Image(_)) => None, + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => Some(texels), + Stored::Unmade(recipe) => Some(&recipe.texels), } } @@ -5948,7 +6080,7 @@ impl Texture { /// of one (`Buffer::new_tiled_texture`): one image of its own holds every level, a copy of /// the bytes taken at use (`shadow.rs`'s **Copies taken at use**). pub(super) fn tiled_levels(&self) -> bool { - matches!(self.storage(), Storage::Shadow { image, .. } if image.plan().levels > 1) + matches!(self.stored(), Stored::Made(Storage::Shadow { image, .. }) if image.plan().levels > 1) } /// Whether the CPU's `get_bytes` and `replace_region` of the texture's `level` (a view's, @@ -5982,13 +6114,17 @@ impl Texture { /// image (not a shadow, not a texture buffer), not presenting a stand-in while its bytes are /// detached (`detach.rs`), so a write of those bytes is a write of its texels. pub(super) fn aliases_buffer(&self) -> bool { - matches!(self.storage(), Storage::Alias { .. }) && self.linear_image().unwrap_or(false) + matches!(self.stored(), Stored::Made(Storage::Alias { .. })) + && self.linear_image().unwrap_or(false) } /// Whether the texture is a shadow of its buffer's bytes now (`shadow.rs`): its own image, /// copied in from the bytes and back, not an image over them. pub(super) fn shadows_bytes(&self) -> bool { - matches!(self.storage(), Storage::Shadow { .. }) + matches!( + self.stored(), + Stored::Made(Storage::Shadow { .. }) | Stored::Unmade(_) + ) } /// Keep `copies`, those of its read twin's shadow of the twin's bytes (`read_twin.rs`), held @@ -6009,29 +6145,35 @@ impl Texture { /// lying over them now ([`image_over_buffer`](Self::image_over_buffer)), or through the /// shadow image the encoders copy them into and back (`shadow.rs`), which the pass renders. pub(crate) fn renders_bytes(&self) -> bool { - self.image_over_buffer() || matches!(self.storage(), Storage::Shadow { .. }) + self.image_over_buffer() || self.shadows_bytes() } /// Whether the texture's image lies over its buffer's bytes now: an aliasing image, not /// presenting a stand-in while its bytes are detached (`detach.rs`), so a pass that renders it /// writes those bytes. pub(super) fn image_over_buffer(&self) -> bool { - match self.storage() { - Storage::Alias { image, .. } => lock(&image.detached).is_none(), + match self.stored() { + Stored::Made(Storage::Alias { image, .. }) => lock(&image.detached).is_none(), _ => false, } } /// Whether the texture is a buffer's bytes: a texture buffer or a shadowed texture. pub(super) fn over_buffer(&self) -> bool { - !matches!(self.storage(), Storage::Image(_)) + !matches!(self.stored(), Stored::Made(Storage::Image(_))) } /// The copies of a shadowed texture, of a texture buffer viewed through a staging buffer /// (`Texels::into_texture_buffer`), or of a heap's depth or stencil texture held as a shadow of /// the heap's bytes (`texture/heap.rs`), or `None` for another texture. pub(super) fn shadow(&self) -> Option<&Arc> { - match self.storage() { + let storage = match self.stored() { + Stored::Made(storage) => storage, + // A shadow left unmade has no copies: nothing copies into or out of it before a + // command uses it, which makes it (`texture/lazy_shadow.rs`). + Stored::Unmade(_) => return None, + }; + match storage { Storage::Shadow { copies, .. } => Some(copies), Storage::Texels(texels) => texels.staged(), Storage::Image(image) => match &image.owner { @@ -6045,7 +6187,12 @@ impl Texture { /// Whether two textures (or views) hold their texels in one image or buffer. pub(super) fn same_storage(&self, other: &Texture) -> bool { - match (self.storage(), other.storage()) { + let (made, other_made) = match (self.stored(), other.stored()) { + (Stored::Made(made), Stored::Made(other_made)) => (made, other_made), + (Stored::Unmade(a), Stored::Unmade(b)) => return std::ptr::eq(a, b), + _ => return false, + }; + match (made, other_made) { (Storage::Image(a), Storage::Image(b)) => { Arc::ptr_eq(view_shadow::truth(a), view_shadow::truth(b)) } @@ -6114,8 +6261,8 @@ impl Texture { /// texture's first byte in it; `None` for any other texture, a view and a two-plane texture /// of more levels or slices among them. pub(super) fn heap_planes(&self) -> Option<(&Heap, u64)> { - match self.storage() { - Storage::Image(image) if self.0.parent.is_none() => match &image.owner { + match self.stored() { + Stored::Made(Storage::Image(image)) if self.0.parent.is_none() => match &image.owner { Owner::HeapShadow(shadow) if shadow.copies.holds_blit_rows() => { Some((self.0.heap.as_ref()?, shadow.place.offset)) } @@ -6130,8 +6277,8 @@ impl Texture { /// the texture's first byte in it, and their layout; `None` for any other texture, a view /// among them. pub(super) fn heap_two_planes(&self) -> Option<(&Heap, u64, &TwoPlaneHeapLayout)> { - match self.storage() { - Storage::Image(image) if self.0.parent.is_none() => match &image.owner { + match self.stored() { + Stored::Made(Storage::Image(image)) if self.0.parent.is_none() => match &image.owner { Owner::HeapShadow(shadow) => { let layout = shadow.copies.plane_layout()?; Some((self.0.heap.as_ref()?, shadow.place.offset, layout)) @@ -6144,16 +6291,22 @@ impl Texture { /// The image whose bytes a blit of the texture addresses: a view shadow's texture's. fn kept_image(&self) -> Option<&Arc> { - match self.storage() { - Storage::Image(image) => Some(view_shadow::truth(image)), - Storage::Alias { image, .. } | Storage::Shadow { image, .. } => Some(image), - Storage::Texels(_) => None, + match self.stored() { + Stored::Made(Storage::Image(image)) => Some(view_shadow::truth(image)), + Stored::Made(Storage::Alias { image, .. } | Storage::Shadow { image, .. }) => { + Some(image) + } + Stored::Made(Storage::Texels(_)) | Stored::Unmade(_) => None, } } - /// The plan of the texture's image; refused as [`image`](Self::image) is. + /// The plan of the texture's image, a shadow's left unmade too, which this makes not + /// (`texture/lazy_shadow.rs`). Refused for a texture buffer, as [`image`](Self::image) is. pub(super) fn image_plan(&self) -> Result<&ImagePlan, Error> { - Ok(self.image()?.plan()) + match self.stored() { + Stored::Unmade(recipe) => Ok(&recipe.plan), + Stored::Made(_) => Ok(self.image()?.plan()), + } } /// Whether the texture's image is linear now: a linear image (`Image::linear`) that is not @@ -6169,7 +6322,7 @@ impl Texture { /// refuses. For the crate's device tests. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(super) fn placed_type(&self) -> Option { - match &self.image().ok()?.owner { + match &self.made_image()?.owner { Owner::Runtime { placement, .. } => Some(placement.type_index()), _ => None, } @@ -6180,7 +6333,7 @@ impl Texture { /// image in a buffer's, a heap's or the caller's memory, and where /// [`image`](Self::image) refuses. pub(super) fn overflowed(&self) -> bool { - self.image().is_ok_and(|image| { + self.made_image().is_some_and(|image| { matches!(&image.owner, Owner::Runtime { placement, .. } if placement.overflowed()) }) } @@ -6190,7 +6343,7 @@ impl Texture { /// [`image`](Self::image) refuses. A shadowed view's image is in memory of its own /// (`texture/view_shadow.rs`). pub(super) fn placed_bytes(&self) -> Option { - match &self.image().ok()?.owner { + match &self.made_image()?.owner { Owner::Runtime { placement, .. } => Some(placement.size()), Owner::ViewShadow(shadow) => Some(shadow.placement.size()), Owner::Buffer { .. } @@ -6206,7 +6359,7 @@ impl Texture { /// image (`Device::new_texture_with_vk_image_plane`): a copy, fill or mipmap generation, a /// render pass, a shadow (`NotImplemented(VkImagePlaneCopy)`). `Ok` for every other texture. pub(crate) fn check_plane_copied(&self) -> Result<(), Error> { - match self.image().ok().and_then(|image| image.caller_plane()) { + match self.made_image().and_then(|image| image.caller_plane()) { Some(_) => Err(Error::NotImplemented(RuntimeGap::VkImagePlaneCopy)), None => Ok(()), } @@ -6215,15 +6368,16 @@ impl Texture { /// Whether the texture's image is the caller's (`new_texture_with_vk_image`, /// `texture/wrapped.rs`). pub(super) fn callers_image(&self) -> bool { - self.image() - .is_ok_and(|image| matches!(image.owner, Owner::Caller(_))) + self.made_image() + .is_some_and(|image| matches!(image.owner, Owner::Caller(_))) } /// Whether the texture's image lies in lazily allocated memory: a memoryless texture's, /// where the device has such memory (`image_plan.rs`). MoltenVK runs such an image as Metal's /// memoryless storage, which keeps no texels past the render pass that renders them. pub(super) fn lazily_allocated(&self) -> bool { - self.image().is_ok_and(|image| image.lazily_allocated()) + self.made_image() + .is_some_and(|image| image.lazily_allocated()) } /// The key and extent of the texture's image where its first move still waits with zeros a @@ -6232,7 +6386,7 @@ impl Texture { /// must write whole for its submission to leave the zeros out (`texture/first_move.rs`). /// `None` otherwise. pub(super) fn overwritable(&self) -> Option<(ResourceKey, [u32; 2], vk::ImageAspectFlags)> { - let image = self.image().ok()?; + let image = self.made_image()?; let plan = &image.plan; let single = plan.levels == 1 && plan.layers == 1 && plan.extent[2] == 1; let waiting = @@ -6305,27 +6459,23 @@ impl Texture { /// `[0, 1]` (`depth_clamp.rs`): its depth image's, on a device that may store a value outside /// there clamped. pub(super) fn clamps_depth_upload(&self, aspect: ImageAspectFlags) -> bool { - self.image().is_ok_and(|image| { - depth_clamp::clamps_depth(self.generation(), image.plan().format, aspect) - }) + self.image_plan() + .is_ok_and(|plan| depth_clamp::clamps_depth(self.generation(), plan.format, aspect)) } /// Whether the texture holds texels in its image's depth ([`texel_units`]): not a texture of /// a format that presents no depth (`X32Stencil8`) over a combined image. fn holds_depth_texels(&self) -> bool { - self.image().is_ok_and(|image| { - texel_units(image.plan().format, self.pixel_format()) + self.image_plan().is_ok_and(|plan| { + texel_units(plan.format, self.pixel_format()) .any(|(aspect, _, _)| aspect == ImageAspectFlags::DEPTH) }) } /// Whether the texture's image holds a 32-bit float depth. fn float_depth_image(&self) -> bool { - self.image().is_ok_and(|image| { - matches!( - image.plan().format, - Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT - ) + self.image_plan().is_ok_and(|plan| { + matches!(plan.format, Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT) }) } @@ -6393,11 +6543,8 @@ impl Texture { /// holds a 32-bit float depth that keeps a negative value or a NaN (the device does not clamp /// such an upload, `ImageFacts::depth_clamps`); `None` for any other texture. fn keeps_signed_depth(&self) -> Option { - let image = self.image().ok()?; - let float_depth = matches!( - image.plan().format, - Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT - ); + let plan = self.image_plan().ok()?; + let float_depth = matches!(plan.format, Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT); if !float_depth || !self.usage().contains(TextureUsage::RENDER_TARGET) { return None; } @@ -6419,13 +6566,10 @@ impl Texture { aspect: ImageAspectFlags, on_host: bool, ) { - let Ok(image) = self.image() else { + let Ok(plan) = self.image_plan() else { return; }; - let float_depth = matches!( - image.plan().format, - Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT - ); + let float_depth = matches!(plan.format, Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT); if aspect != ImageAspectFlags::DEPTH || !float_depth { return; } @@ -6537,12 +6681,13 @@ impl Texture { /// A sparse texture's image beyond the `VkImage` (`sparse/texture.rs`); `None` for a texture /// that is not sparse. pub(super) fn sparse_image(&self) -> Option<&SparseImage> { - match self.storage() { - Storage::Image(image) => match &image.owner { + match self.stored() { + Stored::Made(Storage::Image(image)) => match &image.owner { Owner::Sparse(sparse) => Some(sparse), _ => None, }, - Storage::Texels(_) | Storage::Alias { .. } | Storage::Shadow { .. } => None, + Stored::Made(Storage::Texels(_) | Storage::Alias { .. } | Storage::Shadow { .. }) + | Stored::Unmade(_) => None, } } @@ -6551,12 +6696,28 @@ impl Texture { /// may be `Access::NONE`). pub(super) fn bound_use(&self, read: Access, write: Access) -> Use { let record = &self.0.record; - let image = match self.storage() { - Storage::Image(image) | Storage::Shadow { image, .. } => image, + let image = match self.stored() { + Stored::Made(Storage::Image(image) | Storage::Shadow { image, .. }) => image, // An aliasing image's uses are uses of the buffer's bytes it lies in. - Storage::Texels(texels) | Storage::Alias { texels, .. } => { + Stored::Made(Storage::Texels(texels) | Storage::Alias { texels, .. }) => { return texels.bound_use(read, write) } + // A shadow left unmade: a use of the image it will be, its key taken as the texture + // was made, in memory of its own (`texture/lazy_shadow.rs`). + Stored::Unmade(recipe) => { + return Use { + key: recipe.identity.key, + tracked: recipe.identity.tracked, + range: UseRange::Image { + aspects: texture_aspects(&recipe.plan), + levels: record.base_level..record.base_level + record.level_count, + layers: record.base_layer..record.base_layer + record.layer_count, + place: ImagePlace::WHOLE, + }, + read, + write, + } + } }; let identity = image.identity; Use { @@ -6584,7 +6745,7 @@ impl Texture { access: Access, write: bool, ) -> Result, Error> { - if let Storage::Alias { texels, .. } = self.storage() { + if let Storage::Alias { texels, .. } = self.storage()? { return Ok(if write { texels.bound_use(Access::NONE, access) } else { @@ -6628,11 +6789,14 @@ impl Texture { /// runtime's own reads: a caller's handle is `device`'s, as a recovery lets go of the /// object's handle of a lost generation at that generation's rest (`device/carry.rs`). pub(crate) fn generation(&self) -> &Device { - match self.storage() { - Storage::Image(image) - | Storage::Alias { image, .. } - | Storage::Shadow { image, .. } => &image.device, - Storage::Texels(texels) => texels.buffer.generation(), + match self.stored() { + Stored::Made( + Storage::Image(image) + | Storage::Alias { image, .. } + | Storage::Shadow { image, .. }, + ) => &image.device, + Stored::Made(Storage::Texels(texels)) => texels.buffer.generation(), + Stored::Unmade(recipe) => recipe.texels.generation(), } } @@ -6727,11 +6891,14 @@ impl Texture { /// Apple M3 Max under macOS 27.0.1. pub fn resource_options(&self) -> ResourceOptions { let _held = self.hold(); - let options = match self.storage() { - Storage::Image(image) => image.options, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => texels.options(), + let options = match self.stored() { + Stored::Made(Storage::Image(image)) => image.options, + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels.options(), + Stored::Unmade(recipe) => recipe.texels.options(), }; options.with_hazard_tracking_mode(self.hazard_tracking_mode()) } @@ -6753,11 +6920,14 @@ impl Texture { /// `hazardTrackingMode`: `Tracked` or `Untracked`, `Default` resolved as Metal resolves it. pub fn hazard_tracking_mode(&self) -> HazardTrackingMode { let _held = self.hold(); - let tracked = match self.storage() { - Storage::Image(image) - | Storage::Alias { image, .. } - | Storage::Shadow { image, .. } => image.identity.tracked, - Storage::Texels(texels) => texels.tracked(), + let tracked = match self.stored() { + Stored::Made( + Storage::Image(image) + | Storage::Alias { image, .. } + | Storage::Shadow { image, .. }, + ) => image.identity.tracked, + Stored::Made(Storage::Texels(texels)) => texels.tracked(), + Stored::Unmade(recipe) => recipe.identity.tracked, }; if tracked { HazardTrackingMode::Tracked @@ -6769,11 +6939,14 @@ impl Texture { /// `allowGPUOptimizedContents`. pub fn allow_gpu_optimized_contents(&self) -> bool { let _held = self.hold(); - match self.storage() { - Storage::Image(image) => image.allow_gpu_optimized_contents, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => texels.allow_gpu_optimized_contents, + match self.stored() { + Stored::Made(Storage::Image(image)) => image.allow_gpu_optimized_contents, + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels.allow_gpu_optimized_contents, + Stored::Unmade(recipe) => recipe.texels.allow_gpu_optimized_contents, } } @@ -6898,12 +7071,17 @@ impl Texture { /// for it (`texture/heap.rs`); `None` for any other texture, a texture over a buffer the /// program placed in a heap included. fn heap_texels(&self) -> Option<&Buffer> { - match self.storage() { - Storage::Texels(texels) if texels.home == TexelsHome::Heap => Some(&texels.buffer), - Storage::Image(_) - | Storage::Texels(_) - | Storage::Alias { .. } - | Storage::Shadow { .. } => None, + match self.stored() { + Stored::Made(Storage::Texels(texels)) if texels.home == TexelsHome::Heap => { + Some(&texels.buffer) + } + Stored::Made( + Storage::Image(_) + | Storage::Texels(_) + | Storage::Alias { .. } + | Storage::Shadow { .. }, + ) + | Stored::Unmade(_) => None, } } @@ -6913,11 +7091,14 @@ impl Texture { if let Some(heap) = self.heap() { return TextureMemory::Heap(heap); } - match self.storage() { - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => TextureMemory::Buffer(&texels.buffer), - Storage::Image(_) => { + match self.stored() { + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => TextureMemory::Buffer(&texels.buffer), + Stored::Unmade(recipe) => TextureMemory::Buffer(&recipe.texels.buffer), + Stored::Made(Storage::Image(_)) => { let mut root = self; while let Some(parent) = root.parent_texture() { root = parent; @@ -6971,11 +7152,14 @@ impl Texture { return Ok(()); } let root = self.root(); - let detached = match root.storage() { - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => texels.buffer.detached(), - Storage::Image(_) => (root.heap_place()) + let detached = match root.stored() { + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels.buffer.detached(), + Stored::Unmade(recipe) => recipe.texels.buffer.detached(), + Stored::Made(Storage::Image(_)) => (root.heap_place()) .and(root.0.heap.as_ref()) .and_then(Heap::bytes) .is_some_and(Buffer::detached), @@ -6992,23 +7176,31 @@ impl Texture { /// there); and whether a stand-in of zero bytes presents the image exactly (not one of /// texels its copies convert from the bytes, `stand_in.rs`). fn image_over_bytes(&self) -> Option<(&Buffer, &Arc, bool)> { - let (image, exact) = match self.storage() { - Storage::Alias { image, .. } | Storage::Image(image) => (image, true), - Storage::Shadow { image, copies, .. } => (image, !copies.converts()), - Storage::Texels(_) => return None, + let (image, exact) = match self.stored() { + Stored::Made(Storage::Alias { image, .. } | Storage::Image(image)) => (image, true), + Stored::Made(Storage::Shadow { image, copies, .. }) => (image, !copies.converts()), + // A shadow left unmade is noted as it is made (`texture/lazy_shadow.rs`). + Stored::Made(Storage::Texels(_)) | Stored::Unmade(_) => return None, }; let root = self.root(); - let bytes = match root.storage() { - Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => &texels.buffer, - Storage::Image(_) => root.heap_place().and(root.0.heap.as_ref())?.bytes()?, - Storage::Texels(_) => return None, + let bytes = match root.stored() { + Stored::Made(Storage::Alias { texels, .. } | Storage::Shadow { texels, .. }) => { + &texels.buffer + } + Stored::Made(Storage::Image(_)) => { + root.heap_place().and(root.0.heap.as_ref())?.bytes()? + } + Stored::Made(Storage::Texels(_)) | Stored::Unmade(_) => return None, }; Some((bytes, image, exact)) } /// Where an automatic or placement heap's texture (or a view of one) lies. fn heap_place(&self) -> Option<&heap::HeapPlace> { - self.storage().heap_place() + match self.stored() { + Stored::Made(storage) => storage.heap_place(), + Stored::Unmade(_) => None, + } } /// `parentTexture`: the texture a view was made from (a view of a view has that view). @@ -7185,8 +7377,8 @@ impl Texture { // as `Depth32Float_Stencil8` over them in its GPU's own layout, no defined answer (an M4 // under macOS 27.0.1), and stops every other format ("not castable"). Only its own format // views it. - let own_x32 = matches!(self.storage(), - Storage::Image(image) if image.plan().pixel_format == PixelFormat::X32Stencil8); + let own_x32 = matches!(self.stored(), + Stored::Made(Storage::Image(image)) if image.plan().pixel_format == PixelFormat::X32Stencil8); if own_x32 && record.pixel_format != PixelFormat::X32Stencil8 { use super::view_plan::ViewProblem; return Err(invalid( @@ -7210,7 +7402,7 @@ impl Texture { // ETC2 or EAC format's sRGB form's codes are its linear form's). A view of an ASTC // texture in its other colour space reads the carrier's second twin, made now where it // has none (`texture/decoded_twin.rs`). - if let Storage::Image(image) = self.storage() { + if let Stored::Made(Storage::Image(image)) = self.stored() { let truth = view_shadow::truth(image); let pf = record.pixel_format; let astc = super::astc::decode_of(truth.plan()).map(|held| (held, AstcDecode::of(pf))); @@ -7239,7 +7431,7 @@ impl Texture { // bits, which its bindings take as the image in its own format through a swizzle and a // pass renders through a shadow; a binding's own view is checked again where it is made. A texture buffer's view is a // texel buffer view of the same bytes, which takes any format of its class. - let apart = match self.storage() { + let apart = match self.storage()? { Storage::Texels(_) => false, Storage::Image(image) | Storage::Alias { image, .. } @@ -7257,7 +7449,7 @@ impl Texture { record.read_as = Some(read_as); storage } else if !apart { - self.storage().clone() + self.storage()?.clone() } else if let Some((image, read_as)) = self.read_through(&record) { self.generation() .shared() @@ -7402,17 +7594,23 @@ impl Texture { } None => bytes, }; - let image = match self.storage() { - Storage::Image(image) => image, + let image = match self.stored() { + Stored::Made(Storage::Image(image)) => image, // A tiled texture's levels past the first lie in its image alone // (`Buffer::new_tiled_texture`). - Storage::Shadow { image, .. } if self.level_in_image(level) => image, - Storage::Texels(texels) | Storage::Alias { texels, .. } => { + Stored::Made(Storage::Shadow { image, .. }) if self.level_in_image(level) => image, + Stored::Made(Storage::Texels(texels) | Storage::Alias { texels, .. }) => { return texels.write(CALL, &image_region, &host, bytes.slice()) } + // An unmade shadow's texture (`texture/lazy_shadow.rs`) is its bytes to the CPU. + Stored::Unmade(recipe) => { + return recipe + .texels + .write(CALL, &image_region, &host, bytes.slice()) + } // A tiled texture's first level is the buffer's bytes: written, the texture takes its // copy again at its next use, as after `did_modify_data` (two x86 Macs). - Storage::Shadow { texels, copies, .. } => { + Stored::Made(Storage::Shadow { texels, copies, .. }) => { texels.write(CALL, &image_region, &host, bytes.slice())?; if let Some(levels) = &copies.levels { levels.mark_stale(); @@ -7609,8 +7807,8 @@ impl Texture { // are the heap's bytes, which `read_region` reads (as `replace_region` writes them), and // a level it does not hold (a mipmapped texture's later one) lies in the image alone. let heap_shadow = matches!( - self.storage(), - Storage::Image(image) if matches!( + self.stored(), + Stored::Made(Storage::Image(image)) if matches!( &image.owner, Owner::HeapShadow(shadow) if shadow.holds(image.plan(), &image_region) ) @@ -7670,7 +7868,7 @@ impl Texture { /// and no wait, as Metal's `getBytes` of such a texture waits for no GPU work; else through a /// staging buffer, by a submission waited for. fn read_color_words(&self, region: &ImageRegion, words: &mut [u8]) -> Result<(), Error> { - let Storage::Image(image) = self.storage() else { + let Storage::Image(image) = self.storage()? else { return Err(internal("a two-plane texture's copy without its image")); }; // A shadowed view's texels are its texture's (`texture/view_shadow.rs`). @@ -7744,16 +7942,22 @@ impl Texture { host: &HostLayout, bytes: &mut [u8], ) -> Result<(), Error> { - let image = match self.storage() { - Storage::Image(image) => image, + let image = match self.stored() { + Stored::Made(Storage::Image(image)) => image, // A tiled texture's levels past the first lie in its image alone; its first is the // buffer's bytes (`Buffer::new_tiled_texture`). - Storage::Shadow { image, .. } if self.tiled_levels() && image_region.level > 0 => image, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => { - return texels.read(call, image_region, host, bytes) + Stored::Made(Storage::Shadow { image, .. }) + if self.tiled_levels() && image_region.level > 0 => + { + image } + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => return texels.read(call, image_region, host, bytes), + // An unmade shadow's texture (`texture/lazy_shadow.rs`) is its bytes to the CPU. + Stored::Unmade(recipe) => return recipe.texels.read(call, image_region, host, bytes), }; // A heap shadow's texels are the heap's bytes (but a two-plane texture's later levels'). if let Owner::HeapShadow(shadow) = &image.owner { @@ -7834,7 +8038,7 @@ impl Texture { // A memoryless texture buffer's CPU access faults in plain Metal's call (SIGSEGV, an M3 // Max under macOS 27.0.1): refused. Another memoryless texture's moves nothing (below). let memoryless = self.is_memoryless(); - if memoryless && !matches!(self.storage(), Storage::Image(_)) { + if memoryless && !matches!(self.stored(), Stored::Made(Storage::Image(_))) { return Err(invalid(call, Problem::StorageMode)); } self.check_rotated_reach()?; @@ -7842,11 +8046,14 @@ impl Texture { // a `Private` IOSurface plane's `getBytes` and `replaceRegion` read and write the // surface's bytes on plain Metal. A texture over a `Private` buffer takes // its storage mode, and is refused as a private texture is. - let reached = match self.storage() { - Storage::Image(_) => false, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => texels.buffer.mapped_contents().is_some(), + let reached = match self.stored() { + Stored::Made(Storage::Image(_)) => false, + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels.buffer.mapped_contents().is_some(), + Stored::Unmade(recipe) => recipe.texels.buffer.mapped_contents().is_some(), }; if self.storage_mode() == StorageMode::Private && !reached { return Err(invalid(call, Problem::Copy(CopyProblem::CpuAccessPrivate))); @@ -7855,13 +8062,13 @@ impl Texture { aspects(pf) .is_some_and(|a| a.contains(ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL)) }; - let (unit, over_buffer) = match self.storage() { + let (unit, over_buffer) = match self.stored() { // A two-plane texture's CPU copies move plane 0's color words (`two_planes.rs`); a // heap's lies apart from the heap's bytes (`texture/heap.rs`). - Storage::Image(_) if two_planes::holds_planes(record.pixel_format) => { + Stored::Made(Storage::Image(_)) if two_planes::holds_planes(record.pixel_format) => { (two_planes::UNIT, false) } - Storage::Image(image) => { + Stored::Made(Storage::Image(image)) => { // The stencil view of a combined depth/stencil texture (`X32Stencil8` of // `Depth32FloatStencil8`, the one `new_texture_view` makes) moves the stencil, a // byte a texel, its depth kept, as its blits do (`copy_unit`): plain Metal's @@ -7884,10 +8091,15 @@ impl Texture { .map_err(|refusal| copy_error(call, refusal))?; (unit, false) } - Storage::Texels(texels) | Storage::Alias { texels, .. } => (texels.unit(), true), + Stored::Made(Storage::Texels(texels) | Storage::Alias { texels, .. }) => { + (texels.unit(), true) + } // A tiled texture's levels past the first lie in its image, copied as an image's; its // first is the buffer's bytes (`Buffer::new_tiled_texture`). - Storage::Shadow { texels, .. } => (texels.unit(), !self.level_in_image(level)), + Stored::Made(Storage::Shadow { texels, .. }) => { + (texels.unit(), !self.level_in_image(level)) + } + Stored::Unmade(recipe) => (recipe.texels.unit(), true), }; let region = texture_region(region, level, slice) .ok_or_else(|| invalid(call, Problem::Copy(CopyProblem::Region)))?; @@ -7917,7 +8129,7 @@ impl Texture { let pitch = cpu_order.map_or(bytes_per_row, |[across, _]| across * u64::from(unit.bytes)); // Metal's answer for a two-plane texture is measured for rows and images a whole row // and image apart or more, by 4-byte multiples. - let planes = matches!(self.storage(), Storage::Image(_)) + let planes = matches!(self.stored(), Stored::Made(Storage::Image(_))) && two_planes::holds_planes(record.pixel_format); if planes { let s = super::copy_plan::shape(region.size, &unit); @@ -7979,8 +8191,8 @@ impl Texture { } // A 2-bit PVRTC texture's carrier halves its regions' x (`pvrtc.rs`); an ASTC texture's // carrier holds each block in 4 x 4 of its texels (`astc.rs`). - let planned = match self.storage() { - Storage::Image(image) + let planned = match self.stored() { + Stored::Made(Storage::Image(image)) if holds_blocks(image.plan()) || super::astc::decode_of(image.plan()).is_some() => { image_region(image.plan(), planned) diff --git a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs index 89dce2824..a6e87ffb6 100644 --- a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs +++ b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs @@ -191,7 +191,7 @@ //! ranges: a copy or a snapshot is another resource) announces it, //! `Degradation::AttachmentReadInPlace`. -use super::{Device, Owner, Storage, Texture}; +use super::{Device, Owner, Storage, Stored, Texture}; use crate::binding_view::{binding_view, VkView}; use crate::command_buffer::CommandBuffer; use crate::error::Error; @@ -444,7 +444,7 @@ impl Texture { /// attached one in place of its copy (`render/attached_levels.rs`): its storage is an image of /// its own, not a sparse one, with no decoded twin, whose image has the sampled usage. pub(crate) fn reads_levels_in_place(&self) -> bool { - let Storage::Image(image) = self.storage() else { + let Stored::Made(Storage::Image(image)) = self.stored() else { return false; }; !matches!(image.owner, Owner::Sparse(_)) @@ -499,7 +499,9 @@ impl Texture { colors: &'s AttachedColors, keep: impl Fn(&AttachedColor) -> bool + 's, ) -> impl Iterator + 's { - let image = self.image().ok(); + // A shadow left unmade is no attachment's: a pass's attachment makes it + // (`texture/lazy_shadow.rs`). + let image = self.made_image(); let record = &self.0.record; let levels = record.base_level..record.base_level + record.level_count; let layers = record.base_layer..record.base_layer + record.layer_count; @@ -549,9 +551,11 @@ impl Texture { /// place at its first level and slice, where the image has `usage` and the texture is of the /// kinds [`snapshot_color`](Self::snapshot_color) names. fn own_color(&self, layout: &PassLayout, usage: ImageUsageFlags) -> Option { - let image = match self.storage() { - Storage::Image(image) | Storage::Shadow { image, .. } => image, - Storage::Alias { image, .. } if self.image_over_buffer() => image, + // A shadow left unmade renders nowhere: a pass's attachment makes it + // (`texture/lazy_shadow.rs`). + let image = match self.stored() { + Stored::Made(Storage::Image(image) | Storage::Shadow { image, .. }) => image, + Stored::Made(Storage::Alias { image, .. }) if self.image_over_buffer() => image, _ => return None, }; let plan = image.plan(); diff --git a/crates/metal2vulkan-runtime/src/texture/attributes.rs b/crates/metal2vulkan-runtime/src/texture/attributes.rs index 71a9f4ad4..f376fcae1 100644 --- a/crates/metal2vulkan-runtime/src/texture/attributes.rs +++ b/crates/metal2vulkan-runtime/src/texture/attributes.rs @@ -33,7 +33,7 @@ use super::super::device::lock; use super::super::error::Error; use super::super::values::StorageMode; use super::super::PurgeableState; -use super::{Image, Owner, Storage, Texture}; +use super::{Image, Owner, Storage, Stored, Texture}; use metal2vulkan::vk::ImageType; use std::sync::Mutex; @@ -101,9 +101,12 @@ impl Texture { // A texture with two faces keeps its state with its own image, whichever face it // presents (`texture/faces.rs`). let parts = self.s(); - let storage = match parts.faces.get() { - Some(_) => &parts.storage, - None => self.storage(), + let storage = match (parts.faces.get(), self.stored()) { + (Some(_), _) => parts.storage.made()?, + (None, Stored::Made(storage)) => storage, + // A shadow left unmade (`texture/lazy_shadow.rs`), Metal's `NonVolatile` as a + // shadow's. + (None, Stored::Unmade(_)) => return None, }; match storage { Storage::Image(image) => match &image.owner { diff --git a/crates/metal2vulkan-runtime/src/texture/carry.rs b/crates/metal2vulkan-runtime/src/texture/carry.rs index a31870bb0..fdcb6c49d 100644 --- a/crates/metal2vulkan-runtime/src/texture/carry.rs +++ b/crates/metal2vulkan-runtime/src/texture/carry.rs @@ -47,7 +47,7 @@ use super::super::values::StorageMode; use super::super::view_plan::ViewRequest; use super::super::ycbcr::IoSurfaceYCbCr; use super::super::Device; -use super::{IdUse, Initial, Owner, Storage, Texture, TextureShared}; +use super::{IdUse, Initial, Owner, Storage, Stored, Texture, TextureShared}; use std::sync::atomic::Ordering; use std::sync::{Arc, Weak}; @@ -359,8 +359,8 @@ impl Texture { /// The buffer the texels of the texture, a texture buffer of `Device::new_texture`, lie in, /// where the recovery carried it to `to`; `None` for any other texture, or where it left it. fn texels_carried_to(&self, to: &Device) -> Option { - match self.storage() { - Storage::Texels(texels) + match self.stored() { + Stored::Made(Storage::Texels(texels)) if texels.home == TexelsHome::Buffer && texels.buffer.generation().same(to) => { Some(texels.buffer.clone()) @@ -374,26 +374,35 @@ impl Texture { if self.root().0.heap.is_some() { return TextureLeft::Heap; } - match self.storage() { - Storage::Image(image) => match &image.owner { - Owner::Heap(_) | Owner::HeapShadow(_) | Owner::HeapUnaliased(_) => { - TextureLeft::Heap + let texels = match self.stored() { + Stored::Made(Storage::Image(image)) => { + return match &image.owner { + Owner::Heap(_) | Owner::HeapShadow(_) | Owner::HeapUnaliased(_) => { + TextureLeft::Heap + } + Owner::Caller(_) => TextureLeft::Caller, + Owner::Sparse(_) => TextureLeft::Sparse, + Owner::Runtime { + shareable: true, .. + } => TextureLeft::Shared, + Owner::Buffer { .. } => TextureLeft::Buffer, + Owner::Runtime { .. } | Owner::ViewShadow(_) => TextureLeft::Other, } - Owner::Caller(_) => TextureLeft::Caller, - Owner::Sparse(_) => TextureLeft::Sparse, - Owner::Runtime { - shareable: true, .. - } => TextureLeft::Shared, - Owner::Buffer { .. } => TextureLeft::Buffer, - Owner::Runtime { .. } | Owner::ViewShadow(_) => TextureLeft::Other, - }, - Storage::Texels(texels) if texels.home == TexelsHome::Shared => TextureLeft::Shared, - Storage::Texels(texels) - | Storage::Alias { texels, .. } - | Storage::Shadow { texels, .. } => match texels.buffer.heap() { - Some(_) => TextureLeft::Heap, - None => TextureLeft::Buffer, - }, + } + Stored::Made(Storage::Texels(texels)) if texels.home == TexelsHome::Shared => { + return TextureLeft::Shared + } + Stored::Made( + Storage::Texels(texels) + | Storage::Alias { texels, .. } + | Storage::Shadow { texels, .. }, + ) => texels, + // A shadow left unmade is over its bytes (`texture/lazy_shadow.rs`). + Stored::Unmade(recipe) => &recipe.texels, + }; + match texels.buffer.heap() { + Some(_) => TextureLeft::Heap, + None => TextureLeft::Buffer, } } } diff --git a/crates/metal2vulkan-runtime/src/texture/copy_images.rs b/crates/metal2vulkan-runtime/src/texture/copy_images.rs index 40b9b5150..2edcd5195 100644 --- a/crates/metal2vulkan-runtime/src/texture/copy_images.rs +++ b/crates/metal2vulkan-runtime/src/texture/copy_images.rs @@ -44,7 +44,7 @@ use super::super::device::lock; use super::super::texture_descriptor::TextureDescriptor; use super::super::Device; -use super::{ImageMaker, ImagePlan, Owner, Storage, Texture}; +use super::{ImageMaker, ImagePlan, Owner, Storage, Stored, Texture}; use metal2vulkan::vk::ImageUsageFlags; use std::sync::Mutex; @@ -78,8 +78,8 @@ fn covers(have: &ImageKey, want: &ImageKey) -> bool { /// The bytes of memory of `texture`'s image, where the runtime placed it in memory of its own; 0 /// for any other. fn image_bytes(texture: &Texture) -> u64 { - match texture.storage() { - Storage::Image(image) => match &image.owner { + match texture.stored() { + Stored::Made(Storage::Image(image)) => match &image.owner { Owner::Runtime { placement, .. } => placement.size(), _ => 0, }, diff --git a/crates/metal2vulkan-runtime/src/texture/faces.rs b/crates/metal2vulkan-runtime/src/texture/faces.rs index 274a4b3ab..a8216a0c6 100644 --- a/crates/metal2vulkan-runtime/src/texture/faces.rs +++ b/crates/metal2vulkan-runtime/src/texture/faces.rs @@ -272,7 +272,7 @@ impl Texture { /// its usage made it a shadow of its own before an attached read could. pub(super) fn faces_fit(&self) -> bool { let (shared, parts) = (&self.0, self.s()); - let Storage::Image(image) = &parts.storage else { + let Some(Storage::Image(image)) = parts.storage.made() else { return false; }; let own = matches!( @@ -335,7 +335,7 @@ impl Texture { /// the two. The attached reads' shadow while the texture presents its own image. pub(super) fn make_faces(&self) -> Result, Error> { let parts = self.s(); - let Storage::Image(own) = &parts.storage else { + let Some(Storage::Image(own)) = parts.storage.made() else { return Err(crate::error::internal( "faces of a texture without an image", )); @@ -434,11 +434,11 @@ impl Texture { let to = 1 - from; let image = |face: usize| -> Arc { let storage = match face { - 0 => &parts.storage, - _ => &faces.other, + 0 => parts.storage.made(), + _ => Some(&faces.other), }; match storage { - Storage::Image(image) => Arc::clone(image), + Some(Storage::Image(image)) => Arc::clone(image), _ => unreachable!("a face is an image"), } }; diff --git a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs index ccbfccbc5..2601d8abe 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs @@ -16,7 +16,7 @@ //! so and checks nothing. use super::first_move::Fresh; -use super::{Image, Owner, Storage, Texture}; +use super::{Image, Owner, Storage, Stored, Texture}; use crate::buffer::MemoryHold; use crate::device::lock; use crate::{ @@ -115,9 +115,9 @@ fn texels() -> Vec { /// The image `texture`'s storage holds, as an alias of a buffer's bytes or as its own. fn image_of(texture: &Texture) -> Option<&Arc> { - match texture.storage() { - Storage::Alias { image, .. } | Storage::Image(image) => Some(image), - Storage::Texels(_) | Storage::Shadow { .. } => None, + match texture.stored() { + Stored::Made(Storage::Alias { image, .. } | Storage::Image(image)) => Some(image), + Stored::Made(Storage::Texels(_) | Storage::Shadow { .. }) | Stored::Unmade(_) => None, } } diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index 1a1acba9d..abbb510c1 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -239,7 +239,7 @@ use super::requirements::Query; use super::stand_in::StandIn; use super::{ image_aspects, image_error, pages_hold, texel_units, DetachedImage, IdUse, Image, ImageObjects, - ImagePlacement, ImageSwap, KeptResolves, Owner, Raw, Remade, Start, Storage, Texture, + ImagePlacement, ImageSwap, KeptResolves, Owner, Raw, Remade, Start, Storage, Stored, Texture, TextureDescriptor, ViewRecord, }; use crate::address::ObjectsToken; @@ -3923,7 +3923,7 @@ impl Device { let (textures, _) = heap.textures_from(0); let mut swaps: Vec = Vec::new(); for texture in &textures { - let Storage::Image(image) = texture.storage() else { + let Stored::Made(Storage::Image(image)) = texture.stored() else { continue; }; let Owner::Heap(place) = &image.owner else { @@ -3997,7 +3997,7 @@ impl Device { .facts(self.compile_device().profile()); let (textures, _) = heap.textures_from(0); for texture in &textures { - let Storage::Image(image) = texture.storage() else { + let Stored::Made(Storage::Image(image)) = texture.stored() else { continue; }; let Owner::Heap(place) = &image.owner else { diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index f0486b98f..aef5b47a7 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -70,7 +70,7 @@ use super::attached_reads::linear_feedback_candidate; use super::route::HostLie; use super::{ first_color_subresource, pages_hold, FirstMove, Image, ImageObjects, ImageSwap, KeptResolves, - KeyMap, LinearMade, LinearRefusal, ObjectsToken, Owner, Raw, Remade, Storage, Texture, + KeyMap, LinearMade, LinearRefusal, ObjectsToken, Owner, Raw, Remade, Storage, Stored, Texture, }; use crate::binding_view::VkView; use crate::buffer::{Buffer, InPlaceWatch, ReadApart}; @@ -224,8 +224,8 @@ impl Texture { /// call waits for (`Image::settle`): the device's check's round (`in_place_check.rs`). `None` /// where the texture is no image aliasing its bytes. pub(crate) fn settle_in_place(&self) -> Option> { - match self.storage() { - Storage::Alias { image, .. } => Some(image.settle()), + match self.stored() { + Stored::Made(Storage::Alias { image, .. }) => Some(image.settle()), _ => None, } } @@ -237,7 +237,7 @@ impl Texture { /// `None` where the texture is no image aliasing its bytes, or its image has no feedback loop /// usage. pub(crate) fn settle_feedback_moves(&self) -> Option> { - let Storage::Alias { image, .. } = self.storage() else { + let Stored::Made(Storage::Alias { image, .. }) = self.stored() else { return None; }; let plan = image.plan(); @@ -275,7 +275,7 @@ impl Texture { &self, draw: &mut crate::check_draw::CheckDraw, ) -> Option> { - let Storage::Alias { image, .. } = self.storage() else { + let Stored::Made(Storage::Alias { image, .. }) = self.stored() else { return None; }; let plan = image.plan(); @@ -311,7 +311,7 @@ impl Texture { texel: ShadowTexelView, (width, height): (u32, u32), ) -> Option> { - let Storage::Alias { image, .. } = self.storage() else { + let Stored::Made(Storage::Alias { image, .. }) = self.stored() else { return None; }; use metal2vulkan::vk::{ diff --git a/crates/metal2vulkan-runtime/src/texture/lazy_shadow.rs b/crates/metal2vulkan-runtime/src/texture/lazy_shadow.rs new file mode 100644 index 000000000..b3f3c9bd6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/texture/lazy_shadow.rs @@ -0,0 +1,215 @@ +//! A shadow left unmade until a reach needs it: a program's texture over a buffer's bytes whose +//! image the device refused for a reason that leaves its rows in place (`texture/texel_rows.rs`) +//! is a shadow (`shadow.rs`) to every reach but a slot of a function that only reads, writes or +//! asks the size of it, which binds its rows. So its shadow is planned and checked as the texture +//! is made (`Device::storage_over_buffer`: its image's plan and usage, its copies' views, how it +//! starts), and made at the first reach of the texture's storage ([`Texture::storage`]): a slot +//! that binds the shadow, a residency (`use_resource`), a pass's attachment, a blit of its image, a +//! view, its `VkImage` handed out, a CPU access. A texture only ever bound through its rows makes +//! none (`WorkCounts::shadows_left_unmade`, `shadows_made_at_use`). +//! +//! - **Which.** A texture whose rows are in place (`TextureFacts::texel_rows`), its shadow not one +//! that waits for its pages' in-place verdict (`texture/storage_form.rs`): every other shadow is +//! made with its texture. +//! - **Until it is made** the texture holds no image. Its resource ID holds no slot in the +//! device's texture table and heap sets ([`heap_sets::place`] places it as its shadow is made), +//! so a read through its ID that no command named reads the neutral, where a shadow made with the +//! texture read whatever its image held: nothing copies into a shadow no command names +//! (`shadow.rs`). A use of the texture names the key planned with its shadow +//! ([`ShadowRecipe::identity`]), so a use before the making and one after name one resource; it +//! has no copies, as nothing is copied into or out of a shadow before a command uses it. +//! - **The making** is the texture's making's, once, under the texture's lock: the image as its +//! memory lies (or as the plan says it starts), its views, its copies, its notice +//! (`shadowed-texture`) and shadow log line, its counts; then its slot is placed and a detach of +//! its bytes reaches its image (`NotedTexture`), as at a texture's making. A slot that binds it +//! copies the bytes in before its command, as before the first command that uses any shadow: +//! the copy is a command of the encoder's own at that point (`encoder.rs`), so it reads what the +//! commands before it wrote through the rows, ordered after them (a rows binding's use is a use +//! of the bytes, `Texture::rows_use`). A kept list of resident textures' shadows is listed +//! again (`DeviceShared::usage_shadows_made`, `shadow::ResidentShadows`). +//! - **Out of memory** at the making fails the call that reached it, with the error the texture's +//! making would have given; the texture stays unmade, and a later reach makes it again. + +use super::{Storage, Texture}; +use crate::buffer_texture::Texels; +use crate::device::lock; +use crate::error::Error; +use crate::heap_sets; +use crate::image_plan::ImagePlan; +use crate::resource::Identity; +use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; +use crate::Device; +use ash::vk; +use metal2vulkan::bind::{ShadowMergeRead, ShadowTexelView}; +use metal2vulkan::vk::Format; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex, OnceLock}; + +/// A texture over a buffer's shadow as its making planned and checked it, to make +/// (`Device::made_shadow`). +pub(in crate::texture) struct ShadowRecipe { + /// The call that made the texture, which its notice names. + pub(in crate::texture) call: &'static str, + /// The buffer's bytes the texture is over. + pub(in crate::texture) texels: Arc, + pub(in crate::texture) descriptor: TextureDescriptor, + pub(in crate::texture) layout: TextureLayout, + /// The shadow image's plan, its undeclared usage and its views' usage in it. + pub(in crate::texture) plan: ImagePlan, + /// Its copies' views: the integer view a dispatch copies back through + /// (`shadow_copy_back.rs`), or the view of its own format its merges read + /// (`shadow_merge.rs`). + pub(in crate::texture) views: ( + Option<(Format, ShadowTexelView, bool)>, + Option, + ), + /// The aspects its copies move. + pub(in crate::texture) aspects: vk::ImageAspectFlags, + /// How its image starts, where not as its memory lies. + pub(in crate::texture) start: Option, + /// The image's identity, its key taken as the texture is made: a use of the texture names + /// it before the image is made too. + pub(in crate::texture) identity: Identity, + /// Whether it is a device copy of host pages, which degrades nothing. + pub(in crate::texture) device_copy: bool, + /// Why the texture is a shadow: its notice's reason. + pub(in crate::texture) why: String, +} + +/// What a texture over a buffer is made over (`Device::storage_over_buffer`): its storage, or the +/// shadow it plans, to make. +pub(in crate::texture) enum Over { + Storage(Storage), + Shadow(Box), +} + +/// A shadow left unmade (the module docs): its recipe, and its storage once made. +pub(in crate::texture) struct LazyShadow { + pub(in crate::texture) recipe: ShadowRecipe, + made: OnceLock, + /// Held while the shadow is made, so one reach makes it. + making: Mutex<()>, +} + +impl LazyShadow { + pub(in crate::texture) fn new(recipe: ShadowRecipe) -> LazyShadow { + LazyShadow { + recipe, + made: OnceLock::new(), + making: Mutex::new(()), + } + } +} + +/// A texture's storage as its parts hold it: made with the texture, or a shadow left unmade until +/// a reach makes it (the module docs). +pub(in crate::texture) enum StorageCell { + Made(Storage), + Lazy(Box), +} + +/// A texture's storage as made so far ([`Texture::stored`]): made, or its shadow's recipe while it +/// is unmade. +pub(in crate::texture) enum Stored<'a> { + Made(&'a Storage), + Unmade(&'a ShadowRecipe), +} + +impl StorageCell { + /// Its storage, where made. + pub(in crate::texture) fn made(&self) -> Option<&Storage> { + match self { + StorageCell::Made(storage) => Some(storage), + StorageCell::Lazy(lazy) => lazy.made.get(), + } + } + + /// As made so far. + pub(in crate::texture) fn stored(&self) -> Stored<'_> { + match self { + StorageCell::Made(storage) => Stored::Made(storage), + StorageCell::Lazy(lazy) => match lazy.made.get() { + Some(storage) => Stored::Made(storage), + None => Stored::Unmade(&lazy.recipe), + }, + } + } + + /// The generation its objects are of, or a shadow's left unmade would be of: its bytes'. + pub(in crate::texture) fn generation(&self) -> &Device { + match self.stored() { + Stored::Made(storage) => storage.generation(), + Stored::Unmade(recipe) => recipe.texels.generation(), + } + } + + /// Whether its image's `VkImage` was handed out; never one not made. + pub(in crate::texture) fn handed_out(&self) -> bool { + self.made().is_some_and(Storage::handed_out) + } + + /// Where an automatic or placement heap's texture's image lies in its heap; never a shadow's. + pub(in crate::texture) fn heap_place(&self) -> Option<&super::heap::HeapPlace> { + self.made().and_then(Storage::heap_place) + } + + /// The texture objects over an image or texels of the texture's own; never a shadow's. + pub(in crate::texture) fn objects(&self) -> Option<&crate::address::ObjectsToken> { + self.made().and_then(Storage::objects) + } +} + +impl Texture { + /// Whether the texture's shadow is left unmade (the module docs). + pub(crate) fn shadow_unmade(&self) -> bool { + matches!(self.stored(), Stored::Unmade(_)) + } + + /// Make the texture's shadow where it is left unmade (the module docs): at a reach that + /// names the texture's image to the GPU before its later questions of the image ask it made + /// (a slot that binds the image, a residency, a pass's attachment, an execution of commands + /// that may bind it). Refused as its making is. + pub(crate) fn made_for_use(&self) -> Result<(), Error> { + self.storage().map(drop) + } + + /// The texture's storage as made so far, its shadow's recipe while that is left unmade (the + /// module docs): what a reach that must not make it reads (its rows' binding, its placement, + /// its facts, its shape and options). + pub(in crate::texture) fn stored(&self) -> Stored<'_> { + match self.presented() { + Some(storage) => Stored::Made(storage), + None => self.s().storage.stored(), + } + } + + /// Its shadow left unmade, made (the module docs): the storage [`Texture::storage`] answers. + /// Refused as its making is. + pub(in crate::texture) fn made_lazily(&self) -> Result<&Storage, Error> { + let parts = self.s(); + let lazy = match &parts.storage { + super::StorageCell::Made(storage) => return Ok(storage), + super::StorageCell::Lazy(lazy) => lazy, + }; + let storage = { + let _making = lock(&lazy.making); + if let Some(made) = lazy.made.get() { + return Ok(made); + } + let device = lazy.recipe.texels.generation(); + let storage = device.made_shadow(&lazy.recipe)?; + lazy.made.get_or_init(|| storage) + }; + let device = storage.generation(); + device.shared().counts.shadow_made_at_use(); + // A kept list of the resident textures' shadows is listed again. + (device.shared().usage_shadows_made).fetch_add(1, Ordering::Release); + // A detach of its bytes reaches its image, and its slot holds it from now on, as at a + // texture's making. + self.note_over_bytes(); + if self.0.id.id().0 != 0 { + heap_sets::place(device, self); + } + Ok(storage) + } +} diff --git a/crates/metal2vulkan-runtime/src/texture/rotation.rs b/crates/metal2vulkan-runtime/src/texture/rotation.rs index 6054b8a0b..870141428 100644 --- a/crates/metal2vulkan-runtime/src/texture/rotation.rs +++ b/crates/metal2vulkan-runtime/src/texture/rotation.rs @@ -165,7 +165,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Result { - let Storage::Shadow { texels, .. } = self.storage() else { + let Storage::Shadow { texels, .. } = self.storage()? else { return Err(internal("a rotated texture without its plane's rows")); }; let rotation = record.presented.rotation; diff --git a/crates/metal2vulkan-runtime/src/texture/shared.rs b/crates/metal2vulkan-runtime/src/texture/shared.rs index 50e0f05b1..82b561798 100644 --- a/crates/metal2vulkan-runtime/src/texture/shared.rs +++ b/crates/metal2vulkan-runtime/src/texture/shared.rs @@ -30,7 +30,7 @@ use super::super::texture_descriptor::TextureDescriptor; use super::super::values::StorageMode; use super::super::view_plan::ViewRecord; use super::super::Device; -use super::{image_error, IdUse, Initial, Owner, Storage, Texture}; +use super::{image_error, IdUse, Initial, Owner, Storage, Stored, Texture}; use metal2vulkan::metal::TextureType; use std::sync::Arc; @@ -184,7 +184,7 @@ impl Device { } let record = &texture.0.record; self.check_texture_placement(CALL, placement, record.usage, record.texture_type)?; - let storage = match texture.storage() { + let storage = match texture.storage()? { Storage::Image(image) => Storage::Image(Arc::clone(image)), Storage::Texels(texels) => Storage::Texels(Arc::clone(texels)), Storage::Alias { .. } | Storage::Shadow { .. } => { @@ -207,8 +207,8 @@ impl Texture { pub fn is_shareable(&self) -> bool { let _held = self.hold(); self.0.parent.is_none() - && match self.storage() { - Storage::Image(image) => { + && match self.stored() { + Stored::Made(Storage::Image(image)) => { matches!( image.owner, Owner::Runtime { @@ -217,8 +217,9 @@ impl Texture { } ) } - Storage::Texels(texels) => texels.home == TexelsHome::Shared, - Storage::Alias { .. } | Storage::Shadow { .. } => false, + Stored::Made(Storage::Texels(texels)) => texels.home == TexelsHome::Shared, + Stored::Made(Storage::Alias { .. } | Storage::Shadow { .. }) + | Stored::Unmade(_) => false, } } diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 9d6979ce4..2a51b244a 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -132,7 +132,8 @@ //! (`scheduler/inbox.rs`). use super::{ - texture_aspects, AliasCount, Image, ImageObjects, Owner, Storage, Texture, TextureShared, + texture_aspects, AliasCount, Image, ImageObjects, Owner, Storage, Stored, Texture, + TextureShared, }; use crate::buffer_texture::Texels; use crate::degradation::Degradation; @@ -560,7 +561,7 @@ impl Texture { // A texture with faces takes its form on the face it presents, for good // (`texture/faces.rs`). self.freeze_faces(); - let Storage::Image(image) = self.storage() else { + let Stored::Made(Storage::Image(image)) = self.stored() else { return; }; let form = &image.form; @@ -601,7 +602,7 @@ impl Texture { // The handle is the face the texture presents, for good (`texture/faces.rs`). self.freeze_faces(); let image = self.image()?; - let lies_in = match self.storage() { + let lies_in = match self.storage()? { Storage::Alias { texels, .. } => Some(texels.buffer.at(0).0), _ => None, }; @@ -618,9 +619,9 @@ impl Texture { /// move no more then ceasing to wait (it moved, its image was handed out, or its verdicts or /// its bytes keep it a shadow). fn storage_form_wanted(&self) -> Option { - let image = match self.storage() { - Storage::Image(image) => image, - Storage::Shadow { .. } => return self.move_wanted(), + let image = match self.stored() { + Stored::Made(Storage::Image(image)) => image, + Stored::Made(Storage::Shadow { .. }) => return self.move_wanted(), _ => return None, }; if image.form.taken.get().is_some() || image.form.exported.load(Ordering::Relaxed) { @@ -639,7 +640,7 @@ impl Texture { /// was made. fn move_wanted(&self) -> Option { let shared = self.s(); - let Storage::Shadow { image, texels, .. } = &shared.storage else { + let Some(Storage::Shadow { image, texels, .. }) = shared.storage.made() else { return None; }; let mut pending = lock(&shared.pending_move); @@ -797,7 +798,7 @@ impl Texture { /// queues with its own fences and events. fn shadow_goes_after_move(&self, core: &mut EncoderCore, pooled: bool) -> Arc { let moved = Arc::new(AtomicBool::new(false)); - let Storage::Shadow { image, copies, .. } = &self.s().storage else { + let Some(Storage::Shadow { image, copies, .. }) = self.s().storage.made() else { return moved; }; if !image.identity.tracked { @@ -833,7 +834,7 @@ impl Texture { /// moves with. pub(crate) fn wait_to_move_in_place(&self, pending: in_place::PendingMove) { let shared = self.s(); - let Storage::Shadow { texels, .. } = &shared.storage else { + let Some(Storage::Shadow { texels, .. }) = shared.storage.made() else { return; }; let wait = MoveWait { @@ -888,7 +889,7 @@ impl Prepared { let Kind::Form { plan, swapped } = &self.kind else { return None; }; - let Storage::Image(image) = texture.storage() else { + let Stored::Made(Storage::Image(image)) = texture.stored() else { return None; }; let Owner::Runtime { placement: old, .. } = &image.owner else { @@ -938,7 +939,7 @@ impl Prepared { return false; }; let shared = texture.s(); - let Storage::Shadow { image: shadow, .. } = &shared.storage else { + let Some(Storage::Shadow { image: shadow, .. }) = shared.storage.made() else { return false; }; if texture.shadowed_again() { diff --git a/crates/metal2vulkan-runtime/src/texture/texel_rows.rs b/crates/metal2vulkan-runtime/src/texture/texel_rows.rs index 2d0a89cbe..a22df6069 100644 --- a/crates/metal2vulkan-runtime/src/texture/texel_rows.rs +++ b/crates/metal2vulkan-runtime/src/texture/texel_rows.rs @@ -28,7 +28,7 @@ //! writes both through the shadow and through the rows merges them, as for any other use of the //! bytes. -use super::{Storage, Texture}; +use super::{Storage, Stored, Texture}; use crate::buffer_texture::Texels; use crate::error::{internal, Error}; use crate::resource::ResourceKey; @@ -120,15 +120,17 @@ impl Texture { /// whose rows are (the module docs). fn rows_texels(&self) -> Result<(&Texels, &RowsInPlace), Error> { let rows = self.s().rows_in_place.as_ref(); - let texels = match self.storage() { - Storage::Shadow { texels, copies, .. } => match &copies.source { + // A shadow left unmade is over the bytes its rows are (`texture/lazy_shadow.rs`). + let texels = match self.stored() { + Stored::Made(Storage::Shadow { texels, copies, .. }) => match &copies.source { ShadowSource::Bytes { target: ShadowTarget::Image { .. }, .. } => Some(&**texels), _ => None, }, - _ => None, + Stored::Unmade(recipe) => Some(&*recipe.texels), + Stored::Made(_) => None, }; match (texels, rows) { (Some(texels), Some(rows)) => Ok((texels, rows)), diff --git a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs index 69460854c..22152956a 100644 --- a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs @@ -47,7 +47,7 @@ //! which a command that makes the texture resident for writing through it names in its uses //! (`binding.rs`). It is exact and announces nothing. -use super::{Image, Owner, Start, Storage, Texture}; +use super::{Image, Owner, Start, Storage, Stored, Texture}; use crate::binding_view::binding_view; use crate::degradation::Degradation; use crate::device::lock; @@ -144,14 +144,9 @@ impl Texture { true => (ImageUsageFlags::STORAGE, TextureUsage::SHADER_WRITE), false => (ImageUsageFlags::SAMPLED, TextureUsage::SHADER_READ), }; - match self.storage() { - Storage::Image(image) - | Storage::Alias { image, .. } - | Storage::Shadow { image, .. } => { - !image.plan().usage.contains(vk) && !self.0.record.usage.contains(metal) - } - Storage::Texels(_) => false, - } + // A shadow left unmade answers by its plan (`texture/lazy_shadow.rs`). + self.image_plan() + .is_ok_and(|plan| !plan.usage.contains(vk) && !self.0.record.usage.contains(metal)) } /// The `VkImageView` a slot binding write of `call` needs of the texture: `desc` the binding @@ -391,7 +386,7 @@ impl Texture { if record.presented.rotation != 0 { return Err(Error::NotImplemented(RuntimeGap::RotatedTexture)); } - let (image, copies, truth) = match self.storage() { + let (image, copies, truth) = match self.storage()? { Storage::Image(image) => { let base = match &image.owner { Owner::ViewShadow(shadow) => &shadow.base, @@ -466,7 +461,7 @@ impl Texture { let mut copies = texels.shadow_copies(image.raw.get(), image.identity, aspects, (None, None))?; // The texture's own image lies in the bytes too where it aliases them. - if matches!(self.storage(), Storage::Alias { .. }) { + if matches!(self.stored(), Stored::Made(Storage::Alias { .. })) { copies.backing = copies.backing.aliased(); } ( @@ -500,24 +495,29 @@ impl Texture { usage: record.usage, }; let feedback = ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT; - let (texels, own) = match self.storage() { - Storage::Alias { image, texels } => { - let usage = match image.plan().usage.contains(feedback) { - true => "with the feedback loop usage", - false => "without the feedback loop usage", - }; - ( - Some(&**texels), - format!("an aliasing image over the bytes, {usage}"), - ) - } - Storage::Shadow { texels, .. } => (Some(&**texels), "a shadow of the bytes".to_owned()), - Storage::Image(_) if self.s().faces.get().is_some() => ( - None, - "an image of its own, one of two faces that take turns (texture/faces.rs)" - .to_owned(), - ), - Storage::Image(_) | Storage::Texels(_) => (None, "an image of its own".to_owned()), + let (texels, own) = match self.stored() { + Stored::Unmade(recipe) => (Some(&*recipe.texels), "a shadow of the bytes".to_owned()), + Stored::Made(storage) => match storage { + Storage::Alias { image, texels } => { + let usage = match image.plan().usage.contains(feedback) { + true => "with the feedback loop usage", + false => "without the feedback loop usage", + }; + ( + Some(&**texels), + format!("an aliasing image over the bytes, {usage}"), + ) + } + Storage::Shadow { texels, .. } => { + (Some(&**texels), "a shadow of the bytes".to_owned()) + } + Storage::Image(_) if self.s().faces.get().is_some() => ( + None, + "an image of its own, one of two faces that take turns (texture/faces.rs)" + .to_owned(), + ), + Storage::Image(_) | Storage::Texels(_) => (None, "an image of its own".to_owned()), + }, }; let why = format!( "a usage shadow: {}; the texture's own image is {own}", diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index 4828ada8b..1761456ec 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -54,7 +54,7 @@ //! `Feature::ViewFormatReinterpretation` (not representable) where the device reinterprets no //! components, else of `Feature::TextureView` (not implemented). -use super::{IdUse, Image, Owner, Storage, Texture}; +use super::{IdUse, Image, Over, Owner, Storage, Stored, Texture}; use crate::degradation::Degradation; use crate::device::lock; use crate::error::{internal, Error, RuntimeGap}; @@ -119,7 +119,7 @@ impl Texture { if let Some(storage) = self.converted_view(call, record) { return storage; } - match self.storage() { + match self.storage()? { Storage::Image(image) => { let base = match &image.owner { Owner::ViewShadow(shadow) => &shadow.base, @@ -166,10 +166,14 @@ impl Texture { let layout = descriptor .check(self.generation().properties().texture_rules()) .map_err(|_| refused(None))?; - // A view's storage never moves in place (`texture/storage_form.rs`). + // A view's storage never moves in place (`texture/storage_form.rs`), and its + // shadow is made with it: a view binds no rows. let over = (Arc::clone(texels), &mut None, &mut false); - self.generation() - .storage_over_buffer(call, over, &descriptor, &layout) + let device = self.generation(); + match device.storage_over_buffer(call, over, &descriptor, &layout)? { + Over::Storage(storage) => Ok(storage), + Over::Shadow(recipe) => device.made_shadow(&recipe), + } } // A texture buffer's views are texel buffer views of its bytes, which take any // format of its class (`Texture::view`). @@ -184,7 +188,7 @@ impl Texture { &self, record: &ViewRecord, ) -> Option<(Arc, (PixelFormat, TextureSwizzleChannels))> { - let Storage::Image(image) = self.storage() else { + let Stored::Made(Storage::Image(image)) = self.stored() else { return None; }; let base = truth(image); @@ -202,16 +206,19 @@ impl Texture { /// A texture presenting what this one's bindings present (`ViewRecord::bound`) over the same /// storage, where they differ: a view that reads its image in the image's own format, as a - /// texture of that format. `None` for every other texture. - pub(crate) fn bound_twin(&self) -> Option { - self.0.record.read_as?; - Some(Texture::made( + /// texture of that format. `None` for every other texture. Refused as the texture's storage + /// is ([`Texture::storage`]). + pub(crate) fn bound_twin(&self) -> Result, Error> { + if self.0.record.read_as.is_none() { + return Ok(None); + } + Ok(Some(Texture::made( self.generation(), - self.storage().clone(), + self.storage()?.clone(), self.0.record.bound(), Some(self.clone()), IdUse::Runtime, - )) + ))) } /// The texture a pass renders into for a view that its bindings present in its image's own @@ -226,7 +233,7 @@ impl Texture { if let Some(shadow) = held.as_ref() { return Ok(shadow.clone()); } - let Storage::Image(image) = self.storage() else { + let Storage::Image(image) = self.storage()? else { return Err(internal("a view read through its image without one")); }; let record = ViewRecord { diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index 753af7be1..0d1f77e3e 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -23,7 +23,7 @@ //! buffer. use super::ycbcr_planes::PlanesImage; -use super::{image_error, IdUse, Image, Storage, Texture}; +use super::{image_error, IdUse, Image, Storage, StorageCell, Stored, Texture}; use crate::address_map::AddressModeMap; use crate::binding_view::VkView; use crate::buffer_texture::{view_usage, Texels}; @@ -276,7 +276,7 @@ impl Device { } let storage = self.converted_storage(call, texels, &descriptor, layout, (planes, span))?; - let made = (storage, in_place.ok(), None); + let made = (StorageCell::Made(storage), in_place.ok(), None); return Ok(Texture::made_with_planes(self, made, record, None, id_use)); } // Over a surface of a P3 matrix: an image of the codes of the code-reading format, its @@ -474,7 +474,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Option> { - let Storage::Shadow { texels, copies, .. } = self.storage() else { + let Stored::Made(Storage::Shadow { texels, copies, .. }) = self.stored() else { return None; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -548,7 +548,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Option> { - let Storage::Shadow { texels, copies, .. } = self.storage() else { + let Stored::Made(Storage::Shadow { texels, copies, .. }) = self.stored() else { return None; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -614,7 +614,7 @@ impl Texture { /// Whether a pass that loads this two-plane YCbCr texture loads nothing measured: one that /// reads each code alone, over a surface of a P3 matrix, and an `_sRGB` twin (`ycbcr.rs`). pub(crate) fn ycbcr_load_unmeasured(&self) -> bool { - let Storage::Shadow { copies, .. } = self.storage() else { + let Stored::Made(Storage::Shadow { copies, .. }) = self.stored() else { return false; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -642,7 +642,7 @@ impl Texture { let pf = self.0.record.pixel_format; let gap = || Error::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(pf)); - let Storage::Shadow { texels, copies, .. } = self.storage() else { + let Stored::Made(Storage::Shadow { texels, copies, .. }) = self.stored() else { return Err(gap()); }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -775,7 +775,7 @@ impl Texture { let pf = self.0.record.pixel_format; let gap = || Error::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(pf)); - let Storage::Shadow { texels, copies, .. } = self.storage() else { + let Stored::Made(Storage::Shadow { texels, copies, .. }) = self.stored() else { return Err(gap()); }; let ShadowSource::Converted { conversion, .. } = &copies.source else { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 7ce4f1839..640e147d3 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -554,6 +554,8 @@ pub(crate) struct Counters { shadowed_textures: AtomicU64, shadows_zeroed: AtomicU64, shadows_over_fresh_pages: AtomicU64, + shadows_left_unmade: AtomicU64, + shadows_made_at_use: AtomicU64, host_textures_in_place: AtomicU64, host_textures_in_place_written: AtomicU64, device_copy_textures: AtomicU64, @@ -4850,6 +4852,18 @@ impl Counters { (self.shadows_over_fresh_pages).fetch_add(1, Ordering::Relaxed); } + /// A texture over a buffer's bytes whose rows are in place was made with its shadow left + /// unmade (`texture/lazy_shadow.rs`). + pub(crate) fn shadow_left_unmade(&self) { + (self.shadows_left_unmade).fetch_add(1, Ordering::Relaxed); + } + + /// A shadow left unmade was made at the first reach of its texture's image + /// (`texture/lazy_shadow.rs`). + pub(crate) fn shadow_made_at_use(&self) { + (self.shadows_made_at_use).fetch_add(1, Ordering::Relaxed); + } + /// A texture over host pages was made a device copy of them (`texture.rs`). pub(crate) fn device_copy_texture(&self) { self.device_copy_textures.fetch_add(1, Ordering::Relaxed); @@ -9716,6 +9730,16 @@ pub struct WorkCounts { /// (`fresh_page_buffers_made`): an image bound to imported memory starts `UNDEFINED`, and its /// first move may write any byte bound to it. pub shadows_over_fresh_pages: u64, + /// Textures over a buffer's bytes whose rows are in place (`TextureFacts::texel_rows`), made + /// with their shadow left unmade: a slot that only reads, writes or asks the size of one binds + /// its rows, and its shadow is made at the first reach of its image + /// (`shadows_made_at_use`, `texture/lazy_shadow.rs`). One only ever bound through its rows + /// makes none, nor counts in `shadowed_textures`. + pub shadows_left_unmade: u64, + /// Of `shadows_left_unmade`, those whose shadow a reach made since: a slot that binds the + /// image, a residency (`use_resource`), a pass's attachment, a view, a handed-out `VkImage`, + /// each counted in `shadowed_textures` as it is made. + pub shadows_made_at_use: u64, /// Textures over host pages (a no-copy buffer's, a no-copy heap's buffer's, or a buffer in /// fresh pages it imported; or a copied host buffer's copy of them, `copied_textures_in_place`) /// that sample, read, render or are written through a shader, made an image aliasing the pages @@ -12070,6 +12094,8 @@ impl Device { linear_alignments_recalled: counters.linear_alignments_recalled.load(Ordering::Relaxed), shadowed_textures: counters.shadowed_textures.load(Ordering::Relaxed), shadows_over_fresh_pages: counters.shadows_over_fresh_pages.load(Ordering::Relaxed), + shadows_left_unmade: counters.shadows_left_unmade.load(Ordering::Relaxed), + shadows_made_at_use: counters.shadows_made_at_use.load(Ordering::Relaxed), host_textures_in_place: counters.host_textures_in_place.load(Ordering::Relaxed), host_textures_in_place_written: counters .host_textures_in_place_written diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9bfe049db..290eb7b2a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2308; +pub const RUNTIME_VERSION: u32 = 2309; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 3853dd972..99b8ea379 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3603,6 +3603,8 @@ field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_truth_written pub field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_unnamed_since pub shadow_texels_unskipped_unnamed_since: u64 field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_unstanding pub shadow_texels_unskipped_unstanding: u64 field metal2vulkan-runtime::WorkCounts.shadowed_textures pub shadowed_textures: u64 +field metal2vulkan-runtime::WorkCounts.shadows_left_unmade pub shadows_left_unmade: u64 +field metal2vulkan-runtime::WorkCounts.shadows_made_at_use pub shadows_made_at_use: u64 field metal2vulkan-runtime::WorkCounts.shadows_over_fresh_pages pub shadows_over_fresh_pages: u64 field metal2vulkan-runtime::WorkCounts.shadows_sharing_truth pub shadows_sharing_truth: u64 field metal2vulkan-runtime::WorkCounts.shadows_zeroed pub shadows_zeroed: u64 diff --git a/docs/API.md b/docs/API.md index b55d159c6..2876976e6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -481,6 +481,13 @@ binds its rows as a texel buffer of the buffer's bytes (the pages, or the buffer at a slot whose function only reads, writes or asks its size (section 5, `TextureFacts::texel_rows`), and those commands copy nothing into or out of the shadow (`WorkCounts::texel_rows_textures`, `texel_rows_bound`); a slot that samples it reads the shadow. +Such a texture's shadow (not one made before its pages' verdicts, nor one over a heap's buffer) is +made at the first reach of its image, not with the texture: a slot that binds the image, a +`use_resource` of it, a render pass's attachment, an execution of commands that inherits its +binding, a view, its `VkImage` handed out (`WorkCounts::shadows_left_unmade`, +`shadows_made_at_use`). One only ever bound through its rows, or read and written by the CPU and +blits, which reach its bytes, makes none, and its resource ID reads the neutral texture until its +shadow is made, as a texture that no command named holds nothing a read through its ID could see. Over a buffer with a read twin, a slot that only reads the texture binds the texture's read twin where it has one in place, and the shadow otherwise. A texture in place renders and @@ -2338,6 +2345,8 @@ bound. format, rebuilding each byte from its normalized value (Vulkan defines that value as the byte over 255), with no copy of them (`WorkCounts::shadow_merges_fetched`); every other format, the sRGB and 16-bit float ones among them, copies them. + A texture whose rows are in place (section 1) gives this notice as its shadow is made, at the + first reach of its image, and one only ever bound through its rows gives none. - `metal2vulkan-degrade-staged-texture-buffer` (performance). `StagedTextureBuffer`: A texture buffer is viewed through a staging buffer: its texels start where the device views none (`minTexelBufferOffsetAlignment`), or run past its buffer's length, where its staging buffer is