From 9b585b229170416d83cfdc8fa4e2c0db8e55e215 Mon Sep 17 00:00:00 2001 From: Andy Leiserson Date: Thu, 9 Jul 2026 14:18:56 -0700 Subject: [PATCH] feat: Support zero-size vertex and index buffer bindings Fixes #3170 (cherry picked from commit fb931396717e6131c8d1af1a4f81aff1a64621f0) --- deno_webgpu/render_bundle.rs | 10 +--- deno_webgpu/render_pass.rs | 5 +- wgpu-core/src/command/bundle.rs | 56 ++++++++++----------- wgpu-core/src/command/render.rs | 66 ++++++++++++------------- wgpu-core/src/command/render_command.rs | 6 +-- wgpu-core/src/device/resource.rs | 30 ++++++----- wgpu-core/src/resource.rs | 57 +++++++++++++-------- wgpu-hal/src/dynamic/command.rs | 8 +-- wgpu-hal/src/gles/command.rs | 4 +- wgpu-hal/src/lib.rs | 55 ++++++--------------- wgpu-hal/src/metal/command.rs | 22 +++++---- wgpu-hal/src/noop/command.rs | 4 +- wgpu-hal/src/vulkan/command.rs | 4 +- wgpu/src/api/buffer.rs | 4 -- wgpu/src/api/render_bundle_encoder.rs | 6 +-- wgpu/src/api/render_pass.rs | 6 +-- wgpu/src/backend/webgpu.rs | 28 ++++------- wgpu/src/backend/wgpu_core.rs | 8 +-- wgpu/src/dispatch.rs | 8 +-- 19 files changed, 178 insertions(+), 209 deletions(-) diff --git a/deno_webgpu/render_bundle.rs b/deno_webgpu/render_bundle.rs index c7cee6949..68dcbfc06 100644 --- a/deno_webgpu/render_bundle.rs +++ b/deno_webgpu/render_bundle.rs @@ -2,7 +2,6 @@ use std::borrow::Cow; use std::cell::RefCell; -use std::num::NonZeroU64; use deno_core::cppgc::Ptr; use deno_core::op2; @@ -261,12 +260,7 @@ impl GPURenderBundleEncoder { JsErrorBox::generic("Encoder has already been finished") })?; - encoder.set_index_buffer( - buffer.id, - index_format.into(), - offset, - size.and_then(NonZeroU64::new), - ); + encoder.set_index_buffer(buffer.id, index_format.into(), offset, size); Ok(()) } @@ -289,7 +283,7 @@ impl GPURenderBundleEncoder { slot, buffer.into_option().map(|buffer| buffer.id), offset, - size.and_then(NonZeroU64::new), + size, ); Ok(()) } diff --git a/deno_webgpu/render_pass.rs b/deno_webgpu/render_pass.rs index 3728992dc..81cd41fd1 100644 --- a/deno_webgpu/render_pass.rs +++ b/deno_webgpu/render_pass.rs @@ -2,7 +2,6 @@ use std::borrow::Cow; use std::cell::RefCell; -use std::num::NonZeroU64; use deno_core::cppgc::Ptr; use deno_core::op2; @@ -336,7 +335,7 @@ impl GPURenderPassEncoder { buffer.id, index_format.into(), offset, - size.and_then(NonZeroU64::new), + size, ) .err(); self.error_handler.push_error(err); @@ -358,7 +357,7 @@ impl GPURenderPassEncoder { slot, buffer.into_option().map(|buffer| buffer.id), offset, - size.and_then(NonZeroU64::new), + size, ) .err(); self.error_handler.push_error(err); diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 73d239dec..b40a179b9 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -84,16 +84,11 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::{ - convert::Infallible, - num::{NonZeroU32, NonZeroU64}, - ops::Range, -}; +use core::{convert::Infallible, num::NonZeroU32, ops::Range}; use arrayvec::ArrayVec; use thiserror::Error; -use wgpu_hal::ShouldBeNonZeroExt; use wgt::error::{ErrorType, WebGpuError}; #[cfg(feature = "trace")] @@ -575,7 +570,7 @@ impl RenderBundleEncoder { buffer: id::BufferId, index_format: wgt::IndexFormat, offset: wgt::BufferAddress, - size: Option, + size: Option, ) { self.base.commands.push(RenderCommand::SetIndexBuffer { buffer, @@ -685,7 +680,7 @@ fn set_index_buffer( buffer_id: id::Id, index_format: wgt::IndexFormat, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let buffer = buffer_guard.get(buffer_id).get()?; @@ -704,19 +699,16 @@ fn set_index_buffer( } .into()); } - let end = offset - + buffer - .resolve_binding_size::(offset, size)? - .get(); + let range = buffer.resolve_vertex_or_index_binding_range(offset, size)?; state .buffer_memory_init_actions .extend(buffer.initialization_status.read().create_action( &buffer, - offset..end.get(), + range.clone(), MemoryInitKind::NeedsInitializedMemory, )); - state.set_index_buffer(buffer, index_format, offset..end.get()); + state.set_index_buffer(buffer, index_format, range); Ok(()) } @@ -727,7 +719,7 @@ fn set_vertex_buffer( slot: u32, buffer_id: Option>, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let max_vertex_buffers = state.device.limits.max_vertex_buffers; if slot >= max_vertex_buffers { @@ -752,17 +744,16 @@ fn set_vertex_buffer( if !offset.is_multiple_of(wgt::VERTEX_ALIGNMENT) { return Err(RenderCommandError::UnalignedVertexBuffer { slot, offset }.into()); } - let binding_size = buffer.resolve_binding_size(offset, size)?; - let buffer_range = offset..(offset + binding_size.get()); + let range = buffer.resolve_vertex_or_index_binding_range(offset, size)?; state .buffer_memory_init_actions .extend(buffer.initialization_status.read().create_action( &buffer, - buffer_range.clone(), + range.clone(), MemoryInitKind::NeedsInitializedMemory, )); - state.vertex.set_buffer(slot as usize, buffer, buffer_range); + state.vertex.set_buffer(slot as usize, buffer, range); if let Some(pipeline) = state.pipeline.as_deref() { state.vertex.update_limits(&pipeline.vertex_steps); } @@ -776,14 +767,17 @@ fn set_vertex_buffer( ) .into()); } - if let Some(size) = size { - return Err(RenderCommandError::from( - crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero { - slot, - size: size.get(), - }, - ) - .into()); + match size { + Some(size) if size != 0 => { + return Err(RenderCommandError::from( + crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero { + slot, + size, + }, + ) + .into()); + } + _ => {} } state.vertex.clear_buffer(slot as usize); @@ -1354,7 +1348,7 @@ impl IndexState { buffer: self.buffer.clone(), index_format: self.format, offset: self.range.start, - size: NonZeroU64::new(binding_size), + size: Some(binding_size), }) } else { None @@ -1610,7 +1604,7 @@ pub mod bundle_ffi { use super::{RenderBundleEncoder, RenderCommand}; use crate::{command::DrawCommandFamily, id, RawString}; use core::{convert::TryInto, slice}; - use wgt::{BufferAddress, BufferSize, DynamicOffset, IndexFormat}; + use wgt::{BufferAddress, DynamicOffset, IndexFormat}; /// # Safety /// @@ -1662,7 +1656,7 @@ pub mod bundle_ffi { slot: u32, buffer_id: Option, offset: BufferAddress, - size: Option, + size: Option, ) { bundle.base.commands.push(RenderCommand::SetVertexBuffer { slot, @@ -1677,7 +1671,7 @@ pub mod bundle_ffi { buffer: id::BufferId, index_format: IndexFormat, offset: BufferAddress, - size: Option, + size: Option, ) { encoder.set_index_buffer(buffer, index_format, offset, size); } diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index dd9334686..83f7311cd 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -6,8 +6,8 @@ use arrayvec::ArrayVec; use thiserror::Error; use wgt::{ error::{ErrorType, WebGpuError}, - BufferAddress, BufferSize, BufferUsages, Color, DynamicOffset, IndexFormat, InstanceFlags, - TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode, + BufferAddress, BufferUsages, Color, DynamicOffset, IndexFormat, InstanceFlags, TextureSelector, + TextureUsages, TextureViewDimension, VertexStepMode, }; use crate::{ @@ -626,7 +626,7 @@ impl VertexState { /// Call `f` for each dirty slot with `(slot_index, buffer, offset, size)` and mark them clean. pub(crate) fn flush(&mut self, mut f: F) where - F: FnMut(u32, &Arc, BufferAddress, BufferSize), + F: FnMut(u32, &Arc, BufferAddress, BufferAddress), { for (i, slot) in self.slots.iter_mut().enumerate() { let Some(slot) = slot.as_mut() else { continue }; @@ -635,13 +635,7 @@ impl VertexState { } slot.is_dirty = false; let size = slot.range.end - slot.range.start; - f( - i as u32, - &slot.buffer, - slot.range.start, - BufferSize::new(size) - .expect("TODO(#3170): empty vertex buffer bindings temporarily unsupported"), - ); + f(i as u32, &slot.buffer, slot.range.start, size); } } } @@ -2669,7 +2663,7 @@ fn set_index_buffer( buffer: Arc, index_format: IndexFormat, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderPassErrorInner> { api_log!("RenderPass::set_index_buffer {}", buffer.error_ident()); @@ -2690,24 +2684,28 @@ fn set_index_buffer( } .into()); } - let binding = buffer - .binding(offset, size, state.pass.base.snatch_guard) + + let range = buffer + .resolve_vertex_or_index_binding_range(offset, size) .map_err(RenderCommandError::from)?; - let end = offset + binding.size.get(); - state.index.update_buffer(offset..end, index_format); + + let raw = buffer.try_raw(state.pass.base.snatch_guard)?; + + state.index.update_buffer(range.clone(), index_format); state.pass.base.buffer_memory_init_actions.extend( buffer.initialization_status.read().create_action( &buffer, - offset..end, + range.clone(), MemoryInitKind::NeedsInitializedMemory, ), ); unsafe { + // SAFETY: The binding range was validated by `resolve_vertex_or_index_binding_range`. hal::DynCommandEncoder::set_index_buffer( state.pass.base.raw_encoder, - binding, + hal::BufferBinding::new_unchecked(raw, range.start, range.end - range.start), index_format, ); } @@ -2721,7 +2719,7 @@ fn set_vertex_buffer( slot: u32, buffer: Option>, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderPassErrorInner> { if let Some(ref buffer) = buffer { api_log!( @@ -2748,10 +2746,9 @@ fn set_vertex_buffer( if !offset.is_multiple_of(wgt::VERTEX_ALIGNMENT) { return Err(RenderCommandError::UnalignedVertexBuffer { slot, offset }.into()); } - let binding_size = buffer - .resolve_binding_size(offset, size) + let range = buffer + .resolve_vertex_or_index_binding_range(offset, size) .map_err(RenderCommandError::from)?; - let buffer_range = offset..(offset + binding_size.get()); state .pass @@ -2762,14 +2759,14 @@ fn set_vertex_buffer( state.pass.base.buffer_memory_init_actions.extend( buffer.initialization_status.read().create_action( &buffer, - buffer_range.clone(), + range.clone(), MemoryInitKind::NeedsInitializedMemory, ), ); state .vertex - .set_buffer(slot as usize, buffer, buffer_range.clone()); + .set_buffer(slot as usize, buffer, range.clone()); if let Some(pipeline) = state.pipeline.as_ref() { state.vertex.update_limits(&pipeline.vertex_steps); } @@ -2783,14 +2780,17 @@ fn set_vertex_buffer( ) .into()); } - if let Some(size) = size { - return Err(RenderCommandError::from( - crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero { - slot, - size: size.get(), - }, - ) - .into()); + match size { + Some(size) if size != 0 => { + return Err(RenderCommandError::from( + crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero { + slot, + size, + }, + ) + .into()); + } + _ => {} } state.vertex.clear_buffer(slot as usize); @@ -3540,7 +3540,7 @@ impl Global { buffer_id: id::BufferId, index_format: IndexFormat, offset: BufferAddress, - size: Option, + size: Option, ) -> Result<(), PassStateError> { let scope = PassErrorScope::SetIndexBuffer; let base = pass_base!(pass, scope); @@ -3561,7 +3561,7 @@ impl Global { slot: u32, buffer_id: Option, offset: BufferAddress, - size: Option, + size: Option, ) -> Result<(), PassStateError> { let scope = PassErrorScope::SetVertexBuffer; let base = pass_base!(pass, scope); diff --git a/wgpu-core/src/command/render_command.rs b/wgpu-core/src/command/render_command.rs index 2661450fd..ab4671c57 100644 --- a/wgpu-core/src/command/render_command.rs +++ b/wgpu-core/src/command/render_command.rs @@ -1,4 +1,4 @@ -use wgt::{BufferAddress, BufferSize, Color}; +use wgt::{BufferAddress, Color}; use super::{DrawCommandFamily, Rect}; #[cfg(feature = "serde")] @@ -23,13 +23,13 @@ pub enum RenderCommand { buffer: R::Buffer, index_format: wgt::IndexFormat, offset: BufferAddress, - size: Option, // optional in encoder; must be `Some` in a finished render bundle + size: Option, // optional in encoder; must be `Some` in a finished render bundle }, SetVertexBuffer { slot: u32, buffer: Option, offset: BufferAddress, - size: Option, // optional in encoder; must be `Some` in a finished render bundle + size: Option, // optional in encoder; must be `Some` in a finished render bundle }, SetBlendConstant(Color), SetStencilReference(u32), diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 839202d95..08432c607 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -1083,18 +1083,21 @@ impl Device { // The great thing about buffer sizes is there are so many to choose from! // - The application may request an arbitrary byte-aligned size. - // - We add an extra byte if it's a vertex or index buffer so that we can simulate - // binding an empty range at the end of the buffer, which Vulkan does not natively - // allow. - // - The overall buffer size must generally be a non-zero multiple of - // COPY_BUFFER_ALIGNMENT (4), but in special cases an additional platform-dependent - // requirement may apply (e.g. 256 for D3D12 constant buffers). + // - If the buffer supports usage as a vertex or index buffer, we must ensure there + // is a naturally aligned block of 4B at the end of the buffer. Zero-size bindings + // are not supported by hal and are redirected to this block by + // `resolve_vertex_or_index_binding_range`. + // - The overall buffer size must be a non-zero multiple of COPY_BUFFER_ALIGNMENT (4). + // In some cases additional platform-dependent requirements may apply. The actual + // allocated size of the buffer is returned by hal along with the buffer object from + // `create_buffer`. `wgpu-core` is responsible for ensuring that any region of the + // buffer, including hal-added padding, is initialized before it may be accessed. // - // Because initialization operates at multiples of COPY_BUFFER_ALIGNMENT, and - // initialization tracking will never determine that it is necessary to initialize a - // region outside the application-visible range, round the tracked initialization range - // down to a multiple of COPY_BUFFER_ALIGNMENT (tail_start), and eagerly zero-initialize - // from there to the buffer's true end offset. + // Because buffer writes for initialization operate at multiples of COPY_BUFFER_ALIGNMENT, + // and because initialization tracking will never determine that it is necessary to + // initialize a region outside the application-visible range, round the tracked + // initialization range down to a multiple of COPY_BUFFER_ALIGNMENT (tail_start), and + // eagerly zero-initialize from there to the buffer's true end. let padded_size = if desc.size == 0 { wgt::COPY_BUFFER_ALIGNMENT @@ -1102,9 +1105,10 @@ impl Device { .usage .intersects(wgt::BufferUsages::VERTEX | wgt::BufferUsages::INDEX) { - desc.size + 1 + // We require 4B of padding with 4B alignment. See above. + align_to(desc.size, wgt::COPY_BUFFER_ALIGNMENT) + wgt::COPY_BUFFER_ALIGNMENT } else { - desc.size + align_to(desc.size, wgt::COPY_BUFFER_ALIGNMENT) }; let tail_start = desc.size & !(wgt::COPY_BUFFER_ALIGNMENT - 1); diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 5fe368262..cc5722ad6 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -11,6 +11,7 @@ use smallvec::SmallVec; use thiserror::Error; use wgt::{ error::{ErrorType, WebGpuError}, + math::align_to, TextureSelector, }; @@ -523,13 +524,11 @@ impl Buffer { /// /// If the binding would overflow the buffer, then an error is returned. /// - /// Zero-size bindings are permitted here for historical reasons. Although - /// zero-size bindings are permitted by WebGPU, they are not permitted by - /// some backends. See [`Buffer::binding`] and - /// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). - pub fn resolve_binding_size< - S: Copy + Into + TryFrom, - >( + /// `S` is `wgt::BufferSize` (`NonZeroU64`) when called from [`Buffer::binding`] + /// for a storage or uniform buffer binding. `S` is `wgt::BufferAddress` (`u64`) + /// when called from `resolve_vertex_or_index_binding_range` for a vertex or + /// index buffer binding. + fn resolve_binding_size + TryFrom>( &self, offset: wgt::BufferAddress, binding_size: Option, @@ -568,26 +567,44 @@ impl Buffer { } } + /// Resolve the binding range for a vertex or index buffer. + /// + /// This function is for vertex and index buffer bindings, which WebGPU + /// allows to have zero size. For storage and uniform buffer bindings, + /// which must have non-zero size, use [`Buffer::binding`]. + /// + /// Returns an error if the binding would overflow the buffer. + pub fn resolve_vertex_or_index_binding_range( + &self, + offset: wgt::BufferAddress, + size: Option, + ) -> Result, BindingError> { + let resolved_size = self.resolve_binding_size(offset, size)?; + if resolved_size != 0 { + Ok(offset..offset + resolved_size) + } else { + // Relocate zero-size binding to end of buffer, because hal does not support + // zero-size bindings (ignores end offsets). `create_buffer` must have + // ensured sufficient padding. + const _: () = { + assert!(wgt::VERTEX_ALIGNMENT == wgt::COPY_BUFFER_ALIGNMENT); + }; + let target = align_to(self.size, wgt::VERTEX_ALIGNMENT); + Ok(target..target) + } + } + /// Create a new [`hal::BufferBinding`] for the buffer with `offset` and /// `binding_size`. /// /// If `binding_size` is `None`, then the remainder of the buffer starting /// from `offset` is used. /// - /// If the binding would overflow the buffer, then an error is returned. + /// Returns an error if the binding would overflow the buffer. /// - /// A zero-size binding at the end of the buffer is permitted here for historical reasons. Although - /// zero-size bindings are permitted by WebGPU, they are not permitted by - /// some backends. The zero-size binding need to be quashed or remapped to a - /// non-zero size, either universally in wgpu-core, or in specific backends - /// that do not support them. See - /// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). - /// - /// Although it seems like it would be simpler and safer to use the resolved - /// size in the returned [`hal::BufferBinding`], doing this (and removing - /// redundant logic in backends to resolve the implicit size) was observed - /// to cause problems in certain CTS tests, so an implicit size - /// specification is preserved in the output. + /// This function is for storage and uniform buffer bindings, which must have + /// non-zero size. For vertex and index buffer bindings, which may have zero + /// size, use [`Buffer::resolve_vertex_or_index_binding_range`]. pub fn binding<'a>( &'a self, offset: wgt::BufferAddress, diff --git a/wgpu-hal/src/dynamic/command.rs b/wgpu-hal/src/dynamic/command.rs index 83762c8ae..b1b1109c5 100644 --- a/wgpu-hal/src/dynamic/command.rs +++ b/wgpu-hal/src/dynamic/command.rs @@ -100,14 +100,14 @@ pub trait DynCommandEncoder: DynResource + core::fmt::Debug { unsafe fn set_index_buffer<'a>( &mut self, - binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferSize>, + binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferAddress>, format: wgt::IndexFormat, ); unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferSize>, + binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferAddress>, ); unsafe fn set_viewport(&mut self, rect: &Rect, depth_range: Range); unsafe fn set_scissor_rect(&mut self, rect: &Rect); @@ -630,7 +630,7 @@ impl DynCommandEncoder for C { unsafe fn set_index_buffer<'a>( &mut self, - binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferSize>, + binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferAddress>, format: wgt::IndexFormat, ) { let binding = binding.expect_downcast(); @@ -640,7 +640,7 @@ impl DynCommandEncoder for C { unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferSize>, + binding: BufferBinding<'a, dyn DynBuffer, wgt::BufferAddress>, ) { let binding = binding.expect_downcast(); unsafe { self.set_vertex_buffer(index, binding) }; diff --git a/wgpu-hal/src/gles/command.rs b/wgpu-hal/src/gles/command.rs index 63a8b5616..ef18e1373 100644 --- a/wgpu-hal/src/gles/command.rs +++ b/wgpu-hal/src/gles/command.rs @@ -1023,7 +1023,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_index_buffer<'a>( &mut self, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, format: wgt::IndexFormat, ) { self.state.index_offset = binding.offset; @@ -1035,7 +1035,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, ) { self.state.dirty_vbuf_mask |= 1 << index; let (_, ref mut vb) = self.state.vertex_buffers[index as usize]; diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 46ba778a7..9f3e6ef2a 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -297,7 +297,7 @@ use core::{ borrow::Borrow, error::Error, fmt, - num::{NonZeroU32, NonZeroU64}, + num::NonZeroU32, ops::{Range, RangeInclusive}, ptr::NonNull, }; @@ -1613,13 +1613,13 @@ pub trait CommandEncoder: WasmNotSendSync + fmt::Debug { unsafe fn set_index_buffer<'a>( &mut self, - binding: BufferBinding<'a, ::Buffer, wgt::BufferSize>, + binding: BufferBinding<'a, ::Buffer, wgt::BufferAddress>, format: wgt::IndexFormat, ); unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: BufferBinding<'a, ::Buffer, wgt::BufferSize>, + binding: BufferBinding<'a, ::Buffer, wgt::BufferAddress>, ); unsafe fn set_viewport(&mut self, rect: &Rect, depth_range: Range); unsafe fn set_scissor_rect(&mut self, rect: &Rect); @@ -2204,16 +2204,18 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// /// ## Zero-length bindings /// -/// Some back ends cannot tolerate zero-length regions; for example, see -/// [VUID-VkDescriptorBufferInfo-offset-00340][340] and +/// Some platform APIs do not accept zero-length regions; for example, see +/// [VUID-VkDescriptorBufferInfo-offset-00340][340], /// [VUID-VkDescriptorBufferInfo-range-00341][341], or the -/// documentation for GLES's [glBindBufferRange][bbr]. This documentation -/// previously stated that a `BufferBinding` must have `offset` strictly less -/// than the size of the buffer, but this restriction was not honored elsewhere -/// in the code, so has been removed. However, it remains the case that -/// some backends do not support zero-length bindings, so additional -/// logic is needed somewhere to handle this properly. See -/// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). +/// documentation for GLES's [glBindBufferRange][bbr]. For +/// [VUID-VkCmdBindVertexBuffers-pOffsets-00626][626], no size is specified, +/// the binding extends from the offset to the end of the buffer, and the offset +/// must be strictly less than the buffer size. +/// +/// WebGPU does not allow zero-length storage/uniform buffer bindings, but does +/// allow zero-length vertex/index buffer bindings. `wgpu-core` ensures that +/// buffers supporting vertex/index usage have 4B of naturally-aligned padding at +/// the end, to enable simulating a zero-length binding at the end of the buffer. /// /// [`offset`]: BufferBinding::offset /// [`size`]: BufferBinding::size @@ -2221,6 +2223,7 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// [`Uniform`]: wgt::BufferBindingType::Uniform /// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340 /// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341 +/// [626]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdBindVertexBuffers-pOffsets-00626 /// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml /// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec #[derive(Debug)] @@ -2252,34 +2255,6 @@ impl Clone for BufferBinding<'_, B, S> { } } -/// Temporary convenience trait to let us call `.get()` on `u64`s in code that -/// really wants to be using `NonZeroU64`. -/// TODO(): remove this -pub trait ShouldBeNonZeroExt { - fn get(&self) -> u64; -} - -impl ShouldBeNonZeroExt for NonZeroU64 { - fn get(&self) -> u64 { - NonZeroU64::get(*self) - } -} - -impl ShouldBeNonZeroExt for u64 { - fn get(&self) -> u64 { - *self - } -} - -impl ShouldBeNonZeroExt for Option { - fn get(&self) -> u64 { - match *self { - Some(non_zero) => non_zero.get(), - None => 0, - } - } -} - impl<'a, B: DynBuffer + ?Sized, S> BufferBinding<'a, B, S> { /// Construct a `BufferBinding` with the given contents. /// diff --git a/wgpu-hal/src/metal/command.rs b/wgpu-hal/src/metal/command.rs index f2e33ed5c..b78a8e80a 100644 --- a/wgpu-hal/src/metal/command.rs +++ b/wgpu-hal/src/metal/command.rs @@ -1364,7 +1364,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_index_buffer<'a>( &mut self, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, format: wgt::IndexFormat, ) { let (stride, raw_type) = conv::map_index_format(format); @@ -1379,7 +1379,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, ) { let buffer_index = VERTEX_BUFFER_SLOT_START + index; let encoder = self.state.render.as_ref().unwrap(); @@ -1391,14 +1391,16 @@ impl crate::CommandEncoder for super::CommandEncoder { ) }; - // TODO(#3170): temporary - //if let Some(size) = NonZeroU64::new(binding.size) { - self.state - .vertex_buffer_size_map - .insert(buffer_index, binding.size); - //} else { - // self.state.vertex_buffer_size_map.remove(&buffer_index); - //} + // The size map uses `NonZeroU64` mostly because it did so in the past when + // `hal::BufferBinding` tried to disallow zero-length bindings. Zero-length bindings + // are valid for vertex buffers, so there isn't really a significance of a + // zero-length buffer being removed from the map (vs. the map storing `u64`). + if let Some(size) = NonZeroU64::new(binding.size) { + self.state.vertex_buffer_size_map.insert(buffer_index, size); + } else { + // `make_sizes_buffer_update` uses zero for buffers that are not in the map. + self.state.vertex_buffer_size_map.remove(&buffer_index); + } if let Some((index, sizes)) = self .state diff --git a/wgpu-hal/src/noop/command.rs b/wgpu-hal/src/noop/command.rs index 7620ca22b..840c5b414 100644 --- a/wgpu-hal/src/noop/command.rs +++ b/wgpu-hal/src/noop/command.rs @@ -172,14 +172,14 @@ impl crate::CommandEncoder for CommandBuffer { unsafe fn set_index_buffer<'a>( &mut self, - binding: crate::BufferBinding<'a, Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, Buffer, wgt::BufferAddress>, format: wgt::IndexFormat, ) { } unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: crate::BufferBinding<'a, Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, Buffer, wgt::BufferAddress>, ) { } unsafe fn set_viewport(&mut self, rect: &crate::Rect, depth_range: Range) {} diff --git a/wgpu-hal/src/vulkan/command.rs b/wgpu-hal/src/vulkan/command.rs index 4bce740e7..20bfcf294 100644 --- a/wgpu-hal/src/vulkan/command.rs +++ b/wgpu-hal/src/vulkan/command.rs @@ -995,7 +995,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_index_buffer<'a>( &mut self, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, format: wgt::IndexFormat, ) { unsafe { @@ -1010,7 +1010,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_vertex_buffer<'a>( &mut self, index: u32, - binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferSize>, + binding: crate::BufferBinding<'a, super::Buffer, wgt::BufferAddress>, ) { let vk_buffers = [binding.buffer.raw]; let vk_offsets = [binding.offset]; diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 3f1c7e661..740a81242 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -669,10 +669,6 @@ impl<'a> BufferSlice<'a> { pub fn size(&self) -> BufferAddress { self.size } - - pub(crate) fn size_expect_nonzero(&self) -> BufferSize { - BufferSize::new(self.size).expect("buffer slice can not be empty") - } } impl<'a> TryFrom> for crate::BufferBinding<'a> { diff --git a/wgpu/src/api/render_bundle_encoder.rs b/wgpu/src/api/render_bundle_encoder.rs index 041b67cac..f243d24b7 100644 --- a/wgpu/src/api/render_bundle_encoder.rs +++ b/wgpu/src/api/render_bundle_encoder.rs @@ -97,8 +97,7 @@ impl<'a> RenderBundleEncoder<'a> { &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here - Some(buffer_slice.size_expect_nonzero()), + Some(buffer_slice.size), ); } @@ -126,8 +125,7 @@ impl<'a> RenderBundleEncoder<'a> { slot, Some(&buffer_slice.buffer.inner), buffer_slice.offset, - // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here - Some(buffer_slice.size_expect_nonzero()), + Some(buffer_slice.size), ); } else { self.inner.set_vertex_buffer(slot, None, 0, None); diff --git a/wgpu/src/api/render_pass.rs b/wgpu/src/api/render_pass.rs index 719cbbd0b..033027f37 100644 --- a/wgpu/src/api/render_pass.rs +++ b/wgpu/src/api/render_pass.rs @@ -109,8 +109,7 @@ impl RenderPass<'_> { &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here - Some(buffer_slice.size_expect_nonzero()), + Some(buffer_slice.size), ); } @@ -140,8 +139,7 @@ impl RenderPass<'_> { slot, Some(&buffer_slice.buffer.inner), buffer_slice.offset, - // TODO(https://github.com/gfx-rs/wgpu/issues/3170): Empty slices should be supported here - Some(buffer_slice.size_expect_nonzero()), + Some(buffer_slice.size), ); } else { self.inner.set_vertex_buffer(slot, None, 0, None); diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index 9121d3599..b79925d54 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -3497,7 +3497,7 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { buffer: &dispatch::DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.as_webgpu(); let index_format = map_index_format(index_format); @@ -3507,7 +3507,7 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { &buffer.inner, index_format, offset as f64, - size.get() as f64, + size as f64, ); } else { self.inner @@ -3520,17 +3520,13 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { slot: u32, buffer: Option<&dispatch::DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.map(|buffer| &buffer.as_webgpu().inner); if let Some(size) = size { - self.inner.set_vertex_buffer_with_f64_and_f64( - slot, - buffer, - offset as f64, - size.get() as f64, - ); + self.inner + .set_vertex_buffer_with_f64_and_f64(slot, buffer, offset as f64, size as f64); } else { self.inner .set_vertex_buffer_with_f64(slot, buffer, offset as f64); @@ -3788,7 +3784,7 @@ impl dispatch::RenderBundleEncoderInterface for WebRenderBundleEncoder { buffer: &dispatch::DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.as_webgpu(); let index_format = map_index_format(index_format); @@ -3798,7 +3794,7 @@ impl dispatch::RenderBundleEncoderInterface for WebRenderBundleEncoder { &buffer.inner, index_format, offset as f64, - size.get() as f64, + size as f64, ); } else { self.inner @@ -3811,17 +3807,13 @@ impl dispatch::RenderBundleEncoderInterface for WebRenderBundleEncoder { slot: u32, buffer: Option<&dispatch::DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.map(|buffer| &buffer.as_webgpu().inner); if let Some(size) = size { - self.inner.set_vertex_buffer_with_f64_and_f64( - slot, - buffer, - offset as f64, - size.get() as f64, - ); + self.inner + .set_vertex_buffer_with_f64_and_f64(slot, buffer, offset as f64, size as f64); } else { self.inner .set_vertex_buffer_with_f64(slot, buffer, offset as f64); diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index fce2ee5c9..204a24a3d 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -3223,7 +3223,7 @@ impl dispatch::RenderPassInterface for CoreRenderPass { buffer: &dispatch::DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.as_core(); @@ -3248,7 +3248,7 @@ impl dispatch::RenderPassInterface for CoreRenderPass { slot: u32, buffer: Option<&dispatch::DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.map(|buffer| buffer.as_core().id); @@ -3818,7 +3818,7 @@ impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder { buffer: &dispatch::DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.as_core(); @@ -3831,7 +3831,7 @@ impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder { slot: u32, buffer: Option<&dispatch::DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ) { let buffer = buffer.map(|buffer| buffer.as_core().id); diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index 2f8031ee8..4067be8c1 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -433,14 +433,14 @@ pub trait RenderPassInterface: CommonTraits + Drop { buffer: &DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ); fn set_vertex_buffer( &mut self, slot: u32, buffer: Option<&DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ); fn set_immediates(&mut self, offset: u32, data: &[u8]); fn set_blend_constant(&mut self, color: crate::Color); @@ -544,14 +544,14 @@ pub trait RenderBundleEncoderInterface: CommonTraits { buffer: &DispatchBuffer, index_format: crate::IndexFormat, offset: crate::BufferAddress, - size: Option, + size: Option, ); fn set_vertex_buffer( &mut self, slot: u32, buffer: Option<&DispatchBuffer>, offset: crate::BufferAddress, - size: Option, + size: Option, ); fn set_immediates(&mut self, offset: u32, data: &[u8]);