using System;
using System.Diagnostics.Contracts;
using DotNetDxc;
using Vortice.DirectX.Direct3D12;
namespace ComputeSharp.Shaders.Translation
{
///
/// A that uses the APIs to compile compute shaders
///
internal sealed class ShaderCompiler
{
///
/// Gets the singleton instance to use
///
public static ShaderCompiler Instance { get; } = new ShaderCompiler();
///
/// The instance to use to create new HLSL shaders
///
private readonly IDxcCompiler Compiler;
///
/// The instance to use to create the bytecode for HLSL sources
///
private readonly IDxcLibrary Library;
///
/// Creates a new instance
///
private ShaderCompiler()
{
HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn();
Compiler = HlslDxcLib.CreateDxcCompiler();
Library = HlslDxcLib.CreateDxcLibrary();
}
///
/// Compiles a new HLSL shader from the input source code
///
/// The HLSL source code to compile
/// The bytecode for the compiled shader
[Pure]
public ShaderBytecode CompileShader(string source)
{
const uint CP_UTF16 = 1200;
IDxcBlobEncoding sourceBlob = Library.CreateBlobWithEncodingOnHeapCopy(source, (uint)(source.Length * 2), CP_UTF16);
IDxcOperationResult result = Compiler.Compile(sourceBlob, "", "CSMain", "cs_6_1", new[] { "-Zpr" }, 1, null, 0, Library.CreateIncludeHandler());
// Get the compiled bytecode in case of success
if (result.GetStatus() == 0)
{
IDxcBlob blob = result.GetResult();
byte[] bytecode = GetBytesFromBlob(blob);
return bytecode;
}
// Compile error
string resultText = GetStringFromBlob(Library, result.GetErrors());
throw new Exception(resultText);
}
///
/// Reads the buffer content from an input instance
///
/// The input instance to read data from
/// The read bytes buffer, as an array
[Pure]
private static unsafe byte[] GetBytesFromBlob(IDxcBlob blob)
{
byte* pMem = (byte*)blob.GetBufferPointer();
uint size = blob.GetBufferSize();
byte[] result = new byte[size];
new Span(pMem, (int)size).CopyTo(result.AsSpan());
return result;
}
///
/// Reads a value from an input instance
///
/// The source to use to load the data
/// The input instance to read data from
/// The resulting read from the input data buffer
[Pure]
private static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob)
{
blob = library.GetBlobAstUf16(blob);
return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2));
}
}
}