Removed legacy shader loading code

このコミットが含まれているのは:
Sergio Pedri committed 2021-07-12 15:58:52 +02:00
1 親 f8207f11ff
コミット 7552dd5189
11ファイル変更
+3 -959

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

-3
ファイルの表示
@@ -14,8 +14,6 @@
<Compile Include="..\ComputeSharp\Core\Attributes\AutoConstructorAttribute.cs" Link="Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="Core\Attributes\GroupSharedAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" Link="Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\ComputeRoot32BitConstantsAttribute.cs" Link="Core\Attributes\__Internals\ComputeRoot32BitConstantsAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" Link="Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchSize.cs" Link="Core\Dispatch\DispatchSize.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\GridIds.cs" Link="Core\Dispatch\GridIds.cs" />
@@ -25,7 +23,6 @@
<Compile Include="..\ComputeSharp\Core\Dispatch\ThreadIds.Normalized.cs" Link="Core\Dispatch\ThreadIds.Normalized.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\InvalidExecutionContextException.cs" Link="Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\MissingMethodSourceException.cs" Link="Core\Exceptions\MissingMethodSourceException.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\MissingShaderMetadataException.cs" Link="Core\Exceptions\MissingShaderMetadataException.cs" />
<Compile Include="..\ComputeSharp\Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
-29
ファイルの表示
@@ -1,29 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on the number of 32 bit constants for a given shader.
/// </summary>
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class ComputeRoot32BitConstantsAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="ComputeRoot32BitConstantsAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="count">The number of 32 bit constants for the annotated method.</param>
public ComputeRoot32BitConstantsAttribute(int count)
{
Count = count;
}
/// <summary>
/// Gets the number of 32 bit constants for the annotated method.
/// </summary>
internal int Count { get; }
}
}
-134
ファイルの表示
@@ -1,134 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.Exceptions;
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on a processed compute shader that can be executed.
/// </summary>
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class IComputeShaderSourceAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="IComputeShaderSourceAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type of the current shader.</param>
/// <param name="types">The collection of custom types.</param>
/// <param name="implicitTextureField">The implicit texture field info, if present.</param>
/// <param name="implicitSamplerFields">The implicit texture sampler field info, if present.</param>
/// <param name="fields">The mapped collection of shader fields.</param>
/// <param name="forwardDeclarations">The forward declarations for static methods.</param>
/// <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="staticFields">The collection of discovered static fields.</param>
/// <param name="sharedBuffers">The collection of group shared buffers.</param>
public IComputeShaderSourceAttribute(
Type shaderType,
string[] types,
string[]? implicitTextureField,
string[]? implicitSamplerFields,
object[] fields,
string[] forwardDeclarations,
string executeMethod,
string[] methods,
object[] defines,
object[] staticFields,
object[] sharedBuffers)
{
ShaderType = shaderType;
Types = types;
ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]);
ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]);
Fields = fields.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
ForwardDeclarations = forwardDeclarations;
ExecuteMethod = executeMethod;
Methods = methods;
Defines = defines.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
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]));
}
/// <summary>
/// Gets the type of the current shader.
/// </summary>
internal Type ShaderType { get; }
/// <summary>
/// Gets the collection of processed custom types.
/// </summary>
internal IReadOnlyCollection<string> Types { get; }
/// <summary>
/// Gets the mapping for the implicit texture field, if the shader is a pixel shader.
/// </summary>
internal (string Name, string Type)? ImplicitTextureField { get; }
/// <summary>
/// Gets the mapping for the implicit sampler field, if necessary.
/// </summary>
internal (string Name, string Type)? ImplicitSamplerField { get; }
/// <summary>
/// Gets the mapping of field names.
/// </summary>
internal IReadOnlyDictionary<string, (string Name, string Type)> Fields { get; }
/// <summary>
/// The forward declarations for static methods.
/// </summary>
internal IReadOnlyCollection<string> ForwardDeclarations { get; }
/// <summary>
/// Gets the source code for the <see cref="IComputeShader.Execute"/> method.
/// </summary>
internal string ExecuteMethod { get; }
/// <summary>
/// Gets the collection of processed methods.
/// </summary>
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered define declarations.
/// </summary>
internal IReadOnlyDictionary<string, string> Defines { get; }
/// <summary>
/// Gets the collection of discovered static fields.
/// </summary>
internal IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of discovered shared buffers.
/// </summary>
internal IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
/// <summary>
/// Gets the associated <see cref="IComputeShaderSourceAttribute"/> instance for a specified type.
/// </summary>
/// <typeparam name="T">The shader type to get the attribute for.</typeparam>
/// <returns>The associated <see cref="IComputeShaderSourceAttribute"/> instance for type <typeparamref name="T"/>.</returns>
[Pure]
internal static IComputeShaderSourceAttribute GetForType<T>()
{
IEnumerable<IComputeShaderSourceAttribute> attributes = typeof(T).Assembly.GetCustomAttributes<IComputeShaderSourceAttribute>();
IComputeShaderSourceAttribute? attribute = attributes.SingleOrDefault(static attribute => attribute.ShaderType == typeof(T));
if (attribute is null)
{
MissingShaderMetadataException.Throw<T>();
}
return attribute!;
}
}
}
-47
ファイルの表示
@@ -1,47 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Text;
namespace ComputeSharp.Exceptions
{
/// <summary>
/// A custom <see cref="Exception"/> type that indicates when metadata is missing for a given shader.
/// </summary>
public sealed class MissingShaderMetadataException : Exception
{
/// <summary>
/// Creates a new <see cref="MissingShaderMetadataException"/> instance.
/// </summary>
/// <param name="error">The error message to include in the exception..</param>
private MissingShaderMetadataException(string error)
: base(error)
{
}
/// <summary>
/// Gets a formatted exception message for a given error.
/// </summary>
/// <param name="type">The type of shader that was failed to be loaded.</param>
/// <returns>A new <see cref="MissingShaderMetadataException"/> instance with a formatted error message.</returns>
[Pure]
private static MissingShaderMetadataException Create(Type type)
{
StringBuilder builder = new(512);
builder.AppendLine($"Failed to retrieve the shader metadata for type {type}.");
builder.AppendLine("This usually indicates that the necessary source generator failed to run. Make sure to be using a IDE with full support " +
"for source generators, and that there are no build warnings in the errors window upon building your project. If a source " +
"generator fails to run correctly, please open an issue at https://github.com/Sergio0694/ComputeSharp and include a working repro along with it.");
return new(builder.ToString());
}
/// <summary>
/// Throws a new <see cref="MissingShaderMetadataException"/> for a given delegate.
/// </summary>
internal static void Throw<T>()
{
throw Create(typeof(T));
}
}
}
+3 -4
ファイルの表示
@@ -2,7 +2,6 @@
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Translation;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
@@ -103,13 +102,13 @@ namespace ComputeSharp.Interop
private static unsafe void GetNonGenericShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
where T : struct, IShader<T>
{
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
ArrayPoolStringBuilder shaderSource = ArrayPoolStringBuilder.Create();
using var shaderSource = HlslShaderRenderer.Render(1, 1, 1, shaderLoader);
shader.BuildHlslString(ref shaderSource, 1, 1, 1);
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan);
using ComPtr<IDxcUtils> dxcUtils = default;
Guid dxcLibraryClsid = FX.CLSID_DxcLibrary;
FX.DxcCreateInstance(&dxcLibraryClsid, FX.__uuidof<IDxcUtils>(), dxcUtils.GetVoidAddressOf()).Assert();
-192
ファイルの表示
@@ -1,192 +0,0 @@
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
namespace ComputeSharp.Shaders.Renderer
{
/// <summary>
/// A type that renders an HLSL template from the previously loaded shader data.
/// </summary>
internal static class HlslShaderRenderer
{
/// <summary>
/// Renders a new HLSL shader source with the given parameters.
/// </summary>
/// <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>
/// <param name="info">The input <see cref="IShaderLoader"/> instance with the shader information.</param>
/// <returns>The source code for the new HLSL shader.</returns>
[Pure]
public static ArrayPoolStringBuilder Render(int threadsX, int threadsY, int threadsZ, IShaderLoader info)
{
var builder = ArrayPoolStringBuilder.Create();
// Header
builder.AppendLine("// ================================================");
builder.AppendLine("// AUTO GENERATED");
builder.AppendLine("// ================================================");
builder.AppendLine("// This shader was created by ComputeSharp.");
builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp.");
// Group size constants
builder.AppendLine();
builder.Append("#define __GroupSize__get_X ");
builder.AppendLine(threadsX.ToString());
builder.Append("#define __GroupSize__get_Y ");
builder.AppendLine(threadsY.ToString());
builder.Append("#define __GroupSize__get_Z ");
builder.AppendLine(threadsZ.ToString());
// Define declarations
foreach (var define in info.DefinesInfo)
{
builder.Append("#define ");
builder.Append(define.Key);
builder.Append(' ');
builder.AppendLine(define.Value);
}
// Static fields
if (info.StaticFields.Count > 0)
{
builder.AppendLine();
foreach (var constant in info.StaticFields)
{
builder.Append(constant.Value.TypeDeclaration);
builder.Append(' ');
builder.Append(constant.Key);
if (constant.Value.Assignment is string assignment)
{
builder.Append(" = ");
builder.Append(assignment);
}
builder.AppendLine(";");
}
}
// Declared types
foreach (var type in info.DeclaredTypes)
{
builder.AppendLine();
builder.AppendLine(type);
}
// Captured variables
builder.AppendLine();
builder.AppendLine("cbuffer _ : register(b0)");
builder.AppendLine('{');
builder.AppendLine(" uint __x;");
builder.AppendLine(" uint __y;");
if (info.IsComputeShader)
{
builder.AppendLine(" uint __z;");
}
foreach (var local in info.FieldsInfo)
{
builder.Append(" ");
builder.Append(local.FieldType);
builder.Append(' ');
builder.Append(local.FieldName);
builder.AppendLine(';');
}
builder.AppendLine('}');
// Resources
foreach (var resource in info.HlslResourceInfo)
{
builder.AppendLine();
switch (resource)
{
// Constant buffer go to cbuffer fields with a dummy local
case HlslResourceInfo.Constant _:
builder.Append("cbuffer _");
builder.Append(resource.FieldName);
builder.Append(" : register(b");
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(')');
builder.AppendLine('{');
builder.Append(" ");
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.AppendLine("[2];");
builder.AppendLine('}');
break;
// Structured buffer have the same syntax but different id
case HlslResourceInfo.ReadOnly _:
char registerId = 't';
goto StructuredBuffer;
case HlslResourceInfo.ReadWrite _:
registerId = 'u';
StructuredBuffer:
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.Append(" : register(");
builder.Append(registerId);
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(");");
break;
// Texture samplers
case HlslResourceInfo.Sampler _:
builder.Append(resource.FieldType);
builder.Append(' ');
builder.Append(resource.FieldName);
builder.Append(" : register(");
builder.Append('s');
builder.Append(resource.RegisterIndex.ToString());
builder.AppendLine(");");
break;
}
}
// Shared buffers
foreach (var buffer in info.SharedBuffers)
{
builder.AppendLine();
builder.Append("groupshared ");
builder.Append(buffer.Value.Type);
builder.Append(' ');
builder.Append(buffer.Key);
builder.Append('[');
if (buffer.Value.Count is int count) builder.Append(count.ToString());
else builder.Append((threadsX * threadsY * threadsZ).ToString());
builder.AppendLine("];");
}
// Forward declarations
foreach (var declaration in info.ForwardDeclarations)
{
builder.AppendLine();
builder.AppendLine(declaration);
}
// Captured methods
foreach (var function in info.MethodsInfo)
{
builder.AppendLine();
builder.AppendLine(function);
}
// Entry point
builder.AppendLine();
builder.AppendLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
builder.AppendLine(info.EntryPoint);
return builder;
}
}
}
-11
ファイルの表示
@@ -1,11 +0,0 @@
#pragma warning disable CS1572, CS1573
namespace ComputeSharp.Shaders.Renderer.Models
{
/// <summary>
/// A model that contains info on a shader field.
/// </summary>
/// <param name="FieldType">The type of the current field in the HLSL shader.</param>
/// <param name="FieldName">The name to use for the current field.</param>
internal record CapturedFieldInfo(string FieldType, string FieldName);
}
-43
ファイルの表示
@@ -1,43 +0,0 @@
namespace ComputeSharp.Shaders.Renderer.Models
{
/// <summary>
/// A model that contains info on a shader resource field.
/// </summary>
/// <param name="FieldType">The type of the current field in the HLSL shader.</param>
/// <param name="FieldName">The name to use for the current field.</param>
/// <param name="RegisterIndex">The register index to bind the resource to.</param>
internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex)
: CapturedFieldInfo(FieldType, FieldName)
{
/// <summary>
/// A model that represents a captured constant buffer in a shader.
/// </summary>
/// <inheritdoc/>
public sealed record Constant(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured readonly typed resource in a shader.
/// Maps to either <see cref="ComputeSharp.ReadOnlyBuffer{T}"/> or <see cref="ComputeSharp.ReadOnlyTexture2D{T}"/>.
/// </summary>
/// <inheritdoc/>
public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured writeable buffer in a shader.
/// Maps to either <see cref="ComputeSharp.ReadWriteBuffer{T}"/> or <see cref="ComputeSharp.ReadWriteTexture2D{T}"/>.
/// </summary>
/// <inheritdoc/>
public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
/// <summary>
/// A model that represents a captured sampler in a shader.
/// This resource type doesn't have a mapping to a public API.
/// </summary>
/// <inheritdoc/>
public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex)
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
}
}
-61
ファイルの表示
@@ -1,61 +0,0 @@
using System.Collections.Generic;
using ComputeSharp.Shaders.Renderer.Models;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of any type.
/// </summary>
internal interface IShaderLoader
{
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
string EntryPoint { get; }
/// <summary>
/// Gets whether or not the current shader is a compute shader (and not a pixel shader).
/// </summary>
bool IsComputeShader { get; }
/// <summary>
/// Gets the collection of <see cref="Renderer.Models.HlslResourceInfo"/> items for the shader fields.
/// </summary>
IReadOnlyList<HlslResourceInfo> HlslResourceInfo { get; }
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
IReadOnlyList<CapturedFieldInfo> FieldsInfo { get; }
/// <summary>
/// Gets the forward declarations for static methods.
/// </summary>
IReadOnlyCollection<string> ForwardDeclarations { get; }
/// <summary>
/// Gets the collection of methods to be used in the shader.
/// </summary>
IReadOnlyCollection<string> MethodsInfo { get; }
/// <summary>
/// Gets the collection of define declarations to be added to the shader.
/// </summary>
IReadOnlyDictionary<string, string> DefinesInfo { get; }
/// <summary>
/// Gets the collection of discovered static fields.
/// </summary>
IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; }
/// <summary>
/// Gets the collection of declared types for the shader.
/// </summary>
IReadOnlyCollection<string> DeclaredTypes { get; }
/// <summary>
/// Gets the collection of discovered group shared buffers.
/// </summary>
IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
}
}
-147
ファイルの表示
@@ -1,147 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
namespace ComputeSharp.Shaders.Mappings
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// </summary>
internal static class HlslKnownTypes
{
/// <summary>
/// The set of HLSL vector types.
/// </summary>
private static HashSet<Type> HlslMappedVectorTypes { get; } = new(new[]
{
typeof(Bool2), typeof(Bool3), typeof(Bool4),
typeof(Int2), typeof(Int3), typeof(Int4),
typeof(UInt2), typeof(UInt3), typeof(UInt4),
typeof(Float2), typeof(Float3), typeof(Float4),
typeof(Double2), typeof(Double3), typeof(Double4)
});
/// <summary>
/// The set of HLSL matrix types.
/// </summary>
private static HashSet<Type> HlslMappedMatrixTypes { get; } = new(new[]
{
typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4),
typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4),
typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4),
typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4),
typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4),
typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4),
typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4),
typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4),
typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4),
typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4),
typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4),
typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4),
typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4),
typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4),
typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4),
typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4),
typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4),
typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4),
typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4),
typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4)
});
/// <summary>
/// Checks whether or not the input type is a known scalar type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL scalar type.</returns>
[Pure]
public static bool IsKnownScalarType(Type type) => type == typeof(bool) ||
type == typeof(Bool) ||
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(float) ||
type == typeof(double);
/// <summary>
/// Checks whether or not the input type is a known vector type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL vector type.</returns>
[Pure]
public static bool IsKnownVectorType(Type type) => HlslMappedVectorTypes.Contains(type) ||
type == typeof(Vector2) ||
type == typeof(Vector3) ||
type == typeof(Vector4);
/// <summary>
/// Checks whether or not the input type is a known matrix type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL matrix type.</returns>
[Pure]
public static bool IsKnownMatrixType(Type type) => HlslMappedMatrixTypes.Contains(type);
/// <summary>
/// Checks whether or not the input type is a known buffer type.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known buffer type.</returns>
[Pure]
public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) ||
IsReadOnlyResourceType(type) ||
IsReadWriteResourceType(type);
/// <summary>
/// Checks whether or not the input type is a <see cref="ConstantBuffer{T}"/> value.
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a <see cref="ConstantBuffer{T}"/> instance.</returns>
[Pure]
public static bool IsConstantBufferType(Type type) => type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>);
/// <summary>
/// Checks whether or not the input type is a known readonly resource type (buffer or texture).
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is a readonly resource type.</returns>
[Pure]
public static bool IsReadOnlyResourceType(Type type)
{
if (!type.IsGenericType) return false;
Type genericType = type.GetGenericTypeDefinition();
return
genericType == typeof(ReadOnlyBuffer<>) ||
genericType == typeof(ReadOnlyTexture2D<>) ||
genericType == typeof(ReadOnlyTexture2D<,>) ||
genericType == typeof(ReadOnlyTexture3D<>) ||
genericType == typeof(ReadOnlyTexture3D<,>) ||
genericType == typeof(IReadOnlyTexture2D<>) ||
genericType == typeof(IReadOnlyTexture3D<>);
}
/// <summary>
/// Checks whether or not the input type is a known writeable resource type (buffer or texture).
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check.</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is a writeable resource type.</returns>
[Pure]
public static bool IsReadWriteResourceType(Type type)
{
if (!type.IsGenericType) return false;
Type genericType = type.GetGenericTypeDefinition();
return
genericType == typeof(ReadWriteBuffer<>) ||
genericType == typeof(ReadWriteTexture2D<>) ||
genericType == typeof(ReadWriteTexture2D<,>) ||
genericType == typeof(ReadWriteTexture3D<>) ||
genericType == typeof(ReadWriteTexture3D<,>) ||
genericType == typeof(IReadWriteTexture2D<>) ||
genericType == typeof(IReadWriteTexture3D<>); ;
}
}
}
-288
ファイルの表示
@@ -1,288 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
#pragma warning disable CS0419, CS0618, CS8618
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader<T> : IShaderLoader
where T : struct, IShader<T>
{
/// <summary>
/// The associated <see cref="IComputeShaderSourceAttribute"/> instance for the current shader type.
/// </summary>
private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType<T>();
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
/// <remarks>
/// This starts at 1 as there's always an initial constant buffer before user-defined ones, containing
/// the captured scalar and vector values as well as the iteration ranges for the shader dispatch.
/// </remarks>
private uint constantBuffersCount = 1;
/// <summary>
/// The number of readonly buffers to define in the shader.
/// </summary>
private uint readOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader.
/// </summary>
private uint readWriteBuffersCount;
/// <summary>
/// The number of samplers to define in the shader.
/// </summary>
private uint samplersCount;
/// <summary>
/// The array of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1;
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="Renderer.Models.HlslResourceInfo"/> items for the shader fields.
/// </summary>
private readonly List<HlslResourceInfo> hlslResourceInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected methods for the shader.
/// </summary>
private readonly List<string> methodsInfo = new();
/// <summary>
/// The <see cref="Dictionary{TKey,TValue}"/> with the discovered define declarations for the shader.
/// </summary>
private readonly Dictionary<string, string> definesInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected declared types for the shader.
/// </summary>
private readonly List<string> declaredTypes = new();
/// <summary>
/// Creates a new <see cref="ShaderLoader{T}"/> instance.
/// </summary>
private ShaderLoader()
{
}
/// <summary>
/// Gets the number of 32 bit constants in the root signature for the shader.
/// </summary>
public int D3D12Root32BitConstantsCount { get; private set; }
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => this.d3D12DescriptorRanges1;
}
/// <inheritdoc/>
public string EntryPoint { get; private set; }
/// <inheritdoc/>
public bool IsComputeShader { get; private set; }
/// <summary>
/// Gets whether or not the current shader requires access to a static sampler.
/// </summary>
public bool IsStaticSamplerUsed { get; private set; }
/// <inheritdoc/>
public IReadOnlyList<HlslResourceInfo> HlslResourceInfo => this.hlslResourceInfo;
/// <inheritdoc/>
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> ForwardDeclarations { get; private set; }
/// <inheritdoc/>
public IReadOnlyCollection<string> MethodsInfo => this.methodsInfo;
/// <inheritdoc/>
public IReadOnlyDictionary<string, string> DefinesInfo => this.definesInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string TypeDeclaration, string? Assignment)> StaticFields { get; private set; }
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; private set; }
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer.
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader.</param>
/// <returns>A new <see cref="ShaderLoader{T}"/> instance representing the input shader.</returns>
[Pure]
public static ShaderLoader<T> Load(in T shader)
{
ShaderLoader<T> @this = new();
@this.LoadMethodMetadata();
// Reading members through reflection requires an object parameter, so here we're just boxing
// the input shader once to avoid allocating it multiple times while processing the shader.
@this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader);
return @this;
}
/// <summary>
/// Loads the metadata info for the current shader.
/// </summary>
private void LoadMethodMetadata()
{
ForwardDeclarations = Attribute.ForwardDeclarations;
EntryPoint = Attribute.ExecuteMethod;
StaticFields = Attribute.StaticFields;
SharedBuffers = Attribute.SharedBuffers;
this.declaredTypes.AddRange(Attribute.Types);
this.methodsInfo.AddRange(Attribute.Methods);
foreach (var pair in Attribute.Defines)
{
this.definesInfo.Add(pair.Key, pair.Value);
}
// Extract the computed count of 32 bit root constants to load
D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)typeof(T).GetMethod(nameof(IShader<T>.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count;
}
/// <summary>
/// Loads the fields info for the current shader being loaded.
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader.</param>
/// <returns>The array of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.</returns>
private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
// Add the implicit texture descriptor if the shader is a pixel shader
foreach (Type interfaceType in typeof(T).GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount));
(string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value;
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
break;
}
}
// Set the current shader type
IsComputeShader = d3D12DescriptorRanges1.Count == 0;
// Ensure the shader has a valid number of captured resources
if (shaderFields.Count == 0 && d3D12DescriptorRanges1.Count == 0)
{
ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field");
}
// Add the implicit sampler descriptor if necessary
if (Attribute.ImplicitSamplerField is not null)
{
(string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value;
this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++));
IsStaticSamplerUsed = true;
}
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo, d3D12DescriptorRanges1);
}
return d3D12DescriptorRanges1.ToArray();
}
/// <summary>
/// Loads a specified <see cref="FieldInfo"/> and adds it to the shader model.
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader.</param>
/// <param name="fieldInfo">The target <see cref="FieldInfo"/> to load.</param>
/// <param name="d3D12DescriptorRanges1">The list of discovered <see cref="D3D12_DESCRIPTOR_RANGE1"/> values.</param>
private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1)
{
Type fieldType = fieldInfo.FieldType;
(string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name];
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount));
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.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.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
}
else if (fieldInfo.GetValue(shader) is Delegate func)
{
Guard.IsTrue(func.Method.IsStatic, fieldInfo.Name, "Captured delegates must be pointing to static methods");
// Captured static delegates with a return type
var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func);
this.declaredTypes.AddRange(methodSource.Types);
this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName));
this.methodsInfo.AddRange(methodSource.Methods);
foreach (var pair in methodSource.Constants)
{
this.definesInfo[pair.Key] = pair.Value;
}
}
else
{
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
}
}
}
}