wgpu

package module
v0.26.4 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2026 License: MIT Imports: 15 Imported by: 4

README

wgpu

Pure Go WebGPU Implementation
No Rust. No CGO. Just Go.

CI codecov Go Reference Go Report Card License Latest Release Go Version Zero CGO

Part of the GoGPU ecosystem


Overview

wgpu is a complete WebGPU implementation written entirely in Go. It provides direct GPU access through multiple hardware abstraction layer (HAL) backends without requiring Rust, CGO, or any external dependencies.

Key Features

Category Capabilities
Backends Vulkan, Metal, DirectX 12, OpenGL ES, Software
Platforms Windows, Linux, macOS, iOS, Browser (WASM — in progress)
API WebGPU-compliant (W3C specification)
Shaders WGSL via gogpu/naga compiler (SPIR-V, HLSL, MSL, GLSL, DXIL)
Compute Full compute shader support, GPU→CPU readback
Present Damage-aware presentation — compositor dirty rects (first WebGPU implementation)
Debug Leak detection, error scopes, validation layers, DRED diagnostics (DX12), structured logging (log/slog)
Build Zero CGO, simple go build

Installation

go get github.com/gogpu/wgpu

Requirements: Go 1.25+

Build:

CGO_ENABLED=0 go build

Note: wgpu uses Pure Go FFI via cgo_import_dynamic, which requires CGO_ENABLED=0. This enables zero C compiler dependency and easy cross-compilation.


Quick Start

package main

import (
    "fmt"

    "github.com/gogpu/wgpu"
    _ "github.com/gogpu/wgpu/hal/allbackends" // Auto-register platform backends
)

func main() {
    // Create instance
    instance, _ := wgpu.CreateInstance(nil)
    defer instance.Release()

    // Request high-performance GPU
    adapter, _ := instance.RequestAdapter(&wgpu.RequestAdapterOptions{
        PowerPreference: wgpu.PowerPreferenceHighPerformance,
    })
    defer adapter.Release()

    // Get adapter info
    info := adapter.Info()
    fmt.Printf("GPU: %s (%s)\n", info.Name, info.Backend)

    // Create device
    device, _ := adapter.RequestDevice(nil)
    defer device.Release()

    // Create a GPU buffer
    buffer, _ := device.CreateBuffer(&wgpu.BufferDescriptor{
        Label: "My Buffer",
        Size:  1024,
        Usage: wgpu.BufferUsageStorage | wgpu.BufferUsageCopyDst,
    })
    defer buffer.Release()

    // Write data to buffer
    if err := device.Queue().WriteBuffer(buffer, 0, []byte{1, 2, 3, 4}); err != nil {
        panic(err)
    }
}

Compute Shaders

// Create shader module from WGSL
shader, _ := device.CreateShaderModule(&wgpu.ShaderModuleDescriptor{
    Label: "Compute Shader",
    WGSL:  wgslSource,
})
defer shader.Release()

// Create compute pipeline
pipeline, _ := device.CreateComputePipeline(&wgpu.ComputePipelineDescriptor{
    Label:      "Compute Pipeline",
    Layout:     pipelineLayout,
    Module:     shader,
    EntryPoint: "main",
})
defer pipeline.Release()

// Record and submit commands
encoder, _ := device.CreateCommandEncoder(nil)
pass, _ := encoder.BeginComputePass(nil)
pass.SetPipeline(pipeline)
pass.SetBindGroup(0, bindGroup, nil)
pass.Dispatch(64, 1, 1)
pass.End()

cmdBuffer, _ := encoder.Finish()
_, _ = device.Queue().Submit(cmdBuffer)  // returns (submissionIndex, error)

Buffer Mapping (GPU → CPU readback)

WebGPU-spec-compliant dual-layer API. Primary path is blocking + context.Context (idiomatic Go, zero allocation); escape hatch MapAsync + Device.Poll is for game loops that cannot afford to block.

// Primary: blocking, idiomatic, zero-alloc.
// Map blocks until the GPU finishes writing the buffer (or ctx cancels).
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := stagingBuf.Map(ctx, wgpu.MapModeRead, 0, size); err != nil {
    log.Fatal(err)
}
defer stagingBuf.Unmap()

rng, _ := stagingBuf.MappedRange(0, size)
data := rng.Bytes()  // []byte view, zero copy, valid until Unmap
process(data)
// Escape hatch: async, non-blocking, for render loops.
pending, _ := stagingBuf.MapAsync(wgpu.MapModeRead, 0, size)

// Continue rendering; auto-polled on next Queue.Submit.
renderFrame()

if ready, _ := pending.Status(); ready {
    rng, _ := stagingBuf.MappedRange(0, size)
    process(rng.Bytes())
    stagingBuf.Unmap()
}

Safety guarantees: UAF protection via generation counters on MappedRange, ErrBufferDestroyed on destroy-during-pending, ErrMapCancelled on unmap-during-pending, ErrMapRangeOverlap for overlapping MappedRange calls, MAP_ALIGNMENT = 8 validation, thread-safe concurrent Device.Poll.

See ADR-BUFFER-MAPPING-API for the full design rationale and comparison with Rust wgpu.

Guides: Getting Started | Backend Differences

Features: WGSL compute shaders, storage/uniform buffers, indirect dispatch, GPU timestamp queries (Vulkan), WebGPU-compliant Buffer.Map / MapAsync GPU→CPU readback with context.Context integration.


Architecture

wgpu/
├── *.go                # Public API (import "github.com/gogpu/wgpu")
├── core/               # Validation, state tracking, deferred resource destruction
├── hal/                # Hardware Abstraction Layer
│   ├── allbackends/    # Platform-specific backend auto-registration
│   ├── noop/           # No-op backend (testing)
│   ├── software/       # CPU software rasterizer (~14K LOC)
│   ├── gles/           # OpenGL ES 3.0+ (~12K LOC)
│   ├── vulkan/         # Vulkan 1.3 (~42K LOC)
│   ├── metal/          # Metal (~7K LOC)
│   └── dx12/           # DirectX 12 (~17K LOC)
├── examples/
│   ├── compute-copy/   # GPU buffer copy with compute shader
│   └── compute-sum/    # Parallel reduction on GPU
└── cmd/
    ├── vk-gen/         # Vulkan bindings generator
    └── ...             # Backend integration tests

Public API

The root package (import "github.com/gogpu/wgpu") provides a safe, ergonomic API aligned with the W3C WebGPU specification. It wraps core/ and hal/ into user-friendly types:

User Application
  ↓ import "github.com/gogpu/wgpu"
Root Package (public API)
  ↓ wraps
core/ (validation) + hal/ (backend interfaces)
  ↓
vulkan/ | metal/ | dx12/ | gles/ | software/

HAL Backend Integration

Backends auto-register via blank imports:

import _ "github.com/gogpu/wgpu/hal/allbackends"

// Platform-specific backends auto-registered:
// - Windows: Vulkan, DX12, GLES, Software
// - Linux:   Vulkan, GLES, Software
// - macOS:   Metal, Software

Backend Details

Platform Support

Backend Windows Linux macOS iOS Notes
Vulkan Yes Yes Yes - MoltenVK on macOS
Metal - - Yes Yes Native Apple GPU
DX12 Yes - - - Windows 10+
GLES Yes Yes - - OpenGL ES 3.0+
Software Yes Yes Yes Yes CPU fallback

Architectures: amd64, arm64 (including Windows ARM64 / Snapdragon X)

Vulkan Backend

Full Vulkan 1.3 implementation with:

  • Auto-generated bindings from official vk.xml
  • Buddy allocator for GPU memory (O(log n), minimal fragmentation)
  • Dynamic rendering (VK_KHR_dynamic_rendering)
  • Classic render pass fallback for Intel compatibility
  • wgpu-style swapchain synchronization
  • MSAA render pass with automatic resolve
  • Complete resource management (Buffer, Texture, Pipeline, BindGroup)
  • Surface creation: Win32, X11, Wayland, Metal (MoltenVK)
  • Debug messenger for validation layer error capture (VK_EXT_debug_utils)
  • Structured diagnostic logging via log/slog

Metal Backend

Native Apple GPU access via:

  • Pure Go Objective-C bridge (goffi)
  • Metal API via runtime message dispatch
  • CAMetalLayer integration for surface presentation
  • MSL shader compilation via naga

DirectX 12 Backend

Windows GPU access via:

  • Pure Go COM bindings (syscall, no CGO)
  • DXGI integration for swapchain and adapters
  • Flip model with VRR support
  • Descriptor heap management with fence-based deferred destruction
  • Encoder pool with allocator recycling (Rust wgpu-core pattern)
  • In-memory shader cache (SHA-256 keyed, LRU eviction, works for both paths)
  • DRED diagnostics (auto-breadcrumbs + page fault tracking on TDR)
  • Dual shader compilation: HLSL→FXC (default, SM 5.1) or DXIL direct via naga (GOGPU_DX12_DXIL=1, SM 6.0+, zero external dependencies — first Pure Go DXIL generator)
  • StagingBelt ring-buffer allocator for zero-allocation GPU data transfer

OpenGL ES Backend

Cross-platform GPU access via OpenGL ES 3.0+:

  • Pure Go EGL/GL bindings (goffi)
  • Full rendering pipeline: VAO, FBO, MSAA, blend, stencil, depth
  • WGSL shader compilation (WGSL → GLSL via naga)
  • Combined texture-sampler binding via SamplerBindMap (Rust wgpu pattern)
  • Text rendering with proper texture completeness handling
  • CopyTextureToBuffer readback for GPU → CPU data transfer
  • Platform detection: X11, Wayland, Surfaceless (headless CI)
  • Works with Mesa llvmpipe for software-only environments

Software Backend

Full-featured CPU rasterizer for headless and windowed rendering. Always compiled — no build tags or GPU hardware required.

// Software backend auto-registers via init().
// No explicit import needed when using hal/allbackends.
// For standalone usage:
import _ "github.com/gogpu/wgpu/hal/software"

// Use cases:
// - CI/CD testing without GPU
// - Server-side image generation
// - Reference implementation
// - Fallback when GPU unavailable
// - Embedded systems without GPU

Rasterization Features:

  • Edge function triangle rasterization (Pineda algorithm)
  • Perspective-correct interpolation
  • Depth buffer (8 compare functions)
  • Stencil buffer (8 operations)
  • Blending (13 factors, 5 operations)
  • 6-plane frustum clipping (Sutherland-Hodgman)
  • 8x8 tile-based parallel rendering

Windowed Presentation:

  • Windows: DWM-safe CreateDIBSection + BitBlt (SDL3/Qt6 pattern), zero-copy into GDI bitmap
  • Linux X11: XPutImage via goffi (Skia pattern), BGRA = X11 ZPixmap native format
  • macOS: Planned (CGImage + CALayer)

Environment Variables

Variable Values Description
GOGPU_DX12_DXIL 1 Enable DXIL direct compilation on DX12 (experimental). Bypasses HLSL→FXC, generates DXIL bytecode directly from naga IR. SM 6.0+, zero external dependencies. Default: off (uses HLSL→FXC).
GOGPU_DX12_DXIL_OVERRIDE_VS file path Replace vertex shader DXIL with contents of the given file. For debugging only.
GOGPU_DX12_DXIL_OVERRIDE_PS file path Replace pixel shader DXIL with contents of the given file. For debugging only.

Note: Backend selection (GOGPU_GRAPHICS_API) is handled by gogpu (the app framework), not by wgpu directly. See gogpu documentation for GOGPU_GRAPHICS_API=vulkan|dx12|metal|gles|software.


Ecosystem

wgpu is the foundation of the GoGPU ecosystem.

Project Description
gogpu/gogpu GPU framework with windowing and input
gogpu/wgpu Pure Go WebGPU (this repo)
gogpu/naga Shader compiler (WGSL to SPIR-V, HLSL, MSL, GLSL, DXIL)
gogpu/gg 2D graphics library with GPU SDF acceleration
gogpu/ui GUI toolkit: 22+ widgets, 4 themes
gogpu/gputypes Shared WebGPU type definitions
go-webgpu/goffi Pure Go FFI library

Documentation


References


Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

Priority areas:

  • Cross-platform testing
  • Performance benchmarks
  • Documentation improvements
  • Bug reports and fixes

License

MIT License — see LICENSE for details.


wgpu — WebGPU in Pure Go

Documentation

Overview

Package wgpu provides a safe, ergonomic WebGPU API for Go applications.

This package wraps the lower-level hal/ and core/ packages into a user-friendly API aligned with the W3C WebGPU specification.

Quick Start

Import this package and a backend registration package:

import (
    "github.com/gogpu/wgpu"
    _ "github.com/gogpu/wgpu/hal/allbackends"
)

instance, err := wgpu.CreateInstance(nil)
// ...

Resource Lifecycle

All GPU resources must be explicitly released with Release(). Resources are reference-counted internally. Using a released resource panics.

Backend Registration

Backends are registered via blank imports:

_ "github.com/gogpu/wgpu/hal/allbackends"  // all available backends
_ "github.com/gogpu/wgpu/hal/vulkan"        // Vulkan only
_ "github.com/gogpu/wgpu/hal/noop"           // testing

Thread Safety

Instance, Adapter, and Device are safe for concurrent use. Encoders (CommandEncoder, RenderPassEncoder, ComputePassEncoder) are NOT thread-safe.

Index

Constants

View Source
const (
	StencilOperationKeep           = hal.StencilOperationKeep
	StencilOperationZero           = hal.StencilOperationZero
	StencilOperationReplace        = hal.StencilOperationReplace
	StencilOperationInvert         = hal.StencilOperationInvert
	StencilOperationIncrementClamp = hal.StencilOperationIncrementClamp
	StencilOperationDecrementClamp = hal.StencilOperationDecrementClamp
	StencilOperationIncrementWrap  = hal.StencilOperationIncrementWrap
	StencilOperationDecrementWrap  = hal.StencilOperationDecrementWrap
)

Stencil operation constants.

View Source
const (
	ErrorFilterValidation  = core.ErrorFilterValidation
	ErrorFilterOutOfMemory = core.ErrorFilterOutOfMemory
	ErrorFilterInternal    = core.ErrorFilterInternal
)
View Source
const (
	BackendVulkan = gputypes.BackendVulkan
	BackendMetal  = gputypes.BackendMetal
	BackendDX12   = gputypes.BackendDX12
	BackendGL     = gputypes.BackendGL
)

Backend constants

View Source
const (
	BackendsAll     = gputypes.BackendsAll
	BackendsPrimary = gputypes.BackendsPrimary
	BackendsVulkan  = gputypes.BackendsVulkan
	BackendsMetal   = gputypes.BackendsMetal
	BackendsDX12    = gputypes.BackendsDX12
	BackendsGL      = gputypes.BackendsGL
)

Backends masks

View Source
const (
	BufferUsageMapRead      = gputypes.BufferUsageMapRead
	BufferUsageMapWrite     = gputypes.BufferUsageMapWrite
	BufferUsageCopySrc      = gputypes.BufferUsageCopySrc
	BufferUsageCopyDst      = gputypes.BufferUsageCopyDst
	BufferUsageIndex        = gputypes.BufferUsageIndex
	BufferUsageVertex       = gputypes.BufferUsageVertex
	BufferUsageUniform      = gputypes.BufferUsageUniform
	BufferUsageStorage      = gputypes.BufferUsageStorage
	BufferUsageIndirect     = gputypes.BufferUsageIndirect
	BufferUsageQueryResolve = gputypes.BufferUsageQueryResolve
)
View Source
const (
	TextureUsageCopySrc          = gputypes.TextureUsageCopySrc
	TextureUsageCopyDst          = gputypes.TextureUsageCopyDst
	TextureUsageTextureBinding   = gputypes.TextureUsageTextureBinding
	TextureUsageStorageBinding   = gputypes.TextureUsageStorageBinding
	TextureUsageRenderAttachment = gputypes.TextureUsageRenderAttachment
)
View Source
const (
	TextureDimension1D = gputypes.TextureDimension1D
	TextureDimension2D = gputypes.TextureDimension2D
	TextureDimension3D = gputypes.TextureDimension3D
)

Texture dimension constants

View Source
const (
	TextureFormatRGBA8Unorm     = gputypes.TextureFormatRGBA8Unorm
	TextureFormatRGBA8UnormSrgb = gputypes.TextureFormatRGBA8UnormSrgb
	TextureFormatBGRA8Unorm     = gputypes.TextureFormatBGRA8Unorm
	TextureFormatBGRA8UnormSrgb = gputypes.TextureFormatBGRA8UnormSrgb
	TextureFormatDepth24Plus    = gputypes.TextureFormatDepth24Plus
	TextureFormatDepth32Float   = gputypes.TextureFormatDepth32Float
)

Commonly used texture format constants

View Source
const (
	ShaderStageVertex   = gputypes.ShaderStageVertex
	ShaderStageFragment = gputypes.ShaderStageFragment
	ShaderStageCompute  = gputypes.ShaderStageCompute
)
View Source
const (
	PresentModeImmediate   = gputypes.PresentModeImmediate
	PresentModeMailbox     = gputypes.PresentModeMailbox
	PresentModeFifo        = gputypes.PresentModeFifo
	PresentModeFifoRelaxed = gputypes.PresentModeFifoRelaxed
)
View Source
const (
	PowerPreferenceNone            = gputypes.PowerPreferenceNone
	PowerPreferenceLowPower        = gputypes.PowerPreferenceLowPower
	PowerPreferenceHighPerformance = gputypes.PowerPreferenceHighPerformance
)
View Source
const MaxBindGroups = 8

MaxBindGroups is the maximum number of bind groups allowed by the WebGPU spec. This is the hard cap (wgpu-hal MAX_BIND_GROUPS = 8). Actual device limits may be lower (typically 4 in the WebGPU spec).

Variables

View Source
var (
	ErrDeviceLost      = hal.ErrDeviceLost
	ErrOutOfMemory     = hal.ErrDeviceOutOfMemory
	ErrSurfaceLost     = hal.ErrSurfaceLost
	ErrSurfaceOutdated = hal.ErrSurfaceOutdated
	ErrTimeout         = hal.ErrTimeout
)

Sentinel errors re-exported from HAL.

View Source
var (
	// ErrReleased is returned when operating on a released resource.
	ErrReleased = errors.New("wgpu: resource already released")

	// ErrNoAdapters is returned when no GPU adapters are found.
	ErrNoAdapters = errors.New("wgpu: no GPU adapters available")

	// ErrNoBackends is returned when no backends are registered.
	ErrNoBackends = errors.New("wgpu: no backends registered (import a backend package)")
)

Public API sentinel errors.

View Source
var (
	// ErrMapAlreadyPending — a Map or MapAsync was called on a buffer
	// that already has an in-flight map request.
	ErrMapAlreadyPending = errors.New("wgpu: buffer map already pending")

	// ErrMapAlreadyMapped — a Map or MapAsync was called on a buffer
	// that is already in the Mapped state.
	ErrMapAlreadyMapped = errors.New("wgpu: buffer is already mapped")

	// ErrMapNotMapped — Unmap or MappedRange was called on a buffer that
	// is not currently mapped.
	ErrMapNotMapped = errors.New("wgpu: buffer is not mapped")

	// ErrMapRangeOverlap — MappedRange was called with a range that
	// overlaps a previously-returned MappedRange that has not yet been
	// invalidated by Unmap.
	ErrMapRangeOverlap = errors.New("wgpu: mapped range overlaps existing")

	// ErrMapRangeDetached — MappedRange.Bytes was called after the owning
	// buffer was unmapped or destroyed, leaving the range invalid.
	ErrMapRangeDetached = errors.New("wgpu: mapped range detached (buffer unmapped)")

	// ErrMapAlignment — the requested offset is not a multiple of 8
	// bytes, or the requested size is not a multiple of 4 bytes, in
	// violation of WebGPU spec MAP_ALIGNMENT / copy alignment.
	ErrMapAlignment = errors.New("wgpu: map offset/size not aligned")

	// ErrMapCanceled — a pending map was canceled by a concurrent
	// Unmap, Destroy, or context cancellation before the GPU resolved it.
	// Analogous to WebGPU AbortError.
	ErrMapCanceled = errors.New("wgpu: map canceled")

	// ErrBufferDestroyed — Buffer.Destroy was called while the map was
	// pending, or a Map call targeted an already-destroyed buffer.
	ErrBufferDestroyed = errors.New("wgpu: buffer destroyed")

	// ErrMapDeviceLost — the device was lost while the map was pending.
	ErrMapDeviceLost = errors.New("wgpu: device lost during map")

	// ErrMapInvalidMode — Map or MapAsync was called on a buffer that
	// was not created with the matching MAP_READ or MAP_WRITE usage.
	ErrMapInvalidMode = errors.New("wgpu: buffer not created with required MAP_READ/MAP_WRITE usage")

	// ErrMapRangeOverflow — the requested offset + size exceeds the
	// buffer size.
	ErrMapRangeOverflow = errors.New("wgpu: map range exceeds buffer size")
)

Typed buffer mapping errors. Callers can use errors.Is to branch on specific failure modes without matching strings.

View Source
var (
	DefaultLimits             = gputypes.DefaultLimits
	DefaultInstanceDescriptor = gputypes.DefaultInstanceDescriptor
)

Default functions (re-exported for convenience)

Functions

func Logger added in v0.21.0

func Logger() *slog.Logger

Logger returns the current logger used by the wgpu stack.

func SetLogger added in v0.21.0

func SetLogger(l *slog.Logger)

SetLogger configures the logger for the entire wgpu stack (public API, core validation layer, and HAL backends: Vulkan, Metal, DX12, GLES).

By default, wgpu produces no log output. Call SetLogger to enable logging for deep debugging across the full GPU pipeline.

SetLogger is safe for concurrent use. Pass nil to disable logging (restore default silent behavior).

Types

type Adapter

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

Adapter represents a physical GPU.

func (*Adapter) Features

func (a *Adapter) Features() Features

Features returns supported features.

func (*Adapter) GetSurfaceCapabilities added in v0.23.0

func (a *Adapter) GetSurfaceCapabilities(surface *Surface) *SurfaceCapabilities

GetSurfaceCapabilities returns the capabilities of a surface for this adapter. Returns nil if the adapter has no HAL (core-only path) or the surface is nil.

func (*Adapter) Info

func (a *Adapter) Info() AdapterInfo

Info returns adapter metadata.

func (*Adapter) Limits

func (a *Adapter) Limits() Limits

Limits returns the adapter's resource limits.

func (*Adapter) Release

func (a *Adapter) Release()

Release releases the adapter.

func (*Adapter) RequestDevice

func (a *Adapter) RequestDevice(desc *DeviceDescriptor) (*Device, error)

RequestDevice creates a logical device from this adapter. If desc is nil, default features and limits are used.

type AdapterInfo

type AdapterInfo = gputypes.AdapterInfo

Adapter types

type AddressMode

type AddressMode = gputypes.AddressMode

Sampler types

type Backend

type Backend = gputypes.Backend

Backend types

type Backends

type Backends = gputypes.Backends

type BindGroup

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

BindGroup represents bound GPU resources for shader access.

func (*BindGroup) Release

func (g *BindGroup) Release()

Release marks the bind group for destruction. The underlying HAL BindGroup (and its descriptor heap slots) is not freed immediately — it is deferred via DestroyQueue until the GPU completes any submission that may reference it. This prevents descriptor use-after-free on DX12 with maxFramesInFlight=2 (BUG-DX12-007).

Matches Rust wgpu pattern: BindGroup::drop() only fires after triage_submissions confirms fence completion.

type BindGroupDescriptor

type BindGroupDescriptor struct {
	Label   string
	Layout  *BindGroupLayout
	Entries []BindGroupEntry
}

BindGroupDescriptor describes a bind group.

type BindGroupEntry

type BindGroupEntry struct {
	Binding     uint32
	Buffer      *Buffer      // For buffer bindings
	Offset      uint64       // Buffer offset
	Size        uint64       // Buffer binding size (0 = rest of buffer)
	Sampler     *Sampler     // For sampler bindings
	TextureView *TextureView // For texture bindings
}

BindGroupEntry describes a single resource binding in a bind group. Exactly one of Buffer, Sampler, or TextureView must be set.

type BindGroupLayout

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

BindGroupLayout defines the structure of resource bindings for shaders.

func (*BindGroupLayout) Release

func (l *BindGroupLayout) Release()

Release destroys the bind group layout. Destruction is deferred until the GPU completes any submission that may reference this layout.

type BindGroupLayoutDescriptor

type BindGroupLayoutDescriptor struct {
	Label   string
	Entries []BindGroupLayoutEntry
}

BindGroupLayoutDescriptor describes a bind group layout.

type BindGroupLayoutEntry

type BindGroupLayoutEntry = gputypes.BindGroupLayoutEntry

Bind group types

type Buffer

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

Buffer represents a GPU buffer.

func (*Buffer) Label

func (b *Buffer) Label() string

Label returns the buffer's debug label.

func (*Buffer) Map added in v0.25.0

func (b *Buffer) Map(ctx context.Context, mode MapMode, offset, size uint64) error

Map blocks until a CPU-visible mapping is established for the given byte range, or until ctx is canceled.

The buffer must have been created with BufferUsageMapRead or BufferUsageMapWrite matching mode. offset must be a multiple of 8 and size must be a multiple of 4 (WebGPU MAP_ALIGNMENT).

After Map succeeds, call MappedRange to obtain a byte view and Unmap when finished. The primary usage pattern mirrors database/sql rows:

if err := buf.Map(ctx, wgpu.MapModeRead, 0, size); err != nil {
    return err
}
defer buf.Unmap()
rng, _ := buf.MappedRange(0, size)
data := rng.Bytes()

Map drives Device.Poll internally; callers do not need to schedule polling themselves. If you need non-blocking behavior use MapAsync.

func (*Buffer) MapAsync added in v0.25.0

func (b *Buffer) MapAsync(mode MapMode, offset, size uint64) (*MapPending, error)

MapAsync initiates a buffer map without blocking the caller.

Returns a *MapPending handle that resolves once the GPU submission that last wrote to the buffer completes. The caller must periodically drive Device.Poll(PollPoll) (or, more commonly, rely on the auto-poll at the tail of Queue.Submit) to let the mapping resolve.

Validation errors surface synchronously — alignment, usage mismatch, range overflow, already-mapped state, etc. A returned MapPending is always valid; its Status() may resolve as failed later if the buffer is destroyed or the map is canceled.

func (*Buffer) MapState added in v0.25.0

func (b *Buffer) MapState() MapState

MapState returns the current mapping state of the buffer.

This is a synchronized snapshot — the state may change immediately after return if another goroutine calls Unmap or Destroy, but the value reflects the state at the moment of the call.

func (*Buffer) MappedRange added in v0.25.0

func (b *Buffer) MappedRange(offset, size uint64) (*MappedRange, error)

MappedRange returns a safe view over the mapped region [offset, offset+size).

The buffer must be in the Mapped state (Map or MapAsync resolved). The returned range overlaps with neither the rest of the buffer nor any previously-returned MappedRange that has not been Unmap'd — WebGPU spec §5.3.4 forbids overlapping getMappedRange calls on the same buffer and we enforce this synchronously.

The returned slice (via MappedRange.Bytes) is invalidated by Unmap.

func (*Buffer) Release

func (b *Buffer) Release()

Release destroys the buffer. The underlying HAL buffer is not freed immediately — destruction is deferred until the GPU completes any submission that may reference it. This prevents use-after-free on DX12/Vulkan when a buffer is released while the GPU is still reading from it (BUG-DX12-TDR).

func (*Buffer) Size

func (b *Buffer) Size() uint64

Size returns the buffer size in bytes.

func (*Buffer) Unmap added in v0.25.0

func (b *Buffer) Unmap() error

Unmap releases the current mapping and invalidates all outstanding MappedRange handles for this buffer. Safe to call multiple times; a second call returns ErrMapNotMapped.

Unmap also cancels a Pending map (the associated MapPending resolves with ErrMapCancelled).

func (*Buffer) Usage

func (b *Buffer) Usage() BufferUsage

Usage returns the buffer's usage flags.

type BufferDescriptor

type BufferDescriptor struct {
	Label            string
	Size             uint64
	Usage            BufferUsage
	MappedAtCreation bool
}

BufferDescriptor describes buffer creation parameters.

type BufferTextureCopy added in v0.21.0

type BufferTextureCopy struct {
	BufferLayout ImageDataLayout
	TextureBase  ImageCopyTexture
	Size         Extent3D
}

BufferTextureCopy defines a buffer-texture copy region.

type BufferUsage

type BufferUsage = gputypes.BufferUsage

Buffer usage

type Color

type Color = gputypes.Color

type ColorTargetState

type ColorTargetState = gputypes.ColorTargetState

type CommandBuffer

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

CommandBuffer holds recorded GPU commands ready for submission. Created by CommandEncoder.Finish().

func (*CommandBuffer) Release added in v0.24.1

func (cb *CommandBuffer) Release()

Release releases a CommandBuffer that will NOT be submitted to the GPU. This returns the HAL encoder to the device pool and drops tracked resource refs.

In normal flow, Submit() takes ownership of the encoder and handles recycling after GPU completion. Release() is for error paths and canceled operations where the CommandBuffer is discarded without submitting.

Matches Rust wgpu-core InnerCommandEncoder::Drop (command/mod.rs:726-738) which always calls reset_all + release_encoder regardless of whether the command buffer was submitted.

A CommandBuffer MUST be either Submit()'d or Release()'d. Failing to do either leaks the HAL encoder (DX12 ~64KB allocator, Vulkan VkCommandPool).

type CommandEncoder

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

CommandEncoder records GPU commands for later submission.

A command encoder is single-use. After calling Finish(), the encoder cannot be used again. Call Device.CreateCommandEncoder() to create a new one.

NOT thread-safe - do not use from multiple goroutines.

func (*CommandEncoder) BeginComputePass

func (e *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) (*ComputePassEncoder, error)

BeginComputePass begins a compute pass. The returned ComputePassEncoder records dispatch commands. Call ComputePassEncoder.End() when done.

func (*CommandEncoder) BeginRenderPass

func (e *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) (*RenderPassEncoder, error)

BeginRenderPass begins a render pass. The returned RenderPassEncoder records draw commands. Call RenderPassEncoder.End() when done.

func (*CommandEncoder) CopyBufferToBuffer

func (e *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset uint64, size uint64)

CopyBufferToBuffer copies data between buffers.

func (*CommandEncoder) CopyTextureToBuffer added in v0.21.0

func (e *CommandEncoder) CopyTextureToBuffer(src *Texture, dst *Buffer, regions []BufferTextureCopy)

CopyTextureToBuffer copies data from a texture to a buffer. This is used for GPU-to-CPU readback of rendered content.

func (*CommandEncoder) DiscardEncoding added in v0.21.0

func (e *CommandEncoder) DiscardEncoding()

DiscardEncoding discards the encoder without producing a command buffer. Use this to abandon an in-progress encoding when an error occurs. If the encoder was acquired from the pool, it is returned for reuse.

func (*CommandEncoder) Finish

func (e *CommandEncoder) Finish() (*CommandBuffer, error)

Finish completes command recording and returns a CommandBuffer. After calling Finish(), the encoder cannot be used again.

The HAL encoder ownership transfers from the CommandEncoder to the CommandBuffer. After GPU completion, Submit() schedules the encoder to be reset via ResetAll and returned to the Device's encoder pool.

func (*CommandEncoder) TransitionTextures added in v0.21.0

func (e *CommandEncoder) TransitionTextures(barriers []TextureBarrier)

TransitionTextures transitions texture states for synchronization. This is needed on Vulkan for layout transitions between render pass and copy operations (e.g., after MSAA resolve before CopyTextureToBuffer). On Metal, GLES, and software backends this is a no-op.

type CommandEncoderDescriptor

type CommandEncoderDescriptor struct {
	Label string
}

CommandEncoderDescriptor describes command encoder creation.

type CompareFunction

type CompareFunction = gputypes.CompareFunction

type CompositeAlphaMode

type CompositeAlphaMode = gputypes.CompositeAlphaMode

type ComputePassDescriptor

type ComputePassDescriptor struct {
	Label string
}

ComputePassDescriptor describes a compute pass.

type ComputePassEncoder

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

ComputePassEncoder records compute dispatch commands.

Created by CommandEncoder.BeginComputePass(). Must be ended with End() before the CommandEncoder can be finished.

NOT thread-safe.

func (*ComputePassEncoder) Dispatch

func (p *ComputePassEncoder) Dispatch(x, y, z uint32)

Dispatch dispatches compute work.

func (*ComputePassEncoder) DispatchIndirect

func (p *ComputePassEncoder) DispatchIndirect(buffer *Buffer, offset uint64)

DispatchIndirect dispatches compute work with GPU-generated parameters.

func (*ComputePassEncoder) End

func (p *ComputePassEncoder) End() error

End ends the compute pass.

func (*ComputePassEncoder) SetBindGroup

func (p *ComputePassEncoder) SetBindGroup(index uint32, group *BindGroup, offsets []uint32)

SetBindGroup sets a bind group for the given index.

func (*ComputePassEncoder) SetPipeline

func (p *ComputePassEncoder) SetPipeline(pipeline *ComputePipeline)

SetPipeline sets the active compute pipeline.

type ComputePipeline

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

ComputePipeline represents a configured compute pipeline.

func (*ComputePipeline) Release

func (p *ComputePipeline) Release()

Release destroys the compute pipeline. Destruction is deferred until the GPU completes any submission that may reference this pipeline.

type ComputePipelineDescriptor

type ComputePipelineDescriptor struct {
	Label      string
	Layout     *PipelineLayout
	Module     *ShaderModule
	EntryPoint string
}

ComputePipelineDescriptor describes a compute pipeline.

type CullMode

type CullMode = gputypes.CullMode

type DepthStencilState

type DepthStencilState struct {
	Format              TextureFormat
	DepthWriteEnabled   bool
	DepthCompare        CompareFunction
	StencilFront        StencilFaceState
	StencilBack         StencilFaceState
	StencilReadMask     uint32
	StencilWriteMask    uint32
	DepthBias           int32
	DepthBiasSlopeScale float32
	DepthBiasClamp      float32
}

DepthStencilState describes depth and stencil testing configuration.

type Device

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

Device represents a logical GPU device. It is the main interface for creating GPU resources.

Device methods are safe for concurrent use, except Release() which must not be called concurrently with other methods.

func NewDeviceFromHAL added in v0.21.0

func NewDeviceFromHAL(
	halDevice hal.Device,
	halQueue hal.Queue,
	features Features,
	limits Limits,
	label string,
) (*Device, error)

NewDeviceFromHAL creates a Device wrapping existing HAL device and queue objects. This constructor is used by backends that manage their own HAL lifecycle (e.g., the Rust FFI backend via wgpu-native) and need to expose their HAL objects through the wgpu public API.

Ownership of halDevice and halQueue is transferred to the returned Device. The caller must not destroy them directly after this call.

func (*Device) CreateBindGroup

func (d *Device) CreateBindGroup(desc *BindGroupDescriptor) (*BindGroup, error)

CreateBindGroup creates a bind group.

func (*Device) CreateBindGroupLayout

func (d *Device) CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) (*BindGroupLayout, error)

CreateBindGroupLayout creates a bind group layout.

func (*Device) CreateBuffer

func (d *Device) CreateBuffer(desc *BufferDescriptor) (*Buffer, error)

CreateBuffer creates a GPU buffer.

func (*Device) CreateCommandEncoder

func (d *Device) CreateCommandEncoder(desc *CommandEncoderDescriptor) (*CommandEncoder, error)

CreateCommandEncoder creates a command encoder for recording GPU commands.

When a device-level encoder pool is available (BUG-DX12-004), the HAL encoder is acquired from the pool instead of creating a new one. This avoids allocating expensive GPU resources (DX12 ID3D12CommandAllocator ~64KB, Vulkan VkCommandPool) on every frame. After GPU completion, the encoder is reset and returned to the pool for reuse. Matches Rust wgpu-core's CommandAllocator pattern (allocator.rs).

func (*Device) CreateComputePipeline

func (d *Device) CreateComputePipeline(desc *ComputePipelineDescriptor) (*ComputePipeline, error)

CreateComputePipeline creates a compute pipeline.

func (*Device) CreateFence added in v0.21.0

func (d *Device) CreateFence() (*Fence, error)

CreateFence creates a GPU synchronization fence. Fences are primarily used by the HAL internally for synchronization. Most callers should use Queue.Submit + Queue.Poll instead.

func (*Device) CreatePipelineLayout

func (d *Device) CreatePipelineLayout(desc *PipelineLayoutDescriptor) (*PipelineLayout, error)

CreatePipelineLayout creates a pipeline layout.

func (*Device) CreateRenderPipeline

func (d *Device) CreateRenderPipeline(desc *RenderPipelineDescriptor) (*RenderPipeline, error)

CreateRenderPipeline creates a render pipeline.

func (*Device) CreateSampler

func (d *Device) CreateSampler(desc *SamplerDescriptor) (*Sampler, error)

CreateSampler creates a texture sampler.

func (*Device) CreateShaderModule

func (d *Device) CreateShaderModule(desc *ShaderModuleDescriptor) (*ShaderModule, error)

CreateShaderModule creates a shader module.

func (*Device) CreateTexture

func (d *Device) CreateTexture(desc *TextureDescriptor) (*Texture, error)

CreateTexture creates a GPU texture.

func (*Device) CreateTextureView

func (d *Device) CreateTextureView(texture *Texture, desc *TextureViewDescriptor) (*TextureView, error)

CreateTextureView creates a view into a texture.

func (*Device) DestroyFence deprecated added in v0.21.0

func (d *Device) DestroyFence(f *Fence)

DestroyFence destroys a fence. The fence must not be in use by the GPU when destroyed.

Deprecated: Use Fence.Release() instead.

func (*Device) Features

func (d *Device) Features() Features

Features returns the device's enabled features.

func (*Device) FreeCommandBuffer added in v0.21.0

func (d *Device) FreeCommandBuffer(cb *CommandBuffer)

FreeCommandBuffer returns a command buffer to the command pool. This must be called after the GPU has finished using the command buffer. The command buffer handle becomes invalid after this call.

func (*Device) GetFenceStatus added in v0.21.0

func (d *Device) GetFenceStatus(f *Fence) (bool, error)

GetFenceStatus returns true if the fence is signaled (non-blocking). This is used for polling completion without blocking.

func (*Device) HalDevice added in v0.21.0

func (d *Device) HalDevice() hal.Device

HalDevice returns the underlying HAL device for advanced use cases. This enables interop with code that needs direct HAL access (e.g., gg GPU accelerator, DeviceProvider interfaces).

Returns nil if the device has been released or has no HAL backend.

func (*Device) HalQueue added in v0.21.0

func (d *Device) HalQueue() hal.Queue

HalQueue returns the underlying HAL queue. Returns nil if the device has been released or has no HAL backend.

func (*Device) Limits

func (d *Device) Limits() Limits

Limits returns the device's resource limits.

func (*Device) Poll added in v0.25.0

func (d *Device) Poll(pollType PollType) bool

Poll drives the per-device pending-map triage loop.

PollPoll drains any buffer mappings whose associated GPU submissions have already completed and returns immediately. This is the fast path for game loops and is called automatically from Queue.Submit, so beginner code paths never need to call Poll explicitly.

PollWait blocks until every currently-pending map resolves: it issues WaitIdle on the HAL device, then drains all buckets. This is the primary path used by Buffer.Map and is appropriate for shutdown drains and short scripts that do not run a render loop.

The return value reports whether Poll observed any in-flight maps — tests use it to assert that Submit-driven auto-polling drained everything without needing an explicit Poll call.

func (*Device) PopErrorScope

func (d *Device) PopErrorScope() *GPUError

PopErrorScope pops the most recently pushed error scope. Returns the captured error, or nil if no error occurred.

func (*Device) PushErrorScope

func (d *Device) PushErrorScope(filter ErrorFilter)

PushErrorScope pushes a new error scope onto the device's error scope stack.

func (*Device) Queue

func (d *Device) Queue() *Queue

Queue returns the device's command queue.

func (*Device) Release

func (d *Device) Release()

Release releases the device and all associated resources. Deferred resource destructions are flushed before the device is destroyed. Shutdown order:

  1. WaitIdle — block until ALL GPU submissions complete
  2. Triage + FlushAll — deferred callbacks fire (encoders return to pool)
  3. Destroy encoder pool (HAL device still alive)
  4. Destroy core + HAL device

WaitIdle is required because FlushAll calls Triage(PollCompleted()), but PollCompleted may return a stale index if GPU hasn't finished. Without WaitIdle, deferred encoder recycling callbacks don't fire, and pool.destroy() destroys encoders whose VkCommandPool is then double-freed by hal.Device.Destroy() → vkDestroyCommandPool crash.

Rust avoids this via Arc ownership + maintain loop. In Go we must be explicit: WaitIdle ensures PollCompleted returns final index.

func (*Device) ResetFence added in v0.21.0

func (d *Device) ResetFence(f *Fence) error

ResetFence resets a fence to the unsignaled state. The fence must not be in use by the GPU.

func (*Device) WaitForFence added in v0.21.0

func (d *Device) WaitForFence(f *Fence, value uint64, timeout time.Duration) (bool, error)

WaitForFence waits for a fence to reach the specified value. Returns true if the fence reached the value, false if timeout expired.

func (*Device) WaitIdle

func (d *Device) WaitIdle() error

WaitIdle waits for all GPU work to complete.

type DeviceDescriptor

type DeviceDescriptor struct {
	Label            string
	RequiredFeatures Features
	RequiredLimits   Limits
}

DeviceDescriptor configures device creation.

type DeviceType

type DeviceType = gputypes.DeviceType

type ErrorFilter

type ErrorFilter = core.ErrorFilter

type Extent3D

type Extent3D struct {
	Width              uint32
	Height             uint32
	DepthOrArrayLayers uint32
}

Extent3D is a 3D size.

type Features

type Features = gputypes.Features

Feature and limit types

type Fence added in v0.21.0

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

Fence is a GPU synchronization primitive. Fences allow CPU-GPU synchronization by signaling when submitted work completes.

Fences are created via Device.CreateFence and should be released via Release() when no longer needed.

func (*Fence) Release added in v0.21.0

func (f *Fence) Release()

Release destroys the fence. After this call, the fence must not be used.

type FilterMode

type FilterMode = gputypes.FilterMode

type FragmentState

type FragmentState struct {
	Module     *ShaderModule
	EntryPoint string
	Targets    []ColorTargetState
}

FragmentState describes the fragment shader stage.

type FrontFace

type FrontFace = gputypes.FrontFace

type GPUError

type GPUError = core.GPUError

Re-export error types from core.

type ImageCopyTexture added in v0.19.7

type ImageCopyTexture struct {
	Texture  *Texture
	MipLevel uint32
	Origin   Origin3D
	Aspect   TextureAspect
}

ImageCopyTexture describes a texture subresource and origin for write operations.

type ImageDataLayout added in v0.19.7

type ImageDataLayout struct {
	Offset       uint64
	BytesPerRow  uint32
	RowsPerImage uint32
}

ImageDataLayout describes the layout of image data in a buffer.

type IndexFormat

type IndexFormat = gputypes.IndexFormat

type Instance

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

Instance is the entry point for GPU operations.

Instance methods are safe for concurrent use, except Release() which must not be called concurrently with other methods.

func CreateInstance

func CreateInstance(desc *InstanceDescriptor) (*Instance, error)

CreateInstance creates a new GPU instance. If desc is nil, all available backends are used.

func (*Instance) CreateSurface

func (i *Instance) CreateSurface(displayHandle, windowHandle uintptr) (*Surface, error)

CreateSurface creates a rendering surface from platform-specific handles. displayHandle and windowHandle are platform-specific:

  • Windows: displayHandle=0, windowHandle=HWND
  • macOS: displayHandle=0, windowHandle=NSView*
  • Linux/X11: displayHandle=Display*, windowHandle=Window
  • Linux/Wayland: displayHandle=wl_display*, windowHandle=wl_surface*

func (*Instance) Release

func (i *Instance) Release()

Release releases the instance and all associated resources.

func (*Instance) RequestAdapter

func (i *Instance) RequestAdapter(opts *RequestAdapterOptions) (*Adapter, error)

RequestAdapter requests a GPU adapter matching the options. If opts is nil, the best available adapter is returned.

When opts.CompatibleSurface is set, backends that require a surface for adapter enumeration (GLES/OpenGL) will perform deferred enumeration using the surface's GL context. This follows the WebGPU spec pattern where requestAdapter accepts a compatible surface hint.

type InstanceDescriptor

type InstanceDescriptor struct {
	Backends Backends
	// Flags controls instance features like debug layers and validation.
	// Use gputypes.InstanceFlagsDebug to enable GPU debug layer.
	Flags gputypes.InstanceFlags
}

InstanceDescriptor configures instance creation.

type LateBufferBindingInfo added in v0.25.4

type LateBufferBindingInfo struct {
	// BindingIndex is the binding number from the layout entry.
	BindingIndex uint32
	// Size is the actual buffer binding size at bind group creation time.
	Size uint64
}

LateBufferBindingInfo records the actual buffer binding size for a layout entry with MinBindingSize == 0. At draw/dispatch time, these sizes are compared against the shader-required minimums stored on the pipeline.

Matches Rust wgpu-core's BindGroupLateBufferBindingInfo (binding_model.rs:1167-1173).

type LateSizedBufferGroup added in v0.25.4

type LateSizedBufferGroup struct {
	ShaderSizes []uint64
}

LateSizedBufferGroup holds the shader-required minimum buffer sizes for bind group entries whose layout specifies MinBindingSize == 0. These sizes are validated at draw/dispatch time against the actual bound buffer sizes.

The order of ShaderSizes matches the order of buffer entries with MinBindingSize == 0 in the corresponding BindGroupLayout, matching Rust wgpu-core's pipeline::LateSizedBufferGroup.

type Limits

type Limits = gputypes.Limits

type LoadOp

type LoadOp = gputypes.LoadOp

Render types

type MapMode added in v0.25.0

type MapMode uint32

MapMode selects the type of access requested for a buffer mapping. Values match WebGPU spec §5.3.2 GPUMapMode.

const (
	// MapModeRead requests a read-only mapping. The buffer must have been
	// created with BufferUsageMapRead.
	MapModeRead MapMode = 1
	// MapModeWrite requests a write-only mapping. The buffer must have
	// been created with BufferUsageMapWrite.
	MapModeWrite MapMode = 2
)

type MapPending added in v0.25.0

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

MapPending is a zero-allocation handle to an in-flight Buffer.MapAsync.

It is allocated from a sync.Pool and must be released to the pool by calling either Wait, Status (until ready=true), or Release — failing to release simply wastes a pool entry until the next GC, but does not leak memory. The handle becomes invalid once the underlying map has resolved; subsequent Status/Wait calls are idempotent and return the cached result.

MapPending is not safe to share between goroutines without external synchronization; the typical pattern is "create on one goroutine, wait on another".

func (*MapPending) Release added in v0.25.0

func (p *MapPending) Release()

Release returns the MapPending to the pool without waiting. Calling this while the map is still in flight is allowed; the pending map continues to resolve inside Device.Poll but its completion is not observable through this handle anymore.

func (*MapPending) Status added in v0.25.0

func (p *MapPending) Status() (ready bool, err error)

Status reports the current state of the pending map without blocking.

  • (true, nil) — mapping is ready; call Buffer.MappedRange.
  • (false, nil) — still pending; caller should continue work and call Device.Poll(PollPoll) in a later tick.
  • (true, err) — mapping failed; the buffer is back in the Unmapped state and err describes why.

After Status returns ready=true the MapPending is automatically returned to the pool; subsequent calls are safe but always return the cached (true, err) pair.

func (*MapPending) Wait added in v0.25.0

func (p *MapPending) Wait(ctx context.Context) error

Wait blocks until the pending map resolves or ctx is canceled.

If ctx is canceled before the GPU resolves the map, Wait returns ctx.Err() and the mapping remains Pending — the caller should normally follow up with Buffer.Unmap to cancel it, or retry Wait later.

type MapState added in v0.25.0

type MapState uint8

MapState reports the current mapping state of a buffer. Matches WebGPU spec §5.3.3 GPUBufferMapState plus the Destroyed terminal state used internally to guard against use-after-destroy.

const (
	// MapStateUnmapped indicates the buffer is not currently mapped.
	MapStateUnmapped MapState = iota
	// MapStatePending indicates the buffer has a Map or MapAsync in
	// progress but the GPU has not yet resolved the underlying fence.
	MapStatePending
	// MapStateMapped indicates the buffer is CPU-accessible via
	// MappedRange; Unmap returns it to Unmapped.
	MapStateMapped
	// MapStateDestroyed indicates Buffer.Destroy has been called and the
	// buffer can never be mapped again. Terminal state.
	MapStateDestroyed
)

type MappedRange added in v0.25.0

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

MappedRange is a safe view over a region of a mapped GPU buffer.

MappedRange replaces raw []byte return from the legacy Queue.ReadBuffer API. It is invalidated atomically on Buffer.Unmap via a per-buffer generation counter — calling Bytes() on a detached range returns nil rather than exposing freed memory, mitigating the UAF pattern that the WebGPU CVE history has accumulated (see ADR §Safety #4).

Typical usage:

if err := buf.Map(ctx, wgpu.MapModeRead, 0, size); err != nil {
    return err
}
defer buf.Unmap()
rng, err := buf.MappedRange(0, size)
if err != nil { return err }
data := rng.Bytes() // valid until buf.Unmap()

A single MappedRange is not thread-safe to share between goroutines without external synchronization; typical use is a single owner that copies data out before Unmap.

MappedRange instances are pooled via sync.Pool for zero-allocation steady-state use. Callers that care about allocation counts should call Release() after consuming Bytes().

func (*MappedRange) Bytes added in v0.25.0

func (m *MappedRange) Bytes() []byte

Bytes returns the underlying byte slice for the mapped range.

The slice is valid until the owning buffer is unmapped; after Unmap the generation counter advances and Bytes() returns nil. Callers should NOT cache the returned slice past Unmap.

Bytes() is safe to call concurrently with itself but not with Unmap on the same buffer — that is the caller's responsibility to coordinate.

func (*MappedRange) Len added in v0.25.0

func (m *MappedRange) Len() int

Len returns the size of the mapped range in bytes.

func (*MappedRange) Offset added in v0.25.0

func (m *MappedRange) Offset() uint64

Offset returns the byte offset of the mapped range within its buffer.

func (*MappedRange) Release added in v0.25.0

func (m *MappedRange) Release()

Release returns the MappedRange to the pool. Calling this is optional — the pool simply fills back up on the next GC cycle — but keeping MappedRange calls zero-alloc in the primary Map path requires the caller to Release after the bytes have been consumed.

After Release the MappedRange is invalid; calling Bytes() returns nil.

type MultisampleState

type MultisampleState = gputypes.MultisampleState

type Origin3D

type Origin3D struct {
	X uint32
	Y uint32
	Z uint32
}

Origin3D is a 3D origin point.

type PipelineLayout

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

PipelineLayout defines the bind group layout arrangement for a pipeline.

func (*PipelineLayout) Release

func (l *PipelineLayout) Release()

Release destroys the pipeline layout. Destruction is deferred until the GPU completes any submission that may reference this layout.

type PipelineLayoutDescriptor

type PipelineLayoutDescriptor struct {
	Label            string
	BindGroupLayouts []*BindGroupLayout
}

PipelineLayoutDescriptor describes a pipeline layout.

type PollType added in v0.25.0

type PollType uint8

PollType selects the blocking behavior of Device.Poll.

const (
	// PollPoll drains any already-completed submissions and returns
	// immediately without blocking on the GPU. This is the fast path
	// for game loops that call Poll every frame.
	PollPoll PollType = iota
	// PollWait blocks until every submission currently known to the
	// device has completed, then drains. Used by Buffer.Map and by
	// Device.Poll(PollWait) for shutdown drains.
	PollWait
)

type PowerPreference

type PowerPreference = gputypes.PowerPreference

type PresentMode

type PresentMode = gputypes.PresentMode

Surface/presentation types

type PrimitiveState

type PrimitiveState = gputypes.PrimitiveState

type PrimitiveTopology

type PrimitiveTopology = gputypes.PrimitiveTopology

Primitive types

type Queue

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

Queue handles command submission and data transfers.

func (*Queue) LastSubmissionIndex added in v0.23.6

func (q *Queue) LastSubmissionIndex() uint64

LastSubmissionIndex returns the most recent submission index. Used by resource Release() methods to schedule deferred destruction.

func (*Queue) Poll added in v0.23.0

func (q *Queue) Poll() uint64

Poll returns the last completed submission index. Non-blocking. All submissions with index <= the returned value have been completed by the GPU.

func (*Queue) SetSwapchainSuppressed added in v0.26.3

func (q *Queue) SetSwapchainSuppressed(suppressed bool)

SetSwapchainSuppressed temporarily disables swapchain semaphore binding for subsequent Submit calls. Used for offscreen renders (e.g., RepaintBoundary) that must not consume acquire/present semaphores intended for the compositor submit.

BUG-WGPU-VK-005: When rendering to an offscreen texture before compositing to the swapchain surface, the offscreen submit must not hijack swapchain semaphores. Without suppression, the compositor submit runs without GPU-side synchronization, causing a race condition (flickering).

Call with true before offscreen submits, false after:

queue.SetSwapchainSuppressed(true)
defer queue.SetSwapchainSuppressed(false)
queue.Submit(offscreenCmds...)

Only meaningful on Vulkan — other backends are no-ops.

func (*Queue) Submit

func (q *Queue) Submit(commandBuffers ...*CommandBuffer) (uint64, error)

Submit submits command buffers for execution. Non-blocking. Returns a submission index that can be used with Poll() to track completion. Command buffers are owned by the caller — free them after Poll confirms completion.

If there are pending WriteBuffer/WriteTexture operations, they are flushed and prepended before the user command buffers in a single HAL submit.

func (*Queue) WriteBuffer

func (q *Queue) WriteBuffer(buffer *Buffer, offset uint64, data []byte) error

WriteBuffer writes data to a buffer. If PendingWrites batching is enabled (DX12/Vulkan/Metal), the write is recorded into a shared command encoder and flushed on the next Submit. For GLES/Software backends, the write is performed immediately.

MapWrite buffers (upload heap on DX12, host-visible on Vulkan) are written directly via HAL without staging — GPU copy into upload heap is undefined behavior on DX12 (upload heap is GENERIC_READ, read-only to GPU). See BUG-DX12-003.

func (*Queue) WriteTexture added in v0.19.7

func (q *Queue) WriteTexture(dst *ImageCopyTexture, data []byte, layout *ImageDataLayout, size *Extent3D) error

WriteTexture writes data to a texture. If PendingWrites batching is enabled (DX12/Vulkan/Metal), the write is recorded into a shared command encoder and flushed on the next Submit. Resource barriers are computed from the texture's tracked CurrentUsage(). For GLES/Software backends, the write is performed immediately via HAL.

type RenderPassColorAttachment

type RenderPassColorAttachment struct {
	View          *TextureView
	ResolveTarget *TextureView
	LoadOp        LoadOp
	StoreOp       StoreOp
	ClearValue    Color
}

RenderPassColorAttachment describes a color attachment.

type RenderPassDepthStencilAttachment

type RenderPassDepthStencilAttachment struct {
	View              *TextureView
	DepthLoadOp       LoadOp
	DepthStoreOp      StoreOp
	DepthClearValue   float32
	DepthReadOnly     bool
	StencilLoadOp     LoadOp
	StencilStoreOp    StoreOp
	StencilClearValue uint32
	StencilReadOnly   bool
}

RenderPassDepthStencilAttachment describes a depth/stencil attachment.

type RenderPassDescriptor

type RenderPassDescriptor struct {
	Label                  string
	ColorAttachments       []RenderPassColorAttachment
	DepthStencilAttachment *RenderPassDepthStencilAttachment
}

RenderPassDescriptor describes a render pass.

type RenderPassEncoder

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

RenderPassEncoder records draw commands within a render pass.

Created by CommandEncoder.BeginRenderPass(). Must be ended with End() before the CommandEncoder can be finished.

NOT thread-safe.

func (*RenderPassEncoder) Draw

func (p *RenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)

Draw draws primitives.

func (*RenderPassEncoder) DrawIndexed

func (p *RenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)

DrawIndexed draws indexed primitives.

func (*RenderPassEncoder) DrawIndexedIndirect

func (p *RenderPassEncoder) DrawIndexedIndirect(buffer *Buffer, offset uint64)

DrawIndexedIndirect draws indexed primitives with GPU-generated parameters.

func (*RenderPassEncoder) DrawIndirect

func (p *RenderPassEncoder) DrawIndirect(buffer *Buffer, offset uint64)

DrawIndirect draws primitives with GPU-generated parameters.

func (*RenderPassEncoder) End

func (p *RenderPassEncoder) End() error

End ends the render pass. After this call, the encoder cannot be used again.

func (*RenderPassEncoder) SetBindGroup

func (p *RenderPassEncoder) SetBindGroup(index uint32, group *BindGroup, offsets []uint32)

SetBindGroup sets a bind group for the given index.

func (*RenderPassEncoder) SetBlendConstant

func (p *RenderPassEncoder) SetBlendConstant(color *Color)

SetBlendConstant sets the blend constant color.

func (*RenderPassEncoder) SetIndexBuffer

func (p *RenderPassEncoder) SetIndexBuffer(buffer *Buffer, format IndexFormat, offset uint64)

SetIndexBuffer sets the index buffer.

func (*RenderPassEncoder) SetPipeline

func (p *RenderPassEncoder) SetPipeline(pipeline *RenderPipeline)

SetPipeline sets the active render pipeline.

func (*RenderPassEncoder) SetScissorRect

func (p *RenderPassEncoder) SetScissorRect(x, y, width, height uint32)

SetScissorRect sets the scissor rectangle for clipping.

func (*RenderPassEncoder) SetStencilReference

func (p *RenderPassEncoder) SetStencilReference(reference uint32)

SetStencilReference sets the stencil reference value.

func (*RenderPassEncoder) SetVertexBuffer

func (p *RenderPassEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset uint64)

SetVertexBuffer sets a vertex buffer for the given slot.

func (*RenderPassEncoder) SetViewport

func (p *RenderPassEncoder) SetViewport(x, y, width, height, minDepth, maxDepth float32)

SetViewport sets the viewport transformation.

type RenderPipeline

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

RenderPipeline represents a configured render pipeline.

func (*RenderPipeline) Release

func (p *RenderPipeline) Release()

Release destroys the render pipeline. Destruction is deferred until the GPU completes any submission that may reference this pipeline.

type RenderPipelineDescriptor

type RenderPipelineDescriptor struct {
	Label        string
	Layout       *PipelineLayout
	Vertex       VertexState
	Primitive    PrimitiveState
	DepthStencil *DepthStencilState
	Multisample  MultisampleState
	Fragment     *FragmentState
}

RenderPipelineDescriptor describes a render pipeline.

type RequestAdapterOptions

type RequestAdapterOptions struct {
	// PowerPreference indicates power consumption preference.
	PowerPreference PowerPreference
	// ForceFallbackAdapter forces the use of a fallback (software) adapter.
	ForceFallbackAdapter bool
	// CompatibleSurface, if non-nil, indicates that the adapter must support
	// rendering to this surface. For GLES backends, this triggers deferred
	// adapter enumeration using the surface's GL context.
	CompatibleSurface *Surface
}

RequestAdapterOptions controls adapter selection.

Following the WebGPU spec, CompatibleSurface is a typed *Surface pointer (not a raw handle). Backends that require a surface for adapter enumeration (e.g., GLES/OpenGL which needs a GL context) use this to perform deferred enumeration when RequestAdapter is called.

type Sampler

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

Sampler represents a texture sampler.

func NewSamplerFromHAL added in v0.21.0

func NewSamplerFromHAL(halSampler hal.Sampler, device *Device) *Sampler

NewSamplerFromHAL creates a Sampler wrapping an existing HAL sampler.

func (*Sampler) Release

func (s *Sampler) Release()

Release destroys the sampler. Destruction is deferred until the GPU completes any submission that may reference this sampler.

type SamplerDescriptor

type SamplerDescriptor struct {
	Label        string
	AddressModeU AddressMode
	AddressModeV AddressMode
	AddressModeW AddressMode
	MagFilter    FilterMode
	MinFilter    FilterMode
	MipmapFilter FilterMode
	LodMinClamp  float32
	LodMaxClamp  float32
	Compare      CompareFunction
	Anisotropy   uint16
}

SamplerDescriptor describes sampler creation parameters.

type ShaderModule

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

ShaderModule represents a compiled shader module.

func (*ShaderModule) Release

func (m *ShaderModule) Release()

Release destroys the shader module. Destruction is deferred until the GPU completes any submission that may reference this shader module.

type ShaderModuleDescriptor

type ShaderModuleDescriptor struct {
	Label string
	WGSL  string   // WGSL source code
	SPIRV []uint32 // SPIR-V bytecode (alternative to WGSL)
}

ShaderModuleDescriptor describes shader module creation parameters.

type ShaderStages

type ShaderStages = gputypes.ShaderStages

Shader types

type StencilFaceState added in v0.21.0

type StencilFaceState struct {
	Compare     CompareFunction
	FailOp      StencilOperation
	DepthFailOp StencilOperation
	PassOp      StencilOperation
}

StencilFaceState describes stencil operations for a face.

type StencilOperation added in v0.21.0

type StencilOperation = hal.StencilOperation

StencilOperation describes a stencil operation.

type StoreOp

type StoreOp = gputypes.StoreOp

type Surface

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

Surface represents a platform rendering surface (e.g., a window).

Surface delegates lifecycle management to core.Surface, which enforces the state machine: Unconfigured -> Configured -> Acquired -> Configured.

func NewSurfaceFromHAL added in v0.21.0

func NewSurfaceFromHAL(halSurface hal.Surface, label string) *Surface

NewSurfaceFromHAL creates a Surface wrapping an existing HAL surface. This constructor is used by backends that create surfaces externally (e.g., the Rust FFI backend).

Ownership of halSurface is transferred to the returned Surface.

func (*Surface) Configure

func (s *Surface) Configure(device *Device, config *SurfaceConfiguration) error

Configure configures the surface for presentation. Must be called before GetCurrentTexture().

func (*Surface) DiscardTexture added in v0.21.0

func (s *Surface) DiscardTexture()

DiscardTexture discards the acquired surface texture without presenting it. Use this if rendering failed or was canceled. If no texture is currently acquired, this is a no-op.

func (*Surface) GetCurrentTexture

func (s *Surface) GetCurrentTexture() (*SurfaceTexture, bool, error)

GetCurrentTexture acquires the next texture for rendering. Returns the surface texture and whether the surface is suboptimal.

If a PrepareFrame hook is registered and reports changed dimensions, the surface is automatically reconfigured before acquiring.

func (*Surface) HAL added in v0.21.0

func (s *Surface) HAL() hal.Surface

HAL returns the underlying HAL surface for backward compatibility. Prefer using Surface methods instead of direct HAL access.

func (*Surface) Present

func (s *Surface) Present(texture *SurfaceTexture) error

Present presents a surface texture to the screen.

func (*Surface) PresentWithDamage added in v0.26.0

func (s *Surface) PresentWithDamage(texture *SurfaceTexture, damageRects []image.Rectangle) error

PresentWithDamage presents a surface texture to the screen, passing optional damage rectangles to the compositor.

damageRects specifies which regions of the surface changed this frame (physical pixels, top-left origin). When nil or empty, the entire surface is presented — identical to Present(). Backends that support damage rects (software partial blit, and in future: DX12 Present1, Vulkan VK_KHR_incremental_present, GLES eglSwapBuffersWithDamageKHR) use them as compositor hints; others accept and ignore them.

func (*Surface) Release

func (s *Surface) Release()

Release releases the surface.

func (*Surface) SetPrepareFrame added in v0.21.0

func (s *Surface) SetPrepareFrame(fn core.PrepareFrameFunc)

SetPrepareFrame registers a platform hook called before each GetCurrentTexture. If the hook returns changed=true with new dimensions, the surface is automatically reconfigured. This is the integration point for HiDPI/DPI change handling:

  • macOS Metal: read CAMetalLayer.contentsScale
  • Windows: handle WM_DPICHANGED
  • Wayland: read wl_output.scale

Pass nil to remove the hook.

func (*Surface) Unconfigure

func (s *Surface) Unconfigure()

Unconfigure removes the surface configuration.

type SurfaceCapabilities added in v0.23.0

type SurfaceCapabilities struct {
	// Formats lists the supported surface texture formats.
	Formats []gputypes.TextureFormat

	// PresentModes lists the supported presentation modes.
	PresentModes []gputypes.PresentMode

	// AlphaModes lists the supported composite alpha modes.
	AlphaModes []gputypes.CompositeAlphaMode
}

SurfaceCapabilities describes what a surface supports on this adapter.

type SurfaceConfiguration

type SurfaceConfiguration struct {
	Width       uint32
	Height      uint32
	Format      TextureFormat
	Usage       TextureUsage
	PresentMode PresentMode
	AlphaMode   CompositeAlphaMode
}

SurfaceConfiguration describes surface settings.

type SurfaceTexture

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

SurfaceTexture is a texture acquired from a surface for rendering.

func (*SurfaceTexture) CreateView

func (st *SurfaceTexture) CreateView(desc *TextureViewDescriptor) (*TextureView, error)

CreateView creates a texture view of this surface texture.

type Texture

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

Texture represents a GPU texture.

func NewTextureFromHAL added in v0.21.0

func NewTextureFromHAL(halTexture hal.Texture, device *Device, format TextureFormat) *Texture

NewTextureFromHAL creates a Texture wrapping an existing HAL texture. Used for backward compatibility and testing.

func (*Texture) Format

func (t *Texture) Format() TextureFormat

Format returns the texture format.

func (*Texture) HalTexture added in v0.21.0

func (t *Texture) HalTexture() hal.Texture

HalTexture returns the underlying HAL texture for advanced use cases. This enables interop with code that needs direct HAL access (e.g., gg GPU accelerator texture barriers and copy operations).

Returns nil if the texture has been released.

func (*Texture) Release

func (t *Texture) Release()

Release destroys the texture. The underlying HAL texture is not freed immediately — destruction is deferred until the GPU completes any submission that may reference it. This prevents use-after-free on DX12/Vulkan.

type TextureAspect

type TextureAspect = gputypes.TextureAspect

type TextureBarrier added in v0.21.0

type TextureBarrier struct {
	Texture *Texture
	Range   TextureRange
	Usage   TextureUsageTransition
}

TextureBarrier defines a texture state transition for synchronization. Required on Vulkan for layout transitions between render pass and copy operations. On Metal, GLES, and software backends this is a no-op.

type TextureDescriptor

type TextureDescriptor struct {
	Label         string
	Size          Extent3D
	MipLevelCount uint32
	SampleCount   uint32
	Dimension     TextureDimension
	Format        TextureFormat
	Usage         TextureUsage
	ViewFormats   []TextureFormat
}

TextureDescriptor describes texture creation parameters.

type TextureDimension

type TextureDimension = gputypes.TextureDimension

type TextureFormat

type TextureFormat = gputypes.TextureFormat

type TextureRange added in v0.21.0

type TextureRange struct {
	Aspect          TextureAspect
	BaseMipLevel    uint32
	MipLevelCount   uint32
	BaseArrayLayer  uint32
	ArrayLayerCount uint32
}

TextureRange specifies a range of texture subresources.

type TextureUsage

type TextureUsage = gputypes.TextureUsage

Texture types

type TextureUsageTransition added in v0.21.0

type TextureUsageTransition struct {
	OldUsage TextureUsage
	NewUsage TextureUsage
}

TextureUsageTransition defines a texture usage state transition.

type TextureView

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

TextureView represents a view into a texture.

func NewTextureViewFromHAL added in v0.21.0

func NewTextureViewFromHAL(halView hal.TextureView, device *Device) *TextureView

NewTextureViewFromHAL creates a TextureView wrapping an existing HAL texture view.

func (*TextureView) HalTextureView added in v0.21.0

func (v *TextureView) HalTextureView() hal.TextureView

HalTextureView returns the underlying HAL texture view for advanced use cases. This enables interop with code that needs direct HAL access (e.g., gg GPU accelerator surface rendering).

Returns nil if the view has been released.

func (*TextureView) Release

func (v *TextureView) Release()

Release marks the texture view for destruction. The underlying HAL TextureView (and its descriptor heap slots) is not freed immediately — it is deferred via DestroyQueue until the GPU completes any submission that may reference it. This prevents descriptor use-after-free on DX12 with maxFramesInFlight=2 (BUG-DX12-007).

type TextureViewDescriptor

type TextureViewDescriptor struct {
	Label           string
	Format          TextureFormat
	Dimension       TextureViewDimension
	Aspect          TextureAspect
	BaseMipLevel    uint32
	MipLevelCount   uint32
	BaseArrayLayer  uint32
	ArrayLayerCount uint32
}

TextureViewDescriptor describes texture view creation parameters.

type TextureViewDimension

type TextureViewDimension = gputypes.TextureViewDimension

type VertexBufferLayout

type VertexBufferLayout = gputypes.VertexBufferLayout

type VertexState

type VertexState struct {
	Module     *ShaderModule
	EntryPoint string
	Buffers    []VertexBufferLayout
}

VertexState describes the vertex shader stage.

Directories

Path Synopsis
cmd
dx12-test command
Command dx12-test is an integration test for the DX12 backend.
Command dx12-test is an integration test for the DX12 backend.
gles-test command
Command gles-test is an integration test for the Pure Go GLES backend.
Command gles-test is an integration test for the Pure Go GLES backend.
sw-test command
Command sw-test validates the software rasterizer backend.
Command sw-test validates the software rasterizer backend.
sw-triangle command
Command sw-triangle renders a red triangle on a blue background using ONLY the software rasterizer backend.
Command sw-triangle renders a red triangle on a blue background using ONLY the software rasterizer backend.
vk-gen command
Command vk-gen generates Pure Go Vulkan bindings from vk.xml specification.
Command vk-gen generates Pure Go Vulkan bindings from vk.xml specification.
vk-test command
Command vk-test is an integration test for the Pure Go Vulkan backend.
Command vk-test is an integration test for the Pure Go Vulkan backend.
vulkan-renderpass-test command
Command vulkan-renderpass-test validates the hypothesis that Intel Iris Xe driver bug is specific to VK_KHR_dynamic_rendering, not vkCreateGraphicsPipelines.
Command vulkan-renderpass-test validates the hypothesis that Intel Iris Xe driver bug is specific to VK_KHR_dynamic_rendering, not vkCreateGraphicsPipelines.
vulkan-triangle command
Command vulkan-triangle is a full integration test for the Pure Go Vulkan backend.
Command vulkan-triangle is a full integration test for the Pure Go Vulkan backend.
wgpu-triangle command
Command wgpu-triangle tests the wgpu public API rendering pipeline.
Command wgpu-triangle tests the wgpu public API rendering pipeline.
wgpu-triangle-mt command
Command wgpu-triangle tests the wgpu public API rendering pipeline.
Command wgpu-triangle tests the wgpu public API rendering pipeline.
Package core provides validation and state management for WebGPU resources.
Package core provides validation and state management for WebGPU resources.
track
Package track provides resource state tracking infrastructure.
Package track provides resource state tracking infrastructure.
examples
compute-copy command
Command compute-copy demonstrates GPU buffer copying via a compute shader.
Command compute-copy demonstrates GPU buffer copying via a compute shader.
compute-particles command
Command compute-particles demonstrates a GPU particle simulation using a compute shader.
Command compute-particles demonstrates a GPU particle simulation using a compute shader.
compute-sum command
Command compute-sum demonstrates a parallel reduction (sum) using a GPU compute shader.
Command compute-sum demonstrates a parallel reduction (sum) using a GPU compute shader.
triangle-headless command
Command triangle-headless renders a triangle to an offscreen texture and writes the result to a PNG file.
Command triangle-headless renders a triangle to an offscreen texture and writes the result to a PNG file.
hal
Package hal provides the Hardware Abstraction Layer for WebGPU implementations.
Package hal provides the Hardware Abstraction Layer for WebGPU implementations.
allbackends
Package allbackends imports all HAL backend implementations.
Package allbackends imports all HAL backend implementations.
dx12
Package dx12 provides a DirectX 12 backend for the HAL.
Package dx12 provides a DirectX 12 backend for the HAL.
dx12/d3d12
Package d3d12 provides low-level Direct3D 12 COM bindings for Windows.
Package d3d12 provides low-level Direct3D 12 COM bindings for Windows.
dx12/d3dcompile
Package d3dcompile provides Pure Go bindings to d3dcompiler_47.dll.
Package d3dcompile provides Pure Go bindings to d3dcompiler_47.dll.
dx12/dxgi
Package dxgi provides low-level DXGI (DirectX Graphics Infrastructure) COM bindings for Windows.
Package dxgi provides low-level DXGI (DirectX Graphics Infrastructure) COM bindings for Windows.
gles
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+.
gles/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.
gles/gl
Package gl provides OpenGL constants and types for the GLES backend.
Package gl provides OpenGL constants and types for the GLES backend.
gles/wgl
Package wgl provides Windows OpenGL (WGL) context management.
Package wgl provides Windows OpenGL (WGL) context management.
metal
Package metal provides a Metal backend for the HAL.
Package metal provides a Metal backend for the HAL.
noop
Package noop provides a no-operation GPU backend.
Package noop provides a no-operation GPU backend.
software
Package software provides a CPU-based software rendering backend.
Package software provides a CPU-based software rendering backend.
software/raster
Package raster provides CPU-based triangle rasterization for the software backend.
Package raster provides CPU-based triangle rasterization for the software backend.
software/shader
Package shader provides callback-based shader execution for the software backend.
Package shader provides callback-based shader execution for the software backend.
vulkan
Package vulkan provides Pure Go Vulkan backend for the HAL.
Package vulkan provides Pure Go Vulkan backend for the HAL.
vulkan/memory
Package memory provides GPU memory allocation for Vulkan backend.
Package memory provides GPU memory allocation for Vulkan backend.
vulkan/vk
Package vk provides Pure Go Vulkan bindings using goffi for FFI calls.
Package vk provides Pure Go Vulkan bindings using goffi for FFI calls.
internal
thread
Package thread provides thread abstraction for GPU operations.
Package thread provides thread abstraction for GPU operations.

Jump to

Keyboard shortcuts

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