1pub mod adapter;
4pub mod depth;
5pub mod descriptor;
6pub mod device;
7pub mod gltf;
8pub mod material;
9pub mod mesh;
10pub mod pipeline;
11pub mod prelude;
12pub mod shader;
13pub mod surface;
14pub mod texture;
15
16pub use wgpu;
17
18use std::sync::Arc;
19
20use adapter::create_instance;
21use device::DeviceQueue;
22use surface::SurfaceState;
23
24#[derive(thiserror::Error, Debug)]
25pub enum RendererError {
26 #[error("Failed to request adapter: {0}")]
27 Adapter(#[from] wgpu::RequestAdapterError),
28 #[error("Failed to request device: {0}")]
29 Device(#[from] wgpu::RequestDeviceError),
30 #[error("Failed to acquire surface texture: {0}")]
31 Surface(#[from] wgpu::SurfaceError),
32}
33
34pub struct Renderer {
35 pub device: Arc<wgpu::Device>,
36 pub queue: Arc<wgpu::Queue>,
37 pub surface: SurfaceState,
38 #[allow(dead_code)]
39 instance: Arc<wgpu::Instance>,
40 #[allow(dead_code)]
41 adapter: Arc<wgpu::Adapter>,
42}
43
44impl Renderer {
45 pub async fn new(window: Arc<winit::window::Window>) -> Result<Self, RendererError> {
46 let instance = Arc::new(create_instance());
47
48 let surface = instance
49 .create_surface(window.clone())
50 .expect("Failed to create surface");
51
52 let adapter = Arc::new(adapter::request_adapter(&instance, Some(&surface)).await?);
53
54 tracing::info!(
55 "Using GPU: {} ({:?})",
56 adapter::adapter_info(&adapter).name,
57 adapter::adapter_info(&adapter).device_type
58 );
59
60 let DeviceQueue { device, queue } = device::request_device(&adapter).await?;
61
62 let size = window.inner_size();
63 let surface = SurfaceState::new(surface, &adapter, &device, size.width, size.height);
64
65 Ok(Self {
66 device: Arc::new(device),
67 queue: Arc::new(queue),
68 surface,
69 instance,
70 adapter,
71 })
72 }
73
74 pub fn resize(&mut self, width: u32, height: u32) {
75 self.surface.resize(&self.device, width, height);
76 }
77
78 pub fn format(&self) -> wgpu::TextureFormat {
79 self.surface.format()
80 }
81
82 pub fn width(&self) -> u32 {
83 self.surface.width()
84 }
85
86 pub fn height(&self) -> u32 {
87 self.surface.height()
88 }
89
90 pub fn begin_frame(&self) -> Result<wgpu::SurfaceTexture, RendererError> {
91 self.surface.acquire().map_err(RendererError::from)
92 }
93
94 pub fn submit(&self, command_buffers: Vec<wgpu::CommandBuffer>) {
95 self.queue.submit(command_buffers);
96 }
97}