Removed unnecessary code

このコミットが含まれているのは:
Sergio Pedri committed 2020-04-13 03:01:41 +02:00
1 親 6d27a2c1c1
コミット 32ca76c535
6ファイル変更
+1 -822

検索条件に一致するファイルはありません

-130
ファイルの表示
@@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Models;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
namespace ComputeSharp.Shaders
{
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader
/// </summary>
internal static class ShaderRunner
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void Run(GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
if (y == 1 && z == 1) threadsX = device.WavefrontSize;
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
Run(device, x, y, z, threadsX, threadsY, threadsZ, action);
}
/// <summary>
/// The mapping used to cache and reuse compiled shaders
/// </summary>
private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void Run(
GraphicsDevice device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
Action<ThreadIds> action)
{
// Try to get the cache shader
CachedShader shaderData;
lock (ShadersCache)
{
var key = (ShaderHashCodeProvider.GetHashCode(action), threadsX, threadsY, threadsZ);
if (!ShadersCache.TryGetValue(key, out shaderData))
{
// Load the input shader
ShaderLoader shaderLoader = ShaderLoader.Load(action);
// Render the loaded shader
ShaderInfo shaderInfo = new ShaderInfo
{
BuffersList = shaderLoader.BuffersList,
FieldsList = shaderLoader.FieldsList,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
FunctionsList = shaderLoader.FunctionsList,
LocalFunctionsList = shaderLoader.LocalFunctionsList
};
string shaderSource = ShaderRenderer.Instance.Render(shaderInfo);
// Compile the loaded shader to HLSL bytecode
ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource);
// Cache for later use
shaderData = new CachedShader(shaderLoader, shaderBytecode);
ShadersCache.Add(key, shaderData);
}
}
// Create the root signature for the pipeline and get the pipeline state
VersionedRootSignatureDescription rootSignatureDescription = new VersionedRootSignatureDescription(new RootSignatureDescription1(RootSignatureFlags.None, shaderData.Loader.RootParameters));
ID3D12RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription);
PipelineState pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode);
// Create the commands list and set the pipeline state
using CommandList commandList = new CommandList(device, CommandListType.Compute);
commandList.SetPipelineState(pipelineState);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z);
// Load the captured buffers
Span<GraphicsResource> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
}
// Initialize the loop targets
Span<Int4> variables = dispatchData.Variables;
using GraphicsResource variablesBuffer = device.AllocateConstantBuffer(variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
// Calculate the dispatch values
int
groupsX = x / threadsX + (x % threadsX == 0 ? 0 : 1),
groupsY = y / threadsY + (y % threadsY == 0 ? 0 : 1),
groupsZ = z / threadsZ + (z % threadsZ == 0 ? 0 : 1);
// Dispatch and wait for completion
commandList.Dispatch(groupsX, groupsY, groupsZ);
commandList.Flush();
}
}
}
-31
ファイルの表示
@@ -1,31 +0,0 @@
using Vortice.Direct3D12;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains info on a cached shader
/// </summary>
internal readonly struct CachedShader
{
/// <summary>
/// The <see cref="ShaderLoader"/> instance with the shader metadata
/// </summary>
public readonly ShaderLoader Loader;
/// <summary>
/// The compiled shader bytecode
/// </summary>
public readonly ShaderBytecode Bytecode;
/// <summary>
/// Creates a new <see cref="CachedShader"/> instance with the specified parameters
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader"/> instance with the shader metadata</param>
/// <param name="bytecode">The compiled shader bytecode</param>
public CachedShader(ShaderLoader loader, ShaderBytecode bytecode)
{
Loader = loader;
Bytecode = bytecode;
}
}
}
-116
ファイルの表示
@@ -5,7 +5,6 @@ using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Mappings;
namespace ComputeSharp.Shaders.Translation
{
@@ -14,11 +13,6 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
internal static class ShaderHashCodeProvider
{
/// <summary>
/// The mapping of hashcodes to aggregate hashing functions
/// </summary>
private static readonly Dictionary<int, Hasher?> HasherMapping = new Dictionary<int, Hasher?>();
/// <summary>
/// A type containing static info for a given shader type <typeparamref name="T"/>
/// </summary>
@@ -123,115 +117,5 @@ namespace ComputeSharp.Shaders.Translation
il.Emit(OpCodes.Ret);
});
}
/// <summary>
/// Gets a unique hashcode for the input shader closure
/// </summary>
/// <param name="action">The input <see cref="Action{T}"/> representing the shader to run</param>
[Pure]
public static int GetHashCode(Action<ThreadIds> action)
{
// Get the delegate hashcode
MethodInfo methodInfo = action.Method;
int hash = methodInfo.GetHashCode();
if (!HasherMapping.TryGetValue(hash, out Hasher? hasher))
{
// Get the candidate fields for delegate checking
FieldInfo[] delegateFieldInfos = (
from fieldInfo in methodInfo.DeclaringType.GetFields()
where fieldInfo.FieldType.IsDelegate() &&
fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type))
select fieldInfo).ToArray();
// If at least one captured delegate is present, build the hasher method
hasher = delegateFieldInfos.Length == 0 ? null : BuildDynamicHasher(action.Method.DeclaringType, delegateFieldInfos);
HasherMapping.Add(hash, hasher);
}
// Aggregate the hash of the captured delegates, if needed
if (hasher != null) hash = hasher(hash, action.Target);
return hash;
}
/// <summary>
/// A <see langword="delegate"/> that represents an aggregate hash function for a given instance
/// </summary>
/// <param name="hash">The initial hash value</param>
/// <param name="instance">The closure instance to use to compute the final hash value</param>
/// <returns>The final hash value for the input closure</returns>
private delegate int Hasher(int hash, object instance);
/// <summary>
/// Builds a new <see cref="Hasher"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values
/// </summary>
/// <param name="declaringType">The declaring <see cref="Type"/> to analyze</param>
/// <param name="fieldInfos">The list of captured fields to inspect</param>
[Pure]
private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection<FieldInfo> fieldInfos)
{
return DynamicMethod<Hasher>.New(il =>
{
// Declare the local variable to store the target instance
il.DeclareLocal(declaringType);
// Load the argument (the object instance)
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, declaringType);
il.Emit(OpCodes.Stloc_0);
// Unroll the member access
MethodInfo
validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static),
getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod,
getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode));
foreach (FieldInfo fieldInfo in fieldInfos)
{
Label label = il.DefineLabel();
// if (fieldInfo.GetValue(obj) != null) {
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.Emit(OpCodes.Brfalse_S, label);
// if (ValidateDelegate(field)) {
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.EmitCall(OpCodes.Call, validateDelegateInfo, null);
il.Emit(OpCodes.Brfalse_S, label);
// hash = hash * 17 + field.Method.GetHashCode();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_S, (byte)17);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Ldloc_0);
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);
il.MarkLabel(label);
}
// Return the computed hash
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
});
}
/// <summary>
/// A method that checks whether an input <see cref="Delegate"/> is supported in HLSL
/// </summary>
/// <param name="candidate">The input <see cref="Delegate"/> instance to check</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ValidateDelegate(Delegate candidate)
{
MethodInfo methodInfo = candidate.Method;
return (methodInfo.IsStatic || methodInfo.DeclaringType.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(methodInfo.ReturnType) || HlslKnownTypes.IsKnownVectorType(methodInfo.ReturnType));
}
}
}
-170
ファイルの表示
@@ -1,170 +0,0 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader"/>
internal sealed partial class ShaderLoader
{
/// <summary>
/// The number of captured graphics resources (buffers)
/// </summary>
private int _ResourcesCount;
/// <summary>
/// The size in bytes of the buffer with the captured variables
/// </summary>
private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count
// The cached loader method
private DispatchDataLoader? _DispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader
/// </summary>
private readonly List<ReadableMember> _CapturedMembers = new List<ReadableMember>();
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader closure
/// </summary>
/// <param name="obj">The shader closure instance to load the data from</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="GraphicsResource"/> instances</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types</param>
private delegate void DispatchDataLoader(object obj, ref GraphicsResource r0, ref byte r1);
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance
/// </summary>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
[Pure]
public DispatchData GetDispatchData(Action<ThreadIds> action, int x, int y, int z)
{
// Resources and variables buffers
GraphicsResource[] resources = ArrayPool<GraphicsResource>.Shared.Rent(_ResourcesCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(_VariablesByteSize);
ref GraphicsResource r0 = ref resources[0];
ref byte r1 = ref variables[0];
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
_DispatchDataLoader!(action.Target, ref r0, ref r1);
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type
/// </summary>
private void BuildDispatchDataLoader()
{
// Mapping of parent members to index of the relative local variable
var map =
_CapturedMembers
.Where(m => !m.IsStatic && m.Parents != null)
.SelectMany(m => m.Parents)
.Distinct()
.Select((m, i) => (Member: m, Index: i))
.ToDictionary(p => (object)p.Member, p => p.Index + 1);
object root = new object(); // Placeholder
map.Add(root, 0);
// Set of indices of the loaded parent members
HashSet<int> loaded = new HashSet<int>(new[] { 0 });
// Build the dynamic IL method
_DispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
// Loads a given member on the top of the execution stack
void LoadMember(ReadableMember member)
{
if (!member.IsStatic)
{
// Load the parent instance on the execution stack if the member isn't static
int index = map[member.Parents?.Last() ?? root];
if (loaded.Contains(index)) il.EmitLoadLocal(index);
else
{
// Seek upwards to find the most in depth loaded parent
int i = member.Parents!.Count - 1;
while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--;
// Load the local variables for all the parents of the current member
il.EmitLoadLocal(i);
for (; i < member.Parents.Count; i++)
{
index = map[member.Parents[i]];
il.Emit(OpCodes.Ldfld, member.Parents[i]);
il.EmitStoreLocal(index);
il.EmitLoadLocal(index);
loaded.Add(index);
}
}
}
il.EmitReadMember(member);
}
// Declare the local variables
il.DeclareLocal(ShaderType);
foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key))
{
il.DeclareLocal(member.MemberType);
}
// Cast the closure instance and assign it to the local variable
il.Emit(OpCodes.Ldarg_0);
il.EmitCastOrUnbox(ShaderType);
il.Emit(OpCodes.Stloc_0);
// Handle all the captured members, both resources and variables
foreach (ReadableMember member in _CapturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (_ResourcesCount > 0) il.EmitAddOffset<GraphicsResource>(_ResourcesCount);
_ResourcesCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16;
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(_VariablesByteSize);
_VariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
/* Load the current member accordingly.
* When this method returns, the value of the current
* member will be at the top of the execution stack */
LoadMember(member);
il.EmitStoreToAddress(member.MemberType);
}
il.Emit(OpCodes.Ret);
});
}
}
}
-329
ファイルの表示
@@ -1,329 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Vortice.Direct3D12;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
/// </summary>
internal sealed partial class ShaderLoader
{
/// <summary>
/// The <see cref="Action{T}"/> that represents the shader to load
/// </summary>
private readonly Action<ThreadIds> Action;
/// <summary>
/// Creates a new <see cref="ShaderLoader"/> with the specified parameters
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
private ShaderLoader(Action<ThreadIds> action)
{
Action = action;
ShaderType = action.Method.DeclaringType;
}
/// <summary>
/// The number of constant buffers to define in the shader
/// </summary>
private int _ConstantBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader
/// </summary>
private int _ReadOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader
/// </summary>
private int _ReadWriteBuffersCount;
/// <summary>
/// Gets the closure <see cref="Type"/> for the <see cref="Action"/> field
/// </summary>
public Type ShaderType { get; }
/// <summary>
/// The <see cref="List{T}"/> of <see cref="DescriptorRange1"/> items that are required to load the captured values
/// </summary>
private readonly List<DescriptorRange1> DescriptorRanges = new List<DescriptorRange1>();
private RootParameter1[] _RootParameters;
/// <summary>
/// Gets the <see cref="RootParameter1"/> array for the current shader
/// </summary>
public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray();
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields
/// </summary>
public IReadOnlyList<HlslBufferInfo> BuffersList => _BuffersList;
private readonly List<CapturedFieldInfo> _FieldsList = new List<CapturedFieldInfo>();
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsList => _FieldsList;
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader
/// </summary>
public string MethodBody { get; private set; }
private readonly List<FunctionInfo> _FunctionsList = new List<FunctionInfo>();
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList => _FunctionsList;
private readonly List<LocalFunctionInfo> _LocalFunctionsList = new List<LocalFunctionInfo>();
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
/// <summary>
/// Loads and processes an input <see cref="Action{T}"/>
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader Load(Action<ThreadIds> action)
{
ShaderLoader @this = new ShaderLoader(action);
@this.LoadFieldsInfo();
@this.LoadMethodSource();
@this.BuildDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
private void LoadFieldsInfo()
{
IReadOnlyList<FieldInfo> shaderFields = ShaderType.GetFields().ToArray();
if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++));
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(fieldInfo);
}
}
/// <summary>
/// Loads a specified <see cref="ReadableMember"/> and adds it to the shader model
/// </summary>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
/// <param name="parents">The list of parent fields to reach the current <see cref="ReadableMember"/> from a given <see cref="Action{T}"/></param>
private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList<ReadableMember>? parents = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
_BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
// Register the captured field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsClass && fieldName.StartsWith("CS$<>"))
{
// Captured scope, update the parents list
List<ReadableMember> updatedParents = parents?.ToList() ?? new List<ReadableMember>();
updatedParents.Add(memberInfo);
// Recurse on the new compiler generated class
IReadOnlyList<FieldInfo> fields = fieldType.GetFields().ToArray();
foreach (FieldInfo fieldInfo in fields)
{
LoadFieldInfo(fieldInfo, null, updatedParents);
}
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(Action.Target) 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
LoadStaticMethodSource(fieldName, func.Method);
}
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
private void LoadMethodSource()
{
// Decompile the shader method
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
var locals = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray();
root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia);
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
_LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(method.Key, method.Value);
}
// 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, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
}
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
// Get the final function info instance
FunctionInfo functionInfo = new FunctionInfo(
methodInfo.ReturnType,
$"{methodInfo.DeclaringType.FullName}{Type.Delimiter}{methodInfo.Name}",
string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")),
root.ReturnType.ToString(),
name,
parameters,
body);
_FunctionsList.Add(functionInfo);
}
}
}
+1 -46
ファイルの表示
@@ -1,5 +1,4 @@
using System;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics;
using ComputeSharp.Shaders;
namespace ComputeSharp
@@ -9,50 +8,6 @@ namespace ComputeSharp
/// </summary>
public static class GraphicsDeviceExtensions
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, Action<ThreadIds> action) => ShaderRunner.Run(device, x, 1, 1, action);
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, int y, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, 1, action);
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, z, action);
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(
this GraphicsDevice device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, action);
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>