SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
8 changed files with 768360 additions and 0 deletions

View file

@ -0,0 +1,25 @@
namespace Brutal.VulkanApi;
/// <summary>
/// Class that wraps a Command Buffer handle.
/// </summary>
public struct CommandBuffer : VulkanHandleWrapper<VkCommandBuffer, VkDevice.FunctionTable>
{
private readonly Ptr<VkDevice.FunctionTable> _pInvoke;
public CommandBuffer(Device device, VkCommandBuffer handle)
{
_pInvoke = device._pInvoke;
Handle = handle;
}
public VkCommandBuffer Handle { get; init; }
public ref VkDevice.FunctionTable PInvoke => ref _pInvoke.Value;
public bool IsNull() => Handle.IsNull();
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkCommandBuffer(CommandBuffer commandBuffer) => commandBuffer.Handle;
}

View file

@ -0,0 +1,138 @@
namespace Brutal.VulkanApi;
/// <summary>
/// Class that wraps a Vulkan Device handle.
/// </summary>
public class Device : VulkanHandleWrapper<VkDevice, VkDevice.FunctionTable>, IDisposable
{
public ref struct CreateInfo()
{
public HashSet<string> Extensions = [];
public Ptr<VkPhysicalDeviceFeatures> Features = null;
public ReadOnlySpan<VkDeviceQueueCreateInfo> QueueCreateInfos = [];
public Ptr Next = null;
public VkAllocator? Allocator = null;
}
/// <summary>
/// The physical device that this device was created from.
/// </summary>
public PhysicalDevice PhysicalDevice { get; }
// Caches a unique queue object for each queue family/index combination.
private readonly Dictionary<(int, int), Queue> _queues = new();
/// <summary>
/// The set of enabled extensions for this device
/// </summary>
public readonly HashSet<string> EnabledExtensions;
protected VkAllocator? _vkAllocator;
internal unsafe Device(PhysicalDevice physicalDevice, CreateInfo createInfo)
{
_vkAllocator = createInfo.Allocator;
EnabledExtensions = createInfo.Extensions;
// Calculate total byte count and individual lengths for each extension
Span<int> lengths = stackalloc int[createInfo.Extensions.Count];
var totalByteCount = 0;
var i = 0;
foreach (var extension in createInfo.Extensions)
{
lengths[i] = Utf8.GetByteCount(extension) + 1; // +1 for null terminator
totalByteCount += lengths[i];
i++;
}
// Allocate memory for all extension strings and their pointers
Span<byte> allExtensionBytes = stackalloc byte[totalByteCount];
var extensionPtrs = stackalloc byte*[createInfo.Extensions.Count];
var writePtr = allExtensionBytes;
// Fill the pointers and copy the strings into the allocated memory
i = 0;
foreach (var ext in createInfo.Extensions)
{
if (!Utf8.TryGetBytes(ext, writePtr, out var bytes))
throw new Exception("Failed to encode extension name to UTF-8");
extensionPtrs[i] = writePtr.AsPointer();
writePtr[bytes] = 0; // Null-terminate the string
writePtr = writePtr[(bytes + 1)..];
i++;
}
var vkCreateInfo = new VkDeviceCreateInfo
{
EnabledExtensionCount = createInfo.Extensions.Count,
QueueCreateInfoCount = createInfo.QueueCreateInfos.Length,
EnabledFeatures = createInfo.Features,
Next = createInfo.Next,
ppEnabledExtensionNames = extensionPtrs,
};
fixed (VkDeviceQueueCreateInfo* queueCreateInfosPtr = createInfo.QueueCreateInfos)
{
vkCreateInfo.QueueCreateInfos = queueCreateInfosPtr;
Handle = physicalDevice.CreateDeviceInternal(vkCreateInfo, _vkAllocator);
}
PhysicalDevice = physicalDevice;
var getDeviceProcAddr = physicalDevice.Instance.GetProcAddr("vkGetDeviceProcAddr"u8);
_pInvoke = Mem.AllocAndCopy(new VkDevice.FunctionTable(Handle, (VkGetDeviceProcAddr)getDeviceProcAddr));
}
/// <summary>
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkGetDeviceQueue.html">vkGetDeviceQueue</see> - Get a queue from a device
/// </summary>
/// <param name="queueFamilyIndex">is the index of the queue family to which the queue belongs.</param>
/// <param name="queueIndex">is the index within this queue family of the queue to retrieve.</param>
/// <returns>Queue object wrapping a QueueHandle</returns>
public Queue GetQueue(int queueFamilyIndex, int queueIndex)
{
var tuple = (queueFamilyIndex, queueIndex);
if (!_queues.TryGetValue(tuple, out var queue))
{
queue = new Queue(this, queueFamilyIndex, queueIndex);
_queues.Add(tuple, queue);
}
return queue;
}
// Detection only, never touch native handles from the finalizer. Mirrors the Instance warning.
~Device()
{
try
{
Vulkan.Log.Warning("Device was not disposed. Native resources leaked; call Dispose().");
}
catch
{
// Logging may be torn down during process exit
}
}
public virtual void Dispose()
{
this.DestroyDeviceInternal(_vkAllocator);
if (_pInvoke.IsNotNull())
Mem.Free(_pInvoke);
GC.SuppressFinalize(this);
}
internal readonly Ptr<VkDevice.FunctionTable> _pInvoke;
public VkDevice Handle { get; init; }
public ref VkDevice.FunctionTable PInvoke => ref _pInvoke.Value;
public bool IsNull() => Handle.IsNull();
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkDevice(Device device) => device.Handle;
}

View file

@ -0,0 +1,169 @@
namespace Brutal.VulkanApi;
public struct VkEmptyTable { }
/// <summary>
/// Class that wraps a Vulkan Instance handle.
/// </summary>
public class Instance : VulkanHandleWrapper<VkInstance, VkInstance.FunctionTable>, IDisposable
{
public unsafe ref struct CreateInfo
{
public VkApplicationInfo AppInfo;
public VkInstanceCreateFlags Flags;
public HashSet<string> EnabledExtensions;
public HashSet<string> EnabledLayers;
public void* Next;
public VkAllocator? Allocator;
}
public readonly PhysicalDevice[] PhysicalDevices;
internal unsafe Instance(CreateInfo createInfo)
{
var instanceCreateInfo = new VkInstanceCreateInfo
{
ApplicationInfo = &createInfo.AppInfo,
Flags = createInfo.Flags,
EnabledExtensionCount = createInfo.EnabledExtensions.Count,
EnabledLayerCount = createInfo.EnabledLayers.Count,
Next = createInfo.Next,
};
_enabledExtensions = createInfo.EnabledExtensions;
_enabledLayers = createInfo.EnabledLayers;
var totalByteCount = 0;
Span<int> lengths = stackalloc int[createInfo.EnabledExtensions.Count + createInfo.EnabledLayers.Count];
var ptrs = stackalloc byte*[createInfo.EnabledExtensions.Count + createInfo.EnabledLayers.Count];
instanceCreateInfo.ppEnabledExtensionNames = ptrs;
instanceCreateInfo.ppEnabledLayerNames = ptrs + createInfo.EnabledExtensions.Count;
// Calculate total byte count and individual lengths for each extension and layer
var i = 0;
foreach (var extension in createInfo.EnabledExtensions)
{
lengths[i] = Utf8.GetByteCount(extension) + 1; // +1 for null terminator
totalByteCount += lengths[i];
i++;
}
foreach (var layer in createInfo.EnabledLayers)
{
lengths[i] = Utf8.GetByteCount(layer) + 1; // +1 for null terminator
totalByteCount += lengths[i];
i++;
}
Span<byte> allBytes = stackalloc byte[totalByteCount];
// Allocate memory for all extension strings and their pointers
var writePtr = allBytes;
// Fill the pointers and copy the strings into the allocated memory
i = 0;
foreach (var extension in createInfo.EnabledExtensions)
{
if (!Utf8.TryGetBytes(extension, writePtr, out var bytes))
throw new Exception("Failed to encode extension name to UTF-8");
ptrs[i] = writePtr.AsPointer();
writePtr[bytes] = 0; // Null-terminate the string
writePtr = writePtr[(bytes + 1)..];
i++;
}
foreach (var layer in createInfo.EnabledLayers)
{
if (!Utf8.TryGetBytes(layer, writePtr, out var bytes))
throw new Exception("Failed to encode layer name to UTF-8");
ptrs[i] = writePtr.AsPointer();
writePtr[bytes] = 0; // Null-terminate the string
writePtr = writePtr[(bytes + 1)..];
i++;
}
Handle = Vulkan.CreateInstanceInternal(instanceCreateInfo, createInfo.Allocator);
_pInvoke = Mem.AllocAndCopy(new VkInstance.FunctionTable(Handle, Vulkan.GetInstanceProcAddr));
_allocator = createInfo.Allocator;
PhysicalDevices = new PhysicalDevice[this.EnumeratePhysicalDevicesInternal_Count()];
fixed (VkPhysicalDevice* physicalDevices = stackalloc VkPhysicalDevice[PhysicalDevices.Length])
{
this.EnumeratePhysicalDevicesInternal_Write(
new Span<VkPhysicalDevice>(physicalDevices, PhysicalDevices.Length)
);
for (var pdIndex = 0; pdIndex < PhysicalDevices.Length; pdIndex++)
PhysicalDevices[pdIndex] = new PhysicalDevice(this, physicalDevices[pdIndex]);
}
}
// Warn about the missed Dispose() and best-effort free the native handle, guarding both since a
// finalizer must never throw and logging or native teardown may already be gone at process exit.
~Instance()
{
try
{
Vulkan.Log.Warning(
"Instance was not disposed. Freeing native resources from the finalizer; call Dispose()."
);
}
catch
{
// Logging may be torn down during process exit
}
try
{
Dispose(fromFinalizer: true);
}
catch
{
// Best-effort cleanup; never let it escape the finalizer
}
}
public bool IsNull() => Handle.IsNull();
/// <summary>
/// Returns true if the given extension is enabled on this instance.
/// </summary>
/// <param name="inExtensionName"></param>
/// <returns></returns>
public bool IsExtensionEnabled(string inExtensionName)
{
return _enabledExtensions.Contains(inExtensionName);
}
// Cached lookups for extensions which were enabled on instance creation
private readonly HashSet<string> _enabledExtensions;
// Cached lookups for layers which were enabled on instance creation
private readonly HashSet<string> _enabledLayers;
private readonly VkAllocator? _allocator;
public void Dispose() => Dispose(fromFinalizer: false);
private void Dispose(bool fromFinalizer)
{
// Skip the native destroy from the finalizer with a custom allocator, its callbacks may already be freed
if (!(fromFinalizer && _allocator != null))
this.DestroyInstanceInternal(_allocator);
if (_pInvoke.IsNotNull())
Mem.Free(_pInvoke);
GC.SuppressFinalize(this);
}
private readonly Ptr<VkInstance.FunctionTable> _pInvoke;
public VkInstance Handle { get; init; }
public ref VkInstance.FunctionTable PInvoke => ref _pInvoke.Value;
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkInstance(Instance instance) => instance.Handle;
}

View file

@ -0,0 +1,214 @@
using System.Numerics;
namespace Brutal.VulkanApi;
/// <summary>
/// Class that wraps a Vulkan PhysicalDevice handle.
/// </summary>
public class PhysicalDevice : VulkanHandleWrapper<VkPhysicalDevice, VkInstance.FunctionTable>
{
/// <summary>
/// The Instance that this physical device was created from.
/// </summary>
public Instance Instance { get; }
/// <summary>
/// Cached PhysicalDevice ExtensionNames.
/// </summary>
/// <remarks>
/// Prefer <see cref="SupportsExtension(ReadOnlySpan{byte})"/> for lookups: this property
/// materializes a managed string per supported extension (200+ on modern drivers), whereas
/// the byte-span lookup avoids all string allocation.
/// </remarks>
public HashSet<string> ExtensionNames
{
get
{
if (_extensionNames == null)
{
var utf8 = ExtensionNamesUtf8;
_extensionNames = new HashSet<string>(utf8.Length);
foreach (var name in utf8)
_extensionNames.Add(Utf8.GetString(name));
}
return _extensionNames;
}
}
private HashSet<string>? _extensionNames;
/// <summary>
/// Supported extension names as raw UTF-8 bytes (trimmed to the null terminator), enumerated
/// once on first access. Backs the allocation-free extension lookups.
/// </summary>
private byte[][] ExtensionNamesUtf8
{
get
{
if (_extensionNamesUtf8 == null)
{
ReadOnlySpan<VkExtensionProperties> extensionProperties =
stackalloc VkExtensionProperties[this.EnumerateDeviceExtensionProperties_Count([])];
var result = this.EnumerateDeviceExtensionProperties_Write([], extensionProperties);
if (result != VkResult.Success)
throw new InvalidOperationException("Failed to enumerate device extension properties: " + result);
var names = new byte[extensionProperties.Length][];
for (var i = 0; i < extensionProperties.Length; i++)
{
unsafe
{
fixed (byte* name = extensionProperties[i].ExtensionName)
names[i] = Utf8.GetNullTerminatedSpan(name).ToArray();
}
}
_extensionNamesUtf8 = names;
}
return _extensionNamesUtf8;
}
}
private byte[][]? _extensionNamesUtf8;
internal PhysicalDevice(Instance inInstance, VkPhysicalDevice inHandle)
{
Handle = inHandle;
Instance = inInstance;
}
/// <summary>
/// Naively returns the index of the first queue family which has the given VkQueueFlag, or -1 if no family is found
/// </summary>
public int GetFirstQueueFamilyWithFlag(VkQueueFlags flag)
{
using var properties = SpanOwner<VkQueueFamilyProperties>.Allocate(this.GetQueueFamilyProperties_Count());
this.GetQueueFamilyProperties_Write(properties.Span);
for (var i = 0; i < properties.Length; ++i)
if (properties.Span[i].QueueFlags.HasFlag(flag))
return i;
return -1;
}
/// <summary>
/// Searches for the first memory type index that satisfies both the specified memory type filter and required property flags.
/// </summary>
/// <param name="memoryTypeFilter">A bitmask representing the candidate memory types.</param>
/// <param name="requiredProperties">The memory property flags that must be present.</param>
/// <returns>The index of the first suitable memory type.</returns>
/// <exception cref="Exception">Thrown if no memory type meets the required criteria.</exception>
public int FindMemoryType(int memoryTypeFilter, VkMemoryPropertyFlags requiredProperties)
{
var memoryProperties = this.GetMemoryProperties();
var memoryTypeCount = memoryProperties.MemoryTypeCount;
for (var i = 0; i < memoryTypeCount; i++)
{
var memoryTypeBits = 1 << i;
var isRequiredMemoryType = (memoryTypeFilter & memoryTypeBits) != 0;
if (!isRequiredMemoryType)
continue;
var properties = memoryProperties.MemoryTypes[i].PropertyFlags;
var hasRequiredProperties = (properties & requiredProperties) == requiredProperties;
if (hasRequiredProperties)
return i;
}
throw new Exception("failed to find suitable memory type!");
}
/// <summary>
/// Searches for the first memory type index that satisfies both the specified memory type filter and required property flags.
/// </summary>
/// <param name="memoryTypeFilter">A bitmask representing the candidate memory types.</param>
/// <param name="requiredProperties">The memory property flags that must be present.</param>
/// <param name="preferredProperties">Memory property flags that are preferred, and will be prioritized</param>
/// <returns>The index of the first suitable memory type.</returns>
/// <exception cref="Exception">Thrown if no memory type meets the required criteria.</exception>
public int FindMemoryType(
int memoryTypeFilter,
VkMemoryPropertyFlags requiredProperties,
VkMemoryPropertyFlags preferredProperties
)
{
var memoryProperties = this.GetMemoryProperties();
var memoryTypeCount = memoryProperties.MemoryTypeCount;
int bestHits = 0;
int bestCandidate = -1;
for (var i = 0; i < memoryTypeCount; i++)
{
var memoryTypeBits = 1 << i;
var isRequiredMemoryType = (memoryTypeFilter & memoryTypeBits) != 0;
if (!isRequiredMemoryType)
continue;
var properties = memoryProperties.MemoryTypes[i].PropertyFlags;
var hasRequiredProperties = (properties & requiredProperties) == requiredProperties;
if (!hasRequiredProperties)
continue;
var prefMatch = (properties & preferredProperties);
// perfect candidate
if (prefMatch == preferredProperties)
return i;
// sort imperfect candidate by most preferredProperties flag hits
int hits = BitOperations.PopCount((ulong)prefMatch);
if (hits > bestHits)
{
bestCandidate = i;
bestHits = hits;
}
}
if (bestCandidate == -1)
throw new Exception("failed to find suitable memory type!");
return bestCandidate;
}
/// <summary>
/// Determines if the physical device supports a given extension, without allocating a string.
/// </summary>
/// <param name="utf8Name">The extension name as UTF-8 bytes, e.g. a <c>"VK_KHR_swapchain"u8</c> literal.</param>
public bool SupportsExtension(ReadOnlySpan<byte> utf8Name)
{
foreach (var name in ExtensionNamesUtf8)
if (utf8Name.SequenceEqual(name))
return true;
return false;
}
/// <summary>
/// Determines if the physical device supports a given extension.
/// </summary>
/// <remarks>
/// Answers from <see cref="ExtensionNames"/> so it stays consistent with that mutable set and
/// with the pre-existing behaviour. This materializes the managed string set on first use;
/// prefer <see cref="SupportsExtension(ReadOnlySpan{byte})"/> on hot paths to avoid the allocation.
/// </remarks>
public bool SupportsExtension(string extension)
{
return ExtensionNames.Contains(extension);
}
/// <summary>
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateDevice.html">vkCreateDevice</see> - Create a new device instance
/// </summary>
/// <returns>Device object wrapping a DeviceHandle</returns>
public Device CreateDevice(Device.CreateInfo createInfo)
{
return new Device(this, createInfo);
}
public VkPhysicalDevice Handle { get; init; }
public ref VkInstance.FunctionTable PInvoke => ref Instance.PInvoke;
public bool IsNull() => Handle.IsNull();
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkPhysicalDevice(PhysicalDevice physicalDevice) => physicalDevice.Handle;
}

View file

@ -0,0 +1,106 @@
namespace Brutal.VulkanApi;
/// <summary>
/// Class that wraps a Vulkan Queue handle.
/// </summary>
public class Queue : VulkanHandleWrapper<VkQueue, VkDevice.FunctionTable>
{
/// <summary>
/// The family index of this queue.
/// </summary>
public int Family { get; }
/// <summary>
/// The index of this queue within the family.
/// </summary>
public int Index { get; }
public Device Device { get; init; }
internal Queue(Device device, int family, int index)
{
Handle = device.GetQueueInternal(family, index);
Family = family;
Index = index;
Device = device;
}
public VkQueue Handle { get; init; }
public ref VkDevice.FunctionTable PInvoke => ref Device.PInvoke;
private VulkanHandleWrapper<VkQueue, VkDevice.FunctionTable> AsWrapper() => this;
public void WaitIdle()
{
lock (_lock)
{
AsWrapper().WaitIdleInternal();
}
}
public void BindSparse(ReadOnlySpan<VkBindSparseInfo> inBindInfo, VkFence inFence)
{
lock (_lock)
{
AsWrapper().BindSparseInternal(inBindInfo, inFence);
}
}
public void BeginDebugUtilsLabelEXT(VkDebugUtilsLabelEXT inLabelInfo)
{
lock (_lock)
{
AsWrapper().BeginDebugUtilsLabelEXTInternal(inLabelInfo);
}
}
public void EndDebugUtilsLabelEXT()
{
lock (_lock)
{
AsWrapper().EndDebugUtilsLabelEXTInternal();
}
}
public void InsertDebugUtilsLabelEXT(VkDebugUtilsLabelEXT inLabelInfo)
{
lock (_lock)
{
AsWrapper().InsertDebugUtilsLabelEXTInternal(inLabelInfo);
}
}
public void Submit(Span<VkSubmitInfo> inSubmits, VkFence inFence)
{
lock (_lock)
{
AsWrapper().SubmitInternal(inSubmits, inFence);
}
}
public void Submit2(Span<VkSubmitInfo2> inSubmits, VkFence inFence)
{
lock (_lock)
{
AsWrapper().Submit2Internal(inSubmits, inFence);
}
}
public VkResult PresentKHR(VkPresentInfoKHR inPresentInfo)
{
lock (_lock)
{
return AsWrapper().PresentKHRInternal(inPresentInfo);
}
}
// Lock to ensure that only one thread is submitting at a time.
private readonly Lock _lock = new();
public bool IsNull() => Handle.IsNull();
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkQueue(Queue queue) => queue.Handle;
}

View file

@ -0,0 +1,13 @@
namespace Brutal.VulkanApi;
public class VkAllocator(VkAllocationCallbacks callbacks) : IDisposable
{
PtrOwner<VkAllocationCallbacks> ptr = new(callbacks);
public static unsafe implicit operator VkAllocationCallbacks*(VkAllocator? allocator) => allocator?.ptr ?? null;
public void Dispose()
{
ptr.Dispose();
}
}

View file

@ -0,0 +1,12 @@
namespace Brutal.VulkanApi;
public class VkResultError : Exception
{
public VkResult Result { get; }
public VkResultError(VkResult result, string message)
: base(message)
{
Result = result;
}
}

View file

@ -0,0 +1,9 @@
namespace Brutal.VulkanApi;
public interface VulkanHandleWrapper<THandleType, TFunctionTable> : IVulkanHandle
where THandleType : unmanaged, IVulkanHandle
where TFunctionTable : unmanaged
{
internal THandleType Handle { get; init; }
public ref TFunctionTable PInvoke { get; }
}