mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 13:08:24 +01:00
first
This commit is contained in:
parent
bd62d51ec9
commit
b578433e37
48 changed files with 784842 additions and 0 deletions
55
Brutal.Vulkan.Abstractions/Allocator/Allocation.cs
Normal file
55
Brutal.Vulkan.Abstractions/Allocator/Allocation.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
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>
|
||||
/// Optional memory allocation flags. When set, the allocator chains a
|
||||
/// <see cref="VkMemoryAllocateFlagsInfo"/> in front of <see cref="Next"/>
|
||||
/// (e.g. <see cref="VkMemoryAllocateFlags.DeviceAddressBit"/> for buffers whose
|
||||
/// device address will be queried).
|
||||
/// </summary>
|
||||
public VkMemoryAllocateFlags AllocateFlags { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum listing memory allocation preferences: whether to prefer GPU or CPU memory
|
||||
/// </summary>
|
||||
public enum MemoryPreference : byte
|
||||
{
|
||||
None,
|
||||
PreferGpu,
|
||||
PreferCpu,
|
||||
}
|
||||
28
Brutal.Vulkan.Abstractions/Allocator/IAllocator.cs
Normal file
28
Brutal.Vulkan.Abstractions/Allocator/IAllocator.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
46
Brutal.Vulkan.Abstractions/Allocator/IBufferAllocator.cs
Normal file
46
Brutal.Vulkan.Abstractions/Allocator/IBufferAllocator.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
8
Brutal.Vulkan.Abstractions/Allocator/IGlobalAllocator.cs
Normal file
8
Brutal.Vulkan.Abstractions/Allocator/IGlobalAllocator.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An allocator that can allocate both buffers and images. Systems that need to allocate
|
||||
/// resources of both kinds can depend on this single interface instead of taking
|
||||
/// <see cref="IBufferAllocator"/> and <see cref="IImageAllocator"/> separately.
|
||||
/// </summary>
|
||||
public interface IGlobalAllocator : IBufferAllocator, IImageAllocator { }
|
||||
72
Brutal.Vulkan.Abstractions/Allocator/IImageAllocator.cs
Normal file
72
Brutal.Vulkan.Abstractions/Allocator/IImageAllocator.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
206
Brutal.Vulkan.Abstractions/BufferEx.cs
Normal file
206
Brutal.Vulkan.Abstractions/BufferEx.cs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
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; }
|
||||
|
||||
/// <inheritdoc cref="AllocationInfo.CreateInfo.AllocateFlags"/>
|
||||
public VkMemoryAllocateFlags AllocFlags;
|
||||
|
||||
/// <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,
|
||||
AllocateFlags = AllocFlags,
|
||||
};
|
||||
set
|
||||
{
|
||||
AllocPreference = value.Preference;
|
||||
AllocRequiredProperties = value.RequiredProperties;
|
||||
AllocPreferredProperties = value.PreferredProperties;
|
||||
AllocPriority = value.Priority;
|
||||
AllocNext = value.Next;
|
||||
AllocFlags = value.AllocateFlags;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>
|
||||
/// Query the buffer's GPU virtual address via
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkGetBufferDeviceAddress.html">vkGetBufferDeviceAddress</see>.
|
||||
/// The buffer must have been created with <see cref="VkBufferUsageFlags.ShaderDeviceAddressBit"/> and its memory
|
||||
/// allocated with <see cref="VkMemoryAllocateFlags.DeviceAddressBit"/> (see <see cref="CreateInfo.AllocFlags"/>).
|
||||
/// </summary>
|
||||
public VkDeviceAddress GetDeviceAddress()
|
||||
{
|
||||
return Allocator.GetDevice().GetBufferDeviceAddress(new VkBufferDeviceAddressInfo { Buffer = VkBuffer });
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
282
Brutal.Vulkan.Abstractions/Classes/DeviceEx.cs
Normal file
282
Brutal.Vulkan.Abstractions/Classes/DeviceEx.cs
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An allocator that allocates images and buffers directly from a Vulkan device.
|
||||
/// </summary>
|
||||
public class DeviceEx : Device, IGlobalAllocator
|
||||
{
|
||||
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().
|
||||
|
||||
/// <summary>
|
||||
/// Resolve the preferred-property flags for an allocation, folding the declared
|
||||
/// <see cref="MemoryPreference"/> into explicit preferred properties.
|
||||
/// </summary>
|
||||
private static VkMemoryPropertyFlags GetPreferredProperties(in AllocationInfo.CreateInfo allocateCreateInfo)
|
||||
{
|
||||
var preferred = allocateCreateInfo.PreferredProperties;
|
||||
|
||||
preferred |= allocateCreateInfo.Preference switch
|
||||
{
|
||||
MemoryPreference.PreferGpu => VkMemoryPropertyFlags.DeviceLocalBit,
|
||||
MemoryPreference.PreferCpu => VkMemoryPropertyFlags.HostVisibleBit | VkMemoryPropertyFlags.HostCoherentBit,
|
||||
_ => VkMemoryPropertyFlags.None,
|
||||
};
|
||||
|
||||
return preferred;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocate device memory for the given requirements, forwarding the caller's pNext chain and,
|
||||
/// when <see cref="AllocationInfo.CreateInfo.AllocateFlags"/> is set, chaining a
|
||||
/// <see cref="VkMemoryAllocateFlagsInfo"/> in front of it.
|
||||
/// </summary>
|
||||
private unsafe VkDeviceMemory AllocateMemoryFor(
|
||||
ByteSize size,
|
||||
int memoryTypeIndex,
|
||||
in AllocationInfo.CreateInfo allocateCreateInfo
|
||||
)
|
||||
{
|
||||
if (allocateCreateInfo.AllocateFlags == VkMemoryAllocateFlags.None)
|
||||
{
|
||||
return this.AllocateMemory(
|
||||
new VkMemoryAllocateInfo
|
||||
{
|
||||
AllocationSize = size,
|
||||
MemoryTypeIndex = memoryTypeIndex,
|
||||
Next = allocateCreateInfo.Next,
|
||||
},
|
||||
VkAllocator
|
||||
);
|
||||
}
|
||||
|
||||
var flagsInfo = new VkMemoryAllocateFlagsInfo
|
||||
{
|
||||
Flags = allocateCreateInfo.AllocateFlags,
|
||||
Next = allocateCreateInfo.Next,
|
||||
};
|
||||
|
||||
return this.AllocateMemory(
|
||||
new VkMemoryAllocateInfo
|
||||
{
|
||||
AllocationSize = size,
|
||||
MemoryTypeIndex = memoryTypeIndex,
|
||||
Next = &flagsInfo,
|
||||
},
|
||||
VkAllocator
|
||||
);
|
||||
}
|
||||
|
||||
/// <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 image
|
||||
var memoryRequirements = this.GetImageMemoryRequirements(image);
|
||||
|
||||
// Pick the first memory type that fits the requirements
|
||||
var selectedMemoryTypeIndex = PhysicalDevice.FindMemoryType(
|
||||
memoryRequirements.MemoryTypeBits,
|
||||
allocateCreateInfo.RequiredProperties,
|
||||
GetPreferredProperties(allocateCreateInfo)
|
||||
);
|
||||
|
||||
var memory = AllocateMemoryFor(memoryRequirements.Size, selectedMemoryTypeIndex, allocateCreateInfo);
|
||||
|
||||
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,
|
||||
GetPreferredProperties(allocateCreateInfo)
|
||||
);
|
||||
|
||||
var memory = AllocateMemoryFor(bufferMemoryRequirements.Size, selectedMemoryTypeIndex, allocateCreateInfo);
|
||||
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 == null)
|
||||
throw new InvalidOperationException(
|
||||
"Allocation has no map-tracking handle; only buffer allocations made by this allocator can be mapped."
|
||||
);
|
||||
|
||||
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 == null)
|
||||
throw new InvalidOperationException(
|
||||
"Allocation has no map-tracking handle; only buffer allocations made by this allocator can be mapped."
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
90
Brutal.Vulkan.Abstractions/DebugNameExtensions.cs
Normal file
90
Brutal.Vulkan.Abstractions/DebugNameExtensions.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
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. Names longer than 255 UTF-8 bytes are truncated.
|
||||
/// </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;
|
||||
|
||||
Span<byte> bytes = stackalloc byte[MAX_DEBUG_NAME_LENGTH];
|
||||
// Encode as much as fits in the 255-byte budget (one byte reserved for the terminator).
|
||||
// FromUtf16 stops at a character boundary when the destination runs out, so a truncated
|
||||
// name is still valid UTF-8 rather than ending mid-character.
|
||||
System.Text.Unicode.Utf8.FromUtf16(
|
||||
name,
|
||||
bytes[..(MAX_DEBUG_NAME_LENGTH - 1)],
|
||||
out _,
|
||||
out var written,
|
||||
replaceInvalidSequences: true,
|
||||
isFinalBlock: true
|
||||
);
|
||||
bytes[written] = 0;
|
||||
|
||||
// Include the terminator: the driver receives a raw char* and reads until NUL
|
||||
device.SetDebugName(handle.VkObjectType, handle.VkHandle, bytes[..(written + 1)]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set a debug name for the handle. The name does not need to be null-terminated;
|
||||
/// a terminator is appended when missing.
|
||||
/// </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;
|
||||
|
||||
// The driver reads until NUL, so the bytes handed over must include one
|
||||
if (name.Length > 0 && name[^1] == 0)
|
||||
{
|
||||
device.SetDebugName(handle.VkObjectType, handle.VkHandle, name);
|
||||
return;
|
||||
}
|
||||
|
||||
var length = Math.Min(name.Length, MAX_DEBUG_NAME_LENGTH - 1);
|
||||
// Don't cut a multi-byte character in half: back up over any continuation bytes (10xxxxxx)
|
||||
// so the truncated prefix is still valid UTF-8
|
||||
while (length > 0 && length < name.Length && (name[length] & 0xC0) == 0x80)
|
||||
length--;
|
||||
Span<byte> terminated = stackalloc byte[MAX_DEBUG_NAME_LENGTH];
|
||||
name[..length].CopyTo(terminated);
|
||||
terminated[length] = 0;
|
||||
|
||||
device.SetDebugName(handle.VkObjectType, handle.VkHandle, terminated[..(length + 1)]);
|
||||
}
|
||||
|
||||
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.Abstractions/DescriptorPoolEx.cs
Normal file
416
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
95
Brutal.Vulkan.Abstractions/DescriptorSetLayoutEx.cs
Normal file
95
Brutal.Vulkan.Abstractions/DescriptorSetLayoutEx.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public class DescriptorSetLayoutEx
|
||||
: VulkanHandleWrapper<VkDescriptorSetLayout, VkEmptyTable>,
|
||||
IDisposable,
|
||||
IDescriptorSetLayoutWrapper
|
||||
{
|
||||
VkDescriptorSetLayout IDescriptorSetLayoutWrapper.DescriptorSetLayout => Handle;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
29
Brutal.Vulkan.Abstractions/Extensions/ByteSizeExtensions.cs
Normal file
29
Brutal.Vulkan.Abstractions/Extensions/ByteSizeExtensions.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Alignment helpers for <see cref="ByteSize"/>.
|
||||
/// </summary>
|
||||
public static class ByteSizeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Round the value up to the next multiple of <paramref name="alignment"/>.
|
||||
/// The alignment must be a power of two; an alignment of zero returns the value unchanged.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static ByteSize AlignUp(this ByteSize value, ByteSize alignment)
|
||||
{
|
||||
if (alignment == 0)
|
||||
return value;
|
||||
|
||||
return ByteSize.Of((value + alignment - 1) & ~(alignment - 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the value is a multiple of <paramref name="alignment"/> (an alignment of zero always matches).
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool IsAlignedTo(this ByteSize value, ByteSize alignment)
|
||||
{
|
||||
return value.AlignUp(alignment) == value;
|
||||
}
|
||||
}
|
||||
273
Brutal.Vulkan.Abstractions/Extensions/CommandBufferExtensions.cs
Normal file
273
Brutal.Vulkan.Abstractions/Extensions/CommandBufferExtensions.cs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Scope handle returned by <see cref="CommandBufferExtensions.DebugScope"/>; ends the
|
||||
/// debug label region on dispose.
|
||||
/// </summary>
|
||||
public readonly struct DebugLabelScope(CommandBuffer inCommandBuffer) : IDisposable
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
inCommandBuffer.EndDebugLabel();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Begins a Vulkan debug label region on the command buffer, encoding the label from a managed string.
|
||||
/// Labels longer than 255 UTF-8 bytes are truncated at a character boundary. See
|
||||
/// <see cref="BeginDebugLabel(CommandBuffer, in ReadOnlySpan{byte}, in float4)"/>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The Vulkan command buffer on which to begin the debug label.</param>
|
||||
/// <param name="inLabel">The label text.</param>
|
||||
/// <param name="inColor">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
|
||||
public static void BeginDebugLabel(this CommandBuffer inCommandBuffer, string inLabel, in float4 inColor = default)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[MAX_DEBUG_LABEL_LENGTH];
|
||||
// Encode as much as fits in the 255-byte budget (one byte reserved for the terminator).
|
||||
// FromUtf16 stops at a character boundary when the destination runs out, so a truncated
|
||||
// label is still valid UTF-8 rather than ending mid-character.
|
||||
System.Text.Unicode.Utf8.FromUtf16(
|
||||
inLabel,
|
||||
bytes[..(MAX_DEBUG_LABEL_LENGTH - 1)],
|
||||
out _,
|
||||
out var written,
|
||||
replaceInvalidSequences: true,
|
||||
isFinalBlock: true
|
||||
);
|
||||
bytes[written] = 0;
|
||||
|
||||
BeginDebugLabel(inCommandBuffer, bytes[..(written + 1)], inColor);
|
||||
}
|
||||
|
||||
private const int MAX_DEBUG_LABEL_LENGTH = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Begins a debug label region and returns a scope that ends it when disposed:
|
||||
/// <c>using var _ = cmd.DebugScope("Shadow pass");</c>
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The Vulkan command buffer to label.</param>
|
||||
/// <param name="inLabel">The label text.</param>
|
||||
/// <param name="inColor">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
|
||||
public static DebugLabelScope DebugScope(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
string inLabel,
|
||||
in float4 inColor = default
|
||||
)
|
||||
{
|
||||
BeginDebugLabel(inCommandBuffer, inLabel, inColor);
|
||||
return new DebugLabelScope(inCommandBuffer);
|
||||
}
|
||||
|
||||
/// <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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
694
Brutal.Vulkan.Abstractions/Extensions/DeviceExtensions.cs
Normal file
694
Brutal.Vulkan.Abstractions/Extensions/DeviceExtensions.cs
Normal file
|
|
@ -0,0 +1,694 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// Pack the enabled attachments and record the index each one lands at
|
||||
var attachments = stackalloc VkAttachmentDescription[3];
|
||||
var attachmentCount = 0;
|
||||
|
||||
var colorIndex = -1;
|
||||
var depthIndex = -1;
|
||||
var resolveIndex = -1;
|
||||
|
||||
if (colorAttachment.HasValue)
|
||||
{
|
||||
colorIndex = attachmentCount;
|
||||
attachments[attachmentCount++] = colorAttachment.Value;
|
||||
}
|
||||
if (depthAttachment.HasValue)
|
||||
{
|
||||
depthIndex = attachmentCount;
|
||||
attachments[attachmentCount++] = depthAttachment.Value;
|
||||
}
|
||||
if (resolveAttachment.HasValue)
|
||||
{
|
||||
resolveIndex = attachmentCount;
|
||||
attachments[attachmentCount++] = resolveAttachment.Value;
|
||||
}
|
||||
|
||||
// Describe the attachment references
|
||||
var references =
|
||||
stackalloc VkAttachmentReference[3] {
|
||||
new VkAttachmentReference { Attachment = colorIndex, Layout = VkImageLayout.ColorAttachmentOptimal },
|
||||
new VkAttachmentReference
|
||||
{
|
||||
Attachment = depthIndex,
|
||||
Layout = VkImageLayout.DepthStencilAttachmentOptimal,
|
||||
},
|
||||
new VkAttachmentReference { Attachment = resolveIndex, Layout = VkImageLayout.ColorAttachmentOptimal },
|
||||
};
|
||||
|
||||
// Create a subpass
|
||||
var subpass = new VkSubpassDescription { PipelineBindPoint = VkPipelineBindPoint.Graphics };
|
||||
if (colorIndex >= 0)
|
||||
{
|
||||
subpass.ColorAttachmentCount = 1;
|
||||
subpass.ColorAttachments = &references[0];
|
||||
}
|
||||
if (depthIndex >= 0)
|
||||
{
|
||||
subpass.DepthStencilAttachment = &references[1];
|
||||
}
|
||||
if (resolveIndex >= 0)
|
||||
{
|
||||
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 the dependency array we'll be passing to the render pass creation
|
||||
var dependencies = stackalloc VkSubpassDependency[2];
|
||||
|
||||
Span<VkSubpassDescription> subpasses = [subpass];
|
||||
|
||||
var dependencyCount = 0;
|
||||
|
||||
dependencies[dependencyCount++] = renderSubpass;
|
||||
if (resolveSubpass.HasValue)
|
||||
dependencies[dependencyCount++] = resolveSubpass.Value;
|
||||
|
||||
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],
|
||||
allocator,
|
||||
new ReadOnlySpan<VkPipeline>(&pipeline, 1)
|
||||
);
|
||||
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a compute pipeline using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateComputePipelines.html">vkCreateComputePipelines</see>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device used for creating the compute 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="VkComputePipelineCreateInfo"/> structure containing the parameters required to create the compute pipeline.
|
||||
/// </param>
|
||||
/// <returns>A <c>VkPipeline</c> object representing the created compute pipeline.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe VkPipeline CreateComputePipeline(
|
||||
this Device inDevice,
|
||||
VkPipelineCache inPipelineCache,
|
||||
VkComputePipelineCreateInfo inCreateInfo,
|
||||
VkAllocator? allocator
|
||||
)
|
||||
{
|
||||
VkPipeline pipeline = new();
|
||||
inDevice.CreateComputePipelines(
|
||||
inPipelineCache,
|
||||
[inCreateInfo],
|
||||
allocator,
|
||||
new ReadOnlySpan<VkPipeline>(&pipeline, 1)
|
||||
);
|
||||
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Query a buffer's GPU virtual address using
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkGetBufferDeviceAddress.html">vkGetBufferDeviceAddress</see>.
|
||||
/// The buffer must have been created with <see cref="VkBufferUsageFlags.ShaderDeviceAddressBit"/> and its memory
|
||||
/// allocated with <see cref="VkMemoryAllocateFlags.DeviceAddressBit"/>.
|
||||
/// </summary>
|
||||
/// <param name="inDevice">The logical device that owns the buffer.</param>
|
||||
/// <param name="inBuffer">The buffer to query.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static VkDeviceAddress GetBufferDeviceAddress(this Device inDevice, VkBuffer inBuffer)
|
||||
{
|
||||
return inDevice.GetBufferDeviceAddress(new VkBufferDeviceAddressInfo { Buffer = inBuffer });
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Binds any <see cref="IDescriptorSetWrapper"/>'s set (and its dynamic offsets, if it declares any)
|
||||
/// to a command buffer. See
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindDescriptorSets.html">vkCmdBindDescriptorSets</see>.
|
||||
/// </summary>
|
||||
/// <param name="inCommandBuffer">The command buffer to which the descriptor set will be bound.</param>
|
||||
/// <param name="inPipelineBindPoint">The pipeline bind point the set is consumed at.</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="inDescriptorSetWrapper">The wrapper whose set and dynamic offsets are bound.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void BindDescriptorSet(
|
||||
this CommandBuffer inCommandBuffer,
|
||||
VkPipelineBindPoint inPipelineBindPoint,
|
||||
VkPipelineLayout inLayout,
|
||||
int inSet,
|
||||
IDescriptorSetWrapper inDescriptorSetWrapper
|
||||
)
|
||||
{
|
||||
var descriptorSet = inDescriptorSetWrapper.DescriptorSet;
|
||||
var dynamicOffsets = inDescriptorSetWrapper.DynamicOffsets;
|
||||
|
||||
// Pinned raw call: the offsets are read-only, but the generated BindDescriptorSets wrapper
|
||||
// currently demands a mutable span even though vkCmdBindDescriptorSets takes a const pointer
|
||||
fixed (ByteSize32* dynamicOffsetsPtr = dynamicOffsets)
|
||||
{
|
||||
inCommandBuffer.PInvoke.vkCmdBindDescriptorSets.Invoke(
|
||||
inCommandBuffer.Handle,
|
||||
inPipelineBindPoint,
|
||||
inLayout,
|
||||
inSet,
|
||||
1,
|
||||
&descriptorSet,
|
||||
dynamicOffsets.Length,
|
||||
(int*)dynamicOffsetsPtr
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
56
Brutal.Vulkan.Abstractions/Extensions/FormatExtensions.cs
Normal file
56
Brutal.Vulkan.Abstractions/Extensions/FormatExtensions.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Classification helpers for <see cref="VkFormat"/>.
|
||||
/// </summary>
|
||||
public static class FormatExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the format has a depth component (including packed depth-stencil formats).
|
||||
/// </summary>
|
||||
public static bool IsDepthFormat(this VkFormat format) =>
|
||||
format switch
|
||||
{
|
||||
VkFormat.D16UNorm
|
||||
or VkFormat.X8D24UNormPack32
|
||||
or VkFormat.D32SFloat
|
||||
or VkFormat.D16UNormS8UInt
|
||||
or VkFormat.D24UNormS8UInt
|
||||
or VkFormat.D32SFloatS8UInt => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when the format has a stencil component (including packed depth-stencil formats).
|
||||
/// </summary>
|
||||
public static bool IsStencilFormat(this VkFormat format) =>
|
||||
format switch
|
||||
{
|
||||
VkFormat.S8UInt or VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when the format has both a depth and a stencil component.
|
||||
/// </summary>
|
||||
public static bool IsDepthStencilFormat(this VkFormat format) =>
|
||||
format switch
|
||||
{
|
||||
VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The full aspect mask implied by the format: depth and/or stencil bits for depth-stencil
|
||||
/// formats, otherwise <see cref="VkImageAspectFlags.ColorBit"/>.
|
||||
/// </summary>
|
||||
public static VkImageAspectFlags GetAspectMask(this VkFormat format) =>
|
||||
format switch
|
||||
{
|
||||
VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt =>
|
||||
VkImageAspectFlags.DepthBit | VkImageAspectFlags.StencilBit,
|
||||
VkFormat.S8UInt => VkImageAspectFlags.StencilBit,
|
||||
VkFormat.D16UNorm or VkFormat.X8D24UNormPack32 or VkFormat.D32SFloat => VkImageAspectFlags.DepthBit,
|
||||
_ => VkImageAspectFlags.ColorBit,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for managing a Vulkan instance
|
||||
/// </summary>
|
||||
public static class InstanceExtensions { }
|
||||
22
Brutal.Vulkan.Abstractions/Extensions/MapInfo.cs
Normal file
22
Brutal.Vulkan.Abstractions/Extensions/MapInfo.cs
Normal file
|
|
@ -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,81 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace Brutal.VulkanApi.Abstractions;
|
||||
|
||||
public static class PhysicalDeviceExtensions
|
||||
{
|
||||
public static DeviceEx CreateDevice(this PhysicalDevice physicalDevice, DeviceEx.CreateInfo createInfo)
|
||||
{
|
||||
return new DeviceEx(physicalDevice, createInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the first format from <paramref name="candidates"/> that supports all of
|
||||
/// <paramref name="features"/> under the given tiling, or <see cref="VkFormat.Undefined"/>
|
||||
/// when none qualifies. Typical use: picking a supported depth(-stencil) format.
|
||||
/// </summary>
|
||||
public static VkFormat FindSupportedFormat(
|
||||
this PhysicalDevice physicalDevice,
|
||||
ReadOnlySpan<VkFormat> candidates,
|
||||
VkImageTiling tiling,
|
||||
VkFormatFeatureFlags features
|
||||
)
|
||||
{
|
||||
foreach (var format in candidates)
|
||||
{
|
||||
var properties = physicalDevice.GetFormatProperties(format);
|
||||
|
||||
var supported = tiling switch
|
||||
{
|
||||
VkImageTiling.Optimal => properties.OptimalTilingFeatures,
|
||||
VkImageTiling.Linear => properties.LinearTilingFeatures,
|
||||
_ => VkFormatFeatureFlags.None,
|
||||
};
|
||||
|
||||
if ((supported & features) == features)
|
||||
return format;
|
||||
}
|
||||
|
||||
return VkFormat.Undefined;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Find the queue family that has all of <paramref name="requiredFlags"/>, none of
|
||||
/// <paramref name="excludedFlags"/>, and the fewest extra capabilities - so a dedicated
|
||||
/// family (e.g. transfer-only, or compute without graphics) wins over the do-everything
|
||||
/// family when one exists. Returns -1 when no family qualifies.
|
||||
/// </summary>
|
||||
public static int FindQueueFamily(
|
||||
this PhysicalDevice physicalDevice,
|
||||
VkQueueFlags requiredFlags,
|
||||
VkQueueFlags excludedFlags = VkQueueFlags.None
|
||||
)
|
||||
{
|
||||
using var properties = SpanOwner<VkQueueFamilyProperties>.Allocate(
|
||||
physicalDevice.GetQueueFamilyProperties_Count()
|
||||
);
|
||||
physicalDevice.GetQueueFamilyProperties_Write(properties.Span);
|
||||
|
||||
var bestFamily = -1;
|
||||
var bestExtraFlags = int.MaxValue;
|
||||
|
||||
for (var i = 0; i < properties.Length; ++i)
|
||||
{
|
||||
var flags = properties.Span[i].QueueFlags;
|
||||
|
||||
if ((flags & requiredFlags) != requiredFlags)
|
||||
continue;
|
||||
if ((flags & excludedFlags) != 0)
|
||||
continue;
|
||||
|
||||
var extraFlags = BitOperations.PopCount(unchecked((uint)(int)(flags & ~requiredFlags)));
|
||||
if (extraFlags >= bestExtraFlags)
|
||||
continue;
|
||||
|
||||
bestFamily = i;
|
||||
bestExtraFlags = extraFlags;
|
||||
}
|
||||
|
||||
return bestFamily;
|
||||
}
|
||||
}
|
||||
137
Brutal.Vulkan.Abstractions/Extensions/QueueExtensions.cs
Normal file
137
Brutal.Vulkan.Abstractions/Extensions/QueueExtensions.cs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
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
|
||||
)
|
||||
{
|
||||
// The implementation reads WaitSemaphoreCount stage masks, so a shorter span is an out-of-bounds read
|
||||
if (waitDstStageMask.Length != waitSemaphores.Length)
|
||||
throw new ArgumentException(
|
||||
"waitDstStageMask must be the same length as waitSemaphores",
|
||||
nameof(waitDstStageMask)
|
||||
);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Submits command buffers with timeline-semaphore wait/signal values, chaining a
|
||||
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkTimelineSemaphoreSubmitInfo.html">VkTimelineSemaphoreSubmitInfo</see>
|
||||
/// onto the submit. The value spans must be the same length as their semaphore spans;
|
||||
/// entries for binary semaphores are ignored by the implementation, so leave them zero.
|
||||
/// </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="waitSemaphoreValues">Timeline values to wait for, one per wait semaphore.</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="signalSemaphoreValues">Timeline values to signal, one per signal semaphore.</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,
|
||||
ReadOnlySpan<ulong> waitSemaphoreValues,
|
||||
Span<CommandBuffer> commandBuffers,
|
||||
Span<VkSemaphore> signalSemaphores,
|
||||
ReadOnlySpan<ulong> signalSemaphoreValues,
|
||||
VkFence fence
|
||||
)
|
||||
{
|
||||
// The implementation reads WaitSemaphoreCount stage masks, so a shorter span is an out-of-bounds read
|
||||
if (waitDstStageMask.Length != waitSemaphores.Length)
|
||||
throw new ArgumentException(
|
||||
"waitDstStageMask must be the same length as waitSemaphores",
|
||||
nameof(waitDstStageMask)
|
||||
);
|
||||
if (waitSemaphoreValues.Length != waitSemaphores.Length)
|
||||
throw new ArgumentException(
|
||||
"waitSemaphoreValues must be the same length as waitSemaphores",
|
||||
nameof(waitSemaphoreValues)
|
||||
);
|
||||
if (signalSemaphoreValues.Length != signalSemaphores.Length)
|
||||
throw new ArgumentException(
|
||||
"signalSemaphoreValues must be the same length as signalSemaphores",
|
||||
nameof(signalSemaphoreValues)
|
||||
);
|
||||
|
||||
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)
|
||||
fixed (ulong* waitValuesPtr = waitSemaphoreValues)
|
||||
fixed (ulong* signalValuesPtr = signalSemaphoreValues)
|
||||
{
|
||||
var timelineInfo = new VkTimelineSemaphoreSubmitInfo
|
||||
{
|
||||
WaitSemaphoreValueCount = waitSemaphoreValues.Length,
|
||||
WaitSemaphoreValues = (nint*)waitValuesPtr,
|
||||
SignalSemaphoreValueCount = signalSemaphoreValues.Length,
|
||||
SignalSemaphoreValues = (nint*)signalValuesPtr,
|
||||
};
|
||||
|
||||
var submitInfo = new VkSubmitInfo
|
||||
{
|
||||
Next = &timelineInfo,
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue