Switched static properties to fields, added globals support

このコミットが含まれているのは:
Sergio Pedri committed 2021-03-11 15:38:13 +01:00
1 親 cc9cce4e81
コミット e12169c11e
12ファイル変更
+83 -147

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

+8 -8
ファイルの表示
@@ -20,7 +20,7 @@
private const int MaxSteps = 30;
private const float MinimumDistance = 0.0009f;
private const float normalDistance = 0.0002f;
private const float NormalDistance = 0.0002f;
private const int Iterations = 7;
private const float Scale = 3.0f;
private const float FieldOfView = 1.0f;
@@ -30,11 +30,11 @@
private const float Ambient = 0.32184f;
private const float Diffuse = 0.5f;
private static Float3 LightDir => 1.0f;
private static Float3 LightColor => new(1.0f, 1.0f, 0.858824f);
private static Float3 LightDir2 => new(1.0f, -1.0f, 1.0f);
private static Float3 LightColor2 => new(0, 0.333333f, 1.0f);
private static Float3 Offset => new(0.92858f, 0.92858f, 0.32858f);
private static readonly Float3 LightDir = 1.0f;
private static readonly Float3 LightColor = new(1.0f, 1.0f, 0.858824f);
private static readonly Float3 LightDir2 = new(1.0f, -1.0f, 1.0f);
private static readonly Float3 LightColor2 = new(0, 0.333333f, 1.0f);
private static readonly Float3 Offset = new(0.92858f, 0.92858f, 0.32858f);
/// <summary>
/// Rotates a given <see cref="Float2"/> value by a specified amount.
@@ -104,7 +104,7 @@
/// </summary>
private Float3 getNormal(in Float3 pos)
{
Float3 e = new(0.0f, normalDistance, 0.0f);
Float3 e = new(0.0f, NormalDistance, 0.0f);
return Hlsl.Normalize(new Float3(
DE(pos + e.YXX) - DE(pos - e.YXX),
@@ -143,7 +143,7 @@
float smoothStep = steps + distance / MinimumDistance;
float ao = 1.1f - smoothStep / MaxSteps;
Float3 normal = getNormal(pos - dir * normalDistance * 3.0f);
Float3 normal = getNormal(pos - dir * NormalDistance * 3.0f);
Float3 color = 1.0f;
Float3 light = GetLight(color, normal);
+1 -1
ファイルの表示
@@ -19,7 +19,7 @@
/// </summary>
public readonly float time;
private static Float3x3 m3 => new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f;
private static readonly Float3x3 m3 = new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f;
private static Float2x2 Rotate(in float a)
{
+1 -4
ファイルの表示
@@ -48,7 +48,4 @@ CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+7 -55
ファイルの表示
@@ -590,74 +590,26 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property type.
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader static field type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)"</c>.
/// Format: <c>"The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyType = new(
public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new(
id: "CMPS0043",
title: "Invalid shader constant property type",
messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
title: "Invalid shader static field type",
messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a constant property of a type that is not supported.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyDeclaration = new(
id: "CMPS0044",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a constant property with an invalid declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor NonReadonlyShaderPropertyDeclaration = new(
id: "CMPS0045",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a non readonly property declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InstanceShaderPropertyDeclaration = new(
id: "CMPS0046",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains an instance property declaration.",
description: "A type representing a compute shader contains a static field of a type that is not supported.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="DispatchSize"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidDispatchSizeUsage = new(
id: "CMPS0047",
id: "CMPS0044",
title: "Invalid DispatchSize usage",
messageFormat: "The DispatchSize type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
+5 -2
ファイルの表示
@@ -46,7 +46,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string>> groups)
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string?>> groups)
{
return
ArrayCreationExpression(
@@ -55,7 +55,10 @@ namespace ComputeSharp.SourceGenerators.Helpers
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions(
group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray()));
group.Select(static item => item is null
? LiteralExpression(SyntaxKind.NullLiteralExpression)
: LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))
.ToArray()))).ToArray()));
}
/// <summary>
+1 -1
ファイルの表示
@@ -164,7 +164,7 @@ namespace ComputeSharp.SourceGenerators
IFieldSymbol fieldSymbol in
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst
!fieldSymbol.IsConst && !fieldSymbol.IsStatic
select fieldSymbol)
{
string typeName = fieldSymbol.Type.GetFullMetadataName();
+32 -44
ファイルの表示
@@ -77,7 +77,7 @@ namespace ComputeSharp.SourceGenerators
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
var staticConstants = GetConstantProperties(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
// Create the compilation unit with the source attribute
var source =
@@ -91,7 +91,7 @@ namespace ComputeSharp.SourceGenerators
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)),
AttributeArgument(NestedArrayExpression(staticConstants)),
AttributeArgument(NestedArrayExpression(staticFields)),
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
@@ -174,7 +174,7 @@ namespace ComputeSharp.SourceGenerators
}
/// <summary>
/// Gets a sequence of shader static constant properties and their mapped names.
/// Gets a sequence of shader static fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the type to process.</param>
@@ -182,9 +182,9 @@ namespace ComputeSharp.SourceGenerators
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant properties in <paramref name="structDeclarationSymbol"/>.</returns>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string>> GetConstantProperties(
private static IEnumerable<IEnumerable<string?>> GetStaticFields(
GeneratorExecutionContext context,
SemanticModel semanticModel,
StructDeclarationSyntax structDeclaration,
@@ -192,55 +192,43 @@ namespace ComputeSharp.SourceGenerators
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var propertyDeclaration in structDeclaration.Members.OfType<PropertyDeclarationSyntax>())
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
{
IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration)!;
if (!propertySymbol.IsStatic)
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
context.ReportDiagnostic(InstanceShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name);
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator)!;
continue;
}
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
{
continue;
}
if (!propertySymbol.IsReadOnly)
{
context.ReportDiagnostic(NonReadonlyShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name);
// Constant properties must be of a primitive, vector or matrix type
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
{
context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
continue;
}
continue;
}
// Constant properties must be named type symbols
if (propertySymbol.Type is not INamedTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
continue;
}
string typeDeclaration = fieldSymbol.IsReadOnly switch
{
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
};
string metadataName = typeSymbol.GetFullMetadataName();
StaticFieldRewriter staticFieldRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
// Constant properties must be of a primitive, vector or matrix type
if (!HlslKnownTypes.IsKnownHlslType(metadataName))
{
context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type);
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString();
continue;
}
ConstantPropertyRewriter constantPropertyRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
if (constantPropertyRewriter.Visit(propertyDeclaration) is ExpressionSyntax expression)
{
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(propertySymbol.Name, out string? mapping);
yield return new[] { mapping ?? propertySymbol.Name, typeName, expression.NormalizeWhitespace().ToFullString() };
yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment };
}
}
}
@@ -14,18 +14,18 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# static properties to convert to HLSL static constants.
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# static field to convert to HLSL static fields (possibly constant).
/// </summary>
internal sealed class ConstantPropertyRewriter : HlslSourceRewriter
internal sealed class StaticFieldRewriter : HlslSourceRewriter
{
/// <summary>
/// Creates a new <see cref="ConstantPropertyRewriter"/> instance with the specified parameters.
/// Creates a new <see cref="StaticFieldRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
public ConstantPropertyRewriter(
public StaticFieldRewriter(
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
@@ -35,22 +35,14 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(PropertyDeclarationSyntax? node)
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
{
if (node!.ExpressionBody is null)
if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
{
Context.ReportDiagnostic(
InvalidShaderConstantPropertyDeclaration,
node,
SemanticModel.GetDeclaredSymbol(node.FirstAncestorOrSelf<StructDeclarationSyntax>()!)!,
SemanticModel.GetDeclaredSymbol(node)!.Name);
return null;
return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
}
ArrowExpressionClauseSyntax? updatedNode = (ArrowExpressionClauseSyntax?)Visit(node.ExpressionBody)!;
return updatedNode.Expression;
return null;
}
/// <inheritdoc/>
+5 -5
ファイルの表示
@@ -25,7 +25,7 @@ namespace ComputeSharp.__Internals
/// <param name="executeMethod">The source code for the <see cref="IComputeShader.Execute"/> method.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="defines">The collection of discovered defines.</param>
/// <param name="constants">The collection of discovered constants.</param>
/// <param name="staticFields">The collection of discovered static fields.</param>
/// <param name="sharedBuffers">The collection of group shared buffers.</param>
public IComputeShaderSourceAttribute(
Type shaderType,
@@ -34,7 +34,7 @@ namespace ComputeSharp.__Internals
string executeMethod,
string[] methods,
object[] defines,
object[] constants,
object[] staticFields,
object[] sharedBuffers)
{
ShaderType = shaderType;
@@ -43,7 +43,7 @@ namespace ComputeSharp.__Internals
ExecuteMethod = executeMethod;
Methods = methods;
Defines = defines.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
Constants = constants.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
StaticFields = staticFields.Cast<string?[]>().ToDictionary(static arg => arg[0]!, static arg => (arg[1]!, arg[2]));
SharedBuffers = sharedBuffers.Cast<object[]>().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2]));
}
@@ -78,9 +78,9 @@ namespace ComputeSharp.__Internals
internal IReadOnlyDictionary<string, string> Defines { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// Gets the collection of discovered static fields.
/// </summary>
internal IReadOnlyDictionary<string, (string Type, string Assignment)> Constants { get; }
internal IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of discovered shared buffers.
+11 -7
ファイルの表示
@@ -51,19 +51,23 @@ namespace ComputeSharp.Shaders.Renderer
builder.AppendLine(define.Value);
}
// Static constants
if (info.ConstantsInfo.Count > 0)
// Static fields
if (info.StaticFields.Count > 0)
{
builder.AppendLine();
foreach (var constant in info.ConstantsInfo)
foreach (var constant in info.StaticFields)
{
builder.Append("static const ");
builder.Append(constant.Value.Type);
builder.Append(constant.Value.TypeDeclaration);
builder.Append(' ');
builder.Append(constant.Key);
builder.Append(" = ");
builder.Append(constant.Value.Assignment);
if (constant.Value.Assignment is string assignment)
{
builder.Append(" = ");
builder.Append(assignment);
}
builder.AppendLine(";");
}
}
+2 -2
ファイルの表示
@@ -34,9 +34,9 @@ namespace ComputeSharp.Shaders.Translation
IReadOnlyDictionary<string, string> DefinesInfo { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// Gets the collection of discovered static fields.
/// </summary>
IReadOnlyDictionary<string, (string Type, string Assignment)> ConstantsInfo { get; }
IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of declared types for the shader.
+2 -2
ファイルの表示
@@ -114,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, string Assignment)> ConstantsInfo { get; private set; }
public IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; private set; }
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; private set; }
@@ -146,7 +146,7 @@ namespace ComputeSharp.Shaders.Translation
private void LoadMethodMetadata()
{
EntryPoint = Attribute.ExecuteMethod;
ConstantsInfo = Attribute.Constants;
StaticFields = Attribute.StaticFields;
SharedBuffers = Attribute.SharedBuffers;
this.declaredTypes.AddRange(Attribute.Types);