Documentation
¶
Overview ¶
Package hal provides the Hardware Abstraction Layer for WebGPU implementations.
The HAL defines backend-agnostic interfaces for GPU operations, allowing different graphics backends (Vulkan, Metal, DX12, GL) to be used interchangeably.
Architecture ¶
The HAL is organized into several layers:
- Backend - Factory for creating instances (entry point)
- Instance - Entry point for adapter enumeration and surface creation
- Adapter - Physical GPU representation with capability queries
- Device - Logical device for resource creation and command submission
- Queue - Command buffer submission and presentation
- CommandEncoder - Command recording
Design Principles ¶
The HAL prioritizes portability over safety, delegating validation to the higher core layer. This means:
- Most methods are unsafe in terms of GPU state validation
- Validation is the caller's responsibility
- Only unrecoverable errors are returned (out of memory, device lost)
- Invalid usage results in undefined behavior at the GPU level
Resource Types ¶
All GPU resources (buffers, textures, pipelines, etc.) implement the Resource interface which provides a Destroy method. Resources must be explicitly destroyed to free GPU memory.
Backend Registration ¶
Backends register themselves using RegisterBackend. The core layer can then query available backends and create instances dynamically:
backend, ok := hal.GetBackend(types.BackendVulkan)
if !ok {
return fmt.Errorf("vulkan backend not available")
}
instance, err := backend.CreateInstance(desc)
Thread Safety ¶
Unless explicitly stated, HAL interfaces are not thread-safe. Synchronization is the caller's responsibility. Notable exceptions:
- Backend registration (RegisterBackend, GetBackend) is thread-safe
- Queue.Submit is typically thread-safe (backend-specific)
Error Handling ¶
The HAL uses error values for unrecoverable errors:
- ErrDeviceOutOfMemory - GPU memory exhausted
- ErrDeviceLost - GPU disconnected or driver reset
- ErrSurfaceLost - Window destroyed or surface invalidated
- ErrSurfaceOutdated - Window resized, need reconfiguration
Validation errors (invalid descriptors, incorrect usage) are the caller's responsibility and are not checked by the HAL.
Reference ¶
This design is based on wgpu-hal from the Rust WebGPU implementation. See: https://github.com/gfx-rs/wgpu/tree/trunk/wgpu-hal
Index ¶
- Variables
- func AvailableBackends() []types.Backend
- func RegisterBackend(backend Backend)
- func RegisterBackendFactory(variant types.Backend, factory BackendFactory)
- type AcquiredSurfaceTexture
- type Adapter
- type Alignments
- type Backend
- type BackendFactory
- type BackendFeatures
- type BackendInfo
- type BackendLimitations
- type BindGroup
- type BindGroupDescriptor
- type BindGroupLayout
- type BindGroupLayoutDescriptor
- type Buffer
- type BufferBarrier
- type BufferCopy
- type BufferDescriptor
- type BufferTextureCopy
- type BufferUsageTransition
- type Capabilities
- type CommandBuffer
- type CommandEncoder
- type CommandEncoderDescriptor
- type CompositeAlphaMode
- type ComputePassDescriptor
- type ComputePassEncoder
- type ComputePassTimestampWrites
- type ComputePipeline
- type ComputePipelineDescriptor
- type ComputeState
- type DepthStencilState
- type Device
- type DownlevelCapabilities
- type DownlevelFlags
- type ExposedAdapter
- type Extent3D
- type Fence
- type FragmentState
- type ImageCopyTexture
- type ImageDataLayout
- type Instance
- type InstanceDescriptor
- type OpenDevice
- type Origin3D
- type PipelineLayout
- type PipelineLayoutDescriptor
- type PresentMode
- type PushConstantRange
- type QuerySet
- type Queue
- type Range
- type RenderBundle
- type RenderPassColorAttachment
- type RenderPassDepthStencilAttachment
- type RenderPassDescriptor
- type RenderPassEncoder
- type RenderPassTimestampWrites
- type RenderPipeline
- type RenderPipelineDescriptor
- type Resource
- type Sampler
- type SamplerDescriptor
- type ShaderModule
- type ShaderModuleDescriptor
- type ShaderSource
- type StencilFaceState
- type StencilOperation
- type Surface
- type SurfaceCapabilities
- type SurfaceConfiguration
- type SurfaceTexture
- type Texture
- type TextureBarrier
- type TextureCopy
- type TextureDescriptor
- type TextureFormatCapabilities
- type TextureFormatCapabilityFlags
- type TextureRange
- type TextureUsageTransition
- type TextureView
- type TextureViewDescriptor
- type VertexState
Constants ¶
This section is empty.
Variables ¶
var ( // ErrBackendNotFound indicates the requested backend is not registered. ErrBackendNotFound = errors.New("hal: backend not found") // ErrDeviceOutOfMemory indicates the GPU has exhausted its memory. // This is unrecoverable - the application should reduce resource usage // or gracefully terminate. ErrDeviceOutOfMemory = errors.New("hal: device out of memory") // ErrDeviceLost indicates the GPU device has been lost. // This can happen due to: // - GPU driver crash or reset // - GPU hardware disconnection // - Driver timeout (TDR on Windows) // The device cannot be recovered and must be recreated. ErrDeviceLost = errors.New("hal: device lost") // ErrSurfaceLost indicates the rendering surface has been destroyed. // This typically happens when the window is closed. // The surface cannot be recovered - create a new one if needed. ErrSurfaceLost = errors.New("hal: surface lost") // ErrSurfaceOutdated indicates the surface configuration is stale. // This happens when: // - Window was resized // - Display mode changed // - Surface pixel format changed // Call Surface.Configure again with updated parameters. ErrSurfaceOutdated = errors.New("hal: surface outdated") // ErrTimeout indicates an operation timed out. // This is typically returned by Wait operations. ErrTimeout = errors.New("hal: timeout") )
Common HAL errors representing unrecoverable GPU states.
Functions ¶
func AvailableBackends ¶
AvailableBackends returns all registered backend types. The order is non-deterministic.
func RegisterBackend ¶
func RegisterBackend(backend Backend)
RegisterBackend registers a backend implementation. This is typically called from init() functions in backend packages. Registering the same backend type multiple times will replace the previous registration.
func RegisterBackendFactory ¶
func RegisterBackendFactory(variant types.Backend, factory BackendFactory)
RegisterBackendFactory registers a factory for lazy backend creation. This is preferred over RegisterBackend for backends that may fail initialization (e.g., missing GPU drivers).
Types ¶
type AcquiredSurfaceTexture ¶
type AcquiredSurfaceTexture struct {
// Texture is the acquired surface texture.
Texture SurfaceTexture
// Suboptimal indicates the surface configuration is suboptimal but usable.
// Consider reconfiguring the surface at a convenient time.
Suboptimal bool
}
AcquiredSurfaceTexture bundles a surface texture with metadata.
type Adapter ¶
type Adapter interface {
// Open opens a logical device with the requested features and limits.
// Returns an error if the adapter cannot support the requested configuration.
Open(features types.Features, limits types.Limits) (OpenDevice, error)
// TextureFormatCapabilities returns capabilities for a specific texture format.
TextureFormatCapabilities(format types.TextureFormat) TextureFormatCapabilities
// SurfaceCapabilities returns capabilities for a specific surface.
// Returns nil if the adapter is not compatible with the surface.
SurfaceCapabilities(surface Surface) *SurfaceCapabilities
// Destroy releases the adapter.
// Any devices created from this adapter must be destroyed first.
Destroy()
}
Adapter represents a physical GPU. Adapters are enumerated from instances and provide capability queries.
type Alignments ¶
type Alignments struct {
// BufferCopyOffset is the required alignment for buffer copy offsets.
BufferCopyOffset uint64
// BufferCopyPitch is the required alignment for buffer copy pitch (bytes per row).
BufferCopyPitch uint64
}
Alignments specifies buffer alignment requirements.
type Backend ¶
type Backend interface {
// Variant returns the backend type identifier.
Variant() types.Backend
// CreateInstance creates a new GPU instance with the given configuration.
// Returns an error if instance creation fails (e.g., drivers not available).
CreateInstance(desc *InstanceDescriptor) (Instance, error)
}
Backend identifies a graphics backend implementation. Backends are registered globally and provide factory methods for instances.
func CreateBackend ¶
CreateBackend creates a backend instance using registered factory. Returns error if no factory is registered for the variant.
func GetBackend ¶
GetBackend returns a registered backend by type. Returns (nil, false) if the backend is not registered.
func SelectBestBackend ¶
SelectBestBackend chooses the most capable available backend. Priority: Vulkan > Metal > DX12 > OpenGL > Noop
type BackendFactory ¶
BackendFactory creates backend instances. This allows lazy initialization of backends.
type BackendFeatures ¶
type BackendFeatures struct {
// SupportsCompute indicates compute shader support.
SupportsCompute bool
// SupportsMultiQueue indicates multiple queue support.
SupportsMultiQueue bool
// SupportsRayTracing indicates ray tracing support.
SupportsRayTracing bool
// MaxTextureSize is the maximum texture dimension.
MaxTextureSize uint32
// MaxBufferSize is the maximum buffer size.
MaxBufferSize uint64
}
BackendFeatures describes capabilities of a backend.
type BackendInfo ¶
type BackendInfo struct {
// Variant identifies the backend type.
Variant types.Backend
// Name is a human-readable backend name.
Name string
// Version of the backend implementation.
Version string
// Features supported by this backend.
Features BackendFeatures
// Limitations of this backend.
Limitations BackendLimitations
}
BackendInfo provides metadata about a backend implementation.
func ProbeBackend ¶
func ProbeBackend(variant types.Backend) (*BackendInfo, error)
ProbeBackend tests if a backend is available without fully initializing it. Returns BackendInfo if available, error otherwise.
type BackendLimitations ¶
type BackendLimitations struct {
// NoAsyncCompute means compute must run on graphics queue.
NoAsyncCompute bool
// LimitedFormats means some texture formats unavailable.
LimitedFormats bool
// NoBindlessResources means bindless not supported.
NoBindlessResources bool
}
BackendLimitations describes known limitations.
type BindGroup ¶
type BindGroup interface {
Resource
}
BindGroup represents bound resources. Bind groups associate actual resources with bind group layouts.
type BindGroupDescriptor ¶
type BindGroupDescriptor struct {
// Label is an optional debug name.
Label string
// Layout is the bind group layout.
Layout BindGroupLayout
// Entries are the resource bindings.
Entries []types.BindGroupEntry
}
BindGroupDescriptor describes a bind group.
type BindGroupLayout ¶
type BindGroupLayout interface {
Resource
}
BindGroupLayout defines the layout of a bind group. Layouts specify the structure of resource bindings for shaders.
type BindGroupLayoutDescriptor ¶
type BindGroupLayoutDescriptor struct {
// Label is an optional debug name.
Label string
// Entries define the bindings in this layout.
Entries []types.BindGroupLayoutEntry
}
BindGroupLayoutDescriptor describes a bind group layout.
type Buffer ¶
type Buffer interface {
Resource
}
Buffer represents a GPU buffer. Buffers are contiguous memory regions accessible by the GPU.
type BufferBarrier ¶
type BufferBarrier struct {
Buffer Buffer
Usage BufferUsageTransition
}
BufferBarrier defines a buffer state transition.
type BufferCopy ¶
BufferCopy defines a buffer-to-buffer copy region.
type BufferDescriptor ¶
type BufferDescriptor struct {
// Label is an optional debug name.
Label string
// Size in bytes.
Size uint64
// Usage specifies how the buffer will be used.
Usage types.BufferUsage
// MappedAtCreation creates the buffer pre-mapped for writing.
MappedAtCreation bool
}
BufferDescriptor describes how to create a buffer.
type BufferTextureCopy ¶
type BufferTextureCopy struct {
BufferLayout ImageDataLayout
TextureBase ImageCopyTexture
Size Extent3D
}
BufferTextureCopy defines a buffer-texture copy region.
type BufferUsageTransition ¶
type BufferUsageTransition struct {
OldUsage types.BufferUsage
NewUsage types.BufferUsage
}
BufferUsageTransition defines a buffer usage state transition.
type Capabilities ¶
type Capabilities struct {
// Limits are the maximum supported limits.
Limits types.Limits
// AlignmentsMask specifies required buffer alignment (bitmask).
AlignmentsMask Alignments
// DownlevelCapabilities for GL/GLES backends.
DownlevelCapabilities DownlevelCapabilities
}
Capabilities contains detailed adapter capabilities.
type CommandBuffer ¶
type CommandBuffer interface {
Resource
}
CommandBuffer holds recorded GPU commands. Command buffers are immutable after encoding and can be submitted to a queue.
type CommandEncoder ¶
type CommandEncoder interface {
// BeginEncoding begins command recording with an optional label.
BeginEncoding(label string) error
// EndEncoding finishes command recording and returns a command buffer.
// After this call, the encoder cannot be used again.
EndEncoding() (CommandBuffer, error)
// DiscardEncoding discards the encoder without creating a command buffer.
// Use this to cancel encoding that encountered errors.
DiscardEncoding()
// ResetAll resets command buffers for reuse.
// This is an optimization to avoid allocating new command buffers.
// Not all backends support this.
ResetAll(commandBuffers []CommandBuffer)
// TransitionBuffers transitions buffer states for synchronization.
// This is required on some backends (Vulkan, DX12) but no-op on others (Metal).
TransitionBuffers(barriers []BufferBarrier)
// TransitionTextures transitions texture states for synchronization.
// This is required on some backends (Vulkan, DX12) but no-op on others (Metal).
TransitionTextures(barriers []TextureBarrier)
// ClearBuffer clears a buffer region to zero.
ClearBuffer(buffer Buffer, offset, size uint64)
// CopyBufferToBuffer copies data between buffers.
CopyBufferToBuffer(src, dst Buffer, regions []BufferCopy)
// CopyBufferToTexture copies data from a buffer to a texture.
CopyBufferToTexture(src Buffer, dst Texture, regions []BufferTextureCopy)
// CopyTextureToBuffer copies data from a texture to a buffer.
CopyTextureToBuffer(src Texture, dst Buffer, regions []BufferTextureCopy)
// CopyTextureToTexture copies data between textures.
CopyTextureToTexture(src, dst Texture, regions []TextureCopy)
// BeginRenderPass begins a render pass.
// Returns a render pass encoder for recording draw commands.
BeginRenderPass(desc *RenderPassDescriptor) RenderPassEncoder
// BeginComputePass begins a compute pass.
// Returns a compute pass encoder for recording dispatch commands.
BeginComputePass(desc *ComputePassDescriptor) ComputePassEncoder
}
CommandEncoder records GPU commands. Command encoders are single-use - after EndEncoding, they cannot be reused.
type CommandEncoderDescriptor ¶
type CommandEncoderDescriptor struct {
// Label is an optional debug name.
Label string
}
CommandEncoderDescriptor describes a command encoder.
type CompositeAlphaMode ¶
type CompositeAlphaMode uint8
CompositeAlphaMode controls how surface alpha is composited.
const ( // CompositeAlphaModeOpaque treats the surface as opaque. CompositeAlphaModeOpaque CompositeAlphaMode = iota // CompositeAlphaModePremultiplied uses premultiplied alpha. CompositeAlphaModePremultiplied // CompositeAlphaModePostmultiplied uses postmultiplied alpha. CompositeAlphaModePostmultiplied // CompositeAlphaModeInherit inherits alpha mode from the system. CompositeAlphaModeInherit )
type ComputePassDescriptor ¶
type ComputePassDescriptor struct {
// Label is an optional debug name.
Label string
// TimestampWrites are timestamp queries (optional).
TimestampWrites *ComputePassTimestampWrites
}
ComputePassDescriptor describes a compute pass.
type ComputePassEncoder ¶
type ComputePassEncoder interface {
// End finishes the compute pass.
// After this call, the encoder cannot be used again.
End()
// SetPipeline sets the active compute pipeline.
SetPipeline(pipeline ComputePipeline)
// SetBindGroup sets a bind group for the given index.
// offsets are dynamic offsets for dynamic uniform/storage buffers.
SetBindGroup(index uint32, group BindGroup, offsets []uint32)
// Dispatch dispatches compute work.
// x, y, z are the number of workgroups to dispatch in each dimension.
Dispatch(x, y, z uint32)
// DispatchIndirect dispatches compute work with GPU-generated parameters.
// buffer contains DispatchIndirectArgs at the given offset.
DispatchIndirect(buffer Buffer, offset uint64)
}
ComputePassEncoder records compute commands within a compute pass.
type ComputePassTimestampWrites ¶
type ComputePassTimestampWrites struct {
// QuerySet is the query set to write to.
QuerySet QuerySet
// BeginningOfPassWriteIndex is the query index for pass start.
// Use nil to skip.
BeginningOfPassWriteIndex *uint32
// EndOfPassWriteIndex is the query index for pass end.
// Use nil to skip.
EndOfPassWriteIndex *uint32
}
ComputePassTimestampWrites describes timestamp query writes.
type ComputePipeline ¶
type ComputePipeline interface {
Resource
}
ComputePipeline is a configured compute pipeline. Compute pipelines define the compute shader and resource layout.
type ComputePipelineDescriptor ¶
type ComputePipelineDescriptor struct {
// Label is an optional debug name.
Label string
// Layout is the pipeline layout.
Layout PipelineLayout
// Compute is the compute shader stage.
Compute ComputeState
}
ComputePipelineDescriptor describes a compute pipeline.
type ComputeState ¶
type ComputeState struct {
// Module is the shader module.
Module ShaderModule
// EntryPoint is the shader entry point function name.
EntryPoint string
}
ComputeState describes the compute shader stage.
type DepthStencilState ¶
type DepthStencilState struct {
// Format is the depth/stencil texture format.
Format types.TextureFormat
// DepthWriteEnabled enables depth writes.
DepthWriteEnabled bool
// DepthCompare is the depth comparison function.
DepthCompare types.CompareFunction
// StencilFront is the stencil state for front faces.
StencilFront StencilFaceState
// StencilBack is the stencil state for back faces.
StencilBack StencilFaceState
// StencilReadMask is the stencil read mask.
StencilReadMask uint32
// StencilWriteMask is the stencil write mask.
StencilWriteMask uint32
// DepthBias is the constant depth bias.
DepthBias int32
// DepthBiasSlopeScale is the slope-scaled depth bias.
DepthBiasSlopeScale float32
// DepthBiasClamp is the maximum depth bias.
DepthBiasClamp float32
}
DepthStencilState describes depth and stencil testing.
type Device ¶
type Device interface {
// CreateBuffer creates a GPU buffer.
CreateBuffer(desc *BufferDescriptor) (Buffer, error)
// DestroyBuffer destroys a GPU buffer.
DestroyBuffer(buffer Buffer)
// CreateTexture creates a GPU texture.
CreateTexture(desc *TextureDescriptor) (Texture, error)
// DestroyTexture destroys a GPU texture.
DestroyTexture(texture Texture)
// CreateTextureView creates a view into a texture.
CreateTextureView(texture Texture, desc *TextureViewDescriptor) (TextureView, error)
// DestroyTextureView destroys a texture view.
DestroyTextureView(view TextureView)
// CreateSampler creates a texture sampler.
CreateSampler(desc *SamplerDescriptor) (Sampler, error)
// DestroySampler destroys a sampler.
DestroySampler(sampler Sampler)
// CreateBindGroupLayout creates a bind group layout.
CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) (BindGroupLayout, error)
// DestroyBindGroupLayout destroys a bind group layout.
DestroyBindGroupLayout(layout BindGroupLayout)
// CreateBindGroup creates a bind group.
CreateBindGroup(desc *BindGroupDescriptor) (BindGroup, error)
// DestroyBindGroup destroys a bind group.
DestroyBindGroup(group BindGroup)
// CreatePipelineLayout creates a pipeline layout.
CreatePipelineLayout(desc *PipelineLayoutDescriptor) (PipelineLayout, error)
// DestroyPipelineLayout destroys a pipeline layout.
DestroyPipelineLayout(layout PipelineLayout)
// CreateShaderModule creates a shader module.
CreateShaderModule(desc *ShaderModuleDescriptor) (ShaderModule, error)
// DestroyShaderModule destroys a shader module.
DestroyShaderModule(module ShaderModule)
// CreateRenderPipeline creates a render pipeline.
CreateRenderPipeline(desc *RenderPipelineDescriptor) (RenderPipeline, error)
// DestroyRenderPipeline destroys a render pipeline.
DestroyRenderPipeline(pipeline RenderPipeline)
// CreateComputePipeline creates a compute pipeline.
CreateComputePipeline(desc *ComputePipelineDescriptor) (ComputePipeline, error)
// DestroyComputePipeline destroys a compute pipeline.
DestroyComputePipeline(pipeline ComputePipeline)
// CreateCommandEncoder creates a command encoder.
CreateCommandEncoder(desc *CommandEncoderDescriptor) (CommandEncoder, error)
// CreateFence creates a synchronization fence.
CreateFence() (Fence, error)
// DestroyFence destroys a fence.
DestroyFence(fence Fence)
// Wait waits for a fence to reach the specified value.
// Returns true if the fence reached the value, false if timeout.
// Returns ErrDeviceLost if the device is lost.
Wait(fence Fence, value uint64, timeout time.Duration) (bool, error)
// Destroy releases the device.
// All resources created from this device must be destroyed first.
Destroy()
}
Device represents a logical GPU device. Devices are used to create resources and command encoders.
type DownlevelCapabilities ¶
type DownlevelCapabilities struct {
// ShaderModel is the supported shader model (5.0, 5.1, 6.0, etc.).
ShaderModel uint32
// Flags are downlevel-specific capability flags.
Flags DownlevelFlags
}
DownlevelCapabilities describes capabilities for downlevel backends (GL/GLES).
type DownlevelFlags ¶
type DownlevelFlags uint32
DownlevelFlags are capability flags for downlevel backends.
const ( // DownlevelFlagsComputeShaders indicates compute shader support. DownlevelFlagsComputeShaders DownlevelFlags = 1 << iota // DownlevelFlagsFragmentWritableStorage indicates fragment shader writable storage support. DownlevelFlagsFragmentWritableStorage // DownlevelFlagsIndirectFirstInstance indicates DrawIndirect with firstInstance support. DownlevelFlagsIndirectFirstInstance // DownlevelFlagsBaseVertexBaseInstance indicates baseVertex/baseInstance support. DownlevelFlagsBaseVertexBaseInstance // DownlevelFlagsReadOnlyDepthStencil indicates read-only depth/stencil support. DownlevelFlagsReadOnlyDepthStencil // DownlevelFlagsAnisotropicFiltering indicates anisotropic filtering support. DownlevelFlagsAnisotropicFiltering )
type ExposedAdapter ¶
type ExposedAdapter struct {
// Adapter is the physical GPU.
Adapter Adapter
// Info contains adapter metadata (name, vendor, device type).
Info types.AdapterInfo
// Features are the supported optional features.
Features types.Features
// Capabilities contains detailed capability information.
Capabilities Capabilities
}
ExposedAdapter bundles an adapter with its capabilities. This is returned by Instance.EnumerateAdapters.
type Fence ¶
type Fence interface {
Resource
}
Fence is a GPU synchronization primitive. Fences allow CPU-GPU synchronization via signaled values.
type FragmentState ¶
type FragmentState struct {
// Module is the shader module.
Module ShaderModule
// EntryPoint is the shader entry point function name.
EntryPoint string
// Targets describe the render target formats and blend state.
Targets []types.ColorTargetState
}
FragmentState describes the fragment shader stage.
type ImageCopyTexture ¶
type ImageCopyTexture struct {
// Texture is the texture to copy to/from.
Texture Texture
// MipLevel is the mip level to copy.
MipLevel uint32
// Origin is the starting point of the copy.
Origin Origin3D
// Aspect specifies which aspect to copy (color, depth, stencil).
Aspect types.TextureAspect
}
ImageCopyTexture specifies a texture location for copying.
type ImageDataLayout ¶
type ImageDataLayout struct {
// Offset is the offset in bytes from the start of the buffer.
Offset uint64
// BytesPerRow is the stride in bytes between rows of the image.
// Must be a multiple of 256 for texture copies.
// Can be 0 for single-row images.
BytesPerRow uint32
// RowsPerImage is the number of rows per image slice.
// Only needed for 3D textures.
// Can be 0 to use the image height.
RowsPerImage uint32
}
ImageDataLayout describes the layout of image data in a buffer.
type Instance ¶
type Instance interface {
// CreateSurface creates a rendering surface from platform handles.
// displayHandle is platform-specific (HDC on Windows, NSWindow* on macOS, etc.).
// windowHandle is the window handle (HWND on Windows, NSView* on macOS, etc.).
CreateSurface(displayHandle, windowHandle uintptr) (Surface, error)
// EnumerateAdapters enumerates available physical GPUs.
// surfaceHint is optional - if provided, only adapters compatible with
// the surface are returned.
EnumerateAdapters(surfaceHint Surface) []ExposedAdapter
// Destroy releases the instance.
// All adapters and surfaces created from this instance must be destroyed first.
Destroy()
}
Instance is the entry point for GPU operations. An instance manages adapter enumeration and surface creation.
type InstanceDescriptor ¶
type InstanceDescriptor struct {
// Backends specifies which backends to enable.
Backends types.Backends
// Flags controls instance behavior (debug, validation, etc.).
Flags types.InstanceFlags
// Dx12ShaderCompiler specifies the DX12 shader compiler (FXC or DXC).
Dx12ShaderCompiler types.Dx12ShaderCompiler
// GlBackend specifies the OpenGL backend flavor (GL or GLES).
GlBackend types.GlBackend
}
InstanceDescriptor describes how to create a GPU instance.
type OpenDevice ¶
type OpenDevice struct {
// Device is the logical GPU device.
Device Device
// Queue is the device's command queue.
Queue Queue
}
OpenDevice is returned when Adapter.Open succeeds. It bundles the device and queue together since they're created atomically.
type PipelineLayout ¶
type PipelineLayout interface {
Resource
}
PipelineLayout defines the layout of a pipeline. Pipeline layouts specify the bind group layouts used by a pipeline.
type PipelineLayoutDescriptor ¶
type PipelineLayoutDescriptor struct {
// Label is an optional debug name.
Label string
// BindGroupLayouts are the bind group layouts used by the pipeline.
BindGroupLayouts []BindGroupLayout
// PushConstantRanges define push constant ranges (Vulkan-specific).
PushConstantRanges []PushConstantRange
}
PipelineLayoutDescriptor describes a pipeline layout.
type PresentMode ¶
type PresentMode uint8
PresentMode controls how frames are presented to the surface.
const ( // PresentModeImmediate presents frames immediately (may tear). PresentModeImmediate PresentMode = iota // PresentModeMailbox replaces pending frames (low latency, no tearing). PresentModeMailbox // PresentModeFifo waits for vsync (no tearing, higher latency). PresentModeFifo // PresentModeFifoRelaxed is like Fifo but tears on late frames. PresentModeFifoRelaxed )
type PushConstantRange ¶
type PushConstantRange struct {
// Stages are the shader stages that can access this range.
Stages types.ShaderStages
// Range is the byte range of the push constants.
Range Range
}
PushConstantRange defines a push constant range.
type Queue ¶
type Queue interface {
// Submit submits command buffers to the GPU.
// If fence is not nil, it will be signaled with fenceValue when commands complete.
Submit(commandBuffers []CommandBuffer, fence Fence, fenceValue uint64) error
// WriteBuffer writes data to a buffer immediately.
// This is a convenience method that creates a staging buffer internally.
WriteBuffer(buffer Buffer, offset uint64, data []byte)
// WriteTexture writes data to a texture immediately.
// This is a convenience method that creates a staging buffer internally.
WriteTexture(dst *ImageCopyTexture, data []byte, layout *ImageDataLayout, size *Extent3D)
// Present presents a surface texture to the screen.
// The texture must have been acquired via Surface.AcquireTexture.
// After this call, the texture is consumed and must not be used.
Present(surface Surface, texture SurfaceTexture) error
// GetTimestampPeriod returns the timestamp period in nanoseconds.
// Used to convert timestamp query results to real time.
GetTimestampPeriod() float32
}
Queue handles command submission and presentation. Queues are typically thread-safe (backend-specific).
type RenderBundle ¶
type RenderBundle interface {
Resource
}
RenderBundle is a pre-recorded set of render commands. Bundles can be executed multiple times for better performance.
type RenderPassColorAttachment ¶
type RenderPassColorAttachment struct {
// View is the texture view to render to.
View TextureView
// ResolveTarget is the MSAA resolve target (optional).
ResolveTarget TextureView
// LoadOp specifies what to do at pass start.
LoadOp types.LoadOp
// StoreOp specifies what to do at pass end.
StoreOp types.StoreOp
// ClearValue is the clear color (used if LoadOp is Clear).
ClearValue types.Color
}
RenderPassColorAttachment describes a color attachment.
type RenderPassDepthStencilAttachment ¶
type RenderPassDepthStencilAttachment struct {
// View is the texture view to use.
View TextureView
// DepthLoadOp specifies what to do with depth at pass start.
DepthLoadOp types.LoadOp
// DepthStoreOp specifies what to do with depth at pass end.
DepthStoreOp types.StoreOp
// DepthClearValue is the depth clear value (used if DepthLoadOp is Clear).
DepthClearValue float32
// DepthReadOnly makes the depth aspect read-only.
DepthReadOnly bool
// StencilLoadOp specifies what to do with stencil at pass start.
StencilLoadOp types.LoadOp
// StencilStoreOp specifies what to do with stencil at pass end.
StencilStoreOp types.StoreOp
// StencilClearValue is the stencil clear value (used if StencilLoadOp is Clear).
StencilClearValue uint32
// StencilReadOnly makes the stencil aspect read-only.
StencilReadOnly bool
}
RenderPassDepthStencilAttachment describes a depth/stencil attachment.
type RenderPassDescriptor ¶
type RenderPassDescriptor struct {
// Label is an optional debug name.
Label string
// ColorAttachments are the color render targets.
ColorAttachments []RenderPassColorAttachment
// DepthStencilAttachment is the depth/stencil target (optional).
DepthStencilAttachment *RenderPassDepthStencilAttachment
// TimestampWrites are timestamp queries (optional).
TimestampWrites *RenderPassTimestampWrites
}
RenderPassDescriptor describes a render pass.
type RenderPassEncoder ¶
type RenderPassEncoder interface {
// End finishes the render pass.
// After this call, the encoder cannot be used again.
End()
// SetPipeline sets the active render pipeline.
SetPipeline(pipeline RenderPipeline)
// SetBindGroup sets a bind group for the given index.
// offsets are dynamic offsets for dynamic uniform/storage buffers.
SetBindGroup(index uint32, group BindGroup, offsets []uint32)
// SetVertexBuffer sets a vertex buffer for the given slot.
SetVertexBuffer(slot uint32, buffer Buffer, offset uint64)
// SetIndexBuffer sets the index buffer.
SetIndexBuffer(buffer Buffer, format types.IndexFormat, offset uint64)
// SetViewport sets the viewport transformation.
SetViewport(x, y, width, height, minDepth, maxDepth float32)
// SetScissorRect sets the scissor rectangle for clipping.
SetScissorRect(x, y, width, height uint32)
// SetBlendConstant sets the blend constant color.
SetBlendConstant(color *types.Color)
// SetStencilReference sets the stencil reference value.
SetStencilReference(reference uint32)
// Draw draws primitives.
// vertexCount is the number of vertices to draw.
// instanceCount is the number of instances to draw.
// firstVertex is the offset into the vertex buffer.
// firstInstance is the offset into the instance data.
Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
// DrawIndexed draws indexed primitives.
// indexCount is the number of indices to draw.
// instanceCount is the number of instances to draw.
// firstIndex is the offset into the index buffer.
// baseVertex is added to each index before fetching vertex data.
// firstInstance is the offset into the instance data.
DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
// DrawIndirect draws primitives with GPU-generated parameters.
// buffer contains DrawIndirectArgs at the given offset.
DrawIndirect(buffer Buffer, offset uint64)
// DrawIndexedIndirect draws indexed primitives with GPU-generated parameters.
// buffer contains DrawIndexedIndirectArgs at the given offset.
DrawIndexedIndirect(buffer Buffer, offset uint64)
// ExecuteBundle executes a pre-recorded render bundle.
// Bundles are an optimization for repeated draw calls.
ExecuteBundle(bundle RenderBundle)
}
RenderPassEncoder records render commands within a render pass. Render passes define rendering targets and operations.
type RenderPassTimestampWrites ¶
type RenderPassTimestampWrites struct {
// QuerySet is the query set to write to.
QuerySet QuerySet
// BeginningOfPassWriteIndex is the query index for pass start.
// Use nil to skip.
BeginningOfPassWriteIndex *uint32
// EndOfPassWriteIndex is the query index for pass end.
// Use nil to skip.
EndOfPassWriteIndex *uint32
}
RenderPassTimestampWrites describes timestamp query writes.
type RenderPipeline ¶
type RenderPipeline interface {
Resource
}
RenderPipeline is a configured render pipeline. Render pipelines define the complete graphics pipeline state.
type RenderPipelineDescriptor ¶
type RenderPipelineDescriptor struct {
// Label is an optional debug name.
Label string
// Layout is the pipeline layout.
Layout PipelineLayout
// Vertex is the vertex stage.
Vertex VertexState
// Primitive is the primitive assembly state.
Primitive types.PrimitiveState
// DepthStencil is the depth/stencil state (optional).
DepthStencil *DepthStencilState
// Multisample is the multisample state.
Multisample types.MultisampleState
// Fragment is the fragment stage (optional for depth-only passes).
Fragment *FragmentState
}
RenderPipelineDescriptor describes a render pipeline.
type Resource ¶
type Resource interface {
// Destroy releases the GPU resource.
// After this call, the resource must not be used.
// Calling Destroy multiple times is undefined behavior.
Destroy()
}
Resource is the base interface for all GPU resources. Resources must be explicitly destroyed to free GPU memory.
type Sampler ¶
type Sampler interface {
Resource
}
Sampler represents a texture sampler. Samplers define how textures are filtered and addressed.
type SamplerDescriptor ¶
type SamplerDescriptor struct {
// Label is an optional debug name.
Label string
// AddressModeU is the addressing mode for U coordinates.
AddressModeU types.AddressMode
// AddressModeV is the addressing mode for V coordinates.
AddressModeV types.AddressMode
// AddressModeW is the addressing mode for W coordinates.
AddressModeW types.AddressMode
// MagFilter is the magnification filter.
MagFilter types.FilterMode
// MinFilter is the minification filter.
MinFilter types.FilterMode
// MipmapFilter is the mipmap filter.
MipmapFilter types.FilterMode
// LodMinClamp is the minimum LOD clamp.
LodMinClamp float32
// LodMaxClamp is the maximum LOD clamp.
LodMaxClamp float32
// Compare is the comparison function for depth textures.
Compare types.CompareFunction
// Anisotropy is the anisotropic filtering level (1-16, 1 is off).
Anisotropy uint16
}
SamplerDescriptor describes how to create a sampler.
type ShaderModule ¶
type ShaderModule interface {
Resource
}
ShaderModule represents a compiled shader module. Shader modules contain executable GPU code in a backend-specific format.
type ShaderModuleDescriptor ¶
type ShaderModuleDescriptor struct {
// Label is an optional debug name.
Label string
// Source is the shader source code.
// Can be WGSL source code or SPIR-V bytecode.
Source ShaderSource
}
ShaderModuleDescriptor describes a shader module.
type ShaderSource ¶
type ShaderSource struct {
// WGSL is the WGSL source code (if present).
WGSL string
// SPIRV is the SPIR-V bytecode (if present).
SPIRV []uint32
}
ShaderSource represents shader source code or bytecode.
type StencilFaceState ¶
type StencilFaceState struct {
// Compare is the stencil comparison function.
Compare types.CompareFunction
// FailOp is the operation when stencil test fails.
FailOp StencilOperation
// DepthFailOp is the operation when depth test fails.
DepthFailOp StencilOperation
// PassOp is the operation when both tests pass.
PassOp StencilOperation
}
StencilFaceState describes stencil operations for a face.
type StencilOperation ¶
type StencilOperation uint8
StencilOperation describes a stencil operation.
const ( // StencilOperationKeep keeps the current value. StencilOperationKeep StencilOperation = iota // StencilOperationZero sets the value to zero. StencilOperationZero // StencilOperationReplace replaces with the reference value. StencilOperationReplace // StencilOperationInvert inverts the bits. StencilOperationInvert // StencilOperationIncrementClamp increments and clamps. StencilOperationIncrementClamp // StencilOperationDecrementClamp decrements and clamps. StencilOperationDecrementClamp // StencilOperationIncrementWrap increments and wraps. StencilOperationIncrementWrap // StencilOperationDecrementWrap decrements and wraps. StencilOperationDecrementWrap )
type Surface ¶
type Surface interface {
Resource
// Configure configures the surface with the given device and settings.
// Must be called before acquiring textures.
Configure(device Device, config *SurfaceConfiguration) error
// Unconfigure removes the surface configuration.
// Call before destroying the device.
Unconfigure(device Device)
// AcquireTexture acquires the next surface texture for rendering.
// The texture must be presented via Queue.Present or discarded via DiscardTexture.
// Returns ErrSurfaceOutdated if the surface needs reconfiguration.
// Returns ErrSurfaceLost if the surface has been destroyed.
// Returns ErrTimeout if the timeout expires before a texture is available.
AcquireTexture(fence Fence) (*AcquiredSurfaceTexture, error)
// DiscardTexture discards a surface texture without presenting it.
// Use this if rendering failed or was canceled.
DiscardTexture(texture SurfaceTexture)
}
Surface represents a rendering surface. Surfaces are platform-specific presentation targets (windows).
type SurfaceCapabilities ¶
type SurfaceCapabilities struct {
// Formats are the supported surface texture formats.
Formats []types.TextureFormat
// PresentModes are the supported presentation modes.
PresentModes []PresentMode
// AlphaModes are the supported alpha modes.
AlphaModes []CompositeAlphaMode
}
SurfaceCapabilities describes surface capabilities.
type SurfaceConfiguration ¶
type SurfaceConfiguration struct {
// Width of the surface in pixels.
Width uint32
// Height of the surface in pixels.
Height uint32
// Format is the texture format for surface textures.
Format types.TextureFormat
// Usage specifies how surface textures will be used.
Usage types.TextureUsage
// PresentMode controls presentation timing.
PresentMode PresentMode
// AlphaMode controls alpha compositing.
AlphaMode CompositeAlphaMode
}
SurfaceConfiguration describes surface settings.
type SurfaceTexture ¶
type SurfaceTexture interface {
Texture
}
SurfaceTexture is a texture acquired from a surface. Surface textures have special lifetime constraints - they must be presented or discarded before the next frame.
type Texture ¶
type Texture interface {
Resource
}
Texture represents a GPU texture. Textures are multi-dimensional images with specific formats.
type TextureBarrier ¶
type TextureBarrier struct {
Texture Texture
Range TextureRange
Usage TextureUsageTransition
}
TextureBarrier defines a texture state transition.
type TextureCopy ¶
type TextureCopy struct {
SrcBase ImageCopyTexture
DstBase ImageCopyTexture
Size Extent3D
}
TextureCopy defines a texture-to-texture copy region.
type TextureDescriptor ¶
type TextureDescriptor struct {
// Label is an optional debug name.
Label string
// Size is the texture dimensions.
Size Extent3D
// MipLevelCount is the number of mip levels (1+ required).
MipLevelCount uint32
// SampleCount is the number of samples per pixel (1 for non-MSAA).
SampleCount uint32
// Dimension is the texture dimension (1D, 2D, 3D).
Dimension types.TextureDimension
// Format is the texture pixel format.
Format types.TextureFormat
// Usage specifies how the texture will be used.
Usage types.TextureUsage
// ViewFormats are additional formats for texture views.
// Required for creating views with different (but compatible) formats.
ViewFormats []types.TextureFormat
}
TextureDescriptor describes how to create a texture.
type TextureFormatCapabilities ¶
type TextureFormatCapabilities struct {
// Flags indicate what operations are supported for this format.
Flags TextureFormatCapabilityFlags
}
TextureFormatCapabilities describes texture format capabilities.
type TextureFormatCapabilityFlags ¶
type TextureFormatCapabilityFlags uint32
TextureFormatCapabilityFlags are capability flags for texture formats.
const ( // TextureFormatCapabilitySampled indicates the format can be sampled in shaders. TextureFormatCapabilitySampled TextureFormatCapabilityFlags = 1 << iota // TextureFormatCapabilityStorage indicates the format can be used for storage textures. TextureFormatCapabilityStorage // TextureFormatCapabilityStorageReadWrite indicates read-write storage support. TextureFormatCapabilityStorageReadWrite // TextureFormatCapabilityRenderAttachment indicates render target support. TextureFormatCapabilityRenderAttachment // TextureFormatCapabilityBlendable indicates blending support as render target. TextureFormatCapabilityBlendable // TextureFormatCapabilityMultisample indicates multisampling support. TextureFormatCapabilityMultisample // TextureFormatCapabilityMultisampleResolve indicates multisample resolve support. TextureFormatCapabilityMultisampleResolve )
type TextureRange ¶
type TextureRange struct {
// Aspect specifies which aspect of the texture (color, depth, stencil).
Aspect types.TextureAspect
// BaseMipLevel is the first mip level in the range.
BaseMipLevel uint32
// MipLevelCount is the number of mip levels (0 means all remaining levels).
MipLevelCount uint32
// BaseArrayLayer is the first array layer in the range.
BaseArrayLayer uint32
// ArrayLayerCount is the number of array layers (0 means all remaining layers).
ArrayLayerCount uint32
}
TextureRange specifies a range of texture subresources.
type TextureUsageTransition ¶
type TextureUsageTransition struct {
OldUsage types.TextureUsage
NewUsage types.TextureUsage
}
TextureUsageTransition defines a texture usage state transition.
type TextureView ¶
type TextureView interface {
Resource
}
TextureView represents a view into a texture. Views specify how a texture is interpreted (format, dimensions, layers).
type TextureViewDescriptor ¶
type TextureViewDescriptor struct {
// Label is an optional debug name.
Label string
// Format is the view format (can differ from texture format if compatible).
// Use TextureFormatUndefined to inherit from the texture.
Format types.TextureFormat
// Dimension is the view dimension (can differ from texture dimension).
// Use TextureViewDimensionUndefined to inherit from the texture.
Dimension types.TextureViewDimension
// Aspect specifies which aspect to view (color, depth, stencil).
Aspect types.TextureAspect
// BaseMipLevel is the first mip level in the view.
BaseMipLevel uint32
// MipLevelCount is the number of mip levels (0 means all remaining levels).
MipLevelCount uint32
// BaseArrayLayer is the first array layer in the view.
BaseArrayLayer uint32
// ArrayLayerCount is the number of array layers (0 means all remaining layers).
ArrayLayerCount uint32
}
TextureViewDescriptor describes how to create a texture view.
type VertexState ¶
type VertexState struct {
// Module is the shader module.
Module ShaderModule
// EntryPoint is the shader entry point function name.
EntryPoint string
// Buffers describe the vertex buffer layouts.
Buffers []types.VertexBufferLayout
}
VertexState describes the vertex shader stage.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package dx12 provides a DirectX 12 backend for the HAL.
|
Package dx12 provides a DirectX 12 backend for the HAL. |
|
Package gles implements the HAL backend for OpenGL ES 3.0 / OpenGL 3.3+.
|
Package gles implements the HAL backend for OpenGL ES 3.0 / OpenGL 3.3+. |
|
egl
Package egl provides EGL (EGL) context management for OpenGL ES on Linux.
|
Package egl provides EGL (EGL) context management for OpenGL ES on Linux. |
|
gl
Package gl provides OpenGL constants and types for the GLES backend.
|
Package gl provides OpenGL constants and types for the GLES backend. |
|
wgl
Package wgl provides Windows OpenGL (WGL) context management.
|
Package wgl provides Windows OpenGL (WGL) context management. |
|
Package metal provides a Metal backend for the HAL.
|
Package metal provides a Metal backend for the HAL. |
|
Package noop provides a no-operation GPU backend.
|
Package noop provides a no-operation GPU backend. |
|
Package vulkan provides Pure Go Vulkan backend for the HAL.
|
Package vulkan provides Pure Go Vulkan backend for the HAL. |
|
memory
Package memory provides GPU memory allocation for Vulkan backend.
|
Package memory provides GPU memory allocation for Vulkan backend. |