use std::convert::Infallible;
use mln_gfx::gpu::{GpuError, TargetFormats, TextureFormat, TextureId};
use mln_gfx::ring::{self, RingBackend, RingTextures};
use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, Error, Size, SyncKind, SyncKinds};
use crate::gpu::{WebGpu, from_wgpu_format};
use crate::renderer_backend::RendererBackend;
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedTextures {
pub textures: Vec<wgpu::Texture>,
pub size: Size,
pub depth_textures: Vec<wgpu::Texture>,
}
impl BorrowedTextures {
#[must_use]
pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
let consumer = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
let producer = if cfg!(target_family = "wasm") { SyncKinds::of(&[SyncKind::QueueOrder]) } else { consumer };
(producer, consumer)
}
#[must_use]
pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
formats.with(DepthStencilFormat::Depth32FloatStencil8)
} else {
formats
}
}
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"));
};
if let Some(depth) = self.depth_textures.first() {
if self.depth_textures.len() != self.textures.len() {
return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
}
if depth_stencil_format(depth.format()).is_none() {
return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
}
}
for texture in self.textures.iter().chain(&self.depth_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"));
}
let kin =
if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
if Some(texture.format()) != kin.map(wgpu::Texture::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)
}
fn depth_format(&self) -> Option<wgpu::TextureFormat> {
self.depth_textures.first().map(wgpu::Texture::format)
}
}
impl RingTextures for BorrowedTextures {
type Image = wgpu::Texture;
fn images(&self) -> &[wgpu::Texture] {
&self.textures
}
fn same_image(a: &wgpu::Texture, b: &wgpu::Texture) -> bool {
a == b
}
fn size(&self) -> Size {
self.size
}
fn has_depth(&self) -> bool {
!self.depth_textures.is_empty()
}
}
#[must_use]
pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
match format {
wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
_ => None,
}
}
pub type BorrowedTarget = ring::BorrowedTarget<WebGpuRing>;
pub struct WebGpuRing;
impl RingBackend for WebGpuRing {
type Gpu = WebGpu;
type Renderer = RendererBackend;
type Textures = BorrowedTextures;
type Wait = Infallible;
type Handed = Infallible;
fn new(_backend: &mut 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:?}")));
}
Ok(WebGpuRing)
}
fn check_replacement(&self, current: &BorrowedTextures, next: &BorrowedTextures) -> Result<(), Error> {
if (next.format(), next.depth_format()) != (current.format(), current.depth_format()) {
return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
}
next.check()
}
fn targets(gpu: &WebGpu, textures: &BorrowedTextures) -> Result<TargetFormats, Error> {
let format = textures.format();
let color = format
.and_then(from_wgpu_format)
.ok_or_else(|| Error::unsupported(format!("the WebGPU target draws into no {format:?}")))?;
let depth_stencil = match textures.depth_format() {
Some(depth) => from_wgpu_format(depth),
None => Some(if gpu.device().device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
TextureFormat::Depth32FloatStencil8
} else {
TextureFormat::Depth24PlusStencil8
}),
};
Ok(TargetFormats { color: Some(color), depth_stencil })
}
fn import(gpu: &mut WebGpu, textures: &BorrowedTextures, slot: usize, depth: bool) -> Result<TextureId, GpuError> {
let list = if depth { &textures.depth_textures } else { &textures.textures };
let texture = list.get(slot).ok_or_else(|| GpuError::Invalid(format!("the ring has no slot {slot}")))?;
Ok(gpu.import_texture(texture))
}
fn wait_for(&mut self, _gpu: &mut WebGpu, consumer: ConsumerSync) -> Result<Option<Infallible>, Error> {
match consumer.sync.kind {
SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(None),
kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
}
}
}