diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index f3a3ae7e..20b6364f 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -43,16 +43,27 @@ namespace ComputeSharp.Shaders.Extensions /// The info on parsed static fields, if any /// A instance that is compatible with HLSL [Pure] - public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel, out (string name, FieldInfo FieldInfo)? variable) + public static SyntaxNode ReplaceMember(this MemberAccessExpressionSyntax node, SemanticModel semanticModel, out (string Name, FieldInfo FieldInfo)? variable) { - SymbolInfo containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression); - SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name); - - ISymbol? memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault(); - // Set the variable to null, replace it later on if needed variable = null; + SymbolInfo containingMemberSymbolInfo; + ISymbol? memberSymbol; + try + { + containingMemberSymbolInfo = semanticModel.GetSymbolInfo(node.Expression); + SymbolInfo memberSymbolInfo = semanticModel.GetSymbolInfo(node.Name); + memberSymbol = memberSymbolInfo.Symbol ?? memberSymbolInfo.CandidateSymbols.FirstOrDefault(); + } + catch (ArgumentException) + { + // Member access on a captured HLSL-compatible field or property + string name = node.Name.ToFullString(); + if (name == "X" || name == "Y" || name == "Z" || name == "W") return node.WithName(SyntaxFactory.IdentifierName(name.ToLowerInvariant())); + return node; + } + // If the input member has no symbol or is not a field, property or method, just return it if (memberSymbol is null || memberSymbol.Kind != SymbolKind.Field && @@ -108,8 +119,8 @@ namespace ComputeSharp.Shaders.Extensions }; } - // Captured variable, treat it like any other captured variable in the closure - if (!isReadonly && fieldInfo != null) + // Captured field, treat it like any other captured variable in the closure + if (fieldInfo != null) { string name = $"{containingMemberSymbolInfo.Symbol.Name}_{fieldInfo.Name}"; variable = (name, fieldInfo); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 6c1649d3..65ff18c2 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -36,15 +36,37 @@ namespace ComputeSharp.Shaders.Translation 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 RootParameter[] _RootParameters; + /// /// Gets the array for the current shader /// - public RootParameter[] RootParameters { get; private set; } + public RootParameter[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); /// /// The of instances mapping the captured buffers in the current shader @@ -116,63 +138,67 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyList shaderFields = ShaderType.GetFields().ToArray(); if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); - List descriptorRanges = new List(); - int constantBuffersCount = 0; - int readOnlyBuffersCount = 0; - int readWriteBuffersCount = 0; - // Descriptor for the buffer for captured scalar/vector variables - descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount++)); + DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++)); // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { - Type fieldType = fieldInfo.FieldType; - string fieldName = fieldInfo.Name; - - // Constant buffer - if (HlslKnownTypes.IsConstantBufferType(fieldType)) - { - descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount)); - - // Track the buffer field - _BufferFields.Add(fieldInfo); - - 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 DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount)); - - // Track the buffer field - _BufferFields.Add(fieldInfo); - - 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 DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount)); - - // Track the buffer field - _BufferFields.Add(fieldInfo); - - 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 - _VariableFields.Add(fieldInfo); - string typeName = HlslKnownTypes.GetMappedName(fieldType); - _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); - } - else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); + LoadFieldInfo(fieldInfo); } - RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); + } + + /// + /// Loads a specified and adds it to the shader model + /// + /// The target to load + /// The optional explicit name to use for the field + private void LoadFieldInfo(FieldInfo fieldInfo, string? name = null) + { + Type fieldType = fieldInfo.FieldType; + string fieldName = name ?? fieldInfo.Name; + + // Constant buffer + if (HlslKnownTypes.IsConstantBufferType(fieldType)) + { + DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); + + // Track the buffer field + _BufferFields.Add(fieldInfo); + + 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 DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); + + // Track the buffer field + _BufferFields.Add(fieldInfo); + + 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 DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); + + // Track the buffer field + _BufferFields.Add(fieldInfo); + + 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 + _VariableFields.Add(fieldInfo); + string typeName = HlslKnownTypes.GetMappedName(fieldType); + _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); + } + else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); } /// @@ -190,9 +216,7 @@ namespace ComputeSharp.Shaders.Translation // Register the captured static fields foreach (var item in syntaxRewriter.StaticFields) { - _VariableFields.Add(item.FieldInfo); - string typeName = HlslKnownTypes.GetMappedName(item.FieldInfo.FieldType); - _FieldsList.Add(new CapturedFieldInfo(item.FieldInfo.FieldType, typeName, item.Name)); + LoadFieldInfo(item.Value, item.Key); } // Get the thread ids identifier name and shader method body diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index 477fe647..cbe726c5 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -23,12 +23,12 @@ namespace ComputeSharp.Shaders.Translation /// public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel; - private readonly List<(string, FieldInfo)> _StaticFields = new List<(string, FieldInfo)>(); + private readonly Dictionary _StaticFields = new Dictionary(); /// - /// Gets the collection of captured static fields used by the target code + /// Gets the mapping of captured static fields used by the target code /// - public IReadOnlyList<(string Name, FieldInfo FieldInfo)> StaticFields => _StaticFields; + public IReadOnlyDictionary StaticFields => _StaticFields; /// public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) @@ -101,7 +101,10 @@ namespace ComputeSharp.Shaders.Translation SyntaxNode syntaxNode = node.ReplaceMember(SemanticModel, out var variable); // Register the captured member, if any - if (variable.HasValue) _StaticFields.Add(variable.Value); + if (variable.HasValue && !_StaticFields.ContainsKey(variable.Value.Name)) + { + _StaticFields.Add(variable.Value.Name, variable.Value.FieldInfo); + } return syntaxNode; } diff --git a/tests/ComputeSharp.Tests/ShaderClosureTests.StaticFields.cs b/tests/ComputeSharp.Tests/ShaderClosureTests.StaticFields.cs new file mode 100644 index 00000000..f0c97dc2 --- /dev/null +++ b/tests/ComputeSharp.Tests/ShaderClosureTests.StaticFields.cs @@ -0,0 +1,141 @@ +using System; +using System.Numerics; +using ComputeSharp.Graphics.Buffers; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + /// + /// A container for static fields and properties to test + /// + public sealed class StaticFieldsContainer + { + /// + /// A field + /// + public static readonly float ReadonlyFloat = MathF.PI; + + /// + /// A field + /// + public static float StaticFloat = MathF.PI; + + /// + /// A field + /// + public static Vector2 ReadonlyVector2 = new Vector2(3.14f, 7.77f); + + /// + /// A field + /// + public static Vector2 StaticVector2 = new Vector2(3.14f, 7.77f); + + /// + /// A field + /// + public static ReadOnlyBuffer StaticBuffer = Gpu.Default.AllocateReadOnlyBuffer(new[] { 3.14f, 7.77f }); + } + + public partial class ShaderClosureTests + { + [TestMethod] + public void StaticReadonlyScalarAssignToBuffer() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = StaticFieldsContainer.ReadonlyFloat; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.ReadonlyFloat) < 0.0001f); + } + + [TestMethod] + public void StaticScalarAssignToBuffer() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat) < 0.0001f); + } + + [TestMethod] + public void StaticScalarRepeatedAssignToBuffer() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat * 2) < 0.0001f); + } + + [TestMethod] + public void StaticReadonlyVectorAssignToBuffer() + { + 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; + }; + + Gpu.Default.For(2, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.ReadonlyVector2.X) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.ReadonlyVector2.Y) < 0.0001f); + } + + [TestMethod] + public void StaticVectorAssignToBuffer() + { + 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; + }; + + Gpu.Default.For(2, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticVector2.X) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.StaticVector2.Y) < 0.0001f); + } + + [TestMethod] + public void StaticReadOnlyBufferAssignToBuffer() + { + 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]; + }; + + Gpu.Default.For(2, action); + + float[] result = buffer.GetData(); + float[] expected = StaticFieldsContainer.StaticBuffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - expected[0]) < 0.0001f); + Assert.IsTrue(MathF.Abs(result[1] - expected[1]) < 0.0001f); + } + } +} diff --git a/tests/ComputeSharp.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.Tests/ShaderClosureTests.cs index 81c37c89..cf789e92 100644 --- a/tests/ComputeSharp.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.Tests/ShaderClosureTests.cs @@ -9,7 +9,7 @@ namespace ComputeSharp.Tests { [TestClass] [TestCategory("ShaderClosure")] - public class ShaderClosureTests + public partial class ShaderClosureTests { [TestMethod] public void LocalScalarAssignToBuffer() @@ -64,11 +64,11 @@ namespace ComputeSharp.Tests } [TestMethod] - public void CopyBetweenWriteableBuffers() + public void CopyBetweenConstantAndWriteableBuffers() { float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); - using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); + using ConstantBuffer input = Gpu.Default.AllocateConstantBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); Action action = id => buffer[id.X] = input[id.X]; @@ -85,7 +85,24 @@ namespace ComputeSharp.Tests { float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); - using ConstantBuffer input = Gpu.Default.AllocateConstantBuffer(source); + using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); + + Action action = id => buffer[id.X] = input[id.X]; + + Gpu.Default.For(source.Length, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(result.AsSpan().ContentEquals(source)); + } + + [TestMethod] + public void CopyBetweenWriteableBuffers() + { + float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); Action action = id => buffer[id.X] = input[id.X];