namespace Brutal.VulkanApi.Abstractions; /// /// Functions to extend the Device class /// public static class DeviceExtensions { /// /// 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. /// /// The logical device used for creating the render pass. /// If true, a color attachment is created and sampled; otherwise, no color attachment is configured. /// If true, a depth attachment is created and sampled; otherwise, no depth attachment is configured. /// Specifies the number of samples per pixel. A value other than VkSampleCountFlags._1 indicates that multisampling is enabled. /// The format to be used for the color attachment image. /// The format to be used for the depth attachment image. /// The format to be used for the resolve attachment image when multisampling is enabled. /// A VkRenderPass object representing the configured render pass. 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 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 ); } /// /// Creates a new pipeline layout object using /// vkCreatePipelineLayout. /// /// The logical device used to create the pipeline layout. /// /// A span of handles that define the descriptor set layouts to be used in the pipeline layout. /// /// /// A span of structures specifying the push constant ranges for the pipeline layout. /// /// A VkPipelineLayout object representing the created pipeline layout. public static VkPipelineLayout CreatePipelineLayout( this Device inDevice, ReadOnlySpan setLayouts, ReadOnlySpan 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 ); } } /// /// Creates a graphics pipeline using /// vkCreateGraphicsPipelines. /// /// The logical device used for creating the graphics pipeline. /// /// A pipeline cache handle. Use VK_NULL_HANDLE if pipeline caching is disabled; otherwise, provide the handle of a valid /// pipeline cache object to enable caching during pipeline creation. /// /// /// A structure containing the parameters required to create the graphics pipeline. /// /// A VkPipeline object representing the created graphics pipeline. [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(&pipeline, 1) ); return pipeline; } /// /// Creates a compute pipeline using /// vkCreateComputePipelines. /// /// The logical device used for creating the compute pipeline. /// /// A pipeline cache handle. Use VK_NULL_HANDLE if pipeline caching is disabled; otherwise, provide the handle of a valid /// pipeline cache object to enable caching during pipeline creation. /// /// /// A structure containing the parameters required to create the compute pipeline. /// /// A VkPipeline object representing the created compute pipeline. [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(&pipeline, 1) ); return pipeline; } /// /// Query a buffer's GPU virtual address using /// vkGetBufferDeviceAddress. /// The buffer must have been created with and its memory /// allocated with . /// /// The logical device that owns the buffer. /// The buffer to query. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static VkDeviceAddress GetBufferDeviceAddress(this Device inDevice, VkBuffer inBuffer) { return inDevice.GetBufferDeviceAddress(new VkBufferDeviceAddressInfo { Buffer = inBuffer }); } /// /// Allocates a single command buffer from the specified command pool using /// vkAllocateCommandBuffers. /// /// The logical device that owns the command pool. /// A structure specifying the command pool and allocation parameters. /// A CommandBuffer object representing the allocated command buffer. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe CommandBuffer AllocateCommandBuffer(this Device device, VkCommandBufferAllocateInfo createInfo) { Span commandBufferHandles = stackalloc VkCommandBuffer[1]; createInfo.CommandBufferCount = 1; device.AllocateCommandBuffersInternal(createInfo, commandBufferHandles); return new CommandBuffer(device, commandBufferHandles[0]); } /// /// Allocates multiple command buffers from the specified command pool using /// vkAllocateCommandBuffers. /// /// The logical device that owns the command pool. /// A structure specifying the command pool and allocation parameters. /// A span of to store the allocated command buffers. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void AllocateCommandBuffers( this Device device, VkCommandBufferAllocateInfo createInfo, Span commandBuffers ) { if (commandBuffers.Length == 0) throw new ArgumentException("The command buffer span must not be empty.", nameof(commandBuffers)); Span 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]); } /// /// Allocates device memory for a buffer using /// vkAllocateMemory. /// It queries the memory requirements of the specified buffer and selects an appropriate memory type that matches the required properties. /// /// The logical device that owns the memory. /// The physical device used to determine a compatible memory type. /// The buffer for which memory is to be allocated. /// The required memory property flags that the allocated memory must satisfy. /// A VkDeviceMemory object representing the allocated memory for the buffer. 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; } /// /// Allocates device memory for an image using /// vkAllocateMemory. /// It queries the memory requirements of the specified image and selects an appropriate memory type that meets the required properties. /// /// The logical device that owns the memory. /// The physical device used to determine a compatible memory type. /// The image for which memory is to be allocated. /// The required memory property flags that the allocated memory must satisfy. /// A VkDeviceMemory object representing the allocated memory for the image. 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; } /// /// Maps device memory to a pointer of type T using vkMapMemory. /// /// The logical device that owns the memory. /// A structure specifying the memory range to map. /// A pointer to the mapped memory cast to type T. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Ptr MapMemory(this Device inDevice, in MapInfo mapInfo) where T : unmanaged { return inDevice.MapMemory(mapInfo).Cast(); } /// /// Maps device memory to a pointer of type T using vkMapMemory. /// /// The logical device that owns the memory. /// A structure specifying the memory range to map. /// A pointer to the mapped memory cast to type T. [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; } /// /// 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. /// /// The type of elements in the source span. /// The logical device that owns the destination memory. /// The source span containing the data to write. /// The VkDeviceMemory object that will receive the data. /// The zero-based byte offset from the beginning of the memory object at which to start writing. /// Reserved for future use; typically set to VkMemoryMapFlags.None. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteMemory( this Device inDevice, Span 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(inSrc.Length)); inDevice.UnmapMemory(inDstMemory); } /// /// 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. /// /// The type of elements in the source array. /// The logical device that owns the destination memory. /// The source array containing the data to write. /// The VkDeviceMemory object that will receive the data. /// The zero-based byte offset from the beginning of the memory object at which to start writing. /// Reserved for future use; typically set to VkMemoryMapFlags.None. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteMemory( this Device inDevice, ReadOnlySpan 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(inSrc.Length)); inDevice.UnmapMemory(inDstMemory); } /// /// Binds a descriptor set to a command buffer using /// vkCmdBindDescriptorSets. /// An optional dynamic offset can be provided. /// /// The command buffer to which the descriptor set will be bound. /// /// 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. /// /// The pipeline layout that defines the descriptor set bindings. /// The index of the descriptor set to bind. /// The descriptor set to be bound to the command buffer. /// /// Span of dynamic offsets to be used with the descriptor set. If no dynamic offsets are needed, pass an empty span. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void BindDescriptorSet( this CommandBuffer inCommandBuffer, VkPipelineBindPoint inPipelineBindPoint, VkPipelineLayout inLayout, int inSet, VkDescriptorSet inDescriptorSet, Span inDynamicOffsets ) { inCommandBuffer.BindDescriptorSets(inPipelineBindPoint, inLayout, inSet, [inDescriptorSet], inDynamicOffsets); } /// /// Binds any 's set (and its dynamic offsets, if it declares any) /// to a command buffer. See /// vkCmdBindDescriptorSets. /// /// The command buffer to which the descriptor set will be bound. /// The pipeline bind point the set is consumed at. /// The pipeline layout that defines the descriptor set bindings. /// The index of the descriptor set to bind. /// The wrapper whose set and dynamic offsets are bound. [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 ); } } /// /// Creates a new fence object using /// vkCreateFence. /// /// The logical device that creates the fence. /// /// Flags that control the creation and initial state of the fence. See for details. /// /// A VkFence object representing the created fence. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static VkFence CreateFence(this Device inDevice, VkFenceCreateFlags inCreateFlags, VkAllocator? allocator) { return inDevice.CreateFence(new VkFenceCreateInfo { Flags = inCreateFlags }, allocator); } /// /// Waits for a fence to become signaled using /// vkWaitForFences. /// The timeout value is adjusted to the closest allowed value by the implementation. /// /// The logical device that owns the fence. /// The fence to wait on. /// /// The timeout period in nanoseconds. The actual timeout may be longer than requested due to implementation-dependent timeout accuracy. /// /// A VkResult indicating the outcome of the wait operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static VkResult WaitForFence(this Device inDevice, VkFence inFence, nint inTimeout) { return inDevice.WaitForFences([inFence], true, inTimeout); } /// /// vkFreeCommandBuffers - Free command buffers /// /// /// /// To free command buffers, call: /// /// /// // Provided by VK_VERSION_1_0 /// void vkFreeCommandBuffers( /// VkDevice device, /// VkCommandPool commandPool, /// uint32_t commandBufferCount, /// const VkCommandBuffer* pCommandBuffers); /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void FreeCommandBuffers( this VulkanHandleWrapper handle, VkCommandPool commandPool, ReadOnlySpan pCommandBuffers ) { Span vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length]; for (var index = 0; index < pCommandBuffers.Length; index++) vkCommandBuffers[index] = pCommandBuffers[index].Handle; handle.FreeCommandBuffersInternal(commandPool, vkCommandBuffers); } /// /// vkCmdExecuteCommands - Execute a secondary command buffer from a primary command buffer /// /// /// /// Secondary command buffers must not be directly submitted to a queue. /// To record a secondary command buffer to execute as part of a primary command /// buffer, call: /// /// /// // Provided by VK_VERSION_1_0 /// void vkCmdExecuteCommands( /// VkCommandBuffer commandBuffer, /// uint32_t commandBufferCount, /// const VkCommandBuffer* pCommandBuffers); /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ExecuteCommands( this VulkanHandleWrapper handle, ReadOnlySpan pCommandBuffers ) { Span vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length]; for (var index = 0; index < pCommandBuffers.Length; index++) vkCommandBuffers[index] = pCommandBuffers[index].Handle; handle.CmdExecuteCommandsInternal(vkCommandBuffers); } }