Skip to main content

pebble/wgpu/
texture_view.rs

1use crate::wgpu::backend::WGPUBackend;
2
3/// A `wgpu::TextureView`, opaque — the [`FrameOperations::Attachment`](crate::rendering::backend::FrameOperations::Attachment)/
4/// [`DepthAttachment`](crate::rendering::backend::FrameOperations::DepthAttachment)
5/// type for [`WGPUBackend`], and [`TextureBuilder::build`]'s return type.
6/// Bundles the backing `wgpu::Texture` alongside the view (kept alive,
7/// never otherwise accessed) — the view alone isn't enough to keep the
8/// underlying resource alive for as long as it's needed.
9pub struct TextureView {
10    view: wgpu::TextureView,
11    _texture: wgpu::Texture,
12}
13
14impl TextureView {
15    pub(crate) fn raw(&self) -> &wgpu::TextureView {
16        &self.view
17    }
18}
19
20/// Builds a one-off GPU-side texture with no source data — a depth buffer,
21/// an off-screen render target — and hands back its
22/// [`TextureView`]. Unlike [`TextureDescriptor`](super::textures::TextureDescriptor),
23/// which loads pixel data from a file/bytes through the asset pipeline,
24/// this allocates an empty texture directly; there's nothing to upload.
25///
26/// ```ignore
27/// let depth_view = TextureBuilder::new(backend.config.width, backend.config.height, wgpu::TextureFormat::Depth16Unorm)
28///     .usage(wgpu::TextureUsages::RENDER_ATTACHMENT)
29///     .build(backend);
30/// ```
31pub struct TextureBuilder<'a> {
32    label: Option<&'a str>,
33    width: u32,
34    height: u32,
35    format: wgpu::TextureFormat,
36    usage: wgpu::TextureUsages,
37    mip_level_count: u32,
38}
39
40impl<'a> TextureBuilder<'a> {
41    pub fn new(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
42        Self { label: None, width, height, format, usage: wgpu::TextureUsages::empty(), mip_level_count: 1 }
43    }
44
45    pub fn label(mut self, label: impl Into<Option<&'a str>>) -> Self {
46        self.label = label.into();
47        self
48    }
49
50    pub fn usage(mut self, usage: wgpu::TextureUsages) -> Self {
51        self.usage = usage;
52        self
53    }
54
55    pub fn mip_level_count(mut self, count: u32) -> Self {
56        self.mip_level_count = count;
57        self
58    }
59
60    pub fn build(self, backend: &WGPUBackend) -> TextureView {
61        let texture = backend.device.create_texture(&wgpu::TextureDescriptor {
62            label: self.label,
63            size: wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 },
64            mip_level_count: self.mip_level_count,
65            sample_count: 1,
66            dimension: wgpu::TextureDimension::D2,
67            format: self.format,
68            usage: self.usage,
69            view_formats: &[],
70        });
71        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
72        TextureView { view, _texture: texture }
73    }
74}