From e3f2c95dfe5ca39d83d3093b56709dd4b820fd3d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 23:07:01 -0800 Subject: [PATCH] Draw the kept draw again rebound: after buffer, offset or bytes binds, rewrite those slots alone A render encoder's kept draw (render/draw_again.rs) drawn again after calls that bound other buffers, offsets or inline bytes at vertex or fragment buffer slots now rebinds only those slots (render/draw_again/rebound.rs, WorkCounts::draws_rebound), where it took every step of a draw. - Translator: BindingPlan::rebind_draw_buffers_into(state, slots, commands) writes again, over the same draw's commands of a state of the same shape, only what the buffer slots decide: their descriptor ranges at their places, the SlotBindOffset, SlotGuestBase and pulled-stride push fields that read them, and their vertex buffers' offsets. Ok(false) for a device-address slot, an argument or root table, a per-bind stride's vertex binding, a mesh, patch or de-indexed draw, or a uniform view a written slot may alias. docs/API.md says so; api_signatures gains it and WorkCounts::draws_rebound. - Runtime: buffer and bytes binds keep the kept draw (log_keeping); the draw compares its tables' stamps with the kept draw's. On a difference, the tables' changes since (argument_table:: changed_since: buffer slots alone, at most 8) are brought into the kept bind state (refresh_changed), and the draw goes on only where its shape stays, its variant and plan then the bind state's kept settle (LiveBind::settles_kept). It rewrites the commands (rebind_draw_buffers_into), set 0's writes and dynamic offsets (binding::rebind_into), push bytes and vertex buffers, and its uses whole (command_uses_into), and takes the checks a draw takes of them: a pulled attribute's reach, the stages' function tables, the attachments' reads; it stops at a pass whose fragments wrote memory, a shadowed texture among its uses, a barrier its fragments need after earlier geometry writes, or a detached buffer. It records with set 0 as any draw finds or writes it (EncoderCore::set_zero_of), its uses noted as any draw notes them, through the kept draw's recording parts against what its command buffer holds; a notice met at each occurrence forgets it once recorded, as every step does. The kept parts (set-0 writes that hold no keeper, dynamic states, the rest of its recording) live in the bind state's storage (LiveBind::kept), filled at the keep alone: a draw that takes every step pays one KeptStorage::keep and nothing per recording. - Checked in builds with debug assertions: the first rebound draw of a kept draw and every second after it take every step instead, which must keep the draw, with the same commands, set-0 writes, dynamic offsets, push bytes, vertex buffers and uses. Tests: tests::draw_again::draws_after_buffer_changes_rebind_what_every_step_binds (MoltenVK, M3): draws after offset and bytes changes rebind (draws_rebound == the draws again but those the check takes), with the same commands of every kind, state commands, noted uses and pixels as the same draws each taking every step, every draw at its own offset and color; a sampler bind between them takes every step. Negative control: the translator not rewriting a changed slot's range fails it at the cross-check ("other commands"). metal2vulkan's tests::engine_graphics_binder rebind test: 1360 rebinds over stage-io plans equal a full instantiate, and its negative control fails. host_ab encode, release, 10k draws per command buffer, us/draw, offset case (one set_vertex_buffer_offset before each draw), measured on this change before its last revision (which moved the kept parts' fill from every full draw's recording to the keep and dropped three Arc clones a keep; its own numbers come with the next landing): Apple M3 Max, MoltenVK 1.4.2, three interleaved rounds (median / mean of round p50s / max p90): lock fix 1.561 / 1.550 / 1.591 -> 0.550 / 0.548 / 0.592 RTX 5080 Laptop GPU, thread CPU per draw, host_ab threads workload, one thread: lock fix 2.006 (shared PSO), 2.001 (own) -> 0.541, 0.585; on 8 threads 10.3 Mdraws/s (was 2.9) The unchanged draw (static) holds: 0.044 -> 0.046 on the M3. (cherry picked from commit 2ee3520ff104094afde523e2eebf7bc8a9a9626d) (cherry picked from commit d00975ea7da92da4886a29f1ebda6397f64202b1) --- .../src/argument_table.rs | 9 + crates/metal2vulkan-runtime/src/binding.rs | 89 ++- crates/metal2vulkan-runtime/src/encoder.rs | 28 +- crates/metal2vulkan-runtime/src/live_bind.rs | 24 +- crates/metal2vulkan-runtime/src/render.rs | 55 +- .../src/render/draw_again.rs | 180 ++++++- .../src/render/draw_again/rebound.rs | 508 ++++++++++++++++++ .../src/render/pass_start_reads.rs | 6 + .../metal2vulkan-runtime/src/render/replay.rs | 20 +- .../src/tests/draw_again.rs | 112 +++- .../metal2vulkan-runtime/src/work_counts.rs | 24 + crates/metal2vulkan/src/bind/graphics.rs | 214 +++++++- crates/metal2vulkan/src/bind/instantiate.rs | 2 +- .../src/tests/engine_graphics_binder.rs | 88 +++ crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 7 + 16 files changed, 1277 insertions(+), 91 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index f769575fe..2aa865af1 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -1179,6 +1179,15 @@ impl ArgumentTable { self.check_reading(kept, read, (maps, views)); } + /// The slots the table's calls changed since its stamp was `read`, where it keeps them + /// ([`Changes`]): those [`refresh_changed`](Self::refresh_changed) brings in. + pub(super) fn changed_since( + &self, + read: Stamp, + ) -> Option + '_> { + self.changes.since(read) + } + /// [`refresh_reading`](Self::refresh_reading) of `kept`, read last under the stamp `read` /// through the same interface and maps: only the slots the table's calls changed since, where /// it keeps them ([`Changes`]) and its slots that tell the view base alignment apart are as diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 42106d9cb..fe4b83e06 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -460,19 +460,72 @@ pub(super) fn dynamic_writes(writes: &mut [Write], dynamic: &[u32], offsets: &mu if dynamic.is_empty() { return; } - for write in writes.iter_mut().filter(|write| write.set == 0) { - let (Ok(at), Info::Buffer(info)) = (dynamic.binary_search(&write.binding), &mut write.info) - else { - continue; - }; - write.ty = dynamic_type(write.ty); - if let Ok(offset) = u32::try_from(info.offset) { - offsets[at] = offset; - info.offset = 0; - } + for write in writes.iter_mut() { + dynamic_write(write, dynamic, offsets); } } +/// [`dynamic_writes`]' work on one write, where it is set 0's at a binding `dynamic` numbers: +/// made dynamic, its offset its binding's in `offsets`. +fn dynamic_write(write: &mut Write, dynamic: &[u32], offsets: &mut [u32]) { + if write.set != 0 { + return; + } + let (Ok(at), Info::Buffer(info)) = (dynamic.binary_search(&write.binding), &mut write.info) + else { + return; + }; + write.ty = dynamic_type(write.ty); + offsets[at] = 0; + if let Ok(offset) = u32::try_from(info.offset) { + offsets[at] = offset; + info.offset = 0; + } +} + +/// Write again, over `writes` and `offsets` (a command's set-0 writes and dynamic offsets as +/// [`bind_into`] and [`dynamic_writes`] made them, for a variant of the dynamic bindings +/// `dynamic`), the descriptors of the plan's writes from the buffer slots `slots`, which the +/// command's tables now bind elsewhere (another buffer, offset or bytes, the shape the same), with +/// `command`'s ranges for them: the writes and offsets [`bind_into`] and [`dynamic_writes`] make +/// for the tables now. `Ok(false)` where a write of theirs is not at its place among `writes` (a +/// heap's, which skips writes): the caller binds whole. +pub(super) fn rebind_into( + device: &Device, + state: &mut State, + (plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>), + slots: &[SlotRef], + (writes, dynamic, offsets): (&mut [Write], &[u32], &mut [u32]), +) -> Result { + if tables.heap.is_some() || writes.len() != plan.descriptors.len() { + return Ok(false); + } + for (write, planned) in writes.iter_mut().zip(&plan.descriptors) { + let slot = match planned.source { + WriteSource::Buffer { slot } | WriteSource::InlineBytes { slot } => slot, + _ => continue, + }; + if !slots.contains(&slot) { + continue; + } + let ty: vk::DescriptorType = planned.ty.into(); + let place = (write.set, write.binding, write.element); + if place != (planned.set, planned.binding, planned.array_element) || write.held.is_some() { + return Ok(false); + } + *write = Write { + set: planned.set, + binding: planned.binding, + element: planned.array_element, + ty, + info: Info::Buffer(descriptor(device, state, command, tables, planned)?), + held: None, + }; + dynamic_write(write, dynamic, offsets); + } + Ok(true) +} + /// One descriptor to write: a buffer's or an image's and sampler's. pub(super) struct Write { pub(super) set: u32, @@ -485,6 +538,20 @@ pub(super) struct Write { pub(super) held: Option, } +impl Write { + /// A copy of it, where it holds no keeper. + pub(super) fn unheld(&self) -> Option { + self.held.is_none().then_some(Write { + set: self.set, + binding: self.binding, + element: self.element, + ty: self.ty, + info: self.info, + held: None, + }) + } +} + /// What a descriptor write holds. #[derive(Clone, Copy)] pub(super) enum Info { @@ -891,7 +958,7 @@ impl SetWrite { } /// `write`'s descriptor, without its set number and keeper. - fn of(write: &Write) -> SetWrite { + pub(super) fn of(write: &Write) -> SetWrite { SetWrite { binding: write.binding, element: write.element, diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 6ef8e9c90..2f2805ada 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -608,6 +608,16 @@ impl EncoderCore { (writes, offsets): (&mut [Write], &mut Vec), ) -> Result<(Option, Option), Error> { binding::dynamic_writes(writes, objects.dynamic_bindings(), offsets); + self.set_zero_of(objects, writes) + } + + /// [`set_zero`](Self::set_zero)'s set for `writes`, made dynamic already + /// (`binding::dynamic_writes`). + pub(super) fn set_zero_of( + &mut self, + objects: &VariantObjects, + writes: &mut [Write], + ) -> Result<(Option, Option), Error> { let layout = objects.set_zero_layout(); if let Some(layout) = layout { if let Some(set) = self.last_set_zero.holds(layout, writes) { @@ -1248,14 +1258,10 @@ impl EncoderCore { /// are. Free while no buffer is detached. Call it once every check of the command passed, /// before any Vulkan call that takes one of the buffers. pub(super) fn skips(&mut self, keys: impl IntoIterator + Clone) -> bool { + if !self.would_skip(keys.clone()) { + return false; + } if !self.taken.dead() { - if self.unattached_as_called { - return false; - } - let rebinds = &self.device().shared().rebinds; - if !rebinds.any_detached(keys.clone()) { - return false; - } self.taken.die(); } self.touch_keys(keys.clone()); @@ -1265,6 +1271,14 @@ impl EncoderCore { true } + /// Whether [`skips`](Self::skips) skips a command that names `keys`, changing nothing. + pub(super) fn would_skip(&self, keys: impl IntoIterator) -> bool { + if self.taken.dead() { + return true; + } + !self.unattached_as_called && self.device().shared().rebinds.any_detached(keys) + } + /// The keys its commands named so far, their uses' and their bindings' (`touch`). pub(super) fn named_keys(&self) -> &BTreeSet { &self.keys diff --git a/crates/metal2vulkan-runtime/src/live_bind.rs b/crates/metal2vulkan-runtime/src/live_bind.rs index b0d1e81dc..af7361599 100644 --- a/crates/metal2vulkan-runtime/src/live_bind.rs +++ b/crates/metal2vulkan-runtime/src/live_bind.rs @@ -76,6 +76,7 @@ use super::binding::{CommandUses, PushWrite, SetWrite, Write}; use super::device::lock; use super::noted_apart::NotedApart; use super::pipeline::{BufferForms, GraphicsState, ProgramName, Settled}; +use super::render::KeptStorage; use super::sampler::OwnedSampler; use super::work_counts::Counters; @@ -122,7 +123,8 @@ impl Reshape { } /// Whether a change it was told of may have changed the shape: a compute encoder's kept state - /// then finds its shape again (`compute/live.rs`). + /// then finds its shape again (`compute/live.rs`), and a draw rebound takes every step + /// (`render/draw_again/rebound.rs`). pub(super) fn may_reshape(self) -> bool { self.0 } @@ -213,6 +215,9 @@ pub(super) struct LiveBind { /// The storage of the samplers the last draw's writes named (`binding::bind_into`), kept /// likewise and empty between draws: its encoder retains them as the draw records. pub(super) samplers: Vec>, + /// What a draw rebound takes of its encoder's kept draw beyond its objects, kept likewise + /// (`render/draw_again/rebound.rs`). + pub(super) kept: KeptStorage, } /// A bind state a [`LiveBind`] set aside, with its shape, its listing's count and what its stage @@ -238,6 +243,11 @@ pub(super) struct SettledHere { } impl SettledHere { + /// What the draw settled. + pub(super) fn settled(&self) -> &Settled { + &self.settled + } + /// What a draw of `pipeline` in `forms` settled. pub(super) fn new(pipeline: &GraphicsState, forms: BufferForms, settled: Settled) -> Self { SettledHere { @@ -288,6 +298,11 @@ impl ReadFrom { self.moved == moved && self.through(interface) && self.maps == *maps } + /// The maps the tables were read with. + pub(super) fn maps(&self) -> &SamplerMaps { + &self.maps + } + /// Whether the tables were read through `interface`: the one at its address, while the /// drawing state that held it then lives. fn through(&self, interface: &PipelineInterface) -> bool { @@ -391,6 +406,13 @@ impl LiveBind { same.then_some(&here.settled) } + /// Whether a draw of `pipeline` in `forms` settles as the state's last recorded draw did + /// ([`settled`](Self::settled)), its shape kept: no change since may have changed it. + pub(super) fn settles_kept(&self, pipeline: &GraphicsState, forms: BufferForms) -> bool { + let shape = self.shape.as_ref(); + shape.is_some_and(|shape| self.settled(pipeline, shape, forms).is_some()) + } + /// Let go of every state's kept settle, as their encoder ends. fn forget_settles(&mut self) { self.settled = None; diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 23c011368..8b7054de2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -430,6 +430,7 @@ use deferral::Logged; pub(crate) use deferral::{lowering, DeferredEncoders, EndInFlight}; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) use deferral::{BATCH_CALLS, HANDED_BATCHES}; +pub(crate) use draw_again::KeptStorage; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) use draw_room::made as draw_rooms_made; pub(crate) use draw_room::SpareDrawRooms; @@ -2633,7 +2634,7 @@ impl RenderLowering { offset: u64, index: u32, ) -> Result<(), Error> { - self.log(|log| { + self.log_keeping(|log| { let buffer = buffer.map(|buffer| log.hold_buffer(buffer)); RenderCall::Buffer(Table::Vertex, buffer, offset, index) }); @@ -2648,7 +2649,7 @@ impl RenderLowering { offsets: &[u64], first: u32, ) -> Result<(), Error> { - self.log(|log| { + self.log_keeping(|log| { RenderCall::Buffers( Table::Vertex, log.buffer_span(buffers), @@ -2671,14 +2672,14 @@ impl RenderLowering { offset: u64, index: u32, ) -> Result<(), Error> { - self.log(|_| RenderCall::BufferOffset(Table::Vertex, offset, index)); + self.log_keeping(|_| RenderCall::BufferOffset(Table::Vertex, offset, index)); self.vertex .set_buffer_offset(&mut self.core, "set_vertex_buffer_offset", offset, index) } /// The lowering of [`RenderCommandEncoder::set_vertex_bytes`]. pub(crate) fn set_vertex_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> { - self.log(|log| RenderCall::Bytes(Table::Vertex, log.byte_span(bytes), index)); + self.log_keeping(|log| RenderCall::Bytes(Table::Vertex, log.byte_span(bytes), index)); self.vertex .set_bytes(&mut self.core, "set_vertex_bytes", bytes, None, index) } @@ -2751,7 +2752,7 @@ impl RenderLowering { offset: u64, index: u32, ) -> Result<(), Error> { - self.log(|log| { + self.log_keeping(|log| { let buffer = buffer.map(|buffer| log.hold_buffer(buffer)); RenderCall::Buffer(Table::Fragment, buffer, offset, index) }); @@ -2766,7 +2767,7 @@ impl RenderLowering { offsets: &[u64], first: u32, ) -> Result<(), Error> { - self.log(|log| { + self.log_keeping(|log| { RenderCall::Buffers( Table::Fragment, log.buffer_span(buffers), @@ -2789,14 +2790,14 @@ impl RenderLowering { offset: u64, index: u32, ) -> Result<(), Error> { - self.log(|_| RenderCall::BufferOffset(Table::Fragment, offset, index)); + self.log_keeping(|_| RenderCall::BufferOffset(Table::Fragment, offset, index)); self.fragment .set_buffer_offset(&mut self.core, "set_fragment_buffer_offset", offset, index) } /// The lowering of [`RenderCommandEncoder::set_fragment_bytes`]. pub(crate) fn set_fragment_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> { - self.log(|log| RenderCall::Bytes(Table::Fragment, log.byte_span(bytes), index)); + self.log_keeping(|log| RenderCall::Bytes(Table::Fragment, log.byte_span(bytes), index)); self.fragment .set_bytes(&mut self.core, "set_fragment_bytes", bytes, None, index) } @@ -3243,7 +3244,7 @@ impl RenderLowering { instance_count: u32, base_instance: u32, ) -> Result<(), Error> { - self.log_draw(|_| { + self.log_keeping(|_| { RenderCall::DrawPrimitives( primitive_type, vertex_start, @@ -7162,6 +7163,10 @@ impl RenderLowering { #[cfg(debug_assertions)] draw_again::Again::Check(checked) => Some(checked), draw_again::Again::No => None, + draw_again::Again::Refused(refused) => { + self.forget_again(); + return Err(refused); + } }; self.forget_again(); let watch = EachWatch::start(); @@ -8379,6 +8384,8 @@ impl RenderLowering { ), &mut live.uses, )?; + // How many it holds of its plan's alone: a draw rebound works out those alone. + let plan_uses = live.uses.len(); let uses = &mut live.uses; // A use of an attachment's memory other than as the attachment, inside its instance, // which no copy serves (`texture/attached_reads.rs`): a draw that reads through snapshots @@ -9828,6 +9835,34 @@ impl RenderLowering { shape: Arc::clone(&shape), created: created.clone(), }); + // What a draw rebound takes of it (`render/draw_again/rebound.rs`), where its state made + // no visible-function table: set-0 writes that hold no keeper, its plan's uses alone, + // no push hole, and its one recording's parts (its variant and plan are the bind + // state's kept settle). + let recorded = match (&draw_states, &draw_pipeline, vk_draws) { + (DrawStates::Whole([state]), DrawPipeline::Made(made), [(index, _, command)]) => { + Some(draw_again::KeptRecording { + layout: objects.layout(), + shape: objects.set_zero_shape(), + pipeline: made.raw, + index: *index, + topology, + primitive_restart, + state: state.clone(), + draw: *command, + }) + } + _ => None, + }; + let rebinds = function_tables.is_empty() + && uses.len() == plan_uses + && bound.holes.is_empty() + && writes.iter().all(|write| write.held.is_none()); + let recorded = recorded.filter(|_| rebinds); + let rebinds = recorded.is_some(); + if let Some(recorded) = recorded { + live.kept.keep(&writes, dynamic, recorded); + } let kept = draw_again::Kept { call, assembly, @@ -9845,6 +9880,8 @@ impl RenderLowering { rasterizes: false, depth_writes: false, draw_alone, + stamps: self.table_stamps(), + rebinds, }; self.again.keep(kept); } diff --git a/crates/metal2vulkan-runtime/src/render/draw_again.rs b/crates/metal2vulkan-runtime/src/render/draw_again.rs index cb132e386..e8b480328 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again.rs @@ -16,15 +16,21 @@ //! 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. +//! - **Forgotten at every call but a buffer bind.** Every call of the encoder but the two direct +//! draws and the vertex and fragment buffer and bytes binds 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. A buffer or bytes bind changes its +//! stage table's slots alone (and takes room in its command buffer's uploads), and a table's +//! stamp tells each change apart (`argument_table::Stamp`): the kept draw keeps the four +//! tables' stamps as it read them, and a draw whose tables kept them is the kept draw again; +//! one after binds is drawn again rebound where it can be (`rebound.rs`), else takes every +//! step. So the encoder's state a draw resolves from is the kept draw's, but for the tables' +//! slots the stamps tell apart, 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 @@ -48,14 +54,22 @@ //! 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. +mod rebound; + use ash::vk; use metal2vulkan::bind::{BindShape, DrawCall}; use std::sync::Arc; use std::time::Duration; +pub(super) use rebound::KeptRecording; +pub(crate) use rebound::KeptStorage; + +use super::bound::Recorded; use super::{Assembly, DrawBuffers, RenderLowering}; +use crate::argument_table::Stamp; use crate::degradation::EachWatch; use crate::draw_source::DrawSource; +use crate::error::Error; use crate::execution::{ExecutedPipeline, Execution}; use crate::noted_apart::NotedInto; use crate::resource::ResourceKey; @@ -81,6 +95,11 @@ struct Counted { draws: u64, pushing_set_zero: u64, last_vertex: u64, + /// Of `draws`, those rebound (`rebound.rs`), the stage tables they read in part, and the state + /// commands and pushed writes they recorded. + rebound: u64, + tables: u64, + recorded: Recorded, } /// What a kept draw was, what it read, and what a draw again repeats of it (the module docs). @@ -111,6 +130,12 @@ pub(super) struct Kept { pub(super) depth_writes: bool, /// Whether it recorded no state command (`Recorded::draw_alone`), as a draw again does. pub(super) draw_alone: bool, + /// The stamps of its vertex, fragment, object and mesh tables as it read them: a draw whose + /// tables kept them binds as it did. + pub(super) stamps: [Stamp; 4], + /// Whether its encoder's bind state keeps what a draw rebound takes of it (`LiveBind::kept`, + /// `rebound.rs`). + pub(super) rebinds: bool, } /// An index source as a kept draw read it in place: the Metal buffer, by key, and offset, and @@ -173,6 +198,8 @@ pub(super) enum Again { Check(Box), /// It is not. No, + /// It was rebound, and refused as every step of it would refuse it. + Refused(Error), } impl DrawAgain { @@ -212,14 +239,26 @@ impl RenderLowering { draws, pushing_set_zero, last_vertex, + rebound, + tables, + recorded, } = self.again.counted; if draws > 0 { let counts = &self.core.device().shared().counts; - counts.draws_drawn_again(draws, pushing_set_zero, last_vertex); + counts.draws_drawn_again(draws - rebound, pushing_set_zero, last_vertex); + if rebound > 0 { + counts.draws_rebound(rebound, tables); + recorded.count(counts); + } self.again.counted = Counted::default(); } } + /// The stamps of the encoder's vertex, fragment, object and mesh tables. + pub(super) fn table_stamps(&self) -> [Stamp; 4] { + [&self.vertex, &self.fragment, &self.object, &self.mesh].map(|table| table.stamp()) + } + /// 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. @@ -247,12 +286,19 @@ impl RenderLowering { if !same { return Again::No; } + let stamps = self.table_stamps(); + if kept.stamps != stamps { + return match kept.rebinds { + true => self.draw_rebound(call, (assembly, draw), buffers, stamps), + false => 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))); + return Again::Check(Box::new(Checked::of(self, None))); } } let counted = &mut self.again.counted; @@ -301,9 +347,6 @@ impl RenderLowering { (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; @@ -311,10 +354,13 @@ impl RenderLowering { } #[cfg(debug_assertions)] if let Some(checked) = checked { - checked.check(self); + checked.check(self, watch.met()); } #[cfg(not(debug_assertions))] let _: Option> = checked; + if watch.met() { + self.forget_again(); + } } } @@ -326,6 +372,65 @@ pub(super) struct Checked { hits: u64, held: Held, announced: u64, + /// What it worked out of its rebound slots, where it is a draw rebound (`rebound.rs`). + rebound: Option, +} + +/// What a draw rebound worked out (`rebound.rs`), which its every step must work out alike. +#[cfg(debug_assertions)] +pub(super) struct Rebound { + commands: metal2vulkan::bind::DrawCommands, + writes: Vec<(u32, crate::binding::SetWrite)>, + offsets: Vec, + pushes: Vec, + vertex_buffers: Vec<(u32, vk::Buffer, u64, u64)>, + uses: Vec>, + resident: std::collections::BTreeSet, +} + +#[cfg(debug_assertions)] +impl Rebound { + /// What `live` and `binds` hold of a draw rebound. + pub(super) fn of(live: &crate::live_bind::LiveBind) -> Rebound { + Rebound { + commands: live.commands.clone(), + writes: Self::writes(live.kept.writes()), + offsets: live.offsets.clone(), + pushes: live.pushes.clone(), + vertex_buffers: live.vertex_buffers.clone(), + uses: live.uses.to_vec(), + resident: live.uses.resident().clone(), + } + } + + fn writes(writes: &[crate::binding::Write]) -> Vec<(u32, crate::binding::SetWrite)> { + (writes.iter()) + .map(|write| (write.set, crate::binding::SetWrite::of(write))) + .collect() + } + + /// Assert that every step of the draw worked out what it did, in `live` and `binds`. + fn assert_as(&self, live: &crate::live_bind::LiveBind) { + let writes = Self::writes(live.kept.writes()); + let same_writes = writes.len() == self.writes.len() + && (writes.iter().zip(&self.writes)) + .all(|((set, write), (kept_set, kept))| set == kept_set && write.same(kept)); + let parts = [ + ("commands", live.commands == self.commands), + ("set-0 writes", same_writes), + ("dynamic offsets", live.offsets == self.offsets), + ("push bytes", live.pushes == self.pushes), + ("vertex buffers", live.vertex_buffers == self.vertex_buffers), + ("uses", *live.uses == self.uses[..]), + ("resident keys", *live.uses.resident() == self.resident), + ]; + for (part, same) in parts { + assert!( + same, + "a draw rebound worked out other {part} than its every step" + ); + } + } } /// No check in builds without debug assertions: no draw again takes every step. @@ -411,7 +516,8 @@ impl Held { #[cfg(debug_assertions)] impl Checked { - fn of(encoder: &mut RenderLowering) -> Checked { + /// The check of the draw again about to take every step, `rebound` where it is rebound. + pub(super) fn of(encoder: &mut RenderLowering, rebound: Option) -> Checked { let kept = encoder.again.kept.take(); let kept = kept.unwrap_or_else(|| unreachable!("a draw again without its kept draw")); Checked { @@ -419,29 +525,49 @@ impl Checked { hits: encoder.again.hits, held: Held::of(encoder), announced: crate::degradation::announced_here(), + rebound, } } - /// Check the draw that took every step against the kept one (the module docs). - fn check(self, encoder: &mut RenderLowering) { + /// Check the draw that took every step, which `met` a notice met at each occurrence or not, + /// against the kept one (the module docs). + fn check(self, encoder: &mut RenderLowering, met: bool) { let Checked { kept, hits, held, announced, + rebound, } = 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)); + if let Some(rebound) = &rebound { + // Its uses differ from the kept draw's: what noting them adds is every step's own. + rebound.assert_as(&crate::device::lock(&encoder.live)); + } else { + assert_eq!( + crate::degradation::announced_here(), + announced, + "a draw again announced a notice" + ); + assert!(!met, "a draw again met a notice met at each occurrence"); + 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; + let (draw_alone, stamps, under) = (again.draw_alone, again.stamps, again.under); + assert!( + draw_alone || rebound.is_some(), + "a draw again recorded a state command" + ); + assert!( + again.rebinds || rebound.is_none(), + "a draw rebound whose every step keeps nothing to rebind" + ); + // A draw rebound reads its tables under their stamps now, its uses noted into the state + // now. + (again.draw_alone, again.stamps, again.under) = (kept.draw_alone, kept.stamps, kept.under); assert!(*again == kept, "a draw again kept another draw"); + (again.draw_alone, again.stamps, again.under) = (draw_alone, stamps, under); encoder.again.hits = hits; } } diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs new file mode 100644 index 000000000..d87e7ba74 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -0,0 +1,508 @@ +//! A render encoder's kept draw drawn again after calls that bound other buffers or offsets at +//! vertex or fragment buffer slots (`WorkCounts::draws_rebound`): its every other step is the kept +//! draw's (`render/draw_again.rs`), so only what those slots decide is worked out again. +//! +//! - **Which draw.** The kept draw again ([`RenderLowering::draw_again`]: the same call and +//! arguments, under the same `Under`, into the same command buffer) after calls that changed +//! only buffer slots of its tables, each table's changes since the kept draw read it still +//! listed (`argument_table::Changes`, at most [`SLOTS`] slots), where the kept draw kept what +//! this takes ([`KeptStorage`]: a draw whose set-0 writes hold no keeper, of no use beyond its +//! plan's and its draw's own, and of a state that made no visible-function table). The kept +//! bind state takes the changed slots (`ArgumentTable::refresh_changed`), and the draw goes on +//! only where its shape stays: its variant, plan, pipeline and draw state are then the kept +//! draw's, functions of the shape and of what no call changed. +//! - **What it works out again.** Its commands, rebound at those slots +//! (`BindingPlan::rebind_draw_buffers_into`: their descriptor ranges, push fields and vertex +//! buffers' offsets); set 0's writes of them with their dynamic offsets (`binding::rebind_into`), +//! and the set its encoder's last set or its command buffer's holds, else a new one +//! (`EncoderCore::set_zero_of`); its push bytes and vertex buffers; and its uses, whole +//! (`binding::command_uses_into`). And the checks a draw of changed tables takes: a pulled +//! attribute's reach, the stages' function tables, the attachments' reads. Each is the function +//! every step of the draw runs, on the same inputs. +//! - **Where it stops.** At a slot of another class, a changed shape, a plan that reads a changed +//! slot some other way, a refusal of any of those steps, a pass whose fragments wrote memory (a +//! stage before them may read a copy of it), a shadowed texture among its uses, or a barrier its +//! fragments need after an earlier draw's geometry writes: the draw takes every step, which +//! answers as it would have. Only the attachments' reads' refusal is answered here, the last of +//! its checks, which may have announced. +//! - **What it records and notes.** Its uses noted as any draw notes them (`note_reaching`, the +//! unordered writes, the pass's reads, the instance's gathered uses, indirect reads and geometry +//! writes); the state commands that changed and its draw, recorded through the kept draw's +//! recording against what its command buffer holds (`render/bound.rs`); its tables' new objects +//! retained; and the rest as a draw again: kept for recording again (but where it met a notice +//! met at each occurrence, as its every step forgets it then), its execution record, its counts +//! until the encoder's next call or its end. +//! - **Checked in builds with debug assertions.** As a draw again is: the first rebound draw of a +//! kept draw and every second after it work out the rebind, then take every step instead, +//! which must keep the draw, with the same commands, set-0 writes, dynamic offsets, push bytes, +//! vertex buffers and uses. + +use ash::vk; +use metal2vulkan::bind::DrawCall; +use metal2vulkan::pipeline::{SlotClass, SlotRef, Stage}; +use std::sync::Arc; + +use super::{Again, RenderLowering}; +use crate::argument_table::Stamp; +use crate::binding::{self, SetWrite, Write}; +use crate::draw_source::{DrawSource, IndexBind}; +use crate::error::Error; +use crate::live_bind::{LiveBind, Reshape}; +use crate::pipeline::{RenderStateKind, Settled}; +use crate::render::{Assembly, DrawBuffers, DrawState, Recording}; + +/// The most buffer slots a draw rebound takes changed: a draw after more takes every step. +const SLOTS: usize = 8; + +/// What a draw rebound takes of the kept draw (the module docs) but its variant and plan, which +/// its bind state's kept settle holds (`LiveBind::settled`): in the storage the bind state keeps +/// from one draw and one encoder to the next (`LiveBind::kept`), read only while the kept draw is +/// kept for one ([`Kept::rebinds`](super::Kept)). It holds no object alive: its writes hold no +/// keeper, and its recording names handles alone. +#[derive(Default)] +pub(crate) struct KeptStorage { + /// Its set-0 writes as its set holds them (`binding::dynamic_writes`). + writes: Vec, + /// Its dynamic states. + dynamic: Vec, + /// The rest of its recording. + recording: Option, +} + +/// A kept draw's recording but for what a draw rebound works out again (its set, dynamic +/// offsets, push bytes and vertex buffers) and its dynamic states (`KeptStorage::dynamic`). +pub(in crate::render) struct KeptRecording { + pub(in crate::render) layout: vk::PipelineLayout, + pub(in crate::render) shape: u64, + pub(in crate::render) pipeline: vk::Pipeline, + pub(in crate::render) index: Option, + pub(in crate::render) topology: metal2vulkan::vk::PrimitiveTopology, + pub(in crate::render) primitive_restart: bool, + pub(in crate::render) state: DrawState, + pub(in crate::render) draw: metal2vulkan::vk::DrawCommand, +} + +impl KeptStorage { + /// Keep, over the storage it holds, what a draw rebound takes of the draw just kept: its set-0 + /// `writes`, each of which holds no keeper, its `dynamic` states and the rest of its + /// `recording`. + pub(in crate::render) fn keep( + &mut self, + writes: &[Write], + dynamic: &[vk::DynamicState], + recording: KeptRecording, + ) { + self.writes.clear(); + self.writes.extend(writes.iter().filter_map(Write::unheld)); + self.dynamic.clear(); + self.dynamic.extend_from_slice(dynamic); + self.recording = Some(recording); + } + + /// The kept draw's set-0 writes. + #[cfg(debug_assertions)] + pub(in crate::render) fn writes(&self) -> &[Write] { + &self.writes + } +} + +/// Whether `live`'s kept settle holds the variant and plan the kept draw ran: where the draw's +/// shape is the kept one and the state it draws ran it (`LiveBind::settles_kept`). +fn settles_kept(encoder: &RenderLowering, live: &LiveBind) -> bool { + match encoder.pipeline.as_ref().map(|pipeline| pipeline.kind()) { + Some(RenderStateKind::Graphics(pipeline)) => live.settles_kept(pipeline, encoder.forms), + _ => false, + } +} + +/// The buffer slots calls changed since the kept draw read its tables: at most [`SLOTS`]. +struct Changed { + slots: [SlotRef; SLOTS], + count: usize, +} + +impl Changed { + /// None yet. + fn new() -> Changed { + let any = SlotRef { + stage: Stage::Vertex, + class: SlotClass::Buffer, + index: 0, + }; + Changed { + slots: [any; SLOTS], + count: 0, + } + } + + /// Add `slot`: whether there was room. + fn add(&mut self, slot: SlotRef) -> bool { + if self.list().contains(&slot) { + return true; + } + let Some(free) = self.slots.get_mut(self.count) else { + return false; + }; + *free = slot; + self.count += 1; + true + } + + fn list(&self) -> &[SlotRef] { + &self.slots[..self.count] + } +} + +impl RenderLowering { + /// The kept draw again after calls that bound other buffers or offsets in its tables, whose + /// stamps are now `stamps` (the module docs): recorded, refused, or [`Again::No`] where it + /// takes every step. + pub(super) fn draw_rebound( + &mut self, + call: &'static str, + (assembly, draw): (Assembly, &DrawCall), + buffers: &DrawBuffers<'_>, + stamps: [Stamp; 4], + ) -> Again { + // A notice met at each occurrence forgets the draw once recorded, as its every step does. + let watch = crate::degradation::EachWatch::start(); + let live = Arc::clone(&self.live); + let mut held = crate::device::lock(&live); + let live = &mut *held; + let Some((changed, read)) = self.bring_in(live, stamps) else { + return Again::No; + }; + if !self.rebind(call, live, &changed, (draw, buffers)) { + return Again::No; + } + #[cfg(debug_assertions)] + { + let hits = self.again.hits; + self.again.hits += 1; + if hits.is_multiple_of(2) { + let rebound = super::Rebound::of(live); + drop(held); + return Again::Check(Box::new(super::Checked::of(self, Some(rebound)))); + } + } + // The attachments' reads: its last check, refused here, as it may have announced. + let attached = + (self.core.device()).degrade_attachment_reads(call, &self.layout, &live.uses); + if let Err(refused) = attached { + return Again::Refused(refused); + } + let recorded = self.record_rebound(live, (call, assembly, draw), buffers, (stamps, read)); + if let Err(refused) = recorded { + return Again::Refused(refused); + } + if watch.met() { + self.forget_again(); + } + Again::Drawn + } + + /// Bring into the kept draw's bind state the slots calls changed since in each table whose + /// stamp is no longer the kept draw's: the changed slots, and how many tables were read in + /// part; `None` where one is not a buffer slot, a table keeps no list of them, or the shape + /// changed (then the kept state makes its shape again, as any draw's does). + fn bring_in(&self, live: &mut LiveBind, stamps: [Stamp; 4]) -> Option<(Changed, u64)> { + let RenderStateKind::Graphics(pipeline) = self.pipeline.as_ref()?.kind() else { + return None; + }; + let kept = self.again.kept.as_ref()?; + let interface = &pipeline.base().interface; + let views = pipeline.at_bind_views(); + let moved = crate::buffer::host_cells_moved(); + let maps = live.read_from.maps().clone(); + if !live.read_from.reads(interface, &maps, moved) { + return None; + } + let tables = [&self.vertex, &self.fragment, &self.object, &self.mesh]; + let stages = [Stage::Vertex, Stage::Fragment, Stage::Object, Stage::Mesh]; + // Each changed table: read last as the kept draw read it, its slots that tell the view + // base alignment apart as the state holds them, its changes since listed, all of buffer + // slots. + let mut changed = Changed::new(); + for (at, (stage, table)) in stages.into_iter().zip(tables).enumerate() { + let under = kept.stamps[at]; + if stamps[at] == under { + continue; + } + let state = live.state.stages.get(&stage)?; + let read = live.read_from.read_under(at) == Some(under); + if !read || !views.holds(stage, state.at_bind_views) { + return None; + } + for (class, index) in table.changed_since(under)? { + if class != SlotClass::Buffer + || !changed.add(SlotRef { + stage, + class, + index, + }) + { + return None; + } + } + } + // Their slots brought in. What one brought in changed stays told where a later table + // takes them no more (`Reshape`), as the draw's every step reads that one again. + let mut reshape = Reshape::default(); + let mut read = 0; + for (at, (stage, table)) in stages.into_iter().zip(tables).enumerate() { + let under = kept.stamps[at]; + if stamps[at] == under { + continue; + } + let from = (live.state.stages.entry(stage).or_default(), under); + if !table.refresh_changed(from, (stage, interface), (&maps, views), &mut reshape) { + live.reshaped(reshape); + return None; + } + read += 1; + } + live.read_from + .read(stamps, (interface, || pipeline.held()), &maps, moved); + let reshaped = reshape.may_reshape(); + live.reshaped(reshape); + (!reshaped).then_some((changed, read)) + } + + /// Work out again in `live` what the slots `changed` decide of the kept draw, `draw` of + /// `buffers`: its commands, set-0 writes and dynamic offsets, push bytes, vertex buffers and + /// uses, with the checks a draw's steps take of them (the module docs). Whether it did; else + /// the draw takes every step, which writes them all again. + fn rebind( + &mut self, + call: &'static str, + live: &mut LiveBind, + changed: &Changed, + (draw, buffers): (&DrawCall, &DrawBuffers<'_>), + ) -> bool { + let kept = settles_kept(self, live) + .then_some(live.settled.as_ref()) + .flatten(); + let Some(Settled { variant, plan, .. }) = kept.map(|here| here.settled()) else { + return false; + }; + let slots = changed.list(); + if plan.rebind_draw_buffers_into(&live.state, slots, &mut live.commands) != Ok(true) { + return false; + } + let compiled = variant.pipeline(); + let interface = &compiled.interface; + let checked = self + .check_vertex_reach(&compiled.vertex_input.pulled, draw) + .is_ok() + && (self.vertex) + .check_function_tables(call, Stage::Vertex, interface) + .is_ok() + && (self.fragment) + .check_function_tables(call, Stage::Fragment, interface) + .is_ok(); + // The pass's fragment writes, a copy of which a stage before the fragments may read + // (`render/pass_start_reads.rs`): none, so each stage reads its encoder's table. + if !checked || self.pass_start.fragments_wrote() { + return false; + } + let stages = [ + (Stage::Vertex, &self.vertex), + (Stage::Fragment, &self.fragment), + (Stage::Object, &self.object), + (Stage::Mesh, &self.mesh), + ]; + let tables = binding::Tables::new(&stages) + .with_pass(&self.layout, plan.views) + .with_residency(&self.residency) + .with_texture_table(None) + .with_sampler_table(None) + .with_function_tables(&[]); + let commands = &live.commands; + let command = binding::Command { + descriptor_bytes: &commands.descriptor_bytes, + descriptor_ranges: &commands.descriptor_ranges, + root_tables: Vec::new(), + push_holes: &commands.push_holes, + uses: &commands.uses, + blobs: Vec::new(), + mesh: None, + tessellation: None, + }; + let objects = variant.objects(); + let rebound = { + let device = self.core.device(); + let mut state = self.core.command_buffer().state(); + let writes = &mut live.kept.writes[..]; + let set_zero = (writes, objects.dynamic_bindings(), &mut live.offsets[..]); + binding::rebind_into( + device, + &mut state, + (&**plan, &command, &tables), + slots, + set_zero, + ) + }; + let index = buffers.index.as_ref().map(DrawSource::metal); + let uses = (&**plan, &command, &tables); + let rebound = rebound.is_ok_and(|done| done) + && binding::command_uses_into(call, uses, (index, None), &mut live.uses).is_ok() + && binding::push_writes_into(&commands.push_constants, &[], &mut live.pushes).is_ok(); + if !rebound { + return false; + } + // Its fixed-function vertex buffers at the changed slots, in the plan's order. + for (bind, at) in plan.vertex_buffers.iter().zip(&mut live.vertex_buffers) { + let slot = SlotRef { + stage: Stage::Vertex, + class: SlotClass::Buffer, + index: bind.buffer_index, + }; + if !slots.contains(&slot) { + continue; + } + let offset = + (commands.buffer_offsets.iter()).find(|(binding, _)| *binding == bind.binding); + let space = match ( + self.vertex.buffers.get(&bind.buffer_index), + self.vertex.bytes.get(&bind.buffer_index), + ) { + (Some((buffer, _)), _) => buffer.space(), + (None, Some(bytes)) => (bytes.region.raw(), bytes.region.offset()), + (None, None) => return false, + }; + let (Some(&(_, offset)), (raw, start)) = (offset, space) else { + return false; + }; + at.1 = raw; + at.2 = start + offset; + } + // No shadowed texture among its uses, and no barrier its fragments need after an earlier + // draw's geometry writes. + let textures = (self.vertex.textures.values()) + .chain(self.fragment.textures.values()) + .chain(self.object.textures.values()) + .chain(self.mesh.textures.values()) + .chain(self.residency.textures()); + // Nor a detached buffer, a draw of which records nothing (`EncoderCore::skips`). + let uses = &live.uses; + let named = (uses.iter().map(|used| used.key)).filter(|key| !uses.resident().contains(key)); + crate::shadow::shadow_uses(textures, uses).is_empty() + && self.current.geometry_writes.barrier_before(uses).is_none() + && !self.core.would_skip(named) + } + + /// Record the draw rebound in `live` (the module docs): its set 0, its uses noted, its state + /// commands and draw, and the rest a draw again takes. A refusal is set 0's or the noting's. + fn record_rebound( + &mut self, + live: &mut LiveBind, + (call, assembly, draw): (&'static str, Assembly, &DrawCall), + buffers: &DrawBuffers<'_>, + (stamps, read): ([Stamp; 4], u64), + ) -> Result<(), Error> { + let kept = settles_kept(self, live) + .then_some(live.settled.as_ref()) + .flatten(); + let unsettled = || crate::error::internal("a draw rebound unsettled"); + let objects = kept.ok_or_else(unsettled)?.settled().variant.objects(); + let (set, written) = match objects.pushes_set_zero() { + true => { + let immutable = objects.immutable_pushes(); + SetWrite::push_into(&live.kept.writes, immutable, &mut live.pushed); + (None, None) + } + false => self.core.set_zero_of(objects, &mut live.kept.writes)?, + }; + let pushed: &[SetWrite] = match objects.pushes_set_zero() { + true => &live.pushed, + false => &[], + }; + let uses = &live.uses; + let stages = (uses.iter()).fold(vk::PipelineStageFlags2::empty(), |all, used| { + all | used.read.stages | used.write.stages + }); + (self.core).note_reaching(stages, (uses, uses.resident()), Some(&mut live.noted))?; + self.unordered.add(uses); + self.pass_start.announce(self.core.device(), uses, false); + self.pass_start.add(uses); + self.gathering().add(&[], uses); + self.current.indirect_reads.add(uses); + self.current.geometry_writes.add(uses); + let owned = (live.kept.recording.as_ref()) + .ok_or_else(|| crate::error::internal("a draw rebound without its recording"))?; + let shared = self.core.device().shared(); + let recording = Recording { + raw: shared.vk(), + command_buffer: self.current.draws, + layout: owned.layout, + shape: owned.shape, + pipeline: owned.pipeline, + sets: set.as_slice(), + offsets: &live.offsets, + pushed, + push_descriptor: shared.push_descriptor, + pushes_after_pipeline_binds: shared.pushes_after_pipeline_binds, + heap: None, + push: &live.pushes, + vertex_buffers: &live.vertex_buffers, + index: owned.index, + indirect: None, + dynamic: &live.kept.dynamic, + topology: owned.topology, + primitive_restart: owned.primitive_restart, + state: &owned.state, + extended: shared.extended_dynamic_state, + mesh: shared.mesh_draws.as_ref(), + draw: owned.draw, + pair: None, + }; + let bound = match self.current.inline { + true => &mut self.held_bound, + false => &mut self.current.bound, + }; + // SAFETY: as the kept draw's recording: the secondary command buffer (or the pass's, + // inline) records the kept draw's instance, and only this encoder records it; every + // object recorded is live until the command buffer completes (the kept draw's retained, + // and the tables' retained below); `bound` is the record of what its draws bound there. + let recorded = unsafe { recording.record(bound) }; + if let Some(written) = written { + self.core.keep_set_zero(written, &live.kept.writes); + } + let kept = (self.again.kept.as_mut()) + .ok_or_else(|| crate::error::internal("a draw rebound without its kept draw"))?; + kept.stamps = stamps; + let counted = &mut self.again.counted; + counted.draws += 1; + counted.rebound += 1; + counted.tables += read; + counted.recorded += recorded; + counted.pushing_set_zero += u64::from(kept.pushes_set_zero); + counted.last_vertex += u64::from(kept.last_vertex); + self.current.recorded = true; + let again = kept.again; + let (reads, rasterizes, depth_writes) = (kept.reads, kept.rasterizes, kept.depth_writes); + let execution = (kept.execution.as_ref()).map(|execution| { + let shape = Arc::clone(&execution.shape); + (execution.pipeline.clone(), shape, execution.created.clone()) + }); + if let Some((pipeline, shape, created)) = execution { + self.core + .executed(|| crate::execution::Execution::new(pipeline, shape, created)); + } + self.keep_draw(again, (call, assembly, *draw), buffers.index.as_ref()); + self.vertex.retain_exclusive(&mut self.core); + self.fragment.retain_exclusive(&mut self.core); + self.object.retain_exclusive(&mut self.core); + self.mesh.retain_exclusive(&mut self.core); + let under = self.under(); + if let Some(kept) = self.again.kept.as_mut() { + kept.under = under; + } + self.draw_calls += 1; + self.command_encoded(reads); + self.called = true; + self.drew |= rasterizes; + self.drew_depth_writes |= depth_writes; + Ok(()) + } +} diff --git a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs index 4183dbb07..3662b67a4 100644 --- a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs +++ b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs @@ -260,6 +260,12 @@ impl PassStartReads { } } + /// Whether a fragment stage of the pass wrote memory: else every stage of its draws reads the + /// encoder's tables ([`tables`](Self::tables)). + pub(super) fn fragments_wrote(&self) -> bool { + !self.fragment.is_empty() + } + /// The tables a draw of `interface`'s pipeline reads in place of the encoder's `vertex`, /// `object` and `mesh`, each as `table` makes it. pub(super) fn tables( diff --git a/crates/metal2vulkan-runtime/src/render/replay.rs b/crates/metal2vulkan-runtime/src/render/replay.rs index dafbf251c..612851b46 100644 --- a/crates/metal2vulkan-runtime/src/render/replay.rs +++ b/crates/metal2vulkan-runtime/src/render/replay.rs @@ -647,16 +647,22 @@ pub(crate) struct DrawIndexedPatchesIndirect { impl RenderLowering { /// Log the call `call` makes of the log, before it runs, where the encoder logs (the module - /// 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`). + /// docs). Every call but a direct draw and a vertex or fragment buffer or bytes bind 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); + self.log_keeping(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) { + /// [`log`](Self::log) a call that keeps the encoder's kept draw: a `draw_primitives` call, + /// drawn again as it was kept or keeping itself, and a vertex or fragment buffer or bytes bind, + /// which changes its table's slots alone, whose stamp the next draw compares + /// (`render/draw_again.rs`). + pub(crate) fn log_keeping( + &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(); @@ -685,7 +691,7 @@ 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. It keeps the - /// encoder's kept draw, as [`log_draw`](Self::log_draw) does. + /// encoder's kept draw, as [`log_keeping`](Self::log_keeping) does. pub(crate) fn log_indexed( &mut self, draw: impl FnOnce(&mut CallLog) -> DrawIndexed, diff --git a/crates/metal2vulkan-runtime/src/tests/draw_again.rs b/crates/metal2vulkan-runtime/src/tests/draw_again.rs index 94c572465..a99031995 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw_again.rs @@ -4,9 +4,13 @@ //! 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. +//! announces at every occurrence, which announces it at every draw. A draw again after calls that +//! bound other buffers, offsets or bytes at its buffer slots rebinds those alone +//! (`render/draw_again/rebound.rs`, `WorkCounts::draws_rebound`), with the same commands and +//! pixels as the same draws taking every step. In builds with debug assertions, every second draw +//! again takes every step instead, and checks that it changed nothing the draw again leaves and, +//! rebound, worked out what every step works out (the modules' checks), so these tests run those +//! checks 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 @@ -21,6 +25,7 @@ use crate::{ DeviceOptions, Error, MessageSink, Origin, PipelineOptions, RenderCommandEncoder, RenderPipelineState, ResourceOptions, ShaderCacheOptions, Size, TextureDescriptor, WorkCounts, }; +use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{BlendFactor, IndexType, PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use std::collections::BTreeMap; @@ -497,3 +502,104 @@ fn a_notice_announced_at_each_occurrence_is_announced_at_every_draw() { } } } + +/// The rectangles of [`offset_rectangles`]' draws, 16 bytes apart: the `at`th from column `at` of +/// the target to its right edge, so that each column shows how many draws reached it. +fn rectangles_from_columns(device: &Device) -> Buffer { + let rectangles: Vec = (0..DRAWS) + .flat_map(|at| [-1.0 + at as f32 * 2.0 / SIDE as f32, -1.0, 1.0, 1.0]) + .collect(); + let bytes = bytes_of(&rectangles, f32::to_le_bytes); + device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap() +} + +/// [`DRAWS`] draws of `state`'s rectangle, the `at`th of the rectangle at `16 * at` bytes of +/// `rectangles` (vertex buffer 0's offset set before each draw but the first) in the color +/// `color(at)` (fragment bytes 0, set before each draw), with `between` called after them. +fn offset_rectangles( + encoder: &mut RenderCommandEncoder, + (state, rectangles): (&RenderPipelineState, &Buffer), + color: impl Fn(u64) -> f32, + between: impl Fn(&mut RenderCommandEncoder), +) { + encoder.set_render_pipeline_state(state).unwrap(); + encoder.set_vertex_buffer(Some(rectangles), 0, 0).unwrap(); + for at in 0..DRAWS { + if at > 0 { + encoder.set_vertex_buffer_offset(16 * at, 0).unwrap(); + between(encoder); + } + let bytes = bytes_of(&[color(at); 4], f32::to_le_bytes); + encoder.set_fragment_bytes(&bytes, 0).unwrap(); + rectangle(encoder); + } +} + +/// Draws after calls that bound other offsets and bytes at buffer slots their functions read +/// rebind those slots alone (`WorkCounts::draws_rebound`), with the same commands of every kind, +/// 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; at another offset each and in another color each, as each column's +/// count of draws and each draw's color show. A call that changed a slot of another class between +/// them (a sampler, which the functions do not read) takes every step. +#[test] +fn draws_after_buffer_changes_rebind_what_every_step_binds() { + let scratch = Scratch::new("draw-again-rebound"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + let rectangles = rectangles_from_columns(&device); + let sampler = device.new_sampler_state(&SamplerDescriptor::new()).unwrap(); + let same_color = + |encoder: &mut RenderCommandEncoder| encoder.set_blend_color(0.0, 0.0, 0.0, 0.0); + let a_sampler = |encoder: &mut RenderCommandEncoder| { + encoder + .set_fragment_sampler_state(Some(&sampler), 0) + .unwrap(); + }; + let one = |_| 1.0 / 64.0; + let each = |at| (at + 1) as f32 / 64.0; + let drawn = (&state, &rectangles); + warm(&device, |encoder| { + offset_rectangles(encoder, drawn, one, |_| {}) + }); + let rebound_count = |counts: &WorkCounts| counts.draws_rebound; + let as_before = |counts: &WorkCounts| counts.draws_as_before; + for color in [&one as &dyn Fn(u64) -> f32, &each] { + let rebound = run(&device, |encoder| { + offset_rectangles(encoder, drawn, color, |_| {}); + }); + let every = run(&device, |encoder| { + offset_rectangles(encoder, drawn, color, same_color); + }); + let sampled = run(&device, |encoder| { + offset_rectangles(encoder, drawn, color, a_sampler); + }); + assert_eq!(rebound.counted(rebound_count), drawn_alone(HITS)); + assert_eq!(rebound.counted(as_before), 0); + assert_eq!(every.counted(rebound_count), 0); + assert_eq!(sampled.counted(rebound_count), 0); + assert_eq!(rebound.commands, every.commands); + assert_eq!(rebound.commands, sampled.commands); + assert_eq!(rebound.commands["cmd_draw"], DRAWS); + assert_eq!(rebound.words, every.words, "the pixels of the draws"); + assert_eq!(rebound.words, sampled.words, "the pixels of the draws"); + 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!(rebound.counted(count), every.counted(count), "{name}"); + } + // Column 0 holds the first draw's color alone; the last column every draw's. + let last = SIDE as usize - 1; + assert_ne!(rebound.words[0], rebound.words[last], "the draws' offsets"); + } +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 7843dbf69..acaebabcb 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -284,6 +284,7 @@ pub(crate) struct Counters { draw_shapes_reused: AtomicU64, draw_shapes_carried: AtomicU64, draws_as_before: AtomicU64, + draws_rebound: AtomicU64, host_holds_looked_up: AtomicU64, dispatches_settled_as_before: AtomicU64, dispatches_planned_as_before: AtomicU64, @@ -1987,6 +1988,15 @@ impl Counters { } } + /// `draws` render draws rebound (`WorkCounts::draws_rebound`), whose stage tables `tables` + /// reads brought in part: counted at their encoder's next call or its end. + pub(crate) fn draws_rebound(&self, draws: u64, tables: u64) { + self.draws_rebound.fetch_add(draws, Ordering::Relaxed); + self.stage_tables_read.fetch_add(tables, Ordering::Relaxed); + self.stage_tables_read_in_part + .fetch_add(tables, 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) { @@ -4559,6 +4569,19 @@ pub struct WorkCounts { /// 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, + /// Render encoders' direct draws recorded as their encoder's last draw again after calls + /// that bound other buffers, offsets or bytes at vertex or fragment buffer slots, rather than + /// taking every step of a draw: a draw that `draws_as_before` would count but for those + /// calls, where the bind state kept its shape, the slots are read through set-0 descriptors + /// (dynamic or pushed), push fields or fixed-function vertex buffers alone, and the uses they + /// make need no barrier, copy or shadow (`render/draw_again/rebound.rs`). Each reads its + /// changed stage tables in part (`stage_tables_read_in_part`), writes again only those slots' + /// descriptors, dynamic offsets, push fields and vertex buffers, notes its uses as any draw + /// does, and records the state commands that changed (`draw_states_recorded`) and its draw; + /// it takes nothing of the shape memo (`draw_shapes_reused`) and settles nothing. Its counts + /// of draws, tables read and states recorded are counted at the encoder's next call or its + /// end. + pub draws_rebound: 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 @@ -5845,6 +5868,7 @@ impl Device { 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), + draws_rebound: counters.draws_rebound.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/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 9b6e386a6..70a820cc1 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2792,6 +2792,29 @@ impl BindingPlan { } instantiate(t, state, draw, commands) } + + /// [`instantiate_draw_into`](Self::instantiate_draw_into)'s commands of `state`, written over + /// `commands`, which hold that method's commands of the same draw of a state that differed + /// from `state` only in what the buffer slots `slots` bind (a buffer or inline bytes, at any + /// offset), the state's shape the same: only what those slots decide is written again (their + /// descriptor ranges, the `SlotBindOffset`, `SlotGuestBase` and pulled-stride push fields that + /// read them, and their fixed-function vertex buffers' offsets), so the commands are those + /// `instantiate_draw_into` writes. `Ok(false)` where the plan or the draw reads one of them + /// some other way (a device-address slot, an argument or root table, a fixed-function binding + /// of a per-bind stride, a mesh, patch or de-indexed draw, a uniform view a written slot may + /// alias): `commands` then hold no draw's commands, as after an error, and the caller + /// instantiates whole. An error is one `instantiate_draw_into` may answer for `state`. + pub fn rebind_draw_buffers_into( + &self, + state: &BindState, + slots: &[SlotRef], + commands: &mut DrawCommands, + ) -> Result { + match self.graphics.as_ref() { + Some(t) if !t.other_layer_variant => rebind_buffers(t, state, slots, commands), + _ => Ok(false), + } + } } /// The Vulkan draw of a Metal draw, and the base vertex and first instance the @@ -4446,31 +4469,7 @@ fn instantiate( }; FieldBytes::of(&word.to_le_bytes()) } - PushField::VertexBufferStride(layout) => { - let fixed = t.pulled_strides.iter().find(|(l, _)| *l == layout); - let stride = match (fixed, vertex.and_then(|v| v.buffers.get(&layout))) { - (Some(&(_, s)), _) => s, - ( - None, - Some(&BoundBuffer::Buffer { - attribute_stride, .. - }), - ) => attribute_stride.unwrap_or(0), - ( - None, - Some(&BoundBuffer::Bytes { - attribute_stride, .. - }), - ) => bytes_stride(attribute_stride, vertex_buffer(layout))?, - _ => { - return Err(internal(format!( - "the bind state's shape differs from the plan's at vertex \ - buffer {layout}" - ))) - } - }; - FieldBytes::of(&stride.to_le_bytes()) - } + PushField::VertexBufferStride(layout) => pulled_stride(t, state, layout)?, field => slot_field(field, &bound.residuals, &t.resources, state) .ok_or_else(|| internal(format!("a render push field {field:?}")))?, }; @@ -4673,6 +4672,171 @@ fn instantiate( Ok(()) } +/// `PushField::VertexBufferStride(layout)`: the stride the pulled layout `layout` reads, the +/// pipeline's where it is static, else the vertex buffer's bind's there. +fn pulled_stride( + t: &GraphicsTemplate, + state: &BindState, + layout: u32, +) -> Result { + let fixed = t.pulled_strides.iter().find(|(l, _)| *l == layout); + let vertex = state.stages.get(&Stage::Vertex); + let stride = match (fixed, vertex.and_then(|v| v.buffers.get(&layout))) { + (Some(&(_, s)), _) => s, + ( + None, + Some(&BoundBuffer::Buffer { + attribute_stride, .. + }), + ) => attribute_stride.unwrap_or(0), + ( + None, + Some(&BoundBuffer::Bytes { + attribute_stride, .. + }), + ) => bytes_stride(attribute_stride, vertex_buffer(layout))?, + _ => { + return Err(internal(format!( + "the bind state's shape differs from the plan's at vertex buffer {layout}" + ))) + } + }; + Ok(FieldBytes::of(&stride.to_le_bytes())) +} + +/// [`BindingPlan::rebind_draw_buffers_into`] of a render plan's template `t`. +fn rebind_buffers( + t: &GraphicsTemplate, + state: &BindState, + slots: &[SlotRef], + out: &mut DrawCommands, +) -> Result { + let changed = |slot: SlotRef| slot.class == SlotClass::Buffer && slots.contains(&slot); + // What the slots decide some other way than below: an argument table's bytes or a root + // table, a mesh or patch draw's own reads, a de-indexed draw's layout, and a uniform view a + // written slot may alias. + let other_reads = !out.descriptor_bytes.is_empty() + || !out.root_tables.is_empty() + || t.stages + .iter() + .any(|st| st.root_first.is_some() || st.table.is_some()) + || t.mesh.is_some() + || t.tessellation.is_some() + || t.deindexed.is_some() + || (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write)); + if other_reads || !slots.iter().all(|&slot| slot.class == SlotClass::Buffer) { + return Ok(false); + } + // Each changed descriptor-form slot's range, at its place among the bound ones' (in + // `bind_buffers`' order), and its residual. + let mut residuals = crate::bind::instantiate::Residuals::default(); + let mut at = 0; + for pb in &t.buffers { + let bound = crate::bind::instantiate::bound_buffer(state, pb.slot, pb.bound)?; + let (bind_offset, length) = match bound { + Some(&BoundBuffer::Buffer { length, offset, .. }) => (offset, length), + Some(&BoundBuffer::Bytes { len, .. }) => (0, u64::from(len.max(1))), + None => continue, + }; + let (set, binding) = match (pb.form, pb.binding) { + (BufferForm::Descriptor(_), Some(key)) => key, + // A device-address slot's root entry. + _ if changed(pb.slot) => return Ok(false), + _ => continue, + }; + let place = at; + at += 1; + if !changed(pb.slot) { + continue; + } + let (range, residual) = + descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range).map_err( + |e| match e { + RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { + slot: pb.slot, + needed, + limit: pb.max_range, + }, + RangeError::Empty => { + BindError::Unsupported(Unsupported::not_representable(Feature::BufferRange)) + } + }, + )?; + let Some(written) = out + .descriptor_ranges + .get_mut(place) + .filter(|r| (r.set, r.binding) == (set, binding)) + else { + return Ok(false); + }; + written.range = range; + residuals.push(pb.slot, residual); + } + // The push fields that read them, in each stage's push write. + let mut pushes = 0; + for st in &t.stages { + let (push_start, push_size) = st.push_range.unwrap_or((0, 0)); + let push = match push_size { + 0 => None, + _ => { + pushes += 1; + Some(pushes - 1) + } + }; + for f in &st.fields { + let bytes = match f.field { + PushField::SlotBindOffset(slot) | PushField::SlotGuestBase(slot) + if changed(slot) => + { + slot_field(f.field, &residuals, &t.resources, state) + .ok_or_else(|| internal(format!("a render push field {:?}", f.field)))? + } + PushField::VertexBufferStride(layout) + if changed(SlotRef { + stage: Stage::Vertex, + class: SlotClass::Buffer, + index: layout, + }) => + { + pulled_stride(t, state, layout)? + } + _ => continue, + }; + let Some(write) = push.and_then(|at| out.push_constants.get_mut(at)) else { + return Ok(false); + }; + put(&mut write.bytes, push_start, &mut [], f.loc, &bytes)?; + } + } + // Each changed fixed-function vertex buffer's offset, at its binding's place (bound in + // `t.vertex_buffers`' order); a per-bind stride's binding, whose extent and stride may move + // with it, is written whole. + let vertex = state.stages.get(&Stage::Vertex); + for (place, vb) in t.vertex_buffers.iter().enumerate() { + if !changed(vb.slot) { + continue; + } + let offset = match vertex.and_then(|v| v.buffers.get(&vb.slot.index)) { + Some(&BoundBuffer::Buffer { offset, .. }) => offset, + Some(&BoundBuffer::Bytes { .. }) => 0, + None => return Err(BindError::UnboundVertexBuffer { slot: vb.slot }), + }; + let fetched = fetchable(vb, &t.vertex_strides, offset_alignment(offset, 0), None); + if matches!(vb.stride, VertexStride::PerBind) || !fetched { + return Ok(false); + } + let Some(written) = out + .buffer_offsets + .get_mut(place) + .filter(|(binding, _)| *binding == vb.binding) + else { + return Ok(false); + }; + written.1 = offset; + } + Ok(true) +} + /// The `at`th value of `list`, which holds at least `at`: the one a draw before left there, else /// `made`, pushed. fn reused(list: &mut Vec, at: usize, made: impl FnOnce() -> T) -> &mut T { diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index 9b2698468..4feedd889 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -534,7 +534,7 @@ pub(crate) struct Residuals { impl Residuals { /// Add `slot`'s residual last. - fn push(&mut self, slot: SlotRef, residual: u32) { + pub(crate) fn push(&mut self, slot: SlotRef, residual: u32) { match self.inline.iter_mut().find(|r| r.is_none()) { Some(free) => *free = Some((slot, residual)), None => self.rest.push((slot, residual)), diff --git a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs index 036e2ad06..30d295526 100644 --- a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs @@ -969,6 +969,94 @@ fn a_per_bind_stride_comes_from_the_bind() { } /// `state` with vertex-stage buffer 0 replaced by `b`. +/// A rebind of buffer slots writes over a draw's commands the commands a whole instantiation of +/// the new state writes: for each committed profile, each state of the vertex buffer and the +/// constant buffer at other offsets and over other allocations that keeps the plan's shape, the +/// commands of the first state rebound at the slots that changed are the new state's. Where the +/// rebind writes nothing (`Ok(false)`), the plan reads a slot some other way. +#[test] +fn a_rebind_of_buffer_slots_writes_what_an_instantiation_writes() { + let Some(bc) = fixture("stage_io") else { + return; + }; + let (vertex, scale) = ( + slot(Stage::Vertex, SlotClass::Buffer, 0), + slot(Stage::Vertex, SlotClass::Buffer, 1), + ); + let draw = DrawCall::Primitives { + vertex_start: 3, + vertex_count: 6, + instance_count: 2, + base_instance: 5, + }; + // The same allocation's length and offset at another address. + let elsewhere = |b: BoundBuffer| match b { + BoundBuffer::Buffer { + length, + offset, + device_address, + attribute_stride, + .. + } => BoundBuffer::Buffer { + length, + offset, + gpu_address: 0x7_0000, + device_address, + attribute_stride, + }, + other => other, + }; + let (mut rebound, mut pushed, mut whole) = (0, 0, 0); + for (stem, dev) in devices() { + let Ok(p) = render_pipeline(&dev, &bc) else { + continue; + }; + // From a constant at an aligned offset, and at one a residual reaches. + for first in [render_state(16), render_state(4)] { + let Ok(plan) = p.plan(&dev, &first.shape()) else { + continue; + }; + let scales = [0, 4, 16, 20, 36, 48, 100, 240, 256]; + let vertices = [0, 24, 48, 72, 96, 2400]; + let cases = scales + .iter() + .flat_map(|&s| vertices.iter().map(move |&v| (s, v))); + for ((s, v), moved) in cases.flat_map(|c| [(c, false), (c, true)]) { + let mut state = render_state(s); + let table = state.stages.get_mut(&Stage::Vertex).expect("vertex"); + table.buffers.insert(0, buffer(24 * 64 + v, v, None)); + if moved { + let b = table.buffers.get(&1).copied().expect("scale"); + table.buffers.insert(1, elsewhere(b)); + } + if state.shape() != first.shape() { + continue; + } + let before = plan.instantiate_draw(&first, &draw).expect("first draw"); + let expected = plan.instantiate_draw(&state, &draw); + let mut cmds = before.clone(); + match plan.rebind_draw_buffers_into(&state, &[vertex, scale], &mut cmds) { + Ok(true) => { + rebound += 1; + pushed += usize::from(cmds.push_constants != before.push_constants); + assert_eq!(Ok(&cmds), expected.as_ref(), "{stem} {s} {v} {moved}"); + } + Ok(false) => whole += 1, + Err(e) => assert_eq!(Err(e), expected, "{stem} {s} {v} {moved}"), + } + } + } + } + assert!( + rebound > 0, + "no rebind wrote commands ({whole} instantiated whole)" + ); + assert!( + pushed > 0, + "no rebind wrote a push field ({rebound} rebound)" + ); +} + fn with_vertex_buffer(state: &BindState, b: BoundBuffer) -> BindState { let mut s = state.clone(); s.stages diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 454869fd0..7a7943c1f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2611,6 +2611,7 @@ 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 +field metal2vulkan-runtime::WorkCounts.draws_rebound pub draws_rebound: u64 field metal2vulkan-runtime::WorkCounts.draws_settled pub draws_settled: u64 field metal2vulkan-runtime::WorkCounts.driver_diagnostics_withheld pub driver_diagnostics_withheld: u64 field metal2vulkan-runtime::WorkCounts.empty_memory_blocks_live pub empty_memory_blocks_live: u64 @@ -8426,6 +8427,7 @@ method metal2vulkan::bind::BindingPlan::instantiate_dispatch pub fn instantiate_ method metal2vulkan::bind::BindingPlan::instantiate_draw pub fn instantiate_draw(&self, state: &BindState, draw: &DrawCall) -> Result method metal2vulkan::bind::BindingPlan::instantiate_draw_into pub fn instantiate_draw_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError> method metal2vulkan::bind::BindingPlan::instantiate_replay pub fn instantiate_replay(&self, state: &BindState, threads_per_group: [u32; 3]) -> Result +method metal2vulkan::bind::BindingPlan::rebind_draw_buffers_into pub fn rebind_draw_buffers_into(&self, state: &BindState, slots: &[SlotRef], commands: &mut DrawCommands) -> Result method metal2vulkan::bind::BindingPlan::relisted_sampler_tables pub fn relisted_sampler_tables(&self, device: &crate::device::Device, samplers: &[crate::bind::ArgumentSampler], placement: HeapPlacement) -> Result>, BindError> method metal2vulkan::bind::BindingPlan::sampler_tables pub fn sampler_tables(&self) -> Vec<(u32, u32)> method metal2vulkan::bind::BindingPlan::specialized_value pub fn specialized_value(&self, key: SpecKey) -> Option diff --git a/docs/API.md b/docs/API.md index 78e8ae628..8924af37c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1049,6 +1049,13 @@ let commands = plan.instantiate_draw(&state, &draw)?; its vectors already hold: keep one from draw to draw (`DrawCommands::default()` to start) and the draws allocate none of it again once it holds as much. +`rebind_draw_buffers_into` writes again only what some buffer slots decide, over the commands of +the same draw of a state of the same shape that differed only in what those slots bind: their +descriptor ranges, the push fields that read them and their vertex buffers' offsets. It answers +`Ok(false)` where the plan reads one of them some other way (a device address, an argument or +root table, a vertex binding of a per-bind stride, a mesh, patch or de-indexed draw) or a uniform +view a written slot may alias; then instantiate the draw whole. + A dispatch is one or more regions (a grid that is not whole threadgroups adds edge regions), each with its group count, specialization and push constants: create one `VkPipeline` per distinct specialization. A kernel that steps a stage-in attribute by thread position, or reads