Return a texture by the surface

This commit is contained in:
Dzmitry Malyshau authored and Dzmitry Malyshau committed 2021-08-11 20:58:42 -04:00
1 parent f78061bcef
commit dffe1f1793
20 files changed
+251 -348

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
- processing SPIR-V inputs for later translation now requires `spirv` compile feature enabled
- new `Features::SPIRV_SHADER_PASSTHROUGH` run-time feature allows providing pass-through SPIR-V (orthogonal to the compile feature)
- several bitflag names are renamed to plural: `TextureUsage`, `BufferUsage`, `ColorWrite`.
- the `SwapChain` is merged into `Surface`.
- the `SwapChain` is merged into `Surface`. Returned frames are `Texture` instead of `TextureView`.
- renamed `TextureUsage` bits: `SAMPLED` -> `TEXTURE_BINDING`, `STORAGE` -> `STORAGE_BINDING`.
- renamed `InputStepMode` to `VertexStepMode`
- Implemented `Rgb9e5Ufloat` format.
+2 -2
View File
@@ -204,9 +204,9 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
}
Action::GetSurfaceTexture { id, parent_id } => {
self.device_maintain_ids::<A>(device).unwrap();
self.surface_get_current_texture_view::<A>(parent_id, id)
self.surface_get_current_texture::<A>(parent_id, id)
.unwrap()
.view_id
.texture_id
.unwrap();
}
Action::CreateBindGroupLayout(id, desc) => {
-2
View File
@@ -91,8 +91,6 @@ pub enum CreateBindGroupError {
MissingTextureUsage(#[from] MissingTextureUsageError),
#[error("binding declared as a single item, but bind group is using it as an array")]
SingleBindingExpected,
#[error("unable to create a bind group with a surface image")]
SurfaceImage,
#[error("buffer offset {0} does not respect `BIND_BUFFER_ALIGNMENT`")]
UnalignedBufferOffset(wgt::BufferAddress),
#[error(
+2 -2
View File
@@ -233,8 +233,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.map_err(ClearError::InvalidTexture)?;
let _dst_raw = dst_texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(ClearError::InvalidTexture(dst))?;
if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) {
return Err(ClearError::MissingCopyDstUsageFlag(None, Some(dst)));
+20 -75
View File
@@ -16,7 +16,7 @@ use crate::{
instance::Surface,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
pipeline::PipelineFlags,
resource::{Texture, TextureView, TextureViewSource},
resource::{Texture, TextureView},
track::{StatefulTrackerSubset, TextureSelector, UsageConflict},
validation::{
check_buffer_usage, check_texture_usage, MissingBufferUsageError, MissingTextureUsageError,
@@ -513,6 +513,16 @@ struct RenderAttachment<'a> {
usage: hal::TextureUses,
}
impl<A: hal::Api> TextureView<A> {
fn to_render_attachment(&self, usage: hal::TextureUses) -> RenderAttachment {
RenderAttachment {
texture_id: &self.parent_id,
selector: &self.selector,
usage,
}
}
}
const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_TARGETS + hal::MAX_COLOR_TARGETS + 1;
type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
@@ -533,7 +543,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
cmd_buf: &mut CommandBuffer<A>,
view_guard: &'a Storage<TextureView<A>, id::TextureViewId>,
surface_guard: &'a Storage<Surface, id::SurfaceId>,
_surface_guard: &'a Storage<Surface, id::SurfaceId>,
) -> Result<Self, RenderPassErrorInner> {
profiling::scope!("start", "RenderPassInfo");
@@ -547,7 +557,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
let mut attachment_type_name = "";
let mut extent = None;
let mut sample_count = 0;
let mut used_surface = None::<(id::Valid<id::SurfaceId>, hal::TextureUses)>;
//TODO: remove this?
let used_surface = None::<(id::Valid<id::SurfaceId>, hal::TextureUses)>;
let mut add_view = |view: &TextureView<A>, type_name| {
if let Some(ex) = extent {
@@ -590,22 +601,13 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
));
}
let source_id = match view.source {
TextureViewSource::Native(ref source_id) => source_id,
TextureViewSource::Surface(_) => unreachable!(),
};
let usage = if at.is_read_only(ds_aspects)? {
is_ds_read_only = true;
hal::TextureUses::DEPTH_STENCIL_READ | hal::TextureUses::RESOURCE
} else {
hal::TextureUses::DEPTH_STENCIL_WRITE
};
render_attachments.push(RenderAttachment {
texture_id: source_id,
selector: &view.selector,
usage,
});
render_attachments.push(view.to_render_attachment(usage));
depth_stencil = Some(hal::DepthStencilAttachment {
target: hal::Attachment {
@@ -636,24 +638,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
));
}
match color_view.source {
TextureViewSource::Native(ref source_id) => {
render_attachments.push(RenderAttachment {
texture_id: source_id,
selector: &color_view.selector,
usage: hal::TextureUses::COLOR_TARGET,
});
}
TextureViewSource::Surface(source_id) => {
//HACK: guess the start usage based on the load op
let start_usage = match at.channel.load_op {
LoadOp::Load => hal::TextureUses::empty(),
LoadOp::Clear => hal::TextureUses::UNINITIALIZED,
};
assert!(used_surface.is_none());
used_surface = Some((source_id, start_usage));
}
};
render_attachments
.push(color_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));
let mut hal_resolve_target = None;
if let Some(resolve_target) = at.resolve_target {
@@ -675,21 +661,8 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
return Err(RenderPassErrorInner::InvalidResolveTargetSampleCount);
}
match resolve_view.source {
TextureViewSource::Native(ref source_id) => {
render_attachments.push(RenderAttachment {
texture_id: source_id,
selector: &resolve_view.selector,
usage: hal::TextureUses::COLOR_TARGET,
});
}
TextureViewSource::Surface(source_id) => {
//HACK: guess the start usage
let start_usage = hal::TextureUses::UNINITIALIZED;
assert!(used_surface.is_none());
used_surface = Some((source_id, start_usage));
}
};
render_attachments
.push(resolve_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));
hal_resolve_target = Some(hal::Attachment {
view: &resolve_view.raw,
@@ -712,21 +685,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
return Err(RenderPassErrorInner::InvalidSampleCount(sample_count));
}
if let Some((surface_id, start_usage)) = used_surface {
let suf_texture = A::get_surface(&surface_guard[surface_id])
.acquired_texture
.as_ref()
.unwrap();
let barrier = hal::TextureBarrier {
texture: std::borrow::Borrow::borrow(suf_texture),
usage: start_usage..hal::TextureUses::COLOR_TARGET,
range: wgt::ImageSubresourceRange::default(),
};
unsafe {
cmd_buf.encoder.raw.transition_textures(iter::once(barrier));
}
}
let view_data = AttachmentData {
colors: color_attachments
.iter()
@@ -771,7 +729,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
mut self,
raw: &mut A::CommandEncoder,
texture_guard: &Storage<Texture<A>, id::TextureId>,
surface_guard: &Storage<Surface, id::SurfaceId>,
_surface_guard: &Storage<Surface, id::SurfaceId>,
) -> Result<(StatefulTrackerSubset, Option<id::Valid<id::SurfaceId>>), RenderPassErrorInner>
{
profiling::scope!("finish", "RenderPassInfo");
@@ -779,19 +737,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
raw.end_render_pass();
}
if let Some(surface_id) = self.used_surface {
let suf = A::get_surface(&surface_guard[surface_id]);
let suf_texture = suf.acquired_texture.as_ref().unwrap();
let barrier = hal::TextureBarrier {
texture: std::borrow::Borrow::borrow(suf_texture),
usage: hal::TextureUses::COLOR_TARGET..hal::TextureUses::empty(),
range: wgt::ImageSubresourceRange::default(),
};
unsafe {
raw.transition_textures(iter::once(barrier));
}
}
for ra in self.render_attachments {
let texture = &texture_guard[ra.texture_id.value];
check_texture_usage(texture.desc.usage, TextureUsages::RENDER_ATTACHMENT)?;
+8 -8
View File
@@ -555,8 +555,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.unwrap();
let dst_raw = dst_texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(TransferError::InvalidTexture(destination.texture))?;
if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) {
return Err(
@@ -664,8 +664,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.unwrap();
let src_raw = src_texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(TransferError::InvalidTexture(source.texture))?;
if !src_texture.desc.usage.contains(TextureUsages::COPY_SRC) {
return Err(TransferError::MissingCopySrcUsageFlag.into());
@@ -801,8 +801,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.unwrap();
let src_raw = src_texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(TransferError::InvalidTexture(source.texture))?;
if !src_texture.desc.usage.contains(TextureUsages::COPY_SRC) {
return Err(TransferError::MissingCopySrcUsageFlag.into());
@@ -824,8 +824,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.unwrap();
let dst_raw = dst_texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(TransferError::InvalidTexture(destination.texture))?;
if !dst_texture.desc.usage.contains(TextureUsages::COPY_DST) {
return Err(
+13 -22
View File
@@ -307,20 +307,6 @@ impl<A: hal::Api> LifetimeTracker<A> {
}
impl<A: HalApi> LifetimeTracker<A> {
pub(super) fn schedule_texture_view_for_destruction(
&mut self,
id: id::Valid<id::TextureViewId>,
view: resource::TextureView<A>,
) {
let submit_index = view.life_guard.submission_index.load(Ordering::Acquire);
self.active
.iter_mut()
.find(|a| a.index == submit_index)
.map_or(&mut self.free_resources, |a| &mut a.last_resources)
.texture_views
.push((id, view.raw));
}
pub(super) fn triage_suspected<G: GlobalIdentityHandlerFactory>(
&mut self,
hub: &Hub<A, G>,
@@ -387,13 +373,14 @@ impl<A: HalApi> LifetimeTracker<A> {
}
if let Some(res) = hub.texture_views.unregister_locked(id.0, &mut *guard) {
match res.source {
resource::TextureViewSource::Native(ref source_id) => {
self.suspected_resources.textures.push(source_id.value);
}
resource::TextureViewSource::Surface { .. } => {}
};
self.schedule_texture_view_for_destruction(id, res);
self.suspected_resources.textures.push(res.parent_id.value);
let submit_index = res.life_guard.submission_index.load(Ordering::Acquire);
self.active
.iter_mut()
.find(|a| a.index == submit_index)
.map_or(&mut self.free_resources, |a| &mut a.last_resources)
.texture_views
.push((id, res.raw));
}
}
}
@@ -413,12 +400,16 @@ impl<A: HalApi> LifetimeTracker<A> {
if let Some(res) = hub.textures.unregister_locked(id.0, &mut *guard) {
let submit_index = res.life_guard.submission_index.load(Ordering::Acquire);
let raw = match res.inner {
resource::TextureInner::Native { raw: Some(raw) } => raw,
_ => continue,
};
self.active
.iter_mut()
.find(|a| a.index == submit_index)
.map_or(&mut self.free_resources, |a| &mut a.last_resources)
.textures
.extend(res.raw);
.push(raw);
}
}
}
+52 -87
View File
@@ -341,16 +341,6 @@ impl<A: HalApi> Device<A> {
self.life_tracker.lock()
}
pub(crate) fn schedule_rogue_texture_view_for_destruction<'this, 'token: 'this>(
&'this self,
view_id: id::Valid<id::TextureViewId>,
view: resource::TextureView<A>,
token: &mut Token<'token, Self>,
) {
self.lock_life(token)
.schedule_texture_view_for_destruction(view_id, view);
}
fn maintain<'this, 'token: 'this, G: GlobalIdentityHandlerFactory>(
&'this self,
hub: &Hub<A, G>,
@@ -570,7 +560,9 @@ impl<A: HalApi> Device<A> {
}
Ok(resource::Texture {
raw: Some(hal_texture),
inner: resource::TextureInner::Native {
raw: Some(hal_texture),
},
device_id: Stored {
value: id::Valid(self_id),
ref_count: self.life_guard.add_ref(),
@@ -619,8 +611,8 @@ impl<A: HalApi> Device<A> {
desc: &resource::TextureViewDescriptor,
) -> Result<resource::TextureView<A>, resource::CreateTextureViewError> {
let texture_raw = texture
.raw
.as_ref()
.inner
.as_raw()
.ok_or(resource::CreateTextureViewError::InvalidTexture)?;
let view_dim = match desc.dimension {
@@ -783,10 +775,10 @@ impl<A: HalApi> Device<A> {
Ok(resource::TextureView {
raw,
source: resource::TextureViewSource::Native(Stored {
parent_id: Stored {
value: id::Valid(texture_id),
ref_count: texture.life_guard.add_ref(),
}),
},
desc: resource::HalTextureViewDescriptor {
format: hal_desc.format,
dimension: hal_desc.dimension,
@@ -1433,25 +1425,18 @@ impl<A: HalApi> Device<A> {
"SampledTexture, ReadonlyStorageTexture or WriteonlyStorageTexture",
)?;
match view.source {
resource::TextureViewSource::Native(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,
)
.map_err(UsageConflict::from)?;
check_texture_usage(texture.desc.usage, pub_usage)?;
}
resource::TextureViewSource::Surface(_) => {
return Err(Error::SurfaceImage);
}
}
// Careful here: the texture may no longer have its own ref count,
// if it was deleted by the user.
used.textures
.change_extend(
view.parent_id.value,
&view.parent_id.ref_count,
view.selector.clone(),
internal_use,
)
.map_err(UsageConflict::from)?;
let texture = &texture_guard[view.parent_id.value];
check_texture_usage(texture.desc.usage, pub_usage)?;
let res_index = hal_textures.len();
hal_textures.push(hal::TextureBinding {
@@ -1480,30 +1465,23 @@ impl<A: HalApi> Device<A> {
.views
.use_extend(&*texture_view_guard, id, (), ())
.map_err(|_| Error::InvalidTextureView(id))?;
let (pub_usage, internal_use) =
Self::texture_use_parameters(binding, decl, view,
"SampledTextureArray, ReadonlyStorageTextureArray or WriteonlyStorageTextureArray"
)?;
let (pub_usage, internal_use) = Self::texture_use_parameters(
binding, decl, view,
"SampledTextureArray, ReadonlyStorageTextureArray or WriteonlyStorageTextureArray"
)?;
match view.source {
resource::TextureViewSource::Native(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,
)
.map_err(UsageConflict::from)?;
check_texture_usage(texture.desc.usage, pub_usage)?;
}
resource::TextureViewSource::Surface(_) => {
return Err(Error::SurfaceImage);
}
}
// Careful here: the texture may no longer have its own ref count,
// if it was deleted by the user.
used.textures
.change_extend(
view.parent_id.value,
&view.parent_id.ref_count,
view.selector.clone(),
internal_use,
)
.map_err(UsageConflict::from)?;
let texture = &texture_guard[view.parent_id.value];
check_texture_usage(texture.desc.usage, pub_usage)?;
hal_textures.push(hal::TextureBinding {
view: &view.raw,
@@ -2450,14 +2428,6 @@ impl<A: hal::Api> Device<A> {
}
}
pub(crate) fn destroy_texture(&self, texture: resource::Texture<A>) {
if let Some(raw) = texture.raw {
unsafe {
self.raw.destroy_texture(raw);
}
}
}
pub(crate) fn destroy_command_buffer(&self, cmd_buf: command::CommandBuffer<A>) {
let mut baked = cmd_buf.into_baked();
unsafe {
@@ -3120,20 +3090,23 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
trace.lock().add(trace::Action::FreeTexture(texture_id));
}
let raw = texture
.raw
.take()
.ok_or(resource::DestroyError::AlreadyDestroyed)?;
let temp = queue::TempResource::Texture(raw);
match texture.inner {
resource::TextureInner::Native { ref mut raw } => {
let raw = raw.take().ok_or(resource::DestroyError::AlreadyDestroyed)?;
let temp = queue::TempResource::Texture(raw);
if device.pending_writes.dst_textures.contains(&texture_id) {
device.pending_writes.temp_resources.push(temp);
} else {
let last_submit_index = texture.life_guard.submission_index.load(Ordering::Acquire);
drop(texture_guard);
device
.lock_life(&mut token)
.schedule_resource_destruction(temp, last_submit_index);
if device.pending_writes.dst_textures.contains(&texture_id) {
device.pending_writes.temp_resources.push(temp);
} else {
let last_submit_index =
texture.life_guard.submission_index.load(Ordering::Acquire);
drop(texture_guard);
device
.lock_life(&mut token)
.schedule_resource_destruction(temp, last_submit_index);
}
}
resource::TextureInner::Surface { .. } => {} //TODO
}
Ok(())
@@ -3260,14 +3233,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let _ref_count = view.life_guard.ref_count.take();
let last_submit_index =
view.life_guard.submission_index.load(Ordering::Acquire);
let device_id = match view.source {
resource::TextureViewSource::Native(ref source_id) => {
texture_guard[source_id.value].device_id.value
}
resource::TextureViewSource::Surface(_) => {
return Err(resource::TextureViewDestroyError::SurfaceImage)
}
};
let device_id = texture_guard[view.parent_id.value].device_id.value;
(last_submit_index, device_id)
}
Err(InvalidId) => {
@@ -4429,7 +4395,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
config: config.clone(),
num_frames,
acquired_texture: None,
active_submission_index: 0,
});
return None;
+8 -10
View File
@@ -410,8 +410,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
)
.unwrap();
let dst_raw = dst
.raw
.as_ref()
.inner
.as_raw()
.ok_or(TransferError::InvalidTexture(destination.texture))?;
if !dst.desc.usage.contains(wgt::TextureUsages::COPY_DST) {
@@ -569,15 +569,13 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
// optimize the tracked states
cmdbuf.trackers.optimize();
//TODO: do we need this code?
for surface_id in cmdbuf.used_surfaces.drain(..) {
let surface = &mut surface_guard[surface_id];
let suf = A::get_surface_mut(surface);
if suf.acquired_texture.is_none() {
return Err(QueueSubmitError::SurfaceOutputDropped);
}
match surface.presentation {
match surface_guard[surface_id].presentation {
Some(ref mut present) => {
present.active_submission_index = submit_index;
if present.acquired_texture.is_none() {
return Err(QueueSubmitError::SurfaceOutputDropped);
}
}
None => return Err(QueueSubmitError::SurfaceUnconfigured),
}
@@ -608,7 +606,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
for id in cmdbuf.trackers.textures.used() {
let texture = &texture_guard[id];
if texture.raw.is_none() {
if texture.inner.as_raw().is_none() {
return Err(QueueSubmitError::DestroyedTexture(id.0));
}
if !texture.life_guard.use_at(submit_index) {
+1 -1
View File
@@ -55,7 +55,7 @@ pub enum Action<'a> {
CreateSampler(id::SamplerId, crate::resource::SamplerDescriptor<'a>),
DestroySampler(id::SamplerId),
GetSurfaceTexture {
id: id::TextureViewId,
id: id::TextureId,
parent_id: id::SurfaceId,
},
Present(id::SurfaceId),
+10 -10
View File
@@ -617,7 +617,7 @@ impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<A, F> {
// we should have `clear_device(device_id)` that specifically destroys
// everything related to a logical device.
fn clear(&self, surface_guard: &mut Storage<Surface, id::SurfaceId>, with_adapters: bool) {
use crate::resource::TextureViewSource;
use crate::resource::TextureInner;
use hal::{Device as _, Surface as _};
let mut devices = self.devices.data.write();
@@ -648,14 +648,9 @@ impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<A, F> {
let textures = self.textures.data.read();
for element in self.texture_views.data.write().map.drain(..) {
if let Element::Occupied(texture_view, _) = element {
match texture_view.source {
TextureViewSource::Native(source_id) => {
let device = &devices[textures[source_id.value].device_id.value];
unsafe {
device.raw.destroy_texture_view(texture_view.raw);
}
}
TextureViewSource::Surface(_) => {} //TODO
let device = &devices[textures[texture_view.parent_id.value].device_id.value];
unsafe {
device.raw.destroy_texture_view(texture_view.raw);
}
}
}
@@ -663,7 +658,12 @@ impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<A, F> {
for element in self.textures.data.write().map.drain(..) {
if let Element::Occupied(texture, _) = element {
devices[texture.device_id.value].destroy_texture(texture);
let device = &devices[texture.device_id.value];
if let TextureInner::Native { raw: Some(raw) } = texture.inner {
unsafe {
device.raw.destroy_texture(raw);
}
}
}
}
for element in self.buffers.data.write().map.drain(..) {
+4 -3
View File
@@ -13,9 +13,10 @@ use thiserror::Error;
pub type RequestAdapterOptions = wgt::RequestAdapterOptions<SurfaceId>;
type HalInstance<A> = <A as hal::Api>::Instance;
//TODO: remove this
pub struct HalSurface<A: hal::Api> {
pub raw: A::Surface,
pub acquired_texture: Option<A::SurfaceTexture>,
//pub acquired_texture: Option<A::SurfaceTexture>,
}
#[derive(Clone, Debug, Error)]
@@ -449,7 +450,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
match inst.create_surface(handle) {
Ok(raw) => Some(HalSurface {
raw,
acquired_texture: None,
//acquired_texture: None,
}),
Err(e) => {
log::warn!("Error: {:?}", e);
@@ -494,7 +495,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
#[allow(clippy::transmute_ptr_to_ref)]
inst.create_surface_from_layer(unsafe { std::mem::transmute(layer) })
},
acquired_texture: None,
//acquired_texture: None,
}),
};
+76 -90
View File
@@ -11,16 +11,16 @@
#[cfg(feature = "trace")]
use crate::device::trace::Action;
use crate::{
conv,
device::DeviceError,
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token},
id::{DeviceId, SurfaceId, TextureViewId, Valid},
id::{DeviceId, SurfaceId, TextureId, Valid},
resource,
track::TextureSelector,
LifeGuard, Stored, SubmissionIndex,
LifeGuard, Stored,
};
use hal::{Device as _, Queue as _, Surface as _};
use std::borrow::Borrow;
use hal::{Queue as _, Surface as _};
use thiserror::Error;
use wgt::SurfaceStatus as Status;
@@ -32,8 +32,7 @@ pub(crate) struct Presentation {
pub(crate) device_id: Stored<DeviceId>,
pub(crate) config: wgt::SurfaceConfiguration,
pub(crate) num_frames: u32,
pub(crate) acquired_texture: Option<Stored<TextureViewId>>,
pub(crate) active_submission_index: SubmissionIndex,
pub(crate) acquired_texture: Option<Stored<TextureId>>,
}
#[derive(Clone, Debug, Error)]
@@ -75,20 +74,20 @@ pub enum ConfigureSurfaceError {
#[derive(Debug)]
pub struct SurfaceOutput {
pub status: Status,
pub view_id: Option<TextureViewId>,
pub texture_id: Option<TextureId>,
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn surface_get_current_texture_view<A: HalApi>(
pub fn surface_get_current_texture<A: HalApi>(
&self,
surface_id: SurfaceId,
view_id_in: Input<G, TextureViewId>,
texture_id_in: Input<G, TextureId>,
) -> Result<SurfaceOutput, SurfaceError> {
profiling::scope!("get_next_texture", "SwapChain");
let hub = A::hub(self);
let mut token = Token::root();
let fid = hub.texture_views.prepare(view_id_in);
let fid = hub.textures.prepare(texture_id_in);
let (mut surface_guard, mut token) = self.surfaces.write(&mut token);
let surface = surface_guard
@@ -96,8 +95,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_err(|_| SurfaceError::Invalid)?;
let (device_guard, mut token) = hub.devices.read(&mut token);
let device = match surface.presentation {
Some(ref present) => &device_guard[present.device_id.value],
let (device, config) = match surface.presentation {
Some(ref present) => {
let device = &device_guard[present.device_id.value];
(device, present.config.clone())
}
None => return Err(SurfaceError::NotConfigured),
};
@@ -108,17 +110,64 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
parent_id: surface_id,
});
}
#[cfg(not(feature = "trace"))]
let _ = device;
let config = surface.presentation.as_ref().unwrap().config.clone();
let suf = A::get_surface_mut(surface);
let (texture, status) = match unsafe { suf.raw.acquire_texture(FRAME_TIMEOUT_MS) } {
let (texture_id, status) = match unsafe { suf.raw.acquire_texture(FRAME_TIMEOUT_MS) } {
Ok(Some(ast)) => {
let present = surface.presentation.as_mut().unwrap();
let texture = resource::Texture {
inner: resource::TextureInner::Surface {
raw: ast.texture,
parent_id: Valid(surface_id),
},
device_id: present.device_id.clone(),
desc: wgt::TextureDescriptor {
label: (),
size: wgt::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
sample_count: 1,
mip_level_count: 1,
format: config.format,
dimension: wgt::TextureDimension::D2,
usage: config.usage,
},
hal_usage: conv::map_texture_usage(config.usage, config.format.into()),
format_features: wgt::TextureFormatFeatures {
allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT,
flags: wgt::TextureFormatFeatureFlags::empty(),
filterable: false,
},
full_range: TextureSelector {
layers: 0..1,
levels: 0..1,
},
life_guard: LifeGuard::new("<Surface>"),
};
let ref_count = texture.life_guard.add_ref();
let id = fid.assign(texture, &mut token);
//suf.acquired_texture = Some(suf_texture);
if present.acquired_texture.is_some() {
return Err(SurfaceError::AlreadyAcquired);
}
present.acquired_texture = Some(Stored {
value: id,
ref_count,
});
let status = if ast.suboptimal {
Status::Suboptimal
} else {
Status::Good
};
(Some(ast.texture), status)
(Some(id.0), status)
}
Ok(None) => (None, Status::Timeout),
Err(err) => (
@@ -137,69 +186,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
),
};
let hal_desc = hal::TextureViewDescriptor {
label: Some("_Frame"),
format: config.format,
dimension: wgt::TextureViewDimension::D2,
usage: hal::TextureUses::COLOR_TARGET,
range: wgt::ImageSubresourceRange::default(),
};
let view_id = match texture {
Some(suf_texture) => {
let raw = unsafe {
device
.raw
.create_texture_view(suf_texture.borrow(), &hal_desc)
.map_err(DeviceError::from)?
};
let view = resource::TextureView {
raw,
source: resource::TextureViewSource::Surface(Valid(surface_id)),
desc: resource::HalTextureViewDescriptor {
format: config.format,
dimension: wgt::TextureViewDimension::D2,
range: wgt::ImageSubresourceRange::default(),
},
format_features: wgt::TextureFormatFeatures {
allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT,
flags: wgt::TextureFormatFeatureFlags::empty(),
filterable: false,
},
extent: wgt::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
samples: 1,
sampled_internal_use: hal::TextureUses::empty(),
selector: TextureSelector {
layers: 0..1,
levels: 0..1,
},
life_guard: LifeGuard::new("<SwapChain View>"),
};
let ref_count = view.life_guard.add_ref();
let id = fid.assign(view, &mut token);
suf.acquired_texture = Some(suf_texture);
let present = surface.presentation.as_mut().unwrap();
if present.acquired_texture.is_some() {
return Err(SurfaceError::AlreadyAcquired);
}
present.acquired_texture = Some(Stored {
value: id,
ref_count,
});
Some(id.0)
}
None => None,
};
Ok(SurfaceOutput { status, view_id })
Ok(SurfaceOutput { status, texture_id })
}
pub fn surface_present<A: HalApi>(
@@ -230,23 +217,22 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
let result = {
let view_id = present
let texture_id = present
.acquired_texture
.take()
.ok_or(SurfaceError::AlreadyAcquired)?;
let suf = A::get_surface_mut(surface);
let suf_texture = suf.acquired_texture.take().unwrap();
let result = unsafe { device.queue.present(&mut suf.raw, suf_texture) };
drop(surface_guard);
let (view, _) = hub.texture_views.unregister(view_id.value.0, &mut token);
if let Some(view) = view {
device.schedule_rogue_texture_view_for_destruction(view_id.value, view, &mut token);
let (texture, _) = hub.textures.unregister(texture_id.value.0, &mut token);
if let Some(texture) = texture {
let suf_texture = match texture.inner {
resource::TextureInner::Surface { raw, .. } => raw,
resource::TextureInner::Native { .. } => unreachable!(),
};
let suf = A::get_surface_mut(surface);
unsafe { device.queue.present(&mut suf.raw, suf_texture) }
} else {
Err(hal::SurfaceError::Outdated) //TODO?
}
result
};
log::debug!("Presented. End of Frame");
+27 -12
View File
@@ -156,9 +156,33 @@ impl<A: hal::Api> Borrow<()> for Buffer<A> {
pub type TextureDescriptor<'a> = wgt::TextureDescriptor<Label<'a>>;
#[derive(Debug)]
pub(crate) enum TextureInner<A: hal::Api> {
Native {
raw: Option<A::Texture>,
},
Surface {
raw: A::SurfaceTexture,
parent_id: Valid<SurfaceId>,
},
}
impl<A: hal::Api> TextureInner<A> {
pub fn as_raw(&self) -> Option<&A::Texture> {
match *self {
TextureInner::Native { raw: Some(ref tex) } => Some(tex),
TextureInner::Native { raw: None } => None,
TextureInner::Surface {
ref raw,
parent_id: _,
} => Some(std::borrow::Borrow::borrow(raw)),
}
}
}
#[derive(Debug)]
pub struct Texture<A: hal::Api> {
pub(crate) raw: Option<A::Texture>,
pub(crate) inner: TextureInner<A>,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) desc: wgt::TextureDescriptor<()>,
pub(crate) hal_usage: hal::TextureUses,
@@ -237,12 +261,6 @@ pub struct TextureViewDescriptor<'a> {
pub range: wgt::ImageSubresourceRange,
}
#[derive(Debug)]
pub(crate) enum TextureViewSource {
Native(Stored<TextureId>),
Surface(Valid<SurfaceId>),
}
#[derive(Debug)]
pub(crate) struct HalTextureViewDescriptor {
pub format: wgt::TextureFormat,
@@ -259,7 +277,7 @@ impl HalTextureViewDescriptor {
#[derive(Debug)]
pub struct TextureView<A: hal::Api> {
pub(crate) raw: A::TextureView,
pub(crate) source: TextureViewSource,
pub(crate) parent_id: Stored<TextureId>,
//TODO: store device_id for quick access?
pub(crate) desc: HalTextureViewDescriptor,
pub(crate) format_features: wgt::TextureFormatFeatures,
@@ -310,10 +328,7 @@ pub enum CreateTextureViewError {
}
#[derive(Clone, Debug, Error)]
pub enum TextureViewDestroyError {
#[error("cannot destroy a surface image")]
SurfaceImage,
}
pub enum TextureViewDestroyError {}
impl<A: hal::Api> Resource for TextureView<A> {
const TYPE: &'static str = "TextureView";
+1 -1
View File
@@ -145,7 +145,7 @@ impl PendingTransition<TextureState> {
tex: &'a resource::Texture<A>,
) -> hal::TextureBarrier<'a, A> {
log::trace!("\ttexture -> {:?}", self);
let texture = tex.raw.as_ref().expect("Texture is destroyed");
let texture = tex.inner.as_raw().expect("Texture is destroyed");
hal::TextureBarrier {
texture,
range: wgt::ImageSubresourceRange {
+2 -1
View File
@@ -296,8 +296,9 @@ fn start<E: Example>(
.expect("Failed to acquire next surface texture!")
}
};
let view = frame.output.texture.create_view(&wgpu::TextureViewDescriptor::default());
example.render(&frame.output.view, &device, &queue, &spawner);
example.render(&view, &device, &queue, &spawner);
}
_ => {}
}
+2 -1
View File
@@ -96,13 +96,14 @@ async fn run(event_loop: EventLoop<()>, window: Window) {
.get_current_frame()
.expect("Failed to acquire next swap chain texture")
.output;
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &frame.view,
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
+2 -1
View File
@@ -112,13 +112,14 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Window, wgpu::Color)>) {
Event::RedrawRequested(window_id) => {
if let Some(viewport) = viewports.get_mut(&window_id) {
let frame = viewport.get_current_frame();
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
let _rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &frame.view,
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(viewport.desc.background),
+10 -7
View File
@@ -893,11 +893,11 @@ impl crate::Context for Context {
}
}
fn surface_get_current_texture_view(
fn surface_get_current_texture(
&self,
surface: &Self::SurfaceId,
) -> (
Option<Self::TextureViewId>,
Option<Self::TextureId>,
SurfaceStatus,
Self::SurfaceOutputDetail,
) {
@@ -907,10 +907,13 @@ impl crate::Context for Context {
.lock()
.expect("Surface was not configured?");
match wgc::gfx_select!(
device_id => global.surface_get_current_texture_view(surface.id, PhantomData)
device_id => global.surface_get_current_texture(surface.id, PhantomData)
) {
Ok(wgc::present::SurfaceOutput { status, view_id }) => (
view_id,
Ok(wgc::present::SurfaceOutput { status, texture_id }) => (
texture_id.map(|id| Texture {
id,
error_sink: Arc::new(Mutex::new(ErrorSinkRaw::new())),
}),
status,
SurfaceOutputDetail {
surface_id: surface.id,
@@ -920,9 +923,9 @@ impl crate::Context for Context {
}
}
fn surface_present(&self, view: &Self::TextureViewId, detail: &Self::SurfaceOutputDetail) {
fn surface_present(&self, texture: &Self::TextureId, detail: &Self::SurfaceOutputDetail) {
let global = &self.0;
match wgc::gfx_select!(*view => global.surface_present(detail.surface_id)) {
match wgc::gfx_select!(texture.id => global.surface_present(detail.surface_id)) {
Ok(_status) => (),
Err(err) => self.handle_error_fatal(err, "Surface::present"),
}
+10 -12
View File
@@ -224,15 +224,15 @@ trait Context: Debug + Send + Sized + Sync {
device: &Self::DeviceId,
config: &SurfaceConfiguration,
);
fn surface_get_current_texture_view(
fn surface_get_current_texture(
&self,
surface: &Self::SurfaceId,
) -> (
Option<Self::TextureViewId>,
Option<Self::TextureId>,
SurfaceStatus,
Self::SurfaceOutputDetail,
);
fn surface_present(&self, view: &Self::TextureViewId, detail: &Self::SurfaceOutputDetail);
fn surface_present(&self, texture: &Self::TextureId, detail: &Self::SurfaceOutputDetail);
fn device_features(&self, device: &Self::DeviceId) -> Features;
fn device_limits(&self, device: &Self::DeviceId) -> Limits;
@@ -630,7 +630,6 @@ pub struct Texture {
pub struct TextureView {
context: Arc<C>,
id: <C as Context>::TextureViewId,
owned: bool,
}
/// Handle to a sampler.
@@ -1331,7 +1330,7 @@ pub struct RenderBundleEncoderDescriptor<'a> {
#[derive(Debug)]
pub struct SurfaceTexture {
/// Accessible view of the frame.
pub view: TextureView,
pub texture: Texture,
detail: <C as Context>::SurfaceOutputDetail,
}
@@ -2075,7 +2074,6 @@ impl Texture {
TextureView {
context: Arc::clone(&self.context),
id: Context::texture_create_view(&*self.context, &self.id, desc),
owned: true,
}
}
@@ -2105,7 +2103,7 @@ impl Drop for Texture {
impl Drop for TextureView {
fn drop(&mut self) {
if self.owned && !thread::panicking() {
if !thread::panicking() {
self.context.texture_view_drop(&self.id);
}
}
@@ -3056,7 +3054,7 @@ impl Queue {
impl Drop for SurfaceTexture {
fn drop(&mut self) {
if !thread::panicking() {
Context::surface_present(&*self.view.context, &self.view.id, &self.detail);
Context::surface_present(&*self.texture.context, &self.texture.id, &self.detail);
}
}
}
@@ -3087,10 +3085,10 @@ impl Surface {
/// If a SurfaceFrame referencing this surface is alive when the swapchain is recreated,
/// recreating the swapchain will panic.
pub fn get_current_frame(&self) -> Result<SurfaceFrame, SurfaceError> {
let (view_id, status, detail) =
Context::surface_get_current_texture_view(&*self.context, &self.id);
let output = view_id.map(|id| SurfaceTexture {
view: TextureView {
let (texture_id, status, detail) =
Context::surface_get_current_texture(&*self.context, &self.id);
let output = texture_id.map(|id| SurfaceTexture {
texture: Texture {
context: Arc::clone(&self.context),
id,
owned: false,