diff --git a/crates/metal2vulkan-runtime/src/clear_reach.rs b/crates/metal2vulkan-runtime/src/clear_reach.rs index 08efe60b8..50038692f 100644 --- a/crates/metal2vulkan-runtime/src/clear_reach.rs +++ b/crates/metal2vulkan-runtime/src/clear_reach.rs @@ -346,7 +346,7 @@ fn set_bits(row: &mut [u64; ROW_WORDS], bits: std::ops::Range) { /// other tile keeps its texels). The whole render area where a draw's pixels are not bounded so: /// an execution of render commands, a tile dispatch, a pass through a rasterization-rate map, or /// more than [`MOST_RECTS`] distinct rectangles. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq)] pub(super) struct DrawnArea { /// Each distinct `[x0, y0, x1, y1]`, half-open, inside the render area. rects: Rects, @@ -356,7 +356,7 @@ pub(super) struct DrawnArea { /// Distinct pixel rectangles: the first held in place, as a pass's draws mostly reach one (its /// render area), so such a pass allocates none for them; the others in order, each once, in a /// list that keeps its room when cleared ([`DrawnArea::clear`]). -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq)] struct Rects { first: Option<[u32; 4]>, /// Empty while `first` is `None`; never holds `first`. diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 81dae221b..f8d8db00c 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2667,6 +2667,19 @@ thread_local! { static MET_EACH: Cell = const { Cell::new(0) }; } +#[cfg(debug_assertions)] +thread_local! { + /// The messages delivered on this thread (builds with debug assertions). + static DELIVERED: Cell = const { Cell::new(0) }; +} + +/// How many messages were delivered on this thread so far (builds with debug assertions): what a +/// check that some work announced nothing compares (`render/draw_again.rs`). +#[cfg(debug_assertions)] +pub(crate) fn announced_here() -> u64 { + DELIVERED.with(Cell::get) +} + /// Count a notice met on this thread that its device announces, or refuses, at every occurrence. fn met_each() { MET_EACH.with(|met| met.set(met.get().wrapping_add(1))); @@ -3192,6 +3205,8 @@ impl Device { /// Hand `message` to the device's message sink, else write it on stderr. fn deliver(&self, message: &DebugMessage) { + #[cfg(debug_assertions)] + DELIVERED.with(|delivered| delivered.set(delivered.get() + 1)); match self.shared().instance.sink() { Some(sink) => sink.deliver(message), None => eprintln!("{}", message.text), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 8bf723358..ce6894aa0 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1349,17 +1349,10 @@ impl EncoderCore { self.touch_reaching(uses, resident); return Ok(()); }; - let shared = self.device().shared(); // Read before the host aliases' uses are worked out, so a change made since counts. - let into = NotedInto { - core: self.id, - parts: self.uses.parts(), - held: self.uses.held().len(), - rebinds: shared.rebinds.any(), - aliases: shared.aliases.version(), - }; + let into = self.noted_into(); if noted.holds(stages, (uses, resident), into) { - shared.counts.command_noted_as_before(); + self.device().shared().counts.command_noted_as_before(); return Ok(()); } let fresh = noted.fresh(uses, into); @@ -1369,6 +1362,50 @@ impl EncoderCore { Ok(()) } + /// The encoder's state a command noted apart now is noted into (`NotedInto`). + pub(super) fn noted_into(&self) -> NotedInto { + let shared = self.device().shared(); + NotedInto { + core: self.id, + parts: self.uses.parts(), + held: self.uses.held().len(), + rebinds: shared.rebinds.any(), + aliases: shared.aliases.version(), + } + } + + /// Whether the command apart `noted` keeps, the last one [`note_reaching`](Self::note_reaching) + /// noted, was noted into the encoder's state now: then a command of its stages and uses, + /// reaching the keys it reached through the resident set alone, is noted already, and noting + /// it notes only its reads of fresh textures and what the encoder made resident since + /// ([`note_again`](Self::note_again)). + pub(super) fn noted_now(&self, noted: &NotedApart) -> bool { + !self.uses.ordered() && noted.noted_into(self.noted_into()) + } + + /// Note again a command apart noted already ([`noted_now`](Self::noted_now)) with `uses`, as + /// [`note_reaching`](Self::note_reaching) notes it, but for its count + /// (`WorkCounts::commands_noted_as_before`), which its caller counts: its reads of fresh + /// textures, and the buffers the encoder made resident since its last command. `uses` may + /// leave out the uses that read no image other than as an attachment, which note nothing. + pub(super) fn note_again(&mut self, uses: &[Use]) { + self.observe_fresh(uses, &[]); + self.hold_resident(); + } + + /// Whether noting a command's reads of fresh textures may announce one + /// (`fresh_unwritten.rs`): the device has a texture still unwritten since it was made. + pub(super) fn observes_fresh(&self) -> bool { + self.device().shared().fresh.any() + } + + /// How many holds and execution records the encoder keeps for its command buffer (builds + /// with debug assertions: `render/draw_again.rs`'s check). + #[cfg(debug_assertions)] + pub(super) fn retained_holds(&self) -> (usize, usize) { + (self.retained.len(), self.executions.len()) + } + /// Record one command apart that runs in `stages` with `uses`, and the uses of the host /// memory beside them ([`aliased`](Self::aliased)), worked out into the vector the encoder /// keeps for them. diff --git a/crates/metal2vulkan-runtime/src/linear_attachment.rs b/crates/metal2vulkan-runtime/src/linear_attachment.rs index 33e00cd55..62029d7db 100644 --- a/crates/metal2vulkan-runtime/src/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/linear_attachment.rs @@ -78,7 +78,7 @@ use metal2vulkan::pipeline::ColorAttachmentState; /// What a pass's draws write of each color attachment, as far as the host bounds it: the box an /// attachment rendered apart is copied in and merged back over ([`choose`]). -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq)] pub(super) struct Coverage { /// By color index: the box of every pixel a draw may write, `[x0, y0, x1, y1]`, half-open. colors: [Option<[u32; 4]>; MAX_COLOR_ATTACHMENTS], diff --git a/crates/metal2vulkan-runtime/src/noted_apart.rs b/crates/metal2vulkan-runtime/src/noted_apart.rs index 50b813f99..977208eb6 100644 --- a/crates/metal2vulkan-runtime/src/noted_apart.rs +++ b/crates/metal2vulkan-runtime/src/noted_apart.rs @@ -33,7 +33,7 @@ use super::resource::ResourceKey; use super::tracker::Use; /// What the last command noted apart was noted with (the module docs). -#[derive(Default)] +#[derive(Clone, Default, PartialEq)] pub(super) struct NotedApart { /// The core of the encoder that noted it and kept it, if any. core: Option, @@ -83,6 +83,18 @@ impl NotedApart { && self.resident.iter().eq(resident) } + /// Whether the last command was noted into `into`: then a command noted with its stages and + /// uses, reaching the same keys through the resident set alone, is noted already + /// ([`holds`](Self::holds)). + pub(super) fn noted_into(&self, into: NotedInto) -> bool { + self.core == Some(into.core) && self.into() == into + } + + /// The last command's uses, as given. + pub(super) fn uses(&self) -> &[Use] { + &self.uses + } + /// Keep the command just noted, of `stages` with `uses`, of which it reached the keys /// `resident` through the resident set alone, noted into `into`. pub(super) fn note( diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 04d000529..1540f6b7f 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -393,6 +393,7 @@ mod bound; mod call_checks; mod color_groups; mod deferral; +mod draw_again; mod draw_room; mod draw_shape; mod executions; @@ -1604,6 +1605,8 @@ pub(crate) struct RenderLowering { /// What the draws recorded inline into the pass's command buffer bound there, in its every /// render pass instance (`render/inline_splits.rs`). held_bound: Bound, + /// The last direct draw, kept for drawing again while no call comes (`render/draw_again.rs`). + again: draw_again::DrawAgain, /// The pass's color group, where the device draws its colors in groups: the encoder draws /// that group's (`render/color_groups.rs`). grouped: Option>, @@ -2093,6 +2096,7 @@ impl RenderLowering { None => inline_first::Inline::Never, }, held_bound: Bound::default(), + again: draw_again::DrawAgain::default(), grouped, }) } @@ -3239,7 +3243,7 @@ impl RenderLowering { instance_count: u32, base_instance: u32, ) -> Result<(), Error> { - self.log(|_| { + self.log_draw(|_| { RenderCall::DrawPrimitives( primitive_type, vertex_start, @@ -4012,6 +4016,8 @@ impl RenderLowering { /// color groups draw (`render/color_groups.rs`). fn end_pass(mut self: Box) -> Result { const CALL: &str = "end_encoding"; + // Its draws again counted (`render/draw_again.rs`). + self.forget_again(); // Over a mutable rasterization-rate map: Metal's GPU hangs at a pass of no draw call until // a command buffer with a draw call over such a map was committed (`rate_mapped_pass.rs`). if self.rate_map.as_ref().is_some_and(RateMappedPass::mutable) { @@ -7149,6 +7155,16 @@ impl RenderLowering { empty: bool, ) -> Result<(), Error> { self.sync_heaps(); + // The encoder's kept draw again, which no call came between: its Vulkan draw alone + // (`render/draw_again.rs`). Any other draw forgets it, and keeps itself where it can. + let checked = match self.draw_again(call, assembly, &draw, &buffers) { + draw_again::Again::Drawn => return Ok(()), + #[cfg(debug_assertions)] + draw_again::Again::Check(checked) => Some(checked), + draw_again::Again::No => None, + }; + self.forget_again(); + let watch = EachWatch::start(); // And whether it rasterizes, without which its primitives reach no tile (`no_raster_t11`). // And whether it chooses its viewport. let (reads, rasterizes, selects) = @@ -7169,6 +7185,9 @@ impl RenderLowering { _ => { let drawn = self.draw_resident(call, assembly, draw, buffers, empty); self.group_outcome(turn, drawn.is_ok()); + if drawn.is_err() { + self.forget_again(); + } drawn?; } } @@ -7184,7 +7203,8 @@ impl RenderLowering { self.called = true; self.drew |= !empty && rasterizes; // A draw that records a command hands the device's pass its depth/stencil state. - self.drew_depth_writes |= !empty && self.state.depth_writes(); + let depth_writes = !empty && self.state.depth_writes(); + self.drew_depth_writes |= depth_writes; // The pixels it may write: its viewports' within its scissors, every viewport where it // chooses one or an amplification offsets it, and anywhere through a rate map. if !empty && rasterizes { @@ -7209,10 +7229,10 @@ impl RenderLowering { match self.pipeline.as_ref().map(RenderPipelineState::kind) { Some(RenderStateKind::Graphics(state)) => { let colors = &state.base().graphics.color_attachments; - let routing = self - .shape_inputs() - .routing(state) - .map_err(|_| internal("a draw of a state its pass refuses"))?; + let Ok(routing) = self.shape_inputs().routing(state) else { + self.again = Default::default(); + return Err(internal("a draw of a state its pass refuses")); + }; let zeroed = !self .shape_inputs() .routed_colors(state, &routing) @@ -7227,6 +7247,7 @@ impl RenderLowering { } } } + self.kept_again(&watch, (reads, !empty && rasterizes, depth_writes), checked); Ok(()) } @@ -9303,6 +9324,26 @@ impl RenderLowering { "a draw replay's draw of other recordings than one", )); } + // Whether the draw takes no step of its own beside its Vulkan draw, and records into the + // current instance as it stood, for keeping it to draw again (`render/draw_again.rs`): + // read before its steps below take their parts. + let stepless = rewrite.is_none() + && listed.is_none() + && bounds.is_none() + && fold.is_none() + && arguments.is_none() + && mesh_steps.is_none() + && tessellation_steps.is_none() + && !before_instance + && made.is_none() + && made_stand_in.is_none() + && made_imageblock.is_none() + && pending.is_none() + && inline.is_none() + && split_inline.is_none() + && matches!(next, Next::Current) + && stood.is_none() + && continuation.is_none(); // Recording starts here: nothing below can be refused. if let Some(written) = written { self.core.keep_set_zero(written, &writes); @@ -9355,6 +9396,8 @@ impl RenderLowering { self.barrier_splits += usize::from(run_barrier_split); self.run_barrier = false; self.gathering().add(&draw_shadows, uses); + // Whether it recorded a barrier in its instance, or a state command (`Recorded`). + let (mut barriered, mut draw_alone) = (false, false); if !empty && !culled { for source in index.into_iter().chain(indirect) { match (source.copy_steps(&mut self.core), before_instance) { @@ -9409,6 +9452,7 @@ impl RenderLowering { // imageblock's, a color's or the depth's stand-in, records after the barrier // (`InterlockedStorage`). let after_writes = interlocked.meets(self.current.interlocked_writes); + barriered |= after_writes; let mut storage_barrier = None; if after_writes { let view_mask = self.current.shape.view_mask; @@ -9437,6 +9481,7 @@ impl RenderLowering { // Instances follow one another behind a barrier from everything before. let written = self.current.indirect_reads.written_in(uses) & PASS_DRAW_STAGES; let mut indirect_barrier = None; + barriered |= !written.is_empty(); if !written.is_empty() { let view_mask = self.current.shape.view_mask; let stages = tracker::legacy_stages(written, vk::PipelineStageFlags::ALL_GRAPHICS); @@ -9462,6 +9507,7 @@ impl RenderLowering { // and mesh functions before any draw's fragments. let mut geometry_barrier = None; if let Some(barrier) = self.current.geometry_writes.barrier_before(uses) { + barriered = true; let view_mask = self.current.shape.view_mask; let scopes = render_target::GEOMETRY_SELF_DEPENDENCY; let mut legacy = barrier.legacy(); @@ -9625,6 +9671,7 @@ impl RenderLowering { } } } + draw_alone = states_recorded.draw_alone(); states_recorded.count(&device.shared().counts); if let Some((making, state, draws, query)) = split { // The record's times: the pipeline's, then those of the other `VkPipeline`s the @@ -9689,6 +9736,114 @@ impl RenderLowering { }); } } + // The draw, kept for drawing again where it took no step of its own, no notice it met + // aside (`kept_again`), and where nothing it left changes what the next draw meets + // (`render/draw_again.rs`). + // Its uses: none written, none read as indirect arguments, and whether one reads an image + // other than as an attachment. + let (unwritten, reads_images) = { + let mut reads_images = false; + let unwritten = uses.iter().all(|used| { + reads_images |= draw_again::reads_image(used); + used.write.is_empty() + && !(used.read.stages).intersects(vk::PipelineStageFlags2::DRAW_INDIRECT) + }); + (unwritten, reads_images) + }; + let ycbcr = |write: &metal2vulkan::bind::DescriptorWrite| { + matches!( + write.source, + WriteSource::YCbCrInPlace { .. } | WriteSource::YCbCrPlanesImage { .. } + ) + }; + let extended = |c: &render_pass::ColorTarget| { + ExtendedRange::of(c.target.texture.pixel_format()).is_some() + }; + let keeps = stepless + && !barriered + && !empty + && !culled + && !self.replaying + && !self.rerouting + && self.replayed.is_none() + && self.grouped.is_none() + && self.rate_map.is_none() + && self.current.kept.is_none() + && matches!(draw_pipeline, DrawPipeline::Made(_)) + && tessellation.is_none() + && !meshes + && pushes.len() == 1 + && vk_draws.len() == 1 + && chunked.is_empty() + && pair_base.is_none() + && matches!(draw_states, DrawStates::Whole(_)) + && snapshot.is_none() + && draw_shadows.is_empty() + && !attached + && stencil_use.is_none() + && tests_use.is_none() + && imageblock_use.is_none() + && tile_buffer.is_none() + && heap.is_none() + && texture_table.is_none() + && sampler_table.is_none() + && unlisted.is_none() + && bound_each.is_none() + && !reads_tile_memory + && !apart + && !first_write + && storage_colors == 0 + && reformats.is_empty() + && views == ViewSetup::default() + && resumed.is_none() + && commands.root_tables.is_empty() + && commands.push_holes.is_empty() + && pass_start.reads_encoders() + && matches!(settings.line, LineRoute::Plain) + && matches!( + provoking, + provoking::Provoking::AsIs | provoking::Provoking::Native + ) + && restarted.is_none() + && !private.private_list + && !private.quad_primitive_ids + && variant.key().primitive_id_indices.is_none() + && indirect.is_none() + && index.is_none_or(DrawSource::in_place) + && unwritten + && !self.extended.keeps_draws() + && live.state.extended_shadows.is_empty() + && !plan.variant.extended_range.values().any(planes) + && !(self.layout.colors.iter().flatten()).any(extended) + && !plan.descriptors.iter().any(ycbcr) + // Its uses noted as the next draw would find them noted (`noted_apart.rs`). + && self.core.noted_now(&live.noted); + if keeps { + let execution = records.then(|| draw_again::KeptExecution { + pipeline: ExecutedPipeline::Render(Arc::clone(variant.shared_pipeline())), + shape: Arc::clone(&shape), + created: created.clone(), + }); + let kept = draw_again::Kept { + call, + assembly, + draw, + index: index.and_then(draw_again::KeptIndex::of), + under: self.under(), + command_buffer: self.current.draws, + command: vk_draws[0].2, + again, + pushes_set_zero: !pushed.is_empty(), + last_vertex: provoking == provoking::Provoking::Native, + reads_images, + execution, + reads: RenderStages::empty(), + rasterizes: false, + depth_writes: false, + draw_alone, + }; + self.again.keep(kept); + } let padding = index.and_then(DrawSource::padding); if let (Some(source), Some(positions)) = (index, padding) { let (buffer, offset) = source.metal(); @@ -11337,90 +11492,7 @@ impl Recording<'_> { if let Some(pair) = &self.pair { pair.record(raw, cb, self.layout); } - match self.draw { - metal2vulkan::vk::DrawCommand::Draw { - vertex_count, - instance_count, - first_vertex, - first_instance, - } => raw.cmd_draw( - cb, - vertex_count, - instance_count, - first_vertex, - first_instance, - ), - metal2vulkan::vk::DrawCommand::DrawIndexed { - index_count, - instance_count, - first_index, - vertex_offset, - first_instance, - .. - } => raw.cmd_draw_indexed( - cb, - index_count, - instance_count, - first_index, - vertex_offset, - first_instance, - ), - metal2vulkan::vk::DrawCommand::DrawIndirect { - offset, - draw_count, - stride, - } => { - if let Some(buffer) = self.indirect { - raw.cmd_draw_indirect(cb, buffer, offset, draw_count, stride); - } - } - metal2vulkan::vk::DrawCommand::DrawIndexedIndirect { - offset, - draw_count, - stride, - .. - } => { - if let Some(buffer) = self.indirect { - raw.cmd_draw_indexed_indirect(cb, buffer, offset, draw_count, stride); - } - } - // A mesh render pipeline's state compiles only where the device enabled - // `meshShader`, which loads the commands. - metal2vulkan::vk::DrawCommand::DrawMeshTasks { - group_count_x, - group_count_y, - group_count_z, - } => { - if let Some(mesh) = self.mesh { - mesh.cmd_draw_mesh_tasks(cb, group_count_x, group_count_y, group_count_z); - } - } - metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirect { - offset, - draw_count, - stride, - } => { - if let (Some(mesh), Some(buffer)) = (self.mesh, self.indirect) { - mesh.cmd_draw_mesh_tasks_indirect(cb, buffer, offset, draw_count, stride); - } - } - metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirectCount { - offset, - count_offset, - max_draw_count, - stride, - } => { - if let (Some(mesh), Some(buffer)) = (self.mesh, self.indirect) { - mesh.cmd_draw_mesh_tasks_indirect_count( - cb, - buffer, - (offset, count_offset), - max_draw_count, - stride, - ); - } - } - } + record_draw_command(raw, cb, self.draw, self.indirect, self.mesh); } Recorded { states: recorded, @@ -11430,6 +11502,110 @@ impl Recording<'_> { } } +/// Record `draw`, the Vulkan draw command, into `cb`: an indirect one from `indirect`, a mesh one +/// through `mesh`, the device's mesh draw commands. +/// +/// # Safety +/// +/// `cb` is recording inside a pass compatible with the bound pipeline's, with every state the +/// pipeline and the command take bound or set, and every handle live until it completes; `mesh` +/// is the device's, where it enabled `meshShader`. +unsafe fn record_draw_command( + raw: &ash::Device, + cb: vk::CommandBuffer, + draw: metal2vulkan::vk::DrawCommand, + indirect: Option, + mesh: Option<&crate::recorder::MeshDraws>, +) { + // SAFETY: the caller's contract. + unsafe { + match draw { + metal2vulkan::vk::DrawCommand::Draw { + vertex_count, + instance_count, + first_vertex, + first_instance, + } => raw.cmd_draw( + cb, + vertex_count, + instance_count, + first_vertex, + first_instance, + ), + metal2vulkan::vk::DrawCommand::DrawIndexed { + index_count, + instance_count, + first_index, + vertex_offset, + first_instance, + .. + } => raw.cmd_draw_indexed( + cb, + index_count, + instance_count, + first_index, + vertex_offset, + first_instance, + ), + metal2vulkan::vk::DrawCommand::DrawIndirect { + offset, + draw_count, + stride, + } => { + if let Some(buffer) = indirect { + raw.cmd_draw_indirect(cb, buffer, offset, draw_count, stride); + } + } + metal2vulkan::vk::DrawCommand::DrawIndexedIndirect { + offset, + draw_count, + stride, + .. + } => { + if let Some(buffer) = indirect { + raw.cmd_draw_indexed_indirect(cb, buffer, offset, draw_count, stride); + } + } + // A mesh render pipeline's state compiles only where the device enabled + // `meshShader`, which loads the commands. + metal2vulkan::vk::DrawCommand::DrawMeshTasks { + group_count_x, + group_count_y, + group_count_z, + } => { + if let Some(mesh) = mesh { + mesh.cmd_draw_mesh_tasks(cb, group_count_x, group_count_y, group_count_z); + } + } + metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirect { + offset, + draw_count, + stride, + } => { + if let (Some(mesh), Some(buffer)) = (mesh, indirect) { + mesh.cmd_draw_mesh_tasks_indirect(cb, buffer, offset, draw_count, stride); + } + } + metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirectCount { + offset, + count_offset, + max_draw_count, + stride, + } => { + if let (Some(mesh), Some(buffer)) = (mesh, indirect) { + mesh.cmd_draw_mesh_tasks_indirect_count( + cb, + buffer, + (offset, count_offset), + max_draw_count, + stride, + ); + } + } + } + } +} + /// Record extended dynamic `state` at the encoder's value `s` (the draw's input `assembly`, /// its topology and primitive restart, for those): whether it is a state recorded here. /// diff --git a/crates/metal2vulkan-runtime/src/render/bound.rs b/crates/metal2vulkan-runtime/src/render/bound.rs index f2a5cbaa6..ba2bfa6e3 100644 --- a/crates/metal2vulkan-runtime/src/render/bound.rs +++ b/crates/metal2vulkan-runtime/src/render/bound.rs @@ -101,6 +101,11 @@ impl std::ops::AddAssign for Recorded { } impl Recorded { + /// Whether the draw recorded no state command and pushed no write: its Vulkan draw alone. + pub(super) fn draw_alone(&self) -> bool { + self.states == 0 && self.writes_pushed == 0 && self.equal_shapes == EqualShapes::default() + } + /// Add them to `counts` (`WorkCounts::draw_states_recorded`, `set_zero_writes_pushed`, /// `set_zero_equal_shape_switches` and kin). pub(super) fn count(self, counts: &crate::work_counts::Counters) { diff --git a/crates/metal2vulkan-runtime/src/render/draw_again.rs b/crates/metal2vulkan-runtime/src/render/draw_again.rs new file mode 100644 index 000000000..cb132e386 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/render/draw_again.rs @@ -0,0 +1,447 @@ +//! A render encoder's last direct draw, kept so that the next draw of the same call with the same +//! arguments, which no call of the encoder came between, records its Vulkan draw alone +//! (`WorkCounts::draws_as_before`). +//! +//! - **What is kept.** Of its last `draw_primitives` or `draw_indexed_primitives` call, the +//! encoder keeps ([`Kept`]) the call, what it assembled, its draw (the binding layer's, indices +//! and offsets included) and its index source; what it read of the state that changes with no +//! call of the encoder ([`Under`]); the command buffer it recorded into and the Vulkan draw +//! command it recorded; and what its other steps did that a draw again repeats (its per-draw +//! counts, its execution record, whether its instance keeps it for recording again). +//! - **Only a plain draw is kept.** One that recorded one Vulkan draw into the current instance as +//! it stood, through a pipeline made ahead, needing nothing before or around it: no split, +//! stand-in, shadow, snapshot, copy, index bounds or rewrite pass, mesh or tessellation work, rate +//! map, color groups, extended-range color, set 1 or handle table, root table or push hole, +//! barrier in its instance, and no write among its uses, which each change what the next draw +//! meets or are work of the draw's own. Its uses are noted as the next draw would note them +//! (`NotedApart`). A draw that met a notice its device announces or refuses at every occurrence +//! (`EachWatch`) keeps nothing: its next draw must meet it again. +//! - **Forgotten at every call.** Every call of the encoder but the two direct draws forgets it as +//! it logs itself (`RenderLowering::log`, which every call does: at the call, on the device's +//! lowering thread, and encoded again), refused or not, whatever it changes. So the encoder's +//! state a draw resolves from is the kept draw's, but for what the kept draw itself left and what +//! changes with no call of the encoder: the latter is [`Under`], compared at each draw: the count +//! of no-copy buffers' moves (a bound buffer's binding, a detach), the residency's generation +//! once the draw made the heaps' new textures resident, whether the device has buffers over host +//! pages and its host aliases' version, and the encoder's parts and held images (what noting +//! reads, `noted_apart.rs`), with the command buffer the current instance records into. +//! - **What a kept draw left holds for the next.** Each of its steps adds to what the encoder +//! holds, and adding the same again changes nothing: its drawn area and coverage (rectangles +//! and boxes, `clear_reach::DrawnArea`, `linear_attachment::Coverage`), the pass's reads +//! (`PassStartReads::add`, which takes an equal range once) and the instance's gathered uses +//! (`InstanceShadows::add`, which skips the uses of the last draw), its writes (none), its noted +//! uses, its retains (each a hold of an object held already: `LastRetained`, a table's stamp, +//! an index buffer the kept draw held), the shape memo's entries and the bind state (found as +//! the kept draw left them), and the pass's first instance, which the kept draw decided +//! (`render/inline_first.rs`). A notice the kept draw met is announced once per device, which it +//! was. Its Vulkan state commands are those its instance's record holds (`render/bound.rs`): a +//! draw again records no state command. +//! - **What a draw again does.** It logs itself, makes resident the heaps' new textures, notes its +//! uses' reads of fresh textures (`fresh_unwritten.rs`), records the kept Vulkan draw command +//! into the kept command buffer, keeps itself for recording again where its instance keeps draws +//! (`render/reroute.rs`), adds its execution record where the device keeps them, and counts +//! itself drawn. It takes no lock and changes no count other threads share: its counts, and +//! those the kept draw counted per draw, are the encoder's until its next call or its end +//! ([`Counted`]). +//! - **Checked in builds with debug assertions.** The first draw again of a kept draw, and every +//! second one after it, takes every step instead, and checks that it announced nothing, recorded +//! no state command, kept an equal draw, retained only its index buffer again, and left the +//! encoder's drawn area, coverage, reads, gathered uses, noted uses and instance as they were. + +use ash::vk; +use metal2vulkan::bind::{BindShape, DrawCall}; +use std::sync::Arc; +use std::time::Duration; + +use super::{Assembly, DrawBuffers, RenderLowering}; +use crate::degradation::EachWatch; +use crate::draw_source::DrawSource; +use crate::execution::{ExecutedPipeline, Execution}; +use crate::noted_apart::NotedInto; +use crate::resource::ResourceKey; +use crate::tracker::{Use, UseRange}; +use metal2vulkan::metal::RenderStages; + +/// The encoder's last direct draw, where it is kept, and the counts of its draws again (the +/// module docs). +#[derive(Default)] +pub(super) struct DrawAgain { + kept: Option, + counted: Counted, + /// Draws again since the draw was kept: in builds with debug assertions, the first and every + /// second one after it take every step instead (the module docs). + #[cfg(debug_assertions)] + hits: u64, +} + +/// The counts of an encoder's draws again not yet added to its device's +/// (`WorkCounts::draws_as_before`, and what the kept draws counted per draw). +#[derive(Default)] +struct Counted { + draws: u64, + pushing_set_zero: u64, + last_vertex: u64, +} + +/// What a kept draw was, what it read, and what a draw again repeats of it (the module docs). +#[derive(PartialEq)] +pub(super) struct Kept { + pub(super) call: &'static str, + pub(super) assembly: Assembly, + pub(super) draw: DrawCall, + pub(super) index: Option, + pub(super) under: Under, + pub(super) command_buffer: vk::CommandBuffer, + pub(super) command: metal2vulkan::vk::DrawCommand, + /// Whether its instance may record it again (`RenderLowering::keep_draw`). + pub(super) again: bool, + /// What it counted per draw beyond its own draw: a push of set 0, a `VkPipeline` of the last + /// provoking vertex. + pub(super) pushes_set_zero: bool, + pub(super) last_vertex: bool, + /// Whether one of its uses reads an image other than as an attachment: its noting looks + /// for fresh textures among them (`EncoderCore::note_again`). + pub(super) reads_images: bool, + /// Its execution record's parts, where the device keeps records. + pub(super) execution: Option, + /// What `RenderLowering::draw` takes of it: the stages whose functions read texture handles + /// from memory, and whether it rasterizes and writes depth. + pub(super) reads: RenderStages, + pub(super) rasterizes: bool, + pub(super) depth_writes: bool, + /// Whether it recorded no state command (`Recorded::draw_alone`), as a draw again does. + pub(super) draw_alone: bool, +} + +/// An index source as a kept draw read it in place: the Metal buffer, by key, and offset, and +/// the `VkBuffer` and offset it read there (`DrawSource`). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct KeptIndex { + key: ResourceKey, + offset: u64, + raw: vk::Buffer, + at: u64, +} + +impl KeptIndex { + /// `source`'s, where it is read in place; `None` for a copy, which each draw takes. + pub(super) fn of(source: &DrawSource<'_>) -> Option { + source.in_place().then(|| KeptIndex { + key: source.buffer.identity().key, + offset: source.offset, + raw: source.raw, + at: source.at, + }) + } +} + +/// An execution record's parts (`Execution::new`): the same where its pipeline and shape are +/// the same objects. +pub(super) struct KeptExecution { + pub(super) pipeline: ExecutedPipeline, + pub(super) shape: Arc, + pub(super) created: Vec, +} + +impl PartialEq for KeptExecution { + fn eq(&self, other: &KeptExecution) -> bool { + let pipeline = match (&self.pipeline, &other.pipeline) { + (ExecutedPipeline::Render(a), ExecutedPipeline::Render(b)) => Arc::ptr_eq(a, b), + (ExecutedPipeline::Compute(a), ExecutedPipeline::Compute(b)) => Arc::ptr_eq(a, b), + _ => false, + }; + pipeline && Arc::ptr_eq(&self.shape, &other.shape) && self.created == other.created + } +} + +/// What a kept draw read that changes with no call of the encoder (the module docs): the no-copy +/// buffers' moves, the residency's generation, and what its uses were noted into. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct Under { + moved: u64, + residency: u64, + into: NotedInto, +} + +/// Whether a draw is its encoder's kept draw again ([`RenderLowering::draw_again`]). +pub(super) enum Again { + /// It is, and was recorded. + Drawn, + /// It is, and takes every step instead, which [`Checked`] checks (builds with debug + /// assertions). + #[cfg(debug_assertions)] + Check(Box), + /// It is not. + No, +} + +impl DrawAgain { + /// Keep `kept`, the draw just recorded. + pub(super) fn keep(&mut self, kept: Kept) { + self.kept = Some(kept); + #[cfg(debug_assertions)] + { + self.hits = 0; + } + } +} + +/// Whether `used` reads an image other than as an attachment: what noting a draw's reads of +/// fresh textures looks at (`EncoderCore::observe_fresh`). +pub(super) fn reads_image(used: &Use) -> bool { + let attachment = + vk::AccessFlags2::COLOR_ATTACHMENT_READ | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_READ; + matches!(used.range, UseRange::Image { .. }) && !(used.read.access & !attachment).is_empty() +} + +impl RenderLowering { + /// What a kept draw reads that changes with no call of the encoder (the module docs). + pub(super) fn under(&self) -> Under { + Under { + moved: crate::buffer::host_cells_moved(), + residency: self.residency.generation(), + into: self.core.noted_into(), + } + } + + /// Forget the kept draw (a call came, another draw, or the encoder's end), adding its draws + /// again's counts to the device's (the module docs). + pub(super) fn forget_again(&mut self) { + self.again.kept = None; + let Counted { + draws, + pushing_set_zero, + last_vertex, + } = self.again.counted; + if draws > 0 { + let counts = &self.core.device().shared().counts; + counts.draws_drawn_again(draws, pushing_set_zero, last_vertex); + self.again.counted = Counted::default(); + } + } + + /// Whether the draw of `call` assembling `assembly`, `draw` with `buffers`, is the kept draw + /// again (the module docs): then, but where it is checked, it is recorded. Call it once the + /// draw made the heaps' new textures resident. + pub(super) fn draw_again( + &mut self, + call: &'static str, + assembly: Assembly, + draw: &DrawCall, + buffers: &DrawBuffers<'_>, + ) -> Again { + let Some(kept) = self.again.kept.as_ref() else { + return Again::No; + }; + let index = buffers.index.as_ref().map(KeptIndex::of); + let same = buffers.indirect.is_none() + && buffers.patch_indices.is_none() + && buffers.control_point_indices.is_none() + && kept.call == call + && kept.assembly == assembly + && kept.draw == *draw + && kept.index == index.flatten() + && index.is_none_or(|index| index.is_some()) + && kept.command_buffer == self.current.draws + && kept.under == self.under(); + if !same { + return Again::No; + } + #[cfg(debug_assertions)] + { + let hits = self.again.hits; + self.again.hits += 1; + if hits.is_multiple_of(2) { + return Again::Check(Box::new(Checked::of(self))); + } + } + let counted = &mut self.again.counted; + counted.draws += 1; + counted.pushing_set_zero += u64::from(kept.pushes_set_zero); + counted.last_vertex += u64::from(kept.last_vertex); + // Its noting: its reads of fresh textures, where any texture is fresh, and what the + // encoder made resident since (nothing: no call came). + match kept.reads_images && self.core.observes_fresh() { + true => self.core.note_again(super::lock(&self.live).noted.uses()), + false => self.core.note_again(&[]), + } + // SAFETY: the kept draw recorded this command into this command buffer, which records + // the same render pass instance, with every handle it binds live until the command + // buffer completes (retained as the kept draw recorded); the command buffer's state is + // the kept draw's, as no call came and no draw recorded since (`render/bound.rs`). + unsafe { + let raw = self.core.device().shared().vk(); + super::record_draw_command(raw, kept.command_buffer, kept.command, None, None); + } + if let Some(execution) = &kept.execution { + let pipeline = execution.pipeline.clone(); + let shape = Arc::clone(&execution.shape); + let created = execution.created.clone(); + self.core + .executed(|| Execution::new(pipeline, shape, created)); + } + let (again, reads) = (kept.again, kept.reads); + let (rasterizes, depth_writes) = (kept.rasterizes, kept.depth_writes); + self.keep_draw(again, (call, assembly, *draw), buffers.index.as_ref()); + self.draw_calls += 1; + self.command_encoded(reads); + self.called = true; + self.drew |= rasterizes; + self.drew_depth_writes |= depth_writes; + Again::Drawn + } + + /// Finish keeping the draw just taken step by step: forget it where `watch` met a notice the + /// device announces or refuses at every occurrence, else note what `RenderLowering::draw` + /// takes of it (`reads`, and whether it rasterized and wrote depth); and where it was + /// `checked`, a kept draw again that took every step, check it (the module docs). + pub(super) fn kept_again( + &mut self, + watch: &EachWatch, + (reads, rasterizes, depth_writes): (RenderStages, bool, bool), + checked: Option>, + ) { + if watch.met() { + self.forget_again(); + } + if let Some(kept) = self.again.kept.as_mut() { + kept.reads = reads; + kept.rasterizes = rasterizes; + kept.depth_writes = depth_writes; + } + #[cfg(debug_assertions)] + if let Some(checked) = checked { + checked.check(self); + } + #[cfg(not(debug_assertions))] + let _: Option> = checked; + } +} + +/// What a draw again that takes every step checks of it (the module docs): the kept draw, what +/// the encoder held before the draw, and the messages delivered on its thread by then. +#[cfg(debug_assertions)] +pub(super) struct Checked { + kept: Kept, + hits: u64, + held: Held, + announced: u64, +} + +/// No check in builds without debug assertions: no draw again takes every step. +#[cfg(not(debug_assertions))] +pub(super) enum Checked {} + +/// What a draw again leaves as it was (the module docs). +#[cfg(debug_assertions)] +struct Held { + drawn: crate::clear_reach::DrawnArea, + instance_drawn: crate::clear_reach::DrawnArea, + coverage: crate::linear_attachment::Coverage, + pass_start: super::pass_start_reads::HeldReads, + gathered: super::shadows::HeldGathered, + noted: crate::noted_apart::NotedApart, + instance: (bool, bool, bool, usize, usize, super::InterlockedStorage), + holds: (usize, usize), + pass: ( + std::collections::BTreeSet, + std::collections::BTreeSet, + bool, + ), +} + +#[cfg(debug_assertions)] +impl Held { + fn of(encoder: &RenderLowering) -> Held { + let current = &encoder.current; + Held { + drawn: encoder.drawn.clone(), + instance_drawn: current.drawn.clone(), + coverage: encoder.coverage.clone(), + pass_start: encoder.pass_start.held(), + gathered: current.shadows.gathered(), + noted: super::lock(&encoder.live).noted.clone(), + instance: ( + current.tile_memory, + current.barriers, + current.imageblock, + current.pieces.len(), + current.before.len(), + current.interlocked_writes, + ), + holds: encoder.core.retained_holds(), + pass: ( + encoder.inputs_read.clone(), + encoder.extended_written.clone(), + encoder.reaches_unnamed, + ), + } + } + + /// Assert that `self`, held after a draw again took every step, is `before`, but for its + /// holds: one more index buffer's where it reads one (`index`), and one more execution + /// record where the device keeps them (`executed`). + fn assert_as(&self, before: &Held, (index, executed): (bool, bool)) { + let parts = [ + ("drawn area", self.drawn == before.drawn), + ( + "instance's drawn area", + self.instance_drawn == before.instance_drawn, + ), + ("coverage", self.coverage == before.coverage), + ("pass's reads", self.pass_start == before.pass_start), + ("gathered uses", self.gathered == before.gathered), + ("noted uses", self.noted == before.noted), + ("instance", self.instance == before.instance), + ("pass", self.pass == before.pass), + ]; + for (part, same) in parts { + assert!(same, "a draw again changed its encoder's {part}"); + } + let holds = ( + before.holds.0 + usize::from(index), + before.holds.1 + usize::from(executed), + ); + assert_eq!( + self.holds, holds, + "a draw again held what its kept draw did not" + ); + } +} + +#[cfg(debug_assertions)] +impl Checked { + fn of(encoder: &mut RenderLowering) -> Checked { + let kept = encoder.again.kept.take(); + let kept = kept.unwrap_or_else(|| unreachable!("a draw again without its kept draw")); + Checked { + kept, + hits: encoder.again.hits, + held: Held::of(encoder), + announced: crate::degradation::announced_here(), + } + } + + /// Check the draw that took every step against the kept one (the module docs). + fn check(self, encoder: &mut RenderLowering) { + let Checked { + kept, + hits, + held, + announced, + } = self; + assert_eq!( + crate::degradation::announced_here(), + announced, + "a draw again announced a notice" + ); + let executed = kept.execution.is_some(); + Held::of(encoder).assert_as(&held, (kept.index.is_some(), executed)); + let again = encoder.again.kept.as_mut(); + let again = again.unwrap_or_else(|| panic!("a draw again kept no draw")); + assert!(again.draw_alone, "a draw again recorded a state command"); + again.draw_alone = kept.draw_alone; + assert!(*again == kept, "a draw again kept another draw"); + encoder.again.hits = hits; + } +} diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index dbab168eb..25c423a14 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -2445,6 +2445,7 @@ impl RenderExecution { heaps_noted: None, inline: super::inline_first::Inline::Never, held_bound: Default::default(), + again: Default::default(), // No pass of several color groups executes render commands // (`render/color_groups.rs`). grouped: None, diff --git a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs index d29799526..4183dbb07 100644 --- a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs +++ b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs @@ -95,6 +95,10 @@ impl Written { } }; let ranges = &mut self.lists[at].1; + // A range held already adds nothing: a pass's draws mostly name the same bytes again. + if ranges.contains(range) { + return; + } ranges.push(range.clone()); if ranges.len() > RANGES_PER_KEY { let start = ranges.iter().map(|r| r.start).min().unwrap_or(0); @@ -157,6 +161,12 @@ pub(super) struct PassStartReads { copies: Vec, } +/// What a pass's reads note ([`PassStartReads::held`]): its lists' keys and ranges, and its +/// copies' count. +#[cfg(debug_assertions)] +#[derive(PartialEq)] +pub(super) struct HeldReads([Vec<(ResourceKey, Vec>)>; 3], usize); + /// The tables a draw's stages before its fragments read in place of the encoder's: each with the /// copies of bytes the pass's fragment stages wrote, `None` where the stage reads the encoder's. #[derive(Default)] @@ -177,6 +187,11 @@ impl PassStartTables { }; table.unwrap_or(encoder) } + + /// Whether every stage reads the encoder's table: no copy replaces a buffer of any. + pub(super) fn reads_encoders(&self) -> bool { + self.vertex.is_none() && self.object.is_none() && self.mesh.is_none() + } } impl PassStartReads { @@ -201,6 +216,17 @@ impl PassStartReads { } } + /// What it notes, without its copies' buffers (builds with debug assertions: + /// `render/draw_again.rs`'s check). + #[cfg(debug_assertions)] + pub(super) fn held(&self) -> HeldReads { + let held = |written: &Written| written.lists[..written.held].to_vec(); + HeldReads( + [&self.fragment, &self.fragment_reads, &self.other].map(held), + self.copies.len(), + ) + } + /// The entries its lists and copies hold room for. pub(super) fn room(&self) -> usize { let maps = [&self.fragment, &self.fragment_reads, &self.other]; diff --git a/crates/metal2vulkan-runtime/src/render/replay.rs b/crates/metal2vulkan-runtime/src/render/replay.rs index a31373ce5..dafbf251c 100644 --- a/crates/metal2vulkan-runtime/src/render/replay.rs +++ b/crates/metal2vulkan-runtime/src/render/replay.rs @@ -647,8 +647,16 @@ pub(crate) struct DrawIndexedPatchesIndirect { impl RenderLowering { /// Log the call `call` makes of the log, before it runs, where the encoder logs (the module - /// docs). + /// docs). Every call but a direct draw logs itself so, which forgets the encoder's kept draw, + /// whatever the call changes (`render/draw_again.rs`). pub(crate) fn log(&mut self, call: impl FnOnce(&mut CallLog) -> RenderCall) { + self.forget_again(); + self.log_draw(call); + } + + /// [`log`](Self::log) a `draw_primitives` call, which keeps the encoder's kept draw: a draw + /// is drawn again as it was kept, or keeps itself (`render/draw_again.rs`). + pub(crate) fn log_draw(&mut self, call: impl FnOnce(&mut CallLog) -> RenderCall) { if let Some(log) = &mut self.log { let call = call(&mut log.calls); let extra = call.extra(); @@ -676,7 +684,8 @@ impl RenderLowering { } /// Log a `draw_indexed_primitives` call, whose arguments `draw` makes of the log, before it - /// runs, where the encoder logs: its arguments go into the log's list of them. + /// runs, where the encoder logs: its arguments go into the log's list of them. It keeps the + /// encoder's kept draw, as [`log_draw`](Self::log_draw) does. pub(crate) fn log_indexed( &mut self, draw: impl FnOnce(&mut CallLog) -> DrawIndexed, diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 5a71f3f3a..4ff433887 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -209,7 +209,29 @@ fn insert(ranges: &mut Vec>, mut range: Range) { } } +/// What an instance's draws gathered ([`InstanceShadows::gathered`]): its shadows' count, its +/// buffers' ranges, its images' and the last draw's uses. +#[cfg(debug_assertions)] +#[derive(PartialEq)] +pub(super) struct HeldGathered( + usize, + Vec<((ResourceKey, bool), Vec>)>, + Vec<((ResourceKey, bool), UseRange)>, + Vec>, +); + impl InstanceShadows { + /// What its draws gathered (builds with debug assertions: `render/draw_again.rs`'s check). + #[cfg(debug_assertions)] + pub(super) fn gathered(&self) -> HeldGathered { + HeldGathered( + self.shadows.len(), + self.bytes[..self.held].to_vec(), + self.images.clone(), + self.last.clone(), + ) + } + /// Whether the draws use no shadowed texture. pub(super) fn is_empty(&self) -> bool { self.shadows.is_empty() diff --git a/crates/metal2vulkan-runtime/src/retained.rs b/crates/metal2vulkan-runtime/src/retained.rs index a7e4ba778..a7db44009 100644 --- a/crates/metal2vulkan-runtime/src/retained.rs +++ b/crates/metal2vulkan-runtime/src/retained.rs @@ -85,6 +85,12 @@ impl Retained { &mut holds.0 } + /// How many holds it keeps (builds with debug assertions: `render/draw_again.rs`'s check). + #[cfg(debug_assertions)] + pub(super) fn len(&self) -> usize { + self.0.as_ref().map_or(0, |holds| holds.0.len()) + } + /// The holds as one entry of a command buffer's (the module docs), or none where there are /// none. pub(super) fn into_entry(self) -> Option> { diff --git a/crates/metal2vulkan-runtime/src/tests/draw_again.rs b/crates/metal2vulkan-runtime/src/tests/draw_again.rs new file mode 100644 index 000000000..8ecab24ed --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/draw_again.rs @@ -0,0 +1,499 @@ +//! A render encoder's draw of its last direct draw again (`render/draw_again.rs`): a draw of the +//! same call with the same arguments, which no call of the encoder came between, records its +//! Vulkan draw command alone (`WorkCounts::draws_as_before`), with the same commands, barriers +//! and pixels as the same draws with a call between each that changes nothing; and only then: not +//! a draw of other arguments, an indirect draw, a draw that writes memory, a draw after a no-copy +//! buffer moved (its binding may read elsewhere), nor a draw that meets a notice its device +//! announces at every occurrence, which announces it at every draw. In builds with debug +//! assertions, every second draw again takes every step instead, and checks that it changed +//! nothing the draw again leaves (the module's check), so these tests run that check too. +//! +//! 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 fixtures +//! `validation/fixtures/public/engine/tob_renders.ll` and `engine/cfb_depth_never.ll` +//! (`llvm-as`). + +use super::blit_holds::{until, Scratch, WAIT}; +use super::encoder_holds::{bytes_of, library, pass, words_of}; +use super::rebind_behind_a_wait::{Page, BYTES}; +use crate::{ + BlitOption, Buffer, CommandBufferStatus, Degradation, DegradeNotice, Device, DeviceKind, + DeviceOptions, Error, MessageSink, Origin, PipelineOptions, RenderCommandEncoder, + RenderPipelineState, ResourceOptions, ShaderCacheOptions, Size, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{BlendFactor, IndexType, PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +/// The draws an encoder of a test draws. +const DRAWS: u64 = 9; + +/// The side of the target. +const SIDE: u64 = 16; + +/// The notices a device announced. +type Heard = Arc>>; + +/// A device of the kind the cfg selects that announces the kinds of `each` at every occurrence, +/// its notices into `heard`. +fn device(cache: &Path, each: &[Degradation], heard: &Heard) -> Device { + let heard = Arc::clone(heard); + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + messages: Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + heard.lock().unwrap().push(notice.clone()); + } + })), + announce_each: each.iter().copied().collect(), + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// The draws again of a pass of [`DRAWS`] of the same draw: all but its first two, the first +/// beginning the pass's instance (which keeps no draw), the second kept. +const HITS: u64 = DRAWS - 2; + +/// How many of the draws again `hits` of a run recorded their Vulkan draw alone: every second one +/// from the first takes every step in a build with debug assertions (the module docs). +fn drawn_alone(hits: u64) -> u64 { + match cfg!(debug_assertions) { + true => hits / 2, + false => hits, + } +} + +/// The state that draws a rectangle (`tob_rect`, `tob_solid`) into `RGBA8Unorm`, adding its color +/// to the target's, so that a target shows how many draws ran. +fn adding_state(device: &Device) -> RenderPipelineState { + state(device, "engine/tob_renders.ll", ("tob_rect", "tob_solid")) +} + +/// The state of the fixture at `path`'s `vertex` and `fragment` functions that draws into +/// `RGBA8Unorm`, adding its color to the target's. +fn state(device: &Device, path: &str, (vertex, fragment): (&str, &str)) -> RenderPipelineState { + let library = library(device, path); + let function = |name| { + let function = library.new_function_with_name(name).unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let mut descriptor = RenderPipelineDescriptor::new(function(vertex)); + descriptor.fragment = Some(function(fragment)); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm); + color.blending_enabled = true; + color.destination_rgb_blend_factor = BlendFactor::One; + color.destination_alpha_blend_factor = BlendFactor::One; + descriptor.color_attachments[0] = Some(color); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// What a run recorded and drew: its commands recorded by kind, the target's words, and the +/// device's counts after it, with the counts' change over it. +struct Ran { + commands: BTreeMap, + words: Vec, + before: WorkCounts, + after: WorkCounts, +} + +impl Ran { + /// How the count `of` changed over the run. + fn counted(&self, of: impl Fn(&WorkCounts) -> u64) -> u64 { + of(&self.after) - of(&self.before) + } +} + +/// The device's commands recorded so far, by kind. +fn commands(device: &Device) -> BTreeMap { + let recorded = format!("{:?}", device.work_counts().commands_recorded); + let fields = recorded + .trim_start_matches("CommandsRecorded {") + .trim_end_matches('}'); + fields + .split(',') + .filter_map(|field| { + let (name, count) = field.split_once(':')?; + Some((name.trim().to_owned(), count.trim().parse().unwrap())) + }) + .collect() +} + +/// Encode `encode` in one pass into a new cleared `RGBA8Unorm` target, commit and wait: what it +/// recorded and drew. +fn run(device: &Device, encode: impl Fn(&mut RenderCommandEncoder)) -> Ran { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + let target = device.new_texture(&descriptor).unwrap(); + let back = device + .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let (before, recorded) = (device.work_counts(), commands(device)); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + let after = device.work_counts(); + let commands = commands(device) + .into_iter() + .map(|(name, count)| { + let before = recorded.get(&name).copied().unwrap_or(0); + (name, count - before) + }) + .collect(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &back, + 0, + SIDE * 4, + SIDE * SIDE * 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + Ran { + commands, + words: words_of(&back), + before, + after, + } +} + +/// Run `encode` on `device` until a run draws no key's residual form and the device's pool is +/// idle: every later draw finds its key's own pipeline made, as a draw that is kept to draw again +/// does (a draw recorded against a making, or of a residual form, keeps nothing). +fn warm(device: &Device, encode: impl Fn(&mut RenderCommandEncoder)) { + until("every key's own pipeline made", || { + let residual = device.work_counts().residual_form_draws; + run(device, &encode); + device.work_counts().residual_form_draws == residual + }); + until("the pipeline pool idle", || { + device.work_counts().pipeline_pool_busy == 0 + }); +} + +/// Set `state`, the rectangle over the whole target and its color, `1 / 64` in each channel. +fn set_rectangle(encoder: &mut RenderCommandEncoder, state: &RenderPipelineState) { + encoder.set_render_pipeline_state(state).unwrap(); + let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + let color = bytes_of(&[1.0f32 / 64.0; 4], f32::to_le_bytes); + encoder.set_fragment_bytes(&color, 0).unwrap(); +} + +/// The rectangle's draw: two triangles. +fn rectangle(encoder: &mut RenderCommandEncoder) { + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0); + assert_eq!(drawn, Ok(())); +} + +/// [`DRAWS`] draws of the rectangle, with `between` called before each but the first. +fn rectangles( + encoder: &mut RenderCommandEncoder, + state: &RenderPipelineState, + between: impl Fn(&mut RenderCommandEncoder), +) { + set_rectangle(encoder, state); + for at in 0..DRAWS { + if at > 0 { + between(encoder); + } + rectangle(encoder); + } +} + +/// Draws of the same rectangle one after another record their Vulkan draws alone, but the first: +/// the same commands of every kind, the same barriers, state commands and noted uses, and the +/// same pixels, as the same draws with a call between each that changes nothing for them +/// (`set_blend_color` of the color the encoder holds), each of which takes every step. +#[test] +fn draws_again_record_what_draws_after_calls_record() { + let scratch = Scratch::new("draw-again"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + let same_color = + |encoder: &mut RenderCommandEncoder| encoder.set_blend_color(0.0, 0.0, 0.0, 0.0); + warm(&device, |encoder| rectangles(encoder, &state, same_color)); + let heard_in = |ran: &dyn Fn() -> Ran| { + heard.lock().unwrap().clear(); + let ran = ran(); + let kinds: Vec = (heard.lock().unwrap().iter()) + .map(|notice| notice.degradation) + .collect(); + (ran, kinds) + }; + let (again, again_heard) = + heard_in(&|| run(&device, |encoder| rectangles(encoder, &state, |_| {}))); + let (after_calls, after_calls_heard) = + heard_in(&|| run(&device, |encoder| rectangles(encoder, &state, same_color))); + assert_eq!(again_heard, after_calls_heard, "the notices of the draws"); + let as_before = |counts: &WorkCounts| counts.draws_as_before; + assert_eq!(again.counted(as_before), drawn_alone(HITS)); + assert_eq!(after_calls.counted(as_before), 0); + assert_eq!(again.commands, after_calls.commands); + assert_eq!(again.commands["cmd_draw"], DRAWS); + assert_eq!(again.words, after_calls.words, "the pixels of the draws"); + // Each of the draws added its color: the target holds more than one draw's. + let one = run(&device, |encoder| { + set_rectangle(encoder, &state); + rectangle(encoder); + }); + assert_ne!(again.words, one.words, "the draws added one draw's color"); + // Their commands, barriers among them, are the same (above), and so are their counts of + // state commands, uses noted as before and pushes of set 0. + let counts: [(&str, fn(&WorkCounts) -> u64); 3] = [ + ("draw_states_recorded", |counts| counts.draw_states_recorded), + ("commands_noted_as_before", |counts| { + counts.commands_noted_as_before + }), + ("draws_pushing_set_zero", |counts| { + counts.draws_pushing_set_zero + }), + ]; + for (name, count) in counts { + assert_eq!(again.counted(count), after_calls.counted(count), "{name}"); + } + // Each of the draws but the first noted its uses as before, the draws again among them. + assert_eq!(again.counted(counts[1].1), DRAWS - 1); +} + +/// Indexed draws of the same indices from the same offset draw again too; at another offset they +/// do not. +#[test] +fn indexed_draws_from_the_same_indices_draw_again() { + let scratch = Scratch::new("draw-again-indexed"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + let indices = bytes_of(&[0u16, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5], u16::to_le_bytes); + let index = device + .new_buffer_with_bytes(&indices, ResourceOptions::shared()) + .unwrap(); + let indexed = |encoder: &mut RenderCommandEncoder, offset: u64| { + let drawn = encoder.draw_indexed_primitives( + PrimitiveType::Triangle, + 6, + IndexType::UInt16, + &index, + offset, + 1, + 0, + 0, + ); + assert_eq!(drawn, Ok(())); + }; + let draws = |encoder: &mut RenderCommandEncoder, offsets: &dyn Fn(u64) -> u64| { + set_rectangle(encoder, &state); + for at in 0..DRAWS { + indexed(encoder, offsets(at)); + } + }; + warm(&device, |encoder| draws(encoder, &|_| 0)); + let same = run(&device, |encoder| draws(encoder, &|_| 0)); + let as_before = |counts: &WorkCounts| counts.draws_as_before; + assert_eq!(same.counted(as_before), drawn_alone(HITS)); + assert_eq!(same.commands["cmd_draw_indexed"], DRAWS); + let moving = run(&device, |encoder| draws(encoder, &|at| (at % 2) * 12)); + assert_eq!(moving.counted(as_before), 0); + assert_eq!(same.words, moving.words, "the pixels of the draws"); +} + +/// No draw draws again but the same direct draw after the same: not a draw of other arguments, +/// an indirect draw, nor a draw that writes memory (`cfb_dn_count`, which counts its fragments in +/// a buffer's word 0); each counts what it drew, every draw's. +#[test] +fn other_draws_take_every_step() { + let scratch = Scratch::new("draw-again-others"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + let as_before = |counts: &WorkCounts| counts.draws_as_before; + // Another base instance at each draw, which the functions do not read. + let others = |encoder: &mut RenderCommandEncoder| { + set_rectangle(encoder, &state); + for at in 0..DRAWS as u32 { + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, at % 2); + assert_eq!(drawn, Ok(())); + } + }; + warm(&device, others); + assert_eq!(run(&device, others).counted(as_before), 0); + // Indirect draws of six vertices, one instance. + let arguments = bytes_of(&[6u32, 1, 0, 0], u32::to_le_bytes); + let indirect = device + .new_buffer_with_bytes(&arguments, ResourceOptions::shared()) + .unwrap(); + let indirect_draws = |encoder: &mut RenderCommandEncoder| { + set_rectangle(encoder, &state); + for _ in 0..DRAWS { + let drawn = encoder.draw_primitives_indirect(PrimitiveType::Triangle, &indirect, 0); + assert_eq!(drawn, Ok(())); + } + }; + warm(&device, indirect_draws); + let ran = run(&device, indirect_draws); + assert_eq!(ran.counted(as_before), 0); + assert_eq!(ran.commands["cmd_draw_indirect"], DRAWS); + // Draws that count their fragments in a buffer: every fragment of every draw counted. + let counting = state_counting(&device); + let counter = device.new_buffer(4, ResourceOptions::shared()).unwrap(); + let counted = |encoder: &mut RenderCommandEncoder| { + encoder.set_render_pipeline_state(&counting).unwrap(); + encoder.set_fragment_buffer(Some(&counter), 0, 0).unwrap(); + for _ in 0..DRAWS { + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0); + assert_eq!(drawn, Ok(())); + } + }; + warm(&device, counted); + clear(&counter); + let ran = run(&device, counted); + assert_eq!(ran.counted(as_before), 0); + assert_eq!(words_of(&counter), [(DRAWS * SIDE * SIDE) as u32]); +} + +/// The state of `cfb_dn_full`, a triangle over the whole target, and `cfb_dn_count`, which counts +/// its invocations in word 0 of buffer 0, into `RGBA8Unorm`. +fn state_counting(device: &Device) -> RenderPipelineState { + state( + device, + "engine/cfb_depth_never.ll", + ("cfb_dn_full", "cfb_dn_count"), + ) +} + +/// Zero `buffer`, a host-visible buffer no command uses now. +fn clear(buffer: &Buffer) { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's `length` bytes, which no command buffer uses now. + unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, buffer.length() as usize) }; +} + +/// A draw after a no-copy buffer moved (a detach, a rebind), on any thread and whatever buffer, +/// takes every step: a binding of the buffer may read elsewhere. The draws after it draw again. +#[test] +fn a_draw_after_a_no_copy_buffer_moved_takes_every_step() { + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("draw-again-moved"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + // SAFETY: each page outlives every buffer over it (dropped after the device), and only the + // buffer's commands use it while it lives; no command uses the buffer. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let no_copy = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("DRAW-AGAIN: the device imports no host memory: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let plain = |encoder: &mut RenderCommandEncoder| rectangles(encoder, &state, |_| {}); + warm(&device, plain); + let as_before = |counts: &WorkCounts| counts.draws_as_before; + let reference = run(&device, plain); + assert_eq!(reference.counted(as_before), drawn_alone(HITS)); + // The buffer detached after the third draw, and over the second page again after the sixth. + let moving = run(&device, |encoder| { + set_rectangle(encoder, &state); + for at in 0..DRAWS { + match at { + 3 => assert_eq!(no_copy.detach_backing(), Ok(true)), + // SAFETY: as above. + 6 => { + unsafe { no_copy.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap() + } + _ => {} + } + rectangle(encoder); + } + }); + // Three runs of three draws: one draw again in the first (its first draw begins the pass's + // instance), two in each other. + assert_eq!( + moving.counted(as_before), + drawn_alone(1) + 2 * drawn_alone(2) + ); + assert_eq!(moving.commands, reference.commands); + assert_eq!(moving.words, reference.words, "the pixels of the draws"); +} + +/// A draw that meets a notice its device announces at every occurrence (`UnsizedPoints`: points +/// of a vertex function that writes no point size) takes every step at every draw, and announces +/// it at each; on a device that announces it once, the draws after the first draw again. +#[test] +fn a_notice_announced_at_each_occurrence_is_announced_at_every_draw() { + fn points(state: &RenderPipelineState) -> impl Fn(&mut RenderCommandEncoder) + '_ { + move |encoder| { + set_rectangle(encoder, state); + for _ in 0..DRAWS { + let drawn = encoder.draw_primitives(PrimitiveType::Point, 0, 4, 1, 0); + assert_eq!(drawn, Ok(())); + } + } + } + let as_before = |counts: &WorkCounts| counts.draws_as_before; + for each in [false, true] { + let scratch = Scratch::new("draw-again-notices"); + let heard = Heard::default(); + let kinds = match each { + true => &[Degradation::UnsizedPoints][..], + false => &[], + }; + let device = device(&scratch.0, kinds, &heard); + let state = adding_state(&device); + warm(&device, points(&state)); + heard.lock().unwrap().clear(); + let ran = run(&device, points(&state)); + let announced = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::UnsizedPoints) + .count() as u64; + match each { + true => { + assert_eq!(announced, DRAWS); + assert_eq!(ran.counted(as_before), 0); + } + false => { + assert_eq!(announced, 0, "announced in the warm runs"); + assert_eq!(ran.counted(as_before), drawn_alone(HITS)); + } + } + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs b/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs index cc787801f..2198635b2 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw_shape_notices.rs @@ -2,7 +2,8 @@ //! announces at every occurrence (`DeviceOptions::announce_each`): a draw whose shape's derivation //! 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 +//! announces at each (`WorkCounts::draw_shapes_reused`, or `draws_as_before` for a draw of the +//! encoder's last draw again, which takes that draw's), as a device that announces every kind //! once does. A draw after a new scissor rectangle reuses its shape too, through its own scissor //! (`render_state::ScissorRects`). An encoder's first draw takes the shape an earlier encoder's //! draw of its drawing state derived from the same values (`WorkCounts::draw_shapes_carried`), so @@ -141,7 +142,8 @@ struct Draws<'a> { impl Draws<'_> { /// Encode the draws in one pass into a new `RGBA8Unorm` target, commit and wait: the draws - /// that reused their shapes. + /// that reused their shapes, each draw of the encoder's last draw again among them, which + /// records as the draw it repeats, of that draw's shape (`render/draw_again.rs`). fn run(&self, device: &Device) -> u64 { let target = target(device, PixelFormat::RGBA8Unorm); let mut descriptor: RenderPassDescriptor = pass(&target); @@ -154,11 +156,12 @@ impl Draws<'_> { } let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); - let reused = device.work_counts().draw_shapes_reused; + let reused = |counts: crate::WorkCounts| counts.draw_shapes_reused + counts.draws_as_before; + let before = reused(device.work_counts()); let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); self.encode(&mut encoder); encoder.end_encoding().unwrap(); - let reused = device.work_counts().draw_shapes_reused - reused; + let reused = reused(device.work_counts()) - before; command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index a46b5de74..5155bbfbd 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -90,6 +90,8 @@ mod dirty_pages_device; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod dispatch_pending; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod draw_again; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod draw_shape_notices; mod driver_defects; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 27379d327..9d92969b6 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -267,6 +267,7 @@ pub(crate) struct Counters { set_zero_sets_found: AtomicU64, draw_shapes_reused: AtomicU64, draw_shapes_carried: AtomicU64, + draws_as_before: AtomicU64, host_holds_looked_up: AtomicU64, dispatches_settled_as_before: AtomicU64, dispatches_planned_as_before: AtomicU64, @@ -1859,6 +1860,23 @@ impl Counters { self.draw_shapes_carried.fetch_add(1, Ordering::Relaxed); } + /// `draws` draws a render encoder recorded as its last draw again (`render/draw_again.rs`), + /// of which `pushing_set_zero` were of a variant that pushes set 0 and `last_vertex` ran a + /// `VkPipeline` of the last provoking vertex: each a draw whose uses were noted already. + pub(crate) fn draws_drawn_again(&self, draws: u64, pushing_set_zero: u64, last_vertex: u64) { + self.draws_as_before.fetch_add(draws, Ordering::Relaxed); + self.commands_noted_as_before + .fetch_add(draws, Ordering::Relaxed); + if pushing_set_zero > 0 { + self.draws_pushing_set_zero + .fetch_add(pushing_set_zero, Ordering::Relaxed); + } + if last_vertex > 0 { + self.provoking_last_pipeline_draws + .fetch_add(last_vertex, Ordering::Relaxed); + } + } + /// An encoder's hold of a key its commands named first that looked the key up among the /// device's buffers over host pages (`rebind::HostedKeys`). pub(crate) fn host_hold_looked_up(&self) { @@ -4302,7 +4320,7 @@ pub struct WorkCounts { /// Draws and dispatches that bound the set 0 their encoder's last command allocated and wrote, /// rather than allocating and writing their own: those that write the same descriptors into a /// set of the same layout (`binding::LastSetZero`). Their recording binds no set where the set - /// is bound already. + /// is bound already. Not a draw drawn again (`draws_as_before`), which binds no set. pub set_zero_sets_reused: u64, /// Draws and dispatches that bound a set 0 an earlier command of their command buffer, in any /// of its encoders, allocated and wrote, rather than allocating and writing their own: those @@ -4322,7 +4340,8 @@ pub struct WorkCounts { /// shape by version or value, and the assembly, the pass's sample positions, 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`). + /// (`DeviceOptions::announce_each`). Not a draw drawn again (`draws_as_before`), which takes + /// nothing of the memo. pub draw_shapes_reused: u64, /// Render encoders' draws that found no shape in their encoder's memo and took their /// settings, with the draw state and `VkPipeline` an earlier draw of them found, from an @@ -4333,6 +4352,21 @@ pub struct WorkCounts { /// rate-mapped pass, nor of a shape whose derivation announces a notice the device announces /// at every occurrence. pub draw_shapes_carried: u64, + /// Render encoders' direct draws recorded as their encoder's last draw again, its Vulkan draw + /// command alone, rather than taking every step of a draw: a draw of the same call with the + /// same arguments (its index buffer read in place at the same offset), which no call of the + /// encoder came between, while no no-copy buffer moved, the encoder's residency kept its + /// generation, the device's host aliases kept their version and the encoder kept its parts + /// and held images, after a draw that recorded one Vulkan draw into the instance as it + /// stood, through a `VkPipeline` made ahead, with no barrier in its instance, no write among + /// its uses, no copy, shadow, snapshot, split, gather, index bounds or rewrite pass, mesh or + /// tessellation work, set 1, root table, rate map, color group or extended-range color, and + /// no notice the device announces at every occurrence (`render/draw_again.rs`). Each is + /// counted in `commands_noted_as_before`, `draws_pushing_set_zero` and + /// `provoking_last_pipeline_draws` as the draw it repeats was, and in no count of work it + /// does not take (`draw_shapes_reused`, `set_zero_sets_reused`, `draw_states_recorded`); all + /// are counted at the encoder's next call or its end. + pub draws_as_before: u64, /// Keys an encoder's commands named first, while the device has a buffer over host pages /// (`new_buffer_with_bytes_no_copy`), that were looked up among those buffers under the lock /// their command buffers' submissions take: the keys of such buffers, and the rare other key @@ -5580,6 +5614,7 @@ impl Device { set_zero_sets_found: counters.set_zero_sets_found.load(Ordering::Relaxed), draw_shapes_reused: counters.draw_shapes_reused.load(Ordering::Relaxed), draw_shapes_carried: counters.draw_shapes_carried.load(Ordering::Relaxed), + draws_as_before: counters.draws_as_before.load(Ordering::Relaxed), host_holds_looked_up: counters.host_holds_looked_up.load(Ordering::Relaxed), dispatches_settled_as_before: (counters.dispatches_settled_as_before) .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs index f1bc2ed57..a713227f8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs @@ -1244,8 +1244,10 @@ pub(super) fn on_device_both_ways(test: impl Fn(&Device)) { /// Draws of an unchanged state into one render pass instance record its state commands once: /// past the first, a draw records nothing, so no pipeline, descriptor set, push constant, buffer /// or dynamic state is set again: where the device binds set 0, each draw past the first binds -/// the set its last draw wrote, the same descriptors (`WorkCounts::set_zero_sets_reused`), and -/// where it pushes set 0 ([`pushes`]), every draw pushes it, its writes the same. The first draw records them all, and the target is the +/// the set its last draw wrote, the same descriptors (`WorkCounts::set_zero_sets_reused`), or +/// draws as its encoder's last draw again (`draws_as_before`), which binds what that draw bound; +/// and where it pushes set 0 ([`pushes`]), every draw pushes it, its writes the same, a draw +/// again as the draw it repeats (counted at the encoder's end). The first draw records them all, and the target is the /// texture's. Every draw takes its key's own pipeline, made beforehand ([`make`]), none the /// residual form, so no pipeline is bound again past the first draw. Both ways /// ([`on_device_both_ways`]). @@ -1265,10 +1267,12 @@ fn draws_of_an_unchanged_state_record_its_commands_once() { let later: Vec = (1..DRAWS) .map(|_| recorded_by(device, &mut encoder)) .collect(); + encoder.end_encoding().unwrap(); let after = device.work_counts(); let pushed = grew(&before, &after, |c| c.draws_pushing_set_zero); - let reused = grew(&before, &after, |c| c.set_zero_sets_reused); - encoder.end_encoding().unwrap(); + let reused = grew(&before, &after, |c| { + c.set_zero_sets_reused + c.draws_as_before + }); let residual = grew(&before, &after, |c| c.residual_form_draws); assert_eq!( residual, 0, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index a7b5e27f4..5a592adc2 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2592,6 +2592,7 @@ field metal2vulkan-runtime::WorkCounts.draw_shapes_found pub draw_shapes_found: field metal2vulkan-runtime::WorkCounts.draw_shapes_made pub draw_shapes_made: u64 field metal2vulkan-runtime::WorkCounts.draw_shapes_reused pub draw_shapes_reused: u64 field metal2vulkan-runtime::WorkCounts.draw_states_recorded pub draw_states_recorded: u64 +field metal2vulkan-runtime::WorkCounts.draws_as_before pub draws_as_before: u64 field metal2vulkan-runtime::WorkCounts.draws_dropped_still_making pub draws_dropped_still_making: u64 field metal2vulkan-runtime::WorkCounts.draws_dropped_unmade pub draws_dropped_unmade: u64 field metal2vulkan-runtime::WorkCounts.draws_pushing_set_zero pub draws_pushing_set_zero: u64