gpuimage

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 12 Imported by: 0

README

go-gpuimage

go-gpuimage is an offscreen WebGPU rendering for Golang, built on gogpu/wgpu. The Go package is gpuimage.

Render into a GPU texture with your own shaders, upload and sample Go images, and read pixels back as *image.NRGBA. There is no window and no event loop. The same API builds natively and for browser WebAssembly (GOOS=js GOARCH=wasm).

The library manages the render target, texture resources, GPU execution, and readback. Shaders, pipelines, buffers, and drawing use upstream WebGPU types directly.

The current release is v0.1.0. The API may change before v1.0. DESIGN.md explains the design and compares related GoGPU libraries. VALIDATION.md records what was tested and how.

Quickstart

Install the library:

go get github.com/NimbleMarkets/go-gpuimage@v0.1.0
import (
	"github.com/gogpu/gputypes"
	"github.com/gogpu/wgpu"

	gpuimage "github.com/NimbleMarkets/go-gpuimage"
)

r, err := gpuimage.New(ctx, gpuimage.Options{Width: 640, Height: 480, Depth: true})
if err != nil { /* errors.Is(err, gpuimage.ErrNoAdapter), or device creation failed */ }
defer r.Close()

// Create pipelines, shaders, and buffers on the renderer's GPU thread.
err = r.Do(func(dev *wgpu.Device) error { /* dev.CreateRenderPipeline(...) */ return nil })

img, stats, err := r.Render(ctx, func(f *gpuimage.Frame) error {
	// f.Device.Queue().WriteBuffer(...) updates uniforms for this frame.
	pass, err := f.Encoder.BeginRenderPass(&wgpu.RenderPassDescriptor{
		ColorAttachments: []wgpu.RenderPassColorAttachment{{
			View: f.Color, LoadOp: gputypes.LoadOpClear, StoreOp: gputypes.StoreOpStore,
			ClearValue: gputypes.Color{R: 0.1, G: 0.1, B: 0.1, A: 1},
		}},
		DepthStencilAttachment: &wgpu.RenderPassDepthStencilAttachment{
			View: f.Depth, DepthLoadOp: gputypes.LoadOpClear, DepthStoreOp: gputypes.StoreOpStore,
			DepthClearValue: 1, StencilReadOnly: true, // required in the browser
		},
	})
	if err != nil { return err }
	// pass.SetPipeline(...); pass.Draw(...)
	return pass.End()
})
// img is a new *image.NRGBA that the caller owns.

Run the examples:

go run ./examples/clear -out frame.png      # clear a target and read it back
go run ./examples/texture -out texture.png  # upload, sample, update, read back

API

Call Purpose
New(ctx, Options) Create the device and the first target.
Renderer.Do(func(*wgpu.Device) error) Run setup or teardown on the GPU thread.
Renderer.Render(ctx, draw) Draw, then read the frame back in the same submission.
Renderer.RenderToTexture(ctx, draw) Draw without reading back.
Renderer.ReadPixels(ctx) Read back the most recent frame.
Renderer.Resize(w, h), Size() Replace the target. A failed resize keeps the old one.
Renderer.AdapterInfo() Adapter name, backend, and device type.
Renderer.UploadTexture(image, TextureOptions) Create a sampled texture from a Go image.
Texture.Update, ReadPixels, Size, Close Replace pixels in place, copy them back, release.
Texture.BindGroup(), BindGroupLayout() Handles for the caller's pipeline.
Renderer.Close() Release everything, including textures still open.

Frame gives the draw callback Device, Encoder, Color, Depth, Width, Height, and Seq. Stats reports Draw, Submit, Map, Copy, and Total durations for a frame.

Pixels and alpha

  • Targets and textures are RGBA8Unorm. Colors are not converted between color spaces.
  • Readback returns the target's bytes as image.NRGBA. If a shader writes premultiplied color, un-premultiply before treating the image as straight alpha. Opaque output needs no conversion.
  • UploadTexture accepts any image.Image, including sub-images and padded strides, and stores straight alpha. Linear filtering of straight alpha darkens edges next to transparent texels; use an opaque image, nearest filtering, or a padded atlas where that matters.
  • GoGPU's gogpu and gg libraries use premultiplied alpha. Convert when exchanging images with them.

Sampled images

tile, err := r.UploadTexture(sourceImage, gpuimage.TextureOptions{})
if err != nil { /* handle error */ }
defer tile.Close()

// Include tile.BindGroupLayout() in your pipeline layout. In WGSL:
// @group(0) @binding(0) var tileTexture: texture_2d<f32>;
// @group(0) @binding(1) var tileSampler: sampler;
// Inside a draw callback, bind tile.BindGroup() at that group index.

err = tile.Update(nextImage)         // same dimensions; the bind group stays valid
pixels, err := tile.ReadPixels(ctx)  // optional CPU copy of the texture

TextureOptions{Filter: gputypes.FilterModeNearest} selects nearest filtering. The zero value selects linear. UVs clamp at the edges.

Threading and ownership

  • Each Renderer owns its instance, adapter, device, target, and textures, and releases them in Close. Calls that need the device return ErrClosed after it closes.
  • All GPU work runs on one goroutine pinned to an OS thread. Calls from any goroutine are serialized, with one frame in flight.
  • Do not call methods that queue GPU work from inside Do or a draw callback. They would wait for the thread they already occupy. Texture handle accessors such as BindGroup and BindGroupLayout are safe to use in callbacks.
  • Objects you create with the device are yours. Release them inside Do before Close.
  • Do not keep the device, encoder, or views from a callback for use on another goroutine.
  • Sharing a device owned by another library is not supported yet. DESIGN.md describes a possible API.

Cancellation

Render, RenderToTexture, and both ReadPixels methods take a context.

  • A call waiting for the GPU thread returns ctx.Err() when the context is cancelled or expires, without drawing.
  • Cancellation during the draw callback or while the GPU finishes the frame also returns ctx.Err(). A running draw callback is not interrupted.
  • After cancellation the GPU may still complete the abandoned frame. Later calls are unaffected.
  • On Metal, a cancellable context added about 0.1 ms per readback in testing, because the wait must poll. context.Background() uses a single blocking wait.
  • With a cancellable context, native RenderToTexture returns once the frame is submitted instead of waiting for the GPU.
  • Do, Resize, UploadTexture, Update, and Close take no context and wait their turn.

Browser

  • Requires a WebGPU-capable browser in a secure context (HTTPS or localhost).
  • Call the library from a Go goroutine, not from inside a JavaScript callback. Readback awaits a promise, which would deadlock the event loop.
  • While a readback is pending, the library requests animation frames so that the browser settles the map promptly.
  • Set StencilReadOnly: true when attaching Frame.Depth. The browser backend otherwise emits stencil operations, which WebGPU rejects for a depth-only format.
  • AdapterInfo cannot identify a software adapter in the browser. Upstream reports every browser adapter as "WebGPU Adapter".

Testing

With Task installed, task list shows every task.

Task Runs Needs
task Race tests and builds of examples, the browser runner, and WASM Nothing
task ci Everything CI runs: race tests, vet, WASM build, Node tests Node
task test-gpu The full suite on a native adapter A GPU
task bench Clear and readback benchmarks, three runs per case A GPU
task test-browser The full suite in headless Chrome Chrome with WebGPU
task validate ci, test-gpu, and test-browser All of the above
task test-vulkan The full suite on Vulkan under the validation layer Linux with Vulkan
task test-vulkan-remote HOST=name Copies the tree to name over ssh and runs test-vulkan there ssh access
task run-examples Both examples, writing PNG files to bin/ A GPU

The same commands without Task:

go test -race ./...                   # helpers and executor, no GPU
GPUIMAGE_GPU_TEST=1 go test ./...     # real native adapter; never with -race

# Helper tests under Node, which has no WebGPU:
GOOS=js GOARCH=wasm go test -exec="$(go env GOROOT)/lib/wasm/go_js_wasm_exec" .

# The full suite in headless Chrome with WebGPU:
go build -o /tmp/browsertest ./internal/browsertest
GPUIMAGE_GPU_TEST=1 GOOS=js GOARCH=wasm go test -exec=/tmp/browsertest -v .

GPU tests log the adapter they ran on. A run on a CPU or fallback adapter does not test hardware GPU behavior.

Benchmarks

BenchmarkRenderReadback measures one complete frame: clear an RGBA8 color target, submit it, wait for the GPU, and copy the pixels into a new image.NRGBA. It includes allocation and garbage collection during the loop. Device creation, ten warmup frames, context creation, and cleanup are outside the timer. It does not draw geometry, upload textures, or use a depth attachment.

Each size runs with context.Background() and with one reused cancellable context that is never cancelled. This measures the cost of checking for cancellation, not the cost of cancelling a frame.

task bench                            # choose the default native backend
task bench BACKEND=metal               # macOS
task bench BACKEND=vulkan              # Linux
task bench BENCHTIME=3s COUNT=5         # longer runs

# Without Task (set GPUIMAGE_BENCH_BACKEND=metal or vulkan to choose):
GPUIMAGE_GPU_TEST=1 go test -run='^$' -bench=BenchmarkRenderReadback \
  -benchmem -benchtime=1s -count=3 .

Run without the race detector or Vulkan validation layers. The benchmark logs the adapter and rejects software adapters. MB/s is the output image size divided by frame time; it is not a measurement of GPU bus bandwidth. Allocation counts cover Go memory, not GPU memory.

Results from 2026-09-27, using wgpu v0.34.5 and naga v0.19.0. Each value is the median of three runs with -benchtime=1s. Lower is better.

Frame size Context Apple M3 Max / Metal NVIDIA GB10 / Vulkan
640x400 Background 0.587 ms 0.480 ms
640x400 Cancellable 0.645 ms 0.684 ms
1280x720 Background 0.657 ms 0.768 ms
1280x720 Cancellable 0.758 ms 0.938 ms
1920x1080 Background 0.820 ms 1.077 ms
1920x1080 Cancellable 0.954 ms 1.199 ms

The Metal run used macOS 27.0 arm64 and Go 1.27.1. The Vulkan run used Ubuntu 24.04.5 arm64, Go 1.26.8, and NVIDIA driver 580.178.04. Vulkan used VK_DRIVER_FILES=/usr/share/vulkan/icd.d/nvidia_icd.json to select the NVIDIA driver. These numbers compare complete systems, including CPU, driver, and Go runtime costs.

Raw output, including throughput and allocations: Metal and Vulkan.

Known limitations

  • naga v0.19.0 generates invalid Metal source for arithmetic on a component of an indexed let or const array, such as positions[i].x * 0.5. List the values explicitly, as the examples do. TestDerivedUVShader reports when upstream fixes this.
  • The color target cannot be sampled by a later pass. It has no TextureBinding usage.
  • No mipmaps, MSAA, sRGB formats, or partial texture updates.
  • Metal, Vulkan on one NVIDIA adapter, and Chrome were run. DX12, GLES, and other browsers compile but were not tested.
  • ReadPixels fails until a frame has been drawn to the current target.

Open Collaboration

We welcome contributions and feedback. Please adhere to our Code of Conduct when engaging our community.

Acknowledgements

Thanks to the GoGPU organization for their dedication to making GPU processing available to Golang developers, especially in the form of the wgpu WebGPU library.

License

This project is released under the MIT License, see LICENSE.txt.

Copyright (c) 2026 Neomantra Corp.


Made with ❤ and 🔥 by the team behind Nimble.Markets.

Documentation

Overview

Package gpuimage provides offscreen WebGPU rendering, texture upload and sampling, and optional pixel readback into Go images. It uses gogpu/wgpu's native and browser backends and exposes upstream types for custom drawing.

Pixels

Targets and textures are RGBA8Unorm without color-space conversion. Readback returns the target's bytes as image.NRGBA, so a shader that writes premultiplied color must be un-premultiplied by the caller. Uploads store straight (non-premultiplied) alpha.

Threading

A Renderer owns one goroutine pinned to an OS thread. Every GPU call — device creation, target allocation, the caller's draw callback, the copy, the map, and all releases — runs on that goroutine. Use Renderer.Do to run pipeline and buffer setup on it, and Frame.Device inside a draw callback.

gogpu/wgpu documents devices as safe for concurrent use and command encoders as not. The single thread is this package's choice: it keeps one frame in flight, keeps the wait for a mapped buffer on the thread that submitted the work, and gives thread-bound backends such as GLES a stable thread. Code that receives the device must not retain it for use on other goroutines.

Browser

On GOOS=js the map step awaits a JavaScript promise, which is fine from any Go goroutine except one that is itself running inside a JS callback (that would deadlock the event loop). Start rendering from a Go goroutine.

When attaching Frame.Depth (a depth-only Depth24Plus view) to a render pass, set StencilReadOnly: true on the RenderPassDepthStencilAttachment. gogpu's browser backend otherwise emits stencilLoadOp/stencilStoreOp, which WebGPU rejects for a format with no stencil aspect; native backends ignore the flag for a depth-only attachment.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("gpuimage: renderer closed")

ErrClosed is returned by every Renderer method after Close.

View Source
var ErrNoAdapter = errors.New("gpuimage: no GPU adapter available")

ErrNoAdapter is returned by New when the instance reports no GPU adapter.

Functions

This section is empty.

Types

type Error

type Error struct {
	Op  string
	Err error
}

Error wraps a gogpu/wgpu failure with the step that produced it.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Frame

type Frame struct {
	Device  *wgpu.Device // the renderer's device, for queue writes and resource updates
	Encoder *wgpu.CommandEncoder
	Color   *wgpu.TextureView // RGBA8Unorm, RenderAttachment|CopySrc
	Depth   *wgpu.TextureView // nil unless Options.Depth
	Width   int
	Height  int
	Seq     uint64 // frame sequence number, starting at 1
}

Frame is handed to the draw callback of Render. Record render passes into Encoder against Color (and Depth when allocated); the Renderer appends the readback copy and submits Encoder once the callback returns. Every field is valid only until the callback returns.

type Options

type Options struct {
	Width, Height int    // initial target size in pixels; both must be > 0
	Depth         bool   // allocate a Depth24Plus attachment alongside the color target
	Label         string // optional prefix for GPU object labels

	// Backends restricts native backend selection. Zero means all.
	Backends gputypes.Backends
	// PowerPreference is forwarded to RequestAdapter.
	PowerPreference gputypes.PowerPreference
	// ForceFallback requests the software (CPU) adapter. Useful for
	// deterministic tests; ignored where no such adapter exists.
	ForceFallback bool
}

Options configures a Renderer at construction.

type Renderer

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

Renderer owns a GPU device and an offscreen render target, and reads frames back as *image.NRGBA. All GPU work runs on an internal executor goroutine pinned to one OS thread. Renderer is safe for concurrent use; calls are serialized. Its methods must not be called from inside Do or a draw callback, which already occupy the executor.

func New

func New(ctx context.Context, opts Options) (*Renderer, error)

New creates the instance, adapter, device, and an initial target of opts.Width×opts.Height. Everything created so far is released on failure.

func (*Renderer) AdapterInfo

func (r *Renderer) AdapterInfo() gputypes.AdapterInfo

AdapterInfo reports immutable adapter metadata: its name, backend, and device type. A DeviceTypeCPU adapter is wgpu's software rasterizer.

func (*Renderer) Close

func (r *Renderer) Close() error

Close releases every GPU object and stops the executor. Idempotent.

func (*Renderer) Do

func (r *Renderer) Do(f func(dev *wgpu.Device) error) error

Do runs f on the executor thread with the device. Use it for pipeline, shader, and buffer setup so those calls obey the single-thread rule.

func (*Renderer) ReadPixels

func (r *Renderer) ReadPixels(ctx context.Context) (*image.NRGBA, Stats, error)

ReadPixels explicitly copies and maps the current color attachment into a caller-owned Go image. Call after drawing; Render combines both steps in one submission. Concurrent callers read the most recently submitted frame. It fails if nothing was drawn since New or the last Resize.

func (*Renderer) Render

func (r *Renderer) Render(ctx context.Context, draw func(*Frame) error) (*image.NRGBA, Stats, error)

Render runs draw against a fresh command encoder, appends the readback copy, submits, maps the staging buffer, and returns a new NRGBA image that the caller owns. One frame is in flight at a time.

Render returns ctx.Err() if ctx ends while the call waits for the GPU thread, during draw, or while the GPU finishes the frame. It does not interrupt a running draw callback. After a cancellation the GPU may still complete the abandoned frame; later calls are unaffected. Watching a context that can end adds about a tenth of a millisecond to a native readback.

func (*Renderer) RenderToTexture

func (r *Renderer) RenderToTexture(ctx context.Context, draw func(*Frame) error) (Stats, error)

RenderToTexture draws and submits without copying pixels to Go, for callers that read back only some frames. The color attachment keeps the frame until the next draw or Resize, and ReadPixels copies it on request. The attachment cannot be sampled: it has no TextureBinding usage.

Native submission waits for the GPU when ctx cannot end, such as context.Background. Otherwise, and always in the browser, it returns once the frame is submitted.

func (*Renderer) Resize

func (r *Renderer) Resize(w, h int) error

Resize replaces the color/depth textures and the staging buffer. It is a no-op when the size is unchanged, and on failure the old target is kept.

func (*Renderer) Size

func (r *Renderer) Size() (w, h int)

Size reports the current target size in pixels.

func (*Renderer) UploadTexture

func (r *Renderer) UploadTexture(src image.Image, opts TextureOptions) (*Texture, error)

UploadTexture copies an image into a sampled GPU texture. The source image can have any bounds or image.Image implementation; pixels are copied before this method returns. Close the Texture when it is no longer needed, or let Renderer.Close release it with the device.

type Stats

type Stats struct {
	Seq         uint64
	Draw        time.Duration // the caller's draw callback
	Submit      time.Duration // copy encode + queue submit
	Map         time.Duration // staging-buffer map wait (GPU sync)
	Copy        time.Duration // de-pad into the NRGBA image
	Total       time.Duration
	BytesPerRow int // padded staging row stride
}

Stats reports where one Render spent its time.

type Texture

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

Texture is an RGBA8 image owned by a Renderer. It can be sampled in a draw callback, updated without reallocating, or copied back to Go pixels. Binding 0 is texture_2d<f32>; binding 1 is a filtering sampler. UVs clamp at the edges.

func (*Texture) BindGroup

func (t *Texture) BindGroup() *wgpu.BindGroup

func (*Texture) BindGroupLayout

func (t *Texture) BindGroupLayout() *wgpu.BindGroupLayout

BindGroupLayout is the layout to include in a caller's pipeline layout. Use BindGroup at the matching group index inside Renderer.Render/Do. These raw GPU handles are valid only while the Texture and Renderer are open.

func (*Texture) Close

func (t *Texture) Close() error

Close releases this texture's GPU resources. It is safe to call more than once; Renderer.Close also releases any textures left open.

func (*Texture) ReadPixels

func (t *Texture) ReadPixels(ctx context.Context) (*image.NRGBA, error)

ReadPixels returns a fresh, tightly packed NRGBA copy of this texture. It synchronizes with pending GPU work; use it only when a CPU consumer needs the pixels. Sampling this texture in a render pass does not require readback.

func (*Texture) Size

func (t *Texture) Size() (int, int)

Size returns the immutable texture dimensions in pixels.

func (*Texture) Update

func (t *Texture) Update(src image.Image) error

Update replaces all pixels without changing the texture or its bind group. Image dimensions must match the original upload.

type TextureOptions

type TextureOptions struct {
	Filter gputypes.FilterMode
}

TextureOptions controls the sampling filter. Zero selects linear filtering. Nearest filtering is useful for pixel art or an atlas without padded tiles.

Directories

Path Synopsis
examples
clear command
Clear renders a solid color offscreen and writes the pixels as a PNG.
Clear renders a solid color offscreen and writes the pixels as a PNG.
texture command
Texture uploads a Go image, samples it in a custom shader, updates it, and writes both rendered frames as PNG files.
Texture uploads a Go image, samples it in a custom shader, updates it, and writes both rendered frames as PNG files.
internal
browsertest command
Command browsertest runs a GOOS=js GOARCH=wasm test binary in headless Chrome so tests can reach a real browser WebGPU device.
Command browsertest runs a GOOS=js GOARCH=wasm test binary in headless Chrome so tests can reach a real browser WebGPU device.

Jump to

Keyboard shortcuts

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