diff --git a/src/ComputeSharp.sln b/src/ComputeSharp.sln
new file mode 100644
index 00000000..e28fc3f4
--- /dev/null
+++ b/src/ComputeSharp.sln
@@ -0,0 +1,61 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.29201.188
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Graphics", "DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj", "{2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Shaders", "DirectX12GameEngine.Shaders\DirectX12GameEngine.Shaders.csproj", "{23AE6EED-79CD-4ADD-9A85-0148BD957D19}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectX12GameEngine.Core", "DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj", "{314EB353-E7E3-4146-8111-685CC83EC1DE}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DirectX12ComputeShaderSample", "DirectX12ComputeShaderSample\DirectX12ComputeShaderSample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Debug|x64.Build.0 = Debug|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|x64.ActiveCfg = Release|Any CPU
+ {2499CC74-BC9A-4B30-A3B6-05F9C7BF9B34}.Release|x64.Build.0 = Release|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Debug|x64.Build.0 = Debug|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|Any CPU.Build.0 = Release|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|x64.ActiveCfg = Release|Any CPU
+ {23AE6EED-79CD-4ADD-9A85-0148BD957D19}.Release|x64.Build.0 = Release|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Debug|x64.Build.0 = Debug|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.ActiveCfg = Release|Any CPU
+ {314EB353-E7E3-4146-8111-685CC83EC1DE}.Release|x64.Build.0 = Release|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Debug|x64.Build.0 = Debug|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.ActiveCfg = Release|Any CPU
+ {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
+ EndGlobalSection
+EndGlobal
diff --git a/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj b/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj
new file mode 100644
index 00000000..0823373d
--- /dev/null
+++ b/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Exe
+ netcoreapp3.0
+
+
+
+
+
+
+
+
diff --git a/src/DirectX12ComputeShaderSample/Gpu.cs b/src/DirectX12ComputeShaderSample/Gpu.cs
new file mode 100644
index 00000000..7e122ace
--- /dev/null
+++ b/src/DirectX12ComputeShaderSample/Gpu.cs
@@ -0,0 +1,50 @@
+using System;
+using System.Linq;
+using DirectX12GameEngine.Graphics;
+using DirectX12GameEngine.Shaders;
+using DirectX12GameEngine.Shaders.Numerics;
+using SharpDX.D3DCompiler;
+using SharpDX.Direct3D12;
+using CommandList = DirectX12GameEngine.Graphics.CommandList;
+using PipelineState = DirectX12GameEngine.Graphics.PipelineState;
+
+namespace DirectX12ComputeShaderSample
+{
+ public static class Gpu
+ {
+ private static GraphicsDevice _Default;
+
+ public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true);
+ }
+
+ public static class GraphicsDeviceExtensions
+ {
+ public static void For(this GraphicsDevice device, int n, Action shader)
+ {
+ // Generate the compute shadr
+ ShaderGenerator shaderGenerator = new ShaderGenerator(shader);
+ ShaderGenerationResult result = shaderGenerator.GenerateShaderForLambda();
+
+ byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, ShaderVersion.ComputeShader, result.ComputeShader);
+
+ // Create the root signature for the pipeline and the pipeline state
+ RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderGenerator.RootParameters);
+ RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription);
+ PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode);
+
+ // Create the commands list
+ using CommandList commandList = new CommandList(device, CommandListType.Compute);
+ commandList.SetPipelineState(pipelineState);
+
+ // Load the captured buffers
+ foreach (var item in shaderGenerator.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
+ {
+ commandList.SetComputeRootDescriptorTable(item.Index, item.Resource);
+ }
+
+ // Dispatch and wait for completion
+ commandList.Dispatch(2, 2, 1);
+ commandList.Flush(true);
+ }
+ }
+}
diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs
new file mode 100644
index 00000000..33ffa741
--- /dev/null
+++ b/src/DirectX12ComputeShaderSample/Program.cs
@@ -0,0 +1,67 @@
+using DirectX12GameEngine.Shaders;
+using DirectX12GameEngine.Shaders.Numerics;
+using System;
+using System.Linq;
+using DirectX12GameEngine.Graphics.Buffers;
+using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer;
+
+namespace DirectX12ComputeShaderSample
+{
+ public class Program
+ {
+ private static void Main()
+ {
+ // Create the graphics buffer
+ int width = 10;
+ int height = 10;
+ float[] array = new float[width * height];
+ for (int i = 0; i < array.Length; i++)
+ {
+ array[i] = i + 1;
+ }
+
+ using Buffer gpuBuffer = Buffer.UnorderedAccess.New(Gpu.Default, array.AsSpan());
+
+ // Variables for closure
+ uint size = (uint)width;
+ var data = gpuBuffer.GetGpuResource();
+
+ // Shader body
+ Action action = id =>
+ {
+ data[id.X + id.Y * size] *= 2;
+ };
+
+ // Run the shader
+ Gpu.Default.For(100, action);
+
+ // Print matrix
+
+ Console.WriteLine("Before:");
+ PrintMatrix(array, width, height);
+
+ gpuBuffer.GetData(array.AsSpan());
+
+ Console.WriteLine();
+ Console.WriteLine("After:");
+ PrintMatrix(array, width, height);
+ }
+
+ private static void PrintMatrix(float[] array, int width, int height)
+ {
+ int numberWidth = array.Max().ToString().Length;
+
+ for (int y = 0; y < height; y++)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ Console.Write(array[x + y * width].ToString().PadLeft(numberWidth));
+ Console.Write(", ");
+ }
+
+ Console.WriteLine();
+ }
+ }
+ }
+}
+
diff --git a/src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj b/src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj
new file mode 100644
index 00000000..50891f1b
--- /dev/null
+++ b/src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj
@@ -0,0 +1,15 @@
+
+
+
+ netstandard2.0
+ true
+
+
+
+
+
+
+
+
+
+
diff --git a/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs
new file mode 100644
index 00000000..4c636790
--- /dev/null
+++ b/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs
@@ -0,0 +1,27 @@
+using System.Diagnostics.Contracts;
+using System.Numerics;
+
+namespace Windows.Foundation
+{
+ ///
+ /// A with some extension methods for the type
+ ///
+ public static class PointExtensions
+ {
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ [Pure]
+ public static Vector2 ToVector2(this in Point value) => new Vector2((float)value.X, (float)value.Y);
+
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ [Pure]
+ public static Point ToPoint(this in Vector2 value) => new Point(value.X, value.Y);
+ }
+}
diff --git a/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs
new file mode 100644
index 00000000..55956a6e
--- /dev/null
+++ b/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs
@@ -0,0 +1,29 @@
+using System.Diagnostics.Contracts;
+using System.Numerics;
+
+namespace Windows.Foundation
+{
+ ///
+ /// A with some extension methods for the type
+ ///
+ public static class RectExtensions
+ {
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ /// The input is read in the following order: , , ,
+ [Pure]
+ public static Vector4 ToVector2(this in Rect value) => new Vector4((float)value.Left, (float)value.Top, (float)value.Right, (float)value.Bottom);
+
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ /// The input is assigned in the following order: , , ,
+ [Pure]
+ public static Rect ToPoint(this in Vector4 value) => new Rect(value.X, value.Y, value.Z, value.W);
+ }
+}
\ No newline at end of file
diff --git a/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs b/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs
new file mode 100644
index 00000000..f8871206
--- /dev/null
+++ b/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs
@@ -0,0 +1,29 @@
+using System.Diagnostics.Contracts;
+using System.Numerics;
+
+namespace Windows.Foundation
+{
+ ///
+ /// A with some extension methods for the type
+ ///
+ public static class SizeExtensions
+ {
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ /// The input is read in the following order: ,
+ [Pure]
+ public static Vector2 ToVector2(this in Size value) => new Vector2((float)value.Width, (float)value.Height);
+
+ ///
+ /// Converts a value to a
+ ///
+ /// The input to convert
+ /// A value representing the input
+ /// The input is assigned in the following order: ,
+ [Pure]
+ public static Size ToPoint(this in Vector2 value) => new Size(value.X, value.Y);
+ }
+}
\ No newline at end of file
diff --git a/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs b/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs
new file mode 100644
index 00000000..559eabee
--- /dev/null
+++ b/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Runtime.CompilerServices;
+
+namespace DirectX12GameEngine.Core.Helpers
+{
+ ///
+ /// A with some helper methods to copy data between memory areas
+ ///
+ public static class MemoryHelper
+ {
+ ///
+ /// Copies the content of a to the area pointed by an input value
+ ///
+ /// The type of values in the input
+ /// The source to read
+ /// The for the destination memory area
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe void Copy(Span source, IntPtr destination) where T : unmanaged
+ {
+ source.CopyTo(new Span(destination.ToPointer(), source.Length));
+ }
+
+ ///
+ /// Copies a memory area pointed by an value to a target
+ ///
+ /// The type of values to read
+ /// The that indicates the memory area to read from
+ /// The destination to write
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe void Copy(IntPtr source, Span destination) where T : unmanaged
+ {
+ new Span(source.ToPointer(), destination.Length).CopyTo(destination);
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/BufferDescription.cs b/src/DirectX12GameEngine.Graphics/BufferDescription.cs
new file mode 100644
index 00000000..89159df8
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/BufferDescription.cs
@@ -0,0 +1,18 @@
+namespace DirectX12GameEngine.Graphics
+{
+ public struct BufferDescription
+ {
+ public BufferDescription(int sizeInBytes, BufferFlags bufferFlags, GraphicsHeapType heapType)
+ {
+ SizeInBytes = sizeInBytes;
+ Flags = bufferFlags;
+ HeapType = heapType;
+ }
+
+ public int SizeInBytes;
+
+ public BufferFlags Flags;
+
+ public GraphicsHeapType HeapType;
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/BufferFlags.cs b/src/DirectX12GameEngine.Graphics/BufferFlags.cs
new file mode 100644
index 00000000..1c0a26b5
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/BufferFlags.cs
@@ -0,0 +1,19 @@
+using System;
+
+namespace DirectX12GameEngine.Graphics
+{
+ [Flags]
+ public enum BufferFlags
+ {
+ None = 0,
+ ConstantBuffer = 1,
+ IndexBuffer = 2,
+ VertexBuffer = 4,
+ RenderTarget = 8,
+ ShaderResource = 16,
+ UnorderedAccess = 32,
+ StructuredBuffer = 64,
+ RawBuffer = 512,
+ ArgumentBuffer = 1024
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs b/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs
new file mode 100644
index 00000000..1ffa6721
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs
@@ -0,0 +1,70 @@
+using System;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics.Buffers.Abstract
+{
+ ///
+ /// An abstract that represents a graphics resource object
+ ///
+ public abstract class GraphicsResource : IDisposable
+ {
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The associated with the current instance
+ protected GraphicsResource(GraphicsDevice device)
+ {
+ GraphicsDevice = device;
+ }
+
+ ///
+ /// Gets the associated with the current instance
+ ///
+ public GraphicsDevice GraphicsDevice { get; }
+
+ ///
+ /// Gets the associated to the currently mapped resource
+ ///
+ public IntPtr MappedResource { get; private set; }
+
+ ///
+ /// Gets the object currently mapped
+ ///
+ protected internal Resource? NativeResource { get; set; }
+
+ ///
+ /// Gets the instance for the current resource
+ ///
+ protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; }
+
+ ///
+ /// Gets the instance for the current resource
+ ///
+ protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; }
+
+ ///
+ /// Maps the current resource to a specified subresource
+ ///
+ /// The index of the target subresource to map
+ /// An for the newly mapped resource
+ public IntPtr Map(int subresource)
+ {
+ IntPtr mappedResource = NativeResource?.Map(subresource) ?? throw new InvalidOperationException("Missing resource");
+ MappedResource = mappedResource;
+ return mappedResource;
+ }
+
+ ///
+ /// Unmaps a subresource specified by a given index
+ ///
+ /// The index of the subresource to unmap
+ public void Unmap(int subresource)
+ {
+ NativeResource?.Unmap(subresource);
+ MappedResource = IntPtr.Zero;
+ }
+
+ ///
+ public virtual void Dispose() => NativeResource?.Dispose();
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs
new file mode 100644
index 00000000..7745734e
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace DirectX12GameEngine.Graphics.Buffers
+{
+ public partial class Buffer
+ {
+ public static class Constant
+ {
+ public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Upload)
+ {
+ return Buffer.New(device, size, BufferFlags.ConstantBuffer, heapType);
+ }
+
+ public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
+ {
+ return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
+ }
+
+ public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
+ {
+ return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
+ }
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs
new file mode 100644
index 00000000..20ec576d
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace DirectX12GameEngine.Graphics.Buffers
+{
+ public partial class Buffer
+ {
+ public static class UnorderedAccess
+ {
+ public static unsafe Buffers.Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default)
+ {
+ return Buffers.Buffer.New(device, size, BufferFlags.UnorderedAccess, heapType);
+ }
+
+ public static unsafe Buffer New(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
+ {
+ return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType);
+ }
+
+ public static unsafe Buffer New(GraphicsDevice device, Span data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
+ {
+ return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs
new file mode 100644
index 00000000..db4052e0
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs
@@ -0,0 +1,232 @@
+using System;
+using System.Runtime.CompilerServices;
+using DirectX12GameEngine.Core.Helpers;
+using DirectX12GameEngine.Graphics.Buffers.Abstract;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics.Buffers
+{
+ public partial class Buffer : GraphicsResource
+ {
+ protected Buffer(GraphicsDevice device) : base(device)
+ {
+ }
+
+ public BufferDescription Description { get; private set; }
+
+ public int SizeInBytes => Description.SizeInBytes;
+
+ public BufferFlags Flags => Description.Flags;
+
+ public GraphicsHeapType Usage => Description.HeapType;
+
+ public int ElementCount { get; protected set; }
+
+ public T[] GetData() where T : unmanaged
+ {
+ T[] data = new T[SizeInBytes / Unsafe.SizeOf()];
+ GetData(data.AsSpan());
+
+ return data;
+ }
+
+ public unsafe void GetData(ref T data, int offsetInBytes = 0) where T : unmanaged
+ {
+ fixed (T* pointer = &data)
+ {
+ GetData(new Span(pointer, 1), offsetInBytes);
+ }
+ }
+
+ public void GetData(Span data, int offsetInBytes = 0) where T : unmanaged
+ {
+ if (Usage == GraphicsHeapType.Default)
+ {
+ using Buffer readbackBaffer = New(GraphicsDevice, data.Length, BufferFlags.None, GraphicsHeapType.Readback);
+ using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
+
+ copyCommandList.CopyBufferRegion(this, offsetInBytes, readbackBaffer, 0, data.Length * Unsafe.SizeOf());
+ copyCommandList.Flush(true);
+
+ readbackBaffer.GetData(data);
+ }
+ else
+ {
+ Map(0);
+ MemoryHelper.Copy(MappedResource + offsetInBytes, data);
+ Unmap(0);
+ }
+ }
+
+ public unsafe void SetData(in T data, int offsetInBytes = 0) where T : unmanaged
+ {
+ fixed (T* pointer = &data)
+ {
+ SetData(new Span(pointer, 1), offsetInBytes);
+ }
+ }
+
+ public void SetData(Span data, int offsetInBytes = 0) where T : unmanaged
+ {
+ if (Usage == GraphicsHeapType.Default)
+ {
+ using Buffer uploadBuffer = New(GraphicsDevice, data, BufferFlags.None, GraphicsHeapType.Upload);
+ using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
+
+ copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, offsetInBytes, data.Length * Unsafe.SizeOf());
+ copyCommandList.Flush(true);
+ }
+ else
+ {
+ Map(0);
+ MemoryHelper.Copy(data, MappedResource + offsetInBytes);
+ Unmap(0);
+ }
+ }
+
+ public Buffers.Buffer ToReadback()
+ {
+ BufferDescription description = Description;
+ description.HeapType = GraphicsHeapType.Readback;
+ description.Flags = BufferFlags.None;
+
+ return New(GraphicsDevice, description);
+ }
+
+ public static Buffers.Buffer New(GraphicsDevice device, BufferDescription description)
+ {
+ return new Buffers.Buffer(device).InitializeFrom(description);
+ }
+
+ public static Buffers.Buffer New(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default)
+ {
+ return New(device, new BufferDescription(size, bufferFlags, heapType));
+ }
+
+ public static Buffer New(GraphicsDevice device, int elementCount, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
+ {
+ int bufferSize = elementCount * Unsafe.SizeOf();
+
+ return new Buffer(device, bufferSize, bufferFlags, heapType);
+ }
+
+ public static unsafe Buffer New(GraphicsDevice device, in T data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
+ {
+ fixed (T* pointer = &data)
+ {
+ return New(device, new Span(pointer, 1), bufferFlags, heapType);
+ }
+ }
+
+ public static Buffer New(GraphicsDevice device, Span data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
+ {
+ Buffer buffer = New(device, data.Length, bufferFlags, heapType);
+ buffer.SetData(data);
+
+ return buffer;
+ }
+
+ protected internal Buffers.Buffer InitializeFrom(BufferDescription description)
+ {
+ ResourceStates resourceStates = ResourceStates.Common;
+
+ if (description.HeapType == GraphicsHeapType.Upload)
+ {
+ resourceStates = ResourceStates.GenericRead;
+ }
+ else if (description.HeapType == GraphicsHeapType.Readback)
+ {
+ resourceStates = ResourceStates.CopyDestination;
+ }
+
+ NativeResource ??= GraphicsDevice.NativeDevice.CreateCommittedResource(
+ new HeapProperties((HeapType)description.HeapType), HeapFlags.None,
+ ConvertToNativeDescription(description), resourceStates);
+
+ Description = description;
+
+ (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = description.Flags switch
+ {
+ BufferFlags.ConstantBuffer => CreateConstantBufferView(),
+ BufferFlags.ShaderResource => CreateShaderResourceView(),
+ BufferFlags.UnorderedAccess => CreateUnorderedAccessView(),
+ _ => default
+ };
+
+ return this;
+ }
+
+ private static ResourceDescription ConvertToNativeDescription(BufferDescription description)
+ {
+ int size = description.SizeInBytes;
+ ResourceFlags flags = ResourceFlags.None;
+
+ if (description.Flags.HasFlag(BufferFlags.UnorderedAccess))
+ {
+ flags |= ResourceFlags.AllowUnorderedAccess;
+ //flags |= ResourceFlags.AllowSimultaneousAccess;
+ }
+
+ return ResourceDescription.Buffer(size, flags);
+ }
+
+ private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
+ {
+ (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
+
+ int constantBufferSize = (SizeInBytes + 255) & ~255;
+
+ ConstantBufferViewDescription cbvDescription = new ConstantBufferViewDescription
+ {
+ BufferLocation = NativeResource.GPUVirtualAddress,
+ SizeInBytes = constantBufferSize
+ };
+
+ GraphicsDevice.NativeDevice.CreateConstantBufferView(cbvDescription, cpuHandle);
+
+ return (cpuHandle, gpuHandle);
+ }
+
+ private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView()
+ {
+ (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
+ GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, null, cpuHandle);
+
+ return (cpuHandle, gpuHandle);
+ }
+
+ private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
+ {
+ (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
+
+ var description = new UnorderedAccessViewDescription
+ {
+ Format = SharpDX.DXGI.Format.R32_Float,
+ Dimension = UnorderedAccessViewDimension.Buffer,
+ Buffer =
+ {
+ ElementCount = ElementCount,
+ }
+ };
+
+ GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
+
+ return (cpuHandle, gpuHandle);
+ }
+ }
+
+ public class Buffer : Buffers.Buffer where T : unmanaged
+ {
+ protected internal Buffer(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) : base(device)
+ {
+ ElementSize = Unsafe.SizeOf();
+ ElementCount = size / ElementSize;
+
+ InitializeFrom(new BufferDescription(size, bufferFlags, heapType));
+ }
+
+ public int ElementSize { get; }
+
+ public T[] GetData() => GetData();
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/ClearFlags.cs b/src/DirectX12GameEngine.Graphics/ClearFlags.cs
new file mode 100644
index 00000000..ddf8e904
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/ClearFlags.cs
@@ -0,0 +1,12 @@
+using System;
+
+namespace DirectX12GameEngine.Graphics
+{
+ [Flags]
+ public enum ClearFlags
+ {
+ None = 0,
+ FlagsDepth = 1,
+ FlagsStencil = 2
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs b/src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs
new file mode 100644
index 00000000..1c130675
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ internal sealed class CommandAllocatorPool : IDisposable
+ {
+ private readonly Queue<(CommandAllocator, long)> commandAllocatorQueue = new Queue<(CommandAllocator, long)>();
+
+ public CommandAllocatorPool(GraphicsDevice device, CommandListType commandListType)
+ {
+ GraphicsDevice = device;
+ CommandListType = commandListType;
+ }
+
+ public CommandListType CommandListType { get; }
+
+ public GraphicsDevice GraphicsDevice { get; }
+
+ public void Dispose()
+ {
+ lock (commandAllocatorQueue)
+ {
+ foreach ((CommandAllocator commandAllocator, long _) in commandAllocatorQueue)
+ {
+ commandAllocator.Dispose();
+ }
+
+ commandAllocatorQueue.Clear();
+ }
+ }
+
+ public void Enqueue(CommandAllocator commandAllocator, long fenceValue)
+ {
+ lock (commandAllocatorQueue)
+ {
+ commandAllocatorQueue.Enqueue((commandAllocator, fenceValue));
+ }
+ }
+
+ public CommandAllocator GetCommandAllocator()
+ {
+ lock (commandAllocatorQueue)
+ {
+ if (commandAllocatorQueue.Count > 0)
+ {
+ (CommandAllocator commandAllocator, long fenceValue) = commandAllocatorQueue.Peek();
+
+ long completedValue = CommandListType switch
+ {
+ CommandListType.Bundle => GraphicsDevice.NativeDirectFence.CompletedValue,
+ CommandListType.Compute => GraphicsDevice.NativeComputeFence.CompletedValue,
+ CommandListType.Copy => GraphicsDevice.NativeCopyFence.CompletedValue,
+ CommandListType.Direct => GraphicsDevice.NativeDirectFence.CompletedValue,
+ _ => throw new NotSupportedException("This command list type is not supported.")
+ };
+
+ if (fenceValue <= completedValue)
+ {
+ commandAllocatorQueue.Dequeue();
+ commandAllocator.Reset();
+
+ return commandAllocator;
+ }
+ }
+
+ return GraphicsDevice.NativeDevice.CreateCommandAllocator((SharpDX.Direct3D12.CommandListType)CommandListType);
+ }
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/DirectX12GameEngine.Graphics/CommandList.cs
new file mode 100644
index 00000000..341aa967
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/CommandList.cs
@@ -0,0 +1,167 @@
+using System;
+using DirectX12GameEngine.Graphics.Buffers.Abstract;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ public sealed class CommandList : IDisposable
+ {
+ private readonly CompiledCommandList currentCommandList;
+
+ public CommandList(GraphicsDevice device, CommandListType commandListType)
+ {
+ GraphicsDevice = device;
+ CommandListType = commandListType;
+
+ CommandAllocator commandAllocator = GetCommandAllocator();
+
+ GraphicsCommandList nativeCommandList = GraphicsDevice.NativeDevice.CreateCommandList((SharpDX.Direct3D12.CommandListType)CommandListType, commandAllocator, null);
+ currentCommandList = new CompiledCommandList(this, commandAllocator, nativeCommandList);
+
+ SetDescriptorHeaps(GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap);
+ }
+
+ public CommandListType CommandListType { get; }
+
+ public GraphicsDevice GraphicsDevice { get; }
+
+ public CompiledCommandList Close()
+ {
+ //foreach (var renderTarget in RenderTargets)
+ //{
+ // ResourceBarrierTransition(renderTarget, ResourceStates.RenderTarget, ResourceStates.Present);
+ //}
+
+ currentCommandList.NativeCommandList.Close();
+
+ return currentCommandList;
+ }
+
+ public void CopyBufferRegion(GraphicsResource source, long sourceOffset, GraphicsResource destination, long destinationOffset, long numBytes)
+ {
+ currentCommandList.NativeCommandList.CopyBufferRegion(destination.NativeResource, destinationOffset, source.NativeResource, sourceOffset, numBytes);
+ }
+
+ public void CopyResource(GraphicsResource source, GraphicsResource destination)
+ {
+ currentCommandList.NativeCommandList.CopyResource(destination.NativeResource, source.NativeResource);
+ }
+
+ public void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ)
+ {
+ currentCommandList.NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ);
+ }
+
+ public void Dispose()
+ {
+ switch (CommandListType)
+ {
+ case CommandListType.Bundle:
+ GraphicsDevice.BundleAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextDirectFenceValue - 1);
+ break;
+ case CommandListType.Direct:
+ GraphicsDevice.DirectAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextDirectFenceValue - 1);
+ break;
+ case CommandListType.Compute:
+ GraphicsDevice.ComputeAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextComputeFenceValue - 1);
+ break;
+ case CommandListType.Copy:
+ GraphicsDevice.CopyAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextCopyFenceValue - 1);
+ break;
+ default:
+ throw new NotSupportedException("This command list type is not supported.");
+ }
+
+ currentCommandList.NativeCommandList.Dispose();
+ }
+
+ public void Flush(bool wait = false)
+ {
+ GraphicsDevice.ExecuteCommandLists(wait, Close());
+ }
+
+ public void Reset()
+ {
+ CommandAllocator commandAllocator = GetCommandAllocator();
+
+ currentCommandList.NativeCommandAllocator = commandAllocator;
+ currentCommandList.NativeCommandList.Reset(currentCommandList.NativeCommandAllocator, null);
+
+ SetDescriptorHeaps(GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap);
+ }
+
+ public void ResourceBarrierTransition(GraphicsResource resource, ResourceStates stateBefore, ResourceStates stateAfter)
+ {
+ currentCommandList.NativeCommandList.ResourceBarrierTransition(resource.NativeResource, stateBefore, stateAfter);
+ }
+
+ public void SetDescriptorHeaps(params DescriptorHeap[] descriptorHeaps)
+ {
+ if (CommandListType != CommandListType.Copy)
+ {
+ currentCommandList.NativeCommandList.SetDescriptorHeaps(descriptorHeaps);
+ }
+ }
+
+ public void SetGraphicsRoot32BitConstant(int rootParameterIndex, int srcData, int destOffsetIn32BitValues)
+ {
+ currentCommandList.NativeCommandList.SetGraphicsRoot32BitConstant(rootParameterIndex, srcData, destOffsetIn32BitValues);
+ }
+
+ public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
+ {
+ SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
+ }
+
+ public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
+ {
+ currentCommandList.NativeCommandList.SetGraphicsRootDescriptorTable(rootParameterIndex, baseDescriptor);
+ }
+
+ public void SetGraphicsRootSignature(RootSignature rootSignature)
+ {
+ currentCommandList.NativeCommandList.SetGraphicsRootSignature(rootSignature);
+ }
+
+ public void SetComputeRoot32BitConstant(int rootParameterIndex, int srcData, int destOffsetIn32BitValues)
+ {
+ currentCommandList.NativeCommandList.SetComputeRoot32BitConstant(rootParameterIndex, srcData, destOffsetIn32BitValues);
+ }
+
+ public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
+ {
+ SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
+ }
+
+ public void SetComputeRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
+ {
+ currentCommandList.NativeCommandList.SetComputeRootDescriptorTable(rootParameterIndex, baseDescriptor);
+ }
+
+ public void SetComputeRootSignature(RootSignature rootSignature)
+ {
+ currentCommandList.NativeCommandList.SetComputeRootSignature(rootSignature);
+ }
+
+ public void SetComputeRootUnorderedAccessView(int rootParameterIndex, GraphicsResource resource)
+ {
+ currentCommandList.NativeCommandList.SetComputeRootUnorderedAccessView(rootParameterIndex, resource.NativeResource.GPUVirtualAddress);
+ }
+
+ public void SetPipelineState(PipelineState pipelineState)
+ {
+ SetComputeRootSignature(pipelineState.RootSignature);
+
+ currentCommandList.NativeCommandList.PipelineState = pipelineState.NativePipelineState;
+ }
+
+ private CommandAllocator GetCommandAllocator() => CommandListType switch
+ {
+ CommandListType.Bundle => GraphicsDevice.BundleAllocatorPool.GetCommandAllocator(),
+ CommandListType.Compute => GraphicsDevice.ComputeAllocatorPool.GetCommandAllocator(),
+ CommandListType.Copy => GraphicsDevice.CopyAllocatorPool.GetCommandAllocator(),
+ CommandListType.Direct => GraphicsDevice.DirectAllocatorPool.GetCommandAllocator(),
+ _ => throw new NotSupportedException("This command list type is not supported.")
+ };
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/CompiledCommandList.cs b/src/DirectX12GameEngine.Graphics/CompiledCommandList.cs
new file mode 100644
index 00000000..a4bc4f07
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/CompiledCommandList.cs
@@ -0,0 +1,20 @@
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ public sealed class CompiledCommandList
+ {
+ internal CompiledCommandList(CommandList builder, CommandAllocator nativeCommandAllocator, GraphicsCommandList nativeCommandList)
+ {
+ Builder = builder;
+ NativeCommandAllocator = nativeCommandAllocator;
+ NativeCommandList = nativeCommandList;
+ }
+
+ internal CommandList Builder { get; set; }
+
+ internal CommandAllocator NativeCommandAllocator { get; set; }
+
+ internal GraphicsCommandList NativeCommandList { get; set; }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs b/src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs
new file mode 100644
index 00000000..ff795e41
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs
@@ -0,0 +1,90 @@
+using System;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ internal sealed class DescriptorAllocator : IDisposable
+ {
+ private const int DescriptorsPerHeap = 4096;
+
+ private readonly object allocatorLock = new object();
+ private readonly int descriptorSize;
+
+ private CpuDescriptorHandle currentCpuHandle;
+ private GpuDescriptorHandle currentGpuHandle;
+ private int remainingHandles;
+
+ public DescriptorAllocator(GraphicsDevice device, DescriptorHeapType descriptorHeapType, DescriptorHeapFlags descriptorHeapFlags = DescriptorHeapFlags.None, int descriptorCount = DescriptorsPerHeap)
+ {
+ if (descriptorCount < 1 || descriptorCount > DescriptorsPerHeap)
+ {
+ throw new ArgumentOutOfRangeException(nameof(descriptorCount), $"Descriptor count must be between 1 and {DescriptorsPerHeap}.");
+ }
+
+ descriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(descriptorHeapType);
+
+ DescriptorHeapDescription rtvHeapDescription = new DescriptorHeapDescription
+ {
+ DescriptorCount = descriptorCount,
+ Flags = descriptorHeapFlags,
+ Type = descriptorHeapType
+ };
+
+ DescriptorHeap = device.NativeDevice.CreateDescriptorHeap(rtvHeapDescription);
+
+ remainingHandles = descriptorCount;
+ currentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
+ currentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
+ }
+
+ public DescriptorHeap DescriptorHeap { get; }
+
+ public (CpuDescriptorHandle, GpuDescriptorHandle) Allocate(int count)
+ {
+ if (count < 1 || (count > remainingHandles && remainingHandles != 0))
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), "Count must be between 1 and the remaining handles if the remaining handles are not 0.");
+ }
+
+ lock (allocatorLock)
+ {
+ if (remainingHandles == 0)
+ {
+ remainingHandles = DescriptorHeap.Description.DescriptorCount;
+ currentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
+ currentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
+ }
+
+ CpuDescriptorHandle cpuDescriptorHandle = currentCpuHandle;
+ GpuDescriptorHandle gpuDescriptorHandle = currentGpuHandle;
+
+ currentCpuHandle += descriptorSize * count;
+ currentGpuHandle += descriptorSize * count;
+ remainingHandles -= count;
+
+ return (cpuDescriptorHandle, gpuDescriptorHandle);
+ }
+ }
+
+ public (CpuDescriptorHandle, GpuDescriptorHandle) AllocateSlot(int slot)
+ {
+ if (slot < 0 || slot > DescriptorHeap.Description.DescriptorCount - 1)
+ {
+ throw new ArgumentOutOfRangeException(nameof(slot), "Slot must be between 0 and the descript count - 1.");
+ }
+
+ lock (allocatorLock)
+ {
+ CpuDescriptorHandle cpuDescriptorHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart + descriptorSize * slot;
+ GpuDescriptorHandle gpuDescriptorHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart + descriptorSize * slot;
+
+ return (cpuDescriptorHandle, gpuDescriptorHandle);
+ }
+ }
+
+ public void Dispose()
+ {
+ DescriptorHeap.Dispose();
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj b/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj
new file mode 100644
index 00000000..e2b2653d
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj
@@ -0,0 +1,18 @@
+
+
+
+ netstandard2.0
+ 8.0
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs
new file mode 100644
index 00000000..42be36df
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs
@@ -0,0 +1,201 @@
+using System;
+using System.Threading;
+using SharpDX.Direct3D;
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ public sealed class GraphicsDevice : IDisposable
+ {
+ private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false);
+
+ public GraphicsDevice(bool enableDebugLayer = false)
+ {
+#if DEBUG
+ if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer();
+#endif
+ NativeDevice = new Device(null, FeatureLevel);
+
+ NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute));
+ NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Copy));
+ NativeDirectCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct));
+
+ BundleAllocatorPool = new CommandAllocatorPool(this, CommandListType.Bundle);
+ ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute);
+ CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy);
+ DirectAllocatorPool = new CommandAllocatorPool(this, CommandListType.Direct);
+
+ NativeComputeFence = NativeDevice.CreateFence(0, FenceFlags.None);
+ NativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None);
+ NativeDirectFence = NativeDevice.CreateFence(0, FenceFlags.None);
+
+ DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView, descriptorCount: 1);
+ RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView, descriptorCount: 2);
+ ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, DescriptorHeapFlags.ShaderVisible);
+
+ CommandList = new CommandList(this, CommandListType.Direct);
+ CommandList.Close();
+
+ CopyCommandList = new CommandList(this, CommandListType.Copy);
+ CopyCommandList.Close();
+ }
+
+ public CommandList CommandList { get; }
+
+ public CommandList CopyCommandList { get; }
+
+ public const FeatureLevel FeatureLevel = SharpDX.Direct3D.FeatureLevel.Level_12_1;
+
+ internal Device NativeDevice { get; }
+
+ internal DescriptorAllocator DepthStencilViewAllocator { get; set; }
+
+ internal DescriptorAllocator RenderTargetViewAllocator { get; set; }
+
+ internal DescriptorAllocator ShaderResourceViewAllocator { get; set; }
+
+ internal CommandAllocatorPool BundleAllocatorPool { get; }
+
+ internal CommandAllocatorPool ComputeAllocatorPool { get; }
+
+ internal CommandAllocatorPool CopyAllocatorPool { get; }
+
+ internal CommandAllocatorPool DirectAllocatorPool { get; }
+
+ internal CommandQueue NativeComputeCommandQueue { get; }
+
+ internal CommandQueue NativeCopyCommandQueue { get; }
+
+ internal CommandQueue NativeDirectCommandQueue { get; }
+
+ internal Fence NativeComputeFence { get; }
+
+ internal Fence NativeCopyFence { get; }
+
+ internal Fence NativeDirectFence { get; }
+
+ internal long NextComputeFenceValue { get; private set; } = 1;
+
+ internal long NextCopyFenceValue { get; private set; } = 1;
+
+ internal long NextDirectFenceValue { get; private set; } = 1;
+
+ public RootSignature CreateRootSignature(RootSignatureDescription rootSignatureDescription)
+ {
+ return NativeDevice.CreateRootSignature(rootSignatureDescription.Serialize());
+ }
+
+ public void Dispose()
+ {
+ NativeDirectCommandQueue.Signal(NativeDirectFence, NextDirectFenceValue);
+ NativeDirectCommandQueue.Wait(NativeDirectFence, NextDirectFenceValue);
+
+ CommandList.Dispose();
+ CopyCommandList.Dispose();
+
+ DepthStencilViewAllocator.Dispose();
+ RenderTargetViewAllocator.Dispose();
+ ShaderResourceViewAllocator.Dispose();
+
+ BundleAllocatorPool.Dispose();
+ ComputeAllocatorPool.Dispose();
+ CopyAllocatorPool.Dispose();
+ DirectAllocatorPool.Dispose();
+
+ NativeComputeCommandQueue.Dispose();
+ NativeCopyCommandQueue.Dispose();
+ NativeDirectCommandQueue.Dispose();
+
+ NativeComputeFence.Dispose();
+ NativeDirectFence.Dispose();
+ NativeDirectFence.Dispose();
+
+ NativeDevice.Dispose();
+ }
+
+ public void ExecuteCommandLists(bool wait, params CompiledCommandList[] commandLists)
+ {
+ Fence fence = commandLists[0].Builder.CommandListType switch
+ {
+ CommandListType.Direct => NativeDirectFence,
+ CommandListType.Compute => NativeComputeFence,
+ CommandListType.Copy => NativeCopyFence,
+ _ => throw new NotSupportedException("This command list type is not supported.")
+ };
+
+ long fenceValue = ExecuteCommandLists(commandLists);
+
+ if (wait)
+ {
+ WaitForFence(fence, fenceValue);
+ }
+ }
+
+ public long ExecuteCommandLists(params CompiledCommandList[] commandLists)
+ {
+ CommandAllocatorPool commandAllocatorPool;
+ CommandQueue commandQueue;
+ Fence fence;
+ long fenceValue;
+
+ switch (commandLists[0].Builder.CommandListType)
+ {
+ case CommandListType.Compute:
+ commandAllocatorPool = ComputeAllocatorPool;
+ commandQueue = NativeComputeCommandQueue;
+
+ fence = NativeComputeFence;
+ fenceValue = NextComputeFenceValue;
+ NextDirectFenceValue++;
+ break;
+ case CommandListType.Copy:
+ commandAllocatorPool = CopyAllocatorPool;
+ commandQueue = NativeCopyCommandQueue;
+
+ fence = NativeCopyFence;
+ fenceValue = NextCopyFenceValue;
+ NextCopyFenceValue++;
+ break;
+ case CommandListType.Direct:
+ commandAllocatorPool = DirectAllocatorPool;
+ commandQueue = NativeDirectCommandQueue;
+
+ fence = NativeDirectFence;
+ fenceValue = NextDirectFenceValue;
+ NextDirectFenceValue++;
+ break;
+ default:
+ throw new NotSupportedException("This command list type is not supported.");
+ }
+
+ SharpDX.Direct3D12.CommandList[] nativeCommandLists = new SharpDX.Direct3D12.CommandList[commandLists.Length];
+
+ for (int i = 0; i < commandLists.Length; i++)
+ {
+ nativeCommandLists[i] = commandLists[i].NativeCommandList;
+ commandAllocatorPool.Enqueue(commandLists[i].NativeCommandAllocator, fenceValue);
+ }
+
+ commandQueue.ExecuteCommandLists(nativeCommandLists);
+ commandQueue.Signal(fence, fenceValue);
+
+ return fenceValue;
+ }
+
+ internal bool IsFenceComplete(Fence fence, long fenceValue)
+ {
+ return fenceValue <= fence.CompletedValue;
+ }
+
+ internal void WaitForFence(Fence fence, long fenceValue)
+ {
+ if (IsFenceComplete(fence, fenceValue)) return;
+
+ lock (fence)
+ {
+ fence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle());
+ fenceEvent.WaitOne();
+ }
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs b/src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs
new file mode 100644
index 00000000..b4299070
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs
@@ -0,0 +1,10 @@
+namespace DirectX12GameEngine.Graphics
+{
+ public enum GraphicsHeapType
+ {
+ Default = 1,
+ Upload = 2,
+ Readback = 3,
+ Custom = 4
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/PipelineState.cs b/src/DirectX12GameEngine.Graphics/PipelineState.cs
new file mode 100644
index 00000000..c74c8967
--- /dev/null
+++ b/src/DirectX12GameEngine.Graphics/PipelineState.cs
@@ -0,0 +1,35 @@
+using SharpDX.Direct3D12;
+
+namespace DirectX12GameEngine.Graphics
+{
+ ///
+ /// A representing a custom pipeline state for a compute operation
+ ///
+ public sealed class PipelineState : ComputePipelineStateDescription
+ {
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The to use
+ /// The value for the current shader
+ /// The bytecode for the compute shader to run
+ public PipelineState(GraphicsDevice device, RootSignature rootSignature, ShaderBytecode computeShader)
+ {
+ RootSignaturePointer = rootSignature;
+ ComputeShader = computeShader;
+ RootSignature = RootSignaturePointer;
+
+ NativePipelineState = device.NativeDevice.CreateComputePipelineState(this);
+ }
+
+ ///
+ /// Gets the value for the current shader
+ ///
+ public RootSignature RootSignature { get; }
+
+ ///
+ /// Gets the instance for the current object
+ ///
+ public SharpDX.Direct3D12.PipelineState NativePipelineState { get; }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj
new file mode 100644
index 00000000..581e66ea
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj
@@ -0,0 +1,37 @@
+
+
+
+ netstandard2.0
+ 8.0
+ enable
+ true
+
+
+
+
+ native
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ runtimes\win-x64\native
+ true
+ PreserveNewest
+
+
+
+
diff --git a/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs b/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs
new file mode 100644
index 00000000..bca60382
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs
@@ -0,0 +1,122 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+
+namespace DirectX12GameEngine.Shaders
+{
+ public static class MemberInfoExtensions
+ {
+ public static Type GetElementOrDeclaredType(this Type type) => type.IsArray ? type.GetElementType() : type;
+
+ public static bool IsOverride(this MethodInfo methodInfo)
+ {
+ return methodInfo != methodInfo.GetBaseDefinition();
+ }
+
+ public static IList GetBaseMethods(this MethodInfo methodInfo)
+ {
+ List methodInfos = new List() { methodInfo };
+
+ if (methodInfo.IsOverride())
+ {
+ MethodInfo? currentMethodInfo = methodInfo.DeclaringType.BaseType?.GetMethod(methodInfo.Name);
+
+ while (currentMethodInfo != null)
+ {
+ methodInfos.Add(currentMethodInfo);
+ currentMethodInfo = currentMethodInfo.DeclaringType.BaseType?.GetMethod(currentMethodInfo.Name);
+ }
+ }
+
+ return methodInfos;
+ }
+
+ public static IEnumerable GetNestedTypesInTypeHierarchy(this Type type, BindingFlags bindingAttr)
+ {
+ IEnumerable nestedTypes = type.GetNestedTypes(bindingAttr);
+
+ Type parent = type.BaseType;
+
+ while (parent != null)
+ {
+ nestedTypes = parent.GetNestedTypes(bindingAttr).Concat(nestedTypes);
+ parent = parent.BaseType;
+ }
+
+ return nestedTypes;
+ }
+
+ public static IEnumerable GetMembersInTypeHierarchy(this Type type, BindingFlags bindingAttr)
+ {
+ Dictionary lookup = new Dictionary();
+
+ int index = 0;
+ lookup[type] = index++;
+
+ Type parent = type.BaseType;
+
+ while (parent != null)
+ {
+ lookup[parent] = index;
+ index++;
+ parent = parent.BaseType;
+ }
+
+ return type.GetMembers(bindingAttr).OrderByDescending(prop => lookup[prop.DeclaringType]);
+ }
+
+ public static IEnumerable GetMembersInTypeHierarchyInOrder(this Type type, BindingFlags bindingAttr)
+ {
+ return type.GetMembersInTypeHierarchy(bindingAttr)
+ .GroupBy(m => m.DeclaringType)
+ .Select(g => g.OrderBy(m => m.GetCustomAttribute()?.Order))
+ .SelectMany(m => m);
+ }
+
+ public static IEnumerable GetMembersInOrder(this Type type, BindingFlags bindingAttr)
+ {
+ return type.GetMembers(bindingAttr)
+ .OrderBy(m => m.GetCustomAttribute()?.Order);
+ }
+
+ public static object? GetMemberValue(this MemberInfo memberInfo, object? obj) => memberInfo switch
+ {
+ FieldInfo fieldInfo => obj is null ? null : fieldInfo.GetValue(obj),
+ PropertyInfo propertyInfo => obj is null ? null : propertyInfo.GetValue(obj),
+ _ => null
+ };
+
+ public static Type? GetMemberType(this MemberInfo memberInfo, object? obj) => memberInfo switch
+ {
+ FieldInfo fieldInfo => obj is null ? fieldInfo.FieldType : fieldInfo.GetValue(obj)?.GetType() ?? fieldInfo.FieldType,
+ PropertyInfo propertyInfo => obj is null ? propertyInfo.PropertyType : propertyInfo.GetValue(obj)?.GetType() ?? propertyInfo.PropertyType,
+ _ => null
+ };
+
+ public static Type? GetMemberType(this MemberInfo memberInfo) => memberInfo switch
+ {
+ FieldInfo fieldInfo => fieldInfo.FieldType,
+ PropertyInfo propertyInfo => propertyInfo.PropertyType,
+ _ => null
+ };
+
+ public static ShaderResourceAttribute? GetResourceAttribute(this MemberInfo memberInfo, Type? memberType)
+ {
+ ShaderResourceAttribute? resourceType = memberInfo.GetCustomAttribute();
+
+ if (resourceType is null) return null;
+
+ return resourceType.Override
+ ? resourceType
+ : memberType?.GetCustomAttribute() ?? resourceType;
+ }
+
+ public static bool IsStatic(this MemberInfo memberInfo) => memberInfo switch
+ {
+ FieldInfo fieldInfo => fieldInfo.IsStatic,
+ PropertyInfo propertyInfo => propertyInfo.GetAccessors(true)[0].IsStatic,
+ _ => false
+ };
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/Numerics/UInt2.cs b/src/DirectX12GameEngine.Shaders/Numerics/UInt2.cs
new file mode 100644
index 00000000..719c2b8a
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/Numerics/UInt2.cs
@@ -0,0 +1,9 @@
+namespace DirectX12GameEngine.Shaders.Numerics
+{
+ public struct UInt2
+ {
+ public uint X;
+
+ public uint Y;
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/Numerics/UInt3.cs b/src/DirectX12GameEngine.Shaders/Numerics/UInt3.cs
new file mode 100644
index 00000000..8cd63223
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/Numerics/UInt3.cs
@@ -0,0 +1,13 @@
+namespace DirectX12GameEngine.Shaders.Numerics
+{
+ public struct UInt3
+ {
+ public uint X;
+
+ public uint Y;
+
+ public uint Z;
+
+ public UInt2 XY => new UInt2 { X = X, Y = Y };
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/Numerics/Vector2.cs b/src/DirectX12GameEngine.Shaders/Numerics/Vector2.cs
new file mode 100644
index 00000000..87f937ec
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/Numerics/Vector2.cs
@@ -0,0 +1,7 @@
+namespace DirectX12GameEngine.Shaders.Numerics
+{
+ public struct Vector2
+ {
+ public static float Length(System.Numerics.Vector2 value) => value.Length();
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/Numerics/Vector4.cs b/src/DirectX12GameEngine.Shaders/Numerics/Vector4.cs
new file mode 100644
index 00000000..0c045611
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/Numerics/Vector4.cs
@@ -0,0 +1,28 @@
+namespace DirectX12GameEngine.Shaders.Numerics
+{
+ public struct Vector4
+ {
+ private readonly float[] memory;
+
+ public Vector4(float x, float y, float z, float w)
+ {
+ memory = new float[] { x, y, z, w };
+ }
+
+ public float this[int i]
+ {
+ get => memory[i];
+ set => memory[i] = value;
+ }
+
+ public static implicit operator System.Numerics.Vector4(Vector4 value)
+ {
+ return new System.Numerics.Vector4(value[0], value[1], value[2], value[3]);
+ }
+
+ public static implicit operator Vector4(System.Numerics.Vector4 value)
+ {
+ return new Vector4(value.X, value.Y, value.Z, value.W);
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs
new file mode 100644
index 00000000..ffe9aba0
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs
@@ -0,0 +1,68 @@
+using System;
+using System.IO;
+using DotNetDxc;
+using SharpDX.D3DCompiler;
+
+namespace DirectX12GameEngine.Shaders
+{
+ public static class ShaderCompiler
+ {
+ static ShaderCompiler()
+ {
+ HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn();
+ }
+
+ public static byte[] CompileShaderFile(string filePath, ShaderVersion? version = null, string? entryPoint = null)
+ {
+ string shaderSource = File.ReadAllText(filePath);
+ return CompileShader(shaderSource, version, entryPoint, filePath);
+ }
+
+ public static byte[] CompileShader(string shaderSource, ShaderVersion? version = null, string? entryPoint = null, string filePath = "")
+ {
+ IDxcCompiler compiler = HlslDxcLib.CreateDxcCompiler();
+ IDxcLibrary library = HlslDxcLib.CreateDxcLibrary();
+
+ const uint CP_UTF16 = 1200;
+
+ IDxcBlobEncoding sourceBlob = library.CreateBlobWithEncodingOnHeapCopy(shaderSource, (uint)(shaderSource.Length * 2), CP_UTF16);
+ IDxcOperationResult result = compiler.Compile(sourceBlob, filePath, entryPoint ?? "CSMain", "cs_6_1", new[] { "-Zpr" }, 1, null, 0, library.CreateIncludeHandler());
+
+ if (result.GetStatus() == 0)
+ {
+ IDxcBlob blob = result.GetResult();
+ byte[] bytecode = GetBytesFromBlob(blob);
+
+ return bytecode;
+ }
+ else
+ {
+ string resultText = GetStringFromBlob(library, result.GetErrors());
+ throw new Exception(resultText);
+ }
+ }
+
+ public static unsafe byte[] GetBytesFromBlob(IDxcBlob blob)
+ {
+ byte* pMem = (byte*)blob.GetBufferPointer();
+ uint size = blob.GetBufferSize();
+ byte[] result = new byte[size];
+
+ fixed (byte* pTarget = result)
+ {
+ for (uint i = 0; i < size; i++)
+ {
+ pTarget[i] = pMem[i];
+ }
+ }
+
+ return result;
+ }
+
+ public static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob)
+ {
+ blob = library.GetBlobAstUf16(blob);
+ return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2));
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs
new file mode 100644
index 00000000..84cb358a
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Reflection;
+
+namespace DirectX12GameEngine.Shaders
+{
+ public class ShaderGenerationResult
+ {
+ public ShaderGenerationResult(string shaderSource, string computeShader)
+ {
+ ShaderSource = shaderSource;
+ ComputeShader = computeShader;
+ }
+
+ public string ShaderSource { get; }
+
+ public string ComputeShader { get; set; }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs
new file mode 100644
index 00000000..0aa9f330
--- /dev/null
+++ b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs
@@ -0,0 +1,870 @@
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Numerics;
+using System.Reflection;
+using System.Reflection.Metadata;
+using System.Text.RegularExpressions;
+using DirectX12GameEngine.Graphics.Buffers.Abstract;
+using DirectX12GameEngine.Shaders.Numerics;
+using ICSharpCode.Decompiler;
+using ICSharpCode.Decompiler.CSharp;
+using ICSharpCode.Decompiler.Metadata;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using SharpDX.Direct3D12;
+using Vector2 = System.Numerics.Vector2;
+using Vector4 = System.Numerics.Vector4;
+
+namespace DirectX12GameEngine.Shaders
+{
+ public class ShaderGenerator
+ {
+ private static readonly object compilationLock = new object();
+ private static readonly Dictionary decompilers = new Dictionary();
+ private static readonly IEnumerable peFiles;
+ private static readonly Dictionary typeDefinitions = new Dictionary();
+
+ private static Compilation compilation;
+
+ private readonly List collectedTypes = new List();
+ private readonly BindingFlags bindingAttr;
+ private readonly HlslBindingTracker bindingTracker = new HlslBindingTracker();
+ private readonly object shader;
+ private readonly StringWriter stringWriter = new StringWriter();
+ private readonly IndentedTextWriter writer;
+
+ private ShaderGenerationResult? result;
+
+ static ShaderGenerator()
+ {
+ IEnumerable assemblyPaths;
+
+ if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly().Location))
+ {
+ assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location);
+ }
+ else
+ {
+ assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p =>
+ {
+ try
+ {
+ PEFile peFile = new PEFile(p);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ });
+ }
+
+ var metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p));
+ peFiles = assemblyPaths.Select(p => new PEFile(p));
+
+ compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences);
+
+ AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
+ }
+
+ private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e)
+ {
+ if (!e.LoadedAssembly.IsDynamic)
+ {
+ PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location);
+ compilation = compilation.AddReferences(metadataReference);
+ }
+ }
+
+ public ShaderGenerator(object shader, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)
+ {
+ this.shader = shader;
+ this.bindingAttr = bindingAttr;
+
+ writer = new IndentedTextWriter(stringWriter);
+ }
+
+ public bool IsGenerated => result != null;
+
+ public void AddType(Type type)
+ {
+ CollectStructure(type, null);
+ }
+
+ public RootParameter[] RootParameters { get; private set; }
+
+ public IReadOnlyList ReadWriteBuffers { get; private set; }
+
+ public ShaderGenerationResult GenerateShaderForLambda()
+ {
+ if (result != null) return result;
+
+ if (!(shader is Action action)) throw new InvalidOperationException("Missing lambda shader");
+
+ Type shaderType = action.Method.DeclaringType;
+ object shaderInstance = action.Target;
+
+ var fields = shaderType.GetFields().ToArray();
+
+ // Collect the fields
+ foreach (FieldInfo fieldInfo in fields)
+ {
+ CollectStructure(fieldInfo.FieldType, fieldInfo.GetValue(shaderInstance));
+ }
+
+ // Collect the method
+ CollectTopLevelMethod(action.Method);
+
+ // Writing stage
+ foreach (ShaderTypeDefinition type in collectedTypes)
+ {
+ WriteStructure(type.Type, type.Instance);
+ }
+
+ // Write the fields, assuming that all buffers are unordered access views, and the other fields are constant buffers
+ var parameters = new List();
+ var rwbuffers = new List();
+ foreach (FieldInfo fieldInfo in fields)
+ {
+ Type? memberType = fieldInfo.FieldType;
+
+ if (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == typeof(RWBufferResource<>))
+ {
+ var range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, bindingTracker.UnorderedAccessView);
+ parameters.Add(range);
+ var buffer = fieldInfo.GetValue(shaderInstance);
+ var resource = (GraphicsResource)memberType.GetProperty(nameof(RWBufferResource.Buffer)).GetValue(buffer);
+ rwbuffers.Add(resource);
+ WriteUnorderedAccessView(fieldInfo, memberType, bindingTracker.UnorderedAccessView++);
+ }
+ //else WriteConstantBuffer(fieldInfo, memberType, bindingTracker.ConstantBuffer++);
+ else WriteStaticVariable(fieldInfo, memberType, fieldInfo.GetValue(shaderInstance));
+ }
+ RootParameters = parameters.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray();
+ ReadWriteBuffers = rwbuffers;
+
+ // Write the actual shader body
+ writer.WriteLine("[Shader(\"compute\")]");
+ writer.WriteLine("[NumThreads(5, 5, 1)]");
+ WriteTopLevelMethod(action.Method);
+
+ stringWriter.GetStringBuilder().TrimEnd();
+ writer.WriteLine();
+
+ result = new ShaderGenerationResult(stringWriter.ToString(), "Foo"); /* action.Method.Name */
+
+ return result;
+ }
+
+ private void CollectStructure(Type type, object? obj)
+ {
+ type = type.GetElementOrDeclaredType();
+
+ if (HlslKnownTypes.ContainsKey(type) || collectedTypes.Any(d => d.Type == type)) return;
+
+ ShaderTypeDefinition shaderTypeDefinition = new ShaderTypeDefinition(type, obj);
+
+ if (type.IsEnum)
+ {
+ collectedTypes.Add(shaderTypeDefinition);
+ return;
+ }
+
+ Type parentType = type.BaseType;
+
+ while (parentType != null)
+ {
+ CollectStructure(parentType, obj);
+ parentType = parentType.BaseType;
+ }
+
+ foreach (Type interfaceType in type.GetInterfaces())
+ {
+ CollectStructure(interfaceType, obj);
+ }
+
+ var memberInfos = type.GetMembersInOrder(bindingAttr);
+
+ if (!type.IsInterface)
+ {
+ memberInfos = memberInfos.Where(m => m.IsDefined(typeof(ShaderResourceAttribute)));
+ }
+
+ foreach (MemberInfo memberInfo in memberInfos)
+ {
+ Type? memberType = memberInfo.GetMemberType(obj);
+ ShaderResourceAttribute? resourceType = memberInfo.GetResourceAttribute(memberType);
+
+ if (memberInfo is MethodInfo methodInfo)
+ {
+ if (type.IsInterface || resourceType is ShaderMethodAttribute)
+ {
+ CollectMethod(methodInfo);
+ }
+ }
+ else if (memberType != null && memberType != type)
+ {
+ CollectStructure(memberType, memberInfo.GetMemberValue(obj));
+
+ if (resourceType != null)
+ {
+ shaderTypeDefinition.ResourceDefinitions.Add(new ResourceDefinition(memberType, resourceType));
+ }
+ }
+ }
+
+ collectedTypes.Add(shaderTypeDefinition);
+ }
+
+ private void WriteStructure(Type type, object? obj)
+ {
+ if (type.IsEnum)
+ {
+ writer.WriteLine($"enum class {type.Name}");
+ }
+ else if (type.IsInterface)
+ {
+ writer.WriteLine($"interface {type.Name}");
+ }
+ else
+ {
+ writer.Write($"struct {type.Name}");
+
+ if (type.BaseType != null && type.BaseType != typeof(object) && type.BaseType != typeof(ValueType))
+ {
+ writer.Write($" : {type.BaseType.Name}, ");
+
+ // NOTE: Types might no expose every interface method.
+
+ //foreach (Type interfaceType in type.GetInterfaces())
+ //{
+ // writer.Write(interfaceType.Name + ", ");
+ //}
+
+ stringWriter.GetStringBuilder().Length -= 2;
+ }
+
+ writer.WriteLine();
+ }
+
+ writer.WriteLine("{");
+ writer.Indent++;
+
+ var fieldAndPropertyInfos = type.GetMembersInOrder(bindingAttr | BindingFlags.DeclaredOnly).Where(m => m is FieldInfo || m is PropertyInfo);
+ var methodInfos = type.GetMembersInTypeHierarchyInOrder(bindingAttr).Where(m => m is MethodInfo);
+ var memberInfos = fieldAndPropertyInfos.Concat(methodInfos);
+
+ if (!type.IsInterface && !type.IsEnum)
+ {
+ memberInfos = memberInfos.Where(m => m.IsDefined(typeof(ShaderResourceAttribute)));
+ }
+
+ foreach (MemberInfo memberInfo in memberInfos)
+ {
+ Type? memberType = memberInfo.GetMemberType(obj);
+ ShaderResourceAttribute? resourceType = memberInfo.GetResourceAttribute(memberType);
+
+ if (memberInfo is MethodInfo methodInfo)
+ {
+ if (type.IsInterface || resourceType is ShaderMethodAttribute)
+ {
+ WriteMethod(methodInfo);
+ }
+ }
+ else if (memberType != null && resourceType != null)
+ {
+ if (type.IsEnum)
+ {
+ writer.Write(memberInfo.Name);
+ writer.WriteLine(",");
+ }
+ else
+ {
+ WriteStructureField(memberInfo, memberType);
+ }
+ }
+ }
+
+ stringWriter.GetStringBuilder().TrimEnd();
+
+ writer.Indent--;
+ writer.WriteLine();
+ writer.WriteLine("};");
+ writer.WriteLine();
+
+ if (type.IsEnum) return;
+
+ foreach (MemberInfo memberInfo in memberInfos.Where(m => m.IsStatic()))
+ {
+ Type? memberType = memberInfo.GetMemberType(obj);
+
+ if (memberType != null)
+ {
+ WriteStaticStructureField(memberInfo, memberType);
+ }
+ }
+ }
+
+ private void WriteStructureField(MemberInfo memberInfo, Type memberType)
+ {
+ if (memberInfo.IsStatic())
+ {
+ writer.Write("static");
+ writer.Write(" ");
+ }
+
+ writer.Write($"{HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}");
+
+ int arrayCount = memberType.IsArray ? 2 : 0;
+ writer.Write(GetArrayString(arrayCount));
+
+ writer.Write(GetHlslSemantic(memberInfo.GetCustomAttribute()));
+ writer.WriteLine(";");
+ writer.WriteLine();
+ }
+
+ private void WriteStaticStructureField(MemberInfo memberInfo, Type memberType)
+ {
+ string declaringType = HlslKnownTypes.GetMappedName(memberInfo.DeclaringType);
+ writer.WriteLine($"static {HlslKnownTypes.GetMappedName(memberType)} {declaringType}::{memberInfo.Name};");
+ writer.WriteLine();
+ }
+
+ private void WriteResource(MemberInfo memberInfo, Type memberType, ShaderResourceAttribute resourceType)
+ {
+ switch (resourceType)
+ {
+ case ConstantBufferResourceAttribute _:
+ WriteConstantBuffer(memberInfo, memberType, bindingTracker.ConstantBuffer++);
+ break;
+ case UnorderedAccessViewResourceAttribute _:
+ WriteUnorderedAccessView(memberInfo, memberType, bindingTracker.UnorderedAccessView++);
+ break;
+ case StaticResourceAttribute _:
+ WriteStaticResource(memberInfo, memberType);
+ break;
+ default:
+ throw new NotSupportedException("This shader resource type is not supported.");
+ }
+ }
+
+ private void WriteStaticVariable(MemberInfo memberInfo, Type memberType, object value)
+ {
+ writer.Write($"static {HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}");
+ writer.Write($" = {value};");
+ writer.WriteLine();
+ }
+
+ private void WriteConstantBuffer(MemberInfo memberInfo, Type memberType, int binding)
+ {
+ int arrayCount = memberType.IsArray ? 2 : 0;
+
+ writer.Write($"cbuffer {memberInfo.Name}Buffer");
+ writer.Write(GetHlslSemantic(memberInfo.GetCustomAttribute()));
+ writer.WriteLine($" : register(b{binding})");
+ writer.WriteLine("{");
+ writer.Indent++;
+ writer.WriteLine($"{HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}{GetArrayString(arrayCount)};");
+ writer.Indent--;
+ writer.WriteLine("}");
+ writer.WriteLine();
+ }
+
+ private void WriteUnorderedAccessView(MemberInfo memberInfo, Type memberType, int binding)
+ {
+ writer.Write($"{HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}");
+ writer.Write(" : SV_DispatchThreadId");
+ writer.Write($" : register(u{binding})");
+ writer.WriteLine(";");
+ writer.WriteLine();
+ }
+
+ private void WriteStaticResource(MemberInfo memberInfo, Type memberType)
+ {
+ List generatedMemberInfos = new List();
+
+ foreach (ResourceDefinition resourceDefinition in collectedTypes.First(d => d.Type == memberType).ResourceDefinitions)
+ {
+ MemberInfo generatedMemberInfo = new FakeMemberInfo($"__Generated__{bindingTracker.StaticResource++}__");
+ generatedMemberInfos.Add(generatedMemberInfo);
+
+ WriteResource(generatedMemberInfo, resourceDefinition.MemberType, resourceDefinition.ResourceType);
+ }
+
+ writer.Write($"static {HlslKnownTypes.GetMappedName(memberType)} {memberInfo.Name}");
+ writer.Write(GetHlslSemantic(memberInfo.GetCustomAttribute()));
+
+ if (generatedMemberInfos.Count != 0)
+ {
+ writer.Write(" = { ");
+
+ foreach (MemberInfo generatedMemberInfo in generatedMemberInfos)
+ {
+ writer.Write(generatedMemberInfo.Name);
+ writer.Write(", ");
+ }
+
+ writer.Write("}");
+ }
+
+ writer.WriteLine(";");
+ writer.WriteLine();
+ }
+
+ private static string GetArrayString(int arrayCount) => arrayCount > 0 ? $"[{arrayCount}]" : "";
+
+ private static string GetHlslSemantic(ShaderSemanticAttribute? semanticAttribute)
+ {
+ if (semanticAttribute is null) return "";
+
+ Type semanticType = semanticAttribute.GetType();
+
+ if (HlslKnownSemantics.ContainsKey(semanticType))
+ {
+ string semanticName = HlslKnownSemantics.GetMappedName(semanticType);
+
+ return semanticAttribute is ShaderSemanticWithIndexAttribute semanticAttributeWithIndex
+ ? " : " + semanticName + semanticAttributeWithIndex.Index
+ : " : " + semanticName;
+ }
+
+ throw new NotSupportedException();
+ }
+
+ private void CollectTopLevelMethod(MethodInfo methodInfo)
+ {
+ IList methodInfos = methodInfo.GetBaseMethods();
+
+ for (int depth = methodInfos.Count - 1; depth >= 0; depth--)
+ {
+ MethodInfo currentMethodInfo = methodInfos[depth];
+ CollectMethod(currentMethodInfo);
+ }
+ }
+
+ private void CollectMethod(MethodInfo methodInfo)
+ {
+ GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel);
+
+ ShaderSyntaxCollector syntaxCollector = new ShaderSyntaxCollector(this, semanticModel);
+ syntaxCollector.Visit(root);
+ }
+
+ private void WriteTopLevelMethod(MethodInfo methodInfo)
+ {
+ IList methodInfos = methodInfo.GetBaseMethods();
+
+ for (int depth = methodInfos.Count - 1; depth >= 0; depth--)
+ {
+ MethodInfo currentMethodInfo = methodInfos[depth];
+ WriteMethod(currentMethodInfo, depth);
+ }
+ }
+
+ private void WriteMethod(MethodInfo methodInfo, int depth = 0)
+ {
+ GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel);
+
+ ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(this, semanticModel, true, depth);
+ root = syntaxRewriter.Visit(root);
+
+ string shaderSource = root.ToFullString();
+ shaderSource = shaderSource.Replace("internal void b__0", "void Foo");
+ shaderSource = shaderSource.Replace("uint3 id", "uint3 id : SV_DispatchThreadId");
+
+ // TODO: See why the System namespace in System.Math is not present in UWP projects.
+ shaderSource = shaderSource.Replace("Math.Max", "max");
+ shaderSource = shaderSource.Replace("Math.Pow", "pow");
+ shaderSource = shaderSource.Replace("Math.Sin", "sin");
+
+ shaderSource = shaderSource.Replace("vector", "vec");
+ shaderSource = Regex.Replace(shaderSource, @"\d+[fF]", m => m.Value.Replace("f", ""));
+
+ // Indent every line
+ string indent = "";
+
+ for (int i = 0; i < writer.Indent; i++)
+ {
+ indent += IndentedTextWriter.DefaultTabString;
+ }
+
+ shaderSource = shaderSource.Replace(Environment.NewLine, Environment.NewLine + indent).TrimEnd(' ');
+
+ writer.WriteLine(shaderSource);
+ }
+
+ private static void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode root, out SemanticModel semanticModel)
+ {
+ lock (compilationLock)
+ {
+ GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle);
+
+ if (!decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler))
+ {
+ decompiler = CreateDecompiler(assemblyPath);
+ decompilers.Add(assemblyPath, decompiler);
+ }
+
+ string sourceCode = decompiler.DecompileAsString(methodHandle);
+
+ SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
+ root = syntaxTree.GetRoot();
+
+ compilation = compilation.AddSyntaxTrees(syntaxTree);
+ semanticModel = compilation.GetSemanticModel(syntaxTree);
+ }
+ }
+
+ private static void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle)
+ {
+ assemblyPath = methodInfo.DeclaringType.Assembly.Location;
+
+ if (!string.IsNullOrEmpty(assemblyPath))
+ {
+ methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
+ }
+ else
+ {
+ if (!typeDefinitions.TryGetValue(methodInfo.DeclaringType, out var tuple))
+ {
+ foreach (PEFile peFile in peFiles)
+ {
+ TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName);
+
+ if (!typeDefinitionHandle.IsNil)
+ {
+ tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle));
+ typeDefinitions.Add(methodInfo.DeclaringType, tuple);
+
+ break;
+ }
+ }
+
+ if (tuple.PEFile is null) throw new InvalidOperationException();
+ }
+
+ PEFile peFileForMethod = tuple.PEFile;
+ TypeDefinition typeDefinition = tuple.TypeDefinition;
+
+ assemblyPath = peFileForMethod.FileName;
+
+ methodHandle = typeDefinition.GetMethods()
+ .Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name))
+ .First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length);
+ }
+ }
+
+ private static CSharpDecompiler CreateDecompiler(string assemblyPath)
+ {
+ UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard");
+
+ DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest)
+ {
+ ObjectOrCollectionInitializers = false,
+ UsingDeclarations = false
+ };
+
+ decompilerSettings.CSharpFormattingOptions.IndentationString = IndentedTextWriter.DefaultTabString;
+
+ return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings);
+ }
+
+ internal static class HlslKnownAttributes
+ {
+ private static readonly HashSet allowedAttributes = new HashSet()
+ {
+ typeof(NumThreadsAttribute).FullName,
+ typeof(ShaderAttribute).FullName
+ };
+
+ public static bool Contains(string name)
+ {
+ return HlslKnownSemantics.ContainsKey(name) || allowedAttributes.Contains(name);
+ }
+ }
+
+ internal static class HlslKnownSemantics
+ {
+ private static readonly Dictionary knownSemantics = new Dictionary()
+ {
+ { typeof(PositionSemanticAttribute).FullName, "Position" },
+ { typeof(NormalSemanticAttribute).FullName, "Normal" },
+ { typeof(TextureCoordinateSemanticAttribute).FullName, "TexCoord" },
+ { typeof(ColorSemanticAttribute).FullName, "Color" },
+ { typeof(TangentSemanticAttribute).FullName, "Tangent" },
+
+ { typeof(SystemTargetSemanticAttribute).FullName, "SV_Target" },
+ { typeof(SystemDispatchThreadIdSemanticAttribute).FullName, "SV_DispatchThreadId" },
+ { typeof(SystemIsFrontFaceSemanticAttribute).FullName, "SV_IsFrontFace" },
+ { typeof(SystemInstanceIdSemanticAttribute).FullName, "SV_InstanceId" },
+ { typeof(SystemPositionSemanticAttribute).FullName, "SV_Position" },
+ { typeof(SystemRenderTargetArrayIndexSemanticAttribute).FullName, "SV_RenderTargetArrayIndex" }
+ };
+
+ public static bool ContainsKey(Type type)
+ {
+ return knownSemantics.ContainsKey(type.GetElementOrDeclaredType().FullName);
+ }
+
+ public static bool ContainsKey(string name)
+ {
+ return knownSemantics.ContainsKey(name);
+ }
+
+ public static string GetMappedName(Type type)
+ {
+ return knownSemantics[type.GetElementOrDeclaredType().FullName];
+ }
+
+ public static string GetMappedName(string name)
+ {
+ return knownSemantics[name];
+ }
+ }
+
+ internal static class HlslKnownTypes
+ {
+ private static readonly Dictionary knownTypes = new Dictionary()
+ {
+ { typeof(void).FullName, "void" },
+ { typeof(bool).FullName, "bool" },
+ { typeof(uint).FullName, "uint" },
+ { typeof(int).FullName, "int" },
+ { typeof(double).FullName, "double" },
+ { typeof(float).FullName, "float" },
+ { typeof(Vector2).FullName, "float2" },
+ { typeof(Vector3).FullName, "float3" },
+ { typeof(Vector4).FullName, "float4" },
+ { typeof(Numerics.Vector4).FullName, "float4" },
+ { typeof(Numerics.UInt2).FullName, "uint2" },
+ { typeof(Numerics.UInt3).FullName, "uint3" },
+ { typeof(Matrix4x4).FullName, "float4x4" },
+ { typeof(SamplerResource).FullName, "SamplerState" },
+ { typeof(SamplerComparisonResource).FullName, "SamplerComparisonState" },
+ { typeof(Texture2DResource).FullName, "Texture2D" },
+ { typeof(Texture2DArrayResource).FullName, "Texture2DArray" },
+ { typeof(TextureCubeResource).FullName, "TextureCube" },
+ { typeof(RWBufferResource<>).FullName, "RWBuffer" },
+ { typeof(RWTexture2DResource<>).FullName, "RWTexture2D" },
+ };
+
+ public static bool ContainsKey(Type type)
+ {
+ type = type.GetElementOrDeclaredType();
+ string typeFullName = type.Namespace + Type.Delimiter + type.Name;
+
+ return knownTypes.ContainsKey(typeFullName);
+ }
+
+ public static bool ContainsKey(string name)
+ {
+ int indexOfOpenBracket = name.IndexOf('<');
+ name = indexOfOpenBracket >= 0 ? name.Remove(indexOfOpenBracket) + "`1" : name;
+
+ return knownTypes.ContainsKey(name);
+ }
+
+ public static string GetMappedName(Type type)
+ {
+ type = type.GetElementOrDeclaredType();
+ string typeFullName = type.Namespace + Type.Delimiter + type.Name;
+
+ string mappedName = knownTypes.TryGetValue(typeFullName, out string mapped) ? mapped : type.Name;
+
+ return type.IsGenericType ? mappedName + $"<{GetMappedName(type.GetGenericArguments()[0])}>" : mappedName;
+ }
+
+ public static string GetMappedName(string name)
+ {
+ int indexOfOpenBracket = name.IndexOf('<');
+
+ string genericArguments = indexOfOpenBracket >= 0 ? name.Substring(indexOfOpenBracket) : "";
+ name = indexOfOpenBracket >= 0 ? name.Remove(indexOfOpenBracket) + "`1" : name;
+
+ string mappedName = knownTypes.TryGetValue(name, out string mapped) ? mapped : Regex.Match(name, @"[^\.]+$").Value;
+
+ return mappedName + genericArguments;
+ }
+ }
+
+ internal static class HlslKnownMethods
+ {
+ private static readonly Dictionary knownMethods = new Dictionary()
+ {
+ { "System.Math.Cos", "cos" },
+ { "System.MathF.Cos", "cos" },
+ { "System.Math.Max", "max" },
+ { "System.Math.Pow", "pow" },
+ { "System.MathF.Pow", "pow" },
+ { "System.Math.Sin", "sin" },
+ { "System.MathF.Sin", "sin" },
+ { "System.Math.PI", "3.1415926535897931" },
+ { "System.MathF.PI", "3.14159274f" },
+
+ { "DirectX12GameEngine.Shaders.Numerics.Vector2.Length", "length" },
+
+ { "DirectX12GameEngine.Shaders.Numerics.UInt2.X", ".x" },
+ { "DirectX12GameEngine.Shaders.Numerics.UInt2.Y", ".y" },
+
+ { "DirectX12GameEngine.Shaders.Numerics.UInt3.X", ".x" },
+ { "DirectX12GameEngine.Shaders.Numerics.UInt3.Y", ".y" },
+ { "DirectX12GameEngine.Shaders.Numerics.UInt3.Z", ".z" },
+ { "DirectX12GameEngine.Shaders.Numerics.UInt3.XY", ".xy" },
+
+ { "System.Numerics.Vector3.X", ".x" },
+ { "System.Numerics.Vector3.Y", ".y" },
+ { "System.Numerics.Vector3.Z", ".z" },
+ { "System.Numerics.Vector3.Cross", "cross" },
+ { "System.Numerics.Vector3.Dot", "dot" },
+ { "System.Numerics.Vector3.Lerp", "lerp" },
+ { "System.Numerics.Vector3.Transform", "mul" },
+ { "System.Numerics.Vector3.TransformNormal", "mul" },
+ { "System.Numerics.Vector3.Normalize", "normalize" },
+ { "System.Numerics.Vector3.Zero", "(float3)0" },
+ { "System.Numerics.Vector3.One", "float3(1.0f, 1.0f, 1.0f)" },
+ { "System.Numerics.Vector3.UnitX", "float3(1.0f, 0.0f, 0.0f)" },
+ { "System.Numerics.Vector3.UnitY", "float3(0.0f, 1.0f, 0.0f)" },
+ { "System.Numerics.Vector3.UnitZ", "float3(0.0f, 0.0f, 1.0f)" },
+
+ { "System.Numerics.Vector4.X", ".x" },
+ { "System.Numerics.Vector4.Y", ".y" },
+ { "System.Numerics.Vector4.Z", ".z" },
+ { "System.Numerics.Vector4.W", ".w" },
+ { "System.Numerics.Vector4.Lerp", "lerp" },
+ { "System.Numerics.Vector4.Transform", "mul" },
+ { "System.Numerics.Vector4.Normalize", "normalize" },
+ { "System.Numerics.Vector4.Zero", "(float4)0" },
+ { "System.Numerics.Vector4.One", "float4(1.0f, 1.0f, 1.0f, 1.0f)" },
+
+ { "System.Numerics.Matrix4x4.Multiply", "mul" },
+ { "System.Numerics.Matrix4x4.Transpose", "transpose" },
+ { "System.Numerics.Matrix4x4.Translation", "[3].xyz" },
+ { "System.Numerics.Matrix4x4.M11", "[0][0]" },
+ { "System.Numerics.Matrix4x4.M12", "[0][1]" },
+ { "System.Numerics.Matrix4x4.M13", "[0][2]" },
+ { "System.Numerics.Matrix4x4.M14", "[0][3]" },
+ { "System.Numerics.Matrix4x4.M21", "[1][0]" },
+ { "System.Numerics.Matrix4x4.M22", "[1][1]" },
+ { "System.Numerics.Matrix4x4.M23", "[1][2]" },
+ { "System.Numerics.Matrix4x4.M24", "[1][3]" },
+ { "System.Numerics.Matrix4x4.M31", "[2][0]" },
+ { "System.Numerics.Matrix4x4.M32", "[2][1]" },
+ { "System.Numerics.Matrix4x4.M33", "[2][2]" },
+ { "System.Numerics.Matrix4x4.M34", "[2][3]" },
+ { "System.Numerics.Matrix4x4.M41", "[3][0]" },
+ { "System.Numerics.Matrix4x4.M42", "[3][1]" },
+ { "System.Numerics.Matrix4x4.M43", "[3][2]" },
+ { "System.Numerics.Matrix4x4.M44", "[3][3]" }
+ };
+
+ public static bool Contains(ISymbol containingMemberSymbol, ISymbol memberSymbol)
+ {
+ string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString();
+
+ if (knownMethods.ContainsKey(fullTypeName + Type.Delimiter + memberSymbol.Name))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ public static string? GetMappedName(ISymbol containingMemberSymbol, ISymbol memberSymbol)
+ {
+ string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString();
+
+ if (knownMethods.TryGetValue(fullTypeName + Type.Delimiter + memberSymbol.Name, out string mapped))
+ {
+ if (!memberSymbol.IsStatic)
+ {
+ return containingMemberSymbol.Name + mapped;
+ }
+
+ return mapped;
+ }
+
+ if (memberSymbol.IsStatic)
+ {
+ return containingMemberSymbol.Name + "::" + memberSymbol.Name;
+ }
+
+ return null;
+ }
+ }
+
+ private class HlslBindingTracker
+ {
+ public int ConstantBuffer { get; set; }
+
+ public int Sampler { get; set; }
+
+ public int Texture { get; set; }
+
+ public int UnorderedAccessView { get; set; }
+
+ public int StaticResource { get; set; }
+ }
+
+ private class ShaderTypeDefinition
+ {
+ public ShaderTypeDefinition(Type type, object? instance)
+ {
+ Type = type;
+ Instance = instance;
+ }
+
+ public object? Instance { get; }
+
+ public Type Type { get; }
+
+ public List ResourceDefinitions { get; } = new List();
+ }
+
+ private class ResourceDefinition
+ {
+ public ResourceDefinition(Type memberType, ShaderResourceAttribute resourceType)
+ {
+ MemberType = memberType;
+ ResourceType = resourceType;
+ }
+
+ public Type MemberType { get; }
+
+ public ShaderResourceAttribute ResourceType { get; }
+ }
+
+ private class FakeMemberInfo : MemberInfo
+ {
+ public FakeMemberInfo(string name)
+ {
+ Name = name;
+ }
+
+ public override Type DeclaringType => throw new NotImplementedException();
+
+ public override MemberTypes MemberType => MemberTypes.Field;
+
+ public override string Name { get; }
+
+ public override Type ReflectedType => throw new NotImplementedException();
+
+ public override object[] GetCustomAttributes(bool inherit)
+ {
+ return Array.Empty