diff --git a/samples/NetCoreComputeShaderSample/NetCoreComputeShaderSample.csproj b/samples/NetCoreComputeShaderSample/NetCoreComputeShaderSample.csproj
new file mode 100644
index 00000000..bfb20336
--- /dev/null
+++ b/samples/NetCoreComputeShaderSample/NetCoreComputeShaderSample.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Exe
+ netcoreapp3.0
+
+
+
+
+
+
+
diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/samples/NetCoreComputeShaderSample/Program.cs
similarity index 66%
rename from src/DirectX12ComputeShaderSample/Program.cs
rename to samples/NetCoreComputeShaderSample/Program.cs
index 48be6ecd..de9ba68f 100644
--- a/src/DirectX12ComputeShaderSample/Program.cs
+++ b/samples/NetCoreComputeShaderSample/Program.cs
@@ -1,11 +1,9 @@
-using DirectX12GameEngine.Shaders;
-using System;
+using System;
using System.Linq;
-using DirectX12GameEngine.Graphics.Buffers;
-using DirectX12GameEngine.Shaders.Primitives;
-using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer;
+using ComputeSharp;
+using ComputeSharp.Graphics.Buffers;
-namespace DirectX12ComputeShaderSample
+namespace NetCoreComputeShaderSample
{
public class Program
{
@@ -20,29 +18,26 @@ namespace DirectX12ComputeShaderSample
array[i] = i + 1;
}
- using Buffer gpuBuffer = Buffer.UnorderedAccess.New(Gpu.Default, array.AsSpan());
+ // Print the initial matrix
+ Console.WriteLine("Before:");
+ PrintMatrix(array, width, height);
- // Variables for closure
- uint size = (uint)width;
- var data = gpuBuffer.GetGpuResource();
+ using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
// Shader body
Action action = id =>
{
- data[id.X + id.Y * size] *= 2;
+ uint offset = id.X + id.Y * (uint)width;
+ gpuBuffer[offset] *= 2;
};
// Run the shader
Gpu.Default.For(100, action);
- // Print matrix
+ // Get the data back
+ gpuBuffer.GetData(array);
- Console.WriteLine("Before:");
- PrintMatrix(array, width, height);
-
- gpuBuffer.GetData(array.AsSpan());
-
- Console.WriteLine();
+ // Print the updated matrix
Console.WriteLine("After:");
PrintMatrix(array, width, height);
}
diff --git a/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs
similarity index 90%
rename from src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs
rename to src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs
index 1ffa6721..46f42eec 100644
--- a/src/DirectX12GameEngine.Graphics/Buffers/Abstract/GraphicsResource.cs
+++ b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs
@@ -1,7 +1,7 @@
using System;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics.Buffers.Abstract
+namespace ComputeSharp.Graphics.Buffers.Abstract
{
///
/// An abstract that represents a graphics resource object
@@ -35,12 +35,12 @@ namespace DirectX12GameEngine.Graphics.Buffers.Abstract
///
/// Gets the instance for the current resource
///
- protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; }
+ protected internal CpuDescriptorHandle? NativeCpuDescriptorHandle { get; protected set; }
///
/// Gets the instance for the current resource
///
- protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; }
+ protected internal GpuDescriptorHandle? NativeGpuDescriptorHandle { get; protected set; }
///
/// Maps the current resource to a specified subresource
diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer.cs b/src/ComputeSharp.Graphics/Buffers/Buffer.cs
new file mode 100644
index 00000000..703bc324
--- /dev/null
+++ b/src/ComputeSharp.Graphics/Buffers/Buffer.cs
@@ -0,0 +1,175 @@
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using ComputeSharp.Graphics.Buffers.Abstract;
+using ComputeSharp.Graphics.Helpers;
+using SharpDX.Direct3D12;
+
+namespace ComputeSharp.Graphics.Buffers
+{
+ ///
+ /// A representing a typed buffer stored on GPU memory
+ ///
+ /// The type of items stored on the buffer
+ public class Buffer : GraphicsResource where T : unmanaged
+ {
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The associated with the current instance
+ /// The number of items to store in the current buffer
+ /// The heap type for the current buffer
+ protected internal Buffer(GraphicsDevice device, int size, HeapType heapType) : base(device)
+ {
+ Size = size;
+ ElementSizeInBytes = Unsafe.SizeOf();
+ SizeInBytes = Size * ElementSizeInBytes;
+ HeapType = heapType;
+
+ ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None;
+ ResourceDescription description = ResourceDescription.Buffer(SizeInBytes, flags);
+ ResourceStates resourceStates = heapType switch
+ {
+ HeapType.Upload => ResourceStates.GenericRead,
+ HeapType.Readback => ResourceStates.CopyDestination,
+ _ => ResourceStates.Common
+ };
+
+ NativeResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, resourceStates);
+
+ (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = heapType switch
+ {
+ HeapType.Default => CreateUnorderedAccessView(),
+ HeapType.Upload => CreateConstantBufferView(),
+ _ => default
+ };
+ }
+
+ ///
+ /// Creates the descriptors for a constant buffer
+ ///
+ /// The CPU and GPU handles for a constant buffer
+ [Pure]
+ private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
+ {
+ (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
+
+ int constantBufferSize = (SizeInBytes + 255) & ~255;
+
+ ConstantBufferViewDescription description = new ConstantBufferViewDescription
+ {
+ BufferLocation = NativeResource!.GPUVirtualAddress,
+ SizeInBytes = constantBufferSize
+ };
+
+ GraphicsDevice.NativeDevice.CreateConstantBufferView(description, cpuHandle);
+
+ return (cpuHandle, gpuHandle);
+ }
+
+ ///
+ /// Creates the descriptors for a read write buffer
+ ///
+ /// The CPU and GPU handles for a read write buffer
+ [Pure]
+ private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
+ {
+ (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
+
+ UnorderedAccessViewDescription description = new UnorderedAccessViewDescription
+ {
+ Format = SharpDX.DXGI.Format.R32_Float,
+ Dimension = UnorderedAccessViewDimension.Buffer,
+ Buffer = { ElementCount = Size }
+ };
+
+ GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
+
+ return (cpuHandle, gpuHandle);
+ }
+
+ ///
+ /// Gets the size of the current buffer, as in the number of values it contains
+ ///
+ public int Size { get; }
+
+ ///
+ /// Gets the size in bytes of the current buffer
+ ///
+ public int SizeInBytes { get; }
+
+ ///
+ /// Gets the size in bytes of each value contained in the buffer
+ ///
+ public int ElementSizeInBytes { get; }
+
+ ///
+ /// Gets the heap type being targeted by the current buffer
+ ///
+ public HeapType HeapType { get; }
+
+ ///
+ /// Reads the contents of the current instance and returns an array
+ ///
+ /// A array with the contents of the current buffer
+ [Pure]
+ public T[] GetData()
+ {
+ T[] data = new T[Size];
+ GetData(data);
+
+ return data;
+ }
+
+ ///
+ /// Reads the contents of the current instance and writes them into a target
+ ///
+ /// The input to write data to
+ public void GetData(Span span)
+ {
+ // Create a temporary readback buffer if the current buffer type is read write (can't be read from directly)
+ if (HeapType == HeapType.Default)
+ {
+ using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, HeapType.Readback);
+ using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
+
+ copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes);
+ copyCommandList.Flush(true);
+
+ readbackBaffer.GetData(span);
+ }
+ else
+ {
+ // Map and read the memory back directly
+ Map(0);
+ MemoryHelper.Copy(MappedResource, span);
+ Unmap(0);
+ }
+ }
+
+ ///
+ /// Writes the contents of a given to the current instance
+ ///
+ /// The input to read data from
+ public void SetData(Span span)
+ {
+ // Create a temporary upload buffer if the current buffer type is read write (can't be written to directly)
+ if (HeapType == HeapType.Default)
+ {
+ using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, HeapType.Upload);
+ using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
+
+ uploadBuffer.SetData(span);
+ copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes);
+ copyCommandList.Flush(true);
+ }
+ else
+ {
+ // Map and copy the memory directly
+ Map(0);
+ MemoryHelper.Copy(span, MappedResource);
+ Unmap(0);
+ }
+ }
+ }
+}
diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs
new file mode 100644
index 00000000..28dc83ff
--- /dev/null
+++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using ComputeSharp.Graphics;
+using ComputeSharp.Graphics.Buffers;
+
+namespace ComputeSharp
+{
+ ///
+ /// A with extension methods for the type to allocate buffers
+ ///
+ public static class BufferExtensions
+ {
+ ///
+ /// Allocates a new read write buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The size of the buffer to allocate
+ /// A zeroed instance of size
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, int size) where T : unmanaged
+ {
+ return new ReadWriteBuffer(device, size);
+ }
+
+ ///
+ /// Allocates a new read write buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input array with the data to copy on the allocated buffer
+ /// A read write instance with the contents of the input array
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, T[] array) where T : unmanaged
+ {
+ return device.AllocateReadWriteBuffer(array.AsSpan());
+ }
+
+ ///
+ /// Allocates a new read write buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input 2D array with the data to copy on the allocated buffer
+ /// A read write instance with the contents of the input 2D array
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged
+ {
+ fixed (T* p = array)
+ {
+ Span span = new Span(p, array.Length);
+ return device.AllocateReadWriteBuffer(span);
+ }
+ }
+
+ ///
+ /// Allocates a new read write buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input with the data to copy on the allocated buffer
+ /// A read write instance with the contents of the input
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, Span span) where T : unmanaged
+ {
+ ReadWriteBuffer buffer = new ReadWriteBuffer(device, span.Length);
+ buffer.SetData(span);
+
+ return buffer;
+ }
+
+ ///
+ /// Allocates a new constant buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input array with the data to copy on the allocated buffer
+ /// A constant instance with the contents of the input array
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged
+ {
+ return device.AllocateConstantBuffer(array.AsSpan());
+ }
+
+ ///
+ /// Allocates a new constant buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input 2D array with the data to copy on the allocated buffer
+ /// A constant instance with the contents of the input 2D array
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static unsafe ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged
+ {
+ fixed (T* p = array)
+ {
+ Span span = new Span(p, array.Length);
+ return device.AllocateConstantBuffer(span);
+ }
+ }
+
+ ///
+ /// Allocates a new constant buffer with the specified parameters
+ ///
+ /// The type of items to store in the buffer
+ /// The instance to use to allocate the buffer
+ /// The input with the data to copy on the allocated buffer
+ /// A constant instance with the contents of the input
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) where T : unmanaged
+ {
+ ReadOnlyBuffer buffer = new ReadOnlyBuffer(device, span.Length);
+ buffer.SetData(span);
+
+ return buffer;
+ }
+ }
+}
diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs
new file mode 100644
index 00000000..c86d4084
--- /dev/null
+++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs
@@ -0,0 +1,26 @@
+using System;
+using SharpDX.Direct3D12;
+
+namespace ComputeSharp.Graphics.Buffers
+{
+ ///
+ /// A representing a typed read write buffer stored on GPU memory
+ ///
+ /// The type of items stored on the buffer
+ public sealed class ReadOnlyBuffer : Buffer where T : unmanaged
+ {
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The associated with the current instance
+ /// The number of items to store in the current buffer
+ internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Upload) { }
+
+ ///
+ /// Gets a single value from the current read write buffer
+ ///
+ /// The index of the value to get
+ /// This API can only be used from a compute shader, and will always throw if used anywhere else
+ public T this[uint i] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
+ }
+}
diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs
new file mode 100644
index 00000000..ded6d1e9
--- /dev/null
+++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs
@@ -0,0 +1,30 @@
+using System;
+using SharpDX.Direct3D12;
+
+namespace ComputeSharp.Graphics.Buffers
+{
+ ///
+ /// A representing a typed read write buffer stored on GPU memory
+ ///
+ /// The type of items stored on the buffer
+ public sealed class ReadWriteBuffer : Buffer where T : unmanaged
+ {
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The associated with the current instance
+ /// The number of items to store in the current buffer
+ internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Default) { }
+
+ ///
+ /// Gets or sets a single value from the current read write buffer
+ ///
+ /// The index of the value to get or set
+ /// This API can only be used from a compute shader, and will always throw if used anywhere else
+ public T this[uint i]
+ {
+ get => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
+ set => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs b/src/ComputeSharp.Graphics/CommandAllocatorPool.cs
similarity index 98%
rename from src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs
rename to src/ComputeSharp.Graphics/CommandAllocatorPool.cs
index 1c130675..a14dccd0 100644
--- a/src/DirectX12GameEngine.Graphics/CommandAllocatorPool.cs
+++ b/src/ComputeSharp.Graphics/CommandAllocatorPool.cs
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
internal sealed class CommandAllocatorPool : IDisposable
{
diff --git a/src/DirectX12GameEngine.Graphics/CommandList.cs b/src/ComputeSharp.Graphics/CommandList.cs
similarity index 94%
rename from src/DirectX12GameEngine.Graphics/CommandList.cs
rename to src/ComputeSharp.Graphics/CommandList.cs
index 341aa967..355f1981 100644
--- a/src/DirectX12GameEngine.Graphics/CommandList.cs
+++ b/src/ComputeSharp.Graphics/CommandList.cs
@@ -1,8 +1,8 @@
using System;
-using DirectX12GameEngine.Graphics.Buffers.Abstract;
+using ComputeSharp.Graphics.Buffers.Abstract;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
public sealed class CommandList : IDisposable
{
@@ -110,7 +110,8 @@ namespace DirectX12GameEngine.Graphics
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
{
- SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
+ if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor");
+ SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value);
}
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
@@ -130,7 +131,8 @@ namespace DirectX12GameEngine.Graphics
public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
{
- SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
+ if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor");
+ SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value);
}
public void SetComputeRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
diff --git a/src/DirectX12GameEngine.Graphics/CompiledCommandList.cs b/src/ComputeSharp.Graphics/CompiledCommandList.cs
similarity index 93%
rename from src/DirectX12GameEngine.Graphics/CompiledCommandList.cs
rename to src/ComputeSharp.Graphics/CompiledCommandList.cs
index a4bc4f07..57e2a7ff 100644
--- a/src/DirectX12GameEngine.Graphics/CompiledCommandList.cs
+++ b/src/ComputeSharp.Graphics/CompiledCommandList.cs
@@ -1,6 +1,6 @@
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
public sealed class CompiledCommandList
{
diff --git a/src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj
similarity index 78%
rename from src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj
rename to src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj
index 50891f1b..497079a7 100644
--- a/src/DirectX12GameEngine.Core/DirectX12GameEngine.Core.csproj
+++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj
@@ -2,11 +2,14 @@
netstandard2.0
+ 8.0
+ enable
true
+
diff --git a/src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs b/src/ComputeSharp.Graphics/DescriptorAllocator.cs
similarity index 98%
rename from src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs
rename to src/ComputeSharp.Graphics/DescriptorAllocator.cs
index ff795e41..5a041bf2 100644
--- a/src/DirectX12GameEngine.Graphics/DescriptorAllocator.cs
+++ b/src/ComputeSharp.Graphics/DescriptorAllocator.cs
@@ -1,7 +1,7 @@
using System;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
internal sealed class DescriptorAllocator : IDisposable
{
diff --git a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs
similarity index 96%
rename from src/DirectX12GameEngine.Graphics/GraphicsDevice.cs
rename to src/ComputeSharp.Graphics/GraphicsDevice.cs
index 42be36df..8aeb3983 100644
--- a/src/DirectX12GameEngine.Graphics/GraphicsDevice.cs
+++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs
@@ -3,7 +3,7 @@ using System.Threading;
using SharpDX.Direct3D;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
public sealed class GraphicsDevice : IDisposable
{
@@ -15,6 +15,7 @@ namespace DirectX12GameEngine.Graphics
if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer();
#endif
NativeDevice = new Device(null, FeatureLevel);
+ WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin;
NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute));
NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Copy));
@@ -40,6 +41,11 @@ namespace DirectX12GameEngine.Graphics
CopyCommandList.Close();
}
+ ///
+ /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width")
+ ///
+ public int WavefrontSize { get; }
+
public CommandList CommandList { get; }
public CommandList CopyCommandList { get; }
diff --git a/src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs b/src/ComputeSharp.Graphics/GraphicsResourceUsage.cs
similarity index 75%
rename from src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs
rename to src/ComputeSharp.Graphics/GraphicsResourceUsage.cs
index b4299070..64448684 100644
--- a/src/DirectX12GameEngine.Graphics/GraphicsResourceUsage.cs
+++ b/src/ComputeSharp.Graphics/GraphicsResourceUsage.cs
@@ -1,4 +1,4 @@
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
public enum GraphicsHeapType
{
diff --git a/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs
similarity index 97%
rename from src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs
rename to src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs
index 559eabee..6e3a516b 100644
--- a/src/DirectX12GameEngine.Core/Helpers/MemoryHelper.cs
+++ b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs
@@ -1,7 +1,7 @@
using System;
using System.Runtime.CompilerServices;
-namespace DirectX12GameEngine.Core.Helpers
+namespace ComputeSharp.Graphics.Helpers
{
///
/// A with some helper methods to copy data between memory areas
diff --git a/src/DirectX12GameEngine.Graphics/PipelineState.cs b/src/ComputeSharp.Graphics/PipelineState.cs
similarity index 97%
rename from src/DirectX12GameEngine.Graphics/PipelineState.cs
rename to src/ComputeSharp.Graphics/PipelineState.cs
index c74c8967..c7dcdc5e 100644
--- a/src/DirectX12GameEngine.Graphics/PipelineState.cs
+++ b/src/ComputeSharp.Graphics/PipelineState.cs
@@ -1,6 +1,6 @@
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Graphics
+namespace ComputeSharp.Graphics
{
///
/// A representing a custom pipeline state for a compute operation
diff --git a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj
similarity index 80%
rename from src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj
rename to src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj
index 936e6672..086f0e66 100644
--- a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj
+++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj
@@ -18,8 +18,7 @@
-
-
+
@@ -36,11 +35,7 @@
-
-
-
-
-
+
PreserveNewest
diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs
new file mode 100644
index 00000000..d7739008
--- /dev/null
+++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs
@@ -0,0 +1,67 @@
+using System.Diagnostics.Contracts;
+using System.Linq;
+using ComputeSharp.Shaders.Mappings;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace ComputeSharp.Shaders.Extensions
+{
+ ///
+ /// A with some extension methods for C# syntax nodes
+ ///
+ public static class SyntaxNodeExtensions
+ {
+ ///
+ /// Checks a value and replaces the value type to be HLSL compatible, if needed
+ ///
+ /// The type of the input instance
+ /// The input to check and modify if needed
+ /// The to use for the input node
+ /// A instance that represents a type compatible with HLSL
+ [Pure]
+ public static TRoot ReplaceType(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
+ {
+ string value = HlslKnownTypes.GetMappedName(type.ToString());
+
+ // If the HLSL mapped full type name equals the original type, just return the input node
+ if (value == type.ToString()) return node;
+
+ // Process and return the type name
+ TypeSyntax newType = SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia());
+ return node.ReplaceNode(type, newType);
+ }
+
+ ///
+ /// Checks a instance and replaces it to be HLSL compatible, if needed
+ ///
+ /// The input to check and modify if needed
+ /// The to use to load symbols for the input node
+ /// A instance that is compatible with HLSL
+ [Pure]
+ public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel)
+ {
+ SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression);
+ SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
+
+ ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
+
+ // If the input member has no symbol or is not a field, property or method, just return it
+ if (memberSymbol is null ||
+ memberSymbol.Kind != SymbolKind.Field &&
+ memberSymbol.Kind != SymbolKind.Property &&
+ memberSymbol.Kind != SymbolKind.Method)
+ {
+ return node;
+ }
+
+ // Process the input node if it's a known method invocation
+ if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
+ {
+ return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
+ }
+
+ return node;
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
similarity index 95%
rename from src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs
rename to src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
index 6e33493c..143e087e 100644
--- a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs
+++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownMethods.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.CodeAnalysis;
-namespace DirectX12GameEngine.Shaders.Mappings
+namespace ComputeSharp.Shaders.Mappings
{
///
/// A that contains and maps known HLSL method names to common .NET method
@@ -30,9 +30,9 @@ namespace DirectX12GameEngine.Shaders.Mappings
["System.MathF.PI"] = "3.14159274f",
// ThreadIds
- ["DirectX12GameEngine.Shaders.Primitives.ThreadIds.X"] = ".x",
- ["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Y"] = ".y",
- ["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Z"] = ".z",
+ ["ComputeSharp.ThreadIds.X"] = ".x",
+ ["ComputeSharp.ThreadIds.Y"] = ".y",
+ ["ComputeSharp.ThreadIds.Z"] = ".z",
// Vector3
["System.Numerics.Vector3.X"] = ".x",
diff --git a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
similarity index 93%
rename from src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs
rename to src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
index c6038358..32bf790d 100644
--- a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs
@@ -3,9 +3,9 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
using System.Text.RegularExpressions;
-using DirectX12GameEngine.Shaders.Primitives;
+using ComputeSharp.Graphics.Buffers;
-namespace DirectX12GameEngine.Shaders.Mappings
+namespace ComputeSharp.Shaders.Mappings
{
///
/// A that contains and maps known HLSL type names to common .NET types
@@ -27,7 +27,7 @@ namespace DirectX12GameEngine.Shaders.Mappings
[typeof(Vector4).FullName] = "float4",
[typeof(Matrix4x4).FullName] = "float4x4",
[typeof(ThreadIds).FullName] = "uint3",
- [typeof(RWBufferResource<>).FullName] = "RWBuffer"
+ [typeof(ReadWriteBuffer<>).FullName] = "RWBuffer"
};
///
@@ -54,13 +54,13 @@ namespace DirectX12GameEngine.Shaders.Mappings
type == typeof(Matrix4x4);
///
- /// Checks whether or not the input type is a value
+ /// Checks whether or not the input type is a value
///
/// The input instance to check
- /// A indicating whether the input is in fact a instance
+ /// A indicating whether the input is in fact a instance
[Pure]
public static bool IsReadWriteBufferType(Type type) => type.IsGenericType &&
- type.GetGenericTypeDefinition() == typeof(RWBufferResource<>);
+ type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>);
///
/// Checks whether or not a given is an HLSL known type
diff --git a/src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs b/src/ComputeSharp.Shaders/Primitives/ThreadIds.cs
similarity index 91%
rename from src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs
rename to src/ComputeSharp.Shaders/Primitives/ThreadIds.cs
index 08cf64b3..219f4ef9 100644
--- a/src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs
+++ b/src/ComputeSharp.Shaders/Primitives/ThreadIds.cs
@@ -1,4 +1,4 @@
-namespace DirectX12GameEngine.Shaders.Primitives
+namespace ComputeSharp
{
///
/// A that indicates the ids of a given GPU thread running a compute shader
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs
similarity index 93%
rename from src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs
index ead23005..ff7cc533 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs
@@ -1,4 +1,4 @@
-namespace DirectX12GameEngine.Shaders.Renderer.Models.Abstract
+namespace ComputeSharp.Shaders.Renderer.Models.Fields.Abstract
{
///
/// A that contains info on a shader field
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
similarity index 90%
rename from src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
index aa453dab..1f8c3160 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs
@@ -1,6 +1,6 @@
-using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
+using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
-namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
+namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
///
/// A that contains info on a constant buffer field
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
similarity index 90%
rename from src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
index abfb06c9..e7280bc2 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs
@@ -1,6 +1,6 @@
-using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
+using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
-namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
+namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
///
/// A that contains info on a read write buffer field
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
similarity index 90%
rename from src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
index ff41f95e..ab6ca039 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs
@@ -1,6 +1,6 @@
-using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
+using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
-namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
+namespace ComputeSharp.Shaders.Renderer.Models.Fields
{
///
/// A that contains info on a static scalar field
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
similarity index 67%
rename from src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs
rename to src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
index 64ba1e8d..2a2e09df 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs
+++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs
@@ -1,9 +1,9 @@
using System.Collections.Generic;
-using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
+using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
-namespace DirectX12GameEngine.Shaders.Renderer.Models
+namespace ComputeSharp.Shaders.Renderer.Models
{
///
/// A that contains info to render a shader source to compile
@@ -16,20 +16,35 @@ namespace DirectX12GameEngine.Shaders.Renderer.Models
public IReadOnlyList FieldsList { get; set; }
///
- /// Gets or sets the number of threads in the X group
+ /// Gets or sets the total number of threads to run on the X axis
///
public int ThreadsX { get; set; }
///
- /// Gets or sets the number of threads in the Y group
+ /// Gets or sets the total number of threads to run on the Y axis
///
public int ThreadsY { get; set; }
///
- /// Gets or sets the number of threads in the Z group
+ /// Gets or sets the total number of threads to run on the Z axis
///
public int ThreadsZ { get; set; }
+ ///
+ /// Gets or sets the number of threads in the X group
+ ///
+ public int NumThreadsX { get; set; }
+
+ ///
+ /// Gets or sets the number of threads in the Y group
+ ///
+ public int NumThreadsY { get; set; }
+
+ ///
+ /// Gets or sets the number of threads in the Z group
+ ///
+ public int NumThreadsZ { get; set; }
+
///
/// Gets or sets the name for the threads id variable used in the shader
///
diff --git a/src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs
similarity index 92%
rename from src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs
rename to src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs
index 5533346f..f9aeb680 100644
--- a/src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs
+++ b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs
@@ -2,9 +2,9 @@
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
-using DirectX12GameEngine.Shaders.Renderer.Models;
+using ComputeSharp.Shaders.Renderer.Models;
-namespace DirectX12GameEngine.Shaders.Renderer
+namespace ComputeSharp.Shaders.Renderer
{
///
/// A that uses the mustache templating system to render HLSL shaders
@@ -24,7 +24,7 @@ namespace DirectX12GameEngine.Shaders.Renderer
string
assemblyPath = Assembly.GetExecutingAssembly().Location,
assemblyDirectory = Path.GetDirectoryName(assemblyPath) ?? throw new InvalidOperationException("Can't find the assembly directory"),
- templatePath = Path.Combine(assemblyDirectory, "Assets", "ShaderTemplate.mustache");
+ templatePath = Path.Combine(assemblyDirectory, "Renderer", "Templates", "ShaderTemplate.mustache");
Template = File.ReadAllText(templatePath);
}
diff --git a/src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
similarity index 73%
rename from src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache
rename to src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
index 3ab5de4a..eee11e3e 100644
--- a/src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache
+++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache
@@ -18,6 +18,11 @@ cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}})
{{/FieldsList}}
{{!Shader entry point}}
[Shader("compute")]
-[NumThreads({{ThreadsX}}, {{ThreadsY}}, {{ThreadsZ}})]
+[NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})]
void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId)
+{
+if ({{ThreadsIdsVariableName}}.x < {{ThreadsX}} &&
+ {{ThreadsIdsVariableName}}.y < {{ThreadsY}} &&
+ {{ThreadsIdsVariableName}}.z < {{ThreadsZ}})
{{&ShaderBody}}
+}
diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs
new file mode 100644
index 00000000..1b5cbe0e
--- /dev/null
+++ b/src/ComputeSharp.Shaders/ShaderRunner.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Linq;
+using ComputeSharp.Graphics;
+using ComputeSharp.Shaders.Renderer;
+using ComputeSharp.Shaders.Renderer.Models;
+using ComputeSharp.Shaders.Translation;
+using SharpDX.Direct3D12;
+using CommandList = ComputeSharp.Graphics.CommandList;
+using PipelineState = ComputeSharp.Graphics.PipelineState;
+
+namespace ComputeSharp.Shaders
+{
+ ///
+ /// A responsible for performing all the necessary operations to compile and run a compute shader
+ ///
+ public static class ShaderRunner
+ {
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters
+ ///
+ /// The to use to run the shader
+ /// The number of threads to run on the X axis
+ /// The number of threads to run on the Y axis
+ /// The number of threads to run on the Z axis
+ /// The input representing the compute shader to run
+ public static void Run(GraphicsDevice device, int x, int y, int z, Action action)
+ {
+ // Calculate the optimized thread num and group values
+ int
+ threadsX = device.WavefrontSize,
+ threadsY = y > 1 ? device.WavefrontSize : 1,
+ threadsZ = z > 1 ? device.WavefrontSize : 1,
+ groupsX = (x - 1) / device.WavefrontSize + 1,
+ groupsY = (y - 1) / device.WavefrontSize + 1,
+ groupsZ = (z - 1) / device.WavefrontSize + 1;
+
+ // Load the input shader
+ ShaderLoader shaderLoader = ShaderLoader.Load(action);
+
+ // Render the loaded shader
+ ShaderInfo shaderInfo = new ShaderInfo
+ {
+ FieldsList = shaderLoader.FieldsInfo,
+ ThreadsX = x,
+ ThreadsY = y,
+ ThreadsZ = z,
+ NumThreadsX = threadsX,
+ NumThreadsY = threadsY,
+ NumThreadsZ = threadsZ,
+ ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
+ ShaderBody = shaderLoader.MethodBody
+ };
+ string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
+
+ // Compile the loaded shader to HLSL bytecode
+ ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource);
+
+ // Create the root signature for the pipeline and the pipeline state
+ RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.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 buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
+ {
+ commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
+ }
+
+ // Dispatch and wait for completion
+ commandList.Dispatch(groupsX, groupsY, groupsZ);
+ commandList.Flush(true);
+ }
+ }
+}
diff --git a/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs
similarity index 68%
rename from src/DirectX12GameEngine.Shaders/MethodDecompiler.cs
rename to src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs
index 031f2e21..20c2a95a 100644
--- a/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs
+++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs
@@ -12,7 +12,7 @@ using ICSharpCode.Decompiler.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
-namespace DirectX12GameEngine.Shaders
+namespace ComputeSharp.Shaders.Translation
{
///
/// A that is able to decompile arbitrary methods
@@ -108,8 +108,8 @@ namespace DirectX12GameEngine.Shaders
lock (Lock)
{
// Get the handle of the input method
- GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle);
-
+ string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException();
+ EntityHandle methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
// Get or create a decompiler for the target assembly, and decompile the method
if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler))
{
@@ -129,55 +129,6 @@ namespace DirectX12GameEngine.Shaders
}
}
- ///
- /// Loads the assembly path and method handle for the input instance
- ///
- /// The input to inspect
- /// The path of the assembly containing the input method
- /// The handle for the input method
- private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle)
- {
- // Try to get the method handle from the assembly of the declaring type
- Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type");
- string path = declaringType.Assembly.Location;
- if (!string.IsNullOrEmpty(path))
- {
- assemblyPath = path;
- methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
- }
- else
- {
- // Try to get the PEFile and type definition for the method declaring type
- if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple))
- {
- foreach (PEFile peFile in PEFiles)
- {
- // If not available, browse through the loaded PEFiles to find the type definition
- 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($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}");
- }
-
- PEFile peFileForMethod = tuple.PEFile;
- TypeDefinition typeDefinition = tuple.TypeDefinition;
-
- // Retrieve the assembly path and method handle from the loaded PEFile and metadata
- 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);
- }
- }
-
///
/// Creates a new instance targeting a given assembly
///
diff --git a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs
similarity index 98%
rename from src/DirectX12GameEngine.Shaders/ShaderCompiler.cs
rename to src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs
index ea64c675..712fbd85 100644
--- a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs
@@ -3,7 +3,7 @@ using System.Diagnostics.Contracts;
using DotNetDxc;
using SharpDX.Direct3D12;
-namespace DirectX12GameEngine.Shaders
+namespace ComputeSharp.Shaders.Translation
{
///
/// A that uses the APIs to compile compute shaders
diff --git a/src/DirectX12GameEngine.Shaders/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
similarity index 91%
rename from src/DirectX12GameEngine.Shaders/ShaderLoader.cs
rename to src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
index 4f49fe48..acdeac27 100644
--- a/src/DirectX12GameEngine.Shaders/ShaderLoader.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
@@ -4,18 +4,17 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
-using DirectX12GameEngine.Graphics.Buffers.Abstract;
-using DirectX12GameEngine.Shaders.Mappings;
-using DirectX12GameEngine.Shaders.Primitives;
-using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
-using DirectX12GameEngine.Shaders.Renderer.Models.Fields;
+using ComputeSharp.Graphics.Buffers.Abstract;
+using ComputeSharp.Shaders.Mappings;
+using ComputeSharp.Shaders.Renderer.Models.Fields;
+using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDX.Direct3D12;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
-namespace DirectX12GameEngine.Shaders
+namespace ComputeSharp.Shaders.Translation
{
///
/// A responsible for loading and processing instances
@@ -123,9 +122,7 @@ namespace DirectX12GameEngine.Shaders
descriptorRanges.Add(range);
// Reference to the underlying buffer
- object readWriteBuffer = fieldInfo.GetValue(ShaderInstance);
- GraphicsResource resource = (GraphicsResource)fieldType.GetProperty(nameof(RWBufferResource.Buffer)).GetValue(readWriteBuffer);
- readWriteBuffers.Add(resource);
+ readWriteBuffers.Add((GraphicsResource)fieldValue);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++);
@@ -154,7 +151,7 @@ namespace DirectX12GameEngine.Shaders
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out SyntaxNode root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
- ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, true);
+ ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel);
root = syntaxRewriter.Visit(root);
// Get the thread ids identifier name and shader method body
@@ -164,6 +161,7 @@ namespace DirectX12GameEngine.Shaders
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", ""));
+ MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
}
}
}
diff --git a/src/DirectX12GameEngine.Shaders/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
similarity index 60%
rename from src/DirectX12GameEngine.Shaders/ShaderSyntaxRewriter.cs
rename to src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
index f2e9c018..63b4a0e9 100644
--- a/src/DirectX12GameEngine.Shaders/ShaderSyntaxRewriter.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
@@ -1,33 +1,31 @@
-using System;
-using System.Linq;
+using ComputeSharp.Shaders.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-namespace DirectX12GameEngine.Shaders
+namespace ComputeSharp.Shaders.Translation
{
+ ///
+ /// A custom that processes C# methods to convert to HLSL
+ ///
public class ShaderSyntaxRewriter : CSharpSyntaxRewriter
{
- private readonly int depth;
- private readonly bool isTopLevel;
- private readonly SemanticModel semanticModel;
+ ///
+ /// The instance to use to rewrite the decompiled code
+ ///
+ private readonly SemanticModel SemanticModel;
- public ShaderSyntaxRewriter(SemanticModel semanticModel, bool isTopLevel = false, int depth = 0)
- {
- this.semanticModel = semanticModel;
- this.isTopLevel = isTopLevel;
- this.depth = depth;
- }
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ ///
+ public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel;
+ ///
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
- if (isTopLevel && depth > 0)
- {
- node = node.ReplaceToken(node.Identifier, SyntaxFactory.Identifier($"Base_{depth}_{node.Identifier.ValueText}"));
- }
-
SyntaxTokenList modifiers = new SyntaxTokenList();
if (node.Modifiers.Any(SyntaxKind.StaticKeyword))
@@ -38,6 +36,7 @@ namespace DirectX12GameEngine.Shaders
return node.ReplaceType(node.ReturnType).WithModifiers(modifiers);
}
+ ///
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
node = (ParameterSyntax)base.VisitParameter(node);
@@ -47,18 +46,23 @@ namespace DirectX12GameEngine.Shaders
return node;
}
+ ///
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
node = (CastExpressionSyntax)base.VisitCastExpression(node);
+
return node.ReplaceType(node.Type);
}
+ ///
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
+
return node.ReplaceType(node.Declaration.Type);
}
+ ///
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
node = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node);
@@ -68,48 +72,25 @@ namespace DirectX12GameEngine.Shaders
{
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
- else
- {
- return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
- }
+
+ return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
}
+ ///
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
node = (DefaultExpressionSyntax)base.VisitDefaultExpression(node);
node = node.ReplaceType(node.Type);
+
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
+ ///
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
node = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node);
- if (node.Expression is BaseExpressionSyntax)
- {
- if (isTopLevel)
- {
- return SyntaxFactory.IdentifierName($"Base_{depth + 1}_{node.Name}");
- }
- else
- {
- SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
- ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
-
- if (memberSymbol != null)
- {
- return SyntaxFactory.IdentifierName($"{memberSymbol.ContainingType.Name}::{node.Name}");
- }
- else
- {
- throw new InvalidOperationException();
- }
- }
- }
- else
- {
- return node.ReplaceMember(semanticModel);
- }
+ return node.ReplaceMember(SemanticModel);
}
}
}
diff --git a/src/ComputeSharp.sln b/src/ComputeSharp.sln
index e28fc3f4..56d82d29 100644
--- a/src/ComputeSharp.sln
+++ b/src/ComputeSharp.sln
@@ -3,13 +3,20 @@ 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}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Graphics", "ComputeSharp.Graphics\ComputeSharp.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}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Shaders", "ComputeSharp.Shaders\ComputeSharp.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}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp", "ComputeSharp\ComputeSharp.csproj", "{314EB353-E7E3-4146-8111-685CC83EC1DE}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DirectX12ComputeShaderSample", "DirectX12ComputeShaderSample\DirectX12ComputeShaderSample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetCoreComputeShaderSample", "..\samples\NetCoreComputeShaderSample\NetCoreComputeShaderSample.csproj", "{7A48A85D-8866-4DED-A404-653ED09BF396}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_SolutionItems", "{1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}"
+ ProjectSection(SolutionItems) = preProject
+ ..\.gitignore = ..\.gitignore
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -55,6 +62,9 @@ Global
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
+ EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
EndGlobalSection
diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj
new file mode 100644
index 00000000..57aeb7e6
--- /dev/null
+++ b/src/ComputeSharp/ComputeSharp.csproj
@@ -0,0 +1,20 @@
+
+
+
+ netstandard2.0
+ 8.0
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs
new file mode 100644
index 00000000..f9bdc634
--- /dev/null
+++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs
@@ -0,0 +1,39 @@
+using System;
+using ComputeSharp.Graphics;
+using ComputeSharp.Shaders;
+
+namespace ComputeSharp
+{
+ ///
+ /// A that contains extension methods for the type, used to run compute shaders
+ ///
+ public static class GraphicsDeviceExtensions
+ {
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters
+ ///
+ /// The to use to run the shader
+ /// The number of threads to run on the X axis
+ /// The input representing the compute shader to run
+ public static void For(this GraphicsDevice device, int x, Action action) => ShaderRunner.Run(device, x, 1, 1, action);
+
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters
+ ///
+ /// The to use to run the shader
+ /// The number of threads to run on the X axis
+ /// The number of threads to run on the Y axis
+ /// The input representing the compute shader to run
+ public static void For(this GraphicsDevice device, int x, int y, Action action) => ShaderRunner.Run(device, x, y, 1, action);
+
+ ///
+ /// Compiles and runs the input shader on a target instance, with the specified parameters
+ ///
+ /// The to use to run the shader
+ /// The number of threads to run on the X axis
+ /// The number of threads to run on the Y axis
+ /// The number of threads to run on the Z axis
+ /// The input representing the compute shader to run
+ public static void For(this GraphicsDevice device, int x, int y, int z, Action action) => ShaderRunner.Run(device, x, y, z, action);
+ }
+}
diff --git a/src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs b/src/ComputeSharp/Extensions/Windows.Foundation/PointExtensions.cs
similarity index 100%
rename from src/DirectX12GameEngine.Core/Extensions/PointExtensions.cs
rename to src/ComputeSharp/Extensions/Windows.Foundation/PointExtensions.cs
diff --git a/src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs b/src/ComputeSharp/Extensions/Windows.Foundation/RectExtensions.cs
similarity index 100%
rename from src/DirectX12GameEngine.Core/Extensions/RectExtensions.cs
rename to src/ComputeSharp/Extensions/Windows.Foundation/RectExtensions.cs
diff --git a/src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs b/src/ComputeSharp/Extensions/Windows.Foundation/SizeExtensions.cs
similarity index 100%
rename from src/DirectX12GameEngine.Core/Extensions/SizeExtensions.cs
rename to src/ComputeSharp/Extensions/Windows.Foundation/SizeExtensions.cs
diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs
new file mode 100644
index 00000000..7af82c16
--- /dev/null
+++ b/src/ComputeSharp/Gpu.cs
@@ -0,0 +1,17 @@
+using ComputeSharp.Graphics;
+
+namespace ComputeSharp
+{
+ ///
+ /// A that acts as an entry-point for all the library APIs, exposing the available GPU devices
+ ///
+ public static class Gpu
+ {
+ private static GraphicsDevice _Default;
+
+ ///
+ /// Gets the default instance for the current machine
+ ///
+ public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true);
+ }
+}
diff --git a/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj b/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj
deleted file mode 100644
index 0823373d..00000000
--- a/src/DirectX12ComputeShaderSample/DirectX12ComputeShaderSample.csproj
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
- Exe
- netcoreapp3.0
-
-
-
-
-
-
-
-
diff --git a/src/DirectX12ComputeShaderSample/Gpu.cs b/src/DirectX12ComputeShaderSample/Gpu.cs
deleted file mode 100644
index 65f9f084..00000000
--- a/src/DirectX12ComputeShaderSample/Gpu.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-using System;
-using System.Linq;
-using DirectX12GameEngine.Graphics;
-using DirectX12GameEngine.Shaders;
-using DirectX12GameEngine.Shaders.Primitives;
-using DirectX12GameEngine.Shaders.Renderer;
-using DirectX12GameEngine.Shaders.Renderer.Models;
-using SharpDX.Direct3D12;
-using CommandList = DirectX12GameEngine.Graphics.CommandList;
-using PipelineState = DirectX12GameEngine.Graphics.PipelineState;
-using ShaderBytecode = SharpDX.Direct3D12.ShaderBytecode;
-
-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 action)
- {
- // Load the input shader
- ShaderLoader shaderLoader = ShaderLoader.Load(action);
-
- // Render the loaded shader
- ShaderInfo shaderInfo = new ShaderInfo
- {
- FieldsList = shaderLoader.FieldsInfo,
- ThreadsX = n,
- ThreadsY = 1,
- ThreadsZ = 1,
- ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
- ShaderBody = shaderLoader.MethodBody
- };
- string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
-
- // Compile the loaded shader to HLSL bytecode
- ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource);
-
- // Create the root signature for the pipeline and the pipeline state
- RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.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 buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
- {
- commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
- }
-
- // Dispatch and wait for completion
- commandList.Dispatch(1, 1, 1);
- commandList.Flush(true);
- }
- }
-}
diff --git a/src/DirectX12GameEngine.Graphics/BufferDescription.cs b/src/DirectX12GameEngine.Graphics/BufferDescription.cs
deleted file mode 100644
index 89159df8..00000000
--- a/src/DirectX12GameEngine.Graphics/BufferDescription.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-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
deleted file mode 100644
index 1c0a26b5..00000000
--- a/src/DirectX12GameEngine.Graphics/BufferFlags.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-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/Buffer.Constant.cs b/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs
deleted file mode 100644
index 7745734e..00000000
--- a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.Constant.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-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
deleted file mode 100644
index 20ec576d..00000000
--- a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.UnorderedAccess.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-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
deleted file mode 100644
index db4052e0..00000000
--- a/src/DirectX12GameEngine.Graphics/Buffers/Buffer.cs
+++ /dev/null
@@ -1,232 +0,0 @@
-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/DirectX12GameEngine.Graphics.csproj b/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj
deleted file mode 100644
index e2b2653d..00000000
--- a/src/DirectX12GameEngine.Graphics/DirectX12GameEngine.Graphics.csproj
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
- netstandard2.0
- 8.0
- enable
- true
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs
deleted file mode 100644
index 84cb358a..00000000
--- a/src/DirectX12GameEngine.Shaders/ShaderGenerationResult.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-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/ShaderResource.cs b/src/DirectX12GameEngine.Shaders/ShaderResource.cs
deleted file mode 100644
index 2cf469ec..00000000
--- a/src/DirectX12GameEngine.Shaders/ShaderResource.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.Numerics;
-using DirectX12GameEngine.Graphics.Buffers;
-using Buffer = System.Buffer;
-
-namespace DirectX12GameEngine.Shaders
-{
- public abstract class ShaderResource
- {
- }
-
- public sealed class RWBufferResource : ShaderResource where T : unmanaged
- {
- internal RWBufferResource(Buffer buffer) => Buffer = buffer;
-
- public Buffer Buffer { get; }
-
- public T this[uint index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
- }
-
- public static class RWBufferResourceExtensions
- {
- public static RWBufferResource GetGpuResource(this Buffer buffer) where T : unmanaged
- {
- return new RWBufferResource(buffer);
- }
- }
-}
diff --git a/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs b/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs
deleted file mode 100644
index b2e0f0fb..00000000
--- a/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System.Linq;
-using DirectX12GameEngine.Shaders.Mappings;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-namespace DirectX12GameEngine.Shaders
-{
- public static class SyntaxNodeExtensions
- {
- public static TRoot ReplaceType(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
- {
- string value = HlslKnownTypes.GetMappedName(type.ToString());
-
- if (value == type.ToString())
- {
- return node;
- }
- else
- {
- return node.ReplaceNode(type, SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia()));
- }
- }
-
- public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel)
- {
- SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression);
- SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
-
- ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
-
- if (memberSymbol is null || (memberSymbol.Kind != SymbolKind.Field && memberSymbol.Kind != SymbolKind.Property && memberSymbol.Kind != SymbolKind.Method))
- {
- return node;
- }
-
- if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
- {
- return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
- }
-
- return node;
- }
- }
-}