Added initial BuildHlslString source generator implementation

Not actually working yet, pending other changes to pipeline creation
このコミットが含まれているのは:
Sergio Pedri committed 2021-07-12 15:58:52 +02:00
1 親 6302cf005c
コミット e432a197a0
9ファイル変更
+561 -209

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

+333 -20
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
@@ -16,6 +17,7 @@ using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618
@@ -83,7 +85,7 @@ namespace ComputeSharp.SourceGenerators
// Explore the syntax tree and extract the processed info
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture");
var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
@@ -92,6 +94,22 @@ namespace ComputeSharp.SourceGenerators
var processedConstants = GetProcessedConstants(constantDefinitions);
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
GenerateRenderMethod(
context,
structDeclaration,
structDeclarationSymbol,
processedConstants,
staticFields,
processedTypes,
isComputeShader,
processedMembers,
implicitTextureType,
isSamplerUsed,
sharedBuffers,
forwardDeclarations,
processedMethods,
entryPoint);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddUsings(
@@ -99,16 +117,16 @@ namespace ComputeSharp.SourceGenerators
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))),
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(ArrayExpression(implicitTextureField)),
AttributeArgument(ArrayExpression(implicitSamplerField)),
AttributeArgument(NestedArrayExpression(processedMembers)),
AttributeArgument(ArrayExpression(forwardDeclarations)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)),
AttributeArgument(NestedArrayExpression(staticFields)),
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(""))), // TODO
AttributeArgument(ArrayExpression(Array.Empty<string>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>())), // TODO
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>()))))) // TODO
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
@@ -127,7 +145,7 @@ namespace ComputeSharp.SourceGenerators
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string>> GetProcessedFields(
private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types,
@@ -176,7 +194,8 @@ namespace ComputeSharp.SourceGenerators
continue;
}
else if (!HlslKnownTypes.IsKnownHlslType(metadataName))
else if (typeSymbol.IsUnmanagedType &&
!HlslKnownTypes.IsKnownHlslType(metadataName))
{
// Track the type if it's a custom struct
types.Add(typeSymbol);
@@ -187,7 +206,7 @@ namespace ComputeSharp.SourceGenerators
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
// Yield back the current mapping for the name (if the name used a reserved keyword)
yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName };
yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName);
}
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
@@ -208,7 +227,7 @@ namespace ComputeSharp.SourceGenerators
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string?>> GetStaticFields(
private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
GeneratorExecutionContext context,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
@@ -256,7 +275,7 @@ namespace ComputeSharp.SourceGenerators
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString();
yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment };
yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment);
}
}
}
@@ -295,7 +314,7 @@ namespace ComputeSharp.SourceGenerators
continue;
}
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
@@ -414,14 +433,14 @@ namespace ComputeSharp.SourceGenerators
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
[Pure]
internal static IEnumerable<IEnumerable<string>> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var constant in constantDefinitions)
{
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return new string[] { constantName, constant.Value };
yield return (constantName, constant.Value);
}
}
@@ -475,6 +494,300 @@ namespace ComputeSharp.SourceGenerators
context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
}
}
private static void GenerateRenderMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<string> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<string>? forwardDeclarations,
IEnumerable<string> processedMethods,
string executeMethod)
{
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
IEnumerable<StatementSyntax> bodyStatements = GenerateRenderMethodBody(
definedConstants,
staticFields,
declaredTypes,
isComputeShader,
instanceFields,
implicitTextureType,
isSamplerUsed,
sharedBuffers,
forwardDeclarations,
processedMethods,
executeMethod);
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public struct ShaderType : IShader<ShaderType>
// {
// [GeneratedCode("...", "...")]
// [DebuggerNonUserCode]
// [ExcludeFromCodeCoverage]
// [EditorBrowsable(EditorBrowsableState.Never)]
// [Obsolete("This method is not intended to be called directly by user code")]
// public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
// {
// <BODY>
// }
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers)
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("IShader"))
.AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("BuildHlslString"))
.AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code")))))))
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(bodyStatements)));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Add the method source attribute
context.AddSource("PREVIEW" + structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<string> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<string>? forwardDeclarations,
IEnumerable<string> processedMethods,
string executeMethod)
{
// Header
yield return ParseStatement("builder.AppendLine(\"// ================================================\");");
yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");");
yield return ParseStatement("builder.AppendLine(\"// ================================================\");");
yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");");
yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");");
// Group size constants
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");");
yield return ParseStatement("builder.AppendLine(threadsX.ToString());");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");");
yield return ParseStatement("builder.AppendLine(threadsY.ToString());");
yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");");
yield return ParseStatement("builder.AppendLine(threadsZ.ToString());");
// Define declarations
foreach (var (name, value) in definedConstants)
{
yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");");
}
// Static fields
if (staticFields.Any())
{
yield return ParseStatement("builder.AppendLine();");
foreach (var field in staticFields)
{
if (field.Assignment is string assignment)
{
yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");");
}
else
{
yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");");
}
}
}
// Declared types
foreach (var type in declaredTypes)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{type}\");");
}
// Captured variables
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");");
yield return ParseStatement("builder.AppendLine('{');");
yield return ParseStatement("builder.AppendLine(\" uint __x;\");");
yield return ParseStatement("builder.AppendLine(\" uint __y;\");");
if (isComputeShader)
{
yield return ParseStatement("builder.AppendLine(\" uint __z;\");");
}
// User-defined values
foreach (var instanceField in instanceFields)
{
if (instanceField.Symbol.Type.IsUnmanagedType)
{
yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName};\");");
}
}
yield return ParseStatement("builder.AppendLine('}');");
int
constantBuffersCount = 0,
readOnlyBuffersCount = 0,
readWriteBuffersCount = 0;
// Optional implicit texture field
if (!isComputeShader)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");");
}
// Optional sampler field
if (isSamplerUsed)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");");
}
// Resources
foreach (var instanceField in instanceFields)
{
string metadataName = instanceField.Symbol.GetFullMetadataName();
if (HlslKnownTypes.IsConstantBufferType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"cbuffer _{instanceField.HlslName} : register(b{constantBuffersCount++})\");");
yield return ParseStatement("builder.AppendLine('{');");
yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName}[2];\");");
yield return ParseStatement("builder.AppendLine('}');");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(t{readOnlyBuffersCount++});\");");
}
else if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(u{readWriteBuffersCount++});\");");
}
}
// Shared buffers
foreach (var sharedBuffer in sharedBuffers)
{
object count = (object?)sharedBuffer.Count ?? "threadsX * threadsY * threadsZ";
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"groupshared {sharedBuffer.Type} {sharedBuffer.Name} [{count}];\");");
}
// Forward declarations
if (forwardDeclarations is not null)
{
foreach (var forwardDeclaration in forwardDeclarations)
{
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");");
}
}
// Captured methods
if (processedMethods is not null)
{
foreach (var method in processedMethods)
{
yield return ParseStatement("builder.AppendLine();");
yield return
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method)))));
}
}
// Entry point
yield return ParseStatement("builder.AppendLine();");
yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");");
yield return
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod)))));
}
}
}
+31
ファイルの表示
@@ -101,6 +101,16 @@ namespace ComputeSharp.SourceGenerators.Mappings
return knownTypes;
}
/// <summary>
/// Checks whether or not a given type name matches a constant buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a constant buffer type.</returns>
public static bool IsConstantBufferType(string typeName)
{
return typeName == "ComputeSharp.ConstantBuffer`1";
}
/// <summary>
/// Checks whether or not a given type name matches a structured buffer type.
/// </summary>
@@ -118,6 +128,27 @@ namespace ComputeSharp.SourceGenerators.Mappings
};
}
/// <summary>
/// Checks whether or not a given type name matches a readonly typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
public static bool IsReadOnlyTypedResourceType(string typeName)
{
switch (typeName)
{
case "ComputeSharp.ReadOnlyBuffer`1":
case "ComputeSharp.ReadOnlyTexture2D`1":
case "ComputeSharp.ReadOnlyTexture2D`2":
case "ComputeSharp.ReadOnlyTexture3D`1":
case "ComputeSharp.ReadOnlyTexture3D`2":
case "ComputeSharp.IReadOnlyTexture2D`1":
case "ComputeSharp.IReadOnlyTexture3D`1":
return true;
default: return false;
};
}
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
+3 -2
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
@@ -83,7 +84,7 @@ namespace ComputeSharp.SourceGenerators
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
AttributeArgument(NestedArrayExpression(Array.Empty<string[]>()))))) // TODO
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
+12 -1
ファイルの表示
@@ -17,7 +17,7 @@ namespace ComputeSharp.__Internals
/// </summary>
/// <returns>The unique dispatch identifier for the shader.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
[Obsolete("This method is not intended to be used directly by user code")]
int GetDispatchId();
/// <summary>
@@ -33,5 +33,16 @@ namespace ComputeSharp.__Internals
[Obsolete("This method is not intended to be called directly by user code")]
void LoadDispatchData<TDataLoader>(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z)
where TDataLoader : struct, IDispatchDataLoader;
/// <summary>
/// Builds the HLSL source code for the current shader instance.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write the HLSL source to.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ);
}
}
+2 -166
ファイルの表示
@@ -1,8 +1,5 @@
using System;
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
@@ -191,166 +188,5 @@ namespace ComputeSharp.Shaders.Renderer
return builder;
}
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
[Pure]
public static ArrayPoolStringBuilder Create()
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(1024);
builder.index = 0;
return builder;
}
/// <inheritdoc/>
public ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
}
/// <summary>
/// Appends a character to the current buffer.
/// </summary>
public void Append(char character)
{
EnsureCapacity(1);
this.array[this.index++] = character;
}
/// <summary>
/// Appends the input sequence of characters to the current buffer, with a trailing new line.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void AppendLine(string value)
{
EnsureCapacity(value.Length + 1);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a character and a new line to the current buffer.
/// </summary>
public void AppendLine(char character)
{
EnsureCapacity(2);
this.array[this.index++] = character;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a new line to the current buffer.
/// </summary>
public void AppendLine()
{
EnsureCapacity(1);
this.array[this.index++] = '\n';
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(array);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}
}
}
+169
ファイルの表示
@@ -0,0 +1,169 @@
using System;
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
[Pure]
public static ArrayPoolStringBuilder Create()
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(1024);
builder.index = 0;
return builder;
}
/// <inheritdoc/>
public ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
}
/// <summary>
/// Appends a character to the current buffer.
/// </summary>
public void Append(char character)
{
EnsureCapacity(1);
this.array[this.index++] = character;
}
/// <summary>
/// Appends the input sequence of characters to the current buffer, with a trailing new line.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void AppendLine(string value)
{
EnsureCapacity(value.Length + 1);
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
this.index += value.Length;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a character and a new line to the current buffer.
/// </summary>
public void AppendLine(char character)
{
EnsureCapacity(2);
this.array[this.index++] = character;
this.array[this.index++] = '\n';
}
/// <summary>
/// Appends a new line to the current buffer.
/// </summary>
public void AppendLine()
{
EnsureCapacity(1);
this.array[this.index++] = '\n';
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(array);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}
}
+9 -9
ファイルの表示
@@ -237,19 +237,19 @@ namespace ComputeSharp.Shaders
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader<T> shaderData)
private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader<T> shaderData)
{
// Load the input shader
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create();
// Render the loaded shader
using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader);
shader.BuildHlslString(ref builder, threadsX, threadsY, threadsZ);
// Compile the loaded shader to HLSL bytecode
IDxcBlobObject shaderBytecode = new(ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan));
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan);
// Get the cached shader data
shaderData = new CachedShader<T>(shaderLoader, shaderBytecode);
builder.Dispose();
IDxcBlobObject shaderBytecode = new(dxcBlobBytecode.Get());
shaderData = new CachedShader<T>(null!, shaderBytecode); // TODO
}
/// <summary>
+2 -2
ファイルの表示
@@ -17,9 +17,9 @@ namespace ComputeSharp.Shaders.Translation.Interop
/// Creates a new <see cref="IDxcBlobObject"/> instance with the specified parameters.
/// </summary>
/// <param name="dxcBlob">The <see cref="IDxcBlob"/> instance to wrap.</param>
public IDxcBlobObject(ComPtr<IDxcBlob> dxcBlob)
public IDxcBlobObject(IDxcBlob* dxcBlob)
{
this.dxcBlob = dxcBlob;
this.dxcBlob = new ComPtr<IDxcBlob>(dxcBlob);
}
/// <summary>
-9
ファイルの表示
@@ -26,11 +26,6 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType<T>();
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
@@ -254,21 +249,18 @@ namespace ComputeSharp.Shaders.Translation
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++));
}
else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++));
}
else if (HlslKnownTypes.IsReadWriteResourceType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount));
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
}
else if (fieldInfo.GetValue(shader) is Delegate func)
@@ -289,7 +281,6 @@ namespace ComputeSharp.Shaders.Translation
}
else
{
this.capturedFields.Add(fieldInfo);
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
}
}