vulkan

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: BSD-3-Clause Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-gfx/vulkan

A pure-Go (no cgo) binding to the part of Vulkan a compute workload needs. It calls the system loader libvulkan.so.1 through purego, so a binary built with CGO_ENABLED=0 can be cross-compiled on one machine and copied to another that has a Vulkan driver.

in, err := vulkan.Open(vulkan.Options{Validation: false})
if err != nil { /* errors.Is(err, vulkan.ErrUnsupported): no loader */ }
defer in.Close()

pd, err := in.Pick(vulkan.Filter{}) // discrete GPU first, then integrated, ..., CPU
dev, err := pd.Open()               // one device, one compute queue
defer dev.Close()

px, _ := dev.NewBuffer(1<<20, vulkan.UsageStorage) // host-visible, coherent, mapped
sh, _ := dev.NewShader(words)                      // SPIR-V words, e.g. go-gfx/wgsl's spirv.Module
pipe, _ := dev.NewComputePipeline(sh, "main", []vulkan.Binding{{0, vulkan.StorageBuffer}})
pipe.Bind(0, px)

cb, _ := dev.NewCommandBuffer()
cb.Begin(); cb.Dispatch(pipe, 64, 1, 1); cb.End()
fence, _ := dev.Submit(cb)
ok, err := fence.Wait(time.Second)   // px.Bytes() now holds the shader's writes

Surface

Piece Entry points
Loader Open (dlopen libvulkan.so.1, vkGetInstanceProcAddr; device functions through vkGetDeviceProcAddr)
Instance Options{Validation} enables VK_LAYER_KHRONOS_validation (ErrLayerNotPresent if absent), Instance.Close
Physical device Instance.Devices, Instance.Pick(Filter), Pick(infos, Filter); DeviceInfo carries name, type, vendor, API and driver version, driver name and the limits the binding checks
Device and queue PhysicalDevice.Open (one compute queue), Device.Close
Buffers Device.NewBuffer(size, usage), Buffer.Bytes, Buffer.Close
Shader Device.NewShader(words)
Pipeline Device.NewComputePipeline(shader, entry, bindings), Pipeline.Bind; descriptor set layout, pool and set are owned by the pipeline
Commands Device.NewCommandBuffer, Begin, Dispatch, End, Close
Fences Device.Submit, Fence.Wait, Fence.Done, Fence.Close
Errors a negative VkResult is *Error{Op, Result}; errors.Is(err, vulkan.ErrDeviceLost) and the other sentinels

Safety

  • A buffer size is checked before allocation against maxStorageBufferRange or maxUniformBufferRange for its usage, against maxMemoryAllocationSize (twice: for the request and for the driver's memoryRequirements.size), and against the largest Go slice, all in uint64, so 32-bit wrap-around cannot make a huge request look small. A refusal is ErrTooLarge.
  • A shader is checked for the SPIR-V magic number and a bound of 2^24 words.
  • Every handle made on the way is destroyed on an error path: a test fails each fallible driver call in turn, on a fake driver, and requires zero live handles afterwards.
  • The layout of every struct passed to Vulkan is generated from the Khronos registry (below) and pinned by a generated test.

Struct layouts: vkgen

internal/vk/types_gen.go is generated from the Khronos registry (registry/vk.xml.gz, Vulkan-Headers vulkan-sdk-1.4.363.0, Apache-2.0 OR MIT, kept gzipped: 0.3 MB instead of 3.3 MB; gunzip -k gives the original) by cmd/vkgen, with sizes and offsets computed by the C rules for a 64-bit target. It also writes layout_gen_test.go, which pins unsafe.Sizeof, unsafe.Alignof and unsafe.Offsetof of every Go struct against that table.

go generate ./internal/vk                       # rewrites both files
go run ./cmd/vkgen -r registry/vk.xml.gz -o internal/vk --check   # fails on drift

The registry reader is fuzzed (FuzzParse, corpus committed in internal/vkgen/testdata/fuzz).

Testing

The pure-Go parts run against a fake driver on every platform and are held to 100 % coverage. The real driver is exercised where one exists:

  • CI, Ubuntu with lavapipe and the Khronos validation layer, with the test binary built CGO_ENABLED=0: a compute dispatch of a fill kernel (emitted by go-gfx/wgsl's spirv package) must write the expected bytes, and the run must produce zero validation messages (the test captures stdout and stderr). A second test proves that lane can fail: a pipeline layout that does not match the shader draws a VUID- message.
  • A break check: binding the pixels' descriptor to the wrong buffer must not produce the expected bytes.
  • VULKAN_REQUIRE=1 turns "no Vulkan here" from a skip into a failure; VULKAN_VALIDATION=1 enables the layer; VULKAN_VENDOR=0x1002 restricts the pick to a vendor.

lavapipe, spirv-val and the validation layer are oracles in CI only: nothing at build time or run time depends on them.

Out of scope

  • Window-system integration: no VK_KHR_surface, no swapchain, no WSI.
  • Graphics pipelines, render passes, images, samplers.
  • Callbacks (VK_EXT_debug_utils): the validation layer's output is read from stdout and stderr.
  • 32-bit targets: non-dispatchable handles are uint64_t passed in two words there, and purego's 32-bit Linux targets are Tier 2. On other platforms Open returns ErrUnsupported. Supported: linux/amd64 and linux/arm64.
  • Windows (vulkan-1.dll) and macOS (MoltenVK).

Close keeps the loader mapped for the life of the process: drivers may keep threads alive after their instance is destroyed.

Threading

A queue is externally synchronised: a Device and everything made from it belong to one goroutine at a time.

Documentation

Overview

Package vulkan is a pure-Go (no cgo) binding to the part of Vulkan a compute workload needs: the loader, an instance with the optional Khronos validation layer, a physical-device pick, one device and one compute queue, host-visible coherent buffers, shader modules from SPIR-V words, compute pipelines with their descriptor sets, command buffers, dispatch and fences.

It calls the system loader libvulkan.so.1 through purego, so a binary built with CGO_ENABLED=0 can be cross-compiled and copied to a machine that has a Vulkan driver. It is Linux 64-bit only (amd64, arm64); elsewhere Open returns ErrUnsupported. There is no window-system integration and no graphics pipeline.

Threading: a queue is externally synchronised, so a Device and everything made from it belong to one goroutine at a time.

Close order: close buffers, pipelines, shaders, command buffers and fences before their Device, and the Device before the Instance.

Index

Constants

The usages a compute workload needs.

The device types, in the registry's numbering.

View Source
const (
	VendorAMD    uint32 = 0x1002
	VendorNVIDIA uint32 = 0x10de
	VendorIntel  uint32 = 0x8086
)

Well-known PCI vendor identifiers.

The kinds a compute shader here uses.

Variables

View Source
var (
	ErrOutOfHostMemory      = &Error{Result: Result(vk.ErrorOutOfHostMemory)}
	ErrOutOfDeviceMemory    = &Error{Result: Result(vk.ErrorOutOfDeviceMemory)}
	ErrInitializationFailed = &Error{Result: Result(vk.ErrorInitializationFailed)}
	ErrDeviceLost           = &Error{Result: Result(vk.ErrorDeviceLost)}
	ErrMemoryMapFailed      = &Error{Result: Result(vk.ErrorMemoryMapFailed)}
	ErrLayerNotPresent      = &Error{Result: Result(vk.ErrorLayerNotPresent)}
	ErrExtensionNotPresent  = &Error{Result: Result(vk.ErrorExtensionNotPresent)}
	ErrFeatureNotPresent    = &Error{Result: Result(vk.ErrorFeatureNotPresent)}
	ErrIncompatibleDriver   = &Error{Result: Result(vk.ErrorIncompatibleDriver)}
	ErrTooManyObjects       = &Error{Result: Result(vk.ErrorTooManyObjects)}
	ErrFragmentedPool       = &Error{Result: Result(vk.ErrorFragmentedPool)}
	ErrOutOfPoolMemory      = &Error{Result: Result(vk.ErrorOutOfPoolMemory)}
	ErrUnknown              = &Error{Result: Result(vk.ErrorUnknown)}
)

The VkResult errors a compute client can meet. errors.Is(err, ErrDeviceLost) is true for any *Error that carries that code.

View Source
var (
	// ErrUnsupported means this platform has no binding (it is Linux, 64-bit
	// only) or the Vulkan loader library is not installed.
	ErrUnsupported = errors.ErrUnsupported
	// ErrNoDevice means no physical device matches the filter.
	ErrNoDevice = errors.New("vulkan: no matching physical device")
	// ErrTooLarge means a size exceeds a limit of the device or of the process.
	ErrTooLarge = errors.New("vulkan: size exceeds a device limit")
	// ErrInvalid means an argument the binding refuses before calling Vulkan.
	ErrInvalid = errors.New("vulkan: invalid argument")
	// ErrNoMemoryType means the device offers no host-visible coherent memory
	// for the buffer.
	ErrNoMemoryType = errors.New("vulkan: no host-visible coherent memory type")
	// ErrClosed means the object, or the device it belongs to, was closed.
	ErrClosed = errors.New("vulkan: object is closed")
)

Errors of this package that are not a VkResult.

Functions

func Pick

func Pick(infos []DeviceInfo, f Filter) (int, error)

Pick chooses among infos: the best-ranked device that passes the filter and reports Vulkan 1.1 or later, the first of equals. It returns an index into infos, or ErrNoDevice.

Types

type Binding

type Binding struct {
	Binding uint32
	Kind    DescriptorKind
}

Binding declares one binding of descriptor set 0.

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer is a VkBuffer bound to host-visible, host-coherent memory that stays mapped for its whole life.

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Bytes is the mapped memory: len(Bytes()) is the size asked for. It is valid until Close, and writes by the host are visible to the device at the next submission (the memory is coherent).

func (*Buffer) Close

func (b *Buffer) Close()

Close unmaps and frees the buffer. It is safe to call twice, and a no-op once the device is closed.

func (*Buffer) Size

func (b *Buffer) Size() uint64

Size is the size in bytes.

type BufferUsage

type BufferUsage uint32

BufferUsage says what a buffer is for.

type CommandBuffer

type CommandBuffer struct {
	// contains filtered or unexported fields
}

CommandBuffer is a primary command buffer with a command pool of its own.

func (*CommandBuffer) Begin

func (c *CommandBuffer) Begin() error

Begin starts recording. Beginning an already recording buffer is ErrInvalid. The buffer is recorded for one submission at a time (reset by Begin).

func (*CommandBuffer) Close

func (c *CommandBuffer) Close()

Close destroys the command pool, which frees the buffer. It is safe to call twice, and a no-op once the device is closed. No submission may be pending.

func (*CommandBuffer) Dispatch

func (c *CommandBuffer) Dispatch(p *Pipeline, x, y, z uint32) error

Dispatch records: bind the pipeline and its descriptor set, dispatch x*y*z workgroups, then a barrier that makes the shader's writes visible to the host, so the mapped buffers can be read after the fence. The counts are checked against maxComputeWorkGroupCount.

func (*CommandBuffer) End

func (c *CommandBuffer) End() error

End finishes recording.

type DescriptorKind

type DescriptorKind int32

DescriptorKind is the kind of resource bound at a binding.

type Device

type Device struct {
	// contains filtered or unexported fields
}

Device is a VkDevice with one compute queue.

func (*Device) Close

func (d *Device) Close() error

Close waits for the queue to go idle and destroys the device. The caller has closed everything made from it. It is safe to call twice.

func (*Device) Info

func (d *Device) Info() DeviceInfo

Info is the physical device's description.

func (*Device) NewBuffer

func (d *Device) NewBuffer(size uint64, usage BufferUsage) (*Buffer, error)

NewBuffer creates a buffer of size bytes. The size is checked against the device limits first; every handle made on the way is destroyed on an error.

func (*Device) NewCommandBuffer

func (d *Device) NewCommandBuffer() (*CommandBuffer, error)

NewCommandBuffer creates a command pool on the compute queue family and one command buffer from it. On an error nothing is left alive.

func (*Device) NewComputePipeline

func (d *Device) NewComputePipeline(sh *Shader, entry string, bindings []Binding) (*Pipeline, error)

NewComputePipeline builds the descriptor set layout for bindings, the pipeline layout, the pipeline for entry point entry of sh, and a descriptor set. On an error nothing is left alive.

func (*Device) NewShader

func (d *Device) NewShader(words []uint32) (*Shader, error)

NewShader creates a shader module from SPIR-V words (for instance from go-gfx/wgsl's spirv.Module). The words are checked for the magic number and a sane length; the driver (and the validation layer) check the rest.

func (*Device) Submit

func (d *Device) Submit(c *CommandBuffer) (*Fence, error)

Submit sends the recorded buffer to the compute queue and returns a fence that signals when it has run.

type DeviceInfo

type DeviceInfo struct {
	Index         int // position in the enumeration
	Name          string
	Type          DeviceType
	VendorID      uint32
	DeviceID      uint32
	APIVersion    Version
	DriverVersion uint32 // vendor-specific encoding; Mesa drivers use Version's
	DriverName    string // from VkPhysicalDeviceDriverProperties
	DriverInfo    string

	// Limits the binding checks before it allocates or dispatches.
	MaxStorageBufferRange    uint32
	MaxUniformBufferRange    uint32
	MaxMemoryAllocationSize  uint64
	MaxComputeWorkGroupCount [3]uint32
}

DeviceInfo is what a physical device reports.

type DeviceType

type DeviceType int32

DeviceType is VkPhysicalDeviceType.

func (DeviceType) String

func (t DeviceType) String() string

String names the type.

type Error

type Error struct {
	Op     string // the Vulkan command, "vkCreateBuffer"
	Result Result
}

Error is a Vulkan call that returned a negative VkResult. Use errors.Is with the sentinels below to test for one code, or errors.As to read the call.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches a sentinel (an *Error with no Op) that carries the same code.

type Fence

type Fence struct {
	// contains filtered or unexported fields
}

Fence is a VkFence that signals when a submission completes.

func (*Fence) Close

func (f *Fence) Close()

Close destroys the fence. It is safe to call twice.

func (*Fence) Done

func (f *Fence) Done() (bool, error)

Done polls the fence without blocking.

func (*Fence) Wait

func (f *Fence) Wait(timeout time.Duration) (bool, error)

Wait blocks until the fence signals or the timeout passes. It reports whether the fence is signalled; a timeout is (false, nil).

type Filter

type Filter struct {
	VendorID uint32       // 0 for any vendor
	Types    []DeviceType // empty for any type
}

Filter narrows Pick. The zero Filter accepts every device.

type Instance

type Instance struct {
	// contains filtered or unexported fields
}

Instance is a VkInstance.

func Open

func Open(o Options) (*Instance, error)

Open loads libvulkan.so.1 and creates an instance.

func (*Instance) Close

func (in *Instance) Close() error

Close destroys the instance and closes the loader. It is safe to call twice.

func (*Instance) Devices

func (in *Instance) Devices() ([]*PhysicalDevice, error)

Devices lists the physical devices.

func (*Instance) Pick

func (in *Instance) Pick(f Filter) (*PhysicalDevice, error)

Pick returns the device chosen by the package-level Pick.

type Options

type Options struct {
	// ApplicationName is reported to the driver. It may be empty.
	ApplicationName string
	// Validation enables VK_LAYER_KHRONOS_validation. When the layer is not
	// installed Open fails with ErrLayerNotPresent: a validation run that
	// silently validated nothing would prove nothing.
	Validation bool
}

Options configures Open.

type PhysicalDevice

type PhysicalDevice struct {
	Info DeviceInfo
	// contains filtered or unexported fields
}

PhysicalDevice is a VkPhysicalDevice. It needs no Close.

func (*PhysicalDevice) Open

func (pd *PhysicalDevice) Open() (*Device, error)

Open creates a device with one compute queue on this physical device.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline is a compute pipeline with its layout, and one descriptor set (set 0) allocated from a pool of its own.

func (*Pipeline) Bind

func (p *Pipeline) Bind(binding uint32, b *Buffer) error

Bind points a binding of the pipeline's descriptor set at a whole buffer. The binding must be declared by the pipeline, and the buffer must have the usage that kind of binding needs. Bind before recording the dispatch that uses it, and not while a submission that uses the set is in flight.

func (*Pipeline) Close

func (p *Pipeline) Close()

Close destroys the pipeline, its layouts and its pool (which frees the set).

type Result

type Result int32

Result is a VkResult. Negative values are errors, zero is success, positive values are successful statuses (VK_NOT_READY, VK_TIMEOUT, VK_INCOMPLETE).

func (Result) String

func (r Result) String() string

String is the registry's name of the code, or "VkResult(n)".

type Shader

type Shader struct {
	// contains filtered or unexported fields
}

Shader is a VkShaderModule.

func (*Shader) Close

func (s *Shader) Close()

Close destroys the module; a pipeline made from it keeps working.

type Version

type Version uint32

Version is a packed Vulkan version (VK_MAKE_API_VERSION).

func (Version) Major

func (v Version) Major() uint32

Major, Minor and Patch are the fields of the packed version.

func (Version) Minor

func (v Version) Minor() uint32

Minor is the minor number.

func (Version) Patch

func (v Version) Patch() uint32

Patch is the patch number.

func (Version) String

func (v Version) String() string

String is "major.minor.patch".

Directories

Path Synopsis
cmd
vkgen command
Command vkgen generates the Go mirrors of the Vulkan structures that go-gfx/vulkan uses from the Khronos registry (vk.xml).
Command vkgen generates the Go mirrors of the Vulkan structures that go-gfx/vulkan uses from the Khronos registry (vk.xml).
internal
native
Package native opens the system Vulkan loader, libvulkan.so.1, through purego and resolves the entry points of internal/vk's function tables.
Package native opens the system Vulkan loader, libvulkan.so.1, through purego and resolves the entry points of internal/vk's function tables.
vk
vkgen
Package vkgen reads the Khronos registry (vk.xml) and generates the Go mirrors of the Vulkan structures, enumerations and handles that go-gfx/vulkan calls.
Package vkgen reads the Khronos registry (vk.xml) and generates the Go mirrors of the Vulkan structures, enumerations and handles that go-gfx/vulkan calls.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL