🐎 Batch fixed-offset draws with direct Vulkan commands

Reuse the ordinary draw state across a fixed binding without submitting indirect commands. RX 6500M timing showed the indirect command path still took 0.909 ms against 0.351 ms for the same direct workload, even with the ordinary shader.
This commit is contained in:
YXC0915 committed 2026-12-04 18:02:14 +08:00
1 parent acb2f3756b
commit 1dd4e970c0
3 files changed
+51 -130

No files matched your search

-58
View File
@@ -383,55 +383,9 @@ impl Draws {
struct DrawTable {
words: Box<[u32]>,
native_indirect: bool,
cache: Mutex<TableCache>,
}
/// A multi-draw changes DrawIndex from zero to the draw's position in the command. Check
/// the original module before specialization, including builtins on interface block members.
fn ignores_draw_index(words: &[u32]) -> bool {
const MAGIC: u32 = 0x0723_0203;
const DECORATE: u32 = 71;
const MEMBER_DECORATE: u32 = 72;
const BUILT_IN: u32 = 11;
const DRAW_INDEX: u32 = 4426;
let Some(mut instructions) = words.get(5..).filter(|_| words.first() == Some(&MAGIC)) else {
return false;
};
while let Some(&header) = instructions.first() {
let count = (header >> 16) as usize;
let Some((instruction, tail)) = instructions.split_at_checked(count) else {
return false;
};
if count == 0
|| matches!(
(header & 0xffff, instruction),
(DECORATE, [_, _, BUILT_IN, DRAW_INDEX])
| (MEMBER_DECORATE, [_, _, _, BUILT_IN, DRAW_INDEX])
)
{
return false;
}
instructions = tail;
}
true
}
#[test]
fn native_multi_draw_rejects_modules_with_a_draw_index_builtin() {
let accepts = |instruction: &[u32]| {
let mut words = vec![0x0723_0203, 0x0001_0300, 0, 10, 0];
words.extend_from_slice(instruction);
ignores_draw_index(&words)
};
assert!(accepts(&[4 << 16 | 71, 1, 11, 42]));
assert!(!accepts(&[4 << 16 | 71, 1, 11, 4426]));
assert!(!accepts(&[5 << 16 | 72, 1, 0, 11, 4426]));
assert!(!accepts(&[0]));
assert!(!accepts(&[4 << 16 | 71, 1]));
}
#[derive(Default)]
struct TableCache {
rejected: u32,
@@ -1628,11 +1582,6 @@ impl RenderCompiled {
&& !draws.unbound_storage
&& draws.fetched.is_empty()
&& (0..BUFFER_SLOTS).any(|slot| draws.table_slot(slot).is_some());
let native_indirect = can_table
&& pipeline
.stages
.iter()
.all(|stage| ignores_draw_index(&stage.spirv));
let mut notes: Vec<_> = constexpr_notes(translator.profile(), &constexprs).collect();
// Where a stage declares `SpecKey::TexelBufferWords`, whether one reaches a texture buffer
// through a handle: the content's words twin is made beside it.
@@ -1648,7 +1597,6 @@ impl RenderCompiled {
if can_table && module.stage == vk::ShaderStageFlags::VERTEX {
table = Some(DrawTable {
words: words.into_boxed_slice(),
native_indirect,
cache: Mutex::default(),
});
}
@@ -1801,12 +1749,6 @@ impl RenderCompiled {
self.draws.table_slot(slot)
}
pub(crate) fn native_multi_draw(&self) -> bool {
self.table
.as_ref()
.is_some_and(|table| table.native_indirect)
}
pub(crate) fn table_pipeline(
&self,
slot: u32,
@@ -161,13 +161,6 @@ pub struct VertexOffsetDraw {
pub base_instance: u32,
}
fn write_draw_command(command: &mut [u8; 16], draw: &VertexOffsetDraw) {
command[..4].copy_from_slice(&draw.vertex_count.to_le_bytes());
command[4..8].copy_from_slice(&draw.instance_count.to_le_bytes());
command[8..12].copy_from_slice(&draw.vertex_start.to_le_bytes());
command[12..].copy_from_slice(&draw.base_instance.to_le_bytes());
}
/// How recording a batch stopped after consuming a prefix of its items.
#[derive(Debug)]
pub enum BatchStop {
@@ -2606,7 +2599,8 @@ impl RenderCommandEncoder {
}
/// Records a prefix of buffer binds and non-indexed draws of the same primitive type.
/// The caller can process the remaining items with the ordinary bind and draw calls.
/// A fixed-offset prefix reuses the ordinary draw state; changing offsets use the draw
/// table. The caller can process the remaining items with ordinary bind and draw calls.
/// A successful return of zero leaves the encoder unchanged.
#[expect(
clippy::result_large_err,
@@ -2635,16 +2629,9 @@ impl RenderCommandEncoder {
return Ok(0);
}
// The table slot and environment checks above already rule out draws that require
// per-draw synchronization or lowering. Repeated offsets can use the ordinary shader.
let native_cap = if state.inner.compiled.native_multi_draw() {
cap
} else {
0
};
let fixed_count = draws[1..]
.iter()
.take(native_cap)
.take(cap)
.take_while(|draw| draw.offset == draws[0].offset)
.count();
let fixed_offset = fixed_count >= MIN_TAIL;
@@ -2653,8 +2640,8 @@ impl RenderCommandEncoder {
topology,
vk::PrimitiveTopology::LINE_LIST | vk::PrimitiveTopology::LINE_STRIP
);
// A normal head draw establishes the ordinary pipeline and push constants, including
// after a preceding batch that was recorded with the draw-table variant.
// A fixed binding starts with an ordinary draw so the pipeline, descriptors and push
// constants are current even after a preceding draw-table batch.
let skip_head = !fixed_offset
&& self.pass_drew
&& self.table_draw_facts_ready()
@@ -2694,8 +2681,8 @@ impl RenderCommandEncoder {
.as_ref()
.expect("the batch draws with this pipeline");
let compiled = &state.inner.compiled;
let first_instance =
self.core.draw_indirect_first_instance && !compiled.draws.first_instance_zero;
let first_instance = !compiled.draws.first_instance_zero
&& (fixed_offset || self.core.draw_indirect_first_instance);
let length = buffer.length();
let tail = &draws[head_done..];
let count = tail
@@ -2719,6 +2706,28 @@ impl RenderCommandEncoder {
if count < MIN_TAIL {
return Ok(head_done);
}
if fixed_offset {
// SAFETY: the ordinary head established rendering, the pipeline, and the
// unchanged buffer binding. These draw arguments were validated above, and the
// table and environment guards exclude draws that need per-draw synchronization.
let device = &self.core.device;
for draw in &tail[..count] {
unsafe {
device.cmd_draw(
self.command,
draw.vertex_count,
draw.instance_count,
draw.vertex_start,
draw.base_instance,
);
}
}
if self.facts.levels {
self.building()
.count_by(Metric::LevelFieldCommands, count as u64);
}
return Ok(head_done + count);
}
let tail_error = |mut stop| {
if let BatchStop::Device { completed, .. } = &mut stop {
@@ -2726,29 +2735,6 @@ impl RenderCommandEncoder {
}
stop
};
if fixed_offset {
// With an unchanged binding the ordinary shader already reads the right address.
// Only the indirect commands need uploading, with no draw table or variant.
let upload_len = ROW * count;
let bytes = &mut self.batch_bytes;
bytes.resize(bytes.len().max(upload_len), 0);
for (command, draw) in bytes[..upload_len]
.as_chunks_mut::<ROW>()
.0
.iter_mut()
.zip(&tail[..count])
{
write_draw_command(command, draw);
}
let building = self.building.as_mut().expect("the encoder is open");
let Some(placed) =
batch_tail(building.write_ring_placed(&bytes[..upload_len])).map_err(tail_error)?
else {
return Ok(head_done);
};
self.record_multi_draw(placed.buffer, placed.offset, count);
return Ok(head_done + count);
}
let Some(Some(pipeline)) =
batch_tail(compiled.table_pipeline(slot, fields, topology, self.raster))
.map_err(tail_error)?
@@ -2773,7 +2759,10 @@ impl RenderCommandEncoder {
let word = address_word(address.wrapping_add(draw.offset));
row[..8].copy_from_slice(&word.to_le_bytes());
row[8..].copy_from_slice(&bounds(length, draw.offset));
write_draw_command(command, draw);
command[..4].copy_from_slice(&draw.vertex_count.to_le_bytes());
command[4..8].copy_from_slice(&draw.instance_count.to_le_bytes());
command[8..12].copy_from_slice(&draw.vertex_start.to_le_bytes());
command[12..].copy_from_slice(&draw.base_instance.to_le_bytes());
}
let building = self.building.as_mut().expect("the encoder is open");
let Some(placed) =
@@ -2804,8 +2793,20 @@ impl RenderCommandEncoder {
self.record_state(topology, restart, hidden);
let building = self.building.as_mut().expect("the encoder is open");
building.push_draw(&self.core, command, &self.batch_bytes[..self.push.len()]);
self.core.device.cmd_draw_indirect(
command,
placed.buffer,
placed.offset + table_len as u64,
count as u32,
ROW as u32,
);
}
let building = self.building.as_mut().expect("the encoder is open");
building.count(Metric::MultiDrawCalls);
building.count_by(Metric::MultiDrawItems, count as u64);
if self.facts.levels {
building.count_by(Metric::LevelFieldCommands, count as u64);
}
self.record_multi_draw(placed.buffer, placed.offset + table_len as u64, count);
// Keep the ordinary CPU push current. Building still holds the table push and variant.
let Bound::Buffer { offset, .. } = &mut self.tables[VERTEX].buffers[slot as usize] else {
@@ -2817,25 +2818,8 @@ impl RenderCommandEncoder {
if let Some(at) = fields.bounds {
self.push[at..at + 4].copy_from_slice(&table.bounds(slot)[..4]);
}
Ok(head_done + count)
}
/// Records a batch from the command buffer's retained ring allocation.
fn record_multi_draw(&mut self, buffer: vk::Buffer, offset: u64, count: usize) {
// SAFETY: the callers established rendering and bound the pipeline, validated the count
// against the device's limit, and uploaded count indirect commands to the retained ring.
unsafe {
self.core
.device
.cmd_draw_indirect(self.command, buffer, offset, count as u32, 16);
}
let building = self.building.as_mut().expect("the encoder is open");
building.count(Metric::MultiDrawCalls);
building.count_by(Metric::MultiDrawItems, count as u64);
if self.facts.levels {
building.count_by(Metric::LevelFieldCommands, count as u64);
}
(self.drew, self.pass_drew) = (true, true);
Ok(head_done + count)
}
fn table_draw_facts_ready(&self) -> bool {
@@ -299,7 +299,7 @@ fn multi_draw_order_bounds_and_state_match_each_pixel() {
}
#[test]
fn fixed_offset_multi_draw_uses_the_ordinary_pipeline() {
fn fixed_offset_draw_batch_uses_the_ordinary_pipeline() {
each_device_with("fixed_offset_multi_draw", options, |name, _, device| {
let [constant, _] = pipelines(name, &device);
let mut buffers = Buffers::new(&device);
@@ -354,14 +354,9 @@ fn fixed_offset_multi_draw_uses_the_ordinary_pipeline() {
after.pipelines_created, before.pipelines_created,
"{name}: the cached ordinary pipeline"
);
assert_eq!(
after.multi_draw_calls - before.multi_draw_calls,
u64::from(expected_tail > 0)
);
assert_eq!(
after.multi_draw_items - before.multi_draw_items,
expected_tail as u64
);
assert_eq!(after.multi_draw_calls, before.multi_draw_calls);
assert_eq!(after.multi_draw_items, before.multi_draw_items);
assert_eq!(after.ring_writes, before.ring_writes);
});
}