vulkan.cr
Vulkan for Crystal
require "vulkan" provides an object-oriented API alongside the raw LibVulkan C bindings. This shard has no Garnet, windowing, shader or submission-policy dependency.
Commands with a first handle parameter become methods on that resource. Descriptors are Crystal objects: optional references use T?, strings use String, and variable-length inputs use arrays. Native handles, pointers, output allocations and C-layout records stay inside the implementation.
shader_info = Vulkan::ShaderModuleCreateInfo.new(code: spirv_words)
shader = device.create_shader_module(shader_info)
stage = Vulkan::PipelineShaderStageCreateInfo.new(
stage: LibVulkan::SHADER_STAGE_COMPUTE_BIT,
module: shader,
name: "main",
)
command.bind_pipeline(LibVulkan::PIPELINE_BIND_POINT_COMPUTE, pipeline)
command.dispatch(1_u32, 1_u32, 1_u32)
command.end_recording
queue.submit([Vulkan::SubmitInfo.new(command_buffers: [command])])
queue.wait_idle
device.destroy_shader_module(shader)
Create methods return resource objects; queries return values or arrays. Failures raise Vulkan::Error, which retains the native result code. Wait operations return WaitStatus; event queries return a boolean. Image acquisition returns AcquiredImage, including the suboptimal flag. Other non-success statuses raise instead of returning potentially uninitialized output.
Descriptors accept keyword initialization and normal property assignment. Array counts are derived during marshalling; structure tags are initialized automatically. Set next to another descriptor to build an extension chain. Queries with a single record output accept an optional preconfigured output descriptor, including its chain. Clear-value unions marshal the member most recently assigned through its setter.
device.map_memory(memory, size) returns a checked MappedMemory. Its read returns owned bytes, write copies bytes into the mapping, and close unmaps it. Callers remain responsible for Vulkan synchronization and noncoherent memory flush/invalidation.
Ownership and native interoperability
Resources created through the typed API own their native handles. Ordinary Crystal references express ownership: queues retain in-flight submissions, submissions retain command buffers and synchronization objects, command buffers retain recorded resources, and resources retain their native parents. Finalizers release native handles directly. There is no global cleanup registry or separate reference-counting graph.
GC timing is nondeterministic. Explicit destroy/free methods remain available, but callers must ensure those resources are no longer in use. Ownership does not replace Vulkan synchronization: the wrappers do not make concurrent recording, descriptor mutation, queue access, or explicit destruction thread-safe.
Descriptors own their native record and backing allocations. to_unsafe borrows that representation, retaining a stable address across unchanged conversions. A borrow must not outlive its wrapper or span mutation of the descriptor, its arrays, or nested descriptors. Mutation and concurrent use require caller synchronization. Native record constructors copy strings and arrays into owned Crystal storage. There is no per-call conversion scope.
info = Vulkan::BufferCreateInfo.new(size: 4096_u64,
usage: LibVulkan::BUFFER_USAGE_TRANSFER_DST_BIT)
buffer = device.create_buffer(info) # owns the newly created handle
# Explicit FFI escape hatches:
native = buffer.to_unsafe
borrowed = Vulkan::Buffer.new(native, owner: buffer)
copy = Vulkan::BufferCreateInfo.new(info.to_unsafe.value)
A constructor receiving an existing handle borrows it by default. Pass its owning wrapper as owner: to retain the allocation. Use owned: true only to adopt a newly owned handle, with the correct parent and allocator; never independently adopt the same handle twice. Ordinary methods continue to accept objects, arrays and values rather than pointers.
Command buffers retain resources referenced during recording, including bound buffers and descriptor sets. Successful reset or beginning a new recording drops the previous recording's references. Completion alone preserves them so the command buffer can be submitted again.
Each queue owns its submissions until completion is observed. Queue operations poll private completion fences; queue.poll also reclaims completed submissions without waiting. queue.wait_idle and device.wait_idle release the relevant completed submissions immediately. When the caller supplies a fence, an additional empty submission signals a private fence so resetting the caller's fence cannot invalidate completion tracking. Repeated device queue queries return the same live wrapper through a weak identity cache.
If an otherwise-unused queue is collected with outstanding work, its finalizer waits for queue idle before releasing its references. This can block GC; keep active queues reachable and poll them during the normal application loop. No application-side resource registration is needed for typed recording and submission calls.
Swapchains retain acquisition synchronization objects until fence completion. Queues retain presentation resources until queue/device idle; the bound baseline API has no presentation completion fence. Repeated presentations retain each referenced resource only once. These WSI paths are compiled but are not exercised by the headless lifetime tests.
Buffer/image memory bindings, creation dependencies, and descriptor writes retain their referenced resources. Descriptor sets without individual-free pool support remain native pool allocations until pool destruction/reset. Pool reset invalidates their wrappers. For opaque update-template payloads, device addresses, or operations issued directly through LibVulkan, use resource.retain(dependency) and keep the operation's owner reachable for its required lifetime; raw data cannot convey those ownership relationships automatically.
Optional custom allocation uses HostAllocator and HostMemory. The resource retains its allocator and uses it again during cleanup. MappedMemory retains its memory and device, and unmaps directly when closed or collected.
The standalone compute test demonstrates instance/device creation, memory mapping, a caller-supplied shader, recording and submission without pointer syntax. LibVulkan remains available explicitly for raw FFI interoperability.
Coverage and generation
The checked-in manifest binds 224 commands: core Vulkan 1.0–1.3 and selected WSI commands. This is not exhaustive extension or Vulkan 1.4 coverage. Applications must enable required features/extensions and respect runtime API availability. tools/functions.txt is the exact inventory. Additional extension-chain records must be added as coverage expands.
Generate a Clang JSON AST from a C translation unit containing #include <vulkan/vulkan.h>, then run:
crystal run tools/generate.cr -- /path/to/ast.json
crystal run tools/generate_api.cr -- /path/to/ast.json
crystal run tools/check_abi.cr
The API generator uses the vendored Khronos registry in tools/registry/vk.xml for pointer direction, array lengths, optionality and structure tags. Keep that registry aligned with the SDK used to generate the raw bindings.
To compile every generated command body without executing native calls:
VULKAN_TYPECHECK_OUTPUT=/tmp/vulkan-typecheck.cr crystal run tools/generate_api.cr -- /path/to/ast.json
CRYSTAL_PATH="$(crystal env CRYSTAL_PATH):$PWD/src" crystal build /tmp/vulkan-typecheck.cr --no-codegen
From the Garnet workspace, scripts/check-render-api vulkan runs the specs plus optimized CPU and GPU GC-lifetime fixtures; scripts/check-render-api abi checks 172 native records. Tests require the Vulkan loader, a driver and glslangValidator. On macOS, MoltenVK and portability extensions are used. Current native ABI validation is on arm64 macOS; other targets require their own checks.
vulkan.cr
- 0
- 0
- 0
- 1
- 0
- 1 day ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:09:41 GMT