webgpu

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: BSD-3-Clause Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package webgpu will host the WebGPU implementation of the backend-neutral gpu.Painter interface (WebGPU migration, pre-rebrand issue #198, Phase 2 / pre-rebrand tracker #201).

At this stage the package only carries the WGSL shader ports (pre-rebrand tracker #205); the concrete painter is added in Phase 2. The shaders are embedded so the eventual painter can create shader modules without touching the filesystem, mirroring internal/painter/gl/shaders.go.

Shader porting conventions

Each GLSL desktop/_es pair (internal/painter/gl/shaders) collapses to a single WGSL module in shaders/, containing both the vertex and fragment entry points. Entry points follow a fixed naming convention so the painter can look them up without per-shader configuration:

  • vertex: vs_main
  • fragment: fs_main (blur additionally exposes fs_main_h / fs_main_v)

Coordinate systems differ between OpenGL and WebGPU; the ports preserve the GL fragment math exactly by translating at the boundary:

  • Clip space: both APIs use x,y in [-1,1] with +y up, so the NDC vertex positions are fed unchanged. (WebGPU's z range is [0,1] vs GL's [-1,1], but every 2D shader here writes z=0, which is valid in both.)

  • Framebuffer space: GL's gl_FragCoord has its origin bottom-left (y-up) while WebGPU's @builtin(position) has its origin top-left (y-down). The SDF shaders that sample the framebuffer position reconstruct the GL convention as vec2(pos.x, frame_size.y - pos.y) before applying inv_transform, so the SDF body stays byte-for-byte identical to the GLSL. frame_size is in framebuffer pixels (== gl_FragCoord's range), so frame_size.y is the correct flip pivot.

  • inv_transform is uploaded by the painter exactly as in GL (it already maps GL pixel space back to untransformed pixel space; see gl.painter.uploadInvTransform).

  • Texture V axis: GL samples with v=0 at the bottom, WebGPU with v=0 at the top. This is a texture-upload/sampling concern handled by the painter, not the shader — the WGSL samples texCoord as given.

Uniform buffer layout

WGSL uniform buffers follow std140-like alignment (f32:4, vec2:8, vec3/vec4: 16, mat3x3:48 with 16-byte column stride, mat4x4:64). Each module's uniform struct is declared field-by-field with its byte offset noted so the painter can populate the buffer with a matching memory layout.

Package webgpu provides a WebGPU implementation of the backend-neutral gpu.Painter (WebGPU migration, pre-rebrand tracker #198). The shader ports and the device-independent pipeline/uniform/layout foundation compile on every platform; the GPU-facing painter here pulls in the cgo wgpu-native binding and is now the default backend (Phase 5, pre-rebrand tracker #204). The legacy OpenGL painter is the fallback behind the `gl` build tag.

Default build uses this painter; for the GL fallback build with: go build -tags gl ...

Index

Constants

View Source
const (
	// VertexEntry is the vertex entry point present in every shader module.
	VertexEntry = "vs_main"
	// FragmentEntry is the fragment entry point present in every shader module
	// except blur, which exposes BlurFragmentEntryH / BlurFragmentEntryV.
	FragmentEntry = "fs_main"
	// BlurFragmentEntryH is the horizontal-pass fragment entry of the blur shader.
	BlurFragmentEntryH = "fs_main_h"
	// BlurFragmentEntryV is the vertical-pass fragment entry of the blur shader.
	BlurFragmentEntryV = "fs_main_v"
	// SimpleSoftFragmentEntry is the simple shader's second fragment entry,
	// which draws the faintest texels too (#442).
	SimpleSoftFragmentEntry = "fs_main_soft"
)

Entry-point naming convention shared by every WGSL module (see doc.go).

View Source
const QuadInstanceFloats = 24

QuadInstanceFloats is the number of float32s in one quad instance.

Variables

View Source
var ErrDeviceLost = errors.New("webgpu: the GPU device was lost")

ErrDeviceLost is BeginFrame's error once the GPU device is lost: a driver reset, or the device destroyed. Nothing more can be drawn with the Device; the painter makes a new one (#1150).

Functions

func Mat3ToStd140

func Mat3ToStd140(m [9]float32) [12]float32

Mat3ToStd140 expands a column-major 3x3 matrix (9 floats, as produced by geo.Matrix.ToGL) into the std140 layout used for a WGSL mat3x3<f32>: three columns each padded from vec3 to vec4 (the 4th float of every column unused).

func Names

func Names() []string

Names returns the names of the available WGSL shader modules.

func NewPainter

func NewPainter(c core.Canvas, ctx driver.WithContext) gpu.Painter

NewPainter creates a WebGPU renderer for the provided canvas. It matches the gl.NewPainter signature so the driver can swap backends at the call site. The driver must supply a surface descriptor (via SetSurfaceDescriptor, using the platform bridge) before Init brings the device up.

func ShaderSource

func ShaderSource(name string) []byte

ShaderSource returns the WGSL source for the named shader module (e.g. "round_rectangle"). It returns nil if the name is unknown. The returned module contains both the vertex (VertexEntry) and fragment (FragmentEntry, or the blur pair) entry points.

Types

type ArcUniforms

type ArcUniforms struct {
	FrameSize    [2]float32 // offset 0
	EdgeSoftness float32    // offset 8
	InnerRadius  float32    // offset 12
	RectCoords   [4]float32 // offset 16
	OuterRadius  float32    // offset 32
	StartAngle   float32    // offset 36
	EndAngle     float32    // offset 40
	CornerRadius float32    // offset 44
	FillColor    [4]float32 // offset 48
	StrokeWidth  float32    // offset 64

	StrokeColor  [4]float32  // offset 80
	InvTransform [12]float32 // offset 96
	// contains filtered or unexported fields
}

ArcUniforms matches shaders/arc.wgsl (size 144).

type BlendMode

type BlendMode int

BlendMode selects a color-target blend state, mirroring the GL BlendFunc pairs the painter uses.

const (
	// BlendOver is straight (non-premultiplied) alpha over: src*srcA + dst*(1-srcA).
	BlendOver BlendMode = iota
	// BlendPremul is premultiplied alpha over: src*1 + dst*(1-srcA). Used where
	// the shader already multiplies rgb by alpha (ripple, blur).
	BlendPremul
	// BlendReplace writes the source unchanged (no blending).
	BlendReplace
)

type BlurUniforms

type BlurUniforms struct {
	Resolution [2]float32 // offset 0
	BlurRadius float32    // offset 8
	// contains filtered or unexported fields
}

BlurUniforms matches shaders/blur.wgsl (size 16, incl. trailing pad to 16).

type Descriptor

type Descriptor struct {
	Name         string       // matches ShaderSource / Names
	Vertex       VertexLayout // interleaved vertex layout
	Textured     bool         // true if the shader binds a texture+sampler at bindings 1 & 2
	DefaultBlend BlendMode    // blend mode the painter uses by default for this shader
	Topology     Topology     // primitive topology for this shader's geometry
}

Descriptor bundles the per-shader data the pipeline cache needs.

func DescriptorFor

func DescriptorFor(name string) (Descriptor, bool)

DescriptorFor returns the pipeline descriptor for the named shader, and false if the name is unknown.

type Device

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

Device owns the WebGPU instance/adapter/device/queue/surface and the caches (shader modules, pipelines) shared by the painter. It is the WebGPU analogue of the GL painter's per-platform context plus its ProgramState set, built from the backend-neutral descriptors in layout.go and the WGSL in shaders/.

This is the device-dependent half of WebGPU Phase 2 (pre-rebrand tracker #201): PSO management keyed by shader+blend+format, bind groups for uniforms+texture/sampler, a per-frame command encoder + render pass, and surface acquire/present. The draw-op geometry (Paint dispatch) is layered on top in painter.go.

func NewDevice

func NewDevice(sd *wgpu.SurfaceDescriptor, width, height int) (d *Device, err error)

NewDevice brings up WebGPU against the given surface (created from a native window handle by the platform surface bridge) at the initial pixel size.

func (*Device) AppendInstance added in v1.2.0

func (d *Device) AppendInstance(key PipelineKey, uniform []byte, view *wgpu.TextureView, inst []float32, x, y, w, h int)

AppendInstance adds one instance to the pending batch, which is drawn with a single instanced draw when anything else touches the pass: another draw, a scissor or stencil change, a target push or pop, or the end of the frame (#475). An instance wholly outside the pass's clip is dropped, as Record drops a draw. rect is the instance's pixel bounds, for that test.

func (*Device) BeginFrame

func (d *Device) BeginFrame(clear wgpu.Color) error

func (*Device) CaptureImage

func (d *Device) CaptureImage() *image.RGBA

CaptureImage reads the last presented frame back into an *image.RGBA, or nil if no frame has been captured yet (the per-frame copy starts after EnableCapture). Channels are normalized to RGBA even when the surface format is BGRA.

func (*Device) CaptureTexture

func (d *Device) CaptureTexture(tex *wgpu.Texture, w, h int) *image.RGBA

CaptureTexture reads back an arbitrary texture (surface format, CopySrc) into an *image.RGBA. Used as the first-capture fallback that reads the persistent canvas FBO directly, before the per-frame copy has been populated (pre-rebrand tracker #219).

func (*Device) ClearScissor

func (d *Device) ClearScissor()

ClearScissor resets the scissor rectangle to the full active render target.

func (*Device) CopyActiveTargetRegion

func (d *Device) CopyActiveTargetRegion(x, y, w, h int) (*Texture, int, int, error)

CopyActiveTargetRegion copies a pixel rectangle of the current render target into a fresh sampled texture, for backdrop blur (pre-rebrand tracker #223): the already-rendered content under a widget is captured, blurred, and drawn back. The active pass is ended for the copy (a GPU copy cannot run inside a render pass) and reopened with LoadOp=Load afterwards so its contents are preserved. The region is clamped to the target and the clamped width/height returned (so the caller can size the blur to match); the returned texture is owned by the caller (release it, e.g. via ReleaseTextureAfterFrame).

func (*Device) CreateAtlasTexture added in v1.2.0

func (d *Device) CreateAtlasTexture(w, h int) (*Texture, error)

CreateAtlasTexture creates an empty w×h RGBA texture that WriteTextureRegion fills piece by piece: the glyph atlas of the batched painter (#475).

func (*Device) CreateImageTexture

func (d *Device) CreateImageTexture(img image.Image) (*Texture, error)

CreateImageTexture creates a persistent sampled RGBA8 texture from a Go image. Ownership transfers to the caller (the painter's texture cache), which must Release it. The image's raw 8-bit RGBA bytes are uploaded as-is.

func (*Device) CreateRenderTexture

func (d *Device) CreateRenderTexture(w, h int) (*Texture, error)

CreateRenderTexture creates an off-screen color target (e.g. a RepaintBoundary FBO) in the surface format — so the cached render pipelines, keyed by the surface format, work unchanged when rendering into it — usable both as a render attachment and a sampled texture for the later blit.

func (*Device) CreateYCbCrTexture added in v1.3.0

func (d *Device) CreateYCbCrTexture(img *image.YCbCr) (*Texture, error)

CreateYCbCrTexture creates an RGBA texture for frames of img's size and layout, with the plane textures and bind group WriteYCbCr converts through. It does not convert img: call WriteYCbCr for that.

func (*Device) Culls added in v1.2.0

func (d *Device) Culls(x, y, w, h int) bool

Culls reports whether a draw covering the pixel rect (x, y, w, h) of the active render target would produce no pixels, because the rect lies wholly outside the clip the open pass applies. It answers false when no pass is open: nothing is known, so nothing may be skipped.

func (*Device) Destroy

func (d *Device) Destroy()

Destroy releases every GPU resource. Safe to call on a partially-built Device.

func (*Device) DiscardFrame

func (d *Device) DiscardFrame()

DiscardFrame abandons an open frame without presenting it: it ends the render pass, drops the unsubmitted command encoder, and releases the acquired surface texture (the SurfaceOutput) and its view. A frame is left open when paint() begins one but the driver skips Present because the window is not visible; the held SurfaceOutput then makes the next surface reconfigure (Resize → Configure) or RecreateSurface a fatal WebGPU validation error ("SurfaceOutput must be dropped before a new Surface is made"). Callers invoke this before reconfiguring.

func (*Device) EnableCapture

func (d *Device) EnableCapture()

EnableCapture requests that EndFrame maintain the per-frame capture copy from now on (pre-rebrand tracker #219). Until this is called, the copy is skipped to save the per-frame GPU cost.

func (*Device) EndFrame

func (d *Device) EndFrame() error

EndFrame closes the render pass, copies the frame into the capture texture (so Capture can read it back later), submits the command buffer and presents.

func (*Device) Format

func (d *Device) Format() uint32

Format returns the surface's texture format as a neutral uint32, for use in PipelineKey.Format.

func (*Device) GPUFrameNanos

func (d *Device) GPUFrameNanos() (uint64, bool)

GPUFrameNanos returns the most recent frame's measured GPU drain time in nanoseconds, and whether a valid measurement is available.

func (*Device) HasOpenFrame

func (d *Device) HasOpenFrame() bool

HasOpenFrame reports whether BeginFrame acquired a surface texture that has not yet been presented or discarded.

func (*Device) Pass

func (d *Device) Pass() *wgpu.RenderPassEncoder

Pass returns the active render pass (valid between BeginFrame and EndFrame).

func (*Device) Pipeline

func (d *Device) Pipeline(key PipelineKey) (*wgpu.RenderPipeline, error)

Pipeline returns the cached/built pipeline for the key.

func (*Device) PopTarget

func (d *Device) PopTarget()

func (*Device) PushOffscreenTarget

func (d *Device) PushOffscreenTarget(t *Texture, w, h int, clear wgpu.Color)

PushOffscreenTarget pushes an off-screen render target whose first pass clears the color to the given value and gets a fresh DEDICATED depth-stencil attachment (cleared to far / 0). The dedicated attachment — rather than the shared size-keyed one — keeps the off-screen pass's depth/stencil from aliasing, and thus clearing, the canvas pass's stencil clip when the pixel sizes coincide (pre-rebrand tracker #231). It is released after the frame is submitted (frameDepths). Falls back to the shared attachment if the dedicated one cannot be created. Used by Scene3D (z-buffering, pre-rebrand tracker #231) and by the box-shadow / blur off-screen passes (pre-rebrand tracker #223), which need the same clip isolation.

func (*Device) PushTarget

func (d *Device) PushTarget(t *Texture, w, h int)

PushTarget / PopTarget expose the render-target stack to the painter's RepaintBoundary implementation (boundary.go). The pushed *Texture is kept on the stack entry so a nested backdrop blur can read it back (pre-rebrand tracker #223).

func (*Device) PushTargetLoad

func (d *Device) PushTargetLoad(t *Texture, w, h int)

PushTargetLoad pushes a render target whose first pass preserves (LoadOp=Load) the texture's existing contents instead of clearing them. Used for the persistent canvas FBO (canvas_fbo.go), so a dirty-region partial repaint keeps the previous frame's pixels outside the redrawn region.

func (*Device) Record

func (d *Device) Record(dc DrawCall) error

Record draws dc into the active render pass. The common path packs the draw's vertices and uniform block into the per-frame arenas (flushed with one WriteBuffer each in EndFrame) and indexes them via a vertex byte offset and a uniform dynamic offset; a draw that would overflow the arena's current capacity falls back to transient per-draw buffers (and the arena grows for the next frame). Must be called between BeginFrame and EndFrame.

func (*Device) RecreateSurface

func (d *Device) RecreateSurface(sd *wgpu.SurfaceDescriptor)

RecreateSurface rebuilds the presentation surface from a new native-window descriptor, keeping the existing device/adapter/queue/pipelines. Android destroys the ANativeWindow when the app is backgrounded and delivers a fresh handle on resume; without rebuilding the surface the painter keeps presenting to the destroyed one — a black canvas and a main-thread stall/ANR (pre-rebrand tracker #310).

func (*Device) ReleaseSurface

func (d *Device) ReleaseSurface()

ReleaseSurface drops this device's presentation surface without tearing down the device/adapter/queue/pipelines, so another window's surface can take over the shared Android ANativeWindow — two configured Vulkan swapchains on one native window can't both present (pre-rebrand tracker #753). The surface is rebuilt by RecreateSurface when this window is presented again. No-op if already surfaceless.

func (*Device) ReleaseTextureAfterFrame

func (d *Device) ReleaseTextureAfterFrame(t *Texture)

ReleaseTextureAfterFrame defers a transient texture's release until the frame is submitted, so draws that sample it stay valid until the GPU is done with them. Used by the box-shadow / backdrop-blur ping-pong + capture targets (pre-rebrand tracker #223).

func (*Device) Resize

func (d *Device) Resize(width, height int)

Resize reconfigures the surface for a new pixel size. It is a no-op when the size is unchanged: the mobile paint loop calls SetOutputSize on every frame (driver.paintWindow), so reconfiguring unconditionally would re-run surface.Configure per frame — wasted work, and on iOS/Metal it makes wgpu re-read the CAMetalLayer view dimensions from the render goroutine, flooding the log with "Unable to get the current view dimensions on a non-main thread" (pre-rebrand tracker #262). Only an actual size change needs a reconfigure.

func (*Device) SetScissor

func (d *Device) SetScissor(x, y, w, h int)

SetScissor restricts subsequent draws to the given pixel rectangle. The rect is remembered so it can be restored after a render-target pop (pre-rebrand tracker #235). The rect is clamped to the active render target's bounds: WebGPU rejects a scissor that extends past the attachment (a validation error that can escalate to a lost device), and dirty-region / clip rects are padded and can spill a few pixels past the canvas edge.

func (*Device) SetStencilRef

func (d *Device) SetStencilRef(ref uint32)

SetStencilRef sets the active render pass's stencil reference value (used by the painter's clip / fill stencil ops). No-op outside a frame.

func (*Device) SetStencilZero added in v1.2.0

func (d *Device) SetStencilZero(zero bool)

SetStencilZero records whether the open pass's stencil is zero everywhere. Anything that writes the stencil without restoring it to zero sets false.

func (*Device) StencilZero added in v1.2.0

func (d *Device) StencilZero() bool

StencilZero reports whether the open pass's stencil is known to be zero everywhere.

func (*Device) WriteTexturePixels

func (d *Device) WriteTexturePixels(t *Texture, pix []byte, w, h int) error

WriteTexturePixels re-uploads premultiplied 8-bit RGBA pixels into an existing texture, the WebGPU counterpart of GL's TexSubImage2D. The dimensions must match the texture's allocation — a size change needs a fresh texture, which the caller detects via Texture.Size. Used by streaming rasters (#34) so video frames update in place instead of reallocating a texture every frame.

func (*Device) WriteTextureRegion added in v1.2.0

func (d *Device) WriteTextureRegion(t *Texture, x, y, w, h int, pix []byte)

WriteTextureRegion uploads w×h RGBA pixels into t at (x, y).

func (*Device) WriteYCbCr added in v1.3.0

func (d *Device) WriteYCbCr(t *Texture, img *image.YCbCr, matrix int, fullRange bool) error

WriteYCbCr uploads img's planes into t, which CreateYCbCrTexture made for frames like it, and converts them into t's RGBA by the given matrix and range. The conversion is submitted on its own, ahead of the frame being recorded, so it does not break the frame's render pass.

type DrawCall

type DrawCall struct {
	Key         PipelineKey
	Vertices    []float32
	VertexCount int
	Uniform     []byte
	TexView     *wgpu.TextureView // nil unless the shader samples a texture
	// InstanceCount draws VertexCount vertices that many times, with
	// Vertices holding per-instance data (a PerInstance layout). 0 means 1.
	InstanceCount int
}

DrawCall is one recorded draw: a pipeline (by key), an interleaved vertex buffer, the matching uniform block bytes, and an optional texture for the `simple`/`blur` shaders.

type GradientUniforms added in v1.3.0

type GradientUniforms struct {
	FrameSize [2]float32 // offset 0
	Size      [2]float32 // offset 8
	Origin    [2]float32 // offset 16
	Kind      float32    // offset 24
	StopCount float32    // offset 28
	Linear    [4]float32 // offset 32
	Radial    [4]float32 // offset 48
	Alpha     float32    // offset 64

	InvTransform [12]float32   // offset 80
	StopPos      [8]float32    // offset 128
	StopCol      [6][4]float32 // offset 160
	// contains filtered or unexported fields
}

GradientUniforms matches shaders/gradient.wgsl (size 256, the most a uniform block may be: uniformBlockStride).

type LineUniforms

type LineUniforms struct {
	Color     [4]float32 // offset 0
	LineWidth float32    // offset 16
	Feather   float32    // offset 20
	// contains filtered or unexported fields
}

LineUniforms matches shaders/line.wgsl (size 32, incl. trailing pad to 16).

type PathUniforms

type PathUniforms struct {
	FillColor [4]float32 // offset 0
}

PathUniforms matches shaders/path.wgsl (size 16).

type PipelineCache

type PipelineCache[T any] struct {
	// contains filtered or unexported fields
}

PipelineCache lazily builds and memoizes pipelines by key. It is generic over the pipeline handle type T so the device-independent caching logic is testable without the WebGPU binding; the //go:build webgpu painter instantiates it with *wgpu.RenderPipeline.

func NewPipelineCache

func NewPipelineCache[T any](build func(PipelineKey) (T, error)) *PipelineCache[T]

NewPipelineCache returns a cache that calls build once per distinct key.

func (*PipelineCache[T]) Get

func (c *PipelineCache[T]) Get(key PipelineKey) (T, error)

Get returns the pipeline for the key, building (and caching) it on first use.

func (*PipelineCache[T]) Len

func (c *PipelineCache[T]) Len() int

Len returns the number of cached pipelines.

func (*PipelineCache[T]) Release

func (c *PipelineCache[T]) Release(fn func(T))

Release calls fn for every cached pipeline and empties the cache. Used to free GPU resources (e.g. on a scale/format change or painter teardown).

type PipelineKey

type PipelineKey struct {
	Shader   string
	Fragment string
	Blend    BlendMode
	Stencil  StencilMode
	// Depth enables hardware z-buffering (depth write + less-than test) on top of
	// the always-present depth-stencil attachment. Only the Scene3D pipeline sets
	// it; every 2D op leaves it false (depth inert, compare Always, no write).
	Depth  bool
	Format uint32
}

PipelineKey identifies a unique render pipeline (PSO). A pipeline is keyed by the shader module, the fragment entry point (so blur's fs_main_h / fs_main_v get distinct pipelines), the blend mode, the depth-stencil mode, whether hardware depth testing is enabled (Scene3D z-buffering, pre-rebrand tracker #224), and the render-target texture format (kept as a neutral uint32 so this file stays free of GPU binding types).

type PolygonUniforms

type PolygonUniforms struct {
	FrameSize    [2]float32  // offset 0
	EdgeSoftness float32     // offset 8
	OuterRadius  float32     // offset 12
	RectCoords   [4]float32  // offset 16
	Angle        float32     // offset 32
	Sides        float32     // offset 36
	CornerRadius float32     // offset 40
	StrokeWidth  float32     // offset 44
	FillColor    [4]float32  // offset 48
	StrokeColor  [4]float32  // offset 64
	InvTransform [12]float32 // offset 80
}

PolygonUniforms matches shaders/polygon.wgsl (size 128).

type RectangleUniforms

type RectangleUniforms struct {
	FrameSize   [2]float32 // offset 0
	StrokeWidth float32    // offset 8

	RectCoords   [4]float32  // offset 16
	FillColor    [4]float32  // offset 32
	StrokeColor  [4]float32  // offset 48
	InvTransform [12]float32 // offset 64 (mat3x3, 16-byte column stride)
	// contains filtered or unexported fields
}

RectangleUniforms matches shaders/rectangle.wgsl (size 112).

type RippleUniforms

type RippleUniforms struct {
	FrameSize    [2]float32  // offset 0
	EdgeSoftness float32     // offset 8
	RippleRadius float32     // offset 12
	RectCoords   [4]float32  // offset 16
	RectSizeHalf [2]float32  // offset 32
	RippleCenter [2]float32  // offset 40
	Radius       [4]float32  // offset 48 (tr, br, tl, bl)
	RippleColor  [4]float32  // offset 64
	InvTransform [12]float32 // offset 80
}

RippleUniforms matches shaders/ripple.wgsl (size 128).

type RoundRectangleUniforms

type RoundRectangleUniforms struct {
	FrameSize       [2]float32 // offset 0
	StrokeWidthHalf float32    // offset 8
	EdgeSoftness    float32    // offset 12
	RectCoords      [4]float32 // offset 16
	RectSizeHalf    [2]float32 // offset 32

	Radius       [4]float32  // offset 48
	FillColor    [4]float32  // offset 64
	StrokeColor  [4]float32  // offset 80
	InvTransform [12]float32 // offset 96
	// contains filtered or unexported fields
}

RoundRectangleUniforms matches shaders/round_rectangle.wgsl (size 144).

type Scene3DUniforms

type Scene3DUniforms struct {
	MVP      [16]float32 // offset 0  (mat4x4)
	LightDir [3]float32  // offset 64 (vec3)

	LightColor [3]float32 // offset 80 (vec3)
	Ambient    float32    // offset 92
	// contains filtered or unexported fields
}

Scene3DUniforms matches shaders/scene3d.wgsl (size 96).

type SimpleUniforms

type SimpleUniforms struct {
	Alpha        float32    // offset 0
	CornerRadius float32    // offset 4
	Size         [2]float32 // offset 8
	Inset        [4]float32 // offset 16
}

SimpleUniforms matches shaders/simple.wgsl (size 32).

type StencilMode

type StencilMode int

StencilMode selects the depth-stencil state baked into a pipeline (stencil clipping + path fill, pre-rebrand tracker #202/#222). Every pipeline carries one so it validates against the depth-stencil attachment now present on every render pass; the default StencilNone disables stencil entirely (compare Always, no write) and writes color, matching the pre-stencil behaviour. The painter switches mode via the pipeline key while writing a clip mask or filling a path.

const (
	// StencilNone disables the stencil test and writes color (the default for
	// every normal draw): stencil compare Always, no stencil write.
	StencilNone StencilMode = iota
	// StencilWriteReplace writes the stencil reference to every bit where
	// fragments pass and masks color off: with ref 0 it zeroes the stencil,
	// emulating a mid-pass clear.
	StencilWriteReplace
	// StencilClearWinding zeroes the winding bits (paint.StencilWindingMask)
	// and keeps the clip depth, color masked off: a path op's fresh start
	// inside the rounded clips around it (#1015).
	StencilClearWinding
	// StencilClearDepth zeroes the depth bits and keeps the winding bits,
	// color masked off: a first rounded clip on a stencil not known to be
	// zero, inside a path clip as well.
	StencilClearDepth
	// StencilWriteIncrDecr increments the winding bits on front faces and
	// decrements them on back faces (non-zero winding), color masked off: the
	// path clip / fill winding pass outside every rounded clip.
	StencilWriteIncrDecr
	// StencilWriteIncrDecrInClip is StencilWriteIncrDecr only where the depth
	// bits equal the reference: the winding pass inside a rounded clip, which
	// so cuts the path (#1015).
	StencilWriteIncrDecrInClip
	// StencilWriteInvert inverts the winding bits, color masked off: the
	// even-odd fill winding pass.
	StencilWriteInvert
	// StencilWriteInvertInClip is StencilWriteInvert inside a rounded clip.
	StencilWriteInvertInClip
	// StencilTestEqual draws color only where the depth bits equal the
	// reference (rounded-rect clip content).
	StencilTestEqual
	// StencilTestNotEqual draws color only where the winding bits are not the
	// reference, 0 (path clip content and the path-fill bounding-box quad).
	StencilTestNotEqual
	// StencilStampBit0 to StencilStampBit3 stamp and erase a rounded clip's
	// depth: where the depth bits, all but bit n, equal the reference, they
	// are replaced with it, color masked off. Depth d stamps with bit
	// paint.ClipStampBit(d) and reference paint.ClipDepthCode(d), and erases
	// with paint.ClipDepthCode(d-1), so a nested clip only narrows the clip
	// around it (#1012, #1015).
	StencilStampBit0
	StencilStampBit1
	StencilStampBit2
	StencilStampBit3
	// StencilStampWinding replaces the depth bits with the reference where the
	// winding bits are non-zero, color masked off: a path clip becomes a
	// clip level, so what is drawn inside it, rounded clips included, is cut
	// by it (#1015).
	StencilStampWinding
)

type SurfaceStatusError

type SurfaceStatusError struct {
	Status wgpu.SurfaceGetCurrentTextureStatus
}

SurfaceStatusError carries a non-success surface-acquire status as an error. The bindings report the status in the returned SurfaceTexture rather than as an error, so acquireSurfaceTexture converts it here — keeping the classification below a pure function over an error, as the recovery path and its tests expect.

func (*SurfaceStatusError) Error

func (e *SurfaceStatusError) Error() string

type Texture

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

Texture is a sampled GPU texture owned by the caller (the painter's texture cache), as opposed to the transient per-frame textures. Release it via the painter's Free / dirty-texture lifecycle.

func (*Texture) FitsYCbCr added in v1.3.0

func (t *Texture) FitsYCbCr(img *image.YCbCr) bool

FitsYCbCr reports whether t was made by CreateYCbCrTexture for frames of img's size and layout, so WriteYCbCr can convert img into it.

func (*Texture) Release

func (t *Texture) Release()

Release frees the texture and its view, including its GPU memory, and the planes of a Y'CbCr texture.

func (*Texture) Size

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

Size reports the texture's allocated pixel dimensions.

func (*Texture) View

func (t *Texture) View() *wgpu.TextureView

View returns the texture view for use as a DrawCall.TexView.

type Topology

type Topology int

Topology is the primitive topology for a shader's geometry, mirroring the GL painter's DrawArrays mode (triangle strip for 4-vertex quads, triangle list for explicit triangles).

const (
	// TriangleList draws every 3 vertices as a separate triangle.
	TriangleList Topology = iota
	// TriangleStrip draws a connected strip (4-vertex quads).
	TriangleStrip
)

type VertexAttr

type VertexAttr struct {
	Location int          // @location in the WGSL vertex input
	Format   VertexFormat // scalar/vector float format
	Offset   int          // byte offset within the vertex
}

VertexAttr is one interleaved vertex attribute.

type VertexFormat

type VertexFormat int

VertexFormat is a vertex attribute's scalar/vector float format.

const (
	Float32 VertexFormat = iota + 1
	Float32x2
	Float32x3
	Float32x4
)

func (VertexFormat) Floats

func (f VertexFormat) Floats() int

Floats returns the number of 32-bit floats in the format.

func (VertexFormat) Size

func (f VertexFormat) Size() int

Size returns the byte size of the format.

type VertexLayout

type VertexLayout struct {
	Stride int // bytes per vertex
	Attrs  []VertexAttr
	// PerInstance steps the buffer once per instance instead of per vertex:
	// the shader builds each instance's quad from the vertex index (#475).
	PerInstance bool
}

VertexLayout describes one interleaved vertex buffer.

Directories

Path Synopsis
Package tintcheck holds a test that compiles every WGSL shader of the WebGPU painter (internal/painter/webgpu/shaders/*.wgsl) with a browser's WebGPU shader compiler — Chrome's Tint — in headless Chrome (#685).
Package tintcheck holds a test that compiles every WGSL shader of the WebGPU painter (internal/painter/webgpu/shaders/*.wgsl) with a browser's WebGPU shader compiler — Chrome's Tint — in headless Chrome (#685).

Jump to

Keyboard shortcuts

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