From 646c30c538f32355f2cdfd4ef4a48e8bc2d42fe1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:50:33 +0800 Subject: [PATCH] :racehorse: Encode Vulkan vertex draws in batches (cherry picked from commit e26f05db2da74159dd54aaefebc61350d083cd3b) --- crates/reims-vgpu-vulkan/src/recorder.rs | 145 +++++ .../src/rt_platform/render.rs | 519 +++++++++++++++++- 2 files changed, 636 insertions(+), 28 deletions(-) diff --git a/crates/reims-vgpu-vulkan/src/recorder.rs b/crates/reims-vgpu-vulkan/src/recorder.rs index 4fa17d131..004d1e5c0 100644 --- a/crates/reims-vgpu-vulkan/src/recorder.rs +++ b/crates/reims-vgpu-vulkan/src/recorder.rs @@ -4570,6 +4570,151 @@ mod tests { (platform, device) } + /// A draw batch records the original Metal calls in order, including each new buffer offset. + #[test] + fn on_vulkan_draw_batches_record_each_bind_and_draw() { + use crate::core::platform::Platform as _; + use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _, WorkNames}; + use crate::core::platform::descriptor::RenderPassDescriptor as _; + use crate::core::platform::device::GpuDevice as _; + use crate::core::platform::render::{RenderCmd, RenderEncoder as _, VertexDraw}; + use crate::core::platform::resource::Library as _; + use crate::core::platform::values::{ + ColorAttachmentDesc, ColorAttachmentSet, FullRenderPipelineDesc, TextureDesc, + }; + use crate::core::raise::OnFault; + + in_recording_child( + "recorder::tests::on_vulkan_draw_batches_record_each_bind_and_draw", + |streams| { + let run = || -> Result<(), &'static str> { + let (platform, device) = recording_device(); + let on = OnFault::Return; + let function = |bytes: &[u8], name| { + let Ok(Ok(Some(library))) = device.new_library(bytes) else { + return Err("no library"); + }; + library + .new_function(on, name) + .ok() + .flatten() + .ok_or("no function") + }; + let vertex = function( + include_bytes!("../../../tests/shaders/vert.metallib"), + "tri_vert", + )?; + let fragment = function( + include_bytes!("../../../tests/shaders/frag.metallib"), + "tri_frag", + )?; + let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment)); + desc.colors = vec![( + 0, + ColorAttachmentDesc { + pixel_format: 80, + ..ColorAttachmentDesc::default() + }, + )]; + let Ok(Some(pipeline)) = device.new_render_pipeline_state_full(&desc) else { + return Err("no pipeline"); + }; + let Ok(Some(buffer)) = device.new_buffer_of_length(on, 256, 0) else { + return Err("no vertex buffer"); + }; + let Ok(Some(target)) = device.new_texture( + on, + &platform.texture_descriptor(&TextureDesc { + pixel_format: 80, + width: 4, + height: 4, + usage: 4, + ..TextureDesc::default() + }), + ) else { + return Err("no render target"); + }; + let queue = device.new_command_queue().ok_or("no queue")?; + let Ok(Some(cb)) = queue.command_buffer(on) else { + return Err("no command buffer"); + }; + cb.names_work(&std::sync::Arc::new(WorkNames::new(1))); + let pass = platform.render_pass_descriptor(); + assert_eq!( + pass.set_color_attachment( + on, + 0, + &ColorAttachmentSet { + texture: Some(Some(&target)), + load_action: Some(2), + store_action: Some(1), + ..ColorAttachmentSet::default() + } + ), + Ok(()) + ); + let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else { + return Err("no render encoder"); + }; + assert_eq!( + encoder.encode( + on, + RenderCmd::SetRenderPipelineState { + pipeline_state: Some(&pipeline), + } + ), + Ok(()) + ); + let draw = VertexDraw { + buffer: Some(&buffer), + offset: 0, + index: 0, + primitive_type: 3, + vertex_start: 0, + vertex_count: 3, + }; + let draws = [draw, VertexDraw { offset: 16, ..draw }]; + assert_eq!(encoder.encode_draws(on, &draws), Ok(())); + assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(())); + + let receiver = id_at(encoder.rec_ptr()).ok_or("no encoder stream id")?; + let buffer = id_at(buffer.rec_ptr()).ok_or("no buffer stream id")?; + let (calls, _) = recorded(streams, |calls| { + calls + .iter() + .any(|c| c.receiver == receiver && c.selector == "endEncoding") + }); + let selectors_and_args: Vec<_> = calls + .iter() + .filter(|c| c.receiver == receiver) + .map(|c| (c.selector.as_str(), c.args.as_slice())) + .collect(); + assert_eq!(selectors_and_args.len(), 6, "{calls:?}"); + let bind = + |offset| [Value::Object(buffer), Value::Uint(offset), Value::Uint(0)]; + let primitives = [Value::Uint(3), Value::Uint(0), Value::Uint(3)]; + assert_eq!( + selectors_and_args[1..5], + [ + ("setVertexBuffer:offset:atIndex:", bind(0).as_slice()), + ( + "drawPrimitives:vertexStart:vertexCount:", + primitives.as_slice() + ), + ("setVertexBuffer:offset:atIndex:", bind(16).as_slice()), + ( + "drawPrimitives:vertexStart:vertexCount:", + primitives.as_slice() + ), + ] + ); + Ok(()) + }; + assert_eq!(run(), Ok(())); + }, + ); + } + /// A stream starts with the device's making and then its identity, rt's `deviceName` and /// `hasUnifiedMemory`, before any call on the device. #[test] diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/render.rs b/crates/reims-vgpu-vulkan/src/rt_platform/render.rs index 279641956..8680971cf 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/render.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/render.rs @@ -109,7 +109,7 @@ use metal2vulkan::metal::{ }; use metal2vulkan_runtime as rt; -use crate::core::platform::render::{RenderCmd, RenderEncoder}; +use crate::core::platform::render::{RenderCmd, RenderEncoder, VertexDraw, encode_each}; use crate::core::platform::types::{MtlScissorRect, MtlViewport}; use crate::core::platform::{Handle, ObjId}; use crate::core::raise::{OnFault, RaiseResult}; @@ -123,7 +123,7 @@ use super::diag::{self, Bound, Point, Target, Use}; use super::fault::{EncoderKind, EncoderNames, Naming}; use super::render_pipeline::{Formats, Raster, RtRenderPipeline}; use super::texture::RtTexture; -use super::unbuilt::{Unbuilt, naming_functions, refuse}; +use super::unbuilt::{Named, Unbuilt, naming_functions, refuse}; use super::{RtBuffer, RtObj, RtPlatform}; /// A count, a base or an index past rt's 32 bits. @@ -250,6 +250,40 @@ impl RtRenderEncoder { } } + /// Records a draw gap's details and returns the functions to name when reporting the refusal. + #[cold] + fn refusal_functions( + &self, + seen: &Seen, + sel: &'static str, + stopped: &Stop, + draw: bool, + primitive: Option, + viewports: Option>, + ) -> Named { + let functions = match (stopped, &seen.state) { + (Stop::Rt(_) | Stop::Unbuilt(_), Some(state)) if draw => state.functions(), + _ => Vec::new(), + }; + if let Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind })) = stopped { + let what = DrawDetail { + primitive, + raster: seen.state.as_ref().map(|state| state.raster()), + formats: (*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(seen)), + viewports, + }; + naming_functions(functions.clone(), || { + super::unbuilt::refusal_detail(sel, error, Some(&what)); + }); + match kind { + rt::DrawKind::AttachmentRead => self.attachment_read(seen), + rt::DrawKind::FetchedAttachment => self.fetched_attachment(seen), + _ => {} + } + } + functions + } + /// Encodes `cmd` but `endEncoding`, which the caller ends. fn command(&self, open: &mut Open, cmd: RenderCmd<'_, RtPlatform>) -> Result<(), Stop> { let Open { @@ -268,8 +302,7 @@ impl RtRenderEncoder { vertex_count, } => { set(*pipeline)?; - let (start, count) = (small(vertex_start)?, small(vertex_count)?); - e.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?; + draw_primitives(e, primitive_type, vertex_start, vertex_count)?; } RenderCmd::DrawPrimitivesInstances { primitive_type, @@ -688,6 +721,18 @@ fn set(pipeline: Option) -> Result<(), Stop> { } } +/// The short draw form, after checking that a pipeline is bound. +fn draw_primitives( + encoder: &mut rt::RenderCommandEncoder, + primitive_type: u64, + vertex_start: u64, + vertex_count: u64, +) -> Result<(), Stop> { + let (start, count) = (small(vertex_start)?, small(vertex_count)?); + encoder.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?; + Ok(()) +} + /// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise. fn unbuilt_unless(at_default: bool) -> Result<(), Stop> { match at_default { @@ -1104,30 +1149,9 @@ impl RenderEncoder for RtObj { note_names(names, &cmd); } let stopped = self.command(&mut open, cmd).err(); - let functions = match (&stopped, &open.seen.state) { - (Some(Stop::Rt(_) | Stop::Unbuilt(_)), Some(state)) if draw => state.functions(), - _ => Vec::new(), - }; - if let Some(Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind }))) = &stopped - { - let raster = open.seen.state.as_ref().map(|state| state.raster()); - let formats = - (*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(&open.seen)); - let what = DrawDetail { - primitive, - raster, - formats, - viewports, - }; - naming_functions(functions.clone(), || { - super::unbuilt::refusal_detail(sel, error, Some(&what)); - }); - match kind { - rt::DrawKind::AttachmentRead => self.attachment_read(&open.seen), - rt::DrawKind::FetchedAttachment => self.fetched_attachment(&open.seen), - _ => {} - } - } + let functions = stopped.as_ref().map_or_else(Vec::new, |stop| { + self.refusal_functions(&open.seen, sel, stop, draw, primitive, viewports) + }); let icb_gap = |error: &rt::Error| { matches!( error, @@ -1153,6 +1177,69 @@ impl RenderEncoder for RtObj { recorded_answer } + fn encode_draws(&self, on: OnFault, draws: &[VertexDraw<'_, RtPlatform>]) -> RaiseResult<()> { + if draws.is_empty() { + return Ok(()); + } + if crate::recorder::on() || super::copied::any() { + return encode_each(self, on, draws); + } + let held = self.open.lock(); + let mut open = held.borrow_mut(); + let Open { + rt, + pipeline, + seen, + naming, + } = &mut *open; + let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else { + drop(open); + drop(held); + return encode_each(self, on, draws); + }; + let mut last = None; + let mut buffer = None; + for (i, draw) in draws.iter().enumerate() { + if let Some(bound) = draw.buffer { + names.bound_buffers.add_named(bound.named()); + } + let key = draw.buffer.map(std::ptr::from_ref); + if key != last { + last = key; + buffer = draw.buffer.map(|b| b.rt()); + } + let bound = small(draw.index).and_then(|index| { + encoder + .set_vertex_buffer(buffer, draw.offset, index) + .map_err(Stop::from) + }); + // A refusal is reported once. After a refused bind, the draw still sees the + // encoder's existing binding, and only commands that have yet to run go to encode. + if let Err(stop) = bound { + drop(open); + drop(held); + report(draw.vertex_buffer().selector(), Some(stop)); + self.encode(on, draw.primitives())?; + return encode_each(self, on, &draws[i + 1..]); + } + if let Err(stop) = draw_primitives( + encoder, + draw.primitive_type, + draw.vertex_start, + draw.vertex_count, + ) { + let sel = draw.primitives().selector(); + let functions = + self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None); + drop(open); + drop(held); + naming_functions(functions, || report(sel, Some(stop))); + return encode_each(self, on, &draws[i + 1..]); + } + } + Ok(()) + } + /// Holds the encoder for `run` ([`RtRenderEncoder`]'s `open`): the commands `run` sends take /// its lock again on this thread, and another thread's wait for it to end. fn encoding(&self, run: impl FnOnce() -> T) -> T { @@ -1515,6 +1602,382 @@ mod tests { words.iter().flat_map(|w| w.to_le_bytes()).collect() } + /// Each draw, including the draw after a refused bind, uses the binding it would see + /// alone. The visibility result counts the draws even when a later one covers their pixels. + #[test] + fn draw_batches_match_individual_commands_on_vulkan() -> Result<(), &'static str> { + check_draw_batch(DrawBatchCase::Existing) + } + + #[test] + fn draw_batches_clear_and_rebind_a_vertex_buffer_on_vulkan() -> Result<(), &'static str> { + check_draw_batch(DrawBatchCase::Unbind) + } + + #[test] + fn draw_batches_report_a_gap_and_continue_on_vulkan() -> Result<(), &'static str> { + check_draw_batch(DrawBatchCase::Gap) + } + + #[test] + fn draw_batches_record_bound_buffer_names_on_vulkan() -> Result<(), &'static str> { + check_draw_batch(DrawBatchCase::Names) + } + + #[derive(PartialEq, Eq)] + enum DrawBatchCase { + Existing, + Unbind, + Gap, + Names, + } + + fn check_draw_batch(case: DrawBatchCase) -> Result<(), &'static str> { + use crate::core::platform::command::WorkNames; + use crate::rt_platform::fault::{Ids, Operands, name_buffer}; + use std::sync::Arc; + + let platform = RtPlatform::new(); + let device = platform.system_default_device().ok_or("no Vulkan device")?; + let queue = device.new_command_queue().ok_or("no command queue")?; + let state = vdesc_state(&device, &function(&device, COLOR, "render_color")); + let (red, green, cyan, blue) = ( + [255, 0, 0, 255], + [0, 255, 0, 255], + [0, 255, 255, 255], + [0, 0, 255, 255], + ); + let a = shared(&device, &vertices(&[green, cyan])); + let b = shared(&device, &vertices(&[blue])); + name_buffer(&a, 7); + let results = shared(&device, &[0; 8]); + let on = OnFault::Return; + let Ok(Some(target)) = device.new_texture( + on, + &platform.texture_descriptor(&TextureDesc { + width: 4, + height: 4, + usage: 5, + ..TextureDesc::default() + }), + ) else { + return Err("no render target"); + }; + let pass = pass(&target, 2); + pass.set_pass(&PassSet { + visibility_result_buffer: Some(Some(&results)), + ..PassSet::default() + }); + let draw_a = VertexDraw { + buffer: Some(&a), + offset: 0, + index: 0, + primitive_type: TRIANGLE, + vertex_start: 0, + vertex_count: 3, + }; + let next_a = VertexDraw { + offset: 36, + ..draw_a + }; + let draw_b = VertexDraw { + buffer: Some(&b), + ..draw_a + }; + let bad_bind = VertexDraw { + index: 31, + ..draw_b + }; + let bad_draw = VertexDraw { + primitive_type: u64::MAX, + ..draw_b + }; + let codes = [RtRefusal::Refused, RtRefusal::Ours, RtRefusal::Gap].map(RtRefusal::code); + let render = |draws: &[VertexDraw<'_, RtPlatform>], + batch, + operands: bool, + no_pipeline: bool, + ended| { + let Ok(Some(cb)) = queue.command_buffer(on) else { + return Err("no command buffer"); + }; + if !operands { + cb.names_work(&Arc::new(WorkNames::new(1))); + } + let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else { + return Err("no render encoder"); + }; + if !no_pipeline { + assert_eq!( + encoder.encode( + on, + RenderCmd::SetRenderPipelineState { + pipeline_state: Some(&state), + }, + ), + Ok(()) + ); + } + assert_eq!( + encoder.encode( + on, + RenderCmd::SetVisibilityResultMode { mode: 2, offset: 0 } + ), + Ok(()) + ); + if case == DrawBatchCase::Gap { + // Triangles still draw; the line in the middle hits rt's DrawKind::LineWidth. + encoder + .open + .lock() + .borrow_mut() + .rt + .as_mut() + .ok_or("no rt encoder")? + .set_line_width(2.0); + } + if ended { + assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(())); + } + let before = codes.map(counted); + let answer = if batch { + encoder.encode_draws(on, draws) + } else { + encode_each(&encoder, on, draws) + }; + assert_eq!(answer, Ok(())); + let refused = std::array::from_fn(|i| counted(codes[i]) - before[i]); + let names = encoder.open.lock().borrow_mut().naming.names().cloned(); + if let Some(names) = &names { + assert_eq!(names.operands, operands.then(Operands::default)); + } + if !ended { + assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(())); + } + assert_eq!(cb.commit(on), Ok(())); + assert_eq!(cb.wait_until_completed(on), Ok(())); + assert_eq!(cb.status(), CommandBufferStatus::COMPLETED); + let mut pixels = [0; 64]; + target.read_pixels(&mut pixels, 16); + // SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished. + let samples = + u64::from_le_bytes(unsafe { results.contents().as_ptr::<[u8; 8]>().read() }); + Ok(( + pixels, + samples, + refused, + names.map(|names| names.bound_buffers), + )) + }; + + if case != DrawBatchCase::Existing { + let (draws, colour, samples, refused) = match case { + DrawBatchCase::Unbind => ( + vec![ + draw_a, + VertexDraw { + buffer: None, + ..draw_a + }, + next_a, + ], + cyan, + 32, + [0, 1, 0], + ), + DrawBatchCase::Gap => ( + vec![ + draw_a, + VertexDraw { + primitive_type: 1, + vertex_count: 2, + ..draw_b + }, + next_a, + ], + cyan, + 32, + [0, 0, 1], + ), + DrawBatchCase::Names => (vec![draw_a, next_a, draw_b, draw_b], blue, 64, [0, 0, 0]), + DrawBatchCase::Existing => unreachable!("handled by the cases below"), + }; + let batch = render(&draws, true, true, false, false)?; + assert_eq!(batch, render(&draws, false, true, false, false)?); + let mut bound = Ids::default(); + bound.add(7); + match case { + DrawBatchCase::Gap => bound.add(0), + DrawBatchCase::Names => { + bound.add(0); + bound.add(0); + } + _ => {} + } + assert_eq!( + batch, + ( + std::array::from_fn(|i| colour[i % 4]), + samples, + refused, + Some(bound) + ) + ); + return Ok(()); + } + + for (draws, operands, no_pipeline, ended, colour, samples, refusals) in [ + (&[][..], false, false, false, red, 0, 0), + (&[draw_a, next_a][..], false, false, false, cyan, 32, 0), + ( + &[draw_a, next_a, draw_b][..], + false, + false, + false, + blue, + 48, + 0, + ), + ( + &[draw_a, next_a, draw_b][..], + true, + false, + false, + blue, + 48, + 0, + ), + (&[draw_a, bad_bind][..], false, false, false, green, 32, 1), + ( + &[draw_a, bad_bind, next_a][..], + false, + false, + false, + cyan, + 48, + 1, + ), + ( + &[draw_a, bad_draw, bad_bind][..], + false, + false, + false, + blue, + 32, + 2, + ), + (&[draw_a, draw_b][..], false, true, false, red, 0, 2), + (&[draw_a, draw_b][..], false, false, true, red, 0, 4), + (&[][..], false, false, true, red, 0, 0), + ] { + let batch = render(draws, true, operands, no_pipeline, ended)?; + assert_eq!(batch, render(draws, false, operands, no_pipeline, ended)?); + assert_eq!( + (batch.0, batch.1, batch.2[0]), + (std::array::from_fn(|i| colour[i % 4]), samples, refusals) + ); + } + Ok(()) + } + + #[test] + fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> { + use crate::core::host::HostPtr; + use crate::core::num::ToUsize as _; + use crate::core::platform::HostRange; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + + let platform = RtPlatform::new(); + let device = platform.system_default_device().ok_or("no Vulkan device")?; + let queue = device.new_command_queue().ok_or("no command queue")?; + let on = OnFault::Return; + let page = device.facts().page_size; + let layout = + Layout::from_size_align(page.to_usize(), page.to_usize()).map_err(|_| "page layout")?; + // SAFETY: the page layout has nonzero size. + let memory = HostPtr::from_ptr(unsafe { alloc_zeroed(layout) }); + if memory == HostPtr::from_ptr(std::ptr::null_mut::()) { + return Err("page allocation"); + } + // SAFETY: the page lives until the buffer's deallocator runs. + let bytes = unsafe { HostRange::new(memory, page) }; + let buffer = device + .new_buffer_over_host_memory( + on, + bytes, + super::super::buffer::READ_ONLY, + // SAFETY: this frees the page once the copy and its users let it go. + Some(Box::new(move || unsafe { + dealloc(memory.as_ptr(), layout) + })), + ) + .map_err(|_| "buffer creation raised")? + .ok_or("no copied buffer")?; + assert!(buffer.copied().is_some()); + assert!(super::super::copied::any()); + let green = [0, 255, 0, 255]; + let data = vertices(&[green]); + // SAFETY: the vertices fit in the mapped page, and the copy was already initialized. + unsafe { + memory + .as_ptr::() + .copy_from_nonoverlapping(data.as_ptr(), data.len()) + }; + let state = vdesc_state(&device, &function(&device, COLOR, "render_color")); + let target = device + .new_texture( + on, + &platform.texture_descriptor(&TextureDesc { + width: 4, + height: 4, + usage: 5, + ..TextureDesc::default() + }), + ) + .map_err(|_| "texture creation raised")? + .ok_or("no render target")?; + let pass = pass(&target, 2); + let commands = queue + .command_buffer(on) + .map_err(|_| "command buffer raised")? + .ok_or("no command buffer")?; + let encoder = commands + .render_encoder(on, &pass) + .map_err(|_| "render encoder raised")? + .ok_or("no render encoder")?; + assert_eq!( + encoder.encode( + on, + RenderCmd::SetRenderPipelineState { + pipeline_state: Some(&state) + } + ), + Ok(()) + ); + assert_eq!( + encoder.encode_draws( + on, + &[VertexDraw { + buffer: Some(&buffer), + offset: 0, + index: 0, + primitive_type: TRIANGLE, + vertex_start: 0, + vertex_count: 3, + }] + ), + Ok(()) + ); + assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(())); + assert_eq!(commands.commit(on), Ok(())); + assert_eq!(commands.wait_until_completed(on), Ok(())); + assert_eq!(commands.status(), CommandBufferStatus::COMPLETED); + let mut pixels = [0; 64]; + target.read_pixels(&mut pixels, 16); + assert_eq!(pixels, std::array::from_fn(|i| green[i % 4])); + Ok(()) + } + /// A run of `encoding` holds the encoder: the run's own commands go through and draw, and a /// command another thread sends meanwhile waits for the run to end, then goes through. #[test]