ivy-vulkan 0.10.3

Low level vulkan abstractions for the Ivy game engine.
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use crate::context::SharedVulkanContext;
use crate::descriptors::DescriptorBindable;
use crate::traits::FromExtent;
use crate::{buffer, commands::*, Error, Result};
use crate::{Buffer, BufferAccess};
use ash::vk::{Extent3D, ImageAspectFlags, ImageView, SharingMode};
use gpu_allocator::vulkan::{Allocation, AllocationCreateDesc};
use gpu_allocator::MemoryLocation;
use ivy_base::Extent;
use ivy_resources::LoadResource;
use std::borrow::Cow;
use std::ops::Deref;
use std::path::Path;

use ash::vk;

pub use vk::Format;
pub use vk::ImageLayout;
pub use vk::ImageUsageFlags as ImageUsage;
pub use vk::SampleCountFlags;

/// Specifies texture creation info.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureInfo {
    pub extent: Extent,
    /// The maximum amount of mip levels to use.
    /// Actual value may be lower due to texture size.
    /// A value of zero uses the maximum mip levels.
    /// NOTE: Multisampled images cannot use more than one miplevel
    pub mip_levels: u32,
    /// The type/aspect of texture.
    pub usage: ImageUsage,
    /// The pixel format.
    pub format: Format,
    pub samples: SampleCountFlags,
}

impl TextureInfo {
    /// Returns a texture info most suitable for a sampled color texture with
    /// the supplied extent using mipmapping.
    pub fn color(extent: Extent) -> Self {
        TextureInfo {
            extent,
            usage: ImageUsage::TRANSFER_DST | ImageUsage::TRANSFER_SRC | ImageUsage::SAMPLED,
            mip_levels: calculate_mip_levels(extent),
            ..Default::default()
        }
    }

    /// Creates a texture suitable for depth attachment
    pub fn depth(extent: Extent) -> Self {
        TextureInfo {
            extent,
            mip_levels: 1,
            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
                | ImageUsage::SAMPLED
                | ImageUsage::INPUT_ATTACHMENT,
            format: Format::D32_SFLOAT,
            samples: SampleCountFlags::TYPE_1,
        }
    }
}

impl Default for TextureInfo {
    fn default() -> Self {
        Self {
            extent: (512, 512).into(),
            mip_levels: 1,
            usage: ImageUsage::SAMPLED,
            format: Format::R8G8B8A8_SRGB,
            samples: SampleCountFlags::TYPE_1,
        }
    }
}

// Represents a texture combining an image and image view. A texture also stores its own width,
// height, format, mipmapping levels and samples. Manages the deallocation of image memory unless
// created manually without provided allocation using `from_image`.
pub struct Texture {
    context: SharedVulkanContext,
    image: vk::Image,
    image_view: vk::ImageView,
    format: vk::Format,
    // May not necessarily own the allocation
    allocation: Option<Allocation>,
    extent: Extent,
    mip_levels: u32,
    samples: vk::SampleCountFlags,
    usage: ImageUsage,
}

impl Texture {
    /// Loads a color texture from an image in memory.
    /// Uses the width and height of the loaded image, no resizing.
    /// Uses mipmapping.
    pub fn from_memory(context: SharedVulkanContext, data: &[u8]) -> Result<Self> {
        let image = ivy_image::Image::load_from_memory(data, 4)?;

        let extent = (image.width(), image.height()).into();

        let texture = Self::new(context, &TextureInfo::color(extent))?;

        let size = image.width() as u64 * image.height() as u64 * 4;

        assert_eq!(size, image.pixels().len() as _);

        texture.write(image.pixels())?;
        Ok(texture)
    }
    /// Loads a color texture from an image file.
    /// Uses the width and height of the loaded image, no resizing.
    /// Uses mipmapping.
    pub fn load<P: AsRef<Path>>(context: SharedVulkanContext, path: P) -> Result<Self> {
        let image = ivy_image::Image::load(&path, 4)?;

        let extent = (image.width(), image.height()).into();

        let texture = Self::new(context, &TextureInfo::color(extent))?;

        let size = image.width() as u64 * image.height() as u64 * 4;

        assert_eq!(size, image.pixels().len() as _);

        texture.write(image.pixels())?;
        Ok(texture)
    }

    /// Creates a new unitialized texture
    /// Note, raw pixels must match format, width, and height
    pub fn new(context: SharedVulkanContext, info: &TextureInfo) -> Result<Self> {
        let mut mip_levels = calculate_mip_levels(info.extent);

        // Don't use more mip_levels than info
        if info.mip_levels != 0 {
            mip_levels = mip_levels.min(info.mip_levels)
        }

        let location = MemoryLocation::GpuOnly;

        let image_info = vk::ImageCreateInfo {
            image_type: vk::ImageType::TYPE_2D,
            format: info.format,
            extent: Extent3D::from_extent(info.extent),
            mip_levels,
            array_layers: 1,
            samples: info.samples,
            tiling: vk::ImageTiling::OPTIMAL,
            usage: info.usage,
            sharing_mode: SharingMode::EXCLUSIVE,
            initial_layout: vk::ImageLayout::UNDEFINED,
            ..Default::default()
        };

        let allocator = context.allocator();

        let device = context.device();
        let image = unsafe { device.create_image(&image_info, None)? };

        let requirements = unsafe { device.get_image_memory_requirements(image) };

        let allocation = allocator.write().allocate(&AllocationCreateDesc {
            name: "Image",
            requirements,
            location,
            linear: false,
        })?;

        unsafe { device.bind_image_memory(image, allocation.memory(), allocation.offset())? };

        Self::from_image(context, info, image, Some(allocation))
    }

    /// Creates a texture from an already existing VkImage
    /// If allocation is provided, the image will be destroyed along with self
    pub fn from_image(
        context: SharedVulkanContext,
        info: &TextureInfo,
        image: vk::Image,
        allocation: Option<Allocation>,
    ) -> Result<Self> {
        let aspect_mask = if info.usage.contains(ImageUsage::DEPTH_STENCIL_ATTACHMENT) {
            ImageAspectFlags::DEPTH
        } else {
            vk::ImageAspectFlags::COLOR
        };

        let create_info = vk::ImageViewCreateInfo::builder()
            .image(image)
            .view_type(vk::ImageViewType::TYPE_2D)
            .format(info.format)
            .subresource_range(vk::ImageSubresourceRange {
                aspect_mask,
                base_mip_level: 0,
                level_count: info.mip_levels,
                base_array_layer: 0,
                layer_count: 1,
            });

        let image_view = unsafe { context.device().create_image_view(&create_info, None) }?;

        Ok(Self {
            context,
            image,
            image_view,
            extent: info.extent,
            mip_levels: info.mip_levels,
            format: info.format,
            samples: info.samples,
            usage: info.usage,
            allocation,
        })
    }

    pub fn write(&self, pixels: &[u8]) -> Result<()> {
        // Create a new or reuse staging buffer
        let staging = Buffer::new(
            self.context.clone(),
            vk::BufferUsageFlags::TRANSFER_SRC,
            BufferAccess::Mapped,
            pixels,
        )?;

        let transfer_pool = self.context.transfer_pool();
        let graphics_queue = self.context.graphics_queue();

        // Prepare the image layout
        transition_layout(
            transfer_pool,
            graphics_queue,
            self.image,
            self.mip_levels,
            vk::ImageLayout::UNDEFINED,
            vk::ImageLayout::TRANSFER_DST_OPTIMAL,
        )?;

        buffer::copy_to_image(
            transfer_pool,
            graphics_queue,
            staging.buffer(),
            self.image,
            vk::ImageLayout::TRANSFER_DST_OPTIMAL,
            self.extent,
        )?;

        // Generate Mipmaps
        generate_mipmaps(
            transfer_pool,
            graphics_queue,
            self.image,
            self.extent,
            self.mip_levels,
        )?;

        Ok(())
    }

    pub fn format(&self) -> vk::Format {
        self.format
    }

    pub fn image(&self) -> vk::Image {
        self.image
    }

    pub fn image_view(&self) -> vk::ImageView {
        self.image_view
    }

    pub fn mip_levels(&self) -> u32 {
        self.mip_levels
    }

    /// Return a reference to the texture's samples.
    pub fn samples(&self) -> vk::SampleCountFlags {
        self.samples
    }

    /// Return a reference to the texture's type
    pub fn usage(&self) -> ImageUsage {
        self.usage
    }

    // Returns the textures width and height
    pub fn extent(&self) -> Extent {
        self.extent
    }
}

impl AsRef<vk::ImageView> for Texture {
    fn as_ref(&self) -> &vk::ImageView {
        &self.image_view
    }
}

impl AsRef<vk::Image> for Texture {
    fn as_ref(&self) -> &vk::Image {
        &self.image
    }
}

impl From<&Texture> for vk::ImageView {
    fn from(val: &Texture) -> Self {
        val.image_view
    }
}

impl From<&Texture> for vk::Image {
    fn from(val: &Texture) -> Self {
        val.image
    }
}

impl Drop for Texture {
    fn drop(&mut self) {
        let allocator = self.context.allocator();

        let device = self.context.device();

        // Destroy allocation if texture owns image
        if let Some(allocation) = self.allocation.take() {
            allocator.write().free(allocation).unwrap();
            unsafe { device.destroy_image(self.image(), None) };
        }

        // Destroy image view
        unsafe {
            device.destroy_image_view(self.image_view, None);
        }
    }
}

fn calculate_mip_levels(extent: Extent) -> u32 {
    (extent.width.max(extent.height) as f32).log2().floor() as u32 + 1
}

fn generate_mipmaps(
    commandpool: &CommandPool,
    queue: vk::Queue,
    image: vk::Image,
    extent: Extent,
    mip_levels: u32,
) -> Result<()> {
    let mut barrier = vk::ImageMemoryBarrier {
        s_type: vk::StructureType::IMAGE_MEMORY_BARRIER,
        p_next: std::ptr::null(),
        src_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
        dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
        image,
        subresource_range: vk::ImageSubresourceRange {
            aspect_mask: vk::ImageAspectFlags::COLOR,
            base_mip_level: 0,
            level_count: 1,
            base_array_layer: 0,
            layer_count: 1,
        },
        ..Default::default()
    };

    let mut mip_width = extent.width;
    let mut mip_height = extent.height;

    commandpool.single_time_command(queue, |commandbuffer| {
        for i in 1..mip_levels {
            barrier.subresource_range.base_mip_level = i - 1;
            barrier.old_layout = vk::ImageLayout::TRANSFER_DST_OPTIMAL;
            barrier.new_layout = vk::ImageLayout::TRANSFER_SRC_OPTIMAL;

            barrier.src_access_mask = vk::AccessFlags::TRANSFER_WRITE;
            barrier.dst_access_mask = vk::AccessFlags::TRANSFER_READ;

            commandbuffer.pipeline_barrier(
                vk::PipelineStageFlags::TRANSFER,
                vk::PipelineStageFlags::TRANSFER,
                &[],
                &[barrier],
            );

            let offset = vk::Offset3D {
                x: if mip_width > 1 {
                    (mip_width / 2) as _
                } else {
                    1
                },
                y: if mip_height > 1 {
                    (mip_height / 2) as _
                } else {
                    1
                },
                z: 1,
            };

            let blit = vk::ImageBlit {
                src_offsets: [
                    vk::Offset3D { x: 0, y: 0, z: 0 },
                    vk::Offset3D {
                        x: mip_width as i32,
                        y: mip_height as i32,
                        z: 1,
                    },
                ],
                dst_offsets: [vk::Offset3D { x: 0, y: 0, z: 0 }, offset],
                src_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: vk::ImageAspectFlags::COLOR,
                    mip_level: i - 1,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                dst_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: vk::ImageAspectFlags::COLOR,
                    mip_level: i,
                    base_array_layer: 0,
                    layer_count: 1,
                },
            };

            commandbuffer.blit_image(
                image,
                vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
                image,
                vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                &[blit],
                vk::Filter::LINEAR,
            );

            // Transition new mip level to SHADER_READ_ONLY_OPTIMAL
            barrier.old_layout = vk::ImageLayout::TRANSFER_SRC_OPTIMAL;
            barrier.new_layout = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL;
            barrier.src_access_mask = vk::AccessFlags::TRANSFER_READ;
            barrier.dst_access_mask = vk::AccessFlags::SHADER_READ;

            commandbuffer.pipeline_barrier(
                vk::PipelineStageFlags::TRANSFER,
                vk::PipelineStageFlags::FRAGMENT_SHADER,
                &[],
                &[barrier],
            );

            if mip_width > 1 {
                mip_width /= 2;
            }

            if mip_height > 1 {
                mip_height /= 2;
            }
        }

        // Transition the last mip level to SHADER_READ_ONLY_OPTIMAL
        barrier.subresource_range.base_mip_level = mip_levels - 1;
        barrier.old_layout = vk::ImageLayout::TRANSFER_DST_OPTIMAL;
        barrier.new_layout = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL;
        barrier.src_access_mask = vk::AccessFlags::TRANSFER_WRITE;
        barrier.dst_access_mask = vk::AccessFlags::SHADER_READ;

        commandbuffer.pipeline_barrier(
            vk::PipelineStageFlags::TRANSFER,
            vk::PipelineStageFlags::FRAGMENT_SHADER,
            &[],
            &[barrier],
        );
    })
}

// Transitions image layout from one layout to another using a pipeline barrier
fn transition_layout(
    commandpool: &CommandPool,
    queue: vk::Queue,
    image: vk::Image,
    mip_levels: u32,
    old_layout: vk::ImageLayout,
    new_layout: vk::ImageLayout,
) -> Result<()> {
    let (src_access_mask, dst_access_mask, src_stage_mask, dst_stage_mask) =
        match (old_layout, new_layout) {
            (vk::ImageLayout::UNDEFINED, vk::ImageLayout::TRANSFER_DST_OPTIMAL) => (
                vk::AccessFlags::default(),
                vk::AccessFlags::TRANSFER_WRITE,
                vk::PipelineStageFlags::TOP_OF_PIPE,
                vk::PipelineStageFlags::TRANSFER,
            ),

            (vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL) => (
                vk::AccessFlags::TRANSFER_WRITE,
                vk::AccessFlags::SHADER_READ,
                vk::PipelineStageFlags::TRANSFER,
                vk::PipelineStageFlags::FRAGMENT_SHADER,
            ),
            _ => return Err(Error::UnsupportedLayoutTransition(old_layout, new_layout)),
        };

    let barrier = vk::ImageMemoryBarrier {
        s_type: vk::StructureType::IMAGE_MEMORY_BARRIER,
        p_next: std::ptr::null(),
        src_access_mask,
        dst_access_mask,
        old_layout,
        new_layout,
        src_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
        dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
        image,
        subresource_range: vk::ImageSubresourceRange {
            aspect_mask: vk::ImageAspectFlags::COLOR,
            base_mip_level: 0,
            level_count: mip_levels,
            base_array_layer: 0,
            layer_count: 1,
        },
    };

    commandpool.single_time_command(queue, |commandbuffer| {
        commandbuffer.pipeline_barrier(src_stage_mask, dst_stage_mask, &[], &[barrier])
    })
}

impl DescriptorBindable for Texture {
    fn bind_resource<'a>(
        &self,
        binding: u32,
        stage: vk::ShaderStageFlags,
        builder: &'a mut crate::descriptors::DescriptorBuilder,
    ) -> Result<&'a mut crate::descriptors::DescriptorBuilder> {
        Ok(builder.bind_image(binding, stage, self))
    }
}

pub struct InputAttachment {
    pub image: ImageView,
}

impl InputAttachment {
    pub fn new<T: AsRef<ImageView>>(texture: T) -> Self {
        Self {
            image: *texture.as_ref(),
        }
    }
}

impl From<InputAttachment> for ImageView {
    fn from(val: InputAttachment) -> Self {
        val.image
    }
}

impl AsRef<ImageView> for InputAttachment {
    fn as_ref(&self) -> &ImageView {
        &self.image
    }
}

impl DescriptorBindable for InputAttachment {
    fn bind_resource<'a>(
        &self,
        binding: u32,
        stage: vk::ShaderStageFlags,
        builder: &'a mut crate::descriptors::DescriptorBuilder,
    ) -> Result<&'a mut crate::descriptors::DescriptorBuilder> {
        Ok(builder.bind_input_attachment(binding, stage, self.image))
    }
}

impl Deref for InputAttachment {
    type Target = ImageView;

    fn deref(&self) -> &ImageView {
        &self.image
    }
}

pub struct CombinedImageSampler {
    pub image: ImageView,
    pub sampler: vk::Sampler,
}

impl CombinedImageSampler {
    pub fn new<T: AsRef<ImageView>, S: AsRef<vk::Sampler>>(texture: T, sampler: S) -> Self {
        Self {
            image: *texture.as_ref(),
            sampler: *sampler.as_ref(),
        }
    }

    /// Get the combined image sampler's image.
    pub fn image(&self) -> ImageView {
        self.image
    }

    /// Get the combined image sampler's sampler.
    pub fn sampler(&self) -> vk::Sampler {
        self.sampler
    }
}
impl DescriptorBindable for CombinedImageSampler {
    fn bind_resource<'a>(
        &self,
        binding: u32,
        stage: vk::ShaderStageFlags,
        builder: &'a mut crate::descriptors::DescriptorBuilder,
    ) -> Result<&'a mut crate::descriptors::DescriptorBuilder> {
        Ok(builder.bind_combined_image_sampler(binding, stage, self.image, self.sampler))
    }
}

impl LoadResource for Texture {
    type Info = Cow<'static, str>;

    type Error = Error;

    fn load(resources: &ivy_resources::Resources, path: &Self::Info) -> Result<Self> {
        let context = resources.get_default::<SharedVulkanContext>()?;
        Self::load(context.clone(), path.as_ref())
    }
}