use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use super::PostBackend;
use crate::renderer::{RenderTarget, Renderer};
static NEXT_ID: AtomicU32 = AtomicU32::new(0x4000_0000);
pub const INTERMEDIATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
#[derive(Clone)]
pub struct Target {
id: u32,
width: u32,
height: u32,
format: wgpu::TextureFormat,
rt: Option<Arc<RenderTarget>>,
}
impl std::fmt::Debug for Target {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Target")
.field("id", &self.id)
.field("width", &self.width)
.field("height", &self.height)
.field("format", &self.format)
.finish()
}
}
impl Target {
pub fn new(
renderer: &mut Renderer,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Self {
let rt = Arc::new(RenderTarget::new(
&renderer.device_arc(),
width.max(1),
height.max(1),
format,
));
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
renderer.register_render_target(id, &rt);
Self::from_registered(id, rt)
}
pub fn next_id() -> u32 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
pub fn external(id: u32, width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
Self {
id,
width: width.max(1),
height: height.max(1),
format,
rt: None,
}
}
pub fn intermediate(renderer: &mut Renderer, width: u32, height: u32) -> Self {
Self::new(renderer, width, height, INTERMEDIATE_FORMAT)
}
pub fn from_registered(id: u32, rt: Arc<RenderTarget>) -> Self {
Self {
id,
width: rt.width,
height: rt.height,
format: rt.format,
rt: Some(rt),
}
}
pub fn id(&self) -> u32 {
self.id
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn format(&self) -> wgpu::TextureFormat {
self.format
}
pub fn render_target(&self) -> &Arc<RenderTarget> {
self.rt
.as_ref()
.expect("a wgpu render target (this one belongs to another backend)")
}
pub fn wgpu_render_target(&self) -> Option<&Arc<RenderTarget>> {
self.rt.as_ref()
}
pub fn same(&self, other: &Target) -> bool {
self.id == other.id
}
}
pub fn ensure(
slot: &mut Option<Target>,
renderer: &mut (impl PostBackend + ?Sized),
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Target {
let (width, height) = (width.max(1), height.max(1));
if let Some(t) = slot {
if t.size() == (width, height) && t.format() == format {
return t.clone();
}
renderer.unregister_render_target(t.id);
}
let t = renderer.new_target(width, height, format);
*slot = Some(t.clone());
t
}
pub fn release(slot: &mut Option<Target>, renderer: &mut (impl PostBackend + ?Sized)) {
if let Some(t) = slot.take() {
renderer.unregister_render_target(t.id);
}
}