diff --git a/crates/metal2vulkan-runtime/src/live_bind.rs b/crates/metal2vulkan-runtime/src/live_bind.rs index 8bd6dda6a..b6bec94af 100644 --- a/crates/metal2vulkan-runtime/src/live_bind.rs +++ b/crates/metal2vulkan-runtime/src/live_bind.rs @@ -864,6 +864,27 @@ impl LiveBind { Ok(()) } + /// Keep each kept draw set aside with the state of another pipeline state that `rehomes` + /// keeps (re-homed into the render pass instance a draw began after a split, given the draw + /// and that state's last draw's uses, the kept draw's own), and let go of the others + /// (`RenderLowering::rehome_aside`): how many it kept. + pub(super) fn rehome_kept( + &mut self, + mut rehomes: impl FnMut(&mut DrawKept, &CommandUses) -> Result, + ) -> Result { + let mut rehomed = 0; + for aside in &mut self.set_aside { + let Some(kept) = aside.draw_kept.as_mut() else { + continue; + }; + match rehomes(kept, &aside.uses)? { + true => rehomed += 1, + false => aside.draw_kept = None, + } + } + Ok(rehomed) + } + /// Of the kept draws set aside with the states of other pipeline states, keep for the next /// render encoder of its encoder's command buffer (`render/carried.rs`) those that `carries` /// tells carry (given each and whether its state holds its settle), and let go of every diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 1a2fd7df2..8890d787d 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1763,6 +1763,10 @@ pub(crate) struct RenderLowering { /// nothing but them: keeping nothing, it forgets only the kept draws that read its pass's /// colors (`render/draw_again.rs`). snapshots_alone: bool, + /// The direct draw being drawn kept nothing only because it recorded into a later instance + /// after a split: it keeps the kept draws set aside into that instance, but those that read + /// its pass's colors (`render/draw_again.rs`, re-homed past a split). + split_alone: bool, /// The heap set versions the plain draws it replayed bound (`heap_sets::Bound`), each once, /// which a kept recording of them binds again (`kept_commands::KeptEffects`). replayed_heaps: Vec>, @@ -2564,6 +2568,7 @@ impl RenderLowering { replay_plain: false, plain_drawn: false, snapshots_alone: false, + split_alone: false, replayed_heaps: Vec::new(), rerouting: false, forms: BufferForms::Bound, @@ -8444,6 +8449,7 @@ impl RenderLowering { } self.drop_kept(); self.snapshots_alone = false; + self.split_alone = false; let watch = EachWatch::start(); // And whether it rasterizes, without which its primitives reach no tile (`no_raster_t11`). // And whether it chooses its viewport. @@ -8483,6 +8489,7 @@ impl RenderLowering { // snapshots, kept or not: it forgets the kept draws that read those alone // (`render/draw_again.rs`). match self.again_kept().map(|kept| kept.reader.is_some()) { + None if self.split_alone => self.rehome_aside(live)?, None if self.snapshots_alone => self.forget_readers(live)?, None => self.forget_again(), Some(true) => self.forget_aside_readers(live)?, @@ -11071,6 +11078,9 @@ impl RenderLowering { || made_imageblock.is_some() || pending.is_some(); let stepless = !later_instance && !own_steps; + // Into a later instance after a split alone: not a continuation, nor with a stand-in + // arriving (`render/draw_again.rs`, re-homed past a split). + let split_only = later_instance && stood.is_none() && continuation.is_none(); self.snapshots_alone = snapshots_alone && !begun && !later_instance; // Recording starts here: nothing below can be refused. if let Some(written) = written { @@ -11680,7 +11690,8 @@ impl RenderLowering { (Some(wanted), Some(snapshot::Pair { steps: Some(_), .. })) if !wanted.in_place && wanted.pins == 0 ); - let plain_but_heap = stepless + // Plain but for the later instance it may have recorded into: `stepless` but for that. + let plain_apart = !own_steps && !own_zeros && !barriered && !empty @@ -11689,7 +11700,6 @@ impl RenderLowering { && self.replayed.is_none() && self.grouped.is_none() && self.rate_map.is_none() - && self.current.kept.is_none() && matches!(draw_pipeline, DrawPipeline::Made(_)) && tessellation.is_none() && !meshes @@ -11739,8 +11749,9 @@ impl RenderLowering { && !plan.variant.extended_range.values().any(planes) && !(self.layout.colors.iter().flatten()).any(extended) && !facts.in_place(); - let plain = - plain_but_heap && heap.is_none() && texture_table.is_none() && sampler_table.is_none(); + let plain_but_heap = !later_instance && plain_apart; + let tableless = heap.is_none() && texture_table.is_none() && sampler_table.is_none(); + let plain = plain_but_heap && tableless; // A replayed draw that reads the heap is plain where a kept recording of it binds the heap // set again as it did (`heap_sets::Bound`), it reads no sampler table and its tables bind // no texture its heap part reads; the texture table is the device's one buffer, which a @@ -11781,6 +11792,20 @@ impl RenderLowering { let under = self.kept_under(); let keeps = plain && !self.replaying && self.core.noted_now(&live.noted, under.noted_into()); + // A draw that keeps nothing only because it recorded into a later instance after a + // split, of the shape, views and formats of the one before, its other steps a plain + // draw's, keeps the kept draws set aside into it (`render/draw_again.rs`). + self.split_alone = !keeps + && split_only + && plain_apart + && tableless + && !self.replaying + && (self.earlier.last()).is_some_and(|before| { + *before.shape == *self.current.shape + && before.views == self.current.views + && before.reformats.is_empty() + && self.current.reformats.is_empty() + }); // What kept a direct draw of its own from being kept (`WorkCounts::draws_unkept`). if !keeps && !self.replaying && !self.rerouting && !empty && !culled { let unkept = UnkeptDraw { @@ -11870,6 +11895,7 @@ impl RenderLowering { settled: through_record, carried: false, across: false, + rehomed: false, made: draw_again::KeptPipeline(Arc::clone(made)), reader: match (&snapshot, &pair_base) { ( diff --git a/crates/metal2vulkan-runtime/src/render/draw_again.rs b/crates/metal2vulkan-runtime/src/render/draw_again.rs index d1bc5b074..fabc8c0ae 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again.rs @@ -11,6 +11,10 @@ //! - **Only a plain draw is kept.** One that recorded one Vulkan draw into the current instance as //! it stood, or into its pass's first instance begun inline at it (`render/inline_first.rs`: //! the next draw finds the instance begun, its record holding the states the kept draw set), +//! an instance recorded inline after a split among them, whose room keeps its draws' +//! recordings until its copies are known (`render/inline_splits.rs`): a kept draw's next draw +//! there is rebound (`rebound.rs`), its recording kept in the room as every step's is, never a +//! Vulkan draw recorded ahead of the room's, //! through a pipeline made ahead, needing nothing before or around it of its own: no //! split, stand-in, snapshot (but a reader's, below), copy, index bounds or rewrite pass, mesh or //! tessellation work, rate map, color groups, extended-range color or its shadow, set 1 or @@ -42,7 +46,8 @@ //! and encoded again), refused or not, whatever it changes, with every kept draw set aside //! (below), counted by the call's kind (`WorkCounts::kept_draws_let_go_*`); so does a draw that //! keeps nothing (a draw again, a draw rebound and a draw kept are the only draws that leave -//! them), but a reader through snapshots that writes nothing else (below). A bind changes its +//! them), but a reader through snapshots that writes nothing else, and a draw that keeps +//! nothing only for a split, which re-homes them (below). A bind changes its //! stage table's slots alone (and a bytes bind takes room in its command buffer's uploads), and a //! table's stamp tells each change apart (`argument_table::Stamp`): the kept draw keeps the four //! tables' stamps as it read them, and a draw whose tables kept them is the kept draw again; one @@ -152,6 +157,24 @@ //! nothing else the state decides of a draw reads, a kept draw whose route meets every condition //! of a restate ([`Kept::restates_by_scissors`]) takes the new scissors alone into its draw //! state and derives nothing else again (`WorkCounts::draws_restated_scissors`). +//! - **Re-homed past a split.** A draw that keeps nothing only because it recorded into a later +//! render pass instance of its pass than the one it found (a split, not a continuation or a +//! stand-in's arrival: the read of a color attachment's texture after a barrier among them), +//! of the shape, views and formats of the one before, its other steps those of a plain draw, +//! wrote nothing but its pass's colors (and their copies the split takes): it keeps the kept +//! draws set aside with the states of other pipeline states into its instance +//! (`RenderLowering::rehome_aside`, `WorkCounts::kept_draws_rehomed`), but those that read +//! its pass's colors other than through snapshots of their own (as past a reader below), the +//! readers through snapshots, the draws carried in and not drawn since, and those that read +//! what changes with no call otherwise than it did, which it lets go. Each is kept there as a +//! carried draw is kept in the instance its encoder opened with ([`Kept::rehomed`]): after +//! draws of other states, recorded through no record, under another render state, so its +//! next draw is rebound (`rebound.rs`), deriving again what the render state decides and +//! adding the pixels it may write to the instance's drawn area (`restated.rs`), its uses +//! noted, added to the pass's reads and gathered whole into the new instance with its +//! shadowed textures' (which the copies before it then take), where it uses those exactly as +//! the kept draw did, and every state command it sets recorded against what that instance's +//! record holds. Its tables' stamps are its own still: its encoder's tables went on. //! - **Carried to the next encoder.** An encoder that ends with a kept draw of its pass's first //! instance carries it, with its bind state and settles and the kept draws set aside with the //! states of up to seven other pipeline states (`live_bind::SET_ASIDE`), into its command @@ -344,6 +367,12 @@ pub(crate) struct Kept { /// encoder's command buffer what every step retains beyond the tables' objects, which that /// command buffer may hold no longer (`rebound.rs`). pub(super) across: bool, + /// Whether it was set aside when a draw that kept nothing only for recording into a later + /// render pass instance of its pass began that instance, and was kept into it + /// ([`rehomed_into`](Kept::rehomed_into), the module docs), and has not been drawn since: + /// its next draw is rebound, gathering its uses whole into that instance and its shadowed + /// textures' uses with them (`rebound.rs`). + pub(super) rehomed: bool, /// The `VkPipeline` it recorded through, held while it is kept: its recording names it by /// handle, and a draw carried across retains it (`render/carried.rs`). pub(super) made: KeptPipeline, @@ -394,6 +423,37 @@ impl Kept { (under.moved, under.residency, under.samplers) == (moved, residency, samplers) } + /// Keep this draw, set aside, into the render pass instance a draw that kept nothing only for + /// recording into it began after a split, of the shape of the one before (the module docs): + /// recording into `draws` through no record of that instance's, under a render state of + /// another stamp (so its next draw derives again what that state decides, adding the pixels + /// it may write to the instance's drawn area: `restated.rs`), kept under `under`, what the + /// draw that began it was kept under. Where what it read that changes with no call is not as + /// `under` holds it, but what it was noted into (which its next draw, rebound, notes its uses + /// into whole), it is not kept: `false`. + pub(super) fn rehomed_into(&mut self, under: Under, draws: vk::CommandBuffer) -> bool { + let read = |under: &Under| { + let into = under.into; + ( + under.moved, + under.residency, + under.samplers, + into.rebinds, + into.aliases, + ) + }; + if read(&self.under) != read(&under) { + return false; + } + self.stated = Stated::default(); + self.between = true; + self.under = under; + self.command_buffer = draws; + self.settled = None; + self.rehomed = true; + true + } + /// Whether the draw read a texture an attachment of its pass renders through a sampled slot /// narrowed to levels apart from the attached ones (`render/attached_levels.rs`). One that /// reads it through its copy carries: the next encoder's draw rebound gathers its own copies @@ -497,6 +557,7 @@ impl Kept { settled, carried, across, + rehomed, made, reader, } = self; @@ -539,6 +600,7 @@ impl Kept { ("settled", *settled == other.settled), ("carried", *carried == other.carried), ("across", *across == other.across), + ("rehomed", *rehomed == other.rehomed), ("made", *made == other.made), ("reader", *reader == other.reader), ] @@ -810,6 +872,32 @@ impl RenderLowering { live.forget_kept_where(|kept, uses| kept.reads_colors((&mut *memo, layout, version), uses)) } + /// Keep the kept draws set aside with other pipeline states' bind states (`live`) into the + /// render pass instance the draw just drawn began after a split, keeping nothing only for + /// recording into it (the module docs): each that reads its pass's colors other than through + /// snapshots of its own (whose next draw's steps read them past the split), a reader through + /// snapshots, one carried in and not drawn since, and one that read what changes with no call + /// otherwise than that draw ([`Kept::rehomed_into`]) let go, the others kept into it + /// (`WorkCounts::kept_draws_rehomed`). The last direct draw's is that draw's, which kept + /// nothing. + pub(super) fn rehome_aside(&mut self, live: &mut LiveBind) -> Result<(), Error> { + let (under, draws) = (self.kept_under(), self.current.draws); + let (memo, version) = (&mut self.attached, self.layout.version()); + let layout: &PassLayout = &self.layout; + let rehomed = live.rehome_kept(|kept, uses| -> Result { + if kept.reader.is_some() + || kept.carried + || kept.reads_colors((&mut *memo, layout, version), uses)? + { + return Ok(false); + } + Ok(kept.rehomed_into(under, draws)) + })?; + self.again.kept = None; + self.core.counts().kept_draws_rehomed(rehomed); + Ok(()) + } + /// Keep every kept draw across a memory barrier over the render targets alone that records /// nothing but its barrier inside the current instance, or nothing (`fence.rs`), but those /// whose next draw's steps it changes: each that reads its pass's colors other than through @@ -1027,7 +1115,16 @@ impl RenderLowering { } } let stamps = self.table_stamps(); - if reargued || kept.stamps != stamps || kept.between || kept.stated != self.again.stated { + // In an instance recorded inline after a split, a draw again records its recording into + // the instance's room, as every step's (`render/inline_splits.rs`): rebound, through no + // Vulkan draw of its own recorded ahead of the room's. + let room = self.current.kept.is_some(); + if reargued + || kept.stamps != stamps + || kept.between + || kept.stated != self.again.stated + || room + { return match kept.rebinds { true => { let drawn = (assembly, draw, reargued); @@ -1430,6 +1527,8 @@ impl Checked { // A carried draw's every step began the pass's first instance, which its kept draw named // before any did, and keeps a draw carried no more, nor across (`render/carried.rs`). let (command_buffer, carried, across) = (again.command_buffer, again.carried, again.across); + // A draw re-homed is kept into its instance as its every step keeps itself there. + let rehomed = again.rehomed; assert!( draw_alone || rebound, "a draw again recorded a state command" @@ -1448,6 +1547,7 @@ impl Checked { (again.command_buffer, again.carried) = (kept.command_buffer, kept.carried); again.across = kept.across; } + again.rehomed = kept.rehomed; // The shapes' values where only their objects may differ. let shapes = match (&again.execution, &kept.execution) { (Some(again), Some(kept)) => Some(*again.shape == *kept.shape), @@ -1464,6 +1564,7 @@ impl Checked { (again.settled, again.between, again.stated) = (settled, between, stated); (again.command_buffer, again.carried) = (command_buffer, carried); again.across = across; + again.rehomed = rehomed; encoder.again.hits = hits; } } diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs index 35739f98a..93c442e69 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -133,6 +133,18 @@ //! `VkPipeline`, which its encoder's later draws then retain no more, as after every step's //! (`LastRetained`); one carried across a commit (`Kept::across`), whose command buffer holds //! none of them, the call's index buffer too. +//! - **Re-homed.** A kept draw kept into a later render pass instance of its pass by a draw that +//! kept nothing only for recording into it (`render/draw_again.rs`, `Kept::rehomed`) is +//! rebound as one after draws of other states and calls that set the render state, through no +//! record: its tables' stamps are its own, so it brings in what its encoder's calls changed +//! since, as any draw rebound does; its uses are made again whole, and its uses of shadowed +//! textures, where each is its kept draw's as used, are gathered with them into its instance, +//! whose copies then take them, as every step gathers them there. +//! - **Into an instance recorded inline after a split** (`render/inline_splits.rs`), which keeps +//! its draws' recordings in its room until its copies are known: its recording is kept there +//! as every step's is, and recorded at its group's end through the pass's record, which +//! compares every state it sets; the kept draw is then recorded through no record +//! (`Kept::settled`). //! - **A draw that reads through no snapshot** reads its pass's colors through none again, as //! every step would ([`RenderLowering::reads_otherwise`]): every step reads none of them in //! place (`RenderLowering::in_place_wanted`), asks to read none through snapshots, or reads the @@ -1047,10 +1059,12 @@ impl RenderLowering { // Its uses: where only buffer slots changed, the kept draw's with those slots' patched in // place, which reads the stages' tables alone, else made again whole, those of what the // encoder made resident kept (`binding::command_uses_into`); a carried draw's whole, as its - // kept draw's are another encoder's (`render/carried.rs`). + // kept draw's are another encoder's (`render/carried.rs`), and a re-homed one's, as its + // kept draw's were gathered into another instance (`Kept::rehomed`). // A draw of other arguments patches its index buffer's use too, as a moved slot's. + let rehomed = (self.again.kept.as_ref()).is_some_and(|kept| kept.rehomed); let patch = (&**plan, &command, &stages[..]); - let inside = match images || carried || reads { + let inside = match images || carried || rehomed || reads { true => None, false => { let moved_uses = (&mut live.kept.moved_at, &mut live.kept.moved); @@ -1207,6 +1221,8 @@ impl RenderLowering { // where it uses some exactly where the kept draw did (a draw that uses some is never kept // for recording again, `Kept::again`, which a carried draw takes as it was). stop.0 = ArgumentsStop::Shadows; + // A re-homed draw's kept draw gathered them into the instance before the split: where it + // uses them as the kept draw did, it gathers them into its own (`Kept::rehomed`). let gathers = match carried { true if shadows.is_empty() == live.kept.shadows.is_empty() => shadows, true => return None, @@ -1214,7 +1230,10 @@ impl RenderLowering { if !(shadows.iter().map(ShadowUse::used_as)).eq(live.kept.shadows.iter().copied()) { return None; } - Vec::new() + match rehomed { + true => shadows, + false => Vec::new(), + } } }; let named = @@ -1643,8 +1662,13 @@ impl RenderLowering { let mut recorded = Recorded::default(); let raw = shared.vk(); let cb = self.current.draws; - match pairs { - None => { + // An instance recorded inline after a split keeps its draws' recordings in its room until + // its copies are known, recorded then through the pass's record (`render/inline_splits.rs`): + // this one's too, through no record of its own. + let room = self.current.kept.is_some(); + match (pairs, &mut self.current.kept) { + (None, Some(held)) => held.draw(&recording, owned.pipeline), + (None, None) => { // SAFETY: as the kept draw's recording: the secondary command buffer (or the // pass's, inline) records the kept draw's instance, and only this encoder // records it; every object recorded is live until the command buffer completes @@ -1652,7 +1676,14 @@ impl RenderLowering { // record of what its draws bound there. recorded += unsafe { recording.record(bound) }; } - Some(pairs) => { + // A reader through snapshots never records into such an instance (its admission), + // nor is it kept into one (`RenderLowering::rehome_aside`). + (Some(_), Some(_)) => { + return Err(crate::error::internal( + "a reader rebound into an instance recorded inline after a split", + )) + } + (Some(pairs), None) => { for pair in pairs { let counted = query.filter(|_| pair.phase == Phase::Drawing); // SAFETY: as above; the pass is one `render_target` made, of no views, and @@ -1678,9 +1709,10 @@ impl RenderLowering { let kept = (self.again.kept.as_mut()) .ok_or_else(|| crate::error::internal("a draw rebound without its kept draw"))?; kept.stamps = stamps; - kept.settled = Some(settled); + kept.settled = (!room).then_some(settled); kept.between = false; kept.stated = stated; + kept.rehomed = false; // A carried draw is the encoder's own from here, recorded into the instance it began, with // its reads through copies and its shadows', which the next draw rebound compares. let carried = kept.carried; diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index cdff69884..d816f5fbb 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -3087,6 +3087,7 @@ impl RenderExecution { replay_plain: true, plain_drawn: false, snapshots_alone: false, + split_alone: false, replayed_heaps: Vec::new(), rerouting: false, forms, diff --git a/crates/metal2vulkan-runtime/src/render/inline_splits.rs b/crates/metal2vulkan-runtime/src/render/inline_splits.rs index 40ea75fe8..e381447f8 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_splits.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_splits.rs @@ -41,6 +41,11 @@ //! - **The kept draws' room** is one the device keeps from an earlier such instance whose pass //! ended ([`SpareKept`]): each draw's recording is written over one left there, so an instance //! of no more draws than an earlier one's allocates nothing for them. +//! - **Draws kept to draw again** (`render/draw_again.rs`): a plain draw recorded into such an +//! instance is kept as any, and so are the kept draws a split re-homes into it; the next draw +//! of each is rebound (`render/draw_again/rebound.rs`), its recording kept in the room as +//! every step's is, never a Vulkan draw recorded into the pass's command buffer ahead of the +//! room's. //! - **Admitted** at a split, the new instance's first draw recording: the pass's first instance //! recorded inline, every instance since did, and the instance before is no continuation; the //! pass has no attachment that is a shadowed texture (`shadows::attachments_shadowed`), so the diff --git a/crates/metal2vulkan-runtime/src/tests/draw_again.rs b/crates/metal2vulkan-runtime/src/tests/draw_again.rs index 610977952..fcca80101 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw_again.rs @@ -84,7 +84,7 @@ const HITS: u64 = DRAWS - 1; /// How many of the draws again `hits` of a run recorded their Vulkan draw alone: every second one /// from the first takes every step in a build with debug assertions (the module docs). -fn drawn_alone(hits: u64) -> u64 { +pub(super) fn drawn_alone(hits: u64) -> u64 { match cfg!(debug_assertions) { true => hits / 2, false => hits, @@ -131,6 +131,29 @@ impl Ran { pub(super) fn counted(&self, of: impl Fn(&WorkCounts) -> u64) -> u64 { of(&self.after) - of(&self.before) } + + /// Every count of the device's `WorkCounts` that the run moved, as `name +n` by name (the + /// counts' `Debug` fields, a nested one's by its own name): what a failing test prints. + pub(super) fn moved(&self) -> String { + let fields = |counts: &WorkCounts| -> BTreeMap { + let text = format!("{counts:?}"); + text.split([',', '{', '}', '[', ']', '(', ')']) + .filter_map(|field| { + let (name, count) = field.split_once(':')?; + Some((name.trim().to_owned(), count.trim().parse().ok()?)) + }) + .collect() + }; + let before = fields(&self.before); + let moved: Vec = fields(&self.after) + .into_iter() + .filter_map(|(name, after)| { + let moved = after.checked_sub(before.get(&name).copied().unwrap_or(0))?; + (moved != 0).then(|| format!("{name} +{moved}")) + }) + .collect(); + moved.join(", ") + } } /// The device's commands recorded so far, by kind. @@ -173,13 +196,25 @@ fn run_on( descriptor.usage = TextureUsage::RENDER_TARGET; descriptor.resource_options = ResourceOptions::private(); let target = device.new_texture(&descriptor).unwrap(); + run_into(device, queue, &target, encode, waited) +} + +/// [`run_on`] into `target`, an `RGBA8Unorm` texture the pass clears. +pub(super) fn run_into( + device: &Device, + queue: &CommandQueue, + target: &Texture, + encode: impl Fn(&mut RenderCommandEncoder), + waited: bool, +) -> Ran { + let (width, height) = (target.width(), target.height()); let back = device - .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .new_buffer(width * height * 4, ResourceOptions::shared()) .unwrap(); let command_buffer = queue.command_buffer().unwrap(); let (before, recorded) = (device.work_counts(), commands(device)); let mut encoder = command_buffer - .render_command_encoder(&pass(&target)) + .render_command_encoder(&pass(target)) .unwrap(); encode(&mut encoder); encoder.end_encoding().unwrap(); @@ -197,15 +232,15 @@ fn run_on( .collect(); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.copy_from_texture_to_buffer( - &target, + target, 0, 0, Origin::new(0, 0, 0), - Size::new(SIDE, SIDE, 1), + Size::new(width, height, 1), &back, 0, - SIDE * 4, - SIDE * SIDE * 4, + width * 4, + width * height * 4, BlitOption::None, ) .unwrap(); @@ -252,7 +287,7 @@ const CHECKS_WAIT: Duration = Duration::from_secs(120); /// `WorkCounts::commands_recorded` counts as it counts a run's: a run whose window met one counted /// its commands too, 32 `cmd_reset_query_pool`, 64 `cmd_write_timestamp` and 32 /// `end_command_buffer` of the queue-switch check under twelve processes' load on an RTX 5080. -fn checks_ended(device: &Device) { +pub(super) fn checks_ended(device: &Device) { assert!( device.settle_queue_switch_check(CHECKS_WAIT), "the device's queue-switch check ended" diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index bbd1a2be2..4ad0d02c3 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -716,6 +716,8 @@ mod sparse; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod sparse_host_pages; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod split_keeps; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod srgb_fetch_images; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod stage_entries_shared; diff --git a/crates/metal2vulkan-runtime/src/tests/split_keeps.rs b/crates/metal2vulkan-runtime/src/tests/split_keeps.rs new file mode 100644 index 000000000..23a2ddf96 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/split_keeps.rs @@ -0,0 +1,272 @@ +//! A render encoder's kept draws past a split (`render/draw_again.rs`, re-homed past a split): a +//! draw that keeps nothing only because it recorded into an instance after a split, here one that +//! reads its own attachment after a memory barrier over the render targets, re-homes the kept +//! draws set aside into the instance (`WorkCounts::kept_draws_rehomed`), and the draws after it of +//! their pipeline states are rebound (`WorkCounts::draws_rebound`) into the instance, which records +//! inline after the split (`render/inline_splits.rs`), and so are the draws again there with no +//! call between (never a Vulkan draw of their own ahead of the instance's room), with the same +//! commands of every kind, state commands and pixels as the same draws each taking every step. In +//! builds with debug assertions, every second draw again takes every step instead and checks what +//! it worked out (`render/draw_again.rs`'s checks), so the test runs those checks too. +//! +//! 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. The functions are `tob_rect`, +//! `tob_sample`, `tob_solid` and `tob_read` of the owned fixture +//! `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`). + +use super::blit_holds::{until, Scratch}; +use super::draw_again::{checks_ended, device, drawn_alone, run_into, Heard, Ran}; +use super::encoder_holds::library; +use crate::{ + CommandQueue, Device, PipelineOptions, Region, RenderCommandEncoder, RenderPipelineState, + ResourceOptions, SamplerState, ScissorRect, Texture, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::{ + BarrierScope, BlendFactor, PixelFormat, PrimitiveType, RenderStages, TextureUsage, +}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; + +/// The target's side, in pixels. +const SIDE: u64 = 16; + +/// The texels of the two textures draw A samples, the first before the split, the second after. +const TEXELS: [[u8; 4]; 2] = [[200, 0, 0, 255], [0, 0, 200, 255]]; + +/// The colors draw B adds, the first before the split, the second after. +const ADDED: [[u8; 4]; 2] = [[0, 51, 0, 0], [51, 51, 0, 255]]; + +/// The boxes `[x0, y0, x1, y1)` of the encoder's draws, in its order: A, B, the reader, A, B (and +/// B's draws again, [`AGAIN`]). +const BOXES: [[u64; 4]; 5] = [ + [0, 0, 8, 8], + [4, 4, 12, 12], + [2, 2, 10, 10], + [6, 6, 14, 14], + [8, 0, 16, 8], +]; + +/// The draws of the last B again after it, with no call between. +const AGAIN: u64 = 2; + +/// The states and resources of the encoder's draws. +struct Draws { + /// `tob_sample`, opaque. + sampling: RenderPipelineState, + /// `tob_solid`, adding its color to the target's. + adding: RenderPipelineState, + /// `tob_read`, opaque: the target's texel at the fragment's pixel. + reading: RenderPipelineState, + textures: [Texture; 2], + sampler: SamplerState, +} + +impl Draws { + fn new(device: &Device) -> Draws { + let state = |fragment: &str, adding: bool| { + let library = library(device, "engine/tob_renders.ll"); + let function = |name| { + let function = library.new_function_with_name(name).unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); + descriptor.fragment = Some(function(fragment)); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm); + if adding { + color.blending_enabled = true; + color.destination_rgb_blend_factor = BlendFactor::One; + color.destination_alpha_blend_factor = BlendFactor::One; + } + descriptor.color_attachments[0] = Some(color); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() + }; + let texture = |texel: [u8; 4]| { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 1, 1, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let whole = Region::new_2d(0, 0, 1, 1); + texture.replace_region(whole, 0, 0, &texel, 4, 0).unwrap(); + texture + }; + Draws { + sampling: state("tob_sample", false), + adding: state("tob_solid", true), + reading: state("tob_read", false), + textures: TEXELS.map(texture), + sampler: device.new_sampler_state(&SamplerDescriptor::new()).unwrap(), + } + } + + /// The encoder's draws into `target` (the module docs), after the sampler and fragment buffer 0 + /// bound before them (as the walk binds them, so that every state's bind state holds the slot + /// B binds), each setting its state, its scissor rectangle (its box) and its corners, with + /// `between` called after each: A sampling the first texture, B adding the first color, a + /// memory barrier over the render targets from the fragment stage to the fragment stage, the + /// reader, A sampling the second texture, B adding the second color, and B's draw again + /// [`AGAIN`] times. + fn encode( + &self, + encoder: &mut RenderCommandEncoder, + target: &Texture, + between: &dyn Fn(&mut RenderCommandEncoder), + ) { + encoder + .set_fragment_sampler_state(Some(&self.sampler), 0) + .unwrap(); + let added = ADDED[0].map(|byte| f32::from(byte) / 255.0); + encoder.set_fragment_bytes(&floats(added), 0).unwrap(); + for (at, area) in BOXES.into_iter().enumerate() { + match at { + 0 | 3 => { + let texture = &self.textures[at / 3]; + encoder.set_render_pipeline_state(&self.sampling).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + } + 1 | 4 => { + encoder.set_render_pipeline_state(&self.adding).unwrap(); + let added = ADDED[at / 4].map(|byte| f32::from(byte) / 255.0); + encoder.set_fragment_bytes(&floats(added), 0).unwrap(); + } + _ => { + let fragment = RenderStages::FRAGMENT; + let scope = BarrierScope::RENDER_TARGETS; + encoder.memory_barrier_with_scope(scope, fragment, fragment); + encoder.set_render_pipeline_state(&self.reading).unwrap(); + encoder.set_fragment_texture(Some(target), 0).unwrap(); + } + } + let [x0, y0, x1, y1] = area; + let rect = ScissorRect { + x: x0, + y: y0, + width: x1 - x0, + height: y1 - y0, + }; + encoder.set_scissor_rect(rect).unwrap(); + encoder.set_vertex_bytes(&corners(area), 0).unwrap(); + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0); + assert_eq!(drawn, Ok(())); + between(encoder); + } + for _ in 0..AGAIN { + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0); + assert_eq!(drawn, Ok(())); + between(encoder); + } + } + + /// [`Draws::encode`] into a new cleared private target, with `between` after each draw, on + /// `queue`: what it recorded and drew. + fn run( + &self, + device: &Device, + queue: &CommandQueue, + between: &dyn Fn(&mut RenderCommandEncoder), + ) -> Ran { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let target = device.new_texture(&descriptor).unwrap(); + let encode = |encoder: &mut RenderCommandEncoder| self.encode(encoder, &target, between); + run_into(device, queue, &target, encode, true) + } +} + +fn floats(v: [f32; 4]) -> Vec { + v.iter().flat_map(|f| f.to_le_bytes()).collect() +} + +/// The corners, in normalized device coordinates, of the target's pixels `[x0, x1) x [y0, y1)`. +fn corners([x0, y0, x1, y1]: [u64; 4]) -> Vec { + let x = |p: u64| p as f32 / SIDE as f32 * 2.0 - 1.0; + let y = |p: u64| 1.0 - p as f32 / SIDE as f32 * 2.0; + floats([x(x0), y(y1), x(x1), y(y0)]) +} + +/// The two kept draws set aside when the reader splits the pass are re-homed into the instance +/// after the split, and the draws of their states after it are rebound there, as are B's draws +/// again with no call between (a draw again's every other form records a Vulkan draw of its own, +/// which an instance after a split records only from its room), with the same +/// commands, state commands and pixels as every draw taking every step after a call between each +/// that changes nothing for them (`set_tessellation_factor_scale`, which no draw of their states +/// reads), which forgets the kept draws. The reader splits the pass once in both runs, and no +/// draw keeps nothing for another reason than its own (`WorkCounts::draws_unkept_other`): a draw +/// into the instance after the split keeps itself. +#[test] +fn kept_draws_set_aside_are_rebound_past_a_split() { + let scratch = Scratch::new("split-keeps"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let queue = device.new_command_queue().unwrap(); + let draws = Draws::new(&device); + until("every key's own pipeline made", || { + let residual = device.work_counts().residual_form_draws; + draws.run(&device, &queue, &|_| {}); + device.work_counts().residual_form_draws == residual + }); + until("the pipeline pool idle", || { + device.work_counts().pipeline_pool_busy == 0 + }); + checks_ended(&device); + let forgets = |encoder: &mut RenderCommandEncoder| encoder.set_tessellation_factor_scale(1.0); + let kept = draws.run(&device, &queue, &|_| {}); + let every = draws.run(&device, &queue, &forgets); + eprintln!("kept: {}", kept.moved()); + eprintln!("every step: {}", every.moved()); + let counted = |of: fn(&WorkCounts) -> u64| (kept.counted(of), every.counted(of)); + assert_eq!( + counted(|c| c.inline_split_instances), + (1, 1), + "the instances after the split" + ); + assert_eq!( + counted(|c| c.instance_splits_attached_read), + (1, 1), + "the splits by the reader's read of its attachment" + ); + assert_eq!( + counted(|c| c.kept_draws_rehomed), + (2, 0), + "the kept draws re-homed" + ); + assert_eq!( + counted(|c| c.draws_unlike_kept + c.draws_rebind_stopped), + (0, 0), + "the draws unlike their kept draws, or whose rebind stopped" + ); + assert_eq!( + counted(|c| c.draws_rebound), + (drawn_alone(2 + AGAIN), 0), + "the draws rebound" + ); + assert_eq!( + counted(|c| c.draws_unkept_other), + (0, 0), + "the draws that kept nothing for another reason" + ); + assert_eq!(kept.commands, every.commands); + assert_eq!(kept.commands["cmd_draw"], BOXES.len() as u64 + AGAIN); + assert_eq!( + kept.counted(|c| c.draw_states_recorded), + every.counted(|c| c.draw_states_recorded) + ); + assert_eq!(kept.words, every.words, "the pixels of the draws"); + // The draws after the split drew what they bound: the second texture, the second color (added + // by B and its draws again). + let word = |x: u64, y: u64| kept.words[(y * SIDE + x) as usize]; + assert_eq!( + word(13, 13), + u32::from_le_bytes(TEXELS[1]), + "A after the split" + ); + assert_eq!( + word(15, 1), + u32::from_le_bytes(ADDED[1].map(|byte| byte.saturating_mul(1 + AGAIN as u8))), + "B after the split" + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index e7f34f0a9..935aeaffa 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -872,6 +872,7 @@ struct CommandCounters { draws_rebind_stopped: AtomicU64, draws_restated: AtomicU64, draws_restated_scissors: AtomicU64, + kept_draws_rehomed: AtomicU64, draws_rebound_arguments: AtomicU64, draws_rebind_stopped_arguments: AtomicU64, draws_rebind_stopped_arguments_by: [AtomicU64; ArgumentsStop::COUNT], @@ -1873,6 +1874,14 @@ impl Counting<'_> { self.0.add(|counts| &counts.draws_restated_scissors, 1); } + /// `count` kept draws set aside kept into the render pass instance a draw began after a + /// split (`WorkCounts::kept_draws_rehomed`). + pub(crate) fn kept_draws_rehomed(&self, count: u64) { + if count > 0 { + self.0.add(|counts| &counts.kept_draws_rehomed, count); + } + } + /// A render draw rebound with other arguments than its kept draw's /// (`WorkCounts::draws_rebound_arguments`). pub(crate) fn draw_rebound_arguments(&self) { @@ -8645,6 +8654,14 @@ pub struct WorkCounts { /// `draws_restated` too; one whose rebind then stopped, or which a build with debug /// assertions checked by its every step, took every step. pub draws_restated_scissors: u64, + /// Render encoders' kept draws set aside with the states of other pipeline states, kept into + /// the render pass instance a draw began after a split, of the same shape, where that draw + /// kept nothing only for recording into it (`render/draw_again.rs`): each but those that read + /// the pass's colors other than through snapshots of their own, a reader through snapshots, + /// one carried in and not drawn since, or one that read what changes with no call otherwise, + /// which are let go. The next draw of each is rebound into that instance (`draws_rebound`), + /// in place of taking every step (`draws_none_kept`). + pub kept_draws_rehomed: u64, /// Of `draws_rebound`, those that differed from the draw they repeat only in their arguments /// (`draws_unlike_kept_arguments_alone` lists them: their call of the same primitive type, /// with indices or without, their counts and starts, index buffer, index type or index buffer @@ -11722,6 +11739,7 @@ impl Device { draws_moved_inside: commands(|counts| &counts.draws_moved_inside), draws_restated: commands(|counts| &counts.draws_restated), draws_restated_scissors: commands(|counts| &counts.draws_restated_scissors), + kept_draws_rehomed: commands(|counts| &counts.kept_draws_rehomed), draws_rebound_arguments: commands(|counts| &counts.draws_rebound_arguments), draws_rebound_carried: commands(|counts| &counts.draws_rebound_carried), draws_none_kept: commands(|counts| &counts.draws_none_kept), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 0757ecb7b..3853dd972 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3249,6 +3249,7 @@ field metal2vulkan-runtime::WorkCounts.kept_draws_let_go_other pub kept_draws_le field metal2vulkan-runtime::WorkCounts.kept_draws_let_go_store_action pub kept_draws_let_go_store_action: u64 field metal2vulkan-runtime::WorkCounts.kept_draws_let_go_use pub kept_draws_let_go_use: u64 field metal2vulkan-runtime::WorkCounts.kept_draws_let_go_visibility pub kept_draws_let_go_visibility: u64 +field metal2vulkan-runtime::WorkCounts.kept_draws_rehomed pub kept_draws_rehomed: u64 field metal2vulkan-runtime::WorkCounts.kept_draws_uncarried_attached pub kept_draws_uncarried_attached: u64 field metal2vulkan-runtime::WorkCounts.kept_padding_aliases pub kept_padding_aliases: u64 field metal2vulkan-runtime::WorkCounts.kept_resident_keys_compared pub kept_resident_keys_compared: u64