Merge pull request #699 from Sergio0694/dev/constructors-support
Add support for constructors in DX12 and D2D1 shaders
このコミットが含まれているのは:
13ファイル変更
+545
-40
検索条件に一致するファイルはありません
@@ -79,3 +79,4 @@ CMPSD2D0069 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://gith
|
||||
CMPSD2D0070 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0071 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0072 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPSD2D0073 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
+7
-1
@@ -51,6 +51,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
@@ -75,6 +76,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
token,
|
||||
out bool methodsNeedD2D1RequiresScenePosition);
|
||||
@@ -97,7 +99,8 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
discoveredTypes,
|
||||
instanceMethods);
|
||||
instanceMethods,
|
||||
constructors);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -306,6 +309,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
/// <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="constructors">The collection of discovered constructors 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>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
@@ -317,6 +321,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
CancellationToken token,
|
||||
out bool needsD2D1RequiresScenePosition)
|
||||
@@ -360,6 +365,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
diagnostics,
|
||||
isShaderEntryPoint);
|
||||
|
||||
@@ -557,19 +557,19 @@ partial class DiagnosticDescriptors
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a method invocation that is not valid from a shader.
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a method or constructor invocation that is not valid from a shader.
|
||||
/// <para>
|
||||
/// Format: <c>"The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)"</c>.
|
||||
/// Format: <c>"The method or constructor {0} cannot be used in a D2D1 shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidMethodCall = new(
|
||||
public static readonly DiagnosticDescriptor InvalidMethodOrConstructorCall = new(
|
||||
id: "CMPSD2D0040",
|
||||
title: "Invalid method invocation from a D2D1 shader",
|
||||
messageFormat: "The method {0} cannot be used in a D2D1 shader (methods need to either be HLSL intrinsics or with source available for analysis)",
|
||||
title: "Invalid method or constructor invocation from a D2D1 shader",
|
||||
messageFormat: "The method or constructor {0} cannot be used in a D2D1 shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)",
|
||||
category: "ComputeSharp.D2D1.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "A D2D1 shader can only invoke methods that are either HLSL intrinsics or with source available for analysis.",
|
||||
description: "A D2D1 shader can only invoke methods or constructors that are either HLSL intrinsics or with source available for analysis.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
@@ -1080,4 +1080,20 @@ partial class DiagnosticDescriptors
|
||||
isEnabledByDefault: true,
|
||||
description: "A collection expression cannot be used in a pixel shader.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a constructor with a base constructor declaration.
|
||||
/// <para>
|
||||
/// Format: <c>"The constructor {0} has a base constructor declaration, which cannot be used in a D2D1 shader (only standalone constructors are allowed)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidBaseConstructorDeclaration = new(
|
||||
id: "CMPSD2D0073",
|
||||
title: "Invalid base constructor declaration",
|
||||
messageFormat: "The constructor {0} has a base constructor declaration, which cannot be used in a D2D1 shader (only standalone constructors are allowed)",
|
||||
category: "ComputeSharp.D2D1.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "Only standalone constructors (with no base constructor declaration) can be used in a D2D1 shader.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
+30
-5
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
@@ -46,12 +45,14 @@ internal static class HlslDefinitionsSyntaxProcessor
|
||||
/// <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>
|
||||
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
public static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
IEnumerable<INamedTypeSymbol> types,
|
||||
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
|
||||
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IReadOnlyDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors)
|
||||
{
|
||||
using ImmutableArrayBuilder<(string, string)> builder = new();
|
||||
|
||||
@@ -98,12 +99,36 @@ internal static class HlslDefinitionsSyntaxProcessor
|
||||
VariableDeclarator(Identifier(mappedName!)))));
|
||||
}
|
||||
|
||||
// Declare the methods of the current type
|
||||
foreach (KeyValuePair<IMethodSymbol, MethodDeclarationSyntax> method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type)))
|
||||
// Enumerate all members in a single pass, so we can avoid materializing the collection.
|
||||
// Additionally, this lets us add all members to the struct declaration in a single go.
|
||||
static IEnumerable<MethodDeclarationSyntax> GatherInstanceMethods(
|
||||
INamedTypeSymbol type,
|
||||
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IReadOnlyDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors)
|
||||
{
|
||||
structDeclaration = structDeclaration.AddMembers(method.Value);
|
||||
// Normal instance methods
|
||||
foreach (KeyValuePair<IMethodSymbol, MethodDeclarationSyntax> method in instanceMethods)
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(method.Key.ContainingType, type))
|
||||
{
|
||||
yield return method.Value;
|
||||
}
|
||||
}
|
||||
|
||||
// Constructors and stubs
|
||||
foreach (KeyValuePair<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> methods in constructors)
|
||||
{
|
||||
if (SymbolEqualityComparer.Default.Equals(methods.Key.ContainingType, type))
|
||||
{
|
||||
yield return methods.Value.Stub;
|
||||
yield return methods.Value.Ctor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the methods of the current type
|
||||
structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(GatherInstanceMethods(type, instanceMethods, constructors)));
|
||||
|
||||
// Insert the trailing ; right after the closing bracket (after normalization)
|
||||
builder.Add((
|
||||
structType,
|
||||
|
||||
@@ -118,37 +118,64 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
|
||||
/// <returns>The rewritten <see cref="SyntaxNode"/> for the object creation expression.</returns>
|
||||
private SyntaxNode VisitObjectCreationExpression(BaseObjectCreationExpressionSyntax node, BaseObjectCreationExpressionSyntax updatedNode, TypeSyntax targetType)
|
||||
{
|
||||
// Emit a diagnostic if the object being created is not valid (ie. it's a managed type)
|
||||
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
|
||||
ITypeSymbol? typeSymbol = SemanticModel.For(node).GetTypeInfo(node).Type;
|
||||
|
||||
// Handle the edge case of the type being null (shouldn't really happen)
|
||||
if (typeSymbol is null)
|
||||
{
|
||||
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
|
||||
Diagnostics.Add(InvalidObjectCreationExpression, node, "<invalid>");
|
||||
|
||||
return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
|
||||
}
|
||||
|
||||
// Emit a diagnostic if the object being created is not valid (ie. it's a managed type)
|
||||
if (!typeSymbol.IsUnmanagedType)
|
||||
{
|
||||
Diagnostics.Add(InvalidObjectCreationExpression, node, typeSymbol);
|
||||
|
||||
return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
|
||||
}
|
||||
|
||||
// Mutate the syntax like with explicit object creation expressions. This also handles object
|
||||
// initializer expressions. If those are used, the HLSL will just contain a default expression.
|
||||
// There is a diagnostic being emitted to inform the users if that path is hit. If users want
|
||||
// to create an object and immediately set some values, they should use a factory method.
|
||||
if (updatedNode is not { ArgumentList.Arguments.Count: > 0, Initializer: null })
|
||||
if (updatedNode is not { ArgumentList.Arguments.Count: >= 0, Initializer: null })
|
||||
{
|
||||
return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
|
||||
}
|
||||
|
||||
// Add explicit casts like with the explicit object creation expressions above
|
||||
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
|
||||
HlslKnownTypes.IsMatrixType(matrixType.GetFullyQualifiedMetadataName()))
|
||||
{
|
||||
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
|
||||
{
|
||||
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
|
||||
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
|
||||
string typeName = typeSymbol.GetFullyQualifiedMetadataName();
|
||||
|
||||
updatedNode = updatedNode.ReplaceNode(
|
||||
updatedNode.ArgumentList!.Arguments[i].Expression,
|
||||
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
|
||||
if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
// Special when we have no arguments, ie. we're calling the default parameterless constructor.
|
||||
// We need to add this check here because for user defined types, there may be explicit constructors.
|
||||
if (updatedNode.ArgumentList.Arguments.Count == 0)
|
||||
{
|
||||
return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
|
||||
}
|
||||
|
||||
// Add explicit casts to each individual argument
|
||||
if (HlslKnownTypes.IsMatrixType(typeName))
|
||||
{
|
||||
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
|
||||
{
|
||||
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
|
||||
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
|
||||
|
||||
updatedNode = updatedNode.ReplaceNode(
|
||||
updatedNode.ArgumentList!.Arguments[i].Expression,
|
||||
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
|
||||
}
|
||||
}
|
||||
|
||||
// In either case, for built-in HLSL types, we can just invoke the constructor directly
|
||||
return InvocationExpression(targetType, updatedNode.ArgumentList!);
|
||||
}
|
||||
|
||||
return InvocationExpression(targetType, updatedNode.ArgumentList!);
|
||||
// We're invoking a user defined constructor
|
||||
return VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -364,4 +391,18 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
|
||||
|
||||
return updatedToken.WithoutTrivia();
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="VisitObjectCreationExpression(ObjectCreationExpressionSyntax)"/>
|
||||
/// <param name="node">The original input <see cref="BaseObjectCreationExpressionSyntax"/> instance.</param>
|
||||
/// <param name="updatedNode">The updated <see cref="BaseObjectCreationExpressionSyntax"/> instance with tweaked syntax.</param>
|
||||
/// <param name="targetType">The <see cref="TypeSyntax"/> for the object being created.</param>
|
||||
/// <returns>The rewritten <see cref="SyntaxNode"/> for the object creation expression.</returns>
|
||||
protected virtual SyntaxNode VisitUserDefinedObjectCreationExpression(
|
||||
BaseObjectCreationExpressionSyntax node,
|
||||
BaseObjectCreationExpressionSyntax updatedNode,
|
||||
TypeSyntax targetType)
|
||||
{
|
||||
// By default, constructors are not supported, so just return an empty value
|
||||
return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,6 @@ using Microsoft.CodeAnalysis.Operations;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable IDE0052
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxRewriters;
|
||||
|
||||
/// <summary>
|
||||
@@ -37,6 +35,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// </summary>
|
||||
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered constructors for custom struct types.
|
||||
/// </summary>
|
||||
private readonly IDictionary<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> constructors;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of processed local functions in the current tree.
|
||||
/// </summary>
|
||||
@@ -53,7 +56,8 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
private readonly bool isEntryPoint;
|
||||
|
||||
/// <summary>
|
||||
/// The identifier of the current <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> tree being visited.
|
||||
/// The identifier of the current <see cref="ConstructorDeclarationSyntax"/>, <see cref="MethodDeclarationSyntax"/>
|
||||
/// or <see cref="LocalFunctionStatementSyntax"/> tree being visited (used to rewrite local functions).
|
||||
/// </summary>
|
||||
private SyntaxToken currentMethodIdentifier;
|
||||
|
||||
@@ -70,6 +74,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// <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="constructors">The collection of discovered constructors 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>
|
||||
@@ -79,6 +84,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
bool isEntryPoint)
|
||||
@@ -87,6 +93,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
this.shaderType = shaderType;
|
||||
this.staticMethods = staticMethods;
|
||||
this.instanceMethods = instanceMethods;
|
||||
this.constructors = constructors;
|
||||
this.localFunctions = [];
|
||||
this.implicitVariables = [];
|
||||
this.isEntryPoint = isEntryPoint;
|
||||
@@ -99,6 +106,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// <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="constructors">The collection of discovered constructors 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>
|
||||
private ShaderSourceRewriter(
|
||||
@@ -106,12 +114,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
|
||||
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
|
||||
{
|
||||
this.staticMethods = staticMethods;
|
||||
this.instanceMethods = instanceMethods;
|
||||
this.constructors = constructors;
|
||||
this.implicitVariables = [];
|
||||
this.localFunctions = [];
|
||||
}
|
||||
@@ -121,6 +131,37 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, LocalFunctionStatementSyntax> LocalFunctions => this.localFunctions;
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public ConstructorDeclarationSyntax? Visit(ConstructorDeclarationSyntax? node)
|
||||
{
|
||||
if (node is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
this.currentMethodIdentifier = node.Identifier;
|
||||
|
||||
// Constructors have no return type, so there is no return type identifier to replace.
|
||||
// We simply track the type of the type being constructed and then continue normally.
|
||||
// This is done separately where the constructor operation is being processed.
|
||||
ConstructorDeclarationSyntax? updatedNode = (ConstructorDeclarationSyntax?)base.Visit(node)!;
|
||||
|
||||
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (updatedNode is not null)
|
||||
{
|
||||
BlockSyntax implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
|
||||
|
||||
// Add the tracked implicit declarations (at the start of the body)
|
||||
updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements([.. updatedNode.Body!.Statements]);
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
|
||||
{
|
||||
@@ -481,7 +522,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
{
|
||||
if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode)
|
||||
{
|
||||
Diagnostics.Add(InvalidMethodCall, node, method);
|
||||
Diagnostics.Add(InvalidMethodOrConstructorCall, node, method);
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
@@ -491,6 +532,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
DiscoveredTypes,
|
||||
this.staticMethods,
|
||||
this.instanceMethods,
|
||||
this.constructors,
|
||||
ConstantDefinitions,
|
||||
Diagnostics);
|
||||
|
||||
@@ -534,7 +576,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
{
|
||||
if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode)
|
||||
{
|
||||
Diagnostics.Add(InvalidMethodCall, node, method);
|
||||
Diagnostics.Add(InvalidMethodOrConstructorCall, node, method);
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
@@ -544,6 +586,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
DiscoveredTypes,
|
||||
this.instanceMethods,
|
||||
this.instanceMethods,
|
||||
this.constructors,
|
||||
ConstantDefinitions,
|
||||
Diagnostics);
|
||||
|
||||
@@ -591,6 +634,124 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override SyntaxNode VisitUserDefinedObjectCreationExpression(
|
||||
BaseObjectCreationExpressionSyntax node,
|
||||
BaseObjectCreationExpressionSyntax updatedNode,
|
||||
TypeSyntax targetType)
|
||||
{
|
||||
if (SemanticModel.For(node).GetOperation(node) is IObjectCreationOperation { Constructor: IMethodSymbol constructor, Type: INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol })
|
||||
{
|
||||
DiscoveredTypes.Add(typeSymbol);
|
||||
|
||||
// If there are no arguments, check that the constructor is explicitly defined and is not
|
||||
// the default parameterless constructor. In that case, we just fallback to a default value.
|
||||
if (updatedNode.ArgumentList is not { Arguments.Count: > 0 } && constructor.IsImplicitlyDeclared)
|
||||
{
|
||||
return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType);
|
||||
}
|
||||
|
||||
string returnTypeHlslIdentifier = typeSymbol.GetFullyQualifiedName().ToHlslIdentifierName();
|
||||
|
||||
if (!this.constructors.ContainsKey(constructor))
|
||||
{
|
||||
// If we can't find the constructor declaration for the syntax reference of the constructor, it means that either the
|
||||
// type is from another assembly (hence we have no syntax references at all), or the constructor is compiler generated
|
||||
// (even if IsImplicitlyDeclared is false) and a primary constructor. This is deliberately not supported, as there
|
||||
// are very subtle ways in which captures can interact with fields and methods, and we cannot guarantee to track and
|
||||
// rewrite all of them correctly to exactly preserve the same semantics. So we just block such cases entirely as well.
|
||||
if (constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not ConstructorDeclarationSyntax constructorNode)
|
||||
{
|
||||
Diagnostics.Add(InvalidMethodOrConstructorCall, node, constructor);
|
||||
|
||||
return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType);
|
||||
}
|
||||
|
||||
// Chaining constructors is not supported, so emit a diagnostic to inform the user.
|
||||
// The rest of the code will work as usual, but the semantics of the other chained
|
||||
// constructor being invoked is not preserved, so the resulting code is not the same.
|
||||
if (constructorNode.Initializer is not null)
|
||||
{
|
||||
Diagnostics.Add(InvalidBaseConstructorDeclaration, node, constructor);
|
||||
}
|
||||
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(
|
||||
SemanticModel,
|
||||
DiscoveredTypes,
|
||||
this.instanceMethods,
|
||||
this.instanceMethods,
|
||||
this.constructors,
|
||||
ConstantDefinitions,
|
||||
Diagnostics);
|
||||
|
||||
ConstructorDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(constructorNode)!.WithoutTrivia();
|
||||
|
||||
// Extracts the arguments from the list of parameters of the current method
|
||||
ArgumentSyntax[] ExtractArguments()
|
||||
{
|
||||
using ImmutableArrayBuilder<ArgumentSyntax> arguments = new();
|
||||
|
||||
foreach (ParameterSyntax parameter in processedMethod.ParameterList.Parameters)
|
||||
{
|
||||
arguments.Add(Argument(IdentifierName(parameter.Identifier.Text)));
|
||||
}
|
||||
|
||||
return arguments.ToArray();
|
||||
}
|
||||
|
||||
// Create a static method acting as the constructor stub:
|
||||
//
|
||||
// static <TYPE_NAME> __ctor(<PARAMETERS>)
|
||||
// {
|
||||
// <TYPE_NAME> __this = (<TYPE_NAME>)0;
|
||||
//
|
||||
// __this.__ctor__init(<PARAMETERS>);
|
||||
//
|
||||
// return __this;
|
||||
// }
|
||||
MethodDeclarationSyntax stubNode =
|
||||
MethodDeclaration(IdentifierName(returnTypeHlslIdentifier), "__ctor")
|
||||
.AddModifiers(Token(SyntaxKind.StaticKeyword))
|
||||
.WithParameterList(processedMethod.ParameterList)
|
||||
.AddBodyStatements(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(IdentifierName(returnTypeHlslIdentifier)).AddVariables(
|
||||
VariableDeclarator(Identifier("__this")).WithInitializer(EqualsValueClause(
|
||||
CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))))))),
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("__this"),
|
||||
IdentifierName("__ctor__init")))
|
||||
.AddArgumentListArguments(ExtractArguments())),
|
||||
ReturnStatement(IdentifierName("__this")));
|
||||
|
||||
// Create the actual constructor to invoke, as an instance method:
|
||||
//
|
||||
// void __ctor__init(<PARAMETERS>)
|
||||
// {
|
||||
// <CONSTRUCTOR_STATEMENTS>
|
||||
// }
|
||||
MethodDeclarationSyntax ctorNode =
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "__ctor__init")
|
||||
.WithParameterList(processedMethod.ParameterList)
|
||||
.WithBody(processedMethod.Body);
|
||||
|
||||
this.constructors.Add(constructor, (stubNode, ctorNode));
|
||||
}
|
||||
|
||||
// Rewrite the expression to invoke the rewritten constructor:
|
||||
//
|
||||
// <TYPE_NAME>::__ctor(...)
|
||||
return
|
||||
InvocationExpression(IdentifierName($"{returnTypeHlslIdentifier}::__ctor"))
|
||||
.WithArgumentList(updatedNode.ArgumentList!);
|
||||
}
|
||||
|
||||
return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites a sampled texture access.
|
||||
/// </summary>
|
||||
|
||||
@@ -66,3 +66,4 @@ CMPS0057 | ComputeSharp.Shaders | Warning | [Documentation](https://github.com/S
|
||||
CMPS0058 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPS0059 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPS0060 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
CMPS0061 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
|
||||
@@ -57,6 +57,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Setup the semantic model and basic properties
|
||||
@@ -90,6 +91,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
isComputeShader,
|
||||
token);
|
||||
@@ -112,7 +114,8 @@ partial class ComputeShaderDescriptorGenerator
|
||||
diagnostics,
|
||||
structDeclarationSymbol,
|
||||
discoveredTypes,
|
||||
instanceMethods);
|
||||
instanceMethods,
|
||||
constructors);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -359,6 +362,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
/// <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="constructors">The collection of discovered constructors 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>
|
||||
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
|
||||
@@ -370,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
|
||||
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
bool isComputeShader,
|
||||
CancellationToken token)
|
||||
@@ -419,6 +424,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
instanceMethods,
|
||||
constructors,
|
||||
constantDefinitions,
|
||||
diagnostics,
|
||||
isShaderEntryPoint);
|
||||
|
||||
@@ -670,19 +670,19 @@ partial class DiagnosticDescriptors
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a method invocation that is not valid from a shader.
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a method or constructor invocation that is not valid from a shader.
|
||||
/// <para>
|
||||
/// Format: <c>"The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)"</c>.
|
||||
/// Format: <c>"The method or constructor {0} cannot be used in a shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidMethodCall = new(
|
||||
public static readonly DiagnosticDescriptor InvalidMethodOrConstructorCall = new(
|
||||
id: "CMPS0049",
|
||||
title: "Invalid method invocation from a shader",
|
||||
messageFormat: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)",
|
||||
title: "Invalid method or constructor invocation from a shader",
|
||||
messageFormat: "The method or constructor {0} cannot be used in a shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)",
|
||||
category: "ComputeSharp.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "Shaders can only invoke methods that are either HLSL intrinsics or with source available for analysis.",
|
||||
description: "Shaders can only invoke methods or constructors that are either HLSL intrinsics or with source available for analysis.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
@@ -856,4 +856,20 @@ partial class DiagnosticDescriptors
|
||||
isEnabledByDefault: true,
|
||||
description: "A collection expression cannot be used in a compute shader.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a constructor with a base constructor declaration.
|
||||
/// <para>
|
||||
/// Format: <c>"The constructor {0} has a base constructor declaration, which cannot be used in a shader (only standalone constructors are allowed)"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static readonly DiagnosticDescriptor InvalidBaseConstructorDeclaration = new(
|
||||
id: "CMPS0061",
|
||||
title: "Invalid base constructor declaration",
|
||||
messageFormat: "The constructor {0} has a base constructor declaration, which cannot be used in a shader (only standalone constructors are allowed)",
|
||||
category: "ComputeSharp.Shaders",
|
||||
defaultSeverity: DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true,
|
||||
description: "Only standalone constructors (with no base constructor declaration) can be used in a shader.",
|
||||
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma warning disable IDE0290
|
||||
|
||||
namespace ComputeSharp.D2D1.Tests.Effects;
|
||||
|
||||
public struct ColorWrapper
|
||||
{
|
||||
private float4 value;
|
||||
|
||||
public ColorWrapper(float4 color)
|
||||
{
|
||||
this.value = color;
|
||||
}
|
||||
|
||||
public float4 Invert()
|
||||
{
|
||||
return new(Hlsl.Saturate(1.0f - this.value.RGB), 1);
|
||||
}
|
||||
}
|
||||
|
||||
[D2DInputCount(1)]
|
||||
[D2DInputSimple(0)]
|
||||
[D2DShaderProfile(D2D1ShaderProfile.PixelShader50)]
|
||||
[D2DGeneratedPixelShaderDescriptor]
|
||||
public partial struct InvertWithUserTypeWithConstructorEffect : ID2D1PixelShader
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public float4 Execute()
|
||||
{
|
||||
ColorWrapper wrapper = new(D2D.GetInput(0));
|
||||
|
||||
return wrapper.Invert();
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,12 @@ public class EffectsTests
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertWithThresholdEffect(1), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvertWithUserTypeWithConstructor()
|
||||
{
|
||||
D2D1TestRunner.RunAndCompareShader(new InvertWithUserTypeWithConstructorEffect(), null, "Landscape.png", "Landscape_Inverted.png");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Pixelate()
|
||||
{
|
||||
|
||||
@@ -1419,6 +1419,68 @@ public class DiagnosticsTests
|
||||
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0031", "CMPS0047", "CMPS0060");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidBaseConstructorDeclaration()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
|
||||
public struct MyStruct
|
||||
{
|
||||
public MyStruct(int x)
|
||||
{
|
||||
}
|
||||
|
||||
public MyStruct(float x)
|
||||
: this((int)x)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public partial struct MyShader : IComputeShader
|
||||
{
|
||||
public ReadWriteBuffer<int> buffer;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
MyStruct value = new(3.14f);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0047", "CMPS0061");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidMethodOrConstructorCall_PrimaryConstructor()
|
||||
{
|
||||
const string source = """
|
||||
using ComputeSharp;
|
||||
|
||||
public struct MyStruct(int x)
|
||||
{
|
||||
public int PlusOne()
|
||||
{
|
||||
return x + 1;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public partial struct MyShader : IComputeShader
|
||||
{
|
||||
public ReadWriteBuffer<int> buffer;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
buffer[ThreadIds.X] = new MyStruct(ThreadIds.X).PlusOne();
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0047", "CMPS0049");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the output of a source generator.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
using ComputeSharp.Tests.Attributes;
|
||||
using ComputeSharp.Tests.Extensions;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
#pragma warning disable IDE0008, IDE0009, IDE0290, CA1861
|
||||
|
||||
namespace ComputeSharp.Tests;
|
||||
|
||||
[TestClass]
|
||||
public partial class UserDefinedTypeConstructorTests
|
||||
{
|
||||
[CombinatorialTestMethod]
|
||||
[Device(Device.Warp)]
|
||||
public void ImplicitParameterlessConstructor(Device device)
|
||||
{
|
||||
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer([111, 222]);
|
||||
|
||||
device.Get().For(1, new ImplicitParameterlessConstructorShader(buffer));
|
||||
|
||||
int[] results = buffer.ToArray();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 0, 0 }, results);
|
||||
}
|
||||
|
||||
public struct MyValueTypeWithNoConstructor
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public readonly partial struct ImplicitParameterlessConstructorShader(ReadWriteBuffer<int> buffer) : IComputeShader
|
||||
{
|
||||
public void Execute()
|
||||
{
|
||||
MyValueTypeWithNoConstructor valueType = new();
|
||||
|
||||
buffer[0] = valueType.X;
|
||||
buffer[1] = valueType.Y;
|
||||
}
|
||||
}
|
||||
|
||||
[CombinatorialTestMethod]
|
||||
[Device(Device.Warp)]
|
||||
public void ExplicitParameterlessConstructor(Device device)
|
||||
{
|
||||
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(2);
|
||||
|
||||
device.Get().For(1, new ExplicitParameterlessConstructorShader(buffer));
|
||||
|
||||
int[] results = buffer.ToArray();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 42, 12345 }, results);
|
||||
}
|
||||
|
||||
public struct MyValueTypeWithParameterlessConstructor
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
|
||||
public MyValueTypeWithParameterlessConstructor()
|
||||
{
|
||||
X = 42;
|
||||
this.Y = 12345;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public readonly partial struct ExplicitParameterlessConstructorShader(ReadWriteBuffer<int> buffer) : IComputeShader
|
||||
{
|
||||
public void Execute()
|
||||
{
|
||||
MyValueTypeWithParameterlessConstructor valueType = new();
|
||||
|
||||
buffer[0] = valueType.X;
|
||||
buffer[1] = valueType.Y;
|
||||
}
|
||||
}
|
||||
|
||||
// See https://github.com/Sergio0694/ComputeSharp/issues/481
|
||||
[CombinatorialTestMethod]
|
||||
[Device(Device.Warp)]
|
||||
public void ConstructorWithParameters(Device device)
|
||||
{
|
||||
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(8);
|
||||
|
||||
device.Get().For(1, new ConstructorWithParametersShader(buffer));
|
||||
|
||||
int[] results = buffer.ToArray();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 42, 123456, 3, 4, 111, 222, 5, 6 }, results);
|
||||
}
|
||||
|
||||
public struct MyValueTypeWithConstructorWithParameters
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
public float2 Z;
|
||||
|
||||
public MyValueTypeWithConstructorWithParameters(int x, int y, float2 z)
|
||||
{
|
||||
X = x;
|
||||
this.Y = y;
|
||||
this.Z = z;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
public readonly partial struct ConstructorWithParametersShader(ReadWriteBuffer<int> buffer) : IComputeShader
|
||||
{
|
||||
public void Execute()
|
||||
{
|
||||
MyValueTypeWithConstructorWithParameters valueType = new(42, 123456, new float2(3, 4));
|
||||
|
||||
buffer[0] = valueType.X;
|
||||
buffer[1] = valueType.Y;
|
||||
buffer[2] = (int)valueType.Z.X;
|
||||
buffer[3] = (int)valueType.Z.Y;
|
||||
|
||||
var valueType2 = new MyValueTypeWithConstructorWithParameters(111, 222, new float2(5, 6));
|
||||
|
||||
buffer[4] = valueType2.X;
|
||||
buffer[5] = valueType2.Y;
|
||||
buffer[6] = (int)valueType2.Z.X;
|
||||
buffer[7] = (int)valueType2.Z.Y;
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする