use std::any::Any;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use mln_gfx::command_encoder::CommandEncoder as GfxCommandEncoder;
use mln_gfx::frame::{self, FrameTarget, Handoff};
use mln_gfx::{ConsumerSync, GpuSync, SyncKind, SyncKinds};
use mln_util::error::Error;
use mln_util::size::Size;
use crate::command_encoder::CommandEncoder;
use crate::draw_target::{DrawTarget, TargetResource};
use crate::renderer_backend::RendererBackend;
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedTextures {
pub textures: Vec<wgpu::Texture>,
pub size: Size,
}
impl BorrowedTextures {
#[must_use]
pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
(kinds, kinds)
}
pub fn check(&self) -> Result<(), Error> {
let Some(first) = self.textures.first() else {
return Err(Error::invalid_argument("a ring needs at least one texture"));
};
for texture in &self.textures {
let size = texture.size();
if (size.width, size.height) != (self.size.width, self.size.height) {
return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
}
if texture.format() != first.format() {
return Err(Error::invalid_argument("the ring's textures must share a format"));
}
if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
|| texture.dimension() != wgpu::TextureDimension::D2
|| texture.mip_level_count() != 1
|| texture.sample_count() != 1
|| size.depth_or_array_layers != 1
{
return Err(Error::invalid_argument(
"each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
));
}
}
Ok(())
}
fn format(&self) -> Option<wgpu::TextureFormat> {
self.textures.first().map(wgpu::Texture::format)
}
}
struct Resource {
device: wgpu::Device,
textures: RefCell<BorrowedTextures>,
selected: Cell<usize>,
depth_stencil_format: wgpu::TextureFormat,
depth_stencil: RefCell<Option<(Size, wgpu::TextureView)>>,
}
impl TargetResource for Resource {
fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
let textures = self.textures.borrow();
let texture = textures.textures.get(self.selected.get())?;
Some(texture.create_view(&wgpu::TextureViewDescriptor::default()))
}
fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
self.textures.borrow().format()
}
fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
let size = self.textures.borrow().size;
let mut depth_stencil = self.depth_stencil.borrow_mut();
if depth_stencil.as_ref().is_none_or(|(made, _)| *made != size) {
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("borrowed ring depth and stencil"),
size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.depth_stencil_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
*depth_stencil = Some((size, texture.create_view(&wgpu::TextureViewDescriptor::default())));
}
depth_stencil.as_ref().map(|(_, view)| view.clone())
}
fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
Some(self.depth_stencil_format)
}
fn as_any(&self) -> &dyn Any {
self
}
}
pub struct BorrowedTarget {
backend: Rc<RendererBackend>,
resource: Rc<Resource>,
target: Rc<DrawTarget>,
producer: SyncKind,
}
impl BorrowedTarget {
pub fn new(backend: Rc<RendererBackend>, textures: BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
textures.check()?;
if !BorrowedTextures::sync_kinds().0.contains(producer) {
return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
}
let device = backend.device().device().clone();
let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
wgpu::TextureFormat::Depth32FloatStencil8
} else {
wgpu::TextureFormat::Depth24PlusStencil8
};
let size = textures.size;
let resource = Rc::new(Resource {
device,
textures: RefCell::new(textures),
selected: Cell::new(0),
depth_stencil_format,
depth_stencil: RefCell::new(None),
});
let target = Rc::new(DrawTarget::new(size, resource.clone()));
Ok(BorrowedTarget { backend, resource, target, producer })
}
#[must_use]
pub fn depth(&self) -> usize {
self.resource.textures.borrow().textures.len()
}
pub fn select(&self, slot: usize) {
self.resource.selected.set(slot);
}
#[expect(
clippy::needless_pass_by_value,
reason = "the release takes the host's sync, as every backend's does, and drops it"
)]
pub fn release(&self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
match consumer.sync.kind {
SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
}
}
pub fn discard(&self, _slot: usize) {}
pub fn replace(&self, textures: BorrowedTextures) -> Result<(), Error> {
if textures.textures.len() != self.depth() {
return Err(Error::invalid_argument("a ring keeps its depth"));
}
if textures.format() != self.resource.textures.borrow().format() {
return Err(Error::unsupported("a ring keeps its format"));
}
textures.check()?;
self.target.set_size(textures.size);
*self.resource.textures.borrow_mut() = textures;
Ok(())
}
}
impl FrameTarget for BorrowedTarget {
fn begin_frame(&self) -> Option<Rc<dyn frame::DrawTarget>> {
Some(self.target.clone())
}
fn end_frame(&self, encoder: &dyn GfxCommandEncoder) -> Handoff {
let Some(encoder) = encoder.as_any().downcast_ref::<CommandEncoder>() else {
return Handoff::Dropped;
};
encoder.submit_frame(Some(self.target.resource()));
let sync = if self.producer == SyncKind::QueueOrder {
GpuSync::of(SyncKind::QueueOrder)
} else {
let wait = wgpu::PollType::Wait { submission_index: None, timeout: None };
let _ = self.backend.device().device().poll(wait);
GpuSync::of(SyncKind::CpuComplete)
};
Handoff::GivenBack { slot: self.resource.selected.get(), sync }
}
}