From fcf7a9a31dc95f9a80827a44172e19e0c4089167 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 15:41:58 +0200 Subject: [PATCH 01/39] Added IComputeShader interface --- src/ComputeSharp.Core/Interfaces/IComputeShader.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/ComputeSharp.Core/Interfaces/IComputeShader.cs diff --git a/src/ComputeSharp.Core/Interfaces/IComputeShader.cs b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs new file mode 100644 index 00000000..66f145dd --- /dev/null +++ b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs @@ -0,0 +1,14 @@ +namespace ComputeSharp +{ + /// + /// An representing a compute shader. + /// + public interface IComputeShader + { + /// + /// Executes the current compute shader. + /// + /// The value with the current execution indices. + void Execute(ThreadIds ids); + } +} From 71213829e70065cb0e2fc0d1aa535bdd0612722a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 16:05:17 +0200 Subject: [PATCH 02/39] Added shader hashcode handling for generic types --- .../Translation/ShaderHashCodeProvider.cs | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 93c32d04..9e5a6f0f 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -19,6 +19,108 @@ namespace ComputeSharp.Shaders.Translation /// private static readonly Dictionary HasherMapping = new Dictionary(); + /// + /// 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 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 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 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(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); + }); + } + /// /// Gets a unique hashcode for the input shader closure /// From d8f3eaaa64a67bd2eabd37b659d6e107f613a12a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 16:14:00 +0200 Subject: [PATCH 03/39] Minor code style tweaks --- .../Translation/ShaderHashCodeProvider.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 9e5a6f0f..e42f0681 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -60,6 +60,7 @@ namespace ComputeSharp.Shaders.Translation /// /// 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)] @@ -78,6 +79,7 @@ namespace ComputeSharp.Shaders.Translation /// /// 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 @@ -87,6 +89,7 @@ namespace ComputeSharp.Shaders.Translation /// /// 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) @@ -96,7 +99,7 @@ namespace ComputeSharp.Shaders.Translation { MethodInfo getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, - getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); + getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode)); foreach (FieldInfo fieldInfo in fieldInfos) { // (hashcode << 5) + hashcode @@ -182,7 +185,7 @@ namespace ComputeSharp.Shaders.Translation MethodInfo validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static), getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, - getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); + getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode)); foreach (FieldInfo fieldInfo in fieldInfos) { Label label = il.DefineLabel(); From 997ed35c90a289cb64b4a9b56187fce746dd0542 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 16:43:26 +0200 Subject: [PATCH 04/39] Added ShaderLoader type --- .../Translation/ShaderLoader{T}.IL.cs | 170 +++++++++ .../Translation/ShaderLoader{T}.cs | 332 ++++++++++++++++++ 2 files changed, 502 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs new file mode 100644 index 00000000..889f1abe --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -0,0 +1,170 @@ +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 +{ + /// + internal sealed partial class ShaderLoader + { + /// + /// The number of captured graphics resources (buffers) + /// + private int _ResourcesCount; + + /// + /// The size in bytes of the buffer with the captured variables + /// + private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count + + // The cached loader method + private DispatchDataLoader? _DispatchDataLoader; + + /// + /// The of instances mapping the captured variables in the current shader + /// + private readonly List _CapturedMembers = new List(); + + /// + /// A that loads all the captured members from a shader closure + /// + /// The shader closure 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(object obj, ref GraphicsResource r0, ref byte r1); + + /// + /// Gets a new instance with all the captured data for the current shader instance + /// + /// The input 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(Action action, int x, int y, int z) + { + // Resources and variables buffers + GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); + byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); + ref GraphicsResource r0 = ref resources[0]; + ref byte r1 = ref variables[0]; + + // 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 + _DispatchDataLoader!(action.Target, ref r0, ref r1); + + return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); + } + + /// + /// Builds a new instance that loads the dispatch data for the current shader type + /// + 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 loaded = new HashSet(new[] { 0 }); + + // Build the dynamic IL method + _DispatchDataLoader = DynamicMethod.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(typeof(T)); + 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(typeof(T)); + 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(_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); + }); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs new file mode 100644 index 00000000..ad0a7141 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -0,0 +1,332 @@ +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 +{ + /// + /// A responsible for loading and processing shaders of a given type + /// + /// The type of compute shader currently in use + internal sealed partial class ShaderLoader + where T : struct, IComputeShader + { + /// + /// The current (boxed) shader being loaded + /// + /// + /// The overhead for the boxing can be ignored here since this will + /// only be done once per shader type/variables combination + /// + private readonly object Shader; + + /// + /// Creates a new with the specified parameters + /// + /// The instance to use to build the shader + private ShaderLoader(T shader) + { + Shader = shader; + } + + /// + /// The number of constant buffers to define in the shader + /// + private int _ConstantBuffersCount; + + /// + /// The number of readonly buffers to define in the shader + /// + private int _ReadOnlyBuffersCount; + + /// + /// The number of read write buffers to define in the shader + /// + private int _ReadWriteBuffersCount; + + /// + /// The of items that are required to load the captured values + /// + private readonly List DescriptorRanges = new List(); + + private RootParameter1[]? _RootParameters; + + /// + /// Gets the array for the current shader + /// + public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray(); + + private readonly List _BuffersList = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList BuffersList => _BuffersList; + + private readonly List _FieldsList = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList FieldsList => _FieldsList; + + /// + /// 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; } + + private readonly List _FunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList FunctionsList => _FunctionsList; + + private readonly List _LocalFunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; + + /// + /// 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 ShaderLoader(shader); + + @this.LoadFieldsInfo(); + @this.LoadMethodSource(); + @this.BuildDispatchDataLoader(); + + return @this; + } + + /// + /// Loads the fields info for the current shader being loaded + /// + private void LoadFieldsInfo() + { + IReadOnlyList shaderFields = typeof(T).GetFields().ToArray(); + + if (shaderFields.Count == 0) 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); + } + } + + /// + /// Loads a specified and adds it to the shader model + /// + /// The target to load + /// The optional explicit name to use for the field + /// The list of parent fields to reach the current from a given + private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? 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 updatedParents = parents?.ToList() ?? new List(); + updatedParents.Add(memberInfo); + + // Recurse on the new compiler generated class + IReadOnlyList fields = fieldType.GetFields().ToArray(); + foreach (FieldInfo fieldInfo in fields) + { + LoadFieldInfo(fieldInfo, null, updatedParents); + } + } + else if (fieldType.IsDelegate() && + memberInfo.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 + LoadStaticMethodSource(fieldName, func.Method); + } + else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); + } + + /// + /// Loads the entry method for the current shader being loaded + /// + private void LoadMethodSource() + { + // Decompile the shader method + MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + + // Rewrite the shader method (eg. to fix the type declarations) + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); + root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); + + // Extract the implicit local functions + var locals = root.DescendantNodes().OfType().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); + } + + /// + /// Loads additional static methods used by the shader + /// + /// The HLSL name of the new method to load + /// The instance for the method to load + 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 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); + } + } +} From 21e5628af8ad2c75d6abbf1637940d097a4a120c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 17:27:25 +0200 Subject: [PATCH 05/39] Simplified shader resources loading --- .../Translation/ShaderLoader{T}.IL.cs | 79 +++---------------- .../Translation/ShaderLoader{T}.cs | 13 --- 2 files changed, 10 insertions(+), 82 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 889f1abe..7a4242fd 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -2,7 +2,6 @@ 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; @@ -34,22 +33,22 @@ namespace ComputeSharp.Shaders.Translation private readonly List _CapturedMembers = new List(); /// - /// A that loads all the captured members from a shader closure + /// A that loads all the captured members from a shader instance /// - /// The shader closure instance to load the data from + /// 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(object obj, ref GraphicsResource r0, ref byte r1); + private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1); /// /// Gets a new instance with all the captured data for the current shader instance /// - /// The input representing the compute shader to run + /// 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(Action action, int x, int y, int z) + public DispatchData GetDispatchData(in T shader, int x, int y, int z) { // Resources and variables buffers GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); @@ -63,7 +62,7 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - _DispatchDataLoader!(action.Target, ref r0, ref r1); + _DispatchDataLoader!(shader, ref r0, ref r1); return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); } @@ -73,66 +72,8 @@ namespace ComputeSharp.Shaders.Translation /// 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 loaded = new HashSet(new[] { 0 }); - - // Build the dynamic IL method _DispatchDataLoader = DynamicMethod.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(typeof(T)); - 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(typeof(T)); - il.Emit(OpCodes.Stloc_0); - - // Handle all the captured members, both resources and variables foreach (ReadableMember member in _CapturedMembers) { if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) @@ -155,11 +96,11 @@ namespace ComputeSharp.Shaders.Translation } 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); + // Load the reference to the input delegate if the member is not static + if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0); + // Read the current member and store it to the target address + il.EmitReadMember(member); il.EmitStoreToAddress(member.MemberType); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index ad0a7141..89ab1f73 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -202,19 +202,6 @@ namespace ComputeSharp.Shaders.Translation 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 updatedParents = parents?.ToList() ?? new List(); - updatedParents.Add(memberInfo); - - // Recurse on the new compiler generated class - IReadOnlyList fields = fieldType.GetFields().ToArray(); - foreach (FieldInfo fieldInfo in fields) - { - LoadFieldInfo(fieldInfo, null, updatedParents); - } - } else if (fieldType.IsDelegate() && memberInfo.GetValue(Shader) is Delegate func && (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) && From a50abf275b9851dfa9206e9d7e279778669c4d5d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 18:49:20 +0200 Subject: [PATCH 06/39] Removed unnecessary parameter --- .../Translation/ShaderLoader{T}.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 89ab1f73..fc8082e3 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -151,8 +151,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The target to load /// The optional explicit name to use for the field - /// The list of parent fields to reach the current from a given - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? parents = null) + private void LoadFieldInfo(ReadableMember memberInfo, string? name = null) { Type fieldType = memberInfo.MemberType; string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); @@ -162,8 +161,6 @@ namespace ComputeSharp.Shaders.Translation { 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]); @@ -174,8 +171,6 @@ namespace ComputeSharp.Shaders.Translation // 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); @@ -186,8 +181,6 @@ namespace ComputeSharp.Shaders.Translation // 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); @@ -195,8 +188,6 @@ namespace ComputeSharp.Shaders.Translation } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { - // Register the captured field - memberInfo.Parents = parents; _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); From 2a1e82c3644d8cf8c21d167ecb01229dca86c58e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 19:40:35 +0200 Subject: [PATCH 07/39] Removed original shader reference in loader class --- .../Translation/ShaderLoader{T}.cs | 54 +++++++++---------- 1 file changed, 25 insertions(+), 29 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index fc8082e3..a9e9ddef 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -28,22 +28,9 @@ namespace ComputeSharp.Shaders.Translation where T : struct, IComputeShader { /// - /// The current (boxed) shader being loaded + /// Creates a new instance /// - /// - /// The overhead for the boxing can be ignored here since this will - /// only be done once per shader type/variables combination - /// - private readonly object Shader; - - /// - /// Creates a new with the specified parameters - /// - /// The instance to use to build the shader - private ShaderLoader(T shader) - { - Shader = shader; - } + private ShaderLoader() { } /// /// The number of constant buffers to define in the shader @@ -118,10 +105,15 @@ namespace ComputeSharp.Shaders.Translation [Pure] public static ShaderLoader Load(in T shader) { - ShaderLoader @this = new ShaderLoader(shader); + ShaderLoader @this = new ShaderLoader(); - @this.LoadFieldsInfo(); - @this.LoadMethodSource(); + /* 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.LoadMethodSource(box); @this.BuildDispatchDataLoader(); return @this; @@ -130,7 +122,8 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads the fields info for the current shader being loaded /// - private void LoadFieldsInfo() + /// The boxed instance to use to build the shader + private void LoadFieldsInfo(object shader) { IReadOnlyList shaderFields = typeof(T).GetFields().ToArray(); @@ -142,16 +135,17 @@ namespace ComputeSharp.Shaders.Translation // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { - LoadFieldInfo(fieldInfo); + 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 /// The optional explicit name to use for the field - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null) + private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null) { Type fieldType = memberInfo.MemberType; string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); @@ -194,14 +188,14 @@ namespace ComputeSharp.Shaders.Translation _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); } else if (fieldType.IsDelegate() && - memberInfo.GetValue(Shader) is Delegate func && + memberInfo.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 - LoadStaticMethodSource(fieldName, func.Method); + LoadStaticMethodSource(shader, fieldName, func.Method); } else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); } @@ -209,7 +203,8 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads the entry method for the current shader being loaded /// - private void LoadMethodSource() + /// The boxed instance to use to build the shader + private void LoadMethodSource(object shader) { // Decompile the shader method MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); @@ -234,13 +229,13 @@ namespace ComputeSharp.Shaders.Translation // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) { - LoadFieldInfo(member.Value, member.Key); + LoadFieldInfo(shader, member.Value, member.Key); } // Register the captured static methods foreach (var method in syntaxRewriter.StaticMethods) { - LoadStaticMethodSource(method.Key, method.Value); + LoadStaticMethodSource(shader, method.Key, method.Value); } // Get the thread ids identifier name and shader method body @@ -256,9 +251,10 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads additional static methods used by the shader /// + /// The boxed instance to use to build the shader /// The HLSL name of the new method to load /// The instance for the method to load - private void LoadStaticMethodSource(string name, MethodInfo methodInfo) + private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo) { // Decompile the target method MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); @@ -270,13 +266,13 @@ namespace ComputeSharp.Shaders.Translation // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) { - LoadFieldInfo(member.Value, member.Key); + LoadFieldInfo(shader, member.Value, member.Key); } // Register the captured static methods foreach (var method in syntaxRewriter.StaticMethods) { - LoadStaticMethodSource(method.Key, method.Value); + LoadStaticMethodSource(shader, method.Key, method.Value); } // Get the function parameters From a7e3d6bec9a5dcdd15bc0bb901382a96c9ac0c84 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 20:24:30 +0200 Subject: [PATCH 08/39] Added CachedShader type --- .../Translation/Models/CachedShader{T}.cs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs new file mode 100644 index 00000000..3b0005e0 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs @@ -0,0 +1,33 @@ +using Vortice.Direct3D12; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A that contains info on a cached shader + /// + /// The type of compute shader in use + internal readonly struct CachedShader + where T : struct, IComputeShader + { + /// + /// The instance with the shader metadata + /// + public readonly ShaderLoader Loader; + + /// + /// The compiled shader bytecode + /// + public readonly ShaderBytecode Bytecode; + + /// + /// Creates a new instance with the specified parameters + /// + /// The instance with the shader metadata + /// The compiled shader bytecode + public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) + { + Loader = loader; + Bytecode = bytecode; + } + } +} From 807dcb576c3f4951188074e6fbaf7b364c7dad77 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 20:24:36 +0200 Subject: [PATCH 09/39] Added ShaderKey type --- .../Translation/Models/ShaderKey.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs diff --git a/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs new file mode 100644 index 00000000..89c3cd1d --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A representing a key for a given shader + /// + [StructLayout(LayoutKind.Explicit)] + internal readonly struct ShaderKey : IEquatable + { + /// + /// The hashcode of the current shader type + /// + [FieldOffset(0)] + private readonly int Id; + + /// + /// The number of iterations to run on the X axis + /// + [FieldOffset(4)] + private readonly int ThreadsX; + + /// + /// The number of iterations to run on the Y axis + /// + [FieldOffset(8)] + private readonly int ThreadsY; + + /// + /// The number of iterations to run on the Z axis + /// + [FieldOffset(12)] + private readonly int ThreadsZ; + + /// + /// Creates a new instance with the specified parameters + /// + /// The hashcode of the current shader type + /// 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 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ShaderKey(int id, int threadsX, int threadsY, int threadsZ) + { + Id = id; + ThreadsX = threadsX; + ThreadsY = threadsY; + ThreadsZ = threadsZ; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ShaderKey other) + { + return + Unsafe.As(ref Unsafe.AsRef(Id)) + == Unsafe.As(ref Unsafe.AsRef(other.Id)) && + Unsafe.As(ref Unsafe.AsRef(ThreadsY)) + == Unsafe.As(ref Unsafe.AsRef(other.ThreadsY)); + } + + /// + public override bool Equals(object? obj) + { + return obj is ShaderKey other && Equals(other); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() + { + ulong ul0 = Unsafe.As(ref Unsafe.AsRef(Id)); + + int hash = unchecked((int)ul0) ^ (int)(ul0 >> 32); + + ulong ul1 = Unsafe.As(ref Unsafe.AsRef(ThreadsY)); + + hash = (hash << 5) + hash + unchecked((int)ul1) ^ ((int)(ul1 >> 32)); + + return hash; + } + } +} From 9324a3a42b645adbff0e4da9b96bfc7c9476b305 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 20:30:39 +0200 Subject: [PATCH 10/39] Added ShaderRunner type --- .../ComputeSharp.Shaders.csproj | 1 + src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 131 ++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 src/ComputeSharp.Shaders/ShaderRunner{T}.cs diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 5ed31bb6..555630bc 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -9,6 +9,7 @@ + diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs new file mode 100644 index 00000000..a4c85b2d --- /dev/null +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -0,0 +1,131 @@ +using System; +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 Microsoft.Collections.Extensions; +using Vortice.Direct3D12; +using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using PipelineState = ComputeSharp.Graphics.Commands.PipelineState; + +namespace ComputeSharp.Shaders +{ + /// + /// A responsible for performing all the necessary operations to compile and run a compute shader + /// + /// The type of compute shader to run + internal static class ShaderRunner + where T : struct, IComputeShader + { + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The to use to run the shader + /// 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 + /// The input instance representing the compute shader to run + public static void Run(GraphicsDevice device, int x, int y, int z, in T shader) + { + // 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, shader); + } + + /// + /// The mapping used to cache and reuse compiled shaders + /// + private static readonly DictionarySlim> ShadersCache = new DictionarySlim>(); + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The to use to run the shader + /// 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 + /// The number of threads in each thread group for the X axis + /// The number of threads in each thread group for the Y axis + /// The number of threads in each thread group for the Z axis + /// The input instance representing the compute shader to run + public static void Run( + GraphicsDevice device, + int x, int y, int z, + int threadsX, int threadsY, int threadsZ, + in T shader) + { + // Try to get the cache shader + CachedShader shaderData; + lock (ShadersCache) + { + var key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); + if (!ShadersCache.TryGetValue(key, out shaderData)) + { + // Load the input shader + ShaderLoader shaderLoader = ShaderLoader.Load(shader); + + // 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 + ShadersCache.GetOrAddValueRef(key) = new CachedShader(shaderLoader, shaderBytecode); + } + } + + // 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(shader, x, y, z); + + // Load the captured buffers + Span resources = dispatchData.Resources; + for (int i = 0; i < resources.Length; i++) + { + commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); + } + + // Initialize the loop targets + Span 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(); + } + } +} From 80f35ddcd2237e2994d1ce85506b886eaefe3c28 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 20:33:25 +0200 Subject: [PATCH 11/39] Added new generic extensions --- .../Extensions/GraphicsDeviceExtensions.cs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index db36a328..49f5f7df 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -52,5 +52,69 @@ namespace ComputeSharp int x, int y, int z, int threadsX, int threadsY, int threadsZ, Action action) => ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, action); + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The type of compute shader to run + /// The to use to run the shader + /// The number of iterations to run on the X axis + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, 1, 1, shader); + } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The type of compute shader to run + /// The to use to run the shader + /// The number of iterations to run on the X axis + /// The number of iterations to run on the Y axis + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, int y, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, 1, shader); + } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The type of compute shader to run + /// The to use to run the shader + /// 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 + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, int y, int z, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, z, shader); + } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters + /// + /// The type of compute shader to run + /// The to use to run the shader + /// 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 + /// The number of threads in each thread group for the X axis + /// The number of threads in each thread group for the Y axis + /// The number of threads in each thread group for the Z axis + /// The input instance representing the compute shader to run + public static void For( + this GraphicsDevice device, + int x, int y, int z, + int threadsX, int threadsY, int threadsZ, + in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, shader); + } } } From f0da5b033c1578a17651d6cdb65310525d4a021a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 22:23:46 +0200 Subject: [PATCH 12/39] Bug fixes in the shader compilation --- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 2 +- .../Translation/Enums/MethodType.cs | 4 +- .../Translation/MethodDecompiler.cs | 121 ++---------------- .../Translation/ShaderLoader.cs | 2 +- .../Translation/ShaderLoader{T}.cs | 2 +- 5 files changed, 19 insertions(+), 112 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index a4c85b2d..1ebb6005 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -89,7 +89,7 @@ namespace ComputeSharp.Shaders ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource); // Cache for later use - ShadersCache.GetOrAddValueRef(key) = new CachedShader(shaderLoader, shaderBytecode); + ShadersCache.GetOrAddValueRef(key) = shaderData = new CachedShader(shaderLoader, shaderBytecode); } } diff --git a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs index 7df4f830..c3c188e8 100644 --- a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs +++ b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs @@ -6,9 +6,9 @@ internal enum MethodType { /// - /// An instance method that belongs to a closure class + /// The instance method on some shader type /// - Closure, + Execute, /// /// A standalone, static method diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 5c10cd5b..b4bd6bef 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,7 +6,6 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; -using System.Text; using System.Text.RegularExpressions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Enums; @@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = methodType switch { - MethodType.Closure => GetSyntaxTreeForClosureMethod(methodInfo), + MethodType.Execute => GetSyntaxTreeForClosureMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") }; @@ -147,7 +146,11 @@ namespace ComputeSharp.Shaders.Translation SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Get the root node to return - rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); + rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(methodInfo.Name)); // Update the incremental compilation and retrieve the syntax tree for the method Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); @@ -161,29 +164,11 @@ namespace ComputeSharp.Shaders.Translation [Pure] private string GetSyntaxTreeForClosureMethod(MethodInfo methodInfo) { - // Decompile the method source and fix the method declaration for local methods converted to lambdas - string - sourceCode = DecompileMethodOrDeclaringType(methodInfo), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"), - methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"); - - // Workaround for some local methods not being decompiled correctly - if (!methodFixedCode.Contains("internal void Main")) - { - string - methodOnlySourceCode = DecompileMethodOrDeclaringType(methodInfo, true), - methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"), - methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}"; - - int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}'); - methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode); - } - - // Unwrap the nested fields - string unwrappedSourceCode = UnwrapSyntaxTree(methodFixedCode); + // Decompile the method source + string sourceCode = DecompileMethodOrDeclaringType(methodInfo); // Remove the in keyword from the source - string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(? - /// A used to preprocess the closure type declarations for both lambda expressions and local methods - /// - private static readonly Regex ClosureTypeDeclarationRegex = new Regex(@"(?<=private sealed class )<\w*>[\w_]+", RegexOptions.Compiled); - - /// - /// A used to preprocess the entry point declaration for both lambda expressions and local methods - /// - private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(?:private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled); - - /// - /// A used to find fields that represent nested closure types - /// - private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); - - /// - /// A used to identify compiler generated fields - /// - private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled); - - /// - /// Unwraps all the nested captured fields in the given source code, moving them to the top level - /// - /// The input source code to process - [Pure] - private string UnwrapSyntaxTree(string source) - { - List parsedFields = new List(); - - // Local function to recursively extract all the nested fields - void ParseNestedFields(string typeSource) - { - // Find the field declarations - Match match = NestedClosureFieldRegex.Match(typeSource); - if (!match.Success) return; - - // Load the nested closure type - string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type - Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); - - // Decompile the type and get a readable source code - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); - CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; - string - sourceCode = decompiler.DecompileAsString(typeHandle), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); - - // Load the syntax tree and retrieve the list of fields - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); - FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); - - // Add the captured fields - foreach (FieldDeclarationSyntax field in fields) - if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) - parsedFields.Add(field); - - // Explore the new decompiled type - ParseNestedFields(typeFixedCode); - } - - ParseNestedFields(source); - - if (parsedFields.Count > 0) - { - // Build the aggregated string with all the captured fields - StringBuilder builder = new StringBuilder(); - foreach (FieldDeclarationSyntax field in parsedFields) - builder.AppendLine(field.ToFullString()); - string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); - - // Replace the field declarations - Match match = NestedClosureFieldRegex.Match(source); - source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";" - source = source.Insert(match.Index - 11, fields); - - // Adjust the method body to remove references to compiler generated fields - source = CompilerGeneratedFieldRegex.Replace(source, string.Empty); - } - - return source; - } - /// /// Refactors all the inline out expressions with a variable declaration /// @@ -308,7 +211,11 @@ namespace ComputeSharp.Shaders.Translation // Load the syntax tree and the entry node SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); - MethodDeclarationSyntax rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); + MethodDeclarationSyntax rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(entryPoint)); // Get the out declarations to replace var outs = ( diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index fbf49dc5..9c8df435 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -232,7 +232,7 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodSource() { // Decompile the shader method - MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + 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); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index a9e9ddef..5b52b14b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -208,7 +208,7 @@ namespace ComputeSharp.Shaders.Translation { // Decompile the shader method MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); From 037daa1e8ae42197f648121eeec0e2643db67fef Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 01:44:58 +0200 Subject: [PATCH 13/39] Fixed parsing of static functions with attributes --- .../Translation/MethodDecompiler.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index b4bd6bef..4ff57cfd 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -137,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = methodType switch { - MethodType.Execute => GetSyntaxTreeForClosureMethod(methodInfo), + MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") }; @@ -150,7 +150,8 @@ namespace ComputeSharp.Shaders.Translation .GetRoot() .DescendantNodes() .OfType() - .First(node => node.Identifier.ToString().Equals(methodInfo.Name)); + .First(node => node.Identifier.ToString().Equals(methodInfo.Name) || + node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); // Update the incremental compilation and retrieve the syntax tree for the method Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); @@ -162,7 +163,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The input to inspect [Pure] - private string GetSyntaxTreeForClosureMethod(MethodInfo methodInfo) + private string GetSyntaxTreeForExecuteMethod(MethodInfo methodInfo) { // Decompile the method source string sourceCode = DecompileMethodOrDeclaringType(methodInfo); @@ -186,8 +187,16 @@ namespace ComputeSharp.Shaders.Translation string sourceCode = DecompileMethodOrDeclaringType(methodInfo, true), methodFixedCode = sourceCode.Replace(methodInfo.Name, Regex.Replace(methodInfo.Name, "[<>|]", "_")), - prototype = methodFixedCode.Split(Environment.NewLine)[0], - commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodFixedCode}", + methodWithoutAttributes = CSharpSyntaxTree + .ParseText(methodFixedCode) + .GetRoot() + .DescendantNodes() + .OfType() + .First() + .WithAttributeLists(default) + .ToString(), + prototype = methodWithoutAttributes.Split(Environment.NewLine)[0], + commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}", inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?() - .First(node => node.Identifier.ToString().Equals(entryPoint)); + .First(node => node.Identifier.ToString().Equals(entryPoint) || + node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); // Get the out declarations to replace var outs = ( From a944549a693f2ff0dc06e711f4006aa9f6df6ed2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 01:45:08 +0200 Subject: [PATCH 14/39] Moved unit tests to new syntax --- .../ShaderHashCodeTests.cs | 45 +++- .../HlslVectorTypesTests.cs | 94 +++++-- .../ComputeSharp.Tests/InitializationTests.cs | 14 +- .../InternalStaticMembersTests.cs | 99 ++++++-- tests/ComputeSharp.Tests/IntrinsicTests.cs | 70 ++++-- .../ComputeSharp.Tests/InvalidShaderTests.cs | 31 ++- .../ComputeSharp.Tests/ShaderClosureTests.cs | 180 ++++++------- .../ComputeSharp.Tests/ShaderDispatchTests.cs | 50 +++- tests/ComputeSharp.Tests/StaticFieldsTests.cs | 99 ++++++-- .../StaticFunctionsTests.cs | 238 ++++++++++++++++-- .../ComputeSharp.Tests/StaticMethodsTests.cs | 91 ++++++- .../StaticPropertiesTests.cs | 113 +++++++-- 12 files changed, 854 insertions(+), 270 deletions(-) diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index bd0dfa99..c973bdd0 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -8,25 +8,48 @@ namespace ComputeSharp.Tests.Internals [TestCategory("ShaderHashCodes")] public class ShaderHashCodeTests { + public struct Shader1 : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = A; + } + } + [TestMethod] public void ShaderWithNoCapturedDelegates() { float value = 10; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action1 = id => buffer[0] = value; + Shader1 shader1 = new Shader1 { A = value, B = buffer }; int - hash1 = ShaderHashCodeProvider.GetHashCode(action1), - hash2 = ShaderHashCodeProvider.GetHashCode(action1); + hash1 = ShaderHashCodeProvider.GetHashCode(shader1), + hash2 = ShaderHashCodeProvider.GetHashCode(shader1); Assert.IsTrue(hash1 == hash2); - Action action2 = id => buffer[0] = value; + Shader1 shader2 = new Shader1 { A = value, B = buffer }; - int hash3 = ShaderHashCodeProvider.GetHashCode(action2); + int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); - Assert.IsFalse(hash1 == hash3); + Assert.IsTrue(hash1 == hash3); + } + + public struct Shader2 : IComputeShader + { + public float A; + public ReadWriteBuffer B; + public Func F; + + public void Execute(ThreadIds ids) + { + B[0] = F(A); + } } [TestMethod] @@ -36,17 +59,19 @@ namespace ComputeSharp.Tests.Internals using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = f(2); + Shader2 shader1 = new Shader2 { A = 1, B = buffer, F = f }; int - hash1 = ShaderHashCodeProvider.GetHashCode(action), - hash2 = ShaderHashCodeProvider.GetHashCode(action); + hash1 = ShaderHashCodeProvider.GetHashCode(shader1), + hash2 = ShaderHashCodeProvider.GetHashCode(shader1); Assert.IsTrue(hash1 == hash2); f = x => x + 1; - int hash3 = ShaderHashCodeProvider.GetHashCode(action); + Shader2 shader2 = new Shader2 { A = 1, B = buffer, F = f }; + + int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); Assert.IsFalse(hash1 == hash3); } diff --git a/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs b/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs index def28124..46dc389e 100644 --- a/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs +++ b/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs @@ -7,18 +7,50 @@ namespace ComputeSharp.Tests [TestCategory("HlslVectorTypes")] public class HlslVectorTypesTests { + private struct SequentialCompilation_Shader_1 : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F2.XY; + } + } + + private struct SequentialCompilation_Shader_2 : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[1] = F2.XY; + } + } + [TestMethod] public void SequentialCompilation() { Float2 f2 = new Float2(1, 2); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action1 = id => buffer[0] = f2.YX; + var shader1 = new SequentialCompilation_Shader_1 { F2 = f2, B = buffer }; + var shader2 = new SequentialCompilation_Shader_2 { F2 = f2, B = buffer }; - Action action2 = id => buffer[1] = f2.YX; + Gpu.Default.For(1, shader1); + Gpu.Default.For(1, shader2); + } - Gpu.Default.For(1, action1); - Gpu.Default.For(1, action2); + private struct LocalFloatAssignToFloat2Buffer_Shader : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F2.YX; + } } [TestMethod] @@ -27,9 +59,9 @@ namespace ComputeSharp.Tests Float2 f2 = new Float2(1, 2); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = f2.YX; + var shader = new LocalFloatAssignToFloat2Buffer_Shader { F2 = f2, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Float2[] result = buffer.GetData(); @@ -37,29 +69,50 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0].Y - f2.X) < 0.0001f); } + private struct Int2Properties_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = 1; + } + } + [TestMethod] public void Int2Properties() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0].X = 1; + var shader = new Int2Properties_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Int2[] result = buffer.GetData(); Assert.IsTrue(result[0].X == 1); } + private struct LocalBoolAssignToBool2Buffer_Shader : IComputeShader + { + public Bool2 B2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = B2; + } + } + [TestMethod] public void LocalBoolAssignToBool2Buffer() { Bool2 b2 = Bool2.TrueY; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = b2; + var shader = new LocalBoolAssignToBool2Buffer_Shader { B2 = b2, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Bool2[] result = buffer.GetData(); @@ -67,19 +120,26 @@ namespace ComputeSharp.Tests Assert.IsTrue(result[0].Y == b2.Y); } + private struct Bool3Operations_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Bool3.TrueX; + B[1] = Bool3.True; + B[2].YZ = Bool2.True; + } + } + [TestMethod] public void Bool3Operations() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(3); - Action action = id => - { - buffer[0] = Bool3.TrueX; - buffer[1] = Bool3.True; - buffer[2].YZ = Bool2.True; - }; + var shader = new Bool3Operations_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Bool3[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 397214ef..1406152f 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -17,6 +17,16 @@ namespace ComputeSharp.Tests else Assert.ThrowsException(() => Gpu.Default); } + private struct RunShaderOnAllDevicesShader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = ids.X; + } + } + [TestMethod] public void RunShaderOnAllDevices() { @@ -24,9 +34,9 @@ namespace ComputeSharp.Tests { using (ReadWriteBuffer buffer = gpu.AllocateReadWriteBuffer(100)) { - Action action = id => buffer[id.X] = id.X; + var shader = new RunShaderOnAllDevicesShader { B = buffer }; - gpu.For(100, action); + gpu.For(100, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); diff --git a/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs b/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs index 5cdc6087..ea58abc3 100644 --- a/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs +++ b/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs @@ -39,60 +39,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticFields")] public class InternalStaticMembersTests { + private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.StaticFloat; + var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat; + var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.ReadonlyVector2.X; + else B[1] = StaticMembersContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.ReadonlyVector2.X; - else buffer[1] = StaticMembersContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -100,18 +137,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.StaticVector2.X; + else B[1] = StaticMembersContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.StaticVector2.X; - else buffer[1] = StaticMembersContainer.StaticVector2.Y; - }; + var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -119,18 +163,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.StaticBuffer[0]; + else B[1] = StaticMembersContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.StaticBuffer[0]; - else buffer[1] = StaticMembersContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticMembersContainer.StaticBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/IntrinsicTests.cs b/tests/ComputeSharp.Tests/IntrinsicTests.cs index d6cd3365..b240f081 100644 --- a/tests/ComputeSharp.Tests/IntrinsicTests.cs +++ b/tests/ComputeSharp.Tests/IntrinsicTests.cs @@ -7,22 +7,30 @@ namespace ComputeSharp.Tests [TestCategory("Intrinsics")] public class IntrinsicTests { + private struct IntrinsicWithInlineOutParamater_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + B[1] = Hlsl.Cos(A); + Hlsl.SinCos(A, out float sine, out float cosine); + B[2] = sine; + B[3] = cosine; + } + } + [TestMethod] public void IntrinsicWithInlineOutParamater() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - buffer[1] = Hlsl.Cos(angle); - Hlsl.SinCos(angle, out float sine, out float cosine); - buffer[2] = sine; - buffer[3] = cosine; - }; + var shader = new IntrinsicWithInlineOutParamater_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -30,40 +38,56 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - result[3]) < 0.0001f); } + private struct IntrinsicWithInlineOutParamaterAndDiscard_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + Hlsl.SinCos(A, out float sine, out _); + B[1] = sine; + } + } + [TestMethod] public void IntrinsicWithInlineOutParamaterAndDiscard() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - Hlsl.SinCos(angle, out float sine, out _); - buffer[1] = sine; - }; + var shader = new IntrinsicWithInlineOutParamaterAndDiscard_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - result[1]) < 0.0001f); } + private struct IntrinsicWithOutParamaters_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + B[1] = Hlsl.Cos(A); + Hlsl.SinCos(A, out B[2], out B[3]); + } + } + [TestMethod] public void IntrinsicWithOutParamaters() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - buffer[1] = Hlsl.Cos(angle); - Hlsl.SinCos(angle, out buffer[2], out buffer[3]); - }; + var shader = new IntrinsicWithOutParamaters_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.Tests/InvalidShaderTests.cs b/tests/ComputeSharp.Tests/InvalidShaderTests.cs index 393dbfba..a1da283e 100644 --- a/tests/ComputeSharp.Tests/InvalidShaderTests.cs +++ b/tests/ComputeSharp.Tests/InvalidShaderTests.cs @@ -10,24 +10,41 @@ namespace ComputeSharp.Tests [TestCategory("InvalidShader")] public class InvalidShaderTests { - [TestMethod] - public void EmptyShaderCompileError() + private struct EmptyShaderCompileError_Shader : IComputeShader { - Action action = id => { }; - - Assert.ThrowsException(() => Gpu.Default.For(10, action)); + public void Execute(ThreadIds ids) { } } [TestMethod] + [ExpectedException(typeof(InvalidOperationException))] + public void EmptyShaderCompileError() + { + var shader = default(EmptyShaderCompileError_Shader); + + Gpu.Default.For(10, shader); + } + + private struct DeviceMismatchException_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = 1; + } + } + + [TestMethod] + [ExpectedException(typeof(GraphicsDeviceMismatchException))] public void DeviceMismatchException() { ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); GraphicsDevice device = Gpu.EnumerateDevices().First(); - Action action = id => buffer[0] = 1; + var shader = new DeviceMismatchException_Shader { B = buffer }; - Assert.ThrowsException(() => device.For(1, action)); + device.For(1, shader); } } } diff --git a/tests/ComputeSharp.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.Tests/ShaderClosureTests.cs index 808edeaa..40573273 100644 --- a/tests/ComputeSharp.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.Tests/ShaderClosureTests.cs @@ -10,19 +10,33 @@ namespace ComputeSharp.Tests [TestCategory("ShaderClosure")] public class ShaderClosureTests { + private struct LocalScalarAssignToBuffer_Shader : IComputeShader where T : unmanaged + { + public T Value; + public T Zero; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X % 2 == 0) B[ids.X] = Value; + else B[ids.X] = Zero; + } + } + private static void LocalScalarAssignToBuffer(T value, Func equals) where T : unmanaged { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); T zero = default; - Action action = id => + var shader = new LocalScalarAssignToBuffer_Shader { - if (id.X % 2 == 0) buffer[id.X] = value; - else buffer[id.X] = zero; + Value = value, + Zero = zero, + B = buffer }; - Gpu.Default.For(4, action); + Gpu.Default.For(4, shader); T[] result = buffer.GetData(); @@ -41,19 +55,27 @@ namespace ComputeSharp.Tests LocalScalarAssignToBuffer(true, (a, b) => a == b); } + private struct ShaderWithBoolType_Shader : IComputeShader + { + public ReadWriteBuffer B; + public ReadWriteBuffer I; + + public void Execute(ThreadIds ids) + { + if (B[ids.X]) I[ids.X] = ids.X + 1; + B[ids.X] = (ids.X % 2) == 0; + } + } + [TestMethod] public void ShaderWithBoolType() { using ReadWriteBuffer bools = Gpu.Default.AllocateReadWriteBuffer(new Bool[] { true, false, true, true }); using ReadWriteBuffer ints = Gpu.Default.AllocateReadWriteBuffer(4); - void Foo(ThreadIds id) - { - if (bools[id.X]) ints[id.X] = id.X + 1; - bools[id.X] = (id.X % 2) == 0; - } + var shader = new ShaderWithBoolType_Shader { B = bools, I = ints }; - Gpu.Default.For(4, Foo); + Gpu.Default.For(4, shader); Bool[] boolResults = bools.GetData(); @@ -70,19 +92,18 @@ namespace ComputeSharp.Tests Assert.IsTrue(intResults[3] == 4); } - [TestMethod] - public void LocalScalarAssignToBufferWithinLocalMethod() + private struct LocalKnownVectorAssignToBuffer_Shader : IComputeShader { - float value = 10; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + public Vector4 V4; + public ReadWriteBuffer B; - void Foo(ThreadIds id) => buffer[0] = value; - - Gpu.Default.For(1, Foo); - - float[] result = buffer.GetData(); - - Assert.IsTrue((int)result[0] == (int)value); + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = V4.X; + else if (ids.X == 1) B[1] = V4.Y; + else if (ids.X == 2) B[2] = V4.Z; + else if (ids.X == 3) B[3] = V4.W; + } } [TestMethod] @@ -91,15 +112,9 @@ namespace ComputeSharp.Tests Vector4 vector4 = new Vector4(1, 2, 3, 4); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); - Action action = id => - { - if (id.X == 0) buffer[0] = vector4.X; - else if (id.X == 1) buffer[1] = vector4.Y; - else if (id.X == 2) buffer[2] = vector4.Z; - else if (id.X == 3) buffer[3] = vector4.W; - }; + var shader = new LocalKnownVectorAssignToBuffer_Shader { V4 = vector4, B = buffer }; - Gpu.Default.For(4, action); + Gpu.Default.For(4, shader); float[] result = buffer.GetData(); float[] expected = { 1, 2, 3, 4 }; @@ -107,6 +122,17 @@ namespace ComputeSharp.Tests Assert.IsTrue(result.AsSpan().ContentEquals(expected)); } + private struct CopyBetweenConstantAndWriteableBuffers_Shader : IComputeShader + { + public ConstantBuffer C; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = C[ids.X]; + } + } + [TestMethod] public void CopyBetweenConstantAndWriteableBuffers() { @@ -115,15 +141,26 @@ namespace ComputeSharp.Tests using ConstantBuffer input = Gpu.Default.AllocateConstantBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenConstantAndWriteableBuffers_Shader { C = input, B = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } + private struct CopyBetweenReadOnlyAndWriteableBuffers_Shader : IComputeShader + { + public ReadOnlyBuffer IN; + public ReadWriteBuffer OUT; + + public void Execute(ThreadIds ids) + { + OUT[ids.X] = IN[ids.X]; + } + } + [TestMethod] public void CopyBetweenReadOnlyAndWriteableBuffers() { @@ -132,15 +169,26 @@ namespace ComputeSharp.Tests using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenReadOnlyAndWriteableBuffers_Shader { IN = input, OUT = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } + private struct CopyBetweenWriteableBuffers_Shader : IComputeShader + { + public ReadWriteBuffer IN; + public ReadWriteBuffer OUT; + + public void Execute(ThreadIds ids) + { + OUT[ids.X] = IN[ids.X]; + } + } + [TestMethod] public void CopyBetweenWriteableBuffers() { @@ -149,75 +197,13 @@ namespace ComputeSharp.Tests using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenWriteableBuffers_Shader { IN = input, OUT = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } - - [TestMethod] - public void CopyBetweenNestedClosuresEasy() - { - int value1 = 1; - using (ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value2 = 2; - Action action = id => - { - int sum = value1 + value2; - buffer1[0] = sum; - }; - - Gpu.Default.For(1, action); - - int[] result1 = buffer1.GetData(); - - Assert.IsTrue(result1[0] == value1 + value2); - } - } - - [TestMethod] - public void CopyBetweenNestedClosuresHard() - { - int value1 = 1, value2 = 55, value3 = 77; - using (ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value4 = 2, value5 = 24, value6 = 99; - using (ReadWriteBuffer buffer2 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value7 = 3, value8 = 12, value9 = 333; - using (ReadWriteBuffer buffer3 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value10 = 4, value11 = 22; - Action action = id => - { - int sum_gpu = - value1 + value2 + value3 + value4 + - value5 + value6 + value7 + value8 + - value9 + value10 + value11; - buffer1[0] = buffer2[0] = buffer3[0] = sum_gpu; - }; - - Gpu.Default.For(1, action); - - int[] result1 = buffer1.GetData(); - int[] result2 = buffer2.GetData(); - int[] result3 = buffer3.GetData(); - - int sum_cpu = - value1 + value2 + value3 + value4 + - value5 + value6 + value7 + value8 + - value9 + value10 + value11; - - Assert.IsTrue(result1[0] == sum_cpu); - Assert.IsTrue(result2[0] == sum_cpu); - Assert.IsTrue(result3[0] == sum_cpu); - } - } - } - } } } diff --git a/tests/ComputeSharp.Tests/ShaderDispatchTests.cs b/tests/ComputeSharp.Tests/ShaderDispatchTests.cs index 9c4c2f7c..8957192c 100644 --- a/tests/ComputeSharp.Tests/ShaderDispatchTests.cs +++ b/tests/ComputeSharp.Tests/ShaderDispatchTests.cs @@ -9,14 +9,24 @@ namespace ComputeSharp.Tests [TestCategory("ShaderDispatch")] public class ShaderDispatch { + private struct WriteToReadWriteBufferDispatch1D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = ids.X; + } + } + [TestMethod] public void WriteToReadWriteBufferDispatch1D() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); - Action action = id => buffer[id.X] = id.X; + var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer }; - Gpu.Default.For(100, action); + Gpu.Default.For(100, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -29,9 +39,9 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); - Action action = id => buffer[id.X] = id.X; + var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer }; - Gpu.Default.For(100, 1, 1, 64, 1, 1, action); + Gpu.Default.For(100, 1, 1, 64, 1, 1, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -39,14 +49,24 @@ namespace ComputeSharp.Tests Assert.IsTrue(array.AsSpan().ContentEquals(expected)); } + private struct WriteToReadWriteBufferDispatch2D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X + ids.Y * 10] = ids.X + ids.Y * 10; + } + } + [TestMethod] public void WriteToReadWriteBufferDispatch2D() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); - Action action = id => buffer[id.X + id.Y * 10] = id.X + id.Y * 10; + var shader = new WriteToReadWriteBufferDispatch2D_Shader { B = buffer }; - Gpu.Default.For(10, 10, action); + Gpu.Default.For(10, 10, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -54,14 +74,24 @@ namespace ComputeSharp.Tests Assert.IsTrue(array.AsSpan().ContentEquals(expected)); } + private struct WriteToReadWriteBufferDispatch3D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X + ids.Y * 10 + ids.Z * 100] = ids.X + ids.Y * 10 + ids.Z * 100; + } + } + [TestMethod] public void WriteToReadWriteBufferDispatch3D() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); - Action action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100; + var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer }; - Gpu.Default.For(10, 10, 10, action); + Gpu.Default.For(10, 10, 10, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); @@ -74,9 +104,9 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); - Action action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100; + var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer }; - Gpu.Default.For(10, 10, 10, 4, 4, 4, action); + Gpu.Default.For(10, 10, 10, 4, 4, 4, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); diff --git a/tests/ComputeSharp.Tests/StaticFieldsTests.cs b/tests/ComputeSharp.Tests/StaticFieldsTests.cs index 2d73b3ae..e2aeb367 100644 --- a/tests/ComputeSharp.Tests/StaticFieldsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFieldsTests.cs @@ -39,60 +39,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticFields")] public class StaticFieldsTests { + private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat; + var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat; + var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.ReadonlyVector2.X; + else B[1] = StaticFieldsContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.ReadonlyVector2.X; - else buffer[1] = StaticFieldsContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -100,18 +137,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.StaticVector2.X; + else B[1] = StaticFieldsContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticVector2.X; - else buffer[1] = StaticFieldsContainer.StaticVector2.Y; - }; + var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -119,18 +163,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.StaticBuffer[0]; + else B[1] = StaticFieldsContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticBuffer[0]; - else buffer[1] = StaticFieldsContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticFieldsContainer.StaticBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs index ce7ccb7c..93b979a5 100644 --- a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs @@ -7,14 +7,77 @@ namespace ComputeSharp.Tests [TestCategory("StaticFunctions")] public class StaticFunctionsTests { + private struct ExternalStaticFunctionDirect_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Square(4); + } + } + + [TestMethod] + public void ExternalStaticFunctionDirect() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + var shader = new ExternalStaticFunctionDirect_Shader { B = buffer }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f); + } + + private struct ExternalStaticFunctionWithAttributesDirect_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.SquareWithAttributes(4); + } + } + + [TestMethod] + public void ExternalStaticFunctionWithAttributesDirect() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + var shader = new ExternalStaticFunctionWithAttributesDirect_Shader { B = buffer }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f); + } + + private struct FloatToFloatFunc_Shader : IComputeShader + { + public Func F; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F(3); + } + } + [TestMethod] public void FloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Func square = StaticMethodsContainer.Square; + var shader = new FloatToFloatFunc_Shader + { + F = StaticMethodsContainer.Square, + B = buffer + }; - Gpu.Default.For(1, id => buffer[0] = square(3)); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -28,7 +91,13 @@ namespace ComputeSharp.Tests Func square = StaticMethodsContainer.InternalSquare; - Gpu.Default.For(1, id => buffer[0] = square(3)); + var shader = new FloatToFloatFunc_Shader + { + F = square, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -40,23 +109,39 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Func func = StaticMethodsContainer.Square; + var shader = new FloatToFloatFunc_Shader + { + F = StaticMethodsContainer.Square, + B = buffer + }; - Gpu.Default.For(1, id => buffer[0] = func(3)); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); - func = StaticMethodsContainer.Negate; + shader.F = StaticMethodsContainer.Negate; - Gpu.Default.For(1, id => buffer[0] = func(3)); + Gpu.Default.For(1, shader); result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] + 3) < 0.0001f); } + private struct ChangingFuncsFromExternalMethod_Shader : IComputeShader + { + public Func F; + public ReadWriteBuffer B; + public float I; + + public void Execute(ThreadIds ids) + { + B[0] = F(I); + } + } + [TestMethod] public void ChangingFuncsFromExternalMethod() { @@ -69,7 +154,14 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = func(input)); + var shader = new ChangingFuncsFromExternalMethod_Shader + { + F = func, + B = buffer, + I = input + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -78,6 +170,17 @@ namespace ComputeSharp.Tests public delegate float Squarer(float x); + private struct CustomStaticDelegate_Shader : IComputeShader + { + public Squarer F; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F(3); + } + } + [TestMethod] public void CustomStaticDelegate() { @@ -85,7 +188,13 @@ namespace ComputeSharp.Tests Squarer square = StaticMethodsContainer.Square; - Gpu.Default.For(1, id => buffer[0] = square(3)); + var shader = new CustomStaticDelegate_Shader + { + F = square, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -99,7 +208,13 @@ namespace ComputeSharp.Tests Func f = x => x * x; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -115,7 +230,33 @@ namespace ComputeSharp.Tests Func f = Func; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void StaticLocalFunction() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + static float f(float x) => x * x; + + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -129,7 +270,13 @@ namespace ComputeSharp.Tests float f(float x) => x * x; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -138,12 +285,24 @@ namespace ComputeSharp.Tests public static float Square(float x) => x * x; + private struct StaticMethodInSameClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Square(3); + } + } + [TestMethod] public void StaticMethodInSameClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = Square(3)); + var shader = new StaticMethodInSameClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -152,46 +311,77 @@ namespace ComputeSharp.Tests public static Func SquareFunc { get; } = x => x * x; + private struct StaticFunctionInSameClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = SquareFunc(3); + } + } + [TestMethod] public void StaticFunctionInSameClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = SquareFunc(3)); + var shader = new StaticFunctionInSameClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct StaticFunctionInExternalClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.SquareFunc(3); + } + } + [TestMethod] public void StaticFunctionInExternalClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticPropertiesContainer.SquareFunc(3)); + var shader = new StaticFunctionInExternalClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + + private struct ReadmeSample_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * 1; + float pow = Hlsl.Pow(B[offset], 2); // 9 + B[offset] = Sigmoid(pow); // 0.9998766 + } + } + [TestMethod] public void ReadmeSample() { float[] buffer = { 3 }; using ReadWriteBuffer xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer); - static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + var shader = new ReadmeSample_Shader { B = xBuffer }; - void Kernel(ThreadIds id) - { - int offset = id.X + id.Y * 1; - float pow = Hlsl.Pow(xBuffer[offset], 2); // 9 - xBuffer[offset] = Sigmoid(pow); // 0.9998766 - } - - Gpu.Default.For(1, Kernel); + Gpu.Default.For(1, shader); float[] result = xBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/StaticMethodsTests.cs b/tests/ComputeSharp.Tests/StaticMethodsTests.cs index 3efd02a7..ee321748 100644 --- a/tests/ComputeSharp.Tests/StaticMethodsTests.cs +++ b/tests/ComputeSharp.Tests/StaticMethodsTests.cs @@ -1,5 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests @@ -12,6 +14,11 @@ namespace ComputeSharp.Tests [Pure] public static float Square(float x) => x * x; + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static float SquareWithAttributes(float x) => x * x; + [Pure] public static float Negate(float x) => -x; @@ -33,36 +40,72 @@ namespace ComputeSharp.Tests [TestCategory("StaticMethods")] public class StaticMethodsTests { + private struct FloatToFloatFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Square(3); + } + } + [TestMethod] public void FloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Square(3)); + var shader = new FloatToFloatFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct InternalFloatToFloatFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.InternalSquare(3); + } + } + [TestMethod] public void InternalFloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.InternalSquare(3)); + var shader = new InternalFloatToFloatFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct FloatToFloat4Func_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Range(3); + } + } + [TestMethod] public void FloatToFloat4Func() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Range(3)); + var shader = new FloatToFloat4Func_Shader { B = buffer }; + + Gpu.Default.For(1, shader); Float4[] result = buffer.GetData(); @@ -72,37 +115,73 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0].W - 6) < 0.0001f); } + private struct Float4ToIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14)); + } + } + [TestMethod] public void Float4ToIntFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14))); + var shader = new Float4ToIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); int[] result = buffer.GetData(); Assert.IsTrue(result[0] == 20); } + private struct IntToOutIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + StaticMethodsContainer.Assign(7, out B[0]); + } + } + [TestMethod] public void IntToOutIntFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => StaticMethodsContainer.Assign(7, out buffer[0])); + var shader = new IntToOutIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); int[] result = buffer.GetData(); Assert.IsTrue(result[0] == 7); } + private struct IntToRefIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + StaticMethodsContainer.ReadAndSquare(ref B[0]); + } + } + [TestMethod] public void IntToRefIntFunc() { int[] data = { 3 }; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(data); - Gpu.Default.For(1, id => StaticMethodsContainer.ReadAndSquare(ref buffer[0])); + var shader = new IntToRefIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); buffer.GetData(data); diff --git a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs index bf5ceb57..e785b42b 100644 --- a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs +++ b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs @@ -44,60 +44,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticProperties")] public class StaticPropertiesTests { + private struct StaticReadonlyScalarPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.StaticFloat; + var shader = new StaticScalarPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarPropertyRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarPropertyRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat; + var shader = new StaticScalarPropertyRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.ReadonlyVector2.X; + else B[1] = StaticPropertiesContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.ReadonlyVector2.X; - else buffer[1] = StaticPropertiesContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -105,18 +142,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticVector2.X; + else B[1] = StaticPropertiesContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticVector2.X; - else buffer[1] = StaticPropertiesContainer.StaticVector2.Y; - }; + var shader = new StaticVectorPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -124,18 +168,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticBuffer[0]; + else B[1] = StaticPropertiesContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticBuffer[0]; - else buffer[1] = StaticPropertiesContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticPropertiesContainer.StaticBuffer.GetData(); @@ -146,14 +197,24 @@ namespace ComputeSharp.Tests public static int SomeNumber = 7; + private struct StaticLocalScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = SomeNumber; + } + } + [TestMethod] public void StaticLocalScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = SomeNumber; + var shader = new StaticLocalScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); int[] result = buffer.GetData(); From bae73b562c10ce553e7c630bf667eb94944c78da Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 02:44:11 +0200 Subject: [PATCH 15/39] Updated ComputeSharp sample --- .../HlslBokehBlurProcessor{TPixel}.cs | 86 +++++++++++++++---- .../HlslGaussianBlurProcessor{TPixel}.cs | 82 ++++++++++++++---- 2 files changed, 136 insertions(+), 32 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index ea2b0df7..cc432f8b 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -292,6 +292,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( ReadOnlyBuffer source, ReadWriteBuffer target, @@ -299,20 +300,44 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new VerticalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadOnlyBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; + int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY); + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); Vector4 color = source[offsetY * width + offsetX]; Vector2 factors = kernel[i]; @@ -321,10 +346,10 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.Y * color; } - int offsetXY = id.Y * width * 2 + id.X * 2; + int offsetXY = ids.Y * width * 2 + ids.X * 2; target[offsetXY] = real; target[offsetXY + 1] = imaginary; - }); + } } /// @@ -335,6 +360,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The with the values for the current complex kernel /// The weight factor for the real component of the complex pixel values /// The weight factor for the imaginary component of the complex pixel values + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolutionAndAccumulatePartials( ReadWriteBuffer source, ReadWriteBuffer target, @@ -344,17 +370,45 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new HorizontalConvolutionAndAccumulatePartialsProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + z = z, + w = w, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + public float z; + public float w; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; - int offsetY = Hlsl.Clamp(id.Y, 0, maxY); + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { @@ -368,8 +422,8 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.X * sourceImaginary + factors.Y * sourceReal; } - target[id.Y * width + id.X] += real * z + imaginary * w; - }); + target[ids.Y * width + ids.X] += real * z + imaginary * w; + } } /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 274f3228..6201af7e 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -111,6 +111,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( ReadWriteBuffer source, ReadWriteBuffer target, @@ -118,28 +119,52 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new VerticalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; + int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY); + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); Vector4 color = source[offsetY * width + offsetX]; result += kernel[i] * color; } - int offsetXY = id.Y * width + id.X; + int offsetXY = ids.Y * width + ids.X; target[offsetXY] = result; - }); + } } /// @@ -148,6 +173,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolution( ReadWriteBuffer source, ReadWriteBuffer target, @@ -155,16 +181,40 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new HorizontalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct HorizontalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; - int offsetY = Hlsl.Clamp(id.Y, 0, maxY); + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); int offsetXY; for (int i = 0; i < kernelLength; i++) @@ -176,9 +226,9 @@ namespace ComputeSharp.BokehBlur.Processors result += kernel[i] * color; } - offsetXY = id.Y * width + id.X; + offsetXY = ids.Y * width + ids.X; target[offsetXY] = result; - }); + } } /// From b457c994576f092049db4f14beedb6d22250087e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 02:51:24 +0200 Subject: [PATCH 16/39] Refactored benchmark kernel --- samples/ComputeSharp.Benchmark/Dnn.cs | 50 +++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Dnn.cs index 38f110e6..904ddd78 100644 --- a/samples/ComputeSharp.Benchmark/Dnn.cs +++ b/samples/ComputeSharp.Benchmark/Dnn.cs @@ -61,24 +61,60 @@ namespace ComputeSharp.Benchmark /// The weights tensor /// The bias tensor /// The result tensor + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void FullyConnectedForwardGpu( int c, int n, int m, int p, ReadOnlyBuffer x, ReadOnlyBuffer w, ReadOnlyBuffer b, ReadWriteBuffer y) { - void Kernel(ThreadIds id) + Gpu.Default.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y)); + } + + /// + /// Kernel for + /// + private readonly struct FullyConnectedForwardKernel : IComputeShader + { + private readonly int n; + private readonly int m; + private readonly int p; + + private readonly ReadOnlyBuffer x; + private readonly ReadOnlyBuffer w; + private readonly ReadOnlyBuffer b; + private readonly ReadWriteBuffer y; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public FullyConnectedForwardKernel( + int n, + int m, + int p, + ReadOnlyBuffer x, + ReadOnlyBuffer w, + ReadOnlyBuffer b, + ReadWriteBuffer y) { - int x_offset = id.X * n * p + id.Y * m; + this.n = n; + this.m = m; + this.p = p; + this.x = x; + this.w = w; + this.b = b; + this.y = y; + } + + /// + public void Execute(ThreadIds ids) + { + int x_offset = ids.X * n * p + ids.Y * m; float result = 0f; for (int k = 0; k < m; k++) { - result += x[x_offset + k] * w[k * p + id.Z]; + result += x[x_offset + k] * w[k * p + ids.Z]; } - y[id.X * n * p + id.Y * p + id.Z] = result + b[id.Z]; - }; - - Gpu.Default.For(c, n, p, Kernel); + y[ids.X * n * p + ids.Y * p + ids.Z] = result + b[ids.Z]; + } } } } From bc49147e8e77d37ef99fad81cfc4f637cd3c4656 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 02:57:59 +0200 Subject: [PATCH 17/39] Fixed shader not loading non public instance members --- src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 5b52b14b..761c23b7 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -125,7 +125,7 @@ namespace ComputeSharp.Shaders.Translation /// The boxed instance to use to build the shader private void LoadFieldsInfo(object shader) { - IReadOnlyList shaderFields = typeof(T).GetFields().ToArray(); + IReadOnlyList shaderFields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).ToArray(); if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); From 6d27a2c1c194e4ed53a413af4551f44b339c6689 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 02:58:18 +0200 Subject: [PATCH 18/39] Refactored main sample --- samples/ComputeSharp.Sample/Program.cs | 30 +++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/samples/ComputeSharp.Sample/Program.cs b/samples/ComputeSharp.Sample/Program.cs index f94bc6d1..5d2cfcf5 100644 --- a/samples/ComputeSharp.Sample/Program.cs +++ b/samples/ComputeSharp.Sample/Program.cs @@ -27,11 +27,7 @@ namespace ComputeSharp.Sample using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array); // Run the shader - Gpu.Default.For(100, id => - { - int offset = id.X + id.Y * width; - gpuBuffer[offset] *= 2; - }); + Gpu.Default.For(100, new MainKernel(width, gpuBuffer)); // Get the data back gpuBuffer.GetData(array); @@ -42,6 +38,30 @@ namespace ComputeSharp.Sample Console.WriteLine("=================================================="); } + /// + /// Kernel for + /// + private readonly struct MainKernel : IComputeShader + { + private readonly int width; + + private readonly ReadWriteBuffer buffer; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public MainKernel(int width, ReadWriteBuffer buffer) + { + this.width = width; + this.buffer = buffer; + } + + /// + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * width; + buffer[offset] *= 2; + } + } + /// /// Prints a matrix in a properly formatted way /// From 32ca76c5357580e450213fdade8fa559e7e01aec Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 03:01:41 +0200 Subject: [PATCH 19/39] Removed unnecessary code --- src/ComputeSharp.Shaders/ShaderRunner.cs | 130 ------- .../Translation/Models/CachedShader.cs | 31 -- .../Translation/ShaderHashCodeProvider.cs | 116 ------ .../Translation/ShaderLoader.IL.cs | 170 --------- .../Translation/ShaderLoader.cs | 329 ------------------ .../Extensions/GraphicsDeviceExtensions.cs | 47 +-- 6 files changed, 1 insertion(+), 822 deletions(-) delete mode 100644 src/ComputeSharp.Shaders/ShaderRunner.cs delete mode 100644 src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs delete mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs delete mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader.cs diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs deleted file mode 100644 index 090a474e..00000000 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ /dev/null @@ -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 -{ - /// - /// A responsible for performing all the necessary operations to compile and run a compute shader - /// - internal static class ShaderRunner - { - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// 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 - /// The input representing the compute shader to run - public static void Run(GraphicsDevice device, int x, int y, int z, Action 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); - } - - /// - /// The mapping used to cache and reuse compiled shaders - /// - private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>(); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// 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 - /// The number of threads in each thread group for the X axis - /// The number of threads in each thread group for the Y axis - /// The number of threads in each thread group for the Z axis - /// The input representing the compute shader to run - public static void Run( - GraphicsDevice device, - int x, int y, int z, - int threadsX, int threadsY, int threadsZ, - Action 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 resources = dispatchData.Resources; - for (int i = 0; i < resources.Length; i++) - { - commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); - } - - // Initialize the loop targets - Span 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(); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs deleted file mode 100644 index 8c5cf20c..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Vortice.Direct3D12; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains info on a cached shader - /// - internal readonly struct CachedShader - { - /// - /// The instance with the shader metadata - /// - public readonly ShaderLoader Loader; - - /// - /// The compiled shader bytecode - /// - public readonly ShaderBytecode Bytecode; - - /// - /// Creates a new instance with the specified parameters - /// - /// The instance with the shader metadata - /// The compiled shader bytecode - public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) - { - Loader = loader; - Bytecode = bytecode; - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index e42f0681..feaf9efe 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -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 /// internal static class ShaderHashCodeProvider { - /// - /// The mapping of hashcodes to aggregate hashing functions - /// - private static readonly Dictionary HasherMapping = new Dictionary(); - /// /// A type containing static info for a given shader type /// @@ -123,115 +117,5 @@ namespace ComputeSharp.Shaders.Translation il.Emit(OpCodes.Ret); }); } - - /// - /// Gets a unique hashcode for the input shader closure - /// - /// The input representing the shader to run - [Pure] - public static int GetHashCode(Action 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; - } - - /// - /// A that represents an aggregate hash function for a given instance - /// - /// The initial hash value - /// The closure instance to use to compute the final hash value - /// The final hash value for the input closure - private delegate int Hasher(int hash, object instance); - - /// - /// Builds a new instance for the target and sequence of values - /// - /// The declaring to analyze - /// The list of captured fields to inspect - [Pure] - private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection fieldInfos) - { - return DynamicMethod.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); - }); - } - - /// - /// A method that checks whether an input is supported in HLSL - /// - /// The input instance to check - [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)); - } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs deleted file mode 100644 index c1aad0c1..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ /dev/null @@ -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 -{ - /// - internal sealed partial class ShaderLoader - { - /// - /// The number of captured graphics resources (buffers) - /// - private int _ResourcesCount; - - /// - /// The size in bytes of the buffer with the captured variables - /// - private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count - - // The cached loader method - private DispatchDataLoader? _DispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader - /// - private readonly List _CapturedMembers = new List(); - - /// - /// A that loads all the captured members from a shader closure - /// - /// The shader closure 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(object obj, ref GraphicsResource r0, ref byte r1); - - /// - /// Gets a new instance with all the captured data for the current shader instance - /// - /// The input 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(Action action, int x, int y, int z) - { - // Resources and variables buffers - GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); - byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); - ref GraphicsResource r0 = ref resources[0]; - ref byte r1 = ref variables[0]; - - // 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 - _DispatchDataLoader!(action.Target, ref r0, ref r1); - - return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); - } - - /// - /// Builds a new instance that loads the dispatch data for the current shader type - /// - 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 loaded = new HashSet(new[] { 0 }); - - // Build the dynamic IL method - _DispatchDataLoader = DynamicMethod.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(_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); - }); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs deleted file mode 100644 index 9c8df435..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ /dev/null @@ -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 -{ - /// - /// A responsible for loading and processing instances - /// - internal sealed partial class ShaderLoader - { - /// - /// The that represents the shader to load - /// - private readonly Action Action; - - /// - /// Creates a new with the specified parameters - /// - /// The to use to build the shader - private ShaderLoader(Action action) - { - Action = action; - ShaderType = action.Method.DeclaringType; - } - - /// - /// The number of constant buffers to define in the shader - /// - private int _ConstantBuffersCount; - - /// - /// The number of readonly buffers to define in the shader - /// - private int _ReadOnlyBuffersCount; - - /// - /// The number of read write buffers to define in the shader - /// - private int _ReadWriteBuffersCount; - - /// - /// Gets the closure for the field - /// - public Type ShaderType { get; } - - /// - /// The of items that are required to load the captured values - /// - private readonly List DescriptorRanges = new List(); - - private RootParameter1[] _RootParameters; - - /// - /// Gets the array for the current shader - /// - public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray(); - - private readonly List _BuffersList = new List(); - - /// - /// Gets the collection of items for the shader fields - /// - public IReadOnlyList BuffersList => _BuffersList; - - private readonly List _FieldsList = new List(); - - /// - /// Gets the collection of items for the shader fields - /// - public IReadOnlyList FieldsList => _FieldsList; - - /// - /// 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; } - - private readonly List _FunctionsList = new List(); - - /// - /// Gets the collection of items for the shader - /// - public IReadOnlyList FunctionsList => _FunctionsList; - - private readonly List _LocalFunctionsList = new List(); - - /// - /// Gets the collection of items for the shader - /// - public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; - - /// - /// 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(); - @this.BuildDispatchDataLoader(); - - return @this; - } - - /// - /// Loads the fields info for the current shader being loaded - /// - private void LoadFieldsInfo() - { - IReadOnlyList 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); - } - } - - /// - /// Loads a specified and adds it to the shader model - /// - /// The target to load - /// The optional explicit name to use for the field - /// The list of parent fields to reach the current from a given - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? 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 updatedParents = parents?.ToList() ?? new List(); - updatedParents.Add(memberInfo); - - // Recurse on the new compiler generated class - IReadOnlyList 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); - } - } - - /// - /// Loads the entry method for the current shader being loaded - /// - 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().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); - } - - /// - /// Loads additional static methods used by the shader - /// - /// The HLSL name of the new method to load - /// The instance for the method to load - 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 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); - } - } -} diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 49f5f7df..7bd3d7e2 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -1,5 +1,4 @@ -using System; -using ComputeSharp.Graphics; +using ComputeSharp.Graphics; using ComputeSharp.Shaders; namespace ComputeSharp @@ -9,50 +8,6 @@ namespace ComputeSharp /// public static class GraphicsDeviceExtensions { - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// The number of iterations to run on the X axis - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, Action action) => ShaderRunner.Run(device, x, 1, 1, action); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// The number of iterations to run on the X axis - /// The number of iterations to run on the Y axis - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, int y, Action action) => ShaderRunner.Run(device, x, y, 1, action); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// 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 - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, int y, int z, Action action) => ShaderRunner.Run(device, x, y, z, action); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// The to use to run the shader - /// 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 - /// The number of threads in each thread group for the X axis - /// The number of threads in each thread group for the Y axis - /// The number of threads in each thread group for the Z axis - /// The input representing the compute shader to run - public static void For( - this GraphicsDevice device, - int x, int y, int z, - int threadsX, int threadsY, int threadsZ, - Action action) => ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, action); - /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// From 028693053f0cc81be744167047362ffc4f13e870 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 13:33:38 +0200 Subject: [PATCH 20/39] Fixed a bug when loading private fields --- src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 761c23b7..d4f925ff 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -125,7 +125,11 @@ namespace ComputeSharp.Shaders.Translation /// The boxed instance to use to build the shader private void LoadFieldsInfo(object shader) { - IReadOnlyList shaderFields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).ToArray(); + IReadOnlyList shaderFields = typeof(T).GetFields( + BindingFlags.Instance | + BindingFlags.Static | + BindingFlags.Public | + BindingFlags.NonPublic).ToArray(); if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); From 717fd71d8c0d12e79567998078a061903f75a09a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 13:34:03 +0200 Subject: [PATCH 21/39] Updated ImageSharp to nightly version --- .../ComputeSharp.ImageProcessing.csproj | 2 +- .../Processors/HlslBokehBlurProcessor.cs | 6 +- .../HlslBokehBlurProcessor{TPixel}.cs | 47 ++++++------ .../Processors/HlslGaussianBlurProcessor.cs | 6 +- .../HlslGaussianBlurProcessor{TPixel}.cs | 72 ++++++++----------- 5 files changed, 57 insertions(+), 76 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index 6bd66e66..b422d295 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -16,7 +16,7 @@ - + diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index c62cd173..2ae2eef1 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,7 +1,6 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -59,9 +58,10 @@ namespace ComputeSharp.BokehBlur.Processors public float Gamma { get; } /// - public IImageProcessor CreatePixelSpecificProcessor(Image source, Rectangle sourceRectangle) where TPixel : struct, IPixel + public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) + where TPixel : unmanaged, IPixel { - return new HlslBokehBlurProcessor(this, source, sourceRectangle); + return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index cc432f8b..00930fd5 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -11,7 +11,6 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -20,7 +19,8 @@ namespace ComputeSharp.BokehBlur.Processors /// /// The pixel format /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve - public sealed class HlslBokehBlurProcessor : IImageProcessor where TPixel : struct, IPixel + public sealed class HlslBokehBlurProcessor : ImageProcessor + where TPixel : unmanaged, IPixel { /// /// The kernel radius @@ -62,24 +62,20 @@ namespace ComputeSharp.BokehBlur.Processors /// private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Vector2[][] Kernels)> Cache = new ConcurrentDictionary<(int, int), (Vector4[], float, Vector2[][])>(); - /// - /// The source instance to modify - /// - private readonly Image Source; - /// /// Initializes a new instance of the class /// /// The defining the processor parameters + /// The configuration which allows altering default behaviour or extending the library /// The source instance to modify /// The source that indicates the area to edit - public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Image source, Rectangle sourceRectangle) + public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { Radius = definition.Radius; KernelSize = Radius * 2 + 1; ComponentsCount = definition.Components; Gamma = definition.Gamma; - Source = source; // Reuse the initialized values from the cache, if possible var parameters = (Radius, ComponentsCount); @@ -259,12 +255,12 @@ namespace ComputeSharp.BokehBlur.Processors } /// - public void Apply() + protected override void OnFrameApply(ImageFrame source) { // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(); + using IMemoryOwner source4 = GetExposedVector4Buffer(source); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); @@ -281,9 +277,11 @@ namespace ComputeSharp.BokehBlur.Processors ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); } - // Apply the inverse gamma exposure pass, and write the final pixel data + // Apply the inverse gamma exposure pass processingBuffer.GetData(source4.Memory.Span); - ApplyInverseGammaExposure(source4); + + // Write the final pixel data + ApplyInverseGammaExposure(source4, source); } /// @@ -429,16 +427,17 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. /// + /// The source image [Pure] - private IMemoryOwner GetExposedVector4Buffer() + private IMemoryOwner GetExposedVector4Buffer(ImageFrame source) { - IMemoryOwner source4 = Source.GetConfiguration().MemoryAllocator.Allocate(Source.Width * Source.Height); + IMemoryOwner source4 = Configuration.MemoryAllocator.Allocate(source.Width * source.Height); float exp = Gamma; int width = Source.Width; - Parallel.For(0, Source.Height, y => + Parallel.For(0, source.Height, y => { - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); + ref TPixel rPixel = ref source.GetPixelRowSpan(y).GetPinnableReference(); ref Vector4 r4 = ref source4.Memory.Span.Slice(y * width).GetPinnableReference(); for (int x = 0; x < width; x++) @@ -458,17 +457,18 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image /// /// The source buffer to read from - private void ApplyInverseGammaExposure(IMemoryOwner sourceValues) + /// The source image + private void ApplyInverseGammaExposure(IMemoryOwner sourceValues, ImageFrame source) { - int width = Source.Width; + int width = source.Width; float expGamma = 1 / Gamma; - Parallel.For(0, Source.Height, y => + Parallel.For(0, source.Height, y => { Vector4 low = Vector4.Zero; var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); + ref TPixel rPixel = ref source.GetPixelRowSpan(y).GetPinnableReference(); ref Vector4 r4 = ref sourceValues.Memory.Span.Slice(y * width).GetPinnableReference(); for (int x = 0; x < width; x++) @@ -483,8 +483,5 @@ namespace ComputeSharp.BokehBlur.Processors } }); } - - /// - public void Dispose() { } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index c32bc696..d628edad 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,7 +1,6 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -48,9 +47,10 @@ namespace ComputeSharp.BokehBlur.Processors public int Radius { get; } /// - public IImageProcessor CreatePixelSpecificProcessor(Image source, Rectangle sourceRectangle) where TPixel : struct, IPixel + public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) + where TPixel : unmanaged, IPixel { - return new HlslGaussianBlurProcessor(this, source, sourceRectangle); + return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 6201af7e..864e221b 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -1,13 +1,12 @@ using System; +using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -15,29 +14,26 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies Gaussian blur processing to an image. /// /// The pixel format. - internal class HlslGaussianBlurProcessor : IImageProcessor where TPixel : struct, IPixel + internal class HlslGaussianBlurProcessor : ImageProcessor + where TPixel : unmanaged, IPixel { /// /// The 1D kernel to apply /// private readonly float[] Kernel; - /// - /// The source instance to modify - /// - private readonly Image Source; - /// /// Initializes a new instance of the class /// /// The defining the processor parameters + /// The configuration which allows altering default behaviour or extending the library /// The source for the current processor instance /// The source area to process for the current processor instance - public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Image source, Rectangle sourceRectangle) + public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { int kernelSize = definition.Radius * 2 + 1; Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); - Source = source; } /// @@ -89,20 +85,31 @@ namespace ComputeSharp.BokehBlur.Processors } /// - public void Apply() + protected override void OnFrameApply(ImageFrame source) { - using Image source = Source.CloneAs(); - Span sourceSpan = MemoryMarshal.Cast(source.GetPixelSpan()); + IMemoryGroup group = source.GetPixelMemoryGroup(); - using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceSpan); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + for (int i = group.Count - 1; i >= 0; i--) + { + Span spanTPixel = group[i].Span; - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer); + using IMemoryOwner group4 = Configuration.MemoryAllocator.Allocate(spanTPixel.Length); - sourceBuffer.GetData(sourceSpan); - WriteResultData(source); + Span spanVector4 = group4.Memory.Span; + + PixelOperations.Instance.ToVector4(Configuration, spanTPixel, spanVector4); + + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer); + + sourceBuffer.GetData(spanVector4); + + PixelOperations.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel); + } } /// @@ -230,28 +237,5 @@ namespace ComputeSharp.BokehBlur.Processors target[offsetXY] = result; } } - - /// - /// Writes the final data to the source image - /// - /// The source to read from - private void WriteResultData(Image image) - { - int width = Source.Width; - - Parallel.For(0, Source.Height, y => - { - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref MemoryMarshal.Cast(image.GetPixelRowSpan(y)).GetPinnableReference(); - - for (int x = 0; x < width; x++) - { - Unsafe.Add(ref rPixel, x).FromVector4(Unsafe.Add(ref r4, x)); - } - }); - } - - /// - public void Dispose() { } } } From 4b79f826b4c418bb3aa8eb4340c69b4542b7f660 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 13:57:29 +0200 Subject: [PATCH 22/39] More code refactorings to image processors --- .../HlslBokehBlurProcessor{TPixel}.cs | 178 +++++++++++++----- .../ComputeSharp.ImageProcessing/Program.cs | 6 +- 2 files changed, 131 insertions(+), 53 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 00930fd5..ae125ced 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -6,9 +6,9 @@ using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Threading.Tasks; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -257,31 +257,36 @@ namespace ComputeSharp.BokehBlur.Processors /// protected override void OnFrameApply(ImageFrame source) { - // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(source); + IMemoryGroup group = source.GetPixelMemoryGroup(); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); - using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); - - ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters - - // Perform two 1D convolutions for each component in the current instance - for (int i = 0; i < Kernels.Length; i++) + for (int i = group.Count - 1; i >= 0; i--) { - kernelBuffer.SetData(Kernels[i]); - Vector4 parameters = Unsafe.Add(ref param0, i); + // Preliminary gamma highlight pass + using IMemoryOwner source4 = GetExposedVector4Buffer(group[i]); - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + + ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters + + // Perform two 1D convolutions for each component in the current instance + for (int j = 0; j < Kernels.Length; j++) + { + kernelBuffer.SetData(Kernels[j]); + Vector4 parameters = Unsafe.Add(ref param0, j); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + } + + // Apply the inverse gamma exposure pass + processingBuffer.GetData(source4.Memory.Span); + + // Write the final pixel data + ApplyInverseGammaExposure(source4.Memory, group[i]); } - - // Apply the inverse gamma exposure pass - processingBuffer.GetData(source4.Memory.Span); - - // Write the final pixel data - ApplyInverseGammaExposure(source4, source); } /// @@ -429,59 +434,134 @@ namespace ComputeSharp.BokehBlur.Processors /// /// The source image [Pure] - private IMemoryOwner GetExposedVector4Buffer(ImageFrame source) + private IMemoryOwner GetExposedVector4Buffer(Memory source) { - IMemoryOwner source4 = Configuration.MemoryAllocator.Allocate(source.Width * source.Height); + IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); + float exp = Gamma; int width = Source.Width; + int height = source.Length / width; - Parallel.For(0, source.Height, y => + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration)); + + return target; + } + + /// + /// The processor for + /// + private readonly struct GetExposedVector4BufferProcessor : IRowOperation + { + private readonly int width; + private readonly float exp; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public GetExposedVector4BufferProcessor( + int width, + float exp, + Memory source, + Memory target, + Configuration configuration) { - ref TPixel rPixel = ref source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref source4.Memory.Span.Slice(y * width).GetPinnableReference(); + this.width = width; + this.exp = exp; + this.source = source; + this.target = target; + this.configuration = configuration; + } - for (int x = 0; x < width; x++) + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowTPixel = source.Span.Slice(offset, width); + Span rowVector4 = target.Span.Slice(offset, width); + + PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); + + foreach (ref Vector4 v in rowVector4) { - ref Vector4 v = ref Unsafe.Add(ref r4, x); - v = Unsafe.Add(ref rPixel, x).ToVector4(); v.X = MathF.Pow(v.X, exp); v.Y = MathF.Pow(v.Y, exp); v.Z = MathF.Pow(v.Z, exp); } - }); - - return source4; + } } /// /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image /// - /// The source buffer to read from - /// The source image - private void ApplyInverseGammaExposure(IMemoryOwner sourceValues, ImageFrame source) + /// The source buffer to read from + /// The target image + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyInverseGammaExposure(Memory source, Memory target) { - int width = source.Width; + int width = Source.Width; + int height = source.Length / width; float expGamma = 1 / Gamma; - Parallel.For(0, source.Height, y => + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration)); + } + + /// + /// The processor for + /// + private readonly struct ApplyInverseGammaExposureProcessor : IRowOperation + { + private readonly int width; + private readonly float exp; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ApplyInverseGammaExposureProcessor( + int width, + float exp, + Memory source, + Memory target, + Configuration configuration) { + this.width = width; + this.exp = exp; + this.source = source; + this.target = target; + this.configuration = configuration; + } + + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowVector4 = source.Span.Slice(offset, width); + Span rowTPixel = target.Span.Slice(offset, width); + Vector4 low = Vector4.Zero; var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - ref TPixel rPixel = ref source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref sourceValues.Memory.Span.Slice(y * width).GetPinnableReference(); - - for (int x = 0; x < width; x++) + foreach (ref Vector4 v in rowVector4) { - Vector4 v = Unsafe.Add(ref r4, x); var clamp = Vector4.Clamp(v, low, high); - v.X = MathF.Pow(clamp.X, expGamma); - v.Y = MathF.Pow(clamp.Y, expGamma); - v.Z = MathF.Pow(clamp.Z, expGamma); - - Unsafe.Add(ref rPixel, x).FromVector4(v); + v.X = MathF.Pow(clamp.X, exp); + v.Y = MathF.Pow(clamp.Y, exp); + v.Z = MathF.Pow(clamp.Z, exp); } - }); + + PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + } } } } diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs index 9aaac4e1..91f52ca5 100644 --- a/samples/ComputeSharp.ImageProcessing/Program.cs +++ b/samples/ComputeSharp.ImageProcessing/Program.cs @@ -3,7 +3,6 @@ using System.IO; using System.Reflection; using ComputeSharp.BokehBlur.Processors; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors; @@ -15,7 +14,7 @@ namespace ComputeSharp.ImageProcessing { Console.WriteLine(">> Loading image"); string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg"); - using Image image = Image.Load(path); + using Image image = Image.Load(path); // Apply a series of processors and save the results foreach (var effect in new (string Name, IImageProcessor Processor)[] @@ -25,8 +24,7 @@ namespace ComputeSharp.ImageProcessing }) { Console.WriteLine($">> Applying {effect.Name}"); - using Image copy = image.Clone(); - copy.Mutate(c => c.ApplyProcessor(effect.Processor)); + using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor)); Console.WriteLine($">> Saving {effect.Name} to disk"); string targetPath = Path.Combine( From 6e959a14c305d2f09abc2147438bd4d749a019e5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 14:16:22 +0200 Subject: [PATCH 23/39] Updated README with new syntax --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 9548b097..5e07cac5 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,27 @@ More details available [here](https://www.nuget.org/packages/ComputeSharp/). The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back. ```C# +// Define a simple shader +public readonly struct MyShader : IComputeShader +{ + public readonly ReadWriteBuffer buffer; + + public MyShader(ReadWriteBuffer buffer) + { + this.buffer = buffer; + } + + public void Execute(ThreadIds ids) + { + buffer[ids.X] = ids.X; + } +} + // Allocate a writeable buffer on the GPU, with the contents of the array using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); // Run the shader -Gpu.Default.For(1000, id => buffer[id.X] = id.X); +Gpu.Default.For(1000, new MyShader(buffer)); // Get the data back float[] array = buffer.GetData(); @@ -69,9 +85,41 @@ There are a number of extension APIs for the `GraphicsDevice` class that can be ## Advanced usage -**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. +**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. ```C# +// Define a class with some utility static functions +public static class Activations +{ + public static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); +} + +// Define the shader +public readonly struct ActivationShader : IComputeShader +{ + private readonly int width; + + public readonly ReadOnlyBuffer x; + public readonly ReadWriteBuffer y; + + public ActivationShader( + int width, + ReadOnlyBuffer x, + ReadWriteBuffer y) + { + this.width = width; + this.x = x; + this.y = y; + } + + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * width; + float pow = Hlsl.Pow(x[offset], 2); + y[offset] = Activations.Sigmoid(pow); + } +} + int height = 10, width = 10; float[] x = new float[height * width]; // Array to sum to y float[] y = new float[height * width]; // Result array (assume both had some values) @@ -79,18 +127,8 @@ float[] y = new float[height * width]; // Result array (assume both had some val using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x); using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); -static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); - -// Shader body -void Kernel(ThreadIds id) -{ - int offset = id.X + id.Y * width; - float pow = Hlsl.Pow(xBuffer[offset], 2); - yBuffer[offset] = Sigmoid(pow); -} - // Run the shader -Gpu.Default.For(width, height, Kernel); +Gpu.Default.For(width, height, new ActivationShader(width, xBuffer, yBuffer)); // Get the data back and write it to the y array yBuffer.GetData(y); @@ -102,7 +140,7 @@ The **ComputeSharp** library requires .NET Standard 2.1 support, and it is avail - .NET Core >= 3.0 - Windows (x86 or x64) -Additionally, you need an IDE with .NET Core 3.0 and C# 8.0 support to compile the library and samples on your PC. +Additionally, you need an IDE with .NET Core 3.1 and C# 8.0 support to compile the library and samples on your PC. # Special thanks From ac079c8cd150e5eee0ffbbeea834d4ae81974a1b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 14:18:41 +0200 Subject: [PATCH 24/39] Updated target frameworks and NuGet packages --- .../ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj | 4 ++-- samples/ComputeSharp.Benchmark/DnnBenchmark.cs | 2 +- .../ComputeSharp.ImageProcessing.csproj | 2 +- samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj | 2 +- .../ComputeSharp.Tests.Internals.csproj | 8 ++++---- tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj | 8 ++++---- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index f93e3c60..0c070ff3 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -2,11 +2,11 @@ Exe - netcoreapp3.0 + netcoreapp3.1 - + diff --git a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs b/samples/ComputeSharp.Benchmark/DnnBenchmark.cs index 7cdcd870..f7fc3936 100644 --- a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/DnnBenchmark.cs @@ -130,7 +130,7 @@ namespace ComputeSharp.Benchmark /// /// Runs a fully connected forward operation on the CPU /// - [Benchmark] + [Benchmark(Baseline = true)] public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y); /// diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index b422d295..df1e75a1 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp3.0 + netcoreapp3.1 diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj index bfb20336..430f758a 100644 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp3.0 + netcoreapp3.1 diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 6f0f9fe8..518343ba 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -1,15 +1,15 @@  - netcoreapp3.0 + netcoreapp3.1 false - - - + + + diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index 6f0f9fe8..518343ba 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -1,15 +1,15 @@  - netcoreapp3.0 + netcoreapp3.1 false - - - + + + From 40629dd4e908494d9604b189eae516bb9a586969 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 15:16:43 +0200 Subject: [PATCH 25/39] Updated NuGet packages in main projects --- src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj | 4 ++-- src/ComputeSharp.Graphics/GraphicsDevice.cs | 4 ++-- src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs | 4 ++-- src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 873afc89..eb97cc79 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 4275c34e..a4177ccc 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -2,9 +2,9 @@ using System.Threading; using ComputeSharp.Graphics.Commands; using Vortice.Direct3D12; -using Vortice.DirectX.Direct3D; using Vortice.DXGI; using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using Direct3DFeatureLevel = Vortice.Direct3D.FeatureLevel; namespace ComputeSharp.Graphics { @@ -16,7 +16,7 @@ namespace ComputeSharp.Graphics /// /// Gets the value that needs to be supported by GPUs mapped to a instance /// - public const FeatureLevel FeatureLevel = Vortice.DirectX.Direct3D.FeatureLevel.Level_12_1; + public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1; /// /// The instance used to wait for completion when executing commands diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index 70537bb2..be1af1ef 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; +using Vortice.Direct3D; using Vortice.Direct3D12; -using Vortice.DirectX.Direct3D; using Vortice.DXGI; namespace ComputeSharp.Graphics.Helpers @@ -23,7 +23,7 @@ namespace ComputeSharp.Graphics.Helpers { List<(ID3D12Device, AdapterDescription)> devices = new List<(ID3D12Device, AdapterDescription)>(); - foreach (IDXGIAdapter1 adapter in factory.EnumAdapters1()) + foreach (IDXGIAdapter1 adapter in factory.Adapters1) { if (adapter.Description.DedicatedVideoMemory == 0) continue; if (D3D12.D3D12CreateDevice(adapter, FeatureLevel.Level_12_0, out ID3D12Device device).Success) diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 555630bc..a46b9c92 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -7,11 +7,11 @@ - - + + - - + + From e2ccda0144db28a5fa4155fe22a29524d03ed98b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 13 Apr 2020 15:19:16 +0200 Subject: [PATCH 26/39] Made Gpu.Default property thread-safe --- src/ComputeSharp/Gpu.cs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 75507597..26ae6399 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -21,6 +21,11 @@ namespace ComputeSharp { Devices = DeviceHelper.QueryAllSupportedDevices(); IsSupported = Devices.Any(); + + if (IsSupported) + { + _Default = new GraphicsDevice(Devices[0].Device, Devices[0].Description); + } } /// @@ -28,25 +33,17 @@ namespace ComputeSharp /// private static readonly IReadOnlyList<(ID3D12Device Device, AdapterDescription Description)> Devices; - /// - /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) - /// - public static bool IsSupported { get; } - - private static GraphicsDevice? _Default; + private static readonly GraphicsDevice? _Default; /// /// Gets the default instance for the current machine /// - public static GraphicsDevice Default - { - get - { - if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine"); + public static GraphicsDevice Default => _Default ?? throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - return _Default ??= new GraphicsDevice(Devices[0].Device, Devices[0].Description); - } - } + /// + /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) + /// + public static bool IsSupported { get; } /// /// Enumerates all the available objects on the current machine From 7fcf755e6492b577cac096075671b3e3a17fd0f9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 14 Apr 2020 12:30:10 +0200 Subject: [PATCH 27/39] Minor code refactoring --- .../Buffers/Abstract/HlslBuffer{T}.cs | 12 ++++++------ .../Buffers/Abstract/HlslStructuredBuffer{T}.cs | 4 ++-- .../Buffers/ConstantBuffer{T}.cs | 13 +++++++------ .../Helpers/MemoryHelper.cs | 16 ++++++++-------- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 76b0e267..4b938cca 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -71,18 +71,18 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public void SetData(T[] array, int offset, int count) => SetData(array.AsSpan(), offset, count); /// - /// Writes the contents of a given to the current instance + /// Writes the contents of a given to the current instance /// - /// The input to read data from - public void SetData(Span span) => SetData(span, 0, Size); + /// The input to read data from + public void SetData(ReadOnlySpan span) => SetData(span, 0, Size); /// - /// Writes the contents of a given to a specified area of the current instance + /// Writes the contents of a given to a specified area of the current instance /// - /// The input to read data from + /// The input to read data from /// The offset to start writing data to /// The number of items to write - public abstract void SetData(Span span, int offset, int count); + public abstract void SetData(ReadOnlySpan span, int offset, int count); /// /// Writes the contents of a given to the current instance diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs index 92ad8911..657e1f71 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -36,12 +36,12 @@ namespace ComputeSharp.Graphics.Buffers.Abstract } /// - public override void SetData(Span span, int offset, int count) + public override void SetData(ReadOnlySpan span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer); transferBuffer.Map(); - MemoryHelper.Copy(span, 0, transferBuffer.MappedResource, 0, count); + MemoryHelper.Copy(span, transferBuffer.MappedResource, 0, count); transferBuffer.Unmap(); using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 591d6dda..8ff900c1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -2,6 +2,7 @@ using System.Buffers; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.Exceptions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; @@ -78,15 +79,15 @@ namespace ComputeSharp } /// - public override void SetData(Span span, int offset, int count) + public override void SetData(ReadOnlySpan span, int offset, int count) { if (IsPaddingPresent) { // Create the temporary array byte[] temporaryArray = ArrayPool.Shared.Rent(count * PaddedElementSizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Array pool arrays can be longer - ref T tin = ref span.GetPinnableReference(); - ref byte tout = ref temporarySpan.GetPinnableReference(); + ReadOnlySpan temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Array pool arrays can be longer + ref T tin = ref MemoryMarshal.GetReference(span); + ref byte tout = ref MemoryMarshal.GetReference(temporarySpan); // Copy the input data to the temporary array and add the padding for (int i = 0; i < count; i++) @@ -97,7 +98,7 @@ namespace ComputeSharp // Copy the padded data to the GPU Map(); - MemoryHelper.Copy(temporarySpan, 0, MappedResource, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); + MemoryHelper.Copy(temporarySpan, MappedResource, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); Unmap(); ArrayPool.Shared.Return(temporaryArray); @@ -106,7 +107,7 @@ namespace ComputeSharp { // Directly copy the input span if there is no padding Map(); - MemoryHelper.Copy(span, 0, MappedResource, offset, count); + MemoryHelper.Copy(span, MappedResource, offset, count); Unmap(); } } diff --git a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs index 560db122..b9911acb 100644 --- a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs @@ -9,19 +9,19 @@ namespace ComputeSharp.Graphics.Helpers internal static class MemoryHelper { /// - /// Copies the content of a to the area pointed by an input value + /// Copies the content of a to the area pointed by an input value /// - /// The type of values in the input - /// The source to read - /// The source offset to start reading data from + /// The type of values in the input + /// The source to read /// The for the destination memory area /// The destination offset to start writing data to /// The total number of items to copy - public static unsafe void Copy(Span source, int sourceOffset, IntPtr destination, int destinationOffset, int count) where T : unmanaged + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Copy(ReadOnlySpan source, IntPtr destination, int destinationOffset, int count) where T : unmanaged { - ref T rout = ref Unsafe.AsRef(destination.ToPointer()); - void* target = Unsafe.AsPointer(ref Unsafe.Add(ref rout, destinationOffset)); - source.Slice(sourceOffset, count).CopyTo(new Span(target, count)); + T* p = (T*)destination.ToPointer() + destinationOffset; + + source.CopyTo(new Span(p, count)); } /// From fa779e678d614d0a657db23c4607802a5c878592 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 14 Apr 2020 12:44:44 +0200 Subject: [PATCH 28/39] Code refactoring, improved resource mapping --- .../Buffers/Abstract/GraphicsResource.cs | 58 +++++++++++++------ .../Abstract/HlslStructuredBuffer{T}.cs | 13 +++-- .../Buffers/ConstantBuffer{T}.cs | 26 +++++---- 3 files changed, 61 insertions(+), 36 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs index 2f65e9a8..6e266844 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; using Vortice.Direct3D12; namespace ComputeSharp.Graphics.Buffers.Abstract @@ -22,11 +23,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// public GraphicsDevice GraphicsDevice { get; } - /// - /// Gets the associated to the currently mapped resource - /// - internal IntPtr MappedResource { get; private set; } - /// /// Gets the object currently mapped /// @@ -45,24 +41,50 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// Maps the current resource to a specified subresource /// - /// An for the newly mapped resource - internal IntPtr Map() + /// A instance representing the mapped resource + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal MappedResource MapResource() { - IntPtr mappedResource = NativeResource?.Map(0) ?? throw new InvalidOperationException("Missing resource"); - MappedResource = mappedResource; - return mappedResource; - } + var resource = NativeResource ?? throw new InvalidOperationException("Missing resource"); - /// - /// Unmaps a subresource specified by a given index - /// - internal void Unmap() - { - NativeResource?.Unmap(0); - MappedResource = IntPtr.Zero; + return new MappedResource(resource); } /// public virtual void Dispose() => NativeResource?.Dispose(); + + /// + /// A type representing a mapped memory resource + /// + internal readonly ref struct MappedResource + { + /// + /// The target to map + /// + private readonly ID3D12Resource Resource; + + /// + /// The pointer to the mapped resource + /// + public readonly IntPtr Pointer; + + /// + /// Creates a new instance for a given value + /// + /// The input instance to map + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public MappedResource(ID3D12Resource resource) + { + Resource = resource; + Pointer = resource.Map(0); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + Resource.Unmap(0); + } + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs index 657e1f71..c5db3eb5 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -30,9 +30,9 @@ namespace ComputeSharp.Graphics.Buffers.Abstract copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); copyCommandList.Flush(); - transferBuffer.Map(); - MemoryHelper.Copy(transferBuffer.MappedResource, 0, span, 0, count); - transferBuffer.Unmap(); + using MappedResource resource = transferBuffer.MapResource(); + + MemoryHelper.Copy(resource.Pointer, 0, span, 0, count); } /// @@ -40,9 +40,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer); - transferBuffer.Map(); - MemoryHelper.Copy(span, transferBuffer.MappedResource, 0, count); - transferBuffer.Unmap(); + using (MappedResource resource = transferBuffer.MapResource()) + { + MemoryHelper.Copy(span, resource.Pointer, 0, count); + } using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 8ff900c1..14371062 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -53,9 +53,10 @@ namespace ComputeSharp Span temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Copy the padded data to the temporary array - Map(); - MemoryHelper.Copy(MappedResource, offset * PaddedElementSizeInBytes, temporarySpan, 0, count * PaddedElementSizeInBytes); - Unmap(); + using (MappedResource resource = MapResource()) + { + MemoryHelper.Copy(resource.Pointer, offset * PaddedElementSizeInBytes, temporarySpan, 0, count * PaddedElementSizeInBytes); + } ref byte tin = ref temporarySpan.GetPinnableReference(); ref T tout = ref span.GetPinnableReference(); @@ -72,9 +73,9 @@ namespace ComputeSharp else { // Directly copy the data back if there is no padding - Map(); - MemoryHelper.Copy(MappedResource, offset, span, 0, count); - Unmap(); + using MappedResource resource = MapResource(); + + MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); } } @@ -97,18 +98,19 @@ namespace ComputeSharp } // Copy the padded data to the GPU - Map(); - MemoryHelper.Copy(temporarySpan, MappedResource, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); - Unmap(); + using (MappedResource resource = MapResource()) + { + MemoryHelper.Copy(temporarySpan, resource.Pointer, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); + } ArrayPool.Shared.Return(temporaryArray); } else { // Directly copy the input span if there is no padding - Map(); - MemoryHelper.Copy(span, MappedResource, offset, count); - Unmap(); + using MappedResource resource = MapResource(); + + MemoryHelper.Copy(span, resource.Pointer, offset, count); } } From 35fb4ea6706ffd7fd07c299ed07fc6204ce4169c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 14 Apr 2020 13:39:46 +0200 Subject: [PATCH 29/39] Fixed an XML comment --- src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index feaf9efe..c0421fde 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -81,7 +81,7 @@ namespace ComputeSharp.Shaders.Translation where T : struct, IComputeShader; /// - /// Builds a new instance for the target and sequence of values + /// 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 From b10189ba6f5f9abc92e03283f68e8481beb8ae71 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 14 Apr 2020 13:44:20 +0200 Subject: [PATCH 30/39] Updated .nuspec file --- src/ComputeSharp/ComputeSharp.nuspec | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp/ComputeSharp.nuspec b/src/ComputeSharp/ComputeSharp.nuspec index 2f661804..7bbc3e6c 100644 --- a/src/ComputeSharp/ComputeSharp.nuspec +++ b/src/ComputeSharp/ComputeSharp.nuspec @@ -2,7 +2,7 @@ ComputeSharp - 1.3.1 + 2.0.0 ComputeSharp Sergio Pedri Sergio Pedri @@ -12,17 +12,18 @@ false A .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders Bug fixes, NuGet updates - Copyright (c) 2019 Sergio Pedri + Copyright (c) 2020 Sergio Pedri dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu - - - - - - + + + + + + + From c474682c19c6c6278d80dce0915f0ee05ee293fd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 20 Apr 2020 18:19:03 +0200 Subject: [PATCH 31/39] Fixed concurrent GPU dispatche glitches --- src/ComputeSharp.Graphics/GraphicsDevice.cs | 22 +++++---------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index a4177ccc..9a5165b6 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -18,11 +18,6 @@ namespace ComputeSharp.Graphics /// public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1; - /// - /// The instance used to wait for completion when executing commands - /// - private readonly AutoResetEvent AutoResetEvent = new AutoResetEvent(false); - /// /// The instance to use for compute operations /// @@ -126,11 +121,6 @@ namespace ComputeSharp.Graphics /// internal ID3D12Fence NativeDirectFence { get; } - /// - /// The used to lock command list executions - /// - private readonly object Lock = new object(); - /// /// Gets the next fence value for compute operations /// @@ -174,11 +164,11 @@ namespace ComputeSharp.Graphics if (fenceValue <= fence.CompletedValue) return; - lock (Lock) - { - fence.SetEventOnCompletion(fenceValue, AutoResetEvent.SafeWaitHandle.DangerousGetHandle()); - AutoResetEvent.WaitOne(); - } + using ManualResetEvent fenceEvent = new ManualResetEvent(false); + + fence.SetEventOnCompletion(fenceValue, fenceEvent); + + fenceEvent.WaitOne(); } /// @@ -244,8 +234,6 @@ namespace ComputeSharp.Graphics NativeDirectFence.Dispose(); NativeDevice.Dispose(); - - AutoResetEvent.Dispose(); } } } From df91d76ff84461d65fd9748a2b6d0ce256640987 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 30 Apr 2020 16:04:51 +0200 Subject: [PATCH 32/39] Removed nullability warnings --- src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index d4f925ff..0541da9a 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -244,7 +244,7 @@ namespace ComputeSharp.Shaders.Translation // Get the thread ids identifier name and shader method body ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; - MethodBody = root.Body.ToFullString(); + MethodBody = root.Body!.ToFullString(); // Additional preprocessing MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); @@ -283,13 +283,13 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyList 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 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(); + 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); From c1d09b237f8dbbf035697a9a9dc3bddfee232583 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 1 May 2020 13:52:25 +0200 Subject: [PATCH 33/39] Updated ImageProcessing project with ImageSharp-rc1 --- .../ComputeSharp.ImageProcessing.csproj | 2 +- .../Processors/HlslBokehBlurProcessor{TPixel}.cs | 9 +++------ .../Processors/HlslGaussianBlurProcessor{TPixel}.cs | 6 ++---- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index df1e75a1..b09ecf3d 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -16,7 +16,7 @@ - + diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index ae125ced..b400ecce 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -257,12 +256,10 @@ namespace ComputeSharp.BokehBlur.Processors /// protected override void OnFrameApply(ImageFrame source) { - IMemoryGroup group = source.GetPixelMemoryGroup(); - - for (int i = group.Count - 1; i >= 0; i--) + foreach (Memory memory in source.GetPixelMemoryGroup()) { // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(group[i]); + using IMemoryOwner source4 = GetExposedVector4Buffer(memory); using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); @@ -285,7 +282,7 @@ namespace ComputeSharp.BokehBlur.Processors processingBuffer.GetData(source4.Memory.Span); // Write the final pixel data - ApplyInverseGammaExposure(source4.Memory, group[i]); + ApplyInverseGammaExposure(source4.Memory, memory); } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 864e221b..25df7eaa 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -87,11 +87,9 @@ namespace ComputeSharp.BokehBlur.Processors /// protected override void OnFrameApply(ImageFrame source) { - IMemoryGroup group = source.GetPixelMemoryGroup(); - - for (int i = group.Count - 1; i >= 0; i--) + foreach (Memory memory in source.GetPixelMemoryGroup()) { - Span spanTPixel = group[i].Span; + Span spanTPixel = memory.Span; using IMemoryOwner group4 = Configuration.MemoryAllocator.Allocate(spanTPixel.Length); From f6797d2ff3cdbe5811bf8541e7ade41887da95ae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 1 May 2020 19:12:22 +0200 Subject: [PATCH 34/39] Fixed an XML comment --- src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 7a4242fd..24814bdf 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -11,7 +11,7 @@ using ComputeSharp.Shaders.Translation.Models; namespace ComputeSharp.Shaders.Translation { - /// + /// internal sealed partial class ShaderLoader { /// From 874dd5943a45b1cfb7e1cd4aa833c8debccdf930 Mon Sep 17 00:00:00 2001 From: John Date: Wed, 10 Jun 2020 21:27:30 +0100 Subject: [PATCH 35/39] Fix constant buffer copying See #67 --- .../Buffers/ConstantBuffer{T}.cs | 58 ++++++------------- 1 file changed, 17 insertions(+), 41 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 14371062..d609f74f 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -24,7 +24,7 @@ namespace ComputeSharp /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize() * 16, BufferType.Constant) { } + internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize(), BufferType.Constant) { } /// /// Gets the right padded size for elements to store in the current instance @@ -33,7 +33,7 @@ namespace ComputeSharp private static int GetPaddedSize() { int size = Unsafe.SizeOf(); - return size % 16 == 0 ? 1 : size / 16 + 1; + return (size + 15) & ~15; } /// @@ -44,31 +44,20 @@ namespace ComputeSharp public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ConstantBuffer)}[int]"); /// - public override void GetData(Span span, int offset, int count) + public override unsafe void GetData(Span span, int offset, int count) { if (IsPaddingPresent) { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(count * PaddedElementSizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); - // Copy the padded data to the temporary array using (MappedResource resource = MapResource()) { - MemoryHelper.Copy(resource.Pointer, offset * PaddedElementSizeInBytes, temporarySpan, 0, count * PaddedElementSizeInBytes); + ref var dest = ref MemoryMarshal.GetReference(span); + byte* untypedSrc = (byte*)resource.Pointer; + for (var i = offset; i < count; i++) + { + Unsafe.Add(ref dest, i) = *(T*)&untypedSrc[i * GetPaddedSize()]; + } } - - ref byte tin = ref temporarySpan.GetPinnableReference(); - ref T tout = ref span.GetPinnableReference(); - - // Copy the padded data to the target span, removing the padding - for (int i = 0; i < count; i++) - { - ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); - Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); - } - - ArrayPool.Shared.Return(temporaryArray); } else { @@ -80,36 +69,23 @@ namespace ComputeSharp } /// - public override void SetData(ReadOnlySpan span, int offset, int count) + /// + public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { + using MappedResource resource = MapResource(); if (IsPaddingPresent) { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(count * PaddedElementSizeInBytes); - ReadOnlySpan temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Array pool arrays can be longer - ref T tin = ref MemoryMarshal.GetReference(span); - ref byte tout = ref MemoryMarshal.GetReference(temporarySpan); - - // Copy the input data to the temporary array and add the padding - for (int i = 0; i < count; i++) + // Copy element-by-element + ref var src = ref MemoryMarshal.GetReference(span); + byte* untypedDest = (byte*)resource.Pointer; + for (var i = offset; i < count; i++) { - ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); - Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + *(T*)&untypedDest[i * GetPaddedSize()] = Unsafe.Add(ref src, i); } - - // Copy the padded data to the GPU - using (MappedResource resource = MapResource()) - { - MemoryHelper.Copy(temporarySpan, resource.Pointer, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); - } - - ArrayPool.Shared.Return(temporaryArray); } else { // Directly copy the input span if there is no padding - using MappedResource resource = MapResource(); - MemoryHelper.Copy(span, resource.Pointer, offset, count); } } From c613d92413a8e45a044032e9759351ba5b305fa3 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 11 Jun 2020 15:07:21 +0100 Subject: [PATCH 36/39] Resolve offset bug, fix mapped resource location, remove all pointers where possible --- .../Buffers/ConstantBuffer{T}.cs | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index d609f74f..0deb2358 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -30,6 +30,7 @@ namespace ComputeSharp /// Gets the right padded size for elements to store in the current instance /// [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetPaddedSize() { int size = Unsafe.SizeOf(); @@ -46,29 +47,27 @@ namespace ComputeSharp /// public override unsafe void GetData(Span span, int offset, int count) { + using MappedResource resource = MapResource(); if (IsPaddingPresent) { // Copy the padded data to the temporary array - using (MappedResource resource = MapResource()) { ref var dest = ref MemoryMarshal.GetReference(span); - byte* untypedSrc = (byte*)resource.Pointer; - for (var i = offset; i < count; i++) + ref byte untypedSrc = ref Unsafe.AsRef((void*)resource.Pointer); + untypedSrc = ref Unsafe.Add(ref untypedSrc, offset * GetPaddedSize()); + + for (var i = 0; i < count; i++) { - Unsafe.Add(ref dest, i) = *(T*)&untypedSrc[i * GetPaddedSize()]; + Unsafe.Add(ref dest, i) = Unsafe.As(ref Unsafe.Add(ref untypedSrc, i * GetPaddedSize())); } } } else { - // Directly copy the data back if there is no padding - using MappedResource resource = MapResource(); - MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); } } - /// /// public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { @@ -77,10 +76,12 @@ namespace ComputeSharp { // Copy element-by-element ref var src = ref MemoryMarshal.GetReference(span); - byte* untypedDest = (byte*)resource.Pointer; - for (var i = offset; i < count; i++) + ref byte untypedDest = ref Unsafe.AsRef((void*)resource.Pointer); + untypedDest = ref Unsafe.Add(ref untypedDest, offset * GetPaddedSize()); + + for (var i = 0; i < count; i++) { - *(T*)&untypedDest[i * GetPaddedSize()] = Unsafe.Add(ref src, i); + Unsafe.As(ref Unsafe.Add(ref untypedDest, i * GetPaddedSize())) = Unsafe.Add(ref src, i); } } else From 8aa83aae9150af20f1d599d6e1fffc016a3f97eb Mon Sep 17 00:00:00 2001 From: John Date: Thu, 11 Jun 2020 15:19:02 +0100 Subject: [PATCH 37/39] Inline else expression --- src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 0deb2358..4d50c4bd 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -84,11 +84,8 @@ namespace ComputeSharp Unsafe.As(ref Unsafe.Add(ref untypedDest, i * GetPaddedSize())) = Unsafe.Add(ref src, i); } } - else - { - // Directly copy the input span if there is no padding - MemoryHelper.Copy(span, resource.Pointer, offset, count); - } + // Directly copy as there is no padding + else MemoryHelper.Copy(span, resource.Pointer, offset, count); } /// From ec8e0b6b1e861f0794647a01c8f69328bae0ed76 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 11 Jun 2020 16:26:47 +0200 Subject: [PATCH 38/39] Minor code style tweaks --- .../Buffers/ConstantBuffer{T}.cs | 42 ++++++++++--------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 4d50c4bd..75cd89cc 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -1,5 +1,4 @@ using System; -using System.Buffers; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -34,6 +33,7 @@ namespace ComputeSharp private static int GetPaddedSize() { int size = Unsafe.SizeOf(); + return (size + 15) & ~15; } @@ -48,43 +48,45 @@ namespace ComputeSharp public override unsafe void GetData(Span span, int offset, int count) { using MappedResource resource = MapResource(); + if (IsPaddingPresent) { - // Copy the padded data to the temporary array - { - ref var dest = ref MemoryMarshal.GetReference(span); - ref byte untypedSrc = ref Unsafe.AsRef((void*)resource.Pointer); - untypedSrc = ref Unsafe.Add(ref untypedSrc, offset * GetPaddedSize()); + ref T spanRef = ref MemoryMarshal.GetReference(span); + ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); - for (var i = 0; i < count; i++) - { - Unsafe.Add(ref dest, i) = Unsafe.As(ref Unsafe.Add(ref untypedSrc, i * GetPaddedSize())); - } + // Move to the initial ref + resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); + + for (var i = 0; i < count; i++) + { + ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); + + Unsafe.Add(ref spanRef, i) = Unsafe.As(ref targetRef); } } - else - { - MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); - } + else MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); } /// public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { using MappedResource resource = MapResource(); + if (IsPaddingPresent) { - // Copy element-by-element - ref var src = ref MemoryMarshal.GetReference(span); - ref byte untypedDest = ref Unsafe.AsRef((void*)resource.Pointer); - untypedDest = ref Unsafe.Add(ref untypedDest, offset * GetPaddedSize()); + ref T spanRef = ref MemoryMarshal.GetReference(span); + ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); + + // Move to the initial offset + resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); for (var i = 0; i < count; i++) { - Unsafe.As(ref Unsafe.Add(ref untypedDest, i * GetPaddedSize())) = Unsafe.Add(ref src, i); + ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); + + Unsafe.As(ref targetRef) = Unsafe.Add(ref spanRef, i); } } - // Directly copy as there is no padding else MemoryHelper.Copy(span, resource.Pointer, offset, count); } From 1cf3b897b82c3e283466449bce1efcafea4fa9fb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 11 Jun 2020 17:05:22 +0200 Subject: [PATCH 39/39] Minor code refactoring --- .../ComputeSharp.ImageProcessing.csproj | 2 +- .../HlslGaussianBlurProcessor{TPixel}.cs | 1 - .../Abstract/HlslStructuredBuffer{T}.cs | 9 ++++----- .../Buffers/ConstantBuffer{T}.cs | 1 - .../Commands/CommandList.cs | 18 ++++-------------- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 1 - 6 files changed, 9 insertions(+), 23 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index b09ecf3d..a849bebf 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -16,7 +16,7 @@ - + diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 25df7eaa..1cd556b2 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -4,7 +4,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs index c5db3eb5..15e2d11e 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -25,10 +25,11 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public override void GetData(Span span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); - copyCommandList.Flush(); + using (CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy)) + { + copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); + } using MappedResource resource = transferBuffer.MapResource(); @@ -48,7 +49,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes); - copyCommandList.Flush(); } /// @@ -60,7 +60,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); } else SetDataWithCpuBuffer(buffer); } diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 75cd89cc..186a3154 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -99,7 +99,6 @@ namespace ComputeSharp using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); } else SetDataWithCpuBuffer(buffer); } diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 413af34e..6f288bce 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -88,23 +88,13 @@ namespace ComputeSharp.Graphics.Commands NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); } - /// - /// Executes the pending operations and waits for them to be completed - /// - public void Flush() - { - Close(); - GraphicsDevice.ExecuteCommandList(this); - } - - /// - /// Closes the current native command list - /// - public void Close() => NativeCommandList.Close(); - /// public override void Dispose() { + NativeCommandList.Close(); + + GraphicsDevice.ExecuteCommandList(this); + switch (CommandListType) { case CommandListType.Direct: diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 1ebb6005..eba0bbb6 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -125,7 +125,6 @@ namespace ComputeSharp.Shaders // Dispatch and wait for completion commandList.Dispatch(groupsX, groupsY, groupsZ); - commandList.Flush(); } } }