diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index eb0c1d7ed..da624a897 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -1359,7 +1359,11 @@ or does not check is rebuilt from the generations' names, with young counted ful A slot the fragment function reads only at its own pixel reads the draw's scissor, a pixel wider each way, clamped into its level; any other slot reads every level and layer its texture reaches. What is new to the shadow is copied as one area where it is one (a wider scissor's - band), else as the whole read, with no look-ahead. + band), else as the whole read, with no look-ahead. At the pass's first draw, where the pass + cleared the attachment and every read of its level and layer lies in it alone and inside the + render area, the shadow's level and layer is cleared to the pass's clear colour between the + same barriers instead of copied (the shadow is of the attachment's format, so the clear writes + the texels the pass's did); a draw of the pass before it, of any pipeline, leaves the copy. - `memory_barrier` after a draw of the encoder that wrote memory ends the rendering, records one barrier and begins the rendering again, loading what it stored. After draws that only rendered, in a pass that moved an image to the feedback layout, the barrier is owed to the next draw that diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 2254d41a5..4b9cc085d 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -597,7 +597,8 @@ pub struct Metrics { /// after a draw that wrote memory, one at a draw that moves an attachment's image to the /// feedback layout, one at a draw that reads an attachment after a memory barrier owed to it, /// and two around the copies a draw that reads an attachment makes into its image's shadow - /// ([`attachment_read_copies`](Self::attachment_read_copies)). Any other draw takes none. + /// ([`attachment_read_copies`](Self::attachment_read_copies)), or the clear of the shadow + /// that stands for a copy of what its pass cleared. Any other draw takes none. pub barriers: u64, /// Bytes the runtime copied for a call: `replace_region` and `get_bytes` staging, the copies /// between a texture over a buffer and its image of its own @@ -715,7 +716,8 @@ pub struct Metrics { /// not make: one for each area of a level, a range of its layers and a rectangle, at the /// pass's first draw that reads the image and at a draw after a memory barrier after draws, /// of what the draw reads, and at another draw, of what it reads that the shadow does not - /// hold yet. + /// hold yet. What the pass's first draw reads of the level and layer the pass cleared, + /// inside the render area, is no copy: the shadow's is cleared to the pass's clear colour. pub attachment_read_copies: u64, /// The bytes of those copies, which count in [`bytes_copied`](Self::bytes_copied) too. pub attachment_read_copy_bytes: u64, diff --git a/crates/metal2vulkan-rt/src/pass.rs b/crates/metal2vulkan-rt/src/pass.rs index 8709084fa..1e9795068 100644 --- a/crates/metal2vulkan-rt/src/pass.rs +++ b/crates/metal2vulkan-rt/src/pass.rs @@ -231,6 +231,14 @@ impl Target { self.layout != self.attachment.home } + /// The colour the pass clears it to, as its rendering's load clears it: `None` for an + /// attachment the pass loads or does not care for, and for the stencil attachment. + pub(crate) fn clear_color(&self) -> Option { + let color = self.attachment.aspects == vk::ImageAspectFlags::COLOR; + // SAFETY: a colour attachment's clear value is its colour (`Pass::check`). + (color && self.load == vk::AttachmentLoadOp::CLEAR).then(|| unsafe { self.clear.color }) + } + /// Its `VkRenderingAttachmentInfo`; `resumed`, for a rendering the pass begins again, which /// loads what the pass stored. pub(crate) fn info(&self, resumed: bool) -> vk::RenderingAttachmentInfo<'static> { diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index a0b8ff6b6..61d8a5b79 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -49,9 +49,11 @@ //! the rendering ends, one barrier orders every earlier command before the copies and moves what //! they copy to the transfer layouts (the image's rendered level and layer from the attachment //! layout, the rest of it from home, the shadow from home), the copies are recorded, one barrier -//! moves both back, and the rendering begins again. A memory barrier after draws leaves every -//! shadow holding nothing, so the next draw that reads an attachment copies what it reads again, -//! after what the earlier draws rendered; it records nothing itself. +//! moves both back, and the rendering begins again. At the pass's first draw, what it reads of the +//! level and layer the pass cleared, inside the render area, is a clear of the shadow's to the +//! pass's clear colour instead, between the same barriers. A memory barrier after draws leaves +//! every shadow holding nothing, so the next draw that reads an attachment copies what it reads +//! again, after what the earlier draws rendered; it records nothing itself. //! //! A draw sets Metal's state as dynamic state: every state at the encoder's first draw, Metal's //! defaults where the encoder set none, and after that what changed. A viewport is Vulkan's with @@ -174,6 +176,10 @@ struct Shadowed { /// The bytes of a texel. texel: u64, held: Held, + /// The colour the pass cleared the rendered level and layer to, where the shadow is of the + /// attachment's format, so that a clear of the shadow with it writes the texels the pass's + /// clear wrote (`crate::shadow`); `None` elsewhere. + cleared: Option, } /// What a buffer slot holds. @@ -295,6 +301,8 @@ pub struct RenderCommandEncoder { wrote: bool, /// A draw since the encoder last ordered its draws rendered. drew: bool, + /// A draw of the pass recorded: what the pass cleared may hold more than its clear colour. + pass_drew: bool, /// A memory barrier after draws that wrote no memory, which the next draw that reads an /// attachment pays. owed: bool, @@ -360,6 +368,7 @@ impl CommandBuffer { topology: None, wrote: false, drew: false, + pass_drew: false, owed: false, moved: Vec::new(), loop_aspects: vk::ImageAspectFlags::NONE, @@ -876,6 +885,7 @@ impl RenderCommandEncoder { .find(|t| t.texture.hazard_id() == hazard) .expect("an attachment a draw reads is one of its pass's"); let a = &target.attachment; + let same = texture.shadow_format() == Some(a.format); self.shadowed.push(Shadowed { hazard, image: a.image, @@ -886,6 +896,7 @@ impl RenderCommandEncoder { home: a.home, texel: target.texture.texel_bytes(), held: Held::default(), + cleared: target.clear_color().filter(|_| same), }); self.shadowed.len() - 1 } @@ -906,7 +917,9 @@ impl RenderCommandEncoder { ); let read_only = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL; let (mut away, mut back, mut copies) = (Vec::new(), Vec::new(), Vec::new()); + let mut clears = Vec::new(); let (mut count, mut bytes) = (0, 0); + let (untouched, render_area) = (!self.pass_drew, self.pass.area); for (s, areas) in self.shadowed.iter().zip(&planned) { if areas.is_empty() { continue; @@ -918,10 +931,24 @@ impl RenderCommandEncoder { base_array_layer: first, layer_count: end - first, }; - let ranges = shadow::ranges(areas); - let (rendered, rest) = shadow::parted(&ranges, s.rendered); + let (level, layer) = s.rendered; + // At the pass's first draw, the level and layer it cleared holds only its clear + // colour inside the render area: the shadow's is cleared to it in place of a copy. + let clear = + (s.cleared).filter(|_| untouched && shadow::clears(areas, s.rendered, render_area)); + let copied: Vec = match clear { + Some(color) => { + clears.push((s.shadow, color, range((level, [layer, layer + 1])))); + (areas.iter()) + .filter(|area| !area.reaches(s.rendered)) + .copied() + .collect() + } + None => areas.clone(), + }; + let sources = shadow::ranges(&copied); + let (rendered, rest) = shadow::parted(&sources, s.rendered); if rendered { - let (level, layer) = s.rendered; let at = range((level, [layer, layer + 1])); away.push(layout_barrier(s.image, at, s.layout, source)); back.push(layout_barrier(s.image, at, source, s.layout)); @@ -930,14 +957,18 @@ impl RenderCommandEncoder { away.push(layout_barrier(s.image, at, s.home, source)); back.push(layout_barrier(s.image, at, source, s.home)); } - for at in ranges.into_iter().map(range) { + for at in shadow::ranges(areas).into_iter().map(range) { away.push(layout_barrier(s.shadow, at, read_only, destination)); back.push(layout_barrier(s.shadow, at, destination, read_only)); } - let regions: Vec = - (areas.iter()).map(|area| region(area, s.aspects)).collect(); - count += areas.len() as u64; - bytes += (areas.iter()) + if copied.is_empty() { + continue; + } + let regions: Vec = (copied.iter()) + .map(|area| region(area, s.aspects)) + .collect(); + count += copied.len() as u64; + bytes += (copied.iter()) .map(|area| area.texels() * s.texel) .sum::(); copies.push((s.image, s.shadow, regions)); @@ -951,7 +982,9 @@ impl RenderCommandEncoder { // it retires (its pass's attachment texture holds it, and it its shadow); each range // is in the layout it moves from: the rendered level and layer in the one the pass // renders it in, the rest of the image and the shadow at home; each region lies in - // both images, in their transfer layouts between the barriers. + // both images, in their transfer layouts between the barriers; each cleared range is + // a colour level and layer of its shadow, in the transfer destination layout, which + // no region of the copies reaches. unsafe { device.cmd_pipeline_barrier2( command, @@ -959,6 +992,9 @@ impl RenderCommandEncoder { .memory_barriers(&memory) .image_memory_barriers(&away), ); + for (shadow, color, range) in &clears { + device.cmd_clear_color_image(command, *shadow, destination, color, &[*range]); + } for (image, shadow, regions) in &copies { device.cmd_copy_image(command, *image, source, *shadow, destination, regions); } @@ -1316,7 +1352,7 @@ impl RenderCommandEncoder { building.wrote_host(); } self.wrote |= draws.writes_memory; - self.drew = true; + (self.drew, self.pass_drew) = (true, true); let (bind, first) = building.bind_graphics(pipeline); self.fill_push(&state); let building = (self.building.as_mut()) diff --git a/crates/metal2vulkan-rt/src/shadow.rs b/crates/metal2vulkan-rt/src/shadow.rs index f7e723fab..3a396a4ec 100644 --- a/crates/metal2vulkan-rt/src/shadow.rs +++ b/crates/metal2vulkan-rt/src/shadow.rs @@ -12,6 +12,13 @@ //! a memory barrier after draws, which orders what they rendered before later reads, leaves it //! holding nothing, so the next draw that reads the image copies what it reads again. //! +//! Where the pass cleared the attachment and the draw is the pass's first, the rendered level and +//! layer holds only the clear colour inside the render area: where every read of that level and +//! layer lies in it alone and inside the render area, the shadow's is cleared to the same colour +//! (the pass's clear value, the shadow of the attachment's format) in place of the copy, and the +//! rest of what the draw reads is copied. A draw of the pass recorded before, of any pipeline, +//! leaves the copy. +//! //! A slot the fragment function reads only at its own pixel (`StageModule::own_pixel_textures`) //! reads the rectangle of the draw's scissor, a pixel wider each way for its helper invocations, //! clamped into its level; any other slot reads every level and layer its texture reaches. @@ -46,6 +53,11 @@ impl Area { .product() } + /// Whether it holds a texel of level `level`'s layer `layer`. + pub(crate) fn reaches(&self, (level, layer): (u32, u32)) -> bool { + !self.is_empty() && self.level == level && self.layers[0] <= layer && layer < self.layers[1] + } + /// Whether it holds every texel of `other`. fn contains(&self, other: &Area) -> bool { self.level == other.level @@ -128,6 +140,18 @@ pub(crate) fn whole(level: u32, levels: u32, layer: u32, layers: u32, size: [u32 .collect() } +/// Whether a clear of `rendered`, the level and layer a pass cleared that no draw of the pass has +/// rendered since, gives the shadow what the image holds of each of `areas` that reaches it: one +/// does, and each such lies in that level and layer alone and inside the render area `area` +/// (`[width, height]` from the level's origin), which holds only the clear colour. +pub(crate) fn clears(areas: &[Area], rendered: (u32, u32), area: [u32; 2]) -> bool { + let layer = rendered.1; + let mut reaching = areas.iter().filter(|a| a.reaches(rendered)).peekable(); + reaching.peek().is_some() + && reaching + .all(|a| a.layers == [layer, layer + 1] && a.x[1] <= area[0] && a.y[1] <= area[1]) +} + /// The subresources `areas` reach, each a level and a range of its layers, the ranges of one level /// joined where they meet or overlap: what a copy's barriers move, each subresource once. pub(crate) fn ranges(areas: &[Area]) -> Vec<(u32, [u32; 2])> { diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs index b63481eb8..6774df3c2 100644 --- a/crates/metal2vulkan-rt/src/tests/draw.rs +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -1044,9 +1044,10 @@ mod on_device { /// fragment's own pixel and at another pixel. Through the feedback loop, the rendering is /// ended and begun again around one barrier, and the pass's first such draw moves the image to /// the feedback layout, a barrier of its own. Through a copy, on a device without the loop, - /// the pass's first such draw and the one after the memory barrier each copy what they read - /// into the image's shadow, between two barriers of their own, and the memory barrier records - /// nothing; the copies, their bytes and the live shadows are printed. A device without the + /// the pass's first such draw, the pass's first draw, clears the image's shadow to the pass's + /// clear colour, and the one after the memory barrier copies what it reads into the shadow, + /// each between two barriers of their own, and the memory barrier records nothing; the + /// copies, their bytes and the live shadows are printed. A device without the /// attachment reads refuses the draw, `Gap::Draw { AttachmentRead }`, and records nothing for /// it. #[test] @@ -1124,9 +1125,9 @@ mod on_device { let after = counters.metrics(); let shadows = counters.gauges(); // Through the loop: the pass's two, the move, the memory barrier's, the segment's - // end. Through a copy: the pass's two, two around each of the two copies, the - // segment's end, and the upload's end, which moves the new shadow home ahead of - // the pass. + // end. Through a copy: the pass's two, two around the shadow's clear and two + // around the copy, the segment's end, and the upload's end, which moves the new + // shadow home ahead of the pass. let barriers = match looped { true => 5, false => 8, @@ -1139,8 +1140,8 @@ mod on_device { (barriers, 1), "{name} {case}: barriers, passes" ); - // The whole target each time: its own pixels under a scissor over it, or the - // texture's one level and layer. + // The whole target, after the memory barrier: its own pixels under a scissor over + // it, or the texture's one level and layer. The first read is the clear's. let bytes = u64::from(SIDE * SIDE * 4); let copies = ( after.attachment_read_copies - before.attachment_read_copies, @@ -1149,7 +1150,7 @@ mod on_device { ); let want = match looped { true => (0, 0, 0), - false => (2, 2 * bytes, 2 * bytes), + false => (1, bytes, bytes), }; assert_eq!( copies, want, @@ -1186,10 +1187,102 @@ mod on_device { }); } + /// The pass's first draw reads the attachment its pass cleared, at its own pixel. Through a + /// copy, on a device without the feedback loop, a clear of the image's shadow to the pass's + /// clear colour stands for the copy, which no copy counts, and every pixel reads the clear + /// colour; after one draw of the pass, of a pipeline that reads no texture, the reading draw + /// copies the whole target. Through the feedback loop, neither copies. + #[test] + fn every_device_reads_its_cleared_attachment_at_its_pass_first_draw() { + let Some(library) = examples() else { + return; + }; + let plain = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + let own = descriptor(&library, "own_pixel_fragment", PixelFormat::RGBA8Unorm); + each_device("attachment_clear", |name, _, device| { + if !device.core().attachment_reads { + println!("{name}: no attachment reads"); + return; + } + (device.grant_indices(IndexClass::Texture, 4096, 4)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let looped = device.core().feedback.is_some(); + let plain = state(name, &device, &plain); + let reading = state(name, &device, &own); + let mut buffers = Buffers::new(&device); + // Two triangles over the whole target: the reading one adds nothing, the plain one is + // blue. + let whole = [-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]; + let positions = buffers.of(&device, &floats(&[whole; 2].concat())); + let colors: Vec = [[0.0; 4], BLUE] + .iter() + .flat_map(|c| [*c; 3].concat()) + .collect(); + let colors = buffers.of(&device, &floats(&colors)); + let queue = device.new_command_queue(4).expect("a queue"); + let color = readable(&device, PixelFormat::RGBA8Unorm, 1, 4096); + let counters = device.counters(); + for (case, drawn) in [("no draw before", false), ("one draw before", true)] { + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut d = pass(&color, None); + d.color_attachments[0].clear_color = crate::ClearColor::new(0.2, 0.4, 0.6, 1.0); + let mut encoder = (command_buffer.render_command_encoder(&d)) + .unwrap_or_else(|error| panic!("{name} {case}: {error}")); + let draw = |result: Result<(), Error>| { + result.unwrap_or_else(|e| panic!("{name} {case}: {e}")) + }; + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.set_fragment_texture(Some(&color), 0)); + if drawn { + draw(encoder.set_render_pipeline_state(&plain)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + } + draw(encoder.set_render_pipeline_state(&reading)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + let copies = ( + after.attachment_read_copies - before.attachment_read_copies, + after.attachment_read_copy_bytes - before.attachment_read_copy_bytes, + ); + let want = match (looped, drawn) { + (false, true) => (1, u64::from(SIDE * SIDE * 4)), + _ => (0, 0), + }; + assert_eq!( + copies, want, + "{name} {case}: copies into the shadow and their bytes" + ); + assert_eq!( + counters.gauges().shadows > 0, + !looped, + "{name} {case}: the target's shadow" + ); + println!( + "{name} {case}: attachment_read_copies {}, attachment_read_copy_bytes {}", + copies.0, copies.1 + ); + if !drawn { + let want = [51, 102, 153, 255].repeat((SIDE * SIDE) as usize); + assert_eq!( + read(&color, 4), + want, + "{name} {case}: every pixel the clear colour, read" + ); + } + } + }); + } + /// A pass that renders a texture's second level reads its first through a view of both /// levels, which reaches the rendered one, and samples the level an earlier pass rendered: - /// through the feedback loop, its whole image moved, or through a copy of both levels into - /// its shadow, one copy a level. + /// through the feedback loop, its whole image moved, or through its shadow, the lower level + /// copied into it and the rendered one, which the pass cleared and no draw rendered yet, + /// cleared. #[test] fn every_device_samples_a_lower_level_while_its_pass_renders_the_next() { let Some(library) = examples() else { @@ -1239,9 +1332,9 @@ mod on_device { copies, match looped { true => 0, - false => 2, + false => 1, }, - "{name}: copies into the shadow, one a level" + "{name}: copies into the shadow, the lower level's" ); println!("{name}: attachment_read_copies {copies}"); let side = SIDE / 2; diff --git a/crates/metal2vulkan-rt/src/tests/shadow.rs b/crates/metal2vulkan-rt/src/tests/shadow.rs index 09602806f..72d6cac6b 100644 --- a/crates/metal2vulkan-rt/src/tests/shadow.rs +++ b/crates/metal2vulkan-rt/src/tests/shadow.rs @@ -10,8 +10,10 @@ //! - A held area that covers another drops it, and past eight the oldest goes. //! - A copy's barriers move each subresource once, the rendered level and layer apart from the //! rest. +//! - A clear of the level and layer its pass cleared stands for the copy where every read that +//! reaches it lies in it alone and inside the render area, and one does. -use crate::shadow::{own_pixel, parted, ranges, whole, Area, Held}; +use crate::shadow::{clears, own_pixel, parted, ranges, whole, Area, Held}; /// An area of level 0, layer 0. fn rect(x: [u32; 2], y: [u32; 2]) -> Area { @@ -211,3 +213,62 @@ fn a_copys_barriers_move_each_subresource_once_the_rendered_one_apart() { assert_eq!(parted(&[(0, [2, 3])], (0, 2)), (true, Vec::new())); assert_eq!(parted(&joined, (1, 1)), (false, joined.clone())); } + +#[test] +fn a_clear_stands_for_the_copy_of_reads_of_the_cleared_level_and_layer_inside_the_render_area() { + let rendered = (0, 0); + // Reads of the rendered level and layer inside the render area: a clear. + assert!(clears(&[rect([0, 64], [0, 64])], rendered, [64, 64])); + assert!(clears(&[rect([7, 17], [3, 13])], rendered, [32, 32])); + // A read past the render area reads texels the pass did not clear. + assert!(!clears(&[rect([0, 33], [0, 8])], rendered, [32, 32])); + assert!(!clears(&[rect([0, 8], [0, 33])], rendered, [32, 32])); + // No read of the rendered level and layer: nothing to clear. + let other_level = Area { + level: 1, + ..rect([0, 32], [0, 32]) + }; + assert!(!clears(&[other_level], rendered, [64, 64])); + assert!(!clears(&[rect([4, 4], [0, 64])], rendered, [64, 64])); + // Beside a read of another level, which is copied, the rendered one's is still a clear. + assert!(clears( + &[other_level, rect([0, 64], [0, 64])], + rendered, + [64, 64] + )); + // A read of the rendered layer among others reaches layers the pass did not clear. + let layers = Area { + layers: [0, 6], + ..rect([0, 16], [0, 16]) + }; + assert!(!clears(&[layers], rendered, [16, 16])); + assert!(!clears( + &[layers, rect([0, 16], [0, 16])], + rendered, + [16, 16] + )); + // Another layer of the level: the rendered layer 3 alone. + let third = Area { + layers: [3, 4], + ..rect([0, 16], [0, 16]) + }; + assert!(clears(&[third], (0, 3), [16, 16])); + assert!(!clears(&[third], rendered, [16, 16])); +} + +#[test] +fn an_area_reaches_the_levels_and_layers_it_holds_a_texel_of() { + let layers = Area { + level: 2, + layers: [1, 4], + x: [0, 4], + y: [0, 4], + }; + assert!(layers.reaches((2, 1)) && layers.reaches((2, 3))); + assert!(!layers.reaches((2, 4)) && !layers.reaches((2, 0)) && !layers.reaches((1, 1))); + let empty = Area { + x: [4, 4], + ..layers + }; + assert!(!empty.reaches((2, 1))); +} diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index d04451d78..de54b7bcf 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -2524,6 +2524,11 @@ impl Texture { Ok(Some(shadow)) } + /// The format its image's shadow is made in, the image's; `None` for an image of no shadow. + pub(crate) fn shadow_format(&self) -> Option { + (self.inner.image.shadowing.as_ref()).map(|shadowing| shadowing.made.2.format) + } + /// What a draw reads of its image through it (`crate::shadow`): with `own_pixel`, the draw's /// scissor (per axis `[first, end)`), the rectangle a fragment function that reads only at its /// own pixel reads of its first level and layer; else every level and layer it reaches.