mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
39 changed files with 768360 additions and 0 deletions
|
|
@ -0,0 +1,46 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Struct containing information about a memory allocation. Intentionally made similar to VMA's AllocationInfo
|
||||
/// </summary>
|
||||
/// <param name="Allocator">Allocator that sourced this allocation</param>
|
||||
/// <param name="Memory">Device memory handle</param>
|
||||
/// <param name="AllocSize">Size available in the memory allocation (might be more than requested)</param>
|
||||
/// <param name="AllocOffset">Offset into the memory allocation</param>
|
||||
/// <param name="MemoryTypeIndex">Memory type this allocation was made from</param>
|
||||
/// <param name="AllocHandle">Custom handle, optionally used by allocator</param>
|
||||
public readonly record struct AllocationInfo(
|
||||
IAllocator Allocator,
|
||||
VkDeviceMemory Memory,
|
||||
ByteSize AllocSize,
|
||||
ByteSize AllocOffset,
|
||||
int MemoryTypeIndex,
|
||||
nint AllocHandle
|
||||
)
|
||||
{
|
||||
/// <summary>
|
||||
/// Struct containing information about a memory allocation. Intentionally made similar to VMA's AllocationCreateInfo
|
||||
/// </summary>
|
||||
/// <param name="Preference">Memory location preference can just leave as 'None'</param>
|
||||
/// <param name="RequiredProperties">Flags that must be set in a Memory Type chosen for an allocation</param>
|
||||
/// <param name="PreferredProperties">Flags that preferably should be set in a memory type chosen for an allocation</param>
|
||||
/// <param name="Priority">A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations</param>
|
||||
/// <param name="Next">For advanced use only. A pointer to an application-defined structure that can be used to pass custom data to the allocator</param>
|
||||
public record struct CreateInfo(
|
||||
MemoryPreference Preference,
|
||||
VkMemoryPropertyFlags RequiredProperties,
|
||||
VkMemoryPropertyFlags PreferredProperties,
|
||||
float Priority,
|
||||
Ptr Next
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum listing memory allocation preferences: whether to prefer GPU or CPU memory
|
||||
/// </summary>
|
||||
public enum MemoryPreference : byte
|
||||
{
|
||||
None,
|
||||
PreferGpu,
|
||||
PreferCpu,
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Base interface for a Vulkan allocator
|
||||
/// </summary>
|
||||
public interface IAllocator
|
||||
{
|
||||
/// <summary>
|
||||
/// Get the Vulkan device this allocator is associated with
|
||||
/// </summary>
|
||||
/// <returns>Vulkan device handle</returns>
|
||||
Device GetDevice();
|
||||
|
||||
VkAllocator? VkAllocator { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Safely maps memory (allocated by this allocator) to a pointer.
|
||||
/// </summary>
|
||||
/// <param name="allocationMapInfo">Allocation info for memory</param>
|
||||
/// <returns>Pointer to mapped memory</returns>
|
||||
Ptr MapMemory(in AllocationMapInfo allocationMapInfo);
|
||||
|
||||
/// <summary>
|
||||
/// Safely unmaps memory (allocated by this allocator) from a pointer
|
||||
/// </summary>
|
||||
/// <param name="allocationMapInfo">Allocation info for memory</param>
|
||||
void UnmapMemory(in AllocationMapInfo allocationMapInfo);
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Struct containing information about a buffer allocation
|
||||
/// </summary>
|
||||
/// <param name="VkBuffer">Handle to the Vulkan buffer</param>
|
||||
/// <param name="BufferOffset">Offset within the buffer where this allocation starts</param>
|
||||
/// <param name="BufferSize">Size of the allocation within the buffer</param>
|
||||
/// <param name="Usage">Usage flags this buffer supports, for reference</param>
|
||||
/// <param name="AllocationInfo">The internal memory allocation</param>
|
||||
public readonly record struct BufferAllocationInfo(
|
||||
VkBuffer VkBuffer,
|
||||
ByteSize BufferOffset,
|
||||
ByteSize BufferSize,
|
||||
VkBufferUsageFlags Usage,
|
||||
AllocationInfo AllocationInfo
|
||||
) : IMappable
|
||||
{
|
||||
ByteSize IMappable.MapSize => BufferSize;
|
||||
ByteSize IMappable.MapOffset => BufferOffset;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface for a buffer allocator object capable of allocating and freeing buffers
|
||||
/// </summary>
|
||||
public interface IBufferAllocator : IAllocator
|
||||
{
|
||||
/// <summary>
|
||||
/// Allocate a buffer with the given creation and allocation info
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="bufferCreateInfo">Vulkan buffer creation info</param>
|
||||
/// <param name="allocateCreateInfo">Memory allocation info</param>
|
||||
/// <returns>Struct containing all relevant information about allocation</returns>
|
||||
public BufferAllocationInfo AllocateBuffer(
|
||||
in string name,
|
||||
in VkBufferCreateInfo bufferCreateInfo,
|
||||
in AllocationInfo.CreateInfo allocateCreateInfo
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Free buffer allocation
|
||||
/// </summary>
|
||||
/// <param name="inAllocation">Allocation info for the buffer previously sourced from this allocator</param>
|
||||
public void FreeAllocation(in BufferAllocationInfo inAllocation);
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Struct containing information about an image allocation
|
||||
/// </summary>
|
||||
public struct ImageAllocationInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Image handle
|
||||
/// </summary>
|
||||
public VkImage Image;
|
||||
|
||||
/// <summary>
|
||||
/// Size of image
|
||||
/// </summary>
|
||||
public VkExtent3D Extent;
|
||||
|
||||
/// <summary>
|
||||
/// Format of image, for reference
|
||||
/// </summary>
|
||||
public VkFormat Format;
|
||||
|
||||
/// <summary>
|
||||
/// Number of mip levels
|
||||
/// </summary>
|
||||
public int MipLevels;
|
||||
|
||||
/// <summary>
|
||||
/// Number of array layers allocated
|
||||
/// </summary>
|
||||
public int ArrayLayers;
|
||||
|
||||
/// <summary>
|
||||
/// Memory allocation info
|
||||
/// </summary>
|
||||
public AllocationInfo MemAllocationInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Allocator-specific handle
|
||||
/// </summary>
|
||||
public nint AllocHandle => MemAllocationInfo.AllocHandle;
|
||||
|
||||
/// <summary>
|
||||
/// Allocator that sourced this image
|
||||
/// </summary>
|
||||
public IImageAllocator Allocator => (IImageAllocator)MemAllocationInfo.Allocator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface for an image allocator object capable of allocating and freeing images
|
||||
/// </summary>
|
||||
public interface IImageAllocator : IAllocator
|
||||
{
|
||||
/// <summary>
|
||||
/// Allocate an image with the given creation and allocation info.
|
||||
/// </summary>
|
||||
/// <param name="name">Debug name of allocation</param>
|
||||
/// <param name="imageCreateInfo">Vulkan image creation info</param>
|
||||
/// <param name="allocateCreateInfo">Memory allocation info</param>
|
||||
/// <returns>Struct containing all relevant information about the allocation</returns>
|
||||
public ImageAllocationInfo AllocateImage(
|
||||
in string name,
|
||||
in VkImageCreateInfo imageCreateInfo,
|
||||
in AllocationInfo.CreateInfo allocateCreateInfo
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Free an image allocation
|
||||
/// </summary>
|
||||
/// <param name="inAllocation">Struct containing all relevant information about the allocation</param>
|
||||
public void FreeAllocation(in ImageAllocationInfo inAllocation);
|
||||
}
|
||||
190
brutal.vulkan/Brutal.Vulkan.Abstractions/BufferEx.cs
Normal file
190
brutal.vulkan/Brutal.Vulkan.Abstractions/BufferEx.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Extends the <see cref="VkBuffer"/> type to provide additional functionality.
|
||||
/// </summary>
|
||||
public readonly struct BufferEx : IDisposable, INullable, IMappable, IBindBuffer
|
||||
{
|
||||
public ref struct CreateInfo
|
||||
{
|
||||
/// <summary>The name to apply to the buffer and allocation</summary>
|
||||
public required string Name;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.Flags"/>
|
||||
public VkBufferCreateFlags BufferFlags;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.Size"/>
|
||||
public ByteSize BufferSize;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.Usage"/>
|
||||
public VkBufferUsageFlags BufferUsage;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.SharingMode"/>
|
||||
public VkSharingMode BufferSharingMode;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.QueueFamilyIndexCount"/>
|
||||
public int BufferQueueFamilyIndexCount;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.QueueFamilyIndices"/>
|
||||
public unsafe int* BufferQueueFamilyIndices;
|
||||
|
||||
/// <inheritdoc cref="VkBufferCreateInfo.Next"/>
|
||||
public Ptr BufferNext { get; set; }
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.Preference"/>
|
||||
public MemoryPreference AllocPreference;
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.RequiredProperties"/>
|
||||
public VkMemoryPropertyFlags AllocRequiredProperties;
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.PreferredProperties"/>
|
||||
public VkMemoryPropertyFlags AllocPreferredProperties;
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.Priority"/>
|
||||
public float AllocPriority;
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.Next"/>
|
||||
public Ptr AllocNext { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Extract or populate this struct with a VkBufferCreateInfo
|
||||
/// </summary>
|
||||
public unsafe VkBufferCreateInfo BufferCreateInfo
|
||||
{
|
||||
get =>
|
||||
new()
|
||||
{
|
||||
Flags = BufferFlags,
|
||||
Size = BufferSize,
|
||||
Usage = BufferUsage,
|
||||
SharingMode = BufferSharingMode,
|
||||
QueueFamilyIndexCount = BufferQueueFamilyIndexCount,
|
||||
QueueFamilyIndices = BufferQueueFamilyIndices,
|
||||
Next = BufferNext,
|
||||
};
|
||||
set
|
||||
{
|
||||
BufferFlags = value.Flags;
|
||||
BufferSize = value.Size;
|
||||
BufferUsage = value.Usage;
|
||||
BufferSharingMode = value.SharingMode;
|
||||
BufferQueueFamilyIndexCount = value.QueueFamilyIndexCount;
|
||||
BufferQueueFamilyIndices = value.QueueFamilyIndices;
|
||||
BufferNext = value.Next;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract or populate this struct with an AllocationInfo.CreateInfo
|
||||
/// </summary>
|
||||
public AllocationInfo.CreateInfo AllocationInfo
|
||||
{
|
||||
get =>
|
||||
new()
|
||||
{
|
||||
Preference = AllocPreference,
|
||||
RequiredProperties = AllocRequiredProperties,
|
||||
PreferredProperties = AllocPreferredProperties,
|
||||
Priority = AllocPriority,
|
||||
Next = AllocNext,
|
||||
};
|
||||
set
|
||||
{
|
||||
AllocPreference = value.Preference;
|
||||
AllocRequiredProperties = value.RequiredProperties;
|
||||
AllocPreferredProperties = value.PreferredProperties;
|
||||
AllocPriority = value.Priority;
|
||||
AllocNext = value.Next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Source of the buffer allocation
|
||||
/// </summary>
|
||||
public readonly IBufferAllocator Allocator;
|
||||
|
||||
/// <summary>
|
||||
/// Allocation info for the buffer
|
||||
/// </summary>
|
||||
public readonly BufferAllocationInfo BufferAllocationInfo;
|
||||
|
||||
/// <summary>
|
||||
/// The size of the buffer allocation
|
||||
/// </summary>
|
||||
public ByteSize BufferSize => BufferAllocationInfo.BufferSize;
|
||||
|
||||
/// <summary>
|
||||
/// Offset within the owning buffer where this buffer starts
|
||||
/// </summary>
|
||||
public ByteSize BindOffset => BufferAllocationInfo.BufferOffset;
|
||||
|
||||
/// <summary>
|
||||
/// Usage flags this buffer supports
|
||||
/// </summary>
|
||||
public VkBufferUsageFlags Usage => BufferAllocationInfo.Usage;
|
||||
|
||||
internal BufferEx(IBufferAllocator allocator, CreateInfo createInfo)
|
||||
{
|
||||
Allocator = allocator;
|
||||
|
||||
BufferAllocationInfo = allocator.AllocateBuffer(
|
||||
createInfo.Name,
|
||||
createInfo.BufferCreateInfo,
|
||||
createInfo.AllocationInfo
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a BufferEx from an existing buffer allocation
|
||||
/// </summary>
|
||||
/// <param name="allocationInfo">Pre-allocated buffer sourced from an IBufferAllocator</param>
|
||||
public BufferEx(BufferAllocationInfo allocationInfo)
|
||||
{
|
||||
BufferAllocationInfo = allocationInfo;
|
||||
Allocator = (IBufferAllocator)allocationInfo.AllocationInfo.Allocator;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Allocator.FreeAllocation(BufferAllocationInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vulkan buffer handle
|
||||
/// </summary>
|
||||
public VkBuffer VkBuffer => BufferAllocationInfo.VkBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// Vulkan device memory handle
|
||||
/// </summary>
|
||||
public VkDeviceMemory VkDeviceMemory => BufferAllocationInfo.AllocationInfo.Memory;
|
||||
|
||||
public BufferPartitionInfo AsPartition()
|
||||
{
|
||||
if (IsNull())
|
||||
throw new NullReferenceException(nameof(VkBuffer));
|
||||
|
||||
return BufferPartitionInfo.FullPartition(BufferAllocationInfo);
|
||||
}
|
||||
|
||||
public static implicit operator BufferPartitionInfo(BufferEx buffer) => buffer.AsPartition();
|
||||
|
||||
public bool IsNull()
|
||||
{
|
||||
return VkBuffer.IsNull();
|
||||
}
|
||||
|
||||
AllocationInfo IMappable.AllocationInfo => BufferAllocationInfo.AllocationInfo;
|
||||
ByteSize IMappable.MapSize => BufferSize;
|
||||
ByteSize IMappable.MapOffset => ByteSize.Zero; // BufferOffset should not be used here
|
||||
}
|
||||
|
||||
public static class BufferExExtensions
|
||||
{
|
||||
public static BufferEx CreateBuffer(this IBufferAllocator allocator, BufferEx.CreateInfo createInfo)
|
||||
{
|
||||
return new BufferEx(allocator, createInfo);
|
||||
}
|
||||
}
|
||||
224
brutal.vulkan/Brutal.Vulkan.Abstractions/Classes/DeviceEx.cs
Normal file
224
brutal.vulkan/Brutal.Vulkan.Abstractions/Classes/DeviceEx.cs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An allocator that allocates images and buffers directly from a Vulkan device.
|
||||
/// </summary>
|
||||
public class DeviceEx : Device, IImageAllocator, IBufferAllocator
|
||||
{
|
||||
public new ref struct CreateInfo()
|
||||
{
|
||||
public HashSet<string> Extensions = [];
|
||||
public Ptr<VkPhysicalDeviceFeatures> Features = null;
|
||||
public ReadOnlySpan<VkDeviceQueueCreateInfo> QueueCreateInfos = [];
|
||||
public Ptr Next = null;
|
||||
public VkAllocator? Allocator = null;
|
||||
}
|
||||
|
||||
internal DeviceEx(PhysicalDevice physicalDevice, CreateInfo createInfo)
|
||||
: base(
|
||||
physicalDevice,
|
||||
new Device.CreateInfo
|
||||
{
|
||||
Extensions = createInfo.Extensions,
|
||||
Features = createInfo.Features,
|
||||
QueueCreateInfos = createInfo.QueueCreateInfos,
|
||||
Next = createInfo.Next,
|
||||
Allocator = createInfo.Allocator,
|
||||
}
|
||||
) { }
|
||||
|
||||
// No finalizer: the base Device owns the only native handle and frees it in Dispose().
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ImageAllocationInfo AllocateImage(
|
||||
in string name,
|
||||
in VkImageCreateInfo imageCreateInfo,
|
||||
in AllocationInfo.CreateInfo allocateCreateInfo
|
||||
)
|
||||
{
|
||||
var image = this.CreateImage(imageCreateInfo, VkAllocator);
|
||||
// Check the memory requirements for the vertex buffer
|
||||
var memoryRequirements = this.GetImageMemoryRequirements(image);
|
||||
|
||||
// Pick the first memory type that fits the requirements
|
||||
var selectedMemoryTypeIndex = PhysicalDevice.FindMemoryType(
|
||||
memoryRequirements.MemoryTypeBits,
|
||||
allocateCreateInfo.RequiredProperties,
|
||||
allocateCreateInfo.PreferredProperties
|
||||
);
|
||||
|
||||
// TODO: preferred properties?
|
||||
var memory = this.AllocateMemory(PhysicalDevice, image, allocateCreateInfo.RequiredProperties, VkAllocator);
|
||||
|
||||
this.BindImageMemory(image, memory, ByteSize.Zero);
|
||||
|
||||
if (name.Length > 0)
|
||||
{
|
||||
this.SetDebugName(image, name);
|
||||
this.SetDebugName(memory, name);
|
||||
}
|
||||
|
||||
return new ImageAllocationInfo
|
||||
{
|
||||
Image = image,
|
||||
Extent = imageCreateInfo.Extent,
|
||||
Format = imageCreateInfo.Format,
|
||||
MipLevels = imageCreateInfo.MipLevels,
|
||||
ArrayLayers = imageCreateInfo.ArrayLayers,
|
||||
MemAllocationInfo = new AllocationInfo
|
||||
{
|
||||
Allocator = this,
|
||||
Memory = memory,
|
||||
AllocOffset = ByteSize.Zero,
|
||||
AllocSize = memoryRequirements.Size,
|
||||
MemoryTypeIndex = selectedMemoryTypeIndex,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public void FreeAllocation(in ImageAllocationInfo inAllocation)
|
||||
{
|
||||
if (inAllocation.MemAllocationInfo.Memory.IsNull())
|
||||
return; // No allocation to free
|
||||
if (inAllocation.MemAllocationInfo.Allocator == null)
|
||||
throw new InvalidOperationException("Tried to free memory but allocator was null. Who allocated this?");
|
||||
if (inAllocation.MemAllocationInfo.Allocator != this)
|
||||
throw new InvalidOperationException("Allocation was not made from this allocator.");
|
||||
this.DestroyImage(inAllocation.Image, VkAllocator);
|
||||
this.FreeMemory(inAllocation.MemAllocationInfo.Memory, VkAllocator);
|
||||
}
|
||||
|
||||
public unsafe void FreeAllocation(in BufferAllocationInfo inAllocation)
|
||||
{
|
||||
if (inAllocation.AllocationInfo.Memory.IsNull())
|
||||
return; // No allocation to free
|
||||
if (inAllocation.AllocationInfo.Allocator == null)
|
||||
throw new InvalidOperationException("Tried to free memory but allocator was null. Who allocated this?");
|
||||
if (inAllocation.AllocationInfo.Allocator != this)
|
||||
throw new InvalidOperationException("Allocation was not made from this allocator.");
|
||||
var handle = (BufferAllocationHandle*)inAllocation.AllocationInfo.AllocHandle;
|
||||
if (handle == null)
|
||||
throw new InvalidOperationException("Allocation handle is null.");
|
||||
if (handle->RefCount != 0)
|
||||
throw new InvalidOperationException("Memory is still mapped. Unmap the memory before freeing it.");
|
||||
|
||||
this.DestroyBuffer(inAllocation.VkBuffer, VkAllocator);
|
||||
this.FreeMemory(inAllocation.AllocationInfo.Memory, VkAllocator);
|
||||
|
||||
Mem.Free(handle);
|
||||
}
|
||||
|
||||
private struct BufferAllocationHandle
|
||||
{
|
||||
public int RefCount;
|
||||
public AllocationMapInfo.MapKey Key;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public unsafe BufferAllocationInfo AllocateBuffer(
|
||||
in string name,
|
||||
in VkBufferCreateInfo bufferCreateInfo,
|
||||
in AllocationInfo.CreateInfo allocateCreateInfo
|
||||
)
|
||||
{
|
||||
var buffer = this.CreateBuffer(bufferCreateInfo, VkAllocator);
|
||||
|
||||
// Check the memory requirements for the vertex buffer
|
||||
var bufferMemoryRequirements = this.GetBufferMemoryRequirements(buffer);
|
||||
|
||||
// Pick the first memory type that fits the requirements
|
||||
var selectedMemoryTypeIndex = PhysicalDevice.FindMemoryType(
|
||||
bufferMemoryRequirements.MemoryTypeBits,
|
||||
allocateCreateInfo.RequiredProperties,
|
||||
allocateCreateInfo.PreferredProperties
|
||||
);
|
||||
|
||||
var memory = this.AllocateMemory(
|
||||
new VkMemoryAllocateInfo
|
||||
{
|
||||
AllocationSize = bufferMemoryRequirements.Size,
|
||||
MemoryTypeIndex = selectedMemoryTypeIndex,
|
||||
Next = allocateCreateInfo.Next,
|
||||
},
|
||||
VkAllocator
|
||||
);
|
||||
this.BindBufferMemory(buffer, memory, ByteSize.Zero);
|
||||
if (name.Length > 0)
|
||||
{
|
||||
this.SetDebugName(buffer, name);
|
||||
this.SetDebugName(memory, name);
|
||||
}
|
||||
|
||||
var handle = Mem.AllocZeroed<BufferAllocationHandle>();
|
||||
|
||||
return new BufferAllocationInfo(
|
||||
buffer,
|
||||
ByteSize.Zero,
|
||||
bufferCreateInfo.Size,
|
||||
bufferCreateInfo.Usage,
|
||||
new AllocationInfo
|
||||
{
|
||||
Allocator = this,
|
||||
Memory = memory,
|
||||
AllocOffset = ByteSize.Zero,
|
||||
AllocSize = bufferMemoryRequirements.Size,
|
||||
MemoryTypeIndex = selectedMemoryTypeIndex,
|
||||
AllocHandle = (nint)handle,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
unsafe Ptr IAllocator.MapMemory(in AllocationMapInfo allocationMapInfo)
|
||||
{
|
||||
var allocationInfo = allocationMapInfo.AllocationInfo;
|
||||
|
||||
var handle = (BufferAllocationHandle*)allocationMapInfo.AllocationInfo.AllocHandle;
|
||||
|
||||
if (handle->RefCount != 0)
|
||||
{
|
||||
if (!allocationMapInfo.IsSubsetOf(handle->Key))
|
||||
throw new InvalidOperationException(
|
||||
"Memory is already mapped to a different region. Unmap the memory before mapping again."
|
||||
);
|
||||
|
||||
handle->RefCount++;
|
||||
return handle->Key.MapPtr.Offset(allocationMapInfo.Region.Offset - handle->Key.MapOffset);
|
||||
}
|
||||
|
||||
var ptr = this.MapMemory(
|
||||
allocationInfo.Memory,
|
||||
allocationMapInfo.Region.Offset,
|
||||
allocationMapInfo.Region.Size,
|
||||
VkMemoryMapFlags.None
|
||||
);
|
||||
if (ptr == null)
|
||||
throw new InvalidOperationException("Failed to map memory.");
|
||||
|
||||
handle->RefCount = 1;
|
||||
handle->Key = new AllocationMapInfo.MapKey(ptr, allocationMapInfo.Region.Size, allocationMapInfo.Region.Offset);
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
unsafe void IAllocator.UnmapMemory(in AllocationMapInfo allocationMapInfo)
|
||||
{
|
||||
var allocationInfo = allocationMapInfo.AllocationInfo;
|
||||
|
||||
var handle = (BufferAllocationHandle*)allocationInfo.AllocHandle;
|
||||
|
||||
if (handle->RefCount == 0)
|
||||
throw new InvalidOperationException("Memory is not mapped.");
|
||||
if (--handle->RefCount > 0)
|
||||
return;
|
||||
|
||||
this.UnmapMemory(allocationInfo.Memory);
|
||||
handle->Key = new AllocationMapInfo.MapKey(null, ByteSize.Zero, ByteSize.Zero);
|
||||
}
|
||||
|
||||
Device IAllocator.GetDevice() => this;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public VkAllocator? VkAllocator => _vkAllocator;
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public static class DebugNameExtensions
|
||||
{
|
||||
private const int MAX_DEBUG_NAME_LENGTH = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Set a debug name for the handle.
|
||||
/// </summary>
|
||||
/// <param name="device">Handle to the device that will assign the name</param>
|
||||
/// <param name="handle">The Vulkan handle we want to assign a name to</param>
|
||||
/// <param name="name">The name to assign to the handle</param>
|
||||
[Conditional("DEBUG")]
|
||||
public static void SetDebugName<T>(this Device device, T handle, string name)
|
||||
where T : IVulkanHandle
|
||||
{
|
||||
if (!device.PhysicalDevice.Instance.IsExtensionEnabled(VK.EXT_DEBUG_UTILS_EXTENSION_NAME))
|
||||
return;
|
||||
|
||||
var bytes = SpanOwner<byte>.Allocate(MAX_DEBUG_NAME_LENGTH);
|
||||
var written = Utf8.GetBytes(name, bytes.Span);
|
||||
bytes.Span[written] = 0;
|
||||
|
||||
device.SetDebugName(handle.VkObjectType, handle.VkHandle, bytes.Span[..written]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set a debug name for the handle.
|
||||
/// </summary>
|
||||
/// <param name="device">Handle to the device that will assign the name</param>
|
||||
/// <param name="handle">The Vulkan handle we want to assign a name to</param>
|
||||
/// <param name="name">The name to assign to the handle</param>
|
||||
[Conditional("DEBUG")]
|
||||
public static void SetDebugName<T>(this Device device, T handle, ReadOnlySpan<byte> name)
|
||||
where T : IVulkanHandle
|
||||
{
|
||||
if (!device.PhysicalDevice.Instance.IsExtensionEnabled(VK.EXT_DEBUG_UTILS_EXTENSION_NAME))
|
||||
return;
|
||||
|
||||
device.SetDebugName(handle.VkObjectType, handle.VkHandle, name);
|
||||
}
|
||||
|
||||
private static unsafe void SetDebugName(
|
||||
this Device device,
|
||||
VkObjectType objectType,
|
||||
nint handle,
|
||||
ReadOnlySpan<byte> name
|
||||
)
|
||||
{
|
||||
fixed (byte* namePtr = name)
|
||||
device.SetDebugUtilsObjectNameEXT(
|
||||
new VkDebugUtilsObjectNameInfoEXT
|
||||
{
|
||||
ObjectType = objectType,
|
||||
ObjectHandle = handle,
|
||||
ObjectName = namePtr,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
416
brutal.vulkan/Brutal.Vulkan.Abstractions/DescriptorPoolEx.cs
Normal file
416
brutal.vulkan/Brutal.Vulkan.Abstractions/DescriptorPoolEx.cs
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
using System.Text;
|
||||
|
||||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public class DescriptorPoolEx : VulkanHandleWrapper<VkDescriptorPool, VkEmptyTable>, IDisposable
|
||||
{
|
||||
public ref struct CreateInfo
|
||||
{
|
||||
/// <inheritdoc cref="VkDescriptorPoolCreateInfo.Next"/>
|
||||
public unsafe void* Next;
|
||||
|
||||
/// <inheritdoc cref="VkDescriptorPoolCreateInfo.MaxSets"/>
|
||||
public int MaxSets;
|
||||
|
||||
/// <inheritdoc cref="VkDescriptorPoolCreateInfo.Flags"/>
|
||||
public VkDescriptorPoolCreateFlags Flags;
|
||||
|
||||
/// <inheritdoc cref="VkDescriptorPoolCreateInfo.PoolSizes"/>
|
||||
public Span<VkDescriptorPoolSize> PoolSizes;
|
||||
|
||||
/// <summary>
|
||||
/// Extract or populate this struct with a VkDescriptorPoolCreateInfo
|
||||
/// </summary>
|
||||
public unsafe VkDescriptorPoolCreateInfo DescriptorPoolCreateInfo
|
||||
{
|
||||
get =>
|
||||
new()
|
||||
{
|
||||
Flags = Flags,
|
||||
MaxSets = MaxSets,
|
||||
Next = Next,
|
||||
PoolSizes = PoolSizes.AsPointer(),
|
||||
PoolSizeCount = PoolSizes.Length,
|
||||
};
|
||||
set
|
||||
{
|
||||
Next = value.Next;
|
||||
Flags = value.Flags;
|
||||
MaxSets = value.MaxSets;
|
||||
PoolSizes = new(value.PoolSizes, value.PoolSizeCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Device Device { get; }
|
||||
|
||||
public int MaxSets { get; }
|
||||
|
||||
public int RemainingSets { get; private set; }
|
||||
|
||||
public VkDescriptorPoolCreateFlags Flags { get; }
|
||||
|
||||
public record struct PoolSize(VkDescriptorType Type, int InitialCount, int RemainingCount);
|
||||
|
||||
public readonly PoolSize[] PoolSizes;
|
||||
|
||||
public readonly Dictionary<VkDescriptorSet, DescriptorSetLayoutEx> MappedDescriptorSets;
|
||||
private readonly VkAllocator? _allocator;
|
||||
|
||||
internal DescriptorPoolEx(Device device, CreateInfo createInfo, VkAllocator? allocator)
|
||||
{
|
||||
Device = device;
|
||||
MaxSets = createInfo.MaxSets;
|
||||
RemainingSets = MaxSets;
|
||||
Flags = createInfo.Flags;
|
||||
_allocator = allocator;
|
||||
|
||||
PoolSizes = new PoolSize[createInfo.PoolSizes.Length];
|
||||
for (var i = 0; i < createInfo.PoolSizes.Length; i++)
|
||||
PoolSizes[i] = new PoolSize(
|
||||
createInfo.PoolSizes[i].Type,
|
||||
createInfo.PoolSizes[i].DescriptorCount,
|
||||
createInfo.PoolSizes[i].DescriptorCount
|
||||
);
|
||||
|
||||
Handle = device.CreateDescriptorPool(createInfo.DescriptorPoolCreateInfo, allocator);
|
||||
|
||||
MappedDescriptorSets = new Dictionary<VkDescriptorSet, DescriptorSetLayoutEx>(MaxSets);
|
||||
}
|
||||
|
||||
internal unsafe VkDescriptorSet AllocateDescriptorSet(DescriptorSetLayoutEx layout)
|
||||
{
|
||||
TryAllocateFromLayouts([layout]);
|
||||
|
||||
var layoutHandle = layout.Handle;
|
||||
|
||||
VkDescriptorSet descriptorSet;
|
||||
|
||||
Device.AllocateDescriptorSets(
|
||||
new VkDescriptorSetAllocateInfo
|
||||
{
|
||||
DescriptorPool = Handle,
|
||||
DescriptorSetCount = 1,
|
||||
SetLayouts = &layoutHandle,
|
||||
},
|
||||
new ReadOnlySpan<VkDescriptorSet>(&descriptorSet, 1)
|
||||
);
|
||||
|
||||
MappedDescriptorSets.Add(descriptorSet, layout);
|
||||
|
||||
return descriptorSet;
|
||||
}
|
||||
|
||||
internal unsafe void AllocateDescriptorSets(DescriptorSetLayoutEx layout, Span<VkDescriptorSet> descriptorSets)
|
||||
{
|
||||
TryAllocateFromLayouts([layout], descriptorSets.Length);
|
||||
|
||||
Span<VkDescriptorSetLayout> layouts = stackalloc VkDescriptorSetLayout[descriptorSets.Length];
|
||||
for (var i = 0; i < descriptorSets.Length; i++)
|
||||
layouts[i] = layout.Handle;
|
||||
|
||||
Device.AllocateDescriptorSets(
|
||||
new VkDescriptorSetAllocateInfo
|
||||
{
|
||||
DescriptorPool = Handle,
|
||||
DescriptorSetCount = descriptorSets.Length,
|
||||
SetLayouts = layouts.AsPointer(),
|
||||
},
|
||||
descriptorSets
|
||||
);
|
||||
|
||||
for (var i = 0; i < descriptorSets.Length; i++)
|
||||
MappedDescriptorSets.Add(descriptorSets[i], layout);
|
||||
}
|
||||
|
||||
internal unsafe void AllocateDescriptorSets(
|
||||
Span<DescriptorSetLayoutEx> layouts,
|
||||
Span<VkDescriptorSet> descriptorSets
|
||||
)
|
||||
{
|
||||
if (layouts.Length != descriptorSets.Length)
|
||||
throw new ArgumentException("layouts and descriptorSets must be the same length");
|
||||
|
||||
TryAllocateFromLayouts(layouts);
|
||||
|
||||
Span<VkDescriptorSetLayout> layoutHandles = stackalloc VkDescriptorSetLayout[layouts.Length];
|
||||
|
||||
for (var i = 0; i < layouts.Length; i++)
|
||||
layoutHandles[i] = layouts[i].Handle;
|
||||
|
||||
Device.AllocateDescriptorSets(
|
||||
new VkDescriptorSetAllocateInfo
|
||||
{
|
||||
DescriptorPool = Handle,
|
||||
DescriptorSetCount = layouts.Length,
|
||||
SetLayouts = layoutHandles.AsPointer(),
|
||||
},
|
||||
descriptorSets
|
||||
);
|
||||
|
||||
for (var i = 0; i < layouts.Length; i++)
|
||||
MappedDescriptorSets.Add(descriptorSets[i], layouts[i]);
|
||||
}
|
||||
|
||||
protected void TryAllocateFromLayouts(Span<DescriptorSetLayoutEx> layouts, int multiplier = 1)
|
||||
{
|
||||
var requiredSets = layouts.Length * multiplier;
|
||||
|
||||
if (RemainingSets < requiredSets)
|
||||
throw DescriptorPoolOutOfMemoryException.OutOfSets(this, requiredSets);
|
||||
|
||||
// Create a copy of the pool sizes to avoid modifying the original in case of failure
|
||||
Span<PoolSize> poolSizes = stackalloc PoolSize[PoolSizes.Length];
|
||||
PoolSizes.CopyTo(poolSizes);
|
||||
|
||||
foreach (var layout in layouts)
|
||||
TryAllocateFromLayout(poolSizes, layout, multiplier);
|
||||
|
||||
// Commit the changes if allocation was successful
|
||||
poolSizes.CopyTo(PoolSizes);
|
||||
RemainingSets -= requiredSets;
|
||||
}
|
||||
|
||||
private void TryAllocateFromLayout(Span<PoolSize> poolSizes, DescriptorSetLayoutEx layout, int multiplier)
|
||||
{
|
||||
foreach (var (type, required) in layout.Descriptors)
|
||||
TryAllocateDescriptors(poolSizes, type, required * multiplier);
|
||||
}
|
||||
|
||||
private void TryAllocateDescriptors(Span<PoolSize> poolSizes, VkDescriptorType type, int required)
|
||||
{
|
||||
// Try to find a pool size that matches the type and has enough remaining descriptors
|
||||
for (var i = 0; i < poolSizes.Length; i++)
|
||||
{
|
||||
if (poolSizes[i].Type != type)
|
||||
continue;
|
||||
|
||||
if (poolSizes[i].RemainingCount < required)
|
||||
throw DescriptorPoolOutOfMemoryException.OutOfDescriptors(this, type, required);
|
||||
|
||||
poolSizes[i].RemainingCount -= required;
|
||||
return;
|
||||
}
|
||||
|
||||
// If no matching pool size was found, allocation failed
|
||||
throw DescriptorPoolInvalidOperationException.DescriptorTypeNotFound(this, type);
|
||||
}
|
||||
|
||||
internal void FreeDescriptorSets(Span<VkDescriptorSet> descriptorSets)
|
||||
{
|
||||
if ((Flags & VkDescriptorPoolCreateFlags.FreeDescriptorSetBit) == 0)
|
||||
throw DescriptorPoolInvalidOperationException.BadFreeOperation(this);
|
||||
|
||||
foreach (var descriptorSet in descriptorSets)
|
||||
{
|
||||
if (!MappedDescriptorSets.TryGetValue(descriptorSet, out var layout))
|
||||
throw DescriptorPoolInvalidOperationException.FreeInvalidDescriptorSet(this, descriptorSet);
|
||||
|
||||
// Returns the descriptors and credits RemainingSets by one (multiplier -1)
|
||||
TryAllocateFromLayouts([layout], -1);
|
||||
MappedDescriptorSets.Remove(descriptorSet);
|
||||
}
|
||||
|
||||
Device.FreeDescriptorSetsInternal(Handle, descriptorSets);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
MappedDescriptorSets.Clear();
|
||||
Device.DestroyDescriptorPool(Handle, _allocator);
|
||||
}
|
||||
|
||||
public VkDescriptorPool Handle { get; init; }
|
||||
public ref VkEmptyTable PInvoke => throw new NotImplementedException();
|
||||
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
public VkObjectType VkObjectType => Handle.VkObjectType;
|
||||
public IntPtr VkHandle => Handle.VkHandle;
|
||||
|
||||
public static implicit operator VkDescriptorPool(DescriptorPoolEx descriptorPool) => descriptorPool.Handle;
|
||||
}
|
||||
|
||||
public static class DescriptorPoolExExtensions
|
||||
{
|
||||
public static DescriptorPoolEx CreateDescriptorPool(
|
||||
this Device device,
|
||||
DescriptorPoolEx.CreateInfo createInfo,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
return new DescriptorPoolEx(device, createInfo, allocator);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates a single descriptor set from the specified descriptor pool using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateDescriptorSets.html">vkAllocateDescriptorSets</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the descriptor pool.</param>
|
||||
/// <param name="inDescriptorPool">The descriptor pool from which to allocate the descriptor set.</param>
|
||||
/// <param name="inDescriptorSetLayout">
|
||||
/// A <see cref="VkDescriptorSetLayout"/> handle that describes the layout of the descriptor set to be allocated.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkDescriptorSet</c> object representing the allocated descriptor set.</returns>
|
||||
public static VkDescriptorSet AllocateDescriptorSet(
|
||||
this Device inDevice,
|
||||
DescriptorPoolEx inDescriptorPool,
|
||||
DescriptorSetLayoutEx inDescriptorSetLayout
|
||||
)
|
||||
{
|
||||
return inDescriptorPool.AllocateDescriptorSet(inDescriptorSetLayout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates one or more descriptor sets from the specified descriptor pool using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateDescriptorSets.html">vkAllocateDescriptorSets</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the descriptor pool.</param>
|
||||
/// <param name="inDescriptorPool">The descriptor pool from which the descriptor sets will be allocated.</param>
|
||||
/// <param name="inDescriptorSetLayouts">
|
||||
/// A span of <see cref="VkDescriptorSetLayout"/> handles, each describing the layout of a descriptor set to be allocated.
|
||||
/// </param>
|
||||
/// <param name="outDescriptorSets">An array of <c>VkDescriptorSet</c> objects representing the allocated descriptor sets.</param>
|
||||
public static void AllocateDescriptorSets(
|
||||
this Device inDevice,
|
||||
DescriptorPoolEx inDescriptorPool,
|
||||
Span<DescriptorSetLayoutEx> inDescriptorSetLayouts,
|
||||
Span<VkDescriptorSet> outDescriptorSets
|
||||
)
|
||||
{
|
||||
inDescriptorPool.AllocateDescriptorSets(inDescriptorSetLayouts, outDescriptorSets);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates an array of descriptor sets from the specified descriptor pool using a single descriptor set layout repeated for each set.
|
||||
/// This method constructs a span containing the same <see cref="VkDescriptorSetLayout"/> for every descriptor set to be allocated.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the descriptor pool.</param>
|
||||
/// <param name="inDescriptorPool">The descriptor pool from which the descriptor sets will be allocated.</param>
|
||||
/// <param name="inDescriptorSetLayout">
|
||||
/// A <see cref="VkDescriptorSetLayout"/> handle that describes the layout of each descriptor set.
|
||||
/// </param>
|
||||
/// <param name="outDescriptorSets">A span to be filled with the allocated descriptor sets.</param>
|
||||
/// <returns>An array of <c>VkDescriptorSet</c> objects representing the allocated descriptor sets.</returns>
|
||||
public static void AllocateDescriptorSets(
|
||||
this Device inDevice,
|
||||
DescriptorPoolEx inDescriptorPool,
|
||||
DescriptorSetLayoutEx inDescriptorSetLayout,
|
||||
Span<VkDescriptorSet> outDescriptorSets
|
||||
)
|
||||
{
|
||||
inDescriptorPool.AllocateDescriptorSets(inDescriptorSetLayout, outDescriptorSets);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frees descriptor sets that were previously allocated from the specified descriptor pool
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkFreeDescriptorSets.html">vkFreeDescriptorSets</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the descriptor pool.</param>
|
||||
/// <param name="inDescriptorPool">The descriptor pool from which the descriptor sets were allocated.</param>
|
||||
/// <param name="inDescriptorSet">The descriptor set to free</param>
|
||||
public static void FreeDescriptorSet(
|
||||
this Device inDevice,
|
||||
DescriptorPoolEx inDescriptorPool,
|
||||
VkDescriptorSet inDescriptorSet
|
||||
)
|
||||
{
|
||||
inDescriptorPool.FreeDescriptorSets([inDescriptorSet]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frees an array of descriptor sets that were previously allocated from the specified descriptor pool.
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkFreeDescriptorSets.html">vkFreeDescriptorSets</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the descriptor pool.</param>
|
||||
/// <param name="inDescriptorPool">The descriptor pool from which the descriptor sets were allocated.</param>
|
||||
/// <param name="inDescriptorSets">Span of descriptor sets to free</param>
|
||||
public static void FreeDescriptorSets(
|
||||
this Device inDevice,
|
||||
DescriptorPoolEx inDescriptorPool,
|
||||
Span<VkDescriptorSet> inDescriptorSets
|
||||
)
|
||||
{
|
||||
inDescriptorPool.FreeDescriptorSets(inDescriptorSets);
|
||||
}
|
||||
}
|
||||
|
||||
public class DescriptorPoolInvalidOperationException(DescriptorPoolEx pool, string message)
|
||||
: InvalidOperationException(message)
|
||||
{
|
||||
public DescriptorPoolEx Pool = pool;
|
||||
|
||||
public static DescriptorPoolInvalidOperationException BadFreeOperation(DescriptorPoolEx pool) =>
|
||||
new(pool, "Tried to free sets from a pool that was not created with the 'FreeDescriptorSet' flag");
|
||||
|
||||
public static DescriptorPoolInvalidOperationException FreeInvalidDescriptorSet(
|
||||
DescriptorPoolEx pool,
|
||||
VkDescriptorSet descriptorSet
|
||||
) => new(pool, "Tried to free a descriptor set that was not allocated from this pool");
|
||||
|
||||
public static DescriptorPoolInvalidOperationException DescriptorTypeNotFound(
|
||||
DescriptorPoolEx pool,
|
||||
VkDescriptorType type
|
||||
) => new(pool, $"Tried to allocate descriptor of type '{type}' that was never allocated for this pool");
|
||||
}
|
||||
|
||||
public class DescriptorPoolOutOfMemoryException(DescriptorPoolEx pool, string message) : OutOfMemoryException(message)
|
||||
{
|
||||
public DescriptorPoolEx Pool = pool;
|
||||
|
||||
public static DescriptorPoolOutOfMemoryException OutOfSets(DescriptorPoolEx pool, int required)
|
||||
{
|
||||
var remaining = pool.RemainingSets;
|
||||
|
||||
return new DescriptorPoolOutOfMemoryException(
|
||||
pool,
|
||||
new StringBuilder("Tried to allocate ")
|
||||
.Append(required == 1 ? "a new set" : $"{required} new sets")
|
||||
.Append(", but there ")
|
||||
.Append(
|
||||
remaining switch
|
||||
{
|
||||
0 => "are no sets remaining",
|
||||
1 => "is only 1 set remaining",
|
||||
_ => $"are only {remaining} sets remaining",
|
||||
}
|
||||
)
|
||||
.ToString()
|
||||
);
|
||||
}
|
||||
|
||||
public static DescriptorPoolOutOfMemoryException OutOfDescriptors(
|
||||
DescriptorPoolEx pool,
|
||||
VkDescriptorType type,
|
||||
int required
|
||||
)
|
||||
{
|
||||
// Find the matching pool size without a LINQ enumerator/closure on this error path
|
||||
var remaining = 0;
|
||||
foreach (var poolSize in pool.PoolSizes)
|
||||
{
|
||||
if (poolSize.Type != type)
|
||||
continue;
|
||||
remaining = poolSize.RemainingCount;
|
||||
break;
|
||||
}
|
||||
|
||||
return new DescriptorPoolOutOfMemoryException(
|
||||
pool,
|
||||
new StringBuilder("Tried to allocate ")
|
||||
.Append(required == 1 ? "a new descriptor" : $"{required} new descriptors")
|
||||
.Append(" of type '")
|
||||
.Append(type)
|
||||
.Append("', but there ")
|
||||
.Append(
|
||||
remaining switch
|
||||
{
|
||||
0 => "are no descriptors of this type remaining",
|
||||
1 => "is only 1 descriptor of this type remaining",
|
||||
_ => $"are only {remaining} descriptors of this type remaining",
|
||||
}
|
||||
)
|
||||
.ToString()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public class DescriptorSetLayoutEx : VulkanHandleWrapper<VkDescriptorSetLayout, VkEmptyTable>, IDisposable
|
||||
{
|
||||
public Device Device { get; }
|
||||
public Dictionary<VkDescriptorType, int> Descriptors { get; } = new();
|
||||
private readonly VkAllocator? _allocator;
|
||||
|
||||
public unsafe ref struct CreateInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// <c>pNext</c> is `NULL` or a pointer to a structure extending this structure.
|
||||
/// </summary>
|
||||
public void* Next;
|
||||
|
||||
/// <summary>
|
||||
/// <c>flags</c> is a bitmask specifying options for descriptor set layout creation.
|
||||
/// </summary>
|
||||
public VkDescriptorSetLayoutCreateFlags Flags;
|
||||
|
||||
/// <summary>
|
||||
/// <c>pBindings</c> is a pointer to an array of <c>VkDescriptorSetLayoutBinding</c> structures.
|
||||
/// </summary>
|
||||
public Span<VkDescriptorSetLayoutBinding> Bindings;
|
||||
|
||||
/// <summary>
|
||||
/// Extract or populate this struct with a VkDescriptorSetLayoutCreateInfo
|
||||
/// </summary>
|
||||
public VkDescriptorSetLayoutCreateInfo DescriptorSetLayoutCreateInfo
|
||||
{
|
||||
get =>
|
||||
new()
|
||||
{
|
||||
Next = Next,
|
||||
Flags = Flags,
|
||||
BindingCount = Bindings.Length,
|
||||
Bindings = Bindings.AsPointer(),
|
||||
};
|
||||
set
|
||||
{
|
||||
Next = value.Next;
|
||||
Flags = value.Flags;
|
||||
Bindings = new(value.Bindings, value.BindingCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal DescriptorSetLayoutEx(Device device, CreateInfo createInfo, VkAllocator? allocator)
|
||||
{
|
||||
Device = device;
|
||||
Handle = device.CreateDescriptorSetLayout(createInfo.DescriptorSetLayoutCreateInfo, allocator);
|
||||
_allocator = allocator;
|
||||
|
||||
foreach (var binding in createInfo.Bindings)
|
||||
{
|
||||
if (Descriptors.ContainsKey(binding.DescriptorType))
|
||||
Descriptors[binding.DescriptorType] += binding.DescriptorCount;
|
||||
else
|
||||
Descriptors[binding.DescriptorType] = binding.DescriptorCount;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Device.DestroyDescriptorSetLayout(Handle, _allocator);
|
||||
}
|
||||
|
||||
public VkDescriptorSetLayout Handle { get; init; }
|
||||
public ref VkEmptyTable PInvoke => throw new NotImplementedException();
|
||||
|
||||
public bool IsNull() => Handle.IsNull();
|
||||
|
||||
public VkObjectType VkObjectType => Handle.VkObjectType;
|
||||
public IntPtr VkHandle => Handle.VkHandle;
|
||||
|
||||
public static implicit operator VkDescriptorSetLayout(DescriptorSetLayoutEx descriptorSetLayout) =>
|
||||
descriptorSetLayout.Handle;
|
||||
}
|
||||
|
||||
public static class DescriptorSetLayoutExExtensions
|
||||
{
|
||||
public static DescriptorSetLayoutEx CreateDescriptorSetLayout(
|
||||
this Device device,
|
||||
DescriptorSetLayoutEx.CreateInfo createInfo,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
return new DescriptorSetLayoutEx(device, createInfo, allocator);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for recording Vulkan command buffer commands.
|
||||
/// </summary>
|
||||
public static class CommandBufferExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Resets the command buffer to its initial state using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkResetCommandBuffer.html">vkResetCommandBuffer</see>.
|
||||
/// The command buffer must not be in a pending state and will be reset to the initial state.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to reset.</param>
|
||||
public static void Reset(this CommandBuffer inCommandBuffer)
|
||||
{
|
||||
inCommandBuffer.Reset(VkCommandBufferResetFlags.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins recording commands on the command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
|
||||
public static void Begin(this CommandBuffer inCommandBuffer)
|
||||
{
|
||||
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = VkCommandBufferUsageFlags.None });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins a Vulkan debug label region on the command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBeginDebugUtilsLabelEXT.html">vkCmdBeginDebugUtilsLabelEXT</see>.
|
||||
/// This allows grouping commands within a labeled region for better debugging and profiling.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The Vulkan command buffer on which to begin the debug label.</param>
|
||||
/// <param name="label">A read-only span of bytes representing the label name. The label should be null-terminated.</param>
|
||||
/// <param name="color">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
|
||||
public static unsafe void BeginDebugLabel(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
in ReadOnlySpan<byte> label,
|
||||
in float4 color
|
||||
)
|
||||
{
|
||||
var vkLabel = new VkDebugUtilsLabelEXT { LabelName = label.AsPointer() };
|
||||
vkLabel.Color[0] = color.R;
|
||||
vkLabel.Color[1] = color.G;
|
||||
vkLabel.Color[2] = color.B;
|
||||
vkLabel.Color[3] = color.A;
|
||||
inCommandBuffer.BeginDebugUtilsLabelEXT(vkLabel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the current Vulkan debug label region on the command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdEndDebugUtilsLabelEXT.html">vkCmdEndDebugUtilsLabelEXT</see>.
|
||||
/// This marks the end of a previously started debug label region, allowing Vulkan debugging tools to identify command groups.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The Vulkan command buffer on which to end the debug label.</param>
|
||||
public static void EndDebugLabel(this CommandBuffer inCommandBuffer)
|
||||
{
|
||||
inCommandBuffer.EndDebugUtilsLabelEXT();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins recording commands on the command buffer with specified usage flags using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
|
||||
/// <param name="usage">The usage flags determining how the command buffer will be used.</param>
|
||||
public static void Begin(this CommandBuffer inCommandBuffer, VkCommandBufferUsageFlags usage)
|
||||
{
|
||||
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = usage });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins recording commands on the command buffer with specified usage flags and inheritance information
|
||||
/// for secondary command buffers, using <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
|
||||
/// <param name="usage">The usage flags for the command buffer.</param>
|
||||
/// <param name="inheritanceInfo">
|
||||
/// For secondary command buffers, a pointer to a <c>VkCommandBufferInheritanceInfo</c> structure providing additional state;
|
||||
/// ignored for primary command buffers.
|
||||
/// </param>
|
||||
public static void Begin(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkCommandBufferUsageFlags usage,
|
||||
VkCommandBufferInheritanceInfo inheritanceInfo
|
||||
)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = usage, InheritanceInfo = &inheritanceInfo });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a command to copy data between buffers using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdCopyBuffer.html">vkCmdCopyBuffer</see>.
|
||||
/// Copies the specified region from the source buffer to the destination buffer.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer that will record the copy command.</param>
|
||||
/// <param name="inSrcBuffer">The source buffer.</param>
|
||||
/// <param name="inDstBuffer">The destination buffer.</param>
|
||||
/// <param name="inRegion">A <c>VkBufferCopy</c> structure defining the region to copy.</param>
|
||||
public static void CopyBuffer(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkBuffer inSrcBuffer,
|
||||
VkBuffer inDstBuffer,
|
||||
VkBufferCopy inRegion
|
||||
)
|
||||
{
|
||||
inCommandBuffer.CopyBuffer(inSrcBuffer, inDstBuffer, [inRegion]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a command to copy a specified number of bytes from the source buffer to the destination buffer.
|
||||
/// This is a convenience overload that assumes zero offsets.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer that will record the copy command.</param>
|
||||
/// <param name="inSrcBuffer">The source buffer.</param>
|
||||
/// <param name="inDstBuffer">The destination buffer.</param>
|
||||
/// <param name="inSize">The number of bytes to copy from the start of the buffers.</param>
|
||||
public static void CopyBuffer(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkBuffer inSrcBuffer,
|
||||
VkBuffer inDstBuffer,
|
||||
ByteSize inSize
|
||||
)
|
||||
{
|
||||
CopyBuffer(
|
||||
inCommandBuffer,
|
||||
inSrcBuffer,
|
||||
inDstBuffer,
|
||||
new VkBufferCopy
|
||||
{
|
||||
Size = inSize,
|
||||
DstOffset = ByteSize.Zero,
|
||||
SrcOffset = ByteSize.Zero,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds a vertex buffer to the command buffer at the specified binding index using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindVertexBuffers.html">vkCmdBindVertexBuffers</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to record the binding command.</param>
|
||||
/// <param name="inBinding">The vertex input binding index to update.</param>
|
||||
/// <param name="inBuffer">The vertex buffer to bind.</param>
|
||||
/// <param name="inOffset">The offset (in bytes) within the buffer to start binding from. Defaults to 0.</param>
|
||||
public static void BindVertexBuffer(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
int inBinding,
|
||||
VkBuffer inBuffer,
|
||||
ByteSize inOffset = default
|
||||
)
|
||||
{
|
||||
inCommandBuffer.BindVertexBuffers(inBinding, [inBuffer], [inOffset]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a command to update a push constant value of type <typeparamref name="T"/> in the command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdPushConstants.html">vkCmdPushConstants</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to record the push constant update.</param>
|
||||
/// <param name="inLayout">The pipeline layout that defines the push constant ranges.</param>
|
||||
/// <param name="inStageFlags">A bitmask of <c>VkShaderStageFlags</c> indicating which shader stages will access the push constant.</param>
|
||||
/// <param name="inOffset">The byte offset within the push constant range at which to start updating.</param>
|
||||
/// <param name="inData">The push constant value to update.</param>
|
||||
public static void PushConstants<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkPipelineLayout inLayout,
|
||||
VkShaderStageFlags inStageFlags,
|
||||
ByteSize inOffset,
|
||||
T inData
|
||||
)
|
||||
where T : unmanaged
|
||||
{
|
||||
inCommandBuffer.PushConstants(inLayout, inStageFlags, inOffset, [inData]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a command to update a sequence of push constants of type <typeparamref name="T"/> in the command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdPushConstants.html">vkCmdPushConstants</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to record the push constant update.</param>
|
||||
/// <param name="inLayout">The pipeline layout that defines the push constant ranges.</param>
|
||||
/// <param name="inStageFlags">A bitmask of <c>VkShaderStageFlags</c> indicating which shader stages will access the push constants.</param>
|
||||
/// <param name="inOffset">The byte offset within the push constant range at which to start updating.</param>
|
||||
/// <param name="inData">A span containing the push constant values to update.</param>
|
||||
public static void PushConstants<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkPipelineLayout inLayout,
|
||||
VkShaderStageFlags inStageFlags,
|
||||
ByteSize inOffset,
|
||||
ReadOnlySpan<T> inData
|
||||
)
|
||||
where T : unmanaged
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (T* ptr = inData)
|
||||
{
|
||||
inCommandBuffer.PInvoke.vkCmdPushConstants.Invoke(
|
||||
inCommandBuffer.Handle,
|
||||
inLayout,
|
||||
inStageFlags,
|
||||
(int)inOffset,
|
||||
(int)ByteSize.Of<T>(inData.Length),
|
||||
ptr
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,593 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Functions to extend the Device class
|
||||
/// </summary>
|
||||
public static class DeviceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a default render pass configured for common rendering scenarios. This method sets up attachments for color,
|
||||
/// depth, and, if multisampling is enabled, resolve operations, and configures the corresponding subpass dependencies.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device used for creating the render pass.</param>
|
||||
/// <param name="sampleColor">If true, a color attachment is created and sampled; otherwise, no color attachment is configured.</param>
|
||||
/// <param name="sampleDepth">If true, a depth attachment is created and sampled; otherwise, no depth attachment is configured.</param>
|
||||
/// <param name="sampleCount">Specifies the number of samples per pixel. A value other than <c>VkSampleCountFlags._1</c> indicates that multisampling is enabled.</param>
|
||||
/// <param name="colorFormat">The format to be used for the color attachment image.</param>
|
||||
/// <param name="depthFormat">The format to be used for the depth attachment image.</param>
|
||||
/// <param name="resolvedFormat">The format to be used for the resolve attachment image when multisampling is enabled.</param>
|
||||
/// <returns>A <c>VkRenderPass</c> object representing the configured render pass.</returns>
|
||||
public static unsafe VkRenderPass CreateDefaultRenderPass(
|
||||
this Device inDevice,
|
||||
bool sampleColor,
|
||||
bool sampleDepth,
|
||||
VkSampleCountFlags sampleCount,
|
||||
VkFormat colorFormat,
|
||||
VkFormat depthFormat,
|
||||
VkFormat resolvedFormat,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
var multisamplingEnabled = sampleCount != VkSampleCountFlags._1Bit;
|
||||
|
||||
VkAttachmentDescription? colorAttachment = null;
|
||||
VkAttachmentDescription? depthAttachment = null;
|
||||
VkAttachmentDescription? resolveAttachment = null;
|
||||
|
||||
// Describe the color attachment
|
||||
if (sampleColor)
|
||||
{
|
||||
var storeOp = VkAttachmentStoreOp.DontCare;
|
||||
var finalLayout = VkImageLayout.ShaderReadOnlyOptimal;
|
||||
if (multisamplingEnabled)
|
||||
{
|
||||
storeOp = VkAttachmentStoreOp.DontCare;
|
||||
finalLayout = VkImageLayout.ColorAttachmentOptimal;
|
||||
}
|
||||
|
||||
colorAttachment = new VkAttachmentDescription
|
||||
{
|
||||
Format = colorFormat,
|
||||
Samples = sampleCount,
|
||||
LoadOp = VkAttachmentLoadOp.Clear,
|
||||
StoreOp = storeOp,
|
||||
StencilLoadOp = VkAttachmentLoadOp.DontCare,
|
||||
StencilStoreOp = VkAttachmentStoreOp.DontCare,
|
||||
InitialLayout = VkImageLayout.Undefined,
|
||||
FinalLayout = finalLayout,
|
||||
};
|
||||
}
|
||||
|
||||
// Describe the depth attachment
|
||||
if (sampleDepth)
|
||||
{
|
||||
depthAttachment = new VkAttachmentDescription
|
||||
{
|
||||
Format = depthFormat,
|
||||
Samples = sampleCount,
|
||||
LoadOp = VkAttachmentLoadOp.Clear,
|
||||
StoreOp = VkAttachmentStoreOp.Store,
|
||||
StencilLoadOp = VkAttachmentLoadOp.DontCare,
|
||||
StencilStoreOp = VkAttachmentStoreOp.DontCare,
|
||||
InitialLayout = VkImageLayout.Undefined,
|
||||
FinalLayout = VkImageLayout.DepthStencilReadOnlyOptimal,
|
||||
};
|
||||
}
|
||||
|
||||
// Describe the Multisample-to-singlesample color resolve attachments
|
||||
if (multisamplingEnabled)
|
||||
{
|
||||
// Resolve color attachment
|
||||
if (sampleColor)
|
||||
{
|
||||
resolveAttachment = new VkAttachmentDescription
|
||||
{
|
||||
Format = resolvedFormat,
|
||||
Samples = VkSampleCountFlags._1Bit,
|
||||
LoadOp = VkAttachmentLoadOp.DontCare,
|
||||
StoreOp = VkAttachmentStoreOp.Store,
|
||||
StencilLoadOp = VkAttachmentLoadOp.DontCare,
|
||||
StencilStoreOp = VkAttachmentStoreOp.DontCare,
|
||||
InitialLayout = VkImageLayout.Undefined,
|
||||
FinalLayout = VkImageLayout.ShaderReadOnlyOptimal,
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve depth attachment
|
||||
if (sampleDepth)
|
||||
{
|
||||
// (Not yet implemented)
|
||||
}
|
||||
}
|
||||
|
||||
// Describe the attachment references
|
||||
var references =
|
||||
stackalloc VkAttachmentReference[3] {
|
||||
new VkAttachmentReference { Attachment = 0, Layout = VkImageLayout.ColorAttachmentOptimal },
|
||||
new VkAttachmentReference { Attachment = 1, Layout = VkImageLayout.DepthStencilAttachmentOptimal },
|
||||
new VkAttachmentReference { Attachment = 2, Layout = VkImageLayout.ColorAttachmentOptimal },
|
||||
};
|
||||
|
||||
// Create a subpass
|
||||
var subpass = new VkSubpassDescription { PipelineBindPoint = VkPipelineBindPoint.Graphics };
|
||||
if (sampleColor)
|
||||
{
|
||||
subpass.ColorAttachmentCount = 1;
|
||||
subpass.ColorAttachments = &references[0];
|
||||
}
|
||||
if (sampleDepth)
|
||||
{
|
||||
subpass.DepthStencilAttachment = &references[1];
|
||||
}
|
||||
if (multisamplingEnabled)
|
||||
{
|
||||
subpass.ResolveAttachments = &references[2];
|
||||
}
|
||||
|
||||
// Create subpass dependencies determined by whether multisampling is enabled or not
|
||||
VkSubpassDependency renderSubpass;
|
||||
VkSubpassDependency? resolveSubpass = null;
|
||||
if (multisamplingEnabled)
|
||||
{
|
||||
renderSubpass = new VkSubpassDependency
|
||||
{
|
||||
SrcSubpass = VK.SUBPASS_EXTERNAL,
|
||||
DstSubpass = 0,
|
||||
SrcStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
|
||||
DstStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
|
||||
SrcAccessMask = VkAccessFlags.None,
|
||||
DstAccessMask = VkAccessFlags.ColorAttachmentWriteBit | VkAccessFlags.ColorAttachmentReadBit,
|
||||
DependencyFlags = VkDependencyFlags.None,
|
||||
};
|
||||
resolveSubpass = new VkSubpassDependency
|
||||
{
|
||||
SrcSubpass = VK.SUBPASS_EXTERNAL,
|
||||
DstSubpass = 0,
|
||||
SrcStageMask = VkPipelineStageFlags.EarlyFragmentTestsBit | VkPipelineStageFlags.LateFragmentTestsBit,
|
||||
DstStageMask = VkPipelineStageFlags.EarlyFragmentTestsBit | VkPipelineStageFlags.LateFragmentTestsBit,
|
||||
SrcAccessMask = VkAccessFlags.DepthStencilAttachmentWriteBit,
|
||||
DstAccessMask =
|
||||
VkAccessFlags.DepthStencilAttachmentWriteBit | VkAccessFlags.DepthStencilAttachmentReadBit,
|
||||
DependencyFlags = VkDependencyFlags.None,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
renderSubpass = new VkSubpassDependency
|
||||
{
|
||||
SrcSubpass = VK.SUBPASS_EXTERNAL,
|
||||
DstSubpass = 0,
|
||||
SrcStageMask =
|
||||
VkPipelineStageFlags.ColorAttachmentOutputBit | VkPipelineStageFlags.LateFragmentTestsBit,
|
||||
DstStageMask =
|
||||
VkPipelineStageFlags.ColorAttachmentOutputBit | VkPipelineStageFlags.EarlyFragmentTestsBit,
|
||||
SrcAccessMask = VkAccessFlags.DepthStencilAttachmentWriteBit,
|
||||
DstAccessMask = VkAccessFlags.ColorAttachmentWriteBit | VkAccessFlags.DepthStencilAttachmentWriteBit,
|
||||
DependencyFlags = VkDependencyFlags.None,
|
||||
};
|
||||
}
|
||||
|
||||
// Build arrays of structures we'll be passing to the render pass creation
|
||||
var attachments = stackalloc VkAttachmentDescription[3];
|
||||
var dependencies = stackalloc VkSubpassDependency[2];
|
||||
|
||||
Span<VkSubpassDescription> subpasses = [subpass];
|
||||
|
||||
var attachmentCount = 0;
|
||||
var dependencyCount = 0;
|
||||
|
||||
attachments[attachmentCount++] = colorAttachment!.Value;
|
||||
attachments[attachmentCount++] = depthAttachment!.Value;
|
||||
|
||||
if (multisamplingEnabled)
|
||||
{
|
||||
attachments[attachmentCount++] = resolveAttachment!.Value;
|
||||
dependencies[dependencyCount++] = renderSubpass;
|
||||
dependencies[dependencyCount++] = resolveSubpass!.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
dependencies[dependencyCount++] = renderSubpass;
|
||||
}
|
||||
|
||||
return inDevice.CreateRenderPass(
|
||||
new VkRenderPassCreateInfo
|
||||
{
|
||||
Flags = 0,
|
||||
AttachmentCount = attachmentCount,
|
||||
Attachments = attachments,
|
||||
SubpassCount = subpasses.Length,
|
||||
Subpasses = subpasses.AsPointer(),
|
||||
DependencyCount = dependencyCount,
|
||||
Dependencies = dependencies,
|
||||
},
|
||||
allocator
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new pipeline layout object using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreatePipelineLayout.html">vkCreatePipelineLayout</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device used to create the pipeline layout.</param>
|
||||
/// <param name="setLayouts">
|
||||
/// A span of <see cref="VkDescriptorSetLayout"/> handles that define the descriptor set layouts to be used in the pipeline layout.
|
||||
/// </param>
|
||||
/// <param name="pushConstantRanges">
|
||||
/// A span of <see cref="VkPushConstantRange"/> structures specifying the push constant ranges for the pipeline layout.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkPipelineLayout</c> object representing the created pipeline layout.</returns>
|
||||
public static VkPipelineLayout CreatePipelineLayout(
|
||||
this Device inDevice,
|
||||
ReadOnlySpan<VkDescriptorSetLayout> setLayouts,
|
||||
ReadOnlySpan<VkPushConstantRange> pushConstantRanges,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (VkDescriptorSetLayout* p1 = setLayouts)
|
||||
fixed (VkPushConstantRange* p2 = pushConstantRanges)
|
||||
return inDevice.CreatePipelineLayout(
|
||||
new VkPipelineLayoutCreateInfo
|
||||
{
|
||||
SetLayouts = p1,
|
||||
PushConstantRanges = p2,
|
||||
SetLayoutCount = setLayouts.Length,
|
||||
PushConstantRangeCount = pushConstantRanges.Length,
|
||||
},
|
||||
allocator
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a graphics pipeline using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateGraphicsPipelines.html">vkCreateGraphicsPipelines</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device used for creating the graphics pipeline.</param>
|
||||
/// <param name="inPipelineCache">
|
||||
/// A pipeline cache handle. Use <c>VK_NULL_HANDLE</c> if pipeline caching is disabled; otherwise, provide the handle of a valid
|
||||
/// pipeline cache object to enable caching during pipeline creation.
|
||||
/// </param>
|
||||
/// <param name="inCreateInfo">
|
||||
/// A <see cref="VkGraphicsPipelineCreateInfo"/> structure containing the parameters required to create the graphics pipeline.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkPipeline</c> object representing the created graphics pipeline.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe VkPipeline CreateGraphicsPipeline(
|
||||
this Device inDevice,
|
||||
VkPipelineCache inPipelineCache,
|
||||
VkGraphicsPipelineCreateInfo inCreateInfo,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
VkPipeline pipeline = new();
|
||||
inDevice.CreateGraphicsPipelines(
|
||||
inPipelineCache,
|
||||
[inCreateInfo],
|
||||
null,
|
||||
new ReadOnlySpan<VkPipeline>(&pipeline, 1)
|
||||
);
|
||||
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates a single command buffer from the specified command pool using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateCommandBuffers.html">vkAllocateCommandBuffers</see>.
|
||||
/// </summary>
|
||||
/// <param name="device">The logical device that owns the command pool.</param>
|
||||
/// <param name="createInfo">A <see cref="VkCommandBufferAllocateInfo"/> structure specifying the command pool and allocation parameters.</param>
|
||||
/// <returns>A <c>CommandBuffer</c> object representing the allocated command buffer.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe CommandBuffer AllocateCommandBuffer(this Device device, VkCommandBufferAllocateInfo createInfo)
|
||||
{
|
||||
Span<VkCommandBuffer> commandBufferHandles = stackalloc VkCommandBuffer[1];
|
||||
createInfo.CommandBufferCount = 1;
|
||||
device.AllocateCommandBuffersInternal(createInfo, commandBufferHandles);
|
||||
return new CommandBuffer(device, commandBufferHandles[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates multiple command buffers from the specified command pool using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateCommandBuffers.html">vkAllocateCommandBuffers</see>.
|
||||
/// </summary>
|
||||
/// <param name="device">The logical device that owns the command pool.</param>
|
||||
/// <param name="createInfo">A <see cref="VkCommandBufferAllocateInfo"/> structure specifying the command pool and allocation parameters.</param>
|
||||
/// <param name="commandBuffers">A span of <see cref="CommandBuffer"/> to store the allocated command buffers.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void AllocateCommandBuffers(
|
||||
this Device device,
|
||||
VkCommandBufferAllocateInfo createInfo,
|
||||
Span<CommandBuffer> commandBuffers
|
||||
)
|
||||
{
|
||||
if (commandBuffers.Length == 0)
|
||||
throw new ArgumentException("The command buffer span must not be empty.", nameof(commandBuffers));
|
||||
|
||||
Span<VkCommandBuffer> commandBufferHandles = stackalloc VkCommandBuffer[commandBuffers.Length];
|
||||
createInfo.CommandBufferCount = commandBuffers.Length;
|
||||
device.AllocateCommandBuffersInternal(createInfo, commandBufferHandles);
|
||||
for (var i = 0; i < commandBuffers.Length; i++)
|
||||
commandBuffers[i] = new CommandBuffer(device, commandBufferHandles[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates device memory for a buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateMemory.html">vkAllocateMemory</see>.
|
||||
/// It queries the memory requirements of the specified buffer and selects an appropriate memory type that matches the required properties.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the memory.</param>
|
||||
/// <param name="inPhysicalDevice">The physical device used to determine a compatible memory type.</param>
|
||||
/// <param name="inBuffer">The buffer for which memory is to be allocated.</param>
|
||||
/// <param name="inRequiredProperties">The required memory property flags that the allocated memory must satisfy.</param>
|
||||
/// <returns>A <c>VkDeviceMemory</c> object representing the allocated memory for the buffer.</returns>
|
||||
public static VkDeviceMemory AllocateMemory(
|
||||
this Device inDevice,
|
||||
PhysicalDevice inPhysicalDevice,
|
||||
VkBuffer inBuffer,
|
||||
VkMemoryPropertyFlags inRequiredProperties,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
// Check the memory requirements for the vertex buffer
|
||||
var bufferMemoryRequirements = inDevice.GetBufferMemoryRequirements(inBuffer);
|
||||
var bufferMemoryTypeIndex = inPhysicalDevice.FindMemoryType(
|
||||
bufferMemoryRequirements.MemoryTypeBits,
|
||||
inRequiredProperties
|
||||
);
|
||||
|
||||
// Allocate memory for the vertex buffer
|
||||
var memory = inDevice.AllocateMemory(
|
||||
new VkMemoryAllocateInfo
|
||||
{
|
||||
AllocationSize = bufferMemoryRequirements.Size,
|
||||
MemoryTypeIndex = bufferMemoryTypeIndex,
|
||||
},
|
||||
allocator
|
||||
);
|
||||
|
||||
return memory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates device memory for an image using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateMemory.html">vkAllocateMemory</see>.
|
||||
/// It queries the memory requirements of the specified image and selects an appropriate memory type that meets the required properties.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the memory.</param>
|
||||
/// <param name="inPhysicalDevice">The physical device used to determine a compatible memory type.</param>
|
||||
/// <param name="inImage">The image for which memory is to be allocated.</param>
|
||||
/// <param name="inRequiredProperties">The required memory property flags that the allocated memory must satisfy.</param>
|
||||
/// <returns>A <c>VkDeviceMemory</c> object representing the allocated memory for the image.</returns>
|
||||
public static VkDeviceMemory AllocateMemory(
|
||||
this Device inDevice,
|
||||
PhysicalDevice inPhysicalDevice,
|
||||
VkImage inImage,
|
||||
VkMemoryPropertyFlags inRequiredProperties,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
// Check the memory requirements for the vertex buffer
|
||||
var bufferMemoryRequirements = inDevice.GetImageMemoryRequirements(inImage);
|
||||
var bufferMemoryTypeIndex = inPhysicalDevice.FindMemoryType(
|
||||
bufferMemoryRequirements.MemoryTypeBits,
|
||||
inRequiredProperties
|
||||
);
|
||||
|
||||
// Allocate memory for the vertex buffer
|
||||
var memory = inDevice.AllocateMemory(
|
||||
new VkMemoryAllocateInfo
|
||||
{
|
||||
AllocationSize = bufferMemoryRequirements.Size,
|
||||
MemoryTypeIndex = bufferMemoryTypeIndex,
|
||||
},
|
||||
allocator
|
||||
);
|
||||
|
||||
return memory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps device memory to a pointer of type T using vkMapMemory.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the memory.</param>
|
||||
/// <param name="mapInfo">A <see cref="MapInfo"/> structure specifying the memory range to map.</param>
|
||||
/// <returns>A pointer to the mapped memory cast to type T.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Ptr<T> MapMemory<T>(this Device inDevice, in MapInfo mapInfo)
|
||||
where T : unmanaged
|
||||
{
|
||||
return inDevice.MapMemory(mapInfo).Cast<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps device memory to a pointer of type T using vkMapMemory.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the memory.</param>
|
||||
/// <param name="mapInfo">A <see cref="MapInfo"/> structure specifying the memory range to map.</param>
|
||||
/// <returns>A pointer to the mapped memory cast to type T.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe Ptr MapMemory(this Device inDevice, in MapInfo mapInfo)
|
||||
{
|
||||
if (mapInfo.Region.Size < 1 && mapInfo.Region.Size != VK.WHOLE_SIZE)
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(mapInfo.Region.Size),
|
||||
"The size of the memory region must be greater than zero, or VK.WHOLE_SIZE."
|
||||
);
|
||||
|
||||
var ptr = inDevice.MapMemory(mapInfo.Memory, mapInfo.Region.Offset, mapInfo.Region.Size, mapInfo.Flags);
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes data from a span to device memory. This method maps the specified memory, copies the data from the source span,
|
||||
/// and then unmaps the memory.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of elements in the source span.</typeparam>
|
||||
/// <param name="inDevice">The logical device that owns the destination memory.</param>
|
||||
/// <param name="inSrc">The source span containing the data to write.</param>
|
||||
/// <param name="inDstMemory">The <c>VkDeviceMemory</c> object that will receive the data.</param>
|
||||
/// <param name="inOffset">The zero-based byte offset from the beginning of the memory object at which to start writing.</param>
|
||||
/// <param name="inFlags">Reserved for future use; typically set to <c>VkMemoryMapFlags.None</c>.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void WriteMemory<T>(
|
||||
this Device inDevice,
|
||||
Span<T> inSrc,
|
||||
VkDeviceMemory inDstMemory,
|
||||
ByteSize inOffset = default,
|
||||
VkMemoryMapFlags inFlags = VkMemoryMapFlags.None
|
||||
)
|
||||
where T : unmanaged
|
||||
{
|
||||
Ptr ptr = inDevice.MapMemory(inDstMemory, inOffset, ByteSize.Of(inSrc), inFlags);
|
||||
Mem.Copy(inSrc, ptr.AsSpan<T>(inSrc.Length));
|
||||
inDevice.UnmapMemory(inDstMemory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes data from an array to device memory. This method maps the specified memory, copies the data from the source array,
|
||||
/// and then unmaps the memory.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of elements in the source array.</typeparam>
|
||||
/// <param name="inDevice">The logical device that owns the destination memory.</param>
|
||||
/// <param name="inSrc">The source array containing the data to write.</param>
|
||||
/// <param name="inDstMemory">The <c>VkDeviceMemory</c> object that will receive the data.</param>
|
||||
/// <param name="inOffset">The zero-based byte offset from the beginning of the memory object at which to start writing.</param>
|
||||
/// <param name="inFlags">Reserved for future use; typically set to <c>VkMemoryMapFlags.None</c>.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void WriteMemory<T>(
|
||||
this Device inDevice,
|
||||
ReadOnlySpan<T> inSrc,
|
||||
VkDeviceMemory inDstMemory,
|
||||
ByteSize inOffset = default,
|
||||
VkMemoryMapFlags inFlags = VkMemoryMapFlags.None
|
||||
)
|
||||
where T : unmanaged
|
||||
{
|
||||
Ptr ptr = inDevice.MapMemory(inDstMemory, inOffset, ByteSize.Of(inSrc), inFlags);
|
||||
Mem.Copy(inSrc, ptr.AsSpan<T>(inSrc.Length));
|
||||
inDevice.UnmapMemory(inDstMemory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds a descriptor set to a command buffer using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindDescriptorSets.html">vkCmdBindDescriptorSets</see>.
|
||||
/// An optional dynamic offset can be provided.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to which the descriptor set will be bound.</param>
|
||||
/// <param name="inPipelineBindPoint">
|
||||
/// The pipeline bind point indicating the type of pipeline that will use the descriptor set. Binding at a specific bind point
|
||||
/// does not disturb descriptor sets bound at other bind points.
|
||||
/// </param>
|
||||
/// <param name="inLayout">The pipeline layout that defines the descriptor set bindings.</param>
|
||||
/// <param name="inSet">The index of the descriptor set to bind.</param>
|
||||
/// <param name="inDescriptorSet">The descriptor set to be bound to the command buffer.</param>
|
||||
/// <param name="inDynamicOffsets">
|
||||
/// Span of dynamic offsets to be used with the descriptor set. If no dynamic offsets are needed, pass an empty span.
|
||||
/// </param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void BindDescriptorSet(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkPipelineBindPoint inPipelineBindPoint,
|
||||
VkPipelineLayout inLayout,
|
||||
int inSet,
|
||||
VkDescriptorSet inDescriptorSet,
|
||||
Span<ByteSize32> inDynamicOffsets
|
||||
)
|
||||
{
|
||||
inCommandBuffer.BindDescriptorSets(inPipelineBindPoint, inLayout, inSet, [inDescriptorSet], inDynamicOffsets);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new fence object using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateFence.html">vkCreateFence</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that creates the fence.</param>
|
||||
/// <param name="inCreateFlags">
|
||||
/// Flags that control the creation and initial state of the fence. See <see cref="VkFenceCreateFlags"/> for details.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkFence</c> object representing the created fence.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static VkFence CreateFence(this Device inDevice, VkFenceCreateFlags inCreateFlags, VkAllocator? allocator)
|
||||
{
|
||||
return inDevice.CreateFence(new VkFenceCreateInfo { Flags = inCreateFlags }, allocator);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for a fence to become signaled using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkWaitForFences.html">vkWaitForFences</see>.
|
||||
/// The timeout value is adjusted to the closest allowed value by the implementation.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the fence.</param>
|
||||
/// <param name="inFence">The fence to wait on.</param>
|
||||
/// <param name="inTimeout">
|
||||
/// The timeout period in nanoseconds. The actual timeout may be longer than requested due to implementation-dependent timeout accuracy.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkResult</c> indicating the outcome of the wait operation.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static VkResult WaitForFence(this Device inDevice, VkFence inFence, nint inTimeout)
|
||||
{
|
||||
return inDevice.WaitForFences([inFence], true, inTimeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkFreeCommandBuffers.html">vkFreeCommandBuffers</see> - Free command buffers
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// To free command buffers, call:
|
||||
/// </para>
|
||||
/// <code>
|
||||
/// // Provided by VK_VERSION_1_0
|
||||
/// void vkFreeCommandBuffers(
|
||||
/// VkDevice device,
|
||||
/// VkCommandPool commandPool,
|
||||
/// uint32_t commandBufferCount,
|
||||
/// const VkCommandBuffer* pCommandBuffers);
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void FreeCommandBuffers(
|
||||
this VulkanHandleWrapper<VkDevice, VkDevice.FunctionTable> handle,
|
||||
VkCommandPool commandPool,
|
||||
ReadOnlySpan<CommandBuffer> pCommandBuffers
|
||||
)
|
||||
{
|
||||
Span<VkCommandBuffer> vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length];
|
||||
for (var index = 0; index < pCommandBuffers.Length; index++)
|
||||
vkCommandBuffers[index] = pCommandBuffers[index].Handle;
|
||||
handle.FreeCommandBuffersInternal(commandPool, vkCommandBuffers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdExecuteCommands.html">vkCmdExecuteCommands</see> - Execute a secondary command buffer from a primary command buffer
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Secondary command buffers <i>must</i> not be directly submitted to a queue.
|
||||
/// To record a secondary command buffer to execute as part of a primary command
|
||||
/// buffer, call:
|
||||
/// </para>
|
||||
/// <code>
|
||||
/// // Provided by VK_VERSION_1_0
|
||||
/// void vkCmdExecuteCommands(
|
||||
/// VkCommandBuffer commandBuffer,
|
||||
/// uint32_t commandBufferCount,
|
||||
/// const VkCommandBuffer* pCommandBuffers);
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void ExecuteCommands(
|
||||
this VulkanHandleWrapper<VkCommandBuffer, VkDevice.FunctionTable> handle,
|
||||
ReadOnlySpan<CommandBuffer> pCommandBuffers
|
||||
)
|
||||
{
|
||||
Span<VkCommandBuffer> vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length];
|
||||
for (var index = 0; index < pCommandBuffers.Length; index++)
|
||||
vkCommandBuffers[index] = pCommandBuffers[index].Handle;
|
||||
handle.CmdExecuteCommandsInternal(vkCommandBuffers);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for IDisposable objects.
|
||||
/// </summary>
|
||||
public static class DisposableExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Disposes each element in the provided span.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
|
||||
/// <param name="inObjects">The span of IDisposable objects to dispose.</param>
|
||||
public static void Dispose<T>(this Span<T> inObjects)
|
||||
where T : IDisposable
|
||||
{
|
||||
foreach (var obj in inObjects)
|
||||
obj.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes each element in the provided array.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
|
||||
/// <param name="inObjects">The array of IDisposable objects to dispose.</param>
|
||||
public static void Dispose<T>(this T[] inObjects)
|
||||
where T : IDisposable
|
||||
{
|
||||
foreach (var obj in inObjects)
|
||||
obj.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes each element in the provided enumerable collection.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
|
||||
/// <param name="inObjects">The enumerable collection of IDisposable objects to dispose.</param>
|
||||
public static void Destroy<T>(this IEnumerable<T> inObjects)
|
||||
where T : IDisposable
|
||||
{
|
||||
using var enumerator = inObjects.GetEnumerator();
|
||||
|
||||
while (enumerator.MoveNext())
|
||||
enumerator.Current.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for managing a Vulkan instance
|
||||
/// </summary>
|
||||
public static class InstanceExtensions { }
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
[DebuggerDisplay("Offset: {Offset}, Size: {Size}")]
|
||||
public struct MapRegion()
|
||||
{
|
||||
public ByteSize Offset { get; init; } = ByteSize.Zero;
|
||||
public ByteSize Size { get; init; } = VK.WHOLE_SIZE;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Information required to map a memory region.
|
||||
/// </summary>
|
||||
public readonly struct MapInfo(VkDeviceMemory memory)
|
||||
{
|
||||
public readonly VkDeviceMemory Memory = memory;
|
||||
public MapRegion Region { get; init; } = new();
|
||||
public VkMemoryMapFlags Flags { get; init; } = VkMemoryMapFlags.None;
|
||||
|
||||
public static implicit operator MapInfo(VkDeviceMemory memory) => new(memory);
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public static class PhysicalDeviceExtensions
|
||||
{
|
||||
public static DeviceEx CreateDevice(this PhysicalDevice physicalDevice, DeviceEx.CreateInfo createInfo)
|
||||
{
|
||||
return new DeviceEx(physicalDevice, createInfo);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for submitting command buffers and handling synchronization for Vulkan queues.
|
||||
/// </summary>
|
||||
public static class QueueExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Submits command buffers to a Vulkan queue with specified wait and signal semaphores, and a fence for synchronization.
|
||||
/// </summary>
|
||||
/// <param name="queue">The Vulkan queue to submit command buffers to.</param>
|
||||
/// <param name="waitSemaphores">A span of semaphores to wait on before executing the command buffers.</param>
|
||||
/// <param name="waitDstStageMask">A span of pipeline stage flags indicating the stages to wait for.</param>
|
||||
/// <param name="commandBuffers">A span of command buffers to execute.</param>
|
||||
/// <param name="signalSemaphores">A span of semaphores to signal after executing the command buffers.</param>
|
||||
/// <param name="fence">A fence that is signaled when the queue finishes executing the submitted command buffers.</param>
|
||||
public static void Submit(
|
||||
this Queue queue,
|
||||
Span<VkSemaphore> waitSemaphores,
|
||||
Span<VkPipelineStageFlags> waitDstStageMask,
|
||||
Span<CommandBuffer> commandBuffers,
|
||||
Span<VkSemaphore> signalSemaphores,
|
||||
VkFence fence
|
||||
)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
var commandBuffersPtr = stackalloc VkCommandBuffer[commandBuffers.Length];
|
||||
for (var i = 0; i < commandBuffers.Length; i++)
|
||||
commandBuffersPtr[i] = commandBuffers[i].Handle;
|
||||
|
||||
fixed (VkSemaphore* waitSemaphoresPtr = waitSemaphores)
|
||||
fixed (VkPipelineStageFlags* waitDstStageMaskPtr = waitDstStageMask)
|
||||
fixed (VkSemaphore* signalSemaphoresPtr = signalSemaphores)
|
||||
{
|
||||
var submitInfo = new VkSubmitInfo
|
||||
{
|
||||
WaitSemaphoreCount = waitSemaphores.Length,
|
||||
WaitSemaphores = waitSemaphoresPtr,
|
||||
WaitDstStageMask = waitDstStageMaskPtr,
|
||||
CommandBufferCount = commandBuffers.Length,
|
||||
CommandBuffers = commandBuffersPtr,
|
||||
SignalSemaphoreCount = signalSemaphores.Length,
|
||||
SignalSemaphores = signalSemaphoresPtr,
|
||||
};
|
||||
|
||||
queue.Submit([submitInfo], fence);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public static class ShaderModuleExtensions
|
||||
{
|
||||
public static unsafe VkShaderModule FromSpirv(Device device, ReadOnlySpan<byte> bytes, VkAllocator? allocator)
|
||||
{
|
||||
return device.CreateShaderModule(
|
||||
new VkShaderModuleCreateInfo { Code = bytes.Cast<byte, int>().AsPointer(), CodeSize = ByteSize.Of(bytes) },
|
||||
allocator
|
||||
);
|
||||
}
|
||||
}
|
||||
65
brutal.vulkan/Brutal.Vulkan.Abstractions/FrameResources.cs
Normal file
65
brutal.vulkan/Brutal.Vulkan.Abstractions/FrameResources.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Structure to hold frame resources for the Renderer
|
||||
/// </summary>
|
||||
public class FrameResources(Device inDevice) : IDisposable
|
||||
{
|
||||
/// <summary> Index of this frame </summary>
|
||||
public int FrameIndex = 0;
|
||||
|
||||
/// <summary> Framebuffer for this frame </summary>
|
||||
public VkFramebuffer Framebuffer = default;
|
||||
|
||||
/// <summary> Image for the swapchain </summary>
|
||||
public VkImage ColorImage = default;
|
||||
|
||||
/// <summary> Whether this frame owns the color image </summary>
|
||||
public bool OwnsColorImage = false;
|
||||
|
||||
/// <summary> Bound memory for the SwapchainImage </summary>
|
||||
public VkDeviceMemory ColorImageMemory = default;
|
||||
|
||||
/// <summary> Image view for the swapchain </summary>
|
||||
public VkImageView ColorImageView = default;
|
||||
|
||||
/// <summary> Image for the depth buffer </summary>
|
||||
public VkImage DepthImage = default;
|
||||
|
||||
/// <summary> Bound memory for the DepthImage </summary>
|
||||
public VkDeviceMemory DepthImageMemory = default;
|
||||
|
||||
/// <summary> Image view for the depth buffer </summary>
|
||||
public VkImageView DepthImageView = default;
|
||||
|
||||
/// <summary> Image for the multisampled image </summary>
|
||||
public VkImage MultisampledImage = default;
|
||||
|
||||
/// <summary> Bound memory for the MultisampledImage </summary>
|
||||
public VkDeviceMemory MultisampledImageMemory = default;
|
||||
|
||||
/// <summary> Image view for the multisampled image </summary>
|
||||
public VkImageView MultisampledImageView = default;
|
||||
|
||||
public required VkAllocator? Allocator;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
inDevice.DestroyImageView(ColorImageView, Allocator);
|
||||
inDevice.DestroyImageView(DepthImageView, Allocator);
|
||||
inDevice.DestroyImageView(MultisampledImageView, Allocator);
|
||||
|
||||
if (OwnsColorImage)
|
||||
{
|
||||
inDevice.DestroyImage(ColorImage, Allocator);
|
||||
inDevice.FreeMemory(ColorImageMemory, Allocator);
|
||||
}
|
||||
|
||||
inDevice.DestroyImage(DepthImage, Allocator);
|
||||
inDevice.DestroyImage(MultisampledImage, Allocator);
|
||||
inDevice.FreeMemory(DepthImageMemory, Allocator);
|
||||
inDevice.FreeMemory(MultisampledImageMemory, Allocator);
|
||||
|
||||
inDevice.DestroyFramebuffer(Framebuffer, Allocator);
|
||||
}
|
||||
}
|
||||
10
brutal.vulkan/Brutal.Vulkan.Abstractions/GlobalUsings.cs
Normal file
10
brutal.vulkan/Brutal.Vulkan.Abstractions/GlobalUsings.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
global using System.Runtime.CompilerServices;
|
||||
global using Brutal.Collections;
|
||||
global using Brutal.Logging;
|
||||
global using Brutal.Memory;
|
||||
global using Brutal.Numerics;
|
||||
global using Brutal.Pointers;
|
||||
global using Brutal.Pointers.Extensions;
|
||||
global using Brutal.Strings;
|
||||
global using CommunityToolkit.HighPerformance;
|
||||
global using CommunityToolkit.HighPerformance.Buffers;
|
||||
155
brutal.vulkan/Brutal.Vulkan.Abstractions/IBindBuffer.cs
Normal file
155
brutal.vulkan/Brutal.Vulkan.Abstractions/IBindBuffer.cs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An interface describing a buffer that can be bound to a command buffer.
|
||||
/// </summary>
|
||||
public interface IBindBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// The Vulkan buffer handle.
|
||||
/// </summary>
|
||||
public VkBuffer VkBuffer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The offset within the parent buffer where this buffer starts for binding.
|
||||
/// </summary>
|
||||
public ByteSize BindOffset { get; }
|
||||
}
|
||||
|
||||
public static class BindBufferExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Binds a vertex buffer to the command buffer at the specified binding index using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindVertexBuffers.html">vkCmdBindVertexBuffers</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to record the binding command.</param>
|
||||
/// <param name="inBinding">The vertex input binding index to update.</param>
|
||||
/// <param name="inBuffer">The vertex buffer to bind.</param>
|
||||
/// <param name="inAdditionalOffset">Optional additional offset to add to the buffer's bind offset.</param>
|
||||
public static void BindVertexBuffer<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
int inBinding,
|
||||
T inBuffer,
|
||||
ByteSize inAdditionalOffset = default
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
inCommandBuffer.BindVertexBuffer(inBinding, inBuffer.VkBuffer, inBuffer.BindOffset + inAdditionalOffset);
|
||||
}
|
||||
|
||||
///<summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindVertexBuffers.html">vkCmdBindVertexBuffers</see> - Bind vertex buffers to a command buffer</summary>
|
||||
///<param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
///<param name="inFirstBinding">is the index of the first vertex input binding whose state is updated by the command.</param>
|
||||
///<param name="inBuffers">is a pointer to an array of buffer handles.</param>
|
||||
public static unsafe void BindVertexBuffers<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
int inFirstBinding,
|
||||
Span<T> inBuffers
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
Span<VkBuffer> buffers = stackalloc VkBuffer[inBuffers.Length];
|
||||
Span<ByteSize64> offsets = stackalloc ByteSize64[inBuffers.Length];
|
||||
|
||||
for (var i = 0; i < inBuffers.Length; i++)
|
||||
{
|
||||
buffers[i] = inBuffers[i].VkBuffer;
|
||||
offsets[i] = inBuffers[i].BindOffset;
|
||||
}
|
||||
|
||||
inCommandBuffer.BindVertexBuffers(inFirstBinding, buffers, offsets);
|
||||
}
|
||||
|
||||
///<summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindVertexBuffers.html">vkCmdBindVertexBuffers</see> - Bind vertex buffers to a command buffer</summary>
|
||||
///<param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
///<param name="inFirstBinding">is the index of the first vertex input binding whose state is updated by the command.</param>
|
||||
///<param name="inBuffers">is a pointer to an array of buffer handles.</param>
|
||||
///<param name="inAdditionalOffsets">is a pointer to an array of buffer offsets, beyond the buffer's bind offset.</param>
|
||||
public static unsafe void BindVertexBuffers<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
int inFirstBinding,
|
||||
Span<T> inBuffers,
|
||||
Span<ByteSize> inAdditionalOffsets
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
if (inBuffers.Length != inAdditionalOffsets.Length)
|
||||
throw new ArgumentException("inBuffers and inAdditionalOffsets must be the same length");
|
||||
|
||||
Span<VkBuffer> buffers = stackalloc VkBuffer[inBuffers.Length];
|
||||
Span<ByteSize64> offsets = stackalloc ByteSize64[inBuffers.Length];
|
||||
|
||||
for (var i = 0; i < inBuffers.Length; i++)
|
||||
{
|
||||
buffers[i] = inBuffers[i].VkBuffer;
|
||||
offsets[i] = inBuffers[i].BindOffset + inAdditionalOffsets[i];
|
||||
}
|
||||
|
||||
inCommandBuffer.BindVertexBuffers(inFirstBinding, buffers, offsets);
|
||||
}
|
||||
|
||||
///<summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindIndexBuffer.html">vkCmdBindIndexBuffer</see> - Bind an index buffer to a command buffer</summary>
|
||||
///<param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
///<param name="inBuffer">is the buffer being bound.</param>
|
||||
///<param name="inIndexType">is a <c>VkIndexType</c> value specifying the size of the indices.</param>
|
||||
public static void BindIndexBuffer<T>(this CommandBuffer inCommandBuffer, T inBuffer, VkIndexType inIndexType)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
inCommandBuffer.BindIndexBuffer(inBuffer.VkBuffer, inBuffer.BindOffset, inIndexType);
|
||||
}
|
||||
|
||||
/// <summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindIndexBuffer.html">vkCmdBindIndexBuffer</see> - Bind an index buffer to a command buffer</summary>
|
||||
/// <param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
/// <param name="inBuffer">is the buffer being bound.</param>
|
||||
/// <param name="inAdditionalOffset">is an additional offset to add to the buffer's bind offset.</param>
|
||||
/// <param name="inIndexType">is a <c>VkIndexType</c> value specifying the size of the indices.</param>
|
||||
public static void BindIndexBuffer<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
T inBuffer,
|
||||
ByteSize inAdditionalOffset,
|
||||
VkIndexType inIndexType
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
inCommandBuffer.BindIndexBuffer(inBuffer.VkBuffer, inBuffer.BindOffset + inAdditionalOffset, inIndexType);
|
||||
}
|
||||
|
||||
///<summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdDrawIndirect.html">vkCmdDrawIndirect</see> - Draw primitives with indirect parameters</summary>
|
||||
///<param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
///<param name="inBuffer">is the buffer containing draw parameters.</param>
|
||||
///<param name="inDrawCount">is the number of draws to execute, and <i>can</i> be zero.</param>
|
||||
///<param name="inStride">is the byte stride between successive sets of draw parameters.</param>
|
||||
public static void DrawIndirect<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
T inBuffer,
|
||||
ElementCount inDrawCount,
|
||||
ByteSize inStride
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
inCommandBuffer.DrawIndirect(inBuffer.VkBuffer, inBuffer.BindOffset, inDrawCount, inStride);
|
||||
}
|
||||
|
||||
/// <summary><see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdDrawIndirect.html">vkCmdDrawIndirect</see> - Draw primitives with indirect parameters</summary>
|
||||
/// <param name="inCommandBuffer">is the command buffer into which the command is recorded.</param>
|
||||
/// <param name="inBuffer">is the buffer containing draw parameters.</param>
|
||||
/// <param name="inAdditionalOffset">is an additional offset to add to the buffer's bind offset.</param>
|
||||
/// <param name="inDrawCount">is the number of draws to execute, and <i>can</i> be zero.</param>
|
||||
/// <param name="inStride">is the byte stride between successive sets of draw parameters.</param>
|
||||
public static void DrawIndirect<T>(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
T inBuffer,
|
||||
ByteSize inAdditionalOffset,
|
||||
ElementCount inDrawCount,
|
||||
ByteSize inStride
|
||||
)
|
||||
where T : IBindBuffer
|
||||
{
|
||||
inCommandBuffer.DrawIndirect(
|
||||
inBuffer.VkBuffer,
|
||||
inBuffer.BindOffset + inAdditionalOffset,
|
||||
inDrawCount,
|
||||
inStride
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue