diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 27ce281db..e773b7aa0 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -63,8 +63,17 @@ pub(super) const ATTRIBUTE_STRIDE_STATIC: u64 = u64::MAX; /// limit for inline bytes, 4 KiB. pub(super) const INLINE_BYTES_LIMIT: u64 = 4096; + /// Whether `stage`'s slots are `slots` (none for a stage it does not keep): a table read under + /// them that binds the same offsets leaves the same out ([`ArgumentTable::at_bind_views`]), + /// as it left out its own as it was read. + pub(super) fn holds(&self, stage: Stage, slots: u64) -> bool { + self.of(stage) + .map_or(0, |kept| kept.load(Ordering::Relaxed)) + == slots + } + /// One stage's bound objects, by Metal index. -#[derive(Clone, Default)] +#[derive(Default)] pub(super) struct ArgumentTable { /// A compute encoder's table ([`ArgumentTable::compute`]): it holds buffers bound past their /// length and takes an offset at an index with no buffer as no change (the module docs). @@ -93,6 +102,49 @@ pub(super) struct ArgumentTable { pub(super) bytes: BTreeMap, /// What the table bound as an encoder's core last retained it ([`retain`](Self::retain)). retained: Retained, + /// Its contents' stamp, drawn afresh by every call that may change them. + stamp: Stamp, +} + +/// A copy binds what the table binds, under a stamp of its own: a copy changed in place (a +/// pass's copies of bytes its fragment stages wrote: `render/pass_start_reads.rs`) binds others. +impl Clone for ArgumentTable { + fn clone(&self) -> ArgumentTable { + ArgumentTable { + compute: self.compute, + buffers: self.buffers.clone(), + function_tables: self.function_tables.clone(), + null_tables: self.null_tables.clone(), + attribute_strides: self.attribute_strides.clone(), + textures: self.textures.clone(), + samplers: self.samplers.clone(), + bytes: self.bytes.clone(), + retained: self.retained.clone(), + stamp: Stamp::fresh(), + } + } +} + +/// What an argument table binds, named by a number drawn afresh for each new table (a copy +/// included) and at each call that may change what it binds, which no other table of the process +/// takes ([`ArgumentTable::stamp`]): while a table's stamp holds, it binds what it bound, by +/// identity. A table made for one command (an execution's own buffers) is filled in place before +/// any command reads it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Stamp(u64); + +impl Stamp { + /// A stamp no table took before. + fn fresh() -> Stamp { + static NEXT: AtomicU64 = AtomicU64::new(0); + Stamp(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + +impl Default for Stamp { + fn default() -> Stamp { + Stamp::fresh() + } } /// The core an argument table was last retained into ([`EncoderCore::id`]) and the objects it @@ -112,6 +164,8 @@ impl Clone for Retained { #[derive(Clone, Default)] struct RetainedBy { core: Option, + /// The table's stamp then: while it holds, the table binds those objects still. + stamp: Option, /// Each object's slot (its table, then its index) and address; its storage is kept from /// one retain to the next. bound: Vec<((SlotClass, u32), usize)>, @@ -312,6 +366,11 @@ impl ArgumentTable { } } + /// The stamp of what the table binds now ([`Stamp`]). + pub(super) fn stamp(&self) -> Stamp { + self.stamp + } + /// Refuse `buffer` at `offset` in `call` of an encoder of `core`: a buffer of another device, /// and, in a render stage's table, an offset past its length (a compute table holds it). fn check_buffer( @@ -355,6 +414,7 @@ impl ArgumentTable { stride: u64, index: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); check_index(call, index, BUFFER_SLOTS)?; let stride = attribute_stride(stride); if let Some(buffer) = buffer { @@ -397,6 +457,7 @@ impl ArgumentTable { strides: Option<&[u64]>, first: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); if buffers.len() != offsets.len() || strides.is_some_and(|s| s.len() != buffers.len()) { return Err(invalid(call, Problem::LengthMismatch)); } @@ -457,6 +518,7 @@ impl ArgumentTable { stride: u64, index: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); check_index(call, index, BUFFER_SLOTS)?; let stride = attribute_stride(stride); if let Some(len) = self.bytes.get(&index).map(|bytes| bytes.len) { @@ -522,6 +584,7 @@ impl ArgumentTable { stride: Option, index: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); check_index(call, index, BUFFER_SLOTS)?; let length = bytes.len() as u64; if length > INLINE_BYTES_LIMIT { @@ -571,6 +634,7 @@ impl ArgumentTable { textures: &[Option<&Texture>], first: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); check_range(call, first, textures.len(), TEXTURE_SLOTS)?; for texture in textures.iter().flatten() { core.check_device(call, texture.device())?; @@ -596,6 +660,7 @@ impl ArgumentTable { clamps: Option<(&[f32], &[f32])>, first: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); if let Some((min, max)) = clamps { if min.len() != samplers.len() || max.len() != samplers.len() { return Err(invalid(call, Problem::LengthMismatch)); @@ -625,6 +690,7 @@ impl ArgumentTable { tables: &[Option<&VisibleFunctionTable>], first: u32, ) -> Result<(), Error> { + self.stamp = Stamp::fresh(); check_range(call, first, tables.len(), BUFFER_SLOTS)?; for table in tables.iter().flatten() { core.check_device(call, table.device())?; @@ -870,16 +936,17 @@ impl ArgumentTable { self.check_reading(kept, read, maps); } - /// That `kept`, brought in place by [`refresh_reading`](Self::refresh_reading), is the table - /// `stage`'s function of `interface` reads whole - /// ([`stage_table_reading`](Self::stage_table_reading)), each sampler as `maps` binds it - /// (debug builds): the same slots, each bound alike as its value prints (a float's sign told - /// apart, every NaN alike: [`same_as_printed`]), and nothing else in the table. Compared slot - /// by slot, with no table read whole made and nothing printed unless a slot differs, so a + /// That `kept`, brought in place by [`refresh_reading`](Self::refresh_reading) (or kept unread + /// while nothing it reads changed: `live_bind::ReadFrom`), is the table `stage`'s function of + /// `interface` reads whole ([`stage_table_reading`](Self::stage_table_reading)), each sampler + /// as `maps` binds it and its slots that tell the view base alignment apart as `views` leaves + /// them (debug builds): the same slots, each bound alike as its value prints (a float's sign + /// told apart, every NaN alike: [`same_as_printed`]), and nothing else in the table. Compared + /// slot by slot, with no table read whole made and nothing printed unless a slot differs, so a /// draw allocates as many times with debug assertions as without (`runtime_lane::frame_costs` /// holds its bound in every build). A slot that differs is named in the panic. #[cfg(debug_assertions)] - fn check_reading( + pub(super) fn check_reading( &self, kept: &StageTable, read: (Stage, &PipelineInterface), @@ -975,30 +1042,15 @@ impl ArgumentTable { /// Hold everything bound until `core`'s command buffer completes: a command uses it, and /// the command buffer lists it among its used resources (`used_resources.rs`). Once while it /// binds the same objects: where `core` retained the table before and it binds exactly the - /// objects it bound then (by identity), `core` holds them and keeps their keys, each a function - /// of its object, until the command buffer completes, so nothing is retained again. Where it - /// binds others, `core` holds each object the table bound at its slot then already, and takes - /// the rest, each by another reference to it (`retained.rs`): its last first, so they go in - /// the table's order, as one hold of them all went. + /// objects it bound then (by identity; at once where its stamp is the one it had then, else + /// slot by slot), `core` holds them and keeps their keys, each a function of its object, until + /// the command buffer completes, so nothing is retained again. Where it binds others, `core` + /// holds each object the table bound at its slot then already, and takes the rest, each by + /// another reference to it (`retained.rs`): its last first, so they go in the table's order, + /// as one hold of them all went. pub(super) fn retain(&self, core: &mut EncoderCore) { let mut retained = lock(&self.retained.0); - let now = self.bound().map(|(slot, object)| (slot, object.address())); - if retained.core == Some(core.id()) && retained.bound.iter().copied().eq(now) { - return; - } - let keys = self.buffers.values().map(|(b, _)| b.identity().key); - let texture_keys = self.textures.values().map(Texture::use_key); - core.touch_keys(keys.chain(texture_keys)); - for (slot, object) in self.bound().rev() { - if !retained.holds(core, slot, object) { - core.retain_shared(object.held()); - } - } - let RetainedBy { core: by, bound } = &mut *retained; - bound.clear(); - bound.extend(self.bound().map(|(slot, object)| (slot, object.address()))); - *by = Some(core.id()); - core.device().shared().counts.argument_table_retained(); + stamp, } /// Let go of `object`, which the table bound at `slot` until a call replaced or unbound it: diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 8b412c98f..feda2f884 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -49,6 +49,7 @@ use super::address_map::SamplerMaps; use super::argument_table::{ArgumentTable, InlineBytes}; use super::buffer::Buffer; use super::command_buffer::{NotedTable, State}; +use super::device::lock; use super::error::{internal, Error, RuntimeGap}; use super::function_table::{self, TableSnapshot, VisibleFunctionTable}; use super::heap_sets::{Keeper, TextureTable, HEAP_SET}; @@ -58,7 +59,7 @@ use super::render_target; use super::residency::{Residency, Used}; use super::resource::ResourceKey; use super::sampler::{OwnedSampler, SamplerState}; -use super::texture::Texture; +use super::texture::{Texture, TextureShared}; use super::tracker::{Access, Use, UseRange}; use super::upload::Upload; use super::Device; @@ -74,7 +75,7 @@ use metal2vulkan::pipeline::{HandleClass, SlotClass, SlotRef, Stage, StorageAtta use std::collections::BTreeSet; use std::ops::Deref; use std::sync::atomic::Ordering; -use std::sync::Arc; +use std::sync::{Arc, Mutex, Weak}; /// What an encoder binds: each stage's argument table. pub(super) struct Tables<'a> { @@ -453,9 +454,9 @@ pub(super) struct Hole { address: u64, } -/// What a command records besides its pipeline and its draw or groups. +/// What a command records besides its pipeline, its draw or groups, and its descriptor writes +/// ([`bind`]'s). pub(super) struct Bound { - pub(super) writes: Vec, /// The push holes' addresses, for [`push_writes`]. pub(super) holes: Vec, /// The Vulkan samplers the writes name, which the command buffer holds until it completes. @@ -516,7 +517,9 @@ fn padded(n: usize) -> u64 { } /// The descriptors, uploads, and push hole addresses of `command`, a command (by `call`) of -/// `plan` over `tables`, uploading into the command buffer's `state`. +/// `plan` over `tables`, uploading into the command buffer's `state`: the descriptor writes in +/// `writes`, emptied first, so a caller that keeps the vector writes each command's over the last +/// one's storage (a draw's, `LiveBind::writes`). pub(super) fn bind( call: &'static str, device: &Device, @@ -524,9 +527,10 @@ pub(super) fn bind( plan: &BindingPlan, command: &Command<'_>, tables: &Tables<'_>, - mut memo: Option<&mut BindMemo>, + (mut memo, writes): (Option<&mut BindMemo>, &mut Vec), ) -> Result { - let mut writes = Vec::with_capacity(plan.descriptors.len()); + writes.clear(); + writes.reserve(plan.descriptors.len()); let mut samplers = Vec::new(); // The sampler tables, whose regions the command buffer writes again as it commits. let sampler_keys = plan.sampler_tables(); @@ -670,7 +674,6 @@ pub(super) fn bind( }); } Ok(Bound { - writes, holes, samplers, sampler_tables, @@ -835,7 +838,22 @@ pub(super) fn push_writes( let at = (hole.offset - write.1) as usize; write.2[at..at + 8].copy_from_slice(&hole.address.to_le_bytes()); } - Ok(filled) + let mut pushed = Vec::new(); + Self::push_into(writes, immutable, &mut pushed); + pushed + } + + /// [`pushed`](Self::pushed) in `pushed`, emptied first: over the last draw's storage, where + /// the caller keeps it (`LiveBind::pushed`). + pub(super) fn push_into(writes: &[Write], immutable: &[SetWrite], pushed: &mut Vec) { + pushed.clear(); + let writes = writes.iter().map(|write| SetWrite { + binding: write.binding, + element: write.element, + ty: write.ty, + info: write.info, + }); + pushed.extend(writes.chain(immutable.iter().copied())); } /// The descriptor writes [`write_sets`] hands the driver in one call: their infos sit on the stack. @@ -932,10 +950,12 @@ const KEPT: usize = 8; /// holds (a page's tiles) finds every one it bound before. const KEPT_VIEWS: usize = 256; -/// The image views and samplers a render encoder's last binds made or found +/// The image views and samplers render encoders' last binds made or found /// ([`image_descriptor`]), kept by everything each is a function of, so that a bind of the same -/// takes them again without working them out (the encoder's, dropped with it, so it keeps -/// nothing alive past the textures its draws retain): +/// takes them again without working them out. An encoder that ends gives its memo to its device +/// ([`SpareBindMemos`]), and the next render encoder opened takes it, so a pass that binds the +/// textures and samplers the one before it bound works none out. A memo holds its textures +/// weakly, so it keeps none alive: /// /// - **A view** of a texture slot is a function of the texture (its storage, image, decoded and /// depth twins and record are fixed as it is made; its usage shadow is made once and kept), the @@ -943,7 +963,8 @@ const KEPT_VIEWS: usize = 256; /// image keeps once made until it lets them all go under its views lock (a rebind's or a /// storage form's new `VkImage`, a detach's stand-in, a reattach). Each letting go counts in /// `DeviceShared::views_epoch`: the views are kept while it holds, and all dropped once it -/// moves. +/// moves. A view is kept by its texture's address ([`KeptView`]), which stays the texture's +/// while the memo keeps the view: a texture found there is the one the view is of. /// - **A sampler's description** (`sampler_desc`'s answer) for a sampler slot is a function of /// the descriptor the bind maps the slot's state to (its LOD clamps and the address modes its /// textures map), the facts `sampler_desc` takes beside the device (the use: a comparison, an @@ -952,20 +973,53 @@ const KEPT_VIEWS: usize = 256; /// state for its `VkSampler` of the description (`SamplerState::vk_sampler`), so the state keeps /// and forgets its samplers as before. /// -/// A view's key holds its texture, so one seen again is the same object; a sampler's -/// descriptor is compared exactly, a float field by its bits. +/// A sampler's descriptor is compared exactly, a float field by its bits. #[derive(Default)] pub(super) struct BindMemo { /// The views epoch the views were kept under. epoch: u64, - views: KeyMap, + views: KeyMap, samplers: Vec, } -/// What a view a bind made or found is a function of ([`BindMemo`]): a binding of the texture as -/// the view, a storage one where the first flag is set, of a texture the draw's instance renders -/// where the second is (`Tables::attached`). -type ViewKey = (Texture, ImageViewDesc, bool, bool); +/// What a view a bind made or found is a function of ([`BindMemo`]): a binding of the texture at +/// the address as the view, a storage one where the first flag is set, of a texture the draw's +/// instance renders where the second is (`Tables::attached`). +type ViewKey = (usize, ImageViewDesc, bool, bool); + +/// A view a [`BindMemo`] keeps, and its texture, held weakly: a texture that goes leaves its +/// allocation, and so its address, to its weak handles, so no other texture is at the address +/// while the view is kept. +struct KeptView { + texture: Weak, + raw: vk::ImageView, +} + +/// The most bind memos a device keeps for its render encoders to take: one per encoder open at +/// once beyond it starts empty. +const SPARE_BIND_MEMOS: usize = 4; + +/// A device's bind memos that ended render encoders left, which the render encoders it opens +/// next take ([`BindMemo`]): at most [`SPARE_BIND_MEMOS`], the latest given taken first. +#[derive(Default)] +pub(super) struct SpareBindMemos(Mutex>); + +impl SpareBindMemos { + /// The memo a render encoder opening takes: the latest an encoder gave back, else an empty + /// one. + pub(super) fn take(&self) -> BindMemo { + lock(&self.0).pop().unwrap_or_default() + } + + /// Keep `memo`, an ended render encoder's, for the next encoder to take, where fewer than + /// [`SPARE_BIND_MEMOS`] are kept; else it goes. + pub(super) fn give(&self, memo: BindMemo) { + let mut spare = lock(&self.0); + if spare.len() < SPARE_BIND_MEMOS { + spare.push(memo); + } + } +} /// A sampler description a bind worked out ([`BindMemo`]): `descriptor`'s under `facts`. struct KeptSampler { @@ -1044,15 +1098,18 @@ fn image_descriptor( let Some(kept_views) = kept_views.as_deref_mut() else { return texture.slot_view(call, view, storage, attached); }; - let key = (texture.clone(), *view, storage, attached); - if let Some(raw) = kept_views.get(&key) { - return Ok(*raw); + let key = (texture.address(), *view, storage, attached); + if let Some(kept) = kept_views.get(&key) { + debug_assert_eq!(kept.texture.as_ptr() as usize, key.0); + return Ok(kept.raw); } + device.shared().counts.bind_view_worked_out(); let raw = texture.slot_view(call, view, storage, attached)?; if kept_views.len() == KEPT_VIEWS { kept_views.clear(); } - kept_views.insert(key, raw); + let texture = texture.downgrade(); + kept_views.insert(key, KeptView { texture, raw }); Ok::<_, Error>(raw) }; let mut sampler = |slot: SlotRef, use_: SamplerUse, opaque_black, format| { @@ -1588,7 +1645,24 @@ pub(super) fn command_uses( index: Option<(&Buffer, u64)>, indirect: Option<(&Buffer, u64)>, ) -> Result { - let mut uses = Vec::new(); + let mut uses = CommandUses::default(); + command_uses_into(call, (plan, command, tables), (index, indirect), &mut uses)?; + Ok(uses) +} + +/// [`command_uses`] in `into`, emptied first: over the last draw's storage, where the caller keeps +/// it (`LiveBind::uses`). +pub(super) fn command_uses_into( + call: &'static str, + (plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>), + (index, indirect): (Option<(&Buffer, u64)>, Option<(&Buffer, u64)>), + into: &mut CommandUses, +) -> Result<(), Error> { + let CommandUses { uses, resident } = into; + uses.clear(); + resident.clear(); + // One use at most a resource use of the plan's or the command's: room for them all at once. + uses.reserve(plan.uses.len() + command.uses.len()); // The keys of the buffers made resident the command reaches through the resident set, by // address; every other use names its resource (a descriptor, a root table's static, a view). // Those it names are gathered once it reaches one so: until then each use names its key. @@ -1712,15 +1786,15 @@ pub(super) fn command_uses( write: access(write, resource.access.write), }); } - let resident = reached.difference(&named).copied().collect(); - Ok(CommandUses { uses, resident }) + resident.extend(reached.difference(&named).copied()); + Ok(()) } /// A dispatch's or draw's uses (`command_uses`), for the tracker, and the keys among them that /// the command reaches through its root tables' resident set alone: buffers and heaps an encoder /// made resident, which no use of the command names. The encoder's core takes both /// (`EncoderCore::command_reaching`, `note_reaching`); a use added later names its key. -#[derive(Default)] +#[derive(Clone, Default)] pub(super) struct CommandUses { uses: Vec>, resident: BTreeSet, diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 520264cf5..ec7e2a1d6 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -239,6 +239,17 @@ impl TexturesOver { } } +/// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie +/// elsewhere ([`HostCell::replace`]: rebound or detached). +static HOST_CELLS_MOVED: AtomicU64 = AtomicU64::new(0); + +/// The count of the times a no-copy buffer of the process came to lie elsewhere (rebound or +/// detached) so far: while it holds, every buffer's binding is what it was (its base, its +/// addresses), which is what an encoder's kept bind state reads of them (`live_bind.rs`). +pub(super) fn host_cells_moved() -> u64 { + HOST_CELLS_MOVED.load(Ordering::Acquire) +} + /// A texture being made over a buffer's host pages ([`Buffer::making_texture`]): a detach /// refuses until it goes, once the texture is noted (`Buffer::note_texture`) or its making /// failed. @@ -358,7 +369,7 @@ impl HostCell { /// Lie `lying` from now on: where the buffer lay. pub(super) fn replace(&self, lying: Lying) -> Lying { - std::mem::replace(&mut *lock(&self.pages), lying) + lay } /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), forgetting those diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 9cb3a466c..3b2c6bea1 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1608,6 +1608,7 @@ fn record( } false => Vec::new(), }; + let mut writes = Vec::new(); let bound = { let mut state = core.command_buffer().state(); binding::bind( @@ -1617,7 +1618,7 @@ fn record( &plan, &command, &bound_tables, - None, + (None, &mut writes), )? }; let mut push = Vec::with_capacity(commands.regions.len()); @@ -1628,7 +1629,7 @@ fn record( let objects = std::sync::Arc::clone(variant.objects()); // Set 0 per dispatch; set 1 the device's (written below, once nothing refuses). let (heap_writes, writes): (Vec<_>, Vec<_>) = - bound.writes.into_iter().partition(|write| write.set > 0); + writes.into_iter().partition(|write| write.set > 0); let set = objects.set_zero(&mut core.command_buffer().state().descriptors)?; // The dispatch binds the variant: the kinds its making announces at every occurrence. let formats: BoundFormats<'_> = &|slot| bound_tables.bound_format(slot); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 75373f69d..f704a8c4c 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -3329,16 +3329,9 @@ impl Device { samplers: &[crate::SamplerState], ) { const NOTE: PrecisionNote = PrecisionNote::ArgumentPixelSamplerScaling; - let Some(stage) = stages.iter().find(|s| s.precision_notes.contains(&NOTE)) else { + let Some(stage) = self.argument_pixel_samplers_noted(stages) else { return; }; - if !self - .shared() - .announced - .pending(Degradation::ArgumentPixelSamplerScaling) - { - return; - } let Some(state) = samplers.iter().find(|s| s.scales_in_an_argument_buffer()) else { return; }; @@ -3356,6 +3349,23 @@ impl Device { }); } + /// The stage of `stages` whose note [`degrade_argument_pixel_samplers`] may announce: one + /// that records `PrecisionNote::ArgumentPixelSamplerScaling`, where the device has not + /// announced it yet; `None` where it would announce nothing, whatever the states. + /// + /// [`degrade_argument_pixel_samplers`]: Self::degrade_argument_pixel_samplers + pub(crate) fn argument_pixel_samplers_noted<'a>( + &self, + stages: &'a [StageModule], + ) -> Option<&'a StageModule> { + const NOTE: PrecisionNote = PrecisionNote::ArgumentPixelSamplerScaling; + let stage = stages.iter().find(|s| s.precision_notes.contains(&NOTE))?; + self.shared() + .announced + .pending(Degradation::ArgumentPixelSamplerScaling) + .then_some(stage) + } + /// Why `stage`, which records `note`, degrades: [`note_reason`](Self::note_reason)'s, and for /// `PrecisionNote::FunctionStorageAssumed` the private memory a thread of the stage keeps and /// the Function storage the device's profile holds, measured or the floor of a device not diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index fa0501193..18533208a 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -379,6 +379,11 @@ pub(super) struct DeviceShared { /// The command pools and descriptor pools command buffers that completed gave back, for the /// next to take (`spares.rs`). pub(super) spares: Spares, + /// The bind states its ended render encoders left, which the next ones start from + /// (`live_bind.rs`). + pub(super) live_binds: crate::live_bind::SpareLiveBinds, + /// The bind memos its ended render encoders left, which the next ones take (`binding.rs`). + pub(super) bind_memos: crate::binding::SpareBindMemos, /// Counts of its commit path's work, for the lanes (`work_counts.rs`). pub(super) counts: super::work_counts::Counters, /// Where the driver fails pending work as memory a device-address buffer lay in is freed, @@ -1393,6 +1398,8 @@ impl Device { host_copies, sparse, spares: Spares::default(), + live_binds: Default::default(), + bind_memos: Default::default(), counts: Default::default(), parking: parking.map_or_else(OnceLock::new, OnceLock::from), uncommitted: Arc::default(), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 1c46cf875..3b7e9ff76 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -34,6 +34,7 @@ use super::error::{internal, invalid, vulkan, CommandBufferError, Error, Problem use super::execution::Execution; use super::fresh_unwritten::FreshRead; use super::heap::Heap; +use super::noted_apart::{NotedApart, NotedInto}; use super::pending_dispatch::PendingDispatch; use super::rebind::{Holds, Taken}; use super::replay::Replay; @@ -861,12 +862,15 @@ impl EncoderCore { /// Note one command recorded outside the encoder's own `VkCommandBuffer` (a render encoder's /// draw, in its secondary command buffer) that runs in `stages` with `uses`. Only an /// unordered encoder's commands are recorded so: they need no barrier between them. Call it - /// before recording the command; it refuses (internal) an ordered encoder. + /// before recording the command; it refuses (internal) an ordered encoder. A draw noted with + /// the same uses, reaching the same keys through the resident set alone, as the last one + /// `noted` keeps (a render encoder's draws'), into the same state, is noted already + /// (`noted_apart.rs`); a command with no `noted` (a tile dispatch) is noted whole. pub(super) fn note_reaching( &mut self, stages: vk::PipelineStageFlags2, - uses: &[Use], - resident: &BTreeSet, + (uses, resident): (&[Use], &BTreeSet), + noted: Option<&mut NotedApart>, ) -> Result<(), Error> { if self.uses.ordered() { return Err(super::error::internal( @@ -874,10 +878,25 @@ impl EncoderCore { )); } self.observe_fresh(uses, &[]); - let aliased = self.aliased(uses); - self.uses - .record(stages, aliased.as_deref().unwrap_or(uses), None); + let Some(noted) = noted else { + 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(), + }; + if noted.holds(stages, (uses, resident), into) { + shared.counts.command_noted_as_before(); + return Ok(()); + } self.touch_reaching(uses, resident); + noted.note(stages, (uses, resident), into); Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/host_aliases.rs b/crates/metal2vulkan-runtime/src/host_aliases.rs index 5d4853297..ac79f3c14 100644 --- a/crates/metal2vulkan-runtime/src/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/host_aliases.rs @@ -82,7 +82,7 @@ use super::memory::MemoryClass; use super::resource::ResourceKey; use super::tracker::{Use, UseRange}; use std::collections::BTreeMap; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, Weak}; /// The key a buffer that joined another's memory adds to its uses: the memory's. @@ -101,6 +101,10 @@ pub(super) struct HostAliases { crowded: AtomicBool, /// How many memories are noted: with none, a reported remap has none to end. noted: AtomicUsize, + /// How many times the buffers that joined a memory or the placements changed: while it + /// stands, [`augment`](Self::augment) gives the same uses for the same uses + /// (`noted_apart.rs`). Each change counts once it is made, under the lock. + version: AtomicU64, inner: Mutex>, } @@ -110,6 +114,7 @@ impl Default for HostAliases { any: AtomicBool::new(false), crowded: AtomicBool::new(false), noted: AtomicUsize::new(0), + version: AtomicU64::new(0), inner: Mutex::new(Inner { made_over: KeyMap::default(), memories: Memories::default(), @@ -218,6 +223,7 @@ impl HostAliases { let alias = Alias { key: owner }; Arc::make_mut(aliases).insert(key, alias); self.any.store(true, Ordering::Relaxed); + self.changed(); Some(alias) } @@ -272,6 +278,7 @@ impl HostAliases { inner.placements.unplace(key); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + self.changed(); } /// The buffer of `key` (a no-copy buffer, or a no-copy heap's own buffer, whose uses are of @@ -284,6 +291,7 @@ impl HostAliases { inner.placements.place(key, at); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + self.changed(); } /// The buffer of `key` lies over no host bytes from now on (its bytes detached). @@ -292,6 +300,21 @@ impl HostAliases { inner.placements.unplace(key); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + self.changed(); + } + + /// Count a change of the buffers that joined a memory or of the placements, made under the + /// lock the caller holds ([`version`](Self::version)). + fn changed(&self) { + self.version.fetch_add(1, Ordering::Relaxed); + } + + /// How many times the buffers that joined a memory or the placements changed: two calls of + /// [`augment`](Self::augment) with the same uses, between which it stood, give the same + /// uses. A change made before a call (one the caller ordered before it) counts by then. + pub(super) fn version(&self) -> u64 { + self.version.load(Ordering::Relaxed) + } } /// `uses` and, for each use of a buffer that joined a memory, a use of the memory's key of diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 15f459cc8..b5758d6ab 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -141,6 +141,7 @@ mod mipmap_scratch; mod misplaced_notices; mod nan_clear; mod neutral; +mod noted_apart; mod owned_kernel; mod pending_dispatch; mod pipeline; diff --git a/crates/metal2vulkan-runtime/src/live_bind.rs b/crates/metal2vulkan-runtime/src/live_bind.rs index 869675417..1efe85160 100644 --- a/crates/metal2vulkan-runtime/src/live_bind.rs +++ b/crates/metal2vulkan-runtime/src/live_bind.rs @@ -2,29 +2,79 @@ //! last draw bound to its own in place, and makes its bind shape again only where a change may have //! changed it. //! -//! - **Brought in place.** Each slot's binding is derived again from the encoder's tables at each -//! draw and compared with the kept one (`ArgumentTable::refresh_reading`), and every other field -//! is computed as before and compared ([`Reshape::field`]). The new value is always stored, so -//! the state is the draw's exactly, a float of the other sign (which compares equal) included. -//! No `set*` call marks a slot: a bound buffer's pages may be rebound or detached between draws, -//! which changes its binding with no call, so deriving the binding is the check. While the same -//! slots stay bound, nothing is allocated. +//! - **Brought in place.** Each slot's binding is derived again from the encoder's tables and +//! compared with the kept one (`ArgumentTable::refresh_reading`), at each draw whose table may +//! bring in another: a stage's table read last through the same interface and samplers' maps, +//! that no call changed since (its stamp, `argument_table::Stamp`), whose slots that tell the +//! device's view base alignment apart its drawing state still holds as they were read +//! (`argument_table::AtBindViews`, which another table's offsets may shrink), and that no rebind +//! or detach of a no-copy buffer may have changed (which changes a bound buffer's binding with +//! no call: `buffer::host_cells_moved`), is not read again ([`ReadFrom`]; checked whole in debug +//! builds). +//! Every other field is computed as before and compared ([`Reshape::field`]), as much of it as +//! the shape reads ([`Reshape::shaped`]; a value no shape reads, such as the depth/stencil state, +//! the stencil references or the blend color, is stored uncompared). The new value is always +//! stored, so the state is the draw's exactly, a float of the other sign (which compares equal) +//! included. While the same slots stay bound, nothing is allocated. //! - **The shape found again only where it may have changed.** A bind shape is each bound slot's //! shape beside the shapes of the state's other fields (`BindState::shape`: a stage's tables //! are its slots' shapes, and a stage with none is left out). Where every changed slot keeps its -//! shape, no slot was bound or unbound, and no other field changed, the shape is the kept one. +//! shape, no slot was bound or unbound, and no other field's shape changed, the shape is the +//! kept one: a function of those alone, so a draw that changes only values the shape does not +//! read (a depth/stencil state, as draws between which the program sets another) finds it kept. //! After any other change, and at an encoder's first draw, it is one the drawing state settled //! lately where the state has it (`BindState::position_of_shape`, compared in place: //! `GraphicsState::kept_shape`), so a pass that draws as the one before it makes none; else it //! is made again, whole. +//! - **One per pipeline state lately drawn.** Beside the state its last draw brought in place, the +//! encoder sets aside the states of up to [`SET_ASIDE`] pipeline states it drew before that one +//! ([`LiveBind::select`]), and a draw starts from its pipeline state's, where one is set aside: +//! draws that switch between pipeline states each find their own state's shape kept, and their +//! stage tables read through their own interface, where no slot of theirs changed its shape. +//! Exact for the reason a draw's is: whichever state a draw starts from, it brings every field +//! in place, and the starting state decides only whether the shape is kept. +//! - **Kept from one encoder to the next.** An encoder that ends gives its state, with its shape, +//! to its device ([`SpareLiveBinds`]), and the next render encoder opened starts from it, as a +//! draw starts from the draw before it: its first draw brings it in place, so a pass that binds +//! as the one before it finds its shape kept and adds no slot. Exact for the reason a draw's is: +//! every field of the state a render encoder's draw binds is derived again at each draw (its +//! slots, by `ArgumentTable::refresh_reading`, which unbinds every slot the encoder's tables do +//! not bind; every other field, by `RenderCommandEncoder::settle_draw` and +//! `refresh_bind_state`), and none other is ever set: a render encoder's state holds no compute +//! or tile field (`stage_in_region`, `kept_imageblock_bytes`, `resident_ranges`, a stage's +//! acceleration structures), which a tile dispatch binds in a state of its own. The state names +//! no object (its bindings are values, and its tables' drawing state is held weakly), so a kept +//! one holds nothing alive; the next encoder's tables are new, with stamps of their own. +//! - **The draws' storage kept with it.** The vectors a draw fills and drops (its commands, push +//! writes, uses, descriptor writes, pushed set 0 and vertex buffers) are kept here too, each +//! draw's written over the last one's storage. Those hold values and raw handles, but for the +//! descriptor writes, whose keepers hold samplers and function tables: those are emptied as +//! the draw is done with them ([`Emptied`]), so they hold nothing past it, as a new vector's did. -use metal2vulkan::bind::{BindShape, BindState}; +use ash::vk; +use metal2vulkan::pipeline::PipelineInterface; +use std::any::Any; use std::collections::btree_map::Entry; use std::collections::BTreeMap; -use std::sync::Arc; +use std::ops::{Deref, DerefMut}; +use std::sync::{Arc, Mutex, Weak}; +use super::address_map::SamplerMaps; +use super::argument_table::Stamp; +use super::binding::{CommandUses, PushWrite, SetWrite, Write}; +use super::device::lock; +use super::noted_apart::NotedApart; use super::work_counts::Counters; +/// The most bind states a device keeps for its render encoders to start from: one per encoder +/// open at once beyond it starts empty, as every encoder did before. +const SPARE_LIVE_BINDS: usize = 4; + +/// The most states a [`LiveBind`] sets aside, of the pipeline states its draws drew through before +/// the last draw's ([`LiveBind::select`]): a draw of one of more pipeline states in turn than +/// this starts from the state set aside longest. +const SET_ASIDE: usize = 7; + /// Whether the changes brought into a kept bind state may have changed its shape. #[derive(Clone, Copy, Debug, Default)] pub(super) struct Reshape(bool); @@ -66,6 +116,30 @@ impl Reshape { } *field = value; } + + /// [`field`](Self::field) of a value the caller holds on to: compared in place, and copied + /// into `field` only where it differs, so a field held as it was copies nothing. For a type + /// whose equality is its value's (`Eq`), so a field kept as equal holds what a copy would. + pub(super) fn field_from(&mut self, field: &mut T, value: &T) { + if *field != *value { + self.0 = true; + field.clone_from(value); + } + } + + /// Store `value` in `field`, a field of the kept state of which the shape reads `shape` alone + /// (`BindState::shape`): its shape may change only where that does. + pub(super) fn shaped( + &mut self, + field: &mut T, + value: T, + shape: impl Fn(&T) -> S, + ) { + if !self.0 && shape(field) != shape(&value) { + self.0 = true; + } + *field = value; + } } /// A render encoder's bind state as its last draw bound it, and its shape while no change may @@ -74,12 +148,154 @@ impl Reshape { pub(super) struct LiveBind { /// The state. Each draw brings it to its own through [`Reshape`] (its values past its settle, /// which no shape reads, aside), and then hands the reshape to [`reshaped`](Self::reshaped). - pub(super) state: BindState, + /// Boxed, so a draw of another pipeline state changes it for one set aside by its address + /// ([`select`](Self::select)). + pub(super) state: Box, /// The state's shape, `None` where a change may have changed it. shape: Option>, + /// The count of the device's sampler IDs' slots' changes (`Device::sampler_slots_changed`) + /// at which the state's argument samplers are every live sampler state: while the count + /// holds, a draw lists them as they are, without taking the states again + /// (`sampler::ArgumentSamplers`). `None` where they are not (none listed yet, or those a + /// variant's set-1 arrays hold alone). + pub(super) listed_at: Option, + /// What the state's stage tables were read from ([`ReadFrom`]). + pub(super) read_from: ReadFrom, + /// The states the encoder's draws of other pipeline states brought in place, each as its + /// pipeline state's last draw left it ([`select`](Self::select)). + set_aside: [SetAside; SET_ASIDE], + /// How many times a state went aside: each set aside holds the count as it went, so the one + /// set aside longest holds the least. + asides: u64, + /// The last draw its encoder noted apart (`noted_apart.rs`), kept here so its storage goes + /// from one encoder to the next. + pub(super) noted: NotedApart, + /// The last draw's uses (`binding::command_uses_into`), kept likewise. + pub(super) uses: CommandUses, + /// The storage of the last draw's descriptor writes (`binding::bind`), kept likewise and + /// empty between draws ([`Emptied`]). + pub(super) writes: Vec, + /// The last draw's pushed set 0 (`binding::SetWrite::push_into`), kept likewise. + pub(super) pushed: Vec, + /// The last draw's vertex buffers, `(binding, buffer, offset, stride)`, kept likewise. + pub(super) vertex_buffers: Vec<(u32, vk::Buffer, u64, u64)>, +} + +/// A bind state a [`LiveBind`] set aside, with its shape, its listing's count and what its stage +/// tables were read from, as [`LiveBind`] holds them for its last draw's state. +#[derive(Default)] +struct SetAside { + state: Box, + shape: Option>, + listed_at: Option, + read_from: ReadFrom, + /// [`LiveBind::asides`] as it went aside. + at: u64, +} + +/// What a kept state's stage tables were read from at the draw that read them last +/// (`RenderCommandEncoder::refresh_bind_state`; the module docs): the encoder's table of each +/// stage by its stamp (`argument_table::Stamp`), the interface they were read through, the +/// samplers' address-mode maps, and the count of no-copy buffers' moves +/// (`buffer::host_cells_moved`). A stage's table that keeps its stamp, read through the same +/// interface with the same maps while no no-copy buffer moved, brings in what it brought in then +/// where its drawing state's slots that tell the view base alignment apart are still those it +/// read under (`AtBindViews::holds`, checked at each draw): a slot's binding is a function of the +/// object bound there (its length, its base and addresses, which only a move changes; a texture's +/// facts, made with it; a sampler's descriptor), of the table's other entries, of the function's +/// reading of the slot (the interface), of the maps, and of those slots. +#[derive(Default)] +pub(super) struct ReadFrom { + /// Each stage's table's stamp, by the stage's place in the draw's reading order. + tables: [Option; 4], + /// The interface they were read through, by address, with the drawing state that holds it, + /// held without keeping it alive: while that state lives, no other interface lies there. + interface: Option<(usize, Weak)>, + /// The maps they were read with. + maps: SamplerMaps, + /// The count of no-copy buffers' moves as they were read. + moved: u64, +} + +impl ReadFrom { + /// Whether the tables were read through `interface` with `maps` at `moved` moves: then a + /// table that keeps its stamp is [`unchanged`](Self::unchanged). + pub(super) fn reads( + &self, + interface: &PipelineInterface, + maps: &SamplerMaps, + moved: u64, + ) -> bool { + self.moved == moved && self.through(interface) && self.maps == *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 { + let at = std::ptr::from_ref(interface).addr(); + (self.interface.as_ref()) + .is_some_and(|(read, state)| *read == at && state.strong_count() > 0) + } + + /// Whether the table at `at` in the reading order, stamped `stamp`, is the one read. + pub(super) fn unchanged(&self, at: usize, stamp: Stamp) -> bool { + self.tables[at] == Some(stamp) + } + + /// The tables of `stamps` read now through `interface` (of the drawing state `state` gives) + /// with `maps` at `moved` moves. + pub(super) fn read( + &mut self, + stamps: [Stamp; 4], + (interface, state): ( + &PipelineInterface, + impl FnOnce() -> Arc, + ), + maps: &SamplerMaps, + moved: u64, + ) { + if !self.through(interface) { + let at = std::ptr::from_ref(interface).addr(); + self.interface = Some((at, Arc::downgrade(&state()))); + } + if self.maps != *maps { + self.maps = maps.clone(); + } + self.tables = stamps.map(Some); + self.moved = moved; + } } impl LiveBind { + /// Start a draw through `interface` from the state that pipeline state's last draw left, where + /// one is set aside: it and the state in place change places. Where none is, the state in + /// place changes places with the one set aside longest, which the draw starts from. Both are + /// states as draws left them (or empty, as a new encoder's): exact whichever a draw starts + /// from, as it brings every field of the state in place (the module docs), so this chooses + /// only whether the shape may be kept, and which reads the draw skips. + pub(super) fn select(&mut self, interface: &PipelineInterface) { + if self.read_from.through(interface) { + return; + } + let set_aside = self.set_aside.iter(); + let at = match set_aside + .clone() + .position(|aside| aside.read_from.through(interface)) + { + Some(at) => at, + None => (set_aside.enumerate()) + .min_by_key(|(_, aside)| aside.at) + .map_or(0, |(at, _)| at), + }; + self.asides += 1; + let aside = &mut self.set_aside[at]; + std::mem::swap(&mut self.state, &mut aside.state); + std::mem::swap(&mut self.shape, &mut aside.shape); + std::mem::swap(&mut self.listed_at, &mut aside.listed_at); + std::mem::swap(&mut self.read_from, &mut aside.read_from); + aside.at = self.asides; + } + /// Take the changes brought into the state since its shape was made. pub(super) fn reshaped(&mut self, reshape: Reshape) { if reshape.0 { @@ -88,7 +304,7 @@ impl LiveBind { } /// The state's shape: the kept one, else the one `found` finds of the state, else made - /// again (counted in `counts`). + /// again (counted in `counts`, found or made). pub(super) fn shape( &mut self, counts: &Counters, @@ -107,6 +323,7 @@ impl LiveBind { *shape == self.state.shape(), "a bind shape found that is not its state's" ); + counts.draw_shape_found(); shape } None => { @@ -118,3 +335,66 @@ impl LiveBind { shape } } + +/// A vector in storage kept beyond its use (a [`LiveBind`]'s), emptied as it is made and as it +/// drops: what it holds lives as long as it would in a vector of its own, on every path out of its +/// use, while the storage goes on to the next one. +pub(super) struct Emptied<'a, T>(&'a mut Vec); + +impl<'a, T> Emptied<'a, T> { + /// `storage`, emptied. + pub(super) fn new(storage: &'a mut Vec) -> Emptied<'a, T> { + storage.clear(); + Emptied(storage) + } +} + +impl Deref for Emptied<'_, T> { + type Target = Vec; + + fn deref(&self) -> &Vec { + self.0 + } +} + +impl DerefMut for Emptied<'_, T> { + fn deref_mut(&mut self) -> &mut Vec { + self.0 + } +} + +impl Drop for Emptied<'_, T> { + fn drop(&mut self) { + self.0.clear(); + } +} + +/// A device's bind states that ended render encoders left, which the render encoders it opens +/// next start from (the module docs): at most [`SPARE_LIVE_BINDS`], the latest given taken first. +/// Each is kept in the shared cell its encoder held it in, so an encoder's open and end move and +/// allocate none. +#[derive(Default)] +pub(super) struct SpareLiveBinds(Mutex>>>); + +impl SpareLiveBinds { + /// The state a render encoder opening starts from: the latest an encoder gave back, else an + /// empty one. + pub(super) fn take(&self) -> Arc> { + lock(&self.0).pop().unwrap_or_default() + } + + /// Keep `live`, an ended render encoder's state, for the next encoder to start from, where + /// nothing else holds it (no draw does once its encoder ended) and fewer than + /// [`SPARE_LIVE_BINDS`] are kept; else it goes. A draw that panicked holding it left it as + /// far as it got, which the next draw brings in place as any. + pub(super) fn give(&self, mut live: Arc>) { + if Arc::get_mut(&mut live).is_none() { + return; + } + live.clear_poison(); + let mut spare = lock(&self.0); + if spare.len() < SPARE_LIVE_BINDS { + spare.push(live); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/noted_apart.rs b/crates/metal2vulkan-runtime/src/noted_apart.rs new file mode 100644 index 000000000..ad9513723 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/noted_apart.rs @@ -0,0 +1,108 @@ +//! The last command an unordered encoder noted apart (`EncoderCore::note_reaching`: a render +//! encoder's draw), kept so a command noted with the same uses notes nothing again. +//! +//! Noting a command records its uses in the encoder's current part (`EncoderUses::record`: each +//! tracked use unioned into the one of its resource and range, the part's stages widened) and +//! touches their keys (`EncoderCore::touch_reaching`: each kept among the encoder's keys, each +//! buffer over host pages held, each key the resident set does not reach named). Each step only +//! adds, and adding an equal use, key or name again changes nothing. So a command is noted +//! already when it matches the last noted command in its uses, the keys of them it reaches +//! through the resident set alone, its stages, and the host aliases' version +//! (`HostAliases::version`: while it stands, the uses recorded, those with the host aliases' uses +//! added by `HostAliases::augment`, are the same for the same uses, so a command noted already +//! does not work them out). It must also be noted while the encoder records into the same part, +//! holds the same images in their attachment layout, and the device's buffers over host pages +//! are there as they were (`Rebinds::any`). Its noting is skipped +//! (`WorkCounts::commands_noted_as_before`); every other command is noted as before and kept. +//! The encoder's parts and held images only grow, so their counts tell a change apart. +//! +//! A render encoder keeps it with its bind state (`live_bind.rs`), which the next render encoder +//! starts from, so its storage is kept from one encoder to the next and a draw allocates none: +//! it names the encoder core that noted it (`EncoderCore::id`, no other core's), and another +//! encoder's command is never taken for one it noted. + +use ash::vk; +use std::collections::BTreeSet; + +use super::resource::ResourceKey; +use super::tracker::Use; + +/// What the last command noted apart was noted with (the module docs). +#[derive(Default)] +pub(super) struct NotedApart { + /// The core of the encoder that noted it and kept it, if any. + core: Option, + stages: vk::PipelineStageFlags2, + /// Its uses as given, and the keys of them it reached through the resident set alone, in + /// order. + uses: Vec>, + resident: Vec, + /// The encoder's parts and held images then. + parts: usize, + held: usize, + /// Whether the device had a buffer over host pages then. + rebinds: bool, + /// The host aliases' version then. + aliases: u64, +} + +/// The encoder's state a command is noted into: its core, its parts and held images (counts), +/// whether the device has a buffer over host pages, and the host aliases' version +/// (`HostAliases::version`). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct NotedInto { + pub(super) core: u64, + pub(super) parts: usize, + pub(super) held: usize, + pub(super) rebinds: bool, + pub(super) aliases: u64, +} + +impl NotedApart { + /// Whether a command of `stages` with `uses`, of which it reaches the keys `resident` + /// through the resident set alone, noted into `into`, is the last one noted (the module + /// docs). + pub(super) fn holds( + &self, + stages: vk::PipelineStageFlags2, + (uses, resident): (&[Use], &BTreeSet), + into: NotedInto, + ) -> bool { + self.core == Some(into.core) + && self.stages == stages + && self.into() == into + && *self.uses == *uses + && self.resident.iter().eq(resident) + } + + /// 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( + &mut self, + stages: vk::PipelineStageFlags2, + (uses, resident): (&[Use], &BTreeSet), + into: NotedInto, + ) { + self.core = Some(into.core); + self.stages = stages; + // Its storage is kept from one command to the next. + self.uses.clear(); + self.uses.extend_from_slice(uses); + self.resident.clear(); + self.resident.extend(resident); + self.parts = into.parts; + self.held = into.held; + self.rebinds = into.rebinds; + self.aliases = into.aliases; + } + + fn into(&self) -> NotedInto { + NotedInto { + core: self.core.unwrap_or_default(), + parts: self.parts, + held: self.held, + rebinds: self.rebinds, + aliases: self.aliases, + } + } +} diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 0c557a2d6..9f58cd5c7 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -1905,8 +1905,9 @@ impl GraphicsState { /// What a draw of bind shape `shape` runs on in `forms` ([`settle`](Self::settle)'s answer), /// through what the state settled last for its latest [`SETTLED`] shapes: a draw of an equal - /// shape in the same forms (the very one, which its encoder kept, `live_bind.rs`, or an equal - /// one) settles as it did, not planned again; any other settles, and is kept in place of the + /// shape in the same forms (the very one, which its encoder kept, `live_bind.rs`, looked for + /// first by identity, or an equal one, compared whole where none is the very one) settles as + /// it did, not planned again; any other settles, and is kept in place of the /// one used least lately. Exact: what `settle` answers is a function of the shape and `forms` /// alone. A refused settle keeps nothing, and is answered as `settle` refuses it. pub(crate) fn settle_shape( @@ -1916,9 +1917,13 @@ impl GraphicsState { ) -> Result { { let mut kept = lock(&self.0.settled); - let found = kept - .iter() - .position(|(kept, last)| *kept == forms && last.shape == *shape); + // The very shape first, as a draw's encoder keeps the one it found here; else an + // equal one, compared whole. + let found = (kept.iter()) + .position(|(kept, last)| *kept == forms && Arc::ptr_eq(&last.shape, shape)) + .or_else(|| { + (kept.iter()).position(|(kept, last)| *kept == forms && last.shape == *shape) + }); if let Some(entry) = found.and_then(|at| kept.remove(at)) { let last = entry.1.clone(); kept.push_front(entry); diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index da46d3c60..328181be1 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -295,7 +295,7 @@ use super::index_rewrite::{self, RewritePass, RewriteSteps}; use super::kept_bytes; use super::linear_attachment; use super::linear_merge::LinearMerge; -use super::live_bind::{LiveBind, Reshape}; +use super::live_bind::{Emptied, LiveBind, Reshape}; use super::nan_clear::{keeps_nan_sign, NanClears, NanDepthWrite}; use super::pipeline::Settled; use super::pipeline::{BufferForms, DrawPipeline}; @@ -320,7 +320,7 @@ use super::resource::ResourceKey; use super::sample_planes::{self, Planes, PlanesCommands}; use super::sample_positions; use super::sampler::OwnedSampler; -use super::sampler::SamplerState; +use super::sampler::{ArgumentSamplers, SamplerState}; use super::sampler_listing::SamplerListing; use super::shadow::{self, ShadowCopy}; use super::shadow_stencil::ShadowStencil; @@ -354,8 +354,8 @@ use metal2vulkan::metal::{ RenderStages, TriangleFillMode, Winding, }; use metal2vulkan::pipeline::{ - ColorGroup, GraphicsState, PipelineInterface, PushField, RuntimeFact, Stage, - StorageAttachmentUse, StorageAttachmentView, + ColorGroup, GraphicsState, PushField, RuntimeFact, Stage, StorageAttachmentUse, + StorageAttachmentView, }; use pass_start_reads::{PassStartReads, PassStartTables}; use pass_steps::{InstanceSteps, PassSteps, StagedDispatch}; @@ -640,10 +640,12 @@ struct DrawSettings { written_clamp: Option, /// The depth bias its primitives take: none for points and lines. bias: Option, - /// Where its colors go among the pass's, the pass's colors it zeroes and its own it drops. + /// Where its colors go among the pass's. routing: Arc, - zeroed_colors: BTreeMap, - dropped_colors: BTreeSet, + /// The pass's colors it zeroes and its own it drops, where the encoder keeps no such colors + /// for its pipeline state in its pass (`Routed`): found for the draw alone. `None` where the + /// encoder keeps them, which the draw reads in place ([`RenderCommandEncoder::draw_colors`]). + routed_colors: Option, /// Whether the depth it renders against is `Depth16Unorm` (`BindState::depth16_pass`). depth16_pass: Option, /// The side of its depth bias (`BindState::depth16_bias_raises`). @@ -1227,7 +1229,8 @@ pub struct RenderCommandEncoder { /// The last draw's variant, plan and specialization under which the bound values' notices /// were quiet (`Device::degrade_bound_values`), where it was. quiet_bound_values: Option, - /// The views and sampler descriptions its draws' binds made or found (`binding::BindMemo`). + /// The views and sampler descriptions its draws' binds made or found, taken from the + /// device's ended render encoders' and given back as it ends (`binding::BindMemo`). bind_memo: binding::BindMemo, /// What its last draw retained of its own ([`LastRetained`]). last_retained: LastRetained, @@ -1333,11 +1336,23 @@ impl QuietBoundValues { } /// A drawing state's routing into a pass's colors ([`RenderCommandEncoder::routing`]), with the -/// state and the pass's color formats it was found for: a function of those alone. +/// state and the pass's color formats it was found for, and the colors a draw of it zeroes and +/// drops by that routing ([`RenderCommandEncoder::routed_colors`]): each a function of those +/// alone. struct Routed { state: DrawingState, pass: [Option; MAX_COLOR_ATTACHMENTS], routing: Result, u32>, + /// `None` where the state's routing is refused. + colors: Option, +} + +/// The pass colors a draw of a drawing state zeroes, and the state's colors it drops, by its +/// routing ([`RenderCommandEncoder::zeroed_colors`], [`RenderCommandEncoder::dropped_colors`]). +#[derive(Clone)] +struct RoutedColors { + zeroed: BTreeMap, + dropped: BTreeSet, } impl std::fmt::Debug for RenderCommandEncoder { @@ -1551,7 +1566,10 @@ impl RenderCommandEncoder { grouped, } = opening; let keeping = capture::Keeping::of(&layout); - let rerecord = reroute::keeps_whole(core.device()) || extended.keeps_draws(); + // The bind state the device's last ended render encoder left (`live_bind.rs`). + let live = core.device().shared().live_binds.take(); + // The views and sampler descriptions its binds made or found (`binding::BindMemo`). + let bind_memo = core.device().shared().bind_memos.take(); RenderCommandEncoder { core, earlier: Vec::new(), @@ -1645,10 +1663,10 @@ impl RenderCommandEncoder { extended, pass_start: PassStartReads::default(), restart: None, - live: Arc::default(), + live, log, quiet_bound_values: None, - bind_memo: binding::BindMemo::default(), + bind_memo, last_retained: LastRetained::default(), inline: match inline { Some(splits) => inline_first::Inline::Open { splits }, @@ -1774,6 +1792,10 @@ impl DrawDynamic { } } +/// No colors or slots: what a draw's set of them is compared with where it names none +/// ([`RenderCommandEncoder::settle_draw`]). +static NO_INDICES: BTreeSet = BTreeSet::new(); + /// The dynamic states a draw records, beside `VERTEX_INPUT_BINDING_STRIDE` (recorded with the /// vertex buffers). const RECORDED: [vk::DynamicState; 16] = [ @@ -1844,8 +1866,14 @@ impl RenderCommandEncoder { // Routed once here: the check and each draw read it (`routing`). if let RenderStateKind::Graphics(graphics) = state.kind() { let pass = self.pass_formats(); + let routing = graphics.routed(&pass, || Self::route(graphics, &pass)); + let colors = routing + .as_ref() + .ok() + .map(|routing| self.colors_by(graphics, routing)); self.routed = Some(Routed { - routing: graphics.routed(&pass, || Self::route(graphics, &pass)), + routing, + colors, state: graphics.clone(), pass, }); @@ -3437,8 +3465,16 @@ impl RenderCommandEncoder { drew_depth_writes, inline, grouped, + live, + bind_memo, .. } = self; + // The views and sampler descriptions its binds made or found, which the device's next + // render encoder takes (`binding::BindMemo`). + core.device().shared().bind_memos.give(bind_memo); + // The bind state its last draw left, which the device's next render encoder starts from + // (`live_bind.rs`): no draw holds it once the encoder ends. + core.device().shared().live_binds.give(live); earlier.push(current); let mut instances = earlier; // The first instance's render pass and framebuffer, where it recorded inline in the @@ -4885,71 +4921,98 @@ impl RenderCommandEncoder { /// encoder made resident are its used resources, each in its render stages, `argument_samplers` /// the device's sampler states a draw lists, each at the heap element of its resource ID, and /// `function_tables` the live tables its state made (`render/arguments.rs`). Each stage's table - /// is read as `interface`, the state's, reads it: a buffer where a stage reads a - /// visible-function table reads as a null table. The vertex, object and mesh stages' tables are - /// `pass_start`'s, with the copies of bytes the pass's fragment stages wrote, or the encoder's - /// (`render/pass_start_reads.rs`; the object and mesh stages' changed). Each stage's samplers - /// are bound as `maps` binds them. The depth/stencil state and the fields the draw's settings - /// state are the caller's to bring ([`settle_draw`](Self::settle_draw)); the values a draw - /// sets past its settle, which no shape reads, are Metal's defaults until it sets them. + /// is read as the interface of `pipeline`, the drawing state, reads it: a buffer where a stage + /// reads a visible-function table reads as a null table; a table read last through the same + /// interface and maps, that no call changed, whose slots that tell the device's view base + /// alignment apart the state still holds as it read them, and that no no-copy buffer's move + /// may have changed since, is not read again (`live_bind::ReadFrom`). The vertex, object and + /// mesh stages' tables are `pass_start`'s, with the copies of bytes the pass's fragment stages + /// wrote, or the encoder's (`render/pass_start_reads.rs`; the object and mesh stages' + /// changed). Each stage's samplers are bound as `maps` binds them, and the buffer slots that + /// tell the device's view base alignment apart are the state's + /// (`argument_table::AtBindViews`). The depth/stencil state and the fields the draw's settings + /// state are the caller's to bring ([`settle_draw`](Self::settle_draw)); the values a draw sets + /// past its settle, which no shape reads, are Metal's defaults until it sets them. fn refresh_bind_state( &self, live: &mut LiveBind, pass_start: &PassStartTables, - (argument_samplers, function_tables): (&[SamplerState], &[VisibleFunctionTable]), - (interface, maps): (&PipelineInterface, &SamplerMaps), + (argument_samplers, function_tables): (&mut ArgumentSamplers, &[VisibleFunctionTable]), + (pipeline, maps): (&DrawingState, &SamplerMaps), ) -> Reshape { let mut reshape = Reshape::default(); + let interface = &pipeline.base().interface; let state = &mut live.state; - for (stage, table) in [ + let views = pipeline.at_bind_views(); + let tables = [ (Stage::Vertex, pass_start.or(Stage::Vertex, &self.vertex)), (Stage::Fragment, &self.fragment), (Stage::Object, pass_start.or(Stage::Object, &self.object)), (Stage::Mesh, pass_start.or(Stage::Mesh, &self.mesh)), - ] { + ]; + // Read again only where what a table brings in may have changed since it was read + // (`live_bind::ReadFrom`); a table that keeps its stamp is checked in debug builds alone. + let moved = crate::buffer::host_cells_moved(); + let same = live.read_from.reads(interface, maps, moved); + let counts = &self.core.device().shared().counts; + for (at, (stage, table)) in tables.into_iter().enumerate() { let kept = state.stages.entry(stage).or_default(); - table.refresh_reading(kept, (stage, interface), maps, &mut reshape); + // Its slots that tell the view base alignment apart are as the state holds them + // (`AtBindViews::holds`): another table's offsets may have left some out since. + let views_held = views.holds(stage, kept.at_bind_views); + if same && views_held && live.read_from.unchanged(at, table.stamp()) { + #[cfg(debug_assertions)] + table.check_reading(kept, (stage, interface), (maps, views)); + continue; + } + counts.stage_table_read(); } + let stamps = tables.map(|(_, table)| table.stamp()); + live.read_from + .read(stamps, (interface, || pipeline.held()), maps, moved); // The object function's threadgroup memory lengths, which its draws specialize. let object = state.stages.entry(Stage::Object).or_default(); - reshape.field( + reshape.field_from( &mut object.threadgroup_lengths, - self.object_threadgroup_lengths.clone(), + &self.object_threadgroup_lengths, ); reshape.field(&mut state.used_resources, self.residency.used_resources()); - // Listed again only where the device's sampler states changed since. - if !heap_sets::lists(&state.argument_samplers, argument_samplers) { - reshape.field( - &mut state.argument_samplers, - heap_sets::listed(argument_samplers), - ); + // Listed again only where the device's sampler states changed since: not where the + // listing kept is of every live state at the count of their slots' changes that still + // holds; else they are taken and compared state by state. + let device = self.core.device(); + let current = argument_samplers.states().is_none() + && live.listed_at == Some(device.sampler_slots_changed()); + if !current { + let states = argument_samplers.take(device); + if !heap_sets::lists(&state.argument_samplers, states) { + reshape.field(&mut state.argument_samplers, heap_sets::listed(states)); + } + live.listed_at = argument_samplers.listed_at(); } let listed = function_tables .iter() .map(VisibleFunctionTable::listed) .collect(); reshape.field(&mut state.function_tables, listed); - reshape.field(&mut state.heap_placement, HeapPlacement::ResourceId); reshape.field( &mut state.render_target_array_length, self.render_target_array_length, ); - reshape.field(&mut state.viewport_count, self.state.viewport_count(true)); + // Values no shape reads (`BindState::shape`), stored as they are: a change of one leaves + // the shape as it was (`live_bind.rs`). + state.heap_placement = HeapPlacement::ResourceId; + state.viewport_count = self.state.viewport_count(true); // An extended-range blend computed in the shader reads the blend color as push data. - reshape.field(&mut state.blend_color, self.state.blend_color()); + state.blend_color = self.state.blend_color(); // A fragment function that runs the draw's depth test itself clamps its depth as the // encoder's depth clip mode says, read as push data (its range: `draw_resident`). - reshape.field( - &mut state.depth_clip_mode_clamp, - self.state.depth_clip_mode_clamp(), - ); + state.depth_clip_mode_clamp = self.state.depth_clip_mode_clamp(); // A fragment function that runs the draw's stencil test itself reads the references as // push data. - reshape.field( - &mut state.stencil_references, - self.state.stencil_reference(), - ); - // Only a tessellation pipeline reads the factors: any other's shape leaves them out. + state.stencil_references = self.state.stencil_reference(); + // Only a tessellation pipeline reads the factors: any other's shape leaves them out. The + // shape reads whether they name a buffer alone. let kind = self.pipeline.as_ref().map(RenderPipelineState::kind); let factors = match kind { Some(RenderStateKind::Graphics(graphics)) @@ -4959,7 +5022,9 @@ impl RenderCommandEncoder { } _ => TessellationFactors::default(), }; - reshape.field(&mut state.tessellation_factors, factors); + reshape.shaped(&mut state.tessellation_factors, factors, |f| { + f.buffer.is_some() + }); state.primitive_type = None; state.depth_range = <[f32; 2]>::default(); state.depth_bias = [0.0; 3]; @@ -5059,17 +5124,16 @@ impl RenderCommandEncoder { /// What the tests of `depth_stencil` can do to the fragments of a draw of `pipeline` /// (`BindState::fragment_tests`) whose fragment function may store a color through the /// interlocked storage form before them: one that states `RuntimeFact::TestedStorageWrites`, - /// or one whose draw writes the instance's `interlocked` colors through that form, whose - /// variant may state it. `FragmentTests::Any`, which no other plan reads, for every other - /// draw, so that its plans stay one per shape whatever its tests. + /// `FragmentTests::Any`, which no other plan reads, for every other draw, so that its plans + /// stay one per shape whatever its tests. fn fragment_tests( &self, pipeline: &DrawingState, depth_stencil: &DepthStencilDescriptor, - interlocked: &BTreeSet, + stores: bool, ) -> FragmentTests { let base = pipeline.base(); - let tested = !interlocked.is_empty() + let tested = stores || base .dependencies .iter() @@ -5927,6 +5991,50 @@ impl RenderCommandEncoder { } } + /// The pass colors a draw of `pipeline`, routed by `routing`, zeroes and the colors of its own + /// it drops: those the encoder kept as `pipeline` was set where the pass's colors are still + /// the ones they were found for (a function of the state and those colors alone, as `routing` + /// is), else found again. + fn routed_colors( + &self, + pipeline: &DrawingState, + routing: &Routing, + ) -> std::borrow::Cow<'_, RoutedColors> { + match &self.routed { + Some(Routed { + state, + pass, + colors: Some(colors), + .. + }) if state.same(pipeline) && *pass == self.pass_formats() => { + std::borrow::Cow::Borrowed(colors) + } + _ => std::borrow::Cow::Owned(self.colors_by(pipeline, routing)), + } + } + + /// The pass colors a draw of `pipeline` under `settings` zeroes and the colors of its own it + /// drops: those its settings found for it alone, else those the encoder keeps + /// ([`routed_colors`](Self::routed_colors)), read in place. + fn draw_colors<'a>( + &'a self, + pipeline: &DrawingState, + settings: &'a DrawSettings, + ) -> std::borrow::Cow<'a, RoutedColors> { + match &settings.routed_colors { + Some(colors) => std::borrow::Cow::Borrowed(colors), + None => self.routed_colors(pipeline, &settings.routing), + } + } + + /// [`zeroed_colors`](Self::zeroed_colors) and [`dropped_colors`](Self::dropped_colors) of a + /// draw of `pipeline` routed by `routing`. + fn colors_by(&self, pipeline: &DrawingState, routing: &Routing) -> RoutedColors { + let zeroed = self.zeroed_colors(pipeline, routing); + let dropped = self.dropped_colors(pipeline, routing, zeroed.is_empty()); + RoutedColors { zeroed, dropped } + } + /// The pass's colors at no place of `pipeline`'s record (`routing`), the pass's format of /// each by the location the draw references it at, where plain Metal zeroes them at every /// sample a draw covers (`color_reformat::Uncovered::Zeroed`; Metal probes, probes): a draw @@ -6134,11 +6242,16 @@ impl RenderCommandEncoder { /// probe): a draw runs the variant whose fragment function keeps no output there /// (`BindShape::dropped_colors`), so its pipeline writes no location without an attachment, /// and none into a pass color it keeps. They are the state's colors at no place of the pass's - /// record (`routing`); a pass color the draw keeps (`zeroed_colors` names none), at whose - /// location the state has no color; and in a routed draw each location its subpass leaves - /// out where the state has no color, which the function may write all the same. Empty for a - /// state without a fragment function, which writes no color. - fn dropped_colors(&self, pipeline: &DrawingState, routing: &Routing) -> BTreeSet { + /// record (`routing`); a pass color the draw keeps (`none_zeroed`: its `zeroed_colors` names + /// none), at whose location the state has no color; and in a routed draw each location its + /// subpass leaves out where the state has no color, which the function may write all the same. + /// Empty for a state without a fragment function, which writes no color. + fn dropped_colors( + &self, + pipeline: &DrawingState, + routing: &Routing, + none_zeroed: bool, + ) -> BTreeSet { let descriptor = pipeline.descriptor(); if descriptor.vertex().is_some_and(|d| d.fragment.is_none()) { return BTreeSet::new(); @@ -6152,7 +6265,7 @@ impl RenderCommandEncoder { .is_none_or(|pf| pf == PixelFormat::Invalid) }; let mut dropped = routing.dropped.clone(); - if Self::writes_colors(pipeline) && self.zeroed_colors(pipeline, routing).is_empty() { + if Self::writes_colors(pipeline) && none_zeroed { dropped.extend(routing.uncovered.keys().copied().filter(|&l| lacks(l))); } let left_out = (0u32..).zip(&routing.locations); @@ -6660,7 +6773,7 @@ impl RenderCommandEncoder { let routing = self .routing(state) .map_err(|_| internal("a draw of a state its pass refuses"))?; - let zeroed = !self.zeroed_colors(state, &routing).is_empty(); + let zeroed = !self.routed_colors(state, &routing).zeroed.is_empty(); let writes = linear_attachment::writes(colors); let writes = linear_attachment::pass_writes(&writes, &routing, zeroed); self.coverage.add(&writes, rects) @@ -6807,9 +6920,6 @@ impl RenderCommandEncoder { let hidden_depth = settings.hidden.is_some(); let (_, stencil) = self.aspects(); let max = pipeline.base().graphics.max_vertex_amplification_count; - // The device's sampler states, less those at IDs no set-1 sampler array of the variant - // holds (`heap_sets::fit_samplers`). - let mut argument_samplers = self.core.device().argument_samplers(); let function_tables = pipeline.function_tables(); let mut unlisted = None; let reads_tile_memory = pipeline.reads_tile_memory(); @@ -6820,6 +6930,14 @@ impl RenderCommandEncoder { // A capture draw (`render/capture.rs`) runs before the pass: it reads the bytes as they // were then, in place, and announces nothing its first recording did not. let capture = self.capture_addresses(); + // The device's sampler states, less those at IDs no set-1 sampler array of the variant + // holds (`heap_sets::fit_samplers`): taken where the draw needs them + // (`sampler::ArgumentSamplers`), and at once for a capture draw, whose capture form is + // another variant than the one settled. + let mut argument_samplers = match capture { + Some(_) => ArgumentSamplers::taken(self.core.device()), + None => ArgumentSamplers::untaken(), + }; let pass_start = match capture { Some(_) => PassStartTables::default(), None => self.pass_start.tables( @@ -6881,9 +6999,12 @@ impl RenderCommandEncoder { } } }; - self.core - .device() - .degrade_argument_pixel_samplers(&variant.pipeline().stages, &argument_samplers); + let device = self.core.device(); + let stages = &variant.pipeline().stages; + if device.argument_pixel_samplers_noted(stages).is_some() { + device.degrade_argument_pixel_samplers(stages, argument_samplers.take(device)); + } + let zeroes_colors = !self.draw_colors(&pipeline, &settings).zeroed.is_empty(); let DrawSettings { hidden, failing_state, @@ -7207,6 +7328,7 @@ impl RenderCommandEncoder { let snapshot_split = snapshot.as_ref().is_some_and(|w| self.snapshot_apart(w)); let storage_colors = self.storage_colors(&plan); let apart = snapshot_split || storage_colors & self.current.feedback.0 != 0; + && self.writes_memoryless(&pipeline, &routing, zeroes_colors); // A capture draw records into the capture's instance, the current one. let (next, stood) = match capture { Some(_) => (Next::Current, None), @@ -7398,7 +7520,11 @@ impl RenderCommandEncoder { tables = tables.with_snapshots(views); } if let Some(heap) = &heap { - tables = tables.with_heap(&argument_samplers, heap); + // Taken as the draw settled: its variant has set-1 arrays. + let states = argument_samplers + .states() + .ok_or_else(|| internal("a heap's draw without its argument samplers"))?; + tables = tables.with_heap(states, heap); } if let Some((records, indices)) = capture { tables = tables.with_capture(records, indices); @@ -7493,25 +7619,28 @@ impl RenderCommandEncoder { .map(tessellation_scan::TessellationWork::regions), }; let (index, indirect) = (buffers.index.as_ref(), buffers.indirect.as_ref()); - let mut uses = binding::command_uses( + // Over the last draw's uses, in their storage (`LiveBind::uses`). + binding::command_uses_into( call, - &plan, - &command, - &tables, - index.map(DrawSource::metal), - indirect.map(DrawSource::metal), + (&plan, &command, &tables), + ( + index.map(DrawSource::metal), + indirect.map(DrawSource::metal), + ), + &mut live.uses, )?; + 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 // reads no attachment otherwise (`snapshot_holds`). if snapshot.is_none() { - device.degrade_attachment_reads(call, layout, uses.iter())?; + device.degrade_attachment_reads(call, layout, uses)?; } // In a pass of several color groups, what the draw reads of what another group writes // (`render/color_groups.rs`): checked at its first recording. if capture.is_none() && !self.rerouting { let roots = !commands.root_tables.is_empty(); - self.check_group_reads(&uses, roots, &plan)?; + self.check_group_reads(uses, roots, &plan)?; } uses.extend(inputs); uses.extend(storage_uses); @@ -7547,7 +7676,7 @@ impl RenderCommandEncoder { .chain(self.object.textures.values()) .chain(self.mesh.textures.values()) .chain(self.residency.textures()); - let mut draw_shadows = shadow::shadow_uses(textures, &uses); + let mut draw_shadows = shadow::shadow_uses(textures, uses); // A draw that reads an attachment's texture at its fragments' own pixels alone copies in // only the texels around its scissors (`texture/attached_reads.rs`). if attached { @@ -7565,7 +7694,8 @@ impl RenderCommandEncoder { self.capture_missed(); return Ok(()); } - let mut vertex_buffers = Vec::with_capacity(plan.vertex_buffers.len()); + // Over the last draw's, in their storage (`LiveBind::vertex_buffers`). + live.vertex_buffers.clear(); for bind in &plan.vertex_buffers { let table = pass_start.or(Stage::Vertex, &self.vertex); let offset = commands @@ -7593,8 +7723,9 @@ impl RenderCommandEncoder { (None, Some(bytes)) => (bytes.region.raw(), bytes.region.offset()), (None, None) => return Err(internal("the plan binds an unbound vertex buffer")), }; - vertex_buffers.push((bind.binding, raw, start + offset, stride.unwrap_or(0))); + (live.vertex_buffers).push((bind.binding, raw, start + offset, stride.unwrap_or(0))); } + let vertex_buffers = &live.vertex_buffers[..]; let profile = device.compile_device().profile(); let selects = graphics.writes_viewport_index; let mut fixed = self.draw_fixed( @@ -7821,10 +7952,18 @@ impl RenderCommandEncoder { if let DrawPipeline::Made(made) = &draw_pipeline { variant.first_use(made, specialization, &formats); } - let bound = { + // Set 0's writes and the heap set's, in the last draw's storage (`LiveBind::writes`), + // emptied as the draw returns: their keepers hold nothing past it. + let mut writes = Emptied::new(&mut live.writes); let mut state = self.core.command_buffer().state(); let memo = Some(&mut self.bind_memo); - binding::bind(call, &device, &mut state, &plan, &command, &tables, memo)? + call, + &device, + &mut state, + &plan, + &command, + &tables, + (memo, &mut writes), }; // The draw's push bytes, filled in place. let push = binding::push_writes(commands.push_constants, &bound.holes)?; @@ -7855,13 +7994,14 @@ impl RenderCommandEncoder { }; let objects = Arc::clone(variant.objects()); // Set 0 per draw; set 1 the device's (written below, once nothing refuses). - let mut writes = bound.writes; let heap_writes: Vec<_> = writes.extract_if(.., |write| write.set > 0).collect(); - let set = objects.set_zero(&mut self.core.command_buffer().state().descriptors)?; - // SAFETY: the set was just allocated and no command uses it yet; every buffer, view - // and sampler written is live (the command buffer retains them below, and a refusal - // leaves the set unused in its pool). - unsafe { binding::write_sets(&device, set.as_slice(), &writes) }?; + let pushed: &[binding::SetWrite] = match objects.pushes_set_zero() { + true => { + // Over the last draw's, in their storage (`LiveBind::pushed`). + binding::SetWrite::push_into(&writes, objects.immutable_pushes(), &mut live.pushed); + &live.pushed + } + &[] // The Vulkan draws: the binder's, the index bounds pass's two, or the index rewrite // pass's one. let sized = device.shared().sized_index_bind; @@ -7989,10 +8129,12 @@ impl RenderCommandEncoder { }); // A capture draw's uses are the capture's command's, before the pass (`capture_uses`). if capture.is_none() { - self.core.note_reaching(stages, &uses, uses.resident())?; - self.unordered.add(&uses); - self.pass_start.announce(&device, &uses, mesh_before); - self.pass_start.add(&uses); + let reaching = (&**uses, uses.resident()); + self.core + .note_reaching(stages, reaching, Some(&mut live.noted))?; + self.unordered.add(uses); + self.pass_start.announce(&device, uses, mesh_before); + self.pass_start.add(uses); } let heap_set = match heap { Some(_) => Some(heap_sets::bind( @@ -8000,7 +8142,7 @@ impl RenderCommandEncoder { &objects, &mut self.core.command_buffer().state().heaps, heap_writes, - Some(&*uses), + Some(&**uses), )?), None => None, }; @@ -8291,7 +8433,7 @@ impl RenderCommandEncoder { self.tile_memory_splits += usize::from(tile_memory_split); self.barrier_splits += usize::from(run_barrier_split); self.run_barrier = false; - self.gathering().add(&draw_shadows, &uses); + self.gathering().add(&draw_shadows, uses); if !empty && !culled { for source in index.into_iter().chain(indirect) { match (source.copy_steps(&mut self.core), before_instance) { @@ -8397,19 +8539,23 @@ impl RenderCommandEncoder { }; // An emulated tessellation draw records its chunks in place of the amplifications: // each chunk's push writes, then its draw. - let entries: Vec<(&[binding::PushWrite], &[_])> = match chunked.is_empty() { - true => pushes.iter().map(|push| (&push[..], vk_draws)).collect(), - false => chunked - .iter() - .map(|(push, draw)| (&push[..], &draw[..])) - .collect(), + let entries = match chunked.is_empty() { + true => pushes.len(), + false => chunked.len(), + }; + let entry = |a: usize| -> (&[binding::PushWrite], &[_]) { + match chunked.get(a) { + Some((push, draw)) => (&push[..], &draw[..]), + None => (&pushes[a][..], vk_draws), + } }; for &phase in phases { let mut first = true; // Amplification by amplification, each through its recordings' regions: Metal // renders every primitive of one before the next's, and a pixel's regions are one. // An emulated tessellation draw's chunks, likewise, in order. - for (a, &(push, vk_draws)) in entries.iter().enumerate() { + for a in 0..entries { + let (push, vk_draws) = entry(a); for state in draw_states.of(a) { for &(index, indirect, draw) in vk_draws { if indirect.is_some() @@ -8443,9 +8589,10 @@ impl RenderCommandEncoder { layout: objects.layout(), pipeline: made_now.unwrap_or_default(), sets: set.as_slice(), + pushed, heap: heap_set, push, - vertex_buffers: &vertex_buffers, + vertex_buffers, index, indirect, dynamic, @@ -8631,7 +8778,7 @@ impl RenderCommandEncoder { self.core.retain(function_tables); } if capture.is_some() { - self.capture_uses(uses); + self.capture_uses(uses.clone()); } Ok(()) } @@ -8842,8 +8989,10 @@ impl RenderCommandEncoder { let routing = self .routing(pipeline) .map_err(|_| internal("a draw of a state its pass refuses"))?; - let zeroed_colors = self.zeroed_colors(pipeline, &routing); - let dropped_colors = self.dropped_colors(pipeline, &routing); + let routed_colors = match self.routed_colors(pipeline, &routing) { + std::borrow::Cow::Borrowed(_) => None, + std::borrow::Cow::Owned(colors) => Some(colors), + }; // A compensated depth, which a vertex clamp takes natively too, replaces the native // range (`clamp_draw_depth`). let compensated = compensation.is_some_and(|c| c.depth.is_some()); @@ -8867,8 +9016,7 @@ impl RenderCommandEncoder { written_clamp, bias, routing, - zeroed_colors, - dropped_colors, + routed_colors, depth16_pass, depth16_bias_raises, primitive_id_indices: None, @@ -8909,7 +9057,7 @@ impl RenderCommandEncoder { live: &mut LiveBind, (pipeline, settings): (&DrawingState, &DrawSettings), pass_start: &PassStartTables, - (argument_samplers, unlisted): (&mut Vec, &mut Option<(u64, u64)>), + (argument_samplers, unlisted): (&mut ArgumentSamplers, &mut Option<(u64, u64)>), (function_tables, snapshot): (&[VisibleFunctionTable], &mut Option), ) -> Result { // Its runtime samplers' address modes as the textures they sample map them. @@ -8918,33 +9066,32 @@ impl RenderCommandEncoder { // reads and writes beside the codes (`render/extended_shadow.rs`); its interlocked // colors are the others. let mut shadows = self.extended_shadows_bound(); - let mut interlocked: BTreeSet = self - .interlocked_colors(pipeline) - .difference(&shadows) - .copied() - .collect(); - let interface = &pipeline.base().interface; + // From the state the pipeline state's last draw left, where the encoder set it aside. + live.select(&pipeline.base().interface); loop { let mut reshape = self.refresh_bind_state( live, pass_start, (argument_samplers, function_tables), - (interface, &sampler_maps), + (pipeline, &sampler_maps), ); let state = &mut live.state; - reshape.field( - &mut state.vertex_amplification, - settings.amplification.clone(), - ); - reshape.field( + // Each field the draw's settings or the loop hold on to compared in place, and copied + // only where it changed. + reshape.field_from(&mut state.vertex_amplification, &settings.amplification); + // The shape reads the compensation's kind alone, and whether a clamp range is set. + reshape.shaped( &mut state.viewport_compensation, settings.compensation.map(|c| c.viewport), + |c| c.map(|c| c.compensation), ); - reshape.field( + reshape.shaped( &mut state.depth_clamp_range, settings.written_clamp.map(|w| w.range), + Option::is_some, ); - reshape.field(&mut state.zeroed_colors, settings.zeroed_colors.clone()); + let colors = self.draw_colors(pipeline, settings); + reshape.field_from(&mut state.zeroed_colors, &colors.zeroed); reshape.field(&mut state.depth16_pass, settings.depth16_pass); reshape.field( &mut state.depth16_biased, @@ -8955,18 +9102,17 @@ impl RenderCommandEncoder { &mut state.primitive_id_indices, settings.primitive_id_indices, ); - reshape.field(&mut state.dropped_colors, settings.dropped_colors.clone()); - reshape.field(&mut state.interlocked_colors, interlocked.clone()); - reshape.field(&mut state.extended_shadows, shadows.clone()); - let snapshots = snapshot.as_ref().map(|w| w.slots.clone()); - reshape.field(&mut state.snapshot_textures, snapshots.unwrap_or_default()); + reshape.field_from(&mut state.dropped_colors, &colors.dropped); + reshape.field_from(&mut state.extended_shadows, shadows); + let snapshots = snapshot.as_ref().map_or(&NO_INDICES, |w| &w.slots); + reshape.field_from(&mut state.snapshot_textures, snapshots); let depth_stencil = match &settings.failing_state { Some(failing) => failing.failing_depth(), None => self.state.depth_stencil_descriptor(), }; - reshape.field(&mut state.depth_stencil, depth_stencil); - let stored: BTreeSet = interlocked.union(&shadows).copied().collect(); - let tests = self.fragment_tests(pipeline, &state.depth_stencil, &stored); + // No shape reads the depth/stencil state but through the fragment tests (below). + state.depth_stencil = depth_stencil; + let tests = self.fragment_tests(pipeline, &state.depth_stencil, stores); reshape.field(&mut state.fragment_tests, tests); let tiles = settings.tiles.map(|(tile, area)| { let memory = self @@ -9002,22 +9148,7 @@ impl RenderCommandEncoder { if self.rerouting { return Err(refused); } - shadows = BTreeSet::new(); - interlocked = self.interlocked_colors(pipeline); - continue; - } - // A variant whose writes of the instance's interlocked colors the storage form - // refuses (a blend, among others), or the bind layer does not build (an amplified - // draw's): remembered, and the draw records in an instance of its own, as without - // them; a reroute fails instead. - Err(refused @ (Error::Unsupported(_) | Error::Bind(BindError::Unsupported(_)))) - if !interlocked.is_empty() => - { - pipeline.refuse_interlock(&interlocked); - if self.rerouting { - return Err(refused); - } - interlocked = BTreeSet::new(); + shadows = &NO_INDICES; continue; } settled => settled?, @@ -9032,9 +9163,12 @@ impl RenderCommandEncoder { } } let set = settled.variant.pipeline().layout.sets.get(1); - if heap_sets::fit_samplers(set, argument_samplers, unlisted) { + if argument_samplers.fit(set, unlisted) { return Ok(settled); } + // A variant of set-1 arrays writes the listed states' elements: it takes the states, + // listed again (alike, where the kept listing is current) against them. + argument_samplers.take(self.core.device()); } } diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index a0ecacb0e..87ba8ac93 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -288,6 +288,7 @@ use crate::render_target::{self, Feedback, PassShape, Position, RenderPassObject use crate::residency::{every_render_stage, Residency}; use crate::resource::ResourceKey; use crate::sample_planes::{PlanesCommands, PlanesStep}; +use crate::sampler::ArgumentSamplers; use crate::shadow::{self, ShadowUse}; use crate::shadow_stencil::ShadowStencil; use crate::tessellation::{FactorBuffer, Factors}; @@ -1605,7 +1606,7 @@ impl RenderCommandEncoder { ) -> Result { let assembly = Assembly::Primitives(primitive_type); let settings = self.draw_settings(CALL, state, assembly, false)?; - let mut argument_samplers = self.core.device().argument_samplers(); + let mut argument_samplers = ArgumentSamplers::taken(self.core.device()); let function_tables = state.function_tables(); let live = Arc::clone(&self.live); let settled = self.settle_draw( @@ -1616,9 +1617,9 @@ impl RenderCommandEncoder { (&function_tables, &mut None), )?; let Settled { variant, plan, .. } = settled; - self.core - .device() - .degrade_argument_pixel_samplers(&variant.pipeline().stages, &argument_samplers); + let device = self.core.device(); + let stages = &variant.pipeline().stages; + device.degrade_argument_pixel_samplers(stages, argument_samplers.take(device)); // The neutrals the plan binds, which the step makes none of (`neutral.rs`). One not made // here (the device out of memory) leaves the variant settled: the step refuses the // neutral where it binds it, typed (`CommandBufferError::HostStepObject`). diff --git a/crates/metal2vulkan-runtime/src/render/extended_shadow.rs b/crates/metal2vulkan-runtime/src/render/extended_shadow.rs index 5fd8167a3..381e28fd0 100644 --- a/crates/metal2vulkan-runtime/src/render/extended_shadow.rs +++ b/crates/metal2vulkan-runtime/src/render/extended_shadow.rs @@ -410,10 +410,11 @@ fn color( impl RenderCommandEncoder { /// The shadows a draw binds: the held ones, none while the encoder records an execution's /// commands or a capture draw. - pub(super) fn extended_shadows_bound(&self) -> BTreeSet { + pub(super) fn extended_shadows_bound(&self) -> &BTreeSet { + static NONE: BTreeSet = BTreeSet::new(); match self.replaying || self.capture_addresses().is_some() { - true => BTreeSet::new(), - false => self.extended.live.clone(), + true => &NONE, + false => &self.extended.live, } } @@ -526,8 +527,7 @@ impl RenderCommandEncoder { return; } let graphics = &pipeline.base().graphics; - let touched: Vec = bound - .into_iter() + let touched: Vec = (bound.iter().copied()) .filter(|&c| reads_color(graphics, c) || writes_color(graphics, c)) .collect(); self.extended.end(&touched); diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index 7f5db64b7..5c1160c7c 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -1088,9 +1088,11 @@ impl RenderCommandEncoder { let textures = self.tile.textures.values().chain(self.residency.textures()); let mut shadows = InstanceShadows::default(); shadows.add(&shadow::shadow_uses(textures, &uses), &uses); + let mut writes = Vec::new(); let bound = { let mut state = self.core.command_buffer().state(); - binding::bind(call, &device, &mut state, &plan, &command, &tables, None)? + let into = (None, &mut writes); + binding::bind(call, &device, &mut state, &plan, &command, &tables, into)? }; // The formats its notices name, where the device announces any of its variant's kinds // at every occurrence (announced as the dispatch records, below), taken while its @@ -1133,7 +1135,7 @@ impl RenderCommandEncoder { let objects = Arc::clone(variant.objects()); // Set 0 per dispatch; set 1 the device's (written below, once nothing refuses). let (heap_writes, writes): (Vec<_>, Vec<_>) = - bound.writes.into_iter().partition(|write| write.set > 0); + writes.into_iter().partition(|write| write.set > 0); let set = objects.set_zero(&mut self.core.command_buffer().state().descriptors)?; // SAFETY: the set was just allocated and no command uses it yet; every buffer, view // and sampler written is live (the command buffer retains them below, and a refusal @@ -1144,7 +1146,8 @@ impl RenderCommandEncoder { .fold(vk::PipelineStageFlags2::empty(), |all, used| { all | used.read.stages | used.write.stages }); - self.core.note_reaching(stages, &uses, uses.resident())?; + self.core + .note_reaching(stages, (&*uses, uses.resident()), None)?; self.unordered.add(&uses); self.unordered_dispatches.add(&uses); let heap_set = match heap { diff --git a/crates/metal2vulkan-runtime/src/render_pass.rs b/crates/metal2vulkan-runtime/src/render_pass.rs index dbe63914f..8ff8cb7ad 100644 --- a/crates/metal2vulkan-runtime/src/render_pass.rs +++ b/crates/metal2vulkan-runtime/src/render_pass.rs @@ -1238,8 +1238,9 @@ pub(super) fn layout( } _ => descriptor, }; - let mut colors: Vec> = Vec::new(); - let mut extents: Vec<([u32; 2], u32)> = Vec::new(); + // One entry each color attachment: room for them all at once, so no color target moves. + let mut colors: Vec> = + Vec::with_capacity(descriptor.color_attachments.len()); let positioned = Some(!descriptor.sample_positions.is_empty()); for (index, color) in descriptor.color_attachments.iter().enumerate() { let which = Attachment::Color(index as u32); diff --git a/crates/metal2vulkan-runtime/src/resource_ids.rs b/crates/metal2vulkan-runtime/src/resource_ids.rs index b3dc48069..13acc72dc 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids.rs @@ -299,6 +299,10 @@ pub(super) struct ResourceIds { /// How many holders hold a sampler ID now (the module docs' live count), shared with the /// device, which reads it without this lock ([`ResourceIds::sampler_id_reads`]). sampler_ids_live: Arc, + /// How many times a sampler ID's slot took a holder or let one go, shared with the device, + /// which reads it without this lock ([`ResourceIds::sampler_id_reads`]): while it holds, the + /// live states [`samplers`](Self::samplers) lists are the ones it listed. + sampler_slots_changed: Arc, } /// What a device reads of its sampler IDs without their lock: the live count and the sampler @@ -307,6 +311,8 @@ pub(super) struct ResourceIds { pub(super) struct SamplerIdReads { pub(super) live: Arc, pub(super) pool_size: Arc, + /// The count of changes of the sampler IDs' slots (`ResourceIds::sampler_slots_changed`). + pub(super) slots_changed: Arc, } impl Default for ResourceIds { @@ -325,6 +331,7 @@ impl Default for ResourceIds { libraries: BTreeMap::new(), functions: BTreeMap::new(), sampler_ids_live: Arc::default(), + sampler_slots_changed: Arc::default(), } } } @@ -350,9 +357,15 @@ impl ResourceIds { SamplerIdReads { live: Arc::clone(&self.sampler_ids_live), pool_size: Arc::clone(&self.samplers.pool_size), + slots_changed: Arc::clone(&self.sampler_slots_changed), } } + /// A sampler ID's slot took a holder or let one go: the device's live states may differ. + fn sampler_slot_changed(&self) { + self.sampler_slots_changed.fetch_add(1, Ordering::AcqRel); + } + /// A holder took a sampler ID (`taken`) or gave one back: the live count follows. fn count_sampler_id(&self, taken: bool) { if taken { @@ -462,16 +475,20 @@ impl ResourceIds { self.released_pipelines.get(&id).copied() } - /// The live holders of sampler IDs, in ID order: the states a sampler table lists. - pub(super) fn samplers(&self) -> Vec> { - self.samplers + /// The live holders of sampler IDs, in ID order: the states a sampler table lists, with the + /// count of the slots' changes they are live at (`sampler_slots_changed`). + pub(super) fn samplers(&self) -> (u64, Vec>) { + let changed = self.sampler_slots_changed.load(Ordering::Acquire); + let states = self + .samplers .slots .values() .filter_map(|slot| match &slot.holder { Holder::Sampler(state) => state.upgrade(), _ => None, }) - .collect() + .collect(); + (changed, states) } } @@ -830,6 +847,9 @@ impl IdHold { generation, }, ); + if self.space == IdSpace::Sampler { + all.sampler_slot_changed(); + } } /// The ID. @@ -868,6 +888,9 @@ impl Drop for IdHold { if let Some(kind) = kind { all.released_pipelines.insert(self.id, (kind, self.serial)); } + if self.space == IdSpace::Sampler { + all.sampler_slot_changed(); + } } } } diff --git a/crates/metal2vulkan-runtime/src/sampler.rs b/crates/metal2vulkan-runtime/src/sampler.rs index 1663c7f4e..1de71ea31 100644 --- a/crates/metal2vulkan-runtime/src/sampler.rs +++ b/crates/metal2vulkan-runtime/src/sampler.rs @@ -504,8 +504,98 @@ impl Device { /// The live sampler states, in resource-ID order, each the holder of its ID /// (`resource_ids.rs`): what an argument buffer can name (`BindState::argument_samplers`). pub(super) fn argument_samplers(&self) -> Vec { - let states = lock(&self.shared().resource_ids).samplers(); - states.into_iter().map(SamplerState).collect() + self.argument_samplers_at().1 + } + + /// [`argument_samplers`](Self::argument_samplers), with the count of the sampler IDs' slots' + /// changes they are live at ([`sampler_slots_changed`](Self::sampler_slots_changed)). + fn argument_samplers_at(&self) -> (u64, Vec) { + let (changed, states) = lock(&self.shared().resource_ids).samplers(); + (changed, states.into_iter().map(SamplerState).collect()) + } + + /// [`argument_samplers_at`](Self::argument_samplers_at), for a draw's listing: counted + /// (`WorkCounts::argument_samplers_taken`). + fn argument_samplers_for_draw(&self) -> (u64, Vec) { + self.shared().counts.argument_samplers_taken(); + self.argument_samplers_at() + } + + /// The count of the changes of the sampler IDs' slots so far: while it holds, the live + /// sampler states are the ones [`argument_samplers`](Self::argument_samplers) answered at it. + pub(super) fn sampler_slots_changed(&self) -> u64 { + self.shared() + .sampler_ids + .slots_changed + .load(Ordering::Acquire) + } +} + +/// The device's live sampler states a draw lists (`BindState::argument_samplers`), each at the +/// heap element of its resource ID, taken from the device only where the draw needs them +/// (`RenderCommandEncoder::settle_draw`): a kept bind state listed at the count of the sampler +/// IDs' slots' changes that still holds lists them already (`LiveBind::listed_at`), and a draw +/// that writes no heap element and names no state in a notice takes none. +pub(super) struct ArgumentSamplers { + /// The states and the count of slot changes they were live at, once taken. + taken: Option<(u64, Vec)>, + /// Those the draw's variant's set-1 sampler arrays leave out were dropped + /// (`heap_sets::fit_samplers`): the states are no longer every live one. + trimmed: bool, +} + +impl ArgumentSamplers { + /// None taken yet. + pub(super) fn untaken() -> ArgumentSamplers { + ArgumentSamplers { + taken: None, + trimmed: false, + } + } + + /// `device`'s, taken now. + pub(super) fn taken(device: &Device) -> ArgumentSamplers { + ArgumentSamplers { + taken: Some(device.argument_samplers_for_draw()), + trimmed: false, + } + } + + /// The states, taken from `device` now where none were yet. + pub(super) fn take(&mut self, device: &Device) -> &mut Vec { + let (_, states) = self + .taken + .get_or_insert_with(|| device.argument_samplers_for_draw()); + states + } + + /// The states, where they were taken. + pub(super) fn states(&self) -> Option<&[SamplerState]> { + self.taken.as_ref().map(|(_, states)| &states[..]) + } + + /// The count of slot changes every live state is listed at: where the states were taken + /// and not trimmed. + pub(super) fn listed_at(&self) -> Option { + match (&self.taken, self.trimmed) { + (Some((changed, _)), false) => Some(*changed), + _ => None, + } + } + + /// Keep those of the taken states that `set`, the variant's set 1, holds + /// (`heap_sets::fit_samplers`, `unlisted` saying so): whether every one fits. + pub(super) fn fit( + &mut self, + set: Option<&metal2vulkan::pipeline::DescriptorSetLayout>, + unlisted: &mut Option<(u64, u64)>, + ) -> bool { + let Some((_, states)) = &mut self.taken else { + return set.is_none(); + }; + let fits = super::heap_sets::fit_samplers(set, states, unlisted); + self.trimmed |= !fits; + fits } } diff --git a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs index 9936deb56..84bd0c068 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs @@ -485,3 +485,36 @@ fn a_sample_through_a_second_key_waits_for_a_render_through_the_first() { }] ); } + +/// The version counts each change of what `augment` reads: a buffer joining another's memory, +/// a key placed, rebound or unplaced, a buffer forgotten. A buffer over a memory of its own, a +/// rebound buffer leaving its memory, a reported remap, and `augment` itself change nothing it +/// reads, and leave it standing. +#[test] +fn the_version_counts_each_change_augment_reads() { + let aliases = Aliases::default(); + let (first, second, placed) = (ResourceKey::new(), ResourceKey::new(), ResourceKey::new()); + let version = aliases.version(); + join(&aliases, first, (0x40000, 0x1000)); + assert_eq!(aliases.version(), version, "a memory of its own"); + join(&aliases, second, (0x40000, 0x1000)); + let joined = aliases.version(); + assert!(joined > version, "joined"); + aliases.augment(&[write(second, 0..64)]); + aliases.leave(second); + assert_eq!(aliases.version(), joined, "augment, leave and a remap"); + let mut last = joined; + let mut changed = |what: &str| { + let now = aliases.version(); + assert!(now > last, "{what}"); + last = now; + }; + aliases.place(placed, (0x80000, 0x2000)); + changed("placed"); + aliases.place(placed, (0x90000, 0x2000)); + changed("rebound"); + aliases.unplace(placed); + changed("unplaced"); + aliases.forget(second); + changed("forgotten"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 7d04c495f..e50bbe87f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -99,6 +99,7 @@ mod mipmap_scratch; mod multisample_buffer_copy; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod nan_signs; +mod noted_apart; mod numbered_samplers; mod options; mod own; @@ -137,6 +138,8 @@ mod surface_two_planes; mod teardown_threads; mod texture; mod texture_descriptor; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod texture_facts; mod tracker; mod trails; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/noted_apart.rs b/crates/metal2vulkan-runtime/src/tests/noted_apart.rs new file mode 100644 index 000000000..c43339510 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/noted_apart.rs @@ -0,0 +1,68 @@ +//! The last command an unordered encoder noted apart (`noted_apart.rs`). + +use super::super::noted_apart::{NotedApart, NotedInto}; +use super::super::resource::ResourceKey; +use super::super::tracker::{Access, Use, UseRange}; +use ash::vk; +use std::collections::BTreeSet; + +/// A fragment shader's read of `bytes` of the buffer `key`. +fn read(key: ResourceKey, bytes: std::ops::Range) -> Use { + let access = Access::new( + vk::PipelineStageFlags2::FRAGMENT_SHADER, + vk::AccessFlags2::SHADER_STORAGE_READ, + ); + Use::reads(key, true, UseRange::Bytes(bytes), access) +} + +/// A command reaching a buffer through the resident set alone is the last one noted while its +/// uses, the keys it so reaches, its stages and the state it is noted into are the last's: not +/// with another key reached so, another use, other stages, another core, a part or held image +/// more, a device with buffers over host pages where it had none, or after the host aliases +/// changed (their version). +#[test] +fn a_command_reaching_the_same_resident_keys_is_noted_already() { + let (argument, reached, other) = (ResourceKey::new(), ResourceKey::new(), ResourceKey::new()); + let uses = [read(argument, 0..64), read(reached, 0..4096)]; + let resident = BTreeSet::from([reached]); + let stages = vk::PipelineStageFlags2::FRAGMENT_SHADER; + let into = NotedInto { + core: 7, + parts: 1, + held: 0, + rebinds: false, + aliases: 3, + }; + let mut noted = NotedApart::default(); + assert!(!noted.holds(stages, (&uses, &resident), into)); + noted.note(stages, (&uses, &resident), into); + assert!(noted.holds(stages, (&uses, &resident), into)); + // The same uses, reaching no key or another through the resident set alone. + assert!(!noted.holds(stages, (&uses, &BTreeSet::new()), into)); + assert!(!noted.holds(stages, (&uses, &BTreeSet::from([argument])), into)); + assert!(!noted.holds(stages, (&uses, &BTreeSet::from([reached, other])), into)); + // Another use, other stages. + let more = [read(argument, 0..64), read(reached, 0..8192)]; + assert!(!noted.holds(stages, (&more, &resident), into)); + let vertex = vk::PipelineStageFlags2::VERTEX_SHADER; + assert!(!noted.holds(vertex, (&uses, &resident), into)); + // Another state noted into. + let changed = [ + NotedInto { core: 8, ..into }, + NotedInto { parts: 2, ..into }, + NotedInto { held: 1, ..into }, + NotedInto { + rebinds: true, + ..into + }, + NotedInto { aliases: 4, ..into }, + ]; + for other in changed { + assert!(!noted.holds(stages, (&uses, &resident), other)); + } + // Noted again with another resident key: that one holds, the first no longer. + let others = BTreeSet::from([other]); + noted.note(stages, (&uses, &others), into); + assert!(noted.holds(stages, (&uses, &others), into)); + assert!(!noted.holds(stages, (&uses, &resident), into)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/texture_facts.rs b/crates/metal2vulkan-runtime/src/tests/texture_facts.rs new file mode 100644 index 000000000..1c776d5cf --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/texture_facts.rs @@ -0,0 +1,72 @@ +//! A texture's binding facts (`Texture::facts`), worked out at the first read and kept: the kept +//! facts are the ones worked out again from what the texture was made with, after a view of it +//! was made, with a depth texture's twin, and a view's are its own. (Whether a storage binding +//! takes the usage shadow is a test of the image's and the texture's usage, made with them, not +//! of the shadow, which is made later.) +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. + +use crate::{Device, DeviceKind, DeviceOptions, ResourceOptions, Texture, TextureDescriptor}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; + +/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU. +fn device() -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// A private 2D texture of `format`, 16 by 16, of `usage`. +fn texture(device: &Device, format: PixelFormat, usage: TextureUsage) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(format, 16, 16, false); + descriptor.usage = usage; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() +} + +/// That `texture`'s kept facts are the ones worked out again now. +fn kept_as_worked_out(texture: &Texture, what: &str) { + assert_eq!( + texture.facts(), + texture.worked_out_facts(), + "{what}: the kept facts are not the ones worked out again" + ); +} + +#[test] +fn a_texture_s_kept_facts_are_the_ones_worked_out_again_and_a_view_s_its_own() { + let device = device(); + let read_write = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let color = texture( + &device, + PixelFormat::RGBA8Unorm, + read_write | TextureUsage::PIXEL_FORMAT_VIEW, + ); + let first = color.facts(); + // A view made after the texture's facts were kept has its own, of its own format. + let view = color.new_texture_view(PixelFormat::RGBA8Uint).unwrap(); + assert_eq!(view.facts().pixel_format, PixelFormat::RGBA8Uint); + assert_eq!(first.pixel_format, PixelFormat::RGBA8Unorm); + kept_as_worked_out(&view, "a view made after its texture's facts were kept"); + kept_as_worked_out(&color, "a texture after a view of it was made"); + assert_eq!(color.facts(), first, "kept once made"); + // A depth texture's twin is made with its image: its facts say so from the first read. + let depth = texture( + &device, + PixelFormat::Depth32Float, + TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET, + ); + let facts = depth.facts(); + assert_eq!(facts.depth_twin, depth.twin_image().is_some()); + kept_as_worked_out(&depth, "a depth texture"); +} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index be8fbd48c..72756a19b 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -370,13 +370,14 @@ pub(super) struct TextureShared { /// `HeapPlace::heap`), so a command buffer that keeps the image keeps nothing of the heap but /// its memory, and the heap goes at the program's release, as Metal frees it. heap: Option, - /// The formats a storage binding views the texture's pixel format in - /// (`storage_view_formats`), found at the first binding plan that reads them ([`facts`]) and - /// kept: they follow from the pixel format and the device's profile alone, and finding them - /// again at every draw was 2.2% of the thread encoding a window server's frame on RADV. + /// The facts a binding plan reads of the texture ([`facts`]), worked out at the first draw or + /// plan that reads them and kept: they follow from what the texture is made with alone (its + /// record, its image's plan and twins, its storage) and the device's profile, none of which + /// changes while it lives. Working them out again at every draw that binds it was each + /// bound texture's walk of its storage view formats and image plan. /// /// [`facts`]: Texture::facts - storage_formats: OnceLock>, + facts: OnceLock, } impl Drop for TextureShared { @@ -4673,7 +4674,7 @@ impl Texture { kept_backings: Mutex::new(Vec::new()), render_shadow: Mutex::new(None), heap, - storage_formats: OnceLock::new(), + facts: OnceLock::new(), })); if let Some(objects) = texture.0.storage.objects() { objects.object_made(); @@ -5161,8 +5162,14 @@ impl Texture { Ok(&self.image()?.resolves) } - /// The facts a binding plan reads of the texture. + /// The facts a binding plan reads of the texture, worked out once and kept + /// (`TextureShared::facts`). pub(super) fn facts(&self) -> TextureFacts { + *self.0.facts.get_or_init(|| self.worked_out_facts()) + } + + /// The facts a binding plan reads of the texture, worked out from what it was made with. + pub(super) fn worked_out_facts(&self) -> TextureFacts { let record = self.0.record.bound(); let mut facts = texture_facts(&record); facts.depth_twin = self.twin_image().is_some(); @@ -5173,11 +5180,8 @@ impl Texture { // the shadow, made with them. facts.own_format_views = !self.needs_usage_shadow(true) && self.image().is_ok_and(|image| { - let formats = self.0.storage_formats.get_or_init(|| { - let profile = self.device().compile_device().profile(); - storage_view_formats(record.pixel_format, profile) - }); - formats + let profile = self.device().compile_device().profile(); + storage_view_formats(record.pixel_format, profile) .iter() .any(|&format| !views_as(image.plan(), format, false)) }); diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index 7285f8f29..a20ad18bb 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -620,6 +620,30 @@ impl Few { self.first = Some(self.rest.remove(0)); } } + + fn len(&self) -> usize { + usize::from(self.first.is_some()) + self.rest.len() + } + + /// Change the values as `change` changes them as one list, in order. + fn change_all(&mut self, change: impl FnOnce(&mut Vec)) { + if let Some(first) = self.first.take() { + self.rest.insert(0, first); + } + change(&mut self.rest); + if !self.rest.is_empty() { + self.first = Some(self.rest.remove(0)); + } + } +} + +impl<'a, T> IntoIterator for &'a Few { + type Item = &'a T; + type IntoIter = std::iter::Chain, std::slice::Iter<'a, T>>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } } impl IntoIterator for Few { @@ -964,8 +988,10 @@ pub(super) struct EncoderUses { /// The uses of one part of an encoder. struct Part { - /// The tracked uses so far, one per range, at most [`ENTRIES_PER_KEY`] per resource. - tracked: KeyMap>>, + /// The tracked uses so far, one per range, at most [`ENTRIES_PER_KEY`] per resource: most + /// resources have one, held inline ([`Few`]), so a command's first use of a resource + /// allocates nothing of its own. + tracked: KeyMap>>, stages: vk::PipelineStageFlags2, } @@ -1042,7 +1068,7 @@ impl EncoderUses { None => ranges.push(used.clone()), } if ranges.len() > ENTRIES_PER_KEY { - coalesce_uses(ranges); + ranges.change_all(coalesce_uses); } } } @@ -1121,6 +1147,12 @@ impl EncoderUses { } } + /// How many parts the encoder's commands were recorded in so far: one more at each + /// [`split`](Self::split). + pub(super) fn parts(&self) -> usize { + self.parts.len() + } + /// The part commands are recorded into now. fn current(&mut self) -> &mut Part { let last = self.parts.len() - 1; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 3a16fb7e8..fdd5d02b6 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -103,6 +103,11 @@ pub(crate) struct Counters { stand_in_copies_made: AtomicU64, stand_in_copies_made_at_draws: AtomicU64, draw_shapes_made: AtomicU64, + draw_shapes_found: AtomicU64, + argument_samplers_taken: AtomicU64, + bind_views_worked_out: AtomicU64, + stage_tables_read: AtomicU64, + commands_noted_as_before: AtomicU64, draws_settled: AtomicU64, depth16_sided_draws: AtomicU64, bound_notices_made: AtomicU64, @@ -620,6 +625,36 @@ impl Counters { self.draw_shapes_made.fetch_add(1, Ordering::Relaxed); } + /// A draw found the bind shape of its bind state among those its drawing state settled + /// lately (`LiveBind::shape`). + pub(crate) fn draw_shape_found(&self) { + self.draw_shapes_found.fetch_add(1, Ordering::Relaxed); + } + + /// A draw took the device's live sampler states to list (`sampler::ArgumentSamplers`). + pub(crate) fn argument_samplers_taken(&self) { + self.argument_samplers_taken.fetch_add(1, Ordering::Relaxed); + } + + /// A render encoder's bind worked out a texture slot's view that its bind memo did not keep + /// (`binding::BindMemo`). + pub(crate) fn bind_view_worked_out(&self) { + self.bind_views_worked_out.fetch_add(1, Ordering::Relaxed); + } + + /// A draw read a stage's table into its encoder's kept bind state + /// (`ArgumentTable::refresh_reading`). + pub(crate) fn stage_table_read(&self) { + self.stage_tables_read.fetch_add(1, Ordering::Relaxed); + } + + /// A draw's uses were noted already: the last command its encoder noted had them + /// (`noted_apart.rs`). + pub(crate) fn command_noted_as_before(&self) { + self.commands_noted_as_before + .fetch_add(1, Ordering::Relaxed); + } + /// A draw settled its variant and plan from its bind shape (`GraphicsState::settle_shape`). pub(crate) fn draw_settled(&self) { self.draws_settled.fetch_add(1, Ordering::Relaxed); @@ -1413,6 +1448,31 @@ pub struct WorkCounts { /// Bind shapes draws made of their bind states: none for a draw whose bound slots keep their /// shapes and whose other bind state is its encoder's last draw's. pub draw_shapes_made: u64, + /// Bind shapes draws found among those their drawing states settled lately, compared with + /// their bind states in place: none for a draw whose bound slots keep their shapes and whose + /// other bind state's shape is its encoder's last draw's (values no shape reads, such as the + /// depth/stencil state, the stencil references or the blend color, may differ). + pub draw_shapes_found: u64, + /// Draws (and commands of other encoders that settle as draws do) that took the device's + /// live sampler states to list as their argument samplers: none for a draw whose kept bind + /// state lists them at the count of their slots' changes that still holds, whose variant has + /// no set-1 arrays and names no state in a notice (`sampler::ArgumentSamplers`). + pub argument_samplers_taken: u64, + /// Texture slot views render encoders' binds worked out: none for a bind of a texture, as a + /// view, that a bind of the same or an earlier encoder of the device bound, while no image of + /// the device let its views go (`binding::BindMemo`). + pub bind_views_worked_out: u64, + /// Stage tables (vertex, fragment, object, mesh) that draws, and commands of other encoders + /// that settle as draws do, read into their encoder's kept bind state: four a draw at most, + /// none for a table no call changed since a draw read it through the same drawing state's + /// interface, with the same samplers' address-mode maps, while no no-copy buffer was rebound + /// or detached (`live_bind::ReadFrom`). + pub stage_tables_read: u64, + /// Draws whose uses their encoder did not note again: the last command it noted had the same + /// uses, with the same uses of host aliases added, into the same part, with the same images + /// held in their attachment layout, and none of them reached through the resident set alone + /// (`noted_apart.rs`). + pub commands_noted_as_before: u64, /// Draws that settled their variant and plan from their bind shapes: none for a draw whose /// bind shape is one of the latest its pipeline state settled in the same buffer forms. pub draws_settled: u64, @@ -1805,6 +1865,11 @@ impl Device { .stand_in_copies_made_at_draws .load(Ordering::Relaxed), draw_shapes_made: counters.draw_shapes_made.load(Ordering::Relaxed), + draw_shapes_found: counters.draw_shapes_found.load(Ordering::Relaxed), + argument_samplers_taken: counters.argument_samplers_taken.load(Ordering::Relaxed), + bind_views_worked_out: counters.bind_views_worked_out.load(Ordering::Relaxed), + stage_tables_read: counters.stage_tables_read.load(Ordering::Relaxed), + commands_noted_as_before: counters.commands_noted_as_before.load(Ordering::Relaxed), draws_settled: counters.draws_settled.load(Ordering::Relaxed), depth16_sided_draws: counters.depth16_sided_draws.load(Ordering::Relaxed), bound_notices_made: counters.bound_notices_made.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/address_maps.rs b/crates/metal2vulkan-validation/src/runtime_lane/address_maps.rs index dfda88869..35e77a7a6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/address_maps.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/address_maps.rs @@ -13,7 +13,8 @@ //! the mapped modes, through the same pipeline variant (its SPIR-V) and the same bind shape //! but for the map the shape states, so every emulation that reads the mode follows; a map that //! leaves the bound modes as they are changes neither. The same holds for a fragment function's -//! texture sampled through a runtime sampler slot, the consumer's path; +//! texture sampled through a runtime sampler slot, the consumer's path, and for one encoder's +//! draws that rebind that slot between a mapped texture and its texels unmapped; //! - a constexpr sampler whose modes a mapped texture's map changes samples it through its slot's //! pipeline variant, its immutable sampler holding the mapped modes; one whose modes the map //! keeps samples the texture as an unmapped one, through the unmapped texture's pipeline; a map @@ -378,23 +379,7 @@ fn a_mapped_texture_samples_as_its_mapped_sampler() { #[test] fn a_fragments_runtime_sampler_takes_its_textures_map() { on_device(|device, _| { - let bitcode = llvm_assemble(&engine_dir().join("tob_renders.ll")).unwrap(); - let library = device.new_library_with_air(&bitcode).unwrap(); - let function = |name| { - StageSource::Function( - library - .new_function_with_name(name) - .unwrap() - .function_descriptor(), - ) - }; - let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); - descriptor.fragment = Some(function("tob_sample")); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); - let pipeline = device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .unwrap(); + let pipeline = sampling_pipeline(device); let plain = texture(device, TextureUsage::SHADER_READ, |_| {}); let mut wrong = Vec::new(); let (mut checked, mut refusals) = (0usize, 0usize); @@ -476,6 +461,129 @@ fn a_fragments_runtime_sampler_takes_its_textures_map() { }); } +/// A pipeline state of `tob_renders`'s `tob_rect` (a rectangle of the corners at vertex buffer 0) +/// and `tob_sample` into an `RGBA32Float` color attachment. +fn sampling_pipeline(device: &Device) -> RenderPipelineState { + let bitcode = llvm_assemble(&engine_dir().join("tob_renders.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = |name| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); + descriptor.fragment = Some(function("tob_sample")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// One encoder's draws that rebind the fragment texture slot in turn to a mapped texture and to +/// the same texels unmapped, alike but for the map, through one repeating sampler state (the +/// consumer's second rule maps repeat to clamp to edge): each texture draws twice in a row over +/// its half of the target, so a bind takes the view and the sampler its write took last, and +/// after each rebind those an earlier bind took, the sampler's modes mapped or not. Each half is, +/// bit for bit, what a draw of the unmapped texels over the whole target draws there through the +/// mode its texture is sampled with ([`drawn`]): clamp to edge for the mapped texture, repeat for +/// the other; and the two modes draw other texels in each half. +#[test] +fn draws_rebinding_a_slot_between_a_texture_and_its_mapped_twin_keep_each_view_and_sampler() { + on_device(|device, _| { + let pipeline = sampling_pipeline(device); + let plain = texture(device, TextureUsage::SHADER_READ, |_| {}); + let mapped = texture(device, TextureUsage::SHADER_READ, |d| { + d.address_mode_map = all_edges(); + }); + assert_eq!(all_edges().mode(Mode::Repeat), Mode::ClampToEdge); + let filter = SamplerMinMagFilter::Nearest; + let border = SamplerBorderColor::TransparentBlack; + let (repeat, clamp) = states(device, Mode::Repeat, all_edges(), filter, border).unwrap(); + let (w, h) = (u64::from(4 * WIDTH), u64::from(3 * HEIGHT)); + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA32Float, w, h, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::shared(); + let target = device.new_texture(&target).unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&pipeline).unwrap(); + encoder + .set_fragment_sampler_state(Some(&repeat), 0) + .unwrap(); + let halves = [ + (&mapped, [-1.0f32, -1.0, 0.0, 1.0]), + (&plain, [0.0, -1.0, 1.0, 1.0]), + ]; + for _ in 0..3 { + for (texture, corners) in &halves { + let corners: Vec = corners.iter().flat_map(|v| v.to_le_bytes()).collect(); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + for _ in 0..2 { + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + } + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + let mut bytes = vec![0u8; (16 * w * h) as usize]; + target + .get_bytes(&mut bytes, 16 * w, 0, Region::new_2d(0, 0, w, h), 0, 0) + .unwrap(); + let got: Vec<[u32; 4]> = bytes + .as_chunks::<16>() + .0 + .iter() + .map(|v| { + let w = |i: usize| u32::from_le_bytes([v[i], v[i + 1], v[i + 2], v[i + 3]]); + [w(0), w(4), w(8), w(12)] + }) + .collect(); + let clamped = drawn(device, &pipeline, &plain, &clamp).unwrap().texels; + let repeated = drawn(device, &pipeline, &plain, &repeat).unwrap().texels; + // The left half's pixels, or the right half's, by row. + let half = |texels: &[[u32; 4]], right: bool| -> Vec<[u32; 4]> { + (texels.iter().enumerate()) + .filter(|&(at, _)| (at as u64 % w >= w / 2) == right) + .map(|(_, &texel)| texel) + .collect() + }; + for right in [false, true] { + assert_ne!( + half(&clamped, right), + half(&repeated, right), + "right {right}" + ); + } + assert_eq!( + half(&got, false), + half(&clamped, false), + "the mapped texture's half" + ); + assert_eq!( + half(&got, true), + half(&repeated, true), + "the unmapped texture's half" + ); + }); +} + /// What one draw of `pipeline` (`tob_rect` over the whole target, `tob_sample`) into an /// `RGBA32Float` target four textures wide and three high read from `texture` through `sampler`: /// each pixel's bits, and the executed variant's SPIR-V and bind shape. `Err` for the draw's diff --git a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs index 2d30799c8..8ce2080e4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs @@ -10,10 +10,23 @@ //! another shape (a texture of another format, a slot's binding of another class) finds its //! shape among those the state settled lately, or makes it and settles it: draws alternating //! between two shapes make and settle each once, and a pass that draws as the one before it -//! makes and settles none. -//! - **Pipelines.** A draw of a pipeline state whose last draw found its `VkPipeline` made, of -//! the same variant and an equal key, finds that entry again without looking the key up -//! (`WorkCounts::graphics_pipelines_looked_up`), states switched between included. +//! makes and settles none. A draw that changes only values no shape reads (the depth/stencil +//! state, the stencil references, the blend color) keeps its encoder's last draw's shape, and +//! looks for none among those settled (`WorkCounts::draw_shapes_found`); nor do draws that +//! switch between pipeline states whose bind states differ, each starting from its own pipeline +//! state's last draw's state, which the encoder set aside. +//! - **Zeroed colors.** Draws into a pass of a color their pipeline state lacks, which Metal +//! zeroes where they cover it, read the colors they zero where their encoder keeps them, compare +//! them with their bind state's in place, and copy none while those hold (allocations counted on +//! the drawing thread). +//! - **Argument samplers.** A draw lists the device's live sampler states as its encoder's bind +//! state keeps them, without taking them again, until a state is made or goes +//! (`WorkCounts::argument_samplers_taken`). +//! - **Views.** A pass that binds the textures the pass before it bound works out none of their +//! views (`WorkCounts::bind_views_worked_out`); a texture made after one of them went works out +//! its own. +//! - **Stage tables.** A draw reads into its encoder's bind state only the stage tables a call +//! changed since a draw read them, through the same pipeline state's interface //! - **Recorded states.** A draw records into its secondary command buffer only the state //! commands that set what changed since the draws before it there //! (`WorkCounts::draw_states_recorded`): of an unchanged state, none but its own descriptor set; @@ -21,7 +34,8 @@ //! - **Retains.** An argument table that binds the objects its encoder last retained it with is //! not retained again (`WorkCounts::argument_tables_retained`): one whose objects changed is, //! and an object the program let go of after its draw lives until the command buffer -//! completes. +//! completes. Its encoder lists every object a retain took or held already +//! (`CommandBuffer::ended_encoders`), a slot rebound to one that looks like its last included. //! //! The pipeline is the owned fixture `tob_renders`'s `tob_rect` (a rectangle of the corners at //! vertex buffer 0) and `tob_sample` (texture 0 through sampler 0, where its pixel lies). @@ -29,8 +43,7 @@ use super::degrade_notices::on_device; use super::{buffer_with, WAIT}; use crate::air_library::AirLibrary; -use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::metal::state::DepthStencilDescriptor; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ @@ -58,6 +71,12 @@ struct Scene { /// A pipeline state of `tob_rect` and `tob_sample` into an `RGBA8Unorm` color attachment, which /// `blends` (Metal's default factors, which store the fragment's color) or not. fn pipeline(device: &Device, blends: bool) -> RenderPipelineState { + pipeline_of(device, "tob_sample", blends) +} + +/// A pipeline state of `tob_rect` and `tob_renders`'s fragment function `fragment` into an +/// `RGBA8Unorm` color attachment, which `blends` or not ([`pipeline`]). +fn pipeline_of(device: &Device, fragment: &str, blends: bool) -> RenderPipelineState { let ll = engine_dir().join("tob_renders.ll"); let library = device .new_library_with_air(&llvm_assemble(&ll).unwrap()) @@ -71,7 +90,7 @@ fn pipeline(device: &Device, blends: bool) -> RenderPipelineState { ) }; let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); - descriptor.fragment = Some(function("tob_sample")); + descriptor.fragment = Some(function(fragment)); let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm); color.blending_enabled = blends; descriptor.color_attachments[0] = Some(color); @@ -213,6 +232,195 @@ fn draws_of_an_unchanged_state_settle_and_retain_it_once() { }); } +/// Draws that change between them only values no bind shape reads, one column each: the stencil +/// references, the blend color, and the depth/stencil state (of a depth test every fragment +/// passes, with and without depth writes). None past the first looks for a bind shape, makes one +/// or settles: each keeps its encoder's last draw's. Each column is the texture's. +#[test] +fn draws_that_change_only_values_no_shape_reads_keep_their_shape() { + on_device(|device, _| { + let scene = Scene::new(device); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let ll = engine_dir().join("tob_renders.ll"); + let library = device + .new_library_with_air(&llvm_assemble(&ll).unwrap()) + .unwrap(); + let function = |name| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); + descriptor.fragment = Some(function("tob_sample")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + descriptor.depth_format = Some(PixelFormat::Depth32Float); + let pipeline = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let mut depth = TextureDescriptor::texture_2d(PixelFormat::Depth32Float, SIDE, SIDE, false); + depth.usage = TextureUsage::RENDER_TARGET; + depth.resource_options = ResourceOptions::private(); + let depth = device.new_texture(&depth).unwrap(); + let states = [false, true].map(|writes| { + let mut state = DepthStencilDescriptor::default(); + state.depth_compare_function = CompareFunction::LessEqual; + state.depth_write_enabled = writes; + device.new_depth_stencil_state(&state).unwrap() + }); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(scene.target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 1.0, 1.0); + pass.depth_attachment.texture = Some(depth); + pass.depth_attachment.load_action = LoadAction::Clear; + pass.depth_attachment.store_action = StoreAction::DontCare; + pass.depth_attachment.clear_depth = 1.0; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&pipeline).unwrap(); + encoder + .set_fragment_sampler_state(Some(&scene.sampler), 0) + .unwrap(); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + let mut first = None; + for c in 0..SIDE { + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + encoder.set_stencil_reference_value(c as u32); + let level = c as f32 / SIDE as f32; + encoder.set_blend_color(level, 1.0 - level, level, 1.0); + encoder + .set_depth_stencil_state(&states[(c % 2) as usize]) + .unwrap(); + draw(&mut encoder); + first.get_or_insert_with(|| device.work_counts()); + } + let (first, rest) = (first.unwrap(), device.work_counts()); + encoder.end_encoding().unwrap(); + assert_eq!(grew(&first, &rest, |c| c.draw_shapes_found), 0); + assert_eq!(grew(&first, &rest, |c| c.draw_shapes_made), 0); + assert_eq!(grew(&first, &rest, |c| c.draws_settled), 0); + let pixels = scene.pixels(&command_buffer); + assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); + }); +} + +/// Draws of one encoder take the device's live sampler states to list only where they changed +/// since the listing their encoder's bind state keeps (`WorkCounts::argument_samplers_taken`): +/// none while no sampler state is made or goes; a state made between two draws, and that state +/// gone, each make the next draw take them once. Each column is the texture's. +#[test] +fn draws_take_the_device_s_sampler_states_only_where_they_changed() { + on_device(|device, _| { + let scene = Scene::new(device); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let (command_buffer, mut encoder) = scene.encoder(device); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + let taken = || device.work_counts().argument_samplers_taken; + let mut counts = Vec::new(); + let mut made = None; + for c in 0..SIDE { + // A sampler state made before column 3's draw, gone before column 6's. + if c == 3 { + let mut descriptor = SamplerDescriptor::new(); + descriptor.lod_max_clamp = 7.0; + made = Some(device.new_sampler_state(&descriptor).unwrap()); + } + if c == 6 { + made = None; + } + let before = taken(); + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + draw(&mut encoder); + counts.push(taken() - before); + } + assert!(made.is_none()); + encoder.end_encoding().unwrap(); + // The first draws settle the encoder's state from another's, and may take them. + assert_eq!(counts[2..], [0, 1, 0, 0, 1, 0], "{counts:?}"); + let pixels = scene.pixels(&command_buffer); + assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); + }); +} + +/// Draws read into their encoder's kept bind state only the stage tables a call changed since a +/// draw read them (`WorkCounts::stage_tables_read`): each column's first draw the vertex table, +/// whose bytes it sets, and the fragment table too where it binds another texture; its second +/// draw, with no call before it, none; and every table at the draw after another pipeline state +/// is set, whose interface they are read through. Each second draw's uses are its first's, which +/// its encoder noted already (`WorkCounts::commands_noted_as_before`); so are each first draw's +/// the draw's before it, inline bytes being no use (they lie in the command buffer's upload +/// arena, which hazard tracking leaves alone), another pipeline state of the same stages too, but +/// at the encoder's first draw, which no draw of its noted, and where another texture is bound. +/// Each column is its texture's. +#[test] +fn draws_read_only_the_stage_tables_a_call_changed() { + on_device(|device, _| { + let scene = Scene::new(device); + let blending = pipeline(device, true); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let green = solid(device, PixelFormat::RGBA8Unorm, GREEN); + let (command_buffer, mut encoder) = scene.encoder(device); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + let read = || device.work_counts().stage_tables_read; + let noted = || device.work_counts().commands_noted_as_before; + let mut counts = Vec::new(); + let mut notes = Vec::new(); + for c in 0..SIDE { + match c { + 3 => encoder.set_fragment_texture(Some(&green), 0).unwrap(), + 5 => encoder.set_render_pipeline_state(&blending).unwrap(), + _ => {} + } + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + let (before, noted_before) = (read(), noted()); + draw(&mut encoder); + let (first, noted_first) = (read() - before, noted() - noted_before); + draw(&mut encoder); + counts.push((first, read() - before - first)); + notes.push((noted_first, noted() - noted_before - noted_first)); + } + encoder.end_encoding().unwrap(); + let as_before = [ + (0, 1), + (1, 1), + (1, 1), + (0, 1), + (1, 1), + (1, 1), + (1, 1), + (1, 1), + ]; + assert_eq!(notes, as_before, "{notes:?}"); + // The first draw reads the tables from another encoder's state: all four. + let reads = [ + (4, 0), + (1, 0), + (1, 0), + (2, 0), + (1, 0), + (4, 0), + (1, 0), + (1, 0), + ]; + assert_eq!(counts, reads, "{counts:?}"); + let pixels = scene.pixels(&command_buffer); + for (i, &pixel) in pixels.iter().enumerate() { + let want = match i as u64 % SIDE >= 3 { + true => GREEN, + false => RED, + }; + assert_eq!(pixel, want, "pixel {i}: {pixels:?}"); + } + }); +} + /// Draws that each bind another texture of the same type, format and usage, and other inline /// bytes of the same length, one column each: none past the first makes a bind shape (its /// texture slot keeps its shape) or settles, and each retains the fragment table, whose texture @@ -324,6 +532,49 @@ fn a_pass_that_draws_as_the_one_before_makes_no_shape() { }); } +/// A pass that binds the two textures the pass before it bound works out neither's view: its +/// encoder takes the views the last one's binds found (`WorkCounts::bind_views_worked_out`). +/// One of them let go of and a texture of another color made, a third pass works out the new +/// texture's view alone, and draws its color. Every column is drawn. The textures are +/// `RGBA8Unorm`, as the target, so each texel's bytes are the pixel its column stores. +#[test] +fn a_pass_that_binds_as_the_one_before_works_out_no_view() { + on_device(|device, _| { + let scene = Scene::new(device); + let pass = |textures: &[&Texture; 2]| { + let before = device.work_counts(); + let (command_buffer, mut encoder) = scene.encoder(device); + for c in 0..SIDE { + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + encoder + .set_fragment_texture(Some(textures[(c % 2) as usize]), 0) + .unwrap(); + draw(&mut encoder); + } + encoder.end_encoding().unwrap(); + let after = device.work_counts(); + let worked_out = grew(&before, &after, |c| c.bind_views_worked_out); + (worked_out, scene.pixels(&command_buffer)) + }; + let green = solid(device, PixelFormat::RGBA8Unorm, GREEN); + let other = solid(device, PixelFormat::RGBA8Unorm, GREEN); + let (first, pixels) = pass(&[&green, &other]); + assert_eq!(first, 2); + assert!(pixels.iter().all(|&p| p == GREEN), "{pixels:?}"); + let (second, pixels) = pass(&[&green, &other]); + assert_eq!(second, 0); + assert!(pixels.iter().all(|&p| p == GREEN), "{pixels:?}"); + drop(other); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let (third, pixels) = pass(&[&green, &red]); + assert_eq!(third, 1); + for (at, &pixel) in pixels.iter().enumerate() { + let want = if at.is_multiple_of(2) { GREEN } else { RED }; + assert_eq!(pixel, want, "pixel {at}: {pixels:?}"); + } + }); +} + /// Draws whose vertex buffer slot 0 binds a buffer and inline bytes in turn, a binding of another /// class at the slot each draw, a slot's class being of its shape, make and settle each shape /// once (the state keeps the settles of its latest shapes, among which a draw finds its shape). @@ -402,6 +653,159 @@ fn draws_switching_pipeline_states_find_their_pipelines_again() { }); } +/// Draws that switch at every draw between pipeline states whose bind states differ (`tob_sample`, +/// and `tob_solid`, which reads its color through a uniform view of fragment buffer 0), each +/// binding what it bound before but its column's bytes, find each one's shape kept past the first +/// draw of each: the encoder sets aside the state of the pipeline state it drew before +/// (`LiveBind::select`), so none looks its shape up among those settled +/// (`WorkCounts::draw_shapes_found`), makes one or settles. Before, each draw past the first two +/// looked its shape up, the state its encoder kept having last been read through the other +/// pipeline state's interface. Each column is its own pipeline state's color. +#[test] +fn draws_switching_between_pipeline_states_of_other_states_keep_each_shape() { + on_device(|device, _| { + let scene = Scene::new(device); + let pipelines = [ + scene.pipeline.clone(), + pipeline_of(device, "tob_solid", false), + ]; + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let green: Vec = [0.0f32, 1.0, 0.0, 1.0] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let (command_buffer, mut encoder) = scene.encoder(device); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + encoder.set_fragment_bytes(&green, 0).unwrap(); + let mut first = None; + for c in 0..SIDE { + encoder + .set_render_pipeline_state(&pipelines[(c % 2) as usize]) + .unwrap(); + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + draw(&mut encoder); + if c == 1 { + first = Some(device.work_counts()); + } + } + let (first, rest) = (first.unwrap(), device.work_counts()); + encoder.end_encoding().unwrap(); + assert_eq!(grew(&first, &rest, |c| c.draw_shapes_found), 0); + assert_eq!(grew(&first, &rest, |c| c.draw_shapes_made), 0); + assert_eq!(grew(&first, &rest, |c| c.draws_settled), 0); + let pixels = scene.pixels(&command_buffer); + for (at, &pixel) in pixels.iter().enumerate() { + let want = [RED, GREEN][at % 2]; + assert_eq!(pixel, want, "pixel {at}: {pixels:?}"); + } + }); +} + +/// The most allocations a draw into a pass of a color its pipeline state lacks makes beyond a +/// draw of the same state into a pass of its own colors alone, both of a state unchanged but for +/// its column's bytes ([`draws_into_a_pass_color_their_state_lacks_copy_no_color_set`]), on +/// average: none. The colors the draw zeroes are those the encoder kept as the pipeline state was +/// set, which its settings read in place (`RenderCommandEncoder::draw_colors`), and its bind +/// state compares in place (`Reshape::field_from`), copying them only where they changed. +/// Measured: -0.20 on ANV (UHD 770); 0.80 where the settings copied them, 1.80 where the bind +/// state copied them too. +#[cfg(not(m2v_system_alloc))] +const ZEROED_COLORS_EXTRA: f64 = 0.3; +/// [`ZEROED_COLORS_EXTRA`] in a build with debug assertions, where each draw's checks build its +/// state's whole bind shape (`LiveBind::shape`), the colors it zeroes included. Measured: 0.80 +/// on lavapipe; 1.80 where the settings copied them, on lavapipe and on ANV (UHD 770). +#[cfg(not(m2v_system_alloc))] +const ZEROED_COLORS_EXTRA_DEBUG: f64 = 1.3; + +/// Draws into a pass with a color their pipeline state lacks, which plain Metal zeroes where a +/// draw covers it (`BindState::zeroed_colors`), allocate at most [`ZEROED_COLORS_EXTRA`] each +/// beyond the same draws into a pass of the state's colors alone, past a first command buffer that +/// made the pipelines: an unchanged set of colors to zero is read in place, and copied neither +/// into the draw's settings nor into its bind state again. Each draw binds what the draw before it bound but its column's +/// bytes; the target is the texture's, and the lacked color zero where the draws covered it. +#[cfg(not(m2v_system_alloc))] +#[test] +fn draws_into_a_pass_color_their_state_lacks_copy_no_color_set() { + use crate::worker::alloc::thread_allocations; + // Enough draws that what grows by doubling (the command buffer's lists) adds little to each. + const DRAWS: u64 = 64; + on_device(|device, _| { + let scene = Scene::new(device); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let mut lacked = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + lacked.usage = TextureUsage::RENDER_TARGET; + lacked.resource_options = ResourceOptions::shared(); + let lacked = device.new_texture(&lacked).unwrap(); + // The allocations each draw past the first two makes, of a pass of the target and, where + // given, a second color cleared to `CLEAR`; and the command buffer. + let draws = |second: Option<&Texture>| { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + for (at, texture) in [Some(&scene.target), second].into_iter().enumerate() { + let color = &mut pass.color_attachments[at]; + color.texture = texture.cloned(); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 1.0, 1.0); + } + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&scene.pipeline).unwrap(); + encoder + .set_fragment_sampler_state(Some(&scene.sampler), 0) + .unwrap(); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + let mut before = None; + for at in 0..DRAWS { + encoder.set_vertex_bytes(&column(at % SIDE), 0).unwrap(); + draw(&mut encoder); + if at == 1 { + before = thread_allocations(); + } + } + let each = thread_allocations() + .zip(before) + .map(|(after, before)| (after - before) as f64 / (DRAWS - 2) as f64); + encoder.end_encoding().unwrap(); + (each, command_buffer) + }; + // Every pipeline made first, in a command buffer of each pass. + for second in [None, Some(&lacked)] { + let (_, command_buffer) = draws(second); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + } + pipelines_settled(device); + let (own, command_buffer) = draws(None); + assert!(scene.pixels(&command_buffer).iter().all(|&p| p == RED)); + let (beside, command_buffer) = draws(Some(&lacked)); + let pixels = scene.pixels(&command_buffer); + assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); + let mut bytes = vec![0u8; (4 * SIDE * SIDE) as usize]; + let region = Region::new_2d(0, 0, SIDE, SIDE); + lacked + .get_bytes(&mut bytes, 4 * SIDE, 0, region, 0, 0) + .unwrap(); + assert!(bytes.iter().all(|&b| b == 0), "{bytes:?}"); + let (Some(own), Some(beside)) = (own, beside) else { + eprintln!("DRAW-WORK {}: allocations not counted", device.name()); + return; + }; + eprintln!( + "DRAW-WORK {}: {beside:.2} allocations a draw beside a lacked color, {own:.2} without", + device.name() + ); + let bound = match cfg!(debug_assertions) { + true => ZEROED_COLORS_EXTRA_DEBUG, + false => ZEROED_COLORS_EXTRA, + }; + assert!( + beside - own <= bound, + "{beside:.2} allocations a draw beside a lacked color, {own:.2} without" + ); + }); +} + /// Draw through `encoder` (`draw`), returning the state commands it recorded /// (`WorkCounts::draw_states_recorded`). fn recorded_by(device: &Device, encoder: &mut RenderCommandEncoder) -> u64 { @@ -632,3 +1036,55 @@ fn a_slot_rebound_to_a_texture_let_go_after_its_draw_holds_it_until_completion() } }); } + +/// Draws that each set other vertex bytes and rebind the fragment table's texture slot 0 in turn +/// to one of two textures that look alike (one format, size, usage and texels), the table also +/// binding a buffer and, at slot 1, a texture the shader does not read: each draw retains the +/// table, holding what its last retain held and taking the rest. The ended encoder lists the +/// target, the buffer and the three textures (`CommandBuffer::ended_encoders`), whether a draw +/// took one or held it already; each column is the textures' color. +#[test] +fn draws_rebinding_a_slot_to_a_texture_that_looks_alike_list_each_object() { + on_device(|device, _| { + let scene = Scene::new(device); + let alike = [ + solid(device, PixelFormat::RGBA8Unorm, RED), + solid(device, PixelFormat::RGBA8Unorm, RED), + ]; + // Bound throughout, and read by no draw: held from the first retain on. + let unread = solid(device, PixelFormat::RGBA8Unorm, CLEAR); + let unread_buffer = buffer_with(device, &[0; 16]).unwrap(); + let (command_buffer, mut encoder) = scene.encoder(device); + encoder.set_fragment_texture(Some(&unread), 1).unwrap(); + encoder + .set_fragment_buffer(Some(&unread_buffer), 0, 0) + .unwrap(); + let mut first = None; + for c in 0..SIDE { + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + encoder + .set_fragment_texture(Some(&alike[(c % 2) as usize]), 0) + .unwrap(); + draw(&mut encoder); + first.get_or_insert_with(|| device.work_counts()); + } + let (first, rest) = (first.unwrap(), device.work_counts()); + encoder.end_encoding().unwrap(); + assert_eq!( + grew(&first, &rest, |c| c.argument_tables_retained), + SIDE - 1 + ); + let ended = command_buffer.ended_encoders(); + assert_eq!(ended.len(), 1); + let used = &ended[0].used_resources; + let want = [&scene.target, &alike[0], &alike[1], &unread]; + assert_eq!(used.textures.len(), want.len(), "{:?}", used.textures); + for (at, texture) in want.into_iter().enumerate() { + assert!(used.textures.contains(texture), "texture {at} not listed"); + } + assert_eq!(used.buffers, std::slice::from_ref(&unread_buffer)); + assert!(used.heaps.is_empty(), "{:?}", used.heaps); + let pixels = scene.pixels(&command_buffer); + assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index 7626e8655..03bf3b71c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -60,6 +60,12 @@ //! that the buffer keeps its bytes. Its lines also give a frame's wall time through its last //! command buffer's completion, the GPU's work included. //! +//! `frame_costs_repeating` measures the plain device with each of a pass's draws but its panel +//! drawn again right after itself, with no call before it ([`REPEATED`]): 11 draws a pass, 5 of +//! which (45%) follow a draw with no call between them, about the share of the consumer's guest's +//! draws on the Iris Xe (43%). Its draws bind what the draws before them bound, which every draw +//! of the other runs changes. +//! //! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`, in a //! build with `--cfg m2v_system_alloc` for the times, whose lib test binary keeps the system //! allocator as a consumer's process does (the counting one costs the draw path about a sixth of @@ -81,11 +87,17 @@ //! commit none, and the frame's submissions none but the barrier command buffers they record to //! keep, on a device that keeps them (`Device::work_counts`). They count, and time nothing. +use super::render_arguments::{Members, ORDERED}; +use super::renders::public_render; use super::{buffer_with, loader, open_device, ScratchCache, WAIT}; use crate::air_library::AirLibrary; +use crate::candidate::engine::graphics::Assembly; +use crate::candidate::engine::resources::pixel_format; +use crate::candidate::runtime_case::render_pipeline_state; +use crate::case::indirect_commands::metal_primitive_type; use crate::gpu::TEST_DEVICE; use crate::worker::alloc; -use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::bind::{DrawCall, SamplerDescriptor}; use metal2vulkan::error::RuntimeDriverDefect; use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; use metal2vulkan::metal::{ @@ -114,6 +126,9 @@ const COUNTED: usize = 20; const BUFFERS: usize = 67; /// The draws of a pass. const DRAWS: usize = 6; +/// In a repeating run ([`Run::REPEATING`]), the draws of a pass drawn again right after +/// themselves, with no call between the two: every one but the panel. +const REPEATED: [bool; DRAWS] = [true, true, true, true, false, true]; /// Every `RESOLVED`th pass draws into a 4-sample texture resolved into its layer. const RESOLVED: usize = 4; /// The window layers the passes draw into, and their side. @@ -125,16 +140,16 @@ const TEXTURE_SIDE: u64 = 64; /// The bytes of `zwd_shapes`' `ZwdShape`: rectangle, fill, outline and shape. const SHAPE_BYTES: usize = 64; /// The most allocations a frame's draw makes on the encoding thread on average, its state changes -/// and its draw call together, once every pipeline is made. Measured: 24.5 on RADV (Radeon 780M) -/// and ANV (Iris Xe), 24.7 on lavapipe. +/// over the last draw's (`BindingPlan::instantiate_draw_into`), and the draw its uses, descriptor +/// writes, pushed set 0 and vertex buffers over the last draw's (`LiveBind`), so none of them +/// allocate, and a pass's draws hold the first rectangle they reach (`clear_reach::DrawnArea`) and #[cfg(not(m2v_system_alloc))] -const DRAW_ALLOCATIONS: f64 = 27.0; +const DRAW_ALLOCATIONS: f64 = 9.0; /// [`DRAW_ALLOCATIONS`] in a build with debug assertions, which CI's tests are: the draw path's /// allocations and those of `LiveBind::shape`'s checks there, which build the state's whole bind -/// shape at each draw to compare the kept or found one with it. Measured: 35.93 on lavapipe -/// (llvmpipe, LLVM 23.1.1, Mesa 26.2.4), where a build without debug assertions makes 24.62. +/// shape at each draw to compare the kept or found one with it. Measured: 17.88 on lavapipe #[cfg(not(m2v_system_alloc))] -const DRAW_ALLOCATIONS_DEBUG: f64 = 38.0; +const DRAW_ALLOCATIONS_DEBUG: f64 = 20.0; /// The most allocations a frame's pass open (`render_command_encoder`) makes on the encoding /// thread on average, once every pipeline is made. Measured: 13.0 on RADV (Radeon 780M), on /// lavapipe and on ANV (Iris Xe). @@ -186,6 +201,8 @@ struct Run { announced: bool, checked: bool, layers: Layers, + /// Whether the [`REPEATED`] draws of each pass are drawn again with no call before them. + repeats: bool, } impl Run { @@ -193,6 +210,7 @@ impl Run { announced: false, checked: false, layers: Layers::Private, + repeats: false, }; const CHECKED: Run = Run { announced: false, @@ -204,6 +222,11 @@ impl Run { checked: false, layers: Layers::Private, }; + const REPEATING: Run = Run { + repeats: true, + ..Run::PLAIN + }; + /// The plain device's run with layers over buffers, its passes loading and storing them so. const fn over_buffers(load: LoadAction, store: StoreAction) -> Run { @@ -225,6 +248,10 @@ impl Run { Layers::OverBuffers(load, store) => { format!("{device}, layers over buffers, {load:?} load, {store:?} store") } + let device = match self.repeats { + false => device, + true => format!("{device}, draws repeated with no call before them"), + }; } } } @@ -276,7 +303,8 @@ struct Workload { layers: Layers, /// The buffers the layers lie over, where they do. layer_buffers: Vec, - queue: CommandQueue, + /// Whether each pass draws its [`REPEATED`] draws again with no call before them. + repeats: bool, /// A checked run's submissions checked. checks: Option>, /// One sample, and four. @@ -403,7 +431,11 @@ fn shape(n: usize) -> [u8; SHAPE_BYTES] { } impl Workload { - fn new(device: Device, checked: bool, layers: Layers) -> Workload { + fn new( + device: Device, + checked: bool, + layers: Layers, + ) -> Workload { let library = |name: &str| { device.new_library_with_air(&llvm_assemble(&engine_dir().join(name)).unwrap()) }; @@ -461,7 +493,7 @@ impl Workload { Workload { layers, layer_buffers, - queue: device.new_command_queue().unwrap(), + repeats, checks: checked.then(Arc::default), pipelines, sampler, @@ -541,6 +573,11 @@ impl Workload { encoder.set_fragment_bytes(&shape, 0).unwrap(); } } + self.draw_call(encoder); + } + + /// The draw call of every draw: its rectangle's six indices. + fn draw_call(&self, encoder: &mut RenderCommandEncoder) { encoder .draw_indexed_primitives( PrimitiveType::Triangle, @@ -555,6 +592,14 @@ impl Workload { .unwrap(); } + fn draws(&self) -> usize { + DRAWS + + REPEATED + .iter() + .filter(|&&again| again && self.repeats) + .count() + } + /// Encode and commit one frame, then wait for its last command buffer: what each step cost. fn frame(&self) -> Frame { self.frame_reading(Reads::default()) @@ -589,6 +634,8 @@ impl Workload { if let Some(before) = &before { begun[1].add(Begun::since(&self.device, before)); } + } + } } let before = counts(); let ((), ended) = step(reads.instructions, || encoder.end_encoding().unwrap()); @@ -1139,13 +1186,19 @@ fn measure(runs: &[Run]) { (count(&counts) - count(&counts_before)) as f64 / TIMED as f64 }; eprintln!( - "FRAME-COST {name} {label}: a frame's work: {:.0} bind shapes made, {:.0} draws \ - settled, {:.0} pipelines looked up, {:.0} draw states recorded, {:.0} argument \ - tables retained, {:.1} command pools made, {:.1} timeline waits, {:.1} addressable \ - buffers made, {:.1} queue submissions, {:.1} commits handed off, {:.1} submission \ - checks", + "FRAME-COST {name} {label}: a frame's work: {:.0} bind shapes made, {:.0} found, \ + {:.0} draws settled, {:.0} argument sampler lists taken, {:.0} bind views worked \ + out, {:.0} stage tables read, {:.0} draws' uses noted as before, {:.0} pipelines \ + looked up, {:.0} draw states recorded, {:.0} draws pushing set 0, {:.0} argument \ + tables retained, {:.1} command pools made, \ + {:.1} timeline waits, {:.1} addressable buffers made, {:.1} queue submissions, {:.1} \ per_frame(|c| c.draw_shapes_made), + per_frame(|c| c.draw_shapes_found), per_frame(|c| c.draws_settled), + per_frame(|c| c.argument_samplers_taken), + per_frame(|c| c.bind_views_worked_out), + per_frame(|c| c.stage_tables_read), + per_frame(|c| c.commands_noted_as_before), per_frame(|c| c.graphics_pipelines_looked_up), per_frame(|c| c.draw_states_recorded), per_frame(|c| c.argument_tables_retained), @@ -1256,6 +1309,12 @@ fn frame_costs_announced() { measure(&[Run::ANNOUNCED]); } +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn frame_costs_repeating() { + measure(&[Run::REPEATING]); +} + #[test] #[ignore = "a measurement, not a check: run by name with --run-ignored all"] fn frame_costs_over_buffers() { @@ -1291,8 +1350,9 @@ fn allocations_each(frame: &Frame, steps: StepsOf) -> f64 { /// A frame's draws allocate at most [`DRAW_ALLOCATIONS`] each on average on the encoding thread /// ([`DRAW_ALLOCATIONS_DEBUG`] with debug assertions), once every pipeline is made: what the draw /// path keeps of what it found before (each texture's storage view formats, the pipeline state's -/// routing into the pass's colors, the settles of its latest bind shapes and the shapes -/// themselves, the format table) is not made again at each draw, and what a draw retains, binds +/// routing into the pass's colors and the colors it zeroes and drops, the settles of its latest +/// bind shapes and the shapes themselves, the bind state the device's last ended render encoder +/// left, the format table) is not made again at each draw, and what a draw retains, binds /// and records it holds and builds without allocating where the object or the list allows. Its /// passes' ends allocate at most [`PASS_END_ALLOCATIONS`] each: a pass end retains what its /// commands use as one object, and makes no tile grid where a draw reaches every tile, no sample @@ -1501,3 +1561,124 @@ fn a_frame_s_commits_allocate_within_their_bound() { {SUBMIT_ALLOCATIONS}" ); } + +/// Draws in a pass of [`frame_costs_resident`]. +const RESIDENT_DRAWS: usize = 32; + +/// The plain device's draws that reach a buffer through the resident set alone, as the consumer's +/// guest's draws reach its argument buffers' buffers: [`RESIDENT_DRAWS`] draws a pass of +/// `render_arguments`' [`ORDERED`] case (a fragment function updating the buffer its argument +/// buffer points to, made resident with `use_resources`), each of the same uses, a pass a command +/// buffer, 20 untimed and 100 timed frames: a draw's user-space instructions and wall time, and +/// how many of a pass's draws its encoder noted as before (`WorkCounts::commands_noted_as_before`). +/// A device that cannot make the case's pipeline prints its refusal. +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn frame_costs_resident() { + let cache = ScratchCache::new().unwrap(); + let heard = Heard::default(); + let device = device(&cache, false, &heard, CompletionPolicy::default()); + let case = public_render(ORDERED); + let state = match render_pipeline_state(&device, &case.inputs()) { + Ok(state) => state, + Err(error) => { + println!( + "FRAME-COST {}: resident draws refused: {error}", + device.name() + ); + return; + } + }; + let render = &case.render; + let members = Members::of(&device, render.fragment.as_ref().unwrap()); + let target = &render.color_targets[&0]; + let [width, height] = target.dimensions; + let format = pixel_format(target.format); + let mut descriptor = TextureDescriptor::texture_2d(format, width.into(), height.into(), false); + descriptor.usage = TextureUsage::RENDER_TARGET; + let texture = device.new_texture(&descriptor).unwrap(); + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(texture); + attachment.load_action = LoadAction::Clear; + attachment.store_action = StoreAction::Store; + let DrawCall::Primitives { + vertex_start, + vertex_count, + instance_count, + base_instance, + } = render.draw + else { + panic!("{ORDERED}: a draw of primitives"); + }; + let &Assembly::Primitives(primitive) = &render.assembly else { + panic!("{ORDERED}: a draw of primitives"); + }; + let queue = device.new_command_queue().unwrap(); + let resources = members.resources(); + let stages = RenderStages::VERTEX | RenderStages::FRAGMENT; + let usage = ResourceUsage::READ | ResourceUsage::WRITE; + let frame = |counted: bool, draws: &mut Vec| { + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + for (&index, owner) in &members.owners { + encoder.set_fragment_buffer(Some(owner), 0, index).unwrap(); + } + encoder.use_resources(&resources, usage, stages).unwrap(); + for _ in 0..RESIDENT_DRAWS { + let ((), drawn) = step(counted, || { + encoder + .draw_primitives( + metal_primitive_type(primitive), + vertex_start, + vertex_count, + instance_count, + base_instance, + ) + .unwrap() + }); + draws.push(drawn); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer + }; + let mut draws = Vec::new(); + for _ in 0..20 { + frame(false, &mut draws) + .wait_until_completed_for(WAIT) + .unwrap(); + } + draws.clear(); + let noted = || device.work_counts().commands_noted_as_before; + let before = noted(); + const FRAMES: usize = 100; + for _ in 0..FRAMES { + let last = frame(true, &mut draws); + last.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(last.status(), CommandBufferStatus::Completed); + } + let noted = (noted() - before) as f64 / FRAMES as f64; + let walls: Vec = draws.iter().map(|d| d.wall.as_secs_f64() * 1e6).collect(); + let [wall, wall_p90] = percentiles(walls); + let instructions: Vec = draws + .iter() + .filter_map(|d| d.instructions) + .map(|n| n as f64) + .collect(); + let counted = match instructions.is_empty() { + true => "instructions not counted".to_owned(), + false => { + let mean = instructions.iter().sum::() / instructions.len() as f64; + let [p50, _] = percentiles(instructions); + format!("{mean:.0} user-space instructions each (p50 {p50:.0})") + } + }; + println!( + "FRAME-COST {}: resident draws, {RESIDENT_DRAWS} a pass of the same uses: draw: \ + {wall:.2} us (p50; p90 {wall_p90:.2}); {counted}; {noted:.1} of a pass's draws noted as \ + before", + device.name() + ); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_arguments.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_arguments.rs index ca167948c..2c0139703 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_arguments.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_arguments.rs @@ -39,7 +39,7 @@ pub(super) const SAMPLED: &str = /// Sixteen fragments of each pixel update a word of a buffer their argument buffer points to, in /// a raster order group. -const ORDERED: &str = +pub(super) const ORDERED: &str = "sixteen-overlapping-triangles-update-a-raster-ordered-argument-buffer-member"; /// Run `test` on a validated device of the lane, then fail on any validation message. @@ -128,9 +128,15 @@ impl Members { } } -/// Draw `case` on `device` once, with its fragment function's argument buffers' members made -/// resident in `stages`: its color target 0 and the members, once the command buffer completed. -fn draw(device: &Device, case: &PublicRender, stages: RenderStages) -> (Texture, Members) { +/// Draw `case` on `device` `times` times in one encoder, with its fragment function's argument +/// buffers' members made resident in `stages`: its color target 0 and the members, once the +/// command buffer completed. +fn draw( + device: &Device, + case: &PublicRender, + stages: RenderStages, + times: usize, +) -> (Texture, Members) { let render = &case.render; let fragment = render.fragment.as_ref().expect("a fragment case"); let members = Members::of(device, fragment); @@ -185,15 +191,17 @@ fn draw(device: &Device, case: &PublicRender, stages: RenderStages) -> (Texture, let &Assembly::Primitives(primitive) = &render.assembly else { panic!("{}: a draw of primitives", case.case.name); }; - encoder - .draw_primitives( - metal_primitive_type(primitive), - vertex_start, - vertex_count, - instance_count, - base_instance, - ) - .unwrap(); + for _ in 0..times { + encoder + .draw_primitives( + metal_primitive_type(primitive), + vertex_start, + vertex_count, + instance_count, + base_instance, + ) + .unwrap(); + } encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); @@ -239,7 +247,7 @@ fn a_fragment_samples_what_its_argument_buffer_names() { let case = public_render(SAMPLED); let metal = case.metal_output.clone().unwrap(); on_device(|device| { - let (target, members) = draw(device, &case, RenderStages::FRAGMENT); + let (target, members) = draw(device, &case, RenderStages::FRAGMENT, 1); assert_eq!(members.samplers.len(), 1); assert_eq!(output(&case, &target, &members), metal); }); @@ -261,11 +269,77 @@ fn a_fragment_updates_the_buffer_its_argument_buffer_points_to() { return; } let stages = RenderStages::VERTEX | RenderStages::FRAGMENT; - let (target, members) = draw(device, &case, stages); + let (target, members) = draw(device, &case, stages, 1); assert_eq!(output(&case, &target, &members), metal); }); } +/// Four draws of [`ORDERED`] in one encoder take the same uses, the buffer they update reached +/// through the resident set alone: each after the first is noted already, the encoder having +/// noted the same uses, reaching the same keys so, for the one before +/// (`WorkCounts::commands_noted_as_before`). Each draw still updates as it would alone: a word +/// Metal's one draw takes `k` rounds of `v -> 3v + 1` from its first value takes `4k`. A pipeline +/// the device cannot make is an honest refusal, and is printed. +#[test] +fn draws_reaching_a_resident_buffer_as_the_one_before_are_noted_once() { + let case = public_render(ORDERED); + let metal = case.metal_output.clone().unwrap(); + on_device(|device| { + if let Err(error) = render_pipeline_state(device, &case.inputs()) { + let why = error.to_string(); + eprintln!("REFUSED {ORDERED}: {why}"); + assert!(refusal(&why), "{why}"); + return; + } + let stages = RenderStages::VERTEX | RenderStages::FRAGMENT; + let noted = || device.work_counts().commands_noted_as_before; + let before = noted(); + let (target, members) = draw(device, &case, stages, 4); + assert_eq!(noted() - before, 3); + let RenderOutput::ArgumentBufferBuffer { + owner, + field_offset, + offset, + length, + .. + } = case.render.output + else { + panic!("{ORDERED}: an argument-buffer buffer's output"); + }; + let fragment = case.render.fragment.as_ref().unwrap(); + let first = &fragment.resources.argument_buffer_buffers[&(owner, field_offset)]; + let (offset, length) = (offset as usize, length as usize); + let words = |bytes: &[u8]| -> Vec { + (bytes.as_chunks::<4>().0.iter()) + .map(|word| u32::from_le_bytes(*word)) + .collect() + }; + let round = |v: u32| v.wrapping_mul(3).wrapping_add(1); + let rounds = |mut v: u32, n: usize| { + for _ in 0..n { + v = round(v); + } + v + }; + let drawn = words(&output(&case, &target, &members)); + let once = words(&metal); + let firsts = words(&first[offset..offset + length]); + assert_eq!((drawn.len(), once.len()), (firsts.len(), firsts.len())); + for (word, ((&first, &once), &drawn)) in firsts.iter().zip(&once).zip(&drawn).enumerate() { + let k = (0..=64) + .find(|&k| rounds(first, k) == once) + .unwrap_or_else(|| { + panic!("word {word}: Metal's {once:#x} is no rounds of {first:#x}") + }); + assert_eq!( + drawn, + rounds(first, 4 * k), + "word {word}: {k} rounds a draw" + ); + } + }); +} + /// `use_resource(s)` and `use_heap(s)` refuse another device's resource or heap, as a compute /// encoder's do, and a refusal makes nothing resident. #[test]