atagen

monolith

public
Star0
Watch0
acf5e98485297185fedf9038c5d17c72e7983674
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/render-vk/src/image.rsRust242 lines7.4 KB
1
use crate::Error;
2
use crate::device::Shared;
3
use crate::format::{components, vk_format};
4
use ash::vk;
5
use gpu_allocator::MemoryLocation;
6
use gpu_allocator::vulkan::{Allocation, AllocationCreateDesc, AllocationScheme};
7
use smithay::backend::allocator::Fourcc;
8
use smithay::backend::renderer::{Texture, TextureMapping};
9
use std::fmt;
10
use std::marker::PhantomData;
11
use std::sync::{Arc, Mutex};
12
13
pub(crate) enum Memory {
14
    Allocated(Allocation),
15
    /// Memory imported from a dmabuf, owned directly.
16
    Imported(vk::DeviceMemory),
17
}
18
19
pub(crate) struct ImageInner {
20
    pub shared: Arc<Shared>,
21
    pub image: vk::Image,
22
    pub view: vk::ImageView,
23
    pub memory: Mutex<Option<Memory>>,
24
    pub fourcc: Fourcc,
25
    pub format: vk::Format,
26
    pub width: u32,
27
    pub height: u32,
28
    pub layout: Mutex<vk::ImageLayout>,
29
    /// Shared with other devices or processes through a dmabuf. Every use
30
    /// acquires the image from the foreign queue family and releases it after.
31
    pub external: bool,
32
}
33
34
impl fmt::Debug for ImageInner {
35
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36
        f.debug_struct("ImageInner")
37
            .field("image", &self.image)
38
            .field("fourcc", &self.fourcc)
39
            .field("size", &(self.width, self.height))
40
            .field("external", &self.external)
41
            .finish()
42
    }
43
}
44
45
impl Drop for ImageInner {
46
    fn drop(&mut self) {
47
        let d = &self.shared.device.device;
48
        unsafe {
49
            d.destroy_image_view(self.view, None);
50
            d.destroy_image(self.image, None);
51
        }
52
        match self.memory.lock().unwrap_or_else(|e| e.into_inner()).take() {
53
            Some(Memory::Allocated(a)) => {
54
                let _ = self
55
                    .shared
56
                    .allocator
57
                    .lock()
58
                    .unwrap_or_else(|e| e.into_inner())
59
                    .free(a);
60
            }
61
            Some(Memory::Imported(m)) => unsafe { d.free_memory(m, None) },
62
            None => {}
63
        }
64
    }
65
}
66
67
impl ImageInner {
68
    pub fn create(
69
        shared: &Arc<Shared>,
70
        fourcc: Fourcc,
71
        width: u32,
72
        height: u32,
73
        usage: vk::ImageUsageFlags,
74
    ) -> Result<Arc<Self>, Error> {
75
        let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?;
76
        if width == 0 || height == 0 {
77
            return Err(Error::InvalidSize(width as i32, height as i32));
78
        }
79
        let d = &shared.device.device;
80
        let info = vk::ImageCreateInfo::default()
81
            .image_type(vk::ImageType::TYPE_2D)
82
            .format(fmt.format)
83
            .extent(vk::Extent3D {
84
                width,
85
                height,
86
                depth: 1,
87
            })
88
            .mip_levels(1)
89
            .array_layers(1)
90
            .samples(vk::SampleCountFlags::TYPE_1)
91
            .tiling(vk::ImageTiling::OPTIMAL)
92
            .usage(usage)
93
            .initial_layout(vk::ImageLayout::UNDEFINED);
94
        let image = unsafe { d.create_image(&info, None)? };
95
        let requirements = unsafe { d.get_image_memory_requirements(image) };
96
        let allocation = shared
97
            .allocator
98
            .lock()
99
            .unwrap_or_else(|e| e.into_inner())
100
            .allocate(&AllocationCreateDesc {
101
                name: "image",
102
                requirements,
103
                location: MemoryLocation::GpuOnly,
104
                linear: false,
105
                allocation_scheme: AllocationScheme::GpuAllocatorManaged,
106
            });
107
        let allocation = match allocation {
108
            Ok(a) => a,
109
            Err(e) => {
110
                unsafe { d.destroy_image(image, None) };
111
                return Err(e.into());
112
            }
113
        };
114
        let memory = Memory::Allocated(allocation);
115
        let (mem, offset) = match &memory {
116
            Memory::Allocated(a) => (unsafe { a.memory() }, a.offset()),
117
            Memory::Imported(m) => (*m, 0),
118
        };
119
        Self::finish(
120
            shared, image, memory, mem, offset, fourcc, width, height, false,
121
        )
122
    }
123
124
    /// Binds memory, creates the view and wraps everything up. Takes
125
    /// ownership of `image` and `memory`, releasing both on failure.
126
    #[expect(clippy::too_many_arguments)]
127
    pub fn finish(
128
        shared: &Arc<Shared>,
129
        image: vk::Image,
130
        memory: Memory,
131
        mem: vk::DeviceMemory,
132
        offset: u64,
133
        fourcc: Fourcc,
134
        width: u32,
135
        height: u32,
136
        external: bool,
137
    ) -> Result<Arc<Self>, Error> {
138
        let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?;
139
        let d = &shared.device.device;
140
        let mut inner = Self {
141
            shared: shared.clone(),
142
            image,
143
            view: vk::ImageView::null(),
144
            memory: Mutex::new(Some(memory)),
145
            fourcc,
146
            format: fmt.format,
147
            width,
148
            height,
149
            layout: Mutex::new(if external {
150
                vk::ImageLayout::GENERAL
151
            } else {
152
                vk::ImageLayout::UNDEFINED
153
            }),
154
            external,
155
        };
156
        unsafe { d.bind_image_memory(image, mem, offset)? };
157
        let view_info = vk::ImageViewCreateInfo::default()
158
            .image(image)
159
            .view_type(vk::ImageViewType::TYPE_2D)
160
            .format(fmt.format)
161
            .components(components(fmt.opaque))
162
            .subresource_range(color_range());
163
        inner.view = unsafe { d.create_image_view(&view_info, None)? };
164
        Ok(Arc::new(inner))
165
    }
166
167
    pub fn layout(&self) -> vk::ImageLayout {
168
        *self.layout.lock().unwrap_or_else(|e| e.into_inner())
169
    }
170
171
    pub fn set_layout(&self, layout: vk::ImageLayout) {
172
        *self.layout.lock().unwrap_or_else(|e| e.into_inner()) = layout;
173
    }
174
}
175
176
pub(crate) fn color_range() -> vk::ImageSubresourceRange {
177
    vk::ImageSubresourceRange::default()
178
        .aspect_mask(vk::ImageAspectFlags::COLOR)
179
        .level_count(1)
180
        .layer_count(1)
181
}
182
183
/// A sampled texture.
184
#[derive(Clone, Debug)]
185
pub struct VulkanTexture(pub(crate) Arc<ImageInner>);
186
187
/// An image the renderer can draw into, from [`smithay::backend::renderer::Offscreen`].
188
#[derive(Debug)]
189
pub struct VulkanImage(pub(crate) Arc<ImageInner>);
190
191
impl VulkanImage {
192
    /// The image's contents as a texture, for drawing it elsewhere.
193
    pub fn texture(&self) -> VulkanTexture {
194
        VulkanTexture(self.0.clone())
195
    }
196
}
197
198
/// A bound render target, borrowing whatever it was bound from.
199
#[derive(Debug)]
200
pub struct VulkanTarget<'a>(
201
    pub(crate) Arc<ImageInner>,
202
    pub(crate) PhantomData<&'a mut ()>,
203
);
204
205
/// Pixels read back from the GPU.
206
#[derive(Debug)]
207
pub struct VulkanMapping {
208
    pub(crate) data: Vec<u8>,
209
    pub(crate) width: u32,
210
    pub(crate) height: u32,
211
    pub(crate) fourcc: Fourcc,
212
}
213
214
macro_rules! texture_impl {
215
    ($t:ty, |$s:ident| $inner:expr) => {
216
        impl Texture for $t {
217
            fn width(&self) -> u32 {
218
                let $s = self;
219
                $inner.width
220
            }
221
            fn height(&self) -> u32 {
222
                let $s = self;
223
                $inner.height
224
            }
225
            fn format(&self) -> Option<Fourcc> {
226
                let $s = self;
227
                Some($inner.fourcc)
228
            }
229
        }
230
    };
231
}
232
233
texture_impl!(VulkanTexture, |s| s.0);
234
texture_impl!(VulkanImage, |s| s.0);
235
texture_impl!(VulkanTarget<'_>, |s| s.0);
236
texture_impl!(VulkanMapping, |s| s);
237
238
impl TextureMapping for VulkanMapping {
239
    fn flipped(&self) -> bool {
240
        false
241
    }
242
}