shader-compiler
Garnet Shader Compiler
Builds Slang shader programs for every Garnet renderer (Vulkan, Metal, OpenGL/GLES and Direct3D 12) from one source, and generates a typed Crystal module for each. Everything runs in process: slang.cr compiles, spirv-cross.cr translates, and spirv.cr checks the result. No external shader tools are needed.
Usage
Put a shaders.json beside your .slang files:
{
"namespace": "Garnet::Graphics::Shaders",
"crystal": "../src/garnet-graphics/shaders",
"programs": ["mesh3d.slang"],
"include": ["../../shared-shaders"]
}
Paths are relative to the directory holding shaders.json. Then build:
garnet shaders build graphics/shaders # writes artifacts and Crystal modules
garnet shaders build graphics/shaders --check # exits 3 if anything is stale
garnet shaders builds this shard's garnet-shaders tool on first use and rebuilds it when its sources change. The CLI itself stays free of native dependencies.
Imports resolve against the shaders.json directory, then include, then the shaders directory of every dependency of the project or shard that owns it, which the CLI passes as --include options. That is how a game's programs import garnet.lighting from the graphics shard without listing paths. Run the tool directly with --include PATH to add search paths yourself.
What a build produces
For each program NAME.slang:
| Output | Contents |
|---|---|
generated/NAME/ENTRY.spv |
SPIR-V 1.3 for Vulkan, with the entry point's own name |
generated/NAME/ENTRY.metal, ENTRY.ios.metal |
MSL 2.1 for macOS and iOS |
generated/NAME/ENTRY.glsl, ENTRY.essl |
GLSL 330 core and ESSL 300 |
generated/NAME/ENTRY.hlsl |
HLSL shader model 5.1 for Direct3D 12 |
generated/NAME/NAME.json |
Manifest: entry points, resources, GL block names, Direct3D registers and uniform layouts with Slang user attributes |
CRYSTAL/NAME.cr |
NAMESPACE::Name: the embedded artifacts and a typed packer per uniform block |
Commit the outputs, so people who use the shaders don't need the compiler. Outputs are deterministic and already formatted, and files a program no longer produces are removed.
Backends
Each program compiles to SPIR-V once per backend family, with every family macro defined: GARNET_VULKAN, GARNET_METAL and GARNET_GL are each 1 for its own family and 0 otherwise. Branch on them only for real platform differences, such as Vulkan's flipped clip-space Y. Entry points must be the same in every family.
Translation rules:
- Resources keep their SPIR-V binding numbers everywhere. Metal
buffer,textureandsamplerindices equal them. - GLSL 330 has no binding qualifiers and links stages by name, so names stand in for bindings: varyings are
garnet_varying<location>on both sides, uniform blocksgarnet_block<binding>(also listed inGL_BLOCKS) and combined samplersgarnet_sampler<binding>. A renderer binds each block to the same-numbered block binding and each sampler to the same-numbered texture unit, for any program. GL vertex stages remap depth to -1..1. - For GL,
NMin/NMax/NClampbecome plainmin/max/clamp. GLSL has no NaN-aware forms and would otherwise emulate them. - Matrices use column-major layout, matching GLSL:
mul(m, v)is GLSL'sm * v.
Direct3D 12 (HLSL)
SPIRV-Cross's HLSL backend translates the Metal family's SPIR-V, because Direct3D and Metal share every screen-space convention that the shaders branch on. As a result, GARNET_METAL is 1 in Direct3D shaders too.
| Convention | Direct3D 12 | What the build does |
|---|---|---|
| Clip-space y | Up, as on Metal and GL | Nothing: the Metal family has no Vulkan y flip (#if GARNET_VULKAN branches are off). |
| Clip-space depth | 0..1, as on Metal and Vulkan | Nothing: GL's -1..1 fix-up applies only to GLSL. |
| Framebuffer and texture rows | Row 0 at the top, as on Metal and Vulkan | Nothing. ddy points down the image (ddyUp negates it), and renderers pass the same row-direction flags (such as the flipY of garnet.screen) as on Metal. Readbacks return rows top-down, like Metal and Vulkan, so a renderer that reads pixels back flips nothing. |
SV_VertexID, SV_InstanceID |
Exclude BaseVertexLocation and StartInstanceLocation |
Shaders use SV_VulkanVertexID/SV_VulkanInstanceID, which become SV_VertexID/SV_InstanceID. SPIRV-Cross's base-vertex constant buffer is disabled, and a build fails if it appears. Renderers must draw with base vertex, start vertex and start instance 0, as the Vulkan renderer already does, so both APIs see the same IDs. |
| Textures and samplers | Separate objects | A combined Sampler2D at binding N becomes Texture2D NAME : register(tN) and SamplerState _NAME_sampler : register(sN). A separate Texture2D or SamplerState takes tN or sN. |
| Matrix packing | cbuffer registers |
Members keep their std140 offsets as packoffsets, and matrices stay column_major, so the bytes the generated packers write work unchanged. |
Shader model 5.1. D3DCompile (d3dcompiler_47.dll, which ships with Windows) compiles it to DXBC, so the renderer needs no DXC. 5.1 is the first model with register spaces.
Registers. Every resource keeps its SPIR-V binding as its register index and its descriptor set as its register space:
| Slang resource | SPIR-V | HLSL |
|---|---|---|
ConstantBuffer<T> |
set S, binding N | cbuffer … : register(bN, spaceS) (CBV) |
Texture2D |
set S, binding N | Texture2D … : register(tN, spaceS) (SRV) |
SamplerState |
set S, binding N | SamplerState … : register(sN, spaceS) (sampler) |
Sampler2D (combined) |
set S, binding N | tN and sN, both in spaceS |
Garnet's programs use set 0 only. No program uses push constants: the reflection accepts only descriptor bindings, so there are no root constants. The build fails if the HLSL declares a register that the reflection does not predict.
Reflection for root signatures. The manifest's hlsl object holds shader_model ("5_1"), entry_function ("main") and registers. Each register is {"name", "kind", "register", "index", "space"}, and kind is cbv, srv or sampler, which matches a D3D12_DESCRIPTOR_RANGE_TYPE. The generated module exposes the same list as HLSL_REGISTERS, an array of {name, kind, index, space} tuples such as {"draw", :cbv, 2, 0}. The list covers the whole program, so a root signature built from it serves every entry point.
Entry points and signatures.
- Every entry function is named
main. Compile vertex stages asvs_5_1and fragment stages asps_5_1. - Vertex inputs use the semantic
TEXCOORDwith the SPIR-V location as the semantic index. AD3D12_INPUT_ELEMENT_DESCfor location L is{"TEXCOORD", L, …}. - Varyings are
TEXCOORDLas well, followed bySV_Position. - Direct3D links a pixel shader to a vertex shader by register as well as by semantic, and
D3DCompileassigns registers in declaration order. SPIR-V keeps only the varyings a stage reads, so the build pads each vertex output and fragment input signature to declare every varying of the entry point's Slang interface, in location order. Unused varyings are namedgarnet_link<L>, and unwritten vertex outputs are zeroed. The fragment's pixel-only system values, such asSV_IsFrontFace, come last. - A fragment stage must therefore take the same varyings struct that its vertex stage returns, as the 3D materials do with
garnet.mesh3d'sVaryings.
Checks
A build fails, naming the program, entry point and backend, when:
- a varying lacks a location;
- a stage uses
BaseInstance,BaseVertexorDrawIndex, which need Vulkan draw parameters (useSV_VulkanInstanceID); - HLSL declares a register the reflection does not predict, needs base-vertex constants, or has a varying that cannot be padded (only scalar and vector varyings link);
- any backend's SPIR-V lays out a uniform block differently from Slang's reflection, which would break the shared packer;
- a uniform field is not a scalar, vector, square matrix or array of those;
- Slang reports an error. Its diagnostics are passed through.
The generated module
block = Garnet::Graphics::Shaders::Mesh3D::Draw3D.new
block.view_projection = frame.view_projection # Mat4 or any Indexable(Float32), column-major
block.set_models(0, transform) # array element, bounds-checked
block.tint = StaticArray[1_f32, 1_f32, 1_f32, 1_f32]
upload(block.bytes) # std140, Draw3D::SIZE bytes
entry = Garnet::Graphics::Shaders::Mesh3D::MESH3D_FRAGMENT
entry.spirv; entry.metal; entry.metal_ios; entry.metal_function; entry.glsl; entry.essl; entry.hlsl
Garnet::Graphics::Shaders::Mesh3D::BINDINGS # => {"base" => 0, "draw" => 2, ...}
Garnet::Graphics::Shaders::Mesh3D::HLSL_REGISTERS # => [{"base", :srv, 0, 0}, {"base", :sampler, 0, 0}, ...]
Garnet::Graphics::Shaders::Mesh3D::Draw3D::FIELDS.first.attributes # Slang user attributes
Setters check component counts, matrix sizes and array bounds. FIELDS records each field's type, offset, array length and attributes such as [Range(0, 4)] or [Color], for editors and tools.
Development
garnet env --for shader-compiler/spec/builder_spec.cr # prints CRYSTAL_PATH
crystal spec
crystal run src/main.cr -- build spec/fixtures/shaders # after changing the fixture or the generator
crystal tool format --check src spec
ameba
On Windows, CI also compiles the fixture's HLSL with the Windows SDK's fxc.exe (-T vs_5_1/ps_5_1 -E main).
spec/fixtures/shaders/surface.slang covers every field kind the generator supports. Its committed output is checked for staleness and loaded at run time by the packer specs.
License
MIT. See LICENSE.
shader-compiler
- 0
- 0
- 0
- 0
- 3
- about 1 hour ago
- December 1, 2026
MIT License
Thu, 03 Dec 2026 12:16:33 GMT