use std::sync::Arc;
pub struct GpuContext {
pub instance: wgpu::Instance,
pub adapter: wgpu::Adapter,
pub device: Arc<wgpu::Device>,
pub queue: Arc<wgpu::Queue>,
}
const OPTIONAL_FEATURES: wgpu::Features = wgpu::Features::RG11B10UFLOAT_RENDERABLE
.union(wgpu::Features::TIMESTAMP_QUERY)
.union(wgpu::Features::PIPELINE_CACHE)
.union(TEXTURE_FEATURES);
pub const TEXTURE_FEATURES: wgpu::Features = wgpu::Features::TEXTURE_COMPRESSION_BC
.union(wgpu::Features::TEXTURE_COMPRESSION_ETC2)
.union(wgpu::Features::TEXTURE_COMPRESSION_ASTC)
.union(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
.union(wgpu::Features::FLOAT32_FILTERABLE);
impl GpuContext {
pub async fn headless() -> Result<Self, String> {
Self::headless_with_optional_features(wgpu::Features::empty()).await
}
pub async fn headless_with_optional_features(optional: wgpu::Features) -> Result<Self, String> {
let instance = instance(backends());
let adapter = request_adapter(&instance, None).await?;
Self::open_with_optional_features(instance, adapter, optional).await
}
pub async fn with_surface(
target: wgpu::SurfaceTarget<'static>,
) -> Result<(Self, wgpu::Surface<'static>), String> {
Self::with_surface_and_optional_features(target, wgpu::Features::empty()).await
}
pub async fn with_surface_and_optional_features(
target: wgpu::SurfaceTarget<'static>,
optional: wgpu::Features,
) -> Result<(Self, wgpu::Surface<'static>), String> {
let instance = instance(backends());
let surface = instance
.create_surface(target)
.map_err(|e| format!("no surface: {e}"))?;
let adapter = request_adapter(&instance, Some(&surface)).await?;
let gpu = Self::open_with_optional_features(instance, adapter, optional).await?;
Ok((gpu, surface))
}
pub async fn open(instance: wgpu::Instance, adapter: wgpu::Adapter) -> Result<Self, String> {
Self::open_with_optional_features(instance, adapter, wgpu::Features::empty()).await
}
pub async fn open_with_optional_features(
instance: wgpu::Instance,
adapter: wgpu::Adapter,
optional: wgpu::Features,
) -> Result<Self, String> {
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("threers device"),
required_features: (OPTIONAL_FEATURES | optional) & adapter.features(),
required_limits: renderer_limits(&adapter),
..Default::default()
})
.await
.map_err(|e| format!("no device: {e}"))?;
#[cfg(target_arch = "wasm32")]
report_uncaptured_errors(&device, "threers");
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
})
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos"
))]
pub async unsafe fn from_metal_layer(
layer: *mut std::ffi::c_void,
) -> Result<(Self, wgpu::Surface<'static>), String> {
let instance = instance(backends());
let surface = unsafe {
instance
.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(layer))
.map_err(|e| format!("no surface from the layer: {e}"))?
};
let adapter = request_adapter(&instance, Some(&surface)).await?;
let gpu = Self::open(instance, adapter).await?;
Ok((gpu, surface))
}
pub async fn headless_webgl2() -> Result<Self, String> {
let instance = instance(backends());
let adapter = request_adapter(&instance, None).await?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("threers device (WebGL2 limits)"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits()),
..Default::default()
})
.await
.map_err(|e| format!("no device: {e}"))?;
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
})
}
#[cfg(not(target_arch = "wasm32"))]
pub fn headless_blocking() -> Result<Self, String> {
pollster::block_on(Self::headless())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn headless_webgl2_blocking() -> Result<Self, String> {
pollster::block_on(Self::headless_webgl2())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn with_surface_blocking(
target: wgpu::SurfaceTarget<'static>,
) -> Result<(Self, wgpu::Surface<'static>), String> {
pollster::block_on(Self::with_surface(target))
}
pub fn surface_config(
&self,
surface: &wgpu::Surface<'_>,
width: u32,
height: u32,
prefer_srgb: bool,
) -> wgpu::SurfaceConfiguration {
let caps = surface.get_capabilities(&self.adapter);
let format = caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb() == prefer_srgb)
.unwrap_or(caps.formats[0]);
wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width: width.max(1),
height: height.max(1),
present_mode: caps.present_modes[0],
alpha_mode: caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
color_space: wgpu::SurfaceColorSpace::Srgb,
}
}
pub fn describe(&self) -> String {
let info = self.adapter.get_info();
format!("{} ({:?}, {:?})", info.name, info.backend, info.device_type)
}
}
#[cfg(target_arch = "wasm32")]
pub fn report_uncaptured_errors(device: &wgpu::Device, label: &'static str) {
use std::sync::atomic::{AtomicU32, Ordering};
const MAX: u32 = 16;
let seen = AtomicU32::new(0);
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
let n = seen.fetch_add(1, Ordering::Relaxed);
let msg = if n < MAX {
format!("[{label}] GPU error: {e}")
} else if n == MAX {
format!("[{label}] further GPU errors are not printed")
} else {
return;
};
web_sys::console::error_1(&msg.into());
}));
}
pub fn renderer_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
let adapter_limits = adapter.limits();
let floor = if adapter.get_info().backend == wgpu::Backend::Gl {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::downlevel_defaults()
};
let mut limits = floor.using_resolution(adapter_limits.clone());
limits.max_sampled_textures_per_shader_stage = adapter_limits
.max_sampled_textures_per_shader_stage
.max(limits.max_sampled_textures_per_shader_stage);
limits.max_samplers_per_shader_stage = adapter_limits
.max_samplers_per_shader_stage
.max(limits.max_samplers_per_shader_stage);
limits
}
fn backends() -> wgpu::Backends {
if cfg!(target_arch = "wasm32") {
wgpu::Backends::BROWSER_WEBGPU
} else {
wgpu::Backends::PRIMARY
}
}
fn instance(backends: wgpu::Backends) -> wgpu::Instance {
let mut d = wgpu::InstanceDescriptor::new_without_display_handle();
d.backends = backends;
wgpu::Instance::new(d)
}
async fn request_adapter(
instance: &wgpu::Instance,
surface: Option<&wgpu::Surface<'_>>,
) -> Result<wgpu::Adapter, String> {
instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: surface,
force_fallback_adapter: false,
apply_limit_buckets: false,
})
.await
.map_err(|e| format!("no adapter: {e}"))
}
pub mod testing {
#[cfg(not(target_arch = "wasm32"))]
use super::GpuContext;
#[cfg(not(target_arch = "wasm32"))]
pub fn context(what: &str) -> Option<GpuContext> {
match GpuContext::headless_blocking() {
Ok(gpu) => Some(gpu),
Err(e) => {
eprintln!("skipping {what}: {e}");
None
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_renderer_limits_raise_the_two_that_matter() {
let Some(gpu) = testing::context("limits") else {
return;
};
let limits = renderer_limits(&gpu.adapter);
let downlevel = wgpu::Limits::downlevel_defaults();
let adapter = gpu.adapter.limits();
for (name, got, floor, have) in [
(
"sampled textures",
limits.max_sampled_textures_per_shader_stage,
downlevel.max_sampled_textures_per_shader_stage,
adapter.max_sampled_textures_per_shader_stage,
),
(
"samplers",
limits.max_samplers_per_shader_stage,
downlevel.max_samplers_per_shader_stage,
adapter.max_samplers_per_shader_stage,
),
] {
assert!(got >= floor, "{name}: {got} is below the downlevel {floor}");
assert!(
got >= have,
"{name}: {got} leaves the adapter's {have} unused"
);
}
assert!(
limits.max_texture_dimension_2d >= 4096,
"the shadow atlas is 4096 and this allows {}",
limits.max_texture_dimension_2d
);
}
#[test]
fn a_headless_context_can_carry_a_renderer() {
let Some(gpu) = testing::context("headless context") else {
return;
};
assert!(!gpu.describe().is_empty());
let _renderer = crate::Renderer::new(
gpu.device.clone(),
gpu.queue.clone(),
wgpu::TextureFormat::Rgba8Unorm,
64,
64,
);
}
}