#![allow(
unreachable_patterns,
irrefutable_let_patterns,
reason = "the backends' variants depend on the build's features and target"
)]
#![cfg_attr(
target_family = "wasm",
expect(
unused_macros,
unused_imports,
reason = "the browser build has only canvases' backends, and none of the targets that the others make"
)
)]
use std::rc::Rc;
use std::sync::Arc;
use mln_gfx::{ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameTarget, RendererBackend, SyncKind, Window};
use mln_util::error::Error;
use mln_util::image::PremultipliedImage;
use mln_util::size::Size;
use super::target::{
BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
};
trait Offscreen: FrameTarget {
fn resize(&self, size: Size);
fn read_image(&self) -> Result<PremultipliedImage, Error>;
}
trait Presenting: FrameTarget {
fn resize(&self, size: Size);
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
impl Borrowed for mln_mtl::BorrowedTarget {
fn select(&self, slot: usize) {
mln_mtl::BorrowedTarget::select(self, slot);
}
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
mln_mtl::BorrowedTarget::release(self, slot, consumer)
}
fn discard(&self, slot: usize) {
mln_mtl::BorrowedTarget::discard(self, slot);
}
fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
let RingKind::Metal(textures) = ring.kind else {
return Err(Error::unsupported("a ring of Metal textures takes Metal textures only"));
};
mln_mtl::BorrowedTarget::replace(self, textures).map(pending)
}
fn take_pending(&self) -> Pending {
pending(mln_mtl::BorrowedTarget::take_pending(self))
}
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
impl PendingReads for mln_mtl::PendingReads {
fn poll(&mut self) -> bool {
mln_mtl::PendingReads::poll(self)
}
}
trait Borrowed: FrameTarget {
fn select(&self, slot: usize);
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
fn discard(&self, slot: usize);
fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error>;
fn take_pending(&self) -> Pending {
None
}
}
pub(crate) trait PendingReads {
fn poll(&mut self) -> bool;
}
pub(crate) type Pending = Option<Box<dyn PendingReads>>;
#[cfg(any(
all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
all(feature = "metal", target_vendor = "apple")
))]
fn pending(mut reads: impl PendingReads + 'static) -> Pending {
(!reads.poll()).then(|| -> Box<dyn PendingReads> { Box::new(reads) })
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
impl Borrowed for mln_vulkan::BorrowedTarget {
fn select(&self, slot: usize) {
mln_vulkan::BorrowedTarget::select(self, slot);
}
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
mln_vulkan::BorrowedTarget::release(self, slot, consumer)
}
fn discard(&self, slot: usize) {
mln_vulkan::BorrowedTarget::discard(self, slot);
}
fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
let RingKind::Vulkan(images) = ring.kind else {
return Err(Error::unsupported("a ring of Vulkan images takes Vulkan images only"));
};
mln_vulkan::BorrowedTarget::replace(self, images).map(pending)
}
fn take_pending(&self) -> Pending {
pending(mln_vulkan::BorrowedTarget::take_pending(self))
}
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
impl PendingReads for mln_vulkan::PendingReads {
fn poll(&mut self) -> bool {
mln_vulkan::PendingReads::poll(self)
}
}
trait Exported: FrameTarget {
fn select(&self, slot: usize);
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
fn discard(&self, slot: usize);
fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error>;
fn size(&self) -> Size;
fn image(&self, slot: usize) -> Option<ExportedFrame>;
}
macro_rules! exported {
($type:ty) => {
impl Exported for $type {
fn select(&self, slot: usize) {
<$type>::select(self, slot);
}
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
<$type>::release(self, slot, consumer)
}
fn discard(&self, slot: usize) {
<$type>::discard(self, slot);
}
fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
<$type>::resize(self, size, held)
}
fn size(&self) -> Size {
<$type>::size(self)
}
fn image(&self, slot: usize) -> Option<ExportedFrame> {
<$type>::image(self, slot)
}
}
};
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
exported!(mln_vulkan::ExportedTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
exported!(mln_mtl::ExportedTarget);
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
exported!(mln_gl::ExportedTarget);
macro_rules! offscreen {
($type:ty) => {
impl Offscreen for $type {
fn resize(&self, size: Size) {
<$type>::resize(self, size);
}
fn read_image(&self) -> Result<PremultipliedImage, Error> {
<$type>::read_image(self)
}
}
};
}
macro_rules! presenting {
($type:ty) => {
impl Presenting for $type {
fn resize(&self, size: Size) {
<$type>::resize(self, size);
}
}
};
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
offscreen!(mln_webgpu::OffscreenTarget);
#[cfg(feature = "webgpu")]
presenting!(mln_webgpu::SurfaceTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
offscreen!(mln_mtl::OffscreenTarget);
#[cfg(all(feature = "metal", target_vendor = "apple"))]
presenting!(mln_mtl::SurfaceTarget);
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
offscreen!(mln_vulkan::OffscreenTarget);
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
presenting!(mln_vulkan::SurfaceTarget);
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
offscreen!(mln_gl::OffscreenTarget);
#[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
presenting!(mln_gl::SurfaceTarget);
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
presenting!(mln_gl::HostSurfaceTarget);
#[cfg(all(feature = "gl", target_family = "wasm"))]
presenting!(mln_gl::CanvasTarget);
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
impl Borrowed for mln_webgpu::BorrowedTarget {
fn select(&self, slot: usize) {
mln_webgpu::BorrowedTarget::select(self, slot);
}
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
mln_webgpu::BorrowedTarget::release(self, slot, consumer)
}
fn discard(&self, slot: usize) {
mln_webgpu::BorrowedTarget::discard(self, slot);
}
fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
let RingKind::WebGpu(textures) = ring.kind else {
return Err(Error::unsupported("a ring of WebGPU textures takes WebGPU textures only"));
};
mln_webgpu::BorrowedTarget::replace(self, textures).map(|()| None)
}
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
impl Borrowed for mln_gl::BorrowedTarget {
fn select(&self, slot: usize) {
mln_gl::BorrowedTarget::select(self, slot);
}
fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
mln_gl::BorrowedTarget::release(self, slot, consumer)
}
fn discard(&self, slot: usize) {
mln_gl::BorrowedTarget::discard(self, slot);
}
fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
let RingKind::Gl(textures) = ring.kind else {
return Err(Error::unsupported("a ring of OpenGL textures takes OpenGL textures only"));
};
mln_gl::BorrowedTarget::replace(self, textures).map(|()| None)
}
}
#[derive(Clone)]
enum Backend {
#[cfg(feature = "webgpu")]
WebGpu(Rc<mln_webgpu::RendererBackend>),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Metal(Rc<mln_mtl::RendererBackend>),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Vulkan(Rc<mln_vulkan::RendererBackend>),
#[cfg(feature = "gl")]
Gl(Rc<mln_gl::RendererBackend>),
}
impl Backend {
fn as_dyn(&self) -> Rc<dyn RendererBackend> {
match *self {
#[cfg(feature = "webgpu")]
Backend::WebGpu(ref backend) => Rc::<mln_webgpu::RendererBackend>::clone(backend),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Backend::Metal(ref backend) => Rc::<mln_mtl::RendererBackend>::clone(backend),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Backend::Vulkan(ref backend) => Rc::<mln_vulkan::RendererBackend>::clone(backend),
#[cfg(feature = "gl")]
Backend::Gl(ref backend) => Rc::<mln_gl::RendererBackend>::clone(backend),
}
}
#[cfg_attr(
not(any(feature = "gl", all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))),
expect(clippy::unnecessary_wraps, reason = "only Vulkan and OpenGL backends can fail to start")
)]
fn new(device: &Device) -> Result<Backend, Error> {
match *device {
#[cfg(feature = "webgpu")]
Device::WebGpu(ref device) => Ok(Backend::WebGpu(Rc::new(mln_webgpu::RendererBackend::new(device)))),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(ref device) => Ok(Backend::Metal(Rc::new(mln_mtl::RendererBackend::new(device)))),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(ref device) => Ok(Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::new(device)?))),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Device::Gl(ref device) => Ok(Backend::Gl(Rc::new(mln_gl::RendererBackend::new(device)?))),
#[cfg(all(feature = "gl", target_family = "wasm"))]
Device::WebGl(_) => {
Err(Error::unsupported("WebGL2 renders only into a canvas, with the canvas's own context"))
}
}
}
fn borrowed(&self, ring: BorrowedRing, producer: SyncKind) -> Result<Box<dyn Borrowed>, Error> {
match (self, ring.kind) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Backend::Vulkan(backend), RingKind::Vulkan(images)) => {
Ok(Box::new(mln_vulkan::BorrowedTarget::new(Rc::clone(backend), images, producer)?))
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(Backend::Metal(backend), RingKind::Metal(textures)) => {
Ok(Box::new(mln_mtl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
(Backend::WebGpu(backend), RingKind::WebGpu(textures)) => {
Ok(Box::new(mln_webgpu::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
(Backend::Gl(backend), RingKind::Gl(textures)) => {
Ok(Box::new(mln_gl::BorrowedTarget::new(Rc::clone(backend), textures, producer)?))
}
_ => {
let _ = producer;
Err(Error::unsupported("the session's backend renders into no ring of this kind"))
}
}
}
fn exported(
&self,
device: &Device,
ring: &ExportedRing,
kind: ExportKind,
size: Size,
producer: SyncKind,
) -> Result<Box<dyn Exported>, Error> {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Backend::Vulkan(backend) => {
Ok(Box::new(mln_vulkan::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Backend::Metal(backend) => {
Ok(Box::new(mln_mtl::ExportedTarget::new(Rc::clone(backend), ring, kind, size, producer)?))
}
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
Backend::Gl(backend) => {
let Device::Gl(device) = device else {
return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
};
Ok(Box::new(mln_gl::ExportedTarget::new(Rc::clone(backend), device, ring, kind, size, producer)?))
}
_ => {
let _ = (device, ring, kind, size, producer);
Err(Error::unsupported("the session's backend exports no ring"))
}
}
}
#[cfg(target_family = "wasm")]
#[expect(clippy::unused_self, reason = "the other builds' targets are of the backend")]
fn offscreen(&self, _size: Size) -> Result<Box<dyn Offscreen>, Error> {
Err(Error::unsupported("the browser build renders into canvases only"))
}
#[cfg(not(target_family = "wasm"))]
#[expect(clippy::unnecessary_wraps, reason = "the browser build's fails")]
fn offscreen(&self, size: Size) -> Result<Box<dyn Offscreen>, Error> {
Ok(match *self {
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
Backend::WebGpu(ref backend) => Box::new(mln_webgpu::OffscreenTarget::new(Rc::clone(backend), size)),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Backend::Metal(ref backend) => Box::new(mln_mtl::OffscreenTarget::new(Rc::clone(backend), size)),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Backend::Vulkan(ref backend) => Box::new(mln_vulkan::OffscreenTarget::new(Rc::clone(backend), size)),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Backend::Gl(ref backend) => Box::new(mln_gl::OffscreenTarget::new(Rc::clone(backend), size)),
})
}
fn surface(&self, mut surface: Surface, size: Size) -> Result<Box<dyn Presenting>, Error> {
let overlay = surface.take_overlay()?;
match (self, surface.kind) {
#[cfg(feature = "webgpu")]
(Backend::WebGpu(backend), kind) => {
#[cfg(target_family = "wasm")]
let format = match &kind {
SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
super::target::CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
super::target::CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
super::target::CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
}),
_ => None,
};
#[cfg(not(target_family = "wasm"))]
let format = None;
let target = webgpu_surface(backend, kind)?;
let options = mln_webgpu::SurfaceOptions { format, ..mln_webgpu::SurfaceOptions::default() };
let target = mln_webgpu::SurfaceTarget::new(Rc::clone(backend), target, size, options)?;
target.set_overlay(overlay_of(overlay, |overlay| match overlay {
SurfaceOverlay::WebGpu(overlay) => Ok(overlay),
other => Err(other),
})?);
Ok(Box::new(target))
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(Backend::Metal(backend), SurfaceKind::MetalLayer(layer)) => {
let target = mln_mtl::SurfaceTarget::new(backend, layer, size, true);
target.set_overlay(overlay_of(overlay, |overlay| match overlay {
SurfaceOverlay::Metal(overlay) => Ok(overlay),
other => Err(other),
})?);
Ok(Box::new(target))
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Backend::Vulkan(backend), SurfaceKind::Window(window)) => {
let target = mln_vulkan::SurfaceTarget::new(Rc::clone(backend), window, size, true)?;
target.set_overlay(vulkan_overlay(overlay)?);
Ok(Box::new(target))
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Backend::Vulkan(backend), SurfaceKind::Vulkan(surface)) => {
let target = mln_vulkan::SurfaceTarget::on_host_surface(Rc::clone(backend), surface, size, true)?;
target.set_overlay(vulkan_overlay(overlay)?);
Ok(Box::new(target))
}
_ => {
let _ = (size, overlay);
Err(Error::unsupported("the session's backend presents to no surface of this kind"))
}
}
}
}
#[cfg_attr(
not(any(
feature = "webgpu",
all(feature = "metal", target_vendor = "apple"),
all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))),
)),
expect(dead_code, reason = "a build without a backend that takes overlays uses none")
)]
fn overlay_of<T>(
overlay: Option<SurfaceOverlay>,
own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
) -> Result<Option<T>, Error> {
overlay
.map(own)
.transpose()
.map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
fn vulkan_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
overlay_of(overlay, |overlay| match overlay {
SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
other => Err(other),
})
}
#[cfg(feature = "webgpu")]
fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
let instance = || {
backend
.device()
.instance()
.ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
};
let made = match kind {
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
SurfaceKind::Wgpu(surface) => return Ok(surface),
SurfaceKind::Window(window) => instance()?.create_surface(window),
#[cfg(target_family = "wasm")]
SurfaceKind::WebCanvas { canvas, .. } => {
use wasm_bindgen::JsCast as _;
let canvas = canvas.take().map(|canvas| (*canvas).clone()).unwrap_or_default();
let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
};
instance()?.create_surface(target)
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
};
made.map_err(|error| Error::native(format!("can't make a surface on the window: {error}")))
}
fn surface_backend(device: &Device, surface: Surface, size: Size) -> Result<(Backend, Box<dyn Presenting>), Error> {
match (device, &surface.kind) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Device::Vulkan(device), SurfaceKind::Window(window)) => {
let window = Arc::clone(window);
let mut surface = surface;
let overlay = vulkan_overlay(surface.take_overlay()?)?;
let (backend, target) = mln_vulkan::SurfaceTarget::with_backend(device, window, size, true)?;
target.set_overlay(overlay);
Ok((Backend::Vulkan(backend), Box::new(target)))
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Device::Vulkan(device), SurfaceKind::Vulkan(_)) => {
let backend = Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::presenting(device)?));
let target = backend.surface(surface, size)?;
Ok((backend, target))
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
(Device::Gl(device), SurfaceKind::Gl(host)) => {
if surface.overlay.is_some() {
return Err(Error::unsupported("a host's EGL surface takes no overlay"));
}
let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, *host, size)?;
Ok((Backend::Gl(backend), Box::new(target)))
}
#[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
(Device::Gl(_), SurfaceKind::Window(window)) => {
let window = Arc::clone(window);
let mut surface = surface;
let overlay = overlay_of(surface.take_overlay()?, |overlay| match overlay {
SurfaceOverlay::Gl(overlay) => Ok(overlay),
other => Err(other),
})?;
let (backend, target) = mln_gl::SurfaceTarget::with_backend(window, size, true)?;
target.set_overlay(overlay);
Ok((Backend::Gl(backend), Box::new(target)))
}
#[cfg(all(feature = "gl", target_family = "wasm"))]
(Device::WebGl(context), SurfaceKind::WebCanvas { canvas, .. }) => {
use wasm_bindgen::JsCast as _;
let canvas = canvas.take().map(|canvas| (*canvas).clone()).unwrap_or_default();
if let Some(context) = context.0.as_ref().and_then(|context| context.get()) {
let own =
js_sys::Reflect::get(&context, &wasm_bindgen::JsValue::from_str("canvas")).unwrap_or_default();
if !js_sys::Object::is(&own, &canvas) {
return Err(Error::invalid_argument("a WebGL device's sessions present to its context's canvas"));
}
}
let canvas = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
Ok(canvas) => mln_gl::WebCanvas::Offscreen(canvas),
Err(canvas) => mln_gl::WebCanvas::Element(canvas.unchecked_into()),
};
let (backend, target) = mln_gl::CanvasTarget::with_backend(canvas, size)?;
Ok((Backend::Gl(backend), Box::new(target)))
}
_ => {
let backend = Backend::new(device)?;
let target = backend.surface(surface, size)?;
Ok((backend, target))
}
}
}
enum Frames {
Offscreen(Box<dyn Offscreen>),
Presenting(Option<Box<dyn Presenting>>),
Borrowed {
target: Option<Box<dyn Borrowed>>,
producer: SyncKind,
},
Exported(Box<dyn Exported>),
}
pub struct LocalTarget {
device: Device,
backend: Backend,
frames: Frames,
window: Option<Arc<dyn Window>>,
}
impl LocalTarget {
pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
let device = match device {
Some(device) => device,
None => Device::new(DeviceOptions::default())?,
};
let backend = Backend::new(&device)?;
let frames = Frames::Offscreen(backend.offscreen(size)?);
Ok(LocalTarget { device, backend, frames, window: None })
}
pub fn surface(surface: Surface, device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
surface.check_area()?;
let window = surface.host_window();
let device = match device {
Some(device) => device,
None => default_surface_device(&surface)?,
};
let (backend, target) = surface_backend(&device, surface, size)?;
Ok(LocalTarget { device, backend, frames: Frames::Presenting(Some(target)), window })
}
pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
let backend = Backend::new(&device)?;
let frames = Frames::Borrowed { target: Some(backend.borrowed(ring, producer)?), producer };
Ok(LocalTarget { device, backend, frames, window: None })
}
pub fn exported(
device: Device,
ring: &ExportedRing,
kind: ExportKind,
size: Size,
producer: SyncKind,
) -> Result<LocalTarget, Error> {
let backend = Backend::new(&device)?;
let frames = Frames::Exported(backend.exported(&device, ring, kind, size, producer)?);
Ok(LocalTarget { device, backend, frames, window: None })
}
#[must_use]
pub fn device(&self) -> &Device {
&self.device
}
#[must_use]
pub fn backend(&self) -> Rc<dyn RendererBackend> {
self.backend.as_dyn()
}
#[must_use]
pub fn frames(&self) -> Option<&dyn FrameTarget> {
match &self.frames {
Frames::Offscreen(target) => Some(&**target),
Frames::Presenting(target) => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
Frames::Borrowed { target, .. } => target.as_deref().map(|target| -> &dyn FrameTarget { target }),
Frames::Exported(target) => Some(&**target),
}
}
#[must_use]
pub fn window_has_area(&self) -> bool {
self.window.as_deref().is_none_or(mln_gfx::window::has_area)
}
#[must_use]
pub fn is_presenting(&self) -> bool {
matches!(self.frames, Frames::Presenting(_))
}
#[must_use]
pub fn is_exported(&self) -> bool {
matches!(self.frames, Frames::Exported(_))
}
#[must_use]
pub fn is_borrowed(&self) -> bool {
matches!(self.frames, Frames::Borrowed { .. })
}
#[must_use]
pub fn ring_released(&self) -> bool {
matches!(self.frames, Frames::Borrowed { target: None, .. })
}
fn ring(&self) -> Result<&dyn Borrowed, Error> {
match &self.frames {
Frames::Borrowed { target: Some(target), .. } => Ok(&**target),
Frames::Borrowed { target: None, .. } => Err(Error::invalid_state("the ring was released")),
_ => Err(Error::unsupported("the target has no ring")),
}
}
pub fn select_slot(&self, slot: usize) -> Result<(), Error> {
if let Frames::Exported(target) = &self.frames {
target.select(slot);
return Ok(());
}
self.ring()?.select(slot);
Ok(())
}
pub fn release_slot(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
if let Frames::Exported(target) = &self.frames {
return target.release(slot, consumer);
}
self.ring()?.release(slot, consumer)
}
pub fn discard_slot(&self, slot: usize) -> Result<(), Error> {
if let Frames::Exported(target) = &self.frames {
target.discard(slot);
return Ok(());
}
self.ring()?.discard(slot);
Ok(())
}
#[must_use]
pub fn exported_size(&self) -> Option<Size> {
match &self.frames {
Frames::Exported(target) => Some(target.size()),
_ => None,
}
}
pub fn resize_exported(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
match &self.frames {
Frames::Exported(target) => target.resize(size, held),
_ => Err(Error::unsupported("the target exports no ring")),
}
}
#[must_use]
pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
match &self.frames {
Frames::Exported(target) => target.image(slot).map(|frame| FrameTexture::exported(frame, &self.device)),
_ => None,
}
}
pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<Pending, Error> {
match &mut self.frames {
Frames::Borrowed { target: Some(target), .. } => target.replace(ring),
Frames::Borrowed { target, producer } => {
*target = Some(self.backend.borrowed(ring, *producer)?);
Ok(None)
}
_ => Err(Error::unsupported("the target has no ring")),
}
}
#[must_use]
pub fn is_offscreen(&self) -> bool {
matches!(self.frames, Frames::Offscreen(_))
}
pub fn resize(&self, size: Size) {
match &self.frames {
Frames::Offscreen(target) => target.resize(size),
Frames::Presenting(Some(target)) => target.resize(size),
Frames::Presenting(None) | Frames::Borrowed { .. } | Frames::Exported(_) => {}
}
}
pub fn read_image(&self) -> Result<PremultipliedImage, Error> {
match &self.frames {
Frames::Offscreen(target) => target.read_image(),
Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
Frames::Borrowed { .. } | Frames::Exported(_) => {
Err(Error::unsupported("a ring's frames are the host's to read"))
}
}
}
pub(crate) fn release_surface(&mut self) -> Pending {
match &mut self.frames {
Frames::Presenting(target) => {
drop(target.take());
self.window = None;
None
}
Frames::Borrowed { target, .. } => target.take().and_then(|target| target.take_pending()),
Frames::Offscreen(_) | Frames::Exported(_) => None,
}
}
pub fn set_surface(&mut self, surface: Surface, size: Size) -> Result<bool, Error> {
if !matches!(self.frames, Frames::Presenting(_)) {
return Err(Error::unsupported("only a surface target presents to another surface"));
}
surface.check_area()?;
let window = surface.host_window();
let retry = surface.clone_window();
let (new_backend, target) = match self.backend.surface(surface, size) {
Ok(target) => (false, target),
Err(error) if error.kind == mln_util::ErrorKind::Unsupported => {
let surface = retry.ok_or(error)?;
let (backend, target) = surface_backend(&self.device, surface, size)?;
self.backend = backend;
(true, target)
}
Err(error) => return Err(error),
};
self.frames = Frames::Presenting(Some(target));
self.window = window;
Ok(new_backend)
}
}
fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
match surface.kind {
SurfaceKind::Window(_) if cfg!(target_vendor = "apple") => {
Device::with_backend(super::target::BackendType::WebGPU, DeviceOptions::default())
}
SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
#[cfg(all(target_family = "wasm", feature = "gl"))]
SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl(super::target::WebGlContext::default())),
#[cfg(all(target_family = "wasm", not(feature = "gl")))]
SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
}
}