Documentation
¶
Overview ¶
Package webgpu is WebGPU for Go programs that run in the browser (GOOS=js GOARCH=wasm), in a window or a worker: typed handles named after the WebGPU IDL (https://www.w3.org/TR/webgpu/), errors as Go errors, promises awaited without blocking the event loop, and quotas an embedder can enforce on code it does not trust.
Shape ¶
g, err := webgpu.Navigator() // navigator.gpu
a, err := g.RequestAdapter(ctx, nil) // refuses a fallback adapter by default
d, err := a.RequestDevice(ctx, &webgpu.DeviceDescriptor{Quota: q})
b, err := d.CreateBuffer(webgpu.BufferDescriptor{Size: 64, Usage: webgpu.BufferUsageVertex | webgpu.BufferUsageCopyDst})
err = d.Queue().WriteBuffer(b, 0, vertices) // range checked here
enc, _ := d.CreateCommandEncoder("frame")
pass, _ := enc.BeginRenderPass(desc)
pass.SetPipeline(p); pass.SetVertexBuffer(0, b, 0, 0); pass.Draw(3, 1, 0, 0)
err = pass.End() // first refused command, if any
Descriptors are Go structs; a zero field is left out of the dictionary so the browser applies the specification's default.
Batched encoding ¶
A syscall/js call costs about ten times the WebGPU call it carries. A Recorder records a whole submit as uint32 words in Go and Submit replays it with one call into replay.js (ReplayJS, loaded once by InstallReplay), which issues the WebGPU calls from JavaScript. Every command is checked as in the direct API. Submissions are numbered on the device's timeline (package timeline): WaitSubmitted(ctx, seq) waits for the GPU, and completing a number completes every earlier one.
Errors ¶
WebGPU reports most mistakes asynchronously, as validation errors on the device that nobody sees without an error scope. This package checks what it can in Go first and returns a *BoundsError at the call: out-of-range buffer writes and copies, texture regions outside a mip level, linear layouts that do not fit their data (the specification's "validating linear texture data"), missing usages. Exceptions the browser throws are *JSError; device errors are *GPUError, through PushErrorScope and PopErrorScope or OnUncapturedError (delivered with the next round trip to the GPU process).
Promises ¶
RequestAdapter, RequestDevice, MapAsync, PopErrorScope, OnSubmittedWorkDone and the Create*PipelineAsync methods wait on a promise: only the calling goroutine blocks, the browser's event loop keeps running. They must not be called from a js.FuncOf callback, whose goroutine holds the event loop. Each takes a context.
Quotas ¶
A Quota bounds GPU memory (buffer and texture bytes, computed by the package: TextureBytes), live pipelines, WGSL source size, and the features and limits a device may require. It is charged before the browser is called and refunded on Destroy, Release, or the loss of the device; several devices may share one. Nothing is reachable except through a Device the embedder created.
Surfaces ¶
A Surface is an OffscreenCanvas with a WebGPU context: render into CurrentTexture, and Present moves the frame out as an ImageBitmap (standalone canvases are never presented by the browser). CanvasSupport returns ErrNoCanvasContext where the browser has no such context (Firefox outside Windows): the signal to fall back to another renderer.
Outside GOOS=js the package compiles (descriptors, validation, quotas) and Navigator does not exist.
Index ¶
- Constants
- Variables
- func CanvasSupport() error
- func DecodeDescriptor(kind wire.Kind, b []byte, resolve Resolver) (any, error)
- func EncodeDescriptor(desc any) (wire.Kind, []byte, error)
- func InstallReplay(ctx context.Context, url string) error
- func ReplayID(h any) (uint32, error)
- func ReplayInstalled() bool
- func TextureBytes(d TextureDescriptor) (int64, error)
- type Adapter
- type AdapterInfo
- type AddressMode
- type BindGroup
- type BindGroupDescriptor
- type BindGroupEntry
- type BindGroupLayout
- type BindGroupLayoutDescriptor
- type BindGroupLayoutEntry
- type BlendComponent
- type BlendFactor
- type BlendOperation
- type BlendState
- type BoundsError
- type Buffer
- func (b *Buffer) Destroy()
- func (b *Buffer) MapAsync(ctx context.Context, mode MapMode, offset, size uint64) error
- func (b *Buffer) ReadMapped(offset uint64, dst []byte) error
- func (b *Buffer) Size() uint64
- func (b *Buffer) Unmap() error
- func (b *Buffer) Usage() BufferUsage
- func (b *Buffer) WriteMapped(offset uint64, src []byte) error
- type BufferBindingLayout
- type BufferBindingType
- type BufferDescriptor
- type BufferUsage
- type CanvasAlphaMode
- type Color
- type ColorTargetState
- type ColorWrite
- type CommandBuffer
- type CommandEncoder
- func (e *CommandEncoder) BeginComputePass(label string) (*ComputePassEncoder, error)
- func (e *CommandEncoder) BeginRenderPass(desc RenderPassDescriptor) (*RenderPassEncoder, error)
- func (e *CommandEncoder) ClearBuffer(b *Buffer, offset, size uint64) error
- func (e *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64) error
- func (e *CommandEncoder) CopyBufferToTexture(src TexelCopyBufferInfo, dst TexelCopyTextureInfo, size Extent3D) error
- func (e *CommandEncoder) CopyTextureToBuffer(src TexelCopyTextureInfo, dst TexelCopyBufferInfo, size Extent3D) error
- func (e *CommandEncoder) CopyTextureToTexture(src, dst TexelCopyTextureInfo, size Extent3D) error
- func (e *CommandEncoder) Finish() (*CommandBuffer, error)
- func (o *CommandEncoder) Label() string
- func (o *CommandEncoder) Value() js.Value
- type CompareFunction
- type CompilationMessage
- type ComputePassEncoder
- func (p *ComputePassEncoder) DispatchWorkgroups(x, y, z uint32)
- func (p *ComputePassEncoder) DispatchWorkgroupsIndirect(b *Buffer, offset uint64)
- func (p *ComputePassEncoder) End() error
- func (o *ComputePassEncoder) Label() string
- func (p *ComputePassEncoder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
- func (p *ComputePassEncoder) SetPipeline(cp *ComputePipeline)
- func (o *ComputePassEncoder) Value() js.Value
- type ComputePassRecorder
- func (p *ComputePassRecorder) DispatchWorkgroups(x, y, z uint32)
- func (p *ComputePassRecorder) DispatchWorkgroupsIndirect(b *Buffer, offset uint64)
- func (p *ComputePassRecorder) End() error
- func (p *ComputePassRecorder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
- func (p *ComputePassRecorder) SetPipeline(pl *ComputePipeline)
- type ComputePipeline
- type ComputePipelineDescriptor
- type CullMode
- type DepthStencilState
- type Device
- func (d *Device) Completed() uint64
- func (d *Device) CreateBindGroup(desc BindGroupDescriptor) (*BindGroup, error)
- func (d *Device) CreateBindGroupLayout(desc BindGroupLayoutDescriptor) (*BindGroupLayout, error)
- func (d *Device) CreateBuffer(desc BufferDescriptor) (*Buffer, error)
- func (d *Device) CreateCommandEncoder(label string) (*CommandEncoder, error)
- func (d *Device) CreateComputePipeline(desc ComputePipelineDescriptor) (*ComputePipeline, error)
- func (d *Device) CreateComputePipelineAsync(ctx context.Context, desc ComputePipelineDescriptor) (*ComputePipeline, error)
- func (d *Device) CreatePipelineLayout(desc PipelineLayoutDescriptor) (*PipelineLayout, error)
- func (d *Device) CreateRenderBundleEncoder(desc RenderBundleEncoderDescriptor) (*RenderBundleEncoder, error)
- func (d *Device) CreateRenderPipeline(desc RenderPipelineDescriptor) (*RenderPipeline, error)
- func (d *Device) CreateRenderPipelineAsync(ctx context.Context, desc RenderPipelineDescriptor) (*RenderPipeline, error)
- func (d *Device) CreateSampler(desc *SamplerDescriptor) (*Sampler, error)
- func (d *Device) CreateShaderModule(desc ShaderModuleDescriptor) (*ShaderModule, error)
- func (d *Device) CreateTexture(desc TextureDescriptor) (*Texture, error)
- func (d *Device) Destroy()
- func (o *Device) Label() string
- func (d *Device) Limit(name string) (uint64, bool)
- func (d *Device) Lost() <-chan struct{}
- func (d *Device) LostInfo() DeviceLostInfo
- func (d *Device) NewRecorder() *Recorder
- func (d *Device) NewSurface(desc SurfaceDescriptor) (*Surface, error)
- func (d *Device) NewSurfaceFromCanvas(canvas js.Value, desc SurfaceDescriptor) (*Surface, error)
- func (d *Device) OnUncapturedError(fn func(error)) (remove func())
- func (d *Device) PopErrorScope(ctx context.Context) error
- func (d *Device) PushErrorScope(filter ErrorFilter)
- func (d *Device) Queue() *Queue
- func (d *Device) Quota() *Quota
- func (d *Device) ReadTexture(ctx context.Context, src TexelCopyTextureInfo, ...) ([]byte, error)
- func (d *Device) Replay(words []uint32, data []byte, refs ...any) (seq uint64, err error)
- func (d *Device) Submitted() uint64
- func (o *Device) Value() js.Value
- func (d *Device) WaitSubmitted(ctx context.Context, seq uint64) error
- type DeviceDescriptor
- type DeviceLostInfo
- type ErrorFilter
- type Extent3D
- type FeatureName
- type FilterMode
- type FormatInfo
- type FragmentState
- type FrontFace
- type GPU
- type GPUError
- type IndexFormat
- type JSError
- type LoadOp
- type MapMode
- type MipmapFilterMode
- type MultisampleState
- type Origin3D
- type PipelineLayout
- type PipelineLayoutDescriptor
- type PowerPreference
- type PrimitiveState
- type PrimitiveTopology
- type ProgrammableStage
- type Queue
- func (o *Queue) Label() string
- func (q *Queue) OnSubmittedWorkDone(ctx context.Context) error
- func (q *Queue) Submit(cbs ...*CommandBuffer) error
- func (o *Queue) Value() js.Value
- func (q *Queue) WriteBuffer(b *Buffer, offset uint64, data []byte) error
- func (q *Queue) WriteTexture(dst TexelCopyTextureInfo, data []byte, layout TexelCopyBufferLayout, ...) error
- type Quota
- type QuotaError
- type ReadSink
- type Readback
- type Recorder
- func (r *Recorder) BeginComputePass() *ComputePassRecorder
- func (r *Recorder) BeginRenderPass(desc RenderPassDescriptor) *RenderPassRecorder
- func (r *Recorder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64)
- func (r *Recorder) CopyTextureToTexture(src, dst TexelCopyTextureInfo, size Extent3D)
- func (r *Recorder) Err() error
- func (r *Recorder) Len() int
- func (r *Recorder) ReadBuffer(b *Buffer, offset, size uint64) *Readback
- func (r *Recorder) Reset()
- func (r *Recorder) Submit() (seq uint64, err error)
- func (r *Recorder) WriteBuffer(b *Buffer, offset uint64, data []byte)
- func (r *Recorder) WriteTexture(dst TexelCopyTextureInfo, data []byte, layout TexelCopyBufferLayout, ...)
- type RemoteSink
- type RenderBundle
- type RenderBundleEncoder
- func (r *RenderBundleEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
- func (r *RenderBundleEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, ...)
- func (r *RenderBundleEncoder) DrawIndexedIndirect(b *Buffer, offset uint64)
- func (r *RenderBundleEncoder) DrawIndirect(b *Buffer, offset uint64)
- func (r *RenderBundleEncoder) Err() error
- func (e *RenderBundleEncoder) Finish(label string) (*RenderBundle, error)
- func (r *RenderBundleEncoder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
- func (r *RenderBundleEncoder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
- func (r *RenderBundleEncoder) SetPipeline(p *RenderPipeline)
- func (r *RenderBundleEncoder) SetVertexBuffer(slot uint32, b *Buffer, offset, size uint64)
- type RenderBundleEncoderDescriptor
- type RenderPassColorAttachment
- type RenderPassDepthStencilAttachment
- type RenderPassDescriptor
- type RenderPassEncoder
- func (r *RenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
- func (r *RenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, ...)
- func (r *RenderPassEncoder) DrawIndexedIndirect(b *Buffer, offset uint64)
- func (r *RenderPassEncoder) DrawIndirect(b *Buffer, offset uint64)
- func (p *RenderPassEncoder) End() error
- func (r *RenderPassEncoder) Err() error
- func (p *RenderPassEncoder) ExecuteBundles(bundles ...*RenderBundle)
- func (r *RenderPassEncoder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
- func (p *RenderPassEncoder) SetBlendConstant(c Color)
- func (r *RenderPassEncoder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
- func (r *RenderPassEncoder) SetPipeline(p *RenderPipeline)
- func (p *RenderPassEncoder) SetScissorRect(x, y, w, h uint32)
- func (p *RenderPassEncoder) SetStencilReference(ref uint32)
- func (r *RenderPassEncoder) SetVertexBuffer(slot uint32, b *Buffer, offset, size uint64)
- func (p *RenderPassEncoder) SetViewport(x, y, w, h, minDepth, maxDepth float32)
- type RenderPassRecorder
- func (p *RenderPassRecorder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
- func (p *RenderPassRecorder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, ...)
- func (p *RenderPassRecorder) DrawIndexedIndirect(b *Buffer, offset uint64)
- func (p *RenderPassRecorder) DrawIndirect(b *Buffer, offset uint64)
- func (p *RenderPassRecorder) End() error
- func (p *RenderPassRecorder) ExecuteBundles(bundles ...*RenderBundle)
- func (p *RenderPassRecorder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
- func (p *RenderPassRecorder) SetBlendConstant(c Color)
- func (p *RenderPassRecorder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
- func (p *RenderPassRecorder) SetPipeline(pl *RenderPipeline)
- func (p *RenderPassRecorder) SetScissorRect(x, y, w, h uint32)
- func (p *RenderPassRecorder) SetStencilReference(ref uint32)
- func (p *RenderPassRecorder) SetVertexBuffer(slot uint32, b *Buffer, offset, size uint64)
- func (p *RenderPassRecorder) SetViewport(x, y, w, h, minDepth, maxDepth float32)
- type RenderPipeline
- type RenderPipelineDescriptor
- type RequestAdapterOptions
- type Resolver
- type Sampler
- type SamplerBindingLayout
- type SamplerBindingType
- type SamplerDescriptor
- type ShaderModule
- type ShaderModuleDescriptor
- type ShaderStage
- type StencilFaceState
- type StencilOperation
- type StorageTextureAccess
- type StorageTextureBindingLayout
- type StoreOp
- type Surface
- func (s *Surface) Canvas() js.Value
- func (s *Surface) CurrentTexture() (*Texture, error)
- func (s *Surface) CurrentView() (*TextureView, error)
- func (s *Surface) Destroy()
- func (s *Surface) Format() TextureFormat
- func (s *Surface) Present() (js.Value, error)
- func (s *Surface) Resize(width, height int) error
- func (s *Surface) Size() (width, height int)
- type SurfaceDescriptor
- type TexelCopyBufferInfo
- type TexelCopyBufferLayout
- type TexelCopyTextureInfo
- type Texture
- func (t *Texture) CreateView(desc *TextureViewDescriptor) (*TextureView, error)
- func (t *Texture) DepthOrArrayLayers() uint32
- func (t *Texture) Descriptor() TextureDescriptor
- func (t *Texture) Destroy()
- func (t *Texture) Format() TextureFormat
- func (t *Texture) Height() uint32
- func (t *Texture) Width() uint32
- type TextureAspect
- type TextureBindingLayout
- type TextureDescriptor
- type TextureDimension
- type TextureFormat
- type TextureSampleType
- type TextureUsage
- type TextureView
- type TextureViewCreation
- type TextureViewDescriptor
- type TextureViewDimension
- type VertexAttribute
- type VertexBufferLayout
- type VertexFormat
- type VertexState
- type VertexStepMode
Constants ¶
const ( TextureFormatR8Unorm TextureFormat = "r8unorm" TextureFormatR8Uint TextureFormat = "r8uint" TextureFormatRG8Unorm TextureFormat = "rg8unorm" TextureFormatR32Float TextureFormat = "r32float" TextureFormatR32Uint TextureFormat = "r32uint" TextureFormatRGBA8Unorm TextureFormat = "rgba8unorm" TextureFormatRGBA8UnormSRGB TextureFormat = "rgba8unorm-srgb" TextureFormatBGRA8Unorm TextureFormat = "bgra8unorm" TextureFormatBGRA8UnormSRGB TextureFormat = "bgra8unorm-srgb" TextureFormatRGBA16Float TextureFormat = "rgba16float" TextureFormatRGBA32Float TextureFormat = "rgba32float" TextureFormatStencil8 TextureFormat = "stencil8" TextureFormatDepth16Unorm TextureFormat = "depth16unorm" TextureFormatDepth24Plus TextureFormat = "depth24plus" TextureFormatDepth24PlusStencil8 TextureFormat = "depth24plus-stencil8" TextureFormatDepth32Float TextureFormat = "depth32float" TextureDimension1D TextureDimension = "1d" TextureDimension2D TextureDimension = "2d" TextureDimension3D TextureDimension = "3d" TextureViewDimension1D TextureViewDimension = "1d" TextureViewDimension2D TextureViewDimension = "2d" TextureViewDimension2DArray TextureViewDimension = "2d-array" TextureViewDimensionCube TextureViewDimension = "cube" TextureViewDimensionCubeArray TextureViewDimension = "cube-array" TextureViewDimension3D TextureViewDimension = "3d" TextureAspectAll TextureAspect = "all" TextureAspectStencilOnly TextureAspect = "stencil-only" TextureAspectDepthOnly TextureAspect = "depth-only" AddressModeClampToEdge AddressMode = "clamp-to-edge" AddressModeRepeat AddressMode = "repeat" AddressModeMirrorRepeat AddressMode = "mirror-repeat" FilterModeNearest FilterMode = "nearest" FilterModeLinear FilterMode = "linear" MipmapFilterModeNearest MipmapFilterMode = "nearest" MipmapFilterModeLinear MipmapFilterMode = "linear" CompareFunctionNever CompareFunction = "never" CompareFunctionLess CompareFunction = "less" CompareFunctionEqual CompareFunction = "equal" CompareFunctionLessEqual CompareFunction = "less-equal" CompareFunctionGreater CompareFunction = "greater" CompareFunctionNotEqual CompareFunction = "not-equal" CompareFunctionGreaterEqual CompareFunction = "greater-equal" CompareFunctionAlways CompareFunction = "always" PrimitiveTopologyPointList PrimitiveTopology = "point-list" PrimitiveTopologyLineList PrimitiveTopology = "line-list" PrimitiveTopologyLineStrip PrimitiveTopology = "line-strip" PrimitiveTopologyTriangleList PrimitiveTopology = "triangle-list" PrimitiveTopologyTriangleStrip PrimitiveTopology = "triangle-strip" IndexFormatUint16 IndexFormat = "uint16" IndexFormatUint32 IndexFormat = "uint32" FrontFaceCCW FrontFace = "ccw" FrontFaceCW FrontFace = "cw" CullModeNone CullMode = "none" CullModeFront CullMode = "front" CullModeBack CullMode = "back" VertexFormatUint8x4 VertexFormat = "uint8x4" VertexFormatUnorm8x4 VertexFormat = "unorm8x4" VertexFormatUint16x2 VertexFormat = "uint16x2" VertexFormatFloat16x2 VertexFormat = "float16x2" VertexFormatFloat16x4 VertexFormat = "float16x4" VertexFormatFloat32 VertexFormat = "float32" VertexFormatFloat32x2 VertexFormat = "float32x2" VertexFormatFloat32x3 VertexFormat = "float32x3" VertexFormatFloat32x4 VertexFormat = "float32x4" VertexFormatUint32 VertexFormat = "uint32" VertexFormatUint32x2 VertexFormat = "uint32x2" VertexFormatUint32x4 VertexFormat = "uint32x4" VertexStepModeVertex VertexStepMode = "vertex" VertexStepModeInstance VertexStepMode = "instance" LoadOpLoad LoadOp = "load" LoadOpClear LoadOp = "clear" StoreOpStore StoreOp = "store" StoreOpDiscard StoreOp = "discard" BlendFactorZero BlendFactor = "zero" BlendFactorOne BlendFactor = "one" BlendFactorSrc BlendFactor = "src" BlendFactorOneMinusSrc BlendFactor = "one-minus-src" BlendFactorSrcAlpha BlendFactor = "src-alpha" BlendFactorOneMinusSrcAlpha BlendFactor = "one-minus-src-alpha" BlendFactorDst BlendFactor = "dst" BlendFactorOneMinusDst BlendFactor = "one-minus-dst" BlendFactorDstAlpha BlendFactor = "dst-alpha" BlendFactorOneMinusDstAlpha BlendFactor = "one-minus-dst-alpha" BlendFactorConstant BlendFactor = "constant" BlendOperationAdd BlendOperation = "add" BlendOperationSubtract BlendOperation = "subtract" BlendOperationReverseSubtract BlendOperation = "reverse-subtract" BlendOperationMin BlendOperation = "min" BlendOperationMax BlendOperation = "max" StencilOperationKeep StencilOperation = "keep" StencilOperationZero StencilOperation = "zero" StencilOperationReplace StencilOperation = "replace" StencilOperationInvert StencilOperation = "invert" BufferBindingTypeUniform BufferBindingType = "uniform" BufferBindingTypeStorage BufferBindingType = "storage" BufferBindingTypeReadOnlyStorage BufferBindingType = "read-only-storage" SamplerBindingTypeFiltering SamplerBindingType = "filtering" SamplerBindingTypeNonFiltering SamplerBindingType = "non-filtering" SamplerBindingTypeComparison SamplerBindingType = "comparison" TextureSampleTypeFloat TextureSampleType = "float" TextureSampleTypeUnfilterable TextureSampleType = "unfilterable-float" TextureSampleTypeDepth TextureSampleType = "depth" TextureSampleTypeSint TextureSampleType = "sint" TextureSampleTypeUint TextureSampleType = "uint" StorageTextureAccessWriteOnly StorageTextureAccess = "write-only" StorageTextureAccessReadOnly StorageTextureAccess = "read-only" StorageTextureAccessReadWrite StorageTextureAccess = "read-write" FeatureTimestampQuery FeatureName = "timestamp-query" FeatureDepth32FloatStencil8 FeatureName = "depth32float-stencil8" FeatureTextureCompressionBC FeatureName = "texture-compression-bc" FeatureIndirectFirstInstance FeatureName = "indirect-first-instance" FeatureShaderF16 FeatureName = "shader-f16" FeatureFloat32Filterable FeatureName = "float32-filterable" PowerPreferenceLowPower PowerPreference = "low-power" PowerPreferenceHighPerformance PowerPreference = "high-performance" CanvasAlphaModeOpaque CanvasAlphaMode = "opaque" CanvasAlphaModePremultiplied CanvasAlphaMode = "premultiplied" ErrorFilterValidation ErrorFilter = "validation" ErrorFilterOutOfMemory ErrorFilter = "out-of-memory" ErrorFilterInternal ErrorFilter = "internal" )
const ( BufferUsageMapRead BufferUsage = 0x0001 BufferUsageMapWrite BufferUsage = 0x0002 BufferUsageCopySrc BufferUsage = 0x0004 BufferUsageCopyDst BufferUsage = 0x0008 BufferUsageIndex BufferUsage = 0x0010 BufferUsageVertex BufferUsage = 0x0020 BufferUsageUniform BufferUsage = 0x0040 BufferUsageStorage BufferUsage = 0x0080 BufferUsageIndirect BufferUsage = 0x0100 BufferUsageQueryResolve BufferUsage = 0x0200 TextureUsageCopySrc TextureUsage = 0x01 TextureUsageCopyDst TextureUsage = 0x02 TextureUsageTextureBinding TextureUsage = 0x04 TextureUsageStorageBinding TextureUsage = 0x08 TextureUsageRenderAttachment TextureUsage = 0x10 ShaderStageVertex ShaderStage = 0x1 ShaderStageFragment ShaderStage = 0x2 ShaderStageCompute ShaderStage = 0x4 MapModeRead MapMode = 0x1 MapModeWrite MapMode = 0x2 ColorWriteRed ColorWrite = 0x1 ColorWriteGreen ColorWrite = 0x2 ColorWriteBlue ColorWrite = 0x4 ColorWriteAlpha ColorWrite = 0x8 ColorWriteAll ColorWrite = 0xF )
const ReplayJSName = "webgpu-replay.js"
ReplayJSName is the file name ReplayJS is conventionally served under.
Variables ¶
var ( // ErrNoWebGPU: this context has no navigator.gpu (no WebGPU, or not a // secure context, or not GOOS=js). ErrNoWebGPU = errors.New("webgpu: navigator.gpu is not available") // ErrNoAdapter: requestAdapter resolved to null. ErrNoAdapter = errors.New("webgpu: no adapter") // ErrFallbackAdapter: the only adapter is a fallback (software) one and // the caller did not accept it. Work on such an adapter is not GPU work. ErrFallbackAdapter = errors.New("webgpu: only a fallback (software) adapter") // ErrDestroyed: the object (or its device) was destroyed or released. ErrDestroyed = errors.New("webgpu: object destroyed") // ErrNoCanvasContext: OffscreenCanvas.getContext("webgpu") returned // null here (e.g. Firefox outside Windows); fall back to another // renderer. ErrNoCanvasContext = errors.New("webgpu: no WebGPU context on OffscreenCanvas") )
var ErrDescriptor = errors.New("webgpu: descriptor")
ErrDescriptor is wrapped by every EncodeDescriptor and DecodeDescriptor error.
var ErrMapState = errors.New("webgpu: buffer is not unmapped")
ErrMapState: MapAsync on a buffer that is already mapped; WebGPU requires the "unmapped" state.
var ErrNoReplay = errors.New("webgpu: replay.js is not loaded (InstallReplay)")
ErrNoReplay: replay.js is not loaded in this window or worker; see InstallReplay.
var ErrNotRead = errors.New("webgpu: the read-back has not completed")
ErrNotRead: a Readback whose submit has not completed (or failed).
var ErrRecorderState = errors.New("webgpu: recorder: command out of order")
ErrRecorderState: a command outside the pass it belongs to, a pass left open at Submit, or a Recorder used after Submit.
var LimitNames = []string{
"maxTextureDimension1D", "maxTextureDimension2D", "maxTextureDimension3D", "maxTextureArrayLayers",
"maxBindGroups", "maxBindGroupsPlusVertexBuffers", "maxImmediateSize", "maxBindingsPerBindGroup",
"maxDynamicUniformBuffersPerPipelineLayout", "maxDynamicStorageBuffersPerPipelineLayout",
"maxSampledTexturesPerShaderStage", "maxSamplersPerShaderStage",
"maxStorageBuffersPerShaderStage", "maxStorageBuffersInVertexStage", "maxStorageBuffersInFragmentStage",
"maxStorageTexturesPerShaderStage", "maxStorageTexturesInVertexStage", "maxStorageTexturesInFragmentStage",
"maxUniformBuffersPerShaderStage", "maxUniformBufferBindingSize", "maxStorageBufferBindingSize",
"minUniformBufferOffsetAlignment", "minStorageBufferOffsetAlignment",
"maxVertexBuffers", "maxBufferSize", "maxVertexAttributes", "maxVertexBufferArrayStride",
"maxInterStageShaderVariables", "maxColorAttachments", "maxColorAttachmentBytesPerSample",
"maxComputeWorkgroupStorageSize", "maxComputeInvocationsPerWorkgroup",
"maxComputeWorkgroupSizeX", "maxComputeWorkgroupSizeY", "maxComputeWorkgroupSizeZ",
"maxComputeWorkgroupsPerDimension",
}
LimitNames are the attributes of GPUSupportedLimits (https://www.w3.org/TR/webgpu/#gpusupportedlimits). The interface's attributes live on its prototype and cannot be enumerated, so they are read by name; a name the browser does not have is skipped.
var ReplayJS string
ReplayJS is replay.js, the JavaScript half of batched encoding (Recorder). A page with a strict Content-Security-Policy (script-src 'self') must serve it from its own origin, as it serves wasm_exec.js, and pass its URL to InstallReplay; ReplayJSName is the conventional file name.
Functions ¶
func CanvasSupport ¶
func CanvasSupport() error
CanvasSupport reports whether this window or worker can render WebGPU into an OffscreenCanvas: nil if so, ErrNoCanvasContext (wrapped, with the reason) if not. MDN's compatibility data lists the webgpu context of OffscreenCanvas in Chrome 113+ (all platforms from 144), Safari 26, and Firefox 141 on Windows only: elsewhere a program should fall back to another renderer, and this is the signal.
func DecodeDescriptor ¶ added in v0.3.0
DecodeDescriptor rebuilds a creation descriptor of kind from its wire bytes, resolving references with resolve. It returns the same types EncodeDescriptor takes. The bytes come from another party: the body must name no unknown field, the reference count must match the body, every reference must resolve to an object of the right type, and the object fields of the body are discarded, never trusted.
func EncodeDescriptor ¶ added in v0.3.0
EncodeDescriptor returns the kind and wire bytes of a creation descriptor: BufferDescriptor, TextureDescriptor, TextureViewCreation, SamplerDescriptor, ShaderModuleDescriptor, BindGroupLayoutDescriptor, PipelineLayoutDescriptor, BindGroupDescriptor, RenderPipelineDescriptor or ComputePipelineDescriptor. Referenced objects must not be nil except where the descriptor allows it (a pipeline's layout, a render pipeline's fragment state).
func InstallReplay ¶
InstallReplay loads replay.js into this window or worker, once. url is where the page serves ReplayJS (same origin under a strict CSP); empty, the embedded copy is loaded from a blob: URL, which a CSP of script-src 'self' refuses. In a worker the script is loaded with importScripts (classic workers only); in a window with a <script> element.
func ReplayID ¶ added in v0.3.0
ReplayID returns the id that streams and wire descriptors name h by (allocated on first use): the id a transport translates a foreign stream's or descriptor's ids to. h is any object handle of this package.
func ReplayInstalled ¶
func ReplayInstalled() bool
ReplayInstalled reports whether replay.js is loaded here.
func TextureBytes ¶
func TextureBytes(d TextureDescriptor) (int64, error)
TextureBytes is what a texture costs in GPU memory as this package counts it: every mip level's physical extent, in texel blocks, times the format's memory cost, times the sample count. It is an upper bound for quota purposes, not a promise about the driver's allocation.
Types ¶
type Adapter ¶
type Adapter struct {
// contains filtered or unexported fields
}
Adapter is a GPUAdapter.
func (*Adapter) HasFeature ¶
func (a *Adapter) HasFeature(f FeatureName) bool
HasFeature reports whether the adapter supports a feature.
func (*Adapter) Info ¶
func (a *Adapter) Info() AdapterInfo
Info returns the adapter's GPUAdapterInfo.
func (*Adapter) Label ¶
func (o *Adapter) Label() string
Label returns the label the object was created with.
func (*Adapter) RequestDevice ¶
RequestDevice is adapter.requestDevice(). The descriptor's Quota is checked first: a feature or limit it does not allow never reaches the browser.
type AdapterInfo ¶
AdapterInfo is a GPUAdapterInfo. Fallback reports a fallback (software) adapter, e.g. SwiftShader: work done on it is not GPU work.
type AddressMode ¶
type AddressMode string
type BindGroup ¶
type BindGroup struct {
// contains filtered or unexported fields
}
BindGroup is a GPUBindGroup.
type BindGroupDescriptor ¶
type BindGroupDescriptor struct {
Label string
Layout *BindGroupLayout
Entries []BindGroupEntry
}
BindGroupDescriptor is a GPUBindGroupDescriptor.
type BindGroupEntry ¶
type BindGroupEntry struct {
Binding uint32
Buffer *Buffer
Offset uint64
Size uint64
Sampler *Sampler
TextureView *TextureView
}
BindGroupEntry is a GPUBindGroupEntry: exactly one of Buffer, Sampler, TextureView is set. Size 0 binds the rest of the buffer from Offset.
type BindGroupLayout ¶
type BindGroupLayout struct {
// contains filtered or unexported fields
}
BindGroupLayout is a GPUBindGroupLayout.
type BindGroupLayoutDescriptor ¶
type BindGroupLayoutDescriptor struct {
Label string
Entries []BindGroupLayoutEntry
}
BindGroupLayoutDescriptor is a GPUBindGroupLayoutDescriptor.
type BindGroupLayoutEntry ¶
type BindGroupLayoutEntry struct {
Binding uint32
Visibility ShaderStage
Buffer *BufferBindingLayout
Sampler *SamplerBindingLayout
Texture *TextureBindingLayout
StorageTexture *StorageTextureBindingLayout
}
BindGroupLayoutEntry is a GPUBindGroupLayoutEntry: exactly one of Buffer, Sampler, Texture, StorageTexture is set.
type BlendComponent ¶
type BlendComponent struct {
Operation BlendOperation
SrcFactor, DstFactor BlendFactor
}
BlendComponent is a GPUBlendComponent.
type BlendFactor ¶
type BlendFactor string
type BlendOperation ¶
type BlendOperation string
type BlendState ¶
type BlendState struct{ Color, Alpha BlendComponent }
BlendState is a GPUBlendState.
type BoundsError ¶
BoundsError reports an argument the package refused before it reached the browser: an out-of-range write, a misaligned offset, a missing usage. WebGPU itself would report most of these only asynchronously, as a validation error on the device; here they are an error at the call.
func (*BoundsError) Error ¶
func (e *BoundsError) Error() string
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer is a GPUBuffer.
func (*Buffer) Destroy ¶
func (b *Buffer) Destroy()
Destroy is buffer.destroy(); it refunds the buffer's quota once.
func (*Buffer) ReadMapped ¶
ReadMapped copies len(dst) bytes of the mapped range starting at offset into dst.
type BufferBindingLayout ¶
type BufferBindingLayout struct {
Type BufferBindingType
HasDynamicOffset bool
MinBindingSize uint64
}
BufferBindingLayout is a GPUBufferBindingLayout.
type BufferBindingType ¶
type BufferBindingType string
type BufferDescriptor ¶
type BufferDescriptor struct {
Label string
Size uint64
Usage BufferUsage
MappedAtCreation bool
}
BufferDescriptor is a GPUBufferDescriptor.
type BufferUsage ¶
type BufferUsage uint32
Flag sets, with the values of the IDL's GPUFlagsConstant namespaces.
type CanvasAlphaMode ¶
type CanvasAlphaMode string
type ColorTargetState ¶
type ColorTargetState struct {
Format TextureFormat
Blend *BlendState
WriteMask *ColorWrite
}
ColorTargetState is a GPUColorTargetState; a nil WriteMask writes all channels.
type ColorWrite ¶
type ColorWrite uint32
Flag sets, with the values of the IDL's GPUFlagsConstant namespaces.
type CommandBuffer ¶
type CommandBuffer struct {
// contains filtered or unexported fields
}
CommandBuffer is a GPUCommandBuffer.
type CommandEncoder ¶
type CommandEncoder struct {
// contains filtered or unexported fields
}
CommandEncoder is a GPUCommandEncoder.
func (*CommandEncoder) BeginComputePass ¶
func (e *CommandEncoder) BeginComputePass(label string) (*ComputePassEncoder, error)
BeginComputePass is encoder.beginComputePass().
func (*CommandEncoder) BeginRenderPass ¶
func (e *CommandEncoder) BeginRenderPass(desc RenderPassDescriptor) (*RenderPassEncoder, error)
BeginRenderPass is encoder.beginRenderPass().
func (*CommandEncoder) ClearBuffer ¶
func (e *CommandEncoder) ClearBuffer(b *Buffer, offset, size uint64) error
ClearBuffer is encoder.clearBuffer(buffer, offset, size); size 0 clears to the end.
func (*CommandEncoder) CopyBufferToBuffer ¶
func (e *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64) error
CopyBufferToBuffer is encoder.copyBufferToBuffer(), ranges checked.
func (*CommandEncoder) CopyBufferToTexture ¶
func (e *CommandEncoder) CopyBufferToTexture(src TexelCopyBufferInfo, dst TexelCopyTextureInfo, size Extent3D) error
CopyBufferToTexture is encoder.copyBufferToTexture(), the region and layout checked against the texture and the buffer.
func (*CommandEncoder) CopyTextureToBuffer ¶
func (e *CommandEncoder) CopyTextureToBuffer(src TexelCopyTextureInfo, dst TexelCopyBufferInfo, size Extent3D) error
CopyTextureToBuffer is encoder.copyTextureToBuffer(), checked likewise.
func (*CommandEncoder) CopyTextureToTexture ¶
func (e *CommandEncoder) CopyTextureToTexture(src, dst TexelCopyTextureInfo, size Extent3D) error
CopyTextureToTexture is encoder.copyTextureToTexture(); the browser validates the regions.
func (*CommandEncoder) Finish ¶
func (e *CommandEncoder) Finish() (*CommandBuffer, error)
Finish is encoder.finish().
type CompareFunction ¶
type CompareFunction string
type CompilationMessage ¶ added in v0.10.0
type CompilationMessage struct {
Type string // "error", "warning" or "info"
Message string
Line int // 1-based, 0 if unknown
Column int // 1-based, 0 if unknown
}
CompilationMessage is one message of GPUShaderModule.getCompilationInfo().
func (CompilationMessage) String ¶ added in v0.10.0
func (m CompilationMessage) String() string
type ComputePassEncoder ¶
type ComputePassEncoder struct {
// contains filtered or unexported fields
}
ComputePassEncoder is a GPUComputePassEncoder.
func (*ComputePassEncoder) DispatchWorkgroups ¶
func (p *ComputePassEncoder) DispatchWorkgroups(x, y, z uint32)
DispatchWorkgroups is dispatchWorkgroups(x, y, z).
func (*ComputePassEncoder) DispatchWorkgroupsIndirect ¶
func (p *ComputePassEncoder) DispatchWorkgroupsIndirect(b *Buffer, offset uint64)
DispatchWorkgroupsIndirect is dispatchWorkgroupsIndirect(buffer, offset); the 12-byte record must lie in the buffer.
func (*ComputePassEncoder) Label ¶
func (o *ComputePassEncoder) Label() string
Label returns the label the object was created with.
func (*ComputePassEncoder) SetBindGroup ¶
func (p *ComputePassEncoder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
SetBindGroup is setBindGroup(index, group, dynamicOffsets).
func (*ComputePassEncoder) SetPipeline ¶
func (p *ComputePassEncoder) SetPipeline(cp *ComputePipeline)
SetPipeline is setPipeline(pipeline).
type ComputePassRecorder ¶
type ComputePassRecorder struct {
// contains filtered or unexported fields
}
ComputePassRecorder records a compute pass's commands.
func (*ComputePassRecorder) DispatchWorkgroups ¶
func (p *ComputePassRecorder) DispatchWorkgroups(x, y, z uint32)
DispatchWorkgroups records dispatchWorkgroups.
func (*ComputePassRecorder) DispatchWorkgroupsIndirect ¶
func (p *ComputePassRecorder) DispatchWorkgroupsIndirect(b *Buffer, offset uint64)
DispatchWorkgroupsIndirect records dispatchWorkgroupsIndirect.
func (*ComputePassRecorder) SetBindGroup ¶
func (p *ComputePassRecorder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
SetBindGroup records setBindGroup.
func (*ComputePassRecorder) SetPipeline ¶
func (p *ComputePassRecorder) SetPipeline(pl *ComputePipeline)
SetPipeline records setPipeline.
type ComputePipeline ¶
type ComputePipeline struct {
// contains filtered or unexported fields
}
ComputePipeline is a GPUComputePipeline; Release refunds its quota.
func (*ComputePipeline) GetBindGroupLayout ¶
func (p *ComputePipeline) GetBindGroupLayout(index uint32) (*BindGroupLayout, error)
GetBindGroupLayout is pipeline.getBindGroupLayout(index).
func (*ComputePipeline) Release ¶
func (p *ComputePipeline) Release()
Release gives the pipeline's quota back.
type ComputePipelineDescriptor ¶
type ComputePipelineDescriptor struct {
Label string
Layout *PipelineLayout
Compute ProgrammableStage
}
ComputePipelineDescriptor is a GPUComputePipelineDescriptor. A nil Layout is "auto".
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 is a GPUDepthStencilState. DepthWriteEnabled is always sent; nil masks mean the default 0xFFFFFFFF.
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device is a GPUDevice. Its Quota (from DeviceDescriptor) bounds what it may hold.
func (*Device) CreateBindGroup ¶
func (d *Device) CreateBindGroup(desc BindGroupDescriptor) (*BindGroup, error)
CreateBindGroup is device.createBindGroup(). Buffer ranges are checked against the buffers' sizes first.
func (*Device) CreateBindGroupLayout ¶
func (d *Device) CreateBindGroupLayout(desc BindGroupLayoutDescriptor) (*BindGroupLayout, error)
CreateBindGroupLayout is device.createBindGroupLayout().
func (*Device) CreateBuffer ¶
func (d *Device) CreateBuffer(desc BufferDescriptor) (*Buffer, error)
CreateBuffer is device.createBuffer(). The size is charged to the quota first.
func (*Device) CreateCommandEncoder ¶
func (d *Device) CreateCommandEncoder(label string) (*CommandEncoder, error)
CreateCommandEncoder is device.createCommandEncoder().
func (*Device) CreateComputePipeline ¶
func (d *Device) CreateComputePipeline(desc ComputePipelineDescriptor) (*ComputePipeline, error)
CreateComputePipeline is device.createComputePipeline(); it counts against the quota's Pipelines until Release.
func (*Device) CreateComputePipelineAsync ¶
func (d *Device) CreateComputePipelineAsync(ctx context.Context, desc ComputePipelineDescriptor) (*ComputePipeline, error)
CreateComputePipelineAsync is device.createComputePipelineAsync().
func (*Device) CreatePipelineLayout ¶
func (d *Device) CreatePipelineLayout(desc PipelineLayoutDescriptor) (*PipelineLayout, error)
CreatePipelineLayout is device.createPipelineLayout().
func (*Device) CreateRenderBundleEncoder ¶
func (d *Device) CreateRenderBundleEncoder(desc RenderBundleEncoderDescriptor) (*RenderBundleEncoder, error)
CreateRenderBundleEncoder is device.createRenderBundleEncoder(): record draws once, replay them every frame with ExecuteBundles.
func (*Device) CreateRenderPipeline ¶
func (d *Device) CreateRenderPipeline(desc RenderPipelineDescriptor) (*RenderPipeline, error)
CreateRenderPipeline is device.createRenderPipeline(); it counts against the quota's Pipelines until Release.
func (*Device) CreateRenderPipelineAsync ¶
func (d *Device) CreateRenderPipelineAsync(ctx context.Context, desc RenderPipelineDescriptor) (*RenderPipeline, error)
CreateRenderPipelineAsync is device.createRenderPipelineAsync(): the pipeline is compiled off the caller's critical path, and a shader error is an error here rather than on the device.
func (*Device) CreateSampler ¶
func (d *Device) CreateSampler(desc *SamplerDescriptor) (*Sampler, error)
CreateSampler is device.createSampler().
func (*Device) CreateShaderModule ¶
func (d *Device) CreateShaderModule(desc ShaderModuleDescriptor) (*ShaderModule, error)
CreateShaderModule is device.createShaderModule() with WGSL source, bounded by the quota's ShaderBytes.
func (*Device) CreateTexture ¶
func (d *Device) CreateTexture(desc TextureDescriptor) (*Texture, error)
CreateTexture is device.createTexture(). Its size (TextureBytes) is charged to the quota first.
func (*Device) Destroy ¶
func (d *Device) Destroy()
Destroy destroys the device and everything created from it, and refunds its quota. Lost is closed once the browser confirms.
func (*Device) Label ¶
func (o *Device) Label() string
Label returns the label the object was created with.
func (*Device) Limit ¶
Limit returns one of the device's limits (e.g. "maxBufferSize") as the browser reported it, and whether it is known.
func (*Device) Lost ¶
func (d *Device) Lost() <-chan struct{}
Lost is closed when the device is lost (destroyed, or by the browser: a GPU reset, a watchdog). LostInfo then says why.
func (*Device) LostInfo ¶
func (d *Device) LostInfo() DeviceLostInfo
LostInfo is why the device was lost; zero while it is not.
func (*Device) NewRecorder ¶
NewRecorder returns a Recorder for the device.
func (*Device) NewSurface ¶
func (d *Device) NewSurface(desc SurfaceDescriptor) (*Surface, error)
NewSurface creates a standalone OffscreenCanvas of desc's size, within the device's quota (SurfaceWidth, SurfaceHeight).
func (*Device) NewSurfaceFromCanvas ¶
NewSurfaceFromCanvas configures an OffscreenCanvas the caller owns (one a page made with transferControlToOffscreen and posted to a worker); its size is the canvas's, checked against the quota.
func (*Device) OnUncapturedError ¶
OnUncapturedError calls fn, on a new goroutine, for every WebGPU error no error scope caught. It returns a function that removes the handler.
func (*Device) PopErrorScope ¶
PopErrorScope is device.popErrorScope(): nil if the scope caught nothing, a *GPUError if it did, another error if popping failed.
func (*Device) PushErrorScope ¶
func (d *Device) PushErrorScope(filter ErrorFilter)
PushErrorScope is device.pushErrorScope(filter).
func (*Device) ReadTexture ¶ added in v0.6.0
func (d *Device) ReadTexture(ctx context.Context, src TexelCopyTextureInfo, width, height, bytesPerTexel int) ([]byte, error)
ReadTexture copies a 2D region of a texture to Go memory: width x height texels of bytesPerTexel bytes each, row after row without padding. It does what every readback needs: a copy to a mappable buffer whose rows are padded to 256 bytes (bytesPerRow must be a multiple of 256), a submit, a map, and the unpadding. The texture needs COPY_SRC. Meant for tests and screenshots, not for a frame loop (it waits for the GPU).
func (*Device) Replay ¶ added in v0.3.0
Replay submits a stream recorded elsewhere — another process, a virtual machine's guest over virtio-gpu — whose object ids are the replay ids of refs (each a *Buffer, *Texture, *TextureView, *BindGroup, *RenderPipeline, *ComputePipeline or *RenderBundle of this device; wire.Remap translates a foreign stream's ids to them). The stream is checked with wire.Decode first and may name no other object, so it reaches only what the caller granted. It returns the submission's number on the device's timeline, as Recorder.Submit does.
func (*Device) Submitted ¶
Submitted is the number of the device's last queue submission (Queue Submit and Recorder.Submit), from 1.
func (*Device) Value ¶
Value returns the underlying browser object, for interoperation with other syscall/js code. Using it to destroy or mutate the object behind the package's back defeats its accounting.
func (*Device) WaitSubmitted ¶
WaitSubmitted waits until submission seq (a number Recorder.Submit returned, or Device.Submitted) is complete on the GPU. Completions are in order: waiting for one waits for every earlier one, and one onSubmittedWorkDone promise answers every waiter it covers, so many waiters cost one round trip to the GPU process.
type DeviceDescriptor ¶
type DeviceDescriptor struct {
Label string
RequiredFeatures []FeatureName
RequiredLimits map[string]uint64
Quota *Quota
}
DeviceDescriptor is a GPUDeviceDescriptor plus the Quota the device enforces.
type DeviceLostInfo ¶
DeviceLostInfo says why a device was lost: Reason "destroyed" (Destroy was called) or "unknown".
type ErrorFilter ¶
type ErrorFilter string
type Extent3D ¶
type Extent3D struct{ Width, Height, DepthOrArrayLayers uint32 }
Extent3D is a GPUExtent3DDict. DepthOrArrayLayers 0 means 1.
type FeatureName ¶
type FeatureName string
type FilterMode ¶
type FilterMode string
type FormatInfo ¶
type FormatInfo struct {
// BlockWidth and BlockHeight are the texel block's size in texels: 1x1
// for every pixel-based format.
BlockWidth, BlockHeight uint32
// CopyBytes is the texel block copy footprint of the format's only
// copyable aspect, 0 if no aspect can be copied from or to a buffer
// without naming one (depth24plus, and the combined depth-stencil
// formats, whose aspects are copied separately).
CopyBytes uint32
// MemoryBytes bounds what one texel block costs in GPU memory. The
// specification calls this informative and gives ranges for some
// depth-stencil formats; the upper bound is used, so quotas never
// under-count.
MemoryBytes uint32
// Depth and Stencil say which aspects the format has.
Depth, Stencil bool
// CopyDst is false for formats whose depth aspect may not be the
// destination of a texel copy (depth32float and friends).
CopyDst bool
}
FormatInfo describes a texture format's texel blocks, after the WebGPU specification's texture format capability tables (https://www.w3.org/TR/webgpu/#texture-format-caps).
type FragmentState ¶
type FragmentState struct {
Module *ShaderModule
EntryPoint string
Constants map[string]float64
Targets []ColorTargetState
}
FragmentState is a GPUFragmentState.
type GPU ¶
type GPU struct {
// contains filtered or unexported fields
}
GPU is navigator.gpu of the window or worker the program runs in.
func (*GPU) PreferredCanvasFormat ¶
func (g *GPU) PreferredCanvasFormat() TextureFormat
PreferredCanvasFormat is navigator.gpu.getPreferredCanvasFormat().
func (*GPU) RequestAdapter ¶
RequestAdapter is navigator.gpu.requestAdapter(). It answers ErrNoAdapter when the browser offers none, and ErrFallbackAdapter for a fallback adapter unless opts.AllowFallback.
type GPUError ¶
GPUError is a WebGPU error reported on the device: by PopErrorScope or to an uncaptured-error handler. Kind is "validation", "out-of-memory" or "internal".
type IndexFormat ¶
type IndexFormat string
type JSError ¶
JSError is an exception the browser threw synchronously (a TypeError for a malformed descriptor, an OperationError, ...).
type MapMode ¶
type MapMode uint32
Flag sets, with the values of the IDL's GPUFlagsConstant namespaces.
type MipmapFilterMode ¶
type MipmapFilterMode string
type MultisampleState ¶
MultisampleState is a GPUMultisampleState. Zero Count means 1, zero Mask all samples.
type PipelineLayout ¶
type PipelineLayout struct {
// contains filtered or unexported fields
}
PipelineLayout is a GPUPipelineLayout.
type PipelineLayoutDescriptor ¶
type PipelineLayoutDescriptor struct {
Label string
BindGroupLayouts []*BindGroupLayout
}
PipelineLayoutDescriptor is a GPUPipelineLayoutDescriptor.
type PowerPreference ¶
type PowerPreference string
type PrimitiveState ¶
type PrimitiveState struct {
Topology PrimitiveTopology
StripIndexFormat IndexFormat
FrontFace FrontFace
CullMode CullMode
UnclippedDepth bool
}
PrimitiveState is a GPUPrimitiveState.
type PrimitiveTopology ¶
type PrimitiveTopology string
type ProgrammableStage ¶
type ProgrammableStage struct {
Module *ShaderModule
EntryPoint string
Constants map[string]float64
}
ProgrammableStage is a GPUProgrammableStage.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue is a GPUQueue.
func (*Queue) Label ¶
func (o *Queue) Label() string
Label returns the label the object was created with.
func (*Queue) OnSubmittedWorkDone ¶
OnSubmittedWorkDone waits until the GPU finished the work submitted so far (queue.onSubmittedWorkDone()).
func (*Queue) Submit ¶
func (q *Queue) Submit(cbs ...*CommandBuffer) error
Submit is queue.submit(commandBuffers).
func (*Queue) Value ¶
Value returns the underlying browser object, for interoperation with other syscall/js code. Using it to destroy or mutate the object behind the package's back defeats its accounting.
func (*Queue) WriteBuffer ¶
WriteBuffer is queue.writeBuffer(buffer, offset, data). The buffer's COPY_DST usage, 4-byte alignment and the range are checked first: an out-of-range write is an error here, not a silent device error. The bytes are copied before WriteBuffer returns, so data may be reused.
func (*Queue) WriteTexture ¶
func (q *Queue) WriteTexture(dst TexelCopyTextureInfo, data []byte, layout TexelCopyBufferLayout, size Extent3D) error
WriteTexture is queue.writeTexture(destination, data, layout, size). The region must lie inside the destination's mip level and the layout inside data (the specification's "validating linear texture data"), both checked first.
type Quota ¶
type Quota struct {
// MemoryBytes bounds buffer and texture bytes alive (texture sizes are
// computed by the package from the descriptor, mips and samples
// included). 0 is no limit.
MemoryBytes int64
// Pipelines bounds render and compute pipelines alive. 0 is no limit.
Pipelines int
// ShaderBytes bounds one WGSL source. 0 is no limit.
ShaderBytes int
// ReadBytes bounds the read window of one submit: the bytes its
// Recorder.ReadBuffer commands may return together. 0 is no limit
// (wire.MaxReadWindow still bounds it).
ReadBytes int
// Features lists the optional features a device may require. Any
// other required feature is refused, timestamp-query included unless
// listed.
Features []FeatureName
// Limits caps the limits a device may require; a required limit not
// named here is refused.
Limits map[string]uint64
// SurfaceWidth and SurfaceHeight bound a Surface's size. 0 is no
// limit.
SurfaceWidth, SurfaceHeight int
// contains filtered or unexported fields
}
Quota bounds what devices may hold. An embedder that runs untrusted code through this package (the go-wasmcontainers playground does) gives each tenant a Quota and passes it in DeviceDescriptor.Quota; several devices may share one. A nil Quota is no limit.
The package charges a Quota before it calls the browser and refunds on Destroy or Release, so a refused request never reaches WebGPU.
type QuotaError ¶
type QuotaError struct {
Resource string // "memory", "pipelines", "shader", "feature", "limit"
Limit int64
Want int64
Name string // the feature or limit, when Resource names one
}
QuotaError reports a request a Quota refused.
func (*QuotaError) Error ¶
func (e *QuotaError) Error() string
type ReadSink ¶ added in v0.7.0
type ReadSink interface {
RemoteSink
SubmitRead(words []uint32, data []byte, window []byte) error
}
ReadSink is a RemoteSink that also returns read-backs: SubmitRead executes the submit as Submit does and, once its GPU work has completed, fills window (len = the submit's read window) as the stream's ReadBuffer commands say. A remote device whose sink is not a ReadSink refuses a submit that reads.
type Readback ¶ added in v0.7.0
type Readback struct {
// contains filtered or unexported fields
}
Readback is the result of one Recorder.ReadBuffer: its bytes are valid after the Recorder's Submit returned without error.
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder records one submit. Its methods mirror the direct API; like a pass encoder's, they return nothing on the per-draw path: the first refused command is kept, not recorded, and returned by End or Submit. A Recorder is not safe for concurrent use; Reset reuses its memory for the next frame.
func (*Recorder) BeginComputePass ¶
func (r *Recorder) BeginComputePass() *ComputePassRecorder
BeginComputePass records encoder.beginComputePass.
func (*Recorder) BeginRenderPass ¶
func (r *Recorder) BeginRenderPass(desc RenderPassDescriptor) *RenderPassRecorder
BeginRenderPass records encoder.beginRenderPass and returns the pass recorder. Up to 8 color attachments.
func (*Recorder) CopyBufferToBuffer ¶
func (r *Recorder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64)
CopyBufferToBuffer records encoder.copyBufferToBuffer, checked.
func (*Recorder) CopyTextureToTexture ¶ added in v0.3.0
func (r *Recorder) CopyTextureToTexture(src, dst TexelCopyTextureInfo, size Extent3D)
CopyTextureToTexture records encoder.copyTextureToTexture. As on the direct path, the browser validates the regions; the textures must not be nil and the aspects must be WebGPU's.
func (*Recorder) ReadBuffer ¶ added in v0.7.0
ReadBuffer records a read of [offset, offset+size) of b, a MAP_READ buffer, after this submit's GPU work. Record the copy into b before it (CopyBufferToBuffer); the read sees everything the stream does. Submit delivers the bytes to the returned Readback. A refused read is kept as the Recorder's error, as every command's is, and in the Readback.
func (*Recorder) Reset ¶
func (r *Recorder) Reset()
Reset forgets everything recorded, keeping the memory.
func (*Recorder) Submit ¶
Submit replays everything recorded in one call to JavaScript (one command encoder, finished and submitted at the end), then resets the Recorder for the next frame. It returns the first refused command, if any (refused commands were not recorded; the others were submitted), or what the browser threw. Every pass must be ended.
seq numbers the submission on the device's timeline (from 1, shared with Queue.Submit); Device.WaitSubmitted(ctx, seq) waits for the GPU to finish it. It is 0 when nothing was replayed.
func (*Recorder) WriteBuffer ¶
WriteBuffer records queue.writeBuffer: the bytes are copied into the recorder now and written, in order, when Submit replays the stream. Checked like Queue.WriteBuffer.
func (*Recorder) WriteTexture ¶ added in v0.4.0
func (r *Recorder) WriteTexture(dst TexelCopyTextureInfo, data []byte, layout TexelCopyBufferLayout, size Extent3D)
WriteTexture records queue.writeTexture: the bytes are copied into the recorder now and written, in order, when Submit replays the stream, in the same single call as the passes. Checked like Queue.WriteTexture (region inside the mip level, layout inside data).
type RemoteSink ¶ added in v0.3.0
type RemoteSink interface {
// Create makes object id of kind from a wire descriptor
// (EncodeDescriptor's bytes).
Create(id uint32, kind wire.Kind, desc []byte) error
// Destroy releases object id.
Destroy(id uint32) error
// Submit executes one Recorder submit and returns once it has
// executed (a fenced virtio submission), or with the error that lost
// the remote device.
Submit(words []uint32, data []byte) error
}
RemoteSink carries the work of a remote device (NewRemoteDevice, built outside the browser) to where a real device runs it — for example to a virtio-gpu host through go-virtio/gpu's webgpu-batch context.
Object ids are replay ids (ReplayID): the ids streams and descriptors name objects by. The receiver translates them to its own objects (wire.RemapDescriptor, wire.Remap).
type RenderBundle ¶
type RenderBundle struct {
// contains filtered or unexported fields
}
RenderBundle is a GPURenderBundle.
type RenderBundleEncoder ¶
type RenderBundleEncoder struct {
// contains filtered or unexported fields
}
RenderBundleEncoder is a GPURenderBundleEncoder.
func (*RenderBundleEncoder) Draw ¶
func (r *RenderBundleEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
Draw is draw(vertexCount, instanceCount, firstVertex, firstInstance).
func (*RenderBundleEncoder) DrawIndexed ¶
func (r *RenderBundleEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
DrawIndexed is drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance).
func (*RenderBundleEncoder) DrawIndexedIndirect ¶
DrawIndexedIndirect is drawIndexedIndirect(buffer, offset); the 20-byte record must lie in the buffer.
func (*RenderBundleEncoder) DrawIndirect ¶
DrawIndirect is drawIndirect(buffer, offset); the 16-byte record must lie in the buffer.
func (*RenderBundleEncoder) Err ¶
func (r *RenderBundleEncoder) Err() error
Err returns the first refused command so far.
func (*RenderBundleEncoder) Finish ¶
func (e *RenderBundleEncoder) Finish(label string) (*RenderBundle, error)
Finish is finish(): the recorded bundle, or the first refused command.
func (*RenderBundleEncoder) SetBindGroup ¶
SetBindGroup is setBindGroup(index, group, dynamicOffsets).
func (*RenderBundleEncoder) SetIndexBuffer ¶
func (r *RenderBundleEncoder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
SetIndexBuffer is setIndexBuffer(buffer, format, offset, size); size 0 binds to the end of the buffer. The range is checked.
func (*RenderBundleEncoder) SetPipeline ¶
func (r *RenderBundleEncoder) SetPipeline(p *RenderPipeline)
SetPipeline is setPipeline(pipeline).
func (*RenderBundleEncoder) SetVertexBuffer ¶
SetVertexBuffer is setVertexBuffer(slot, buffer, offset, size); size 0 binds to the end of the buffer. The range is checked.
type RenderBundleEncoderDescriptor ¶
type RenderBundleEncoderDescriptor struct {
Label string
ColorFormats []TextureFormat
DepthStencilFormat TextureFormat
SampleCount uint32
DepthReadOnly bool
StencilReadOnly bool
}
RenderBundleEncoderDescriptor is a GPURenderBundleEncoderDescriptor.
type RenderPassColorAttachment ¶
type RenderPassColorAttachment struct {
View *TextureView
DepthSlice *uint32
ResolveTarget *TextureView
ClearValue Color
LoadOp LoadOp
StoreOp StoreOp
}
RenderPassColorAttachment is a GPURenderPassColorAttachment.
type RenderPassDepthStencilAttachment ¶
type RenderPassDepthStencilAttachment struct {
View *TextureView
DepthClearValue float32
DepthLoadOp LoadOp
DepthStoreOp StoreOp
DepthReadOnly bool
StencilClearValue uint32
StencilLoadOp LoadOp
StencilStoreOp StoreOp
StencilReadOnly bool
}
RenderPassDepthStencilAttachment is a GPURenderPassDepthStencilAttachment. Load and store ops left empty are omitted (required by the browser for the aspects the format has, unless read-only).
type RenderPassDescriptor ¶
type RenderPassDescriptor struct {
Label string
ColorAttachments []*RenderPassColorAttachment
DepthStencilAttachment *RenderPassDepthStencilAttachment
MaxDrawCount uint64
}
RenderPassDescriptor is a GPURenderPassDescriptor. A nil entry in ColorAttachments is an unused slot.
type RenderPassEncoder ¶
type RenderPassEncoder struct {
// contains filtered or unexported fields
}
RenderPassEncoder is a GPURenderPassEncoder.
func (*RenderPassEncoder) Draw ¶
func (r *RenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
Draw is draw(vertexCount, instanceCount, firstVertex, firstInstance).
func (*RenderPassEncoder) DrawIndexed ¶
func (r *RenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
DrawIndexed is drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance).
func (*RenderPassEncoder) DrawIndexedIndirect ¶
DrawIndexedIndirect is drawIndexedIndirect(buffer, offset); the 20-byte record must lie in the buffer.
func (*RenderPassEncoder) DrawIndirect ¶
DrawIndirect is drawIndirect(buffer, offset); the 16-byte record must lie in the buffer.
func (*RenderPassEncoder) End ¶
func (p *RenderPassEncoder) End() error
End is end(). It returns the first command the package refused, if any, or the browser's exception.
func (*RenderPassEncoder) Err ¶
func (r *RenderPassEncoder) Err() error
Err returns the first refused command so far.
func (*RenderPassEncoder) ExecuteBundles ¶
func (p *RenderPassEncoder) ExecuteBundles(bundles ...*RenderBundle)
ExecuteBundles is executeBundles(bundles).
func (*RenderPassEncoder) SetBindGroup ¶
SetBindGroup is setBindGroup(index, group, dynamicOffsets).
func (*RenderPassEncoder) SetBlendConstant ¶
func (p *RenderPassEncoder) SetBlendConstant(c Color)
SetBlendConstant is setBlendConstant(color).
func (*RenderPassEncoder) SetIndexBuffer ¶
func (r *RenderPassEncoder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
SetIndexBuffer is setIndexBuffer(buffer, format, offset, size); size 0 binds to the end of the buffer. The range is checked.
func (*RenderPassEncoder) SetPipeline ¶
func (r *RenderPassEncoder) SetPipeline(p *RenderPipeline)
SetPipeline is setPipeline(pipeline).
func (*RenderPassEncoder) SetScissorRect ¶
func (p *RenderPassEncoder) SetScissorRect(x, y, w, h uint32)
SetScissorRect is setScissorRect(x, y, width, height).
func (*RenderPassEncoder) SetStencilReference ¶
func (p *RenderPassEncoder) SetStencilReference(ref uint32)
SetStencilReference is setStencilReference(reference).
func (*RenderPassEncoder) SetVertexBuffer ¶
SetVertexBuffer is setVertexBuffer(slot, buffer, offset, size); size 0 binds to the end of the buffer. The range is checked.
func (*RenderPassEncoder) SetViewport ¶
func (p *RenderPassEncoder) SetViewport(x, y, w, h, minDepth, maxDepth float32)
SetViewport is setViewport(x, y, width, height, minDepth, maxDepth).
type RenderPassRecorder ¶
type RenderPassRecorder struct {
// contains filtered or unexported fields
}
RenderPassRecorder records a render pass's commands.
func (*RenderPassRecorder) Draw ¶
func (p *RenderPassRecorder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
Draw records draw.
func (*RenderPassRecorder) DrawIndexed ¶
func (p *RenderPassRecorder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
DrawIndexed records drawIndexed.
func (*RenderPassRecorder) DrawIndexedIndirect ¶
func (p *RenderPassRecorder) DrawIndexedIndirect(b *Buffer, offset uint64)
DrawIndexedIndirect records drawIndexedIndirect.
func (*RenderPassRecorder) DrawIndirect ¶
func (p *RenderPassRecorder) DrawIndirect(b *Buffer, offset uint64)
DrawIndirect records drawIndirect; the record must lie in the buffer.
func (*RenderPassRecorder) End ¶
func (p *RenderPassRecorder) End() error
End records end. It returns the first refused command so far.
func (*RenderPassRecorder) ExecuteBundles ¶
func (p *RenderPassRecorder) ExecuteBundles(bundles ...*RenderBundle)
ExecuteBundles records executeBundles.
func (*RenderPassRecorder) SetBindGroup ¶
func (p *RenderPassRecorder) SetBindGroup(index uint32, g *BindGroup, dynamicOffsets ...uint32)
SetBindGroup records setBindGroup, dynamic offsets included (replayed through the Uint32Array overload, without an array per call).
func (*RenderPassRecorder) SetBlendConstant ¶
func (p *RenderPassRecorder) SetBlendConstant(c Color)
SetBlendConstant records setBlendConstant (as float32).
func (*RenderPassRecorder) SetIndexBuffer ¶
func (p *RenderPassRecorder) SetIndexBuffer(b *Buffer, format IndexFormat, offset, size uint64)
SetIndexBuffer records setIndexBuffer; size 0 binds to the end.
func (*RenderPassRecorder) SetPipeline ¶
func (p *RenderPassRecorder) SetPipeline(pl *RenderPipeline)
SetPipeline records setPipeline.
func (*RenderPassRecorder) SetScissorRect ¶
func (p *RenderPassRecorder) SetScissorRect(x, y, w, h uint32)
SetScissorRect records setScissorRect.
func (*RenderPassRecorder) SetStencilReference ¶
func (p *RenderPassRecorder) SetStencilReference(ref uint32)
SetStencilReference records setStencilReference.
func (*RenderPassRecorder) SetVertexBuffer ¶
func (p *RenderPassRecorder) SetVertexBuffer(slot uint32, b *Buffer, offset, size uint64)
SetVertexBuffer records setVertexBuffer; size 0 binds to the end. Checked like the direct path.
func (*RenderPassRecorder) SetViewport ¶
func (p *RenderPassRecorder) SetViewport(x, y, w, h, minDepth, maxDepth float32)
SetViewport records setViewport.
type RenderPipeline ¶
type RenderPipeline struct {
// contains filtered or unexported fields
}
RenderPipeline is a GPURenderPipeline; Release refunds its quota.
func (*RenderPipeline) GetBindGroupLayout ¶
func (p *RenderPipeline) GetBindGroupLayout(index uint32) (*BindGroupLayout, error)
GetBindGroupLayout is pipeline.getBindGroupLayout(index), for "auto" layouts.
func (*RenderPipeline) Release ¶
func (p *RenderPipeline) Release()
Release gives the pipeline's quota back; the pipeline must not be used after. (WebGPU pipelines have no destroy; the browser frees them when unreferenced.)
type RenderPipelineDescriptor ¶
type RenderPipelineDescriptor struct {
Label string
Layout *PipelineLayout
Vertex VertexState
Primitive PrimitiveState
DepthStencil *DepthStencilState
Multisample MultisampleState
Fragment *FragmentState
}
RenderPipelineDescriptor is a GPURenderPipelineDescriptor. A nil Layout is "auto".
type RequestAdapterOptions ¶
type RequestAdapterOptions struct {
PowerPreference PowerPreference
ForceFallbackAdapter bool
AllowFallback bool
}
RequestAdapterOptions is a GPURequestAdapterOptions. AllowFallback is ours: without it, a fallback (software) adapter is refused with ErrFallbackAdapter.
type Resolver ¶ added in v0.3.0
Resolver returns the receiver's object for a reference id (a *Buffer, *Texture, *TextureView, *Sampler, *ShaderModule, *BindGroupLayout or *PipelineLayout). DecodeDescriptor checks the object's type.
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler is a GPUSampler.
type SamplerBindingLayout ¶
type SamplerBindingLayout struct{ Type SamplerBindingType }
SamplerBindingLayout is a GPUSamplerBindingLayout.
type SamplerBindingType ¶
type SamplerBindingType string
type SamplerDescriptor ¶
type SamplerDescriptor struct {
Label string
AddressModeU, AddressModeV, AddressModeW AddressMode
MagFilter, MinFilter FilterMode
MipmapFilter MipmapFilterMode
LodMinClamp, LodMaxClamp float32
Compare CompareFunction
MaxAnisotropy uint16
}
SamplerDescriptor is a GPUSamplerDescriptor. LodMaxClamp 0 means the default, 32.
type ShaderModule ¶
type ShaderModule struct {
// contains filtered or unexported fields
}
ShaderModule is a GPUShaderModule.
func (*ShaderModule) CompilationMessages ¶ added in v0.10.0
func (m *ShaderModule) CompilationMessages(ctx context.Context) ([]CompilationMessage, error)
CompilationMessages is module.getCompilationInfo(): what the browser's WGSL compiler said, with positions. Some browsers (Firefox) give only a generic validation error at createShaderModule and keep the compiler's text here. It waits on a promise: not from a js.FuncOf callback.
type ShaderModuleDescriptor ¶
ShaderModuleDescriptor is a GPUShaderModuleDescriptor (WGSL source).
type ShaderStage ¶
type ShaderStage uint32
Flag sets, with the values of the IDL's GPUFlagsConstant namespaces.
type StencilFaceState ¶
type StencilFaceState struct {
Compare CompareFunction
FailOp, DepthFailOp, PassOp StencilOperation
}
StencilFaceState is a GPUStencilFaceState.
type StencilOperation ¶
type StencilOperation string
type StorageTextureAccess ¶
type StorageTextureAccess string
type StorageTextureBindingLayout ¶
type StorageTextureBindingLayout struct {
Access StorageTextureAccess
Format TextureFormat
ViewDimension TextureViewDimension
}
StorageTextureBindingLayout is a GPUStorageTextureBindingLayout.
type Surface ¶
type Surface struct {
// contains filtered or unexported fields
}
Surface is an OffscreenCanvas with a WebGPU context, configured for a device. A standalone surface (NewSurface) never shows itself: Present moves the frame out as an ImageBitmap (transferToImageBitmap, without a copy) for the caller to post to a page and draw. A surface over a canvas a page transferred (NewSurfaceFromCanvas) is presented by the browser at the end of each task, and Present returns no bitmap.
func (*Surface) CurrentTexture ¶
CurrentTexture is context.getCurrentTexture(): the texture to render this frame into. It is the canvas's, not the caller's: not charged to the quota, and Destroy leaves it alone.
func (*Surface) CurrentView ¶ added in v0.5.0
func (s *Surface) CurrentView() (*TextureView, error)
CurrentView is CurrentTexture followed by CreateView(nil), for a frame loop: the returned view (and its Texture) are the same Go objects every call, standing for the new browser objects of this frame, so a frame allocates no handle. The view is valid until the next call; do not keep it, and do not Destroy its texture.
func (*Surface) Destroy ¶
func (s *Surface) Destroy()
Destroy unconfigures the context, destroying its textures.
func (*Surface) Format ¶
func (s *Surface) Format() TextureFormat
Format is the format of the surface's textures.
func (*Surface) Present ¶
Present ends the frame. For a standalone surface it returns the frame as an ImageBitmap (transferToImageBitmap: the image moves out without a copy); the caller must transfer it (postMessage) or close it. For a transferred canvas the browser presents by itself and Present returns js.Undefined().
type SurfaceDescriptor ¶
type SurfaceDescriptor struct {
Width, Height int
// Format is the canvas textures' format; empty is the browser's
// preferred canvas format.
Format TextureFormat
// Usage of the canvas textures; zero is RENDER_ATTACHMENT.
Usage TextureUsage
// AlphaMode; empty is "opaque".
AlphaMode CanvasAlphaMode
}
SurfaceDescriptor configures a Surface: an OffscreenCanvas with a WebGPU context (GPUCanvasConfiguration, https://www.w3.org/TR/webgpu/#canvas-configuration).
type TexelCopyBufferInfo ¶
type TexelCopyBufferInfo struct {
Buffer *Buffer
Layout TexelCopyBufferLayout
}
TexelCopyBufferInfo is a GPUTexelCopyBufferInfo.
type TexelCopyBufferLayout ¶
TexelCopyBufferLayout is a GPUTexelCopyBufferLayout. Zero BytesPerRow and RowsPerImage are "not specified".
type TexelCopyTextureInfo ¶
type TexelCopyTextureInfo struct {
Texture *Texture
MipLevel uint32
Origin Origin3D
Aspect TextureAspect
}
TexelCopyTextureInfo is a GPUTexelCopyTextureInfo.
type Texture ¶
type Texture struct {
// contains filtered or unexported fields
}
Texture is a GPUTexture.
func (*Texture) CreateView ¶
func (t *Texture) CreateView(desc *TextureViewDescriptor) (*TextureView, error)
CreateView is texture.createView(); nil desc is the default view.
func (*Texture) DepthOrArrayLayers ¶
func (*Texture) Descriptor ¶
func (t *Texture) Descriptor() TextureDescriptor
Descriptor returns the texture's descriptor, defaults filled in.
func (*Texture) Destroy ¶
func (t *Texture) Destroy()
Destroy is texture.destroy(); it refunds the texture's quota once. A canvas texture is not the caller's to destroy and is left alone.
func (*Texture) Format ¶
func (t *Texture) Format() TextureFormat
type TextureAspect ¶
type TextureAspect string
type TextureBindingLayout ¶
type TextureBindingLayout struct {
SampleType TextureSampleType
ViewDimension TextureViewDimension
Multisampled bool
}
TextureBindingLayout is a GPUTextureBindingLayout.
type TextureDescriptor ¶
type TextureDescriptor struct {
Label string
Size Extent3D
MipLevelCount uint32
SampleCount uint32
Dimension TextureDimension
Format TextureFormat
Usage TextureUsage
ViewFormats []TextureFormat
}
TextureDescriptor is a GPUTextureDescriptor. Zero MipLevelCount and SampleCount mean 1, zero Dimension "2d".
type TextureDimension ¶
type TextureDimension string
type TextureFormat ¶
type TextureFormat string
func (TextureFormat) Info ¶
func (f TextureFormat) Info() (FormatInfo, error)
Info returns what the package knows of a format. An unknown format is an error: sizes are never guessed, since quotas and copy bounds depend on them.
type TextureSampleType ¶
type TextureSampleType string
type TextureUsage ¶
type TextureUsage uint32
Flag sets, with the values of the IDL's GPUFlagsConstant namespaces.
type TextureView ¶
type TextureView struct {
// contains filtered or unexported fields
}
TextureView is a GPUTextureView.
func (*TextureView) Label ¶
func (o *TextureView) Label() string
Label returns the label the object was created with.
func (*TextureView) Texture ¶
func (v *TextureView) Texture() *Texture
Texture returns the viewed texture.
type TextureViewCreation ¶ added in v0.3.0
type TextureViewCreation struct {
Texture *Texture
Descriptor *TextureViewDescriptor
}
TextureViewCreation is the descriptor of a texture view: the texture and Texture.CreateView's descriptor (nil: the default view).
type TextureViewDescriptor ¶
type TextureViewDescriptor struct {
Label string
Format TextureFormat
Dimension TextureViewDimension
Aspect TextureAspect
BaseMipLevel uint32
MipLevelCount uint32
BaseArrayLayer uint32
ArrayLayerCount uint32
}
TextureViewDescriptor is a GPUTextureViewDescriptor.
type TextureViewDimension ¶
type TextureViewDimension string
type VertexAttribute ¶
type VertexAttribute struct {
Format VertexFormat
Offset uint64
ShaderLocation uint32
}
VertexAttribute is a GPUVertexAttribute.
type VertexBufferLayout ¶
type VertexBufferLayout struct {
ArrayStride uint64
StepMode VertexStepMode
Attributes []VertexAttribute
}
VertexBufferLayout is a GPUVertexBufferLayout.
type VertexFormat ¶
type VertexFormat string
type VertexState ¶
type VertexState struct {
Module *ShaderModule
EntryPoint string
Constants map[string]float64
Buffers []VertexBufferLayout
}
VertexState is a GPUVertexState.
type VertexStepMode ¶
type VertexStepMode string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package atlas packs rectangles into a texture atlas: the placement half of "many small images in one texture" (textures, lightmaps, glyphs, sprites), which a WebGPU program does to bind one texture instead of hundreds.
|
Package atlas packs rectangles into a texture atlas: the placement half of "many small images in one texture" (textures, lightmaps, glyphs, sprites), which a WebGPU program does to bind one texture instead of hundreds. |
|
Package batch is the host side of a batched GPU command stream, without a transport: the table of a guest's object ids, the creation and destruction of its objects, the replay of its streams and, for streams that read back (wire.ReadBuffer), the bounded read window.
|
Package batch is the host side of a batched GPU command stream, without a transport: the table of a guest's object ids, the creation and destruction of its objects, the replay of its streams and, for streams that read back (wire.ReadBuffer), the bounded read window. |
|
internal
|
|
|
cmd/wasmbrowser
module
|
|
|
kernels
|
|
|
argmax
Package argmax generates the WGSL of a greedy sampler in two stages, so that a large vocabulary is not walked by one workgroup: Groups workgroups each reduce a slice of the logits to its (largest, lowest index among equals), then one workgroup reduces the partials and writes the token.
|
Package argmax generates the WGSL of a greedy sampler in two stages, so that a large vocabulary is not walked by one workgroup: Groups workgroups each reduce a slice of the logits to its (largest, lowest index among equals), then one workgroup reduces the partials and writes the token. |
|
q4
Package q4 generates the WGSL of a matrix-vector product for ggml Q4_0 and Q4_1 weights, f32 activations, with no subgroups and no f16.
|
Package q4 generates the WGSL of a matrix-vector product for ggml Q4_0 and Q4_1 weights, f32 activations, with no subgroups and no f16. |
|
Package timeline is a monotonic synchronisation timeline: work is numbered 1, 2, 3, ...
|
Package timeline is a monotonic synchronisation timeline: work is numbered 1, 2, 3, ... |
|
Package wire is the format of the batched command stream a webgpu.Recorder writes and replay.js executes: opcodes, argument layout, and the Go reader that mirrors replay.js.
|
Package wire is the format of the batched command stream a webgpu.Recorder writes and replay.js executes: opcodes, argument layout, and the Go reader that mirrors replay.js. |