1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use crate::{GpuRenderer, GraphicsError};
use async_trait::async_trait;
use log::{debug, info};
use std::{path::Path, sync::Arc};
use wgpu::{
    core::instance::RequestAdapterError, Adapter, Backend, Backends,
    DeviceType, Surface, TextureFormat,
};
use winit::{
    dpi::PhysicalSize,
    event::{Event, WindowEvent},
    window::Window,
};

///Handles the Device and Queue returned from WGPU.
pub struct GpuDevice {
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
}

impl GpuDevice {
    pub fn device(&self) -> &wgpu::Device {
        &self.device
    }

    pub fn queue(&self) -> &wgpu::Queue {
        &self.queue
    }
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash)]
pub enum AdapterPowerSettings {
    LowPower,
    #[default]
    HighPower,
}

#[derive(Debug)]
pub struct AdapterOptions {
    /// Power preference for the adapter.
    pub allowed_backends: Backends,
    pub power: AdapterPowerSettings,
    /// Surface that is required to be presentable with the requested adapter. This does not
    /// create the surface, only guarantees that the adapter can present to said surface.
    /// Recommend checking this always.
    pub compatible_surface: Option<Surface<'static>>,
}

///Handles the Window, Adapter and Surface information.
pub struct GpuWindow {
    pub(crate) adapter: wgpu::Adapter,
    pub(crate) surface: wgpu::Surface<'static>,
    pub(crate) window: Arc<Window>,
    pub(crate) surface_format: wgpu::TextureFormat,
    pub(crate) size: PhysicalSize<f32>,
    pub(crate) inner_size: PhysicalSize<u32>,
    pub(crate) surface_config: wgpu::SurfaceConfiguration,
}

impl GpuWindow {
    pub fn adapter(&self) -> &wgpu::Adapter {
        &self.adapter
    }

    pub fn resize(
        &mut self,
        gpu_device: &GpuDevice,
        size: PhysicalSize<u32>,
    ) -> Result<(), GraphicsError> {
        if size.width == 0 || size.height == 0 {
            return Ok(());
        }

        self.surface_config.height = size.height;
        self.surface_config.width = size.width;
        self.surface
            .configure(gpu_device.device(), &self.surface_config);
        self.size = PhysicalSize::new(size.width as f32, size.height as f32);

        Ok(())
    }

    pub fn size(&self) -> PhysicalSize<f32> {
        self.size
    }

    pub fn surface(&self) -> &wgpu::Surface {
        &self.surface
    }

    pub fn surface_format(&self) -> wgpu::TextureFormat {
        self.surface_format
    }

    pub fn update(
        &mut self,
        gpu_device: &GpuDevice,
        event: &Event<()>,
    ) -> Result<Option<wgpu::SurfaceTexture>, GraphicsError> {
        match event {
            Event::WindowEvent {
                ref event,
                window_id,
            } if *window_id == self.window.id() => match event {
                WindowEvent::Resized(physical_size) => {
                    self.resize(gpu_device, *physical_size)?;
                    self.inner_size = self.window.inner_size();

                    if self.size.width == 0.0
                        || self.size.height == 0.0
                        || self.inner_size.width == 0
                        || self.inner_size.height == 0
                    {
                        return Ok(None);
                    }

                    self.window.request_redraw();
                }
                WindowEvent::RedrawRequested => {
                    if self.size.width == 0.0
                        || self.size.height == 0.0
                        || self.inner_size.width == 0
                        || self.inner_size.height == 0
                    {
                        return Ok(None);
                    }

                    match self.surface.get_current_texture() {
                        Ok(frame) => {
                            self.window.request_redraw();
                            return Ok(Some(frame));
                        }
                        Err(wgpu::SurfaceError::Lost) => {
                            let size = PhysicalSize::new(
                                self.size.width as u32,
                                self.size.height as u32,
                            );
                            self.resize(gpu_device, size)?;
                            self.inner_size = self.window.inner_size();

                            if self.size.width == 0.0
                                || self.size.height == 0.0
                                || self.inner_size.width == 0
                                || self.inner_size.height == 0
                            {
                                return Ok(None);
                            }
                        }
                        Err(wgpu::SurfaceError::Outdated) => {
                            return Ok(None);
                        }
                        Err(e) => return Err(GraphicsError::from(e)),
                    }

                    self.window.request_redraw();
                }
                WindowEvent::Moved(_)
                | WindowEvent::ScaleFactorChanged {
                    scale_factor: _,
                    inner_size_writer: _,
                }
                | WindowEvent::Focused(true)
                | WindowEvent::Occluded(false) => {
                    self.window.request_redraw();
                }
                _ => (),
            },
            _ => (),
        }

        Ok(None)
    }

    pub fn window(&self) -> &Window {
        &self.window
    }

    pub fn create_depth_texture(
        &self,
        gpu_device: &GpuDevice,
    ) -> wgpu::TextureView {
        let size = wgpu::Extent3d {
            width: self.size.width as u32,
            height: self.size.height as u32,
            depth_or_array_layers: 1,
        };

        let texture =
            gpu_device
                .device()
                .create_texture(&wgpu::TextureDescriptor {
                    label: Some("depth texture"),
                    size,
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: wgpu::TextureFormat::Depth32Float,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::RENDER_ATTACHMENT
                        | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[TextureFormat::Depth32Float],
                });

        texture.create_view(&wgpu::TextureViewDescriptor::default())
    }
}

#[async_trait]
pub trait AdapterExt {
    async fn create_renderer(
        self,
        instance: &wgpu::Instance,
        window: &Arc<Window>,
        device_descriptor: &wgpu::DeviceDescriptor,
        trace_path: Option<&Path>,
        present_mode: wgpu::PresentMode,
    ) -> Result<GpuRenderer, GraphicsError>;
}

#[async_trait]
impl AdapterExt for wgpu::Adapter {
    async fn create_renderer(
        self,
        instance: &wgpu::Instance,
        window: &Arc<Window>,
        device_descriptor: &wgpu::DeviceDescriptor,
        trace_path: Option<&Path>,
        present_mode: wgpu::PresentMode,
    ) -> Result<GpuRenderer, GraphicsError> {
        let size = window.inner_size();

        let (device, queue) =
            self.request_device(device_descriptor, trace_path).await?;

        let surface = instance.create_surface(window.clone()).unwrap();
        let caps = surface.get_capabilities(&self);

        debug!("{:?}", caps.formats);

        let rgba = caps
            .formats
            .iter()
            .position(|v| *v == TextureFormat::Rgba8UnormSrgb);
        let bgra = caps
            .formats
            .iter()
            .position(|v| *v == TextureFormat::Bgra8UnormSrgb);

        let format = if let Some(pos) = rgba {
            caps.formats[pos]
        } else if let Some(pos) = bgra {
            caps.formats[pos]
        } else {
            panic!("Your Rendering Device does not support Bgra8UnormSrgb or Rgba8UnormSrgb");
        };

        debug!("surface format: {:?}", format);
        let surface_config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            width: size.width,
            height: size.height,
            present_mode,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![format],
            desired_maximum_frame_latency: 2,
        };

        surface.configure(&device, &surface_config);
        let inner_size = window.inner_size();
        let mut renderer = GpuRenderer::new(
            GpuWindow {
                adapter: self,
                surface,
                window: window.clone(),
                surface_format: format,
                size: PhysicalSize::new(size.width as f32, size.height as f32),
                surface_config,
                inner_size,
            },
            GpuDevice { device, queue },
        );

        // Creates the shader rendering pipelines for each renderer.
        renderer.create_pipelines(renderer.surface_format());
        Ok(renderer)
    }
}

#[async_trait]
pub trait InstanceExt {
    async fn create_device(
        &self,
        window: Arc<Window>,
        options: AdapterOptions,
        device_descriptor: &wgpu::DeviceDescriptor,
        trace_path: Option<&Path>,
        present_mode: wgpu::PresentMode,
    ) -> Result<GpuRenderer, GraphicsError>;

    fn get_adapters(&self, options: AdapterOptions) -> Vec<(Adapter, u32)>;
}

#[async_trait]
impl InstanceExt for wgpu::Instance {
    fn get_adapters(&self, options: AdapterOptions) -> Vec<(Adapter, u32)> {
        let mut adapters = self.enumerate_adapters(options.allowed_backends);
        let mut compatible_adapters: Vec<(Adapter, u32)> = Vec::new();

        while let Some(adapter) = adapters.pop() {
            let information = adapter.get_info();

            if information.backend == Backend::Empty {
                continue;
            }

            let device_type = match information.device_type {
                DeviceType::IntegratedGpu => {
                    if options.power == AdapterPowerSettings::LowPower {
                        1
                    } else {
                        2
                    }
                }
                DeviceType::DiscreteGpu => {
                    if options.power == AdapterPowerSettings::LowPower {
                        2
                    } else {
                        1
                    }
                }
                DeviceType::VirtualGpu | DeviceType::Cpu => 3,
                _ => continue,
            };

            if let Some(ref surface) = options.compatible_surface {
                if !adapter.is_surface_supported(surface) {
                    continue;
                }
            }

            compatible_adapters.push((adapter, device_type));
        }

        compatible_adapters.sort_by(|a, b| a.1.cmp(&b.1));
        compatible_adapters
    }

    async fn create_device(
        &self,
        window: Arc<Window>,
        options: AdapterOptions,
        device_descriptor: &wgpu::DeviceDescriptor,
        trace_path: Option<&Path>,
        present_mode: wgpu::PresentMode,
    ) -> Result<GpuRenderer, GraphicsError> {
        let mut adapters = self.get_adapters(options);

        while let Some(adapter) = adapters.pop() {
            let ret = adapter
                .0
                .create_renderer(
                    self,
                    &window,
                    device_descriptor,
                    trace_path,
                    present_mode,
                )
                .await;

            if ret.is_ok() {
                if adapter.1 == 3 {
                    info!(
                        "A virtual or software rendering Driver was choosen."
                    );
                }
                return ret;
            }
        }

        Err(GraphicsError::Adapter(RequestAdapterError::NotFound))
    }
}