Merge pull request #392 from Sergio0694/dev/struct-instance-methods

Add support for instance methods in custom struct types
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-10-02 13:20:33 -07:00
コミット 3517d5f4d4
12ファイル変更
+230 -57

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

+1
ファイルの表示
@@ -7,6 +7,7 @@
<ItemGroup>
<Compile Include="..\ComputeSharp.ImageProcessing\Primitives\Complex64.cs" Link="Imaging\Primitives\Complex64.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Primitives\ComplexVector4.cs" Link="Imaging\Primitives\ComplexVector4.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor.cs" Link="Imaging\Processors\HlslBokehBlurProcessor.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslBokehBlurProcessor{TPixel}.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor.cs" />
+32
ファイルの表示
@@ -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;
/// <summary>
/// A vector with 4 values of type <see cref="Complex64"/>.
/// </summary>
internal struct ComplexVector4
{
/// <summary>
/// The real part of the complex vector
/// </summary>
public Vector4 Real;
/// <summary>
/// The imaginary part of the complex number
/// </summary>
public Vector4 Imaginary;
/// <summary>
/// Performs a weighted sum on the current instance according to the given parameters
/// </summary>
/// <param name="a">The 'a' parameter, for the real component</param>
/// <param name="b">The 'b' parameter, for the imaginary component</param>
/// <returns>The resulting <see cref="Vector4"/> value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector4 WeightedSum(float a, float b) => (this.Real * a) + (this.Imaginary * b);
}
+4 -5
ファイルの表示
@@ -363,13 +363,12 @@ public sealed partial class HlslBokehBlurProcessor
/// <inheritdoc/>
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);
}
}
@@ -52,6 +52,7 @@ partial class ID2D1ShaderGenerator
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> 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
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
@@ -268,6 +270,7 @@ partial class ID2D1ShaderGenerator
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> 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
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<INamedTypeSymbol> types)
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection<INamedTypeSymbol> 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,
+49 -1
ファイルの表示
@@ -31,6 +31,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
/// <summary>
/// The collection of discovered instance methods for custom struct types.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods;
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
@@ -63,6 +68,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
@@ -71,6 +77,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.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
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.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()}\".")
};
}
}
}
+17 -5
ファイルの表示
@@ -48,6 +48,7 @@ partial class IShaderGenerator
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> 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
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
@@ -325,6 +327,7 @@ partial class IShaderGenerator
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
bool isComputeShader)
{
@@ -365,6 +368,7 @@ partial class IShaderGenerator
semanticModel,
discoveredTypes,
staticMethods,
instanceMethods,
constantDefinitions,
diagnostics,
isShaderEntryPoint);
@@ -436,14 +440,16 @@ partial class IShaderGenerator
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="sourceSymbol">The symbol for the current object being processed.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="sourceSymbol">The symbol for the current object being processed.</param>
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ISymbol sourceSymbol,
IEnumerable<INamedTypeSymbol> types)
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection<INamedTypeSymbol> 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,
+4 -2
ファイルの表示
@@ -84,11 +84,12 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> 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<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> 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
+5
ファイルの表示
@@ -25,6 +25,11 @@
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\Complex64.cs" Link="Imaging\Primitives\Complex64.cs" />
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\ComplexVector4.cs" Link="Imaging\Primitives\ComplexVector4.cs" />
</ItemGroup>
<ItemGroup>
<None Update="Assets\Landscape.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+5 -41
ファイルの表示
@@ -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
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Represents a complex number, where the real and imaginary parts are stored as <see cref="float"/> values.
/// </summary>
private readonly struct Complex64
{
/// <summary>
/// The real part of the complex number.
/// </summary>
public readonly float Real;
/// <summary>
/// The imaginary part of the complex number.
/// </summary>
public readonly float Imaginary;
/// <summary>
/// Initializes a new instance of the <see cref="Complex64"/> struct.
/// </summary>
/// <param name="real">The real part in the complex number.</param>
/// <param name="imaginary">The imaginary part in the complex number.</param>
public Complex64(float real, float imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
/// <summary>
/// Performs the multiplication operation between a <see cref="Complex64"/> instance and a <see cref="float"/> scalar.
/// </summary>
/// <param name="value">The <see cref="Complex64"/> value to multiply.</param>
/// <param name="scalar">The <see cref="float"/> scalar to use to multiply the <see cref="Complex64"/> value.</param>
/// <returns>The <see cref="Complex64"/> result.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Complex64 operator *(Complex64 value, float scalar) => new(value.Real * scalar, value.Imaginary * scalar);
}
}
+1
ファイルの表示
@@ -36,6 +36,7 @@
<ItemGroup>
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\Complex64.cs" Link="Imaging\Primitives\Complex64.cs" />
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Primitives\ComplexVector4.cs" Link="Imaging\Primitives\ComplexVector4.cs" />
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor.cs" Link="Imaging\Processors\HlslBokehBlurProcessor.cs" />
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslBokehBlurProcessor{TPixel}.cs" />
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor.cs" />
+49
ファイルの表示
@@ -416,6 +416,55 @@ namespace ComputeSharp.Tests
return default;
}
}
[TestMethod]
public void StructInstanceMethods()
{
_ = ReflectionServices.GetShaderInfo<StructInstanceMethodsShader>();
}
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<MyStructTypeA> bufferA;
public readonly ReadWriteBuffer<MyStructTypeB> bufferB;
public readonly ReadWriteBuffer<float> results;
/// <inheritdoc/>
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();
}
}
}
}
+48
ファイルの表示
@@ -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<CustomStructType> source = device.Get().AllocateReadWriteBuffer(data);
using ReadWriteBuffer<int> destination = device.Get().AllocateReadWriteBuffer<int>(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<CustomStructType> source;
public readonly ReadWriteBuffer<int> destination;
public void Execute()
{
destination[ThreadIds.X] = source[ThreadIds.X].AddAndGetSum(ThreadIds.X + 1);
}
}
}