use crate::frame::{ImageContent, PresentedImage};
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TestImages {
Fresh,
Kept(usize),
}
pub(crate) struct TestTarget {
pub(crate) size: (u32, u32),
swapchain: Option<TestSwapchain>,
}
impl TestTarget {
pub(crate) fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
size: (u32, u32),
images: TestImages,
) -> Self {
let swapchain = match images {
TestImages::Fresh => None,
TestImages::Kept(count) => Some(TestSwapchain::new(device, format, size, count.max(1))),
};
Self { size, swapchain }
}
pub(crate) fn swapchain(&mut self) -> Option<&mut TestSwapchain> {
self.swapchain.as_mut()
}
pub(crate) fn image(&self, index: usize) -> (&wgpu::Texture, ImageContent) {
self.swapchain
.as_ref()
.expect("a test image needs its swapchain")
.target(index)
}
pub(crate) fn fresh_texture(
&self,
device: &wgpu::Device,
format: wgpu::TextureFormat,
) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("Present Runtime Offscreen Test Target"),
size: wgpu::Extent3d {
width: self.size.0,
height: self.size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
}
}
pub(crate) struct TestSwapchain {
images: Vec<wgpu::Texture>,
kept: Vec<bool>,
next: usize,
}
impl TestSwapchain {
fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
(width, height): (u32, u32),
count: usize,
) -> Self {
let image = |_| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("Present Runtime Test Swapchain Image"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: crate::presentable_root_usages(wgpu::TextureUsages::all()),
view_formats: &[format.remove_srgb_suffix()],
})
};
Self {
images: (0..count).map(image).collect(),
kept: vec![false; count],
next: 0,
}
}
pub(crate) fn acquire(&mut self) -> usize {
let index = self.next;
self.next = (index + 1) % self.images.len();
index
}
fn target(&self, index: usize) -> (&wgpu::Texture, ImageContent) {
let few = |count: usize| u32::try_from(count).expect("a test swapchain holds few images");
let image = PresentedImage {
index: few(index),
kept: self.kept[index],
images: few(self.images.len()),
};
(&self.images[index], ImageContent::Numbered(image))
}
pub(crate) fn present(&mut self, index: usize) {
self.kept[index] = true;
}
}