using System; using System.Diagnostics.Contracts; using Vortice.DirectX.Direct3D12; using Vortice.Dxc; 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 the bytecode for HLSL sources /// private readonly IDxcLibrary Library = Dxc.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) { var result = DxcCompiler.Compile(DxcShaderStage.ComputeShader, source, "CSMain", string.Empty, new DxcCompilerOptions { ShaderModel = DxcShaderModel.Model6_1 }); // Get the compiled bytecode in case of success if (result.GetStatus() == 0) { IDxcBlob blob = result.GetResult(); byte[] bytecode = Dxc.GetBytesFromBlob(blob); return bytecode; } // Compile error string resultText = Dxc.GetStringFromBlob(Library, result.GetErrors()); throw new Exception(resultText); } } }