use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
use winit::window::Window;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RendererInitError {
Surface(String),
Adapter(String),
Device(String),
UnsupportedSurface,
}
impl fmt::Display for RendererInitError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Surface(message) | Self::Adapter(message) | Self::Device(message) => {
formatter.write_str(message)
}
Self::UnsupportedSurface => formatter.write_str("surface has no compatible format"),
}
}
}
impl std::error::Error for RendererInitError {}
pub struct Gpu {
pub device: wgpu::Device,
pub queue: wgpu::Queue,
}
#[derive(Debug)]
pub enum GpuError {
NoAdapter(String),
NoDevice(String),
}
impl std::fmt::Display for GpuError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoAdapter(err) => write!(f, "no wgpu adapter available ({err})"),
Self::NoDevice(err) => write!(f, "adapter cannot create a default device ({err})"),
}
}
}
impl std::error::Error for GpuError {}
fn device_descriptor(label: &'static str) -> wgpu::DeviceDescriptor<'static> {
wgpu::DeviceDescriptor {
label: Some(label),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
experimental_features: wgpu::ExperimentalFeatures::default(),
memory_hints: wgpu::MemoryHints::default(),
trace: wgpu::Trace::Off,
}
}
impl Gpu {
#[cfg(not(target_arch = "wasm32"))]
pub fn headless() -> Result<Self, GpuError> {
pollster::block_on(Self::headless_async())
}
pub async fn headless_async() -> Result<Self, GpuError> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions::default())
.await
.map_err(|err| GpuError::NoAdapter(err.to_string()))?;
let (device, queue) = adapter
.request_device(&device_descriptor("sgl headless device"))
.await
.map_err(|err| GpuError::NoDevice(err.to_string()))?;
Ok(Self { device, queue })
}
}
pub struct Context {
gpu: Gpu,
pub surface_format: wgpu::TextureFormat,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
}
impl Deref for Context {
type Target = Gpu;
fn deref(&self) -> &Gpu {
&self.gpu
}
}
pub struct Frame {
surface_texture: wgpu::SurfaceTexture,
queue: wgpu::Queue,
pub view: wgpu::TextureView,
}
impl Frame {
pub fn present(self) {
self.queue.present(self.surface_texture);
}
}
impl Context {
#[cfg(not(target_arch = "wasm32"))]
pub fn new(window: Arc<Window>, vsync: bool) -> Self {
pollster::block_on(Self::new_async(window, vsync))
}
pub async fn new_async(window: Arc<Window>, vsync: bool) -> Self {
Self::try_new_async(window, vsync)
.await
.unwrap_or_else(|err| panic!("GPU init failed: {err}"))
}
#[cfg(not(target_arch = "wasm32"))]
pub fn try_new(window: Arc<Window>, vsync: bool) -> Result<Self, RendererInitError> {
pollster::block_on(Self::try_new_async(window, vsync))
}
pub async fn try_new_async(
window: Arc<Window>,
vsync: bool,
) -> Result<Self, RendererInitError> {
let instance = wgpu::Instance::default();
let surface = instance
.create_surface(window.clone())
.map_err(|error| RendererInitError::Surface(error.to_string()))?;
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::None,
force_fallback_adapter: false,
compatible_surface: Some(&surface),
apply_limit_buckets: false,
})
.await
.map_err(|error| RendererInitError::Adapter(error.to_string()))?;
let (device, queue) = adapter
.request_device(&device_descriptor("sgl canvas device"))
.await
.map_err(|error| RendererInitError::Device(error.to_string()))?;
let caps = surface.get_capabilities(&adapter);
#[cfg(not(target_arch = "wasm32"))]
let format = caps
.formats
.iter()
.copied()
.find(wgpu::TextureFormat::is_srgb)
.unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
#[cfg(target_arch = "wasm32")]
let format = caps
.formats
.iter()
.copied()
.find(|format| {
matches!(
format,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
)
})
.unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
let alpha_mode = *caps
.alpha_modes
.first()
.ok_or(RendererInitError::UnsupportedSurface)?;
let size = window.inner_size();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
color_space: wgpu::SurfaceColorSpace::Auto,
width: size.width.max(1),
height: size.height.max(1),
present_mode: if vsync {
wgpu::PresentMode::AutoVsync
} else {
wgpu::PresentMode::AutoNoVsync
},
alpha_mode,
view_formats: Vec::new(),
desired_maximum_frame_latency: 2,
};
surface.configure(&device, &config);
Ok(Self {
gpu: Gpu { device, queue },
surface_format: format,
surface,
config,
})
}
pub fn size(&self) -> (u32, u32) {
(self.config.width, self.config.height)
}
pub fn resize(&mut self, width: u32, height: u32) {
if width == 0 || height == 0 {
return;
}
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.gpu.device, &self.config);
}
pub fn acquire(&mut self) -> Option<Frame> {
use wgpu::CurrentSurfaceTexture as Current;
let surface_texture = match self.surface.get_current_texture() {
Current::Success(texture) | Current::Suboptimal(texture) => texture,
Current::Outdated | Current::Lost => {
self.surface.configure(&self.gpu.device, &self.config);
match self.surface.get_current_texture() {
Current::Success(texture) | Current::Suboptimal(texture) => texture,
_ => return None,
}
}
Current::Timeout | Current::Occluded | Current::Validation => return None,
};
let view = surface_texture
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
Some(Frame {
surface_texture,
queue: self.gpu.queue.clone(),
view,
})
}
}