Shaders project renamed

このコミットが含まれているのは:
Sergio Pedri committed 2019-08-12 02:35:38 +02:00
1 親 c178dd64e0
コミット 031dd213b4
19ファイル変更
+2 -2

検索条件に一致するファイルはありません

+23
ファイルの表示
@@ -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}}
+47
ファイルの表示
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetDxc" Version="1.2.0-alpha">
<ExcludeAssets>native</ExcludeAssets>
</PackageReference>
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.0.4861-preview3" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.0-beta1-final" />
<PackageReference Include="Nustache" Version="1.16.0.10" />
<PackageReference Include="SharpDX.D3DCompiler" Version="4.2.1-beta0-g3060495c2a" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputeSharp.Graphics\ComputeSharp.Graphics.csproj" />
</ItemGroup>
<ItemGroup>
<!--<Content Include="..\Libs\runtimes\win-x86\native\*.*">
<PackagePath>runtimes\win-x86\native</PackagePath>
<Pack>true</Pack>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>-->
<Content Include="..\Libs\runtimes\win-x64\native\*.*">
<PackagePath>runtimes\win-x64\native</PackagePath>
<Pack>true</Pack>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Remove="Assets\ShaderTemplate.mustache" />
</ItemGroup>
<ItemGroup>
<Content Include="Assets\ShaderTemplate.mustache">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
+123
ファイルの表示
@@ -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;
}
}
}
+113
ファイルの表示
@@ -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}";
}
}
}
+200
ファイルの表示
@@ -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);
}
}
}
+23
ファイルの表示
@@ -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;
}
}
+29
ファイルの表示
@@ -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;
}
}
}
+31
ファイルの表示
@@ -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;
}
}
}
+31
ファイルの表示
@@ -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;
}
}
}
+31
ファイルの表示
@@ -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;
}
}
}
+43
ファイルの表示
@@ -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; }
}
}
+44
ファイルの表示
@@ -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);
}
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System;
using System.Diagnostics.Contracts;
using DotNetDxc;
using SharpDX.Direct3D12;
namespace DirectX12GameEngine.Shaders
{
/// <summary>
/// A <see langword="class"/> that uses the <see cref="HlslDxcLib"/> APIs to compile compute shaders
/// </summary>
public sealed class 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();
}
/// <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)
{
const uint CP_UTF16 = 1200;
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();
byte[] bytecode = GetBytesFromBlob(blob);
return bytecode;
}
// Compile error
string resultText = GetStringFromBlob(Library, result.GetErrors());
throw new Exception(resultText);
}
/// <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];
new Span<byte>(pMem, (int)size).CopyTo(result.AsSpan());
return result;
}
/// <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));
}
}
}
+169
ファイルの表示
@@ -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 ComputeSharp.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", ""));
}
}
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System;
using System.Numerics;
using ComputeSharp.Graphics.Buffers;
using Buffer = System.Buffer;
namespace DirectX12GameEngine.Shaders
{
public abstract class ShaderResource
{
}
public sealed class RWBufferResource<T> : ShaderResource where T : unmanaged
{
internal RWBufferResource(Buffer<T> buffer) => Buffer = buffer;
public Buffer<T> Buffer { get; }
public T this[uint index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
public static class RWBufferResourceExtensions
{
public static RWBufferResource<T> GetGpuResource<T>(this Buffer<T> buffer) where T : unmanaged
{
return new RWBufferResource<T>(buffer);
}
}
}
+115
ファイルの表示
@@ -0,0 +1,115 @@
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace DirectX12GameEngine.Shaders
{
public class ShaderSyntaxRewriter : CSharpSyntaxRewriter
{
private readonly int depth;
private readonly bool isTopLevel;
private readonly SemanticModel semanticModel;
public ShaderSyntaxRewriter(SemanticModel semanticModel, bool isTopLevel = false, int depth = 0)
{
this.semanticModel = semanticModel;
this.isTopLevel = isTopLevel;
this.depth = depth;
}
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
if (isTopLevel && depth > 0)
{
node = node.ReplaceToken(node.Identifier, SyntaxFactory.Identifier($"Base_{depth}_{node.Identifier.ValueText}"));
}
SyntaxTokenList modifiers = new SyntaxTokenList();
if (node.Modifiers.Any(SyntaxKind.StaticKeyword))
{
modifiers = modifiers.Add(SyntaxFactory.Token(default, SyntaxKind.StaticKeyword, SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))));
}
return node.ReplaceType(node.ReturnType).WithModifiers(modifiers);
}
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
node = (ParameterSyntax)base.VisitParameter(node);
node = node.WithAttributeLists(default);
node = node.ReplaceType(node.Type);
return node;
}
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
node = (CastExpressionSyntax)base.VisitCastExpression(node);
return node.ReplaceType(node.Type);
}
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
return node.ReplaceType(node.Declaration.Type);
}
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
node = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node);
node = node.ReplaceType(node.Type);
if (node.ArgumentList.Arguments.Count == 0)
{
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
else
{
return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
}
}
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
node = (DefaultExpressionSyntax)base.VisitDefaultExpression(node);
node = node.ReplaceType(node.Type);
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
node = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node);
if (node.Expression is BaseExpressionSyntax)
{
if (isTopLevel)
{
return SyntaxFactory.IdentifierName($"Base_{depth + 1}_{node.Name}");
}
else
{
SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
if (memberSymbol != null)
{
return SyntaxFactory.IdentifierName($"{memberSymbol.ContainingType.Name}::{node.Name}");
}
else
{
throw new InvalidOperationException();
}
}
}
else
{
return node.ReplaceMember(semanticModel);
}
}
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using System.Linq;
using DirectX12GameEngine.Shaders.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace DirectX12GameEngine.Shaders
{
public static class SyntaxNodeExtensions
{
public static TRoot ReplaceType<TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
{
string value = HlslKnownTypes.GetMappedName(type.ToString());
if (value == type.ToString())
{
return node;
}
else
{
return node.ReplaceNode(type, SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia()));
}
}
public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel)
{
SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression);
SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name);
ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault();
if (memberSymbol is null || (memberSymbol.Kind != SymbolKind.Field && memberSymbol.Kind != SymbolKind.Property && memberSymbol.Kind != SymbolKind.Method))
{
return node;
}
if (HlslKnownMethods.TryGetMappedName(containingMemberSymbolInfo.Symbol, memberSymbol) is string value)
{
return SyntaxFactory.IdentifierName(value).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
return node;
}
}
}