diff --git a/src/DirectX12ComputeShaderSample/Gpu.cs b/src/DirectX12ComputeShaderSample/Gpu.cs index 1667f05b..65f9f084 100644 --- a/src/DirectX12ComputeShaderSample/Gpu.cs +++ b/src/DirectX12ComputeShaderSample/Gpu.cs @@ -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 shader) + public static void For(this GraphicsDevice device, int n, Action 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); } } diff --git a/src/DirectX12ComputeShaderSample/Program.cs b/src/DirectX12ComputeShaderSample/Program.cs index f962f141..48be6ecd 100644 --- a/src/DirectX12ComputeShaderSample/Program.cs +++ b/src/DirectX12ComputeShaderSample/Program.cs @@ -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 diff --git a/src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache b/src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache new file mode 100644 index 00000000..3ab5de4a --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Assets/ShaderTemplate.mustache @@ -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}} diff --git a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj index 581e66ea..936e6672 100644 --- a/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj +++ b/src/DirectX12GameEngine.Shaders/DirectX12GameEngine.Shaders.csproj @@ -13,6 +13,7 @@ + @@ -34,4 +35,14 @@ + + + + + + + PreserveNewest + + + diff --git a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs b/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs new file mode 100644 index 00000000..6e33493c --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownMethods.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using Microsoft.CodeAnalysis; + +namespace DirectX12GameEngine.Shaders.Mappings +{ + /// + /// A that contains and maps known HLSL method names to common .NET method + /// + internal static class HlslKnownMethods + { + /// + /// The mapping of supported known methods to HLSL methods + /// + private static readonly IReadOnlyDictionary KnownMethods = new Dictionary + { + // 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]" + }; + + /// + /// Checks whether or not a specified method is a known HLSL method + /// + /// The containing member symbol for the method to check + /// The symbol for the method to check + /// A indicating whether the input method is in fact an HLSL known method + [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); + } + + /// + /// Tries to get the mapped HLSL-compatible mthod name for the input symbols + /// + /// The containing member symbol for the method to check + /// The symbol for the method to check + /// The HLSL-compatible method name that can be used in an HLSL shader + [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; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs b/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs new file mode 100644 index 00000000..c6038358 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Mappings/HlslKnownTypes.cs @@ -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 +{ + /// + /// A that contains and maps known HLSL type names to common .NET types + /// + internal static class HlslKnownTypes + { + /// + /// The mapping of supported known types to HLSL types + /// + private static readonly IReadOnlyDictionary KnownTypes = new Dictionary + { + [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" + }; + + /// + /// Checks whether or not the input type is a known scalar type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known HLSL scalar type + [Pure] + public static bool IsKnownScalarType(Type type) => type == typeof(bool) || + type == typeof(int) || + type == typeof(uint) || + type == typeof(float) || + type == typeof(double); + + /// + /// Checks whether or not the input type is a known vector type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known HLSL vector type + [Pure] + public static bool IsKnownVectorType(Type type) => type == typeof(Vector2) || + type == typeof(Vector3) || + type == typeof(Vector4) || + type == typeof(Matrix4x4); + + /// + /// Checks whether or not the input type is a value + /// + /// The input instance to check + /// A indicating whether the input is in fact a instance + [Pure] + public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && + type.GetGenericTypeDefinition() == typeof(RWBufferResource<>); + + /// + /// Checks whether or not a given is an HLSL known type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known HLSL type + [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); + } + + /// + /// Gets the mapped HLSL-compatible type name for the input instance + /// + /// The input instance to map + /// The HLSL-compatible type name that can be used in an HLSL shader + [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; + } + + /// + /// Gets the mapped HLSL-compatible type name for the input type name + /// + /// The input type name to map + /// The HLSL-compatible type name that can be used in an HLSL shader + [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}"; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs b/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs deleted file mode 100644 index f768115d..00000000 --- a/src/DirectX12GameEngine.Shaders/MemberInfoExtensions.cs +++ /dev/null @@ -1,97 +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 GetBaseMethods(this MethodInfo methodInfo) - { - List methodInfos = new List() { methodInfo }; - - if (methodInfo.IsOverride()) - { - MethodInfo? currentMethodInfo = methodInfo.DeclaringType.BaseType?.GetMethod(methodInfo.Name); - - while (currentMethodInfo != null) - { - methodInfos.Add(currentMethodInfo); - currentMethodInfo = currentMethodInfo.DeclaringType.BaseType?.GetMethod(currentMethodInfo.Name); - } - } - - return methodInfos; - } - - public static IEnumerable GetNestedTypesInTypeHierarchy(this Type type, BindingFlags bindingAttr) - { - IEnumerable nestedTypes = type.GetNestedTypes(bindingAttr); - - Type parent = type.BaseType; - - while (parent != null) - { - nestedTypes = parent.GetNestedTypes(bindingAttr).Concat(nestedTypes); - parent = parent.BaseType; - } - - return nestedTypes; - } - - public static IEnumerable GetMembersInTypeHierarchy(this Type type, BindingFlags bindingAttr) - { - Dictionary lookup = new Dictionary(); - - int index = 0; - lookup[type] = index++; - - Type parent = type.BaseType; - - while (parent != null) - { - lookup[parent] = index; - index++; - parent = parent.BaseType; - } - - return type.GetMembers(bindingAttr).OrderByDescending(prop => lookup[prop.DeclaringType]); - } - - public static 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 bool IsStatic(this MemberInfo memberInfo) => memberInfo switch - { - FieldInfo fieldInfo => fieldInfo.IsStatic, - PropertyInfo propertyInfo => propertyInfo.GetAccessors(true)[0].IsStatic, - _ => false - }; - } -} diff --git a/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs b/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs new file mode 100644 index 00000000..031f2e21 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs @@ -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 +{ + /// + /// A that is able to decompile arbitrary methods + /// + public sealed class MethodDecompiler + { + /// + /// Gets the singleton instance to use + /// + public static MethodDecompiler Instance { get; } = new MethodDecompiler(); + + /// + /// The dummy object used to handle concurrent decompilation requests + /// + private readonly object Lock = new object(); + + /// + /// The mapping of available instances targeting different assemblies + /// + private readonly Dictionary Decompilers = new Dictionary(); + + /// + /// The available instances for the loaded assemblies + /// + private readonly IReadOnlyList PEFiles; + + /// + /// The mapping of and values for the discovered instances + /// + private readonly Dictionary TypeDefinitions = new Dictionary(); + + /// + /// The incremental instance for the shader assembly + /// + private Compilation _Compilation; + + /// + /// Creates a new instance + /// + private MethodDecompiler() + { + // Load the assembly paths for all the available dlls + IReadOnlyList 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 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); + } + } + + /// + /// Decompiles a target method and returns its and info + /// + /// The input to inspect + /// The root node for the syntax tree of the input method + /// The semantic model for the input method + 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); + } + } + + /// + /// Loads the assembly path and method handle for the input instance + /// + /// The input to inspect + /// The path of the assembly containing the input method + /// The handle for the input method + private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle) + { + // Try to get the method handle from the assembly of the declaring type + Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type"); + string path = declaringType.Assembly.Location; + if (!string.IsNullOrEmpty(path)) + { + assemblyPath = path; + methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException(); + } + else + { + // Try to get the PEFile and type definition for the method declaring type + if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple)) + { + foreach (PEFile peFile in PEFiles) + { + // If not available, browse through the loaded PEFiles to find the type definition + TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName); + + if (!typeDefinitionHandle.IsNil) + { + tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle)); + TypeDefinitions.Add(methodInfo.DeclaringType, tuple); + + break; + } + } + + if (tuple.PEFile is null) throw new InvalidOperationException($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}"); + } + + PEFile peFileForMethod = tuple.PEFile; + TypeDefinition typeDefinition = tuple.TypeDefinition; + + // Retrieve the assembly path and method handle from the loaded PEFile and metadata + assemblyPath = peFileForMethod.FileName; + methodHandle = typeDefinition.GetMethods() + .Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name)) + .First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length); + } + } + + /// + /// Creates a new instance targeting a given assembly + /// + /// The path of the assembly to decompile + /// A instance that can be used on the targeted assembly + [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); + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Numerics/ThreadIds.cs b/src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs similarity index 91% rename from src/DirectX12GameEngine.Shaders/Numerics/ThreadIds.cs rename to src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs index 8acc868a..08cf64b3 100644 --- a/src/DirectX12GameEngine.Shaders/Numerics/ThreadIds.cs +++ b/src/DirectX12GameEngine.Shaders/Primitives/ThreadIds.cs @@ -1,4 +1,4 @@ -namespace DirectX12GameEngine.Shaders.Numerics +namespace DirectX12GameEngine.Shaders.Primitives { /// /// A that indicates the ids of a given GPU thread running a compute shader diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs new file mode 100644 index 00000000..ead23005 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/Abstract/FieldInfoBase.cs @@ -0,0 +1,29 @@ +namespace DirectX12GameEngine.Shaders.Renderer.Models.Abstract +{ + /// + /// A that contains info on a shader field + /// + public abstract class FieldInfoBase + { + /// + /// Gets or sets the type of the current field + /// + public string FieldType { get; set; } + + /// + /// Gets or sets the name to use for the current field + /// + public string FieldName { get; set; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + protected FieldInfoBase(string fieldType, string fieldName) + { + FieldType = fieldType; + FieldName = fieldName; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs new file mode 100644 index 00000000..aa453dab --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs @@ -0,0 +1,31 @@ +using DirectX12GameEngine.Shaders.Renderer.Models.Abstract; + +namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields +{ + /// + /// A that contains info on a constant buffer field + /// + public sealed class ConstantBufferFieldInfo : FieldInfoBase + { + /// + /// Gets whether or not the current instance represents a constant buffer (always ) + /// + public bool IsConstantBuffer { get; } = true; + + /// + /// Gets the index of the current constant buffer field + /// + public int ConstantBufferIndex { get; set; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + /// The index of the current constant buffer field + public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) + { + ConstantBufferIndex = bufferIndex; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs new file mode 100644 index 00000000..abfb06c9 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/ReadWriteBufferFieldInfo.cs @@ -0,0 +1,31 @@ +using DirectX12GameEngine.Shaders.Renderer.Models.Abstract; + +namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields +{ + /// + /// A that contains info on a read write buffer field + /// + public sealed class ReadWriteBufferFieldInfo : FieldInfoBase + { + /// + /// Gets whether or not the current instance represents a read write buffer (always ) + /// + public bool IsReadWriteBuffer { get; } = true; + + /// + /// Gets the index of the current read write buffer field + /// + public int ReadWriteBufferIndex { get; set; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + /// The index of the current read write buffer field + public ReadWriteBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) + { + ReadWriteBufferIndex = bufferIndex; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs new file mode 100644 index 00000000..ff41f95e --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/Models/Fields/StaticScalarFieldInfo.cs @@ -0,0 +1,31 @@ +using DirectX12GameEngine.Shaders.Renderer.Models.Abstract; + +namespace DirectX12GameEngine.Shaders.Renderer.Models.Fields +{ + /// + /// A that contains info on a static scalar field + /// + public sealed class StaticScalarFieldInfo : FieldInfoBase + { + /// + /// Gets whether or not the current instance represents a static scalar value (always ) + /// + public bool IsStaticScalarField { get; } = true; + + /// + /// Gets or sets the value to set for the current field + /// + public object FieldValue { get; set; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The type of the current field + /// The name of the current field + /// The static value to assign to the current field + public StaticScalarFieldInfo(string fieldType, string fieldName, object fieldValue) : base(fieldType, fieldName) + { + FieldValue = fieldValue; + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs b/src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs new file mode 100644 index 00000000..64ba1e8d --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/Models/ShaderInfo.cs @@ -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 +{ + /// + /// A that contains info to render a shader source to compile + /// + public sealed class ShaderInfo + { + /// + /// Gets the list of fields being present in the current shader + /// + public IReadOnlyList FieldsList { get; set; } + + /// + /// Gets or sets the number of threads in the X group + /// + public int ThreadsX { get; set; } + + /// + /// Gets or sets the number of threads in the Y group + /// + public int ThreadsY { get; set; } + + /// + /// Gets or sets the number of threads in the Z group + /// + public int ThreadsZ { get; set; } + + /// + /// Gets or sets the name for the threads id variable used in the shader + /// + public string ThreadsIdsVariableName { get; set; } + + /// + /// Gets or sets the shader body to compile + /// + public string ShaderBody { get; set; } + } +} diff --git a/src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs b/src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs new file mode 100644 index 00000000..5533346f --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/Renderer/ShaderRenderer.cs @@ -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 +{ + /// + /// A that uses the mustache templating system to render HLSL shaders + /// + public sealed class ShaderRenderer + { + /// + /// Gets the singleton instance to use + /// + public static ShaderRenderer Instance { get; } = new ShaderRenderer(); + + /// + /// Creates a new instance and loads the mustache template to use + /// + 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); + } + + /// + /// Gets the mustache template used by the shader renderer + /// + public string Template { get; } + + /// + /// Renders a new HLSL shader source with the given parameters + /// + /// The input instance with the shader information + /// The source code for the new HLSL shader + [Pure] + public string Render(ShaderInfo info) => Nustache.Core.Render.StringToString(Template, info); + } +} diff --git a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs index ffe9aba0..ea64c675 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderCompiler.cs @@ -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 + /// + /// A that uses the APIs to compile compute shaders + /// + public sealed class ShaderCompiler { - static ShaderCompiler() + /// + /// Gets the singleton instance to use + /// + public static ShaderCompiler Instance { get; } = new ShaderCompiler(); + + /// + /// The instance to use to create new HLSL shaders + /// + private readonly IDxcCompiler Compiler; + + /// + /// The instance to use to create the bytecode for HLSL sources + /// + private readonly IDxcLibrary Library; + + /// + /// Creates a new instance + /// + private ShaderCompiler() { HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn(); + Compiler = HlslDxcLib.CreateDxcCompiler(); + Library = HlslDxcLib.CreateDxcLibrary(); } - public static byte[] CompileShaderFile(string filePath, ShaderVersion? version = null, string? entryPoint = null) + /// + /// Compiles a new HLSL shader from the input source code + /// + /// The HLSL source code to compile + /// The bytecode for the compiled shader + [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) + /// + /// Reads the buffer content from an input instance + /// + /// The input instance to read data from + /// The read bytes buffer, as an array + [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(pMem, (int)size).CopyTo(result.AsSpan()); return result; } - public static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob) + /// + /// Reads a value from an input instance + /// + /// The source to use to load the data + /// The input instance to read data from + /// The resulting read from the input data buffer + [Pure] + private static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob) { blob = library.GetBlobAstUf16(blob); return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2)); diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs deleted file mode 100644 index 8b4a9dfe..00000000 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs +++ /dev/null @@ -1,719 +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 decompilers = new Dictionary(); - private static readonly IEnumerable peFiles; - private static readonly Dictionary typeDefinitions = new Dictionary(); - - private static Compilation compilation; - - private readonly List collectedTypes = new List(); - private readonly BindingFlags bindingAttr; - private readonly HlslBindingTracker bindingTracker = new HlslBindingTracker(); - private readonly object shader; - private readonly StringWriter stringWriter = new StringWriter(); - private readonly IndentedTextWriter writer; - - private ShaderGenerationResult? result; - - static ShaderGenerator() - { - IEnumerable assemblyPaths; - - if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly().Location)) - { - assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location); - } - else - { - assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p => - { - try - { - PEFile peFile = new PEFile(p); - return true; - } - catch - { - return false; - } - }); - } - - var metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p)); - peFiles = assemblyPaths.Select(p => new PEFile(p)); - - compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences); - - AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad; - } - - private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e) - { - if (!e.LoadedAssembly.IsDynamic) - { - PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location); - compilation = compilation.AddReferences(metadataReference); - } - } - - public ShaderGenerator(object shader, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) - { - this.shader = shader; - this.bindingAttr = bindingAttr; - - writer = new IndentedTextWriter(stringWriter); - } - - public bool IsGenerated => result != null; - - public void AddType(Type type) - { - CollectStructure(type, null); - } - - public RootParameter[] RootParameters { get; private set; } - - public IReadOnlyList ReadWriteBuffers { get; private set; } - - public ShaderGenerationResult GenerateShaderForLambda() - { - if (result != null) return result; - - if (!(shader is Action action)) throw new InvalidOperationException("Missing lambda shader"); - - Type shaderType = action.Method.DeclaringType; - object shaderInstance = action.Target; - - var fields = shaderType.GetFields().ToArray(); - - // Collect the fields - foreach (FieldInfo fieldInfo in fields) - { - CollectStructure(fieldInfo.FieldType, fieldInfo.GetValue(shaderInstance)); - } - - // Collect the method - CollectTopLevelMethod(action.Method); - - // Writing stage - foreach (ShaderTypeDefinition type in collectedTypes) - { - WriteStructure(type.Type, type.Instance); - } - - // Write the fields, assuming that all buffers are unordered access views, and the other fields are constant buffers - var parameters = new List(); - var rwbuffers = new List(); - foreach (FieldInfo fieldInfo in fields) - { - Type? memberType = fieldInfo.FieldType; - - if (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == typeof(RWBufferResource<>)) - { - var range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, bindingTracker.UnorderedAccessView); - parameters.Add(range); - var buffer = fieldInfo.GetValue(shaderInstance); - var resource = (GraphicsResource)memberType.GetProperty(nameof(RWBufferResource.Buffer)).GetValue(buffer); - rwbuffers.Add(resource); - WriteUnorderedAccessView(fieldInfo, memberType, bindingTracker.UnorderedAccessView++); - } - //else WriteConstantBuffer(fieldInfo, memberType, bindingTracker.ConstantBuffer++); - else WriteStaticVariable(fieldInfo, memberType, fieldInfo.GetValue(shaderInstance)); - } - RootParameters = parameters.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); - ReadWriteBuffers = rwbuffers; - - // Write the actual shader body - writer.WriteLine("[Shader(\"compute\")]"); - writer.WriteLine("[NumThreads(5, 5, 1)]"); - WriteTopLevelMethod(action.Method); - - stringWriter.GetStringBuilder().TrimEnd(); - writer.WriteLine(); - - result = new ShaderGenerationResult(stringWriter.ToString(), "Foo"); /* action.Method.Name */ - - return result; - } - - private void CollectStructure(Type type, object? obj) - { - type = type.GetElementOrDeclaredType(); - - if (HlslKnownTypes.ContainsKey(type) || collectedTypes.Any(d => d.Type == type)) return; - - ShaderTypeDefinition shaderTypeDefinition = new ShaderTypeDefinition(type, obj); - - if (type.IsEnum) - { - collectedTypes.Add(shaderTypeDefinition); - return; - } - - Type parentType = type.BaseType; - - while (parentType != null) - { - CollectStructure(parentType, obj); - parentType = parentType.BaseType; - } - - foreach (Type interfaceType in type.GetInterfaces()) - { - CollectStructure(interfaceType, obj); - } - - var memberInfos = new MemberInfo[0]; //type.GetMembersInOrder(bindingAttr); - - foreach (MemberInfo memberInfo in memberInfos) - { - Type? memberType = memberInfo.GetMemberType(obj); - - if (memberInfo is MethodInfo methodInfo) - { - if (type.IsInterface) - { - CollectMethod(methodInfo); - } - } - else if (memberType != null && memberType != type) - { - CollectStructure(memberType, memberInfo.GetMemberValue(obj)); - } - } - - 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); - - foreach (MemberInfo memberInfo in new MemberInfo[0]) - { - Type? memberType = memberInfo.GetMemberType(obj); - - if (memberInfo is MethodInfo methodInfo) - { - if (type.IsInterface) - { - WriteMethod(methodInfo); - } - } - else if (memberType != 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 new MemberInfo[0].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.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 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.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 static string GetArrayString(int arrayCount) => arrayCount > 0 ? $"[{arrayCount}]" : ""; - - private void CollectTopLevelMethod(MethodInfo methodInfo) - { - IList methodInfos = methodInfo.GetBaseMethods(); - - for (int depth = methodInfos.Count - 1; depth >= 0; depth--) - { - MethodInfo currentMethodInfo = methodInfos[depth]; - CollectMethod(currentMethodInfo); - } - } - - private void CollectMethod(MethodInfo methodInfo) - { - GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); - - ShaderSyntaxCollector syntaxCollector = new ShaderSyntaxCollector(this, semanticModel); - syntaxCollector.Visit(root); - } - - private void WriteTopLevelMethod(MethodInfo methodInfo) - { - IList methodInfos = methodInfo.GetBaseMethods(); - - for (int depth = methodInfos.Count - 1; depth >= 0; depth--) - { - MethodInfo currentMethodInfo = methodInfos[depth]; - WriteMethod(currentMethodInfo, depth); - } - } - - private void WriteMethod(MethodInfo methodInfo, int depth = 0) - { - GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); - - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, true, depth); - root = syntaxRewriter.Visit(root); - - string shaderSource = root.ToFullString(); - shaderSource = shaderSource.Replace("internal void
b__0", "void Foo"); - shaderSource = shaderSource.Replace("uint3 id", "uint3 id : SV_DispatchThreadId"); - - // TODO: See why the System namespace in System.Math is not present in UWP projects. - shaderSource = shaderSource.Replace("Math.Max", "max"); - shaderSource = shaderSource.Replace("Math.Pow", "pow"); - shaderSource = shaderSource.Replace("Math.Sin", "sin"); - - shaderSource = shaderSource.Replace("vector", "vec"); - shaderSource = Regex.Replace(shaderSource, @"\d+[fF]", m => m.Value.Replace("f", "")); - - // Indent every line - string indent = ""; - - for (int i = 0; i < writer.Indent; i++) - { - indent += IndentedTextWriter.DefaultTabString; - } - - shaderSource = shaderSource.Replace(Environment.NewLine, Environment.NewLine + indent).TrimEnd(' '); - - writer.WriteLine(shaderSource); - } - - private static void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode root, out SemanticModel semanticModel) - { - lock (compilationLock) - { - GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle); - - if (!decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler)) - { - decompiler = CreateDecompiler(assemblyPath); - decompilers.Add(assemblyPath, decompiler); - } - - string sourceCode = decompiler.DecompileAsString(methodHandle); - - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); - root = syntaxTree.GetRoot(); - - compilation = compilation.AddSyntaxTrees(syntaxTree); - semanticModel = compilation.GetSemanticModel(syntaxTree); - } - } - - private static void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle) - { - assemblyPath = methodInfo.DeclaringType.Assembly.Location; - - if (!string.IsNullOrEmpty(assemblyPath)) - { - methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException(); - } - else - { - if (!typeDefinitions.TryGetValue(methodInfo.DeclaringType, out var tuple)) - { - foreach (PEFile peFile in peFiles) - { - TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName); - - if (!typeDefinitionHandle.IsNil) - { - tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle)); - typeDefinitions.Add(methodInfo.DeclaringType, tuple); - - break; - } - } - - if (tuple.PEFile is null) throw new InvalidOperationException(); - } - - PEFile peFileForMethod = tuple.PEFile; - TypeDefinition typeDefinition = tuple.TypeDefinition; - - assemblyPath = peFileForMethod.FileName; - - methodHandle = typeDefinition.GetMethods() - .Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name)) - .First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length); - } - } - - private static CSharpDecompiler CreateDecompiler(string assemblyPath) - { - UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); - - DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) - { - ObjectOrCollectionInitializers = false, - UsingDeclarations = false - }; - - decompilerSettings.CSharpFormattingOptions.IndentationString = IndentedTextWriter.DefaultTabString; - - return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); - } - - internal static class HlslKnownTypes - { - private static readonly Dictionary knownTypes = new Dictionary() - { - { typeof(void).FullName, "void" }, - { typeof(bool).FullName, "bool" }, - { typeof(uint).FullName, "uint" }, - { typeof(int).FullName, "int" }, - { typeof(double).FullName, "double" }, - { typeof(float).FullName, "float" }, - { typeof(Vector2).FullName, "float2" }, - { typeof(Vector3).FullName, "float3" }, - { typeof(Vector4).FullName, "float4" }, - { typeof(Matrix4x4).FullName, "float4x4" }, - { typeof(ThreadIds).FullName, "uint3" }, - { typeof(RWBufferResource<>).FullName, "RWBuffer" }, - }; - - public static bool ContainsKey(Type type) - { - type = type.GetElementOrDeclaredType(); - string typeFullName = type.Namespace + Type.Delimiter + type.Name; - - return knownTypes.ContainsKey(typeFullName); - } - - public static bool ContainsKey(string name) - { - int indexOfOpenBracket = name.IndexOf('<'); - name = indexOfOpenBracket >= 0 ? name.Remove(indexOfOpenBracket) + "`1" : name; - - return knownTypes.ContainsKey(name); - } - - public static string GetMappedName(Type type) - { - type = type.GetElementOrDeclaredType(); - string typeFullName = type.Namespace + Type.Delimiter + type.Name; - - string mappedName = knownTypes.TryGetValue(typeFullName, out string mapped) ? mapped : type.Name; - - return type.IsGenericType ? mappedName + $"<{GetMappedName(type.GetGenericArguments()[0])}>" : mappedName; - } - - public static string GetMappedName(string name) - { - int indexOfOpenBracket = name.IndexOf('<'); - - string genericArguments = indexOfOpenBracket >= 0 ? name.Substring(indexOfOpenBracket) : ""; - name = indexOfOpenBracket >= 0 ? name.Remove(indexOfOpenBracket) + "`1" : name; - - string mappedName = knownTypes.TryGetValue(name, out string mapped) ? mapped : Regex.Match(name, @"[^\.]+$").Value; - - return mappedName + genericArguments; - } - } - - internal static class HlslKnownMethods - { - private static readonly Dictionary knownMethods = new Dictionary() - { - { "System.Math.Cos", "cos" }, - { "System.MathF.Cos", "cos" }, - { "System.Math.Max", "max" }, - { "System.Math.Pow", "pow" }, - { "System.MathF.Pow", "pow" }, - { "System.Math.Sin", "sin" }, - { "System.MathF.Sin", "sin" }, - { "System.Math.PI", "3.1415926535897931" }, - { "System.MathF.PI", "3.14159274f" }, - - { "DirectX12GameEngine.Shaders.Numerics.Vector2.Length", "length" }, - - { "DirectX12GameEngine.Shaders.Numerics.UInt2.X", ".x" }, - { "DirectX12GameEngine.Shaders.Numerics.UInt2.Y", ".y" }, - - { "DirectX12GameEngine.Shaders.Numerics.ThreadIds.X", ".x" }, - { "DirectX12GameEngine.Shaders.Numerics.ThreadIds.Y", ".y" }, - { "DirectX12GameEngine.Shaders.Numerics.ThreadIds.Z", ".z" }, - { "DirectX12GameEngine.Shaders.Numerics.ThreadIds.XY", ".xy" }, - - { "System.Numerics.Vector3.X", ".x" }, - { "System.Numerics.Vector3.Y", ".y" }, - { "System.Numerics.Vector3.Z", ".z" }, - { "System.Numerics.Vector3.Cross", "cross" }, - { "System.Numerics.Vector3.Dot", "dot" }, - { "System.Numerics.Vector3.Lerp", "lerp" }, - { "System.Numerics.Vector3.Transform", "mul" }, - { "System.Numerics.Vector3.TransformNormal", "mul" }, - { "System.Numerics.Vector3.Normalize", "normalize" }, - { "System.Numerics.Vector3.Zero", "(float3)0" }, - { "System.Numerics.Vector3.One", "float3(1.0f, 1.0f, 1.0f)" }, - { "System.Numerics.Vector3.UnitX", "float3(1.0f, 0.0f, 0.0f)" }, - { "System.Numerics.Vector3.UnitY", "float3(0.0f, 1.0f, 0.0f)" }, - { "System.Numerics.Vector3.UnitZ", "float3(0.0f, 0.0f, 1.0f)" }, - - { "System.Numerics.Vector4.X", ".x" }, - { "System.Numerics.Vector4.Y", ".y" }, - { "System.Numerics.Vector4.Z", ".z" }, - { "System.Numerics.Vector4.W", ".w" }, - { "System.Numerics.Vector4.Lerp", "lerp" }, - { "System.Numerics.Vector4.Transform", "mul" }, - { "System.Numerics.Vector4.Normalize", "normalize" }, - { "System.Numerics.Vector4.Zero", "(float4)0" }, - { "System.Numerics.Vector4.One", "float4(1.0f, 1.0f, 1.0f, 1.0f)" }, - - { "System.Numerics.Matrix4x4.Multiply", "mul" }, - { "System.Numerics.Matrix4x4.Transpose", "transpose" }, - { "System.Numerics.Matrix4x4.Translation", "[3].xyz" }, - { "System.Numerics.Matrix4x4.M11", "[0][0]" }, - { "System.Numerics.Matrix4x4.M12", "[0][1]" }, - { "System.Numerics.Matrix4x4.M13", "[0][2]" }, - { "System.Numerics.Matrix4x4.M14", "[0][3]" }, - { "System.Numerics.Matrix4x4.M21", "[1][0]" }, - { "System.Numerics.Matrix4x4.M22", "[1][1]" }, - { "System.Numerics.Matrix4x4.M23", "[1][2]" }, - { "System.Numerics.Matrix4x4.M24", "[1][3]" }, - { "System.Numerics.Matrix4x4.M31", "[2][0]" }, - { "System.Numerics.Matrix4x4.M32", "[2][1]" }, - { "System.Numerics.Matrix4x4.M33", "[2][2]" }, - { "System.Numerics.Matrix4x4.M34", "[2][3]" }, - { "System.Numerics.Matrix4x4.M41", "[3][0]" }, - { "System.Numerics.Matrix4x4.M42", "[3][1]" }, - { "System.Numerics.Matrix4x4.M43", "[3][2]" }, - { "System.Numerics.Matrix4x4.M44", "[3][3]" } - }; - - public static bool Contains(ISymbol containingMemberSymbol, ISymbol memberSymbol) - { - string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString(); - - if (knownMethods.ContainsKey(fullTypeName + Type.Delimiter + memberSymbol.Name)) - { - return true; - } - - return false; - } - - public static string? GetMappedName(ISymbol containingMemberSymbol, ISymbol memberSymbol) - { - string fullTypeName = containingMemberSymbol.IsStatic ? containingMemberSymbol.ToString() : memberSymbol.ContainingType.ToString(); - - if (knownMethods.TryGetValue(fullTypeName + Type.Delimiter + memberSymbol.Name, out string mapped)) - { - if (!memberSymbol.IsStatic) - { - return containingMemberSymbol.Name + mapped; - } - - return mapped; - } - - if (memberSymbol.IsStatic) - { - return containingMemberSymbol.Name + "::" + memberSymbol.Name; - } - - return null; - } - } - - private class HlslBindingTracker - { - public int ConstantBuffer { get; set; } - - public int Sampler { get; set; } - - public int Texture { get; set; } - - public int UnorderedAccessView { get; set; } - - public int StaticResource { get; set; } - } - - private class ShaderTypeDefinition - { - public ShaderTypeDefinition(Type type, object? instance) - { - Type = type; - Instance = instance; - } - - public object? Instance { get; } - - public Type Type { get; } - - public List ResourceDefinitions { get; } = new List(); - } - - private class ResourceDefinition - { - public ResourceDefinition(Type memberType) - { - MemberType = memberType; - } - - public Type MemberType { 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(); - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - return Array.Empty(); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - return false; - } - } - } -} diff --git a/src/DirectX12GameEngine.Shaders/ShaderLoader.cs b/src/DirectX12GameEngine.Shaders/ShaderLoader.cs new file mode 100644 index 00000000..4f49fe48 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/ShaderLoader.cs @@ -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 +{ + /// + /// A responsible for loading and processing instances + /// + public sealed class ShaderLoader + { + /// + /// The that represents the shader to load + /// + private readonly Action Action; + + /// + /// The closure for the field + /// + private readonly Type ShaderType; + + /// + /// The closure instance for the field + /// + private readonly object ShaderInstance; + + /// + /// The sequence of fields in the targeted closure + /// + private readonly IReadOnlyList ShaderFields; + + /// + /// Creates a new with the specified parameters + /// + /// The to use to build the shader + private ShaderLoader(Action action) + { + Action = action; + ShaderType = action.Method.DeclaringType; + ShaderInstance = action.Target; + ShaderFields = ShaderType.GetFields().ToArray(); + } + + /// + /// Gets the array for the current shader + /// + public RootParameter[] RootParameters { get; private set; } + + /// + /// Gets the ordered collection of read write buffers used as fields in the current shader + /// + public IReadOnlyList ReadWriteBuffers { get; private set; } + + private readonly List _FieldsInfo = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList FieldsInfo => _FieldsInfo; + + /// + /// Gets the name of the variable used as input for the shader method + /// + public string ThreadsIdsVariableName { get; private set; } + + /// + /// Gets the generated source code for the method in the current shader + /// + public string MethodBody { get; private set; } + + /// + /// Loads and processes an input + /// + /// The to use to build the shader + /// A new instance representing the input shader + [Pure] + public static ShaderLoader Load(Action action) + { + ShaderLoader @this = new ShaderLoader(action); + + @this.LoadFieldsInfo(); + @this.LoadMethodSource(); + + return @this; + } + + /// + /// Loads the fields info for the current shader being loaded + /// + private void LoadFieldsInfo() + { + if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded"); + + List descriptorRanges = new List(); + List readWriteBuffers = new List(); + 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.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; + } + + /// + /// Loads the entry method for the current shader being loaded + /// + 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().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", "")); + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/ShaderSyntaxCollector.cs b/src/DirectX12GameEngine.Shaders/ShaderSyntaxCollector.cs deleted file mode 100644 index 3fd0adc3..00000000 --- a/src/DirectX12GameEngine.Shaders/ShaderSyntaxCollector.cs +++ /dev/null @@ -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)); - } - } - } -} diff --git a/src/DirectX12GameEngine.Shaders/StringBuilderExtensions.cs b/src/DirectX12GameEngine.Shaders/StringBuilderExtensions.cs deleted file mode 100644 index a481e4d3..00000000 --- a/src/DirectX12GameEngine.Shaders/StringBuilderExtensions.cs +++ /dev/null @@ -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; - } - } -} diff --git a/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs b/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs index beebe2e6..b2e0f0fb 100644 --- a/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs +++ b/src/DirectX12GameEngine.Shaders/SyntaxNodeExtensions.cs @@ -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(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; } } }