wgpu

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package wgpu provides Zero-CGO WebGPU bindings for Go.

This package wraps wgpu-native (Rust WebGPU implementation) using pure Go FFI via syscall on Windows and dlopen on Unix. No CGO is required.

Quick Start

// Initialize the library
if err := wgpu.Init(); err != nil {
    log.Fatal(err)
}

// Create instance
instance, err := wgpu.CreateInstance(nil)
if err != nil {
    log.Fatal(err)
}
defer instance.Release()

// Request adapter (GPU)
adapter, err := instance.RequestAdapter(nil)
if err != nil {
    log.Fatal(err)
}
defer adapter.Release()

// Request device
device, err := adapter.RequestDevice(nil)
if err != nil {
    log.Fatal(err)
}
defer device.Release()

Core Objects

The WebGPU API is structured around several core object types:

Resource Management

All WebGPU objects must be released when no longer needed:

buffer := device.CreateBuffer(&wgpu.BufferDescriptor{...})
defer buffer.Release()

Render Pipeline

A typical render pipeline setup:

// Create shader module
shader := device.CreateShaderModuleWGSL(shaderCode)
defer shader.Release()

// Create render pipeline
pipeline := device.CreateRenderPipeline(&wgpu.RenderPipelineDescriptor{
    Vertex: wgpu.VertexState{
        Module:     vsModule,
        EntryPoint: "main",
        Buffers:    []wgpu.VertexBufferLayout{vertexBufferLayout},
    },
    Fragment: &wgpu.FragmentState{
        Module:     fsModule,
        EntryPoint: "main",
        Targets:    []wgpu.ColorTargetState{{Format: format, WriteMask: wgpu.ColorWriteMaskAll}},
    },
    // ... other configuration
})
defer pipeline.Release()

Compute Pipeline

For GPU compute operations:

pipeline := device.CreateComputePipelineSimple(nil, shader, "main")
defer pipeline.Release()

// Dispatch compute work
computePass := encoder.BeginComputePass(nil)
computePass.SetPipeline(pipeline)
computePass.SetBindGroup(0, bindGroup, nil)
computePass.DispatchWorkgroups(workgroupCount, 1, 1)
computePass.End()

Indirect Drawing

GPU-driven rendering using indirect buffers:

// Create indirect buffer with draw args
args := wgpu.DrawIndirectArgs{
    VertexCount:   3,
    InstanceCount: 100,
}
// Write to buffer...

// Draw using GPU-specified parameters
renderPass.DrawIndirect(indirectBuffer, 0)

RenderBundle

Pre-record render commands for efficient replay:

bundleEncoder := device.CreateRenderBundleEncoderSimple(
    []wgpu.TextureFormat{surfaceFormat},
    wgpu.TextureFormatUndefined,
    1,
)
bundleEncoder.SetPipeline(pipeline)
bundleEncoder.Draw(3, 1, 0, 0)
bundle := bundleEncoder.Finish(nil)
defer bundle.Release()

// Later, in a render pass:
renderPass.ExecuteBundles([]*wgpu.RenderBundle{bundle})

Platform Support

Supported platforms:

  • Windows (x64) - uses syscall.LazyDLL
  • Linux (x64, arm64) - uses goffi/dlopen
  • macOS (x64, arm64) - uses goffi/dlopen

Dependencies

This package requires wgpu-native library:

  • Windows: wgpu_native.dll
  • Linux: libwgpu_native.so
  • macOS: libwgpu_native.dylib

Download from: https://github.com/gfx-rs/wgpu-native/releases

Package wgpu provides cross-platform library loading abstractions.

Package wgpu provides WebGPU bindings for Go. This file contains 3D math helpers optimized for WebGPU/WGSL compatibility.

Package wgpu provides Go bindings to wgpu-native WebGPU implementation.

This package uses cross-platform FFI for calling wgpu-native library. On Windows: syscall.LazyDLL is used directly. On Linux/macOS: goffi is used for dynamic library loading. For callbacks, goffi's NewCallback is used on all platforms. No C compiler required for building or running.

Index

Examples

Constants

View Source
const DepthSliceUndefined uint32 = 0xFFFFFFFF

DepthSliceUndefined is used for 2D textures in color attachments.

View Source
const TimestampLocationUndefined uint32 = 0xFFFFFFFF

TimestampLocationUndefined indicates no timestamp write at this location.

Variables

View Source
var (
	ErrSurfaceNeedsReconfigure = errors.New("wgpu: surface needs reconfigure")
	ErrSurfaceLost             = errors.New("wgpu: surface lost")
	ErrSurfaceTimeout          = errors.New("wgpu: surface texture timeout")
	ErrSurfaceOutOfMemory      = errors.New("wgpu: out of memory")
	ErrSurfaceDeviceLost       = errors.New("wgpu: device lost")
)

Error values for surface operations.

Functions

func Init

func Init() error

Init initializes the wgpu library. Called automatically on first use. Can be called explicitly to check for initialization errors early.

Types

type Adapter

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

Adapter represents a WebGPU adapter (GPU).

func (*Adapter) EnumerateFeatures

func (a *Adapter) EnumerateFeatures() []FeatureName

EnumerateFeatures retrieves all features supported by this adapter. Returns a slice of FeatureName values.

func (*Adapter) GetInfo

func (a *Adapter) GetInfo() (*AdapterInfoGo, error)

GetInfo retrieves information about this adapter. The returned AdapterInfoGo contains Go strings copied from C memory. Returns nil if the adapter is nil or if the operation fails.

func (*Adapter) GetLimits

func (a *Adapter) GetLimits() (*SupportedLimits, error)

GetLimits retrieves the limits of this adapter. Returns nil if the adapter is nil or if the operation fails.

func (*Adapter) Handle

func (a *Adapter) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Adapter) HasFeature

func (a *Adapter) HasFeature(feature FeatureName) bool

HasFeature checks if the adapter supports a specific feature.

func (*Adapter) Release

func (a *Adapter) Release()

Release releases the adapter resources.

func (*Adapter) RequestDevice

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

RequestDevice requests a GPU device from the adapter. This is a synchronous wrapper that blocks until the device is available.

type AdapterInfo

type AdapterInfo struct {
	NextInChain  uintptr // *ChainedStructOut
	Vendor       StringView
	Architecture StringView
	Device       StringView
	Description  StringView
	BackendType  BackendType
	AdapterType  AdapterType
	VendorID     uint32
	DeviceID     uint32
}

AdapterInfo contains information about the adapter.

type AdapterInfoGo

type AdapterInfoGo struct {
	Vendor       string
	Architecture string
	Device       string
	Description  string
	BackendType  BackendType
	AdapterType  AdapterType
	VendorID     uint32
	DeviceID     uint32
}

AdapterInfoGo is the Go-friendly version of AdapterInfo with actual strings.

type AdapterType

type AdapterType uint32

AdapterType describes the type of GPU adapter.

const (
	AdapterTypeDiscreteGPU   AdapterType = 0x00000001
	AdapterTypeIntegratedGPU AdapterType = 0x00000002
	AdapterTypeCPU           AdapterType = 0x00000003
	AdapterTypeUnknown       AdapterType = 0x00000004
)

type AddressMode

type AddressMode uint32

AddressMode determines how texture coordinates outside [0, 1] are handled.

const (
	AddressModeUndefined    AddressMode = 0x00
	AddressModeClampToEdge  AddressMode = 0x01
	AddressModeRepeat       AddressMode = 0x02
	AddressModeMirrorRepeat AddressMode = 0x03
)

type BackendType

type BackendType uint32

BackendType describes the graphics backend being used.

const (
	BackendTypeUndefined BackendType = 0x00000000
	BackendTypeNull      BackendType = 0x00000001
	BackendTypeWebGPU    BackendType = 0x00000002
	BackendTypeD3D11     BackendType = 0x00000003
	BackendTypeD3D12     BackendType = 0x00000004
	BackendTypeMetal     BackendType = 0x00000005
	BackendTypeVulkan    BackendType = 0x00000006
	BackendTypeOpenGL    BackendType = 0x00000007
	BackendTypeOpenGLES  BackendType = 0x00000008
)

type BindGroup

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

BindGroup represents a bind group.

func (*BindGroup) Handle

func (bg *BindGroup) Handle() uintptr

Handle returns the underlying handle.

func (*BindGroup) Release

func (bg *BindGroup) Release()

Release releases the bind group.

type BindGroupDescriptor

type BindGroupDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
	Layout      uintptr // WGPUBindGroupLayout
	EntryCount  uintptr // size_t
	Entries     uintptr // *BindGroupEntry
}

BindGroupDescriptor describes a bind group.

type BindGroupEntry

type BindGroupEntry struct {
	NextInChain uintptr // *ChainedStruct
	Binding     uint32
	Buffer      uintptr // WGPUBuffer (nullable)
	Offset      uint64
	Size        uint64
	Sampler     uintptr // WGPUSampler (nullable)
	TextureView uintptr // WGPUTextureView (nullable)
}

BindGroupEntry describes a single binding in a bind group.

func BufferBindingEntry

func BufferBindingEntry(binding uint32, buffer *Buffer, offset, size uint64) BindGroupEntry

BufferBindingEntry creates a BindGroupEntry for a buffer.

func SamplerBindingEntry

func SamplerBindingEntry(binding uint32, sampler *Sampler) BindGroupEntry

SamplerBindingEntry creates a BindGroupEntry for a sampler.

func TextureBindingEntry

func TextureBindingEntry(binding uint32, textureView *TextureView) BindGroupEntry

TextureBindingEntry creates a BindGroupEntry for a texture view.

type BindGroupLayout

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

BindGroupLayout represents a bind group layout.

func (*BindGroupLayout) Handle

func (bgl *BindGroupLayout) Handle() uintptr

Handle returns the underlying handle.

func (*BindGroupLayout) Release

func (bgl *BindGroupLayout) Release()

Release releases the bind group layout.

type BindGroupLayoutDescriptor

type BindGroupLayoutDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
	EntryCount  uintptr // size_t
	Entries     uintptr // *BindGroupLayoutEntry
}

BindGroupLayoutDescriptor describes a bind group layout.

type BindGroupLayoutEntry

type BindGroupLayoutEntry struct {
	NextInChain    uintptr // *ChainedStruct
	Binding        uint32
	Visibility     ShaderStage
	Buffer         BufferBindingLayout
	Sampler        SamplerBindingLayout
	Texture        TextureBindingLayout
	StorageTexture StorageTextureBindingLayout
}

BindGroupLayoutEntry describes a single binding in a bind group layout.

type BlendComponent

type BlendComponent struct {
	Operation BlendOperation
	SrcFactor BlendFactor
	DstFactor BlendFactor
}

BlendComponent describes blend state for a color component.

type BlendFactor

type BlendFactor uint32

BlendFactor describes a blend factor.

const (
	BlendFactorUndefined         BlendFactor = 0x00
	BlendFactorZero              BlendFactor = 0x01
	BlendFactorOne               BlendFactor = 0x02
	BlendFactorSrc               BlendFactor = 0x03
	BlendFactorOneMinusSrc       BlendFactor = 0x04
	BlendFactorSrcAlpha          BlendFactor = 0x05
	BlendFactorOneMinusSrcAlpha  BlendFactor = 0x06
	BlendFactorDst               BlendFactor = 0x07
	BlendFactorOneMinusDst       BlendFactor = 0x08
	BlendFactorDstAlpha          BlendFactor = 0x09
	BlendFactorOneMinusDstAlpha  BlendFactor = 0x0A
	BlendFactorSrcAlphaSaturated BlendFactor = 0x0B
	BlendFactorConstant          BlendFactor = 0x0C
	BlendFactorOneMinusConstant  BlendFactor = 0x0D
	BlendFactorSrc1              BlendFactor = 0x0E
	BlendFactorOneMinusSrc1      BlendFactor = 0x0F
	BlendFactorSrc1Alpha         BlendFactor = 0x10
	BlendFactorOneMinusSrc1Alpha BlendFactor = 0x11
)

type BlendOperation

type BlendOperation uint32

BlendOperation describes a blend operation.

const (
	BlendOperationUndefined       BlendOperation = 0x00
	BlendOperationAdd             BlendOperation = 0x01
	BlendOperationSubtract        BlendOperation = 0x02
	BlendOperationReverseSubtract BlendOperation = 0x03
	BlendOperationMin             BlendOperation = 0x04
	BlendOperationMax             BlendOperation = 0x05
)

type BlendState

type BlendState struct {
	Color BlendComponent
	Alpha BlendComponent
}

BlendState describes how colors are blended.

type Bool

type Bool uint32

Bool is a WebGPU boolean (uint32).

const (
	False Bool = 0
	True  Bool = 1
)

type Buffer

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

Buffer represents a WebGPU buffer.

func (*Buffer) Destroy

func (b *Buffer) Destroy()

Destroy destroys the buffer, making it invalid.

func (*Buffer) GetMapState

func (b *Buffer) GetMapState() BufferMapState

GetMapState returns the current mapping state of this buffer.

func (*Buffer) GetMappedRange

func (b *Buffer) GetMappedRange(offset, size uint64) unsafe.Pointer

GetMappedRange returns a pointer to the mapped buffer data. The buffer must be mapped (either via MapAsync or MappedAtCreation). offset and size specify the range to access. Returns nil if the buffer is not mapped or the range is invalid.

func (*Buffer) GetSize

func (b *Buffer) GetSize() uint64

GetSize returns the size of the buffer in bytes.

func (*Buffer) GetUsage

func (b *Buffer) GetUsage() BufferUsage

GetUsage returns the usage flags of this buffer.

func (*Buffer) Handle

func (b *Buffer) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Buffer) MapAsync

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

MapAsync maps a buffer for reading or writing. This is a synchronous wrapper that blocks until the mapping is complete. The device parameter is used to poll for completion. After MapAsync succeeds, use GetMappedRange to access the data. Call Unmap when done to release the mapping.

func (*Buffer) Release

func (b *Buffer) Release()

Release releases the buffer reference.

func (*Buffer) Unmap

func (b *Buffer) Unmap()

Unmap unmaps the buffer, making the mapped memory inaccessible. For buffers created with MappedAtCreation, this commits the data to the GPU.

type BufferBindingLayout

type BufferBindingLayout struct {
	NextInChain      uintptr // *ChainedStruct
	Type             BufferBindingType
	HasDynamicOffset Bool
	MinBindingSize   uint64
}

BufferBindingLayout describes buffer binding properties.

type BufferBindingType

type BufferBindingType uint32

BufferBindingType describes how a buffer is bound.

const (
	BufferBindingTypeBindingNotUsed  BufferBindingType = 0x00000000
	BufferBindingTypeUndefined       BufferBindingType = 0x00000001
	BufferBindingTypeUniform         BufferBindingType = 0x00000002
	BufferBindingTypeStorage         BufferBindingType = 0x00000003
	BufferBindingTypeReadOnlyStorage BufferBindingType = 0x00000004
)

type BufferDescriptor

type BufferDescriptor struct {
	NextInChain      uintptr     // *ChainedStruct
	Label            StringView  // Buffer label for debugging
	Usage            BufferUsage // How the buffer will be used
	Size             uint64      // Size in bytes
	MappedAtCreation Bool        // If true, buffer is mapped when created
}

BufferDescriptor describes a buffer to create.

type BufferMapCallbackInfo

type BufferMapCallbackInfo struct {
	NextInChain uintptr // *ChainedStruct
	Mode        CallbackMode
	Callback    uintptr // Function pointer
	Userdata1   uintptr
	Userdata2   uintptr
}

BufferMapCallbackInfo holds callback configuration for MapAsync.

type BufferMapState

type BufferMapState uint32

BufferMapState describes the mapping state of a buffer.

const (
	BufferMapStateUnmapped BufferMapState = 0x00000001
	BufferMapStatePending  BufferMapState = 0x00000002
	BufferMapStateMapped   BufferMapState = 0x00000003
)

type BufferUsage

type BufferUsage uint64

BufferUsage describes how a buffer will be used.

const (
	BufferUsageNone         BufferUsage = 0x0000000000000000
	BufferUsageMapRead      BufferUsage = 0x0000000000000001
	BufferUsageMapWrite     BufferUsage = 0x0000000000000002
	BufferUsageCopySrc      BufferUsage = 0x0000000000000004
	BufferUsageCopyDst      BufferUsage = 0x0000000000000008
	BufferUsageIndex        BufferUsage = 0x0000000000000010
	BufferUsageVertex       BufferUsage = 0x0000000000000020
	BufferUsageUniform      BufferUsage = 0x0000000000000040
	BufferUsageStorage      BufferUsage = 0x0000000000000080
	BufferUsageIndirect     BufferUsage = 0x0000000000000100
	BufferUsageQueryResolve BufferUsage = 0x0000000000000200
)

type CallbackMode

type CallbackMode uint32

CallbackMode controls how callbacks are fired.

const (
	CallbackModeWaitAnyOnly        CallbackMode = 0x00000001
	CallbackModeAllowProcessEvents CallbackMode = 0x00000002
	CallbackModeAllowSpontaneous   CallbackMode = 0x00000003
)

type ChainedStruct

type ChainedStruct struct {
	Next  uintptr // *ChainedStruct
	SType uint32
}

ChainedStruct is used for struct chaining (input).

type ChainedStructOut

type ChainedStructOut struct {
	Next  uintptr // *ChainedStructOut
	SType uint32
}

ChainedStructOut is used for struct chaining (output).

type Color

type Color struct {
	R, G, B, A float64
}

Color represents RGBA color with double precision.

type ColorTargetState

type ColorTargetState struct {
	Format    TextureFormat
	Blend     *BlendState // nil for no blending
	WriteMask ColorWriteMask
}

ColorTargetState describes a render target in a render pipeline.

type ColorWriteMask

type ColorWriteMask uint32

ColorWriteMask describes which color channels to write.

const (
	ColorWriteMaskNone  ColorWriteMask = 0x00
	ColorWriteMaskRed   ColorWriteMask = 0x01
	ColorWriteMaskGreen ColorWriteMask = 0x02
	ColorWriteMaskBlue  ColorWriteMask = 0x04
	ColorWriteMaskAlpha ColorWriteMask = 0x08
	ColorWriteMaskAll   ColorWriteMask = 0x0F
)

type CommandBuffer

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

CommandBuffer represents an encoded command buffer.

func (*CommandBuffer) Handle

func (cb *CommandBuffer) Handle() uintptr

Handle returns the underlying handle.

func (*CommandBuffer) Release

func (cb *CommandBuffer) Release()

Release releases the command buffer.

type CommandBufferDescriptor

type CommandBufferDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
}

CommandBufferDescriptor describes a command buffer.

type CommandEncoder

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

CommandEncoder represents a command encoder.

func (*CommandEncoder) BeginComputePass

func (enc *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) *ComputePassEncoder

BeginComputePass begins a compute pass.

func (*CommandEncoder) BeginRenderPass

func (enc *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) *RenderPassEncoder

BeginRenderPass begins a render pass.

func (*CommandEncoder) ClearBuffer

func (enc *CommandEncoder) ClearBuffer(buffer *Buffer, offset, size uint64)

ClearBuffer clears a region of a buffer to zeros. size = 0 means clear from offset to end of buffer.

func (*CommandEncoder) CopyBufferToBuffer

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

CopyBufferToBuffer copies data between buffers.

func (*CommandEncoder) CopyBufferToTexture

func (enc *CommandEncoder) CopyBufferToTexture(source *TexelCopyBufferInfo, destination *TexelCopyTextureInfo, copySize *Extent3D)

CopyBufferToTexture copies data from a buffer to a texture. Errors are reported via Device error scopes, not as return values.

func (*CommandEncoder) CopyTextureToBuffer

func (enc *CommandEncoder) CopyTextureToBuffer(source *TexelCopyTextureInfo, destination *TexelCopyBufferInfo, copySize *Extent3D)

CopyTextureToBuffer copies data from a texture to a buffer. Errors are reported via Device error scopes, not as return values.

func (*CommandEncoder) CopyTextureToTexture

func (enc *CommandEncoder) CopyTextureToTexture(source *TexelCopyTextureInfo, destination *TexelCopyTextureInfo, copySize *Extent3D)

CopyTextureToTexture copies data from one texture to another. Errors are reported via Device error scopes, not as return values.

func (*CommandEncoder) Finish

Finish finishes recording and returns a command buffer.

func (*CommandEncoder) Handle

func (enc *CommandEncoder) Handle() uintptr

Handle returns the underlying handle.

func (*CommandEncoder) InsertDebugMarker

func (enc *CommandEncoder) InsertDebugMarker(markerLabel string)

InsertDebugMarker inserts a single debug marker label. This is useful for GPU debugging tools to identify specific command points.

func (*CommandEncoder) PopDebugGroup

func (enc *CommandEncoder) PopDebugGroup()

PopDebugGroup ends the current debug group. Must match a preceding PushDebugGroup call.

func (*CommandEncoder) PushDebugGroup

func (enc *CommandEncoder) PushDebugGroup(groupLabel string)

PushDebugGroup begins a labeled debug group. Use PopDebugGroup to end the group. Groups can be nested.

func (*CommandEncoder) Release

func (enc *CommandEncoder) Release()

Release releases the command encoder.

func (*CommandEncoder) ResolveQuerySet

func (enc *CommandEncoder) ResolveQuerySet(querySet *QuerySet, firstQuery, queryCount uint32, destination *Buffer, destinationOffset uint64)

ResolveQuerySet resolves query results to a buffer. The buffer must have BufferUsageQueryResolve usage.

func (*CommandEncoder) WriteTimestamp

func (enc *CommandEncoder) WriteTimestamp(querySet *QuerySet, queryIndex uint32)

WriteTimestamp writes a timestamp to a query. Note: This is a wgpu-native extension. Prefer pass-level timestamps via RenderPassTimestampWrites or ComputePassTimestampWrites when possible.

type CommandEncoderDescriptor

type CommandEncoderDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
}

CommandEncoderDescriptor describes a command encoder.

type CompareFunction

type CompareFunction uint32

CompareFunction for depth/stencil operations.

const (
	CompareFunctionUndefined    CompareFunction = 0x00
	CompareFunctionNever        CompareFunction = 0x01
	CompareFunctionLess         CompareFunction = 0x02
	CompareFunctionEqual        CompareFunction = 0x03
	CompareFunctionLessEqual    CompareFunction = 0x04
	CompareFunctionGreater      CompareFunction = 0x05
	CompareFunctionNotEqual     CompareFunction = 0x06
	CompareFunctionGreaterEqual CompareFunction = 0x07
	CompareFunctionAlways       CompareFunction = 0x08
)

type CompositeAlphaMode

type CompositeAlphaMode uint32

CompositeAlphaMode describes how alpha is handled for surface compositing.

const (
	CompositeAlphaModeAuto            CompositeAlphaMode = 0x00
	CompositeAlphaModeOpaque          CompositeAlphaMode = 0x01
	CompositeAlphaModePremultiplied   CompositeAlphaMode = 0x02
	CompositeAlphaModeUnpremultiplied CompositeAlphaMode = 0x03
	CompositeAlphaModeInherit         CompositeAlphaMode = 0x04
)

type ComputePassDescriptor

type ComputePassDescriptor struct {
	NextInChain     uintptr // *ChainedStruct
	Label           StringView
	TimestampWrites uintptr // *ComputePassTimestampWrites (nullable)
}

ComputePassDescriptor describes a compute pass.

type ComputePassEncoder

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

ComputePassEncoder represents a compute pass encoder.

func (*ComputePassEncoder) DispatchWorkgroups

func (cpe *ComputePassEncoder) DispatchWorkgroups(x, y, z uint32)

DispatchWorkgroups dispatches compute work.

func (*ComputePassEncoder) DispatchWorkgroupsIndirect

func (cpe *ComputePassEncoder) DispatchWorkgroupsIndirect(indirectBuffer *Buffer, indirectOffset uint64)

DispatchWorkgroupsIndirect dispatches compute work using parameters from a GPU buffer. indirectBuffer must contain a DispatchIndirectArgs structure:

  • workgroupCountX (uint32)
  • workgroupCountY (uint32)
  • workgroupCountZ (uint32)

func (*ComputePassEncoder) End

func (cpe *ComputePassEncoder) End()

End ends the compute pass.

func (*ComputePassEncoder) Handle

func (cpe *ComputePassEncoder) Handle() uintptr

Handle returns the underlying handle.

func (*ComputePassEncoder) Release

func (cpe *ComputePassEncoder) Release()

Release releases the compute pass encoder.

func (*ComputePassEncoder) SetBindGroup

func (cpe *ComputePassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)

SetBindGroup sets a bind group.

func (*ComputePassEncoder) SetPipeline

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

SetPipeline sets the compute pipeline.

type ComputePipeline

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

ComputePipeline represents a compute pipeline.

func (*ComputePipeline) GetBindGroupLayout

func (cp *ComputePipeline) GetBindGroupLayout(groupIndex uint32) *BindGroupLayout

GetBindGroupLayout returns the bind group layout at the given index. Useful for auto-layout pipelines.

func (*ComputePipeline) Handle

func (cp *ComputePipeline) Handle() uintptr

Handle returns the underlying handle.

func (*ComputePipeline) Release

func (cp *ComputePipeline) Release()

Release releases the compute pipeline.

type ComputePipelineDescriptor

type ComputePipelineDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
	Layout      uintptr // WGPUPipelineLayout (nullable)
	Compute     ProgrammableStageDescriptor
}

ComputePipelineDescriptor describes a compute pipeline.

type CullMode

type CullMode uint32

CullMode describes which faces to cull.

const (
	CullModeUndefined CullMode = 0x00
	CullModeNone      CullMode = 0x01
	CullModeFront     CullMode = 0x02
	CullModeBack      CullMode = 0x03
)

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 test state (user API).

type Device

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

Device represents a WebGPU device.

func (*Device) CreateBindGroup

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

CreateBindGroup creates a bind group.

func (*Device) CreateBindGroupLayout

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

CreateBindGroupLayout creates a bind group layout.

func (*Device) CreateBindGroupLayoutSimple

func (d *Device) CreateBindGroupLayoutSimple(entries []BindGroupLayoutEntry) *BindGroupLayout

CreateBindGroupLayoutSimple creates a bind group layout with the given entries.

func (*Device) CreateBindGroupSimple

func (d *Device) CreateBindGroupSimple(layout *BindGroupLayout, entries []BindGroupEntry) *BindGroup

CreateBindGroupSimple creates a bind group with buffer entries.

func (*Device) CreateBuffer

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

CreateBuffer creates a new GPU buffer.

func (*Device) CreateCommandEncoder

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

CreateCommandEncoder creates a command encoder.

func (*Device) CreateComputePipeline

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

CreateComputePipeline creates a compute pipeline.

func (*Device) CreateComputePipelineSimple

func (d *Device) CreateComputePipelineSimple(layout *PipelineLayout, shader *ShaderModule, entryPoint string) *ComputePipeline

CreateComputePipelineSimple creates a compute pipeline with the given shader and entry point. If layout is nil, auto layout is used.

func (*Device) CreateDepthTexture

func (d *Device) CreateDepthTexture(width, height uint32, format TextureFormat) *Texture

CreateDepthTexture creates a depth texture with the specified dimensions and format. This is a convenience function for creating depth buffers for render passes.

func (*Device) CreateLinearSampler

func (d *Device) CreateLinearSampler() *Sampler

CreateLinearSampler creates a sampler with linear filtering.

func (*Device) CreateNearestSampler

func (d *Device) CreateNearestSampler() *Sampler

CreateNearestSampler creates a sampler with nearest filtering.

func (*Device) CreatePipelineLayout

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

CreatePipelineLayout creates a pipeline layout.

func (*Device) CreatePipelineLayoutSimple

func (d *Device) CreatePipelineLayoutSimple(layouts []*BindGroupLayout) *PipelineLayout

CreatePipelineLayoutSimple creates a pipeline layout with the given bind group layouts.

func (*Device) CreateQuerySet

func (d *Device) CreateQuerySet(desc *QuerySetDescriptor) *QuerySet

CreateQuerySet creates a new QuerySet for GPU profiling/timestamps.

func (*Device) CreateRenderBundleEncoder

func (d *Device) CreateRenderBundleEncoder(desc *RenderBundleEncoderDescriptor) *RenderBundleEncoder

CreateRenderBundleEncoder creates a render bundle encoder for pre-recording render commands. Render bundles allow you to pre-record a sequence of render commands that can be replayed multiple times, which is useful for static geometry.

func (*Device) CreateRenderBundleEncoderSimple

func (d *Device) CreateRenderBundleEncoderSimple(colorFormats []TextureFormat, depthFormat TextureFormat, sampleCount uint32) *RenderBundleEncoder

CreateRenderBundleEncoderSimple creates a render bundle encoder with common settings.

func (*Device) CreateRenderPipeline

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

CreateRenderPipeline creates a render pipeline.

func (*Device) CreateRenderPipelineSimple

func (d *Device) CreateRenderPipelineSimple(
	layout *PipelineLayout,
	vertexShader *ShaderModule,
	vertexEntryPoint string,
	fragmentShader *ShaderModule,
	fragmentEntryPoint string,
	targetFormat TextureFormat,
) *RenderPipeline

CreateRenderPipelineSimple creates a simple render pipeline with common defaults.

func (*Device) CreateSampler

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

CreateSampler creates a sampler with the specified descriptor.

func (*Device) CreateShaderModule

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

CreateShaderModule creates a shader module from a descriptor. For WGSL shaders, use CreateShaderModuleWGSL instead.

func (*Device) CreateShaderModuleWGSL

func (d *Device) CreateShaderModuleWGSL(code string) *ShaderModule

CreateShaderModuleWGSL creates a shader module from WGSL source code.

func (*Device) CreateTexture

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

CreateTexture creates a texture with the specified descriptor.

func (*Device) GetQueue

func (d *Device) GetQueue() *Queue

GetQueue returns the default queue for the device.

func (*Device) Handle

func (d *Device) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Device) Poll

func (d *Device) Poll(wait bool) bool

Poll polls the device for completed work. If wait is true, blocks until there is work to process. Returns true if the queue is empty. This is a wgpu-native extension.

func (*Device) PopErrorScope

func (d *Device) PopErrorScope(instance *Instance) (ErrorType, string)

PopErrorScope pops the current error scope and returns the first error caught. This is a synchronous wrapper that blocks until the result is available.

IMPORTANT: You must have pushed an error scope before calling this. Calling PopErrorScope on an empty stack will cause a panic in wgpu-native. Use PopErrorScopeAsync if you need to handle empty stack gracefully.

Returns:

  • ErrorType: The type of error that occurred (ErrorTypeNoError if no error)
  • string: Error message (empty if no error)

Note: Error scopes are LIFO - the last pushed scope is popped first.

func (*Device) PopErrorScopeAsync

func (d *Device) PopErrorScopeAsync(instance *Instance) (ErrorType, string, error)

PopErrorScopeAsync pops the current error scope and returns the first error caught. This version returns an error instead of panicking if the operation fails.

Returns:

  • ErrorType: The type of error that occurred (ErrorTypeNoError if no error)
  • string: Error message (empty if no error)
  • error: An error if the operation failed (e.g., empty stack)

Note: Error scopes are LIFO - the last pushed scope is popped first. If the error scope stack is empty, returns an error instead of panicking.

func (*Device) PushErrorScope

func (d *Device) PushErrorScope(filter ErrorFilter)

PushErrorScope pushes an error scope for catching GPU errors. Errors of the specified filter type will be caught until PopErrorScope is called. Error scopes are LIFO (stack-based) - last pushed scope is popped first.

IMPORTANT: You must call PopErrorScope for each PushErrorScope. Popping an empty stack will cause a panic in wgpu-native (known limitation). Users should track push/pop calls manually to avoid stack underflow.

Example usage:

device.PushErrorScope(ErrorFilterValidation)
// ... GPU operations that might produce validation errors
errType, message := device.PopErrorScope(instance)
if errType != ErrorTypeNoError {
    log.Printf("Validation error: %s", message)
}

func (*Device) Release

func (d *Device) Release()

Release releases the device resources.

type DeviceDescriptor

type DeviceDescriptor struct {
	NextInChain uintptr // *ChainedStruct

}

DeviceDescriptor configures device creation. For now, passing nil uses default settings.

type DeviceLostReason

type DeviceLostReason uint32

DeviceLostReason describes why a device was lost.

const (
	// DeviceLostReasonUnknown indicates the device was lost for an unknown reason.
	DeviceLostReasonUnknown DeviceLostReason = 0x00000001
	// DeviceLostReasonDestroyed indicates the device was explicitly destroyed.
	DeviceLostReasonDestroyed DeviceLostReason = 0x00000002
	// DeviceLostReasonInstanceDropped indicates the instance was dropped.
	DeviceLostReasonInstanceDropped DeviceLostReason = 0x00000003
	// DeviceLostReasonFailedCreation indicates device creation failed.
	DeviceLostReasonFailedCreation DeviceLostReason = 0x00000004
)

type DispatchIndirectArgs

type DispatchIndirectArgs struct {
	WorkgroupCountX uint32 // Number of workgroups in X dimension
	WorkgroupCountY uint32 // Number of workgroups in Y dimension
	WorkgroupCountZ uint32 // Number of workgroups in Z dimension
}

DispatchIndirectArgs contains arguments for indirect compute dispatch. This struct must be written to a Buffer for use with DispatchWorkgroupsIndirect. Size: 12 bytes, must be aligned to 4 bytes.

type DrawIndexedIndirectArgs

type DrawIndexedIndirectArgs struct {
	IndexCount    uint32 // Number of indices to draw
	InstanceCount uint32 // Number of instances to draw
	FirstIndex    uint32 // First index in the index buffer
	BaseVertex    int32  // Value added to vertex index before indexing into vertex buffer
	FirstInstance uint32 // First instance index
}

DrawIndexedIndirectArgs contains arguments for indirect indexed draw calls. This struct must be written to a Buffer for use with DrawIndexedIndirect. Size: 20 bytes, must be aligned to 4 bytes.

type DrawIndirectArgs

type DrawIndirectArgs struct {
	VertexCount   uint32 // Number of vertices to draw
	InstanceCount uint32 // Number of instances to draw
	FirstVertex   uint32 // First vertex index
	FirstInstance uint32 // First instance index
}

DrawIndirectArgs contains arguments for indirect (GPU-driven) draw calls. This struct must be written to a Buffer for use with DrawIndirect. Size: 16 bytes, must be aligned to 4 bytes.

type ErrorFilter

type ErrorFilter uint32

ErrorFilter filters error types in error scopes.

const (
	// ErrorFilterValidation catches validation errors.
	ErrorFilterValidation ErrorFilter = 0x00000001
	// ErrorFilterOutOfMemory catches out-of-memory errors.
	ErrorFilterOutOfMemory ErrorFilter = 0x00000002
	// ErrorFilterInternal catches internal errors.
	ErrorFilterInternal ErrorFilter = 0x00000003
)

type ErrorType

type ErrorType uint32

ErrorType describes the type of error that occurred.

const (
	// ErrorTypeNoError indicates no error occurred.
	ErrorTypeNoError ErrorType = 0x00000001
	// ErrorTypeValidation indicates a validation error.
	ErrorTypeValidation ErrorType = 0x00000002
	// ErrorTypeOutOfMemory indicates an out-of-memory error.
	ErrorTypeOutOfMemory ErrorType = 0x00000003
	// ErrorTypeInternal indicates an internal error.
	ErrorTypeInternal ErrorType = 0x00000004
	// ErrorTypeUnknown indicates an unknown error.
	ErrorTypeUnknown ErrorType = 0x00000005
)

type Extent3D

type Extent3D struct {
	Width              uint32
	Height             uint32
	DepthOrArrayLayers uint32
}

Extent3D defines the size of a texture.

type FeatureLevel

type FeatureLevel uint32

FeatureLevel indicates the WebGPU feature level.

const (
	FeatureLevelCompatibility FeatureLevel = 0x00000001
	FeatureLevelCore          FeatureLevel = 0x00000002
)

type FeatureName

type FeatureName uint32

FeatureName describes a WebGPU feature that can be requested.

const (
	// FeatureNameTimestampQuery enables timestamp query support.
	FeatureNameTimestampQuery FeatureName = 0x00000003
)

type FilterMode

type FilterMode uint32

FilterMode determines how textures are sampled.

const (
	FilterModeUndefined FilterMode = 0x00
	FilterModeNearest   FilterMode = 0x01
	FilterModeLinear    FilterMode = 0x02
)

type FragmentState

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

FragmentState describes the fragment stage of a render pipeline.

type FrontFace

type FrontFace uint32

FrontFace describes which winding order is considered front-facing.

const (
	FrontFaceUndefined FrontFace = 0x00
	FrontFaceCCW       FrontFace = 0x01 // Counter-clockwise
	FrontFaceCW        FrontFace = 0x02 // Clockwise
)

type Future

type Future struct {
	ID uint64
}

Future represents an async operation handle.

type IndexFormat

type IndexFormat uint32

IndexFormat describes the format of index buffer data.

const (
	IndexFormatUndefined IndexFormat = 0x00
	IndexFormatUint16    IndexFormat = 0x01
	IndexFormatUint32    IndexFormat = 0x02
)

type Instance

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

Instance represents a WebGPU instance.

func CreateInstance

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

CreateInstance creates a new WebGPU instance. Pass nil for default configuration.

func (*Instance) CreateSurfaceFromWaylandSurface

func (inst *Instance) CreateSurfaceFromWaylandSurface(display, surface uintptr) (*Surface, error)

CreateSurfaceFromWaylandSurface creates a surface from a Wayland surface. display is the wl_display pointer. surface is the wl_surface pointer.

func (*Instance) CreateSurfaceFromXlibWindow

func (inst *Instance) CreateSurfaceFromXlibWindow(display uintptr, window uint64) (*Surface, error)

CreateSurfaceFromXlibWindow creates a surface from an X11 Xlib window. display is the X11 Display pointer. window is the X11 Window ID (XID).

func (*Instance) Handle

func (i *Instance) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Instance) ProcessEvents

func (i *Instance) ProcessEvents()

ProcessEvents processes pending async events.

func (*Instance) Release

func (i *Instance) Release()

Release releases the instance resources.

func (*Instance) RequestAdapter

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

RequestAdapter requests a GPU adapter from the instance. This is a synchronous wrapper that blocks until the adapter is available.

type InstanceCapabilities

type InstanceCapabilities struct {
	NextInChain        uintptr // *ChainedStructOut
	TimedWaitAnyEnable Bool

	TimedWaitAnyMaxCount uint64
	// contains filtered or unexported fields
}

InstanceCapabilities describes instance capabilities. Note: This struct has specific padding requirements to match C layout.

type InstanceDescriptor

type InstanceDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Features    InstanceCapabilities
}

InstanceDescriptor describes an Instance.

type Library

type Library interface {
	// NewProc retrieves a procedure (function) from the library.
	// Returns a Proc interface that can be used to call the function.
	NewProc(name string) Proc
}

Library represents a dynamically loaded library (DLL/SO/DYLIB). Platform-specific implementations handle the actual loading mechanism.

type Limits

type Limits struct {
	MaxTextureDimension1D                     uint32
	MaxTextureDimension2D                     uint32
	MaxTextureDimension3D                     uint32
	MaxTextureArrayLayers                     uint32
	MaxBindGroups                             uint32
	MaxBindGroupsPlusVertexBuffers            uint32
	MaxBindingsPerBindGroup                   uint32
	MaxDynamicUniformBuffersPerPipelineLayout uint32
	MaxDynamicStorageBuffersPerPipelineLayout uint32
	MaxSampledTexturesPerShaderStage          uint32
	MaxSamplersPerShaderStage                 uint32
	MaxStorageBuffersPerShaderStage           uint32
	MaxStorageTexturesPerShaderStage          uint32
	MaxUniformBuffersPerShaderStage           uint32
	MaxUniformBufferBindingSize               uint64
	MaxStorageBufferBindingSize               uint64
	MaxVertexBuffers                          uint32
	MaxBufferSize                             uint64
	MaxVertexAttributes                       uint32
	MaxVertexBufferArrayStride                uint32
	MaxInterStageShaderVariables              uint32
	MaxColorAttachments                       uint32
	MaxColorAttachmentBytesPerSample          uint32
	MaxComputeWorkgroupStorageSize            uint32
	MaxComputeInvocationsPerWorkgroup         uint32
	MaxComputeWorkgroupSizeX                  uint32
	MaxComputeWorkgroupSizeY                  uint32
	MaxComputeWorkgroupSizeZ                  uint32
	MaxComputeWorkgroupsPerDimension          uint32
	MinUniformBufferOffsetAlignment           uint32
	MinStorageBufferOffsetAlignment           uint32
}

Limits describes resource limits for an adapter or device. This contains the most commonly used limits. WebGPU spec defines ~50 limits total.

type LoadOp

type LoadOp uint32

LoadOp describes what happens to render target at the beginning of a pass.

const (
	LoadOpUndefined LoadOp = 0x00
	LoadOpLoad      LoadOp = 0x01 // Keep existing content
	LoadOpClear     LoadOp = 0x02 // Clear to clear value
)

type MapAsyncStatus

type MapAsyncStatus uint32

MapAsyncStatus is the status returned by MapAsync callback.

const (
	MapAsyncStatusSuccess         MapAsyncStatus = 0x00000001
	MapAsyncStatusInstanceDropped MapAsyncStatus = 0x00000002
	MapAsyncStatusError           MapAsyncStatus = 0x00000003
	MapAsyncStatusAborted         MapAsyncStatus = 0x00000004
	MapAsyncStatusUnknown         MapAsyncStatus = 0x00000005
)

type MapMode

type MapMode uint64

MapMode specifies the mapping mode for MapAsync.

const (
	MapModeNone  MapMode = 0x0000000000000000
	MapModeRead  MapMode = 0x0000000000000001
	MapModeWrite MapMode = 0x0000000000000002
)

type Mat4

type Mat4 [16]float32

Mat4 represents a 4x4 matrix in column-major order, compatible with WGSL mat4x4<f32>. Layout: [col0, col1, col2, col3] where each column is [x, y, z, w]. Element at column c, row r is at index c*4+r. This matches WebGPU/WGSL/OpenGL convention (column-major).

Example (Basic)

ExampleMat4_basic demonstrates basic matrix operations

package main

import (
	"fmt"

	"github.com/go-webgpu/webgpu/wgpu"
)

func main() {
	// Create transformation matrices
	translate := wgpu.Mat4Translate(10, 0, 0)
	scale := wgpu.Mat4Scale(2, 2, 2)

	// Combine transformations (order matters: scale first, then translate)
	combined := translate.Mul(scale)

	// Transform a point
	point := wgpu.Vec4{X: 1, Y: 0, Z: 0, W: 1}
	result := combined.MulVec4(point)

	fmt.Printf("Transformed point: (%.0f, %.0f, %.0f)\n", result.X, result.Y, result.Z)
}
Output:

Transformed point: (12, 0, 0)
Example (Rotation)

ExampleMat4_rotation demonstrates rotation matrices

package main

import (
	"fmt"

	"github.com/go-webgpu/webgpu/wgpu"
)

func main() {
	// Rotate 90 degrees around Y axis
	rotation := wgpu.Mat4RotateY(3.14159 / 2) // 90 degrees in radians

	// Apply rotation to a point on X axis
	point := wgpu.Vec4{X: 1, Y: 0, Z: 0, W: 1}
	rotated := rotation.MulVec4(point)

	// Right-hand rule: rotating +X around +Y by 90° gives -Z direction
	fmt.Printf("Rotated point: X≈%.0f, Z≈%.0f\n", rotated.X, rotated.Z)
}
Output:

Rotated point: X≈0, Z≈-1

func Mat4Identity

func Mat4Identity() Mat4

Mat4Identity returns a 4x4 identity matrix. The identity matrix has 1s on the diagonal and 0s elsewhere.

func Mat4LookAt

func Mat4LookAt(eye, center, up Vec3) Mat4

Mat4LookAt returns a view matrix that looks from eye position towards center. eye: camera position center: point the camera is looking at up: up direction vector (typically (0, 1, 0))

This creates a right-handed coordinate system view matrix.

func Mat4Perspective

func Mat4Perspective(fovY, aspect, near, far float32) Mat4

Mat4Perspective returns a perspective projection matrix. fovY: vertical field of view in radians aspect: aspect ratio (width/height) near: near clipping plane distance (must be > 0) far: far clipping plane distance (must be > near)

This uses right-handed coordinate system with Z in [-1, 1] (OpenGL/Vulkan style). For WebGPU with Z in [0, 1], post-multiply with depth range transform.

Example

ExampleMat4Perspective demonstrates perspective projection setup

package main

import (
	"fmt"

	"github.com/go-webgpu/webgpu/wgpu"
)

func main() {
	// Common 3D camera setup
	fov := float32(45.0 * 3.14159 / 180.0) // 45 degrees in radians
	aspect := float32(16.0 / 9.0)          // 16:9 aspect ratio
	near := float32(0.1)
	far := float32(100.0)

	projection := wgpu.Mat4Perspective(fov, aspect, near, far)

	// Create view matrix (camera looking from (0, 0, 5) towards origin)
	eye := wgpu.Vec3{X: 0, Y: 0, Z: 5}
	center := wgpu.Vec3{X: 0, Y: 0, Z: 0}
	up := wgpu.Vec3{X: 0, Y: 1, Z: 0}
	view := wgpu.Mat4LookAt(eye, center, up)

	// Combine projection and view
	viewProj := projection.Mul(view)

	fmt.Printf("View-Projection matrix ready: %v elements\n", len(viewProj))
}
Output:

View-Projection matrix ready: 16 elements

func Mat4RotateX

func Mat4RotateX(radians float32) Mat4

Mat4RotateX returns a rotation matrix around the X axis. Angle is in radians. Positive rotation follows right-hand rule.

func Mat4RotateY

func Mat4RotateY(radians float32) Mat4

Mat4RotateY returns a rotation matrix around the Y axis. Angle is in radians. Positive rotation follows right-hand rule.

func Mat4RotateZ

func Mat4RotateZ(radians float32) Mat4

Mat4RotateZ returns a rotation matrix around the Z axis. Angle is in radians. Positive rotation follows right-hand rule.

func Mat4Scale

func Mat4Scale(x, y, z float32) Mat4

Mat4Scale returns a scaling matrix for the given factors. Scales objects by (x, y, z) along each axis.

func Mat4Translate

func Mat4Translate(x, y, z float32) Mat4

Mat4Translate returns a translation matrix for the given offset. Translates points by (x, y, z) in 3D space.

func (Mat4) Mul

func (m Mat4) Mul(other Mat4) Mat4

Mul multiplies this matrix by another matrix (column-major order). Returns result = m * other (apply m first, then other).

func (Mat4) MulVec4

func (m Mat4) MulVec4(v Vec4) Vec4

MulVec4 multiplies this matrix by a 4D vector. Returns result = m * v (transforms vector by matrix).

type MipmapFilterMode

type MipmapFilterMode uint32

MipmapFilterMode determines how mipmaps are sampled.

const (
	MipmapFilterModeUndefined MipmapFilterMode = 0x00
	MipmapFilterModeNearest   MipmapFilterMode = 0x01
	MipmapFilterModeLinear    MipmapFilterMode = 0x02
)

type MultisampleState

type MultisampleState struct {
	Count                  uint32
	Mask                   uint32
	AlphaToCoverageEnabled bool
}

MultisampleState describes multisampling.

type OptionalBool

type OptionalBool uint32

OptionalBool is a tri-state boolean for WebGPU.

const (
	OptionalBoolFalse     OptionalBool = 0x00000000
	OptionalBoolTrue      OptionalBool = 0x00000001
	OptionalBoolUndefined OptionalBool = 0x00000002
)

type Origin3D

type Origin3D struct {
	X, Y, Z uint32
}

Origin3D defines an offset in a texture.

type PipelineLayout

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

PipelineLayout represents a pipeline layout.

func (*PipelineLayout) Handle

func (pl *PipelineLayout) Handle() uintptr

Handle returns the underlying handle.

func (*PipelineLayout) Release

func (pl *PipelineLayout) Release()

Release releases the pipeline layout.

type PipelineLayoutDescriptor

type PipelineLayoutDescriptor struct {
	NextInChain          uintptr // *ChainedStruct
	Label                StringView
	BindGroupLayoutCount uintptr // size_t
	BindGroupLayouts     uintptr // *WGPUBindGroupLayout
}

PipelineLayoutDescriptor describes a pipeline layout.

type PopErrorScopeStatus

type PopErrorScopeStatus uint32

PopErrorScopeStatus describes the result of PopErrorScope operation.

const (
	// PopErrorScopeStatusSuccess indicates the error scope was successfully popped.
	PopErrorScopeStatusSuccess PopErrorScopeStatus = 0x00000001
	// PopErrorScopeStatusInstanceDropped indicates the instance was dropped.
	PopErrorScopeStatusInstanceDropped PopErrorScopeStatus = 0x00000002
	// PopErrorScopeStatusEmptyStack indicates the error scope stack was empty.
	PopErrorScopeStatusEmptyStack PopErrorScopeStatus = 0x00000003
)

type PowerPreference

type PowerPreference uint32

PowerPreference indicates preference for GPU power usage.

const (
	PowerPreferenceUndefined       PowerPreference = 0x00000000
	PowerPreferenceLowPower        PowerPreference = 0x00000001
	PowerPreferenceHighPerformance PowerPreference = 0x00000002
)

type PresentMode

type PresentMode uint32

PresentMode describes how frames are presented to the surface.

const (
	PresentModeUndefined   PresentMode = 0x00
	PresentModeFifo        PresentMode = 0x01 // VSync, always available
	PresentModeFifoRelaxed PresentMode = 0x02
	PresentModeImmediate   PresentMode = 0x03 // No VSync, may tear
	PresentModeMailbox     PresentMode = 0x04 // Triple buffering
)

type PrimitiveState

type PrimitiveState struct {
	Topology         PrimitiveTopology
	StripIndexFormat IndexFormat
	FrontFace        FrontFace
	CullMode         CullMode
}

PrimitiveState describes how primitives are assembled.

type PrimitiveTopology

type PrimitiveTopology uint32

PrimitiveTopology describes how vertices form primitives.

const (
	PrimitiveTopologyUndefined     PrimitiveTopology = 0x00
	PrimitiveTopologyPointList     PrimitiveTopology = 0x01
	PrimitiveTopologyLineList      PrimitiveTopology = 0x02
	PrimitiveTopologyLineStrip     PrimitiveTopology = 0x03
	PrimitiveTopologyTriangleList  PrimitiveTopology = 0x04
	PrimitiveTopologyTriangleStrip PrimitiveTopology = 0x05
)

type Proc

type Proc interface {
	// Call invokes the procedure with the given arguments.
	// Returns the result value and error (if any).
	// Arguments are passed as uintptr to match C ABI.
	Call(args ...uintptr) (uintptr, uintptr, error)
}

Proc represents a procedure (function pointer) from a dynamically loaded library. It abstracts platform-specific function calling mechanisms.

type ProgrammableStageDescriptor

type ProgrammableStageDescriptor struct {
	NextInChain   uintptr    // *ChainedStruct
	Module        uintptr    // WGPUShaderModule
	EntryPoint    StringView // Entry point function name
	ConstantCount uintptr    // size_t
	Constants     uintptr    // *ConstantEntry
}

ProgrammableStageDescriptor describes a programmable shader stage.

type QuerySet

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

QuerySet represents a query set.

func (*QuerySet) Destroy

func (qs *QuerySet) Destroy()

Destroy destroys the QuerySet, making it invalid.

func (*QuerySet) Handle

func (qs *QuerySet) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*QuerySet) Release

func (qs *QuerySet) Release()

Release releases the QuerySet reference.

type QuerySetDescriptor

type QuerySetDescriptor struct {
	Label string
	Type  QueryType
	Count uint32
}

QuerySetDescriptor describes a QuerySet to create.

type QueryType

type QueryType uint32

QueryType describes the type of queries in a QuerySet.

const (
	// QueryTypeOcclusion specifies occlusion queries.
	QueryTypeOcclusion QueryType = 0x00000001
	// QueryTypeTimestamp specifies timestamp queries for GPU profiling.
	QueryTypeTimestamp QueryType = 0x00000002
)

type Queue

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

Queue represents a WebGPU command queue.

func (*Queue) Handle

func (q *Queue) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Queue) Release

func (q *Queue) Release()

Release releases the queue resources.

func (*Queue) Submit

func (q *Queue) Submit(commands ...*CommandBuffer)

Submit submits command buffers for execution.

func (*Queue) WriteBuffer

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

WriteBuffer writes data to a buffer. This is a convenience method that stages data for upload to the GPU.

func (*Queue) WriteBufferRaw

func (q *Queue) WriteBufferRaw(buffer *Buffer, offset uint64, data unsafe.Pointer, size uint64)

WriteBufferTyped writes typed data to a buffer. The data pointer should point to the first element, size is total byte size.

func (*Queue) WriteTexture

func (q *Queue) WriteTexture(dest *TexelCopyTextureInfo, data []byte, layout *TexelCopyBufferLayout, size *Extent3D)

WriteTexture writes data to a texture.

type RenderBundle

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

RenderBundle represents a pre-recorded bundle of render commands.

func (*RenderBundle) Handle

func (rb *RenderBundle) Handle() uintptr

Handle returns the underlying handle.

func (*RenderBundle) Release

func (rb *RenderBundle) Release()

Release releases the render bundle.

type RenderBundleDescriptor

type RenderBundleDescriptor struct {
	NextInChain uintptr // *ChainedStruct
	Label       StringView
}

RenderBundleDescriptor describes a render bundle.

type RenderBundleEncoder

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

RenderBundleEncoder represents a render bundle encoder.

func (*RenderBundleEncoder) Draw

func (rbe *RenderBundleEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)

Draw records a non-indexed draw call.

func (*RenderBundleEncoder) DrawIndexed

func (rbe *RenderBundleEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)

DrawIndexed records an indexed draw call.

func (*RenderBundleEncoder) DrawIndexedIndirect

func (rbe *RenderBundleEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)

DrawIndexedIndirect records an indirect indexed draw call.

func (*RenderBundleEncoder) DrawIndirect

func (rbe *RenderBundleEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)

DrawIndirect records an indirect draw call.

func (*RenderBundleEncoder) Finish

Finish completes recording and returns the render bundle.

func (*RenderBundleEncoder) Handle

func (rbe *RenderBundleEncoder) Handle() uintptr

Handle returns the underlying handle.

func (*RenderBundleEncoder) Release

func (rbe *RenderBundleEncoder) Release()

Release releases the render bundle encoder.

func (*RenderBundleEncoder) SetBindGroup

func (rbe *RenderBundleEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)

SetBindGroup sets a bind group at the given index.

func (*RenderBundleEncoder) SetIndexBuffer

func (rbe *RenderBundleEncoder) SetIndexBuffer(buffer *Buffer, format IndexFormat, offset, size uint64)

SetIndexBuffer sets the index buffer.

func (*RenderBundleEncoder) SetPipeline

func (rbe *RenderBundleEncoder) SetPipeline(pipeline *RenderPipeline)

SetPipeline sets the render pipeline for subsequent draw calls.

func (*RenderBundleEncoder) SetVertexBuffer

func (rbe *RenderBundleEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset, size uint64)

SetVertexBuffer sets a vertex buffer at the given slot.

type RenderBundleEncoderDescriptor

type RenderBundleEncoderDescriptor struct {
	Label              StringView
	ColorFormatCount   uintptr // size_t
	ColorFormats       *TextureFormat
	DepthStencilFormat TextureFormat
	SampleCount        uint32
	DepthReadOnly      Bool
	StencilReadOnly    Bool
}

RenderBundleEncoderDescriptor describes a render bundle encoder.

type RenderPassColorAttachment

type RenderPassColorAttachment struct {
	View          *TextureView
	ResolveTarget *TextureView // For MSAA, nil otherwise
	LoadOp        LoadOp
	StoreOp       StoreOp
	ClearValue    Color
}

RenderPassColorAttachment describes a color attachment for a render pass.

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 (user API).

type RenderPassDescriptor

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

RenderPassDescriptor describes a render pass.

type RenderPassEncoder

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

RenderPassEncoder represents a render pass encoder.

func (*RenderPassEncoder) Draw

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

Draw draws primitives.

func (*RenderPassEncoder) DrawIndexed

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

DrawIndexed draws indexed primitives.

func (*RenderPassEncoder) DrawIndexedIndirect

func (rpe *RenderPassEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)

DrawIndexedIndirect draws indexed primitives using parameters from a GPU buffer. indirectBuffer must contain a DrawIndexedIndirectArgs structure:

  • indexCount (uint32)
  • instanceCount (uint32)
  • firstIndex (uint32)
  • baseVertex (int32)
  • firstInstance (uint32)

func (*RenderPassEncoder) DrawIndirect

func (rpe *RenderPassEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)

DrawIndirect draws primitives using parameters from a GPU buffer. indirectBuffer must contain a DrawIndirectArgs structure:

  • vertexCount (uint32)
  • instanceCount (uint32)
  • firstVertex (uint32)
  • firstInstance (uint32)

func (*RenderPassEncoder) End

func (rpe *RenderPassEncoder) End()

End ends the render pass.

func (*RenderPassEncoder) ExecuteBundles

func (rpe *RenderPassEncoder) ExecuteBundles(bundles []*RenderBundle)

ExecuteBundles executes pre-recorded render bundles in the render pass. This is useful for replaying static geometry without re-recording commands.

func (*RenderPassEncoder) Handle

func (rpe *RenderPassEncoder) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*RenderPassEncoder) InsertDebugMarker

func (rpe *RenderPassEncoder) InsertDebugMarker(markerLabel string)

InsertDebugMarker inserts a single debug marker label into the render pass. This is useful for GPU debugging tools to identify specific command points.

func (*RenderPassEncoder) PopDebugGroup

func (rpe *RenderPassEncoder) PopDebugGroup()

PopDebugGroup ends the current debug group in the render pass. Must match a preceding PushDebugGroup call.

func (*RenderPassEncoder) PushDebugGroup

func (rpe *RenderPassEncoder) PushDebugGroup(groupLabel string)

PushDebugGroup begins a labeled debug group in the render pass. Use PopDebugGroup to end the group. Groups can be nested.

func (*RenderPassEncoder) Release

func (rpe *RenderPassEncoder) Release()

Release releases the render pass encoder.

func (*RenderPassEncoder) SetBindGroup

func (rpe *RenderPassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)

SetBindGroup sets a bind group for this pass.

func (*RenderPassEncoder) SetBlendConstant

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

SetBlendConstant sets the blend constant color used by blend operations. Errors are reported via Device error scopes.

func (*RenderPassEncoder) SetIndexBuffer

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

SetIndexBuffer sets the index buffer for this pass.

func (*RenderPassEncoder) SetPipeline

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

SetPipeline sets the render pipeline for this pass.

func (*RenderPassEncoder) SetScissorRect

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

SetScissorRect sets the scissor rectangle used during the rasterization stage. Pixels outside the scissor rectangle will be discarded. x, y: top-left corner of the scissor rectangle in pixels width, height: dimensions of the scissor rectangle in pixels

func (*RenderPassEncoder) SetStencilReference

func (rpe *RenderPassEncoder) SetStencilReference(reference uint32)

SetStencilReference sets the stencil reference value used by stencil operations.

func (*RenderPassEncoder) SetVertexBuffer

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

SetVertexBuffer sets a vertex buffer for this pass.

func (*RenderPassEncoder) SetViewport

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

SetViewport sets the viewport used during the rasterization stage. x, y: top-left corner of the viewport in pixels width, height: dimensions of the viewport in pixels minDepth, maxDepth: depth range for the viewport (typically 0.0 to 1.0)

type RenderPassTimestampWrites

type RenderPassTimestampWrites struct {
	QuerySet                  *QuerySet
	BeginningOfPassWriteIndex uint32 // Use TimestampLocationUndefined to disable
	EndOfPassWriteIndex       uint32 // Use TimestampLocationUndefined to disable
}

RenderPassTimestampWrites describes timestamp writes for a render pass.

type RenderPipeline

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

RenderPipeline represents a render pipeline.

func (*RenderPipeline) GetBindGroupLayout

func (rp *RenderPipeline) GetBindGroupLayout(groupIndex uint32) *BindGroupLayout

GetBindGroupLayout returns the bind group layout for the given index.

func (*RenderPipeline) Handle

func (rp *RenderPipeline) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*RenderPipeline) Release

func (rp *RenderPipeline) Release()

Release releases the render pipeline.

type RenderPipelineDescriptor

type RenderPipelineDescriptor struct {
	Label        string
	Layout       *PipelineLayout // nil for auto layout
	Vertex       VertexState
	Primitive    PrimitiveState
	DepthStencil *DepthStencilState // nil for no depth/stencil
	Multisample  MultisampleState
	Fragment     *FragmentState // nil for no fragment stage (depth-only)
}

RenderPipelineDescriptor describes a render pipeline to create.

type RequestAdapterCallbackInfo

type RequestAdapterCallbackInfo struct {
	NextInChain uintptr // *ChainedStruct
	Mode        CallbackMode
	Callback    uintptr // Function pointer
	Userdata1   uintptr
	Userdata2   uintptr
}

RequestAdapterCallbackInfo holds callback configuration.

type RequestAdapterOptions

type RequestAdapterOptions struct {
	NextInChain          uintptr // *ChainedStruct
	FeatureLevel         FeatureLevel
	PowerPreference      PowerPreference
	ForceFallbackAdapter Bool
	CompatibilityMode    Bool
	CompatibleSurface    uintptr // WGPUSurface
}

RequestAdapterOptions configures adapter selection.

type RequestAdapterStatus

type RequestAdapterStatus uint32

RequestAdapterStatus is the status returned by RequestAdapter callback.

const (
	RequestAdapterStatusSuccess         RequestAdapterStatus = 0x00000001
	RequestAdapterStatusInstanceDropped RequestAdapterStatus = 0x00000002
	RequestAdapterStatusUnavailable     RequestAdapterStatus = 0x00000003
	RequestAdapterStatusError           RequestAdapterStatus = 0x00000004
)

type RequestDeviceCallbackInfo

type RequestDeviceCallbackInfo struct {
	NextInChain uintptr // *ChainedStruct
	Mode        CallbackMode
	Callback    uintptr // Function pointer
	Userdata1   uintptr
	Userdata2   uintptr
}

RequestDeviceCallbackInfo holds callback configuration for RequestDevice.

type RequestDeviceStatus

type RequestDeviceStatus uint32

RequestDeviceStatus is the status returned by RequestDevice callback.

const (
	RequestDeviceStatusSuccess         RequestDeviceStatus = 0x00000001
	RequestDeviceStatusInstanceDropped RequestDeviceStatus = 0x00000002
	RequestDeviceStatusError           RequestDeviceStatus = 0x00000003
	RequestDeviceStatusUnknown         RequestDeviceStatus = 0x00000004
)

type SType

type SType uint32

SType identifies chained struct types.

const (
	// Standard WebGPU STypes
	STypeShaderSourceSPIRV SType = 0x00000001
	STypeShaderSourceWGSL  SType = 0x00000002

	// Surface source STypes
	STypeSurfaceSourceMetalLayer          SType = 0x00000004
	STypeSurfaceSourceWindowsHWND         SType = 0x00000005
	STypeSurfaceSourceXlibWindow          SType = 0x00000006
	STypeSurfaceSourceWaylandSurface      SType = 0x00000007
	STypeSurfaceSourceAndroidNativeWindow SType = 0x00000008
	STypeSurfaceSourceXCBWindow           SType = 0x00000009

	// Native extension STypes (from wgpu.h)
	STypeInstanceExtras SType = 0x00030006
)

type Sampler

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

Sampler represents a WebGPU sampler.

func (*Sampler) Handle

func (s *Sampler) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Sampler) Release

func (s *Sampler) Release()

Release releases the sampler reference.

type SamplerBindingLayout

type SamplerBindingLayout struct {
	NextInChain uintptr // *ChainedStruct
	Type        SamplerBindingType
}

SamplerBindingLayout describes sampler binding properties.

type SamplerBindingType

type SamplerBindingType uint32

SamplerBindingType describes how a sampler is bound.

const (
	SamplerBindingTypeBindingNotUsed SamplerBindingType = 0x00000000
	SamplerBindingTypeUndefined      SamplerBindingType = 0x00000001
	SamplerBindingTypeFiltering      SamplerBindingType = 0x00000002
	SamplerBindingTypeNonFiltering   SamplerBindingType = 0x00000003
	SamplerBindingTypeComparison     SamplerBindingType = 0x00000004
)

type SamplerDescriptor

type SamplerDescriptor struct {
	NextInChain   uintptr
	Label         StringView
	AddressModeU  AddressMode
	AddressModeV  AddressMode
	AddressModeW  AddressMode
	MagFilter     FilterMode
	MinFilter     FilterMode
	MipmapFilter  MipmapFilterMode
	LodMinClamp   float32
	LodMaxClamp   float32
	Compare       CompareFunction
	MaxAnisotropy uint16
	// contains filtered or unexported fields
}

SamplerDescriptor describes a sampler to create.

type ShaderModule

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

ShaderModule represents a compiled shader.

func (*ShaderModule) Handle

func (s *ShaderModule) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*ShaderModule) Release

func (s *ShaderModule) Release()

Release releases the shader module resources.

type ShaderModuleDescriptor

type ShaderModuleDescriptor struct {
	NextInChain uintptr    // *ChainedStruct
	Label       StringView // Shader module label for debugging
}

ShaderModuleDescriptor describes a shader module to create.

type ShaderSourceWGSL

type ShaderSourceWGSL struct {
	Chain ChainedStruct
	Code  StringView
}

ShaderSourceWGSL provides WGSL source code for shader creation.

type ShaderStage

type ShaderStage uint64

ShaderStage identifies which shader stages can access a binding.

const (
	ShaderStageNone     ShaderStage = 0x0000000000000000
	ShaderStageVertex   ShaderStage = 0x0000000000000001
	ShaderStageFragment ShaderStage = 0x0000000000000002
	ShaderStageCompute  ShaderStage = 0x0000000000000004
)

type StencilFaceState

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

StencilFaceState describes stencil operations for a face.

type StencilOperation

type StencilOperation uint32

StencilOperation describes stencil buffer operations.

const (
	StencilOperationUndefined      StencilOperation = 0x00000000
	StencilOperationKeep           StencilOperation = 0x00000001
	StencilOperationZero           StencilOperation = 0x00000002
	StencilOperationReplace        StencilOperation = 0x00000003
	StencilOperationInvert         StencilOperation = 0x00000004
	StencilOperationIncrementClamp StencilOperation = 0x00000005
	StencilOperationDecrementClamp StencilOperation = 0x00000006
	StencilOperationIncrementWrap  StencilOperation = 0x00000007
	StencilOperationDecrementWrap  StencilOperation = 0x00000008
)

type StorageTextureAccess

type StorageTextureAccess uint32

StorageTextureAccess describes storage texture access mode.

const (
	StorageTextureAccessBindingNotUsed StorageTextureAccess = 0x00000000
	StorageTextureAccessUndefined      StorageTextureAccess = 0x00000001
	StorageTextureAccessWriteOnly      StorageTextureAccess = 0x00000002
	StorageTextureAccessReadOnly       StorageTextureAccess = 0x00000003
	StorageTextureAccessReadWrite      StorageTextureAccess = 0x00000004
)

type StorageTextureBindingLayout

type StorageTextureBindingLayout struct {
	NextInChain   uintptr // *ChainedStruct
	Access        StorageTextureAccess
	Format        TextureFormat
	ViewDimension TextureViewDimension
}

StorageTextureBindingLayout describes storage texture binding properties.

type StoreOp

type StoreOp uint32

StoreOp describes what happens to render target at the end of a pass.

const (
	StoreOpUndefined StoreOp = 0x00
	StoreOpStore     StoreOp = 0x01 // Write results to texture
	StoreOpDiscard   StoreOp = 0x02 // Discard (e.g., for depth after use)
)

type StringView

type StringView struct {
	Data   uintptr // *char
	Length uintptr // size_t, use SIZE_MAX for null-terminated
}

StringView represents a WebGPU string view (pointer + length).

func EmptyStringView

func EmptyStringView() StringView

EmptyStringView returns an empty string view (null label).

type SupportedLimits

type SupportedLimits struct {
	NextInChain uintptr // *ChainedStructOut
	Limits      Limits
}

SupportedLimits contains adapter limits.

type Surface

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

Surface represents a surface for presenting rendered images.

func (*Surface) Configure

func (s *Surface) Configure(config *SurfaceConfiguration)

Configure configures the surface for rendering. This replaces the deprecated SwapChain API.

func (*Surface) GetCurrentTexture

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

GetCurrentTexture gets the current texture to render to. Returns the texture and its status. Check status before using the texture.

func (*Surface) Handle

func (s *Surface) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Surface) Present

func (s *Surface) Present()

Present presents the current frame to the surface.

func (*Surface) Release

func (s *Surface) Release()

Release releases the surface.

func (*Surface) Unconfigure

func (s *Surface) Unconfigure()

Unconfigure removes the surface configuration.

type SurfaceConfiguration

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

SurfaceConfiguration describes how to configure a surface.

type SurfaceGetCurrentTextureStatus

type SurfaceGetCurrentTextureStatus uint32

SurfaceGetCurrentTextureStatus describes the result of GetCurrentTexture.

const (
	SurfaceGetCurrentTextureStatusSuccessOptimal    SurfaceGetCurrentTextureStatus = 0x01
	SurfaceGetCurrentTextureStatusSuccessSuboptimal SurfaceGetCurrentTextureStatus = 0x02
	SurfaceGetCurrentTextureStatusTimeout           SurfaceGetCurrentTextureStatus = 0x03
	SurfaceGetCurrentTextureStatusOutdated          SurfaceGetCurrentTextureStatus = 0x04
	SurfaceGetCurrentTextureStatusLost              SurfaceGetCurrentTextureStatus = 0x05
	SurfaceGetCurrentTextureStatusOutOfMemory       SurfaceGetCurrentTextureStatus = 0x06
	SurfaceGetCurrentTextureStatusDeviceLost        SurfaceGetCurrentTextureStatus = 0x07
	SurfaceGetCurrentTextureStatusError             SurfaceGetCurrentTextureStatus = 0x08
)

type SurfaceTexture

type SurfaceTexture struct {
	Texture *Texture
	Status  SurfaceGetCurrentTextureStatus
}

SurfaceTexture holds the result of GetCurrentTexture.

type TexelCopyBufferInfo

type TexelCopyBufferInfo struct {
	Layout TexelCopyBufferLayout
	Buffer uintptr // Buffer handle
}

TexelCopyBufferInfo describes a buffer source/destination for copy operations.

type TexelCopyBufferLayout

type TexelCopyBufferLayout struct {
	Offset       uint64
	BytesPerRow  uint32
	RowsPerImage uint32
}

TexelCopyBufferLayout describes buffer layout for WriteTexture.

type TexelCopyTextureInfo

type TexelCopyTextureInfo struct {
	Texture  uintptr
	MipLevel uint32
	Origin   Origin3D
	Aspect   TextureAspect
}

TexelCopyTextureInfo describes a texture for WriteTexture.

type Texture

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

Texture represents a WebGPU texture.

func (*Texture) CreateView

func (t *Texture) CreateView(desc *TextureViewDescriptor) *TextureView

CreateView creates a view into this texture. Pass nil for default view parameters.

func (*Texture) Destroy

func (t *Texture) Destroy()

Destroy destroys the texture.

func (*Texture) GetDepthOrArrayLayers

func (t *Texture) GetDepthOrArrayLayers() uint32

GetDepthOrArrayLayers returns the depth (for 3D textures) or array layer count.

func (*Texture) GetFormat

func (t *Texture) GetFormat() TextureFormat

GetFormat returns the texture format.

func (*Texture) GetHeight

func (t *Texture) GetHeight() uint32

GetHeight returns the height of the texture in texels.

func (*Texture) GetMipLevelCount

func (t *Texture) GetMipLevelCount() uint32

GetMipLevelCount returns the number of mip levels.

func (*Texture) GetWidth

func (t *Texture) GetWidth() uint32

GetWidth returns the width of the texture in texels.

func (*Texture) Handle

func (t *Texture) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*Texture) Release

func (t *Texture) Release()

Release releases the texture reference.

type TextureAspect

type TextureAspect uint32

TextureAspect describes which aspect of a texture to access.

const (
	TextureAspectUndefined   TextureAspect = 0x00
	TextureAspectAll         TextureAspect = 0x01
	TextureAspectStencilOnly TextureAspect = 0x02
	TextureAspectDepthOnly   TextureAspect = 0x03
)

type TextureBindingLayout

type TextureBindingLayout struct {
	NextInChain   uintptr // *ChainedStruct
	SampleType    TextureSampleType
	ViewDimension TextureViewDimension
	Multisampled  Bool
}

TextureBindingLayout describes texture binding properties.

type TextureDescriptor

type TextureDescriptor struct {
	NextInChain     uintptr
	Label           StringView
	Usage           TextureUsage
	Dimension       TextureDimension
	Size            Extent3D
	Format          TextureFormat
	MipLevelCount   uint32
	SampleCount     uint32
	ViewFormatCount uintptr
	ViewFormats     uintptr
}

TextureDescriptor describes a texture to create.

type TextureDimension

type TextureDimension uint32

TextureDimension specifies the dimensionality of a texture.

const (
	TextureDimensionUndefined TextureDimension = 0x00
	TextureDimension1D        TextureDimension = 0x01
	TextureDimension2D        TextureDimension = 0x02
	TextureDimension3D        TextureDimension = 0x03
)

type TextureFormat

type TextureFormat uint32

TextureFormat describes the format of texture data.

const (
	TextureFormatUndefined            TextureFormat = 0x00
	TextureFormatR8Unorm              TextureFormat = 0x01
	TextureFormatR8Snorm              TextureFormat = 0x02
	TextureFormatR8Uint               TextureFormat = 0x03
	TextureFormatR8Sint               TextureFormat = 0x04
	TextureFormatR16Uint              TextureFormat = 0x05
	TextureFormatR16Sint              TextureFormat = 0x06
	TextureFormatR16Float             TextureFormat = 0x07
	TextureFormatRG8Unorm             TextureFormat = 0x08
	TextureFormatRG8Snorm             TextureFormat = 0x09
	TextureFormatRG8Uint              TextureFormat = 0x0A
	TextureFormatRG8Sint              TextureFormat = 0x0B
	TextureFormatR32Float             TextureFormat = 0x0C
	TextureFormatR32Uint              TextureFormat = 0x0D
	TextureFormatR32Sint              TextureFormat = 0x0E
	TextureFormatRG16Uint             TextureFormat = 0x0F
	TextureFormatRG16Sint             TextureFormat = 0x10
	TextureFormatRG16Float            TextureFormat = 0x11
	TextureFormatRGBA8Unorm           TextureFormat = 0x12
	TextureFormatRGBA8UnormSrgb       TextureFormat = 0x13
	TextureFormatRGBA8Snorm           TextureFormat = 0x14
	TextureFormatRGBA8Uint            TextureFormat = 0x15
	TextureFormatRGBA8Sint            TextureFormat = 0x16
	TextureFormatBGRA8Unorm           TextureFormat = 0x17
	TextureFormatBGRA8UnormSrgb       TextureFormat = 0x18
	TextureFormatRGBA16Float          TextureFormat = 0x21
	TextureFormatRGBA32Float          TextureFormat = 0x23
	TextureFormatStencil8             TextureFormat = 0x26
	TextureFormatDepth16Unorm         TextureFormat = 0x27
	TextureFormatDepth24Plus          TextureFormat = 0x28
	TextureFormatDepth24PlusStencil8  TextureFormat = 0x29
	TextureFormatDepth32Float         TextureFormat = 0x2A
	TextureFormatDepth32FloatStencil8 TextureFormat = 0x2B
)

type TextureSampleType

type TextureSampleType uint32

TextureSampleType describes how a texture is sampled.

const (
	TextureSampleTypeBindingNotUsed    TextureSampleType = 0x00000000
	TextureSampleTypeUndefined         TextureSampleType = 0x00000001
	TextureSampleTypeFloat             TextureSampleType = 0x00000002
	TextureSampleTypeUnfilterableFloat TextureSampleType = 0x00000003
	TextureSampleTypeDepth             TextureSampleType = 0x00000004
	TextureSampleTypeSint              TextureSampleType = 0x00000005
	TextureSampleTypeUint              TextureSampleType = 0x00000006
)

type TextureUsage

type TextureUsage uint64

TextureUsage describes how a texture will be used.

const (
	TextureUsageNone             TextureUsage = 0x00
	TextureUsageCopySrc          TextureUsage = 0x01
	TextureUsageCopyDst          TextureUsage = 0x02
	TextureUsageTextureBinding   TextureUsage = 0x04
	TextureUsageStorageBinding   TextureUsage = 0x08
	TextureUsageRenderAttachment TextureUsage = 0x10
)

type TextureView

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

TextureView represents a view into a WebGPU texture.

func (*TextureView) Handle

func (tv *TextureView) Handle() uintptr

Handle returns the underlying handle. For advanced use only.

func (*TextureView) Release

func (tv *TextureView) Release()

Release releases the texture view reference.

type TextureViewDescriptor

type TextureViewDescriptor struct {
	NextInChain     uintptr
	Label           StringView
	Format          TextureFormat
	Dimension       TextureViewDimension
	BaseMipLevel    uint32
	MipLevelCount   uint32
	BaseArrayLayer  uint32
	ArrayLayerCount uint32
	Aspect          TextureAspect

	Usage TextureUsage
	// contains filtered or unexported fields
}

TextureViewDescriptor describes a texture view to create.

type TextureViewDimension

type TextureViewDimension uint32

TextureViewDimension describes the dimension of a texture view.

const (
	TextureViewDimensionUndefined TextureViewDimension = 0x00000000
	TextureViewDimension1D        TextureViewDimension = 0x00000001
	TextureViewDimension2D        TextureViewDimension = 0x00000002
	TextureViewDimension2DArray   TextureViewDimension = 0x00000003
	TextureViewDimensionCube      TextureViewDimension = 0x00000004
	TextureViewDimensionCubeArray TextureViewDimension = 0x00000005
	TextureViewDimension3D        TextureViewDimension = 0x00000006
)

type Vec3

type Vec3 struct {
	X, Y, Z float32
}

Vec3 represents a 3D vector with X, Y, Z components.

Example (Cross)

ExampleVec3_cross demonstrates cross product for normal calculation

package main

import (
	"fmt"

	"github.com/go-webgpu/webgpu/wgpu"
)

func main() {
	// Calculate normal for a triangle (right-hand rule)
	// Triangle vertices: v0, v1, v2
	v0 := wgpu.Vec3{X: 0, Y: 0, Z: 0}
	v1 := wgpu.Vec3{X: 1, Y: 0, Z: 0}
	v2 := wgpu.Vec3{X: 0, Y: 1, Z: 0}

	// Edge vectors
	edge1 := v1.Sub(v0)
	edge2 := v2.Sub(v0)

	// Normal = edge1 × edge2
	normal := edge1.Cross(edge2).Normalize()

	fmt.Printf("Triangle normal: (%.0f, %.0f, %.0f)\n", normal.X, normal.Y, normal.Z)
}
Output:

Triangle normal: (0, 0, 1)

func (Vec3) Cross

func (v Vec3) Cross(other Vec3) Vec3

Cross computes the cross product of this vector with another. Returns v × other (perpendicular to both vectors). Result follows right-hand rule.

func (Vec3) Dot

func (v Vec3) Dot(other Vec3) float32

Dot computes the dot product of this vector with another. Returns v · other (scalar projection).

func (Vec3) Normalize

func (v Vec3) Normalize() Vec3

Normalize returns a unit vector in the same direction as v. If v has zero length, returns zero vector.

func (Vec3) Sub

func (v Vec3) Sub(other Vec3) Vec3

Sub subtracts another vector from this vector. Returns v - other.

type Vec4

type Vec4 struct {
	X, Y, Z, W float32
}

Vec4 represents a 4D vector with X, Y, Z, W components. Compatible with WGSL vec4<f32>.

type VertexAttribute

type VertexAttribute struct {
	Format         VertexFormat
	Offset         uint64
	ShaderLocation uint32
	// contains filtered or unexported fields
}

VertexAttribute describes a vertex attribute.

type VertexBufferLayout

type VertexBufferLayout struct {
	ArrayStride uint64
	StepMode    VertexStepMode

	AttributeCount uintptr
	Attributes     *VertexAttribute
	// contains filtered or unexported fields
}

VertexBufferLayout describes how vertex data is laid out in a buffer.

type VertexFormat

type VertexFormat uint32

VertexFormat describes the format of vertex attribute data.

const (
	VertexFormatUint8     VertexFormat = 0x01
	VertexFormatUint8x2   VertexFormat = 0x02
	VertexFormatUint8x4   VertexFormat = 0x03
	VertexFormatSint8     VertexFormat = 0x04
	VertexFormatSint8x2   VertexFormat = 0x05
	VertexFormatSint8x4   VertexFormat = 0x06
	VertexFormatUnorm8    VertexFormat = 0x07
	VertexFormatUnorm8x2  VertexFormat = 0x08
	VertexFormatUnorm8x4  VertexFormat = 0x09
	VertexFormatSnorm8    VertexFormat = 0x0A
	VertexFormatSnorm8x2  VertexFormat = 0x0B
	VertexFormatSnorm8x4  VertexFormat = 0x0C
	VertexFormatUint16    VertexFormat = 0x0D
	VertexFormatUint16x2  VertexFormat = 0x0E
	VertexFormatUint16x4  VertexFormat = 0x0F
	VertexFormatSint16    VertexFormat = 0x10
	VertexFormatSint16x2  VertexFormat = 0x11
	VertexFormatSint16x4  VertexFormat = 0x12
	VertexFormatUnorm16   VertexFormat = 0x13
	VertexFormatUnorm16x2 VertexFormat = 0x14
	VertexFormatUnorm16x4 VertexFormat = 0x15
	VertexFormatSnorm16   VertexFormat = 0x16
	VertexFormatSnorm16x2 VertexFormat = 0x17
	VertexFormatSnorm16x4 VertexFormat = 0x18
	VertexFormatFloat16   VertexFormat = 0x19
	VertexFormatFloat16x2 VertexFormat = 0x1A
	VertexFormatFloat16x4 VertexFormat = 0x1B
	VertexFormatFloat32   VertexFormat = 0x1C
	VertexFormatFloat32x2 VertexFormat = 0x1D
	VertexFormatFloat32x3 VertexFormat = 0x1E
	VertexFormatFloat32x4 VertexFormat = 0x1F
	VertexFormatUint32    VertexFormat = 0x20
	VertexFormatUint32x2  VertexFormat = 0x21
	VertexFormatUint32x3  VertexFormat = 0x22
	VertexFormatUint32x4  VertexFormat = 0x23
	VertexFormatSint32    VertexFormat = 0x24
	VertexFormatSint32x2  VertexFormat = 0x25
	VertexFormatSint32x3  VertexFormat = 0x26
	VertexFormatSint32x4  VertexFormat = 0x27
)

type VertexState

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

VertexState describes the vertex stage of a render pipeline.

type VertexStepMode

type VertexStepMode uint32

VertexStepMode describes how vertex buffer is advanced.

const (
	VertexStepModeUndefined           VertexStepMode = 0x00
	VertexStepModeVertexBufferNotUsed VertexStepMode = 0x01
	VertexStepModeVertex              VertexStepMode = 0x02
	VertexStepModeInstance            VertexStepMode = 0x03
)

type WGPUStatus

type WGPUStatus uint32

WGPUStatus describes the status returned from certain WebGPU operations.

const (
	WGPUStatusSuccess WGPUStatus = 0x00000000
	WGPUStatusError   WGPUStatus = 0x00000001
)

Jump to

Keyboard shortcuts

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