From 399637e2b8b8657a80913a36e5608bb01106c57b Mon Sep 17 00:00:00 2001 From: Nicolas Silva Date: Fri, 25 Aug 2023 15:48:22 -0400 Subject: [PATCH] Bind group layout dedup (#3925) * Remove generic parameter in compat::Manager. The code is specific to bind group layout ids and the generic parameter gets in the way. * Add a test. The test actually covers wgpu's configuration where deduplication does not require the indirection rather than the new code. I used it to debug the new code with the configuration hard-coded. It's tedious to add a test to cover dedpuplication of bind group layouts for users of wgpu_core to provide their IDs, we can rely on the CTS which has test for that. * Implement bind group layout deduplication for all configurations Currently wgpu-core implement bind group layout deduplication only when it creates its own resource IDs. In other words it works for wgpu but not in Firefox. This PR bridges the gap by allowing an optional indirection in bind group layouts: each BGL may store an ID referring to its "deduplicated" BGL. When referring to a BGL the rest of the code must make sure to follow the indirection. The exception is command buffer processing which is considered hot code and where we first validate against the provided BGL ID and only follow the indirection if the initial check failed. The main pain point with this approach is the various places where wgpu-core manually updates reference counts: we have to be careful about following the indirection to track the right BGL. * Avoid making decisions based on the size of some generic type. --- player/src/lib.rs | 6 +- tests/tests/bind_group_layout_dedup.rs | 144 +++++++++++++++++++++++++ tests/tests/root.rs | 1 + wgpu-core/src/binding_model.rs | 32 ++++++ wgpu-core/src/command/bind.rs | 104 ++++++++++-------- wgpu-core/src/command/compute.rs | 16 ++- wgpu-core/src/command/render.rs | 27 +++-- wgpu-core/src/device/global.rs | 52 ++++++--- wgpu-core/src/device/life.rs | 26 +++-- wgpu-core/src/device/resource.rs | 20 ++-- wgpu-core/src/hub.rs | 1 + wgpu-core/src/identity.rs | 7 +- 12 files changed, 352 insertions(+), 84 deletions(-) create mode 100644 tests/tests/bind_group_layout_dedup.rs diff --git a/player/src/lib.rs b/player/src/lib.rs index f0043cbab..a4be0b1c8 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -36,7 +36,11 @@ impl wgc::identity::IdentityHandlerFactory< IdentityPassThrough(PhantomData) } } -impl wgc::identity::GlobalIdentityHandlerFactory for IdentityPassThroughFactory {} +impl wgc::identity::GlobalIdentityHandlerFactory for IdentityPassThroughFactory { + fn ids_are_generated_in_wgpu() -> bool { + false + } +} pub trait GlobalPlay { fn encode_commands( diff --git a/tests/tests/bind_group_layout_dedup.rs b/tests/tests/bind_group_layout_dedup.rs new file mode 100644 index 000000000..03bc1f1c5 --- /dev/null +++ b/tests/tests/bind_group_layout_dedup.rs @@ -0,0 +1,144 @@ +use wgpu_test::{initialize_test, TestParameters}; + +#[test] +fn bind_group_layout_deduplication() { + initialize_test(TestParameters::default(), |ctx| { + let entries_1 = &[]; + + let entries_2 = &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }]; + + let bgl_1a = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: entries_1, + }); + + let _bgl_2 = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: entries_2, + }); + + let bgl_1b = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: entries_1, + }); + + let bg_1a = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &bgl_1a, + entries: &[], + }); + + let bg_1b = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &bgl_1b, + entries: &[], + }); + + let pipeline_layout = ctx + .device + .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[&bgl_1b], + push_constant_ranges: &[], + }); + + let module = ctx + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(SHADER_SRC.into()), + }); + + let targets = &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: Default::default(), + })]; + + let desc = wgpu::RenderPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: "vs_main", + buffers: &[], + }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: "fs_main", + targets, + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multiview: None, + multisample: wgpu::MultisampleState::default(), + }; + + let pipeline = ctx.device.create_render_pipeline(&desc); + + let texture = ctx.device.create_texture(&wgpu::TextureDescriptor { + label: None, + dimension: wgpu::TextureDimension::D2, + size: wgpu::Extent3d { + width: 32, + height: 32, + depth_or_array_layers: 1, + }, + sample_count: 1, + mip_level_count: 1, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + + let texture_view = texture.create_view(&Default::default()); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &texture_view, + resolve_target: None, + ops: Default::default(), + })], + depth_stencil_attachment: None, + occlusion_query_set: None, + timestamp_writes: None, + }); + + pass.set_bind_group(0, &bg_1b, &[]); + + pass.set_pipeline(&pipeline); + + pass.draw(0..6, 0..1); + + pass.set_bind_group(0, &bg_1a, &[]); + + pass.draw(0..6, 0..1); + } + + ctx.queue.submit(Some(encoder.finish())); + }) +} + +const SHADER_SRC: &str = " +@vertex fn vs_main() -> @builtin(position) vec4 { return vec4(1.0); } +@fragment fn fs_main() -> @location(0) vec4 { return vec4(1.0); } +"; diff --git a/tests/tests/root.rs b/tests/tests/root.rs index 86139c9bd..b376ab498 100644 --- a/tests/tests/root.rs +++ b/tests/tests/root.rs @@ -5,6 +5,7 @@ mod regression { mod issue_4024; } +mod bind_group_layout_dedup; mod buffer; mod buffer_copy; mod buffer_usages; diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index a06476a21..e9723fa60 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -436,6 +436,8 @@ pub struct BindGroupLayoutDescriptor<'a> { pub(crate) type BindEntryMap = FastHashMap; +pub type BindGroupLayouts = crate::storage::Storage, BindGroupLayoutId>; + /// Bind group layout. /// /// The lifetime of BGLs is a bit special. They are only referenced on CPU @@ -450,6 +452,12 @@ pub struct BindGroupLayout { pub(crate) device_id: Stored, pub(crate) multi_ref_count: MultiRefCount, pub(crate) entries: BindEntryMap, + // When a layout created and there already exists a compatible layout the new layout + // keeps a reference to the older compatible one. In some places we substitute the + // bind group layout id with its compatible sibling. + // Since this substitution can come at a cost, it is skipped when wgpu-core generates + // its own resource IDs. + pub(crate) compatible_layout: Option>, #[allow(unused)] pub(crate) dynamic_count: usize, pub(crate) count_validator: BindingTypeMaxCountValidator, @@ -472,6 +480,30 @@ impl Resource for BindGroupLayout { } } +// If a bindgroup needs to be substitued with its compatible equivalent, return the latter. +pub(crate) fn try_get_bind_group_layout( + layouts: &BindGroupLayouts, + id: BindGroupLayoutId, +) -> Option<&BindGroupLayout> { + let layout = layouts.get(id).ok()?; + if let Some(compat) = layout.compatible_layout { + return Some(&layouts[compat]); + } + + Some(layout) +} + +pub(crate) fn get_bind_group_layout( + layouts: &BindGroupLayouts, + id: Valid, +) -> (Valid, &BindGroupLayout) { + let layout = &layouts[id]; + layout + .compatible_layout + .map(|compat| (compat, &layouts[compat])) + .unwrap_or((id, layout)) +} + #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum CreatePipelineLayoutError { diff --git a/wgpu-core/src/command/bind.rs b/wgpu-core/src/command/bind.rs index 9b87028e3..05f90c6bc 100644 --- a/wgpu-core/src/command/bind.rs +++ b/wgpu-core/src/command/bind.rs @@ -1,8 +1,10 @@ use crate::{ - binding_model::{BindGroup, LateMinBufferBindingSizeMismatch, PipelineLayout}, + binding_model::{ + BindGroup, BindGroupLayouts, LateMinBufferBindingSizeMismatch, PipelineLayout, + }, device::SHADER_STAGE_COUNT, hal_api::HalApi, - id::{BindGroupId, BindGroupLayoutId, PipelineLayoutId, Valid}, + id::{BindGroupId, PipelineLayoutId, Valid}, pipeline::LateSizedBufferGroup, storage::Storage, Stored, @@ -13,37 +15,42 @@ use arrayvec::ArrayVec; type BindGroupMask = u8; mod compat { + use crate::{ + binding_model::BindGroupLayouts, + id::{BindGroupLayoutId, Valid}, + }; use std::ops::Range; - #[derive(Debug)] - struct Entry { - assigned: Option, - expected: Option, + #[derive(Debug, Default)] + struct Entry { + assigned: Option>, + expected: Option>, } - impl Default for Entry { - fn default() -> Self { - Self { - assigned: None, - expected: None, - } - } - } - impl Entry { + + impl Entry { fn is_active(&self) -> bool { self.assigned.is_some() && self.expected.is_some() } - fn is_valid(&self) -> bool { - self.expected.is_none() || self.expected == self.assigned + fn is_valid(&self, bind_group_layouts: &BindGroupLayouts) -> bool { + if self.expected.is_none() || self.expected == self.assigned { + return true; + } + + if let Some(id) = self.assigned { + return bind_group_layouts[id].compatible_layout == self.expected; + } + + false } } #[derive(Debug)] - pub struct Manager { - entries: [Entry; hal::MAX_BIND_GROUPS], + pub(crate) struct BoundBindGroupLayouts { + entries: [Entry; hal::MAX_BIND_GROUPS], } - impl Manager { + impl BoundBindGroupLayouts { pub fn new() -> Self { Self { entries: Default::default(), @@ -60,7 +67,10 @@ mod compat { start_index..end.max(start_index) } - pub fn update_expectations(&mut self, expectations: &[T]) -> Range { + pub fn update_expectations( + &mut self, + expectations: &[Valid], + ) -> Range { let start_index = self .entries .iter() @@ -79,7 +89,7 @@ mod compat { self.make_range(start_index) } - pub fn assign(&mut self, index: usize, value: T) -> Range { + pub fn assign(&mut self, index: usize, value: Valid) -> Range { self.entries[index].assigned = Some(value); self.make_range(index) } @@ -91,9 +101,12 @@ mod compat { .filter_map(|(i, e)| if e.is_active() { Some(i) } else { None }) } - pub fn invalid_mask(&self) -> super::BindGroupMask { + pub fn invalid_mask( + &self, + bind_group_layouts: &BindGroupLayouts, + ) -> super::BindGroupMask { self.entries.iter().enumerate().fold(0, |mask, (i, entry)| { - if entry.is_valid() { + if entry.is_valid(bind_group_layouts) { mask } else { mask | 1u8 << i @@ -104,32 +117,36 @@ mod compat { #[test] fn test_compatibility() { - let mut man = Manager::::new(); + fn id(val: u32) -> Valid { + BindGroupLayoutId::dummy(val) + } + + let mut man = BoundBindGroupLayouts::new(); man.entries[0] = Entry { - expected: Some(3), - assigned: Some(2), + expected: Some(id(3)), + assigned: Some(id(2)), }; man.entries[1] = Entry { - expected: Some(1), - assigned: Some(1), + expected: Some(id(1)), + assigned: Some(id(1)), }; man.entries[2] = Entry { - expected: Some(4), - assigned: Some(5), + expected: Some(id(4)), + assigned: Some(id(5)), }; // check that we rebind [1] after [0] became compatible - assert_eq!(man.assign(0, 3), 0..2); + assert_eq!(man.assign(0, id(3)), 0..2); // check that nothing is rebound - assert_eq!(man.update_expectations(&[3, 2]), 1..1); + assert_eq!(man.update_expectations(&[id(3), id(2)]), 1..1); // check that [1] and [2] are rebound on expectations change - assert_eq!(man.update_expectations(&[3, 1, 5]), 1..3); + assert_eq!(man.update_expectations(&[id(3), id(1), id(5)]), 1..3); // reset the first two bindings - assert_eq!(man.update_expectations(&[4, 6, 5]), 0..0); + assert_eq!(man.update_expectations(&[id(4), id(6), id(5)]), 0..0); // check that nothing is rebound, even if there is a match, // since earlier binding is incompatible. - assert_eq!(man.assign(1, 6), 1..1); + assert_eq!(man.assign(1, id(6)), 1..1); // finally, bind everything - assert_eq!(man.assign(0, 4), 0..3); + assert_eq!(man.assign(0, id(4)), 0..3); } } @@ -161,7 +178,7 @@ impl EntryPayload { #[derive(Debug)] pub(super) struct Binder { pub(super) pipeline_layout_id: Option>, //TODO: strongly `Stored` - manager: compat::Manager>, + manager: compat::BoundBindGroupLayouts, payloads: [EntryPayload; hal::MAX_BIND_GROUPS], } @@ -169,14 +186,14 @@ impl Binder { pub(super) fn new() -> Self { Self { pipeline_layout_id: None, - manager: compat::Manager::new(), + manager: compat::BoundBindGroupLayouts::new(), payloads: Default::default(), } } pub(super) fn reset(&mut self) { self.pipeline_layout_id = None; - self.manager = compat::Manager::new(); + self.manager = compat::BoundBindGroupLayouts::new(); for payload in self.payloads.iter_mut() { payload.reset(); } @@ -275,8 +292,11 @@ impl Binder { .map(move |index| payloads[index].group_id.as_ref().unwrap().value) } - pub(super) fn invalid_mask(&self) -> BindGroupMask { - self.manager.invalid_mask() + pub(super) fn invalid_mask( + &self, + bind_group_layouts: &BindGroupLayouts, + ) -> BindGroupMask { + self.manager.invalid_mask(bind_group_layouts) } /// Scan active buffer bindings corresponding to layouts without `min_binding_size` specified. diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 567ef4efa..c9b20c5a0 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -1,6 +1,7 @@ use crate::{ binding_model::{ - BindError, BindGroup, LateMinBufferBindingSizeMismatch, PushConstantUploadError, + BindError, BindGroup, BindGroupLayouts, LateMinBufferBindingSizeMismatch, + PushConstantUploadError, }, command::{ bind::Binder, @@ -283,8 +284,8 @@ struct State { } impl State { - fn is_ready(&self) -> Result<(), DispatchError> { - let bind_mask = self.binder.invalid_mask(); + fn is_ready(&self, bind_group_layouts: &BindGroupLayouts) -> Result<(), DispatchError> { + let bind_mask = self.binder.invalid_mask(bind_group_layouts); if bind_mask != 0 { //let (expected, provided) = self.binder.entries[index as usize].info(); return Err(DispatchError::IncompatibleBindGroup { @@ -403,6 +404,7 @@ impl Global { let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); let (pipeline_guard, mut token) = hub.compute_pipelines.read(&mut token); let (query_set_guard, mut token) = hub.query_sets.read(&mut token); + let (bind_group_layout_guard, mut token) = hub.bind_group_layouts.read(&mut token); let (buffer_guard, mut token) = hub.buffers.read(&mut token); let (texture_guard, _) = hub.textures.read(&mut token); @@ -663,7 +665,9 @@ impl Global { pipeline: state.pipeline, }; - state.is_ready().map_pass_err(scope)?; + state + .is_ready(&*bind_group_layout_guard) + .map_pass_err(scope)?; state .flush_states( raw, @@ -700,7 +704,9 @@ impl Global { pipeline: state.pipeline, }; - state.is_ready().map_pass_err(scope)?; + state + .is_ready(&*bind_group_layout_guard) + .map_pass_err(scope)?; device .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION) diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 7f16f3180..f9202ee3f 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1,5 +1,5 @@ use crate::{ - binding_model::BindError, + binding_model::{BindError, BindGroupLayouts}, command::{ self, bind::Binder, @@ -421,7 +421,11 @@ struct State { } impl State { - fn is_ready(&self, indexed: bool) -> Result<(), DrawError> { + fn is_ready( + &self, + indexed: bool, + bind_group_layouts: &BindGroupLayouts, + ) -> Result<(), DrawError> { // Determine how many vertex buffers have already been bound let vertex_buffer_count = self.vertex.inputs.iter().take_while(|v| v.bound).count() as u32; // Compare with the needed quantity @@ -431,7 +435,7 @@ impl State { }); } - let bind_mask = self.binder.invalid_mask(); + let bind_mask = self.binder.invalid_mask(bind_group_layouts); if bind_mask != 0 { //let (expected, provided) = self.binder.entries[index as usize].info(); return Err(DrawError::IncompatibleBindGroup { @@ -1349,6 +1353,7 @@ impl Global { let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); let (render_pipeline_guard, mut token) = hub.render_pipelines.read(&mut token); let (query_set_guard, mut token) = hub.query_sets.read(&mut token); + let (bind_group_layout_guard, mut token) = hub.bind_group_layouts.read(&mut token); let (buffer_guard, mut token) = hub.buffers.read(&mut token); let (texture_guard, mut token) = hub.textures.read(&mut token); let (view_guard, _) = hub.texture_views.read(&mut token); @@ -1819,7 +1824,9 @@ impl Global { indirect: false, pipeline: state.pipeline, }; - state.is_ready(indexed).map_pass_err(scope)?; + state + .is_ready::(indexed, &bind_group_layout_guard) + .map_pass_err(scope)?; let last_vertex = first_vertex + vertex_count; let vertex_limit = state.vertex.vertex_limit; @@ -1859,7 +1866,9 @@ impl Global { indirect: false, pipeline: state.pipeline, }; - state.is_ready(indexed).map_pass_err(scope)?; + state + .is_ready::(indexed, &*bind_group_layout_guard) + .map_pass_err(scope)?; //TODO: validate that base_vertex + max_index() is // within the provided range @@ -1904,7 +1913,9 @@ impl Global { indirect: true, pipeline: state.pipeline, }; - state.is_ready(indexed).map_pass_err(scope)?; + state + .is_ready::(indexed, &*bind_group_layout_guard) + .map_pass_err(scope)?; let stride = match indexed { false => mem::size_of::(), @@ -1976,7 +1987,9 @@ impl Global { indirect: true, pipeline: state.pipeline, }; - state.is_ready(indexed).map_pass_err(scope)?; + state + .is_ready::(indexed, &*bind_group_layout_guard) + .map_pass_err(scope)?; let stride = match indexed { false => mem::size_of::(), diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 3f22459b3..8fe5a6fcc 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -1078,19 +1078,28 @@ impl Global { } } - // If there is an equivalent BGL, just bump the refcount and return it. - // This is only applicable for identity filters that are generating new IDs, - // so their inputs are `PhantomData` of size 0. - if mem::size_of::>() == 0 { + let mut compatible_layout = None; + { let (bgl_guard, _) = hub.bind_group_layouts.read(&mut token); if let Some(id) = Device::deduplicate_bind_group_layout(device_id, &entry_map, &*bgl_guard) { - return (id, None); + // If there is an equivalent BGL, just bump the refcount and return it. + // This is only applicable if ids are generated in wgpu. In practice: + // - wgpu users take this branch and return the existing + // id without using the indirection layer in BindGroupLayout. + // - Other users like gecko or the replay tool use don't take + // the branch and instead rely on the indirection to use the + // proper bind group layout id. + if G::ids_are_generated_in_wgpu() { + return (id, None); + } + + compatible_layout = Some(id::Valid(id)); } } - let layout = match device.create_bind_group_layout( + let mut layout = match device.create_bind_group_layout( device_id, desc.label.borrow_option(), entry_map, @@ -1099,7 +1108,10 @@ impl Global { Err(e) => break e, }; + layout.compatible_layout = compatible_layout; + let id = fid.assign(layout, &mut token); + return (id.0, None); }; @@ -1244,16 +1256,28 @@ impl Global { .add(trace::Action::CreateBindGroup(fid.id(), desc.clone())); } - let bind_group_layout = match bind_group_layout_guard.get(desc.layout) { + let mut bind_group_layout = match bind_group_layout_guard.get(desc.layout) { Ok(layout) => layout, - Err(_) => break binding_model::CreateBindGroupError::InvalidLayout, + Err(..) => break binding_model::CreateBindGroupError::InvalidLayout, + }; + + let mut layout_id = id::Valid(desc.layout); + if let Some(id) = bind_group_layout.compatible_layout { + layout_id = id; + bind_group_layout = &bind_group_layout_guard[id]; + } + + let bind_group = match device.create_bind_group( + device_id, + bind_group_layout, + layout_id, + desc, + hub, + &mut token, + ) { + Ok(bind_group) => bind_group, + Err(e) => break e, }; - let bind_group = - match device.create_bind_group(device_id, bind_group_layout, desc, hub, &mut token) - { - Ok(bind_group) => bind_group, - Err(e) => break e, - }; let ref_count = bind_group.life_guard.add_ref(); let id = fid.assign(bind_group, &mut token); diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index a12d86410..b641567d7 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -770,14 +770,24 @@ impl LifetimeTracker { //Note: nothing else can bump the refcount since the guard is locked exclusively //Note: same BGL can appear multiple times in the list, but only the last // encounter could drop the refcount to 0. - if guard[id].multi_ref_count.dec_and_check_empty() { - log::debug!("Bind group layout {:?} will be destroyed", id); - #[cfg(feature = "trace")] - if let Some(t) = trace { - t.lock().add(trace::Action::DestroyBindGroupLayout(id.0)); - } - if let Some(lay) = hub.bind_group_layouts.unregister_locked(id.0, &mut *guard) { - self.free_resources.bind_group_layouts.push(lay.raw); + let mut bgl_to_check = Some(id); + while let Some(id) = bgl_to_check.take() { + let bgl = &guard[id]; + if bgl.multi_ref_count.dec_and_check_empty() { + // If This layout points to a compatible one, go over the latter + // to decrement the ref count and potentially destroy it. + bgl_to_check = bgl.compatible_layout; + + log::debug!("Bind group layout {:?} will be destroyed", id); + #[cfg(feature = "trace")] + if let Some(t) = trace { + t.lock().add(trace::Action::DestroyBindGroupLayout(id.0)); + } + if let Some(lay) = + hub.bind_group_layouts.unregister_locked(id.0, &mut *guard) + { + self.free_resources.bind_group_layouts.push(lay.raw); + } } } } diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 074170e56..73f1887e1 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -1,7 +1,8 @@ #[cfg(feature = "trace")] use crate::device::trace; use crate::{ - binding_model, command, conv, + binding_model::{self, get_bind_group_layout, try_get_bind_group_layout}, + command, conv, device::life::WaitIdleError, device::{ AttachmentData, CommandAllocator, MissingDownlevelFlags, MissingFeatures, @@ -1366,7 +1367,11 @@ impl Device { ) -> Option { guard .iter(self_id.backend()) - .find(|&(_, bgl)| bgl.device_id.value.0 == self_id && bgl.entries == *entry_map) + .find(|&(_, bgl)| { + bgl.device_id.value.0 == self_id + && bgl.compatible_layout.is_none() + && bgl.entries == *entry_map + }) .map(|(id, value)| { value.multi_ref_count.inc(); id @@ -1625,6 +1630,7 @@ impl Device { entries: entry_map, #[cfg(debug_assertions)] label: label.unwrap_or("").to_string(), + compatible_layout: None, }) } @@ -1798,6 +1804,7 @@ impl Device { &self, self_id: id::DeviceId, layout: &binding_model::BindGroupLayout, + layout_id: id::Valid, desc: &binding_model::BindGroupDescriptor, hub: &Hub, token: &mut Token>, @@ -2037,7 +2044,7 @@ impl Device { value: id::Valid(self_id), ref_count: self.life_guard.add_ref(), }, - layout_id: id::Valid(desc.layout), + layout_id, life_guard: LifeGuard::new(desc.label.borrow_or_default()), used, used_buffer_ranges, @@ -2286,7 +2293,7 @@ impl Device { let bgl_vec = desc .bind_group_layouts .iter() - .map(|&id| &bgl_guard.get(id).unwrap().raw) + .map(|&id| &try_get_bind_group_layout(bgl_guard, id).unwrap().raw) .collect::>(); let hal_desc = hal::PipelineLayoutDescriptor { label: desc.label.borrow_option(), @@ -2313,8 +2320,9 @@ impl Device { .iter() .map(|&id| { // manually add a dependency to BGL - bgl_guard.get(id).unwrap().multi_ref_count.inc(); - id::Valid(id) + let (id, layout) = get_bind_group_layout(bgl_guard, id::Valid(id)); + layout.multi_ref_count.inc(); + id }) .collect(), push_constant_ranges: desc.push_constant_ranges.iter().cloned().collect(), diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index d3da0be6c..c0670e085 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -243,6 +243,7 @@ impl Access> for RenderBundle {} impl Access> for Root {} impl Access> for Device {} impl Access> for PipelineLayout {} +impl Access> for QuerySet {} impl Access> for Root {} impl Access> for Device {} impl Access> for BindGroupLayout {} diff --git a/wgpu-core/src/identity.rs b/wgpu-core/src/identity.rs index 5f7cc0dc5..fe10bedb0 100644 --- a/wgpu-core/src/identity.rs +++ b/wgpu-core/src/identity.rs @@ -162,9 +162,14 @@ pub trait GlobalIdentityHandlerFactory: + IdentityHandlerFactory + IdentityHandlerFactory { + fn ids_are_generated_in_wgpu() -> bool; } -impl GlobalIdentityHandlerFactory for IdentityManagerFactory {} +impl GlobalIdentityHandlerFactory for IdentityManagerFactory { + fn ids_are_generated_in_wgpu() -> bool { + true + } +} pub type Input = <>::Filter as IdentityHandler>::Input;