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
{
///
/// 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
readWriteBuffers.Add((GraphicsResource)fieldValue);
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", ""));
}
}
}