diff --git a/player/src/lib.rs b/player/src/lib.rs index e4e3621c4..921fb48ad 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -306,11 +306,13 @@ impl GlobalPlay for wgc::hub::Global { .unwrap(); } A::Submit(_index, commands) => { - let encoder = self.device_create_command_encoder::( - device, - &wgt::CommandEncoderDescriptor { label: ptr::null() }, - comb_manager.alloc(device.backend()), - ); + let encoder = self + .device_create_command_encoder::( + device, + &wgt::CommandEncoderDescriptor { label: ptr::null() }, + comb_manager.alloc(device.backend()), + ) + .unwrap(); let cmdbuf = self.encode_commands::(encoder, commands); self.queue_submit::(device, &[cmdbuf]).unwrap(); } diff --git a/wgpu-core/src/command/allocator.rs b/wgpu-core/src/command/allocator.rs index 8d32574a7..5c555d0d7 100644 --- a/wgpu-core/src/command/allocator.rs +++ b/wgpu-core/src/command/allocator.rs @@ -10,6 +10,7 @@ use crate::{ use hal::{command::CommandBuffer as _, device::Device as _, pool::CommandPool as _}; use parking_lot::Mutex; +use thiserror::Error; use std::thread; @@ -80,30 +81,37 @@ impl CommandAllocator { limits: wgt::Limits, private_features: PrivateFeatures, #[cfg(feature = "trace")] enable_tracing: bool, - ) -> CommandBuffer { + ) -> Result, CommandAllocatorError> { //debug_assert_eq!(device_id.backend(), B::VARIANT); let thread_id = thread::current().id(); let mut inner = self.inner.lock(); - let init = inner - .pools - .entry(thread_id) - .or_insert_with(|| CommandPool { - raw: unsafe { - tracing::info!("Starting on thread {:?}", thread_id); - device.create_command_pool( - self.queue_family, - hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL, - ) - } - .unwrap(), - total: 0, - available: Vec::new(), - pending: Vec::new(), - }) - .allocate(); + use std::collections::hash_map::Entry; + let pool = match inner.pools.entry(thread_id) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + tracing::info!("Starting on thread {:?}", thread_id); + let raw = unsafe { + device + .create_command_pool( + self.queue_family, + hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL, + ) + .or(Err(CommandAllocatorError::OutOfMemory))? + }; + let pool = CommandPool { + raw, + total: 0, + available: Vec::new(), + pending: Vec::new(), + }; + e.insert(pool) + } + }; - CommandBuffer { + let init = pool.allocate(); + + Ok(CommandBuffer { raw: vec![init], is_recording: true, recorded_thread_id: thread_id, @@ -118,12 +126,15 @@ impl CommandAllocator { } else { None }, - } + }) } } impl CommandAllocator { - pub fn new(queue_family: hal::queue::QueueFamilyId, device: &B::Device) -> Self { + pub fn new( + queue_family: hal::queue::QueueFamilyId, + device: &B::Device, + ) -> Result { let internal_thread_id = thread::current().id(); tracing::info!("Starting on (internal) thread {:?}", internal_thread_id); let mut pools = FastHashMap::default(); @@ -136,18 +147,18 @@ impl CommandAllocator { queue_family, hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL, ) - .unwrap() + .or(Err(CommandAllocatorError::OutOfMemory))? }, total: 0, available: Vec::new(), pending: Vec::new(), }, ); - CommandAllocator { + Ok(CommandAllocator { queue_family, internal_thread_id, inner: Mutex::new(Inner { pools }), - } + }) } fn allocate_for_thread_id(&self, thread_id: thread::ThreadId) -> B::CommandBuffer { @@ -242,3 +253,9 @@ impl CommandAllocator { } } } + +#[derive(Clone, Debug, Error)] +pub enum CommandAllocatorError { + #[error("not enough memory left")] + OutOfMemory, +} diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 1708aea4f..23f2cefdd 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -10,6 +10,7 @@ mod render; mod transfer; pub(crate) use self::allocator::CommandAllocator; +pub use self::allocator::CommandAllocatorError; pub use self::bundle::*; pub use self::compute::*; pub use self::render::*; diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 94cf1588d..c190efbdd 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -413,6 +413,8 @@ pub enum RenderPassError { InvalidResolveSourceSampleCount, #[error("resolve target must have a sample count of 1")] InvalidResolveTargetSampleCount, + #[error("not enough memory left")] + OutOfMemory, #[error("extent state {state_extent:?} must match extent from view {view_extent:?}")] ExtentStateMismatch { state_extent: hal::image::Extent, @@ -885,7 +887,7 @@ impl Global { device .raw .create_framebuffer(&render_pass, attachments, extent.unwrap()) - .unwrap() + .or(Err(RenderPassError::OutOfMemory))? }; cmb.used_swap_chain = Some((sc_id, framebuffer)); &mut cmb.used_swap_chain.as_mut().unwrap().1 @@ -905,13 +907,15 @@ impl Global { } }); unsafe { - device.raw.create_framebuffer( - &render_pass, - attachments, - extent.unwrap(), - ) + device + .raw + .create_framebuffer( + &render_pass, + attachments, + extent.unwrap(), + ) + .or(Err(RenderPassError::OutOfMemory))? } - .unwrap() }; e.insert(fb) } diff --git a/wgpu-core/src/conv.rs b/wgpu-core/src/conv.rs index 0e88169e4..2398601a1 100644 --- a/wgpu-core/src/conv.rs +++ b/wgpu-core/src/conv.rs @@ -7,6 +7,9 @@ use crate::{ resource, PrivateFeatures, }; +use std::convert::TryInto; +use thiserror::Error; + pub fn map_buffer_usage(usage: wgt::BufferUsage) -> (hal::buffer::Usage, hal::memory::Properties) { use hal::buffer::Usage as U; use hal::memory::Properties as P; @@ -429,11 +432,6 @@ pub fn map_vertex_format(vertex_format: wgt::VertexFormat) -> hal::format::Forma } } -fn checked_u32_as_u16(value: u32) -> u16 { - assert!(value <= ::std::u16::MAX as u32); - value as u16 -} - pub fn is_power_of_two(val: u32) -> bool { val != 0 && (val & (val - 1)) == 0 } @@ -446,28 +444,54 @@ pub fn map_texture_dimension_size( depth, }: wgt::Extent3d, sample_size: u32, -) -> hal::image::Kind { +) -> Result { use hal::image::Kind as H; use wgt::TextureDimension::*; - match dimension { + Ok(match dimension { D1 => { - assert_eq!(height, 1); - assert_eq!(sample_size, 1); - H::D1(width, checked_u32_as_u16(depth)) + if height != 1 { + return Err(MapTextureDimensionSizeError::InvalidHeight); + } + if sample_size != 1 { + return Err(MapTextureDimensionSizeError::InvalidSampleCount( + sample_size, + )); + } + let layers = depth + .try_into() + .or(Err(MapTextureDimensionSizeError::TooManyLayers(depth)))?; + H::D1(width, layers) } D2 => { - assert!( - sample_size <= 32 && is_power_of_two(sample_size), - "Invalid sample_count of {}", - sample_size - ); - H::D2(width, height, checked_u32_as_u16(depth), sample_size as u8) + if sample_size > 32 || !is_power_of_two(sample_size) { + return Err(MapTextureDimensionSizeError::InvalidSampleCount( + sample_size, + )); + } + let layers = depth + .try_into() + .or(Err(MapTextureDimensionSizeError::TooManyLayers(depth)))?; + H::D2(width, height, layers, sample_size as u8) } D3 => { - assert_eq!(sample_size, 1); + if sample_size != 1 { + return Err(MapTextureDimensionSizeError::InvalidSampleCount( + sample_size, + )); + } H::D3(width, height, depth) } - } + }) +} + +#[derive(Clone, Debug, Error)] +pub enum MapTextureDimensionSizeError { + #[error("too many layers ({0}) for texture array")] + TooManyLayers(u32), + #[error("1D textures must have height set to 1")] + InvalidHeight, + #[error("sample count {0} is invalid")] + InvalidSampleCount(u32), } pub fn map_texture_view_dimension(dimension: wgt::TextureViewDimension) -> hal::image::ViewKind { diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index ce166181a..0ab8e996b 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -304,7 +304,7 @@ impl LifetimeTracker { let done_count = self .active .iter() - .position(|a| unsafe { !device.get_fence_status(&a.fence).unwrap() }) + .position(|a| unsafe { !device.get_fence_status(&a.fence).unwrap_or(false) }) .unwrap_or_else(|| self.active.len()); let last_done = if done_count != 0 { self.active[done_count - 1].index diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index 3a70b158b..db6477c29 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -217,8 +217,9 @@ impl Device { private_features: PrivateFeatures, desc: &wgt::DeviceDescriptor, trace_path: Option<&std::path::Path>, - ) -> Self { - let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw); + ) -> Result { + let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw) + .or(Err(CreateDeviceError::OutOfMemory))?; let heaps = unsafe { Heaps::new( &mem_props, @@ -240,7 +241,7 @@ impl Device { None => (), } - Device { + Ok(Device { raw, adapter_id, cmd_allocator, @@ -273,7 +274,7 @@ impl Device { limits: desc.limits.clone(), features: desc.features.clone(), pending_writes: queue::PendingWrites::new(), - } + }) } pub(crate) fn last_completed_submission_index(&self) -> SubmissionIndex { @@ -484,7 +485,7 @@ impl Device { _ => {} } - let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.sample_count); + let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.sample_count)?; let format = conv::map_texture_format(desc.format, self.private_features); let aspects = format.surface_desc().aspects; let usage = conv::map_texture_usage(desc.usage, aspects); @@ -2049,7 +2050,7 @@ impl Global { device_id: id::DeviceId, desc: &wgt::CommandEncoderDescriptor