Issue surface texture transitions

This commit is contained in:
Dzmitry Malyshau authored and Dzmitry Malyshau committed 2021-08-11 20:58:42 -04:00
1 parent dffe1f1793
commit 4a1ae0d7ec
11 files changed
+107 -55

No files matched your search

-3
View File
@@ -25,7 +25,6 @@ use crate::{
};
use hal::CommandEncoder as _;
use smallvec::SmallVec;
use thiserror::Error;
const PUSH_CONSTANT_CLEAR_ARRAY: &[u32] = &[0_u32; 64];
@@ -141,7 +140,6 @@ pub struct CommandBuffer<A: hal::Api> {
status: CommandEncoderStatus,
pub(crate) device_id: Stored<id::DeviceId>,
pub(crate) trackers: TrackerSet,
pub(crate) used_surfaces: SmallVec<[id::Valid<id::SurfaceId>; 1]>,
buffer_memory_init_actions: Vec<MemoryInitTrackerAction<id::BufferId>>,
limits: wgt::Limits,
support_fill_buffer_texture: bool,
@@ -169,7 +167,6 @@ impl<A: HalApi> CommandBuffer<A> {
status: CommandEncoderStatus::Recording,
device_id,
trackers: TrackerSet::new(A::VARIANT),
used_surfaces: Default::default(),
buffer_memory_init_actions: Default::default(),
limits,
support_fill_buffer_texture: features.contains(wgt::Features::CLEAR_COMMANDS),
+3 -17
View File
@@ -13,7 +13,6 @@ use crate::{
error::{ErrorFormatter, PrettyError},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
instance::Surface,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
pipeline::PipelineFlags,
resource::{Texture, TextureView},
@@ -530,7 +529,6 @@ struct RenderPassInfo<'a, A: hal::Api> {
context: RenderPassContext,
trackers: StatefulTrackerSubset,
render_attachments: AttachmentDataVec<RenderAttachment<'a>>,
used_surface: Option<id::Valid<id::SurfaceId>>,
is_ds_read_only: bool,
extent: wgt::Extent3d,
_phantom: PhantomData<A>,
@@ -543,7 +541,6 @@ 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>,
) -> Result<Self, RenderPassErrorInner> {
profiling::scope!("start", "RenderPassInfo");
@@ -557,8 +554,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
let mut attachment_type_name = "";
let mut extent = None;
let mut sample_count = 0;
//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 {
@@ -718,7 +713,6 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
context,
trackers: StatefulTrackerSubset::new(A::VARIANT),
render_attachments,
used_surface: used_surface.map(|(sc_id, _)| sc_id),
is_ds_read_only,
extent,
_phantom: PhantomData,
@@ -729,9 +723,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>,
) -> Result<(StatefulTrackerSubset, Option<id::Valid<id::SurfaceId>>), RenderPassErrorInner>
{
) -> Result<StatefulTrackerSubset, RenderPassErrorInner> {
profiling::scope!("finish", "RenderPassInfo");
unsafe {
raw.end_render_pass();
@@ -753,7 +745,7 @@ impl<'a, A: HalApi> RenderPassInfo<'a, A> {
.map_err(UsageConflict::from)?;
}
Ok((self.trackers, self.used_surface))
Ok(self.trackers)
}
}
@@ -786,8 +778,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let hub = A::hub(self);
let mut token = Token::root();
let (surface_guard, mut token) = self.surfaces.read(&mut token);
let (device_guard, mut token) = hub.devices.read(&mut token);
let (pass_raw, trackers, query_reset_state) = {
@@ -834,7 +824,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
depth_stencil_attachment,
cmd_buf,
&*view_guard,
&*surface_guard,
)
.map_pass_err(scope)?;
@@ -1701,9 +1690,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
log::trace!("Merging {:?} with the render pass", encoder_id);
let (trackers, used_surface) = info
.finish(raw, &*texture_guard, &*surface_guard)
.map_pass_err(scope)?;
let trackers = info.finish(raw, &*texture_guard).map_pass_err(scope)?;
let raw_cmd_buf = unsafe {
raw.end_encoding()
@@ -1711,7 +1698,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_pass_err(scope)?
};
cmd_buf.status = CommandEncoderStatus::Recording;
cmd_buf.used_surfaces.extend(used_surface);
(raw_cmd_buf, trackers, query_reset_state)
};
+68 -17
View File
@@ -9,8 +9,8 @@ use crate::{
device::{DeviceError, WaitIdleError},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Token},
id,
resource::{BufferAccessError, BufferMapState},
FastHashSet,
resource::{BufferAccessError, BufferMapState, TextureInner},
track, FastHashSet,
};
use hal::{CommandEncoder as _, Device as _, Queue as _};
@@ -511,7 +511,6 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let mut token = Token::root();
let callbacks = {
let (mut surface_guard, mut token) = self.surfaces.write(&mut token);
let (mut device_guard, mut token) = hub.devices.write(&mut token);
let device = device_guard
.get_mut(queue_id)
@@ -520,6 +519,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
device.active_submission_index += 1;
let submit_index = device.active_submission_index;
let mut active_executions = Vec::new();
let mut used_surface_textures = track::ResourceTracker::new(A::VARIANT);
{
let (mut command_buffer_guard, mut token) = hub.command_buffers.write(&mut token);
@@ -569,18 +569,6 @@ 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(..) {
match surface_guard[surface_id].presentation {
Some(ref mut present) => {
if present.acquired_texture.is_none() {
return Err(QueueSubmitError::SurfaceOutputDropped);
}
}
None => return Err(QueueSubmitError::SurfaceUnconfigured),
}
}
// update submission IDs
for id in cmdbuf.trackers.buffers.used() {
let buffer = &mut buffer_guard[id];
@@ -606,8 +594,44 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
for id in cmdbuf.trackers.textures.used() {
let texture = &texture_guard[id];
if texture.inner.as_raw().is_none() {
return Err(QueueSubmitError::DestroyedTexture(id.0));
match texture.inner {
TextureInner::Native { raw: None } => {
return Err(QueueSubmitError::DestroyedTexture(id.0));
}
TextureInner::Native { raw: Some(_) } => {}
TextureInner::Surface { .. } => {
use track::ResourceState as _;
let ref_count = cmdbuf.trackers.textures.get_ref_count(id);
//TODO: better error handling here?
{
// first, register it in the device tracker with uninitialized,
// if it wasn't used before.
let mut ts = track::TextureState::default();
let _ = ts.change(
id,
texture.full_range.clone(),
hal::TextureUses::UNINITIALIZED,
None,
);
let _ = trackers.textures.init(
id,
ref_count.clone(),
ts.clone(),
);
}
{
// then, register it in the temporary tracker.
let mut ts = track::TextureState::default();
let _ = ts.change(
id,
texture.full_range.clone(),
hal::TextureUses::empty(),
None,
);
let _ =
used_surface_textures.init(id, ref_count.clone(), ts);
}
}
}
if !texture.life_guard.use_at(submit_index) {
device.temp_suspected.textures.push(id);
@@ -690,6 +714,33 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let transit = unsafe { baked.encoder.end_encoding().unwrap() };
baked.list.insert(0, transit);
// Transition surface textures into `Present` state.
// Note: we could technically do it after all of the command buffers,
// but here we have a command encoder by hand, so it's easier to use it.
if !used_surface_textures.is_empty() {
unsafe {
baked
.encoder
.begin_encoding(Some("_Present"))
.map_err(DeviceError::from)?
};
let texture_barriers = trackers
.textures
.merge_replace(&used_surface_textures)
.map(|pending| {
let tex = &texture_guard[pending.id];
pending.into_hal(tex)
});
let present = unsafe {
baked.encoder.transition_textures(texture_barriers);
baked.encoder.end_encoding().unwrap()
};
baked.list.push(present);
used_surface_textures.clear();
}
// done
active_executions.push(EncoderInFlight {
raw: baked.encoder,
cmd_buffers: baked.list,
+4 -3
View File
@@ -722,13 +722,14 @@ impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<A, F> {
}
}
for element in surface_guard.map.drain(..) {
if let Element::Occupied(mut surface, _epoch) = element {
for element in surface_guard.map.iter_mut() {
if let Element::Occupied(ref mut surface, _epoch) = *element {
if let Some(present) = surface.presentation.take() {
let device = &devices[present.device_id.value];
let suf = A::get_surface_mut(&mut surface);
let suf = A::get_surface_mut(surface);
unsafe {
suf.raw.unconfigure(&device.raw);
//TODO: we could destroy the surface here
}
}
}
+9 -4
View File
@@ -2,10 +2,11 @@
## Lifecycle
When a swapchain view is used in `begin_render_pass()`, we assume the start and end image
layouts purely based on whether or not this view was used in this command buffer before.
It always starts with `Uninitialized` and ends with `Present`, so that no barriers are
needed when we need to actually present it.
Whenever a submission detects the use of any surface texture, it adds it to the device
tracker for the duration of the submission (temporarily, while recording).
It's added with `UNINITIALIZED` state and transitioned into `empty()` state.
When this texture is presented, we remove it from the device tracker as well as
extract it from the hub.
!*/
#[cfg(feature = "trace")]
@@ -222,6 +223,10 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.take()
.ok_or(SurfaceError::AlreadyAcquired)?;
// The texture ID got added to the device tracker by `submit()`,
// and now we are moving it away.
device.trackers.lock().textures.remove(texture_id.value);
let (texture, _) = hub.textures.unregister(texture_id.value.0, &mut token);
if let Some(texture) = texture {
let suf_texture = match texture.inner {
+7 -2
View File
@@ -218,7 +218,7 @@ impl<S: ResourceState> ResourceTracker<S> {
}
/// Remove an id from the tracked map.
pub(crate) fn _remove(&mut self, id: Valid<S::Id>) -> bool {
pub(crate) fn remove(&mut self, id: Valid<S::Id>) -> bool {
let (index, epoch, backend) = id.0.unzip();
debug_assert_eq!(backend, self.backend);
match self.map.remove(&index) {
@@ -263,13 +263,18 @@ impl<S: ResourceState> ResourceTracker<S> {
.map(move |(&index, resource)| Valid(S::Id::zip(index, resource.epoch, backend)))
}
pub fn get_ref_count(&self, id: Valid<S::Id>) -> &RefCount {
let (index, _, _) = id.0.unzip();
&self.map[&index].ref_count
}
/// Return true if there is nothing here.
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Clear the tracked contents.
fn clear(&mut self) {
pub fn clear(&mut self) {
self.map.clear();
}
+2
View File
@@ -1,3 +1,5 @@
//Note: this could be the only place where we need `SmallVec`.
//TODO: consider getting rid of it.
use smallvec::SmallVec;
use std::{cmp::Ordering, fmt::Debug, iter, ops::Range, slice::Iter};
+4 -1
View File
@@ -296,7 +296,10 @@ fn start<E: Example>(
.expect("Failed to acquire next surface texture!")
}
};
let view = frame.output.texture.create_view(&wgpu::TextureViewDescriptor::default());
let view = frame
.output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
example.render(&view, &device, &queue, &spawner);
}
+3 -1
View File
@@ -96,7 +96,9 @@ 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 view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
+3 -1
View File
@@ -112,7 +112,9 @@ 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 view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
+4 -6
View File
@@ -1123,24 +1123,22 @@ impl crate::Context for Context {
surface.0.configure_swap_chain(&mapped);
}
fn surface_get_current_texture_view(
fn surface_get_current_texture(
&self,
_surface: &Self::SurfaceId,
) -> (
Option<Self::TextureViewId>,
Option<Self::TextureId>,
wgt::SurfaceStatus,
Self::SurfaceOutputDetail,
) {
// TODO: Should we pass a descriptor here?
// Or is the default view always correct?
(
None, //TODO: surface.0.get_current_texture().create_view()
None, //TODO: surface.0.get_current_texture(),
wgt::SurfaceStatus::Good,
(),
)
}
fn surface_present(&self, _view: &Self::TextureViewId, _detail: &Self::SurfaceOutputDetail) {
fn surface_present(&self, _texture: &Self::TextureId, _detail: &Self::SurfaceOutputDetail) {
// Swapchain is presented automatically
}