diff --git a/player/src/bin/play.rs b/player/src/bin/play.rs index 2f67b4798..b2ae956bb 100644 --- a/player/src/bin/play.rs +++ b/player/src/bin/play.rs @@ -84,16 +84,19 @@ fn main() { let info = gfx_select!(adapter => global.adapter_get_info(adapter)).unwrap(); log::info!("Picked '{}'", info.name); - gfx_select!(adapter => global.adapter_request_device( + let id = wgc::id::TypedId::zip(1, 0, wgt::Backend::Empty); + let (_, error) = gfx_select!(adapter => global.adapter_request_device( adapter, &desc, None, - wgc::id::TypedId::zip(1, 0, wgt::Backend::Empty) - )) - .expect("Failed to request device") + id + )); + assert_eq!(error, None); + id } _ => panic!("Expected Action::Init"), }; + log::info!("Executing actions"); #[cfg(not(feature = "winit"))] { diff --git a/player/src/lib.rs b/player/src/lib.rs index 96f4a8464..987254bfe 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -186,24 +186,24 @@ impl GlobalPlay for wgc::hub::Global { } } A::CreateBindGroupLayout(id, desc) => { - self.device_create_bind_group_layout::(device, &desc, id) - .unwrap(); + let (_, error) = self.device_create_bind_group_layout::(device, &desc, id); + assert_eq!(error, None); } A::DestroyBindGroupLayout(id) => { self.bind_group_layout_drop::(id); } A::CreatePipelineLayout(id, desc) => { self.device_maintain_ids::(device).unwrap(); - self.device_create_pipeline_layout::(device, &desc, id) - .unwrap(); + let (_, error) = self.device_create_pipeline_layout::(device, &desc, id); + assert_eq!(error, None); } A::DestroyPipelineLayout(id) => { self.pipeline_layout_drop::(id); } A::CreateBindGroup(id, desc) => { self.device_maintain_ids::(device).unwrap(); - self.device_create_bind_group::(device, &desc, id) - .unwrap(); + let (_, error) = self.device_create_bind_group::(device, &desc, id); + assert_eq!(error, None); } A::DestroyBindGroup(id) => { self.bind_group_drop::(id); diff --git a/player/tests/test.rs b/player/tests/test.rs index 3f52ff193..43397c388 100644 --- a/player/tests/test.rs +++ b/player/tests/test.rs @@ -86,17 +86,19 @@ impl Test<'_> { test_num: u32, ) { let backend = adapter.backend(); - let device = gfx_select!(adapter => global.adapter_request_device( + let device = wgc::id::TypedId::zip(test_num, 0, backend); + let (_, error) = gfx_select!(adapter => global.adapter_request_device( adapter, &wgt::DeviceDescriptor { + label: None, features: self.features | wgt::Features::MAPPABLE_PRIMARY_BUFFERS, limits: wgt::Limits::default(), shader_validation: true, }, None, - wgc::id::TypedId::zip(test_num, 0, backend) - )) - .unwrap(); + device + )); + assert_eq!(error, None); let mut command_buffer_id_manager = wgc::hub::IdentityManager::default(); println!("\t\t\tRunning..."); diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index cc5d270a5..c90a65db4 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -26,7 +26,7 @@ use std::{ use thiserror::Error; -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] pub enum CreateBindGroupLayoutError { #[error(transparent)] Device(#[from] DeviceError), @@ -40,7 +40,7 @@ pub enum CreateBindGroupLayoutError { TooManyBindings(BindingTypeMaxCountError), } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] pub enum CreateBindGroupError { #[error(transparent)] Device(#[from] DeviceError), @@ -96,7 +96,7 @@ pub enum CreateBindGroupError { DepthStencilAspect, } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] pub enum BindingZone { #[error("stage {0:?}")] Stage(wgt::ShaderStage), @@ -104,7 +104,7 @@ pub enum BindingZone { Pipeline, } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] #[error("too many bindings of type {kind:?} in {zone}, limit is {count}")] pub struct BindingTypeMaxCountError { pub kind: BindingTypeMaxCountErrorKind, @@ -112,7 +112,7 @@ pub struct BindingTypeMaxCountError { pub count: u32, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub enum BindingTypeMaxCountErrorKind { DynamicUniformBuffers, DynamicStorageBuffers, @@ -336,7 +336,7 @@ impl Resource for BindGroupLayout { } } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] pub enum CreatePipelineLayoutError { #[error(transparent)] Device(#[from] DeviceError), diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index e4eb1a94f..bc13b652f 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -3,8 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{ - binding_model::{self, CreateBindGroupError, CreatePipelineLayoutError}, - command, conv, + binding_model, command, conv, device::life::WaitIdleError, hub::{ GfxBackend, Global, GlobalIdentityHandlerFactory, Hub, Input, InvalidId, Storage, Token, @@ -57,6 +56,8 @@ pub const MAX_VERTEX_BUFFERS: usize = 16; pub const MAX_ANISOTROPY: u8 = 16; pub const SHADER_STAGE_COUNT: usize = 3; +pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor>; + pub fn all_buffer_stages() -> hal::pso::PipelineStage { use hal::pso::PipelineStage as Ps; Ps::DRAW_INDIRECT @@ -252,7 +253,7 @@ impl Device { mem_props: hal::adapter::MemoryProperties, hal_limits: hal::Limits, private_features: PrivateFeatures, - desc: &wgt::DeviceDescriptor, + desc: &DeviceDescriptor, trace_path: Option<&std::path::Path>, ) -> Result { let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw) @@ -1057,16 +1058,351 @@ impl Device { }) } + fn create_bind_group( + &self, + self_id: id::DeviceId, + layout: &binding_model::BindGroupLayout, + desc: &binding_model::BindGroupDescriptor, + hub: &Hub, + token: &mut Token>, + ) -> Result, binding_model::CreateBindGroupError> { + use crate::binding_model::{BindingResource as Br, CreateBindGroupError as Error}; + { + // Check that the number of entries in the descriptor matches + // the number of entries in the layout. + let actual = desc.entries.len(); + let expected = layout.entries.len(); + if actual != expected { + return Err(Error::BindingsNumMismatch { expected, actual }); + } + } + + // TODO: arrayvec/smallvec + // Record binding info for dynamic offset validation + let mut dynamic_binding_info = Vec::new(); + // fill out the descriptors + let mut used = TrackerSet::new(B::VARIANT); + + let (buffer_guard, mut token) = hub.buffers.read(token); + let (texture_guard, mut token) = hub.textures.read(&mut token); //skip token + let (texture_view_guard, mut token) = hub.texture_views.read(&mut token); + let (sampler_guard, _) = hub.samplers.read(&mut token); + + // `BTreeMap` has ordered bindings as keys, which allows us to coalesce + // the descriptor writes into a single transaction. + let mut write_map = BTreeMap::new(); + for entry in desc.entries.iter() { + let binding = entry.binding; + // Find the corresponding declaration in the layout + let decl = layout + .entries + .get(&binding) + .ok_or(Error::MissingBindingDeclaration(binding))?; + let descriptors: SmallVec<[_; 1]> = match entry.resource { + Br::Buffer(ref bb) => { + let (pub_usage, internal_use, min_size, dynamic) = match decl.ty { + wgt::BindingType::UniformBuffer { + dynamic, + min_binding_size, + } => ( + wgt::BufferUsage::UNIFORM, + resource::BufferUse::UNIFORM, + min_binding_size, + dynamic, + ), + wgt::BindingType::StorageBuffer { + dynamic, + min_binding_size, + readonly, + } => ( + wgt::BufferUsage::STORAGE, + if readonly { + resource::BufferUse::STORAGE_LOAD + } else { + resource::BufferUse::STORAGE_STORE + }, + min_binding_size, + dynamic, + ), + _ => { + return Err(Error::WrongBindingType { + binding, + actual: decl.ty.clone(), + expected: "UniformBuffer, StorageBuffer or ReadonlyStorageBuffer", + }) + } + }; + + if bb.offset % wgt::BIND_BUFFER_ALIGNMENT != 0 { + return Err(Error::UnalignedBufferOffset(bb.offset)); + } + + let buffer = used + .buffers + .use_extend(&*buffer_guard, bb.buffer_id, (), internal_use) + .map_err(|_| Error::InvalidBuffer(bb.buffer_id))?; + check_buffer_usage(buffer.usage, pub_usage)?; + let &(ref buffer_raw, _) = buffer + .raw + .as_ref() + .ok_or(Error::InvalidBuffer(bb.buffer_id))?; + + let (bind_size, bind_end) = match bb.size { + Some(size) => { + let end = bb.offset + size.get(); + if end > buffer.size { + return Err(Error::BindingRangeTooLarge { + range: bb.offset..end, + size: buffer.size, + }); + } + (size.get(), end) + } + None => (buffer.size - bb.offset, buffer.size), + }; + + if pub_usage == wgt::BufferUsage::UNIFORM + && (self.limits.max_uniform_buffer_binding_size as u64) < bind_size + { + return Err(Error::UniformBufferRangeTooLarge); + } + + // Record binding info for validating dynamic offsets + if dynamic { + dynamic_binding_info.push(binding_model::BindGroupDynamicBindingData { + maximum_dynamic_offset: buffer.size - bind_end, + }); + } + + if let Some(non_zero) = min_size { + let min_size = non_zero.get(); + if min_size > bind_size { + return Err(Error::BindingSizeTooSmall { + actual: bind_size, + min: min_size, + }); + } + } + + let sub_range = hal::buffer::SubRange { + offset: bb.offset, + size: Some(bind_size), + }; + SmallVec::from([hal::pso::Descriptor::Buffer(buffer_raw, sub_range)]) + } + Br::Sampler(id) => { + match decl.ty { + wgt::BindingType::Sampler { comparison } => { + let sampler = used + .samplers + .use_extend(&*sampler_guard, id, (), ()) + .map_err(|_| Error::InvalidSampler(id))?; + + // Check the actual sampler to also (not) be a comparison sampler + if sampler.comparison != comparison { + return Err(Error::WrongSamplerComparison); + } + + SmallVec::from([hal::pso::Descriptor::Sampler(&sampler.raw)]) + } + _ => { + return Err(Error::WrongBindingType { + binding, + actual: decl.ty.clone(), + expected: "Sampler", + }) + } + } + } + Br::TextureView(id) => { + let view = used + .views + .use_extend(&*texture_view_guard, id, (), ()) + .map_err(|_| Error::InvalidTextureView(id))?; + let (pub_usage, internal_use) = match decl.ty { + wgt::BindingType::SampledTexture { .. } => { + (wgt::TextureUsage::SAMPLED, resource::TextureUse::SAMPLED) + } + wgt::BindingType::StorageTexture { readonly, .. } => ( + wgt::TextureUsage::STORAGE, + if readonly { + resource::TextureUse::STORAGE_LOAD + } else { + resource::TextureUse::STORAGE_STORE + }, + ), + _ => return Err(Error::WrongBindingType { + binding, + actual: decl.ty.clone(), + expected: + "SampledTexture, ReadonlyStorageTexture or WriteonlyStorageTexture", + }), + }; + if view + .aspects + .contains(hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL) + { + return Err(Error::DepthStencilAspect); + } + match view.inner { + resource::TextureViewInner::Native { + ref raw, + ref source_id, + } => { + // Careful here: the texture may no longer have its own ref count, + // if it was deleted by the user. + let texture = &texture_guard[source_id.value]; + used.textures + .change_extend( + source_id.value, + &source_id.ref_count, + view.selector.clone(), + internal_use, + ) + .unwrap(); + check_texture_usage(texture.usage, pub_usage)?; + let image_layout = + conv::map_texture_state(internal_use, view.aspects).1; + SmallVec::from([hal::pso::Descriptor::Image(raw, image_layout)]) + } + resource::TextureViewInner::SwapChain { .. } => { + return Err(Error::SwapChainImage); + } + } + } + Br::TextureViewArray(ref bindings_array) => { + let required_feats = wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY; + if !self.features.contains(required_feats) { + return Err(Error::MissingFeatures(required_feats)); + } + + if let Some(count) = decl.count { + let count = count.get() as usize; + let num_bindings = bindings_array.len(); + if count != num_bindings { + return Err(Error::BindingArrayLengthMismatch { + actual: num_bindings, + expected: count, + }); + } + } else { + return Err(Error::SingleBindingExpected); + } + + let (pub_usage, internal_use) = match decl.ty { + wgt::BindingType::SampledTexture { .. } => { + (wgt::TextureUsage::SAMPLED, resource::TextureUse::SAMPLED) + } + _ => { + return Err(Error::WrongBindingType { + binding, + actual: decl.ty.clone(), + expected: "SampledTextureArray", + }) + } + }; + bindings_array + .iter() + .map(|&id| { + let view = used + .views + .use_extend(&*texture_view_guard, id, (), ()) + .map_err(|_| Error::InvalidTextureView(id))?; + match view.inner { + resource::TextureViewInner::Native { + ref raw, + ref source_id, + } => { + // Careful here: the texture may no longer have its own ref count, + // if it was deleted by the user. + let texture = &texture_guard[source_id.value]; + used.textures + .change_extend( + source_id.value, + &source_id.ref_count, + view.selector.clone(), + internal_use, + ) + .unwrap(); + check_texture_usage(texture.usage, pub_usage)?; + let image_layout = + conv::map_texture_state(internal_use, view.aspects).1; + Ok(hal::pso::Descriptor::Image(raw, image_layout)) + } + resource::TextureViewInner::SwapChain { .. } => { + Err(Error::SwapChainImage) + } + } + }) + .collect::>()? + } + }; + if write_map.insert(binding, descriptors).is_some() { + return Err(Error::DuplicateBinding(binding)); + } + } + + let mut desc_sets = ArrayVec::<[_; 1]>::new(); + self.desc_allocator + .lock() + .allocate( + &self.raw, + &layout.raw, + &layout.desc_counts, + 1, + &mut desc_sets, + ) + .expect("failed to allocate descriptor set"); + let mut desc_set = desc_sets.pop().unwrap(); + + // Set the descriptor set's label for easier debugging. + if let Some(label) = desc.label.as_ref() { + unsafe { + self.raw.set_descriptor_set_name(desc_set.raw_mut(), &label); + } + } + + if let Some(start_binding) = write_map.keys().next().cloned() { + let descriptors = write_map + .into_iter() + .flat_map(|(_, list)| list) + .collect::>(); + let write = hal::pso::DescriptorSetWrite { + set: desc_set.raw(), + binding: start_binding, + array_offset: 0, + descriptors, + }; + unsafe { + self.raw.write_descriptor_sets(iter::once(write)); + } + } + + Ok(binding_model::BindGroup { + raw: desc_set, + device_id: Stored { + value: id::Valid(self_id), + ref_count: self.life_guard.add_ref(), + }, + layout_id: id::Valid(desc.layout), + life_guard: LifeGuard::new(desc.label.borrow_or_default()), + used, + dynamic_binding_info, + }) + } + fn create_pipeline_layout( &self, self_id: id::DeviceId, desc: &binding_model::PipelineLayoutDescriptor, bgl_guard: &Storage, id::BindGroupLayoutId>, - ) -> Result, CreatePipelineLayoutError> { + ) -> Result, binding_model::CreatePipelineLayoutError> { + use crate::binding_model::CreatePipelineLayoutError as Error; + let bind_group_layouts_count = desc.bind_group_layouts.len(); let device_max_bind_groups = self.limits.max_bind_groups as usize; if bind_group_layouts_count > device_max_bind_groups { - return Err(CreatePipelineLayoutError::TooManyGroups { + return Err(Error::TooManyGroups { actual: bind_group_layouts_count, max: device_max_bind_groups, }); @@ -1075,26 +1411,22 @@ impl Device { if !desc.push_constant_ranges.is_empty() && !self.features.contains(wgt::Features::PUSH_CONSTANTS) { - return Err(CreatePipelineLayoutError::MissingFeature( - wgt::Features::PUSH_CONSTANTS, - )); + return Err(Error::MissingFeature(wgt::Features::PUSH_CONSTANTS)); } let mut used_stages = wgt::ShaderStage::empty(); for (index, pc) in desc.push_constant_ranges.iter().enumerate() { if pc.stages.intersects(used_stages) { - return Err( - CreatePipelineLayoutError::MoreThanOnePushConstantRangePerStage { - index, - provided: pc.stages, - intersected: pc.stages & used_stages, - }, - ); + return Err(Error::MoreThanOnePushConstantRangePerStage { + index, + provided: pc.stages, + intersected: pc.stages & used_stages, + }); } used_stages |= pc.stages; let device_max_pc_size = self.limits.max_push_constant_size; if device_max_pc_size < pc.range.end { - return Err(CreatePipelineLayoutError::PushConstantRangeTooLarge { + return Err(Error::PushConstantRangeTooLarge { index, range: pc.range.clone(), max: device_max_pc_size, @@ -1102,13 +1434,13 @@ impl Device { } if pc.range.start % wgt::PUSH_CONSTANT_ALIGNMENT != 0 { - return Err(CreatePipelineLayoutError::MisalignedPushConstantRange { + return Err(Error::MisalignedPushConstantRange { index, bound: pc.range.start, }); } if pc.range.end % wgt::PUSH_CONSTANT_ALIGNMENT != 0 { - return Err(CreatePipelineLayoutError::MisalignedPushConstantRange { + return Err(Error::MisalignedPushConstantRange { index, bound: pc.range.end, }); @@ -1121,12 +1453,12 @@ impl Device { for &id in desc.bind_group_layouts.iter() { let bind_group_layout = bgl_guard .get(id) - .map_err(|_| CreatePipelineLayoutError::InvalidBindGroupLayout(id))?; + .map_err(|_| Error::InvalidBindGroupLayout(id))?; count_validator.merge(&bind_group_layout.count_validator); } count_validator .validate(&self.limits) - .map_err(CreatePipelineLayoutError::TooManyBindings)?; + .map_err(Error::TooManyBindings)?; let descriptor_set_layouts = desc .bind_group_layouts @@ -1967,71 +2299,76 @@ impl Global { device_id: id::DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, id_in: Input, - ) -> Result { + ) -> ( + id::BindGroupLayoutId, + Option, + ) { span!(_guard, INFO, "Device::create_bind_group_layout"); let mut token = Token::root(); let hub = B::hub(self); - let mut entry_map = FastHashMap::default(); - for entry in desc.entries.iter() { - if entry_map.insert(entry.binding, entry.clone()).is_some() { - return Err(binding_model::CreateBindGroupLayoutError::ConflictBinding( - entry.binding, - )); + + let error = 'outer: loop { + let mut entry_map = FastHashMap::default(); + for entry in desc.entries.iter() { + if entry_map.insert(entry.binding, entry.clone()).is_some() { + break 'outer binding_model::CreateBindGroupLayoutError::ConflictBinding( + entry.binding, + ); + } } - } - let (device_guard, mut token) = hub.devices.read(&mut token); - let device = device_guard - .get(device_id) - .map_err(|_| DeviceError::Invalid)?; + let (device_guard, mut token) = hub.devices.read(&mut token); + let device = match device_guard.get(device_id) { + Ok(device) => device, + Err(_) => break DeviceError::Invalid.into(), + }; - // 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 (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 Ok(id); + // 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 (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); + } } - } - let layout = device.create_bind_group_layout( - device_id, - desc.label.as_ref().map(|cow| cow.as_ref()), - entry_map, - )?; + let layout = match device.create_bind_group_layout( + device_id, + desc.label.as_ref().map(|cow| cow.as_ref()), + entry_map, + ) { + Ok(layout) => layout, + Err(e) => break e, + }; - let id = hub - .bind_group_layouts - .register_identity(id_in, layout, &mut token); - #[cfg(feature = "trace")] - if let Some(ref trace) = device.trace { - trace - .lock() - .add(trace::Action::CreateBindGroupLayout(id.0, desc.clone())); - } - Ok(id.0) + let id = hub + .bind_group_layouts + .register_identity(id_in, layout, &mut token); + #[cfg(feature = "trace")] + if let Some(ref trace) = device.trace { + trace + .lock() + .add(trace::Action::CreateBindGroupLayout(id.0, desc.clone())); + } + return (id.0, None); + }; + + let id = hub.bind_group_layouts.register_error( + id_in, + desc.label.borrow_or_default(), + &mut token, + ); + (id, Some(error)) } pub fn bind_group_layout_label(&self, id: id::BindGroupLayoutId) -> String { B::hub(self).bind_group_layouts.label_for_resource(id) } - pub fn bind_group_layout_error( - &self, - id_in: Input, - label: Option<&str>, - ) -> id::BindGroupLayoutId { - B::hub(self).bind_group_layouts.register_error( - id_in, - label.unwrap_or(""), - &mut Token::root(), - ) - } - pub fn bind_group_layout_drop( &self, bind_group_layout_id: id::BindGroupLayoutId, @@ -2065,48 +2402,52 @@ impl Global { device_id: id::DeviceId, desc: &binding_model::PipelineLayoutDescriptor, id_in: Input, - ) -> Result { + ) -> ( + id::PipelineLayoutId, + Option, + ) { span!(_guard, INFO, "Device::create_pipeline_layout"); let hub = B::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); - let device = device_guard - .get(device_id) - .map_err(|_| DeviceError::Invalid)?; + let error = loop { + let device = match device_guard.get(device_id) { + Ok(device) => device, + Err(_) => break DeviceError::Invalid.into(), + }; - let layout = { - let (bgl_guard, _) = hub.bind_group_layouts.read(&mut token); - device.create_pipeline_layout(device_id, desc, &*bgl_guard)? + let layout = { + let (bgl_guard, _) = hub.bind_group_layouts.read(&mut token); + match device.create_pipeline_layout(device_id, desc, &*bgl_guard) { + Ok(layout) => layout, + Err(e) => break e, + } + }; + + let id = hub + .pipeline_layouts + .register_identity(id_in, layout, &mut token); + #[cfg(feature = "trace")] + if let Some(ref trace) = device.trace { + trace + .lock() + .add(trace::Action::CreatePipelineLayout(id.0, desc.clone())); + } + return (id.0, None); }; - let id = hub - .pipeline_layouts - .register_identity(id_in, layout, &mut token); - #[cfg(feature = "trace")] - if let Some(ref trace) = device.trace { - trace - .lock() - .add(trace::Action::CreatePipelineLayout(id.0, desc.clone())); - } - Ok(id.0) + let id = + hub.pipeline_layouts + .register_error(id_in, desc.label.borrow_or_default(), &mut token); + (id, Some(error)) } pub fn pipeline_layout_label(&self, id: id::PipelineLayoutId) -> String { B::hub(self).pipeline_layouts.label_for_resource(id) } - pub fn pipeline_layout_error( - &self, - id_in: Input, - label: Option<&str>, - ) -> id::PipelineLayoutId { - B::hub(self) - .pipeline_layouts - .register_error(id_in, label.unwrap_or(""), &mut Token::root()) - } - pub fn pipeline_layout_drop(&self, pipeline_layout_id: id::PipelineLayoutId) { span!(_guard, INFO, "PipelineLayout::drop"); @@ -2234,392 +2575,71 @@ impl Global { device_id: id::DeviceId, desc: &binding_model::BindGroupDescriptor, id_in: Input, - ) -> Result { - use crate::binding_model::BindingResource as Br; - + ) -> (id::BindGroupId, Option) { span!(_guard, INFO, "Device::create_bind_group"); let hub = B::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); - let device = device_guard - .get(device_id) - .map_err(|_| DeviceError::Invalid)?; let (bind_group_layout_guard, mut token) = hub.bind_group_layouts.read(&mut token); - let bind_group_layout = bind_group_layout_guard - .get(desc.layout) - .map_err(|_| CreateBindGroupError::InvalidLayout)?; - { - // Check that the number of entries in the descriptor matches - // the number of entries in the layout. - let actual = desc.entries.len(); - let expected = bind_group_layout.entries.len(); - if actual != expected { - return Err(CreateBindGroupError::BindingsNumMismatch { expected, actual }); - } - } + let error = loop { + let device = match device_guard.get(device_id) { + Ok(device) => device, + Err(_) => break DeviceError::Invalid.into(), + }; + let bind_group_layout = match bind_group_layout_guard.get(desc.layout) { + Ok(layout) => layout, + Err(_) => break binding_model::CreateBindGroupError::InvalidLayout, + }; - // TODO: arrayvec/smallvec - // Record binding info for dynamic offset validation - let mut dynamic_binding_info = Vec::new(); + 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(); - // fill out the descriptors - let mut used = TrackerSet::new(B::VARIANT); - let desc_set = { - let (buffer_guard, mut token) = hub.buffers.read(&mut token); - let (texture_guard, mut token) = hub.textures.read(&mut token); //skip token - let (texture_view_guard, mut token) = hub.texture_views.read(&mut token); - let (sampler_guard, _) = hub.samplers.read(&mut token); - - // `BTreeMap` has ordered bindings as keys, which allows us to coalesce - // the descriptor writes into a single transaction. - let mut write_map = BTreeMap::new(); - for entry in desc.entries.iter() { - let binding = entry.binding; - // Find the corresponding declaration in the layout - let decl = bind_group_layout - .entries - .get(&binding) - .ok_or(CreateBindGroupError::MissingBindingDeclaration(binding))?; - let descriptors: SmallVec<[_; 1]> = match entry.resource { - Br::Buffer(ref bb) => { - let (pub_usage, internal_use, min_size, dynamic) = match decl.ty { - wgt::BindingType::UniformBuffer { - dynamic, - min_binding_size, - } => ( - wgt::BufferUsage::UNIFORM, - resource::BufferUse::UNIFORM, - min_binding_size, - dynamic, - ), - wgt::BindingType::StorageBuffer { - dynamic, - min_binding_size, - readonly, - } => ( - wgt::BufferUsage::STORAGE, - if readonly { - resource::BufferUse::STORAGE_LOAD - } else { - resource::BufferUse::STORAGE_STORE - }, - min_binding_size, - dynamic, - ), - _ => { - return Err(CreateBindGroupError::WrongBindingType { - binding, - actual: decl.ty.clone(), - expected: - "UniformBuffer, StorageBuffer or ReadonlyStorageBuffer", - }) - } - }; - - if bb.offset % wgt::BIND_BUFFER_ALIGNMENT != 0 { - return Err(CreateBindGroupError::UnalignedBufferOffset(bb.offset)); - } - - let buffer = used - .buffers - .use_extend(&*buffer_guard, bb.buffer_id, (), internal_use) - .map_err(|_| CreateBindGroupError::InvalidBuffer(bb.buffer_id))?; - check_buffer_usage(buffer.usage, pub_usage)?; - let &(ref buffer_raw, _) = buffer - .raw - .as_ref() - .ok_or(CreateBindGroupError::InvalidBuffer(bb.buffer_id))?; - - let (bind_size, bind_end) = match bb.size { - Some(size) => { - let end = bb.offset + size.get(); - if end > buffer.size { - return Err(CreateBindGroupError::BindingRangeTooLarge { - range: bb.offset..end, - size: buffer.size, - }); - } - (size.get(), end) - } - None => (buffer.size - bb.offset, buffer.size), - }; - - if pub_usage == wgt::BufferUsage::UNIFORM - && (device.limits.max_uniform_buffer_binding_size as u64) < bind_size - { - return Err(CreateBindGroupError::UniformBufferRangeTooLarge); - } - - // Record binding info for validating dynamic offsets - if dynamic { - dynamic_binding_info.push(binding_model::BindGroupDynamicBindingData { - maximum_dynamic_offset: buffer.size - bind_end, - }); - } - - if let Some(non_zero) = min_size { - let min_size = non_zero.get(); - if min_size > bind_size { - return Err(CreateBindGroupError::BindingSizeTooSmall { - actual: bind_size, - min: min_size, - }); - } - } - - let sub_range = hal::buffer::SubRange { - offset: bb.offset, - size: Some(bind_size), - }; - SmallVec::from([hal::pso::Descriptor::Buffer(buffer_raw, sub_range)]) - } - Br::Sampler(id) => { - match decl.ty { - wgt::BindingType::Sampler { comparison } => { - let sampler = used - .samplers - .use_extend(&*sampler_guard, id, (), ()) - .map_err(|_| CreateBindGroupError::InvalidSampler(id))?; - - // Check the actual sampler to also (not) be a comparison sampler - if sampler.comparison != comparison { - return Err(CreateBindGroupError::WrongSamplerComparison); - } - - SmallVec::from([hal::pso::Descriptor::Sampler(&sampler.raw)]) - } - _ => { - return Err(CreateBindGroupError::WrongBindingType { - binding, - actual: decl.ty.clone(), - expected: "Sampler", - }) - } - } - } - Br::TextureView(id) => { - let view = used - .views - .use_extend(&*texture_view_guard, id, (), ()) - .map_err(|_| CreateBindGroupError::InvalidTextureView(id))?; - let (pub_usage, internal_use) = match decl.ty { - wgt::BindingType::SampledTexture { .. } => ( - wgt::TextureUsage::SAMPLED, - resource::TextureUse::SAMPLED, - ), - wgt::BindingType::StorageTexture { readonly, .. } => ( - wgt::TextureUsage::STORAGE, - if readonly { - resource::TextureUse::STORAGE_LOAD - } else { - resource::TextureUse::STORAGE_STORE - }, - ), - _ => return Err(CreateBindGroupError::WrongBindingType { - binding, - actual: decl.ty.clone(), - expected: "SampledTexture, ReadonlyStorageTexture or WriteonlyStorageTexture" - }) - }; - if view - .aspects - .contains(hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL) - { - return Err(CreateBindGroupError::DepthStencilAspect); - } - match view.inner { - resource::TextureViewInner::Native { - ref raw, - ref source_id, - } => { - // Careful here: the texture may no longer have its own ref count, - // if it was deleted by the user. - let texture = &texture_guard[source_id.value]; - used.textures - .change_extend( - source_id.value, - &source_id.ref_count, - view.selector.clone(), - internal_use, - ) - .unwrap(); - check_texture_usage(texture.usage, pub_usage)?; - let image_layout = - conv::map_texture_state(internal_use, view.aspects).1; - SmallVec::from([hal::pso::Descriptor::Image(raw, image_layout)]) - } - resource::TextureViewInner::SwapChain { .. } => { - return Err(CreateBindGroupError::SwapChainImage); - } - } - } - Br::TextureViewArray(ref bindings_array) => { - let required_feats = wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY; - if !device.features.contains(required_feats) { - return Err(CreateBindGroupError::MissingFeatures(required_feats)); - } - - if let Some(count) = decl.count { - let count = count.get() as usize; - let num_bindings = bindings_array.len(); - if count != num_bindings { - return Err(CreateBindGroupError::BindingArrayLengthMismatch { - actual: num_bindings, - expected: count, - }); - } - } else { - return Err(CreateBindGroupError::SingleBindingExpected); - } - - let (pub_usage, internal_use) = match decl.ty { - wgt::BindingType::SampledTexture { .. } => { - (wgt::TextureUsage::SAMPLED, resource::TextureUse::SAMPLED) - } - _ => { - return Err(CreateBindGroupError::WrongBindingType { - binding, - actual: decl.ty.clone(), - expected: "SampledTextureArray", - }) - } - }; - bindings_array - .iter() - .map(|&id| { - let view = used - .views - .use_extend(&*texture_view_guard, id, (), ()) - .map_err(|_| CreateBindGroupError::InvalidTextureView(id))?; - match view.inner { - resource::TextureViewInner::Native { - ref raw, - ref source_id, - } => { - // Careful here: the texture may no longer have its own ref count, - // if it was deleted by the user. - let texture = &texture_guard[source_id.value]; - used.textures - .change_extend( - source_id.value, - &source_id.ref_count, - view.selector.clone(), - internal_use, - ) - .unwrap(); - check_texture_usage(texture.usage, pub_usage)?; - let image_layout = - conv::map_texture_state(internal_use, view.aspects).1; - Ok(hal::pso::Descriptor::Image(raw, image_layout)) - } - resource::TextureViewInner::SwapChain { .. } => { - Err(CreateBindGroupError::SwapChainImage) - } - } - }) - .collect::>()? - } - }; - if write_map.insert(binding, descriptors).is_some() { - return Err(CreateBindGroupError::DuplicateBinding(binding)); - } + let id = hub + .bind_groups + .register_identity(id_in, bind_group, &mut token); + tracing::debug!( + "Bind group {:?} {:#?}", + id, + hub.bind_groups.read(&mut token).0[id].used + ); + #[cfg(feature = "trace")] + if let Some(ref trace) = device.trace { + trace + .lock() + .add(trace::Action::CreateBindGroup(id.0, desc.clone())); } - let mut desc_sets = ArrayVec::<[_; 1]>::new(); device - .desc_allocator + .trackers .lock() - .allocate( - &device.raw, - &bind_group_layout.raw, - &bind_group_layout.desc_counts, - 1, - &mut desc_sets, - ) - .expect("failed to allocate descriptor set"); - let mut desc_set = desc_sets.pop().unwrap(); - - // Set the descriptor set's label for easier debugging. - if let Some(label) = desc.label.as_ref() { - unsafe { - device - .raw - .set_descriptor_set_name(desc_set.raw_mut(), &label); - } - } - - if let Some(start_binding) = write_map.keys().next().cloned() { - let descriptors = write_map - .into_iter() - .flat_map(|(_, list)| list) - .collect::>(); - let write = hal::pso::DescriptorSetWrite { - set: desc_set.raw(), - binding: start_binding, - array_offset: 0, - descriptors, - }; - unsafe { - device.raw.write_descriptor_sets(iter::once(write)); - } - } - desc_set + .bind_groups + .init(id, ref_count, PhantomData) + .unwrap(); + return (id.0, None); }; - let bind_group = binding_model::BindGroup { - raw: desc_set, - device_id: Stored { - value: id::Valid(device_id), - ref_count: device.life_guard.add_ref(), - }, - layout_id: id::Valid(desc.layout), - life_guard: LifeGuard::new(desc.label.borrow_or_default()), - used, - dynamic_binding_info, - }; - let ref_count = bind_group.life_guard.add_ref(); - let id = hub .bind_groups - .register_identity(id_in, bind_group, &mut token); - tracing::debug!( - "Bind group {:?} {:#?}", - id, - hub.bind_groups.read(&mut token).0[id].used - ); - #[cfg(feature = "trace")] - if let Some(ref trace) = device.trace { - trace - .lock() - .add(trace::Action::CreateBindGroup(id.0, desc.clone())); - } - - device - .trackers - .lock() - .bind_groups - .init(id, ref_count, PhantomData) - .unwrap(); - Ok(id.0) + .register_error(id_in, desc.label.borrow_or_default(), &mut token); + (id, Some(error)) } pub fn bind_group_label(&self, id: id::BindGroupId) -> String { B::hub(self).bind_groups.label_for_resource(id) } - pub fn bind_group_error( - &self, - id_in: Input, - label: Option<&str>, - ) -> id::BindGroupId { - B::hub(self) - .bind_groups - .register_error(id_in, label.unwrap_or(""), &mut Token::root()) - } - pub fn bind_group_drop(&self, bind_group_id: id::BindGroupId) { span!(_guard, INFO, "BindGroup::drop"); @@ -3847,12 +3867,6 @@ impl Global { B::hub(self).devices.label_for_resource(id) } - pub fn device_error(&self, id_in: Input) -> id::DeviceId { - B::hub(self) - .devices - .register_error(id_in, "", &mut Token::root()) - } - pub fn device_drop(&self, device_id: id::DeviceId) { span!(_guard, INFO, "Device::drop"); diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index 354649819..8fbd08526 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -31,7 +31,7 @@ pub(crate) fn new_render_bundle_encoder_descriptor<'a>( #[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub enum Action<'a> { Init { - desc: wgt::DeviceDescriptor, + desc: crate::device::DeviceDescriptor<'a>, backend: wgt::Backend, }, CreateBuffer(id::BufferId, crate::resource::BufferDescriptor<'a>), diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 2a3d6fe18..c3fdbd44f 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -4,13 +4,13 @@ use crate::{ backend, - device::Device, + device::{Device, DeviceDescriptor}, hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, id::{AdapterId, DeviceId, SurfaceId, Valid}, - span, LifeGuard, PrivateFeatures, Stored, MAX_BIND_GROUPS, + span, LabelHelpers, LifeGuard, PrivateFeatures, Stored, MAX_BIND_GROUPS, }; -use wgt::{Backend, BackendBit, DeviceDescriptor, PowerPreference, BIND_BUFFER_ALIGNMENT}; +use wgt::{Backend, BackendBit, PowerPreference, BIND_BUFFER_ALIGNMENT}; use hal::{ adapter::{AdapterInfo as HalAdapterInfo, DeviceType as HalDeviceType, PhysicalDevice as _}, @@ -127,7 +127,7 @@ pub struct Adapter { life_guard: LifeGuard, } -impl Adapter { +impl Adapter { fn new(raw: hal::adapter::Adapter) -> Self { span!(_guard, INFO, "Adapter::new"); @@ -227,6 +227,150 @@ impl Adapter { life_guard: LifeGuard::new(""), } } + + fn create_device( + &self, + self_id: AdapterId, + desc: &DeviceDescriptor, + trace_path: Option<&std::path::Path>, + ) -> Result, RequestDeviceError> { + // Verify all features were exposed by the adapter + if !self.features.contains(desc.features) { + return Err(RequestDeviceError::UnsupportedFeature( + desc.features - self.features, + )); + } + + // Verify feature preconditions + if desc + .features + .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS) + && self.raw.info.device_type == hal::adapter::DeviceType::DiscreteGpu + { + tracing::warn!("Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. This is a massive performance footgun and likely not what you wanted"); + } + + let phd = &self.raw.physical_device; + let available_features = phd.features(); + + // Check features that are always needed + let wishful_features = hal::Features::ROBUST_BUFFER_ACCESS + | hal::Features::VERTEX_STORES_AND_ATOMICS + | hal::Features::FRAGMENT_STORES_AND_ATOMICS + | hal::Features::NDC_Y_UP + | hal::Features::INDEPENDENT_BLENDING + | hal::Features::SAMPLER_ANISOTROPY + | hal::Features::IMAGE_CUBE_ARRAY; + let mut enabled_features = available_features & wishful_features; + if enabled_features != wishful_features { + tracing::warn!( + "Missing internal features: {:?}", + wishful_features - enabled_features + ); + } + + // Features + enabled_features.set( + hal::Features::TEXTURE_DESCRIPTOR_ARRAY, + desc.features + .contains(wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY), + ); + enabled_features.set( + hal::Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING, + desc.features + .contains(wgt::Features::SAMPLED_TEXTURE_ARRAY_DYNAMIC_INDEXING), + ); + enabled_features.set( + hal::Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING, + desc.features + .contains(wgt::Features::SAMPLED_TEXTURE_ARRAY_NON_UNIFORM_INDEXING), + ); + enabled_features.set( + hal::Features::UNSIZED_DESCRIPTOR_ARRAY, + desc.features.contains(wgt::Features::UNSIZED_BINDING_ARRAY), + ); + enabled_features.set( + hal::Features::MULTI_DRAW_INDIRECT, + desc.features.contains(wgt::Features::MULTI_DRAW_INDIRECT), + ); + enabled_features.set( + hal::Features::DRAW_INDIRECT_COUNT, + desc.features + .contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT), + ); + enabled_features.set( + hal::Features::NON_FILL_POLYGON_MODE, + desc.features.contains(wgt::Features::NON_FILL_POLYGON_MODE), + ); + + let family = self + .raw + .queue_families + .iter() + .find(|family| family.queue_type().supports_graphics()) + .ok_or(RequestDeviceError::NoGraphicsQueue)?; + let mut gpu = + unsafe { phd.open(&[(family, &[1.0])], enabled_features) }.map_err(|err| { + use hal::device::CreationError::*; + match err { + DeviceLost => RequestDeviceError::DeviceLost, + InitializationFailed => RequestDeviceError::Internal, + OutOfMemory(_) => RequestDeviceError::OutOfMemory, + _ => panic!("failed to create `gfx-hal` device: {}", err), + } + })?; + + if let Some(_) = desc.label { + //TODO + } + + let limits = phd.limits(); + assert_eq!( + 0, + BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment, + "Adapter storage buffer offset alignment not compatible with WGPU" + ); + assert_eq!( + 0, + BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment, + "Adapter uniform buffer offset alignment not compatible with WGPU" + ); + if self.limits < desc.limits { + return Err(RequestDeviceError::LimitsExceeded); + } + + let mem_props = phd.memory_properties(); + if !desc.shader_validation { + tracing::warn!("Shader validation is disabled"); + } + let private_features = PrivateFeatures { + shader_validation: desc.shader_validation, + anisotropic_filtering: enabled_features.contains(hal::Features::SAMPLER_ANISOTROPY), + texture_d24: phd + .format_properties(Some(hal::format::Format::X8D24Unorm)) + .optimal_tiling + .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), + texture_d24_s8: phd + .format_properties(Some(hal::format::Format::D24UnormS8Uint)) + .optimal_tiling + .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), + }; + + Device::new( + gpu.device, + Stored { + value: Valid(self_id), + ref_count: self.life_guard.add_ref(), + }, + gpu.queue_groups.swap_remove(0), + mem_props, + limits, + private_features, + desc, + trace_path, + ) + .or(Err(RequestDeviceError::OutOfMemory)) + } } impl crate::hub::Resource for Adapter { @@ -668,152 +812,29 @@ impl Global { desc: &DeviceDescriptor, trace_path: Option<&std::path::Path>, id_in: Input, - ) -> Result { + ) -> (DeviceId, Option) { span!(_guard, INFO, "Adapter::request_device"); let hub = B::hub(self); let mut token = Token::root(); - let device = { - let (adapter_guard, _) = hub.adapters.read(&mut token); - let adapter = adapter_guard - .get(adapter_id) - .map_err(|_| RequestDeviceError::InvalidAdapter)?; - let phd = &adapter.raw.physical_device; - // Verify all features were exposed by the adapter - if !adapter.features.contains(desc.features) { - return Err(RequestDeviceError::UnsupportedFeature( - desc.features - adapter.features, - )); - } - - // Verify feature preconditions - if desc - .features - .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS) - && adapter.raw.info.device_type == hal::adapter::DeviceType::DiscreteGpu - { - tracing::warn!("Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. This is a massive performance footgun and likely not what you wanted"); - } - - let available_features = adapter.raw.physical_device.features(); - - // Check features that are always needed - let wishful_features = hal::Features::ROBUST_BUFFER_ACCESS - | hal::Features::VERTEX_STORES_AND_ATOMICS - | hal::Features::FRAGMENT_STORES_AND_ATOMICS - | hal::Features::NDC_Y_UP - | hal::Features::INDEPENDENT_BLENDING - | hal::Features::SAMPLER_ANISOTROPY - | hal::Features::IMAGE_CUBE_ARRAY; - let mut enabled_features = available_features & wishful_features; - if enabled_features != wishful_features { - tracing::warn!( - "Missing internal features: {:?}", - wishful_features - enabled_features - ); - } - - // Features - enabled_features.set( - hal::Features::TEXTURE_DESCRIPTOR_ARRAY, - desc.features - .contains(wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY), - ); - enabled_features.set( - hal::Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING, - desc.features - .contains(wgt::Features::SAMPLED_TEXTURE_ARRAY_DYNAMIC_INDEXING), - ); - enabled_features.set( - hal::Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING, - desc.features - .contains(wgt::Features::SAMPLED_TEXTURE_ARRAY_NON_UNIFORM_INDEXING), - ); - enabled_features.set( - hal::Features::UNSIZED_DESCRIPTOR_ARRAY, - desc.features.contains(wgt::Features::UNSIZED_BINDING_ARRAY), - ); - enabled_features.set( - hal::Features::MULTI_DRAW_INDIRECT, - desc.features.contains(wgt::Features::MULTI_DRAW_INDIRECT), - ); - enabled_features.set( - hal::Features::DRAW_INDIRECT_COUNT, - desc.features - .contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT), - ); - enabled_features.set( - hal::Features::NON_FILL_POLYGON_MODE, - desc.features.contains(wgt::Features::NON_FILL_POLYGON_MODE), - ); - - let family = adapter - .raw - .queue_families - .iter() - .find(|family| family.queue_type().supports_graphics()) - .ok_or(RequestDeviceError::NoGraphicsQueue)?; - let mut gpu = - unsafe { phd.open(&[(family, &[1.0])], enabled_features) }.map_err(|err| { - use hal::device::CreationError::*; - match err { - DeviceLost => RequestDeviceError::DeviceLost, - InitializationFailed => RequestDeviceError::Internal, - OutOfMemory(_) => RequestDeviceError::OutOfMemory, - _ => panic!("failed to create `gfx-hal` device: {}", err), - } - })?; - - let limits = phd.limits(); - assert_eq!( - 0, - BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment, - "Adapter storage buffer offset alignment not compatible with WGPU" - ); - assert_eq!( - 0, - BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment, - "Adapter uniform buffer offset alignment not compatible with WGPU" - ); - if adapter.limits < desc.limits { - return Err(RequestDeviceError::LimitsExceeded); - } - - let mem_props = phd.memory_properties(); - if !desc.shader_validation { - tracing::warn!("Shader validation is disabled"); - } - let private_features = PrivateFeatures { - shader_validation: desc.shader_validation, - anisotropic_filtering: enabled_features.contains(hal::Features::SAMPLER_ANISOTROPY), - texture_d24: phd - .format_properties(Some(hal::format::Format::X8D24Unorm)) - .optimal_tiling - .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), - texture_d24_s8: phd - .format_properties(Some(hal::format::Format::D24UnormS8Uint)) - .optimal_tiling - .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), + let error = loop { + let (adapter_guard, mut token) = hub.adapters.read(&mut token); + let adapter = match adapter_guard.get(adapter_id) { + Ok(adapter) => adapter, + Err(_) => break RequestDeviceError::InvalidAdapter, }; - - Device::new( - gpu.device, - Stored { - value: Valid(adapter_id), - ref_count: adapter.life_guard.add_ref(), - }, - gpu.queue_groups.swap_remove(0), - mem_props, - limits, - private_features, - desc, - trace_path, - ) - .or(Err(RequestDeviceError::OutOfMemory))? + let device = match adapter.create_device(adapter_id, desc, trace_path) { + Ok(device) => device, + Err(e) => break e, + }; + let id = hub.devices.register_identity(id_in, device, &mut token); + return (id.0, None); }; - let id = hub.devices.register_identity(id_in, device, &mut token); - Ok(id.0) + let id = hub + .devices + .register_error(id_in, desc.label.borrow_or_default(), &mut token); + (id, Some(error)) } } diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 202c84d77..58e8de0be 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -28,7 +28,7 @@ pub fn check_buffer_usage( } } -#[derive(Clone, Debug, Error)] +#[derive(Clone, Debug, Error, PartialEq)] #[error("texture usage is {actual:?} which does not contain required usage {expected:?}")] pub struct MissingTextureUsageError { pub(crate) actual: wgt::TextureUsage, diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index 025bc61c2..7ccc1198b 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -382,7 +382,9 @@ impl Default for Limits { #[derive(Clone, Debug, Default)] #[cfg_attr(feature = "trace", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] -pub struct DeviceDescriptor { +pub struct DeviceDescriptor { + /// Debug label for the device. + pub label: L, /// Features that the device should support. If any feature is not supported by /// the adapter, creating a device will panic. pub features: Features, @@ -394,6 +396,17 @@ pub struct DeviceDescriptor { pub shader_validation: bool, } +impl DeviceDescriptor { + pub fn map_label(&self, fun: impl FnOnce(&L) -> K) -> DeviceDescriptor { + DeviceDescriptor { + label: fun(&self.label), + features: self.features, + limits: self.limits.clone(), + shader_validation: self.shader_validation, + } + } +} + bitflags::bitflags! { /// Describes the shader stages that a binding will be visible from. ///