From 53c2d15e0bc2b5ce44c0e68b70f360037ee0e7bd Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Fri, 14 Feb 2025 12:50:32 +0100 Subject: [PATCH] implement indirect draw validation --- Cargo.lock | 1 + tests/gpu-tests/draw_indirect.rs | 542 +++++++++++ tests/gpu-tests/root.rs | 1 + wgpu-core/Cargo.toml | 1 + wgpu-core/src/command/bundle.rs | 67 +- wgpu-core/src/command/mod.rs | 14 + wgpu-core/src/command/render.rs | 162 +++- wgpu-core/src/command/render_command.rs | 8 + wgpu-core/src/device/queue.rs | 12 + wgpu-core/src/device/resource.rs | 65 ++ wgpu-core/src/indirect_draw_validation.rs | 996 ++++++++++++++++++++ wgpu-core/src/indirect_draw_validation.wgsl | 82 ++ wgpu-core/src/lib.rs | 2 + wgpu-core/src/lock/observing.rs | 5 + wgpu-core/src/lock/rank.rs | 2 + wgpu-core/src/lock/vanilla.rs | 5 + wgpu-core/src/resource.rs | 24 + 17 files changed, 1945 insertions(+), 44 deletions(-) create mode 100644 tests/gpu-tests/draw_indirect.rs create mode 100644 wgpu-core/src/indirect_draw_validation.rs create mode 100644 wgpu-core/src/indirect_draw_validation.wgsl diff --git a/Cargo.lock b/Cargo.lock index 59ff788ed..917a5e2ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4649,6 +4649,7 @@ name = "wgpu-core" version = "24.0.0" dependencies = [ "arrayvec", + "bit-set 0.8.0", "bit-vec 0.8.0", "bitflags 2.9.0", "bytemuck", diff --git a/tests/gpu-tests/draw_indirect.rs b/tests/gpu-tests/draw_indirect.rs new file mode 100644 index 000000000..bf4ed52f4 --- /dev/null +++ b/tests/gpu-tests/draw_indirect.rs @@ -0,0 +1,542 @@ +use wgpu::{ + util::{BufferInitDescriptor, DeviceExt}, + vertex_attr_array, +}; +use wgpu_test::{gpu_test, GpuTestConfiguration, TestParameters, TestingContext}; + +struct TestData { + kind: Kind, + instanced: Option, +} + +struct Instanced { + instance_buffer_content: &'static [f32], + + first_instance: u32, + instance_count: u32, +} + +enum Kind { + NonIndexed { + vertex_buffer_content: &'static [f32], + + first_vertex: u32, + vertex_count: u32, + }, + Indexed { + vertex_buffer_content: &'static [f32], + + index_buffer_content: &'static [u32], + + first_index: u32, + index_count: u32, + }, +} + +impl TestData { + fn vertex_buffer_content(&self) -> &'static [f32] { + match self.kind { + Kind::NonIndexed { + vertex_buffer_content, + .. + } => vertex_buffer_content, + Kind::Indexed { + vertex_buffer_content, + .. + } => vertex_buffer_content, + } + } + + fn write_indirect_args(&self, buf: &mut Vec) { + let (first_instance, instance_count) = match self.instanced { + Some(ref instanced) => (instanced.first_instance, instanced.instance_count), + None => (0, 1), + }; + match self.kind { + Kind::NonIndexed { + first_vertex, + vertex_count, + .. + } => { + buf.extend_from_slice( + wgpu::util::DrawIndirectArgs { + vertex_count, + instance_count, + first_vertex, + first_instance, + } + .as_bytes(), + ); + } + Kind::Indexed { + first_index, + index_count, + .. + } => { + buf.extend_from_slice( + wgpu::util::DrawIndexedIndirectArgs { + index_count, + instance_count, + first_index, + base_vertex: 0, + first_instance, + } + .as_bytes(), + ); + } + } + } +} + +async fn run_test(ctx: TestingContext, test_data: TestData, expect_noop: bool) { + let mut vertex_buffer_layouts = Vec::new(); + vertex_buffer_layouts.push(wgpu::VertexBufferLayout { + array_stride: 8, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &vertex_attr_array![0 => Float32x2], + }); + let vertex_buffer = ctx.device.create_buffer_init(&BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(test_data.vertex_buffer_content()), + usage: wgpu::BufferUsages::VERTEX, + }); + + let index_buffer = match test_data.kind { + Kind::NonIndexed { .. } => None, + Kind::Indexed { + index_buffer_content, + .. + } => Some(ctx.device.create_buffer_init(&BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(index_buffer_content), + usage: wgpu::BufferUsages::INDEX, + })), + }; + + let instance_buffer = test_data.instanced.as_ref().map(|instanced| { + vertex_buffer_layouts.push(wgpu::VertexBufferLayout { + array_stride: 8, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &vertex_attr_array![1 => Float32x2], + }); + ctx.device.create_buffer_init(&BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(instanced.instance_buffer_content), + usage: wgpu::BufferUsages::VERTEX, + }) + }); + + let shader_src = if instance_buffer.is_none() { + " + @vertex + fn vs_main(@location(0) position: vec2f) -> @builtin(position) vec4f { + return vec4f(position, 0.0, 1.0); + } + + @fragment + fn fs_main() -> @location(0) vec4f { + return vec4f(1.0); + } + " + } else { + " + @vertex + fn vs_main(@location(0) position: vec2f, @location(1) position_offset: vec2f) -> @builtin(position) vec4f { + return vec4f(position + position_offset, 0.0, 1.0); + } + + @fragment + fn fs_main() -> @location(0) vec4f { + return vec4f(1.0); + } + " + }; + + let shader = ctx + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(shader_src.into()), + }); + + let pipeline_desc = wgpu::RenderPipelineDescriptor { + label: None, + layout: None, + vertex: wgpu::VertexState { + buffers: &vertex_buffer_layouts, + module: &shader, + entry_point: Some("vs_main"), + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::R8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview: None, + cache: None, + }; + let pipeline = ctx.device.create_render_pipeline(&pipeline_desc); + + let out_texture = ctx.device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 256, + height: 256, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let out_texture_view = out_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + let readback_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 * 256, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + + // Use 2 passes to trigger internal validation buffer reuse + let passes = 2; + // Issue 2 draws per indirect buffer to trigger internal validation batching + let draws = 2; // try 66000 to test multiple temporary validation buffers + + let mut indirect_bytes = Vec::new(); + for _ in 0..passes * draws { + test_data.write_indirect_args(&mut indirect_bytes); + } + let indirect_buffer = ctx.device.create_buffer_init(&BufferInitDescriptor { + label: None, + contents: &indirect_bytes, + usage: wgpu::BufferUsages::INDIRECT, + }); + // Use a secondary indirect buffer to test multiple validation batches. + let indirect_buffer2 = ctx.device.create_buffer_init(&BufferInitDescriptor { + label: None, + contents: &indirect_bytes, + usage: wgpu::BufferUsages::INDIRECT, + }); + + let mut encoder = ctx + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + + for pass_index in 0..passes { + let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + ops: wgpu::Operations::default(), + resolve_target: None, + view: &out_texture_view, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + }); + + rpass.set_pipeline(&pipeline); + rpass.set_vertex_buffer(0, vertex_buffer.slice(..)); + if let Some(ref instance_buffer) = instance_buffer { + rpass.set_vertex_buffer(1, instance_buffer.slice(..)); + } + if let Some(ref index_buffer) = index_buffer { + rpass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint32); + } + for draw_index in 0..draws { + if index_buffer.is_some() { + let offset = pass_index * draw_index * 20; + rpass.draw_indexed_indirect(&indirect_buffer, offset); + rpass.draw_indexed_indirect(&indirect_buffer2, offset); + } else { + let offset = pass_index * draw_index * 20; + rpass.draw_indirect(&indirect_buffer, offset); + rpass.draw_indirect(&indirect_buffer2, offset); + } + } + } + + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture: &out_texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &readback_buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(256), + rows_per_image: None, + }, + }, + wgpu::Extent3d { + width: 256, + height: 256, + depth_or_array_layers: 1, + }, + ); + + ctx.queue.submit([encoder.finish()]); + + let slice = readback_buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| ()); + + ctx.async_poll(wgpu::PollType::wait()).await.unwrap(); + + let data = slice.get_mapped_range(); + let succeeded = if expect_noop { + data.iter().all(|b| *b == 0) + } else { + data.iter().all(|b| *b == u8::MAX) + }; + assert!(succeeded); +} + +macro_rules! make_test { + ($name:ident, $test_data:expr) => { + make_test!($name, $test_data, false, wgpu::Features::empty()); + }; + ($name:ident, $test_data:expr, $features:expr) => { + make_test!($name, $test_data, false, $features); + }; + ($name:ident, $test_data:expr, $expect_noop:expr, $features:expr) => { + #[gpu_test] + static $name: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .downlevel_flags(wgpu::DownlevelFlags::INDIRECT_EXECUTION) + .features($features) + .limits(wgpu::Limits::downlevel_defaults()), + ) + .run_async(|ctx| run_test(ctx, $test_data, $expect_noop)); + }; +} +macro_rules! make_failing_test { + ($name:ident, $test_data:expr) => { + make_test!($name, $test_data, true, wgpu::Features::empty()); + }; + ($name:ident, $test_data:expr, $features:expr) => { + make_test!($name, $test_data, true, $features); + }; +} + +fn get_draw_test_data(first_vertex: u32, vertex_count: u32) -> TestData { + let vertex_buffer_content = &[ + // Triangle 1 + -1.0, -1.0, // Bottom left + 1.0, 1.0, // Top right + -1.0, 1.0, // Top left + // Triangle 2 + -1.0, -1.0, // Bottom left + 1.0, -1.0, // Bottom right + 1.0, 1.0, // Top right + ]; + TestData { + kind: Kind::NonIndexed { + vertex_buffer_content, + first_vertex, + vertex_count, + }, + instanced: None, + } +} + +make_test!(DRAW, get_draw_test_data(0, 6)); +make_failing_test!(DRAW_OOB_START, get_draw_test_data(1, 6)); +make_failing_test!(DRAW_OOB_COUNT, get_draw_test_data(0, 7)); + +fn get_instanced_draw_test_data( + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, +) -> TestData { + let vertex_buffer_content = &[ + // Triangle 1 + -0.5, -0.5, // Bottom left + 0.5, 0.5, // Top right + -0.5, 0.5, // Top left + // Triangle 2 + -0.5, -0.5, // Bottom left + 0.5, -0.5, // Bottom right + 0.5, 0.5, // Top right + ]; + let instance_buffer_content = &[ + -0.5, -0.5, // Move quad to bottom left + 0.5, 0.5, // Move quad to top right + -0.5, 0.5, // Move quad to top left + 0.5, -0.5, // Move quad to bottom right + ]; + TestData { + kind: Kind::NonIndexed { + vertex_buffer_content, + first_vertex, + vertex_count, + }, + instanced: Some(Instanced { + instance_buffer_content, + first_instance, + instance_count, + }), + } +} + +make_test!(INSTANCED_DRAW, get_instanced_draw_test_data(0, 6, 0, 4)); +make_failing_test!( + INSTANCED_DRAW_OOB_START, + get_instanced_draw_test_data(1, 6, 0, 4) +); +make_failing_test!( + INSTANCED_DRAW_OOB_COUNT, + get_instanced_draw_test_data(0, 7, 0, 4) +); +make_failing_test!( + INSTANCED_DRAW_OOB_INSTANCE_START, + get_instanced_draw_test_data(0, 6, 1, 4), + wgpu::Features::INDIRECT_FIRST_INSTANCE +); +make_failing_test!( + INSTANCED_DRAW_OOB_INSTANCE_COUNT, + get_instanced_draw_test_data(0, 6, 0, 5) +); + +fn get_instanced_draw_with_non_zero_first_instance_test_data() -> TestData { + let vertex_buffer_content = &[ + // Triangle 1 + -0.5, -0.5, // Bottom left + 0.5, 0.5, // Top right + -0.5, 0.5, // Top left + // Triangle 2 + -0.5, -0.5, // Bottom left + 0.5, -0.5, // Bottom right + 0.5, 0.5, // Top right + ]; + let instance_buffer_content = &[ + 10.0, 10.0, // unused + -0.5, -0.5, // Move quad to bottom left + 0.5, 0.5, // Move quad to top right + -0.5, 0.5, // Move quad to top left + 0.5, -0.5, // Move quad to bottom right + ]; + TestData { + kind: Kind::NonIndexed { + vertex_buffer_content, + first_vertex: 0, + vertex_count: 6, + }, + instanced: Some(Instanced { + instance_buffer_content, + first_instance: 1, + instance_count: 4, + }), + } +} + +make_test!( + INSTANCED_DRAW_WITH_NON_ZERO_FIRST_INSTANCE, + get_instanced_draw_with_non_zero_first_instance_test_data(), + wgpu::Features::INDIRECT_FIRST_INSTANCE +); +make_failing_test!( + INSTANCED_DRAW_WITH_NON_ZERO_FIRST_INSTANCE_MISSING_FEATURE, + get_instanced_draw_with_non_zero_first_instance_test_data() +); + +fn get_indexed_draw_test_data(first_index: u32, index_count: u32) -> TestData { + let vertex_buffer_content = &[ + -1.0, -1.0, // Bottom left + 1.0, 1.0, // Top right + -1.0, 1.0, // Top left + 1.0, -1.0, // Bottom right + ]; + let index_buffer_content = &[ + 0, 1, 2, // Triangle 1 + 0, 3, 1, // Triangle 2 + ]; + TestData { + kind: Kind::Indexed { + vertex_buffer_content, + index_buffer_content, + first_index, + index_count, + }, + instanced: None, + } +} + +make_test!(INDEXED_DRAW, get_indexed_draw_test_data(0, 6)); +make_failing_test!(INDEXED_DRAW_OOB_START, get_indexed_draw_test_data(1, 6)); +make_failing_test!(INDEXED_DRAW_OOB_COUNT, get_indexed_draw_test_data(0, 7)); + +fn get_instanced_indexed_draw_test_data( + first_index: u32, + index_count: u32, + first_instance: u32, + instance_count: u32, +) -> TestData { + let vertex_buffer_content = &[ + -0.5, -0.5, // Bottom left + 0.5, 0.5, // Top right + -0.5, 0.5, // Top left + 0.5, -0.5, // Bottom right + ]; + let index_buffer_content = &[ + 0, 1, 2, // Triangle 1 + 0, 3, 1, // Triangle 2 + ]; + let instance_buffer_content = &[ + -0.5, -0.5, // Move quad to bottom left + 0.5, 0.5, // Move quad to top right + -0.5, 0.5, // Move quad to top left + 0.5, -0.5, // Move quad to bottom right + ]; + TestData { + kind: Kind::Indexed { + vertex_buffer_content, + index_buffer_content, + first_index, + index_count, + }, + instanced: Some(Instanced { + instance_buffer_content, + first_instance, + instance_count, + }), + } +} + +make_test!( + INSTANCED_INDEXED_DRAW, + get_instanced_indexed_draw_test_data(0, 6, 0, 4) +); +make_failing_test!( + INSTANCED_INDEXED_DRAW_OOB_START, + get_instanced_indexed_draw_test_data(1, 6, 0, 4) +); +make_failing_test!( + INSTANCED_INDEXED_DRAW_OOB_COUNT, + get_instanced_indexed_draw_test_data(0, 7, 0, 4) +); +make_failing_test!( + INSTANCED_INDEXED_DRAW_OOB_INSTANCE_START, + get_instanced_indexed_draw_test_data(0, 6, 1, 4), + wgpu::Features::INDIRECT_FIRST_INSTANCE +); +make_failing_test!( + INSTANCED_INDEXED_DRAW_OOB_INSTANCE_COUNT, + get_instanced_indexed_draw_test_data(0, 6, 0, 5) +); diff --git a/tests/gpu-tests/root.rs b/tests/gpu-tests/root.rs index f4f10fa83..6da76e406 100644 --- a/tests/gpu-tests/root.rs +++ b/tests/gpu-tests/root.rs @@ -24,6 +24,7 @@ mod compute_pass_ownership; mod create_surface_error; mod device; mod dispatch_workgroups_indirect; +mod draw_indirect; mod dual_source_blending; mod encoder; mod external_texture; diff --git a/wgpu-core/Cargo.toml b/wgpu-core/Cargo.toml index 59d6a7f08..fefa773bf 100644 --- a/wgpu-core/Cargo.toml +++ b/wgpu-core/Cargo.toml @@ -182,6 +182,7 @@ wgpu-types.workspace = true arrayvec.workspace = true bit-vec.workspace = true +bit-set.workspace = true bitflags.workspace = true bytemuck = { workspace = true, optional = true } document-features.workspace = true diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index e192c0b99..8de7b003b 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -784,29 +784,38 @@ fn multi_draw_indirect( let buffer = buffer_guard.get(buffer_id).get()?; - state - .trackers - .buffers - .merge_single(&buffer, wgt::BufferUses::INDIRECT)?; - buffer.same_device(&state.device)?; buffer.check_usage(wgt::BufferUsages::INDIRECT)?; + let vertex_limits = super::VertexLimits::new(state.vertex_buffer_sizes(), &pipeline.steps); + + let stride = super::get_stride_of_indirect_args(indexed); state .buffer_memory_init_actions .extend(buffer.initialization_status.read().create_action( &buffer, - offset..(offset + size_of::() as u64), + offset..(offset + stride), MemoryInitKind::NeedsInitializedMemory, )); - if indexed { + let vertex_or_index_limit = if indexed { let index = match state.index { Some(ref mut index) => index, None => return Err(DrawError::MissingIndexBuffer.into()), }; state.commands.extend(index.flush()); - } + index.limit() + } else { + vertex_limits.vertex_limit + }; + let instance_limit = vertex_limits.instance_limit; + + #[cfg(feature = "indirect-validation")] + let buffer_uses = wgt::BufferUses::STORAGE_READ_ONLY; + #[cfg(not(feature = "indirect-validation"))] + let buffer_uses = wgt::BufferUses::INDIRECT; + + state.trackers.buffers.merge_single(&buffer, buffer_uses)?; state.flush_vertices(); state.flush_binds(used_bind_groups, dynamic_offsets); @@ -815,6 +824,9 @@ fn multi_draw_indirect( offset, count: 1, indexed, + + vertex_or_index_limit, + instance_limit, }); Ok(()) } @@ -833,6 +845,8 @@ pub enum CreateRenderBundleError { #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum ExecutionError { + #[error(transparent)] + Device(#[from] DeviceError), #[error(transparent)] DestroyedResource(#[from] DestroyedResourceError), #[error("Using {0} in a render bundle is not implemented")] @@ -886,6 +900,10 @@ impl RenderBundle { pub(super) unsafe fn execute( &self, raw: &mut dyn hal::DynCommandEncoder, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: &mut crate::indirect_draw_validation::IndirectDrawValidationResources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_batcher: &mut crate::indirect_draw_validation::IndirectDrawValidationBatcher, snatch_guard: &SnatchGuard, ) -> Result<(), ExecutionError> { let mut offsets = self.base.dynamic_offsets.as_slice(); @@ -1028,19 +1046,28 @@ impl RenderBundle { buffer, offset, count: 1, - indexed: false, + indexed, + + vertex_or_index_limit: _vertex_or_index_limit, + instance_limit: _instance_limit, } => { - let buffer = buffer.try_raw(snatch_guard)?; - unsafe { raw.draw_indirect(buffer, *offset, 1) }; - } - Cmd::DrawIndirect { - buffer, - offset, - count: 1, - indexed: true, - } => { - let buffer = buffer.try_raw(snatch_guard)?; - unsafe { raw.draw_indexed_indirect(buffer, *offset, 1) }; + #[cfg(feature = "indirect-validation")] + let (buffer, offset) = indirect_draw_validation_batcher.add( + indirect_draw_validation_resources, + &self.device, + buffer.clone(), + *offset, + *indexed, + *_vertex_or_index_limit, + *_instance_limit, + )?; + #[cfg(not(feature = "indirect-validation"))] + let (buffer, offset) = (buffer.try_raw(snatch_guard)?, *offset); + if *indexed { + unsafe { raw.draw_indexed_indirect(buffer, offset, 1) }; + } else { + unsafe { raw.draw_indirect(buffer, offset, 1) }; + } } Cmd::DrawIndirect { .. } | Cmd::MultiDrawIndirectCount { .. } => { return Err(ExecutionError::Unimplemented("multi-draw-indirect")) diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index abc804373..dd2af650b 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -436,6 +436,9 @@ pub(crate) struct BakedCommands { pub(crate) encoder: CommandEncoder, pub(crate) trackers: Tracker, pub(crate) temp_resources: Vec, + #[cfg(feature = "indirect-validation")] + pub(crate) indirect_draw_validation_resources: + crate::indirect_draw_validation::IndirectDrawValidationResources, buffer_memory_init_actions: Vec, texture_memory_actions: CommandBufferTextureMemoryActions, } @@ -466,6 +469,10 @@ pub struct CommandBufferMutable { tlas_actions: Vec, temp_resources: Vec, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: + crate::indirect_draw_validation::IndirectDrawValidationResources, + #[cfg(feature = "trace")] pub(crate) commands: Option>, } @@ -485,6 +492,8 @@ impl CommandBufferMutable { encoder: self.encoder, trackers: self.trackers, temp_resources: self.temp_resources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: self.indirect_draw_validation_resources, buffer_memory_init_actions: self.buffer_memory_init_actions, texture_memory_actions: self.texture_memory_actions, } @@ -552,6 +561,11 @@ impl CommandBuffer { blas_actions: Default::default(), tlas_actions: Default::default(), temp_resources: Default::default(), + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: + crate::indirect_draw_validation::IndirectDrawValidationResources::new( + device.clone(), + ), #[cfg(feature = "trace")] commands: if device.trace.lock().is_some() { Some(Vec::new()) diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 6d59f1b18..d3cced9dd 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1631,6 +1631,10 @@ impl Global { let device = &cmd_buf.device; let snatch_guard = &device.snatchable_lock.read(); + #[cfg(feature = "indirect-validation")] + let mut indirect_draw_validation_batcher = + crate::indirect_draw_validation::IndirectDrawValidationBatcher::new(); + let (scope, pending_discard_init_fixups) = { device.check_is_valid().map_pass_err(pass_scope)?; @@ -1639,6 +1643,9 @@ impl Global { let buffer_memory_init_actions = &mut cmd_buf_data.buffer_memory_init_actions; let texture_memory_actions = &mut cmd_buf_data.texture_memory_actions; let pending_query_resets = &mut cmd_buf_data.pending_query_resets; + #[cfg(feature = "indirect-validation")] + let indirect_draw_validation_resources = + &mut cmd_buf_data.indirect_draw_validation_resources; // We automatically keep extending command buffers over time, and because // we want to insert a command buffer _before_ what we're about to record, @@ -1819,6 +1826,9 @@ impl Global { offset, count, indexed, + + vertex_or_index_limit: _, + instance_limit: _, } => { let scope = PassErrorScope::Draw { kind: if count != 1 { @@ -1828,8 +1838,19 @@ impl Global { }, indexed, }; - multi_draw_indirect(&mut state, cmd_buf, buffer, offset, count, indexed) - .map_pass_err(scope)?; + multi_draw_indirect( + &mut state, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources, + #[cfg(feature = "indirect-validation")] + &mut indirect_draw_validation_batcher, + cmd_buf, + buffer, + offset, + count, + indexed, + ) + .map_pass_err(scope)?; } ArcRenderCommand::MultiDrawIndirectCount { buffer, @@ -1939,7 +1960,16 @@ impl Global { } ArcRenderCommand::ExecuteBundle(bundle) => { let scope = PassErrorScope::ExecuteBundle; - execute_bundle(&mut state, cmd_buf, bundle).map_pass_err(scope)?; + execute_bundle( + &mut state, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources, + #[cfg(feature = "indirect-validation")] + &mut indirect_draw_validation_batcher, + cmd_buf, + bundle, + ) + .map_pass_err(scope)?; } } } @@ -1972,6 +2002,20 @@ impl Global { cmd_buf_data.pending_query_resets.reset_queries(transit); CommandBuffer::insert_barriers_from_scope(transit, tracker, &scope, snatch_guard); + + #[cfg(feature = "indirect-validation")] + if let Some(ref indirect_draw_validation) = device.indirect_draw_validation { + indirect_draw_validation + .inject_validation_pass( + device, + snatch_guard, + &mut cmd_buf_data.indirect_draw_validation_resources, + &mut cmd_buf_data.temp_resources, + transit, + indirect_draw_validation_batcher, + ) + .map_pass_err(pass_scope)?; + } } encoder.close_and_swap().map_pass_err(pass_scope)?; @@ -2457,6 +2501,10 @@ fn draw_indexed( fn multi_draw_indirect( state: &mut State, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: &mut crate::indirect_draw_validation::IndirectDrawValidationResources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_batcher: &mut crate::indirect_draw_validation::IndirectDrawValidationBatcher, cmd_buf: &Arc, indirect_buffer: Arc, offset: u64, @@ -2470,36 +2518,26 @@ fn multi_draw_indirect( state.is_ready(indexed)?; - let stride = match indexed { - false => size_of::(), - true => size_of::(), - }; - if count != 1 { state .device .require_features(wgt::Features::MULTI_DRAW_INDIRECT)?; } + state .device .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?; indirect_buffer.same_device_as(cmd_buf.as_ref())?; - - state - .info - .usage_scope - .buffers - .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?; - indirect_buffer.check_usage(BufferUsages::INDIRECT)?; - let indirect_raw = indirect_buffer.try_raw(state.snatch_guard)?; if offset % 4 != 0 { return Err(RenderPassErrorInner::UnalignedIndirectBufferOffset(offset)); } - let end_offset = offset + stride as u64 * count as u64; + let stride = get_stride_of_indirect_args(indexed); + + let end_offset = offset + stride * count as u64; if end_offset > indirect_buffer.size { return Err(RenderPassErrorInner::IndirectBufferOverrun { count, @@ -2517,6 +2555,47 @@ fn multi_draw_indirect( ), ); + #[cfg(feature = "indirect-validation")] + let (indirect_raw, offset) = if count == 1 { + state + .info + .usage_scope + .buffers + .merge_single(&indirect_buffer, wgt::BufferUses::STORAGE_READ_ONLY)?; + + indirect_draw_validation_batcher.add( + indirect_draw_validation_resources, + state.device, + indirect_buffer, + offset, + indexed, + if indexed { + state.index.limit + } else { + state.vertex.limits.vertex_limit + }, + state.vertex.limits.instance_limit, + )? + } else { + state + .info + .usage_scope + .buffers + .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?; + + (indirect_buffer.try_raw(state.snatch_guard)?, offset) + }; + #[cfg(not(feature = "indirect-validation"))] + let (indirect_raw, offset) = { + state + .info + .usage_scope + .buffers + .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?; + + (indirect_buffer.try_raw(state.snatch_guard)?, offset) + }; + match indexed { false => unsafe { state.raw_encoder.draw_indirect(indirect_raw, offset, count); @@ -2548,10 +2627,7 @@ fn multi_draw_indirect_count( state.is_ready(indexed)?; - let stride = match indexed { - false => size_of::(), - true => size_of::(), - } as u64; + let stride = get_stride_of_indirect_args(indexed); state .device @@ -2725,6 +2801,10 @@ fn write_timestamp( fn execute_bundle( state: &mut State, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: &mut crate::indirect_draw_validation::IndirectDrawValidationResources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_batcher: &mut crate::indirect_draw_validation::IndirectDrawValidationBatcher, cmd_buf: &Arc, bundle: Arc, ) -> Result<(), RenderPassErrorInner> { @@ -2774,9 +2854,24 @@ fn execute_bundle( .extend(state.texture_memory_actions.register_init_action(action)); } - unsafe { bundle.execute(state.raw_encoder, state.snatch_guard) }.map_err(|e| match e { - ExecutionError::DestroyedResource(e) => RenderCommandError::DestroyedResource(e), - ExecutionError::Unimplemented(what) => RenderCommandError::Unimplemented(what), + unsafe { + bundle.execute( + state.raw_encoder, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_batcher, + state.snatch_guard, + ) + } + .map_err(|e| match e { + ExecutionError::Device(e) => RenderPassErrorInner::Device(e), + ExecutionError::DestroyedResource(e) => { + RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(e)) + } + ExecutionError::Unimplemented(what) => { + RenderPassErrorInner::RenderCommand(RenderCommandError::Unimplemented(what)) + } })?; unsafe { @@ -3097,6 +3192,9 @@ impl Global { offset, count: 1, indexed: false, + + vertex_or_index_limit: 0, + instance_limit: 0, }); Ok(()) @@ -3119,6 +3217,9 @@ impl Global { offset, count: 1, indexed: true, + + vertex_or_index_limit: 0, + instance_limit: 0, }); Ok(()) @@ -3142,6 +3243,9 @@ impl Global { offset, count, indexed: false, + + vertex_or_index_limit: 0, + instance_limit: 0, }); Ok(()) @@ -3165,6 +3269,9 @@ impl Global { offset, count, indexed: true, + + vertex_or_index_limit: 0, + instance_limit: 0, }); Ok(()) @@ -3371,3 +3478,10 @@ impl Global { Ok(()) } } + +pub(crate) const fn get_stride_of_indirect_args(indexed: bool) -> u64 { + match indexed { + false => size_of::() as u64, + true => size_of::() as u64, + } +} diff --git a/wgpu-core/src/command/render_command.rs b/wgpu-core/src/command/render_command.rs index b7fa73915..6fc4cbf5c 100644 --- a/wgpu-core/src/command/render_command.rs +++ b/wgpu-core/src/command/render_command.rs @@ -333,6 +333,9 @@ impl RenderCommand { offset, count, indexed, + + vertex_or_index_limit: 0, + instance_limit: 0, }, RenderCommand::MultiDrawIndirectCount { @@ -464,6 +467,11 @@ pub enum ArcRenderCommand { offset: BufferAddress, count: u32, indexed: bool, + + /// This limit is only populated for commands in a [`RenderBundle`]. + vertex_or_index_limit: u64, + /// This limit is only populated for commands in a [`RenderBundle`]. + instance_limit: u64, }, MultiDrawIndirectCount { buffer: Arc, diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index e19f9bc5f..4e0193e5a 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -267,6 +267,10 @@ pub(crate) struct EncoderInFlight { inner: crate::command::CommandEncoder, pub(crate) trackers: Tracker, pub(crate) temp_resources: Vec, + #[cfg(feature = "indirect-validation")] + #[allow(unused)] // We only need to keep these resources alive. + indirect_draw_validation_resources: + crate::indirect_draw_validation::IndirectDrawValidationResources, /// These are the buffers that have been tracked by `PendingWrites`. pub(crate) pending_buffers: FastHashMap>, @@ -377,6 +381,11 @@ impl PendingWrites { }, trackers: Tracker::new(), temp_resources: mem::take(&mut self.temp_resources), + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: + crate::indirect_draw_validation::IndirectDrawValidationResources::new( + device.clone(), + ), pending_buffers, pending_textures, }; @@ -1196,6 +1205,9 @@ impl Queue { inner: baked.encoder, trackers: baked.trackers, temp_resources: baked.temp_resources, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation_resources: baked + .indirect_draw_validation_resources, pending_buffers: FastHashMap::default(), pending_textures: FastHashMap::default(), }); diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 83fbcc332..66ff65ef6 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -131,6 +131,9 @@ pub struct Device { pub(crate) last_acceleration_structure_build_command_index: AtomicU64, #[cfg(feature = "indirect-validation")] pub(crate) indirect_validation: Option, + #[cfg(feature = "indirect-validation")] + pub(crate) indirect_draw_validation: + Option, // needs to be dropped last #[cfg(feature = "trace")] pub(crate) trace: Mutex>, @@ -164,6 +167,10 @@ impl Drop for Device { if let Some(indirect_validation) = self.indirect_validation.take() { indirect_validation.dispose(self.raw.as_ref()); } + #[cfg(feature = "indirect-validation")] + if let Some(indirect_draw_validation) = self.indirect_draw_validation.take() { + indirect_draw_validation.dispose(self.raw.as_ref()); + } unsafe { self.raw.destroy_buffer(zero_buffer); self.raw.destroy_fence(fence); @@ -267,6 +274,25 @@ impl Device { None }; + #[cfg(feature = "indirect-validation")] + let indirect_draw_validation = if downlevel + .flags + .contains(wgt::DownlevelFlags::INDIRECT_EXECUTION) + { + match crate::indirect_draw_validation::IndirectDrawValidation::new( + raw_device.as_ref(), + &desc.required_features, + ) { + Ok(indirect_draw_validation) => Some(indirect_draw_validation), + Err(e) => { + log::error!("indirect-draw-validation error: {e:?}"); + return Err(DeviceError::Lost); + } + } + } else { + None + }; + Ok(Self { raw: raw_device, adapter: adapter.clone(), @@ -314,6 +340,8 @@ impl Device { last_acceleration_structure_build_command_index: AtomicU64::new(1), #[cfg(feature = "indirect-validation")] indirect_validation, + #[cfg(feature = "indirect-validation")] + indirect_draw_validation, }) } @@ -655,6 +683,10 @@ impl Device { let raw_indirect_validation_bind_group = self.create_indirect_validation_bind_group(buffer.as_ref(), desc.size, desc.usage)?; + #[cfg(feature = "indirect-validation")] + let raw_indirect_draw_validation_bind_group = self + .create_indirect_draw_validation_bind_group(buffer.as_ref(), desc.size, desc.usage)?; + let buffer = Buffer { raw: Snatchable::new(buffer), device: self.clone(), @@ -670,6 +702,8 @@ impl Device { bind_groups: Mutex::new(rank::BUFFER_BIND_GROUPS, WeakVec::new()), #[cfg(feature = "indirect-validation")] raw_indirect_validation_bind_group, + #[cfg(feature = "indirect-validation")] + raw_indirect_draw_validation_bind_group, }; let buffer = Arc::new(buffer); @@ -761,6 +795,14 @@ impl Device { Err(e) => return (Fallible::Invalid(Arc::new(desc.label.to_string())), Some(e)), }; + #[cfg(feature = "indirect-validation")] + let raw_indirect_draw_validation_bind_group = match self + .create_indirect_draw_validation_bind_group(hal_buffer.as_ref(), desc.size, desc.usage) + { + Ok(ok) => ok, + Err(e) => return (Fallible::Invalid(Arc::new(desc.label.to_string())), Some(e)), + }; + unsafe { self.raw().add_raw_buffer(&*hal_buffer) }; let buffer = Buffer { @@ -778,6 +820,8 @@ impl Device { bind_groups: Mutex::new(rank::BUFFER_BIND_GROUPS, WeakVec::new()), #[cfg(feature = "indirect-validation")] raw_indirect_validation_bind_group, + #[cfg(feature = "indirect-validation")] + raw_indirect_draw_validation_bind_group, }; let buffer = Arc::new(buffer); @@ -811,6 +855,27 @@ impl Device { } } + #[cfg(feature = "indirect-validation")] + fn create_indirect_draw_validation_bind_group( + &self, + raw_buffer: &dyn hal::DynBuffer, + buffer_size: u64, + usage: wgt::BufferUsages, + ) -> Result>, resource::CreateBufferError> { + if usage.contains(wgt::BufferUsages::INDIRECT) { + let indirect_draw_validation = self.indirect_draw_validation.as_ref().unwrap(); + let bind_group = indirect_draw_validation + .create_src_bind_group(self.raw(), &self.adapter.limits(), buffer_size, raw_buffer) + .map_err(resource::CreateBufferError::IndirectValidationBindGroup)?; + match bind_group { + Some(bind_group) => Ok(Snatchable::new(bind_group)), + None => Ok(Snatchable::empty()), + } + } else { + Ok(Snatchable::empty()) + } + } + pub(crate) fn create_texture( self: &Arc, desc: &resource::TextureDescriptor, diff --git a/wgpu-core/src/indirect_draw_validation.rs b/wgpu-core/src/indirect_draw_validation.rs new file mode 100644 index 000000000..88d4c75a8 --- /dev/null +++ b/wgpu-core/src/indirect_draw_validation.rs @@ -0,0 +1,996 @@ +use crate::{ + device::{queue::TempResource, Device, DeviceError}, + lock::{rank, Mutex}, + pipeline::{CreateComputePipelineError, CreateShaderModuleError}, + resource::{StagingBuffer, Trackable}, + snatch::SnatchGuard, + track::TrackerIndex, + FastHashMap, +}; +use alloc::{boxed::Box, string::ToString, sync::Arc, vec, vec::Vec}; +use core::{ + mem::{size_of, size_of_val}, + num::NonZeroU64, +}; +use thiserror::Error; +use wgt::Limits; + +/// Note: This needs to be under: +/// +/// default max_compute_workgroups_per_dimension * size_of::() * `workgroup_size` used by the shader +/// +/// = (2^16 - 1) * 2^4 * 2^6 +/// +/// It is currently set to: +/// +/// = (2^16 - 1) * 2^4 +/// +/// This is enough space for: +/// +/// - 65535 [`wgt::DrawIndirectArgs`] / [`MetadataEntry`] +/// - 52428 [`wgt::DrawIndexedIndirectArgs`] +const BUFFER_SIZE: wgt::BufferSize = unsafe { wgt::BufferSize::new_unchecked(1_048_560) }; + +#[derive(Clone, Debug, Error)] +#[non_exhaustive] +pub enum CreateDrawIndirectValidationPipelineError { + #[error(transparent)] + DeviceError(#[from] DeviceError), + #[error(transparent)] + ShaderModule(#[from] CreateShaderModuleError), + #[error(transparent)] + ComputePipeline(#[from] CreateComputePipelineError), +} + +/// Holds all device-level resources that are needed to validate indirect draws. +/// +/// This machinery requires the following limits: +/// +/// - max_bind_groups: 3, +/// - max_dynamic_storage_buffers_per_pipeline_layout: 1, +/// - max_storage_buffers_per_shader_stage: 3, +/// - max_push_constant_size: 8, +/// +/// These are all indirectly satisfied by `DownlevelFlags::INDIRECT_EXECUTION`, which is also +/// required for this module's functionality to work. +#[derive(Debug)] +pub struct IndirectDrawValidation { + module: Box, + metadata_bind_group_layout: Box, + src_bind_group_layout: Box, + dst_bind_group_layout: Box, + pipeline_layout: Box, + pipeline: Box, + + free_indirect_entries: Mutex>, + free_metadata_entries: Mutex>, +} + +impl IndirectDrawValidation { + pub fn new( + device: &dyn hal::DynDevice, + required_features: &wgt::Features, + ) -> Result { + let module = create_validation_module(device)?; + + let metadata_bind_group_layout = + create_bind_group_layout(device, true, false, BUFFER_SIZE)?; + let src_bind_group_layout = + create_bind_group_layout(device, true, true, wgt::BufferSize::new(4 * 4).unwrap())?; + let dst_bind_group_layout = create_bind_group_layout(device, false, false, BUFFER_SIZE)?; + + let pipeline_layout_desc = hal::PipelineLayoutDescriptor { + label: None, + flags: hal::PipelineLayoutFlags::empty(), + bind_group_layouts: &[ + metadata_bind_group_layout.as_ref(), + src_bind_group_layout.as_ref(), + dst_bind_group_layout.as_ref(), + ], + push_constant_ranges: &[wgt::PushConstantRange { + stages: wgt::ShaderStages::COMPUTE, + range: 0..8, + }], + }; + let pipeline_layout = unsafe { + device + .create_pipeline_layout(&pipeline_layout_desc) + .map_err(DeviceError::from_hal)? + }; + + let supports_indirect_first_instance = + required_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE); + let pipeline = create_validation_pipeline( + device, + module.as_ref(), + pipeline_layout.as_ref(), + supports_indirect_first_instance, + )?; + + Ok(Self { + module, + metadata_bind_group_layout, + src_bind_group_layout, + dst_bind_group_layout, + pipeline_layout, + pipeline, + + free_indirect_entries: Mutex::new(rank::BUFFER_POOL, Vec::new()), + free_metadata_entries: Mutex::new(rank::BUFFER_POOL, Vec::new()), + }) + } + + /// `Ok(None)` will only be returned if `buffer_size` is `0`. + pub fn create_src_bind_group( + &self, + device: &dyn hal::DynDevice, + limits: &Limits, + buffer_size: u64, + buffer: &dyn hal::DynBuffer, + ) -> Result>, DeviceError> { + let binding_size = calculate_src_buffer_binding_size(buffer_size, limits); + let Some(binding_size) = NonZeroU64::new(binding_size) else { + return Ok(None); + }; + let hal_desc = hal::BindGroupDescriptor { + label: None, + layout: self.src_bind_group_layout.as_ref(), + entries: &[hal::BindGroupEntry { + binding: 0, + resource_index: 0, + count: 1, + }], + buffers: &[hal::BufferBinding { + buffer, + offset: 0, + size: Some(binding_size), + }], + samplers: &[], + textures: &[], + acceleration_structures: &[], + }; + unsafe { + device + .create_bind_group(&hal_desc) + .map(Some) + .map_err(DeviceError::from_hal) + } + } + + fn acquire_dst_entry( + &self, + device: &dyn hal::DynDevice, + ) -> Result { + let mut free_buffers = self.free_indirect_entries.lock(); + match free_buffers.pop() { + Some(buffer) => Ok(buffer), + None => { + let usage = wgt::BufferUses::INDIRECT | wgt::BufferUses::STORAGE_READ_WRITE; + create_buffer_and_bind_group(device, usage, self.dst_bind_group_layout.as_ref()) + } + } + } + + fn release_dst_entries(&self, entries: impl Iterator) { + self.free_indirect_entries.lock().extend(entries); + } + + fn acquire_metadata_entry( + &self, + device: &dyn hal::DynDevice, + ) -> Result { + let mut free_buffers = self.free_metadata_entries.lock(); + match free_buffers.pop() { + Some(buffer) => Ok(buffer), + None => { + let usage = wgt::BufferUses::COPY_DST | wgt::BufferUses::STORAGE_READ_ONLY; + create_buffer_and_bind_group( + device, + usage, + self.metadata_bind_group_layout.as_ref(), + ) + } + } + } + + fn release_metadata_entries(&self, entries: impl Iterator) { + self.free_metadata_entries.lock().extend(entries); + } + + /// Injects a compute pass that will validate all indirect draws in the current render pass. + pub(crate) fn inject_validation_pass( + &self, + device: &Arc, + snatch_guard: &SnatchGuard, + resources: &mut IndirectDrawValidationResources, + temp_resources: &mut Vec, + encoder: &mut dyn hal::DynCommandEncoder, + batcher: IndirectDrawValidationBatcher, + ) -> Result<(), DeviceError> { + let mut batches = batcher.batches; + + if batches.is_empty() { + return Ok(()); + } + + let max_staging_buffer_size = 1 << 26; // ~67MiB + + let mut staging_buffers = Vec::new(); + + let mut current_size = 0; + for batch in batches.values_mut() { + let data = batch.metadata(); + let offset = if current_size + data.len() > max_staging_buffer_size { + let staging_buffer = + StagingBuffer::new(device, NonZeroU64::new(current_size as u64).unwrap())?; + staging_buffers.push(staging_buffer); + current_size = data.len(); + 0 + } else { + let offset = current_size; + current_size += data.len(); + offset as u64 + }; + batch.staging_buffer_index = staging_buffers.len(); + batch.staging_buffer_offset = offset; + } + if current_size != 0 { + let staging_buffer = + StagingBuffer::new(device, NonZeroU64::new(current_size as u64).unwrap())?; + staging_buffers.push(staging_buffer); + } + + for batch in batches.values() { + let data = batch.metadata(); + let staging_buffer = &mut staging_buffers[batch.staging_buffer_index]; + unsafe { + staging_buffer.write_with_offset( + data, + 0, + batch.staging_buffer_offset as isize, + data.len(), + ) + }; + } + + let staging_buffers: Vec<_> = staging_buffers + .into_iter() + .map(|buffer| buffer.flush()) + .collect(); + + let mut current_metadata_entry = None; + for batch in batches.values_mut() { + let data = batch.metadata(); + let (metadata_resource_index, metadata_buffer_offset) = + resources.get_metadata_subrange(data.len() as u64, &mut current_metadata_entry)?; + batch.metadata_resource_index = metadata_resource_index; + batch.metadata_buffer_offset = metadata_buffer_offset; + } + + let mut buffer_barriers = Vec::new(); + let mut buffer_index_set = bit_set::BitSet::new(); + + for index in batches + .values() + .map(|batch| batch.staging_buffer_index) + .filter(|index| buffer_index_set.insert(*index)) + { + let staging_buffer = &staging_buffers[index]; + + buffer_barriers.push(hal::BufferBarrier { + buffer: staging_buffer.raw(), + usage: hal::StateTransition { + from: wgt::BufferUses::MAP_WRITE, + to: wgt::BufferUses::COPY_SRC, + }, + }); + } + buffer_index_set.clear(); + + for index in batches + .values() + .map(|batch| batch.metadata_resource_index) + .filter(|index| buffer_index_set.insert(*index)) + { + let metadata_buffer = resources.get_metadata_buffer(index); + + buffer_barriers.push(hal::BufferBarrier { + buffer: metadata_buffer, + usage: hal::StateTransition { + from: wgt::BufferUses::STORAGE_READ_ONLY, + to: wgt::BufferUses::COPY_DST, + }, + }); + } + buffer_index_set.clear(); + + unsafe { + encoder.transition_buffers(&buffer_barriers); + } + buffer_barriers.clear(); + + for batch in batches.values() { + let data = batch.metadata(); + let data_size = NonZeroU64::new(data.len() as u64).unwrap(); + + let staging_buffer = &staging_buffers[batch.staging_buffer_index]; + + let metadata_buffer = resources.get_metadata_buffer(batch.metadata_resource_index); + + unsafe { + encoder.copy_buffer_to_buffer( + staging_buffer.raw(), + metadata_buffer, + &[hal::BufferCopy { + src_offset: batch.staging_buffer_offset, + dst_offset: batch.metadata_buffer_offset, + size: data_size, + }], + ); + } + } + + for index in batches + .values() + .map(|batch| batch.metadata_resource_index) + .filter(|index| buffer_index_set.insert(*index)) + { + let metadata_buffer = resources.get_metadata_buffer(index); + + buffer_barriers.push(hal::BufferBarrier { + buffer: metadata_buffer, + usage: hal::StateTransition { + from: wgt::BufferUses::COPY_DST, + to: wgt::BufferUses::STORAGE_READ_ONLY, + }, + }); + } + buffer_index_set.clear(); + + for index in batches + .values() + .map(|batch| batch.dst_resource_index) + .filter(|index| buffer_index_set.insert(*index)) + { + let dst_buffer = resources.get_dst_buffer(index); + + buffer_barriers.push(hal::BufferBarrier { + buffer: dst_buffer, + usage: hal::StateTransition { + from: wgt::BufferUses::INDIRECT, + to: wgt::BufferUses::STORAGE_READ_WRITE, + }, + }); + } + buffer_index_set.clear(); + + unsafe { + encoder.transition_buffers(&buffer_barriers); + } + buffer_barriers.clear(); + + let desc = hal::ComputePassDescriptor { + label: None, + timestamp_writes: None, + }; + unsafe { + encoder.begin_compute_pass(&desc); + } + unsafe { + encoder.set_compute_pipeline(self.pipeline.as_ref()); + } + + for batch in batches.values() { + let pipeline_layout = self.pipeline_layout.as_ref(); + + let metadata_start = + (batch.metadata_buffer_offset / size_of::() as u64) as u32; + let metadata_count = batch.entries.len() as u32; + unsafe { + encoder.set_push_constants( + pipeline_layout, + wgt::ShaderStages::COMPUTE, + 0, + &[metadata_start, metadata_count], + ); + } + + let metadata_bind_group = + resources.get_metadata_bind_group(batch.metadata_resource_index); + unsafe { + encoder.set_bind_group(pipeline_layout, 0, Some(metadata_bind_group), &[]); + } + + let src_bind_group = batch + .src_buffer + .raw_indirect_draw_validation_bind_group + .get(snatch_guard) + .unwrap() + .as_ref(); + unsafe { + encoder.set_bind_group( + pipeline_layout, + 1, + Some(src_bind_group), + &[batch.src_dynamic_offset as u32], + ); + } + + let dst_bind_group = resources.get_dst_bind_group(batch.dst_resource_index); + unsafe { + encoder.set_bind_group(pipeline_layout, 2, Some(dst_bind_group), &[]); + } + + unsafe { + encoder.dispatch([(batch.entries.len() as u32).div_ceil(64), 1, 1]); + } + } + + unsafe { + encoder.end_compute_pass(); + } + + for index in batches + .values() + .map(|batch| batch.dst_resource_index) + .filter(|index| buffer_index_set.insert(*index)) + { + let dst_buffer = resources.get_dst_buffer(index); + + buffer_barriers.push(hal::BufferBarrier { + buffer: dst_buffer, + usage: hal::StateTransition { + from: wgt::BufferUses::STORAGE_READ_WRITE, + to: wgt::BufferUses::INDIRECT, + }, + }); + } + buffer_index_set.clear(); + + unsafe { + encoder.transition_buffers(&buffer_barriers); + } + buffer_barriers.clear(); + + for staging_buffer in staging_buffers { + temp_resources.push(TempResource::StagingBuffer(staging_buffer)); + } + + Ok(()) + } + + pub fn dispose(self, device: &dyn hal::DynDevice) { + let IndirectDrawValidation { + module, + metadata_bind_group_layout, + src_bind_group_layout, + dst_bind_group_layout, + pipeline_layout, + pipeline, + + free_indirect_entries, + free_metadata_entries, + } = self; + + for entry in free_indirect_entries.into_inner().drain(..) { + unsafe { + device.destroy_bind_group(entry.bind_group); + device.destroy_buffer(entry.buffer); + } + } + + for entry in free_metadata_entries.into_inner().drain(..) { + unsafe { + device.destroy_bind_group(entry.bind_group); + device.destroy_buffer(entry.buffer); + } + } + + unsafe { + device.destroy_compute_pipeline(pipeline); + device.destroy_pipeline_layout(pipeline_layout); + device.destroy_bind_group_layout(metadata_bind_group_layout); + device.destroy_bind_group_layout(src_bind_group_layout); + device.destroy_bind_group_layout(dst_bind_group_layout); + device.destroy_shader_module(module); + } + } +} + +fn create_validation_module( + device: &dyn hal::DynDevice, +) -> Result, CreateDrawIndirectValidationPipelineError> { + let src = include_str!("./indirect_draw_validation.wgsl"); + + let module = naga::front::wgsl::parse_str(src).map_err(|inner| { + CreateShaderModuleError::Parsing(naga::error::ShaderError { + source: src.to_string(), + label: None, + inner: Box::new(inner), + }) + })?; + let info = crate::device::create_validator( + wgt::Features::PUSH_CONSTANTS, + wgt::DownlevelFlags::empty(), + naga::valid::ValidationFlags::all(), + ) + .validate(&module) + .map_err(|inner| { + CreateShaderModuleError::Validation(naga::error::ShaderError { + source: src.to_string(), + label: None, + inner: Box::new(inner), + }) + })?; + let hal_shader = hal::ShaderInput::Naga(hal::NagaShader { + module: alloc::borrow::Cow::Owned(module), + info, + debug_source: None, + }); + let hal_desc = hal::ShaderModuleDescriptor { + label: None, + runtime_checks: wgt::ShaderRuntimeChecks::unchecked(), + }; + let module = unsafe { device.create_shader_module(&hal_desc, hal_shader) }.map_err( + |error| match error { + hal::ShaderError::Device(error) => { + CreateShaderModuleError::Device(DeviceError::from_hal(error)) + } + hal::ShaderError::Compilation(ref msg) => { + log::error!("Shader error: {}", msg); + CreateShaderModuleError::Generation + } + }, + )?; + + Ok(module) +} + +fn create_validation_pipeline( + device: &dyn hal::DynDevice, + module: &dyn hal::DynShaderModule, + pipeline_layout: &dyn hal::DynPipelineLayout, + supports_indirect_first_instance: bool, +) -> Result, CreateDrawIndirectValidationPipelineError> { + let pipeline_desc = hal::ComputePipelineDescriptor { + label: None, + layout: pipeline_layout, + stage: hal::ProgrammableStage { + module, + entry_point: "main", + constants: &hashbrown::HashMap::from([( + "supports_indirect_first_instance".to_string(), + f64::from(supports_indirect_first_instance), + )]), + zero_initialize_workgroup_memory: false, + }, + cache: None, + }; + let pipeline = + unsafe { device.create_compute_pipeline(&pipeline_desc) }.map_err(|err| match err { + hal::PipelineError::Device(error) => { + CreateComputePipelineError::Device(DeviceError::from_hal(error)) + } + hal::PipelineError::Linkage(_stages, msg) => CreateComputePipelineError::Internal(msg), + hal::PipelineError::EntryPoint(_stage) => CreateComputePipelineError::Internal( + crate::device::ENTRYPOINT_FAILURE_ERROR.to_string(), + ), + hal::PipelineError::PipelineConstants(_, error) => { + CreateComputePipelineError::PipelineConstants(error) + } + })?; + + Ok(pipeline) +} + +fn create_bind_group_layout( + device: &dyn hal::DynDevice, + read_only: bool, + has_dynamic_offset: bool, + min_binding_size: wgt::BufferSize, +) -> Result, CreateDrawIndirectValidationPipelineError> { + let bind_group_layout_desc = hal::BindGroupLayoutDescriptor { + label: None, + flags: hal::BindGroupLayoutFlags::empty(), + entries: &[wgt::BindGroupLayoutEntry { + binding: 0, + visibility: wgt::ShaderStages::COMPUTE, + ty: wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { read_only }, + has_dynamic_offset, + min_binding_size: Some(min_binding_size), + }, + count: None, + }], + }; + let bind_group_layout = unsafe { + device + .create_bind_group_layout(&bind_group_layout_desc) + .map_err(DeviceError::from_hal)? + }; + + Ok(bind_group_layout) +} + +/// Returns the largest binding size that when combined with dynamic offsets can address the whole buffer. +fn calculate_src_buffer_binding_size(buffer_size: u64, limits: &Limits) -> u64 { + let max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size as u64; + let min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment as u64; + + if buffer_size <= max_storage_buffer_binding_size { + buffer_size + } else { + let buffer_rem = buffer_size % min_storage_buffer_offset_alignment; + let binding_rem = max_storage_buffer_binding_size % min_storage_buffer_offset_alignment; + + // Can the buffer remainder fit in the binding remainder? + // If so, align max binding size and add buffer remainder + if buffer_rem <= binding_rem { + max_storage_buffer_binding_size - binding_rem + buffer_rem + } + // If not, align max binding size, shorten it by a chunk and add buffer remainder + else { + max_storage_buffer_binding_size - binding_rem - min_storage_buffer_offset_alignment + + buffer_rem + } + } +} + +/// Splits the given `offset` into a dynamic offset & offset. +fn calculate_src_offsets(buffer_size: u64, limits: &Limits, offset: u64) -> (u64, u64) { + let binding_size = calculate_src_buffer_binding_size(buffer_size, limits); + + let min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment as u64; + + let chunk_adjustment = match min_storage_buffer_offset_alignment { + // No need to adjust since the src_offset is 4 byte aligned. + 4 => 0, + // With 16/20 bytes of data we can straddle up to 2 8 byte boundaries: + // - 16 bytes of data: (4|8|4) + // - 20 bytes of data: (4|8|8, 8|8|4) + 8 => 2, + // With 16/20 bytes of data we can straddle up to 1 16+ byte boundary: + // - 16 bytes of data: (4|12, 8|8, 12|4) + // - 20 bytes of data: (4|16, 8|12, 12|8, 16|4) + 16.. => 1, + _ => unreachable!(), + }; + + let chunks = binding_size / min_storage_buffer_offset_alignment; + let dynamic_offset_stride = + chunks.saturating_sub(chunk_adjustment) * min_storage_buffer_offset_alignment; + + if dynamic_offset_stride == 0 { + return (0, offset); + } + + let max_dynamic_offset = buffer_size - binding_size; + let max_dynamic_offset_index = max_dynamic_offset / dynamic_offset_stride; + + let src_dynamic_offset_index = offset / dynamic_offset_stride; + + let src_dynamic_offset = + src_dynamic_offset_index.min(max_dynamic_offset_index) * dynamic_offset_stride; + let src_offset = offset - src_dynamic_offset; + + (src_dynamic_offset, src_offset) +} + +#[derive(Debug)] +struct BufferPoolEntry { + buffer: Box, + bind_group: Box, +} + +fn create_buffer_and_bind_group( + device: &dyn hal::DynDevice, + usage: wgt::BufferUses, + bind_group_layout: &dyn hal::DynBindGroupLayout, +) -> Result { + let buffer_desc = hal::BufferDescriptor { + label: None, + size: BUFFER_SIZE.get(), + usage, + memory_flags: hal::MemoryFlags::empty(), + }; + let buffer = unsafe { device.create_buffer(&buffer_desc) }?; + let bind_group_desc = hal::BindGroupDescriptor { + label: None, + layout: bind_group_layout, + entries: &[hal::BindGroupEntry { + binding: 0, + resource_index: 0, + count: 1, + }], + buffers: &[hal::BufferBinding { + buffer: buffer.as_ref(), + offset: 0, + size: Some(BUFFER_SIZE), + }], + samplers: &[], + textures: &[], + acceleration_structures: &[], + }; + let bind_group = unsafe { device.create_bind_group(&bind_group_desc) }?; + Ok(BufferPoolEntry { buffer, bind_group }) +} + +#[derive(Clone)] +struct CurrentEntry { + index: usize, + offset: u64, +} + +/// Holds all command buffer-level resources that are needed to validate indirect draws. +pub(crate) struct IndirectDrawValidationResources { + device: Arc, + dst_entries: Vec, + metadata_entries: Vec, +} + +impl Drop for IndirectDrawValidationResources { + fn drop(&mut self) { + self.device + .indirect_draw_validation + .as_ref() + .unwrap() + .release_dst_entries(self.dst_entries.drain(..)); + + self.device + .indirect_draw_validation + .as_ref() + .unwrap() + .release_metadata_entries(self.metadata_entries.drain(..)); + } +} + +impl IndirectDrawValidationResources { + pub(crate) fn new(device: Arc) -> Self { + IndirectDrawValidationResources { + device, + dst_entries: Vec::new(), + metadata_entries: Vec::new(), + } + } + + fn get_dst_buffer(&self, index: usize) -> &dyn hal::DynBuffer { + self.dst_entries.get(index).unwrap().buffer.as_ref() + } + + fn get_dst_bind_group(&self, index: usize) -> &dyn hal::DynBindGroup { + self.dst_entries.get(index).unwrap().bind_group.as_ref() + } + + fn get_metadata_buffer(&self, index: usize) -> &dyn hal::DynBuffer { + self.metadata_entries.get(index).unwrap().buffer.as_ref() + } + + fn get_metadata_bind_group(&self, index: usize) -> &dyn hal::DynBindGroup { + self.metadata_entries + .get(index) + .unwrap() + .bind_group + .as_ref() + } + + fn get_dst_subrange( + &mut self, + size: u64, + current_entry: &mut Option, + ) -> Result<(usize, u64), DeviceError> { + let indirect_draw_validation = self.device.indirect_draw_validation.as_ref().unwrap(); + let ensure_entry = |index: usize| { + if self.dst_entries.len() <= index { + let entry = indirect_draw_validation.acquire_dst_entry(self.device.raw())?; + self.dst_entries.push(entry); + } + Ok(()) + }; + let entry_data = Self::get_subrange_impl(ensure_entry, current_entry, size)?; + Ok((entry_data.index, entry_data.offset)) + } + + fn get_metadata_subrange( + &mut self, + size: u64, + current_entry: &mut Option, + ) -> Result<(usize, u64), DeviceError> { + let indirect_draw_validation = self.device.indirect_draw_validation.as_ref().unwrap(); + let ensure_entry = |index: usize| { + if self.metadata_entries.len() <= index { + let entry = indirect_draw_validation.acquire_metadata_entry(self.device.raw())?; + self.metadata_entries.push(entry); + } + Ok(()) + }; + let entry_data = Self::get_subrange_impl(ensure_entry, current_entry, size)?; + Ok((entry_data.index, entry_data.offset)) + } + + fn get_subrange_impl( + ensure_entry: impl FnOnce(usize) -> Result<(), hal::DeviceError>, + current_entry: &mut Option, + size: u64, + ) -> Result { + let index = if let Some(current_entry) = current_entry.as_mut() { + if current_entry.offset + size <= BUFFER_SIZE.get() { + let entry_data = current_entry.clone(); + current_entry.offset += size; + return Ok(entry_data); + } else { + current_entry.index + 1 + } + } else { + 0 + }; + + ensure_entry(index).map_err(DeviceError::from_hal)?; + + let entry_data = CurrentEntry { index, offset: 0 }; + + *current_entry = Some(CurrentEntry { + index, + offset: size, + }); + + Ok(entry_data) + } +} + +/// This must match the `MetadataEntry` struct used by the shader. +#[repr(C)] +struct MetadataEntry { + src_offset: u32, + dst_offset: u32, + vertex_or_index_limit: u32, + instance_limit: u32, +} + +impl MetadataEntry { + fn new( + indexed: bool, + src_offset: u64, + dst_offset: u64, + vertex_or_index_limit: u64, + instance_limit: u64, + ) -> Self { + debug_assert_eq!( + 4, + size_of_val(&Limits::default().max_storage_buffer_binding_size) + ); + + let src_offset = src_offset as u32; // max_storage_buffer_binding_size is a u32 + let src_offset = src_offset / 4; // translate byte offset to offset in u32's + + // `src_offset` needs at most 30 bits, + // pack `indexed` in bit 31 of `src_offset` + let src_offset = src_offset | ((indexed as u32) << 31); + + // max value for limits since first_X and X_count indirect draw arguments are u32 + let max_limit = u32::MAX as u64 + u32::MAX as u64; // 1 11111111 11111111 11111111 11111110 + + let vertex_or_index_limit = vertex_or_index_limit.min(max_limit); + let vertex_or_index_limit_bit_32 = (vertex_or_index_limit >> 32) as u32; // extract bit 32 + let vertex_or_index_limit = vertex_or_index_limit as u32; // truncate the limit to a u32 + + let instance_limit = instance_limit.min(max_limit); + let instance_limit_bit_32 = (instance_limit >> 32) as u32; // extract bit 32 + let instance_limit = instance_limit as u32; // truncate the limit to a u32 + + let dst_offset = dst_offset as u32; // max_storage_buffer_binding_size is a u32 + let dst_offset = dst_offset / 4; // translate byte offset to offset in u32's + + // `dst_offset` needs at most 30 bits, + // pack `vertex_or_index_limit_bit_32` in bit 30 of `dst_offset` and + // pack `instance_limit_bit_32` in bit 31 of `dst_offset` + let dst_offset = + dst_offset | (vertex_or_index_limit_bit_32 << 30) | (instance_limit_bit_32 << 31); + + Self { + src_offset, + dst_offset, + vertex_or_index_limit, + instance_limit, + } + } +} + +struct DrawIndirectValidationBatch { + src_buffer: Arc, + src_dynamic_offset: u64, + dst_resource_index: usize, + entries: Vec, + + staging_buffer_index: usize, + staging_buffer_offset: u64, + metadata_resource_index: usize, + metadata_buffer_offset: u64, +} + +impl DrawIndirectValidationBatch { + /// Data to be written to the metadata buffer. + fn metadata(&self) -> &[u8] { + unsafe { + core::slice::from_raw_parts( + self.entries.as_ptr().cast::(), + self.entries.len() * size_of::(), + ) + } + } +} + +/// Accumulates all needed data needed to validate indirect draws. +pub(crate) struct IndirectDrawValidationBatcher { + batches: FastHashMap<(TrackerIndex, u64, usize), DrawIndirectValidationBatch>, + current_dst_entry: Option, +} + +impl IndirectDrawValidationBatcher { + pub(crate) fn new() -> Self { + Self { + batches: FastHashMap::default(), + current_dst_entry: None, + } + } + + /// Add an indirect draw to be validated. + /// + /// Returns an indirect buffer and offset to be used for the draw. + pub(crate) fn add<'a>( + &mut self, + indirect_draw_validation_resources: &'a mut IndirectDrawValidationResources, + device: &Device, + src_buffer: Arc, + offset: u64, + indexed: bool, + vertex_or_index_limit: u64, + instance_limit: u64, + ) -> Result<(&'a dyn hal::DynBuffer, u64), DeviceError> { + let stride = crate::command::get_stride_of_indirect_args(indexed); + + let (dst_resource_index, dst_offset) = indirect_draw_validation_resources + .get_dst_subrange(stride, &mut self.current_dst_entry)?; + + let buffer_size = src_buffer.size; + let limits = device.adapter.limits(); + let (src_dynamic_offset, src_offset) = calculate_src_offsets(buffer_size, &limits, offset); + + let src_buffer_tracker_index = src_buffer.tracker_index(); + + let entry = MetadataEntry::new( + indexed, + src_offset, + dst_offset, + vertex_or_index_limit, + instance_limit, + ); + + match self.batches.entry(( + src_buffer_tracker_index, + src_dynamic_offset, + dst_resource_index, + )) { + hashbrown::hash_map::Entry::Occupied(mut occupied_entry) => { + occupied_entry.get_mut().entries.push(entry) + } + hashbrown::hash_map::Entry::Vacant(vacant_entry) => { + vacant_entry.insert(DrawIndirectValidationBatch { + src_buffer, + src_dynamic_offset, + dst_resource_index, + entries: vec![entry], + + // these will be initialized once we accumulated all entries for the batch + staging_buffer_index: 0, + staging_buffer_offset: 0, + metadata_resource_index: 0, + metadata_buffer_offset: 0, + }); + } + } + + let dst_buffer = indirect_draw_validation_resources.get_dst_buffer(dst_resource_index); + + Ok((dst_buffer, dst_offset)) + } +} diff --git a/wgpu-core/src/indirect_draw_validation.wgsl b/wgpu-core/src/indirect_draw_validation.wgsl new file mode 100644 index 000000000..3675554a0 --- /dev/null +++ b/wgpu-core/src/indirect_draw_validation.wgsl @@ -0,0 +1,82 @@ +override supports_indirect_first_instance: bool; + +struct MetadataEntry { + // bits 0..30 are an offset into `src` + // bit 31 signifies that we are validating an indexed draw + src_offset: u32, + // bits 0..30 are an offset into `dst` + // bit 30 is the most significant bit of `vertex_or_index_limit` + // bit 31 is the most significant bit of `instance_limit` + dst_offset: u32, + vertex_or_index_limit: u32, + instance_limit: u32, +} + +struct MetadataRange { + start: u32, + count: u32, +} +var metadata_range: MetadataRange; + +@group(0) @binding(0) +var metadata: array; +@group(1) @binding(0) +var src: array; +@group(2) @binding(0) +var dst: array; + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) global_invocation_id: vec3u) { + if global_invocation_id.x >= metadata_range.count { return; } + + let metadata = metadata[metadata_range.start + global_invocation_id.x]; + var failed = false; + + let is_indexed = ((metadata.src_offset >> 31) & 1u) == 1u; + let src_base_offset = ((metadata.src_offset << 2) >> 2); + let dst_base_offset = ((metadata.dst_offset << 2) >> 2); + + let first_vertex_or_index = src[src_base_offset + 2]; + let vertex_or_index_count = src[src_base_offset + 0]; + + { + let can_overflow = ((metadata.dst_offset >> 30) & 1u) == 1u; + let sub_overflows = metadata.vertex_or_index_limit < first_vertex_or_index; + failed |= sub_overflows && !can_overflow; + let vertex_or_index_limit = metadata.vertex_or_index_limit - first_vertex_or_index; + failed |= vertex_or_index_limit < vertex_or_index_count; + } + + let first_instance = src[src_base_offset + 3 + u32(is_indexed)]; + let instance_count = src[src_base_offset + 1]; + + { + let can_overflow = (metadata.dst_offset >> 31) == 1u; + let sub_overflows = metadata.instance_limit < first_instance; + failed |= sub_overflows && !can_overflow; + let instance_limit = metadata.instance_limit - first_instance; + failed |= instance_limit < instance_count; + } + + if !supports_indirect_first_instance { + failed |= first_instance != 0u; + } + + if failed { + dst[dst_base_offset + 0] = 0u; + dst[dst_base_offset + 1] = 0u; + dst[dst_base_offset + 2] = 0u; + dst[dst_base_offset + 3] = 0u; + if (is_indexed) { + dst[dst_base_offset + 4] = 0u; + } + } else { + dst[dst_base_offset + 0] = src[src_base_offset + 0]; + dst[dst_base_offset + 1] = src[src_base_offset + 1]; + dst[dst_base_offset + 2] = src[src_base_offset + 2]; + dst[dst_base_offset + 3] = src[src_base_offset + 3]; + if (is_indexed) { + dst[dst_base_offset + 4] = src[src_base_offset + 4]; + } + } +} \ No newline at end of file diff --git a/wgpu-core/src/lib.rs b/wgpu-core/src/lib.rs index 364966ae6..56eaee37e 100644 --- a/wgpu-core/src/lib.rs +++ b/wgpu-core/src/lib.rs @@ -77,6 +77,8 @@ pub mod hub; pub mod id; pub mod identity; #[cfg(feature = "indirect-validation")] +mod indirect_draw_validation; +#[cfg(feature = "indirect-validation")] mod indirect_validation; mod init_tracker; pub mod instance; diff --git a/wgpu-core/src/lock/observing.rs b/wgpu-core/src/lock/observing.rs index 3c880ca02..86b164663 100644 --- a/wgpu-core/src/lock/observing.rs +++ b/wgpu-core/src/lock/observing.rs @@ -80,6 +80,11 @@ impl Mutex { _state: LockStateGuard { saved }, } } + + #[allow(dead_code)] + pub fn into_inner(self) -> T { + self.inner.into_inner() + } } impl<'a, T> std::ops::Deref for MutexGuard<'a, T> { diff --git a/wgpu-core/src/lock/rank.rs b/wgpu-core/src/lock/rank.rs index 652165ebd..b0ccf09c5 100644 --- a/wgpu-core/src/lock/rank.rs +++ b/wgpu-core/src/lock/rank.rs @@ -148,6 +148,8 @@ define_lock_ranks! { rank BLAS_BUILT_INDEX "Blas::built_index" followed by { } rank TLAS_BUILT_INDEX "Tlas::built_index" followed by { } rank TLAS_DEPENDENCIES "Tlas::dependencies" followed by { } + #[allow(dead_code)] + rank BUFFER_POOL "BufferPool::buffers" followed by { } #[cfg(test)] rank PAWN "pawn" followed by { ROOK, BISHOP } diff --git a/wgpu-core/src/lock/vanilla.rs b/wgpu-core/src/lock/vanilla.rs index 6318dae2d..44e73f577 100644 --- a/wgpu-core/src/lock/vanilla.rs +++ b/wgpu-core/src/lock/vanilla.rs @@ -30,6 +30,11 @@ impl Mutex { pub fn lock(&self) -> MutexGuard { MutexGuard(self.0.lock()) } + + #[allow(dead_code)] + pub fn into_inner(self) -> T { + self.0.into_inner() + } } impl<'a, T> ops::Deref for MutexGuard<'a, T> { diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index f8a252d7c..046dac385 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -368,6 +368,8 @@ pub struct Buffer { pub(crate) bind_groups: Mutex>, #[cfg(feature = "indirect-validation")] pub(crate) raw_indirect_validation_bind_group: Snatchable>, + #[cfg(feature = "indirect-validation")] + pub(crate) raw_indirect_draw_validation_bind_group: Snatchable>, } impl Drop for Buffer { @@ -378,6 +380,12 @@ impl Drop for Buffer { self.device.raw().destroy_bind_group(raw); } } + #[cfg(feature = "indirect-validation")] + if let Some(raw) = self.raw_indirect_draw_validation_bind_group.take() { + unsafe { + self.device.raw().destroy_bind_group(raw); + } + } if let Some(raw) = self.raw.take() { resource_log!("Destroy raw {}", self.error_ident()); unsafe { @@ -717,6 +725,11 @@ impl Buffer { .raw_indirect_validation_bind_group .snatch(&mut snatch_guard); + #[cfg(feature = "indirect-validation")] + let raw_indirect_draw_validation_bind_group = self + .raw_indirect_draw_validation_bind_group + .snatch(&mut snatch_guard); + drop(snatch_guard); let bind_groups = { @@ -731,6 +744,8 @@ impl Buffer { bind_groups, #[cfg(feature = "indirect-validation")] raw_indirect_validation_bind_group, + #[cfg(feature = "indirect-validation")] + raw_indirect_draw_validation_bind_group, }) }; @@ -787,6 +802,8 @@ pub struct DestroyedBuffer { bind_groups: WeakVec, #[cfg(feature = "indirect-validation")] raw_indirect_validation_bind_group: Option>, + #[cfg(feature = "indirect-validation")] + raw_indirect_draw_validation_bind_group: Option>, } impl DestroyedBuffer { @@ -810,6 +827,13 @@ impl Drop for DestroyedBuffer { } } + #[cfg(feature = "indirect-validation")] + if let Some(raw) = self.raw_indirect_draw_validation_bind_group.take() { + unsafe { + self.device.raw().destroy_bind_group(raw); + } + } + resource_log!("Destroy raw Buffer (destroyed) {:?}", self.label()); // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point. let raw = unsafe { ManuallyDrop::take(&mut self.raw) };