using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Helpers;
using ComputeSharp.Graphics.Interop;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation
{
///
internal sealed partial class ShaderLoader
{
///
/// A that loads all the captured members from a shader instance.
///
/// The to use to run the shader.
/// The shader instance to load the data from.
/// A reference to the buffer with all the captured instances.
/// A reference to the buffer to use to store all the captured value types.
private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
///
/// The number of captured graphics resources (buffers).
///
private int totalResourceCount;
///
/// The size in bytes of the buffer with the captured variables.
///
/// Initially set to 3 values for X, Y and Z threads counts.
private int totalVariablesByteSize = 3 * sizeof(int);
///
/// The cached instance to load dispatch data before execution.
///
private DispatchDataLoader? dispatchDataLoader;
///
/// The of instances mapping the captured variables in the current shader.
///
private readonly List capturedFields = new();
///
/// Gets a new instance with all the captured data for the current shader instance.
///
/// The to use to run the shader.
/// The input instance representing the compute shader to run.
/// The number of iterations to run on the X axis.
/// The number of iterations to run on the Y axis.
/// The number of iterations to run on the Z axis.
[Pure]
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
{
// Resources and variables buffers
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As(ref r1) = x;
Unsafe.Add(ref Unsafe.As(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
///
/// Builds a new instance that loads the dispatch data for the current shader type.
///
private void BuildDispatchDataLoader()
{
// The delegate signature is .
// Due to how DynamicMethod is implemented (see notes in the XML docs for DynamicMethod.New),
// all offsets for the input arguments are shifted by one. Because of this, we have the following:
//
// ldarg.1 = GraphicsDevice
// ldarg.2 = in T shader
// ldarg.3 = ref D3D12_GPU_DESCRIPTOR_HANDLE r0
// ldarg.4 = ref byte r1
this.dispatchDataLoader = DynamicMethod.New(il =>
{
foreach (FieldInfo fieldInfo in this.capturedFields)
{
if (HlslKnownTypes.IsKnownBufferType(fieldInfo.FieldType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_3);
if (totalResourceCount > 0)
{
il.EmitAddOffset(this.totalResourceCount);
}
il.Emit(OpCodes.Ldarg_2);
il.EmitReadMember(fieldInfo);
// Call NativeObject.ThrowIfDisposed()
il.Emit(OpCodes.Dup);
il.EmitCall(OpCodes.Callvirt, typeof(NativeObject).GetMethod(
nameof(NativeObject.ThrowIfDisposed),
BindingFlags.Instance | BindingFlags.NonPublic)!, null);
// Call ThrowIfDeviceMismatch(GraphicsDevice)
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod(
nameof(Buffer.ThrowIfDeviceMismatch),
BindingFlags.Instance | BindingFlags.NonPublic)!, null);
// Access D3D12GpuDescriptorHandle
il.EmitReadMember(fieldInfo.FieldType.GetField(
nameof(Buffer.D3D12GpuDescriptorHandle),
BindingFlags.Instance | BindingFlags.NonPublic)!);
il.EmitStoreToAddress(typeof(D3D12_GPU_DESCRIPTOR_HANDLE));
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType) ||
HlslKnownTypes.IsKnownVectorType(fieldInfo.FieldType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int elementSizeInBytes = Marshal.SizeOf(fieldInfo.FieldType);
this.totalVariablesByteSize = AlignmentHelper.AlignToBoundary(
this.totalVariablesByteSize,
elementSizeInBytes,
FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT);
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_S, (byte)4);
il.EmitAddOffset(totalVariablesByteSize);
il.Emit(OpCodes.Ldarg_2);
il.EmitReadMember(fieldInfo);
il.EmitStoreToAddress(fieldInfo.FieldType);
this.totalVariablesByteSize += elementSizeInBytes;
}
else ThrowHelper.ThrowArgumentException("Invalid captured member type");
}
il.Emit(OpCodes.Ret);
});
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to the standard alignment for constant buffers. This is
// necessary to enable loading all the dispatch data after reinterpreting it to a sequence
// of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds.
this.totalVariablesByteSize = AlignmentHelper.Pad(
this.totalVariablesByteSize,
FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT);
}
}
}