From a96bd76fef4fbfc05d4c8bd841c0d428fa0639e0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 03:47:27 -0800 Subject: [PATCH] Keep a draw's shape across scissor rectangle changes A render encoder's draw takes its settings, draw state and VkPipeline from its shape memo while the encoder's state keeps its version. Setting a scissor rectangle took the state mutably, so a program that sets one before each draw, as a window compositor does, derived every draw's shape again: settings, draw state, and the pipeline lookup by key. The scissor rectangles now live beside the versioned EncoderState (render_state::ScissorRects). No piece of a draw's shape reads them but its draw state's Vulkan scissors, which each draw now sets from the rectangles it finds, on a draw state it derives or reuses. The commands recorded are the same: each draw records its own scissor as before. Verified: a device test (draw_shape_notices:: draws_after_new_scissor_rectangles_reuse_shapes) draws 8 times through 8 rectangles and finds 7 draws reusing their shape and 8 scissors recorded; with the version bump put back into set_scissor_rect it fails (0 reused). render_state unit tests and the draw_shape_notices device tests pass on MoltenVK (M3 Max). Release, the per-draw repro on the M3 Max over MoltenVK, flat out, cache mode, 3000 buffers: draws_shapes_reused goes from 0 to 13 per buffer (35 draws, 6 passes; the others are the first draw of their pipeline state in their encoder); every other WorkCounts field per buffer is unchanged. A draw with its setters p50 4.25 -> 4.12 us, mean 4.63 -> 4.42 us; the draw call alone p50 3.92 -> 3.79 us (two interleaved rounds each). (cherry picked from commit 603c78fcb85c5d0a732ec6004028d990e0ec8d64) --- crates/metal2vulkan-runtime/src/render.rs | 42 ++++--- .../src/render/call_checks.rs | 9 +- .../src/render/draw_shape.rs | 13 ++- .../src/render/executions.rs | 5 +- .../src/render/snapshot.rs | 2 +- .../metal2vulkan-runtime/src/render_state.rs | 109 +++++++++++------- .../src/tests/draw_shape_notices.rs | 45 +++++++- .../metal2vulkan-runtime/src/work_counts.rs | 13 ++- 8 files changed, 163 insertions(+), 75 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 82c49f6e8..869c412b0 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -315,7 +315,8 @@ use super::render_pass::{ self, AspectTarget, Attachment, DepthStencilTarget, PassLayout, RenderPassDescriptor, RenderPassProblem, Target, MAX_COLOR_ATTACHMENTS, }; -use super::render_state::{self, DepthBiasRecord, EncoderState, ViewportList, MAX_VIEWPORTS}; +use super::render_state::MAX_VIEWPORTS; +use super::render_state::{self, DepthBiasRecord, EncoderState, ScissorRects, ViewportList}; use super::render_state::{Compensation, DepthBiasEffect, WrittenDepthClamp}; use super::render_target::{self, covers, Feedback, PassShape, Position, RenderPassObject}; use super::render_values::{ @@ -1385,6 +1386,8 @@ pub(crate) struct RenderLowering { /// layered pass (`PassLayout::layers`). render_target_array_length: u32, state: Versioned, + /// Apart from `state`: setting them keeps the draws' shapes (`ScissorRects`). + scissors: ScissorRects, pipeline: Option, /// The routing of the drawing state last set (`ShapeInputs::routing`), which its check /// and each of its draws (their settings and their coverage) read. @@ -1969,6 +1972,10 @@ impl RenderLowering { let live = core.device().shared().live_binds.take(); // The views and sampler descriptions its binds made or found (`binding::BindMemo`). let bind_memo = core.device().shared().bind_memos.take(); + // Metal's default viewport and scissor rectangle cover the render area: a rate map's. + let area = rate_map + .as_ref() + .map_or(layout.extent, RateMappedPass::area); Box::new(RenderLowering { core, earlier: Vec::new(), @@ -2001,11 +2008,8 @@ impl RenderLowering { feedback: Feedback::NONE, storage_colors: 0, }, - state: Versioned::new(EncoderState::metal_defaults( - rate_map - .as_ref() - .map_or(layout.extent, RateMappedPass::area), - )), + state: Versioned::new(EncoderState::metal_defaults(area)), + scissors: ScissorRects::metal_default(area), render_target_array_length, visibility: Visibility::new(layout.visibility.clone()), layout: Versioned::new(layout), @@ -3075,13 +3079,15 @@ impl RenderLowering { /// The lowering of [`RenderCommandEncoder::set_scissor_rect`]. pub(crate) fn set_scissor_rect(&mut self, rect: ScissorRect) -> Result<(), Error> { self.log(|_| RenderCall::ScissorRect(rect)); - self.state.set_scissors("set_scissor_rect", &[rect]) + self.scissors = self.state.scissor_rects("set_scissor_rect", &[rect])?; + Ok(()) } /// The lowering of [`RenderCommandEncoder::set_scissor_rects`]. pub(crate) fn set_scissor_rects(&mut self, rects: &[ScissorRect]) -> Result<(), Error> { self.log(|_| RenderCall::ScissorRects(rects.into())); - self.state.set_scissors("set_scissor_rects", rects) + self.scissors = self.state.scissor_rects("set_scissor_rects", rects)?; + Ok(()) } /// The lowering of [`RenderCommandEncoder::set_cull_mode`]. @@ -6501,7 +6507,9 @@ impl RenderLowering { return false; }; let mut scissors = [vk::Rect2D::default(); MAX_VIEWPORTS]; - let rects = self.state.vk_scissors_in(selects, &mut scissors); + let rects = self + .state + .vk_scissors_in(&self.scissors, selects, &mut scissors); let mut drawn: Option<[u32; 4]> = None; for r in rects .iter() @@ -7133,7 +7141,9 @@ impl RenderLowering { false => { let selects = selects || self.amplification.offsets_viewports(); let mut scissors = [vk::Rect2D::default(); MAX_VIEWPORTS]; - let rects = self.state.vk_scissors_in(selects, &mut scissors); + let rects = self + .state + .vk_scissors_in(&self.scissors, selects, &mut scissors); self.drawn.add(rects); // And its instance's, the one it recorded into. self.current.drawn.add(rects); @@ -8388,10 +8398,14 @@ impl RenderLowering { viewports, depth, } = match kept_state { - Some(kept) => { + // Through the scissor rectangles the draw finds, which no other piece of it reads + // (`ScissorRects`). + Some(mut kept) => { + let selects = graphics.writes_viewport_index; + kept.state.scissors = self.state.vk_scissors(&self.scissors, selects); debug_assert!( (self.shape_inputs()) - .draw_state(graphics, &settings, failed) + .draw_state(graphics, &settings, failed, &self.scissors) .is_ok_and(|fresh| fresh == kept), "a draw's state derived again differs from the one kept for its inputs" ); @@ -8400,7 +8414,7 @@ impl RenderLowering { None => { let watch = EachWatch::start(); let inputs = self.shape_inputs(); - let shaped = inputs.draw_state(graphics, &settings, failed)?; + let shaped = inputs.draw_state(graphics, &settings, failed, &self.scissors)?; // Kept where its derivation announced nothing at each occurrence. if let (Some(token), false) = (shape_token, watch.met()) { self.shape_memo.keep_state(token, &variant, &shaped); @@ -8434,7 +8448,7 @@ impl RenderLowering { let regions = pass.draws( slice, &viewports[0], - self.state.first_scissor(), + self.scissors.first(), graphics, &device.shared().region_limits, render_area, diff --git a/crates/metal2vulkan-runtime/src/render/call_checks.rs b/crates/metal2vulkan-runtime/src/render/call_checks.rs index d640f88ae..5d7ce351f 100644 --- a/crates/metal2vulkan-runtime/src/render/call_checks.rs +++ b/crates/metal2vulkan-runtime/src/render/call_checks.rs @@ -256,16 +256,17 @@ impl CallChecks { .set_viewports("set_viewports", viewports, refused)) .map(logged) } + // Checked alone: no later check reads the rectangles. C::ScissorRect(rect) => { let rects = std::slice::from_ref(rect); self.state - .set_scissors("set_scissor_rect", rects) - .map(logged) + .scissor_rects("set_scissor_rect", rects) + .map(|_| Checked::Logged) } C::ScissorRects(rects) => self .state - .set_scissors("set_scissor_rects", rects) - .map(logged), + .scissor_rects("set_scissor_rects", rects) + .map(|_| Checked::Logged), C::CullMode(mode) => { self.state.set_cull_mode(*mode); Ok(Checked::Logged) diff --git a/crates/metal2vulkan-runtime/src/render/draw_shape.rs b/crates/metal2vulkan-runtime/src/render/draw_shape.rs index 90e9776e0..7b9869921 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_shape.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_shape.rs @@ -7,7 +7,10 @@ //! encoder's state and vertex amplification, whether a visibility query counts the draws, the //! pass's rasterization-rate map, whether the encoder records an execution's commands, and the //! routing the encoder kept for its drawing state (a cache of a function of the state and the -//! pass's colors, which changes no piece). Beside them each piece takes the draw's own: its +//! pass's colors, which changes no piece). The encoder's scissor rectangles are no input: the +//! state holds none (`render_state::ScissorRects`), and the draw state's Vulkan scissors, the +//! one piece that reads them, are each draw's own, set again on a draw state it reuses, so a +//! draw after a new rectangle reuses its shape. Beside them each piece takes the draw's own: its //! drawing state, assembly and whether it may draw a primitive //! (`line_width::draws_primitives`); for the draw state its //! variant's compiled state and what the draw's failing depth and shader-side tests make of it; @@ -53,7 +56,7 @@ use crate::pipeline::{FixedState, GraphicsState as DrawingState}; use crate::pipeline::{RawPipeline, RenderVariant}; use crate::rate_mapped_pass::RateMappedPass; use crate::render_pass::{PassLayout, HIDDEN_DEPTH_FORMAT}; -use crate::render_state::{self, DepthBiasRecord, EncoderState, ViewportList}; +use crate::render_state::{self, DepthBiasRecord, EncoderState, ScissorRects, ViewportList}; use crate::render_state::{Compensation, DepthBiasEffect, WrittenDepthClamp}; use crate::render_target::RenderPassObject; use crate::render_values::Viewport; @@ -537,7 +540,8 @@ impl ShapeInputs<'_> { } /// The state a draw of `graphics`, its variant's, records with under `settings` - /// ([`DrawState`]: statically, or as dynamic state), failing as `failing` says, its fragment + /// ([`DrawState`]: statically, or as dynamic state), through the encoder's `scissors`, failing + /// as `failing` says, its fragment /// function the stencil test (`shadow`, a shader-side stencil) or the depth test (`tests`); /// with the viewports in Metal's terms and the compensated /// depth range a rate-mapped pass draws each region through (`rate_mapped_pass.rs`). A 16-bit @@ -547,6 +551,7 @@ impl ShapeInputs<'_> { graphics: &GraphicsState, settings: &DrawSettings, (failing, shadow, tests): (Option<&FailingDraw>, bool, bool), + scissors: &ScissorRects, ) -> Result { let device = self.device; let profile = device.compile_device().profile(); @@ -596,7 +601,7 @@ impl ShapeInputs<'_> { depth, compensation.and_then(|c| c.guard), ), - scissors: self.state.vk_scissors(selects), + scissors: self.state.vk_scissors(scissors, selects), fixed, stencil_reference: self.state.stencil_reference(), depth_bias, diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index f01d692fd..9be99ae84 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -310,7 +310,7 @@ use crate::pipeline::{ }; use crate::rate_mapped_pass::RateMappedPass; use crate::render_pass::{ColorTarget, PassLayout, Target}; -use crate::render_state::EncoderState; +use crate::render_state::{EncoderState, ScissorRects}; use crate::render_target::{self, Feedback, PassShape, Position, RenderPassObject}; use crate::render_values::DrawPrimitiveType; use crate::residency::{every_render_stage, Residency}; @@ -665,6 +665,7 @@ impl RenderLowering { let snapshot = Snapshot { layout: self.layout.clone(), state, + scissors: self.scissors.clone(), vertex: if inherited { self.vertex.clone() } else { @@ -974,6 +975,7 @@ pub(crate) struct RenderExecution { struct Snapshot { layout: PassLayout, state: EncoderState, + scissors: ScissorRects, vertex: ArgumentTable, fragment: ArgumentTable, object: ArgumentTable, @@ -2359,6 +2361,7 @@ impl RenderExecution { passes: vec![(snapshot.shape.clone(), Arc::clone(&snapshot.compatible))], render_target_array_length: snapshot.render_target_array_length, state: Versioned::new(snapshot.state.clone()), + scissors: snapshot.scissors.clone(), pipeline: None, routed: None, vertex: snapshot.vertex.clone(), diff --git a/crates/metal2vulkan-runtime/src/render/snapshot.rs b/crates/metal2vulkan-runtime/src/render/snapshot.rs index d6ee25233..3d548dcdf 100644 --- a/crates/metal2vulkan-runtime/src/render/snapshot.rs +++ b/crates/metal2vulkan-runtime/src/render/snapshot.rs @@ -389,7 +389,7 @@ impl RenderLowering { let mut rects = [vk::Rect2D::default(); MAX_VIEWPORTS]; let bound: u64 = self .state - .vk_scissors_in(selects, &mut rects) + .vk_scissors_in(&self.scissors, selects, &mut rects) .iter() .map(|r| u64::from(r.extent.width) * u64::from(r.extent.height)) .sum(); diff --git a/crates/metal2vulkan-runtime/src/render_state.rs b/crates/metal2vulkan-runtime/src/render_state.rs index f10f90009..4d9fe8352 100644 --- a/crates/metal2vulkan-runtime/src/render_state.rs +++ b/crates/metal2vulkan-runtime/src/render_state.rs @@ -185,13 +185,35 @@ pub enum RenderStateProblem { ViewportNotFinite, } -/// The render encoder's state, in Metal's terms. +/// The render encoder's scissor rectangles (`setScissorRect:`, `setScissorRects:count:`), as +/// [`EncoderState::scissor_rects`] clipped them. Kept apart from the [`EncoderState`]: a draw's +/// shape reads none of them but its draw state's Vulkan scissors, which each draw takes from the +/// rectangles it finds ([`EncoderState::vk_scissors`]), so the draws of a program that sets a +/// rectangle before each, as a window compositor's do, find their shapes kept +/// (`render/draw_shape.rs`). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct ScissorRects(ViewportList); + +impl ScissorRects { + /// Metal's default: the render area of `extent`. + pub(super) fn metal_default([width, height]: [u32; 2]) -> ScissorRects { + let area = ScissorRect::new(0, 0, u64::from(width), u64::from(height)); + ScissorRects(ViewportList::One(area)) + } + + /// The first rectangle, which a draw of a pipeline that selects no viewport uses. + pub(super) fn first(&self) -> &ScissorRect { + &self.0[0] + } +} + +/// The render encoder's state, in Metal's terms, but for its scissor rectangles +/// ([`ScissorRects`]). #[derive(Clone)] pub(super) struct EncoderState { /// The render area's width and height. extent: [u32; 2], viewports: ViewportList, - scissors: ViewportList, cull_mode: CullMode, winding: Winding, /// `None` is Metal's default state, the default descriptor's. @@ -230,12 +252,6 @@ impl EncoderState { 0.0, 1.0, )), - scissors: ViewportList::One(ScissorRect::new( - 0, - 0, - u64::from(width), - u64::from(height), - )), cull_mode: CullMode::None, winding: Winding::Clockwise, depth_stencil: None, @@ -293,13 +309,13 @@ impl EncoderState { Ok(()) } - /// `setScissorRects:count:` (one rectangle for `setScissorRect:`), checked as the module - /// says. - pub(super) fn set_scissors( - &mut self, + /// The rectangles `setScissorRects:count:` (one rectangle for `setScissorRect:`) sets, + /// checked and clipped to the render area as the module says. + pub(super) fn scissor_rects( + &self, call: &'static str, scissors: &[ScissorRect], - ) -> Result<(), Error> { + ) -> Result { // More than 16 rectangles stop Metal's validation, and plain Metal draws (Metal probe case // `scissors_17` on an M4): a draw goes through the rectangles its viewports name // (`EncoderState::vk_scissors`). None, unmeasured, is refused. @@ -315,7 +331,7 @@ impl EncoderState { let start = origin.min(end); (start, origin.saturating_add(size).min(end) - start) }; - self.scissors = scissors + let rects = scissors .iter() .map(|s| { let (x, width) = clip(s.x, s.width, width); @@ -323,7 +339,7 @@ impl EncoderState { ScissorRect::new(x, y, width, height) }) .collect(); - Ok(()) + Ok(ScissorRects(rects)) } pub(super) fn set_cull_mode(&mut self, mode: CullMode) { @@ -812,11 +828,6 @@ impl EncoderState { Ok(biased.then_some(self.depth_bias)) } - /// The first scissor rectangle, which a draw of a pipeline that selects no viewport uses. - pub(super) fn first_scissor(&self) -> &ScissorRect { - &self.scissors[0] - } - /// The powers of two `[sx, sy]` a draw of points widens the Vulkan viewports it uses by, /// about their centers ([`EncoderState::vk_viewports`]), its vertex stage scaling the /// position by their inverses and culling at Metal's guard band ([`guard_points`]): on each @@ -912,40 +923,50 @@ impl EncoderState { .collect() } - /// The draw's scissors in Vulkan's terms: one per viewport it uses, the Metal rectangle of - /// its index, the one rectangle where the encoder holds one, and an empty one past two or - /// more (the module docs), each clipped to the pixels its viewport overlaps, Metal's implicit - /// scissor ([`viewport_pixels`]). - pub(super) fn vk_scissors(&self, selects: bool) -> ViewportList { - self.each_vk_scissor(selects).collect() + /// The draw's scissors in Vulkan's terms, through the encoder's `scissors`: one per viewport + /// it uses, the Metal rectangle of its index, the one rectangle where the encoder holds one, + /// and an empty one past two or more (the module docs), each clipped to the pixels its + /// viewport overlaps, Metal's implicit scissor ([`viewport_pixels`]). + pub(super) fn vk_scissors( + &self, + scissors: &ScissorRects, + selects: bool, + ) -> ViewportList { + self.each_vk_scissor(scissors, selects).collect() } /// [`vk_scissors`](Self::vk_scissors) into `rects`, of [`MAX_VIEWPORTS`] (the most a draw /// uses), without allocating. pub(super) fn vk_scissors_in<'a>( &self, + scissors: &ScissorRects, selects: bool, rects: &'a mut [vk::Rect2D; MAX_VIEWPORTS], ) -> &'a [vk::Rect2D] { let count = rects .iter_mut() - .zip(self.each_vk_scissor(selects)) + .zip(self.each_vk_scissor(scissors, selects)) .map(|(rect, scissor)| *rect = scissor) .count(); &rects[..count] } /// Each of [`vk_scissors`](Self::vk_scissors), in order. - fn each_vk_scissor(&self, selects: bool) -> impl Iterator + '_ { + fn each_vk_scissor<'a>( + &'a self, + scissors: &'a ScissorRects, + selects: bool, + ) -> impl Iterator + 'a { let extent = self.extent.map(i64::from); let none = ScissorRect::new(0, 0, 0, 0); + let rects = &scissors.0; self.used_viewports(selects) .iter() .enumerate() .map(move |(i, viewport)| { - let s = match self.scissors.len() { - 1 => &self.scissors[0], - _ => self.scissors.get(i).unwrap_or(&none), + let s = match rects.len() { + 1 => &rects[0], + _ => rects.get(i).unwrap_or(&none), }; // Inside the render area (checked at the setter). let scissor = [ @@ -2203,15 +2224,20 @@ mod tests { vec![[0.0, 0.0, 4.0, 4.0, 0.0, 1.0]] ); assert_eq!(state.used_viewports(true).len(), 2); - assert_eq!(state.vk_scissors(true).len(), 2, "one scissor each"); + let scissors = ScissorRects::metal_default([8, 4]); + assert_eq!( + state.vk_scissors(&scissors, true).len(), + 2, + "one scissor each" + ); } /// The scissor rules (probe 4): inside the render area, an empty one included; past it, /// clipped to it, as plain Metal draws it; 1 to 16 of them. #[test] fn scissors_stay_inside_the_render_area() { - let mut state = EncoderState::metal_defaults([4, 4]); - let set = |state: &mut EncoderState, s: &[ScissorRect]| state.set_scissors("t", s); + let state = EncoderState::metal_defaults([4, 4]); + let set = |s: &[ScissorRect]| state.scissor_rects("t", s).map(|rects| rects.0); for (given, kept) in [ (ScissorRect::new(1, 1, 2, 2), ScissorRect::new(1, 1, 2, 2)), (ScissorRect::new(0, 0, 0, 0), ScissorRect::new(0, 0, 0, 0)), @@ -2223,18 +2249,18 @@ mod tests { ScissorRect::new(4, 0, 0, 1), ), ] { - assert_eq!(set(&mut state, &[given]), Ok(()), "{given:?}"); - assert_eq!(*state.scissors, [kept], "{given:?}"); + assert_eq!(set(&[given]), Ok(ViewportList::One(kept)), "{given:?}"); } assert_eq!( - set(&mut state, &[]), + set(&[]), Err(invalid( "t", Problem::RenderState(RenderStateProblem::Count { count: 0 }) )) ); // More than 16, as plain Metal takes them (Metal probe case `scissors_17`). - assert_eq!(set(&mut state, &[ScissorRect::new(0, 0, 1, 1); 17]), Ok(())); + let many = set(&[ScissorRect::new(0, 0, 1, 1); 17]); + assert_eq!(many.map(|rects| rects.len()), Ok(17)); } /// A viewport's pixels are those it overlaps (probes 4, 4b and 4c: a 1-pixel viewport at x 4 @@ -2261,7 +2287,8 @@ mod tests { state.viewports = [Viewport::new(4.0, 0.0, 0.0, 8.0, 0.0, 1.0)] .into_iter() .collect(); - assert_eq!(state.vk_scissors(false)[0].extent.width, 0); + let area = ScissorRects::metal_default([8, 8]); + assert_eq!(state.vk_scissors(&area, false)[0].extent.width, 0); assert_eq!( EncoderState::vk_viewports(state.used_viewports(false), None, None)[0].width, 1.0 @@ -2269,8 +2296,8 @@ mod tests { state.viewports = [Viewport::new(2.0, 2.0, 4.0, 4.0, 0.0, 1.0)] .into_iter() .collect(); - state.scissors = [ScissorRect::new(3, 0, 5, 8)].into_iter().collect(); - let clipped = state.vk_scissors(false)[0]; + let rects = state.scissor_rects("t", &[ScissorRect::new(3, 0, 5, 8)]); + let clipped = state.vk_scissors(&rects.unwrap(), false)[0]; assert_eq!( ( clipped.offset.x, diff --git a/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs b/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs index 4d72656db..3a99c423e 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs @@ -3,7 +3,8 @@ //! meets such a kind derives it anew and announces it at every draw, as a device without the memo //! would; a draw whose shape meets none takes it from the memo, whatever other kinds the device //! announces at each (`WorkCounts::draw_shapes_reused`), as a device that announces every kind -//! once does. +//! once does. A draw after a new scissor rectangle reuses its shape too, through its own scissor +//! (`render_state::ScissorRects`). //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixture @@ -14,7 +15,8 @@ use super::encoder_holds::{bytes_of, library, pass}; use crate::{ CommandBufferStatus, Degradation, DegradeNotice, DepthStencilState, Device, DeviceKind, DeviceOptions, MessageSink, PipelineOptions, RenderCommandEncoder, RenderPassDescriptor, - RenderPipelineState, ResourceOptions, ShaderCacheOptions, Texture, TextureDescriptor, + RenderPipelineState, ResourceOptions, ScissorRect, ShaderCacheOptions, Texture, + TextureDescriptor, }; use metal2vulkan::metal::state::DepthStencilDescriptor; use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, TextureUsage}; @@ -120,11 +122,13 @@ fn target(device: &Device, format: PixelFormat) -> Texture { /// What an encoder of a test draws: a rectangle of `state` over the whole target, as triangles, /// and before each, where `points`, as points (whose vertex function writes no point size, of no /// point class: `UnsizedPoints`, `ShapeInputs::settings`), each [`DRAWS`] times; tested against -/// `depth` where given. +/// `depth` where given; each triangles' draw through a scissor rectangle of its own set before it +/// where `scissors`. struct Draws<'a> { state: &'a RenderPipelineState, points: bool, depth: Option<(&'a Texture, &'a DepthStencilState)>, + scissors: bool, } impl Draws<'_> { @@ -162,7 +166,11 @@ impl Draws<'_> { encoder.set_vertex_bytes(&corners, 0).unwrap(); let color = bytes_of(&[0.2f32, 0.4, 0.6, 1.0], f32::to_le_bytes); encoder.set_fragment_bytes(&color, 0).unwrap(); - for _ in 0..DRAWS { + for at in 0..DRAWS as u64 { + if self.scissors { + let rect = ScissorRect::new(at, 0, SIDE - at, SIDE); + assert_eq!(encoder.set_scissor_rect(rect), Ok(())); + } if self.points { let drawn = encoder.draw_primitives(PrimitiveType::Point, 0, 4, 1, 0); assert_eq!(drawn, Ok(())); @@ -196,6 +204,7 @@ fn second_run(each: &[Degradation], points: bool, depth: bool) -> (u64, Counts) state: &state, points, depth: depth.then_some((&texture, &depth_stencil)), + scissors: false, }; until("every key's own pipeline made", || { let residual = device.work_counts().residual_form_draws; @@ -255,6 +264,7 @@ fn a_kind_a_draws_state_meets_is_announced_at_every_draw() { state: &state, points: false, depth: Some((&texture, &depth_stencil)), + scissors: false, }; draws.run(&device); counts(&heard) @@ -275,3 +285,30 @@ fn a_kind_a_draws_state_meets_is_announced_at_every_draw() { }; assert_eq!(reused, expected, "{met:?}"); } + +/// Draws that each set a scissor rectangle of their own before they draw, as a window compositor's +/// do, reuse their shapes as draws through one rectangle do (the rectangles are no input of a +/// shape: `render_state::ScissorRects`), each after the first, and each records its own scissor. +#[test] +fn draws_after_new_scissor_rectangles_reuse_shapes() { + let scratch = Scratch::new("draw-shape-scissors"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = rectangle_state(&device, false); + let draws = Draws { + state: &state, + points: false, + depth: None, + scissors: true, + }; + until("every key's own pipeline made", || { + let residual = device.work_counts().residual_form_draws; + draws.run(&device); + device.work_counts().residual_form_draws == residual + }); + let scissors = device.work_counts().commands_recorded.cmd_set_scissor; + let reused = draws.run(&device); + assert_eq!(reused, DRAWS as u64 - 1); + let recorded = device.work_counts().commands_recorded.cmd_set_scissor - scissors; + assert_eq!(recorded, DRAWS as u64, "a scissor each"); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b253fcea7..2b3f694bf 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -4254,12 +4254,13 @@ pub struct WorkCounts { pub set_zero_sets_found: u64, /// Render encoders' draws that took their shape, what they derive from the encoder's state /// alone, from an earlier draw of their encoder that derived it from the same inputs, rather - /// than deriving it again: their settings, their draw state (fixed state, viewports, scissors, - /// depth bias) and their `VkPipeline`. The inputs are the drawing state, variant, plan and - /// instance's compatible pass by identity, the pass's layout, the encoder's state and vertex - /// amplification and the instance's shape by version, and the assembly, the vertex strides, - /// the fixed state and the topology by value (`render/draw_shape.rs`). None of a shape whose - /// derivation announces a notice the device announces at every occurrence + /// than deriving it again: their settings, their draw state (fixed state, viewports, depth + /// bias; its scissors are each draw's own, from the encoder's scissor rectangles) and their + /// `VkPipeline`. The inputs are the drawing state, variant, plan and instance's compatible + /// pass by identity, the pass's layout, the encoder's state but its scissor rectangles and + /// vertex amplification and the instance's shape by version, and the assembly, the vertex + /// strides, the fixed state and the topology by value (`render/draw_shape.rs`). None of a + /// shape whose derivation announces a notice the device announces at every occurrence /// (`DeviceOptions::announce_each`). pub draw_shapes_reused: u64, /// Compute encoders' dispatches that took the bind state, variant, plan, commands and made