gogpu/wgpu
Pure Go WebGPU implementation with Vulkan, DX12, and Metal backends, zero CGO (part of [GoGPU](https://github.com/gogpu) ecosystem)
About gogpu/wgpu
This large README is shown as a plain-text preview. Read the full README at the source
<h1 align="center">wgpu</h1>
<p align="center">
<strong>Unified Go WebGPU — Three Backends, One API</strong><br>
Pure Go · Rust FFI · Browser WASM — build tag selects the stack
</p>
<p align="center">
<a href="https://github.com/gogpu/wgpu/actions/workflows/ci.yml"><img src="https://github.com/gogpu/wgpu/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
<a href="https://codecov.io/gh/gogpu/wgpu"><img src="https://codecov.io/gh/gogpu/wgpu/branch/main/graph/badge.svg" alt="codecov"></a>
<a href="https://pkg.go.dev/github.com/gogpu/wgpu"><img src="https://pkg.go.dev/badge/github.com/gogpu/wgpu.svg" alt="Go Reference"></a>
<a href="https://goreportcard.com/report/github.com/gogpu/wgpu"><img src="https://goreportcard.com/badge/github.com/gogpu/wgpu" alt="Go Report Card"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"></a>
<a href="https://github.com/gogpu/wgpu/releases"><img src="https://img.shields.io/github/v/release/gogpu/wgpu" alt="Latest Release"></a>
<a href="https://github.com/gogpu/wgpu"><img src="https://img.shields.io/badge/Go-1.25+-00ADD8?logo=go" alt="Go Version"></a>
<a href="https://github.com/gogpu/wgpu"><img src="https://img.shields.io/badge/CGO-none-success" alt="Zero CGO"></a>
</p>
<p align="center">
<sub>Part of the <a href="https://github.com/gogpu">GoGPU</a> ecosystem</sub>
</p>
---
## Overview
**wgpu** is the unified Go WebGPU package with three independent implementations selected by build tags — like Chrome (Dawn) and Firefox (wgpu) implementing the same W3C spec.
### Key Features
| Category | Capabilities |
|----------|--------------|
| **Backends** | Vulkan, Metal, DirectX 12, OpenGL ES, Software, **Browser WebGPU**, **Rust FFI** |
| **Platforms** | Windows, Linux, macOS, **Browser (WASM)**, **Android/arm64 (preview)**; iOS untested |
| **API** | Follows the W3C WebGPU specification |
| **Shaders** | WGSL via gogpu/naga compiler (SPIR-V, HLSL, MSL, GLSL, DXIL) |
| **Compute** | Compute shaders and GPU→CPU readback on every native backend (software: see its known gaps below) |
| **Present** | Damage-aware presentation — compositor dirty rects |
| **Ray Tracing** | Not usable yet: HAL code only, no public API, not run on a GPU. Public inline ray queries are planned, Vulkan first ([status](docs/RAY-TRACING.md), [#369](https://github.com/gogpu/wgpu/issues/369)) |
| **Debug** | Leak detection, error scopes on every build, validation layers, DRED diagnostics (DX12), structured logging (`log/slog`) |
| **Build** | Zero CGO, simple `go build` |
---
## Installation
```bash
go get github.com/gogpu/wgpu
```
**Requirements:** Go 1.25+
**Build:**
```bash
CGO_ENABLED=0 go build
```
> **Note:** wgpu uses Pure Go FFI via [goffi](https://github.com/go-webgpu/goffi). Both `CGO_ENABLED=0` (default, zero C compiler dependency) and `CGO_ENABLED=1` (for race detector or coexistence with CGO libraries) are supported.
Android/arm64 Vulkan is a guarded preview, documented separately in
[Android Vulkan preview](docs/ANDROID.md). It is not yet a full support claim.
New surface integrations should use the explicit safe or unsafe target API
described in [Surface targets](docs/SURFACE-TARGETS.md). The original
two-`uintptr` method remains available as a compatibility adapter.
**Rust FFI backend** (optional, through wgpu-native):
```bash
go build -tags rust
```
> Requires [wgpu-native](https://github.com/gfx-rs/wgpu-native/releases) v29 binary. Set `WGPU_NATIVE_PATH` or place in system PATH. See [go-webgpu/webgpu](https://github.com/go-webgpu/webgpu) for details.
> With go-webgpu/webgpu v0.5.5, `-tags rust` is not usable for real rendering: on Linux amd64 and Intel macOS it aborts at adapter request, and on Windows vertex buffers, depth attachments and explicit bind group layouts abort or crash (see the 0.34.6 known issues in [CHANGELOG.md](CHANGELOG.md)). These are fixed in go-webgpu/webgpu's next release.
**Browser (WASM):**
```bash
GOOS=js GOARCH=wasm go build -o app.wasm .
```
> Three implementations, one API — build tags select the stack:
> | Build Tag | Implementation | Use Case |
> |-----------|---------------|----------|
> | (default) | Pure Go → core → HAL → Vulkan/Metal/DX12/GLES/Software | Zero deps, cross-compile |
> | `-tags rust` | go-webgpu/webgpu → wgpu-native v29 | wgpu-native's backends |
> | `GOOS=js` | syscall/js → Browser WebGPU | Web applications |
>
> **API consistency:** The public API compiles on all build targets. The `HAL()` accessors on `Instance`, `Adapter`, `Device` and `Surface` exist on every build and return `hal.Handles` in that build's terms — the native backend's handles, `KindWebGPU` handles behind the wgpu-native binding, or `KindBrowser` on the browser build — and a nil or released object answers the zero `Handles` (`KindUnknown`). Use `RequestAdapter` → `RequestDevice` for the standard cross-backend path.
---
## Quick Start
```go
package main
import (
"fmt"
"github.com/gogpu/wgpu" // Platform backends register automatically (ADR-083)
)
func main() {
// Create instance
instance, _ := wgpu.CreateInstance(nil)
defer instance.Release()
// Request high-performance GPU
// (or pick one explicitly: instance.EnumerateAdapters() lists every
// adapter the instance knows on the native and browser builds, each
// usable with RequestDevice; the -tags rust build has no enumeration
// until the wgpu-native binding exposes it)
adapter, _ := instance.RequestAdapter(&wgpu.RequestAdapterOptions{
PowerPreference: wgpu.PowerPreferenceHighPerformance,
})
defer adapter.Release()
// Get adapter info
// (adapter.Identity() adds hardware identity where the backend reports
// it: DeviceUUID/PCIBusID on Vulkan — NVMLString() matches nvidia-smi —
// AdapterLUID on Windows, MetalRegistryID on Metal, zero elsewhere)
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
```go
// 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.
```go
// 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)
```
```go
// 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, `ErrMapCanceled` on unmap-during-pending,
`ErrMapRangeOverlap` for overlapping `MappedRange` calls, `MAP_ALIGNMENT = 8`
validation, thread-safe concurrent `Device.Poll`.
Design follows Rust wgpu's buffer mapping model with Go-idiomatic error handling.
**Guides:** [Getting Started](docs/COMPUTE-SHADERS.md) | [Backend Differences](docs/COMPUTE-BACKENDS.md)
Features: WGSL compute shaders, storage/uniform buffers, indirect dispatch, GPU timestamp queries for render and compute passes (Vulkan, DX12 and Windows GLES; not yet on Metal), with `Queue.GetTimestampPeriod`, WebGPU-compliant `Buffer.Map` / `MapAsync` GPU→CPU readback with `context.Context` integration.
---
## Architecture
```
wgpu/
├── *.go # Public API (import "github.com/gogpu/wgpu")
├── hal/ # Public interop surface (BackendKind, Handles)
├── internal/
│ ├── 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
│ │ ├── gles/ # OpenGL 3.3+ / OpenGL ES 3.0+
│ │ ├── vulkan/ # Pure Go Vulkan backend
│ │ ├── metal/ # Metal
│ │ └── dx12/ # DirectX 12
├── examples/
│ ├── compute-copy/ # GPU buffer copy with compute shader
│ └── compute-sum/ # Parallel reduction on GPU
└── cmd/
├── raytracing-headless/ # HAL acceleration structure build, rays traced on the CPU
├── 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 `internal/core` and `internal/hal` into user-friendly types:
```
User Application
↓ import "github.com/gogpu/wgpu" ← always the same import
Root Package (public API: *Device, *Buffer, *Texture...)
↓ build tag selects implementation
├─ [default] _native.go → internal/core → internal/hal → vulkan/metal/dx12/gles/software
├─ [-tags rust] _rust.go → go-webgpu/webgpu → wgpu-native
└─ [js,wasm] _browser.go → syscall/js → Browser WebGPU
```
### Native HAL Backend Integration
For the default (Pure Go) path, importing `github.com/gogpu/wgpu` registers the
platform backends by default (ADR-083). No blank import is needed:
```go
import "github.com/gogpu/wgpu"
// Registered by default:
// - Windows: Vulkan, DX12, GLES (386, amd64, arm64)
// - Linux: Vulkan, GLES (amd64, arm64)
// - macOS: Metal (amd64, arm64; MoltenVK only with -tags wgpu_moltenvk)
// - Android: Vulkan, GLES (arm64)
```
The Pure Go software backend is **registered by default** (ADR-083, v0.35.0): no blank import is needed. It is
outside the default adapter set, so an empty `Backends` mask keeps every existing program's adapters and picks
unchanged. Select it by naming `gputypes.BackendsSoftware` in the mask; `RequestAdapterOptions.ForceFallbackAdapter`
then prefers it over other CPU adapters such as WARP and llvmpipe. `-tags wgpu_nosoftware` leaves it out of the
build.
Other GOOS/GOARCH combinations are outside the default registration set and get no backend: the backend packages are
not importable outside the module. Some of them, for example linux/386, cannot build the Pure Go backends at all
because goffi has no syscall files for that architecture.
Opt out per backend with `-tags wgpu_novulkan`, `wgpu_nodx12`, `wgpu_nometal`,
`wgpu_nogles` or `wgpu_nosoftware`. `wgpu_nosoftware` also removes the software
device from `wgputest`. On macOS, default registration covers Metal only:
Vulkan through MoltenVK is opt-in with `-tags wgpu_moltenvk`. `GOOS=ios`
satisfies the darwin tag, so iOS builds in the default set register Metal.
---
## Backend Details
### Platform Support
| Backend | Windows | Linux | macOS | iOS | Android/arm64 | Notes |
|---------|:-------:|:-----:|:-----:|:---:|:-------------:|-------|
| **Vulkan** | Yes | Yes | Untested | - | Preview | macOS through MoltenVK, not run in CI; [Android contract](docs/ANDROID.md) |
| **Metal** | - | - | Yes | Untested | - | Native Apple GPU; CI runs it on the macOS runner's virtual GPU; never run on iOS |
| **DX12** | Yes | - | - | - | - | Windows 10+ |
| **GLES** | Yes | Yes | - | - | - | OpenGL 3.3+ / OpenGL ES 3.0+ |
| **Software** | Yes | Yes | Yes | Untested | - | CPU fallback |
**Architectures:** amd64, arm64 (including Windows ARM64 / Snapdragon X)
### Vulkan Backend
Pure Go Vulkan backend 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), and Android `ANativeWindow` (preview)
- 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`, experimental, SM 6.0+, no external compiler)
- StagingBelt ring-buffer allocator that reuses staging memory for uploads
### OpenGL ES Backend
Cross-platform GPU access via OpenGL ES 3.0+:
- Pure Go EGL/GL bindings (goffi)
- 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
CPU rasterizer for headless and windowed rendering. Always compiled — no build tags or GPU hardware required.
```go
import "github.com/gogpu/wgpu"
// The software backend is registered by default. Name gputypes.BackendsSoftware
// in the instance mask to select it; with RequestAdapterOptions.ForceFallbackAdapter
// it is preferred over other CPU adapters. -tags wgpu_nosoftware leaves it out.
// Use cases:
// - CI/CD testing without GPU
// - Server-side image generation
// - Fallback when GPU unavailable
// - Embedded systems without GPU
```
**Rasterization Features:**
- Clip-space clipping, then the viewport transform (`SetViewport`, depth range)
- Edge function triangle rasterization (Pineda algorithm) with the top-left fill rule
- Perspective-correct interpolation; `@interpolate(linear)` and `flat` (first vertex)
- 2x2 quads with helper invocations for derivatives and implicit-LOD mip selection
- Depth test (all 8 compare functions)
- Stencil test (all 8 operations, front and back faces)
- Blending (13 factors without dual-source, 5 operations)
- 4-sample multisampled colour: coverage at the standard sample positions, one shade per pixel, per-sample
blending under the pipeline's sample mask, and a resolve that averages in linear (sRGB decoded and re-encoded)
- BC1-BC7 and ETC2/EAC texture sampling (`texture-compression-bc`, `texture-compression-etc2`)
- Encoded commands run at `Queue.Submit`
- **SPIR-V interpreter** — executes vertex/fragment/compute shaders on CPU. Designed for shader debugging, CI/CD testing, and GPU-less environments — **not for production rendering** (interpreted, much slower than JIT software renderers such as SwiftShader).
**Known gaps:** no ASTC; no `depth-clip-control` or `frag_depth`; multisampling is colour-only — multisampled
depth/stencil, alpha to coverage and sampling a multisampled texture are refused with an error.
**Shader memory limits:** a shader's Private variables may total 64 KiB, the Function variables of one function
64 KiB, its Workgroup variables 1 MiB, its composite and null constants 1 MiB, and any type at most `maxBufferSize`
(the WebGPU limit on workgroup storage per entry point applies as well). WebGPU sets no limit for these; they are
eight times the WGSL guarantees for Private and Function storage. What one invocation holds live may reach 256 MiB
and a compute workgroup 1 GiB. A module over them fails pipeline creation. The software backend runs raw SPIR-V
within these documented limits; it is not a sandbox for hostile SPIR-V. For untrusted shaders, use WGSL, which naga
validates.
**Debug & Testing:**
- Render pass instrumentation: HAL debug log events and `RenderPassStats` for the repository's CI end-to-end assertions
- Public `wgpu.HeadlessSurfaceTarget` + `Surface.ReadPixels()` lifecycle for deterministic headless render verification; snapshots are owned, tightly packed RGBA8
- HAL `GetFramebuffer()` remains as a compatibility alias for existing software-backend callers; new root API code should use `Surface.ReadPixels()`
- Damage-aware partial blit with pixel-level test coverage
See [Surface targets](docs/SURFACE-TARGETS.md#headless-software-surface-and-readback)
for the complete configure → acquire → render → submit → present → readback
recipe and the explicit non-WebGPU support contract.
**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:** CGImage + `setContents:` (CALayer) or Metal `nextDrawable` + `replaceRegion` (CAMetalLayer). Contributor: @k-chimi
---
## 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. |
| `GOGPU_DX12_DXIL_VALIDATE` | `1` | With `GOGPU_DX12_DXIL=1`, validate each DXIL blob with `dxil.dll` before pipeline creation and log the validator's message; a rejected blob is written to a file in the system temp directory. For debugging only. |
| `GOGPU_DX12_FORCE_HWND` | `1` | Create DX12 swap chains for the window handle even when the surface asks for premultiplied alpha, which otherwise uses DirectComposition. For tools such as RenderDoc that cannot capture through DirectComposition. |
Frequently Asked Questions
What is gogpu/wgpu?
gogpu/wgpu is a Game Development library for the Go programming language. Pure Go WebGPU implementation with Vulkan, DX12, and Metal backends, zero CGO (part of [GoGPU](https://github.com/gogpu) ecosystem)
How do I install gogpu/wgpu?
Install gogpu/wgpu with the Go module system using `go get gogpu/wgpu`. Check the repository for the current installation instructions.
What category does gogpu/wgpu belong to?
gogpu/wgpu is listed under Game Development, specifically Game Development.