diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 3e2dcc6f..52e8f25f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -14,8 +14,6 @@ - - @@ -25,7 +23,6 @@ - diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs deleted file mode 100644 index 3277c05b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp.__Internals -{ - /// - /// An attribute that contains info on the number of 32 bit constants for a given shader. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [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 - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The number of 32 bit constants for the annotated method. - public ComputeRoot32BitConstantsAttribute(int count) - { - Count = count; - } - - /// - /// Gets the number of 32 bit constants for the annotated method. - /// - internal int Count { get; } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs deleted file mode 100644 index d33a491b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ /dev/null @@ -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 -{ - /// - /// An attribute that contains info on a processed compute shader that can be executed. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [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 - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The type of the current shader. - /// The collection of custom types. - /// The implicit texture field info, if present. - /// The implicit texture sampler field info, if present. - /// The mapped collection of shader fields. - /// The forward declarations for static methods. - /// The source code for the method. - /// The collection of processed methods. - /// The collection of discovered defines. - /// The collection of discovered static fields. - /// The collection of group shared buffers. - 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().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); - ForwardDeclarations = forwardDeclarations; - ExecuteMethod = executeMethod; - Methods = methods; - Defines = defines.Cast().ToDictionary(static c => c[0], static c => c[1]); - StaticFields = staticFields.Cast().ToDictionary(static arg => arg[0]!, static arg => (arg[1]!, arg[2])); - SharedBuffers = sharedBuffers.Cast().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2])); - } - - /// - /// Gets the type of the current shader. - /// - internal Type ShaderType { get; } - - /// - /// Gets the collection of processed custom types. - /// - internal IReadOnlyCollection Types { get; } - - /// - /// Gets the mapping for the implicit texture field, if the shader is a pixel shader. - /// - internal (string Name, string Type)? ImplicitTextureField { get; } - - /// - /// Gets the mapping for the implicit sampler field, if necessary. - /// - internal (string Name, string Type)? ImplicitSamplerField { get; } - - /// - /// Gets the mapping of field names. - /// - internal IReadOnlyDictionary Fields { get; } - - /// - /// The forward declarations for static methods. - /// - internal IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the source code for the method. - /// - internal string ExecuteMethod { get; } - - /// - /// Gets the collection of processed methods. - /// - internal IReadOnlyCollection Methods { get; } - - /// - /// Gets the collection of discovered define declarations. - /// - internal IReadOnlyDictionary Defines { get; } - - /// - /// Gets the collection of discovered static fields. - /// - internal IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of discovered shared buffers. - /// - internal IReadOnlyDictionary SharedBuffers { get; } - - /// - /// Gets the associated instance for a specified type. - /// - /// The shader type to get the attribute for. - /// The associated instance for type . - [Pure] - internal static IComputeShaderSourceAttribute GetForType() - { - IEnumerable attributes = typeof(T).Assembly.GetCustomAttributes(); - IComputeShaderSourceAttribute? attribute = attributes.SingleOrDefault(static attribute => attribute.ShaderType == typeof(T)); - - if (attribute is null) - { - MissingShaderMetadataException.Throw(); - } - - return attribute!; - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs b/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs deleted file mode 100644 index c4b9f7eb..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; - -namespace ComputeSharp.Exceptions -{ - /// - /// A custom type that indicates when metadata is missing for a given shader. - /// - public sealed class MissingShaderMetadataException : Exception - { - /// - /// Creates a new instance. - /// - /// The error message to include in the exception.. - private MissingShaderMetadataException(string error) - : base(error) - { - } - - /// - /// Gets a formatted exception message for a given error. - /// - /// The type of shader that was failed to be loaded. - /// A new instance with a formatted error message. - [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()); - } - - /// - /// Throws a new for a given delegate. - /// - internal static void Throw() - { - throw Create(typeof(T)); - } - } -} diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index cdc099c0..332654f8 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -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(in T shader, out ShaderInfo shaderInfo) where T : struct, IShader { - ShaderLoader shaderLoader = ShaderLoader.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 dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan); - using ComPtr dxcUtils = default; + Guid dxcLibraryClsid = FX.CLSID_DxcLibrary; FX.DxcCreateInstance(&dxcLibraryClsid, FX.__uuidof(), dxcUtils.GetVoidAddressOf()).Assert(); diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs deleted file mode 100644 index b0d797c3..00000000 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Diagnostics.Contracts; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Renderer.Models; -using ComputeSharp.Shaders.Translation; - -namespace ComputeSharp.Shaders.Renderer -{ - /// - /// A type that renders an HLSL template from the previously loaded shader data. - /// - internal static class HlslShaderRenderer - { - /// - /// Renders a new HLSL shader source with the given parameters. - /// - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance with the shader information. - /// The source code for the new HLSL shader. - [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; - } - } -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs deleted file mode 100644 index baf1f12c..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -#pragma warning disable CS1572, CS1573 - -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - internal record CapturedFieldInfo(string FieldType, string FieldName); -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs deleted file mode 100644 index af71a082..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader resource field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - /// The register index to bind the resource to. - internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex) - : CapturedFieldInfo(FieldType, FieldName) - { - /// - /// A model that represents a captured constant buffer in a shader. - /// - /// - public sealed record Constant(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured readonly typed resource in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured writeable buffer in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured sampler in a shader. - /// This resource type doesn't have a mapping to a public API. - /// - /// - public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - } -} diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs deleted file mode 100644 index ccbdc33f..00000000 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using ComputeSharp.Shaders.Renderer.Models; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of any type. - /// - internal interface IShaderLoader - { - /// - /// Gets the generated source code for the method in the current shader. - /// - string EntryPoint { get; } - - /// - /// Gets whether or not the current shader is a compute shader (and not a pixel shader). - /// - bool IsComputeShader { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList HlslResourceInfo { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList FieldsInfo { get; } - - /// - /// Gets the forward declarations for static methods. - /// - IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the collection of methods to be used in the shader. - /// - IReadOnlyCollection MethodsInfo { get; } - - /// - /// Gets the collection of define declarations to be added to the shader. - /// - IReadOnlyDictionary DefinesInfo { get; } - - /// - /// Gets the collection of discovered static fields. - /// - IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of declared types for the shader. - /// - IReadOnlyCollection DeclaredTypes { get; } - - /// - /// Gets the collection of discovered group shared buffers. - /// - IReadOnlyDictionary SharedBuffers { get; } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs deleted file mode 100644 index 90aae996..00000000 --- a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Numerics; - -namespace ComputeSharp.Shaders.Mappings -{ - /// - /// A that contains and maps known HLSL type names to common .NET types. - /// - internal static class HlslKnownTypes - { - /// - /// The set of HLSL vector types. - /// - private static HashSet 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) - }); - - /// - /// The set of HLSL matrix types. - /// - private static HashSet 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) - }); - - /// - /// Checks whether or not the input type is a known scalar type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL scalar type. - [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); - - /// - /// Checks whether or not the input type is a known vector type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL vector type. - [Pure] - public static bool IsKnownVectorType(Type type) => HlslMappedVectorTypes.Contains(type) || - type == typeof(Vector2) || - type == typeof(Vector3) || - type == typeof(Vector4); - - /// - /// Checks whether or not the input type is a known matrix type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL matrix type. - [Pure] - public static bool IsKnownMatrixType(Type type) => HlslMappedMatrixTypes.Contains(type); - - /// - /// Checks whether or not the input type is a known buffer type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known buffer type. - [Pure] - public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || - IsReadOnlyResourceType(type) || - IsReadWriteResourceType(type); - - /// - /// Checks whether or not the input type is a value. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a instance. - [Pure] - public static bool IsConstantBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>); - - /// - /// Checks whether or not the input type is a known readonly resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a readonly resource type. - [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<>); - } - - /// - /// Checks whether or not the input type is a known writeable resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a writeable resource type. - [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<>); ; - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs deleted file mode 100644 index 51af97ba..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ /dev/null @@ -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 -{ - /// - /// A responsible for loading and processing shaders of a given type. - /// - /// The type of compute shader currently in use. - internal sealed partial class ShaderLoader : IShaderLoader - where T : struct, IShader - { - /// - /// The associated instance for the current shader type. - /// - private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); - - /// - /// The number of constant buffers to define in the shader. - /// - /// - /// 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. - /// - private uint constantBuffersCount = 1; - - /// - /// The number of readonly buffers to define in the shader. - /// - private uint readOnlyBuffersCount; - - /// - /// The number of read write buffers to define in the shader. - /// - private uint readWriteBuffersCount; - - /// - /// The number of samplers to define in the shader. - /// - private uint samplersCount; - - /// - /// The array of items that are required to load the captured values. - /// - private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1; - - /// - /// The with the items for the shader fields. - /// - private readonly List hlslResourceInfo = new(); - - /// - /// The with the items for the shader fields. - /// - private readonly List fieldsInfo = new(); - - /// - /// The with the collected methods for the shader. - /// - private readonly List methodsInfo = new(); - - /// - /// The with the discovered define declarations for the shader. - /// - private readonly Dictionary definesInfo = new(); - - /// - /// The with the collected declared types for the shader. - /// - private readonly List declaredTypes = new(); - - /// - /// Creates a new instance. - /// - private ShaderLoader() - { - } - - /// - /// Gets the number of 32 bit constants in the root signature for the shader. - /// - public int D3D12Root32BitConstantsCount { get; private set; } - - /// - /// Gets a with the loaded items for the shader. - /// - public ReadOnlySpan D3D12DescriptorRanges1 - { - get => this.d3D12DescriptorRanges1; - } - - /// - public string EntryPoint { get; private set; } - - /// - public bool IsComputeShader { get; private set; } - - /// - /// Gets whether or not the current shader requires access to a static sampler. - /// - public bool IsStaticSamplerUsed { get; private set; } - - /// - public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; - - /// - public IReadOnlyList FieldsInfo => this.fieldsInfo; - - /// - public IReadOnlyCollection ForwardDeclarations { get; private set; } - - /// - public IReadOnlyCollection MethodsInfo => this.methodsInfo; - - /// - public IReadOnlyDictionary DefinesInfo => this.definesInfo; - - /// - public IReadOnlyCollection DeclaredTypes => this.declaredTypes; - - /// - public IReadOnlyDictionary StaticFields { get; private set; } - - /// - public IReadOnlyDictionary SharedBuffers { get; private set; } - - /// - /// Loads and processes an input shadeer. - /// - /// The instance to use to build the shader. - /// A new instance representing the input shader. - [Pure] - public static ShaderLoader Load(in T shader) - { - ShaderLoader @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; - } - - /// - /// Loads the metadata info for the current shader. - /// - 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.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; - } - - /// - /// Loads the fields info for the current shader being loaded. - /// - /// The boxed instance to use to build the shader. - /// The array of items that are required to load the captured values. - private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader) - { - IReadOnlyList shaderFields = typeof(T).GetFields( - BindingFlags.Instance | - BindingFlags.Public | - BindingFlags.NonPublic).ToArray(); - - List 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(); - } - - /// - /// Loads a specified and adds it to the shader model. - /// - /// The boxed instance to use to build the shader. - /// The target to load. - /// The list of discovered values. - private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List 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)); - } - } - } -}