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.soon Linux,dxcompiler.dllon Windows) at the pathdxcLibrary, or loads the build's pinned DXC library whendxcLibraryisnullptr(the default). If the library cannot be loaded or initialized, it reports anErrorCategory::eUnsupportederror. CalldestroyShaderCompilerwhen you are done with the compiler.compileShader(compiler, source)compiles aShaderSourcecontaining the HLSLcode, targetprofile(such ascs_6_6,vs_6_6, orlib_6_8),entry(defaulting to"main", omitted forlib_profiles),namefor diagnostic messages (defaulting to"shader.hlsl"),includeDirectories, anddefines(NAMEorNAME=VALUE). RI's shader include directory (which provides<equine/root.hlsli>) is always added to the include search path.compileShaderreturns aCompiledShaderwithbytecode(empty if compilation fails) andmessages(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_shadersalso 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_shadersadds-Qstrip_reflect -Qstrip_debugto prove RI does not need reflection). Library profiles (lib_*) compile to DXIL only and omit-E.