diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
index 9261ae98..3a0fde04 100644
--- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
+++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj
@@ -7,6 +7,7 @@
+
diff --git a/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs b/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs
new file mode 100644
index 00000000..3d3431f4
--- /dev/null
+++ b/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs
@@ -0,0 +1,32 @@
+// Copyright (c) Six Labors.
+// Licensed under the Apache License, Version 2.0.
+
+using System.Numerics;
+using System.Runtime.CompilerServices;
+
+namespace SixLabors.ImageSharp;
+
+///
+/// A vector with 4 values of type .
+///
+internal struct ComplexVector4
+{
+ ///
+ /// The real part of the complex vector
+ ///
+ public Vector4 Real;
+
+ ///
+ /// The imaginary part of the complex number
+ ///
+ public Vector4 Imaginary;
+
+ ///
+ /// Performs a weighted sum on the current instance according to the given parameters
+ ///
+ /// The 'a' parameter, for the real component
+ /// The 'b' parameter, for the imaginary component
+ /// The resulting value
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector4 WeightedSum(float a, float b) => (this.Real * a) + (this.Imaginary * b);
+}
\ No newline at end of file
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
index b9187cf0..2677d2a2 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
@@ -363,13 +363,12 @@ public sealed partial class HlslBokehBlurProcessor
///
public void Execute()
{
- float4 real = float4.Zero;
- float4 imaginary = float4.Zero;
int maxY = target.Height;
int maxX = target.Width;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
+ ComplexVector4 result = default;
for (int i = 0; i < kernelLength; i++)
{
@@ -378,11 +377,11 @@ public sealed partial class HlslBokehBlurProcessor
float4 sourceImaginary = imaginaries[offsetX, offsetY];
Complex64 factors = kernel[i];
- real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
- imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
+ result.Real += (Vector4)(factors.Real * sourceReal - factors.Imaginary * sourceImaginary);
+ result.Imaginary += (Vector4)(factors.Real * sourceImaginary + factors.Imaginary * sourceReal);
}
- target[ThreadIds.XY] += real * z + imaginary * w;
+ target[ThreadIds.XY] += (float4)result.WeightedSum(z, w);
}
}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs
index 0cef3803..4b3ee9b2 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs
@@ -52,6 +52,7 @@ partial class ID2D1ShaderGenerator
// We need to sets to track all discovered custom types and static methods
HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+ Dictionary instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
// Extract information on all captured fields
@@ -64,11 +65,11 @@ partial class ID2D1ShaderGenerator
// Explore the syntax tree and extract the processed info
var semanticModelProvider = new SemanticModelProvider(compilation);
- var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition);
+ var (entryPoint, processedMethods) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, out bool methodsNeedD2D1RequiresScenePosition);
var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions, out bool fieldsNeedD2D1RequiresScenePosition);
// Process the discovered types and constants
- var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes);
+ var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods);
var definedConstants = GetDefinedConstants(constantDefinitions);
// Check whether the scene position is required
@@ -258,6 +259,7 @@ partial class ID2D1ShaderGenerator
/// The instance for the type to process.
/// The collection of currently discovered types.
/// The set of discovered and processed static methods.
+ /// The collection of discovered instance methods for custom struct types.
/// The collection of discovered constant definitions.
/// Whether or not the shader needs the [D2DRequiresScenePosition] annotation.
/// A sequence of processed methods in , and the entry point.
@@ -268,6 +270,7 @@ partial class ID2D1ShaderGenerator
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
+ IDictionary instanceMethods,
IDictionary constantDefinitions,
out bool needsD2D1RequiresScenePosition)
{
@@ -303,6 +306,7 @@ partial class ID2D1ShaderGenerator
semanticModel,
discoveredTypes,
staticMethods,
+ instanceMethods,
constantDefinitions,
diagnostics,
isShaderEntryPoint);
@@ -374,11 +378,13 @@ partial class ID2D1ShaderGenerator
/// The collection of produced instances.
/// The type symbol for the shader type.
/// The sequence of discovered custom types.
+ /// The collection of discovered instance methods for custom struct types.
/// A sequence of custom type definitions to add to the shader source.
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
- IEnumerable types)
+ IEnumerable types,
+ IReadOnlyDictionary instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection invalidTypes;
@@ -414,6 +420,12 @@ partial class ID2D1ShaderGenerator
VariableDeclarator(Identifier(mappedName!)))));
}
+ // Declare the methods of the current type
+ foreach (var method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type)))
+ {
+ structDeclaration = structDeclaration.AddMembers(method.Value);
+ }
+
// Insert the trailing ; right after the closing bracket (after normalization)
builder.Add((
structType,
diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs
index c32f24ef..400ab405 100644
--- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -31,6 +31,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
///
private readonly IDictionary staticMethods;
+ ///
+ /// The collection of discovered instance methods for custom struct types.
+ ///
+ private readonly IDictionary instanceMethods;
+
///
/// The collection of processed local functions in the current tree.
///
@@ -63,6 +68,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// The instance for the target syntax tree.
/// The set of discovered custom types.
/// The set of discovered and processed static methods.
+ /// The collection of discovered instance methods for custom struct types.
/// The collection of discovered constant definitions.
/// The collection of produced instances.
/// Whether or not the current instance is processing a shader entry point.
@@ -71,6 +77,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
+ IDictionary instanceMethods,
IDictionary constantDefinitions,
ImmutableArray.Builder diagnostics,
bool isEntryPoint)
@@ -78,6 +85,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
{
this.shaderType = shaderType;
this.staticMethods = staticMethods;
+ this.instanceMethods = instanceMethods;
this.localFunctions = new();
this.implicitVariables = new();
this.isEntryPoint = isEntryPoint;
@@ -89,17 +97,20 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// The instance for the target syntax tree.
/// The set of discovered custom types.
/// The set of discovered and processed static methods.
+ /// The collection of discovered instance methods for custom struct types.
/// The collection of discovered constant definitions.
/// The collection of produced instances.
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
+ IDictionary instanceMethods,
IDictionary constantDefinitions,
ImmutableArray.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.staticMethods = staticMethods;
+ this.instanceMethods = instanceMethods;
this.implicitVariables = new();
this.localFunctions = new();
}
@@ -459,7 +470,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
return updatedNode;
}
- ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics);
+ ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, this.instanceMethods, ConstantDefinitions, Diagnostics);
MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
@@ -472,6 +483,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
{
string metadataName = method.GetFullMetadataName(includeParameters: true);
+ // Check whether this is a Sample(...) call on a normalized texture type
if (HlslKnownMethods.TryGetMappedResourceSamplerAccessType(metadataName, out string? mapping))
{
// Get the syntax for the argument syntax transformation (adding the vector type constructor if needed)
@@ -484,6 +496,42 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
// Rewrite texture resource sampled accesses, if needed
return RewriteSampledTextureAccess(operation, updatedNode.Expression, coordinateSyntax);
}
+
+ // If the instance is a struct type that is available in source, rewrite the instance method.
+ // This path is only taken for instance methods for external struct types, not the shader itself.
+ if (operation.TargetMethod.ContainingType is { TypeKind: TypeKind.Struct } structTypeSymbol &&
+ !SymbolEqualityComparer.Default.Equals(this.shaderType, structTypeSymbol))
+ {
+ DiscoveredTypes.Add(structTypeSymbol);
+
+ var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName();
+
+ // Same as for static methods, ensure the method is available in source, and process it if so
+ if (!this.instanceMethods.ContainsKey(method))
+ {
+ if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode)
+ {
+ Diagnostics.Add(InvalidMethodCall, node, method);
+
+ return updatedNode;
+ }
+
+ ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.instanceMethods, this.instanceMethods, ConstantDefinitions, Diagnostics);
+ MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
+
+ this.instanceMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
+ }
+
+ // Rewrite the expression depending on its type:
+ // - If it's a simple member expression, change the identifier name: eg. foo.Bar(...) => foo.NewName(...)
+ // - If it's an identifier name, change it directly: eg. Bar(...) => NewName(...)
+ return updatedNode.Expression switch
+ {
+ MemberAccessExpressionSyntax memberAccess => updatedNode.WithExpression(memberAccess.WithName(IdentifierName(methodIdentifier))),
+ IdentifierNameSyntax identifierName => updatedNode.WithExpression(IdentifierName(methodIdentifier)),
+ _ => throw new NotSupportedException($"Unsupported instance method expression type \"{updatedNode.Expression.GetType()}\".")
+ };
+ }
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs
index a4b31e9c..703cf89f 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs
@@ -48,6 +48,7 @@ partial class IShaderGenerator
// We need to sets to track all discovered custom types and static methods
HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+ Dictionary instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
// A given type can only represent a single shader type
@@ -64,12 +65,12 @@ partial class IShaderGenerator
var (resourceFields, valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
var delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol);
var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
- var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
+ var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
// Process the discovered types and constants
- var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes);
+ var declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods);
var definedConstants = GetDefinedConstants(constantDefinitions);
// Get the HLSL source data with the intermediate info
@@ -315,6 +316,7 @@ partial class IShaderGenerator
/// The instance for the type to process.
/// The collection of currently discovered types.
/// The set of discovered and processed static methods.
+ /// The collection of discovered instance methods for custom struct types.
/// The collection of discovered constant definitions.
/// Indicates whether or not represents a compute shader.
/// A sequence of processed methods in , and the entry point.
@@ -325,6 +327,7 @@ partial class IShaderGenerator
SemanticModelProvider semanticModel,
ICollection discoveredTypes,
IDictionary staticMethods,
+ IDictionary instanceMethods,
IDictionary constantDefinitions,
bool isComputeShader)
{
@@ -365,6 +368,7 @@ partial class IShaderGenerator
semanticModel,
discoveredTypes,
staticMethods,
+ instanceMethods,
constantDefinitions,
diagnostics,
isShaderEntryPoint);
@@ -436,14 +440,16 @@ partial class IShaderGenerator
///
/// Gets the sequence of processed discovered custom types.
///
- /// The sequence of discovered custom types.
- /// The symbol for the current object being processed.
/// The collection of produced instances.
+ /// The symbol for the current object being processed.
+ /// The sequence of discovered custom types.
+ /// The collection of discovered instance methods for custom struct types.
/// A sequence of custom type definitions to add to the shader source.
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray.Builder diagnostics,
ISymbol sourceSymbol,
- IEnumerable types)
+ IEnumerable types,
+ IReadOnlyDictionary instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection invalidTypes;
@@ -479,6 +485,12 @@ partial class IShaderGenerator
VariableDeclarator(Identifier(mappedName!)))));
}
+ // Declare the methods of the current type
+ foreach (var method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type)))
+ {
+ structDeclaration = structDeclaration.AddMembers(method.Value);
+ }
+
// Insert the trailing ; right after the closing bracket (after normalization)
builder.Add((
structType,
diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
index dd06162d..7985bf26 100644
--- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
@@ -84,11 +84,12 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
// We need to sets to track all discovered custom types and static methods
HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
+ Dictionary instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator
// Explore the syntax tree and extract the processed info
var semanticModel = new SemanticModelProvider(compilation);
var (entryPoint, dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
- var definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes);
+ var definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods);
var definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions);
diagnostics = builder.ToImmutable();
@@ -118,8 +119,9 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
IDictionary constantDefinitions)
{
Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+ Dictionary instanceMethods = new(SymbolEqualityComparer.Default);
- ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics);
+ ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics);
// Process the possible syntax nodes
SyntaxNode visitedMethod = methodDeclaration switch
diff --git a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj
index c6b0d625..de70d87b 100644
--- a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj
+++ b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj
@@ -25,6 +25,11 @@
+
+
+
+
+
PreserveNewest
diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs
index 462281f4..f657c94c 100644
--- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs
+++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs
@@ -9,6 +9,7 @@ using ComputeSharp.D2D1;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Tests.Extensions;
using ComputeSharp.D2D1.Tests.Helpers;
+using SixLabors.ImageSharp;
using Win32;
using Win32.Graphics.Direct2D;
@@ -568,10 +569,9 @@ public sealed partial class BokehBlurEffect
///
public float4 Execute()
{
- float4 real = float4.Zero;
- float4 imaginary = float4.Zero;
int length = this.kernelLength;
int radiusX = length >> 1;
+ ComplexVector4 result = default;
for (int i = 0; i < length; i++)
{
@@ -580,11 +580,11 @@ public sealed partial class BokehBlurEffect
float realFactor = kernelReals[i];
float imaginaryFactor = kernelImaginaries[i];
- real += realFactor * sourceReal - imaginaryFactor * sourceImaginary;
- imaginary += realFactor * sourceImaginary + imaginaryFactor * sourceReal;
+ result.Real += (Vector4)(realFactor * sourceReal - imaginaryFactor * sourceImaginary);
+ result.Imaginary += (Vector4)(realFactor * sourceImaginary + imaginaryFactor * sourceReal);
}
- return real * z + imaginary * w;
+ return result.WeightedSum(z, w);
}
}
}
@@ -633,40 +633,4 @@ public sealed partial class BokehBlurEffect
return pixel;
}
}
-
- ///
- /// Represents a complex number, where the real and imaginary parts are stored as values.
- ///
- private readonly struct Complex64
- {
- ///
- /// The real part of the complex number.
- ///
- public readonly float Real;
-
- ///
- /// The imaginary part of the complex number.
- ///
- public readonly float Imaginary;
-
- ///
- /// Initializes a new instance of the struct.
- ///
- /// The real part in the complex number.
- /// The imaginary part in the complex number.
- public Complex64(float real, float imaginary)
- {
- this.Real = real;
- this.Imaginary = imaginary;
- }
-
- ///
- /// Performs the multiplication operation between a instance and a scalar.
- ///
- /// The value to multiply.
- /// The scalar to use to multiply the value.
- /// The result.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Complex64 operator *(Complex64 value, float scalar) => new(value.Real * scalar, value.Imaginary * scalar);
- }
}
diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
index c14ba3ee..d92c7e29 100644
--- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
+++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj
@@ -36,6 +36,7 @@
+
diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
index 269b2adc..ab8901df 100644
--- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
+++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs
@@ -416,6 +416,55 @@ namespace ComputeSharp.Tests
return default;
}
}
+
+ [TestMethod]
+ public void StructInstanceMethods()
+ {
+ _ = ReflectionServices.GetShaderInfo();
+ }
+
+ public struct MyStructTypeA
+ {
+ public int A;
+ public float B;
+
+ public float Sum()
+ {
+ return A + Bar();
+ }
+
+ public float Bar() => this.B;
+ }
+
+ public struct MyStructTypeB
+ {
+ public MyStructTypeA A;
+ public float B;
+
+ public float Combine()
+ {
+ return A.Sum() + this.B;
+ }
+ }
+
+ [AutoConstructor]
+ internal readonly partial struct StructInstanceMethodsShader : IComputeShader
+ {
+ public readonly MyStructTypeA a;
+ public readonly MyStructTypeB b;
+ public readonly ReadWriteBuffer bufferA;
+ public readonly ReadWriteBuffer bufferB;
+ public readonly ReadWriteBuffer results;
+
+ ///
+ public void Execute()
+ {
+ float result1 = a.Sum() + a.Bar();
+ float result2 = b.Combine();
+
+ results[ThreadIds.X] = result1 + result2 + bufferA[ThreadIds.X].Sum() + bufferB[0].Combine();
+ }
+ }
}
}
diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs
index 4ca56f7e..ad8033c2 100644
--- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs
+++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs
@@ -1,4 +1,6 @@
using System;
+using System.Linq;
+using ComputeSharp.Interop;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -722,4 +724,50 @@ public partial class ShaderRewriterTests
destination2[21] = i2_copy2.Y;
}
}
+
+ // See https://github.com/Sergio0694/ComputeSharp/issues/390
+ [CombinatorialTestMethod]
+ [AllDevices]
+ public void CustomStructWypeWithInstanceMethod(Device device)
+ {
+ CustomStructType[] data = Enumerable.Range(0, 1024).Select(static i => new CustomStructType() { value = i }).ToArray();
+
+ using ReadWriteBuffer source = device.Get().AllocateReadWriteBuffer(data);
+ using ReadWriteBuffer destination = device.Get().AllocateReadWriteBuffer(data.Length, AllocationMode.Clear);
+
+ device.Get().For(source.Length, new CustomStructTypeShader(source, destination));
+
+ CustomStructType[] results1 = source.ToArray();
+ int[] results2 = destination.ToArray();
+
+ for (int i = 0; i < source.Length; i++)
+ {
+ Assert.AreEqual(i * 2 + 1, results1[i].value);
+ Assert.AreEqual(results1[i].value, results2[i]);
+ }
+ }
+
+ public struct CustomStructType
+ {
+ public int value;
+
+ public int AddAndGetSum(int x)
+ {
+ this.value += x;
+
+ return this.value;
+ }
+ }
+
+ [AutoConstructor]
+ internal readonly partial struct CustomStructTypeShader : IComputeShader
+ {
+ public readonly ReadWriteBuffer source;
+ public readonly ReadWriteBuffer destination;
+
+ public void Execute()
+ {
+ destination[ThreadIds.X] = source[ThreadIds.X].AddAndGetSum(ThreadIds.X + 1);
+ }
+ }
}