Skip to content

Shader compiler

What it does

RI consumes shader bytecode only. <RI/Helpers/ShaderCompiler.hpp> compiles HLSL at run time through the DXC library using RI's compile rule: it produces SPIR-V when RI is built for Vulkan, and DXIL when RI is built for D3D12. The same rule compiles the shaders for RI's tests at build time.

  • createShaderCompiler(dxcLibrary) loads a DXC shared library (libdxcompiler.so on Linux, dxcompiler.dll on Windows) at the path dxcLibrary, or loads the build's pinned DXC library when dxcLibrary is nullptr (the default). If the library cannot be loaded or initialized, it reports an ErrorCategory::eUnsupported error. Call destroyShaderCompiler when you are done with the compiler.
  • compileShader(compiler, source) compiles a ShaderSource containing the HLSL code, target profile (such as cs_6_6, vs_6_6, or lib_6_8), entry (defaulting to "main", omitted for lib_ profiles), name for diagnostic messages (defaulting to "shader.hlsl"), includeDirectories, and defines (NAME or NAME=VALUE). RI's shader include directory (which provides <equine/root.hlsli>) is always added to the include search path.
  • compileShader returns a CompiledShader with bytecode (empty if compilation fails) and messages (DXC's warnings and errors, or "DXC could not run" if DXC fails to start).

Each ShaderCompiler is not thread-safe and must be used by only one thread at a time. To compile shaders in parallel, create one ShaderCompiler per thread; you can then also create pipelines on those threads (threads).

Example

    RI::Helpers::ShaderCompiler compiler = RI::Helpers::createShaderCompiler(); // the build's pinned DXC
    const char *code = R"(#include <equine/root.hlsli>
struct Root { uint slot; float value; };
EQ_ROOT_DATA(Root, root);
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
    RWStructuredBuffer<float> output = ResourceDescriptorHeap[root.slot];
    output[id.x] = root.value * SCALE;
})";
    const RI::Helpers::CompiledShader shader =
        RI::Helpers::compileShader(compiler, {.code = code, .profile = "cs_6_6", .defines = {"SCALE=2.0"}});
    if (shader.bytecode.empty()) {
        std::printf("%s", shader.messages.c_str());
        return 1;
    }
    RI::Pipeline pipeline = RI::createComputePipeline(device, {.shader = shader.bytecode});

How to roll your own

Call dxc or the DXC library with RI's arguments, as equine_add_shaders does in cmake/EquineDXC.cmake:

  • For both backends, pass -T <profile> -E main -HV 2021 -I <RI's shaders directory> (equine_add_shaders also passes -WX).
  • For Vulkan (SPIR-V), also pass -spirv -fspv-target-env=vulkan1.3 -fvk-use-dx-layout -fvk-bind-sampler-heap 0 1 -fvk-support-nonzero-base-vertex.
  • For D3D12 (DXIL), no extra arguments are required (equine_add_shaders adds -Qstrip_reflect -Qstrip_debug to prove RI does not need reflection). Library profiles (lib_*) compile to DXIL only and omit -E.