using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Shaders.Translation
{
///
/// A that handles the cache system for the generated shaders
///
internal static class ShaderHashCodeProvider
{
///
/// A type containing static info for a given shader type
///
/// The type of compute shader currently in use
private static class TypeInfo
where T : struct, IComputeShader
{
///
/// The id of the compute shader type in use
///
public static readonly int Id;
///
/// The optional instance, if needed
///
public static readonly Hasher? Hasher;
///
/// Initializes the static members of the type
///
static TypeInfo()
{
Id = HashCode.Combine(typeof(T));
// Get the valid delegates for delegate checking
FieldInfo[] delegateFieldInfos = (
from fieldInfo in typeof(T).GetFields()
where fieldInfo.FieldType.IsDelegate()
select fieldInfo).ToArray();
// If at least one delegate is present, build the hasher method
if (delegateFieldInfos.Length > 0)
{
Hasher = BuildDynamicHasher(delegateFieldInfos);
}
}
}
///
/// Gets a unique hashcode for the input compute shader instance
///
/// The type of compute shader currently in use
/// The input instance representing the shader to run
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetHashCode(in T shader)
where T : struct, IComputeShader
{
int hash = TypeInfo.Id;
Hasher? hasher = TypeInfo.Hasher;
if (hasher != null) hash = hasher(hash, shader);
return hash;
}
///
/// A that represents an aggregate hash function for a given instance
///
/// The type of compute shader currently in use
/// The initial hash value
/// The compute shader instance to use to compute the final hash value
/// The final hash value for the input closure
private delegate int Hasher(int hash, in T shader)
where T : struct, IComputeShader;
///
/// Builds a new instance for the target and sequence of values
///
/// The type of compute shader currently in use
/// The list of captured fields to inspect
[Pure]
private static Hasher BuildDynamicHasher(IReadOnlyCollection fieldInfos)
where T : struct, IComputeShader
{
return DynamicMethod>.New(il =>
{
MethodInfo
getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod,
getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode));
foreach (FieldInfo fieldInfo in fieldInfos)
{
// (hashcode << 5) + hashcode
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_5);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Add);
// hashcode += shader.Function[#].Method.GetHashCode();
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.EmitCall(OpCodes.Callvirt, getMethodInfo, null);
il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Starg_S, (byte)0);
}
// Return the computed hash
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
});
}
}
}