From 880f501b55b0e84a5446e73726ff9904abefc384 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 00:53:44 +0100 Subject: [PATCH] Added .Shaders support for .NET Standard 2.0 --- .../ComputeSharp.Shaders.csproj | 2 +- .../Properties/Polyfills.cs | 37 +++++++++++ .../Renderer/HlslShaderRenderer.cs | 8 +-- .../Translation/Models/DispatchData.cs | 12 ++++ .../ShaderCompiler.LibraryLoading.cs | 66 +++++++++++++++++++ .../Translation/ShaderCompiler.cs | 65 +----------------- .../ShaderLoader{T}.DispatchData.cs | 6 +- .../Translation/ShaderLoader{T}.cs | 40 +++++------ 8 files changed, 146 insertions(+), 90 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Properties/Polyfills.cs create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index f06c8d8c..f2204371 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -1,7 +1,7 @@  - net5.0 + netstandard2.0;net5.0 diff --git a/src/ComputeSharp.Shaders/Properties/Polyfills.cs b/src/ComputeSharp.Shaders/Properties/Polyfills.cs new file mode 100644 index 00000000..227d8a84 --- /dev/null +++ b/src/ComputeSharp.Shaders/Properties/Polyfills.cs @@ -0,0 +1,37 @@ +#if NETSTANDARD2_0 + +using System.ComponentModel; + +namespace System.Runtime.CompilerServices +{ + /// + /// Reserved to be used by the compiler for tracking metadata. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + internal static class IsExternalInit + { + } +} + +namespace System.Reflection +{ + /// + /// Extensions for the type. + /// + internal static class MethodInfoExtensions + { + /// + /// Creates a delegate of type T from a given method. + /// + /// The type of delegate to create. + /// The input . + /// The delegate for this method. + public static T CreateDelegate(this MethodInfo method) + where T : Delegate + { + return (T)method.CreateDelegate(typeof(T)); + } + } +} + +#endif diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 72ee091e..a1a69c70 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -163,11 +163,11 @@ namespace ComputeSharp.Shaders.Renderer /// Appends the input sequence of characters to the current buffer. /// /// The input characters to write. - public void Append(ReadOnlySpan value) + public void Append(string value) { EnsureCapacity(value.Length); - value.CopyTo(this.array.AsSpan(this.index)); + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; } @@ -186,11 +186,11 @@ namespace ComputeSharp.Shaders.Renderer /// Appends the input sequence of characters to the current buffer, with a trailing new line. /// /// The input characters to write. - public void AppendLine(ReadOnlySpan value) + public void AppendLine(string value) { EnsureCapacity(value.Length + 1); - value.CopyTo(this.array.AsSpan(this.index)); + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index ca016a1c..fac76157 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -54,10 +54,16 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { +#if NET5_0 ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); +#else + Span span = this.resourcesArray.AsSpan(0, this.resourcesCount); + + return MemoryMarshal.Cast(span); +#endif } } @@ -69,11 +75,17 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { +#if NET5_0 ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); ref Int4 r1 = ref Unsafe.As(ref r0); int length = (int)((uint)this.variablesByteSize / (uint)sizeof(Int4)); return MemoryMarshal.CreateReadOnlySpan(ref r1, length); +#else + Span span = this.variablesArray.AsSpan(0, this.variablesByteSize); + + return MemoryMarshal.Cast(span); +#endif } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs new file mode 100644 index 00000000..9b860505 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs @@ -0,0 +1,66 @@ +#if NET5_0 +using System; +using System.IO; +using System.Runtime.InteropServices; +using FX = TerraFX.Interop.Windows; +#endif + +namespace ComputeSharp.Shaders.Translation +{ + /// + internal static unsafe partial class ShaderCompiler + { + /// + /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. + /// + private static void InitializeDxcLibrariesLoading() + { +#if NET5_0 + // Test whether the native libraries are present in the same folder of the executable + // (which is the case when the program was built with a runtime identifier), or whether + // they are in the "runtimes\win-x64\native" folder in the executable directory. + string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); + bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); + + // Register a custom library resolver for the two DXC libraries. We need to either manually load the two + // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is + // loaded correctly in case the program was executed with the host being in another directory. + // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. + FX.ResolveLibrary += (libraryName, assembly, searchPath) => + { + if (libraryName is not "dxcompiler") return IntPtr.Zero; + + if (isNuGetRuntimeLibrariesDirectoryPresent) + { + string + dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); + + // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path + if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) + { + return handle; + } + } + else + { + // Even when the two libraries are correctly copied next to the executable in use, we load them + // manually to ensure the operation is successful. This is to avoid failures in cases such as when + // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. + // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these + // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" + // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the + // native library we need, hence the runtime crash. Manually loading the library this way solves this. + if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && + NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) + { + return handle; + } + } + + return IntPtr.Zero; + }; +#endif + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 78c5b1ea..dedc20a0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -1,10 +1,6 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; -using System.IO; -using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; using TerraFX.Interop; @@ -15,7 +11,7 @@ namespace ComputeSharp.Shaders.Translation /// /// A that uses the DXC APIs to compile compute shaders. /// - internal static unsafe class ShaderCompiler + internal static unsafe partial class ShaderCompiler { /// /// The instance to use to create the bytecode for HLSL sources. @@ -56,64 +52,6 @@ namespace ComputeSharp.Shaders.Translation DxcIncludeHandler = dxcIncludeHandler.Move(); } - /// - /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. - /// - private static void InitializeDxcLibrariesLoading() - { - // Test whether the native libraries are present in the same folder of the executable - // (which is the case when the program was built with a runtime identifier), or whether - // they are in the "runtimes\win-x64\native" folder in the executable directory. - string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); - bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); - - // Register a custom library resolver for the two DXC libraries. We need to either manually load the two - // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is - // loaded correctly in case the program was executed with the host being in another directory. - // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. - FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, isNuGetRuntimeLibrariesDirectoryPresent); - } - - /// - /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. - /// This either loads the libraries from the NuGet directory, or just ensures that DXIL is always loaded. - /// - /// - private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool isNuGetRuntimeLibrariesDirectoryPresent) - { - if (libraryName is not "dxcompiler") return IntPtr.Zero; - - if (isNuGetRuntimeLibrariesDirectoryPresent) - { - string - dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), - dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); - - // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path - if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) - { - return handle; - } - } - else - { - // Even when the two libraries are correctly copied next to the executable in use, we load them - // manually to ensure the operation is successful. This is to avoid failures in cases such as when - // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. - // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these - // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" - // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the - // native library we need, hence the runtime crash. Manually loading the library this way solves this. - if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && - NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) - { - return handle; - } - } - - return IntPtr.Zero; - } - /// /// Compiles a new HLSL shader from the input source code. /// @@ -175,7 +113,6 @@ namespace ComputeSharp.Shaders.Translation /// /// The input (faulting) operation. /// This method always throws and never actually returs. - [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] private static ComPtr ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult) { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index 270c40e1..76fe2554 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -4,10 +4,14 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Graphics; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; +#if NET5_0 +using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; +#else +using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; +#endif namespace ComputeSharp.Shaders.Translation { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 92ee855b..11ac00bd 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; -using System.Runtime.InteropServices; using ComputeSharp.__Internals; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models; @@ -43,9 +42,9 @@ namespace ComputeSharp.Shaders.Translation private uint readWriteBuffersCount; /// - /// The of items that are required to load the captured values. + /// The array of items that are required to load the captured values. /// - private readonly List d3D12DescriptorRanges1 = new(); + private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1; /// /// The with the items for the shader fields. @@ -79,7 +78,7 @@ namespace ComputeSharp.Shaders.Translation /// public ReadOnlySpan D3D12DescriptorRanges1 { - get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1); + get => this.d3D12DescriptorRanges1; } /// @@ -107,12 +106,10 @@ namespace ComputeSharp.Shaders.Translation { ShaderLoader @this = new(); - // Reading members through reflection requires an object parameter, - // so here we're just boxing the input shader once to avoid allocating - // it multiple times in the managed heap while processing the shader. - object box = shader; + // 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); - @this.LoadFieldsInfo(box); @this.LoadMethodMetadata(); @this.InitializeDispatchDataLoader(); @@ -123,7 +120,8 @@ namespace ComputeSharp.Shaders.Translation /// Loads the fields info for the current shader being loaded. /// /// The boxed instance to use to build the shader. - private void LoadFieldsInfo(object 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 | @@ -135,51 +133,53 @@ namespace ComputeSharp.Shaders.Translation ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); } + List d3D12DescriptorRanges1 = new(); + // Descriptor for the buffer for captured scalar/vector variables D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); + d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { - LoadFieldInfo(shader, fieldInfo); + 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. - private void LoadFieldInfo(object shader, FieldInfo fieldInfo) + /// 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)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); this.totalResourceCount++;