46ファイル変更
+3036
検索条件に一致するファイルはありません
@@ -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
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj" />
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Shaders\DirectX12GameEngine.Shaders.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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<UInt3> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<float> gpuBuffer = Buffer.UnorderedAccess.New(Gpu.Default, array.AsSpan());
|
||||
|
||||
// Variables for closure
|
||||
uint size = (uint)width;
|
||||
var data = gpuBuffer.GetGpuResource();
|
||||
|
||||
// Shader body
|
||||
Action<UInt3> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Windows.SDK.Contracts" Version="10.0.18362.2002-preview" />
|
||||
<PackageReference Include="System.Memory" Version="4.5.3" />
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.6.0-preview5.19224.8" />
|
||||
<PackageReference Include="System.Runtime.InteropServices.WindowsRuntime" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Windows.Foundation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some extension methods for the <see cref="Point"/> type
|
||||
/// </summary>
|
||||
public static class PointExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Point"/> value to a <see cref="Vector2"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Point"/> to convert</param>
|
||||
/// <returns>A <see cref="Vector2"/> value representing the input <see cref="Point"/></returns>
|
||||
[Pure]
|
||||
public static Vector2 ToVector2(this in Point value) => new Vector2((float)value.X, (float)value.Y);
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Vector2"/> value to a <see cref="Point"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Vector2"/> to convert</param>
|
||||
/// <returns>A <see cref="Point"/> value representing the input <see cref="Vector2"/></returns>
|
||||
[Pure]
|
||||
public static Point ToPoint(this in Vector2 value) => new Point(value.X, value.Y);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Windows.Foundation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some extension methods for the <see cref="Rect"/> type
|
||||
/// </summary>
|
||||
public static class RectExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Rect"/> value to a <see cref="Vector2"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Rect"/> to convert</param>
|
||||
/// <returns>A <see cref="Vector2"/> value representing the input <see cref="Rect"/></returns>
|
||||
/// <remarks>The input <see cref="Rect"/> is read in the following order: <see cref="Rect.Left"/>, <see cref="Rect.Top"/>, <see cref="Rect.Right"/>, <see cref="Rect.Bottom"/></remarks>
|
||||
[Pure]
|
||||
public static Vector4 ToVector2(this in Rect value) => new Vector4((float)value.Left, (float)value.Top, (float)value.Right, (float)value.Bottom);
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Vector2"/> value to a <see cref="Rect"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Vector2"/> to convert</param>
|
||||
/// <returns>A <see cref="Rect"/> value representing the input <see cref="Vector2"/></returns>
|
||||
/// <remarks>The input <see cref="Vector4"/> is assigned in the following order: <see cref="Rect.Left"/>, <see cref="Rect.Top"/>, <see cref="Rect.Right"/>, <see cref="Rect.Bottom"/></remarks>
|
||||
[Pure]
|
||||
public static Rect ToPoint(this in Vector4 value) => new Rect(value.X, value.Y, value.Z, value.W);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Windows.Foundation
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some extension methods for the <see cref="Size"/> type
|
||||
/// </summary>
|
||||
public static class SizeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Size"/> value to a <see cref="Vector2"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Size"/> to convert</param>
|
||||
/// <returns>A <see cref="Vector2"/> value representing the input <see cref="Size"/></returns>
|
||||
/// <remarks>The input <see cref="Size"/> is read in the following order: <see cref="Size.Width"/>, <see cref="Size.Height"/></remarks>
|
||||
[Pure]
|
||||
public static Vector2 ToVector2(this in Size value) => new Vector2((float)value.Width, (float)value.Height);
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Vector2"/> value to a <see cref="Size"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The input <see cref="Vector2"/> to convert</param>
|
||||
/// <returns>A <see cref="Point"/> value representing the input <see cref="Vector2"/></returns>
|
||||
/// <remarks>The input <see cref="Size"/> is assigned in the following order: <see cref="Size.Width"/>, <see cref="Size.Height"/></remarks>
|
||||
[Pure]
|
||||
public static Size ToPoint(this in Vector2 value) => new Size(value.X, value.Y);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace DirectX12GameEngine.Core.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with some helper methods to copy data between memory areas
|
||||
/// </summary>
|
||||
public static class MemoryHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Copies the content of a <see cref="Span{T}"/> to the area pointed by an input <see cref="IntPtr"/> value
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of values in the input <see cref="Span{T}"/></typeparam>
|
||||
/// <param name="source">The source <see cref="Span{T}"/> to read</param>
|
||||
/// <param name="destination">The <see cref="IntPtr"/> for the destination memory area</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void Copy<T>(Span<T> source, IntPtr destination) where T : unmanaged
|
||||
{
|
||||
source.CopyTo(new Span<T>(destination.ToPointer(), source.Length));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a memory area pointed by an <see cref="IntPtr"/> value to a target <see cref="Span{T}"/>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of values to read</typeparam>
|
||||
/// <param name="source">The <see cref="IntPtr"/> that indicates the memory area to read from</param>
|
||||
/// <param name="destination">The destination <see cref="Span{T}"/> to write</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe void Copy<T>(IntPtr source, Span<T> destination) where T : unmanaged
|
||||
{
|
||||
new Span<T>(source.ToPointer(), destination.Length).CopyTo(destination);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics.Buffers.Abstract
|
||||
{
|
||||
/// <summary>
|
||||
/// An abstract <see langword="class"/> that represents a graphics resource object
|
||||
/// </summary>
|
||||
public abstract class GraphicsResource : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GraphicsResource"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
|
||||
protected GraphicsResource(GraphicsDevice device)
|
||||
{
|
||||
GraphicsDevice = device;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="GraphicsDevice"/> associated with the current instance
|
||||
/// </summary>
|
||||
public GraphicsDevice GraphicsDevice { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="IntPtr"/> associated to the currently mapped resource
|
||||
/// </summary>
|
||||
public IntPtr MappedResource { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="Resource"/> object currently mapped
|
||||
/// </summary>
|
||||
protected internal Resource? NativeResource { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="CpuDescriptorHandle"/> instance for the current resource
|
||||
/// </summary>
|
||||
protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="GpuDescriptorHandle"/> instance for the current resource
|
||||
/// </summary>
|
||||
protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current resource to a specified subresource
|
||||
/// </summary>
|
||||
/// <param name="subresource">The index of the target subresource to map</param>
|
||||
/// <returns>An <see cref="IntPtr"/> for the newly mapped resource</returns>
|
||||
public IntPtr Map(int subresource)
|
||||
{
|
||||
IntPtr mappedResource = NativeResource?.Map(subresource) ?? throw new InvalidOperationException("Missing resource");
|
||||
MappedResource = mappedResource;
|
||||
return mappedResource;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unmaps a subresource specified by a given index
|
||||
/// </summary>
|
||||
/// <param name="subresource">The index of the subresource to unmap</param>
|
||||
public void Unmap(int subresource)
|
||||
{
|
||||
NativeResource?.Unmap(subresource);
|
||||
MappedResource = IntPtr.Zero;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual void Dispose() => NativeResource?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -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<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T> New<T>(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<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffers.Buffer.New(device, data, BufferFlags.UnorderedAccess, heapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>() where T : unmanaged
|
||||
{
|
||||
T[] data = new T[SizeInBytes / Unsafe.SizeOf<T>()];
|
||||
GetData(data.AsSpan());
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public unsafe void GetData<T>(ref T data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
GetData(new Span<T>(pointer, 1), offsetInBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public void GetData<T>(Span<T> data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage == GraphicsHeapType.Default)
|
||||
{
|
||||
using Buffer<T> readbackBaffer = New<T>(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<T>());
|
||||
copyCommandList.Flush(true);
|
||||
|
||||
readbackBaffer.GetData(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(MappedResource + offsetInBytes, data);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void SetData<T>(in T data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
SetData(new Span<T>(pointer, 1), offsetInBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetData<T>(Span<T> data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage == GraphicsHeapType.Default)
|
||||
{
|
||||
using Buffer<T> 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<T>());
|
||||
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<T> New<T>(GraphicsDevice device, int elementCount, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
int bufferSize = elementCount * Unsafe.SizeOf<T>();
|
||||
|
||||
return new Buffer<T>(device, bufferSize, bufferFlags, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
return New(device, new Span<T>(pointer, 1), bufferFlags, heapType);
|
||||
}
|
||||
}
|
||||
|
||||
public static Buffer<T> New<T>(GraphicsDevice device, Span<T> data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
Buffer<T> buffer = New<T>(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<T> : Buffers.Buffer where T : unmanaged
|
||||
{
|
||||
protected internal Buffer(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) : base(device)
|
||||
{
|
||||
ElementSize = Unsafe.SizeOf<T>();
|
||||
ElementCount = size / ElementSize;
|
||||
|
||||
InitializeFrom(new BufferDescription(size, bufferFlags, heapType));
|
||||
}
|
||||
|
||||
public int ElementSize { get; }
|
||||
|
||||
public T[] GetData() => GetData<T>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum ClearFlags
|
||||
{
|
||||
None = 0,
|
||||
FlagsDepth = 1,
|
||||
FlagsStencil = 2
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SharpDX.Direct3D12" Version="4.2.1-beta0-gab36f12303" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public enum GraphicsHeapType
|
||||
{
|
||||
Default = 1,
|
||||
Upload = 2,
|
||||
Readback = 3,
|
||||
Custom = 4
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> representing a custom pipeline state for a compute operation
|
||||
/// </summary>
|
||||
public sealed class PipelineState : ComputePipelineStateDescription
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PipelineState"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use</param>
|
||||
/// <param name="rootSignature">The <see cref="SharpDX.Direct3D12.RootSignature"/> value for the current shader</param>
|
||||
/// <param name="computeShader">The bytecode for the compute shader to run</param>
|
||||
public PipelineState(GraphicsDevice device, RootSignature rootSignature, ShaderBytecode computeShader)
|
||||
{
|
||||
RootSignaturePointer = rootSignature;
|
||||
ComputeShader = computeShader;
|
||||
RootSignature = RootSignaturePointer;
|
||||
|
||||
NativePipelineState = device.NativeDevice.CreateComputePipelineState(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="SharpDX.Direct3D12.RootSignature"/> value for the current shader
|
||||
/// </summary>
|
||||
public RootSignature RootSignature { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="SharpDX.Direct3D12.PipelineState"/> instance for the current <see cref="PipelineState"/> object
|
||||
/// </summary>
|
||||
public SharpDX.Direct3D12.PipelineState NativePipelineState { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DotNetDxc" Version="1.2.0-alpha">
|
||||
<ExcludeAssets>native</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.0.4861-preview3" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.0-beta1-final" />
|
||||
<PackageReference Include="SharpDX.D3DCompiler" Version="4.2.1-beta0-g3060495c2a" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj" />
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Graphics\DirectX12GameEngine.Graphics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!--<Content Include="..\Libs\runtimes\win-x86\native\*.*">
|
||||
<PackagePath>runtimes\win-x86\native</PackagePath>
|
||||
<Pack>true</Pack>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>-->
|
||||
<Content Include="..\Libs\runtimes\win-x64\native\*.*">
|
||||
<PackagePath>runtimes\win-x64\native</PackagePath>
|
||||
<Pack>true</Pack>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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<MethodInfo> GetBaseMethods(this MethodInfo methodInfo)
|
||||
{
|
||||
List<MethodInfo> methodInfos = new List<MethodInfo>() { 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<Type> GetNestedTypesInTypeHierarchy(this Type type, BindingFlags bindingAttr)
|
||||
{
|
||||
IEnumerable<Type> 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<MemberInfo> GetMembersInTypeHierarchy(this Type type, BindingFlags bindingAttr)
|
||||
{
|
||||
Dictionary<Type, int> lookup = new Dictionary<Type, int>();
|
||||
|
||||
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<MemberInfo> GetMembersInTypeHierarchyInOrder(this Type type, BindingFlags bindingAttr)
|
||||
{
|
||||
return type.GetMembersInTypeHierarchy(bindingAttr)
|
||||
.GroupBy(m => m.DeclaringType)
|
||||
.Select(g => g.OrderBy(m => m.GetCustomAttribute<ShaderResourceAttribute>()?.Order))
|
||||
.SelectMany(m => m);
|
||||
}
|
||||
|
||||
public static IEnumerable<MemberInfo> GetMembersInOrder(this Type type, BindingFlags bindingAttr)
|
||||
{
|
||||
return type.GetMembers(bindingAttr)
|
||||
.OrderBy(m => m.GetCustomAttribute<ShaderResourceAttribute>()?.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<ShaderResourceAttribute>();
|
||||
|
||||
if (resourceType is null) return null;
|
||||
|
||||
return resourceType.Override
|
||||
? resourceType
|
||||
: memberType?.GetCustomAttribute<ShaderResourceAttribute>() ?? resourceType;
|
||||
}
|
||||
|
||||
public static bool IsStatic(this MemberInfo memberInfo) => memberInfo switch
|
||||
{
|
||||
FieldInfo fieldInfo => fieldInfo.IsStatic,
|
||||
PropertyInfo propertyInfo => propertyInfo.GetAccessors(true)[0].IsStatic,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace DirectX12GameEngine.Shaders.Numerics
|
||||
{
|
||||
public struct UInt2
|
||||
{
|
||||
public uint X;
|
||||
|
||||
public uint Y;
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace DirectX12GameEngine.Shaders.Numerics
|
||||
{
|
||||
public struct Vector2
|
||||
{
|
||||
public static float Length(System.Numerics.Vector2 value) => value.Length();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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<string, CSharpDecompiler> decompilers = new Dictionary<string, CSharpDecompiler>();
|
||||
private static readonly IEnumerable<PEFile> peFiles;
|
||||
private static readonly Dictionary<Type, (PEFile PEFile, TypeDefinition TypeDefinition)> typeDefinitions = new Dictionary<Type, (PEFile, TypeDefinition)>();
|
||||
|
||||
private static Compilation compilation;
|
||||
|
||||
private readonly List<ShaderTypeDefinition> collectedTypes = new List<ShaderTypeDefinition>();
|
||||
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<string> 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<GraphicsResource> ReadWriteBuffers { get; private set; }
|
||||
|
||||
public ShaderGenerationResult GenerateShaderForLambda()
|
||||
{
|
||||
if (result != null) return result;
|
||||
|
||||
if (!(shader is Action<UInt3> 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<DescriptorRange>();
|
||||
var rwbuffers = new List<GraphicsResource>();
|
||||
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<byte>.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<ShaderSemanticAttribute>()));
|
||||
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<ShaderSemanticAttribute>()));
|
||||
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<MemberInfo> generatedMemberInfos = new List<MemberInfo>();
|
||||
|
||||
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<ShaderSemanticAttribute>()));
|
||||
|
||||
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<MethodInfo> 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<MethodInfo> 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 <Main>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<string> allowedAttributes = new HashSet<string>()
|
||||
{
|
||||
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<string, string> knownSemantics = new Dictionary<string, string>()
|
||||
{
|
||||
{ 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<string, string> knownTypes = new Dictionary<string, string>()
|
||||
{
|
||||
{ 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<string, string> knownMethods = new Dictionary<string, string>()
|
||||
{
|
||||
{ "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<ResourceDefinition> ResourceDefinitions { get; } = new List<ResourceDefinition>();
|
||||
}
|
||||
|
||||
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<object>();
|
||||
}
|
||||
|
||||
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
|
||||
{
|
||||
return Array.Empty<object>();
|
||||
}
|
||||
|
||||
public override bool IsDefined(Type attributeType, bool inherit)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public class ShaderMethodAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public ShaderMethodAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public class ShaderAttribute : Attribute
|
||||
{
|
||||
public ShaderAttribute(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using DirectX12GameEngine.Graphics.Buffers;
|
||||
using Buffer = System.Buffer;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public abstract class ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
[SamplerResource]
|
||||
public class SamplerResource : ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
[SamplerResource]
|
||||
public class SamplerComparisonResource : ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
[TextureResource]
|
||||
public class Texture2DResource : ShaderResource
|
||||
{
|
||||
public Vector4 Sample(SamplerResource sampler, Vector2 texCoord) => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
[TextureResource]
|
||||
public class Texture2DResource<T> : ShaderResource where T : unmanaged
|
||||
{
|
||||
public T Sample(SamplerResource sampler, Vector2 texCoord) => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
[TextureResource]
|
||||
public class Texture2DArrayResource : ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
[TextureResource]
|
||||
public class TextureCubeResource : ShaderResource
|
||||
{
|
||||
}
|
||||
|
||||
[UnorderedAccessViewResource]
|
||||
public sealed class RWBufferResource<T> : ShaderResource where T : unmanaged
|
||||
{
|
||||
internal RWBufferResource(Buffer<T> buffer) => Buffer = buffer;
|
||||
|
||||
public Buffer<T> Buffer { get; }
|
||||
|
||||
public T this[uint index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
|
||||
}
|
||||
|
||||
public static class RWBufferResourceExtensions
|
||||
{
|
||||
public static RWBufferResource<T> GetGpuResource<T>(this Buffer<T> buffer) where T : unmanaged
|
||||
{
|
||||
return new RWBufferResource<T>(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
[UnorderedAccessViewResource]
|
||||
public class RWTexture2DResource<T> : ShaderResource where T : unmanaged
|
||||
{
|
||||
public T this[Numerics.UInt2 index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
|
||||
public class ShaderResourceAttribute : Attribute
|
||||
{
|
||||
public ShaderResourceAttribute([CallerLineNumber] int order = 0)
|
||||
{
|
||||
Order = order;
|
||||
}
|
||||
|
||||
public int Order { get; }
|
||||
|
||||
public bool Override { get; set; }
|
||||
}
|
||||
|
||||
public class ConstantBufferResourceAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public ConstantBufferResourceAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class SamplerResourceAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public SamplerResourceAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class TextureResourceAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public TextureResourceAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class UnorderedAccessViewResourceAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public UnorderedAccessViewResourceAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class StaticResourceAttribute : ShaderResourceAttribute
|
||||
{
|
||||
public StaticResourceAttribute([CallerLineNumber] int order = 0) : base(order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public class NumThreadsAttribute : Attribute
|
||||
{
|
||||
public NumThreadsAttribute(int x, int y, int z)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
}
|
||||
|
||||
public int X { get; }
|
||||
|
||||
public int Y { get; }
|
||||
|
||||
public int Z { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)]
|
||||
public abstract class ShaderSemanticAttribute : Attribute
|
||||
{
|
||||
}
|
||||
|
||||
public abstract class ShaderSemanticWithIndexAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
public ShaderSemanticWithIndexAttribute(int index = 0)
|
||||
{
|
||||
Index = index;
|
||||
}
|
||||
|
||||
public int Index { get; }
|
||||
}
|
||||
|
||||
public class PositionSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public PositionSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class NormalSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public NormalSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class TextureCoordinateSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public TextureCoordinateSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class ColorSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public ColorSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class TangentSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public TangentSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class SystemTargetSemanticAttribute : ShaderSemanticWithIndexAttribute
|
||||
{
|
||||
public SystemTargetSemanticAttribute(int index = 0) : base(index)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class SystemDispatchThreadIdSemanticAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
}
|
||||
|
||||
public class SystemInstanceIdSemanticAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
}
|
||||
|
||||
public class SystemIsFrontFaceSemanticAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
}
|
||||
|
||||
public class SystemPositionSemanticAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
}
|
||||
|
||||
public class SystemRenderTargetArrayIndexSemanticAttribute : ShaderSemanticAttribute
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public class ShaderSyntaxCollector : CSharpSyntaxWalker
|
||||
{
|
||||
private readonly SemanticModel semanticModel;
|
||||
private readonly ShaderGenerator shaderGenerator;
|
||||
|
||||
public ShaderSyntaxCollector(ShaderGenerator shaderGenerator, SemanticModel semanticModel)
|
||||
{
|
||||
this.shaderGenerator = shaderGenerator;
|
||||
this.semanticModel = semanticModel;
|
||||
}
|
||||
|
||||
public override void VisitParameter(ParameterSyntax node)
|
||||
{
|
||||
base.VisitParameter(node);
|
||||
|
||||
TypeInfo typeInfo = semanticModel.GetTypeInfo(node.Type);
|
||||
|
||||
string fullTypeName = typeInfo.Type.ToDisplayString(
|
||||
new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces))
|
||||
+ ", " + typeInfo.Type.ContainingAssembly.Identity.ToString();
|
||||
|
||||
shaderGenerator.AddType(Type.GetType(fullTypeName));
|
||||
}
|
||||
|
||||
public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
|
||||
{
|
||||
base.VisitMemberAccessExpression(node);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
ISymbol containingMemberSymbol = containingMemberSymbolInfo.Symbol;
|
||||
|
||||
if (!ShaderGenerator.HlslKnownMethods.Contains(containingMemberSymbol, memberSymbol))
|
||||
{
|
||||
ISymbol symbol = containingMemberSymbol.IsStatic ? containingMemberSymbol : memberSymbol.ContainingType;
|
||||
|
||||
string fullTypeName = symbol.ToDisplayString(
|
||||
new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces))
|
||||
+ ", " + symbol.ContainingAssembly.Identity.ToString();
|
||||
|
||||
shaderGenerator.AddType(Type.GetType(fullTypeName));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public class ShaderSyntaxRewriter : CSharpSyntaxRewriter
|
||||
{
|
||||
private readonly int depth;
|
||||
private readonly bool isTopLevel;
|
||||
private readonly SemanticModel semanticModel;
|
||||
private readonly ShaderGenerator shaderGenerator;
|
||||
|
||||
public ShaderSyntaxRewriter(ShaderGenerator shaderGenerator, SemanticModel semanticModel, bool isTopLevel = false, int depth = 0)
|
||||
{
|
||||
this.shaderGenerator = shaderGenerator;
|
||||
this.semanticModel = semanticModel;
|
||||
this.isTopLevel = isTopLevel;
|
||||
this.depth = depth;
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
modifiers = modifiers.Add(SyntaxFactory.Token(default, SyntaxKind.StaticKeyword, SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))));
|
||||
}
|
||||
|
||||
return node.ReplaceType(node.ReturnType).WithModifiers(modifiers);
|
||||
}
|
||||
|
||||
public override SyntaxNode VisitParameter(ParameterSyntax node)
|
||||
{
|
||||
string? attributeName = node.AttributeLists.FirstOrDefault()?.Attributes.FirstOrDefault()?.Name.ToString();
|
||||
|
||||
node = (ParameterSyntax)base.VisitParameter(node);
|
||||
node = node.WithAttributeLists(default);
|
||||
node = node.ReplaceType(node.Type);
|
||||
|
||||
if (attributeName != null)
|
||||
{
|
||||
node = node.ReplaceToken(node.Identifier, SyntaxFactory.Identifier($"{node.Identifier.ValueText} : {ShaderGenerator.HlslKnownSemantics.GetMappedName(attributeName + "Attribute")}"));
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
public override SyntaxNode VisitAttribute(AttributeSyntax node)
|
||||
{
|
||||
node = (AttributeSyntax)base.VisitAttribute(node);
|
||||
return node.ReplaceType(node.Name);
|
||||
}
|
||||
|
||||
public override SyntaxNode? VisitAttributeList(AttributeListSyntax node)
|
||||
{
|
||||
var knownAttributes = node.Attributes.Where(n => ShaderGenerator.HlslKnownAttributes.Contains(n.Name + "Attribute")).ToArray();
|
||||
|
||||
if (knownAttributes.Length == 0) return null;
|
||||
|
||||
var list = new SeparatedSyntaxList<AttributeSyntax>();
|
||||
list = list.AddRange(knownAttributes);
|
||||
|
||||
node = node.WithAttributes(list);
|
||||
|
||||
return base.VisitAttributeList(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);
|
||||
node = node.ReplaceType(node.Type);
|
||||
|
||||
if (node.ArgumentList.Arguments.Count == 0)
|
||||
{
|
||||
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
|
||||
}
|
||||
else
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Text;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public static class StringBuilderExtensions
|
||||
{
|
||||
public static StringBuilder TrimEnd(this StringBuilder sb)
|
||||
{
|
||||
if (sb.Length == 0) return sb;
|
||||
|
||||
int i;
|
||||
|
||||
for (i = sb.Length - 1; i >= 0; i--)
|
||||
{
|
||||
if (!char.IsWhiteSpace(sb[i]))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i < sb.Length - 1)
|
||||
{
|
||||
sb.Length = i + 1;
|
||||
}
|
||||
|
||||
return sb;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public static class SyntaxNodeExtensions
|
||||
{
|
||||
public static TRoot ReplaceType<TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
|
||||
{
|
||||
string value = ShaderGenerator.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;
|
||||
}
|
||||
|
||||
string? value = ShaderGenerator.HlslKnownMethods.GetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol);
|
||||
|
||||
if (value is null)
|
||||
{
|
||||
return node;
|
||||
}
|
||||
else
|
||||
{
|
||||
return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
バイナリファイルは表示されません。
バイナリファイルは表示されません。
バイナリファイルは表示されません。
バイナリファイルは表示されません。
バイナリファイルは表示されません。
新しいイシューから参照
ユーザーをブロックする