diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/D2D1ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/D2D1ShaderCompiler.cs new file mode 100644 index 00000000..f7b7bafd --- /dev/null +++ b/src/ComputeSharp.Dynamic/Shaders/Translation/D2D1ShaderCompiler.cs @@ -0,0 +1,258 @@ +using System; +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Exceptions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using DirectX = TerraFX.Interop.DirectX.DirectX2; +#endif + +#pragma warning disable IDE1006 + +namespace ComputeSharp.Shaders.Translation; + +/// +/// A that uses the FXC APIs to compile D2D1 pixel shaders. +/// +internal static unsafe class D2D1ShaderCompiler +{ + /// + /// Compiles a new HLSL shader from the input source code. + /// + /// The HLSL source code to compile. + /// Whether to enable linking support for the shader. + /// The bytecode for the compiled shader. + public static ComPtr Compile(ReadOnlySpan source, bool enableLinkingSupport) + { + // Compile the standalone D2D1 full shader + using ComPtr d3DBlobFullShader = CompileD2DFullShader(source); + + if (!enableLinkingSupport) + { + return d3DBlobFullShader.Move(); + } + + // Compile the export function and embed it as private data if requested + using ComPtr d3DBlobFunction = CompileD2DFunction(source); + using ComPtr d3DBlobLinked = EmbedD2DFunctionPrivateData(d3DBlobFullShader.Get(), d3DBlobFunction.Get()); + + return d3DBlobLinked.Move(); + } + + /// + /// Compiles a D2D1 pixel shader with D2D_FULL_SHADER. + /// + ///The HLSL source code to compile. + /// The bytecode for the compiled shader. + private static ComPtr CompileD2DFullShader(ReadOnlySpan source) + { + // Encode the HLSL source to ASCII + int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); + byte[] buffer = ArrayPool.Shared.Rent(maxLength); + int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); + + using ComPtr d3DBlobBytecode = default; + using ComPtr d3DBlobErrors = default; + + int hResult; + + fixed (byte* bufferPtr = buffer) + { + // Prepare the macros for full shader compilation: + // + // -D D2D_FULL_SHADER + // -D D2D_ENTRY=Execute + D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] + { + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_FULL_SHADER)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.NullTerminator)) + }, + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_ENTRY)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)) + }, + new() + }; + + // Compile the shader with -ps_5_0 -O3 -We + hResult = DirectX.D3DCompile( + pSrcData: bufferPtr, + SrcDataSize: (nuint)writtenBytes, + pSourceName: null, + pDefines: macros, + pInclude: null, + pEntrypoint: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)), + pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.ps_5_0)), + Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS, + Flags2: 0, + ppCode: d3DBlobBytecode.GetAddressOf(), + ppErrorMsgs: d3DBlobErrors.GetAddressOf()); + } + + ArrayPool.Shared.Return(buffer); + + // Throw if an error was retrieved, then also double check the HRESULT + if (d3DBlobErrors.Get() is not null) + { + ThrowHslsCompilationException(d3DBlobErrors.Get()); + } + + hResult.Assert(); + + return d3DBlobBytecode.Move(); + } + + /// + /// Compiles a D2D1 pixel shader with D2D_FUNCTION. + /// + ///The HLSL source code to compile. + /// The bytecode for the compiled shader. + private static ComPtr CompileD2DFunction(ReadOnlySpan source) + { + int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); + byte[] buffer = ArrayPool.Shared.Rent(maxLength); + int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); + + using ComPtr d3DBlobBytecode = default; + using ComPtr d3DBlobErrors = default; + + int hResult; + + fixed (byte* bufferPtr = buffer) + { + // Prepare the macros for full shader compilation: + // + // -D D2D_FUNCTION + // -D D2D_ENTRY=Execute + D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] + { + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_FUNCTION)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.NullTerminator)) + }, + new() + { + Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.D2D_ENTRY)), + Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.Execute)) + }, + new() + }; + + // Compile the shader with -lib_5_0 -O3 -We + hResult = DirectX.D3DCompile( + pSrcData: bufferPtr, + SrcDataSize: (nuint)writtenBytes, + pSourceName: null, + pDefines: macros, + pInclude: null, + pEntrypoint: null, + pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(ASCII.lib_5_0)), + Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS, + Flags2: 0, + ppCode: d3DBlobBytecode.GetAddressOf(), + ppErrorMsgs: d3DBlobErrors.GetAddressOf()); + } + + ArrayPool.Shared.Return(buffer); + + // Check for errors and double check like above + if (d3DBlobErrors.Get() is not null) + { + ThrowHslsCompilationException(d3DBlobErrors.Get()); + } + + hResult.Assert(); + + return d3DBlobBytecode.Move(); + } + + /// + /// Embeds the bytecode for an exported shader as private data into another shader bytecode. + /// + /// The bytecode produced by . + /// The bytecode produced by . + /// An instance with the combined data of and . + private static ComPtr EmbedD2DFunctionPrivateData(ID3DBlob* shaderBlob, ID3DBlob* exportBlob) + { + void* shaderPtr = shaderBlob->GetBufferPointer(); + nuint shaderSize = shaderBlob->GetBufferSize(); + + void* exportPtr = exportBlob->GetBufferPointer(); + nuint exportSize = exportBlob->GetBufferSize(); + + using ComPtr resultBlob = default; + + DirectX.D3DSetBlobPart( + pSrcData: shaderPtr, + SrcDataSize: shaderSize, + Part: D3D_BLOB_PART.D3D_BLOB_PRIVATE_DATA, + Flags: 0, + pPart: exportPtr, + PartSize: exportSize, + ppNewShader: resultBlob.GetAddressOf()).Assert(); + + return resultBlob.Move(); + } + + /// + /// Throws an exception when a shader compilation fails. + /// + /// The input (faulting) operation. + /// This method always throws and never actually returs. + [MethodImpl(MethodImplOptions.NoInlining)] + private static ComPtr ThrowHslsCompilationException(ID3DBlob* d3DOperationResult) + { + string message = new((sbyte*)d3DOperationResult->GetBufferPointer()); + + throw new HlslCompilationException(message); + } + + /// + /// A container for ASCII encoded, null-terminated constant strings. + /// + private static class ASCII + { + /// + /// Gets a with the "D2D_FUNCTION" ASCII text. + /// + public static ReadOnlySpan D2D_FUNCTION => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'F', (byte)'U', (byte)'N', (byte)'C', (byte)'T', (byte)'I', (byte)'O', (byte)'N', (byte)'\0' }; + + /// + /// Gets a with the "D2D_FULL_SHADER" ASCII text. + /// + public static ReadOnlySpan D2D_FULL_SHADER => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'F', (byte)'U', (byte)'L', (byte)'L', (byte)'_', (byte)'S', (byte)'H', (byte)'A', (byte)'D', (byte)'E', (byte)'R', (byte)'\0' }; + + /// + /// Gets a with the '\0' ASCII character. + /// + public static ReadOnlySpan NullTerminator => new[] { (byte)'\0' }; + + /// + /// Gets a with the "D2D_ENTRY" ASCII text. + /// + public static ReadOnlySpan D2D_ENTRY => new[] { (byte)'D', (byte)'2', (byte)'D', (byte)'_', (byte)'E', (byte)'N', (byte)'T', (byte)'R', (byte)'Y', (byte)'\0' }; + + /// + /// Gets a with the "Execute" ASCII text. + /// + public static ReadOnlySpan Execute => new[] { (byte)'E', (byte)'x', (byte)'e', (byte)'c', (byte)'u', (byte)'t', (byte)'e', (byte)'\0' }; + + /// + /// Gets a with the "lib_5_0" ASCII text. + /// + public static ReadOnlySpan lib_5_0 => new[] { (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' }; + + /// + /// Gets a with the "ps_5_0" ASCII text. + /// + public static ReadOnlySpan ps_5_0 => new[] { (byte)'p', (byte)'s', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' }; + } +} diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs index 31b529c9..817c071d 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Translation/ShaderCompiler.cs @@ -1,8 +1,5 @@ using System; -using System.Buffers; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; using TerraFX.Interop.DirectX; @@ -87,212 +84,6 @@ internal sealed unsafe partial class ShaderCompiler /// The HLSL source code to compile. /// The bytecode for the compiled shader. public ComPtr Compile(ReadOnlySpan source) - { - fixed (char* optimization = "-O3") - fixed (char* rowMajor = "-Zpr") - fixed (char* warningsAsErrors = "-Werror") - { - const string profile = "cs_6_0"; - const string entryPoint = nameof(IComputeShader.Execute); - - ReadOnlySpan arguments = stackalloc IntPtr[] { (IntPtr)optimization, (IntPtr)rowMajor, (IntPtr)warningsAsErrors }; - - return Compile(source, profile.AsSpan(), entryPoint.AsSpan(), arguments); - } - } - -#if NET6_0_OR_GREATER - public static ComPtr SetPrivateData(ID3DBlob* shaderBlob, ID3DBlob* exportBlob) - { - void* shaderPtr = shaderBlob->GetBufferPointer(); - nuint shaderSize = shaderBlob->GetBufferSize(); - - void* exportPtr = exportBlob->GetBufferPointer(); - nuint exportSize = exportBlob->GetBufferSize(); - - using ComPtr resultBlob = default; - - DirectX.D3DSetBlobPart( - pSrcData: shaderPtr, - SrcDataSize: shaderSize, - Part: D3D_BLOB_PART.D3D_BLOB_PRIVATE_DATA, - Flags: 0, - pPart: exportPtr, - PartSize: exportSize, - ppNewShader: resultBlob.GetAddressOf()).Assert(); - - return resultBlob.Move(); - } - - public static ComPtr CompilePixelShaderFunction(ReadOnlySpan source) - { - int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); - byte[] buffer = ArrayPool.Shared.Rent(maxLength); - int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); - - using ComPtr d3DBlobBytecode = default; - using ComPtr d3DBlobErrors = default; - - fixed (byte* bufferPtr = buffer) - { - // D2D_FUNCTION - ReadOnlySpan d2DFunctionName = new[] - { - (byte)'D', (byte)'2', (byte)'D', (byte)'_', - (byte)'F', (byte)'U', (byte)'N', (byte)'C', (byte)'T', (byte)'I', (byte)'O', (byte)'N', (byte)'\0' - }; - - // (Empty) - ReadOnlySpan d2DFunctionValue = new[] { (byte)'\0' }; - - // D2D_ENTRY - ReadOnlySpan d2DEntryName = new[] - { - (byte)'D', (byte)'2', (byte)'D', (byte)'_', - (byte)'E', (byte)'N', (byte)'T', (byte)'R', (byte)'Y', (byte)'\0' - }; - - // Execute - ReadOnlySpan d2DEntryValue = new[] - { - (byte)'E', (byte)'x', (byte)'e', (byte)'c', (byte)'u', (byte)'t', (byte)'e', (byte)'\0' - }; - - D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] - { - new() - { - Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DFunctionName)), - Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DFunctionValue)) - }, - new() - { - Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DEntryName)), - Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DEntryValue)) - }, - new() - }; - - // ps_4_0 - ReadOnlySpan shaderProfile = new[] - { - (byte)'l', (byte)'i', (byte)'b', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' - }; - - _ = DirectX.D3DCompile( - pSrcData: bufferPtr, - SrcDataSize: (nuint)writtenBytes, - pSourceName: null, - pDefines: macros, - pInclude: null, - pEntrypoint: null, - pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(shaderProfile)), - Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS, - Flags2: 0, - ppCode: d3DBlobBytecode.GetAddressOf(), - ppErrorMsgs: d3DBlobErrors.GetAddressOf()); - } - - ArrayPool.Shared.Return(buffer); - - if (d3DBlobErrors.Get() is not null) - { - ThrowHslsCompilationException(d3DBlobErrors.Get()); - } - - return d3DBlobBytecode.Move(); - } - - public static ComPtr CompilePixelShader(ReadOnlySpan source) - { - int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); - byte[] buffer = ArrayPool.Shared.Rent(maxLength); - int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); - - using ComPtr d3DBlobBytecode = default; - using ComPtr d3DBlobErrors = default; - - fixed (byte* bufferPtr = buffer) - { - // D2D_FULL_SHADER - ReadOnlySpan d2DFullShaderName = new[] - { - (byte)'D', (byte)'2', (byte)'D', (byte)'_', - (byte)'F', (byte)'U', (byte)'L', (byte)'L', (byte)'_', - (byte)'S', (byte)'H', (byte)'A', (byte)'D', (byte)'E', (byte)'R', (byte)'\0' - }; - - // (Empty) - ReadOnlySpan d2DFullShaderValue = new[] { (byte)'\0' }; - - // D2D_ENTRY - ReadOnlySpan d2DEntryName = new[] - { - (byte)'D', (byte)'2', (byte)'D', (byte)'_', - (byte)'E', (byte)'N', (byte)'T', (byte)'R', (byte)'Y', (byte)'\0' - }; - - // Execute - ReadOnlySpan d2DEntryValue = new[] - { - (byte)'E', (byte)'x', (byte)'e', (byte)'c', (byte)'u', (byte)'t', (byte)'e', (byte)'\0' - }; - - D3D_SHADER_MACRO* macros = stackalloc D3D_SHADER_MACRO[] - { - new() - { - Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DFullShaderName)), - Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DFullShaderValue)) - }, - new() - { - Name = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DEntryName)), - Definition = (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DEntryValue)) - }, - new() - }; - - // ps_5_0 - ReadOnlySpan shaderProfile = new[] - { - (byte)'p', (byte)'s', (byte)'_', (byte)'5', (byte)'_', (byte)'0', (byte)'\0' - }; - - DirectX.D3DCompile( - pSrcData: bufferPtr, - SrcDataSize: (nuint)writtenBytes, - pSourceName: null, - pDefines: macros, - pInclude: null, - pEntrypoint: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(d2DEntryValue)), - pTarget: (sbyte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(shaderProfile)), - Flags1: D3DCOMPILE.D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE.D3DCOMPILE_WARNINGS_ARE_ERRORS, - Flags2: 0, - ppCode: d3DBlobBytecode.GetAddressOf(), - ppErrorMsgs: d3DBlobErrors.GetAddressOf()).Assert(); - } - - ArrayPool.Shared.Return(buffer); - - if (d3DBlobErrors.Get() is not null) - { - ThrowHslsCompilationException(d3DBlobErrors.Get()); - } - - return d3DBlobBytecode.Move(); - } -#endif - - /// - /// Compiles a new HLSL shader from the input source code. - /// - /// The HLSL source code to compile. - /// The profile to use for compilation. - /// The entry point for the shader. - /// The arguments to use for compilation (each item must be a * to an individual argument). - /// The bytecode for the compiled shader. - public ComPtr Compile(ReadOnlySpan source, ReadOnlySpan profile, ReadOnlySpan entryPoint, ReadOnlySpan arguments) { using ComPtr dxcBlobEncoding = default; using ComPtr dxcOperationResult = default; @@ -308,19 +99,23 @@ internal sealed unsafe partial class ShaderCompiler dxcBlobEncoding.GetAddressOf()).Assert(); } - // Try to compile the new shader - fixed (char* shaderNamePtr = "") - fixed (char* entryPointPtr = entryPoint) - fixed (char* shaderProfilePtr = profile) - fixed (void* argumentsPtr = arguments) + // Try to compile the new compute shader + fixed (char* shaderName = "") + fixed (char* entryPoint = nameof(IComputeShader.Execute)) + fixed (char* shaderProfile = "cs_6_0") + fixed (char* optimization = "-O3") + fixed (char* rowMajor = "-Zpr") + fixed (char* warningsAsErrors = "-Werror") { + char** arguments = stackalloc char*[3] { optimization, rowMajor, warningsAsErrors }; + DxcCompiler.Get()->Compile( (IDxcBlob*)dxcBlobEncoding.Get(), - (ushort*)shaderNamePtr, - (ushort*)entryPointPtr, - (ushort*)shaderProfilePtr, - (ushort**)argumentsPtr, - (uint)arguments.Length, + (ushort*)shaderName, + (ushort*)entryPoint, + (ushort*)shaderProfile, + (ushort**)arguments, + 3, null, 0, DxcIncludeHandler.Get(), @@ -342,19 +137,6 @@ internal sealed unsafe partial class ShaderCompiler return ThrowHslsCompilationException(dxcOperationResult); } - /// - /// Throws an exception when a shader compilation fails. - /// - /// The input (faulting) operation. - /// This method always throws and never actually returs. - [MethodImpl(MethodImplOptions.NoInlining)] - private static ComPtr ThrowHslsCompilationException(ID3DBlob* d3DOperationResult) - { - string message = new((sbyte*)d3DOperationResult->GetBufferPointer()); - - throw new HlslCompilationException(message); - } - /// /// Throws an exception when a shader compilation fails. /// @@ -371,4 +153,4 @@ internal sealed unsafe partial class ShaderCompiler throw new HlslCompilationException(message); } -} +} \ No newline at end of file