d3d12.cr
d3d12.cr
Crystal bindings for Direct3D 12, DXGI 1.4+ and the HLSL compiler (D3DCompile), with idiomatic wrappers. It is the low-level layer under Garnet's Direct3D 12 renderer, in the spirit of vulkan.cr and metal.cr.
Installation
dependencies:
d3d12:
github: garnet-engine/d3d12.cr
branch: main
Windows 10 or 11 (x64) with the MSVC toolchain that Crystal uses (Visual Studio 2022 Build Tools with the C++ workload and a Windows SDK). The shard links d3d12.lib, dxgi.lib and d3dcompiler.lib from the Windows SDK; the matching DLLs (d3d12.dll, dxgi.dll, d3dcompiler_47.dll) ship with Windows, so nothing has to be copied next to the executable.
Other platforms
Direct3D 12 exists only on Windows. On macOS and Linux the declarations and wrappers still compile, so dependent shards can be type-checked anywhere (crystal build --no-codegen, or --cross-compile --target x86_64-pc-windows-msvc), but no library is linked and nothing can run. The GPU specs are guarded with {% if flag?(:win32) %}; the structure layout and vtable specs run everywhere.
Usage
require "d3d12"
factory = D3D12::Factory.create
adapter = factory.default_adapter # WARP when GARNET_D3D12_WARP=1 or no hardware adapter
device = D3D12::Device.create(adapter)
queue = device.create_command_queue
allocator = device.create_command_allocator
list = device.create_command_list(allocator)
fence = device.create_fence
format = D3D12::Format::R8G8B8A8Unorm
target = device.create_texture_2d(256, 256, format,
flags: D3D12::ResourceFlags::AllowRenderTarget,
initial_state: D3D12::ResourceStates::RenderTarget,
clear_value: D3D12.clear_color(format, 0, 0, 0, 1))
rtvs = device.create_descriptor_heap(D3D12::DescriptorHeapType::Rtv, 1)
device.create_render_target_view(target, rtvs.cpu_handle(0))
list.clear_render_target_view(rtvs.cpu_handle(0), {0.1_f32, 0.2_f32, 0.3_f32, 1.0_f32})
list.close
queue.execute(list)
queue.signal(fence, 1_u64)
fence.wait(1_u64)
Shaders and pipelines
vs = D3D12::Compiler.compile_bytes(source, "vs_main", "vs_5_1")
ps = D3D12::Compiler.compile_bytes(source, "ps_main", "ps_5_1")
root = device.create_root_signature(D3D12::RootSignatureDesc.new(
[D3D12::RootParameter.constants(4, register: 0),
D3D12::RootParameter.table([D3D12::DescriptorRange.new(D3D12::DescriptorRangeType::Srv, 1, 0)], D3D12::ShaderVisibility::Pixel)],
[D3D12.static_sampler(0)]))
desc = D3D12::GraphicsPipelineDesc.new(root, vs, ps)
desc.input_layout = [D3D12::InputElement.new("POSITION", D3D12::Format::R32G32Float, 0_u32)]
desc.rasterizer = D3D12.rasterizer_desc(D3D12::FillMode::Wireframe)
desc.blend = D3D12.blend_desc(D3D12.premultiplied_blend_target)
desc.depth_stencil = D3D12.depth_stencil_desc(depth: true)
desc.depth_stencil_format = D3D12::Format::D32Float
pipeline = device.create_graphics_pipeline_state(desc)
Compiler.compile raises D3D12::CompileError whose diagnostics hold the compiler output. Root signature serialization errors carry the serializer's message.
Coverage
| Area | API |
|---|---|
| Devices | Factory (CreateDXGIFactory2, EnumAdapters1, EnumWarpAdapter, tearing support), Adapter, Device.create, format support and multisample quality levels, D3D12.enable_debug_layer, InfoQueue messages |
| Submission | CommandQueue (execute, signal, wait, timestamp frequency), CommandAllocator, GraphicsCommandList, Fence with Win32 Event waits |
| Descriptors | DescriptorHeap (CBV/SRV/UAV, sampler, RTV, DSV) with CPU/GPU handle arithmetic; RTV, DSV, SRV, UAV, CBV and sampler creation; copy_descriptors |
| Root signatures | RootSignatureDesc with descriptor tables, root constants, root CBV/SRV/UAV and static samplers, serialized with D3D12SerializeRootSignature |
| Pipelines | GraphicsPipelineDesc (input layouts, blend, rasterizer including wireframe fill, depth-stencil, up to 8 render targets, MSAA) and compute pipelines |
| Resources | committed buffers and 2D textures (depth formats, arrays, cube maps, mips), upload/readback heaps, map/write/read, copyable_footprints |
| Commands | draws, dispatch, buffer/texture-region/resource copies, resolves, transition and UAV barriers, root arguments, queries, PIX events |
| Queries | timestamp query heaps, ResolveQueryData, CommandQueue#timestamp_frequency |
| Presentation | Factory#create_swap_chain (CreateSwapChainForHwnd, flip model), SwapChain#present, resize_buffers, buffer, current_back_buffer_index |
Anything not wrapped is reachable through LibD3D12 structures, the generated enums, and COMObject#vcall with a D3D12::VTable slot.
Errors and lifetimes
Failed HRESULTs raise D3D12::Error with code, hresult, the operation and the system message. Device calls also append debug-layer messages and the device-removed reason when available; Error#device_lost? reports a removed, hung or reset device.
Each wrapper owns one COM reference. release drops it (later use raises D3D12::ReleasedError), and unreleased wrappers release when garbage collected. GraphicsCommandList#close ends recording, as in Direct3D; release it with release. Keep resources alive until a fence shows the GPU has finished with them.
Development
The enums, vtable slot order and interface IDs in src/d3d12/generated come from the SDK headers:
crystal run tools/generate.cr -- /path/to/mingw-w64/include # or a Windows SDK um/shared include dir
It defaults to Homebrew's mingw-w64 headers. Structures in src/lib_d3d12.cr are written by hand and checked against the SDK sizes and offsets in spec/layout_spec.cr.
Run the specs on Windows; set GARNET_D3D12_WARP=1 to use WARP, the software rasteriser that ships with Windows (CI does this, because GitHub's runners have no GPU), and GARNET_D3D12_DEBUG=1 to enable the debug layer when the Graphics Tools optional feature is installed:
$env:GARNET_D3D12_WARP = "1"
crystal spec
The Windows CI job builds and runs examples/adapters.cr and runs every spec on WARP: device creation, clear and readback, an HLSL triangle compiled with D3DCompile, depth readback, cube maps and timestamp queries. The Linux job runs the layout specs and cross-compiles the Windows specs; lint runs Ameba.
Contributing
- Fork it and create a branch.
- Add specs for new bindings; keep
crystal tool format --checkandamebaclean. - Open a pull request.
License
MIT; see LICENSE.
d3d12.cr
- 0
- 0
- 0
- 2
- 0
- 5 minutes ago
- December 3, 2026
MIT License
Thu, 03 Dec 2026 13:57:32 GMT