diff --git a/player/src/lib.rs b/player/src/lib.rs index 0f9c8842d..fe952e3d8 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -140,9 +140,7 @@ impl Player { } Action::CreateTextureView { id, parent, desc } => { let parent_texture = self.resolve_texture_id(parent); - let texture_view = device - .create_texture_view(&parent_texture, &desc) - .expect("create_texture_view error"); + let (texture_view, _error) = device.create_texture_view(&parent_texture, &desc); self.texture_views.insert(id, texture_view); } Action::DropTextureView(id) => { diff --git a/wgpu-core/src/as_hal.rs b/wgpu-core/src/as_hal.rs index 4e724b671..8dcc5b0f4 100644 --- a/wgpu-core/src/as_hal.rs +++ b/wgpu-core/src/as_hal.rs @@ -197,7 +197,7 @@ impl Global { let hub = &self.hub; - let view = hub.texture_views.get(id).get().ok()?; + let view = hub.texture_views.get(id); SnatchableResourceGuard::new(view) } diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index c4bc341be..52313b6e0 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -1635,6 +1635,7 @@ impl Global { let base = pass_base!(pass, scope); let hub = &self.hub; + let buffer_transitions = pass_try!( base, scope, @@ -1653,8 +1654,10 @@ impl Global { scope, texture_transitions .map(|texture_transition| -> Result<_, InvalidResourceError> { + let texture_view = hub.texture_views.get(texture_transition.texture); + texture_view.check_valid()?; Ok(wgt::TextureTransition { - texture: hub.texture_views.get(texture_transition.texture).get()?, + texture: texture_view, selector: texture_transition.selector, state: texture_transition.state, }) diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 75a150c47..45596f2f2 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -278,9 +278,9 @@ pub struct RenderPassDescriptor<'a> { pub struct ResolvedRenderPassDescriptor<'a> { pub label: Label<'a>, /// The color attachments of the render pass. - pub color_attachments: Cow<'a, [Option>>]>, + pub color_attachments: Cow<'a, [Option>>]>, /// The depth and stencil attachment of the render pass, if any. - pub depth_stencil_attachment: Option>>, + pub depth_stencil_attachment: Option>>, /// Defines where and when timestamp values will be written for this pass. pub timestamp_writes: Option>>, /// Defines where the occlusion query results will be stored for this pass. @@ -1261,7 +1261,7 @@ impl RenderPassInfo { Ok(()) }; let mut add_view = |view: &TextureView, location| { - let render_extent = view.render_extent.map_err(|reason| { + let render_extent = view.state()?.render_extent.map_err(|reason| { RenderPassErrorInner::TextureViewIsNotRenderable { location, reason } })?; if let Some(ex) = extent { @@ -1552,13 +1552,13 @@ impl RenderPassInfo { resolve: true, }; - let render_extent = resolve_view.render_extent.map_err(|reason| { + let render_extent = resolve_view.state()?.render_extent.map_err(|reason| { RenderPassErrorInner::TextureViewIsNotRenderable { location: resolve_location, reason, } })?; - if color_view.render_extent.unwrap() != render_extent { + if color_view.state()?.render_extent.unwrap() != render_extent { return Err(RenderPassErrorInner::AttachmentsDimensionMismatch { expected_location: attachment_location, expected_extent: extent.unwrap_or_default(), @@ -1792,7 +1792,7 @@ impl RenderPassInfo { Some("(wgpu internal) Zero init discarded depth/stencil aspect"), instance_flags, ), - extent: view.render_extent.unwrap(), + extent: view.state()?.render_extent.unwrap(), sample_count: view.samples, color_attachments: &[], depth_stencil_attachment: Some(hal::DepthStencilAttachment { @@ -1859,7 +1859,7 @@ impl CommandEncoder { store_op, }) = color_attachment { - let view = view.clone().get()?; + view.check_valid()?; view.same_device(device)?; if matches!(*load_op, LoadOp::DontCare(..)) && device @@ -1885,10 +1885,10 @@ impl CommandEncoder { } let resolve_target = if let Some(resolve_target) = resolve_target { - let rt_arc = resolve_target.clone().get()?; - rt_arc.same_device(device)?; + resolve_target.check_valid()?; + resolve_target.same_device(device)?; - Some(rt_arc) + Some(resolve_target) } else { None }; @@ -1896,9 +1896,9 @@ impl CommandEncoder { arc_desc .color_attachments .push(Some(ArcRenderPassColorAttachment { - view, + view: Arc::clone(view), depth_slice: *depth_slice, - resolve_target, + resolve_target: resolve_target.map(Arc::clone), load_op: *load_op, store_op: *store_op, })); @@ -1911,7 +1911,8 @@ impl CommandEncoder { arc_desc.depth_stencil_attachment = if let Some(depth_stencil_attachment) = desc.depth_stencil_attachment { - let view = depth_stencil_attachment.view.get()?; + let view = depth_stencil_attachment.view; + view.check_valid()?; view.same_device(device)?; let format = view.desc.format; diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index b5516e07f..c34ef48df 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -468,49 +468,20 @@ impl Global { let fid = hub.texture_views.prepare(id_in); - let error = 'error: { - let texture = hub.textures.get(texture_id); - let device = &texture.device; + let texture = hub.textures.get(texture_id); + let device = &texture.device; - let view = match device.create_texture_view(&texture, desc) { - Ok(view) => view, - Err(e) => break 'error e, - }; + let (view, error) = device.create_texture_view(&texture, desc); - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::CreateTextureView { - id: view.to_trace(), - parent: texture.to_trace(), - desc: desc.clone(), - }); - } + let id = fid.assign(view); - let id = fid.assign(Fallible::Valid(view)); - - api_log!("Texture::create_view({texture_id:?}) -> {id:?}"); - - return (id, None); - }; - - let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); - (id, Some(error)) + (id, error) } pub fn texture_view_drop(&self, texture_view_id: id::TextureViewId) { - profiling::scope!("TextureView::drop"); - api_log!("TextureView::drop {texture_view_id:?}"); - let hub = &self.hub; let _view = hub.texture_views.remove(texture_view_id); - - #[cfg(feature = "trace")] - if let Ok(view) = _view.get() { - if let Some(t) = view.device.trace.lock().as_mut() { - t.add(trace::Action::DropTextureView(view.to_trace())); - } - } } pub fn device_create_external_texture( @@ -534,12 +505,8 @@ impl Global { let planes = planes .iter() - .map(|plane_id| self.hub.texture_views.get(*plane_id).get()) - .collect::, _>>(); - let planes = match planes { - Ok(planes) => planes, - Err(error) => break 'error error.into(), - }; + .map(|plane_id| self.hub.texture_views.get(*plane_id)) + .collect::>(); let external_texture = match device.create_external_texture(desc, &planes) { Ok(external_texture) => external_texture, @@ -765,7 +732,7 @@ impl Global { e: &BindGroupEntry<'a>, buffer_storage: &Storage>, sampler_storage: &Storage>, - texture_view_storage: &Storage>, + texture_view_storage: &Storage>, tlas_storage: &Storage>, external_texture_storage: &Storage>, ) -> Result, binding_model::CreateBindGroupError> @@ -787,12 +754,7 @@ impl Global { .get() .map_err(binding_model::CreateBindGroupError::from) }; - let resolve_view = |id: &id::TextureViewId| { - texture_view_storage - .get(*id) - .get() - .map_err(binding_model::CreateBindGroupError::from) - }; + let resolve_view = |id: &id::TextureViewId| texture_view_storage.get(*id); let resolve_tlas = |id: &id::TlasId| { tlas_storage .get(*id) @@ -827,13 +789,10 @@ impl Global { ResolvedBindingResource::SamplerArray(Cow::Owned(samplers)) } BindingResource::TextureView(ref view) => { - ResolvedBindingResource::TextureView(resolve_view(view)?) + ResolvedBindingResource::TextureView(resolve_view(view)) } BindingResource::TextureViewArray(ref views) => { - let views = views - .iter() - .map(resolve_view) - .collect::, _>>()?; + let views = views.iter().map(resolve_view).collect::>(); ResolvedBindingResource::TextureViewArray(Cow::Owned(views)) } BindingResource::AccelerationStructure(ref tlas) => { diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 2e09f25f3..2a660d9d1 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -49,7 +49,7 @@ use crate::{ resource::{ self, Buffer, ExternalTexture, Fallible, Labeled, ParentDevice, QuerySet, RawResourceAccess, ResourceState, Sampler, StagingBuffer, Texture, TextureView, - TextureViewNotRenderableReason, Tlas, TrackingData, + TextureViewNotRenderableReason, TextureViewState, Tlas, TrackingData, }, resource_log, snatch::{SnatchGuard, SnatchLock, Snatchable}, @@ -733,7 +733,11 @@ impl Device { let Some(view) = view.upgrade() else { continue; }; - let Some(raw_view) = view.raw.snatch(&mut self.snatchable_lock.write()) + let Ok(view_state) = view.state() else { + continue; + }; + let Some(raw_view) = + view_state.raw.snatch(&mut self.snatchable_lock.write()) else { continue; }; @@ -1795,7 +1799,7 @@ impl Device { texture } - pub fn create_texture_view( + fn create_texture_view_inner( self: &Arc, texture: &Arc, desc: &resource::TextureViewDescriptor, @@ -2127,7 +2131,10 @@ impl Device { }; let view = TextureView { - raw: Snatchable::new(raw), + state: ResourceState::Valid(TextureViewState { + raw: Snatchable::new(raw), + render_extent, + }), parent: texture.clone(), device: self.clone(), desc: resource::HalTextureViewDescriptor { @@ -2138,7 +2145,6 @@ impl Device { range: resolved_range, }, format_features: texture.format_features, - render_extent, samples: texture.desc.sample_count, selector, label: desc.label.to_string(), @@ -2154,6 +2160,36 @@ impl Device { Ok(view) } + pub fn create_texture_view( + self: &Arc, + texture: &Arc, + desc: &resource::TextureViewDescriptor, + ) -> (Arc, Option) { + let (view, error) = match self.create_texture_view_inner(texture, desc) { + Ok(view) => (view, None), + Err(e) => (TextureView::invalid(self, texture, desc), Some(e)), + }; + + api_log!( + "Texture::create_view({:?}) -> {:?}", + Arc::as_ptr(texture), + Arc::as_ptr(&view) + ); + + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use crate::device::trace; + use trace::IntoTrace as _; + trace.add(trace::Action::CreateTextureView { + id: view.to_trace(), + parent: texture.to_trace(), + desc: desc.clone(), + }); + } + + (view, error) + } + pub fn create_external_texture( self: &Arc, desc: &resource::ExternalTextureDescriptor, @@ -3185,6 +3221,7 @@ impl Device { texture_init_actions: &mut Vec, snatch_guard: &'a SnatchGuard<'a>, ) -> Result, CreateBindGroupError> { + view.check_valid()?; view.same_device(self)?; let internal_use = self.texture_use_parameters( diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 3b22e4a14..57a851bfc 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -208,7 +208,7 @@ pub struct Hub { pub(crate) buffers: Registry>, pub(crate) staging_buffers: Registry, pub(crate) textures: Registry>, - pub(crate) texture_views: Registry>, + pub(crate) texture_views: Registry>, pub(crate) external_textures: Registry>, pub(crate) samplers: Registry>, pub(crate) blas_s: Registry>, diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 16dea1240..045a57030 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -17,6 +17,7 @@ use wgt::{ #[cfg(feature = "trace")] use crate::device::trace; use crate::{ + api_log, binding_model::{BindGroup, BindingError}, device::{ queue, resource::DeferredDestroy, BufferMapPendingClosure, Device, DeviceError, @@ -1928,15 +1929,20 @@ pub enum TextureViewNotRenderableReason { } #[derive(Debug)] -pub struct TextureView { +pub struct TextureViewState { pub(crate) raw: Snatchable>, + /// This is `Err` only if the texture view is not renderable + pub(crate) render_extent: Result, +} + +#[derive(Debug)] +pub struct TextureView { + pub(crate) state: ResourceState, // if it's a surface texture - it's none pub(crate) parent: Arc, pub(crate) device: Arc, pub(crate) desc: HalTextureViewDescriptor, pub(crate) format_features: wgt::TextureFormatFeatures, - /// This is `Err` only if the texture view is not renderable - pub(crate) render_extent: Result, pub(crate) samples: u32, pub(crate) selector: TextureSelector, /// The `label` from the descriptor used to create the resource. @@ -1944,8 +1950,21 @@ pub struct TextureView { } impl Drop for TextureView { + #[expect(trivial_casts)] fn drop(&mut self) { - if let Some(raw) = self.raw.take() { + profiling::scope!("TextureView::drop"); + api_log!("TextureView::drop {:?}", self as *const _); + #[cfg(feature = "trace")] + if let Some(t) = self.device.trace.lock().as_mut() { + t.add(trace::Action::DropTextureView(unsafe { + trace::to_trace(self) + })); + } + let ResourceState::Valid(state) = &mut self.state else { + return; + }; + + if let Some(raw) = state.raw.take() { resource_log!("Destroy raw {}", self.error_ident()); unsafe { self.device.raw().destroy_texture_view(raw); @@ -1958,7 +1977,9 @@ impl RawResourceAccess for TextureView { type DynResource = dyn hal::DynTextureView; fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> { - self.raw.get(guard).map(|it| it.as_ref()) + self.state() + .ok() + .and_then(|state| state.raw.get(guard).map(|it| it.as_ref())) } fn try_raw<'a>( @@ -1989,6 +2010,51 @@ impl TextureView { }) } } + + pub(crate) fn state(&self) -> Result<&TextureViewState, InvalidResourceError> { + match &self.state { + ResourceState::Valid(state) => Ok(state), + ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())), + } + } + + pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> { + self.state().map(|_| ()) + } + + pub(crate) fn invalid( + device: &Arc, + texture: &Arc, + desc: &TextureViewDescriptor, + ) -> Arc { + // we do best effort to fill the descriptor with sensible values + Arc::new(TextureView { + state: ResourceState::Invalid, + parent: texture.clone(), + device: device.clone(), + desc: HalTextureViewDescriptor { + texture_format: texture.desc.format, + format: desc.format.unwrap_or(texture.desc.format), + usage: desc.usage.unwrap_or(texture.desc.usage), + dimension: desc.dimension.unwrap_or(match texture.desc.dimension { + wgt::TextureDimension::D1 => wgt::TextureViewDimension::D1, + wgt::TextureDimension::D2 => wgt::TextureViewDimension::D2, + wgt::TextureDimension::D3 => wgt::TextureViewDimension::D3, + }), + range: desc.range, + }, + format_features: texture.format_features, + samples: texture.desc.sample_count, + selector: TextureSelector { + mips: desc.range.base_mip_level + ..(desc.range.base_mip_level + desc.range.mip_level_count.unwrap_or_default()), + layers: desc.range.base_array_layer + ..(desc.range.base_array_layer + + desc.range.array_layer_count.unwrap_or_default()), + }, + label: desc.label.to_string(), + }) + } } #[derive(Clone, Debug, Error)]