Add support for gaps in bind group layouts & update relevant validation (#9034)

* [wgpu-core] add support for optional BG & BGL entries

* [wgpu] allow gaps in bind group layouts

And allow unbinding in the web backend.

* adapt tests

* add changelog entry

* [wgpu] remove generic from `PipelineLayoutDescriptor`
This commit is contained in:
Teodor Tanasoaia authored and GitHub committed 2026-02-25 19:47:36 +01:00
1 parent aad2a00f4d
commit e114d2f0a7
90 files changed
+567 -397

No files matched your search

+80 -21
View File
@@ -690,7 +690,7 @@ pub struct BindGroupLayoutDescriptor<'a> {
/// Used by [`BindGroupLayout`]. It indicates whether the BGL must be
/// used with a specific pipeline. This constraint only happens when
/// the BGLs have been derived from a pipeline without a layout.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) enum ExclusivePipeline {
None,
Render(Weak<RenderPipeline>),
@@ -719,10 +719,17 @@ impl fmt::Display for ExclusivePipeline {
}
}
#[derive(Debug)]
pub enum RawBindGroupLayout {
Owning(ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>),
/// The empty BGL was created by the device and will be destroyed by the device.
RefDeviceEmptyBGL,
}
/// Bind group layout.
#[derive(Debug)]
pub struct BindGroupLayout {
pub(crate) raw: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
pub(crate) raw: RawBindGroupLayout,
pub(crate) device: Arc<Device>,
pub(crate) entries: bgl::EntryMap,
/// It is very important that we know if the bind group comes from the BGL pool.
@@ -744,10 +751,15 @@ impl Drop for BindGroupLayout {
if matches!(self.origin, bgl::Origin::Pool) {
self.device.bgl_pool.remove(&self.entries);
}
// 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) };
unsafe {
self.device.raw().destroy_bind_group_layout(raw);
match self.raw {
RawBindGroupLayout::Owning(ref mut raw) => {
// SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
let raw = unsafe { ManuallyDrop::take(raw) };
unsafe {
self.device.raw().destroy_bind_group_layout(raw);
}
}
RawBindGroupLayout::RefDeviceEmptyBGL => {}
}
}
}
@@ -759,7 +771,24 @@ crate::impl_storage_item!(BindGroupLayout);
impl BindGroupLayout {
pub(crate) fn raw(&self) -> &dyn hal::DynBindGroupLayout {
self.raw.as_ref()
match &self.raw {
RawBindGroupLayout::Owning(raw) => raw.as_ref(),
RawBindGroupLayout::RefDeviceEmptyBGL => self.device.empty_bgl.as_ref(),
}
}
fn empty(device: &Arc<Device>) -> Arc<Self> {
let exclusive_pipeline = crate::OnceCellOrLock::new();
exclusive_pipeline.set(ExclusivePipeline::None).unwrap();
Arc::new(Self {
raw: RawBindGroupLayout::RefDeviceEmptyBGL,
device: device.clone(),
entries: bgl::EntryMap::default(),
origin: bgl::Origin::Derived,
exclusive_pipeline,
binding_count_validator: BindingTypeMaxCountValidator::default(),
label: String::new(),
})
}
}
@@ -785,6 +814,8 @@ pub enum CreatePipelineLayoutError {
TooManyGroups { actual: usize, max: usize },
#[error(transparent)]
InvalidResource(#[from] InvalidResourceError),
#[error("Bind group layout at index {index} has an exclusive pipeline: {pipeline}")]
BglHasExclusivePipeline { index: usize, pipeline: String },
}
impl WebGpuError for CreatePipelineLayoutError {
@@ -796,7 +827,8 @@ impl WebGpuError for CreatePipelineLayoutError {
Self::TooManyBindings(e) => e,
Self::MisalignedImmediateSize { .. }
| Self::ImmediateRangeTooLarge { .. }
| Self::TooManyGroups { .. } => return ErrorType::Validation,
| Self::TooManyGroups { .. }
| Self::BglHasExclusivePipeline { .. } => return ErrorType::Validation,
};
e.webgpu_error_type()
}
@@ -832,8 +864,8 @@ impl WebGpuError for ImmediateUploadError {
#[cfg_attr(feature = "serde", serde(bound = "BGL: Serialize"))]
pub struct PipelineLayoutDescriptor<'a, BGL = BindGroupLayoutId>
where
[BGL]: ToOwned,
<[BGL] as ToOwned>::Owned: fmt::Debug,
[Option<BGL>]: ToOwned,
<[Option<BGL>] as ToOwned>::Owned: fmt::Debug,
{
/// Debug label of the pipeline layout.
///
@@ -843,9 +875,9 @@ where
/// "set = 0", second entry will provide all the bindings for "set = 1" etc.
#[cfg_attr(
feature = "serde",
serde(bound(deserialize = "<[BGL] as ToOwned>::Owned: Deserialize<'de>"))
serde(bound(deserialize = "<[Option<BGL>] as ToOwned>::Owned: Deserialize<'de>"))
)]
pub bind_group_layouts: Cow<'a, [BGL]>,
pub bind_group_layouts: Cow<'a, [Option<BGL>]>,
/// The number of bytes of immediate data that are allocated for use
/// in the shader. The `var<immediate>`s in the shader attached to
/// this pipeline must be equal or smaller than this size.
@@ -864,7 +896,7 @@ pub struct PipelineLayout {
pub(crate) device: Arc<Device>,
/// The `label` from the descriptor used to create the resource.
pub(crate) label: String,
pub(crate) bind_group_layouts: ArrayVec<Arc<BindGroupLayout>, { hal::MAX_BIND_GROUPS }>,
pub(crate) bind_group_layouts: ArrayVec<Option<Arc<BindGroupLayout>>, { hal::MAX_BIND_GROUPS }>,
pub(crate) immediate_size: u32,
}
@@ -884,11 +916,33 @@ impl PipelineLayout {
self.raw.as_ref()
}
pub(crate) fn get_binding_maps(&self) -> ArrayVec<&bgl::EntryMap, { hal::MAX_BIND_GROUPS }> {
self.bind_group_layouts
.iter()
.map(|bgl| &bgl.entries)
.collect()
pub fn get_bind_group_layout(
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
let max_bind_groups = self.device.limits.max_bind_groups;
if index >= max_bind_groups {
return Err(GetBindGroupLayoutError::IndexOutOfRange {
index,
max: max_bind_groups,
});
}
Ok(self
.bind_group_layouts
.get(index as usize)
.cloned()
.flatten()
.unwrap_or_else(|| BindGroupLayout::empty(&self.device)))
}
pub(crate) fn get_bgl_entry(
&self,
group: u32,
binding: u32,
) -> Option<&wgt::BindGroupLayoutEntry> {
let bgl = self.bind_group_layouts.get(group as usize)?;
let bgl = bgl.as_ref()?;
bgl.entries.get(binding)
}
/// Validate immediates match up with expected ranges.
@@ -993,6 +1047,11 @@ pub type ResolvedBindingResource<'a> = BindingResource<
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum BindError {
#[error(
"Dynamic offsets not expected with null bind group at index {group}. However {actual} dynamic offset{s1} were provided.",
s1 = if *.actual >= 2 { "s" } else { "" },
)]
DynamicOffsetCountNotZero { group: u32, actual: usize },
#[error(
"{bind_group} {group} expects {expected} dynamic offset{s0}. However {actual} dynamic offset{s1} were provided.",
s0 = if *.expected >= 2 { "s" } else { "" },
@@ -1201,8 +1260,8 @@ crate::impl_trackable!(BindGroup);
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum GetBindGroupLayoutError {
#[error("Invalid group index {0}")]
InvalidGroupIndex(u32),
#[error("Bind group layout index {index} is greater than the device's configured `max_bind_groups` limit {max}")]
IndexOutOfRange { index: u32, max: u32 },
#[error(transparent)]
InvalidResource(#[from] InvalidResourceError),
}
@@ -1210,7 +1269,7 @@ pub enum GetBindGroupLayoutError {
impl WebGpuError for GetBindGroupLayoutError {
fn webgpu_error_type(&self) -> ErrorType {
match self {
Self::InvalidGroupIndex(_) => ErrorType::Validation,
Self::IndexOutOfRange { .. } => ErrorType::Validation,
Self::InvalidResource(e) => e.webgpu_error_type(),
}
}
+81 -62
View File
@@ -1,5 +1,3 @@
use core::{iter::zip, ops::Range};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use thiserror::Error;
@@ -16,9 +14,8 @@ mod compat {
sync::{Arc, Weak},
vec::Vec,
};
use core::{num::NonZeroU32, ops::Range};
use core::num::NonZeroU32;
use arrayvec::ArrayVec;
use thiserror::Error;
use wgt::{BindingType, ShaderStages};
@@ -44,12 +41,13 @@ mod compat {
}
impl Entry {
fn empty() -> Self {
const fn empty() -> Self {
Self {
assigned: None,
expected: None,
}
}
fn is_active(&self) -> bool {
self.assigned.is_some() && self.expected.is_some()
}
@@ -62,14 +60,10 @@ mod compat {
false
}
} else {
true
false
}
}
fn is_incompatible(&self) -> bool {
self.expected.is_none() || !self.is_valid()
}
fn check(&self) -> Result<(), Error> {
if let Some(expected_bgl) = self.expected.as_ref() {
if let Some(assigned_bgl) = self.assigned.as_ref() {
@@ -191,64 +185,69 @@ mod compat {
}
}
#[derive(Debug, Default)]
#[derive(Debug)]
pub(super) struct BoundBindGroupLayouts {
entries: ArrayVec<Entry, { hal::MAX_BIND_GROUPS }>,
entries: [Entry; hal::MAX_BIND_GROUPS],
rebind_start: usize,
}
impl BoundBindGroupLayouts {
pub fn new() -> Self {
Self {
entries: (0..hal::MAX_BIND_GROUPS).map(|_| Entry::empty()).collect(),
entries: [const { Entry::empty() }; hal::MAX_BIND_GROUPS],
rebind_start: 0,
}
}
pub fn num_valid_entries(&self) -> usize {
// find first incompatible entry
self.entries
.iter()
.position(|e| e.is_incompatible())
.unwrap_or(self.entries.len())
}
/// Get the range of entries that needs to be rebound, and clears it.
pub fn take_rebind_range(&mut self) -> Range<usize> {
let end = self.num_valid_entries();
/// Takes the start index of the bind group range to be rebound, and clears it.
pub fn take_rebind_start_index(&mut self) -> usize {
let start = self.rebind_start;
self.rebind_start = end;
start..end.max(start)
self.rebind_start = self.entries.len();
start
}
pub fn update_start_index(&mut self, start_index: usize) {
pub fn update_rebind_start_index(&mut self, start_index: usize) {
self.rebind_start = self.rebind_start.min(start_index);
}
pub fn update_expectations(&mut self, expectations: &[Arc<BindGroupLayout>]) {
let start_index = self
pub fn update_expectations(&mut self, expectations: &[Option<Arc<BindGroupLayout>>]) {
let mut rebind_start_index = None;
for (i, (e, new_expected_bgl)) in self
.entries
.iter()
.zip(expectations)
.position(|(e, expect)| {
e.expected.is_none() || !e.expected.as_ref().unwrap().is_equal(expect)
})
.unwrap_or(expectations.len());
for (e, expect) in self.entries[start_index..]
.iter_mut()
.zip(expectations[start_index..].iter())
.zip(expectations.iter().chain(core::iter::repeat(&None)))
.enumerate()
{
e.expected = Some(expect.clone());
let (must_set, must_rebind) = match (&mut e.expected, new_expected_bgl) {
(None, None) => (false, false),
(None, Some(_)) => (true, true),
(Some(_), None) => (true, false),
(Some(old_expected_bgl), Some(new_expected_bgl)) => {
let is_different = !old_expected_bgl.is_equal(new_expected_bgl);
(is_different, is_different)
}
};
if must_set {
e.expected = new_expected_bgl.clone();
}
if must_rebind && rebind_start_index.is_none() {
rebind_start_index = Some(i);
}
}
for e in self.entries[expectations.len()..].iter_mut() {
e.expected = None;
if let Some(rebind_start_index) = rebind_start_index {
self.update_rebind_start_index(rebind_start_index);
}
self.update_start_index(start_index);
}
pub fn assign(&mut self, index: usize, value: Arc<BindGroupLayout>) {
self.entries[index].assigned = Some(value);
self.update_start_index(index);
self.update_rebind_start_index(index);
}
pub fn clear(&mut self, index: usize) {
self.entries[index].assigned = None;
}
pub fn list_active(&self) -> impl Iterator<Item = usize> + '_ {
@@ -258,6 +257,13 @@ mod compat {
.filter_map(|(i, e)| if e.is_active() { Some(i) } else { None })
}
pub fn list_valid(&self) -> impl Iterator<Item = usize> + '_ {
self.entries
.iter()
.enumerate()
.filter_map(|(i, e)| if e.is_valid() { Some(i) } else { None })
}
#[allow(clippy::result_large_err)]
pub fn get_invalid(&self) -> Result<(), (usize, Error)> {
for (index, entry) in self.entries.iter().enumerate() {
@@ -295,13 +301,13 @@ struct LateBufferBinding {
}
#[derive(Debug, Default)]
pub(super) struct EntryPayload {
pub(super) group: Option<Arc<BindGroup>>,
pub(super) dynamic_offsets: Vec<wgt::DynamicOffset>,
struct EntryPayload {
group: Option<Arc<BindGroup>>,
dynamic_offsets: Vec<wgt::DynamicOffset>,
late_buffer_bindings: Vec<LateBufferBinding>,
/// Since `LateBufferBinding` may contain information about the bindings
/// not used by the pipeline, we need to know when to stop validating.
pub(super) late_bindings_effective_count: usize,
late_bindings_effective_count: usize,
}
impl EntryPayload {
@@ -313,7 +319,7 @@ impl EntryPayload {
}
}
#[derive(Debug, Default)]
#[derive(Debug)]
pub(super) struct Binder {
pub(super) pipeline_layout: Option<Arc<PipelineLayout>>,
manager: compat::BoundBindGroupLayouts,
@@ -383,7 +389,7 @@ impl Binder {
if let Some(old) = old {
// root constants are the base compatibility property
if old.immediate_size != new.immediate_size {
self.manager.update_start_index(0);
self.manager.update_rebind_start_index(0);
}
}
@@ -431,31 +437,44 @@ impl Binder {
self.manager.assign(index, bind_group.layout.clone());
}
/// Get the range of entries that needs to be rebound, and clears it.
pub(super) fn take_rebind_range(&mut self) -> Range<usize> {
self.manager.take_rebind_range()
pub(super) fn clear_group(&mut self, index: usize) {
self.payloads[index].reset();
self.manager.clear(index);
}
pub(super) fn entries(
/// Takes the start index of the bind group range to be rebound, and clears it.
pub(super) fn take_rebind_start_index(&mut self) -> usize {
self.manager.take_rebind_start_index()
}
pub(super) fn list_valid_with_start(
&self,
range: Range<usize>,
) -> impl ExactSizeIterator<Item = (usize, &'_ EntryPayload)> + Clone + '_ {
let payloads = &self.payloads[range.clone()];
zip(range, payloads)
start: usize,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
let payloads = &self.payloads;
self.manager
.list_valid()
.filter(move |i| *i >= start)
.map(move |index| {
(
index,
payloads[index].group.as_ref().unwrap(),
payloads[index].dynamic_offsets.as_slice(),
)
})
}
pub(super) fn list_active<'a>(&'a self) -> impl Iterator<Item = &'a Arc<BindGroup>> + 'a {
pub(super) fn list_active(&self) -> impl Iterator<Item = &Arc<BindGroup>> + '_ {
let payloads = &self.payloads;
self.manager
.list_active()
.map(move |index| payloads[index].group.as_ref().unwrap())
}
pub(super) fn list_valid<'a>(&'a self) -> impl Iterator<Item = (usize, &'a EntryPayload)> + 'a {
self.payloads
.iter()
.take(self.manager.num_valid_entries())
.enumerate()
pub(super) fn list_valid(
&self,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
self.list_valid_with_start(0)
}
pub(super) fn check_compatibility<T: Labeled>(
+40 -41
View File
@@ -522,17 +522,6 @@ fn set_bind_group(
num_dynamic_offsets: usize,
bind_group_id: Option<id::Id<id::markers::BindGroup>>,
) -> Result<(), RenderBundleErrorInner> {
if bind_group_id.is_none() {
// TODO: do appropriate cleanup for null bind_group.
return Ok(());
}
let bind_group_id = bind_group_id.unwrap();
let bind_group = bind_group_guard.get(bind_group_id).get()?;
bind_group.same_device(&state.device)?;
let max_bind_groups = state.device.limits.max_bind_groups;
if index >= max_bind_groups {
return Err(
@@ -549,14 +538,31 @@ fn set_bind_group(
state.next_dynamic_offset = offsets_range.end;
let offsets = &dynamic_offsets[offsets_range.clone()];
bind_group.validate_dynamic_bindings(index, offsets)?;
let bind_group = bind_group_id.map(|id| bind_group_guard.get(id));
unsafe { state.trackers.merge_bind_group(&bind_group.used)? };
let bind_group = state.trackers.bind_groups.insert_single(bind_group);
if let Some(bind_group) = bind_group {
let bind_group = bind_group.get()?;
bind_group.same_device(&state.device)?;
bind_group.validate_dynamic_bindings(index, offsets)?;
state
.binder
.assign_group(index as usize, bind_group, offsets);
unsafe { state.trackers.merge_bind_group(&bind_group.used)? };
let bind_group = state.trackers.bind_groups.insert_single(bind_group);
state
.binder
.assign_group(index as usize, bind_group, offsets);
} else {
if !offsets.is_empty() {
return Err(RenderBundleErrorInner::Bind(
BindError::DynamicOffsetCountNotZero {
group: index,
actual: offsets.len(),
},
));
}
state.binder.clear_group(index as usize);
}
Ok(())
}
@@ -977,17 +983,12 @@ impl RenderBundle {
num_dynamic_offsets,
bind_group,
} => {
let mut bg = None;
if bind_group.is_some() {
let bind_group = bind_group.as_ref().unwrap();
let raw_bg = bind_group.try_raw(snatch_guard)?;
bg = Some(raw_bg);
}
let raw_bg = bind_group.as_ref().unwrap().try_raw(snatch_guard)?;
unsafe {
raw.set_bind_group(
pipeline_layout.as_ref().unwrap().raw(),
*index,
bg,
raw_bg,
&offsets[..*num_dynamic_offsets],
)
};
@@ -1435,26 +1436,24 @@ impl State {
///
/// This should be further deduplicated with similar code on render/compute passes.
fn flush_bindings(&mut self) {
let range = self.binder.take_rebind_range();
let entries = self.binder.entries(range);
let start = self.binder.take_rebind_start_index();
let entries = self.binder.list_valid_with_start(start);
self.commands.extend(entries.map(|(i, entry)| {
let bind_group = entry.group.as_ref().unwrap();
self.commands
.extend(entries.map(|(i, bind_group, dynamic_offsets)| {
self.buffer_memory_init_actions
.extend_from_slice(&bind_group.used_buffer_ranges);
self.texture_memory_init_actions
.extend_from_slice(&bind_group.used_texture_ranges);
self.buffer_memory_init_actions
.extend_from_slice(&bind_group.used_buffer_ranges);
self.texture_memory_init_actions
.extend_from_slice(&bind_group.used_texture_ranges);
self.flat_dynamic_offsets.extend_from_slice(dynamic_offsets);
self.flat_dynamic_offsets
.extend_from_slice(&entry.dynamic_offsets);
ArcRenderCommand::SetBindGroup {
index: i.try_into().unwrap(),
bind_group: Some(bind_group.clone()),
num_dynamic_offsets: entry.dynamic_offsets.len(),
}
}));
ArcRenderCommand::SetBindGroup {
index: i.try_into().unwrap(),
bind_group: Some(bind_group.clone()),
num_dynamic_offsets: dynamic_offsets.len(),
}
}));
}
fn vertex_buffer_sizes(&self) -> impl Iterator<Item = Option<wgt::BufferAddress>> + '_ {
+10 -13
View File
@@ -933,7 +933,7 @@ fn dispatch_indirect(
state.pass.base.raw_encoder.set_bind_group(
params.pipeline_layout,
0,
Some(params.dst_bind_group),
params.dst_bind_group,
&[],
);
}
@@ -941,14 +941,12 @@ fn dispatch_indirect(
state.pass.base.raw_encoder.set_bind_group(
params.pipeline_layout,
1,
Some(
buffer
.indirect_validation_bind_groups
.get(state.pass.base.snatch_guard)
.unwrap()
.dispatch
.as_ref(),
),
buffer
.indirect_validation_bind_groups
.get(state.pass.base.snatch_guard)
.unwrap()
.dispatch
.as_ref(),
&[params.aligned_offset as u32],
);
}
@@ -1007,15 +1005,14 @@ fn dispatch_indirect(
}
}
for (i, e) in state.pass.binder.list_valid() {
let group = e.group.as_ref().unwrap();
for (i, group, dynamic_offsets) in state.pass.binder.list_valid() {
let raw_bg = group.try_raw(state.pass.base.snatch_guard)?;
unsafe {
state.pass.base.raw_encoder.set_bind_group(
pipeline.layout.raw(),
i as u32,
Some(raw_bg),
&e.dynamic_offsets,
raw_bg,
dynamic_offsets,
);
}
}
+44 -48
View File
@@ -20,7 +20,7 @@ use wgt::DynamicOffset;
#[derive(Clone, Debug, Error)]
#[error(
"Bind group index {index} is greater than the device's requested `max_bind_group` limit {max}"
"Bind group index {index} is greater than the device's configured `max_bind_groups` limit {max}"
)]
pub struct BindGroupIndexOutOfRange {
pub index: u32,
@@ -97,35 +97,42 @@ where
);
state.dynamic_offset_count += num_dynamic_offsets;
let Some(bind_group) = bind_group else {
// TODO: Handle bind_group None.
return Ok(());
};
if let Some(bind_group) = bind_group {
// Add the bind group to the tracker. This is done for both compute and
// render passes, and is used to fail submission of the command buffer if
// any resource in any of the bind groups has been destroyed, whether or
// not the bind group is actually used by the pipeline.
let bind_group = state.base.tracker.bind_groups.insert_single(bind_group);
// Add the bind group to the tracker. This is done for both compute and
// render passes, and is used to fail submission of the command buffer if
// any resource in any of the bind groups has been destroyed, whether or
// not the bind group is actually used by the pipeline.
let bind_group = state.base.tracker.bind_groups.insert_single(bind_group);
bind_group.same_device(device)?;
bind_group.same_device(device)?;
bind_group.validate_dynamic_bindings(index, &state.temp_offsets)?;
bind_group.validate_dynamic_bindings(index, &state.temp_offsets)?;
if merge_bind_groups {
// Merge the bind group's resources into the tracker. We only do this
// for render passes. For compute passes it is done per dispatch in
// [`flush_bindings`].
unsafe {
state.scope.merge_bind_group(&bind_group.used)?;
if merge_bind_groups {
// Merge the bind group's resources into the tracker. We only do this
// for render passes. For compute passes it is done per dispatch in
// [`flush_bindings`].
unsafe {
state.scope.merge_bind_group(&bind_group.used)?;
}
}
}
//Note: stateless trackers are not merged: the lifetime reference
// is held to the bind group itself.
//Note: stateless trackers are not merged: the lifetime reference
// is held to the bind group itself.
state
.binder
.assign_group(index as usize, bind_group, &state.temp_offsets);
state
.binder
.assign_group(index as usize, bind_group, &state.temp_offsets);
} else {
if !state.temp_offsets.is_empty() {
return Err(BindError::DynamicOffsetCountNotZero {
group: index,
actual: state.temp_offsets.len(),
}
.into());
}
state.binder.clear_group(index as usize);
};
Ok(())
}
@@ -135,16 +142,11 @@ where
/// See the compute pass version of `State::flush_bindings` for an explanation
/// of some differences in handling the two types of passes.
pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), DestroyedResourceError> {
let range = state.binder.take_rebind_range();
if range.is_empty() {
return Ok(());
}
let entries = state.binder.entries(range);
for (_, entry) in entries.clone() {
let bind_group = entry.group.as_ref().unwrap();
let start = state.binder.take_rebind_start_index();
let entries = state.binder.list_valid_with_start(start);
let pipeline_layout = state.binder.pipeline_layout.as_ref().unwrap();
for (i, bind_group, dynamic_offsets) in entries {
state.base.buffer_memory_init_actions.extend(
bind_group.used_buffer_ranges.iter().filter_map(|action| {
action
@@ -170,21 +172,15 @@ pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), Destroy
.map(|tlas| crate::ray_tracing::AsAction::UseTlas(tlas.clone()));
state.base.as_actions.extend(used_resource);
}
if let Some(pipeline_layout) = state.binder.pipeline_layout.as_ref() {
for (i, e) in entries {
if let Some(group) = e.group.as_ref() {
let raw_bg = group.try_raw(state.base.snatch_guard)?;
unsafe {
state.base.raw_encoder.set_bind_group(
pipeline_layout.raw(),
i as u32,
Some(raw_bg),
&e.dynamic_offsets,
);
}
}
let raw_bg = bind_group.try_raw(state.base.snatch_guard)?;
unsafe {
state.base.raw_encoder.set_bind_group(
pipeline_layout.raw(),
i as u32,
raw_bg,
dynamic_offsets,
);
}
}
+4 -1
View File
@@ -732,7 +732,10 @@ impl Global {
let bind_group_layouts_guard = hub.bind_group_layouts.read();
desc.bind_group_layouts
.iter()
.map(|bgl_id| bind_group_layouts_guard.get(*bgl_id).get())
.map(|bgl_id| match bgl_id {
Some(bgl_id) => bind_group_layouts_guard.get(*bgl_id).get().map(Some),
None => Ok(None),
})
.collect::<Result<Vec<_>, _>>()
};
+80 -36
View File
@@ -209,6 +209,7 @@ pub struct Device {
pub(crate) adapter: Arc<Adapter>,
pub(crate) queue: OnceCellOrLock<Weak<Queue>>,
pub(crate) zero_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
pub(crate) empty_bgl: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
/// The `label` from the descriptor used to create the resource.
label: String,
@@ -298,6 +299,8 @@ impl Drop for Device {
// SAFETY: We are in the Drop impl and we don't use self.zero_buffer anymore after this point.
let zero_buffer = unsafe { ManuallyDrop::take(&mut self.zero_buffer) };
// SAFETY: We are in the Drop impl and we don't use self.empty_bgl anymore after this point.
let empty_bgl = unsafe { ManuallyDrop::take(&mut self.empty_bgl) };
// SAFETY: We are in the Drop impl and we don't use
// self.default_external_texture_params_buffer anymore after this point.
let default_external_texture_params_buffer =
@@ -312,6 +315,7 @@ impl Drop for Device {
}
unsafe {
self.raw.destroy_buffer(zero_buffer);
self.raw.destroy_bind_group_layout(empty_bgl);
self.raw
.destroy_buffer(default_external_texture_params_buffer);
self.raw.destroy_fence(fence);
@@ -453,6 +457,15 @@ impl Device {
}
.map_err(DeviceError::from_hal)?;
let empty_bgl = unsafe {
raw_device.create_bind_group_layout(&hal::BindGroupLayoutDescriptor {
label: None,
flags: hal::BindGroupLayoutFlags::empty(),
entries: &[],
})
}
.map_err(DeviceError::from_hal)?;
let default_external_texture_params_buffer = unsafe {
raw_device.create_buffer(&hal::BufferDescriptor {
label: hal_label(
@@ -495,6 +508,7 @@ impl Device {
adapter: adapter.clone(),
queue: OnceCellOrLock::new(),
zero_buffer: ManuallyDrop::new(zero_buffer),
empty_bgl: ManuallyDrop::new(empty_bgl),
default_external_texture_params_buffer: ManuallyDrop::new(
default_external_texture_params_buffer,
),
@@ -2471,8 +2485,12 @@ impl Device {
.bind_group_layouts
.iter()
.enumerate()
.map(|(group_index, bgl)| pipeline::LateSizedBufferGroup {
shader_sizes: bgl
.map(|(group_index, bgl)| {
let Some(bgl) = bgl else {
return pipeline::LateSizedBufferGroup::default();
};
let shader_sizes = bgl
.entries
.values()
.filter_map(|entry| match entry.ty {
@@ -2490,7 +2508,8 @@ impl Device {
}
_ => None,
})
.collect(),
.collect();
pipeline::LateSizedBufferGroup { shader_sizes }
})
.collect()
}
@@ -2518,9 +2537,7 @@ impl Device {
}
}
/// Internal function exposed for use by `player` crate only.
#[doc(hidden)]
pub fn create_bind_group_layout_internal(
fn create_bind_group_layout_internal(
self: &Arc<Self>,
label: &crate::Label,
entry_map: bgl::EntryMap,
@@ -2775,7 +2792,7 @@ impl Device {
.map_err(|e| self.handle_hal_error(e))?;
let bgl = BindGroupLayout {
raw: ManuallyDrop::new(raw),
raw: binding_model::RawBindGroupLayout::Owning(ManuallyDrop::new(raw)),
device: self.clone(),
entries: entry_map,
origin,
@@ -3598,6 +3615,14 @@ impl Device {
pub fn create_pipeline_layout(
self: &Arc<Self>,
desc: &binding_model::ResolvedPipelineLayoutDescriptor,
) -> Result<Arc<binding_model::PipelineLayout>, binding_model::CreatePipelineLayoutError> {
self.create_pipeline_layout_impl(desc, false)
}
fn create_pipeline_layout_impl(
self: &Arc<Self>,
desc: &binding_model::ResolvedPipelineLayoutDescriptor,
ignore_exclusive_pipeline_check: bool,
) -> Result<Arc<binding_model::PipelineLayout>, binding_model::CreatePipelineLayoutError> {
use crate::binding_model::CreatePipelineLayoutError as Error;
@@ -3632,8 +3657,23 @@ impl Device {
let mut count_validator = binding_model::BindingTypeMaxCountValidator::default();
for bgl in desc.bind_group_layouts.iter() {
for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
let Some(bgl) = bgl else {
continue;
};
bgl.same_device(self)?;
if !ignore_exclusive_pipeline_check {
let exclusive_pipeline = bgl.exclusive_pipeline.get().unwrap();
if !matches!(exclusive_pipeline, binding_model::ExclusivePipeline::None) {
return Err(Error::BglHasExclusivePipeline {
index,
pipeline: alloc::format!("{exclusive_pipeline}"),
});
}
}
count_validator.merge(&bgl.binding_count_validator);
}
@@ -3641,16 +3681,18 @@ impl Device {
.validate(&self.limits)
.map_err(Error::TooManyBindings)?;
let bind_group_layouts = desc
.bind_group_layouts
.iter()
.cloned()
let get_bgl_iter = || {
desc.bind_group_layouts
.iter()
.map(|bgl| bgl.as_ref().filter(|bgl| !bgl.entries.is_empty()))
};
let bind_group_layouts = get_bgl_iter()
.map(|bgl| bgl.cloned())
.collect::<ArrayVec<_, { hal::MAX_BIND_GROUPS }>>();
let raw_bind_group_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.raw())
let raw_bind_group_layouts = get_bgl_iter()
.map(|bgl| bgl.map(|bgl| bgl.raw()))
.collect::<ArrayVec<_, { hal::MAX_BIND_GROUPS }>>();
let additional_flags = if self.indirect_validation.is_some() {
@@ -3686,7 +3728,7 @@ impl Device {
Ok(layout)
}
pub(crate) fn derive_pipeline_layout(
fn create_derived_pipeline_layout(
self: &Arc<Self>,
mut derived_group_layouts: Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>,
) -> Result<Arc<binding_model::PipelineLayout>, pipeline::ImplicitLayoutError> {
@@ -3702,9 +3744,13 @@ impl Device {
let bind_group_layouts = derived_group_layouts
.into_iter()
.map(|mut bgl_entry_map| {
if bgl_entry_map.is_empty() {
return Ok(None);
}
bgl_entry_map.sort();
match unique_bind_group_layouts.entry(bgl_entry_map) {
hashbrown::hash_map::Entry::Occupied(v) => Ok(Arc::clone(v.get())),
hashbrown::hash_map::Entry::Occupied(v) => Ok(Some(Arc::clone(v.get()))),
hashbrown::hash_map::Entry::Vacant(e) => {
match self.create_bind_group_layout_internal(
&None,
@@ -3713,7 +3759,7 @@ impl Device {
) {
Ok(bgl) => {
e.insert(bgl.clone());
Ok(bgl)
Ok(Some(bgl))
}
Err(e) => Err(e),
}
@@ -3728,7 +3774,7 @@ impl Device {
immediate_size: 0, //TODO?
};
let layout = self.create_pipeline_layout(&layout_desc)?;
let layout = self.create_pipeline_layout_impl(&layout_desc, true)?;
Ok(layout)
}
@@ -3756,9 +3802,7 @@ impl Device {
};
let mut binding_layout_source = match pipeline_layout {
Some(ref pipeline_layout) => {
validation::BindingLayoutSource::Provided(pipeline_layout.get_binding_maps())
}
Some(pipeline_layout) => validation::BindingLayoutSource::Provided(pipeline_layout),
None => validation::BindingLayoutSource::new_derived(&self.limits),
};
let mut shader_binding_sizes = FastHashMap::default();
@@ -3786,12 +3830,9 @@ impl Device {
}
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(_) => {
drop(binding_layout_source);
pipeline_layout.unwrap()
}
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
self.derive_pipeline_layout(entries)?
self.create_derived_pipeline_layout(entries)?
}
};
@@ -3852,6 +3893,10 @@ impl Device {
if is_auto_layout {
for bgl in pipeline.layout.bind_group_layouts.iter() {
let Some(bgl) = bgl else {
continue;
};
// `bind_group_layouts` might contain duplicate entries, so we need to ignore the result.
let _ = bgl
.exclusive_pipeline
@@ -4268,9 +4313,7 @@ impl Device {
};
let mut binding_layout_source = match pipeline_layout {
Some(ref pipeline_layout) => {
validation::BindingLayoutSource::Provided(pipeline_layout.get_binding_maps())
}
Some(pipeline_layout) => validation::BindingLayoutSource::Provided(pipeline_layout),
None => validation::BindingLayoutSource::new_derived(&self.limits),
};
@@ -4510,12 +4553,9 @@ impl Device {
}
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(_) => {
drop(binding_layout_source);
pipeline_layout.unwrap()
}
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
self.derive_pipeline_layout(entries)?
self.create_derived_pipeline_layout(entries)?
}
};
@@ -4667,6 +4707,10 @@ impl Device {
if is_auto_layout {
for bgl in pipeline.layout.bind_group_layouts.iter() {
let Some(bgl) = bgl else {
continue;
};
// `bind_group_layouts` might contain duplicate entries, so we need to ignore the result.
let _ = bgl
.exclusive_pipeline
@@ -183,8 +183,8 @@ impl Dispatch {
),
flags: hal::PipelineLayoutFlags::empty(),
bind_group_layouts: &[
dst_bind_group_layout.as_ref(),
src_bind_group_layout.as_ref(),
Some(dst_bind_group_layout.as_ref()),
Some(src_bind_group_layout.as_ref()),
],
immediate_size: 4,
};
+6 -6
View File
@@ -107,9 +107,9 @@ impl Draw {
),
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(),
Some(metadata_bind_group_layout.as_ref()),
Some(src_bind_group_layout.as_ref()),
Some(dst_bind_group_layout.as_ref()),
],
immediate_size: 8,
};
@@ -422,7 +422,7 @@ impl Draw {
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), &[]);
encoder.set_bind_group(pipeline_layout, 0, metadata_bind_group, &[]);
}
// Make sure the indirect buffer is still valid.
@@ -439,14 +439,14 @@ impl Draw {
encoder.set_bind_group(
pipeline_layout,
1,
Some(src_bind_group),
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), &[]);
encoder.set_bind_group(pipeline_layout, 2, dst_bind_group, &[]);
}
unsafe {
+3 -11
View File
@@ -28,7 +28,7 @@ use crate::{
/// Information about buffer bindings, which
/// is validated against the shader (and pipeline)
/// at draw time as opposed to initialization time.
#[derive(Debug)]
#[derive(Debug, Default)]
pub(crate) struct LateSizedBufferGroup {
// The order has to match `BindGroup::late_buffer_binding_sizes`.
pub(crate) shader_sizes: Vec<wgt::BufferAddress>,
@@ -312,11 +312,7 @@ impl ComputePipeline {
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
self.layout
.bind_group_layouts
.get(index as usize)
.cloned()
.ok_or(GetBindGroupLayoutError::InvalidGroupIndex(index))
self.layout.get_bind_group_layout(index)
}
}
@@ -854,10 +850,6 @@ impl RenderPipeline {
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
self.layout
.bind_group_layouts
.get(index as usize)
.cloned()
.ok_or(GetBindGroupLayoutError::InvalidGroupIndex(index))
self.layout.get_bind_group_layout(index)
}
}
+2 -2
View File
@@ -195,7 +195,7 @@ impl TimestampNormalizer {
Some("(wgpu internal) Timestamp normalizer pipeline layout"),
device.instance_flags,
),
bind_group_layouts: &[temporary_bind_group_layout.as_ref()],
bind_group_layouts: &[Some(temporary_bind_group_layout.as_ref())],
immediate_size: 8,
flags: hal::PipelineLayoutFlags::empty(),
})
@@ -347,7 +347,7 @@ impl TimestampNormalizer {
timestamp_writes: None,
});
encoder.set_compute_pipeline(&*state.pipeline);
encoder.set_bind_group(&*state.pipeline_layout, 0, Some(bind_group), &[]);
encoder.set_bind_group(&*state.pipeline_layout, 0, bind_group, &[]);
encoder.set_immediates(
&*state.pipeline_layout,
0,
+14 -15
View File
@@ -1,6 +1,7 @@
use alloc::{
boxed::Box,
string::{String, ToString as _},
sync::Arc,
vec::Vec,
};
use core::fmt;
@@ -1010,7 +1011,7 @@ pub fn check_texture_format(
}
}
pub enum BindingLayoutSource<'a> {
pub enum BindingLayoutSource {
/// The binding layout is derived from the pipeline layout.
///
/// This will be filled in by the shader binding validation, as it iterates the shader's interfaces.
@@ -1018,10 +1019,10 @@ pub enum BindingLayoutSource<'a> {
/// The binding layout is provided by the user in BGLs.
///
/// This will be validated against the shader's interfaces.
Provided(ArrayVec<&'a bgl::EntryMap, { hal::MAX_BIND_GROUPS }>),
Provided(Arc<crate::binding_model::PipelineLayout>),
}
impl<'a> BindingLayoutSource<'a> {
impl BindingLayoutSource {
pub fn new_derived(limits: &wgt::Limits) -> Self {
let mut array = ArrayVec::new();
for _ in 0..limits.max_bind_groups {
@@ -1247,7 +1248,7 @@ impl Interface {
/// <https://www.w3.org/TR/webgpu/#abstract-opdef-validating-inter-stage-interfaces>.
pub fn check_stage(
&self,
layouts: &mut BindingLayoutSource<'_>,
layouts: &mut BindingLayoutSource,
shader_binding_sizes: &mut FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
entry_point_name: &str,
shader_stage: ShaderStageForValidation,
@@ -1269,7 +1270,7 @@ impl Interface {
let res = &self.resources[handle];
let result = 'err: {
match layouts {
BindingLayoutSource::Provided(layouts) => {
BindingLayoutSource::Provided(pipeline_layout) => {
// update the required binding size for this buffer
if let ResourceType::Buffer { size } = res.ty {
match shader_binding_sizes.entry(res.bind) {
@@ -1282,11 +1283,9 @@ impl Interface {
}
}
let Some(map) = layouts.get(res.bind.group as usize) else {
break 'err Err(BindingError::Missing);
};
let Some(entry) = map.get(res.bind.binding) else {
let Some(entry) =
pipeline_layout.get_bgl_entry(res.bind.group, res.bind.binding)
else {
break 'err Err(BindingError::Missing);
};
@@ -1340,15 +1339,15 @@ impl Interface {
//
// We only need to do this if the binding layout is provided by the user, as derived
// layouts will inherently be correctly tagged.
if let BindingLayoutSource::Provided(layouts) = layouts {
if let BindingLayoutSource::Provided(pipeline_layout) = layouts {
for &(texture_handle, sampler_handle) in entry_point.sampling_pairs.iter() {
let texture_bind = &self.resources[texture_handle].bind;
let sampler_bind = &self.resources[sampler_handle].bind;
let texture_layout = layouts[texture_bind.group as usize]
.get(texture_bind.binding)
let texture_layout = pipeline_layout
.get_bgl_entry(texture_bind.group, texture_bind.binding)
.unwrap();
let sampler_layout = layouts[sampler_bind.group as usize]
.get(sampler_bind.binding)
let sampler_layout = pipeline_layout
.get_bgl_entry(sampler_bind.group, sampler_bind.binding)
.unwrap();
assert!(texture_layout.visibility.contains(stage_bit));
assert!(sampler_layout.visibility.contains(stage_bit));