Files
Neutron/src/GamePort/Rendering/Vulkan/VulkanRenderer.cs
T

640 lines
43 KiB
C#

using System.Numerics;
using System.Runtime.InteropServices;
using GamePort.Assets;
using GamePort.Platform;
using Silk.NET.Vulkan;
using Silk.NET.Vulkan.Extensions.KHR;
using Silk.NET.Vulkan.Extensions.EXT;
using Buffer = Silk.NET.Vulkan.Buffer;
using Image = Silk.NET.Vulkan.Image;
using Semaphore = Silk.NET.Vulkan.Semaphore;
namespace GamePort.Rendering.Vulkan;
/// <summary>A deliberately small, synchronous renderer for recovering the original scenes.</summary>
public sealed unsafe class VulkanRenderer : IDisposable
{
private readonly Vk vk=Vk.GetApi();
private Instance instance;
private PhysicalDevice physical;
private Device device;
private Queue queue;
private uint queueFamily;
private CommandPool pool;
private CommandBuffer command;
private Buffer vertexBuffer,indexBuffer,readback;
private DeviceMemory vertexMemory,indexMemory,readbackMemory;
private Image color,depth;
private DeviceMemory colorMemory,depthMemory;
private ImageView colorView,depthView;
private RenderPass renderPass;
private Framebuffer framebuffer;
private Pipeline pipeline,overlayPipeline,alphaPipeline,additivePipeline,overlayAlphaPipeline,overlayAdditivePipeline;
private PipelineLayout pipelineLayout;
private DescriptorSetLayout descriptorLayout;
private DescriptorPool descriptorPool;
private Sampler sampler;
private readonly List<Texture> textures=[];
private readonly Dictionary<int,DescriptorSet> descriptors=[];
private Mesh mesh;
private readonly nint window;
private SurfaceKHR surface;
private KhrSurface? surfaceApi;
private KhrSwapchain? swapApi;
private SwapchainKHR swapchain;
private Image[] swapImages=[];
private ExtDebugUtils? debugApi;
private DebugUtilsMessengerEXT messenger;
private readonly DebugUtilsMessengerCallbackFunctionEXT debugCallback;
private Semaphore acquired,finished;
private uint width,height;
public string DeviceName { get; private set; }="";
public int ValidationErrors { get; private set; }
public uint Width=>width;
public uint Height=>height;
public int SceneRevision { get; private set; }
public RendererIdentity Identity => new(unchecked((ulong)instance.Handle), unchecked((ulong)device.Handle),
surface.Handle, swapchain.Handle, pipeline.Handle, pipelineLayout.Handle, descriptorLayout.Handle);
private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View);
private sealed record SceneResources(Mesh Mesh, Buffer VertexBuffer, DeviceMemory VertexMemory,
Buffer IndexBuffer, DeviceMemory IndexMemory, DescriptorPool DescriptorPool, Sampler Sampler,
Texture[] Textures, KeyValuePair<int,DescriptorSet>[] Descriptors);
private static void Check(Result result,string operation)
{if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");}
public VulkanRenderer(Mesh mesh,PngImage texture,uint width=960,uint height=720,nint window=0,bool validation=true)
{
this.mesh=mesh;this.width=width;this.height=height;this.window=window;
debugCallback=OnValidation;
try
{
ValidateScene(mesh,texture);
CreateInstance(validation);
if(window!=0)
{
if(!Sdl.SDL_Vulkan_CreateSurface(window,instance.Handle,null,out var handle))throw new InvalidOperationException(Sdl.Error);
surface=new SurfaceKHR(handle);
if(!vk.TryGetInstanceExtension(instance,out surfaceApi))throw new NotSupportedException("VK_KHR_surface unavailable.");
}
CreateDevice();
var poolInfo=new CommandPoolCreateInfo{SType=StructureType.CommandPoolCreateInfo,QueueFamilyIndex=queueFamily,Flags=CommandPoolCreateFlags.ResetCommandBufferBit};
Check(vk.CreateCommandPool(device,&poolInfo,null,out pool),"CreateCommandPool");
var allocation=new CommandBufferAllocateInfo{SType=StructureType.CommandBufferAllocateInfo,CommandPool=pool,Level=CommandBufferLevel.Primary,CommandBufferCount=1};
Check(vk.AllocateCommandBuffers(device,&allocation,out command),"AllocateCommandBuffers");
UploadBuffers();
CreateDescriptors(texture);
CreateRenderPass();
CreatePipeline();
if(window!=0)CreateSwapchain();
CreateTarget();
SceneRevision=1;
}
catch{Dispose();throw;}
}
/// <summary>
/// Replace only scene buffers/textures/descriptors. The renderer, SDL surface,
/// pipelines, swapchain and current render target remain alive. Staging keeps
/// the previous scene usable if allocation/upload of the replacement fails.
/// </summary>
public void ReplaceScene(Mesh replacement,PngImage fallback)
{
ObjectDisposedException.ThrowIf(device.Handle==0,this);
ValidateScene(replacement,fallback);
Check(vk.DeviceWaitIdle(device),"ReplaceSceneWaitIdle");
var previous=DetachScene();
mesh=replacement;
try
{
UploadBuffers();
CreateDescriptors(fallback);
}
catch
{
vk.DeviceWaitIdle(device);
DestroySceneResources();
RestoreScene(previous);
throw;
}
DestroySceneResources(previous);
SceneRevision++;
}
private static void ValidateScene(Mesh mesh,PngImage fallback)
{
ArgumentNullException.ThrowIfNull(mesh);
ArgumentNullException.ThrowIfNull(fallback);
if(mesh.Vertices.Length==0 || mesh.Indices.Length==0 || mesh.Indices.Length%3!=0
|| mesh.Indices.Any(i=>i>=mesh.Vertices.Length))
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
ValidateDrawMaterials(mesh.Draws);
ValidateTexture(fallback);
foreach(var image in mesh.Textures.Values)ValidateTexture(image);
static void ValidateTexture(PngImage image)
{
ArgumentNullException.ThrowIfNull(image);
if(image.Width is 0 or >8192 || image.Height is 0 or >8192
|| (long)image.Width*image.Height*4!=image.Rgba.LongLength)
throw new ArgumentException("Scene texture has invalid dimensions or RGBA length.",nameof(image));
}
}
private static void ValidateDrawMaterials(MeshDraw[] draws)
{
foreach(var draw in draws)
{
if(!float.IsFinite(draw.Opacity) || draw.Opacity<0 || draw.Opacity>1)
throw new ArgumentException("Draw opacity must be finite and between zero and one.",nameof(draws));
if(draw.Blend is not (MeshBlend.Opaque or MeshBlend.Alpha or MeshBlend.Additive))
throw new ArgumentException("Draw blend mode is invalid.",nameof(draws));
}
}
private SceneResources DetachScene()
{
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
descriptorPool,sampler,textures.ToArray(),descriptors.ToArray());
vertexBuffer=default;vertexMemory=default;indexBuffer=default;indexMemory=default;
descriptorPool=default;sampler=default;textures.Clear();descriptors.Clear();
return scene;
}
private void RestoreScene(SceneResources scene)
{
mesh=scene.Mesh;
vertexBuffer=scene.VertexBuffer;vertexMemory=scene.VertexMemory;
indexBuffer=scene.IndexBuffer;indexMemory=scene.IndexMemory;
descriptorPool=scene.DescriptorPool;sampler=scene.Sampler;
textures.AddRange(scene.Textures);
foreach(var entry in scene.Descriptors)descriptors.Add(entry.Key,entry.Value);
}
private void DestroySceneResources() => DestroySceneResources(DetachScene());
private void DestroySceneResources(SceneResources scene)
{
if(scene.DescriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,scene.DescriptorPool,null);
if(scene.Sampler.Handle!=0)vk.DestroySampler(device,scene.Sampler,null);
foreach(var texture in scene.Textures)
{
vk.DestroyImageView(device,texture.View,null);
vk.DestroyImage(device,texture.Image,null);
vk.FreeMemory(device,texture.Memory,null);
}
if(scene.VertexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.VertexBuffer,null);
if(scene.VertexMemory.Handle!=0)vk.FreeMemory(device,scene.VertexMemory,null);
if(scene.IndexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.IndexBuffer,null);
if(scene.IndexMemory.Handle!=0)vk.FreeMemory(device,scene.IndexMemory,null);
}
private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user)
{
if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++;
Console.Error.WriteLine($"Vulkan {severity}: {Marshal.PtrToStringUTF8((nint)data->PMessage)}");
return Vk.False;
}
private void CreateInstance(bool validation)
{
uint n=0;Check(vk.EnumerateInstanceLayerProperties(&n,null),"EnumerateInstanceLayers");
var layers=new LayerProperties[n];
fixed(LayerProperties* p=layers)Check(vk.EnumerateInstanceLayerProperties(&n,p),"EnumerateInstanceLayers");
bool hasLayer=false;
foreach(var layer in layers){var l=layer;if(Marshal.PtrToStringUTF8((nint)l.LayerName)=="VK_LAYER_KHRONOS_validation")hasLayer=true;}
var names=new List<string>();
if(window!=0)
{
var extensions=Sdl.SDL_Vulkan_GetInstanceExtensions(out var count);
if(extensions==null)throw new InvalidOperationException(Sdl.Error);
for(var i=0;i<count;i++)names.Add(Marshal.PtrToStringUTF8((nint)extensions[i])!);
}
validation &= hasLayer;
if(validation)names.Add(ExtDebugUtils.ExtensionName);
Console.WriteLine($"Vulkan validation: {(validation?"enabled":"unavailable or disabled")}");
var native=names.Select(s=>Marshal.StringToCoTaskMemUTF8(s)).ToArray();
var layerName=Marshal.StringToCoTaskMemUTF8("VK_LAYER_KHRONOS_validation");
try
{
var app=new ApplicationInfo{SType=StructureType.ApplicationInfo,ApiVersion=Vk.Version13};
fixed(nint* p=native)
{
var info=new InstanceCreateInfo{SType=StructureType.InstanceCreateInfo,PApplicationInfo=&app,EnabledExtensionCount=(uint)native.Length,PpEnabledExtensionNames=(byte**)p,
EnabledLayerCount=validation?1u:0u,PpEnabledLayerNames=(byte**)&layerName};
Check(vk.CreateInstance(&info,null,out instance),"CreateInstance");
}
if(validation && vk.TryGetInstanceExtension(instance,out debugApi))
{
var debugInfo=new DebugUtilsMessengerCreateInfoEXT{SType=StructureType.DebugUtilsMessengerCreateInfoExt,
MessageSeverity=DebugUtilsMessageSeverityFlagsEXT.WarningBitExt|DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
MessageType=DebugUtilsMessageTypeFlagsEXT.GeneralBitExt|DebugUtilsMessageTypeFlagsEXT.ValidationBitExt|DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
PfnUserCallback=debugCallback};
Check(debugApi!.CreateDebugUtilsMessenger(instance,&debugInfo,null,out messenger),"CreateDebugMessenger");
}
}
finally{foreach(var p in native)Marshal.FreeCoTaskMem(p);Marshal.FreeCoTaskMem(layerName);}
}
private void CreateDevice()
{
foreach(var gpu in vk.GetPhysicalDevices(instance))
{
vk.GetPhysicalDeviceProperties(gpu,out var properties);
if(properties.ApiVersion<Vk.Version13)continue;
uint count=0;vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,null);
var families=new QueueFamilyProperties[count];
fixed(QueueFamilyProperties* p=families)vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,p);
for(uint f=0;f<count;f++)
{
if((families[f].QueueFlags&QueueFlags.GraphicsBit)==0)continue;
if(window!=0){Check(surfaceApi!.GetPhysicalDeviceSurfaceSupport(gpu,f,surface,out var supported),"SurfaceSupport");if(!supported)continue;}
physical=gpu;queueFamily=f;DeviceName=Marshal.PtrToStringUTF8((nint)properties.DeviceName)!;break;
}
if(physical.Handle!=0)break;
}
if(physical.Handle==0)throw new NotSupportedException("A Vulkan 1.3 graphics/presentation device is required.");
float priority=1;
var queueInfo=new DeviceQueueCreateInfo{SType=StructureType.DeviceQueueCreateInfo,QueueFamilyIndex=queueFamily,QueueCount=1,PQueuePriorities=&priority};
var name=Marshal.StringToCoTaskMemUTF8(KhrSwapchain.ExtensionName);
try
{
var info=new DeviceCreateInfo{SType=StructureType.DeviceCreateInfo,QueueCreateInfoCount=1,PQueueCreateInfos=&queueInfo,EnabledExtensionCount=window!=0?1u:0u,PpEnabledExtensionNames=(byte**)&name};
Check(vk.CreateDevice(physical,&info,null,out device),"CreateDevice");
}
finally{Marshal.FreeCoTaskMem(name);}
vk.GetDeviceQueue(device,queueFamily,0,out queue);
if(window!=0)
{
if(!vk.TryGetDeviceExtension(instance,device,out swapApi))throw new NotSupportedException("VK_KHR_swapchain unavailable.");
var si=new SemaphoreCreateInfo{SType=StructureType.SemaphoreCreateInfo};
Check(vk.CreateSemaphore(device,&si,null,out acquired),"CreateSemaphore");
Check(vk.CreateSemaphore(device,&si,null,out finished),"CreateSemaphore");
}
Console.WriteLine($"Vulkan device: {DeviceName}");
}
private uint MemoryType(uint allowed,MemoryPropertyFlags flags)
{
vk.GetPhysicalDeviceMemoryProperties(physical,out var memory);
for(uint i=0;i<memory.MemoryTypeCount;i++)if((allowed&(1u<<(int)i))!=0 && (memory.MemoryTypes[(int)i].PropertyFlags&flags)==flags)return i;
throw new NotSupportedException($"No memory type for {flags}.");
}
private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory)
{
buffer=default;memory=default;
try
{
var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive};
Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer");
vk.GetBufferMemoryRequirements(device,buffer,out var requirements);
var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)};
Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory");
Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory");
}
catch
{
if(buffer.Handle!=0)vk.DestroyBuffer(device,buffer,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
buffer=default;memory=default;
throw;
}
}
private void UploadBuffers()
{
var vertexBytes=MemoryMarshal.AsBytes(mesh.Vertices.AsSpan());
MakeBuffer((ulong)vertexBytes.Length,BufferUsageFlags.VertexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out vertexBuffer,out vertexMemory);
CopyToMemory(vertexMemory,vertexBytes);
var indexBytes=MemoryMarshal.AsBytes(mesh.Indices.AsSpan());
MakeBuffer((ulong)indexBytes.Length,BufferUsageFlags.IndexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out indexBuffer,out indexMemory);
CopyToMemory(indexMemory,indexBytes);
}
public void UpdateVertices(ReadOnlySpan<MeshVertex> vertices)
{
if(vertices.Length!=mesh.Vertices.Length)throw new ArgumentException("Vertex count must match the uploaded mesh.");
// Frames are completed synchronously; host coherent memory is safe to update here.
CopyToMemory(vertexMemory,MemoryMarshal.AsBytes(vertices));
}
private void CopyToMemory(DeviceMemory memory,ReadOnlySpan<byte> bytes)
{
void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory");
try{bytes.CopyTo(new Span<byte>(data,bytes.Length));}
finally{vk.UnmapMemory(device,memory);}
}
private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view)
{
image=default;memory=default;view=default;
try
{
var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined};
Check(vk.CreateImage(device,&info,null,out image),"CreateImage");
vk.GetImageMemoryRequirements(device,image,out var req);
var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)};
Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory");
var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)};
Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView");
}
catch
{
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
if(image.Handle!=0)vk.DestroyImage(device,image,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
image=default;memory=default;view=default;
throw;
}
}
private void Begin()
{
Check(vk.ResetCommandBuffer(command,0),"ResetCommandBuffer");
var info=new CommandBufferBeginInfo{SType=StructureType.CommandBufferBeginInfo,Flags=CommandBufferUsageFlags.OneTimeSubmitBit};
Check(vk.BeginCommandBuffer(command,&info),"BeginCommandBuffer");
}
private void Submit()
{
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;
var info=new SubmitInfo{SType=StructureType.SubmitInfo,CommandBufferCount=1,PCommandBuffers=&cmd};
Check(vk.QueueSubmit(queue,1,&info,default),"QueueSubmit");Check(vk.QueueWaitIdle(queue),"QueueWaitIdle");
}
private void Barrier(Image image,ImageLayout oldLayout,ImageLayout newLayout,AccessFlags source,AccessFlags destination,PipelineStageFlags srcStage,PipelineStageFlags dstStage)
{
var barrier=new ImageMemoryBarrier{SType=StructureType.ImageMemoryBarrier,OldLayout=oldLayout,NewLayout=newLayout,SrcAccessMask=source,DstAccessMask=destination,SrcQueueFamilyIndex=Vk.QueueFamilyIgnored,DstQueueFamilyIndex=Vk.QueueFamilyIgnored,Image=image,SubresourceRange=new ImageSubresourceRange(ImageAspectFlags.ColorBit,0,1,0,1)};
vk.CmdPipelineBarrier(command,srcStage,dstStage,0,0,null,0,null,1,&barrier);
}
private Texture UploadTexture(PngImage image)
{
Buffer staging=default;DeviceMemory memory=default;
Image texture=default;DeviceMemory textureMemory=default;ImageView view=default;
try
{
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out staging,out memory);
CopyToMemory(memory,image.Rgba);
MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out texture,out textureMemory,out view);
Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)};
vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,&copy);
Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit();
var result=new Texture(texture,textureMemory,view);
textures.Add(result);
texture=default;textureMemory=default;view=default;
return result;
}
finally
{
if(staging.Handle!=0)vk.DestroyBuffer(device,staging,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
if(texture.Handle!=0)vk.DestroyImage(device,texture,null);
if(textureMemory.Handle!=0)vk.FreeMemory(device,textureMemory,null);
}
}
private void CreateDescriptors(PngImage fallback)
{
if(descriptorLayout.Handle==0)
{
var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit};
var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding};
Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout");
}
var count=(uint)mesh.Textures.Count+1;
var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count);
var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size};
Check(vk.CreateDescriptorPool(device,&poolInfo,null,out descriptorPool),"CreateDescriptorPool");
var samplerInfo=new SamplerCreateInfo{SType=StructureType.SamplerCreateInfo,MagFilter=Filter.Linear,MinFilter=Filter.Linear,MipmapMode=SamplerMipmapMode.Nearest,AddressModeU=SamplerAddressMode.Repeat,AddressModeV=SamplerAddressMode.Repeat,AddressModeW=SamplerAddressMode.Repeat,MaxLod=0};
Check(vk.CreateSampler(device,&samplerInfo,null,out sampler),"CreateSampler");
var images=new Dictionary<int,PngImage>(mesh.Textures){[-1]=fallback};
foreach(var (id,image) in images)
{
var texture=UploadTexture(image);var descriptor=descriptorLayout;
var alloc=new DescriptorSetAllocateInfo{SType=StructureType.DescriptorSetAllocateInfo,DescriptorPool=descriptorPool,DescriptorSetCount=1,PSetLayouts=&descriptor};
Check(vk.AllocateDescriptorSets(device,&alloc,out var set),"AllocateDescriptorSets");
var imageInfo=new DescriptorImageInfo{Sampler=sampler,ImageView=texture.View,ImageLayout=ImageLayout.ShaderReadOnlyOptimal};
var write=new WriteDescriptorSet{SType=StructureType.WriteDescriptorSet,DstSet=set,DstBinding=0,DescriptorCount=1,DescriptorType=DescriptorType.CombinedImageSampler,PImageInfo=&imageInfo};
vk.UpdateDescriptorSets(device,1,&write,0,null);descriptors[id]=set;
}
}
private void CreateRenderPass()
{
var attachments=stackalloc AttachmentDescription[2];
attachments[0]=new AttachmentDescription{Format=Format.R8G8B8A8Unorm,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.Store,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.TransferSrcOptimal};
attachments[1]=new AttachmentDescription{Format=Format.D32Sfloat,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.DontCare,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.DepthStencilAttachmentOptimal};
var cr=new AttachmentReference(0,ImageLayout.ColorAttachmentOptimal);var dr=new AttachmentReference(1,ImageLayout.DepthStencilAttachmentOptimal);
var subpass=new SubpassDescription{PipelineBindPoint=PipelineBindPoint.Graphics,ColorAttachmentCount=1,PColorAttachments=&cr,PDepthStencilAttachment=&dr};
var dependencies=stackalloc SubpassDependency[2];
dependencies[0]=new SubpassDependency{SrcSubpass=Vk.SubpassExternal,DstSubpass=0,SrcStageMask=PipelineStageFlags.TopOfPipeBit,DstStageMask=PipelineStageFlags.ColorAttachmentOutputBit|PipelineStageFlags.EarlyFragmentTestsBit,DstAccessMask=AccessFlags.ColorAttachmentWriteBit|AccessFlags.DepthStencilAttachmentWriteBit};
dependencies[1]=new SubpassDependency{SrcSubpass=0,DstSubpass=Vk.SubpassExternal,SrcStageMask=PipelineStageFlags.ColorAttachmentOutputBit,DstStageMask=PipelineStageFlags.TransferBit,SrcAccessMask=AccessFlags.ColorAttachmentWriteBit,DstAccessMask=AccessFlags.TransferReadBit};
var info=new RenderPassCreateInfo{SType=StructureType.RenderPassCreateInfo,AttachmentCount=2,PAttachments=attachments,SubpassCount=1,PSubpasses=&subpass,DependencyCount=2,PDependencies=dependencies};
Check(vk.CreateRenderPass(device,&info,null,out renderPass),"CreateRenderPass");
}
private ShaderModule Shader(string name)
{
var bytes=File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory,"Shaders",name));
fixed(byte* p=bytes){var info=new ShaderModuleCreateInfo{SType=StructureType.ShaderModuleCreateInfo,CodeSize=(nuint)bytes.Length,PCode=(uint*)p};Check(vk.CreateShaderModule(device,&info,null,out var shader),"CreateShaderModule");return shader;}
}
private void CreatePipeline()
{
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
try
{
var push=new PushConstantRange(ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit,0,68);var dl=descriptorLayout;
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
var stages=stackalloc PipelineShaderStageCreateInfo[2];
stages[0]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.VertexBit,Module=vertex,PName=(byte*)main};
stages[1]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.FragmentBit,Module=fragment,PName=(byte*)main};
var binding=new VertexInputBindingDescription(0,(uint)sizeof(MeshVertex),VertexInputRate.Vertex);
var attributes=stackalloc VertexInputAttributeDescription[3];
attributes[0]=new VertexInputAttributeDescription(0,0,Format.R32G32B32Sfloat,0);
attributes[1]=new VertexInputAttributeDescription(1,0,Format.R32G32Sfloat,12);
attributes[2]=new VertexInputAttributeDescription(2,0,Format.R32G32B32Sfloat,20);
var input=new PipelineVertexInputStateCreateInfo{SType=StructureType.PipelineVertexInputStateCreateInfo,VertexBindingDescriptionCount=1,PVertexBindingDescriptions=&binding,VertexAttributeDescriptionCount=3,PVertexAttributeDescriptions=attributes};
var assembly=new PipelineInputAssemblyStateCreateInfo{SType=StructureType.PipelineInputAssemblyStateCreateInfo,Topology=PrimitiveTopology.TriangleList};
var viewport=new PipelineViewportStateCreateInfo{SType=StructureType.PipelineViewportStateCreateInfo,ViewportCount=1,ScissorCount=1};
var raster=new PipelineRasterizationStateCreateInfo{SType=StructureType.PipelineRasterizationStateCreateInfo,PolygonMode=PolygonMode.Fill,CullMode=CullModeFlags.None,FrontFace=FrontFace.CounterClockwise,LineWidth=1};
var ms=new PipelineMultisampleStateCreateInfo{SType=StructureType.PipelineMultisampleStateCreateInfo,RasterizationSamples=SampleCountFlags.Count1Bit};
var ds=new PipelineDepthStencilStateCreateInfo{SType=StructureType.PipelineDepthStencilStateCreateInfo,DepthTestEnable=true,DepthWriteEnable=true,DepthCompareOp=CompareOp.LessOrEqual};
var blendAttachment=new PipelineColorBlendAttachmentState{ColorWriteMask=ColorComponentFlags.RBit|ColorComponentFlags.GBit|ColorComponentFlags.BBit|ColorComponentFlags.ABit};
var blend=new PipelineColorBlendStateCreateInfo{SType=StructureType.PipelineColorBlendStateCreateInfo,AttachmentCount=1,PAttachments=&blendAttachment};
var dynamicStates=stackalloc DynamicState[2]{DynamicState.Viewport,DynamicState.Scissor};
var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates};
var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0};
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
ds.DepthTestEnable=false;ds.DepthWriteEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline");
// Blended world geometry tests opaque depth but does not write it.
// Preserve draw order; general transparent-surface sorting is separate work.
blendAttachment.BlendEnable=true;
blendAttachment.SrcColorBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstColorBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.ColorBlendOp=BlendOp.Add;
blendAttachment.SrcAlphaBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstAlphaBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.AlphaBlendOp=BlendOp.Add;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAlphaPipeline),"CreateOverlayAlphaPipeline");
ds.DepthTestEnable=true;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out alphaPipeline),"CreateAlphaPipeline");
blendAttachment.DstColorBlendFactor=BlendFactor.One;
blendAttachment.DstAlphaBlendFactor=BlendFactor.One;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out additivePipeline),"CreateAdditivePipeline");
ds.DepthTestEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAdditivePipeline),"CreateOverlayAdditivePipeline");
}
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
}
private void CreateTarget()
{
MakeImage(width,height,Format.R8G8B8A8Unorm,ImageUsageFlags.ColorAttachmentBit|ImageUsageFlags.TransferSrcBit,ImageAspectFlags.ColorBit,out color,out colorMemory,out colorView);
MakeImage(width,height,Format.D32Sfloat,ImageUsageFlags.DepthStencilAttachmentBit,ImageAspectFlags.DepthBit,out depth,out depthMemory,out depthView);
var views=stackalloc ImageView[2]{colorView,depthView};
var info=new FramebufferCreateInfo{SType=StructureType.FramebufferCreateInfo,RenderPass=renderPass,AttachmentCount=2,PAttachments=views,Width=width,Height=height,Layers=1};
Check(vk.CreateFramebuffer(device,&info,null,out framebuffer),"CreateFramebuffer");
MakeBuffer((ulong)width*height*4,BufferUsageFlags.TransferDstBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out readback,out readbackMemory);
}
private void DestroyTarget()
{
if(framebuffer.Handle!=0)vk.DestroyFramebuffer(device,framebuffer,null);
if(colorView.Handle!=0)vk.DestroyImageView(device,colorView,null);
if(depthView.Handle!=0)vk.DestroyImageView(device,depthView,null);
if(color.Handle!=0)vk.DestroyImage(device,color,null);
if(depth.Handle!=0)vk.DestroyImage(device,depth,null);
if(colorMemory.Handle!=0)vk.FreeMemory(device,colorMemory,null);
if(depthMemory.Handle!=0)vk.FreeMemory(device,depthMemory,null);
if(readback.Handle!=0)vk.DestroyBuffer(device,readback,null);
if(readbackMemory.Handle!=0)vk.FreeMemory(device,readbackMemory,null);
framebuffer=default;colorView=default;depthView=default;color=default;depth=default;
colorMemory=default;depthMemory=default;readback=default;readbackMemory=default;
}
private void CreateSwapchain()
{
Check(surfaceApi!.GetPhysicalDeviceSurfaceCapabilities(physical,surface,out var caps),"SurfaceCapabilities");
uint count=0;Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,null),"SurfaceFormats");
var formats=new SurfaceFormatKHR[count];fixed(SurfaceFormatKHR* p=formats)Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,p),"SurfaceFormats");
var format=formats.FirstOrDefault(f=>f.Format==Format.B8G8R8A8Unorm);if(format.Format==0)format=formats[0];
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);
width=caps.CurrentExtent.Width==uint.MaxValue?Math.Clamp((uint)Math.Max(1,w),caps.MinImageExtent.Width,caps.MaxImageExtent.Width):caps.CurrentExtent.Width;
height=caps.CurrentExtent.Height==uint.MaxValue?Math.Clamp((uint)Math.Max(1,h),caps.MinImageExtent.Height,caps.MaxImageExtent.Height):caps.CurrentExtent.Height;
if((caps.SupportedUsageFlags&ImageUsageFlags.TransferDstBit)==0)throw new NotSupportedException("Swapchain does not support transfer destinations.");
var imageCount=caps.MinImageCount+1;if(caps.MaxImageCount>0)imageCount=Math.Min(imageCount,caps.MaxImageCount);
var info=new SwapchainCreateInfoKHR{SType=StructureType.SwapchainCreateInfoKhr,Surface=surface,MinImageCount=imageCount,ImageFormat=format.Format,ImageColorSpace=format.ColorSpace,ImageExtent=new Extent2D(width,height),ImageArrayLayers=1,ImageUsage=ImageUsageFlags.TransferDstBit,ImageSharingMode=SharingMode.Exclusive,PreTransform=caps.CurrentTransform,CompositeAlpha=CompositeAlphaFlagsKHR.OpaqueBitKhr,PresentMode=PresentModeKHR.FifoKhr,Clipped=true};
Check(swapApi!.CreateSwapchain(device,&info,null,out swapchain),"CreateSwapchain");
count=0;Check(swapApi.GetSwapchainImages(device,swapchain,&count,null),"GetSwapchainImages");swapImages=new Image[count];
fixed(Image* p=swapImages)Check(swapApi.GetSwapchainImages(device,swapchain,&count,p),"GetSwapchainImages");
}
public void Resize()
{
if(window==0)return;
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return;
Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();
swapApi!.DestroySwapchain(device,swapchain,null);swapchain=default;swapImages=[];
CreateSwapchain();CreateTarget();
}
public void Render(Matrix4x4 mvp)
{
// Draw materials are mutable between frames. Reject invalid state before
// acquiring an image or beginning a command buffer, even on hidden draws.
ValidateDrawMaterials(mesh.Draws);
uint imageIndex=0;
if(window!=0)
{
var result=swapApi!.AcquireNextImage(device,swapchain,ulong.MaxValue,acquired,default,&imageIndex);
if(result==Result.ErrorOutOfDateKhr){Resize();return;}
if(result!=Result.SuboptimalKhr)Check(result,"AcquireNextImage");
}
Begin();
var clear=stackalloc ClearValue[2];clear[0].Color=new ClearColorValue(0.12f,0.20f,0.30f,1);clear[1].DepthStencil=new ClearDepthStencilValue(1,0);
var begin=new RenderPassBeginInfo{SType=StructureType.RenderPassBeginInfo,RenderPass=renderPass,Framebuffer=framebuffer,RenderArea=new Rect2D(new Offset2D(0,0),new Extent2D(width,height)),ClearValueCount=2,PClearValues=clear};
vk.CmdBeginRenderPass(command,&begin,SubpassContents.Inline);vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,pipeline);
var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height));
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
// Opaque world first, blended world second, UI last. Within each pass,
// retain source order so existing UI composition remains unchanged.
for(var pass=0;pass<3;pass++)
{
var screenSpace=pass==2;
var transform=screenSpace?Matrix4x4.Identity:mvp;
var stages=ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit;
vk.CmdPushConstants(command,pipelineLayout,stages,0,64,&transform);
foreach(var draw in draws)
{
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
if(!screenSpace && (draw.Blend==MeshBlend.Opaque)!=(pass==0))continue;
var selectedPipeline=(screenSpace,draw.Blend) switch
{
(false,MeshBlend.Alpha)=>alphaPipeline,
(false,MeshBlend.Additive)=>additivePipeline,
(true,MeshBlend.Alpha)=>overlayAlphaPipeline,
(true,MeshBlend.Additive)=>overlayAdditivePipeline,
(true,_)=>overlayPipeline,
_=>pipeline
};
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,selectedPipeline);
var opacity=draw.Opacity;
vk.CmdPushConstants(command,pipelineLayout,stages,64,4,&opacity);
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
}
}
vk.CmdEndRenderPass(command);
if(window==0){Submit();return;}
var target=swapImages[imageIndex];Barrier(target,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
var blit=new ImageBlit{SrcSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),DstSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1)};
blit.SrcOffsets[0]=new Offset3D(0,0,0);blit.SrcOffsets[1]=new Offset3D((int)width,(int)height,1);blit.DstOffsets[0]=new Offset3D(0,0,0);blit.DstOffsets[1]=new Offset3D((int)width,(int)height,1);
vk.CmdBlitImage(command,color,ImageLayout.TransferSrcOptimal,target,ImageLayout.TransferDstOptimal,1,&blit,Filter.Nearest);
Barrier(target,ImageLayout.TransferDstOptimal,ImageLayout.PresentSrcKhr,AccessFlags.TransferWriteBit,0,PipelineStageFlags.TransferBit,PipelineStageFlags.BottomOfPipeBit);
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;var wait=acquired;var signal=finished;var stage=PipelineStageFlags.TransferBit;
var submit=new SubmitInfo{SType=StructureType.SubmitInfo,WaitSemaphoreCount=1,PWaitSemaphores=&wait,PWaitDstStageMask=&stage,CommandBufferCount=1,PCommandBuffers=&cmd,SignalSemaphoreCount=1,PSignalSemaphores=&signal};
Check(vk.QueueSubmit(queue,1,&submit,default),"QueueSubmit");var swap=swapchain;
var present=new PresentInfoKHR{SType=StructureType.PresentInfoKhr,WaitSemaphoreCount=1,PWaitSemaphores=&signal,SwapchainCount=1,PSwapchains=&swap,PImageIndices=&imageIndex};
var presentation=swapApi!.QueuePresent(queue,&present);Check(vk.QueueWaitIdle(queue),"PresentWaitIdle");
if(presentation is Result.ErrorOutOfDateKhr or Result.SuboptimalKhr)Resize();else Check(presentation,"QueuePresent");
}
public byte[] ReadPixels()
{
Begin();var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(width,height,1)};
vk.CmdCopyImageToBuffer(command,color,ImageLayout.TransferSrcOptimal,readback,1,&copy);Submit();
var pixels=new byte[checked((int)(width*height*4))];void* data;
Check(vk.MapMemory(device,readbackMemory,0,(ulong)pixels.Length,0,&data),"ReadbackMap");new ReadOnlySpan<byte>(data,pixels.Length).CopyTo(pixels);vk.UnmapMemory(device,readbackMemory);return pixels;
}
public void SavePpm(string path)
{
var rgba=ReadPixels();Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
using var file=File.Create(path);file.Write(System.Text.Encoding.ASCII.GetBytes($"P6\n{width} {height}\n255\n"));
for(var i=0;i<rgba.Length;i+=4)file.Write(rgba,i,3);
}
public void Dispose()
{
if(device.Handle!=0)
{
vk.DeviceWaitIdle(device);
DestroyTarget();
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
if(alphaPipeline.Handle!=0)vk.DestroyPipeline(device,alphaPipeline,null);
if(additivePipeline.Handle!=0)vk.DestroyPipeline(device,additivePipeline,null);
if(overlayAlphaPipeline.Handle!=0)vk.DestroyPipeline(device,overlayAlphaPipeline,null);
if(overlayAdditivePipeline.Handle!=0)vk.DestroyPipeline(device,overlayAdditivePipeline,null);
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
DestroySceneResources();
if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null);
if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null);
if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null);
if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null);
vk.DestroyDevice(device,null);device=default;
}
if(surface.Handle!=0){surfaceApi!.DestroySurface(instance,surface,null);surface=default;}
if(messenger.Handle!=0){debugApi!.DestroyDebugUtilsMessenger(instance,messenger,null);messenger=default;}
if(instance.Handle!=0){vk.DestroyInstance(instance,null);instance=default;}
vk.Dispose();
}
}
/// <summary>Presentation/device identities for transition verification; swapchain
/// identity may legitimately change on resize, unlike device and surface.</summary>
public readonly record struct RendererIdentity(ulong Instance,ulong Device,ulong Surface,
ulong Swapchain,ulong Pipeline,ulong PipelineLayout,ulong DescriptorLayout);