using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
#pragma warning disable CS0618, CS8618
namespace ComputeSharp.Shaders.Translation
{
///
/// A responsible for loading and processing shaders of a given type.
///
/// The type of compute shader currently in use.
internal sealed partial class ShaderLoader : IShaderLoader
where T : struct, IComputeShader
{
///
/// The associated instance for the current shader type.
///
private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType();
///
/// The number of constant buffers to define in the shader.
///
private uint constantBuffersCount;
///
/// The number of readonly buffers to define in the shader.
///
private uint readOnlyBuffersCount;
///
/// The number of read write buffers to define in the shader.
///
private uint readWriteBuffersCount;
///
/// The of items that are required to load the captured values.
///
private readonly List d3D12DescriptorRanges1 = new();
///
/// The with the items for the shader fields.
///
private readonly List hlslBuffersInfo = new();
///
/// The with the items for the shader fields.
///
private readonly List fieldsInfo = new();
///
/// Creates a new instance.
///
private ShaderLoader()
{
}
///
/// Gets a with the loaded items for the shader.
///
public ReadOnlySpan D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
///
public string EntryPoint { get; private set; }
///
public IReadOnlyList HslsBuffersInfo => this.hlslBuffersInfo;
///
public IReadOnlyList FieldsInfo => this.fieldsInfo;
///
public IReadOnlyCollection MethodsInfo { get; private set; }
///
public IReadOnlyCollection DeclaredTypes { get; private set; }
///
/// Loads and processes an input shadeer
///
/// The instance to use to build the shader
/// A new instance representing the input shader
[Pure]
public static ShaderLoader Load(in T shader)
{
ShaderLoader @this = new();
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@this.LoadMethodMetadata();
@this.BuildDispatchDataLoader();
return @this;
}
///
/// Loads the fields info for the current shader being loaded
///
/// The boxed instance to use to build the shader
private void LoadFieldsInfo(object shader)
{
IReadOnlyList shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
if (shaderFields.Count == 0)
{
ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field");
}
// Descriptor for the buffer for captured scalar/vector variables
D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo);
}
}
///
/// Loads a specified and adds it to the shader model
///
/// The boxed instance to use to build the shader
/// The target to load
private void LoadFieldInfo(object shader, FieldInfo fieldInfo)
{
Type fieldType = fieldInfo.FieldType;
(string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name];
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedFields.Add(fieldInfo);
this.hlslBuffersInfo.Add(new HlslBufferInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedFields.Add(fieldInfo);
this.hlslBuffersInfo.Add(new HlslBufferInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedFields.Add(fieldInfo);
this.hlslBuffersInfo.Add(new HlslBufferInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
this.capturedFields.Add(fieldInfo);
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
}
else if (fieldType.IsDelegate() &&
fieldInfo.GetValue(shader) is Delegate func &&
(func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
throw new NotImplementedException();
}
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
}
///
/// Loads the metadata info for the current shader.
///
private void LoadMethodMetadata()
{
DeclaredTypes = Attribute.Types;
EntryPoint = Attribute.ExecuteMethod;
MethodsInfo = Attribute.Methods;
}
}
}