31ファイル変更
+961
-1446
検索条件に一致するファイルはありません
@@ -2,11 +2,13 @@
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Graphics;
|
||||
using DirectX12GameEngine.Shaders;
|
||||
using DirectX12GameEngine.Shaders.Numerics;
|
||||
using SharpDX.D3DCompiler;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using DirectX12GameEngine.Shaders.Renderer;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models;
|
||||
using SharpDX.Direct3D12;
|
||||
using CommandList = DirectX12GameEngine.Graphics.CommandList;
|
||||
using PipelineState = DirectX12GameEngine.Graphics.PipelineState;
|
||||
using ShaderBytecode = SharpDX.Direct3D12.ShaderBytecode;
|
||||
|
||||
namespace DirectX12ComputeShaderSample
|
||||
{
|
||||
@@ -19,16 +21,28 @@ namespace DirectX12ComputeShaderSample
|
||||
|
||||
public static class GraphicsDeviceExtensions
|
||||
{
|
||||
public static void For(this GraphicsDevice device, int n, Action<UInt3> shader)
|
||||
public static void For(this GraphicsDevice device, int n, Action<ThreadIds> action)
|
||||
{
|
||||
// Generate the compute shadr
|
||||
ShaderGenerator shaderGenerator = new ShaderGenerator(shader);
|
||||
ShaderGenerationResult result = shaderGenerator.GenerateShaderForLambda();
|
||||
// Load the input shader
|
||||
ShaderLoader shaderLoader = ShaderLoader.Load(action);
|
||||
|
||||
byte[] shaderBytecode = ShaderCompiler.CompileShader(result.ShaderSource, ShaderVersion.ComputeShader, result.ComputeShader);
|
||||
// Render the loaded shader
|
||||
ShaderInfo shaderInfo = new ShaderInfo
|
||||
{
|
||||
FieldsList = shaderLoader.FieldsInfo,
|
||||
ThreadsX = n,
|
||||
ThreadsY = 1,
|
||||
ThreadsZ = 1,
|
||||
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
|
||||
ShaderBody = shaderLoader.MethodBody
|
||||
};
|
||||
string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
|
||||
|
||||
// Compile the loaded shader to HLSL bytecode
|
||||
ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource);
|
||||
|
||||
// Create the root signature for the pipeline and the pipeline state
|
||||
RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderGenerator.RootParameters);
|
||||
RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.RootParameters);
|
||||
RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription);
|
||||
PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode);
|
||||
|
||||
@@ -37,13 +51,13 @@ namespace DirectX12ComputeShaderSample
|
||||
commandList.SetPipelineState(pipelineState);
|
||||
|
||||
// Load the captured buffers
|
||||
foreach (var item in shaderGenerator.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
|
||||
foreach (var buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i)))
|
||||
{
|
||||
commandList.SetComputeRootDescriptorTable(item.Index, item.Resource);
|
||||
commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource);
|
||||
}
|
||||
|
||||
// Dispatch and wait for completion
|
||||
commandList.Dispatch(2, 2, 1);
|
||||
commandList.Dispatch(1, 1, 1);
|
||||
commandList.Flush(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using DirectX12GameEngine.Shaders;
|
||||
using DirectX12GameEngine.Shaders.Numerics;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Graphics.Buffers;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using Buffer = DirectX12GameEngine.Graphics.Buffers.Buffer;
|
||||
|
||||
namespace DirectX12ComputeShaderSample
|
||||
@@ -27,7 +27,7 @@ namespace DirectX12ComputeShaderSample
|
||||
var data = gpuBuffer.GetGpuResource();
|
||||
|
||||
// Shader body
|
||||
Action<UInt3> action = id =>
|
||||
Action<ThreadIds> action = id =>
|
||||
{
|
||||
data[id.X + id.Y * size] *= 2;
|
||||
};
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum ClearFlags
|
||||
{
|
||||
None = 0,
|
||||
FlagsDepth = 1,
|
||||
FlagsStencil = 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{{#FieldsList}}
|
||||
{{!Static scalar}}
|
||||
{{#IsStaticScalarField}}
|
||||
static {{&FieldType}} {{FieldName}} = {{FieldValue}};
|
||||
{{/IsStaticScalarField}}
|
||||
{{!Constant buffer}}
|
||||
{{#IsConstantBuffer}}
|
||||
cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}})
|
||||
{
|
||||
{{&FieldType}} {{FieldName}};
|
||||
}
|
||||
{{/IsConstantBuffer}}
|
||||
{{!Read write buffer}}
|
||||
{{#IsReadWriteBuffer}}
|
||||
{{&FieldType}} {{FieldName}} : SV_DispatchThreadId : register(u{{ReadWriteBufferIndex}});
|
||||
{{/IsReadWriteBuffer}}
|
||||
|
||||
{{/FieldsList}}
|
||||
{{!Shader entry point}}
|
||||
[Shader("compute")]
|
||||
[NumThreads({{ThreadsX}}, {{ThreadsY}}, {{ThreadsZ}})]
|
||||
void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId)
|
||||
{{&ShaderBody}}
|
||||
@@ -13,6 +13,7 @@
|
||||
</PackageReference>
|
||||
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.0.4861-preview3" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.0-beta1-final" />
|
||||
<PackageReference Include="Nustache" Version="1.16.0.10" />
|
||||
<PackageReference Include="SharpDX.D3DCompiler" Version="4.2.1-beta0-g3060495c2a" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -34,4 +35,14 @@
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Assets\ShaderTemplate.mustache" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="Assets\ShaderTemplate.mustache">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,123 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET method
|
||||
/// </summary>
|
||||
internal static class HlslKnownMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of supported known methods to HLSL methods
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> KnownMethods = new Dictionary<string, string>
|
||||
{
|
||||
// Math
|
||||
["System.Math.Cos"] = "cos",
|
||||
["System.Math.Max"] = "max",
|
||||
["System.Math.Pow"] = "pow",
|
||||
["System.Math.Sin"] = "sin",
|
||||
["System.Math.PI"] = "3.1415926535897931",
|
||||
|
||||
// MathF
|
||||
["System.MathF.Cos"] = "cos",
|
||||
["System.MathF.Max"] = "max",
|
||||
["System.MathF.Pow"] = "pow",
|
||||
["System.MathF.Sin"] = "sin",
|
||||
["System.MathF.PI"] = "3.14159274f",
|
||||
|
||||
// ThreadIds
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.X"] = ".x",
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Y"] = ".y",
|
||||
["DirectX12GameEngine.Shaders.Primitives.ThreadIds.Z"] = ".z",
|
||||
|
||||
// Vector3
|
||||
["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)",
|
||||
|
||||
// Vector4
|
||||
["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)",
|
||||
|
||||
// Matrix4x4
|
||||
["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]"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a specified method is a known HLSL method
|
||||
/// </summary>
|
||||
/// <param name="containingMemberSymbol">The containing member symbol for the method to check</param>
|
||||
/// <param name="memberSymbol">The symbol for the method to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input method is in fact an HLSL known method</returns>
|
||||
[Pure]
|
||||
public static bool IsKnownMethod(ISymbol containingMemberSymbol, ISymbol memberSymbol)
|
||||
{
|
||||
string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString();
|
||||
return KnownMethods.ContainsKey(fullTypeName + Type.Delimiter + memberSymbol.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the mapped HLSL-compatible mthod name for the input symbols
|
||||
/// </summary>
|
||||
/// <param name="containingMemberSymbol">The containing member symbol for the method to check</param>
|
||||
/// <param name="memberSymbol">The symbol for the method to check</param>
|
||||
/// <returns>The HLSL-compatible method name that can be used in an HLSL shader</returns>
|
||||
[Pure]
|
||||
public static string? TryGetMappedName(ISymbol containingMemberSymbol, ISymbol memberSymbol)
|
||||
{
|
||||
string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString();
|
||||
|
||||
// Check if the target method is a known method
|
||||
if (KnownMethods.TryGetValue($"{fullTypeName}{Type.Delimiter}{memberSymbol.Name}", out string mapped))
|
||||
{
|
||||
// Return the static method if possible, otherwise access the parent instance
|
||||
if (memberSymbol.IsStatic) return mapped;
|
||||
return $"{containingMemberSymbol.Name}{mapped}";
|
||||
}
|
||||
|
||||
if (memberSymbol.IsStatic) return $"{containingMemberSymbol.Name}::{memberSymbol.Name}";
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
using System.Text.RegularExpressions;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types
|
||||
/// </summary>
|
||||
internal static class HlslKnownTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of supported known types to HLSL types
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> KnownTypes = new Dictionary<string, string>
|
||||
{
|
||||
[typeof(bool).FullName] = "bool",
|
||||
[typeof(int).FullName] = "int",
|
||||
[typeof(uint).FullName] = "uint",
|
||||
[typeof(float).FullName] = "float",
|
||||
[typeof(double).FullName] = "double",
|
||||
[typeof(Vector2).FullName] = "float2",
|
||||
[typeof(Vector3).FullName] = "float3",
|
||||
[typeof(Vector4).FullName] = "float4",
|
||||
[typeof(Matrix4x4).FullName] = "float4x4",
|
||||
[typeof(ThreadIds).FullName] = "uint3",
|
||||
[typeof(RWBufferResource<>).FullName] = "RWBuffer"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a known scalar type
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL scalar type</returns>
|
||||
[Pure]
|
||||
public static bool IsKnownScalarType(Type type) => type == typeof(bool) ||
|
||||
type == typeof(int) ||
|
||||
type == typeof(uint) ||
|
||||
type == typeof(float) ||
|
||||
type == typeof(double);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a known vector type
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL vector type</returns>
|
||||
[Pure]
|
||||
public static bool IsKnownVectorType(Type type) => type == typeof(Vector2) ||
|
||||
type == typeof(Vector3) ||
|
||||
type == typeof(Vector4) ||
|
||||
type == typeof(Matrix4x4);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not the input type is a <see cref="RWBufferResource{T}"/> value
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a <see cref="RWBufferResource{T}"/> instance</returns>
|
||||
[Pure]
|
||||
public static bool IsReadWriteBufferType(Type type) => type.IsGenericType &&
|
||||
type.GetGenericTypeDefinition() == typeof(RWBufferResource<>);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a given <see cref="Type"/> is an HLSL known type
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to check</param>
|
||||
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL type</returns>
|
||||
[Pure]
|
||||
public static bool IsKnownType(Type type)
|
||||
{
|
||||
Type declaredType = type.IsArray ? type.GetElementType() : type;
|
||||
string fullname = $"{declaredType.Namespace}{Type.Delimiter}{declaredType.Name}";
|
||||
|
||||
return KnownTypes.ContainsKey(fullname);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the input <see cref="Type"/> instance
|
||||
/// </summary>
|
||||
/// <param name="type">The input <see cref="Type"/> instance to map</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader</returns>
|
||||
[Pure]
|
||||
public static string GetMappedName(Type type)
|
||||
{
|
||||
Type declaredType = type.IsArray ? type.GetElementType() : type;
|
||||
string
|
||||
fullname = $"{declaredType.Namespace}{Type.Delimiter}{declaredType.Name}",
|
||||
mappedName = KnownTypes.TryGetValue(fullname, out string mapped) ? mapped : declaredType.Name,
|
||||
hlslName = declaredType.IsGenericType ? mappedName + $"<{GetMappedName(declaredType.GetGenericArguments()[0])}>" : mappedName;
|
||||
|
||||
return hlslName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the input type name
|
||||
/// </summary>
|
||||
/// <param name="name">The input type name to map</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader</returns>
|
||||
[Pure]
|
||||
public static string GetMappedName(string name)
|
||||
{
|
||||
int indexOfOpenBracket = name.IndexOf('<');
|
||||
string
|
||||
genericArguments = indexOfOpenBracket >= 0 ? name.Substring(indexOfOpenBracket) : string.Empty,
|
||||
polishedName = indexOfOpenBracket >= 0 ? name.Remove(indexOfOpenBracket) + "`1" : name,
|
||||
mappedName = KnownTypes.TryGetValue(polishedName, out string mapped) ? mapped : Regex.Match(polishedName, @"[^\.]+$").Value;
|
||||
|
||||
return $"{mappedName}{genericArguments}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
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,200 @@
|
||||
using System;
|
||||
using System.CodeDom.Compiler;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Metadata;
|
||||
using ICSharpCode.Decompiler;
|
||||
using ICSharpCode.Decompiler.CSharp;
|
||||
using ICSharpCode.Decompiler.Metadata;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that is able to decompile arbitrary methods
|
||||
/// </summary>
|
||||
public sealed class MethodDecompiler
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the singleton <see cref="MethodDecompiler"/> instance to use
|
||||
/// </summary>
|
||||
public static MethodDecompiler Instance { get; } = new MethodDecompiler();
|
||||
|
||||
/// <summary>
|
||||
/// The dummy object used to handle concurrent decompilation requests
|
||||
/// </summary>
|
||||
private readonly object Lock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of available <see cref="CSharpDecompiler"/> instances targeting different assemblies
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, CSharpDecompiler> Decompilers = new Dictionary<string, CSharpDecompiler>();
|
||||
|
||||
/// <summary>
|
||||
/// The available <see cref="PEFile"/> instances for the loaded assemblies
|
||||
/// </summary>
|
||||
private readonly IReadOnlyList<PEFile> PEFiles;
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of <see cref="PEFile"/> and <see cref="TypeDefinition"/> values for the discovered <see cref="Type"/> instances
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, (PEFile PEFile, TypeDefinition TypeDefinition)> TypeDefinitions = new Dictionary<Type, (PEFile, TypeDefinition)>();
|
||||
|
||||
/// <summary>
|
||||
/// The incremental <see cref="Compilation"/> instance for the shader assembly
|
||||
/// </summary>
|
||||
private Compilation _Compilation;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MethodDecompiler"/> instance
|
||||
/// </summary>
|
||||
private MethodDecompiler()
|
||||
{
|
||||
// Load the assembly paths for all the available dlls
|
||||
IReadOnlyList<string> assemblyPaths;
|
||||
if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location))
|
||||
{
|
||||
assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using PEFile _ = new PEFile(p);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
// Load and store all the available PEFile instances
|
||||
PEFiles = assemblyPaths.Select(p => new PEFile(p)).ToArray();
|
||||
|
||||
// Ceate an incremental shader assembly with the available references
|
||||
IEnumerable<PortableExecutableReference> metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p));
|
||||
_Compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences);
|
||||
|
||||
// Monitor for new assemblies being loaded
|
||||
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
|
||||
}
|
||||
|
||||
// Increment the shader assembly when a new assembly is loaded
|
||||
private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e)
|
||||
{
|
||||
if (!e.LoadedAssembly.IsDynamic)
|
||||
{
|
||||
PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location);
|
||||
_Compilation = _Compilation.AddReferences(metadataReference);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
|
||||
/// </summary>
|
||||
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
|
||||
/// <param name="rootNode">The root node for the syntax tree of the input method</param>
|
||||
/// <param name="semanticModel">The semantic model for the input method</param>
|
||||
public void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode rootNode, out SemanticModel semanticModel)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
// Get the handle of the input method
|
||||
GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle);
|
||||
|
||||
// Get or create a decompiler for the target assembly, and decompile the method
|
||||
if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler))
|
||||
{
|
||||
decompiler = CreateDecompiler(assemblyPath);
|
||||
Decompilers.Add(assemblyPath, decompiler);
|
||||
}
|
||||
|
||||
string sourceCode = decompiler.DecompileAsString(methodHandle);
|
||||
|
||||
// Load the method syntax tree
|
||||
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
|
||||
rootNode = syntaxTree.GetRoot();
|
||||
|
||||
// Update the incremental compilation and retrieve the syntax tree for the method
|
||||
_Compilation = _Compilation.AddSyntaxTrees(syntaxTree);
|
||||
semanticModel = _Compilation.GetSemanticModel(syntaxTree);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the assembly path and method handle for the input <see cref="MethodInfo"/> instance
|
||||
/// </summary>
|
||||
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
|
||||
/// <param name="assemblyPath">The path of the assembly containing the input method</param>
|
||||
/// <param name="methodHandle">The handle for the input method</param>
|
||||
private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle)
|
||||
{
|
||||
// Try to get the method handle from the assembly of the declaring type
|
||||
Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type");
|
||||
string path = declaringType.Assembly.Location;
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
assemblyPath = path;
|
||||
methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try to get the PEFile and type definition for the method declaring type
|
||||
if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple))
|
||||
{
|
||||
foreach (PEFile peFile in PEFiles)
|
||||
{
|
||||
// If not available, browse through the loaded PEFiles to find the type definition
|
||||
TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName);
|
||||
|
||||
if (!typeDefinitionHandle.IsNil)
|
||||
{
|
||||
tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle));
|
||||
TypeDefinitions.Add(methodInfo.DeclaringType, tuple);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tuple.PEFile is null) throw new InvalidOperationException($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}");
|
||||
}
|
||||
|
||||
PEFile peFileForMethod = tuple.PEFile;
|
||||
TypeDefinition typeDefinition = tuple.TypeDefinition;
|
||||
|
||||
// Retrieve the assembly path and method handle from the loaded PEFile and metadata
|
||||
assemblyPath = peFileForMethod.FileName;
|
||||
methodHandle = typeDefinition.GetMethods()
|
||||
.Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name))
|
||||
.First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
|
||||
/// </summary>
|
||||
/// <param name="assemblyPath">The path of the assembly to decompile</param>
|
||||
/// <returns>A <see cref="CSharpDecompiler"/> instance that can be used on the targeted assembly</returns>
|
||||
[Pure]
|
||||
private static CSharpDecompiler CreateDecompiler(string assemblyPath)
|
||||
{
|
||||
DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest)
|
||||
{
|
||||
ObjectOrCollectionInitializers = false,
|
||||
UsingDeclarations = false,
|
||||
CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString }
|
||||
};
|
||||
|
||||
UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard");
|
||||
return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace DirectX12GameEngine.Shaders.Numerics
|
||||
{
|
||||
public struct UInt2
|
||||
{
|
||||
public uint X;
|
||||
|
||||
public uint Y;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace DirectX12GameEngine.Shaders.Numerics
|
||||
{
|
||||
public struct Vector2
|
||||
{
|
||||
public static float Length(System.Numerics.Vector2 value) => value.Length();
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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,23 @@
|
||||
namespace DirectX12GameEngine.Shaders.Primitives
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="struct"/> that indicates the ids of a given GPU thread running a compute shader
|
||||
/// </summary>
|
||||
public readonly struct ThreadIds
|
||||
{
|
||||
/// <summary>
|
||||
/// The X id of the current thread
|
||||
/// </summary>
|
||||
public readonly uint X;
|
||||
|
||||
/// <summary>
|
||||
/// The Y id of the current thread
|
||||
/// </summary>
|
||||
public readonly uint Y;
|
||||
|
||||
/// <summary>
|
||||
/// The Z id of the current thread
|
||||
/// </summary>
|
||||
public readonly uint Z;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Abstract
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a shader field
|
||||
/// </summary>
|
||||
public abstract class FieldInfoBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the current field
|
||||
/// </summary>
|
||||
public string FieldType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name to use for the current field
|
||||
/// </summary>
|
||||
public string FieldName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="FieldInfoBase"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="fieldType">The type of the current field</param>
|
||||
/// <param name="fieldName">The name of the current field</param>
|
||||
protected FieldInfoBase(string fieldType, string fieldName)
|
||||
{
|
||||
FieldType = fieldType;
|
||||
FieldName = fieldName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a constant buffer field
|
||||
/// </summary>
|
||||
public sealed class ConstantBufferFieldInfo : FieldInfoBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the current <see cref="FieldInfoBase"/> instance represents a constant buffer (always <see langword="true"/>)
|
||||
/// </summary>
|
||||
public bool IsConstantBuffer { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the index of the current constant buffer field
|
||||
/// </summary>
|
||||
public int ConstantBufferIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ConstantBufferFieldInfo"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="fieldType">The type of the current field</param>
|
||||
/// <param name="fieldName">The name of the current field</param>
|
||||
/// <param name="bufferIndex">The index of the current constant buffer field</param>
|
||||
public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName)
|
||||
{
|
||||
ConstantBufferIndex = bufferIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a read write buffer field
|
||||
/// </summary>
|
||||
public sealed class ReadWriteBufferFieldInfo : FieldInfoBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the current <see cref="FieldInfoBase"/> instance represents a read write buffer (always <see langword="true"/>)
|
||||
/// </summary>
|
||||
public bool IsReadWriteBuffer { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the index of the current read write buffer field
|
||||
/// </summary>
|
||||
public int ReadWriteBufferIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ReadWriteBufferFieldInfo"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="fieldType">The type of the current field</param>
|
||||
/// <param name="fieldName">The name of the current field</param>
|
||||
/// <param name="bufferIndex">The index of the current read write buffer field</param>
|
||||
public ReadWriteBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName)
|
||||
{
|
||||
ReadWriteBufferIndex = bufferIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info on a static scalar field
|
||||
/// </summary>
|
||||
public sealed class StaticScalarFieldInfo : FieldInfoBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the current <see cref="FieldInfoBase"/> instance represents a static scalar value (always <see langword="true"/>)
|
||||
/// </summary>
|
||||
public bool IsStaticScalarField { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value to set for the current field
|
||||
/// </summary>
|
||||
public object FieldValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="StaticScalarFieldInfo"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="fieldType">The type of the current field</param>
|
||||
/// <param name="fieldName">The name of the current field</param>
|
||||
/// <param name="fieldValue">The static value to assign to the current field</param>
|
||||
public StaticScalarFieldInfo(string fieldType, string fieldName, object fieldValue) : base(fieldType, fieldName)
|
||||
{
|
||||
FieldValue = fieldValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Collections.Generic;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field is uninitialized
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains info to render a shader source to compile
|
||||
/// </summary>
|
||||
public sealed class ShaderInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the list of fields being present in the current shader
|
||||
/// </summary>
|
||||
public IReadOnlyList<FieldInfoBase> FieldsList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the X group
|
||||
/// </summary>
|
||||
public int ThreadsX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Y group
|
||||
/// </summary>
|
||||
public int ThreadsY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of threads in the Z group
|
||||
/// </summary>
|
||||
public int ThreadsZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name for the threads id variable used in the shader
|
||||
/// </summary>
|
||||
public string ThreadsIdsVariableName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the shader body to compile
|
||||
/// </summary>
|
||||
public string ShaderBody { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the mustache templating system to render HLSL shaders
|
||||
/// </summary>
|
||||
public sealed class ShaderRenderer
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the singleton <see cref="ShaderRenderer"/> instance to use
|
||||
/// </summary>
|
||||
public static ShaderRenderer Instance { get; } = new ShaderRenderer();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderRenderer"/> instance and loads the mustache template to use
|
||||
/// </summary>
|
||||
private ShaderRenderer()
|
||||
{
|
||||
string
|
||||
assemblyPath = Assembly.GetExecutingAssembly().Location,
|
||||
assemblyDirectory = Path.GetDirectoryName(assemblyPath) ?? throw new InvalidOperationException("Can't find the assembly directory"),
|
||||
templatePath = Path.Combine(assemblyDirectory, "Assets", "ShaderTemplate.mustache");
|
||||
Template = File.ReadAllText(templatePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mustache template used by the shader renderer
|
||||
/// </summary>
|
||||
public string Template { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Renders a new HLSL shader source with the given parameters
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with the shader information</param>
|
||||
/// <returns>The source code for the new HLSL shader</returns>
|
||||
[Pure]
|
||||
public string Render(ShaderInfo info) => Nustache.Core.Render.StringToString(Template, info);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,54 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Diagnostics.Contracts;
|
||||
using DotNetDxc;
|
||||
using SharpDX.D3DCompiler;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public static class ShaderCompiler
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the <see cref="HlslDxcLib"/> APIs to compile compute shaders
|
||||
/// </summary>
|
||||
public sealed class ShaderCompiler
|
||||
{
|
||||
static ShaderCompiler()
|
||||
/// <summary>
|
||||
/// Gets the singleton <see cref="ShaderCompiler"/> instance to use
|
||||
/// </summary>
|
||||
public static ShaderCompiler Instance { get; } = new ShaderCompiler();
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDxcCompiler"/> instance to use to create new HLSL shaders
|
||||
/// </summary>
|
||||
private readonly IDxcCompiler Compiler;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDxcLibrary"/> instance to use to create the bytecode for HLSL sources
|
||||
/// </summary>
|
||||
private readonly IDxcLibrary Library;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderCompiler"/> instance
|
||||
/// </summary>
|
||||
private ShaderCompiler()
|
||||
{
|
||||
HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn();
|
||||
Compiler = HlslDxcLib.CreateDxcCompiler();
|
||||
Library = HlslDxcLib.CreateDxcLibrary();
|
||||
}
|
||||
|
||||
public static byte[] CompileShaderFile(string filePath, ShaderVersion? version = null, string? entryPoint = null)
|
||||
/// <summary>
|
||||
/// Compiles a new HLSL shader from the input source code
|
||||
/// </summary>
|
||||
/// <param name="source">The HLSL source code to compile</param>
|
||||
/// <returns>The bytecode for the compiled shader</returns>
|
||||
[Pure]
|
||||
public ShaderBytecode CompileShader(string source)
|
||||
{
|
||||
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());
|
||||
IDxcBlobEncoding sourceBlob = Library.CreateBlobWithEncodingOnHeapCopy(source, (uint)(source.Length * 2), CP_UTF16);
|
||||
IDxcOperationResult result = Compiler.Compile(sourceBlob, "", "CSMain", "cs_6_1", new[] { "-Zpr" }, 1, null, 0, Library.CreateIncludeHandler());
|
||||
|
||||
// Get the compiled bytecode in case of success
|
||||
if (result.GetStatus() == 0)
|
||||
{
|
||||
IDxcBlob blob = result.GetResult();
|
||||
@@ -35,31 +56,37 @@ namespace DirectX12GameEngine.Shaders
|
||||
|
||||
return bytecode;
|
||||
}
|
||||
else
|
||||
{
|
||||
string resultText = GetStringFromBlob(library, result.GetErrors());
|
||||
throw new Exception(resultText);
|
||||
}
|
||||
|
||||
// Compile error
|
||||
string resultText = GetStringFromBlob(Library, result.GetErrors());
|
||||
throw new Exception(resultText);
|
||||
}
|
||||
|
||||
public static unsafe byte[] GetBytesFromBlob(IDxcBlob blob)
|
||||
/// <summary>
|
||||
/// Reads the buffer content from an input <see cref="IDxcBlob"/> instance
|
||||
/// </summary>
|
||||
/// <param name="blob">The input <see cref="IDxcBlob"/> instance to read data from</param>
|
||||
/// <returns>The read bytes buffer, as an array</returns>
|
||||
[Pure]
|
||||
private 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];
|
||||
}
|
||||
}
|
||||
new Span<byte>(pMem, (int)size).CopyTo(result.AsSpan());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob)
|
||||
/// <summary>
|
||||
/// Reads a <see cref="string"/> value from an input <see cref="IDxcBlob"/> instance
|
||||
/// </summary>
|
||||
/// <param name="library">The source <see cref="IDxcLibrary"/> to use to load the data</param>
|
||||
/// <param name="blob">The input <see cref="IDxcBlob"/> instance to read data from</param>
|
||||
/// <returns>The resulting <see cref="string"/> read from the input data buffer</returns>
|
||||
[Pure]
|
||||
private static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob)
|
||||
{
|
||||
blob = library.GetBlobAstUf16(blob);
|
||||
return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2));
|
||||
|
||||
@@ -1,870 +0,0 @@
|
||||
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,169 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using DirectX12GameEngine.Graphics.Buffers.Abstract;
|
||||
using DirectX12GameEngine.Shaders.Mappings;
|
||||
using DirectX12GameEngine.Shaders.Primitives;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Abstract;
|
||||
using DirectX12GameEngine.Shaders.Renderer.Models.Fields;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field is uninitialized
|
||||
|
||||
namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
|
||||
/// </summary>
|
||||
public sealed class ShaderLoader
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="Action{T}"/> that represents the shader to load
|
||||
/// </summary>
|
||||
private readonly Action<ThreadIds> Action;
|
||||
|
||||
/// <summary>
|
||||
/// The closure <see cref="Type"/> for the <see cref="Action"/> field
|
||||
/// </summary>
|
||||
private readonly Type ShaderType;
|
||||
|
||||
/// <summary>
|
||||
/// The closure instance for the <see cref="Action"/> field
|
||||
/// </summary>
|
||||
private readonly object ShaderInstance;
|
||||
|
||||
/// <summary>
|
||||
/// The sequence of fields in the targeted closure
|
||||
/// </summary>
|
||||
private readonly IReadOnlyList<FieldInfo> ShaderFields;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderLoader"/> with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
|
||||
private ShaderLoader(Action<ThreadIds> action)
|
||||
{
|
||||
Action = action;
|
||||
ShaderType = action.Method.DeclaringType;
|
||||
ShaderInstance = action.Target;
|
||||
ShaderFields = ShaderType.GetFields().ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="RootParameter"/> array for the current shader
|
||||
/// </summary>
|
||||
public RootParameter[] RootParameters { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ordered collection of read write buffers used as fields in the current shader
|
||||
/// </summary>
|
||||
public IReadOnlyList<GraphicsResource> ReadWriteBuffers { get; private set; }
|
||||
|
||||
private readonly List<FieldInfoBase> _FieldsInfo = new List<FieldInfoBase>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of <see cref="FieldInfoBase"/> items for the shader fields
|
||||
/// </summary>
|
||||
public IReadOnlyList<FieldInfoBase> FieldsInfo => _FieldsInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
|
||||
/// </summary>
|
||||
public string ThreadsIdsVariableName { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the generated source code for the method in the current shader
|
||||
/// </summary>
|
||||
public string MethodBody { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads and processes an input <see cref="Action{T}"/>
|
||||
/// </summary>
|
||||
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
|
||||
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
|
||||
[Pure]
|
||||
public static ShaderLoader Load(Action<ThreadIds> action)
|
||||
{
|
||||
ShaderLoader @this = new ShaderLoader(action);
|
||||
|
||||
@this.LoadFieldsInfo();
|
||||
@this.LoadMethodSource();
|
||||
|
||||
return @this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the fields info for the current shader being loaded
|
||||
/// </summary>
|
||||
private void LoadFieldsInfo()
|
||||
{
|
||||
if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded");
|
||||
|
||||
List<DescriptorRange> descriptorRanges = new List<DescriptorRange>();
|
||||
List<GraphicsResource> readWriteBuffers = new List<GraphicsResource>();
|
||||
int readWriteBuffersCount = 0;
|
||||
|
||||
foreach (FieldInfo fieldInfo in ShaderFields)
|
||||
{
|
||||
Type fieldType = fieldInfo.FieldType;
|
||||
string fieldName = fieldInfo.Name;
|
||||
object fieldValue = fieldInfo.GetValue(ShaderInstance);
|
||||
FieldInfoBase processedFieldInfo;
|
||||
|
||||
// Read write buffer
|
||||
if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
|
||||
{
|
||||
// Root parameter for a read write buffer
|
||||
DescriptorRange range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount);
|
||||
descriptorRanges.Add(range);
|
||||
|
||||
// Reference to the underlying buffer
|
||||
object readWriteBuffer = fieldInfo.GetValue(ShaderInstance);
|
||||
GraphicsResource resource = (GraphicsResource)fieldType.GetProperty(nameof(RWBufferResource<byte>.Buffer)).GetValue(readWriteBuffer);
|
||||
readWriteBuffers.Add(resource);
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++);
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownScalarType(fieldType))
|
||||
{
|
||||
// Static scalar field
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
processedFieldInfo = new StaticScalarFieldInfo(typeName, fieldName, fieldValue);
|
||||
}
|
||||
else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}");
|
||||
|
||||
_FieldsInfo.Add(processedFieldInfo);
|
||||
}
|
||||
|
||||
RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray();
|
||||
ReadWriteBuffers = readWriteBuffers;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the entry method for the current shader being loaded
|
||||
/// </summary>
|
||||
private void LoadMethodSource()
|
||||
{
|
||||
// Decompile the shader method
|
||||
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out SyntaxNode root, out SemanticModel semanticModel);
|
||||
|
||||
// Rewrite the shader method (eg. to fix the type declarations)
|
||||
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, true);
|
||||
root = syntaxRewriter.Visit(root);
|
||||
|
||||
// Get the thread ids identifier name and shader method body
|
||||
ConstructorDeclarationSyntax methodNode = root.ChildNodes().OfType<ConstructorDeclarationSyntax>().First();
|
||||
ThreadsIdsVariableName = methodNode.ParameterList.Parameters.First().Identifier.Text;
|
||||
MethodBody = methodNode.Body.ToFullString();
|
||||
|
||||
// Additional preprocessing
|
||||
MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -9,39 +9,6 @@ namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
}
|
||||
|
||||
[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;
|
||||
@@ -58,10 +25,4 @@ namespace DirectX12GameEngine.Shaders
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
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
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,9 @@ namespace DirectX12GameEngine.Shaders
|
||||
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)
|
||||
public ShaderSyntaxRewriter(SemanticModel semanticModel, bool isTopLevel = false, int depth = 0)
|
||||
{
|
||||
this.shaderGenerator = shaderGenerator;
|
||||
this.semanticModel = semanticModel;
|
||||
this.isTopLevel = isTopLevel;
|
||||
this.depth = depth;
|
||||
@@ -42,40 +40,13 @@ namespace DirectX12GameEngine.Shaders
|
||||
|
||||
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);
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Linq;
|
||||
using DirectX12GameEngine.Shaders.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
@@ -9,7 +10,7 @@ namespace DirectX12GameEngine.Shaders
|
||||
{
|
||||
public static TRoot ReplaceType<TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
|
||||
{
|
||||
string value = ShaderGenerator.HlslKnownTypes.GetMappedName(type.ToString());
|
||||
string value = HlslKnownTypes.GetMappedName(type.ToString());
|
||||
|
||||
if (value == type.ToString())
|
||||
{
|
||||
@@ -33,16 +34,12 @@ namespace DirectX12GameEngine.Shaders
|
||||
return node;
|
||||
}
|
||||
|
||||
string? value = ShaderGenerator.HlslKnownMethods.GetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol);
|
||||
|
||||
if (value is null)
|
||||
{
|
||||
return node;
|
||||
}
|
||||
else
|
||||
if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
|
||||
{
|
||||
return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする