⚡ The viewport a draw asks for is the one the driver already has, nineteen draws in twenty
crates/reims-vgpu, Vulkan backend, both pathways (recording is shared; measured
on x86/dGPU).
Two commits' worth of reading landed first, then a third change built on it.
## What the twelve interleaved boots said about the previous two
Two pins differing only by `ShaderVariant` and `VertexBindPlan`, A,B,A,B on one
quiesced host, scored over the fast population. Per draw:
before (n=4) after (n=6)
reflect_us 0.340 [0.332..0.345] 0.021 [0.020..0.021]
sampled_us 1.911 [1.861..1.972] 1.640 [1.574..1.691]
engine_us 6.235 [6.065..6.338] 6.208 [6.033..6.283]
binds_us 2.477 [2.418..2.525] 2.636 [2.510..2.695]
draw_us/draw 13.33 [13.05..13.61] 13.03 [12.82..13.44]
present_hz 114.25 [112.90..115.40] 114.16 [113.40..115.30]
`reflect_us` −94 % and `sampled_us` −14 %, both disjoint, with `engine_us` — a
phase neither change touches — flat as the control. `binds_us` moved the *wrong*
way with ranges that touch, and the sub-column where `VertexBindPlan` removed
two set builds rose 0.04 us, which removing work cannot cause; that is
boot-to-boot spread, and its doc now says the change is unconfirmed rather than
claiming it. Frames did not move, which is what a 2.3 % per-draw change is
supposed to look like here. Both readings are recorded next to the code.
A first attempt ran the pins in sequence and read `engine_us` **+18 %** with
`gpu occupancy` up and `present_hz` down — the GPU clocking down between the
groups. Interleaving is not optional for a pin comparison on this host, and
`AGENTS.md` now carries the `pkill` rule that made the first interleaved attempt
kill its own runner.
## What this commit adds
Every batched draw re-recorded `vkCmdBindPipeline`, `vkCmdSetViewport` and
`vkCmdSetScissor` whatever its predecessor in the same command buffer had
already bound, and built two fresh `Vec`s to do it. Pipeline binding and dynamic
state are properties of a command buffer's *recording*, invalidated at
`vkBeginCommandBuffer` and not at a render pass boundary — which is what makes
skipping them legal on a path where every draw opens and closes its own pass.
`CbGraphicsState` remembers what the recording command buffer carries. The one
rule that makes it sound is that **a pipeline change clears the dynamic half**:
a pipeline declaring a state statically stops it being dynamic, this device does
not build every pipeline with the same dynamic-state list
(`STENCIL_REFERENCE` only appears on stencil pipelines), so a cached dynamic
value cannot cross a pipeline change. One line, and nobody has to answer "which
states did which pipeline declare".
The two `Vec`s become pools-owned scratch, swapped with the bound array rather
than cloned, so the comparison costs no allocation and the per-draw allocation
goes away with it.
Counted on `EngineCounters` atomics, not `note_store_route`: four route calls a
draw is four global-mutex acquisitions, which at 30 000 draws a second would
have cost more than the skips save. `dynstate_pipeline_held` is the one to read
first — it is the ceiling on the other three by construction.
`forget_pass_echo` drops this state with the echo, because they are one fact and
the new half is the dangerous one: a stale echo makes a draw skip an instrument,
a stale `CbGraphicsState` makes it skip a real `vkCmdSetViewport` on a handle a
`vkBeginCommandBuffer` has since reset.
Tests: five over the two matchers, per field and per length, because a missed
field renders the draw through its predecessor's viewport with no error
anywhere. Bit patterns and not `==`, with a test pinning that `-0.0` does not
match `0.0` — resending is always safe and the comparison may be stricter than
float equality but never looser.
Verified: `cargo test -p reims-vgpu --no-default-features
--features backend-vulkan,host-window -- --test-threads=1` — 1907+4+3+1+10+12+53
passed, 0 failed, 5 ignored. Clippy clean with `-D warnings` on the Vulkan arm
and on `--target aarch64-apple-darwin --features backend-metal`.
Not verified: this commit's own change is not booted. Its A/B and the
`dynstate_*_held` rates are the next step — if `dynstate_pipeline_held` is near
zero, consecutive draws never share a pipeline and the cache is inert.
This commit is contained in:
1 parent
f879e0de10
commit
5fb5414f48
6 files changed
+432
-43
No files matched your search
@@ -454,6 +454,25 @@ engine_counters! {
|
||||
/// buffer if it is taken against a boot's `batch_flush_draws /
|
||||
/// batch_flushes`, which says how many draws there were to reuse over.
|
||||
buffer_bind_reuses,
|
||||
/// Graphics state a draw did **not** record because the command buffer
|
||||
/// it joined was already carrying exactly it — see
|
||||
/// `ResourcePools::CbGraphicsState`.
|
||||
///
|
||||
/// Every draw asks all four questions, so each of these is out of
|
||||
/// `chain_phase chains` and none can exceed it. `dynstate_pipeline_held`
|
||||
/// is the one to read first: a pipeline change clears the other three by
|
||||
/// construction, so it is the ceiling on them and a boot where it is
|
||||
/// near zero is a boot where consecutive draws never share a pipeline
|
||||
/// and this whole cache is inert.
|
||||
///
|
||||
/// `dynstate_stencil_held` is out of the *stencil* draws rather than all
|
||||
/// of them — a draw with no stencil state asks nothing and counts
|
||||
/// nowhere — so it is the one that does not belong to the same
|
||||
/// denominator.
|
||||
dynstate_pipeline_held,
|
||||
dynstate_viewport_held,
|
||||
dynstate_scissor_held,
|
||||
dynstate_stencil_held,
|
||||
sampled_cache_hits,
|
||||
sampled_identity_hits,
|
||||
sampled_cache_hit_bytes,
|
||||
|
||||
@@ -3822,8 +3822,10 @@ pub(crate) unsafe fn execute_draw_inner(
|
||||
ctx.device
|
||||
.cmd_begin_render_pass(cb, &rp_begin, vk::SubpassContents::INLINE);
|
||||
pools.note_pass_opened(echo);
|
||||
ctx.device
|
||||
.cmd_bind_pipeline(cb, vk::PipelineBindPoint::GRAPHICS, pipeline);
|
||||
// Only if this command buffer is not already carrying it — the three
|
||||
// `dynstate_*` skips below hang off this one call, because a pipeline change
|
||||
// is what invalidates them. See `super::pools::CbGraphicsState`.
|
||||
unsafe { pools.bind_graphics_pipeline(&ctx.device, cb, counters, pipeline) };
|
||||
if let Some((pool, flags)) = occlusion {
|
||||
ctx.device.cmd_begin_query(cb, pool, 0, flags);
|
||||
}
|
||||
@@ -3851,46 +3853,51 @@ pub(crate) unsafe fn execute_draw_inner(
|
||||
// request or `vkCmdSetViewport` binds a different count than the pipeline
|
||||
// declared.
|
||||
let slots = crate::backend::vulkan::engine::viewport_slot_count(req);
|
||||
let viewports: Vec<vk::Viewport> = (0..slots)
|
||||
.map(|i| {
|
||||
let vp = req.viewports.get(i).copied().unwrap_or(default_vp);
|
||||
vk::Viewport {
|
||||
x: vp.x,
|
||||
y: vp.y + vp.height,
|
||||
width: vp.width,
|
||||
height: -vp.height,
|
||||
min_depth: vp.min_depth,
|
||||
max_depth: vp.max_depth,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
ctx.device.cmd_set_viewport(cb, 0, &viewports);
|
||||
let scissors: Vec<vk::Rect2D> = (0..slots)
|
||||
.map(|i| {
|
||||
let sc = req.scissors.get(i).copied().unwrap_or(default_sc);
|
||||
let x = sc.x.min(req.width);
|
||||
let y = sc.y.min(req.height);
|
||||
vk::Rect2D {
|
||||
offset: vk::Offset2D {
|
||||
x: x as i32,
|
||||
y: y as i32,
|
||||
},
|
||||
extent: vk::Extent2D {
|
||||
width: sc.width.min(req.width - x),
|
||||
height: sc.height.min(req.height - y),
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
ctx.device.cmd_set_scissor(cb, 0, &scissors);
|
||||
// Built into the pools' scratch rather than into two fresh `Vec`s: these are
|
||||
// rebuilt every draw, and the comparison that decides whether the driver
|
||||
// already has them needs a buffer it can swap rather than copy.
|
||||
let (vp_scratch, sc_scratch) = pools.dynamic_scratch();
|
||||
vp_scratch.extend((0..slots).map(|i| {
|
||||
let vp = req.viewports.get(i).copied().unwrap_or(default_vp);
|
||||
vk::Viewport {
|
||||
x: vp.x,
|
||||
y: vp.y + vp.height,
|
||||
width: vp.width,
|
||||
height: -vp.height,
|
||||
min_depth: vp.min_depth,
|
||||
max_depth: vp.max_depth,
|
||||
}
|
||||
}));
|
||||
sc_scratch.extend((0..slots).map(|i| {
|
||||
let sc = req.scissors.get(i).copied().unwrap_or(default_sc);
|
||||
let x = sc.x.min(req.width);
|
||||
let y = sc.y.min(req.height);
|
||||
vk::Rect2D {
|
||||
offset: vk::Offset2D {
|
||||
x: x as i32,
|
||||
y: y as i32,
|
||||
},
|
||||
extent: vk::Extent2D {
|
||||
width: sc.width.min(req.width - x),
|
||||
height: sc.height.min(req.height - y),
|
||||
},
|
||||
}
|
||||
}));
|
||||
unsafe { pools.set_dynamic_viewport_scissor(&ctx.device, cb, counters) };
|
||||
// Dynamic stencil reference (Metal `setStencilFrontReferenceValue:back…`)
|
||||
// — only bound for stencil pipelines, which list STENCIL_REFERENCE as a
|
||||
// dynamic state; front/back set separately to honor Metal's split refs.
|
||||
// dynamic state; front/back set together because Metal's split refs are one
|
||||
// guest state and a cache that held half of it would be two.
|
||||
if let Some(s) = req.depth.as_ref().and_then(|d| d.stencil) {
|
||||
ctx.device
|
||||
.cmd_set_stencil_reference(cb, vk::StencilFaceFlags::FRONT, s.reference_front);
|
||||
ctx.device
|
||||
.cmd_set_stencil_reference(cb, vk::StencilFaceFlags::BACK, s.reference_back);
|
||||
unsafe {
|
||||
pools.set_dynamic_stencil_reference(
|
||||
&ctx.device,
|
||||
cb,
|
||||
counters,
|
||||
s.reference_front,
|
||||
s.reference_back,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(dset) = dset {
|
||||
@@ -4141,7 +4148,7 @@ pub(crate) unsafe fn execute_draw_inner(
|
||||
// on, and cheaper than computing a union of arbitrary rects.
|
||||
counters.note_draw_coverage(if rewrites_whole_attachment {
|
||||
super::counters::DrawCoverage::Full
|
||||
} else if scissors.iter().any(|s| {
|
||||
} else if pools.bound_scissors().iter().any(|s| {
|
||||
s.offset.x <= 0
|
||||
&& s.offset.y <= 0
|
||||
&& s.extent.width >= req.width
|
||||
|
||||
@@ -231,6 +231,9 @@ pub(crate) struct ResourcePools {
|
||||
/// the correctness edge: a bind after a Store into the same pages must see
|
||||
/// what the Store wrote, and reusing a copy taken before it would not.
|
||||
cb_bound_buffers: HashMap<(usize, u64), super::exec::BoundBuffer>,
|
||||
/// Graphics state the command buffer now recording already carries — see
|
||||
/// [`CbGraphicsState`].
|
||||
cb_graphics: CbGraphicsState,
|
||||
/// Staging free-list hits / misses and the miss bucket histogram; see
|
||||
/// `note_staging_miss`. Measure-only.
|
||||
staging_hits: u64,
|
||||
@@ -615,6 +618,81 @@ pub(crate) struct PassEcho {
|
||||
pub(crate) area: (u32, u32),
|
||||
}
|
||||
|
||||
/// Graphics state a recording command buffer already carries, so a draw that
|
||||
/// wants the state its predecessor left does not record the call again.
|
||||
///
|
||||
/// # Why this is sound, and the one rule that makes it so
|
||||
///
|
||||
/// Pipeline binding and dynamic state are properties of a **command buffer's
|
||||
/// recording**, not of a render pass instance: Vulkan invalidates them at
|
||||
/// `vkBeginCommandBuffer` and nowhere else on this path, so a draw that ends its
|
||||
/// pass and begins another has not disturbed either. That is what makes the skip
|
||||
/// legal at all — every batched draw here opens and closes its own pass.
|
||||
///
|
||||
/// The hazard it does *not* clear is static pipeline state. When a pipeline
|
||||
/// declaring some state statically is bound, that state stops being dynamic, and
|
||||
/// a later pipeline declaring it dynamic leaves it undefined until set again.
|
||||
/// This device does not build every pipeline with the same dynamic-state list —
|
||||
/// `VK_DYNAMIC_STATE_STENCIL_REFERENCE` is listed only by pipelines with a
|
||||
/// stencil — so a cached dynamic value is not safe across a pipeline change.
|
||||
///
|
||||
/// **So a pipeline change clears the dynamic half.** That is the whole rule, it
|
||||
/// is one line in [`Self::bind_pipeline`], and it makes the question "which
|
||||
/// states did which pipeline declare dynamic" one nobody has to answer.
|
||||
///
|
||||
/// `cb` is carried for the reason [`PassEcho`] carries it: a command buffer
|
||||
/// handle is recycled, and state left by the previous user of the handle names
|
||||
/// bindings a `vkBeginCommandBuffer` has since made undefined. Every field is
|
||||
/// dropped together when the handle differs, so there is no path that clears one
|
||||
/// and keeps another.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct CbGraphicsState {
|
||||
/// The command buffer every other field is an assertion about.
|
||||
cb: Option<vk::CommandBuffer>,
|
||||
/// The graphics pipeline last bound into `cb`.
|
||||
pipeline: Option<vk::Pipeline>,
|
||||
/// The viewport array last handed to `vkCmdSetViewport`, and the scissor
|
||||
/// array last handed to `vkCmdSetScissor`.
|
||||
viewports: Vec<vk::Viewport>,
|
||||
scissors: Vec<vk::Rect2D>,
|
||||
/// The front/back references last handed to `vkCmdSetStencilReference`.
|
||||
stencil: Option<(u32, u32)>,
|
||||
/// Scratch the next draw builds into, so the comparison costs no allocation.
|
||||
/// Swapped with the bound array when they differ rather than cloned.
|
||||
vp_scratch: Vec<vk::Viewport>,
|
||||
sc_scratch: Vec<vk::Rect2D>,
|
||||
}
|
||||
|
||||
/// Whether two viewport arrays are the value the driver already has.
|
||||
///
|
||||
/// Field by field on the bit pattern, not `==` on the float: the question is
|
||||
/// "are these the bytes already sent", which is exactly bitwise equality, and it
|
||||
/// is also what keeps `clippy::float_cmp` quiet without an `allow` that would
|
||||
/// hide a real float comparison later. `VkViewport` is a fixed Vulkan structure
|
||||
/// of six floats and cannot grow a seventh.
|
||||
fn viewports_match(a: &[vk::Viewport], b: &[vk::Viewport]) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter().zip(b).all(|(x, y)| {
|
||||
x.x.to_bits() == y.x.to_bits()
|
||||
&& x.y.to_bits() == y.y.to_bits()
|
||||
&& x.width.to_bits() == y.width.to_bits()
|
||||
&& x.height.to_bits() == y.height.to_bits()
|
||||
&& x.min_depth.to_bits() == y.min_depth.to_bits()
|
||||
&& x.max_depth.to_bits() == y.max_depth.to_bits()
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether two scissor arrays are the value the driver already has.
|
||||
fn scissors_match(a: &[vk::Rect2D], b: &[vk::Rect2D]) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter().zip(b).all(|(x, y)| {
|
||||
x.offset.x == y.offset.x
|
||||
&& x.offset.y == y.offset.y
|
||||
&& x.extent.width == y.extent.width
|
||||
&& x.extent.height == y.extent.height
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) struct OpenBatch {
|
||||
cb: vk::CommandBuffer,
|
||||
fence: vk::Fence,
|
||||
@@ -3496,3 +3574,102 @@ mod idle_slab_trim_tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dynamic_state_match_tests {
|
||||
use super::{scissors_match, viewports_match};
|
||||
use ash::vk;
|
||||
|
||||
fn vp(x: f32, y: f32, w: f32, h: f32, near: f32, far: f32) -> vk::Viewport {
|
||||
vk::Viewport {
|
||||
x,
|
||||
y,
|
||||
width: w,
|
||||
height: h,
|
||||
min_depth: near,
|
||||
max_depth: far,
|
||||
}
|
||||
}
|
||||
|
||||
fn rect(x: i32, y: i32, w: u32, h: u32) -> vk::Rect2D {
|
||||
vk::Rect2D {
|
||||
offset: vk::Offset2D { x, y },
|
||||
extent: vk::Extent2D {
|
||||
width: w,
|
||||
height: h,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Every field has to be compared, and the test is per field because the
|
||||
/// failure of a missed one is silent: the draw renders through the previous
|
||||
/// draw's viewport, which is wrong pixels with no error anywhere.
|
||||
///
|
||||
/// `height` is negative on this device — Metal NDC is Y-up and Vulkan's is
|
||||
/// Y-down, so every viewport is emitted flipped — which is why the base here
|
||||
/// carries a negative height rather than a tidy positive one.
|
||||
#[test]
|
||||
fn one_differing_viewport_field_is_enough_to_resend() {
|
||||
let base = [vp(1.0, 600.0, 800.0, -600.0, 0.0, 1.0)];
|
||||
assert!(viewports_match(&base, &base.clone()));
|
||||
for other in [
|
||||
vp(2.0, 600.0, 800.0, -600.0, 0.0, 1.0),
|
||||
vp(1.0, 601.0, 800.0, -600.0, 0.0, 1.0),
|
||||
vp(1.0, 600.0, 801.0, -600.0, 0.0, 1.0),
|
||||
vp(1.0, 600.0, 800.0, -601.0, 0.0, 1.0),
|
||||
vp(1.0, 600.0, 800.0, -600.0, 0.5, 1.0),
|
||||
vp(1.0, 600.0, 800.0, -600.0, 0.0, 0.5),
|
||||
] {
|
||||
assert!(!viewports_match(&base, &[other]), "{other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A different count is a different bind whatever the shared prefix says.
|
||||
/// The count is what the pipeline declared, so serving a two-slot draw from
|
||||
/// a one-slot cache would leave slot 1 holding the previous pipeline's.
|
||||
#[test]
|
||||
fn a_shorter_or_longer_array_never_matches() {
|
||||
let one = [vp(0.0, 0.0, 8.0, -8.0, 0.0, 1.0)];
|
||||
let two = [one[0], one[0]];
|
||||
assert!(!viewports_match(&one, &two));
|
||||
assert!(!viewports_match(&two, &one));
|
||||
assert!(!scissors_match(&[rect(0, 0, 8, 8)], &[]));
|
||||
}
|
||||
|
||||
/// Bit patterns, not `==`: `-0.0 == 0.0` is true for floats and false for
|
||||
/// "these are the bytes the driver already has". Resending is always safe
|
||||
/// and never wrong, so the comparison is allowed to be stricter than
|
||||
/// equality and must not be looser.
|
||||
#[test]
|
||||
fn negative_zero_is_a_different_viewport() {
|
||||
let pos = [vp(0.0, 0.0, 8.0, -8.0, 0.0, 1.0)];
|
||||
let neg = [vp(-0.0, 0.0, 8.0, -8.0, 0.0, 1.0)];
|
||||
assert_eq!(pos[0].x, neg[0].x, "float equality says these are the same");
|
||||
assert!(!viewports_match(&pos, &neg), "bit equality must not");
|
||||
}
|
||||
|
||||
/// The same, per field, for the integer rectangles.
|
||||
#[test]
|
||||
fn one_differing_scissor_field_is_enough_to_resend() {
|
||||
let base = [rect(4, 5, 800, 600)];
|
||||
assert!(scissors_match(&base, &base.clone()));
|
||||
for other in [
|
||||
rect(5, 5, 800, 600),
|
||||
rect(4, 6, 800, 600),
|
||||
rect(4, 5, 801, 600),
|
||||
rect(4, 5, 800, 601),
|
||||
] {
|
||||
assert!(!scissors_match(&base, &[other]), "{other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty pair matches, which is what a freshly reset command buffer's
|
||||
/// cache holds — and it must not make the first draw skip its bind. The
|
||||
/// first draw always has at least one slot (`viewport_slot_count` never
|
||||
/// returns zero), so an empty cache can never match it.
|
||||
#[test]
|
||||
fn an_empty_cache_matches_only_an_empty_request() {
|
||||
assert!(viewports_match(&[], &[]));
|
||||
assert!(!viewports_match(&[vp(0.0, 0.0, 1.0, -1.0, 0.0, 1.0)], &[]));
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,7 @@ impl ResourcePools {
|
||||
gather_free: HashMap::new(),
|
||||
gather_live: Vec::new(),
|
||||
cb_bound_buffers: std::collections::HashMap::new(),
|
||||
cb_graphics: super::CbGraphicsState::default(),
|
||||
staging_hits: 0,
|
||||
staging_misses: 0,
|
||||
staging_miss_bins: [0; STAGING_BUCKET_BINS],
|
||||
@@ -1591,15 +1592,30 @@ impl ResourcePools {
|
||||
self.last_pass = Some(echo);
|
||||
}
|
||||
|
||||
/// Forget the echoed pass.
|
||||
/// Forget everything remembered about the command buffer that was
|
||||
/// recording: the echoed pass and the graphics state it carried.
|
||||
///
|
||||
/// Called wherever the command buffer holding it stops being the one a draw
|
||||
/// would record into — a reset at `begin_entry`, a submit at the batch
|
||||
/// Called wherever the command buffer holding them stops being the one a
|
||||
/// draw would record into — a reset at `begin_entry`, a submit at the batch
|
||||
/// flush, and teardown. Missing one would let a joiner believe a pass ended
|
||||
/// in a previous submission is still open, which is why this is a method
|
||||
/// rather than an assignment at each site.
|
||||
///
|
||||
/// Both halves are dropped by one call because they are one fact, and
|
||||
/// because the second is the more dangerous to get wrong. A stale echo makes
|
||||
/// a draw *skip a `vkCmdBeginRenderPass`* only in an instrument that decides
|
||||
/// nothing; a stale [`CbGraphicsState`] makes it skip a real
|
||||
/// `vkCmdSetViewport`, and a recycled handle is exactly the case where that
|
||||
/// state was made undefined by a `vkBeginCommandBuffer` the cache never saw.
|
||||
/// The handle comparison inside that struct is the second lock on the same
|
||||
/// door, not the first.
|
||||
pub(crate) fn forget_pass_echo(&mut self) {
|
||||
self.last_pass = None;
|
||||
self.cb_graphics.cb = None;
|
||||
self.cb_graphics.pipeline = None;
|
||||
self.cb_graphics.viewports.clear();
|
||||
self.cb_graphics.scissors.clear();
|
||||
self.cb_graphics.stencil = None;
|
||||
}
|
||||
|
||||
/// Record a batch-deferred draw's completion: open the batch on its ring
|
||||
@@ -1872,6 +1888,126 @@ impl ResourcePools {
|
||||
self.cb_bound_buffers.clear();
|
||||
}
|
||||
|
||||
/// Bind the graphics pipeline unless this command buffer already carries it.
|
||||
///
|
||||
/// A pipeline change clears the dynamic half of [`CbGraphicsState`], which is
|
||||
/// the rule that makes the three skips below sound whatever dynamic-state
|
||||
/// list each pipeline was built with — see that type's doc.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `cb` must be a command buffer in the recording state, and `pipeline` a
|
||||
/// live graphics pipeline compatible with what the draw is about to record.
|
||||
pub(crate) unsafe fn bind_graphics_pipeline(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
cb: vk::CommandBuffer,
|
||||
counters: &EngineCounters,
|
||||
pipeline: vk::Pipeline,
|
||||
) {
|
||||
let g = &mut self.cb_graphics;
|
||||
if g.cb != Some(cb) {
|
||||
// A recycled handle: everything the previous user of it bound was
|
||||
// made undefined by the `vkBeginCommandBuffer` in between.
|
||||
g.cb = Some(cb);
|
||||
g.pipeline = None;
|
||||
g.viewports.clear();
|
||||
g.scissors.clear();
|
||||
g.stencil = None;
|
||||
}
|
||||
if g.pipeline == Some(pipeline) {
|
||||
counters.dynstate_pipeline_held.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
g.pipeline = Some(pipeline);
|
||||
// Static state on the incoming pipeline may have replaced any of these,
|
||||
// so none of them is known any more.
|
||||
g.viewports.clear();
|
||||
g.scissors.clear();
|
||||
g.stencil = None;
|
||||
unsafe { device.cmd_bind_pipeline(cb, vk::PipelineBindPoint::GRAPHICS, pipeline) };
|
||||
}
|
||||
|
||||
/// The scratch arrays a draw builds its viewport and scissor lists into,
|
||||
/// cleared and ready.
|
||||
///
|
||||
/// Handed out rather than allocated per draw: the lists are rebuilt every
|
||||
/// draw and were two `Vec` allocations on the recording path, and the
|
||||
/// comparison in [`Self::set_dynamic_viewport_scissor`] needs them in a
|
||||
/// buffer it can swap rather than copy.
|
||||
pub(crate) fn dynamic_scratch(&mut self) -> (&mut Vec<vk::Viewport>, &mut Vec<vk::Rect2D>) {
|
||||
let g = &mut self.cb_graphics;
|
||||
g.vp_scratch.clear();
|
||||
g.sc_scratch.clear();
|
||||
(&mut g.vp_scratch, &mut g.sc_scratch)
|
||||
}
|
||||
|
||||
/// Record `vkCmdSetViewport` / `vkCmdSetScissor` from the scratch arrays,
|
||||
/// each only if this command buffer is not already carrying exactly it.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `cb` must be the recording command buffer most recently passed to
|
||||
/// [`Self::bind_graphics_pipeline`], so the pipeline-change rule that
|
||||
/// authorises the skip has been applied.
|
||||
pub(crate) unsafe fn set_dynamic_viewport_scissor(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
cb: vk::CommandBuffer,
|
||||
counters: &EngineCounters,
|
||||
) {
|
||||
let g = &mut self.cb_graphics;
|
||||
if super::viewports_match(&g.vp_scratch, &g.viewports) {
|
||||
counters.dynstate_viewport_held.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
std::mem::swap(&mut g.viewports, &mut g.vp_scratch);
|
||||
unsafe { device.cmd_set_viewport(cb, 0, &g.viewports) };
|
||||
}
|
||||
if super::scissors_match(&g.sc_scratch, &g.scissors) {
|
||||
counters.dynstate_scissor_held.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
std::mem::swap(&mut g.scissors, &mut g.sc_scratch);
|
||||
unsafe { device.cmd_set_scissor(cb, 0, &g.scissors) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The scissor rectangles this command buffer is carrying, which are the
|
||||
/// recording draw's.
|
||||
///
|
||||
/// True on both arms of the skip and that is the point: a draw that set them
|
||||
/// swapped its own array in, and a draw that skipped did so *because* the
|
||||
/// array already there is bit-for-bit what it would have sent. A consumer
|
||||
/// that kept its own copy would be a second spelling of the same rects.
|
||||
pub(crate) fn bound_scissors(&self) -> &[vk::Rect2D] {
|
||||
&self.cb_graphics.scissors
|
||||
}
|
||||
|
||||
/// Record both `vkCmdSetStencilReference` faces unless this command buffer
|
||||
/// already carries exactly this pair.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As [`Self::set_dynamic_viewport_scissor`].
|
||||
pub(crate) unsafe fn set_dynamic_stencil_reference(
|
||||
&mut self,
|
||||
device: &ash::Device,
|
||||
cb: vk::CommandBuffer,
|
||||
counters: &EngineCounters,
|
||||
front: u32,
|
||||
back: u32,
|
||||
) {
|
||||
let g = &mut self.cb_graphics;
|
||||
if g.stencil == Some((front, back)) {
|
||||
counters.dynstate_stencil_held.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
g.stencil = Some((front, back));
|
||||
unsafe {
|
||||
device.cmd_set_stencil_reference(cb, vk::StencilFaceFlags::FRONT, front);
|
||||
device.cmd_set_stencil_reference(cb, vk::StencilFaceFlags::BACK, back);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the guest-read debt and answer whether there was one.
|
||||
///
|
||||
/// Split from the wait so the ledger half is testable without a device: it
|
||||
|
||||
@@ -272,6 +272,38 @@ pub struct ShaderVariant {
|
||||
/// and the draw path ran it twice a draw. It is the larger half of what
|
||||
/// `sampled_phase`'s `Part::Reflect` brackets, measured at 10 486 us/s over
|
||||
/// 29 944 draws — 0.35 us a draw — on a driven macos-13 boot.
|
||||
///
|
||||
/// # What it removed
|
||||
///
|
||||
/// Twelve interleaved driven macos-13 sustained-animation boots, two pinned
|
||||
/// binaries differing only by this and by
|
||||
/// [`crate::runtime::pipeline_resolve::VertexBindPlan`], scored over the
|
||||
/// fast population. Per draw, median over busy census windows, then mean and
|
||||
/// range across boots:
|
||||
///
|
||||
/// ```text
|
||||
/// before (n=4) after (n=6)
|
||||
/// reflect_us 0.340 [0.332..0.345] 0.021 [0.020..0.021]
|
||||
/// sampled_us 1.911 [1.861..1.972] 1.640 [1.574..1.691]
|
||||
/// engine_us 6.235 [6.065..6.338] 6.208 [6.033..6.283]
|
||||
/// ```
|
||||
///
|
||||
/// `reflect_us` is **−94 %** and `sampled_us` **−14 %**, both fully
|
||||
/// disjoint. `engine_us` — a phase neither change touches — does not move,
|
||||
/// which is the control that says the two arms are comparable at all.
|
||||
///
|
||||
/// `draw_us/draw` overall reads 13.33 [13.05..13.61] against 13.03
|
||||
/// [12.82..13.44]: −2.3 %, ranges overlapping. `present_hz` is 114.25
|
||||
/// against 114.16 — no movement, which is exactly what a 2 % per-draw change
|
||||
/// is supposed to look like here. **This bought a phase, not a frame**, and
|
||||
/// the elasticity beside `crate::runtime::drain::census::VBL_REPORT_EARLY`
|
||||
/// says it could not have bought a frame at that size.
|
||||
///
|
||||
/// A first attempt at this reading ran the two pins in sequence rather than
|
||||
/// interleaved, and reported `engine_us` **+18 %** with `gpu occupancy` up
|
||||
/// and `present_hz` down — the GPU clocking down between the two groups,
|
||||
/// with nothing in the log to say so. Interleaving is not optional for a pin
|
||||
/// comparison on this host.
|
||||
pub sampler_bindings: Arc<[u32]>,
|
||||
}
|
||||
|
||||
|
||||
@@ -183,6 +183,24 @@ pub const MEMO_CAPACITY: usize = 1024;
|
||||
/// at that size a sorted `binary_search` is a cache line and a compare where a
|
||||
/// tree is a pointer chase per level. The sort also makes the two sets
|
||||
/// canonical, so an equality between two resolutions means what it reads as.
|
||||
/// # The measurement did not confirm it, and this is what it said
|
||||
///
|
||||
/// The twelve interleaved boots quoted on
|
||||
/// [`crate::runtime::m2v_cache::ShaderVariant::sampler_bindings`] carried this
|
||||
/// change too, and `binds_us` — the column this targets — moved the **wrong
|
||||
/// way**: 2.477 [2.418..2.525] before against 2.636 [2.510..2.695] after, per
|
||||
/// draw. The ranges touch rather than separate, and the sub-column where the two
|
||||
/// set builds used to sit (`binds_us` less `bind_phase`'s three parts) rose 0.04
|
||||
/// us, which removing work cannot cause. So the honest reading is that
|
||||
/// `binds_us`'s boot-to-boot spread is wider than what this change is worth, not
|
||||
/// that the change costs anything.
|
||||
///
|
||||
/// It stays because it is strictly less work — two heap allocations and two tree
|
||||
/// builds a draw become two `binary_search`es over data the pipeline resolution
|
||||
/// already holds — and because per-draw allocation churn is a jitter source as
|
||||
/// well as a mean one. **No claim is made that it bought time.** If a future
|
||||
/// session wants one, `bind_phase` would need a fourth `Part` bracketing the
|
||||
/// lookups themselves; the three it has today do not reach them.
|
||||
pub struct VertexBindPlan {
|
||||
/// Buffer indices feeding at least one Constant-step attribute. A bind of
|
||||
/// one of these may not take the zero-copy rail: the engine prepends a CPU
|
||||
|
||||
Reference in new issue
Block a user