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 ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpDX.Direct3D12; #pragma warning disable CS8618 // Non-nullable field is uninitialized namespace ComputeSharp.Shaders.Translation { /// /// A responsible for loading and processing instances /// internal sealed class ShaderLoader { /// /// The that represents the shader to load /// private readonly Action Action; /// /// Creates a new with the specified parameters /// /// The to use to build the shader private ShaderLoader(Action action) { Action = action; ShaderType = action.Method.DeclaringType; } /// /// Gets the closure for the field /// public Type ShaderType { get; } /// /// Gets the array for the current shader /// public RootParameter[] RootParameters { get; private set; } /// /// The of instances mapping the captured buffers in the current shader /// private readonly List _BufferFields = new List(); /// /// Gets the ordered collection of buffers used as fields in the current shader /// /// The to use to build the shader public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) => _BufferFields.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target))); /// /// The of instances mapping the captured scalar/vector variables in the current shader /// private readonly List _VariableFields = new List(); /// /// Gets the collection of values of the captured fields for the current shader /// /// The to use to build the shader public IEnumerable GetVariables(Action action) => _VariableFields.Select(field => field.GetValue(action.Target)); private readonly List _BuffersList = new List(); /// /// Gets the collection of items for the shader fields /// public IReadOnlyList BuffersList => _BuffersList; private readonly List _FieldsList = new List(); /// /// Gets the collection of items for the shader fields /// public IReadOnlyList FieldsList => _FieldsList; /// /// 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() { IReadOnlyList shaderFields = ShaderType.GetFields().ToArray(); if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); int constantBuffersCount = 0; int readOnlyBuffersCount = 0; int readWriteBuffersCount = 0; // Descriptor for the buffer for captured scalar/vector variables descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount++)); // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) { descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount)); // Track the buffer field _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++)); } else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) { // Root parameter for a readonly buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount)); // Track the buffer field _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++)); } else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) { // Root parameter for a read write buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount)); // Track the buffer field _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++)); } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { // Register the captured field _VariableFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(typeName, fieldName)); } else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); } RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); } /// /// Loads the entry method for the current shader being loaded /// private void LoadMethodSource() { // Decompile the shader method MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); // Get the thread ids identifier name and shader method body ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; MethodBody = root.Body.ToFullString(); // Additional preprocessing MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", "")); MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); MethodBody = Regex.Replace(MethodBody, @"(?